draft: LELEKA_DRAFT_CHECK_MERGE (opt-in): adjacent finite and Q8_1 scale guards of a draft step launch as one batched guard
A draft step launches 48 numerical guards, one kernel per buffer. Runs of guards that are neighbours in the program (no kernel or copy between them) are launched as one mtp_original_check_batch at the position of the run: each entry keeps its own buffer, count, kind and status word, with the predicate and loop of mtp_original_finite / mtp_original_q8_guard, so the status words are the separate launches' words. 3 runs per step (5 prefix guards after the GR block, 5 tail guards after the MLP GR, 2 after the shared gate and up): 12 launches become 3. No guard moves across another command; nothing is removed. New standalone sealed asset mtp_original_check_batch.cu/.ptx (extra-seal-plan.json entry, compile_assets.py + seal_pins.py with nvcc 13.2.86, sha pinned in mtp_original_full_symbols.rs), loaded only with the switch on; no existing sealed asset is touched. Pure planner and descriptor in cuda-model (draft_check_batch) with a simulated-step proof that a NaN/Inf placed in any checked buffer after any kernel leaves identical status words; driver tests on the real command lists; an ignored GPU test (batched against separate guards). Typed setting draft_check_merge, policy field check_merge, off by default. Identity, section delta and GPU proof pending; no speedup claim. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
11bdb54666
commit
306b39807a
@@ -0,0 +1,45 @@
|
||||
// Batched numerical guard of the MTP draft step (LELEKA_DRAFT_CHECK_MERGE, off by default).
|
||||
//
|
||||
// One launch runs the guards of a run of ADJACENT check launches of the step program: grid.y selects the entry, and
|
||||
// every entry is checked by exactly the loop and the predicate of the single-check kernels
|
||||
// `mtp_original_finite` and `mtp_original_q8_guard` (mtp_original_tail.cu / mtp_original_full_checks.cu), and sets
|
||||
// the same status word of its own with the same `atomicOr(status, 1)`. Nothing is read from device memory but the
|
||||
// checked buffer, nothing is written but the entry's status word; the status words are therefore bit-identical to the
|
||||
// ones the separate launches leave.
|
||||
//
|
||||
// The descriptor is ONE by-value parameter of 114 u64 words (the shape of the GrMulti parameter, so the host side
|
||||
// reuses its argument type):
|
||||
// w[0] number of entries (1..=28)
|
||||
// w[1 + 4*e] address of the checked buffer of entry e
|
||||
// w[2 + 4*e] low 32 bits: element count n (floats, or Q8_1 blocks); high 32 bits: kind (0 = f32 words, 1 = Q8_1
|
||||
// block scales)
|
||||
// w[3 + 4*e] address of the entry's status word
|
||||
// w[4 + 4*e] reserved, zero
|
||||
// Launch: grid (ceil(max n / 256), entries, 1), block (256, 1, 1). The grid-stride loop covers every element for any
|
||||
// grid.x, so an entry shorter than the longest one simply has idle blocks.
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
#include <cstdint>
|
||||
namespace strata::kernels {
|
||||
struct Q81Block { half2 ds; int8_t qs[32]; };
|
||||
static_assert(sizeof(Q81Block) == 36, "Q8_1 block layout");
|
||||
struct CheckBatch { unsigned long long w[114]; };
|
||||
static_assert(sizeof(CheckBatch) == 912, "the descriptor is the 912-byte by-value parameter of GrMulti");
|
||||
extern "C" __global__ void mtp_original_check_batch(CheckBatch b) {
|
||||
const unsigned entry = blockIdx.y;
|
||||
if (entry >= static_cast<unsigned>(b.w[0])) return;
|
||||
const unsigned long long data = b.w[1 + 4 * entry];
|
||||
const unsigned long long meta = b.w[2 + 4 * entry];
|
||||
int* status = reinterpret_cast<int*>(b.w[3 + 4 * entry]);
|
||||
const int n = static_cast<int>(meta & 0xffffffffull);
|
||||
const int q8 = static_cast<int>(meta >> 32) == 1;
|
||||
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) {
|
||||
if (!q8) {
|
||||
if (!isfinite(reinterpret_cast<const float*>(data)[i])) atomicOr(status, 1);
|
||||
} else {
|
||||
float2 ds = __half22float2(reinterpret_cast<const Q81Block*>(data)[i].ds);
|
||||
if (!isfinite(ds.x) || !isfinite(ds.y)) atomicOr(status, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace strata::kernels
|
||||
Binary file not shown.
@@ -0,0 +1,155 @@
|
||||
//! `LELEKA_DRAFT_CHECK_MERGE` (off by default): the adjacent finite and Q8_1 scale guards of a draft step program are
|
||||
//! launched as one `mtp_original_check_batch` (docs/experiments/step-ledger.md, row O8). The grouping and the
|
||||
//! descriptor are the pure `leleka_cuda_model::draft_check_batch`; this module classifies the commands of the two
|
||||
//! command lists (the scalar prefix and the tail), builds the batched commands, owns the batch module and launches it.
|
||||
//!
|
||||
//! Only checks that are neighbours in the list are grouped, so no check moves across another command.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_cuda_model::draft_check_batch::{self as batch, Check, CheckKind, THREADS};
|
||||
|
||||
/// Placeholder asset of a batched check in both command lists (the real module tables are far shorter).
|
||||
const BATCH_ASSET: usize = usize::MAX;
|
||||
/// Module of the single-check kernels in the tail command list, and their entries (finite, Q8_1 scales).
|
||||
const TAIL_CHECKS: usize = 18;
|
||||
const TAIL_CHECK_ENTRIES: (usize, usize) = (0, 1);
|
||||
/// The same in the scalar prefix command list.
|
||||
const PREFIX_CHECKS: usize = 2;
|
||||
const PREFIX_CHECK_ENTRIES: (usize, usize) = (11, 12);
|
||||
/// The first prefix commands are the status reset and the embedding lookup; the native embedding is captured by their
|
||||
/// index, so they stay where they are.
|
||||
const PREFIX_KEEP: usize = 2;
|
||||
|
||||
/// The sealed batch module, loaded once for each of the two launch interfaces of the program.
|
||||
pub(super) struct CheckBatchModules {
|
||||
tail: Rc<FM>,
|
||||
prefix: Rc<Module>,
|
||||
}
|
||||
|
||||
impl CheckBatchModules {
|
||||
/// Loads the sealed `mtp_original_check_batch.ptx` into `context`.
|
||||
pub(super) fn load(context: &Context<'_>) -> Result<Self> {
|
||||
let g = context.enter().inspect_err(|_| {
|
||||
context.poison();
|
||||
context.retain_driver();
|
||||
})?;
|
||||
let loaded = Self::load_current();
|
||||
let pop = g.finish();
|
||||
if pop.is_err() {
|
||||
context.poison();
|
||||
context.retain_driver();
|
||||
}
|
||||
combine(loaded, pop)
|
||||
}
|
||||
|
||||
fn load_current() -> Result<Self> {
|
||||
let (ptx, entries) = (symbols::CHECK_BATCH.0, symbols::CHECK_BATCH.1);
|
||||
let sealed = crate::sealed_ptx::pinned(ptx, Some(symbols::CHECK_BATCH_PIN));
|
||||
let ptx = sealed.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
Ok(Self { tail: Rc::new(FM::load(ptx, entries)?), prefix: Rc::new(Module::load(ptx, entries)?) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `shape` the launch shape of the separate check of `check`?
|
||||
fn is_single_launch(shape: &LaunchShape, check: &Check) -> bool {
|
||||
shape.dims.grid == [check.single_grid(), 1, 1] && shape.dims.block == [THREADS, 1, 1] && shape.shared == 0
|
||||
}
|
||||
|
||||
fn check_of(kind: CheckKind, words: (u64, i32, u64), shape: &LaunchShape) -> Option<Check> {
|
||||
let (data, count, flag) = words;
|
||||
let check = Check { kind, data, count: u32::try_from(count).ok()?, flag };
|
||||
is_single_launch(shape, &check).then_some(check)
|
||||
}
|
||||
|
||||
/// Which single-check kernel `(asset, index)` is, given the module and the entries of the list.
|
||||
fn kind_of((asset, index): (usize, usize), module: usize, entries: (usize, usize)) -> Option<CheckKind> {
|
||||
if asset != module {
|
||||
None
|
||||
} else if index == entries.0 {
|
||||
Some(CheckKind::Finite)
|
||||
} else if index == entries.1 {
|
||||
Some(CheckKind::Q8Scale)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The check a tail command is, if it is exactly one separate check launch.
|
||||
fn tail_check(command: &FullCommand) -> Option<Check> {
|
||||
let kind = kind_of((command.asset, command.index), TAIL_CHECKS, TAIL_CHECK_ENTRIES)?;
|
||||
check_of(kind, command.args.check_words()?, &command.shape)
|
||||
}
|
||||
|
||||
/// The check a scalar prefix command is, if it is exactly one separate check launch.
|
||||
fn prefix_check(command: &ScalarCommand) -> Option<Check> {
|
||||
let ScalarCommand::Kernel { asset, index, shape, args } = command else { return None };
|
||||
let kind = kind_of((*asset, *index), PREFIX_CHECKS, PREFIX_CHECK_ENTRIES)?;
|
||||
check_of(kind, args.check_words()?, shape)
|
||||
}
|
||||
|
||||
fn batch_shape(launch: &batch::BatchLaunch) -> LaunchShape {
|
||||
LaunchShape::new(launch.grid, [THREADS, 1, 1], 0)
|
||||
}
|
||||
|
||||
fn tail_batch(checks: &[Check]) -> Result<FullCommand> {
|
||||
let launch = batch::encode(checks)?;
|
||||
let shape = batch_shape(&launch);
|
||||
Ok(FullCommand { asset: BATCH_ASSET, index: 0, shape, args: FA::new(vec![F::GrMulti(launch.words)])? })
|
||||
}
|
||||
|
||||
fn prefix_batch(checks: &[Check]) -> Result<ScalarCommand> {
|
||||
let launch = batch::encode(checks)?;
|
||||
let shape = batch_shape(&launch);
|
||||
Ok(ScalarCommand::Kernel {
|
||||
asset: BATCH_ASSET,
|
||||
index: 0,
|
||||
shape,
|
||||
args: Arguments::new(vec![Arg::GrMulti(launch.words)])?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The tail commands with every run of adjacent checks launched as one batch.
|
||||
pub(super) fn merge_tail(commands: Vec<FullCommand>) -> Result<Vec<FullCommand>> {
|
||||
batch::merge_adjacent(commands, 0, tail_check, tail_batch)
|
||||
}
|
||||
|
||||
/// The scalar prefix commands with every run of adjacent checks launched as one batch.
|
||||
pub(super) fn merge_prefix(commands: Vec<ScalarCommand>) -> Result<Vec<ScalarCommand>> {
|
||||
batch::merge_adjacent(commands, PREFIX_KEEP, prefix_check, prefix_batch)
|
||||
}
|
||||
|
||||
/// Launch one command of a scalar prefix list (the catch-up and the step prefix).
|
||||
pub(super) fn launch_prefix_command(
|
||||
modules: &[Rc<Module>; 6],
|
||||
batch: Option<&CheckBatchModules>,
|
||||
stream: usize,
|
||||
command: &mut ScalarCommand,
|
||||
) -> Result<()> {
|
||||
let ScalarCommand::Kernel { asset, index, shape, args } = command else {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
};
|
||||
if *asset == BATCH_ASSET {
|
||||
return batch.ok_or(Error::ContextPoisoned)?.prefix.launch(*index, *shape, stream, args);
|
||||
}
|
||||
modules.get(*asset).ok_or(Error::InvalidQwenShape)?.launch(*index, *shape, stream, args)
|
||||
}
|
||||
|
||||
/// Launch a batched tail command.
|
||||
pub(super) fn launch_tail_batch(
|
||||
batch: Option<&CheckBatchModules>,
|
||||
stream: usize,
|
||||
command: &mut FullCommand,
|
||||
) -> Result<()> {
|
||||
batch.ok_or(Error::ContextPoisoned)?.tail.launch(command.index, command.shape, stream, &mut command.args)
|
||||
}
|
||||
|
||||
/// Does the tail command launch a batch?
|
||||
pub(super) fn is_tail_batch(command: &FullCommand) -> bool {
|
||||
command.asset == BATCH_ASSET
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gpu_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Model-free GPU proof of `mtp_original_check_batch`: for a finite buffer set and for a NaN or Inf placed at the
|
||||
//! edges and in the middle of every checked buffer (floats and Q8_1 scale pairs), the status words of one batched
|
||||
//! launch, through the tail interface and through the scalar prefix interface, equal the ones of the separate
|
||||
//! launches of `mtp_original_finite` and `mtp_original_q8_guard`.
|
||||
//! Run: `cargo test -p leleka-cuda-driver --features cuda-driver --lib check_batch_program_gpu -- --ignored`.
|
||||
use super::*;
|
||||
use crate::{DeviceBuffer, Driver};
|
||||
use leleka_cuda_model::draft_check_batch::encode;
|
||||
|
||||
const FLOATS: [usize; 3] = [12288, 640, 4];
|
||||
const BLOCKS: usize = 80;
|
||||
const WORDS: usize = 16;
|
||||
|
||||
fn floats_bytes(n: usize, at: Option<(usize, f32)>) -> Vec<u8> {
|
||||
let mut v = vec![1.0f32; n];
|
||||
if let Some((i, x)) = at {
|
||||
v[i] = x;
|
||||
}
|
||||
v.iter().flat_map(|x| x.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// `BLOCKS` Q8_1 blocks of 36 bytes: a finite scale pair, one half replaced by a non-finite code at (block, half).
|
||||
fn blocks_bytes(at: Option<(usize, usize, u16)>) -> Vec<u8> {
|
||||
let mut b = vec![0u8; BLOCKS * 36];
|
||||
for i in 0..BLOCKS {
|
||||
b[i * 36..i * 36 + 4].copy_from_slice(&[0x00, 0x38, 0x00, 0x40]);
|
||||
}
|
||||
if let Some((block, half, code)) = at {
|
||||
let o = block * 36 + 2 * half;
|
||||
b[o..o + 2].copy_from_slice(&code.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
struct Fault {
|
||||
floats: [Option<(usize, f32)>; 3],
|
||||
scale: Option<(usize, usize, u16)>,
|
||||
}
|
||||
|
||||
fn faults() -> Vec<Fault> {
|
||||
let none = || Fault { floats: [None; 3], scale: None };
|
||||
let mut all = vec![none()];
|
||||
for (buffer, n) in FLOATS.into_iter().enumerate() {
|
||||
for i in [0, 1, 255, 256, n / 2, n - 1] {
|
||||
for x in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let mut f = none();
|
||||
f.floats[buffer] = Some((i.min(n - 1), x));
|
||||
all.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
for block in [0, 1, 79] {
|
||||
for half in [0, 1] {
|
||||
for code in [0x7e00u16, 0x7c00, 0xfc00] {
|
||||
all.push(Fault { floats: [None; 3], scale: Some((block, half, code)) });
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn address(buffer: &DeviceBuffer<'_>) -> u64 {
|
||||
buffer.handle.expect("handle").qwen_address()
|
||||
}
|
||||
|
||||
fn read_status(status: &DeviceBuffer<'_>) -> Vec<u32> {
|
||||
let bytes = status.copy_to_owned(WORDS * 4).expect("read");
|
||||
bytes.chunks_exact(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// The device buffers, the checks over them and the two ways to launch them.
|
||||
struct Rig<'a> {
|
||||
context: &'a Context<'a>,
|
||||
stream: usize,
|
||||
data: Vec<DeviceBuffer<'a>>,
|
||||
blocks: DeviceBuffer<'a>,
|
||||
status: DeviceBuffer<'a>,
|
||||
checks: Vec<Check>,
|
||||
batch: CheckBatchModules,
|
||||
singles: FM,
|
||||
}
|
||||
|
||||
impl<'a> Rig<'a> {
|
||||
fn new(context: &'a Context<'a>) -> Self {
|
||||
let stream = context.native_batch_workspace().expect("workspace").blas().expect("blas").stream();
|
||||
let data: Vec<DeviceBuffer<'a>> = FLOATS.iter().map(|n| context.allocate(n * 4).expect("alloc")).collect();
|
||||
let blocks = context.allocate(BLOCKS * 36).expect("alloc");
|
||||
let status = context.allocate(WORDS * 4).expect("alloc");
|
||||
let bases = [(CheckKind::Finite, &data[0], FLOATS[0]), (CheckKind::Finite, &data[1], FLOATS[1])];
|
||||
let bases = bases.into_iter().chain([(CheckKind::Finite, &data[2], FLOATS[2])]);
|
||||
let bases = bases.chain([(CheckKind::Q8Scale, &blocks, BLOCKS)]);
|
||||
let flag = address(&status);
|
||||
let checks = bases
|
||||
.enumerate()
|
||||
.map(|(i, (kind, b, count))| Check {
|
||||
kind,
|
||||
data: address(b),
|
||||
count: count as u32,
|
||||
flag: flag + 4 * i as u64,
|
||||
})
|
||||
.collect();
|
||||
let batch = CheckBatchModules::load(context).expect("sealed batch asset");
|
||||
let (ptx, entries) = symbols::ASSETS[TAIL_CHECKS];
|
||||
Self { context, stream, data, blocks, status, checks, batch, singles: FM::load(ptx, entries).expect("singles") }
|
||||
}
|
||||
|
||||
fn upload(&mut self, fault: &Fault) {
|
||||
for (i, buffer) in self.data.iter_mut().enumerate() {
|
||||
buffer.copy_from(&floats_bytes(FLOATS[i], fault.floats[i])).expect("upload");
|
||||
}
|
||||
self.blocks.copy_from(&blocks_bytes(fault.scale)).expect("upload");
|
||||
}
|
||||
|
||||
fn run(&mut self, launch: impl FnOnce(&Self)) -> Vec<u32> {
|
||||
self.status.copy_from(&[0u8; WORDS * 4]).expect("zero");
|
||||
launch(self);
|
||||
self.context.synchronize().expect("sync");
|
||||
read_status(&self.status)
|
||||
}
|
||||
|
||||
fn separate(&self) {
|
||||
for c in &self.checks {
|
||||
let index = usize::from(c.kind == CheckKind::Q8Scale);
|
||||
let mut args = FA::new(vec![F::U64(c.data), F::I32(c.count as i32), F::U64(c.flag)]).unwrap();
|
||||
let shape = single_shape(c.single_grid());
|
||||
self.singles.launch(index, shape, self.stream, &mut args).expect("single");
|
||||
}
|
||||
}
|
||||
|
||||
fn tail(&self) {
|
||||
let launch = encode(&self.checks).unwrap();
|
||||
let mut args = FA::new(vec![F::GrMulti(launch.words.clone())]).unwrap();
|
||||
self.batch.tail.launch(0, batch_shape(&launch), self.stream, &mut args).expect("batch");
|
||||
}
|
||||
|
||||
fn prefix(&self) {
|
||||
let launch = encode(&self.checks).unwrap();
|
||||
let mut args = Arguments::new(vec![Arg::GrMulti(launch.words.clone())]).unwrap();
|
||||
self.batch.prefix.launch(0, batch_shape(&launch), self.stream, &mut args).expect("batch");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device"]
|
||||
fn the_batched_guard_leaves_the_status_words_of_the_separate_launches() {
|
||||
let driver = Driver::load().expect("driver");
|
||||
let context = driver.device(0).expect("device").create_context(1usize << 30).expect("context");
|
||||
let mut rig = Rig::new(&context);
|
||||
let guard = context.enter().expect("enter");
|
||||
let (mut total, mut caught) = (0, 0);
|
||||
for fault in faults() {
|
||||
rig.upload(&fault);
|
||||
let separate = rig.run(Rig::separate);
|
||||
assert_eq!(rig.run(Rig::tail), separate, "tail interface");
|
||||
assert_eq!(rig.run(Rig::prefix), separate, "prefix interface");
|
||||
total += 1;
|
||||
caught += usize::from(separate.iter().any(|w| *w != 0));
|
||||
}
|
||||
guard.finish().expect("pop");
|
||||
assert_eq!(total - caught, 1, "exactly the clean case raises nothing");
|
||||
}
|
||||
|
||||
fn single_shape(grid: u32) -> LaunchShape {
|
||||
LaunchShape::new([grid, 1, 1], [THREADS, 1, 1], 0)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! The command lists of a draft step with merged checks: the adapters recognise exactly the separate check launches,
|
||||
//! the merged lists stand for the separate ones, and the sealed batch asset is the one the kernel source builds.
|
||||
use super::*;
|
||||
use crate::sealed_ptx::test_support::{assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted};
|
||||
use leleka_cuda_model::draft_check_batch::{BATCH_WORDS, ENTRY_WORDS};
|
||||
|
||||
/// What a command is, for comparing a list before and after merging.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Item {
|
||||
Check(Check),
|
||||
Other(usize, usize),
|
||||
}
|
||||
|
||||
fn single_shape(count: u32) -> LaunchShape {
|
||||
LaunchShape::new([count.div_ceil(THREADS), 1, 1], [THREADS, 1, 1], 0)
|
||||
}
|
||||
|
||||
fn tail_check_command(index: usize, buffer: u64, count: i32, slot: u64) -> FullCommand {
|
||||
let args = vec![F::U64(buffer), F::I32(count), F::U64(0x9000 + 4 * slot)];
|
||||
FullCommand { asset: TAIL_CHECKS, index, shape: single_shape(count as u32), args: FA::new(args).unwrap() }
|
||||
}
|
||||
|
||||
fn tail_other(asset: usize, index: usize) -> FullCommand {
|
||||
let shape = LaunchShape::new([1, 1, 1], [32, 1, 1], 0);
|
||||
FullCommand { asset, index, shape, args: FA::new(vec![F::U64(8)]).unwrap() }
|
||||
}
|
||||
|
||||
fn prefix_check_command(index: usize, buffer: u64, count: i32, slot: u64) -> ScalarCommand {
|
||||
let args = Arguments::new(vec![Arg::U64(buffer), Arg::I32(count), Arg::U64(0x9000 + 4 * slot)]).unwrap();
|
||||
ScalarCommand::Kernel { asset: PREFIX_CHECKS, index, shape: single_shape(count as u32), args }
|
||||
}
|
||||
|
||||
fn prefix_other(asset: usize, index: usize) -> ScalarCommand {
|
||||
let shape = LaunchShape::new([1, 1, 1], [32, 1, 1], 0);
|
||||
ScalarCommand::Kernel { asset, index, shape, args: Arguments::new(vec![Arg::U64(8)]).unwrap() }
|
||||
}
|
||||
|
||||
/// Decodes a batched command's descriptor back into the checks it stands for.
|
||||
fn decode(words: &[u64; BATCH_WORDS], shape: &LaunchShape) -> Vec<Check> {
|
||||
let entries = words[0] as usize;
|
||||
assert!(entries >= 2, "a batch of one is never built");
|
||||
assert_eq!(shape.dims.grid[1] as usize, entries);
|
||||
assert_eq!((shape.dims.block, shape.shared), ([THREADS, 1, 1], 0));
|
||||
(0..entries)
|
||||
.map(|e| {
|
||||
let meta = words[2 + ENTRY_WORDS * e];
|
||||
let kind = if meta >> 32 == 1 { CheckKind::Q8Scale } else { CheckKind::Finite };
|
||||
Check { kind, data: words[1 + ENTRY_WORDS * e], count: meta as u32, flag: words[3 + ENTRY_WORDS * e] }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tail_items(commands: &[FullCommand]) -> Vec<Item> {
|
||||
let mut items = Vec::new();
|
||||
for c in commands {
|
||||
if c.asset == BATCH_ASSET {
|
||||
items.extend(decode(c.args.gr_words().unwrap(), &c.shape).into_iter().map(Item::Check));
|
||||
} else {
|
||||
items.push(tail_check(c).map_or(Item::Other(c.asset, c.index), Item::Check));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
fn prefix_items(commands: &[ScalarCommand]) -> Vec<Item> {
|
||||
let mut items = Vec::new();
|
||||
for c in commands {
|
||||
let ScalarCommand::Kernel { asset, index, shape, args } = c else { panic!("copy") };
|
||||
if *asset == BATCH_ASSET {
|
||||
items.extend(decode(args.gr_words().unwrap(), shape).into_iter().map(Item::Check));
|
||||
} else {
|
||||
items.push(prefix_check(c).map_or(Item::Other(*asset, *index), Item::Check));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
fn tail_list() -> Vec<FullCommand> {
|
||||
vec![
|
||||
tail_other(13, 5),
|
||||
tail_check_command(0, 0x1000, 12288, 0),
|
||||
tail_other(16, 0),
|
||||
tail_check_command(0, 0x2000, 6144, 1),
|
||||
tail_check_command(0, 0x3000, 10240, 7),
|
||||
tail_check_command(1, 0x4000, 192, 5),
|
||||
tail_check_command(0, 0x5000, 4, 10),
|
||||
tail_other(13, 6),
|
||||
tail_check_command(0, 0x6000, 2560, 11),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tail_list_loses_the_adjacent_check_launches_and_nothing_else() {
|
||||
let list = tail_list();
|
||||
let before = tail_items(&list);
|
||||
let merged = merge_tail(list).unwrap();
|
||||
assert_eq!(tail_items(&merged), before);
|
||||
// 9 commands: kernel, check, kernel, 4 adjacent checks (one batch), kernel, check
|
||||
assert_eq!(merged.len(), 6);
|
||||
assert_eq!(merged.iter().filter(|c| c.asset == BATCH_ASSET).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prefix_list_keeps_its_first_commands_and_merges_the_rest() {
|
||||
let list = vec![
|
||||
prefix_other(0, 11),
|
||||
prefix_check_command(11, 0x1000, 2560, 0),
|
||||
prefix_check_command(11, 0x2000, 2560, 1),
|
||||
prefix_other(3, 0),
|
||||
prefix_check_command(11, 0x3000, 2560, 6),
|
||||
prefix_check_command(12, 0x4000, 80, 6),
|
||||
prefix_check_command(11, 0x5000, 10240, 7),
|
||||
];
|
||||
let before = prefix_items(&list);
|
||||
let merged = prefix_items(&merge_prefix(list).unwrap());
|
||||
assert_eq!(merged, before);
|
||||
let list = vec![
|
||||
prefix_other(0, 11),
|
||||
prefix_check_command(11, 0x1000, 2560, 0),
|
||||
prefix_check_command(11, 0x2000, 2560, 1),
|
||||
prefix_check_command(11, 0x3000, 2560, 2),
|
||||
];
|
||||
// index 1 is not merged (the native embedding is captured by command index), 2 and 3 are
|
||||
let merged = merge_prefix(list).unwrap();
|
||||
assert_eq!(merged.len(), 3);
|
||||
assert!(matches!(&merged[2], ScalarCommand::Kernel { asset, .. } if *asset == BATCH_ASSET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_exact_separate_check_launches_are_recognised() {
|
||||
let good = tail_check_command(0, 0x1000, 600, 3);
|
||||
assert_eq!(tail_check(&good), Some(Check { kind: CheckKind::Finite, data: 0x1000, count: 600, flag: 0x900c }));
|
||||
// another kernel of the module, another module, a different grid, other arguments, a negative count
|
||||
let mut other_entry = tail_check_command(0, 0x1000, 600, 3);
|
||||
other_entry.index = 2;
|
||||
let mut other_module = tail_check_command(0, 0x1000, 600, 3);
|
||||
other_module.asset = 17;
|
||||
let mut other_grid = tail_check_command(0, 0x1000, 600, 3);
|
||||
other_grid.shape = LaunchShape::new([4, 1, 1], [THREADS, 1, 1], 0);
|
||||
let mut shared = tail_check_command(0, 0x1000, 600, 3);
|
||||
shared.shape = LaunchShape::new([3, 1, 1], [THREADS, 1, 1], 16);
|
||||
let mut extra_arg = tail_check_command(0, 0x1000, 600, 3);
|
||||
extra_arg.args = FA::new(vec![F::U64(0x1000), F::I32(600), F::U64(0x900c), F::I32(1)]).unwrap();
|
||||
let negative = tail_check_command(0, 0x1000, -1, 3);
|
||||
for command in [&other_entry, &other_module, &other_grid, &shared, &extra_arg, &negative] {
|
||||
assert!(tail_check(command).is_none());
|
||||
}
|
||||
assert_eq!(tail_check(&tail_check_command(1, 0x2000, 20, 5)).unwrap().kind, CheckKind::Q8Scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_that_is_not_a_check_is_never_swallowed() {
|
||||
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
for _ in 0..100 {
|
||||
let list: Vec<FullCommand> = (0..40)
|
||||
.map(|i| match next() % 4 {
|
||||
0 => tail_other(13, (next() % 5) as usize),
|
||||
1 => tail_check_command(1, 0x1000 * (i + 1), 20 + (next() % 500) as i32, i % 30),
|
||||
_ => tail_check_command(0, 0x1000 * (i + 1), 1 + (next() % 12000) as i32, i % 30),
|
||||
})
|
||||
.collect();
|
||||
let before = tail_items(&list);
|
||||
assert_eq!(tail_items(&merge_tail(list).unwrap()), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_check_kernels_are_the_entries_the_lists_name() {
|
||||
let (_, tail) = symbols::ASSETS[TAIL_CHECKS];
|
||||
assert_eq!(tail[TAIL_CHECK_ENTRIES.0], c"mtp_original_finite");
|
||||
assert_eq!(tail[TAIL_CHECK_ENTRIES.1], c"mtp_original_q8_guard");
|
||||
assert_eq!(TAIL_ENTRIES[PREFIX_CHECK_ENTRIES.0], c"mtp_original_finite");
|
||||
assert_eq!(TAIL_ENTRIES[PREFIX_CHECK_ENTRIES.1], c"mtp_original_q8_guard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_batch_asset_is_the_sealed_ptx_of_its_source() {
|
||||
let (ptx, entries) = symbols::CHECK_BATCH;
|
||||
assert_eq!(entries, [c"mtp_original_check_batch"]);
|
||||
assert!(crate::sealed_ptx::pinned(ptx, Some(symbols::CHECK_BATCH_PIN)).is_some());
|
||||
assert!(crate::sealed_ptx::pinned(one_byte_corrupted(ptx), Some(symbols::CHECK_BATCH_PIN)).is_none());
|
||||
assert_real_sm120_ptx("check batch", ptx, ["mtp_original_check_batch"]);
|
||||
assert_nvcc_13_2_86("check batch", ptx);
|
||||
let text = std::str::from_utf8(&ptx[..ptx.len() - 1]).unwrap();
|
||||
assert!(text.contains("mtp_original_check_batch_param_0[912]"), "one 114-word by-value parameter");
|
||||
assert_eq!(text.matches(".entry").count(), 1);
|
||||
assert_eq!(text.matches("atom.global.or.b32").count(), 2, "one atomicOr per kind, as the single kernels");
|
||||
}
|
||||
@@ -24,6 +24,22 @@ impl Arguments {
|
||||
+ self.values.iter().map(|a| if matches!(a, Arg::GrMulti(_)) { 114 * 8 } else { 0 }).sum::<usize>()
|
||||
}
|
||||
|
||||
/// The three words of a check launch (buffer, count, status word), when the arguments are exactly those.
|
||||
pub(crate) fn check_words(&self) -> Option<(u64, i32, u64)> {
|
||||
match &*self.values {
|
||||
[Arg::U64(data), Arg::I32(count), Arg::U64(flag)] => Some((*data, *count, *flag)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn gr_words(&self) -> Option<&[u64; 114]> {
|
||||
match &*self.values {
|
||||
[Arg::GrMulti(words)] => Some(words),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new(values: Vec<Arg>) -> Result<Self> {
|
||||
let mut pointers = Vec::new();
|
||||
pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
|
||||
@@ -77,6 +77,9 @@ pub struct OriginalMtpFullPolicy {
|
||||
/// Enqueue the chain steps of a greedy draft with `min_p` 0 back to back and read them after one stream drain
|
||||
/// (`LELEKA_DRAFT_CHAIN_PIPELINE`; the kernels and their order are the sequential path's).
|
||||
pub chain_pipeline: bool,
|
||||
/// Launch the adjacent finite and Q8_1 scale guards of a step as one batched guard
|
||||
/// (`LELEKA_DRAFT_CHECK_MERGE`; the same checks of the same buffers at the same positions, fewer launches).
|
||||
pub check_merge: bool,
|
||||
}
|
||||
struct TailLayout {
|
||||
sizes: [usize; 36],
|
||||
@@ -154,6 +157,8 @@ pub struct OriginalMtpForwardProgram<'ctx> {
|
||||
/// a chain step OR into the words the draft round's own resets cleared, so the host reads them once for a run
|
||||
/// of steps enqueued back to back.
|
||||
accumulate_flags: bool,
|
||||
/// The batched guard module, loaded when the policy asks for merged checks.
|
||||
check_batch: Option<mtp_original_check_batch_program::CheckBatchModules>,
|
||||
}
|
||||
|
||||
/// The scalar prefix's modules and the buffers its commands run on.
|
||||
@@ -313,6 +318,7 @@ mod role_map_tests {
|
||||
mod context;
|
||||
#[path = "mtp_original_full_forward/full_owned.rs"]
|
||||
mod full_owned;
|
||||
mod mtp_original_check_batch_program;
|
||||
mod mtp_original_full_init;
|
||||
#[path = "mtp_original_full_forward/original_mtp_full_forward.rs"]
|
||||
mod original_mtp_full_forward;
|
||||
|
||||
+19
-1
@@ -1,5 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward (2).
|
||||
|
||||
use super::super::mtp_original_check_batch_program::{CheckBatchModules, merge_prefix, merge_tail};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -16,7 +17,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
let ScalarPrefixPlan { commands: prefix, native_embedding, step_row } = plan;
|
||||
self.program_reject_aliases(scalar, ring)?;
|
||||
let p = self.program_prefix(scalar, ring, step_row)?;
|
||||
let commands = self.plan(&p, policy)?;
|
||||
let (prefix, commands, check_batch) = self.program_commands(scalar.context, &p, (prefix, policy))?;
|
||||
let window = self.program_window(&p, ring)?;
|
||||
let coupled_stage = self.program_coupled_stage(policy)?;
|
||||
Ok(OriginalMtpForwardProgram {
|
||||
@@ -31,9 +32,26 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
coupled_stage,
|
||||
addrs: Self::program_addrs(scalar)?,
|
||||
accumulate_flags: false,
|
||||
check_batch,
|
||||
})
|
||||
}
|
||||
|
||||
/// The tail commands of the step, and with `LELEKA_DRAFT_CHECK_MERGE` the adjacent checks of the scalar prefix and
|
||||
/// of the tail launched as batches, with the module that launches them. Without it the lists are as planned.
|
||||
fn program_commands(
|
||||
&self,
|
||||
context: &'ctx Context<'ctx>,
|
||||
p: &ForwardPrefix<'_, 'ctx>,
|
||||
(prefix, policy): (Vec<ScalarCommand>, &OriginalMtpFullPolicy),
|
||||
) -> Result<(Vec<ScalarCommand>, Vec<FullCommand>, Option<CheckBatchModules>)> {
|
||||
let tail = self.plan(p, policy)?;
|
||||
if !policy.check_merge {
|
||||
return Ok((prefix, tail, None));
|
||||
}
|
||||
let batch = CheckBatchModules::load(context)?;
|
||||
Ok((merge_prefix(prefix)?, merge_tail(tail)?, Some(batch)))
|
||||
}
|
||||
|
||||
fn program_addrs(scalar: &OriginalMtpScalarPrefill<'ctx>) -> Result<ScalarAddrs> {
|
||||
Ok(ScalarAddrs {
|
||||
residual_offset: scalar.layout.offsets[1],
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalMtpForwardProgram, impl OriginalMtpForwardProgram, impl
|
||||
//! OriginalMtpForwardProgram.
|
||||
|
||||
use super::mtp_original_check_batch_program::{
|
||||
CheckBatchModules, is_tail_batch, launch_prefix_command, launch_tail_batch,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use abi::LaunchShape;
|
||||
@@ -20,7 +23,7 @@ impl OriginalMtpForwardProgram<'_> {
|
||||
(&self.tail, &self.ring),
|
||||
(&self.args.split, &mut self.args.window),
|
||||
stream,
|
||||
command,
|
||||
(self.check_batch.as_ref(), command),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -38,7 +41,7 @@ impl OriginalMtpForwardProgram<'_> {
|
||||
e.capture(capture)?;
|
||||
}
|
||||
if !(i == 0 && self.accumulate_flags) {
|
||||
Self::launch_scalar(&self.owners.modules, stream, command)?;
|
||||
launch_prefix_command(&self.owners.modules, self.check_batch.as_ref(), stream, command)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -60,20 +63,16 @@ impl OriginalMtpForwardProgram<'_> {
|
||||
self.owners.modules[0].launch(11, shape, stream, &mut self.args.reset)
|
||||
}
|
||||
|
||||
fn launch_scalar(modules: &[Rc<Module>; 6], stream: usize, command: &mut ScalarCommand) -> Result<()> {
|
||||
match command {
|
||||
ScalarCommand::Kernel { asset, index, shape, args } => modules[*asset].launch(*index, *shape, stream, args),
|
||||
ScalarCommand::Copy { .. } => Err(Error::InvalidQwenShape),
|
||||
}
|
||||
}
|
||||
|
||||
/// One tail command, preceded by the Q split copy or the window-ids transport where Original puts them.
|
||||
fn launch_tail_command(
|
||||
(tail, ring): (&FullOwned<'_>, &MtpOriginalRingResources<'_>),
|
||||
(split, window): (&full_abi::Copy2D, &mut abi::Arguments),
|
||||
stream: usize,
|
||||
command: &mut FullCommand,
|
||||
(batch, command): (Option<&CheckBatchModules>, &mut FullCommand),
|
||||
) -> Result<()> {
|
||||
if is_tail_batch(command) {
|
||||
return launch_tail_batch(batch, stream, command);
|
||||
}
|
||||
if command.asset == 16 && command.index == 0 {
|
||||
tail.modules[13].copy2d(split, stream)?;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalMtpDraftProgram.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::super::mtp_original_check_batch_program::launch_prefix_command;
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> OriginalMtpDraftProgram<'ctx> {
|
||||
@@ -52,12 +53,8 @@ impl<'ctx> OriginalMtpDraftProgram<'ctx> {
|
||||
{
|
||||
e.capture(c)?;
|
||||
}
|
||||
match cmd {
|
||||
ScalarCommand::Kernel { asset, index, shape, args } => {
|
||||
self.program.owners.modules[*asset].launch(*index, *shape, stream, args)?
|
||||
}
|
||||
ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape),
|
||||
}
|
||||
let (modules, batch) = (&self.program.owners.modules, self.program.check_batch.as_ref());
|
||||
launch_prefix_command(modules, batch, stream, cmd)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! crate_original_gpu_schedule_resources, impl OriginalGraphResources_for_OriginalMtpDraftProgram, impl
|
||||
//! OriginalMtpFullForward, fn mapped_i32 ....
|
||||
|
||||
use super::super::mtp_original_check_batch_program::merge_prefix;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -95,6 +96,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
let ra = 2 * self.inner.max_t - 1;
|
||||
let prefix = self.round_prefix(scalar, ring, policy, ra)?;
|
||||
let mut program = self.program(scalar, ring, prefix, policy)?;
|
||||
let catchup_commands = Self::catchup_commands(&program, catchup.commands)?;
|
||||
let coupled_stage = program.coupled_stage.take();
|
||||
let before = self.round_before(scalar, rows)?;
|
||||
let after = self.round_after(scalar, rows, ra)?;
|
||||
@@ -106,12 +108,19 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
before,
|
||||
after,
|
||||
post,
|
||||
catchup: catchup.commands,
|
||||
catchup: catchup_commands,
|
||||
catchup_embed: catchup.native_embedding,
|
||||
coupled_stage,
|
||||
direct_window: None,
|
||||
})
|
||||
}
|
||||
/// The catch-up commands, with their adjacent checks batched when the program's are.
|
||||
fn catchup_commands(
|
||||
program: &OriginalMtpForwardProgram<'ctx>,
|
||||
commands: Vec<ScalarCommand>,
|
||||
) -> Result<Vec<ScalarCommand>> {
|
||||
if program.check_batch.is_some() { merge_prefix(commands) } else { Ok(commands) }
|
||||
}
|
||||
fn check_round_rows(
|
||||
&self,
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
|
||||
@@ -22,3 +22,20 @@ pub(super) use chain_asset_types::DAILY_ASSET;
|
||||
pub(super) use chain_asset_types::DAILY_CHUNK;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use chain_asset_types::DAILY_MERGE_V2;
|
||||
|
||||
/// The sealed batched numerical guard (`LELEKA_DRAFT_CHECK_MERGE`); loaded only when the switch is on, so it is not a
|
||||
/// slot of `ASSETS` and moves no index.
|
||||
#[allow(unused_imports)]
|
||||
pub(super) static CHECK_BATCH: (&[u8], &[&std::ffi::CStr]) =
|
||||
(include_bytes!("mtp_original_check_batch.ptx"), &[c"mtp_original_check_batch"]);
|
||||
|
||||
/// Length (with the terminal NUL) and sha256 of the body of `mtp_original_check_batch.ptx`, compiled from
|
||||
/// `mtp_original_check_batch.cu` by `scripts/gpu-bringup/compile_assets.py` (nvcc 13.2.86, the plan entry of
|
||||
/// `extra-seal-plan.json`) and installed by `seal_pins.py`.
|
||||
pub(super) const CHECK_BATCH_PIN: (usize, [u8; 32]) = (
|
||||
2050,
|
||||
[
|
||||
0x89, 0x7d, 0xf5, 0x42, 0x89, 0x1f, 0x07, 0x6f, 0xdc, 0x3e, 0x9c, 0x12, 0x80, 0xfb, 0xd0, 0x94, 0x82, 0x5a,
|
||||
0x19, 0x79, 0xfc, 0x74, 0xac, 0x15, 0x12, 0x4f, 0xce, 0x82, 0x34, 0x70, 0x6a, 0x66,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -23,6 +23,22 @@ impl Arguments {
|
||||
+ self.values.iter().map(|a| if matches!(a, Arg::GrMulti(_)) { 114 * 8 } else { 0 }).sum::<usize>()
|
||||
}
|
||||
|
||||
/// The three words of a check launch (buffer, count, status word), when the arguments are exactly those.
|
||||
pub(crate) fn check_words(&self) -> Option<(u64, i32, u64)> {
|
||||
match &*self.values {
|
||||
[Arg::U64(data), Arg::I32(count), Arg::U64(flag)] => Some((*data, *count, *flag)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn gr_words(&self) -> Option<&[u64; 114]> {
|
||||
match &*self.values {
|
||||
[Arg::GrMulti(words)] => Some(words),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new(values: Vec<Arg>) -> Result<Self> {
|
||||
let mut pointers = Vec::new();
|
||||
pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
|
||||
@@ -58,6 +58,7 @@ fn full_policy() -> OriginalMtpFullPolicy {
|
||||
kv: DraftKvPolicy::original_int8(1e7f32.powf(-2.0 / 64.0)),
|
||||
coupled_j: None,
|
||||
chain_pipeline: false,
|
||||
check_merge: false,
|
||||
}
|
||||
}
|
||||
impl<'ctx> Replay<'ctx> {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! The batched numerical guard of the MTP draft step (`LELEKA_DRAFT_CHECK_MERGE`, off by default): the host half.
|
||||
//!
|
||||
//! A draft step launches a finite check (`mtp_original_finite`, floats) or a Q8_1 scale check (`mtp_original_q8_guard`,
|
||||
//! blocks) after almost every kernel, one launch per buffer. Where several of those launches are ADJACENT in the
|
||||
//! program (no other kernel or copy between them) the buffers cannot change between the first and the last of them, so
|
||||
//! the run can be checked by one launch of `mtp_original_check_batch` at the position of the run, each entry setting
|
||||
//! the status word its own launch set. Nothing is moved across another command: the checked (buffer, moment) pairs and
|
||||
//! the status words are the ones of the separate launches.
|
||||
//!
|
||||
//! This module holds the pure parts: the descriptor the kernel reads (`encode`, the layout of
|
||||
//! `mtp_original_check_batch.cu`), the grouping of adjacent checks (`merge_adjacent`), and, in the tests, a reference
|
||||
//! of the kernel and the proof that a merged schedule leaves the same status words as the separate one for a
|
||||
//! non-finite value placed anywhere.
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// By-value words of the kernel parameter (the shape of the GrMulti parameter).
|
||||
pub const BATCH_WORDS: usize = 114;
|
||||
/// Words of one entry: buffer address, count and kind, status address, reserved.
|
||||
pub const ENTRY_WORDS: usize = 4;
|
||||
/// Entries one launch holds: word 0 is the count.
|
||||
pub const MAX_ENTRIES: usize = (BATCH_WORDS - 1) / ENTRY_WORDS;
|
||||
/// Threads per block of every check launch, single or batched.
|
||||
pub const THREADS: u32 = 256;
|
||||
|
||||
/// What a check reads: f32 words, or the `half2` scale pair at the head of each 36-byte Q8_1 block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CheckKind {
|
||||
Finite,
|
||||
Q8Scale,
|
||||
}
|
||||
|
||||
/// One check launch: `count` floats or blocks at `data`, a non-finite one sets bit 0 of the word at `flag`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Check {
|
||||
pub kind: CheckKind,
|
||||
pub data: u64,
|
||||
pub count: u32,
|
||||
pub flag: u64,
|
||||
}
|
||||
|
||||
impl Check {
|
||||
/// The grid of the separate launch of this check (block `THREADS`).
|
||||
pub fn single_grid(&self) -> u32 {
|
||||
self.count.div_ceil(THREADS)
|
||||
}
|
||||
}
|
||||
|
||||
/// The descriptor words and the grid of one batched launch.
|
||||
pub struct BatchLaunch {
|
||||
pub words: Box<[u64; BATCH_WORDS]>,
|
||||
pub grid: [u32; 3],
|
||||
}
|
||||
|
||||
/// The launch that checks `checks` (1 to `MAX_ENTRIES`): grid.y is the entry, grid.x covers the longest one.
|
||||
pub fn encode(checks: &[Check]) -> Result<BatchLaunch> {
|
||||
if checks.is_empty() || checks.len() > MAX_ENTRIES {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let mut words = Box::new([0u64; BATCH_WORDS]);
|
||||
words[0] = checks.len() as u64;
|
||||
for (e, check) in checks.iter().enumerate() {
|
||||
if check.count == 0 || check.count > i32::MAX as u32 || check.flag % 4 != 0 || check.data == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let kind = u64::from(check.kind == CheckKind::Q8Scale);
|
||||
words[1 + ENTRY_WORDS * e] = check.data;
|
||||
words[2 + ENTRY_WORDS * e] = u64::from(check.count) | kind << 32;
|
||||
words[3 + ENTRY_WORDS * e] = check.flag;
|
||||
}
|
||||
let x = checks.iter().map(Check::single_grid).max().unwrap_or(1);
|
||||
Ok(BatchLaunch { words, grid: [x, checks.len() as u32, 1] })
|
||||
}
|
||||
|
||||
/// Replaces every maximal run of adjacent checks (as `view` sees them) by batches of at most `MAX_ENTRIES`; a run or
|
||||
/// a chunk of one check, and every item before `keep`, stay as they are. Order and every other item are untouched.
|
||||
pub fn merge_adjacent<T>(
|
||||
items: Vec<T>,
|
||||
keep: usize,
|
||||
view: impl Fn(&T) -> Option<Check>,
|
||||
mut batch: impl FnMut(&[Check]) -> Result<T>,
|
||||
) -> Result<Vec<T>> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(items.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let mut run: Vec<(T, Check)> = Vec::new();
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
match view(&item).filter(|_| i >= keep) {
|
||||
Some(check) => run.push((item, check)),
|
||||
None => {
|
||||
flush_run(&mut run, &mut out, &mut batch)?;
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
flush_run(&mut run, &mut out, &mut batch)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn flush_run<T>(
|
||||
run: &mut Vec<(T, Check)>,
|
||||
out: &mut Vec<T>,
|
||||
batch: &mut impl FnMut(&[Check]) -> Result<T>,
|
||||
) -> Result<()> {
|
||||
let mut rest = std::mem::take(run);
|
||||
while !rest.is_empty() {
|
||||
let tail = rest.split_off(rest.len().min(MAX_ENTRIES));
|
||||
if rest.len() == 1 {
|
||||
out.extend(rest.drain(..).map(|(item, _)| item));
|
||||
} else {
|
||||
let checks: Vec<Check> = rest.iter().map(|(_, check)| *check).collect();
|
||||
out.push(batch(&checks)?);
|
||||
}
|
||||
rest = tail;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod model;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,249 @@
|
||||
//! The model of the device and of the draft step the tests run: memory, the single and batched kernels, schedules, and
|
||||
//! the checks of one step in program order.
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const BLOCK: u32 = THREADS;
|
||||
|
||||
// ------------------------------------------------------------------------------------- memory and kernels
|
||||
|
||||
/// Device memory of the model: f32 buffers, Q8_1 scale pairs, and the status words by address.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Memory {
|
||||
pub(super) floats: BTreeMap<u64, Vec<f32>>,
|
||||
pub(super) scales: BTreeMap<u64, Vec<[f32; 2]>>,
|
||||
pub(super) flags: BTreeMap<u64, u32>,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
/// `atomicOr(status, 1)` of the thread that found a non-finite value.
|
||||
fn raise(&mut self, flag: u64) {
|
||||
*self.flags.entry(flag).or_insert(0) |= 1;
|
||||
}
|
||||
fn bad(&self, kind: CheckKind, data: u64, i: usize) -> bool {
|
||||
match kind {
|
||||
CheckKind::Finite => !self.floats[&data][i].is_finite(),
|
||||
CheckKind::Q8Scale => self.scales[&data][i].iter().any(|v| !v.is_finite()),
|
||||
}
|
||||
}
|
||||
/// The grid-stride loop of one entry, for every (block, thread) of grid `x`; the body of both kernels.
|
||||
fn entry(&mut self, (kind, data, count, flag): (CheckKind, u64, u32, u64), x: u32) {
|
||||
for block in 0..x {
|
||||
for thread in 0..BLOCK {
|
||||
let mut i = block * BLOCK + thread;
|
||||
while i < count {
|
||||
if self.bad(kind, data, i as usize) {
|
||||
self.raise(flag);
|
||||
}
|
||||
i += x * BLOCK;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The separate launch: `mtp_original_finite` or `mtp_original_q8_guard`.
|
||||
pub(super) fn single(&mut self, c: &Check) {
|
||||
self.entry((c.kind, c.data, c.count, c.flag), c.single_grid());
|
||||
}
|
||||
/// `mtp_original_check_batch`, decoded from the descriptor words only, as the kernel does.
|
||||
pub(super) fn batch(&mut self, launch: &BatchLaunch) {
|
||||
let w = &launch.words;
|
||||
for e in 0..launch.grid[1] as usize {
|
||||
assert!(e < w[0] as usize, "a block row past the entry count returns");
|
||||
let meta = w[2 + ENTRY_WORDS * e];
|
||||
let kind = if meta >> 32 == 1 { CheckKind::Q8Scale } else { CheckKind::Finite };
|
||||
self.entry((kind, w[1 + ENTRY_WORDS * e], meta as u32, w[3 + ENTRY_WORDS * e]), launch.grid[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- schedules
|
||||
|
||||
/// A kernel that (re)writes buffers, a separate check, or a batch of checks.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) enum Op {
|
||||
Kernel(usize, Vec<u64>),
|
||||
Check(Check),
|
||||
Batch(Vec<Check>),
|
||||
}
|
||||
|
||||
pub(super) fn view(op: &Op) -> Option<Check> {
|
||||
match op {
|
||||
Op::Check(c) => Some(*c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn merge(ops: Vec<Op>, keep: usize) -> Vec<Op> {
|
||||
merge_adjacent(ops, keep, view, |checks| Ok(Op::Batch(checks.to_vec()))).unwrap()
|
||||
}
|
||||
|
||||
/// The separate schedule a merged one stands for.
|
||||
pub(super) fn expand(ops: &[Op]) -> Vec<Op> {
|
||||
ops.iter()
|
||||
.flat_map(|op| match op {
|
||||
Op::Batch(checks) => checks.iter().copied().map(Op::Check).collect(),
|
||||
other => vec![other.clone()],
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A non-finite value placed in `buffer[element]` right after kernel `after` wrote it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Fault {
|
||||
pub(super) after: usize,
|
||||
pub(super) buffer: u64,
|
||||
pub(super) element: usize,
|
||||
pub(super) value: f32,
|
||||
}
|
||||
|
||||
pub(super) fn write(memory: &mut Memory, buffer: u64, fault: Option<Fault>, kernel: usize) {
|
||||
if let Some(v) = memory.floats.get_mut(&buffer) {
|
||||
v.fill(1.0);
|
||||
}
|
||||
if let Some(v) = memory.scales.get_mut(&buffer) {
|
||||
v.fill([0.5, 2.0]);
|
||||
}
|
||||
let Some(f) = fault.filter(|f| f.after == kernel && f.buffer == buffer) else { return };
|
||||
if let Some(v) = memory.floats.get_mut(&buffer) {
|
||||
let len = v.len();
|
||||
v[f.element % len] = f.value;
|
||||
}
|
||||
if let Some(v) = memory.scales.get_mut(&buffer) {
|
||||
let len = v.len();
|
||||
v[f.element / 2 % len][f.element % 2] = f.value;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run(ops: &[Op], blank: &Memory, fault: Option<Fault>) -> BTreeMap<u64, u32> {
|
||||
let mut memory = blank.clone();
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Kernel(id, buffers) => buffers.iter().for_each(|b| write(&mut memory, *b, fault, *id)),
|
||||
Op::Check(c) => memory.single(c),
|
||||
Op::Batch(checks) => memory.batch(&encode(checks).unwrap()),
|
||||
}
|
||||
}
|
||||
memory.flags
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------- the draft step
|
||||
|
||||
pub(super) const FLAGS: u64 = 0x9000_0000;
|
||||
pub(super) const SCRATCH: u64 = 0x1000_0000;
|
||||
|
||||
pub(super) fn flag(slot: u64) -> u64 {
|
||||
FLAGS + 4 * slot
|
||||
}
|
||||
pub(super) fn buf(i: u64) -> u64 {
|
||||
SCRATCH + 0x10_0000 * i
|
||||
}
|
||||
pub(super) fn finite(i: u64, count: u32, slot: u64) -> Op {
|
||||
Op::Check(Check { kind: CheckKind::Finite, data: buf(i), count, flag: flag(slot) })
|
||||
}
|
||||
pub(super) fn q8(i: u64, count: u32, slot: u64) -> Op {
|
||||
Op::Check(Check { kind: CheckKind::Q8Scale, data: buf(i), count, flag: flag(slot) })
|
||||
}
|
||||
pub(super) fn kernel(id: usize, writes: &[u64]) -> Op {
|
||||
Op::Kernel(id, writes.iter().map(|i| buf(*i)).collect())
|
||||
}
|
||||
|
||||
/// The checked buffers with their sizes: floats, or Q8_1 blocks for the ones in `Q8`.
|
||||
pub(super) const SIZES: [(u64, usize); 13] = [
|
||||
(0, 12288),
|
||||
(1, 6144),
|
||||
(2, 6144),
|
||||
(3, 6144),
|
||||
(4, 2560),
|
||||
(5, 10240),
|
||||
(6, 10240),
|
||||
(7, 320),
|
||||
(8, 4),
|
||||
(9, 2560),
|
||||
(10, 640),
|
||||
(11, 640),
|
||||
(12, 1),
|
||||
];
|
||||
pub(super) const Q8: [(u64, usize); 2] = [(20, 192), (21, 20)];
|
||||
|
||||
pub(super) fn blank() -> Memory {
|
||||
let mut m = Memory::default();
|
||||
for (i, n) in SIZES {
|
||||
m.floats.insert(buf(i), vec![1.0; n]);
|
||||
}
|
||||
for (i, n) in Q8 {
|
||||
m.scales.insert(buf(i), vec![[0.5, 2.0]; n]);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The checks of one draft step in the order of the program: the prefix (with its run of five guards after the GR
|
||||
/// block) and the tail (with its runs of five after the MLP GR and of two after the shared gate and up), the kernels
|
||||
/// between written as buffer writers. Buffers 1, 5, 6, 7 and 8 are written more than once, like `qcur`, `r`, `xn` and
|
||||
/// `lo`.
|
||||
pub(super) fn draft_step() -> Vec<Op> {
|
||||
[prefix_part(), tail_part()].concat()
|
||||
}
|
||||
|
||||
/// The scalar prefix: its guards, with the run of five after the GR block.
|
||||
pub(super) fn prefix_part() -> Vec<Op> {
|
||||
vec![
|
||||
kernel(0, &[9]),
|
||||
finite(9, 2560, 0),
|
||||
kernel(1, &[5]),
|
||||
finite(5, 10240, 1),
|
||||
kernel(2, &[20]),
|
||||
q8(20, 192, 2),
|
||||
kernel(3, &[6]),
|
||||
finite(6, 10240, 3),
|
||||
kernel(4, &[6, 7, 8, 9, 12]),
|
||||
finite(8, 4, 6),
|
||||
finite(6, 10240, 6),
|
||||
finite(7, 320, 7),
|
||||
finite(12, 1, 7),
|
||||
finite(9, 2560, 8),
|
||||
kernel(5, &[10]),
|
||||
finite(10, 640, 10),
|
||||
kernel(6, &[11]),
|
||||
finite(11, 640, 11),
|
||||
]
|
||||
}
|
||||
|
||||
/// The tail: attention and gate, the MLP GR with its run of five, the router and experts, the shared expert with its
|
||||
/// run of two, the combine.
|
||||
pub(super) fn tail_part() -> Vec<Op> {
|
||||
vec![
|
||||
kernel(7, &[0]),
|
||||
finite(0, 12288, 0),
|
||||
kernel(8, &[1]),
|
||||
finite(1, 6144, 1),
|
||||
kernel(9, &[1]),
|
||||
finite(1, 6144, 2),
|
||||
kernel(10, &[2, 3]),
|
||||
finite(2, 6144, 3),
|
||||
kernel(11, &[4]),
|
||||
finite(3, 6144, 4),
|
||||
kernel(17, &[21]),
|
||||
q8(21, 20, 5),
|
||||
kernel(12, &[4]),
|
||||
finite(4, 2560, 6),
|
||||
kernel(13, &[5, 6, 7, 8, 12]),
|
||||
finite(5, 10240, 7),
|
||||
finite(6, 10240, 8),
|
||||
finite(7, 320, 9),
|
||||
finite(8, 4, 10),
|
||||
finite(9, 2560, 11),
|
||||
kernel(14, &[10]),
|
||||
finite(10, 640, 12),
|
||||
kernel(15, &[11]),
|
||||
finite(11, 640, 13),
|
||||
finite(12, 1, 13),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn checks_in(ops: &[Op]) -> usize {
|
||||
ops.iter().map(|op| expand(std::slice::from_ref(op)).iter().filter(|o| view(o).is_some()).count()).sum()
|
||||
}
|
||||
|
||||
pub(super) fn launches_in(ops: &[Op]) -> usize {
|
||||
ops.len()
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! The batched guard leaves the status words of the separate launches, for a non-finite value anywhere.
|
||||
use super::model::*;
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ tests
|
||||
|
||||
#[test]
|
||||
fn the_step_loses_exactly_the_adjacent_check_launches() {
|
||||
let step = draft_step();
|
||||
let merged = merge(step.clone(), 0);
|
||||
assert_eq!(checks_in(&merged), checks_in(&step));
|
||||
// runs of five (prefix guards), five (MLP GR outputs) and two (shared gate and up): 12 launches become 3
|
||||
assert_eq!(launches_in(&step) - launches_in(&merged), 9);
|
||||
assert_eq!(merged.iter().filter(|op| matches!(op, Op::Batch(_))).count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_merged_schedule_expands_to_the_separate_one() {
|
||||
let step = draft_step();
|
||||
assert_eq!(expand(&merge(step.clone(), 0)), step);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_finite_value_anywhere_leaves_the_same_status_words() {
|
||||
let step = draft_step();
|
||||
let merged = merge(step.clone(), 0);
|
||||
let memory = blank();
|
||||
assert_eq!(run(&step, &memory, None), run(&merged, &memory, None));
|
||||
let (mut caught, mut missed) = (0, 0);
|
||||
for fault in faults(&step, &memory) {
|
||||
let separate = run(&step, &memory, Some(fault));
|
||||
let together = run(&merged, &memory, Some(fault));
|
||||
assert_eq!(separate, together, "fault {:?} after kernel {}", fault.value, fault.after);
|
||||
if separate.is_empty() { missed += 1 } else { caught += 1 }
|
||||
}
|
||||
// the model is not vacuous: most faults are caught, and the ones that are not (a buffer overwritten before its
|
||||
// check) are missed by both
|
||||
assert!(caught > 400 && missed > 0, "caught {caught}, missed {missed}");
|
||||
}
|
||||
|
||||
/// Every kernel output, at the first, the last, the block edges and a middle element, with NaN, +Inf and -Inf.
|
||||
fn faults(ops: &[Op], memory: &Memory) -> Vec<Fault> {
|
||||
let mut all = Vec::new();
|
||||
for op in ops {
|
||||
let Op::Kernel(after, buffers) = op else { continue };
|
||||
for &buffer in buffers {
|
||||
let len = memory.floats.get(&buffer).map_or_else(|| memory.scales[&buffer].len() * 2, Vec::len);
|
||||
let spots = [0, 1, 255, 256, 257, len / 2, len - 1].map(|e| e.min(len - 1));
|
||||
for element in spots {
|
||||
for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
all.push(Fault { after: *after, buffer, element, value });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_status_word_stays_the_one_of_its_own_check() {
|
||||
let step = draft_step();
|
||||
let merged = merge(step.clone(), 0);
|
||||
let memory = blank();
|
||||
// a fault in a buffer raises the words of exactly the checks of that buffer after its last write, in both
|
||||
let fault = Fault { after: 13, buffer: buf(6), element: 9000, value: f32::NAN };
|
||||
let words = run(&merged, &memory, Some(fault));
|
||||
assert_eq!(words.keys().copied().collect::<Vec<_>>(), vec![flag(8)]);
|
||||
assert_eq!(words, run(&step, &memory, Some(fault)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_longer_than_a_launch_are_chunked_and_still_expand_to_the_original() {
|
||||
for n in [1usize, 2, 27, 28, 29, 56, 57, 70] {
|
||||
let ops: Vec<Op> = (0..n).map(|i| finite(i as u64 % 13, 4, i as u64)).collect();
|
||||
let merged = merge(ops.clone(), 0);
|
||||
assert_eq!(expand(&merged), ops, "run of {n}");
|
||||
let expected = n / MAX_ENTRIES + usize::from(n % MAX_ENTRIES != 0);
|
||||
assert_eq!(merged.len(), expected, "launches of a run of {n}");
|
||||
assert!(merged.iter().all(|op| !matches!(op, Op::Batch(c) if c.len() < 2 || c.len() > MAX_ENTRIES)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_adjacent_checks_are_merged_and_everything_else_is_untouched() {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
for _ in 0..200 {
|
||||
let ops: Vec<Op> = (0..60)
|
||||
.map(|i| if next() % 3 == 0 { kernel(i, &[next() % 13]) } else { finite(next() % 13, 8, i as u64) })
|
||||
.collect();
|
||||
let keep = (next() % 10) as usize;
|
||||
let merged = merge(ops.clone(), keep);
|
||||
assert_eq!(expand(&merged), ops);
|
||||
assert_eq!(&merged[..keep.min(merged.len())], &ops[..keep.min(merged.len())].to_vec()[..], "items before keep");
|
||||
// between two batches or checks of the result there is a kernel: no two adjacent check launches remain unless
|
||||
// they are on both sides of the protected prefix
|
||||
for pair in merged.windows(2).skip(keep) {
|
||||
let is_check = |op: &Op| matches!(op, Op::Check(_) | Op::Batch(_));
|
||||
assert!(!(is_check(&pair[0]) && is_check(&pair[1])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_protected_prefix_is_never_merged() {
|
||||
let ops = vec![finite(0, 4, 0), finite(1, 4, 1), finite(2, 4, 2), finite(3, 4, 3)];
|
||||
let merged = merge(ops.clone(), 2);
|
||||
assert_eq!(merged.len(), 3);
|
||||
assert_eq!(&merged[..2], &ops[..2]);
|
||||
assert!(matches!(&merged[2], Op::Batch(c) if c.len() == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_descriptor_is_the_layout_the_kernel_reads() {
|
||||
let checks = [
|
||||
Check { kind: CheckKind::Finite, data: 0x1000, count: 10240, flag: 0x2004 },
|
||||
Check { kind: CheckKind::Q8Scale, data: 0x3000, count: 80, flag: 0x2008 },
|
||||
];
|
||||
let launch = encode(&checks).unwrap();
|
||||
assert_eq!(launch.grid, [40, 2, 1]);
|
||||
assert_eq!(launch.words[..9], [2, 0x1000, 10240, 0x2004, 0, 0x3000, 80 | 1 << 32, 0x2008, 0]);
|
||||
assert!(launch.words[9..].iter().all(|w| *w == 0));
|
||||
let source = driver_source!("src/mtp_original_check_batch.cu");
|
||||
for needle in [
|
||||
"unsigned long long w[114]",
|
||||
"sizeof(CheckBatch) == 912",
|
||||
"b.w[1 + 4 * entry]",
|
||||
"b.w[2 + 4 * entry]",
|
||||
"b.w[3 + 4 * entry]",
|
||||
"meta & 0xffffffffull",
|
||||
"meta >> 32",
|
||||
"blockIdx.y",
|
||||
"!isfinite(reinterpret_cast<const float*>(data)[i])",
|
||||
"!isfinite(ds.x) || !isfinite(ds.y)",
|
||||
"atomicOr(status, 1)",
|
||||
] {
|
||||
assert!(source.contains(needle), "kernel source lost `{needle}`");
|
||||
}
|
||||
assert_eq!(MAX_ENTRIES, 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_descriptor_that_the_kernel_could_misread_is_refused() {
|
||||
let ok = Check { kind: CheckKind::Finite, data: 0x1000, count: 4, flag: 0x2000 };
|
||||
assert!(encode(&[ok]).is_ok());
|
||||
assert!(encode(&[]).is_err());
|
||||
assert!(encode(&vec![ok; MAX_ENTRIES + 1]).is_err());
|
||||
assert!(encode(&[Check { count: 0, ..ok }]).is_err());
|
||||
assert!(encode(&[Check { count: i32::MAX as u32 + 1, ..ok }]).is_err());
|
||||
assert!(encode(&[Check { flag: 0x2001, ..ok }]).is_err());
|
||||
assert!(encode(&[Check { data: 0, ..ok }]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_single_launch_grid_is_the_one_the_old_programs_used() {
|
||||
let c = |count| Check { kind: CheckKind::Finite, data: 8, count, flag: 4 };
|
||||
assert_eq!([c(1).single_grid(), c(256).single_grid(), c(257).single_grid(), c(12288).single_grid()], [1, 1, 2, 48]);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ macro_rules! driver_source {
|
||||
mod bringup_trace;
|
||||
pub mod command_profile;
|
||||
pub mod device_arena;
|
||||
pub mod draft_check_batch;
|
||||
mod error;
|
||||
mod error_display;
|
||||
pub mod host_profile;
|
||||
|
||||
@@ -223,6 +223,7 @@ pub(in crate::qwen_forward) fn mtp_full_policy(rope: &RopeConstants) -> Original
|
||||
kv: rope.draft_kv(),
|
||||
coupled_j: None,
|
||||
chain_pipeline: crate::settings::process().serve.draft_chain_pipeline,
|
||||
check_merge: crate::settings::process().serve.draft_check_merge,
|
||||
}
|
||||
}
|
||||
pub(in crate::qwen_forward) fn mtp_scalar_policy(rope: &RopeConstants) -> OriginalMtpScalarPolicy {
|
||||
|
||||
@@ -72,6 +72,7 @@ fn mtp_policies_stay_inside_the_closed_profile_and_share_one_kv_policy() {
|
||||
assert!(full.native_router && full.native_combine && full.native_shared_scalar && full.native_final_gr);
|
||||
assert!(!full.old_grouped_s2 && !full.fp32_final_gr && full.coupled_j.is_none() && full.legacy_router_mode == 0);
|
||||
assert!(!full.chain_pipeline, "the chain pipeline is opt-in");
|
||||
assert!(!full.check_merge, "the merged draft checks are opt-in");
|
||||
assert!(full.gr == OriginalMtpGrVariant::Plain && scalar.gr == OriginalMtpGrVariant::Plain);
|
||||
assert!(!scalar.per_group_sync);
|
||||
assert_eq!(full.kv.theta_scale, scalar.kv.theta_scale);
|
||||
|
||||
@@ -31,6 +31,9 @@ pub(crate) struct ServeSettings {
|
||||
/// `LELEKA_DRAFT_CHAIN_PIPELINE` is `1` or `on`: the MTP chain steps of a greedy draft run back to back, one
|
||||
/// stream drain for the run (identity and paired A/B of docs/experiments/decode-tail-5090.md).
|
||||
pub(crate) draft_chain_pipeline: bool,
|
||||
/// `LELEKA_DRAFT_CHECK_MERGE` is `1` or `on`: the adjacent finite and Q8_1 scale guards of the MTP draft step are
|
||||
/// launched as one batched guard (the same checks of the same buffers, fewer launches; the ledger row O8).
|
||||
pub(crate) draft_check_merge: bool,
|
||||
}
|
||||
|
||||
impl ServeSettings {
|
||||
@@ -47,6 +50,7 @@ impl ServeSettings {
|
||||
cpu_pool_plan: equals(env, "LELEKA_CPU_POOL_PLAN", "on"),
|
||||
prefill_loan_tiers: one_of(env, "LELEKA_PREFILL_LOAN_TIERS", &["1", "on"]),
|
||||
draft_chain_pipeline: one_of(env, "LELEKA_DRAFT_CHAIN_PIPELINE", &["1", "on"]),
|
||||
draft_check_merge: one_of(env, "LELEKA_DRAFT_CHECK_MERGE", &["1", "on"]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,3 +96,11 @@ fn the_draft_chain_pipeline_is_one_or_on_and_off_by_default() {
|
||||
assert_eq!(serve(&[("LELEKA_DRAFT_CHAIN_PIPELINE", value)]).draft_chain_pipeline, want, "pipeline {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_draft_check_merge_is_one_or_on_and_off_by_default() {
|
||||
assert!(!serve(&[]).draft_check_merge);
|
||||
for (value, want) in [("1", true), ("on", true), ("0", false), ("off", false), ("yes", false), ("", false)] {
|
||||
assert_eq!(serve(&[("LELEKA_DRAFT_CHECK_MERGE", value)]).draft_check_merge, want, "merge {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -927,6 +927,25 @@
|
||||
},
|
||||
"group": "draft-round",
|
||||
"optional": false
|
||||
},
|
||||
{
|
||||
"cu": "crates/cuda-driver/src/mtp_original_check_batch.cu",
|
||||
"ptx": "crates/cuda-driver/src/mtp_original_check_batch.ptx",
|
||||
"flags": [
|
||||
"-ptx",
|
||||
"-O3",
|
||||
"-arch=sm_120",
|
||||
"-std=c++17",
|
||||
"--fmad=true",
|
||||
"--ftz=false"
|
||||
],
|
||||
"policy": "precise (the recipe of scripts/build-original-verify-ptx.sh, which built the single-check kernels this one batches; the predicate is the same abs + setp.ne inf)",
|
||||
"entries": [
|
||||
"mtp_original_check_batch"
|
||||
],
|
||||
"encoding": "include_bytes",
|
||||
"group": "draft-check-batch",
|
||||
"optional": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user