diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe.rs b/crates/cuda-driver/tests/original_serve_preflight_probe.rs index df3ac630..4f495dc5 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe.rs @@ -1,212 +1,212 @@ -//! Model-free GPU preflight of `OriginalServeStack::open` / `serve()` (bring-up debugging). -//! -//! Every test builds device objects the serve path constructs WITHOUT needing model weights, one per step, and -//! prints `PREFLIGHT ok|ERR: ` (no panic on the first refusal, so one run reports every -//! trap). A pin mismatch on a sealed asset only shows when the owning object is first constructed, which is what -//! these steps do. Nothing here is a numerical check; no model, shard, capture or credential is read. -//! -//! Run (one thread, or the process-wide GPU lock below serializes them anyway): -//! cargo test --locked --release -p leleka-cuda-driver --features cuda-driver --test original_serve_preflight_probe \ -//! -- --ignored --nocapture --test-threads=1 -//! -//! Environment overrides (all optional): -//! PROBE_BUDGET_GIB context budget in GiB (default 6) -//! PROBE_CAPACITY prompt chunk capacity of the prefill arena (default 1024) -//! PROBE_MAX_T verifier window width / MTP max_t (default 8) -//! PROBE_CELLS serving cell count `max_cells` (default 262144, the trained context) -//! PROBE_GU_MAX/DOWN_MAX/MAX_BLOB per-expert byte sizes the arena is carved from -//! (defaults: IQ3_S gate+up 1408000, IQ4_NL down 921600, blob 2329600) -//! PROBE_HEAD_KIND ggml type id of the native output head (default 14, Q6_K) -//! PROBE_VOCAB vocabulary (default 248320) -use leleka_cuda_driver::*; -use std::sync::Mutex; - -static GPU: Mutex<()> = Mutex::new(()); - -macro_rules! step { - ($name:expr, $e:expr) => {{ - match $e { - Ok(v) => { - eprintln!("PREFLIGHT {} ok", $name); - Some(v) - } - Err(e) => { - eprintln!("PREFLIGHT {} ERR: {e:?}", $name); - None - } - } - }}; -} - -fn env_usize(name: &str, default: usize) -> usize { - std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default) -} - -fn budget() -> usize { - env_usize("PROBE_BUDGET_GIB", 6) << 30 -} - -/// The mode17 verifier geometry exactly as `verify_geometry` in the runtime builds it. -fn geometry(max_t: usize, max_cells: usize, max_blob: usize) -> OriginalVerifyGeometry { - OriginalVerifyGeometry { - max_t, - n: 2560, - hc: 4, - lr: 320, - ff: 640, - experts: 512, - k: 10, - channels: 10240, - value_heads: 48, - key_heads: 16, - heads: 24, - kv_heads: 2, - head_dim: 256, - index_heads: 4, - index_dim: 128, - index_block: 4, - selection: 2051, - max_cells, - vocabulary: env_usize("PROBE_VOCAB", 248_320), - max_expert_blob: max_blob, - } -} - -/// `prefill_layout_options` of the runtime (original_serve_config.rs). -fn layout_options(capacity: usize, max_cells: usize) -> PrefillLayoutOptions { - PrefillLayoutOptions { - capacity, - n_expert: 512, - qsa_heads: 24, - qsa_selection: 2051, - qsa_max_blocks: max_cells / 4 + 2, - mmq_any: true, - mmq_fallback: false, - mmq_gu_max: env_usize("PROBE_GU_MAX", 1_408_000), - mmq_down_max: env_usize("PROBE_DOWN_MAX", 921_600), - max_expert_blob: env_usize("PROBE_MAX_BLOB", 2_329_600), - pinned_share: 1.0, - stream_all_min: 1024, - ring_override: None, - gr_unfused: false, - bf16x2: false, - bf16x2_hc: false, - kv_stage: PrefillKvStage::Int8 { rows: max_cells * 2, head_dim: 256, without_key: false }, - kv_stage_own: false, - } -} - -/// Which gating assets the build itself reports as unsealed (no GPU needed beyond the process). -#[test] -#[ignore = "GPU bring-up probe; no model"] -fn preflight_00_sealed_asset_report() { - let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); - let status = original_serve_asset_status(); - let mut unsealed = 0; - for a in &status { - if !a.sealed { - unsealed += 1; - } - eprintln!("PREFLIGHT asset {:?} {} sealed={}", a.kind, a.name, a.sealed); - } - eprintln!("PREFLIGHT assets total={} unsealed={unsealed} window_unsealed={:?}", status.len(), unsealed_window_assets()); - eprintln!("PREFLIGHT UNBOUND_PRODUCERS={UNBOUND_PRODUCERS:?}"); - let serving = serving_context(); - eprintln!("PREFLIGHT serving_cells={}", serving.geometry.cells()); -} - -/// Device limits the sealed kernels assume (compute capability 12, shared-memory opt-in, SM count). -#[test] -#[ignore = "GPU bring-up probe; no model"] -fn preflight_01_device_limits() { - let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device 0"); - let context = device.create_context(budget()).expect("context"); - let (free, total) = context.memory_info().expect("memory_info"); - eprintln!("PREFLIGHT context ok budget={}GiB free={}MiB total={}MiB", budget() >> 30, free >> 20, total >> 20); - let bank = step!("original_verify_bank(geometry)", context.original_verify_bank(geometry(8, env_usize("PROBE_CELLS", 262_144), 2_329_600))); - drop(bank); -} - -/// Every no-weight constructor that the first request builds lazily (after `open`), or `open` builds without weights. -#[test] -#[ignore = "GPU bring-up probe; no model"] -fn preflight_10_lazy_constructors() { - let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device 0"); - let context = device.create_context(budget()).expect("context"); - let capacity = env_usize("PROBE_CAPACITY", 1024); - let max_t = env_usize("PROBE_MAX_T", 8); - let vocab = env_usize("PROBE_VOCAB", 248_320); - - let _a = step!("original_sampler(rows 8, vocab, history 4096)", context.original_sampler(8, vocab, 4096)); - let _b = step!("original_gpu_stream(BlockingCapture)", context.original_gpu_stream(OriginalStreamKind::BlockingCapture)); - let _c = step!("original_gpu_stream(NonBlocking)", context.original_gpu_stream(OriginalStreamKind::NonBlocking)); - let _d = step!("original_gpu_event(Completion)", context.original_gpu_event(OriginalEventKind::Completion)); - let _e = step!("original_gpu_event(Timing)", context.original_gpu_event(OriginalEventKind::Timing)); - let _f = step!("original_default_gpu_stream", context.original_default_gpu_stream()); - let _g = step!("original_ple_history(9*10240 zeros)", context.original_ple_history(&vec![0.0f32; 9 * 10240])); - let _h = step!("native_batch_workspace", context.native_batch_workspace()); - let _i = step!("gdn_row_queue", context.gdn_row_queue()); - let _j = step!("routed_stage_finite_guard", context.routed_stage_finite_guard()); - let _k = step!("routed_group_workspace", context.routed_group_workspace()); - let _l = step!("routed_resident_queue", context.routed_resident_queue()); - let _m = step!("mtp_input_workspace", context.mtp_input_workspace()); - let _n = step!("native_mmq_workspace", context.native_mmq_workspace()); - let _o = step!("native_integer_iq3_mmq_workspace", context.native_integer_iq3_mmq_workspace()); - let _p = step!("mtp_dense_kv_ring", context.mtp_dense_kv_ring()); - let _q = step!("shared_expert_workspace", context.shared_expert_workspace()); - let _r = step!("moe_prefill_batch", context.moe_prefill_batch()); - let _s = step!("head_greedy_workspace", context.head_greedy_workspace()); - let _t = step!("mapped_expert_copy_scratch", context.mapped_expert_copy_scratch()); - let _u = step!("mtp_original_int8(max_t)", context.mtp_original_int8(max_t)); - let _v = step!("qsa_native_decode", context.qsa_native_decode()); - let _w = step!("qsa_native_gate", context.qsa_native_gate()); - let _x = step!("qsa_prompt_stage", context.qsa_prompt_stage()); - let _y = step!("original_moe_prompt_device(capacity)", context.original_moe_prompt_device(capacity)); - let _z = step!("original_mmq_copy_schedule(32)", context.original_mmq_copy_schedule(32)); - let streams = vec![0.0f32; capacity * 10240]; - let _a1 = step!("gr_native_prompt_batch(capacity)", context.gr_native_prompt_batch(capacity, &streams, GrNativeProfile::HighOnly)); - let _a2 = step!("gdn_prefill_batch_for_prompt(capacity)", context.gdn_prefill_batch_for_prompt(capacity)); - let _a3 = step!("ple_batch_queue_for_prompt(capacity)", context.ple_batch_queue_for_prompt(PleBf16Mode::HighOnly, capacity)); - let _a4 = step!("qsa_native_batch_workspace_for_prompt(capacity)", context.qsa_native_batch_workspace_for_prompt(QsaNativePacking::HighOnly, capacity)); - let _a5 = step!("qsa_prompt_index_workspace_for_capacity", context.qsa_prompt_index_workspace_for_capacity(capacity)); - let _a6 = step!("qsa_prompt_attention_for_capacity", context.qsa_prompt_attention_for_capacity(capacity)); - let _a7 = step!("qsa_prompt_kv", context.qsa_prompt_kv()); - let _a8 = step!("original_qsa_resident_scalar_index", context.original_qsa_resident_scalar_index()); - let _a9 = step!("mtp_original_int8 vocabulary guard", Ok::<_, Error>(vocab)); -} - -/// `OriginalServeStack::open` -> `context.original_prefill_arena(layout)` (sized from the blob byte sizes). -#[test] -#[ignore = "GPU bring-up probe; no model"] -fn preflight_20_prefill_arena() { - let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device 0"); - let context = device.create_context(budget()).expect("context"); - let capacity = env_usize("PROBE_CAPACITY", 1024); - let cells = env_usize("PROBE_CELLS", 262_144); - let options = layout_options(capacity, cells); - match options.carve() { - Ok(layout) => eprintln!( - "PREFLIGHT arena layout borrowed={}MiB separately_owned={}MiB source_needed={}MiB shared_region={}MiB ring_slots={}", - layout.borrowed_bytes >> 20, - layout.separately_owned_bytes >> 20, - layout.source_bytes_needed >> 20, - layout.shared_region_bytes >> 20, - layout.ring_slots - ), - Err(e) => eprintln!("PREFLIGHT arena carve ERR: {e:?}"), - } - let arena = step!("original_prefill_arena(layout)", context.original_prefill_arena(options)); - if let Some(arena) = &arena { - eprintln!("PREFLIGHT arena physically_owned={}MiB capacity={}", arena.physically_owned_bytes() >> 20, arena.capacity()); - } - eprintln!("PREFLIGHT context allocated={}MiB", context.allocated_bytes() >> 20); -} +//! Model-free GPU preflight of `OriginalServeStack::open` / `serve()` (bring-up debugging). +//! +//! Every test builds device objects the serve path constructs WITHOUT needing model weights, one per step, and +//! prints `PREFLIGHT ok|ERR: ` (no panic on the first refusal, so one run reports every +//! trap). A pin mismatch on a sealed asset only shows when the owning object is first constructed, which is what +//! these steps do. Nothing here is a numerical check; no model, shard, capture or credential is read. +//! +//! Run (one thread, or the process-wide GPU lock below serializes them anyway): +//! cargo test --locked --release -p leleka-cuda-driver --features cuda-driver --test original_serve_preflight_probe \ +//! -- --ignored --nocapture --test-threads=1 +//! +//! Environment overrides (all optional): +//! PROBE_BUDGET_GIB context budget in GiB (default 6) +//! PROBE_CAPACITY prompt chunk capacity of the prefill arena (default 1024) +//! PROBE_MAX_T verifier window width / MTP max_t (default 8) +//! PROBE_CELLS serving cell count `max_cells` (default 262144, the trained context) +//! PROBE_GU_MAX/DOWN_MAX/MAX_BLOB per-expert byte sizes the arena is carved from +//! (defaults: IQ3_S gate+up 1408000, IQ4_NL down 921600, blob 2329600) +//! PROBE_HEAD_KIND ggml type id of the native output head (default 14, Q6_K) +//! PROBE_VOCAB vocabulary (default 248320) +use leleka_cuda_driver::*; +use std::sync::Mutex; + +static GPU: Mutex<()> = Mutex::new(()); + +macro_rules! step { + ($name:expr, $e:expr) => {{ + match $e { + Ok(v) => { + eprintln!("PREFLIGHT {} ok", $name); + Some(v) + } + Err(e) => { + eprintln!("PREFLIGHT {} ERR: {e:?}", $name); + None + } + } + }}; +} + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default) +} + +fn budget() -> usize { + env_usize("PROBE_BUDGET_GIB", 6) << 30 +} + +/// The mode17 verifier geometry exactly as `verify_geometry` in the runtime builds it. +fn geometry(max_t: usize, max_cells: usize, max_blob: usize) -> OriginalVerifyGeometry { + OriginalVerifyGeometry { + max_t, + n: 2560, + hc: 4, + lr: 320, + ff: 640, + experts: 512, + k: 10, + channels: 10240, + value_heads: 48, + key_heads: 16, + heads: 24, + kv_heads: 2, + head_dim: 256, + index_heads: 4, + index_dim: 128, + index_block: 4, + selection: 2051, + max_cells, + vocabulary: env_usize("PROBE_VOCAB", 248_320), + max_expert_blob: max_blob, + } +} + +/// `prefill_layout_options` of the runtime (original_serve_config.rs). +fn layout_options(capacity: usize, max_cells: usize) -> PrefillLayoutOptions { + PrefillLayoutOptions { + capacity, + n_expert: 512, + qsa_heads: 24, + qsa_selection: 2051, + qsa_max_blocks: max_cells / 4 + 2, + mmq_any: true, + mmq_fallback: false, + mmq_gu_max: env_usize("PROBE_GU_MAX", 1_408_000), + mmq_down_max: env_usize("PROBE_DOWN_MAX", 921_600), + max_expert_blob: env_usize("PROBE_MAX_BLOB", 2_329_600), + pinned_share: 1.0, + stream_all_min: 1024, + ring_override: None, + gr_unfused: false, + bf16x2: false, + bf16x2_hc: false, + kv_stage: PrefillKvStage::Int8 { rows: max_cells * 2, head_dim: 256, without_key: false }, + kv_stage_own: false, + } +} + +/// Which gating assets the build itself reports as unsealed (no GPU needed beyond the process). +#[test] +#[ignore = "GPU bring-up probe; no model"] +fn preflight_00_sealed_asset_report() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); + let status = original_serve_asset_status(); + let mut unsealed = 0; + for a in &status { + if !a.sealed { + unsealed += 1; + } + eprintln!("PREFLIGHT asset {:?} {} sealed={}", a.kind, a.name, a.sealed); + } + eprintln!("PREFLIGHT assets total={} unsealed={unsealed} window_unsealed={:?}", status.len(), unsealed_window_assets()); + eprintln!("PREFLIGHT UNBOUND_PRODUCERS={UNBOUND_PRODUCERS:?}"); + let serving = serving_context(); + eprintln!("PREFLIGHT serving_cells={}", serving.geometry.cells()); +} + +/// Device limits the sealed kernels assume (compute capability 12, shared-memory opt-in, SM count). +#[test] +#[ignore = "GPU bring-up probe; no model"] +fn preflight_01_device_limits() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device 0"); + let context = device.create_context(budget()).expect("context"); + let (free, total) = context.memory_info().expect("memory_info"); + eprintln!("PREFLIGHT context ok budget={}GiB free={}MiB total={}MiB", budget() >> 30, free >> 20, total >> 20); + let bank = step!("original_verify_bank(geometry)", context.original_verify_bank(geometry(8, env_usize("PROBE_CELLS", 262_144), 2_329_600))); + drop(bank); +} + +/// Every no-weight constructor that the first request builds lazily (after `open`), or `open` builds without weights. +#[test] +#[ignore = "GPU bring-up probe; no model"] +fn preflight_10_lazy_constructors() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device 0"); + let context = device.create_context(budget()).expect("context"); + let capacity = env_usize("PROBE_CAPACITY", 1024); + let max_t = env_usize("PROBE_MAX_T", 8); + let vocab = env_usize("PROBE_VOCAB", 248_320); + + let _a = step!("original_sampler(rows 8, vocab, history 4096)", context.original_sampler(8, vocab, 4096)); + let _b = step!("original_gpu_stream(BlockingCapture)", context.original_gpu_stream(OriginalStreamKind::BlockingCapture)); + let _c = step!("original_gpu_stream(NonBlocking)", context.original_gpu_stream(OriginalStreamKind::NonBlocking)); + let _d = step!("original_gpu_event(Completion)", context.original_gpu_event(OriginalEventKind::Completion)); + let _e = step!("original_gpu_event(Timing)", context.original_gpu_event(OriginalEventKind::Timing)); + let _f = step!("original_default_gpu_stream", context.original_default_gpu_stream()); + let _g = step!("original_ple_history(9*10240 zeros)", context.original_ple_history(&vec![0.0f32; 9 * 10240])); + let _h = step!("native_batch_workspace", context.native_batch_workspace()); + let _i = step!("gdn_row_queue", context.gdn_row_queue()); + let _j = step!("routed_stage_finite_guard", context.routed_stage_finite_guard()); + let _k = step!("routed_group_workspace", context.routed_group_workspace()); + let _l = step!("routed_resident_queue", context.routed_resident_queue()); + let _m = step!("mtp_input_workspace", context.mtp_input_workspace()); + let _n = step!("native_mmq_workspace", context.native_mmq_workspace()); + let _o = step!("native_integer_iq3_mmq_workspace", context.native_integer_iq3_mmq_workspace()); + let _p = step!("mtp_dense_kv_ring", context.mtp_dense_kv_ring()); + let _q = step!("shared_expert_workspace", context.shared_expert_workspace()); + let _r = step!("moe_prefill_batch", context.moe_prefill_batch()); + let _s = step!("head_greedy_workspace", context.head_greedy_workspace()); + let _t = step!("mapped_expert_copy_scratch", context.mapped_expert_copy_scratch()); + let _u = step!("mtp_original_int8(max_t)", context.mtp_original_int8(max_t)); + let _v = step!("qsa_native_decode", context.qsa_native_decode()); + let _w = step!("qsa_native_gate", context.qsa_native_gate()); + let _x = step!("qsa_prompt_stage", context.qsa_prompt_stage()); + let _y = step!("original_moe_prompt_device(capacity)", context.original_moe_prompt_device(capacity)); + let _z = step!("original_mmq_copy_schedule(32)", context.original_mmq_copy_schedule(32)); + let streams = vec![0.0f32; capacity * 10240]; + let _a1 = step!("gr_native_prompt_batch(capacity)", context.gr_native_prompt_batch(capacity, &streams, GrNativeProfile::HighOnly)); + let _a2 = step!("gdn_prefill_batch_for_prompt(capacity)", context.gdn_prefill_batch_for_prompt(capacity)); + let _a3 = step!("ple_batch_queue_for_prompt(capacity)", context.ple_batch_queue_for_prompt(PleBf16Mode::HighOnly, capacity)); + let _a4 = step!("qsa_native_batch_workspace_for_prompt(capacity)", context.qsa_native_batch_workspace_for_prompt(QsaNativePacking::HighOnly, capacity)); + let _a5 = step!("qsa_prompt_index_workspace_for_capacity", context.qsa_prompt_index_workspace_for_capacity(capacity)); + let _a6 = step!("qsa_prompt_attention_for_capacity", context.qsa_prompt_attention_for_capacity(capacity)); + let _a7 = step!("qsa_prompt_kv", context.qsa_prompt_kv()); + let _a8 = step!("original_qsa_resident_scalar_index", context.original_qsa_resident_scalar_index()); + let _a9 = step!("mtp_original_int8 vocabulary guard", Ok::<_, Error>(vocab)); +} + +/// `OriginalServeStack::open` -> `context.original_prefill_arena(layout)` (sized from the blob byte sizes). +#[test] +#[ignore = "GPU bring-up probe; no model"] +fn preflight_20_prefill_arena() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device 0"); + let context = device.create_context(budget()).expect("context"); + let capacity = env_usize("PROBE_CAPACITY", 1024); + let cells = env_usize("PROBE_CELLS", 262_144); + let options = layout_options(capacity, cells); + match options.carve() { + Ok(layout) => eprintln!( + "PREFLIGHT arena layout borrowed={}MiB separately_owned={}MiB source_needed={}MiB shared_region={}MiB ring_slots={}", + layout.borrowed_bytes >> 20, + layout.separately_owned_bytes >> 20, + layout.source_bytes_needed >> 20, + layout.shared_region_bytes >> 20, + layout.ring_slots + ), + Err(e) => eprintln!("PREFLIGHT arena carve ERR: {e:?}"), + } + let arena = step!("original_prefill_arena(layout)", context.original_prefill_arena(options)); + if let Some(arena) = &arena { + eprintln!("PREFLIGHT arena physically_owned={}MiB capacity={}", arena.physically_owned_bytes() >> 20, arena.capacity()); + } + eprintln!("PREFLIGHT context allocated={}MiB", context.allocated_bytes() >> 20); +} /// bytes per 10 blocks of the embedding kinds `OriginalMtpEmbedding::native` admits (`row_bytes == 10 * per`). fn embed_row_bytes(kind: i32) -> usize { @@ -352,3 +352,305 @@ fn preflight_30_synthetic_mtp_full_owner() { let _ = step!("ring.close", ring.close()); eprintln!("PREFLIGHT context allocated={}MiB", context.allocated_bytes() >> 20); } + +fn env_list(name: &str, default: &str) -> Vec { + std::env::var(name).unwrap_or_else(|_| default.to_owned()).split(',').filter_map(|s| s.trim().parse().ok()).collect() +} + +macro_rules! need { + ($name:expr, $e:expr) => { + match step!($name, $e) { + Some(v) => v, + None => return, + } + }; +} + +/// One synthetic verifier assembly: the window graphs T=1..=max_t and the commit graph are RECORDED +/// (`OriginalVerifier::record_all`) over uninitialised correctly sized weights of the given ggml kinds. This is +/// `original_serve_verifier::assemble` without the model: every sealed window module is loaded and every launch is +/// admitted (entry names, grids, shared sizes) exactly as in the serve path. Nothing is replayed. +#[allow(clippy::too_many_arguments)] +fn synthetic_verifier<'ctx>( + context: &'ctx Context<'ctx>, + proj: &[u32], + shared: &[u32], + fmt: (u32, u32), + max_t: usize, + cells: usize, + vocab: usize, + head_kind: u32, + embed_kind: u32, +) { + use std::rc::Rc; + let formats = need!("OriginalVerifyExpertFormats::new", OriginalVerifyExpertFormats::new([fmt; 48], 2560, 640)); + let blob = need!("formats.blob_bytes(0)", formats.blob_bytes(0)); + eprintln!("PREFLIGHT expert fmt gate/up={} down={} blob_bytes={blob}", fmt.0, fmt.1); + let g = geometry(max_t, cells, blob); + let layout = need!("OriginalVerifyExpertLayout::new", OriginalVerifyExpertLayout::new([blob; 48], blob)); + + let size = |k: u32, n_in: usize, n_out: usize| native_head_row_bytes(k, n_in).map(|r| r * n_out); + + // ---- head rows and embedding rows + let head_bytes = need!("head bytes", size(head_kind, 2560, vocab)); + let head = need!("original_native_head", context.original_native_head(head_kind, 2560, vocab, &vec![0u8; head_bytes], NativeHeadDispatch::default())); + let embed_bytes = need!("embed bytes", size(embed_kind, 2560, vocab)); + let embed = need!("original_native_embed", context.original_native_embed(embed_kind, 2560, vocab, &vec![0u8; embed_bytes])); + + // ---- weights (shared across layers where the binding allows it) + macro_rules! buf { + ($name:expr, $bytes:expr) => { + need!($name, context.allocate($bytes)) + }; + } + let mats: Vec<(usize, usize)> = vec![(2560, 10240), (2560, 6144), (6144, 2560), (2560, 512), (2560, 512), (2560, 12288), (6144, 2560)]; + let mut proj_bufs = Vec::new(); + for (i, (&(n_in, n_out), &k)) in mats.iter().zip(proj).enumerate() { + let bytes = need!("projection bytes", size(k, n_in, n_out)); + proj_bufs.push(buf!(format!("alloc projection[{i}] kind {k} ({} MiB)", bytes >> 20), bytes)); + } + let gdn_proj = || { + (0..36) + .map(|_| OriginalVerifyGdnProjections { + qkv: OriginalVerifyNativeMatrix { kind: proj[0], buffer: &proj_bufs[0] }, + gate: OriginalVerifyNativeMatrix { kind: proj[1], buffer: &proj_bufs[1] }, + out: OriginalVerifyNativeMatrix { kind: proj[2], buffer: &proj_bufs[2] }, + }) + .collect::>() + }; + let qsa_proj = || { + (0..12) + .map(|_| OriginalVerifyQsaProjections { + k: OriginalVerifyNativeMatrix { kind: proj[3], buffer: &proj_bufs[3] }, + v: OriginalVerifyNativeMatrix { kind: proj[4], buffer: &proj_bufs[4] }, + q: OriginalVerifyNativeMatrix { kind: proj[5], buffer: &proj_bufs[5] }, + out: OriginalVerifyNativeMatrix { kind: proj[6], buffer: &proj_bufs[6] }, + }) + .collect::>() + }; + // hyper-connection weights + let hc_norm = buf!("alloc hc_norm", 10240 * 4); + let hc_down = buf!("alloc hc_down", 320 * 10240 * 2); + let hc_up = buf!("alloc hc_up", 10240 * 320 * 2); + let hc_inject = buf!("alloc hc_inject", 4 * 10240 * 2); + let half = || HcHalfBuffers { norm: &hc_norm, down: &hc_down, up: &hc_up, inject: &hc_inject }; + let ple_key = buf!("alloc ple_key", 10240 * 2560 * 2); + let ple_value = buf!("alloc ple_value", 2560 * 2560 * 2); + let ple_norm_key = buf!("alloc ple_norm_key", 10240 * 4); + let ple_norm_query = buf!("alloc ple_norm_query", 10240 * 4); + let ple_norm_conv = buf!("alloc ple_norm_conv", 10240 * 4); + let ple_conv1d = buf!("alloc ple_conv1d", 4 * 10240 * 2); + let ple_scratch = buf!("alloc ple_scratch", PLE_SCRATCH_BYTES); + let ple_history = buf!("alloc ple_history", 9 * 10240 * 4); + // QSA norms and indexer projections: pairwise disjoint per layer + let mut qsa_bufs = Vec::new(); + for layer in 0..12 { + let mut five = Vec::new(); + for bytes in [256 * 4, 256 * 4, 128 * 4, 128 * 2560 * 2, 4 * 128 * 2560 * 2] { + five.push(buf!(format!("alloc qsa[{layer}] {bytes}"), bytes)); + } + qsa_bufs.push(five); + } + let mut gamma_bufs = Vec::new(); + for i in 0..12 { + gamma_bufs.push(buf!(format!("alloc gamma[{i}]"), 512)); + } + // MoE: router, shared experts + let router = buf!("alloc router", 512 * 2560 * 2); + let gate_inp = buf!("alloc gate_inp_shexp", 2560 * 2); + let sh_gate = buf!("alloc shared gate", need!("shared gate bytes", size(shared[0], 2560, 640))); + let sh_up = buf!("alloc shared up", need!("shared up bytes", size(shared[1], 2560, 640))); + let sh_down = buf!("alloc shared down", need!("shared down bytes", size(shared[2], 640, 2560))); + // GDN non-matrix weights + let conv = buf!("alloc gdn conv", 10240 * 4 * 4); + let alpha = buf!("alloc gdn alpha", 48 * 2560 * 2); + let beta = buf!("alloc gdn beta", 48 * 2560 * 2); + let dt = buf!("alloc gdn dt", 48 * 4); + let a = buf!("alloc gdn a", 48 * 4); + let norm = buf!("alloc gdn norm", 128 * 4); + eprintln!("PREFLIGHT synthetic verifier weights allocated={}MiB", context.allocated_bytes() >> 20); + + // ---- QSA owners, canonical GDN, verifier + let mut indices = Vec::new(); + let mut mapped = Vec::new(); + let mut batch_ws = need!("native_batch_workspace", context.native_batch_workspace()); + for _ in 0..12 { + indices.push(need!("original_qsa_resident_index", context.original_qsa_resident_index())); + let mut journal = need!("qsa_prompt_kv.into_original_mapped_journal", context.qsa_prompt_kv().and_then(|k| k.into_original_mapped_journal())); + // the prompt path initialises the streamed-KV resolver lazily (append_resident_arena); a prompt of ONE token + // never runs it, so the verifier window would refuse. Reset it here as a prefill would. + if std::env::var_os("PROBE_SKIP_RESOLVER_RESET").is_none() { + let _ = need!("mapped_journal.reset(workspace)", journal.reset(&mut batch_ws)); + } + mapped.push(journal); + } + let indices: [_; 12] = indices.try_into().ok().expect("12"); + let mapped: [_; 12] = mapped.try_into().ok().expect("12"); + let rope = OriginalVerifyRope { + theta_scale: 1e7f32.powf(-2.0 / 64.0), + freq_scale: 1.0, + corr_low: 0.0, + corr_high: 0.0, + ext_factor: 0.0, + magnitude: 1.0, + positions: None, + angles: None, + }; + let gamma: [&DeviceBuffer<'ctx>; 12] = std::array::from_fn(|i| &gamma_bufs[i]); + let qsa_journal = need!("OriginalVerifyQsaJournal::new", OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope)); + let states = vec![0.0f32; 128 * 48 * 128]; + let histories = vec![0.0f32; 10240 * 3]; + let mut canonical = need!( + "original_verify_canonical_gdn", + context.original_verify_canonical_gdn(std::array::from_fn(|_| states.as_slice()), std::array::from_fn(|_| histories.as_slice())) + ); + let mut verifier = need!("OriginalVerifier::new", OriginalVerifier::>::new(context, g)); + + // ---- one aggregate per window width plus the commit graph + let mut windows = Vec::new(); + for t in 1..=max_t + 1 { + let window_t = if t <= max_t { t } else { max_t }; + let gdn_weights: [OriginalVerifyGdnWeights<'_, 'ctx>; 36] = + std::array::from_fn(|_| OriginalVerifyGdnWeights { conv: &conv, alpha: &alpha, beta: &beta, dt: &dt, a: &a, norm: &norm }); + let bank = need!("verifier.bank()", verifier.bank()); + let journal = need!(format!("gdn_journal(t={window_t})"), bank.gdn_journal(&mut canonical, gdn_weights, Some(&ple_history))); + let head_rows = need!(format!("head.rows({window_t})"), head.rows(window_t)); + let resources = need!(format!("OriginalVerifyResources::new(t={window_t})"), OriginalVerifyResources::new(context, journal, Rc::clone(&qsa_journal), head_rows)); + let embed_rows = need!(format!("embed.rows({window_t})"), embed.rows(window_t)); + let w = need!(format!("OriginalVerifyWindowResources::new(t={window_t})"), OriginalVerifyWindowResources::new(context, resources, embed_rows, layout.clone(), window_t)); + let w = need!("with_projections", OriginalVerifyProjBinding::new(context, &g, gdn_proj(), qsa_proj()).and_then(|p| w.with_projections(p))); + let layers: Vec<_> = (0..48).map(|_| HcLayerBuffers { attention: half(), ffn: half() }).collect(); + let output = HcOutputBuffers { norm: &hc_norm, down: &hc_down, up: &hc_up }; + let ple = PleBuffers { + key: PleKeyBuffer::Bf16(&ple_key), + value: &ple_value, + norm_key: &ple_norm_key, + norm_query: &ple_norm_query, + norm_conv: &ple_norm_conv, + conv1d: &ple_conv1d, + scratch: &ple_scratch, + history: &ple_history, + }; + let w = need!("with_gr", OriginalVerifyGrBinding::new(context, layers, output, Some(ple)).and_then(|b| w.with_gr(b))); + let qsa_layers: [OriginalVerifyQsaLayerWeights<'_, 'ctx>; 12] = std::array::from_fn(|i| OriginalVerifyQsaLayerWeights { + attn_q_norm: &qsa_bufs[i][0], + attn_k_norm: &qsa_bufs[i][1], + index_q_norm: &qsa_bufs[i][2], + index_k_proj: &qsa_bufs[i][3], + index_q_proj: &qsa_bufs[i][4], + }); + let w = need!("with_qsa", OriginalVerifyQsaBinding::new(context, g, qsa_layers).and_then(|b| w.with_qsa(b))); + let moe_layers: Vec<_> = (0..48) + .map(|_| OriginalVerifyMoeLayerWeights { + router: &router, + gate_inp_shexp: &gate_inp, + gate_shexp: &sh_gate, + gate_shexp_type: shared[0], + up_shexp: &sh_up, + up_shexp_type: shared[1], + down_shexp: &sh_down, + down_shexp_type: shared[2], + }) + .collect(); + let w = need!("with_moe", OriginalVerifyMoeBinding::new(context, &g, moe_layers, formats.clone()).and_then(|b| w.with_moe(b))); + windows.push(Some(w)); + } + let commit = windows.pop().flatten().expect("commit aggregate"); + let started = std::time::Instant::now(); + let recorded = verifier.record_all( + OriginalVerifyWindowPolicy::mode17(), + |t| windows.get_mut(t - 1).and_then(Option::take).ok_or(Error::InvalidQwenShape), + commit, + ); + let recorded_ok = recorded.is_ok(); + let _ = step!(format!("record_all (T=1..{max_t} + commit) in {:?}", started.elapsed()), recorded); + drop(windows); + if recorded_ok && std::env::var("PROBE_REPLAY").map_or(true, |v| v != "0") { + // Replay the recorded graphs over zero weights: the host plays the all-CPU expert pool (zeros) and the + // empty GPU plan. This runs every captured kernel with its real launch parameters (shared-memory + // attributes, grids, the doorbell/ring spin kernels). A stuck window ends after the 20 s doorbell timeout. + let mut position = 0usize; + let mut publish_ws = need!("native_batch_workspace (publish)", context.native_batch_workspace()); + for t in [1usize, 2, max_t] { + let tokens: Vec = (0..t).map(|i| 100 + i as i32).collect(); + let ple = vec![0.0f32; t * 2560]; + let mut params = SamplerParams::default(); + params.greedy = true; + params.temperature = 0.0; + params.seed = 1; + let sampling = NativeHeadSampling { position: position as u64, params, history: None, history_len: 0, path: SamplerPath::Split, enabled: false }; + let started = std::time::Instant::now(); + let mut groups_seen = 0usize; + let result = verifier.run(&tokens, position, Some(&ple), sampling, |_rows, sink, _copy| { + groups_seen += 1; + sink.with_output(|out| { + out.fill(0.0); + Ok(()) + }) + }); + match step!(format!("verifier.run(t={t}, position={position}) in {:?}, {groups_seen} pool groups", started.elapsed()), result) { + Some(window) => eprintln!("PREFLIGHT window t={t} sampled ids {:?}", window.selection.ids()), + None => break, + } + // alternate the synchronous and the asynchronous (event) commit; the next run / read joins the event + let async_commit = t == 2; + if step!(format!("verifier.commit(keep={t}, async={async_commit})"), verifier.commit(t, async_commit)).is_none() { + break; + } + // the reads `OriginalServeHost::publish_committed` / `settle_state` make after a commit + let _ = step!("verifier.accepted_tokens", verifier.accepted_tokens().map(|a| a.len())); + let _ = step!("with_committed_qsa(0).checkpoint", verifier.with_committed_qsa(0, |index| index.checkpoint(&mut publish_ws)).map(|_| ())); + let _ = step!("qsa_journal.committed_mapped_prefix(0)", qsa_journal.committed_mapped_prefix(0).map(|p| p.next_position())); + let _ = step!("with_committed_gdn(0)", verifier.with_committed_gdn(0, |values, history| Ok((values.len(), history.len())))); + position += t; + } + } + let _ = step!("verifier.close", verifier.close()); +} + +/// Records the verifier window graphs over synthetic weights; one run per projection-kind set. +/// `PROBE_PROJ_KINDS` is a list of ggml types applied to all seven projection matrices (default `8`, i.e. Q8_0); +/// the seven kinds can also be given as `PROBE_PROJ_SET=qkv,gate,out,k,v,q,qout`. +#[test] +#[ignore = "GPU bring-up probe; no model"] +fn preflight_40_synthetic_verifier_record_all() { + let _gpu = GPU.lock().unwrap_or_else(|e| e.into_inner()); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device 0"); + let context = device.create_context(budget()).expect("context"); + let max_t = env_usize("PROBE_MAX_T", 8); + let cells = env_usize("PROBE_CELLS", 262_144); + let vocab = env_usize("PROBE_VOCAB", 248_320); + let head_kind = env_usize("PROBE_HEAD_KIND", 21) as u32; + let embed_kind = env_usize("PROBE_EMBED_KIND", 21) as u32; + let shared = env_list("PROBE_SHARED_KINDS", "8,8,8"); + let fmt = env_list("PROBE_EXPERT_FMT", "21,20"); + let sets: Vec> = match std::env::var("PROBE_PROJ_SET") { + Ok(_) => vec![env_list("PROBE_PROJ_SET", "8,8,8,8,8,8,8")], + Err(_) => env_list("PROBE_PROJ_KINDS", "8").into_iter().map(|k| vec![k; 7]).collect(), + }; + // one dimension varies at a time: projections, then expert formats, then shared-expert kinds + let mut runs: Vec<(Vec, Vec, Vec)> = sets.into_iter().map(|p| (p, shared.clone(), fmt.clone())).collect(); + let base = runs.first().map(|r| r.0.clone()).unwrap_or_else(|| vec![8; 7]); + if let Ok(list) = std::env::var("PROBE_EXPERT_FMTS") { + for pair in list.split(';') { + let f: Vec = pair.split(',').filter_map(|x| x.trim().parse().ok()).collect(); + if f.len() == 2 { + runs.push((base.clone(), shared.clone(), f)); + } + } + } + if let Ok(list) = std::env::var("PROBE_SHARED_SETS") { + for triple in list.split(';') { + let k: Vec = triple.split(',').filter_map(|x| x.trim().parse().ok()).collect(); + if k.len() == 3 { + runs.push((base.clone(), k, fmt.clone())); + } + } + } + for (set, shared, fmt) in runs { + eprintln!("PREFLIGHT ==== projection kinds {set:?} shared {shared:?} expert fmt {fmt:?}"); + synthetic_verifier(&context, &set, &shared, (fmt[0], fmt[1]), max_t, cells, vocab, head_kind, embed_kind); + eprintln!("PREFLIGHT context allocated={}MiB", context.allocated_bytes() >> 20); + } +}