[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M718NMKP3D8ZSJHPGP8RJ3CJ":3,"skill-same:01M718NMKP3D8ZSJHPGP8RJ3CJ":72},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":48,"ownerHtmlUrl":49,"ownerBlogUrl":48,"ownerDescription":50,"updatedAt":51,"install":52,"resources":65},"01M718NMKP3D8ZSJHPGP8RJ3CJ","mtp-tuning",null,"Tune, debug, or extend Llaminar V2 MTP\u002Fspeculative decoding, prefix-cache interaction, vLLM-style accepted-state publication, MTP depth control, grouped verifier kernels, dense\u002FMoE MTP parity, and MTP benchmark dashboards. Use when Codex is asked to improve MTP speed, fix MTP correctness, compare CUDA\u002FROCm\u002FCPU MTP lanes, work on decode-equivalent grouped verifier rows, remove host\u002Fdevice coherence issues, update the MTP project plan\u002Fdashboard, or touch MTP-related tests and perf gates.","Llaminar\u002Fllaminar","Llaminar","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F247404048?v=4","01M718MTZG2TQSA7DEB5DKQDN1","01M718MV06G9CV8S2JMN9XHX8Y",48,"AGPL-3.0","https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.agents\u002Fmtp-tuning\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"mtp","mtp tuning","tuning","remove","dashboard","when","decode","CPU","interaction","host","project","coherence","issues","fix","project plan","work","work on","plan","improve","update","2026-11-10 10:12:30",false,"---\nname: mtp-tuning\ndescription: Tune, debug, or extend Llaminar V2 MTP\u002Fspeculative decoding, prefix-cache interaction, vLLM-style accepted-state publication, MTP depth control, grouped verifier kernels, dense\u002FMoE MTP parity, and MTP benchmark dashboards. Use when Codex is asked to improve MTP speed, fix MTP correctness, compare CUDA\u002FROCm\u002FCPU MTP lanes, work on decode-equivalent grouped verifier rows, remove host\u002Fdevice coherence issues, update the MTP project plan\u002Fdashboard, or touch MTP-related tests and perf gates.\n---\n\n# Llaminar MTP Tuning\n\n## Purpose\n\nUse this skill to work on Llaminar's vLLM-style MTP path without re-learning the\nsame hard-won rules. MTP tuning is only successful when it improves real served\ninference speed while preserving strict decode equivalence across CPU, CUDA, and\nROCm, dense and MoE, greedy and stochastic.\n\nAlways keep these files current:\n\n- `docs\u002Fv2\u002Fprojects\u002F2026-06\u002FMTP_VLLM_STYLE_PROJECT_PLAN.md`: phase plan,\n  accepted architecture, gates, and known debt.\n- `docs\u002Fv2\u002Fprojects\u002F2026-06\u002FMTP_VLLM_STYLE_TUNING_DASHBOARD.md`: compact RAG\n  status and latest speed\u002Fcorrectness evidence. Keep it under the documented\n  size limit.\n- `docs\u002Fv2\u002Fprojects\u002F2026-06\u002FPREFIX_CACHE_MTP_BENCHMARK_NOTES.md`: only for\n  broader historical benchmark notes when the current dashboard is not the\n  right home.\n\nFor backend kernel work, also use the relevant sibling skill:\n\n- `.agents\u002Fcuda-tuning\u002FSKILL.md` for CUDA profiling, Nsight, and generated\n  NativeVNNI dispatch work.\n- `.agents\u002Frocm-tuning\u002FSKILL.md` for HIP\u002FROCm profiling, rocprof, ISA analysis,\n  and generated NativeVNNI dispatch work.\n\n## Architecture North Star\n\nLlaminar is moving toward vLLM-style speculative decode:\n\n1. Draft rows live in speculative slots, not live model state.\n2. The target verifier runs `draft_count + 1` rows: draft rows plus one bonus row.\n3. Device-side sampler\u002Frejection logic produces accepted counts and output tokens.\n4. Only accepted speculative slots are published to live state.\n5. Rejected suffix and bonus-only rows must not mutate live KV, GDN, short-conv,\n   positions, terminal hidden, terminal logits, or sampler history.\n6. Greedy is a deterministic specialization of the stochastic contract, not a\n   separate architecture.\n\nThe canonical transaction shape is:\n\n```text\nprepare spec slots\nrun draft graph\nrun target verifier graph\nrun rejection sampler \u002F accepted-count reducer\npublish accepted state\ndiscard rejected state\nreturn tokens\n```\n\nKeep graphs per-device and symmetric. Do not introduce nested multi-device\nsidecar graphs. LocalTP, LocalPP, NodeTP, and ExpertOverlay must extend the\nsame transaction semantics with collective coordination, not invent separate\nstate machines.\n\n### Canonical MoE LLEP Policy Tuple\n\n`LLEP` names one current-batch routed-row assignment policy. It is not a\ncomplete execution mode, routed-expert storage policy, decode policy, durable\nresidency controller, or hot-cache policy. Keep these axes explicit whenever\nconstructing, testing, or benchmarking a MoE graph:\n\n- dense\u002Fshared trunk: tensor parallel;\n- routed-expert storage and compute: apportioned whole experts;\n- routed phase: uniform;\n- grouped verifier\u002Fdecode assignment: static owner;\n- ordinary large-prefill assignment: least-loaded resident (LLEP);\n- MTP terminal norm\u002Fhead: mirrored full vocabulary;\n- durable expert-residency maintenance: off;\n- hot expert replica cache: off;\n- same-backend transport: one fully captured NCCL or RCCL graph.\n\nThe prefill row threshold is an explicit work-regime boundary, not recovery\nbehavior: below it, execute economical static-owner EP; at or above it, execute\nthe current-batch least-loaded assignment. Set the threshold to zero only in a\nfocused integration test that must force and prove the transfer-backed LLEP\npath. Never let prefill assignment bleed into grouped verifier\u002Fdecode, and\nnever use whole-expert decode movement as a proxy for LLEP.\n\nDeclare the tuple through `DenseParallelPolicy`,\n`RoutedExpertComputePolicy`, `RoutedExpertPhasePolicy`, separate\n`routed_decode_assignment` and `routed_prefill_assignment` domain fields,\n`MTPTerminalHeadPolicy`, `--moe-residency-maintenance`, and\n`--moe-hot-expert-cache`. Graph builders own the resulting stage, collective,\nand event wiring. PerfStats must prove static-owner grouped verification,\nleast-loaded large prefill, mirrored terminal-head execution, full graph\ncapture, and zero segmented execution.\n\n## Non-Negotiable Rules\n\n- Never use CUDA\u002FHIP default or null streams. Every GPU operation needs an\n  explicit stream, including copies, memset, events, reductions, sampling, and\n  graph-captured stages.\n- Never allocate GPU memory in the hot path. Use declared graph workspace,\n  `IWorkspaceConsumer`, arena buffers, or low-level sanctioned allocators.\n- Never mutate tensor residency flags directly. Use `TransferEngine` unless a\n  graph-stage buffer contract already provides the correct resident pointer.\n- Never capture H2D copies inside GPU graphs. Upload persistent inputs before\n  capture and replay device-resident buffers.\n- Never leave quiet recovery paths. Every advertised MTP lane must implement\n  its declared policy or fail fast with a precise diagnostic.\n- Never land special codebook exceptions in production kernels. Use generic\n  dispatch keyed by codebook family, M, aspect ratio, work size, and generated\n  policy tables. Exact shape overlays are additive to a total general dispatch\n  rule; they never substitute for that rule.\n- Never accept token equality alone as correctness proof for verifier kernels.\n  Require distribution and numeric gates.\n- Remove dead-end code and tests once a path is abandoned. Negative tests for\n  deleted approaches just confuse future work.\n- Keep CUDA and ROCm structurally aligned. Backend-specific code should sit\n  behind common stage\u002Fkernel interfaces.\n- Write regression unit or integration tests for every crash, coherence bug,\n  stream bug, dispatch bug, and parity break found during tuning.\n\n## Correctness Gates\n\nUse strict gates before promoting any MTP optimization:\n\n- **Grouped verifier decode must be bitwise serial-row equivalent.** For\n  grouped MTP verifier rows, the acceptance threshold is byte-for-byte identical\n  FP32 output compared with running the same rows through the production M=1\n  serial decode path in the same backend and tensor format. Cosine similarity,\n  relative L2, symmetric KLD, and max-absolute-error are diagnostics for finding\n  the first drift; they are not pass criteria for grouped decode publication.\n- Relative L2: tight enough to catch drift for the tested precision\u002Fpath.\n- Cosine similarity: near 1.0 for logits, hidden rows, and kernel outputs.\n- Symmetric KLD: required when outputs feed sampling or softmax decisions.\n- Max absolute error: required for small-M kernel equivalence.\n- Sampled-token equality: required, but not sufficient by itself.\n- Decode-equivalent continuation: accepted-state publication must match serial\n  decode after continuing for enough rows to expose KV\u002FGDN\u002Fshort-conv mistakes.\n\nGrouped verifier APIs and kernels must accept runtime M up to the graph and\nworkspace capacity; never encode speculative depth as an `M=2..4` template or\nadmission limit. M=1 is the independent production serial-decode oracle. The\ncanonical grouped inventory proves every integer M=2..16 plus M=31 for every\nbackend and every advertised tensor codebook or floating-point tensor format.\nM=31 is a deliberate deeper sentinel for speculative regimes beyond the usual\nfifteen drafts; it is not a maximum. A larger configured graph capacity must\nextend the contiguous sweep through that capacity rather than sample only its\nendpoint. Use fixed-size physical row tiles to bound register pressure and\npreserve weight reuse as M grows; do not generate one kernel specialization per\nspeculative depth.\n\nPrefer dedicated integration tests before wiring a new kernel into graph\nexecution. Good test names to search for include:\n\n```bash\nrg -n \"VerifierRows|decode_equivalent|PrefixMTP|GPUSampling|NativeVNNI|QuantisedGemmSmallM\" tests\u002Fv2\n```\n\nCommon focused gates:\n\n```bash\nctest --test-dir build_v2_integration -R \"^V2_Unit_PrefillDecodeTransition$|^V2_Unit_MTP|^V2_Integration_GPUSamplingKernels\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_.*MTP|^V2_Integration_.*Prefix\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_.*VerifierRows|^V2_Integration_.*QuantisedGemmSmallM|^V2_Integration_.*NativeVNNI\" --output-on-failure --parallel\n```\n\n### Mandatory all-format grouped verifier sweeps\n\nThese integration suites are the first line of defense for grouped verifier\ndecode. They prove that production grouped rows are byte-identical to serial\ndecode across the backend's advertised tensor\u002Fcodebook formats. Run them after\nany change to MTP verifier rows, NativeVNNI\u002FGEMV dispatch, MoE routed\u002Fshared\nexpert kernels, LocalTP verifier output projection, attention, RMSNorm, or GDN\nprojection. A failure here is a production grouped implementation bug; do not\npaper over it with serial row replay, relaxed thresholds, or a backend-specific\nformat exception.\n\nTreat these sweeps as mandatory architecture proof, not ordinary smoke tests.\nGrouped decode is publishable only when every production grouped implementation\nis both byte-exact against serial M=1 decode and genuinely grouped\u002Feconomical\nfor every format that backend can load. If a new grouped verifier operation,\ncodebook family, floating-point tensor format, or backend lane is added, extend\nthe corresponding sweep in the same slice before tuning or claiming the lane is\ncomplete.\n\nThe CUDA all-format gate must include the production fused projection,\nlarge-K KPAR, fused SwiGLU\u002Fdown, FP32, FP16, and BF16 runtime-M tests. Search for\n`RuntimeM2To16` in `Test__CUDAGemmParity.cpp`; the low-level NativeVNNI case also\ncaptures and replays every format\u002Fdepth combination. Equivalent CPU and ROCm\nlanes must use the same contiguous row inventory.\n\nRouted MoE format sweeps must enter through the production router before the\ngrouped expert pass and validate the router-to-expert Q8 publication counter;\nprecomputed host route IDs do not prove this optimization. The canonical\ncounters are `cpu_moe_grouped_verifier_router_q8_reuse_calls`,\n`cuda_moe_grouped_prefill_router_q8_reuse_calls`, and\n`rocm_moe_grouped_prefill_router_q8_reuse_calls`. CPU serial-oracle rows must\nalso observe `cpu_moe_decode_router_q8_reuse_calls`. A byte-equal result without\nthe matching counter is a failed gate because it may only show that two\nindependent quantizers happened to agree for the synthetic input.\n\n```bash\n# Discover the exact registered inventory first, then run every present and\n# future grouped-verifier lane. Do not replace this prefix gate with a hand list.\nctest --test-dir build_v2_integration -N -R \"^V2_Integration_GroupedVerifierRows_\"\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_\" --output-on-failure --parallel\n\n# Backend slices are useful while iterating, but all three remain mandatory\n# before a grouped-verifier slice is accepted.\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_CPU_\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_CUDA_\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_ROCm_\" --output-on-failure --parallel\n```\n\nAs of 2026-07-13 the prefix gate discovers 51 substantive lanes: 13 CPU, 17\nCUDA, and 21 ROCm (`52` CTest entries including the model fixture). The\ninventory includes all-format GEMM, MoE codegroups and\nexpert paths, floating formats, dense QKV\u002FGDN projections, replicated LocalTP\noutput projection, embedding, RMSNorm, fused residual norm, residual add,\nSwiGLU, RoPE, attention, KV-cache append, GDN recurrence, short-conv,\nrequest-batched GDN state, and device-resident stochastic sampling. The\nprefix command is canonical precisely so a newly registered operation cannot be\nomitted from an otherwise plausible-looking hand-maintained regex.\n\nThe backend counts are an inventory, not a symmetry waiver. Before the final\nMTP gate, compare the semantic operation matrix across CPU, CUDA, and ROCm and\nadd every applicable missing lane. In particular, CPU currently lacks the GPU\nstochastic-resident and request-batched recurrent-state lanes, while explicit\nall-format\u002Fruntime-M projection and MoE codegroup discovery is not named\nuniformly across the three backends.\n\nThe CUDA and ROCm `GDNRecurrence` and `ShortConv` lanes also prove captured\ngraph lifetime across accepted-state publication. Each backend captures the\nordinary M=1 decode graph once, runs grouped verifier M=2\u002F3\u002F4 into isolated\nspeculative state, publishes every possible accepted row by a device-owned row\nindex, detaches verifier bindings, and replays the original graph without\nrecapture. Both the continuation output and complete recurrent live state must\nmatch serial M=1 decode in native bytes. This proof is what permits the typed\ncorrection-boundary policy to retain single-token decode and all-position\nverifier captures; a blanket CUDA\u002FROCm graph reset is a regression, not a\nconservative fallback.\n\nThe CUDA and ROCm `KVCacheAppend` gates each enumerate the same 288 production\nroutes: every accepted cache\u002Fsource format pair (including asymmetric prepared\nTQ8-K\u002FTQ4-V), M=2\u002F3\u002F4, position-major and verifier-head-major inputs,\nreplicated and LocalTP-sharded caches, and direct-static versus graph-captured\ndevice-dynamic ring metadata. They require native cache byte equality, sequence\nmetadata equality, prefix-block export\u002Fimport round trips, and exactly one\ngrouped route-counter observation per matrix cell.\n\nThe CPU `RoPE` gate covers FP32, BF16, FP16, pure-integer Q8_1, and Q16_1 with\n32\u002F64\u002F128-value native blocks at M=2\u002F3\u002F4. It compares native bytes against\nserial M=1 decode and checks the `single_grouped_row_head_workshare` route, so a\nrow loop hidden behind the grouped interface is not an acceptable replacement.\n\nThe explicit CUDA and ROCm `RoPE` gates mirror one 24-cell matrix per backend:\nFP32 full\u002Fpartial plus BF16 and FP16, M=2\u002F3\u002F4, and both contiguous\ndevice-scalar and explicit device-row position owners. They compare native GPU\nbytes with the same backend's production M=1 decode kernel, require non-default\nstreams, and reject a missing `single_grouped_launch` route counter.\n\nThe explicit CUDA and ROCm `RMSNorm` gates each cover 18 positive production\ncells: FP32, BF16, and FP16 at M=2\u002F3\u002F4 for 128-column per-head Q\u002FK normalization\nand 4096-column hidden-state normalization. Those widths cross the narrow and\nwide reduction launch policies. Every cell enters `apply_tensor` on a\nnon-default stream, compares native output bytes with same-backend M=1 decode,\nand requires one `one_block_per_row` \u002F `single_grouped_launch` counter. Three\nadditional negative cells prove that every native format rejects an unbound\ndefault stream without publishing route telemetry.\n\nThe CPU, CUDA, and ROCm `ResidualAdd` gates each cover FP32, BF16, and FP16 at\nM=2\u002F3\u002F4 for 128- and 4096-column rows. They require native byte equality against\nsame-backend M=1 decode and exactly one flat workshare\u002Flaunch counter. GPU gates\nalso require device-only `gpu_data_ptr()` ownership and verify that every format\nrejects an unbound default stream; in particular, this guards ROCm BF16's stream\nsetter, which must remain symmetric with FP32 and FP16.\n\nThe CPU, CUDA, and ROCm `FusedResidualNorm` gates cover the same 18 positive\ncells per backend but enter `FusedResidualNormStage`, the actual graph operation\nat attention and FFN residual boundaries. Both the in-place residual publication\nand normalized output must match independent production M=1 stage executions in\nnative bytes. CUDA and ROCm additionally run one null-stream rejection cell per\nformat and require one device-resident fused launch; this prevents the separate\nResidualAdd\u002FRMSNorm suites from masking broken fused type dispatch or stale host\nownership.\n\nThe standalone `SwiGLU` gates cover M=2\u002F3\u002F4 at 544 and 4864 columns. CUDA and\nROCm sweep FP32\u002FBF16\u002FFP16 with explicit streams and one flat launch; CPU adds\nQ8_1 and requires one native workshare. The 544-column case is deliberately 17\nQ8 blocks wide, so grouped execution cannot pair blocks across a row boundary\nwithout the native-byte oracle noticing. These gates complement, rather than\nduplicate, fused GEMM+SwiGLU-down coverage.\n\nUse the backend-specific all-format sweep as the minimum acceptance gate for a\nnarrow kernel edit, then run the full backend group before claiming that grouped\ndecode is proven for that backend. Model-level prefix\u002FMTP parity and\n`Qwen36_MTPForwardVerifierOperationEquivalence` remain required because they\ncatch cross-stage amplification, but they do not replace the all-format sweeps.\n\nDo not run only the easy backend. If CUDA has a deep PyTorch or layer-by-layer\ntest, ROCm and CPU need the same semantic coverage unless the plan explicitly\nmarks the lane as not implemented.\n\nRefresh the inventory with `ctest --test-dir build_v2_integration -N -R\n\"^V2_Integration_GroupedVerifierRows_\"` when adding tests. Keep every canonical\ntest under that namespace so the precommit, CI, and skill prefix gates include\nit automatically.\n\n## Performance Methodology\n\nStart with real inference, then isolate:\n\n1. Capture a Release benchmark for the relevant lane with fixed d1\u002Fd2\u002Fd3 and\n   dynamic depth.\n2. Enable `LLAMINAR_PERF_STATS_GPU_STAGE_TIMING=1` with JSON\u002FCSV export to rank\n   graph-replay bottlenecks on the production captured topology. The deprecated\n   `LLAMINAR_PROFILING` alias must never disable graph capture or select eager\n   execution.\n3. Split host bridge accounting from producer work. A D2H timer that includes\n   waiting for a producer event is not proof of copy overhead.\n4. Attack the biggest real chunk first. For MTP this is usually verifier forward,\n   LM head, grouped GEMV\u002FGEMM, attention, GDN\u002Fshort-conv, sampling, or state\n   publication.\n5. Microbench candidate kernels with strict parity against serial decode.\n6. Re-run the model-level benchmark and parity suite after each concrete slice.\n7. Update the dashboard with the run directory, speedup, acceptance rate, and\n   current RAG.\n\nUseful benchmark shape:\n\n```bash\nscripts\u002Frun_mtp_iteration_benchmark_matrix.sh \\\n  --devices cuda:0,rocm:0 \\\n  --models dense,moe \\\n  --modes greedy,stochastic \\\n  --variants fixed_d1,fixed_d2,fixed_d3,dynamic \\\n  --decode-tokens 16 \\\n  --perfstats \\\n  --output-dir benchmark_results\u002Fmtp_vllm_style\u002F\u003Ctimestamp>\n```\n\nUse `scripts\u002Fsummarize_mtp_perfstats.py` to compare:\n\n- `decode_step_ms`\n- verifier forward \u002F graph replay time\n- stage GPU time by type\n- sidecar time\n- publish time\n- sampler\u002Freducer time\n- response-ready wait versus actual D2H enqueue\u002Fwait\n- acceptance, rejection, and rollback counts\n\n### Isolated NativeVNNI profiler evidence\n\nNativeVNNI policy training has two physically separate evidence transactions.\nCanonical candidate timing runs first, with production warmups and\nsample-interleaved rounds. Only after those observations and raw timing samples\nare immutable may `profiler_evidence.py` derive per-candidate requests.\n`profiler_collectors.py` then starts one fresh process per request and gathers\nLinux `perf`, Nsight Compute, or rocprofiler metrics from an extra isolated\nlaunch. Profiler replay duration is never a timing label.\n\nEvery supported observation needs one evidence record; unsupported candidates\nneed an explicit non-profile state. CUDA\u002FROCm candidates may be pipelines, so\nretain quantization, producer, reducer, and epilogue dispatches independently\nand in launch order. Optional counters unavailable on one architecture remain\ntyped unavailable fields. A missing tool, raw report, required counter, or\nsupported candidate record blocks production evidence completeness. Production\n`scripts\u002Frefresh_native_vnni_dispatch_tables.sh --profile all` enables this gate\nby default, and `--install --skip-profiler-evidence` is forbidden.\n\nThe required `*_profiler_features.csv` export is an authenticated join of the\ncanonical common-observation timing CSV, request manifest, and evidence\nmanifest. It retains pipeline-level canonical timing alongside one ordered row\nper physical dispatch and that dispatch's own counters. Never train from a\nhand-joined profiler CSV or treat profiler replay duration as canonical\nlatency; a corpus\u002Frequest\u002Fevidence digest mismatch must fail the refresh.\n\n### Immutable Git LFS corpora and turnkey refits\n\nThe canonical cross-backend procedure now lives in\n`.agents\u002Fnativevnni-gemm-tuning\u002FSKILL.md`. Keep this section focused on MTP's\nstrict grouped-row equivalence and its interaction with speculative decode.\n\nUse `scripts\u002Ftrain_native_vnni_dispatch.sh --backend \u003Cbackend> --install` as the\nnormal production entry point for `cuda`, `rocm`, `cpu`, and `cpu-prefill`.\nThe command rebuilds both vendor policy scorers, validates their integration\noracles, benchmarks and profiles only when no matching corpus generation is\npublished, fits and certifies, and atomically installs the generated include.\nAdditional refresh options belong after `--`.\n\nPublished generations live under\n`corpora\u002Fnative_vnni_dispatch\u002F\u003Cbackend>\u002F\u003Carchitecture>\u002F\u003Cshape-digest>-\u003Cconfiguration-digest>\u002F`\nin the optional `Llaminar\u002Fcorpora` submodule. All published corpus families\nbelong in that data repository; the source repository pins only its gitlink.\nInitialize and selectively pull LFS through the canonical tuning skill's\ncorpus workflow, never during ordinary builds or Unit\u002Fpreflight gates.\n`corpus.manifest.json` is ordinary Git metadata there; large timing\u002Fprofiler\npayloads are Git LFS objects. Never hand-edit a sealed generation. The corpus verifier\nmust reject unresolved LFS pointers, partial files, symlinks, changed payload\ndigests, and stale resolved shape inventories. Fit-only replay materializes a\ndisposable workspace and uses `--skip-sweep --reuse-profiler-evidence`; it may\nre-export authenticated profiler features but must launch no candidate kernel\nand no profiler. A failed fit is mined again from the same corpus rather than\ntriggering another timing sweep.\n\nThe final corpus directory suffix also binds forwarded collection arguments.\nDo not pass `--shapes` or `--shape-partition` through the turnkey command;\nproduction overlays belong in the shared inventory so all backends see them.\n\nEvery exact overlay comes from the shared resolved shape inventory consumed by\nthe CPU, CUDA, and ROCm trainers. Backend-private shape lists are forbidden.\nAn overlay addition changes the inventory digest and therefore requires a new\ncorpus generation; exact overlays remain additive to mandatory generic rules.\n\n### GPU-accelerated NativeVNNI policy fitting\n\nThe common policy learner can batch its first two exact leaf keys on CUDA and\nROCm. Build `v2_native_vnni_leaf_primary_scorer_cuda` and\n`v2_native_vnni_leaf_primary_scorer_rocm`; production\n`refresh_native_vnni_dispatch_tables.sh --profile all` auto-discovers both\nvendor inventories and uses isolated one-vendor worker processes. Each physical\ndevice defaults to eight CPU orchestration lanes because tree construction is\nstill host work and the scorer kernels are brief. Tune with `--policy-lanes`,\nor explicitly choose `--policy-accelerators cpu` for the canonical CPU fitter.\n\nEach GPU scorer lane must keep one uploaded regret matrix, non-default stream,\nand growable scratch session alive across all leaf batches for a fit. Do not\nreintroduce per-call stream creation, device allocation, or full-matrix upload.\nSchedule CV\u002Ffinal-fit tasks through the longest-first dynamic device queue and\nrefill whichever lane completes first; restore task-index order before policy\nreduction so scheduling cannot affect generated bytes. Static per-lane task\npartitions are forbidden because heterogeneous folds create a severe idle tail.\nRepresent tree point subsets as arbitrary-width integer masks, cache exact\nthreshold membership masks, and retain ordered point tuples only for canonical\nlater-key\u002Freport materialization. Keep the unit invariant that leaf masks are\ndisjoint, cover the full point inventory, and map exactly to retained ordered\npoints; generated report and request bytes must match before\u002Fafter any beam\nrepresentation optimization.\n\nThe GPU computes maximum regret as a diagnostic and the integer count at or\nabove the strict 5% boundary. Python derives p95 and mean regret and retains\ncandidate-name tie-breaking so report\u002Frequest bytes stay identical to CPU\nfitting. A policy is installable only when measured p95 regret and conservative\np95 regret upper bound are both strictly below 5%; maximum regret is never an\ninstallation gate. Run\n`V2_Integration_NativeVNNILeafPrimaryScorer_CUDA` and `_ROCm`; unit tests must\nremain GPU-free. Once acceleration is explicitly requested, a missing DSO,\ndevice, or worker is a hard failure. Never silently resume on CPU, and never\nconfuse policy-scoring GPU work with separately timed candidate kernels or\nisolated profiler launches.\n\nGPU scorers do not replace backend candidate measurement. In particular, CPU\nkernel timing must remain on CPU. On a multisocket trainer host, split distinct\nshape\u002Fsource\u002FISA jobs across an MPMD MPI launch with one rank per socket. Never\nlaunch the same tuple on both ranks, and give every rank distinct aggregate and\nraw-timing paths. Pair only jobs with identical ordered M inventories. Enable\n`LLAMINAR_CPU_NVNNI_PREFILL_MPI_ROUND_SYNC=1` so every warmup and timing round\nends in an MPI active-rank reduction; a locally converged rank must continue\nunmeasured complete-round pacing until every rank finishes the same M phase.\nWithout that coordination, one rank can advance to a larger M and manufacture\nfrequency or memory-pressure drift in its peer's timing series.\n\nInstallable CPU prefill evidence must authenticate\n`mpi-complete-round-v1`, MPI world size\u002Frank, and global warmup\u002Ftiming round\ncounts. The adapter must reject candidate\u002Fglobal round disagreement and any\nmulti-rank production corpus collected with process-local pacing. Do not fix a\ncross-rank transient by raising the sample ceiling, relaxing the 2% drift gate,\nor selecting a convenient stable tail.\n\nWarmup is elapsed-evidence controlled, not round-count controlled. An M64\ncandidate can legitimately require more than 10,000 launches to accumulate one\nsecond, so do not reintroduce a fixed warmup-round ceiling. Keep the 30-second\nper-complete-round watchdog, require every measured launch to make finite\npositive timer progress, and record total phase wall time plus maximum round\nduration. Long-M phases may legitimately exceed 30 seconds across several\nrounds; retain the per-candidate measured-duration gate as the promotion\nrequirement.\n\nAfter the one-second source preconditioning cell, derive each CPU prefill\ncandidate's M-transition warmup from its first production-route latency probe:\n`max(100 ms, min(2 s, probe_latency * 60))`. Authenticate the policy, probe,\nfloor, multiplier, ceiling, effective budget, and achieved duration in raw\nevidence. A fixed 100 ms budget was insufficient for a real IQ3_S M4096\ntransition whose first roughly 45 timing launches were still elevated. Do not\nrepair this class of failure by filtering the timing tail or relaxing the 2%\nfull-history drift gate.\n\nUse timing protocol `elapsed-stability-interleaved-v13` with ceiling policy\n`samples-and-elapsed-v1`. A stable candidate may still stop at the ordinary\n30-sample floor. An unstable candidate must satisfy both `sample_count >= 180`\nand `timed_duration_us >= 2,000,000` before the trainer can reject it; 180 is\nnot an unconditional maximum. A real cheap M64 route reached 180 samples after\nonly about 203 ms while still settling. The forced zero-drift regression must\ncontinue beyond 180 samples, accumulate the full measured-time budget, flush\nboth evidence files, and fail collectively without hanging its peer.\n\nAll MPMD ranks must make timing rejection collectively after flushing their\naggregate and timing sidecars. A rank-local GTest fatal assertion can strand a\npeer in the next-M barrier or MPI finalization. Reduce the failure decision and\nabort the communicator before any rank advances; retain an asymmetric direct\nregression that proves the failure exits instead of hanging.\n\nFor a production CPU corpus, add `--cpu-format-shards` and bound each invocation\nwith `--cpu-batch-limit N`. Re-run against the same output directory with\n`--resume-cpu-partials`; completed shape\u002Fformat\u002FISA outputs are atomic and must\nnot be measured twice. Never treat `.inprogress` files as evidence, combine a\npartial checkpoint, invoke the learner on it, or install from it.\n\nFor GPU corpora, use `--cuda-measurement-lanes N` and\n`--rocm-measurement-lanes N` to assign disjoint round-robin format shards to\nhomogeneous physical devices. The wrapper must reject excess or heterogeneous\nlanes, keep one aggregate\u002Ftiming pair per lane, and merge only after every lane\nis green. CUDA and ROCm timing transactions may run concurrently when they own\nseparate GPUs, but each concurrent command must restrict\n`--policy-accelerators` to its own backend. Never let CUDA policy fitting borrow\nROCm devices, or vice versa, while the borrowed backend is collecting canonical\ntiming. Profiler replay is a separate launch and must never overlap canonical\ntiming on the same physical device.\n\nTreat the checked-in GPU measurement plan as the physical timing authority;\nthe broader shape manifest is the support inventory. Common development shapes\nmust cover every production geometry and every reviewed feature bucket on all\nformats. Backend\u002Fformat-specific refinements must run only on their declared\nsurface: the v1 `fast-m1-cv-refinement-v5` extension is CUDA + Q4_0 + Fast M1,\nis shape-sharded across CUDA lanes, and must never appear in ROCm, another\nformat, or grouped-verifier evidence. Before a production run, execute\n`test_native_vnni_gpu_measurement_plan.py` and the refresh-wrapper regressions;\nthe analyzers must reject missing and unexpected\n`(contract, M, shape, format, execution mode)` surfaces.\n\nThe CPU ordinary-prefill covering plan must include the minimum-N*K production\ngeometry for every codebook\u002FM\u002Faspect\u002FISA domain. Pairwise feature coverage alone\ncan choose all witnesses from one larger model group, leaving the generic\nlearner without enough independent groups to certify a small-shape decision.\nPlan v7's generic covering array contains 1,583 runtime cells and 1,829\nsource-alias cells. Do not install from that base plan alone. Run the zero-kernel\nproduction route probe in all three build\u002Fruntime ISA regimes and pass its\nmanifests to the planner and analyzer. Route closure expands the blessed host\nplan to 1,820 runtime cells, 2,107 source cells, and 653 process jobs because the\nfinite native-AVX512 serial-K-part family must be timed exactly. Its\nlower-boundary anchors add only about 2.65% estimated GEMM work. When rebasing a\ncheckpoint to a new plan contract, reuse an atomic shard only if its complete M\ninventory exactly matches the new source record; otherwise omit the whole\naggregate and timing pair for recollection.\n\nTreat the C++ route manifest as authoritative for thread count, `k_tiles`, and\nthe full-K versus serial-K-part arithmetic bundle. Do not reproduce the\ncache-aware `computeTileConfig()` heuristic in Python. AVX2 serial-K-part has a\nsingle forceable Pairwise schedule and needs no learned tournament. Native\nAVX512 must measure Pairwise and WideRows over its complete finite production\nfamily; the current route-certified corpus selects Pairwise for `M=2`, where\nWideRows is unavailable, and measured WideRows for `M>=3`. Production `Auto`\nmust consume the generated table and fail hard on an unresolved surface.\n\nKeep certification geometry inside the checked-in manifest's supported\nproduction envelope. The current maximum is `1,271,398,400` weight elements,\nset by the largest supported production projection. CPU timing has a narrower\nchecked-in ceiling of `778,567,680` weight elements, exactly the Qwen2.5 32B\n`152064x5120` LM head; retain explicit 32B attention, QKV, FFN-up, FFN-down,\nand LM-head overlays in that matrix. Do not delete larger runtime geometries\nfrom the shared manifest merely to shorten CPU collection. Do not add larger\nsynthetic lattice points merely to make a sweep look exhaustive; the manifest\nloader must reject them.\n\nKeep MTP grouped-verifier measurements at `M=2..16,31`. The ordinary CPU\nNativeVNNI GEMM\u002Fprefill buckets are\n`M={64,256,1024,2048,4096,8192,16384}`. Cap 32B at `1024`, cap 14B at `4096`,\nand run the full range through `16384` for 9B-and-smaller models. The verifier\nand prefill matrices are separate contracts; do not inflate verifier collection\nwith prefill-only batch sizes or run giant 32B prefills merely for symmetry.\nCUDA and ROCm use the same buckets but directly measure every 14B\u002F32B\nprojection through `8192`; their higher ceiling is a backend-specific economy\nobligation, not permission to weaken the CPU timing target.\n\nQuery the authoritative ordinary-prefill matrix with:\n\n```bash\nPYTHONPATH=tests\u002Fv2\u002Fperformance\u002Fkernels \\\n  python3 -m native_vnni_dispatch.prefill_matrix --records\n```\n\nThe production measurement test is\n`CPUNativeVNNIGemvTest.TrainerCsv_StrongPrefill_AllFormats`. It must emit all\neight registry requests, retain normalized requests as unsupported evidence,\nprove both launches byte-equal to serial M1 rows, and keep isolated Linux\n`perf` collection outside the timing samples.\n\nPaired refinement uses the wrapper-owned `fit-cache` directory. The compact\nsource\u002Fmanifest\u002Fprojection identity, candidate costs, and CV results are\ncontent-addressed; candidate costs and CV are cached independently per\nmode\u002Fcodebook\u002Faspect domain and keyed by only that domain's tournament evidence.\nA new edge must not refit unaffected domains. Formula rows are projected lazily\nonly for a cost-miss or final-fit domain; CV traverses fitted trees directly\nfrom the cost matrix. Never serialize the expanded projected corpus. The\nlearner requests unresolved edges from its complete evaluated CV-model frontier\nin the current timing batch. Keep the cache-hit and domain-invalidation\nunit regressions green whenever changing CV, candidate costs, or paired request\nplanning.\n\nOrdinary NativeVNNI prefill is an independent common-policy surface. On CPU,\ntrain only physical schedules proven by\n`NativeVNNIPrefillFullKAllFormatsRuntimeMMatchesSerialDecode`: the row-chunk\ngrid formula and eligible two-row N-block schedules, each with exactly one\nfull-K tile. Reject K-tiled accumulation candidates whose intermediate FP32\nstores change serial-M1 parenthesization. Require the\n`cpu_native_vnni_prefill_gemm_launch` perfstats route to match the requested\ncandidate before admitting timing evidence.\n\nFor M=1 GEMV, report useful prepared-weight bandwidth as a fraction of an\nempirically measured sustainable HBM roofline, alongside physical profiler\ntraffic. Keep canonical median latency as the dispatch label: launch overhead,\nunpack work, and deterministic K-partition traffic can make bandwidth alone\nchoose the wrong winner. Grouped M>1 reports also need GOPS and arithmetic\nintensity because weight reuse can move the kernel away from the HBM roofline.\n\n## Grouped Kernel Tuning\n\nMTP only becomes economical when grouped verifier work is genuinely grouped.\nWrapping serial decode rows under a grouped API is not enough.\nGrouped decode publication also has a stricter correctness bar than ordinary\nnumeric parity: every grouped output row must be bitwise identical to the\nbackend's serial M=1 decode row for the same codebook\u002Fformat. Treat relaxed\nnumeric metrics as failure breadcrumbs, not success thresholds.\n\n### Verifier Kernel Mode Convention\n\nWhen verifier rows can be published into live MTP\u002FKV\u002FGDN state, stages must request\nbackend verifier modes through `ITensorGemm::beginVerifierDecodeEquivalentScope()`.\nDo not call backend `extern \"C\"` toggles or environment variables directly from\nstage code. CUDA and ROCm use this shared RAII hook to select generated small-M\ndispatch\u002Freduction policies that are reproducible against rowwise serial decode;\nCPU may return a no-op scope. Keep one scope per backend class alive for the whole\nserial replay or grouped publication region, and let destruction restore the\nprevious mode.\n\nFor shared-expert MoE verifier rows, the serial replay oracle must bypass normal\ngrouped shared-expert decode shortcuts unless those shortcuts are themselves\nstrictly proven equivalent. Compare grouped publication against canonical M=1\nGEMM\u002FSwiGLU\u002Fdown replay, not against another unproven grouped shortcut.\n\nPrioritize these paths:\n\n- Quantized GEMV\u002FGEMM for every M through the configured verifier capacity and\n  all Q, K, and IQ codebook families.\n- Fused gate\u002Fup and fused SwiGLU\u002Fdown.\n- LM head target\u002Fbonus rows without unnecessary all-position rows.\n- Attention verifier rows.\n- GDN recurrence\u002Fprojection and short-conv rows.\n- MoE routed experts and shared expert paths, but never fuse routed\u002Fshared\n  logic unless strict parity proves it.\n\nDispatch policy must be trained\u002Fgenerated, not hand hardcoded:\n\n- Sweep representative formats and M values.\n- Train\u002Fselect by codebook family, M, aspect ratio, and work-size buckets.\n- Use exact shape winners only as overlays above the generic policy.\n- Validate generated includes before installing them.\n- Keep CPU, CUDA, and ROCm trainer behavior comparable through the common\n  observation schema, exact oracle, learner, and certification gates.\n\nFor CPU, build ISA and effective runtime ISA are separate policy dimensions.\nTrain all three supported regimes: AVX2 build\u002FAVX2 runtime, AVX512 build\u002Fforced\nAVX2 runtime, and AVX512 build\u002FAVX512 runtime. Thread count is also part of the\nruntime key. Never train only the native ISA of the build and assume forced\nruntime dispatch has identical economics. Keep oneDNN artifacts isolated in\n`external\u002Fonednn\u002Fbuild-avx2` and `external\u002Fonednn\u002Fbuild-avx512` so configuring\none build cannot rewrite the dependency used by the other.\n\nThe canonical CPU production refresh is:\n\n```bash\nscripts\u002Frefresh_native_vnni_dispatch_tables.sh \\\n  --backend cpu \\\n  --profile all \\\n  --cpu-threads 28 \\\n  --cpu-measurement-lanes 2 \\\n  --cpu-avx2-sweep-bin build_v2_release\u002Ftests\u002Fv2\u002Fv2_perf_cpu_native_vnni_gemv \\\n  --cpu-avx512-sweep-bin build_v2_release_avx512\u002Ftests\u002Fv2\u002Fv2_perf_cpu_native_vnni_gemv \\\n  --output-dir benchmark_results\u002Fnative_vnni_dispatch\u002F\u003Crun-id> \\\n  --install\n```\n\nUse the physical cores per socket for `--cpu-threads` and the physical socket\ncount for `--cpu-measurement-lanes` on the blessed training host. The wrapper\nassigns distinct even\u002Fodd shape shards to MPI ranks mapped one per socket and\nruns the AVX512 binary twice with distinct runtime dispatch,\nrequires the complete ISA matrix, and permits `--install` only for a production\nQwen 3.6\u002Fall-shape profile. Retain the aggregate CSV, timing sidecar, common\nobservation CSV, generated include, and summary from every production run.\nAlso retain the profiler request\u002Fevidence manifests, authenticated\n`*_profiler_features.csv`, and raw artifact directory; they are bound to the\nobservation and timing-sample digests and cannot be regenerated from a\ndifferent run.\n\nAfter a CPU refresh, rebuild both binaries and run these gates:\n\n```bash\ncmake --build build_v2_release --parallel --target v2_perf_cpu_native_vnni_gemv\ncmake --build build_v2_release_avx512 --parallel --target v2_perf_cpu_native_vnni_gemv\ncmake --build build_v2_integration --parallel --target v2_integration_cpu_native_vnni_gemv\nctest --test-dir build_v2_integration -R \"^V2_Integration_CPUNativeVNNIVerifierISAResolver$\" --output-on-failure\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_CPU_AllFormats$\" --output-on-failure\nctest --test-dir build_v2_integration -R \"^V2_Integration_CPUNativeVNNI_GEMV$\" --output-on-failure\n```\n\nThe ISA resolver gate must validate production route counters for build ISA,\neffective runtime ISA, thread count, and selected grouped policy. Missing\ncertification is a hard failure; do not add a Pairwise or serial-row fallback.\nThe strong CPU trainer also executes a two-projection fused descriptor bundle\ntwice in every format\u002FM cell. It requires serial-row byte equality, repeat byte\nequality, and the `cpu_native_vnni_fused_verifier_rows_projection_launch`\ncounter with a two-row AVX2 or four-row AVX512 physical K-part tile. This proof\nmust remain enabled in all three CPU regimes; a byte-equal trainer candidate\nalone does not prove the production fused scheduler is economical.\n\nIf user asks whether to tune a single known model shape, do the experiment, but\nconvert any durable result into the general training pipeline before landing it.\n\n## State Ownership And Coherence\n\nMost serious MTP bugs come from split host\u002Fdevice ownership. Prefer device-owned\nlive state:\n\n- KV and shifted MTP KV publication\u002Ftruncation should be explicit and atomic.\n- GDN recurrence and short-conv state should publish accepted rows from device\n  speculative slots.\n- Host mirrors may observe state for logging\u002Ftests, but must not be the source\n  of truth for the hot path.\n- Reset APIs must say whether they clear session state, graph captures, prefix\n  cache, KV\u002FGDN live state, MTP sidecar state, or benchmark-only scratch.\n- Request reuse and `clearCache()` need dedicated regression tests.\n\nWhen fixing coherence bugs, add a test that proves continuation after publication,\nnot just immediate logits.\n\n## Sampling And Stochastic MTP\n\nStochastic support must be production-grade:\n\n- CPU, CUDA, and ROCm samplers should share the same math contract.\n- Temperature-zero greedy must still honor penalties and other applicable\n  sampling parameters.\n- GPU stochastic sampling should be device-resident and graph-capturable where\n  possible.\n- The verifier should avoid host token uploads in the hot path. Host-visible\n  tokens are outputs, not the next-step source of truth.\n- Qwen chat thinking-budget phrase injection must be honored; forcing only a\n  stop token is not sufficient.\n\nTest sampler parity on synthetic hard rows and real Qwen3.6 logits. Tie-breaking\nmust be deterministic and documented.\n\n## Dynamic MTP Depth Controller\n\nThe dynamic controller is a policy layer over fixed-depth economics. Do not tune\nit until fixed d1\u002Fd2\u002Fd3 lanes are healthy.\n\nMaintain or generate controller policy from real data:\n\n- Include short repetitive prompts, long prompts, code-generation prompts, and\n  default benchmark prompts.\n- Compare dynamic against fixed d1, d2, and d3 for each backend\u002Fmodel.\n- Dynamic should asymptotically approach the best fixed depth for a prompt class.\n- If backend preferences differ, first rule out math\u002Fparity drift; then explain\n  the performance reason in the dashboard.\n- Keep generated policy files reproducible and tied to holdout data. Avoid\n  one-off hand tuning.\n\n## Multi-Device Lanes\n\nTrack these modes in the dashboard even when implementation is pending:\n\n- SingleDevice CPU\u002FCUDA\u002FROCm.\n- LocalTP CUDA deg2, ROCm deg2, ROCm deg4.\n- LocalPP CUDA\u002FROCm.\n- NodeTP CPU sockets.\n- ExpertOverlay cases such as GPU hot plus CPU cold and mixed CUDA\u002FROCm\u002FCPU.\n\nMulti-device MTP must use common-prefix\u002Fcommon-accepted-count coordination.\nEvery participant enters collectives in the same order. Participants with no\nwork no-op through the same graph\u002Fcollective sequence.\n\n## Commit And Iteration Discipline\n\nFor each slice:\n\n1. State the targeted bottleneck or correctness bug.\n2. Add or update a regression test before or with the fix.\n3. Run focused tests for the touched path.\n4. Run the relevant MTP\u002Fprefix parity and perf gates.\n5. Update the plan and dashboard.\n6. Before a non-WiP commit, run the broader unit gate requested by the project\n   plan or precommit hook and fix failures rather than bypassing them.\n\nWhen a test sweep is large, resume from the last failure while iterating, then\nrun front-to-back once every listed test has passed at least once.\n","# Llaminar MTP Tuning\n\n## Purpose\n\nUse this skill to work on Llaminar's vLLM-style MTP path without re-learning the\nsame hard-won rules. MTP tuning is only successful when it improves real served\ninference speed while preserving strict decode equivalence across CPU, CUDA, and\nROCm, dense and MoE, greedy and stochastic.\n\nAlways keep these files current:\n\n- `docs\u002Fv2\u002Fprojects\u002F2026-06\u002FMTP_VLLM_STYLE_PROJECT_PLAN.md`: phase plan,\n  accepted architecture, gates, and known debt.\n- `docs\u002Fv2\u002Fprojects\u002F2026-06\u002FMTP_VLLM_STYLE_TUNING_DASHBOARD.md`: compact RAG\n  status and latest speed\u002Fcorrectness evidence. Keep it under the documented\n  size limit.\n- `docs\u002Fv2\u002Fprojects\u002F2026-06\u002FPREFIX_CACHE_MTP_BENCHMARK_NOTES.md`: only for\n  broader historical benchmark notes when the current dashboard is not the\n  right home.\n\nFor backend kernel work, also use the relevant sibling skill:\n\n- `.agents\u002Fcuda-tuning\u002FSKILL.md` for CUDA profiling, Nsight, and generated\n  NativeVNNI dispatch work.\n- `.agents\u002Frocm-tuning\u002FSKILL.md` for HIP\u002FROCm profiling, rocprof, ISA analysis,\n  and generated NativeVNNI dispatch work.\n\n## Architecture North Star\n\nLlaminar is moving toward vLLM-style speculative decode:\n\n1. Draft rows live in speculative slots, not live model state.\n2. The target verifier runs `draft_count + 1` rows: draft rows plus one bonus row.\n3. Device-side sampler\u002Frejection logic produces accepted counts and output tokens.\n4. Only accepted speculative slots are published to live state.\n5. Rejected suffix and bonus-only rows must not mutate live KV, GDN, short-conv,\n   positions, terminal hidden, terminal logits, or sampler history.\n6. Greedy is a deterministic specialization of the stochastic contract, not a\n   separate architecture.\n\nThe canonical transaction shape is:\n\n```text\nprepare spec slots\nrun draft graph\nrun target verifier graph\nrun rejection sampler \u002F accepted-count reducer\npublish accepted state\ndiscard rejected state\nreturn tokens\n```\n\nKeep graphs per-device and symmetric. Do not introduce nested multi-device\nsidecar graphs. LocalTP, LocalPP, NodeTP, and ExpertOverlay must extend the\nsame transaction semantics with collective coordination, not invent separate\nstate machines.\n\n### Canonical MoE LLEP Policy Tuple\n\n`LLEP` names one current-batch routed-row assignment policy. It is not a\ncomplete execution mode, routed-expert storage policy, decode policy, durable\nresidency controller, or hot-cache policy. Keep these axes explicit whenever\nconstructing, testing, or benchmarking a MoE graph:\n\n- dense\u002Fshared trunk: tensor parallel;\n- routed-expert storage and compute: apportioned whole experts;\n- routed phase: uniform;\n- grouped verifier\u002Fdecode assignment: static owner;\n- ordinary large-prefill assignment: least-loaded resident (LLEP);\n- MTP terminal norm\u002Fhead: mirrored full vocabulary;\n- durable expert-residency maintenance: off;\n- hot expert replica cache: off;\n- same-backend transport: one fully captured NCCL or RCCL graph.\n\nThe prefill row threshold is an explicit work-regime boundary, not recovery\nbehavior: below it, execute economical static-owner EP; at or above it, execute\nthe current-batch least-loaded assignment. Set the threshold to zero only in a\nfocused integration test that must force and prove the transfer-backed LLEP\npath. Never let prefill assignment bleed into grouped verifier\u002Fdecode, and\nnever use whole-expert decode movement as a proxy for LLEP.\n\nDeclare the tuple through `DenseParallelPolicy`,\n`RoutedExpertComputePolicy`, `RoutedExpertPhasePolicy`, separate\n`routed_decode_assignment` and `routed_prefill_assignment` domain fields,\n`MTPTerminalHeadPolicy`, `--moe-residency-maintenance`, and\n`--moe-hot-expert-cache`. Graph builders own the resulting stage, collective,\nand event wiring. PerfStats must prove static-owner grouped verification,\nleast-loaded large prefill, mirrored terminal-head execution, full graph\ncapture, and zero segmented execution.\n\n## Non-Negotiable Rules\n\n- Never use CUDA\u002FHIP default or null streams. Every GPU operation needs an\n  explicit stream, including copies, memset, events, reductions, sampling, and\n  graph-captured stages.\n- Never allocate GPU memory in the hot path. Use declared graph workspace,\n  `IWorkspaceConsumer`, arena buffers, or low-level sanctioned allocators.\n- Never mutate tensor residency flags directly. Use `TransferEngine` unless a\n  graph-stage buffer contract already provides the correct resident pointer.\n- Never capture H2D copies inside GPU graphs. Upload persistent inputs before\n  capture and replay device-resident buffers.\n- Never leave quiet recovery paths. Every advertised MTP lane must implement\n  its declared policy or fail fast with a precise diagnostic.\n- Never land special codebook exceptions in production kernels. Use generic\n  dispatch keyed by codebook family, M, aspect ratio, work size, and generated\n  policy tables. Exact shape overlays are additive to a total general dispatch\n  rule; they never substitute for that rule.\n- Never accept token equality alone as correctness proof for verifier kernels.\n  Require distribution and numeric gates.\n- Remove dead-end code and tests once a path is abandoned. Negative tests for\n  deleted approaches just confuse future work.\n- Keep CUDA and ROCm structurally aligned. Backend-specific code should sit\n  behind common stage\u002Fkernel interfaces.\n- Write regression unit or integration tests for every crash, coherence bug,\n  stream bug, dispatch bug, and parity break found during tuning.\n\n## Correctness Gates\n\nUse strict gates before promoting any MTP optimization:\n\n- **Grouped verifier decode must be bitwise serial-row equivalent.** For\n  grouped MTP verifier rows, the acceptance threshold is byte-for-byte identical\n  FP32 output compared with running the same rows through the production M=1\n  serial decode path in the same backend and tensor format. Cosine similarity,\n  relative L2, symmetric KLD, and max-absolute-error are diagnostics for finding\n  the first drift; they are not pass criteria for grouped decode publication.\n- Relative L2: tight enough to catch drift for the tested precision\u002Fpath.\n- Cosine similarity: near 1.0 for logits, hidden rows, and kernel outputs.\n- Symmetric KLD: required when outputs feed sampling or softmax decisions.\n- Max absolute error: required for small-M kernel equivalence.\n- Sampled-token equality: required, but not sufficient by itself.\n- Decode-equivalent continuation: accepted-state publication must match serial\n  decode after continuing for enough rows to expose KV\u002FGDN\u002Fshort-conv mistakes.\n\nGrouped verifier APIs and kernels must accept runtime M up to the graph and\nworkspace capacity; never encode speculative depth as an `M=2..4` template or\nadmission limit. M=1 is the independent production serial-decode oracle. The\ncanonical grouped inventory proves every integer M=2..16 plus M=31 for every\nbackend and every advertised tensor codebook or floating-point tensor format.\nM=31 is a deliberate deeper sentinel for speculative regimes beyond the usual\nfifteen drafts; it is not a maximum. A larger configured graph capacity must\nextend the contiguous sweep through that capacity rather than sample only its\nendpoint. Use fixed-size physical row tiles to bound register pressure and\npreserve weight reuse as M grows; do not generate one kernel specialization per\nspeculative depth.\n\nPrefer dedicated integration tests before wiring a new kernel into graph\nexecution. Good test names to search for include:\n\n```bash\nrg -n \"VerifierRows|decode_equivalent|PrefixMTP|GPUSampling|NativeVNNI|QuantisedGemmSmallM\" tests\u002Fv2\n```\n\nCommon focused gates:\n\n```bash\nctest --test-dir build_v2_integration -R \"^V2_Unit_PrefillDecodeTransition$|^V2_Unit_MTP|^V2_Integration_GPUSamplingKernels\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_.*MTP|^V2_Integration_.*Prefix\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_.*VerifierRows|^V2_Integration_.*QuantisedGemmSmallM|^V2_Integration_.*NativeVNNI\" --output-on-failure --parallel\n```\n\n### Mandatory all-format grouped verifier sweeps\n\nThese integration suites are the first line of defense for grouped verifier\ndecode. They prove that production grouped rows are byte-identical to serial\ndecode across the backend's advertised tensor\u002Fcodebook formats. Run them after\nany change to MTP verifier rows, NativeVNNI\u002FGEMV dispatch, MoE routed\u002Fshared\nexpert kernels, LocalTP verifier output projection, attention, RMSNorm, or GDN\nprojection. A failure here is a production grouped implementation bug; do not\npaper over it with serial row replay, relaxed thresholds, or a backend-specific\nformat exception.\n\nTreat these sweeps as mandatory architecture proof, not ordinary smoke tests.\nGrouped decode is publishable only when every production grouped implementation\nis both byte-exact against serial M=1 decode and genuinely grouped\u002Feconomical\nfor every format that backend can load. If a new grouped verifier operation,\ncodebook family, floating-point tensor format, or backend lane is added, extend\nthe corresponding sweep in the same slice before tuning or claiming the lane is\ncomplete.\n\nThe CUDA all-format gate must include the production fused projection,\nlarge-K KPAR, fused SwiGLU\u002Fdown, FP32, FP16, and BF16 runtime-M tests. Search for\n`RuntimeM2To16` in `Test__CUDAGemmParity.cpp`; the low-level NativeVNNI case also\ncaptures and replays every format\u002Fdepth combination. Equivalent CPU and ROCm\nlanes must use the same contiguous row inventory.\n\nRouted MoE format sweeps must enter through the production router before the\ngrouped expert pass and validate the router-to-expert Q8 publication counter;\nprecomputed host route IDs do not prove this optimization. The canonical\ncounters are `cpu_moe_grouped_verifier_router_q8_reuse_calls`,\n`cuda_moe_grouped_prefill_router_q8_reuse_calls`, and\n`rocm_moe_grouped_prefill_router_q8_reuse_calls`. CPU serial-oracle rows must\nalso observe `cpu_moe_decode_router_q8_reuse_calls`. A byte-equal result without\nthe matching counter is a failed gate because it may only show that two\nindependent quantizers happened to agree for the synthetic input.\n\n```bash\n# Discover the exact registered inventory first, then run every present and\n# future grouped-verifier lane. Do not replace this prefix gate with a hand list.\nctest --test-dir build_v2_integration -N -R \"^V2_Integration_GroupedVerifierRows_\"\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_\" --output-on-failure --parallel\n\n# Backend slices are useful while iterating, but all three remain mandatory\n# before a grouped-verifier slice is accepted.\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_CPU_\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_CUDA_\" --output-on-failure --parallel\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_ROCm_\" --output-on-failure --parallel\n```\n\nAs of 2026-07-13 the prefix gate discovers 51 substantive lanes: 13 CPU, 17\nCUDA, and 21 ROCm (`52` CTest entries including the model fixture). The\ninventory includes all-format GEMM, MoE codegroups and\nexpert paths, floating formats, dense QKV\u002FGDN projections, replicated LocalTP\noutput projection, embedding, RMSNorm, fused residual norm, residual add,\nSwiGLU, RoPE, attention, KV-cache append, GDN recurrence, short-conv,\nrequest-batched GDN state, and device-resident stochastic sampling. The\nprefix command is canonical precisely so a newly registered operation cannot be\nomitted from an otherwise plausible-looking hand-maintained regex.\n\nThe backend counts are an inventory, not a symmetry waiver. Before the final\nMTP gate, compare the semantic operation matrix across CPU, CUDA, and ROCm and\nadd every applicable missing lane. In particular, CPU currently lacks the GPU\nstochastic-resident and request-batched recurrent-state lanes, while explicit\nall-format\u002Fruntime-M projection and MoE codegroup discovery is not named\nuniformly across the three backends.\n\nThe CUDA and ROCm `GDNRecurrence` and `ShortConv` lanes also prove captured\ngraph lifetime across accepted-state publication. Each backend captures the\nordinary M=1 decode graph once, runs grouped verifier M=2\u002F3\u002F4 into isolated\nspeculative state, publishes every possible accepted row by a device-owned row\nindex, detaches verifier bindings, and replays the original graph without\nrecapture. Both the continuation output and complete recurrent live state must\nmatch serial M=1 decode in native bytes. This proof is what permits the typed\ncorrection-boundary policy to retain single-token decode and all-position\nverifier captures; a blanket CUDA\u002FROCm graph reset is a regression, not a\nconservative fallback.\n\nThe CUDA and ROCm `KVCacheAppend` gates each enumerate the same 288 production\nroutes: every accepted cache\u002Fsource format pair (including asymmetric prepared\nTQ8-K\u002FTQ4-V), M=2\u002F3\u002F4, position-major and verifier-head-major inputs,\nreplicated and LocalTP-sharded caches, and direct-static versus graph-captured\ndevice-dynamic ring metadata. They require native cache byte equality, sequence\nmetadata equality, prefix-block export\u002Fimport round trips, and exactly one\ngrouped route-counter observation per matrix cell.\n\nThe CPU `RoPE` gate covers FP32, BF16, FP16, pure-integer Q8_1, and Q16_1 with\n32\u002F64\u002F128-value native blocks at M=2\u002F3\u002F4. It compares native bytes against\nserial M=1 decode and checks the `single_grouped_row_head_workshare` route, so a\nrow loop hidden behind the grouped interface is not an acceptable replacement.\n\nThe explicit CUDA and ROCm `RoPE` gates mirror one 24-cell matrix per backend:\nFP32 full\u002Fpartial plus BF16 and FP16, M=2\u002F3\u002F4, and both contiguous\ndevice-scalar and explicit device-row position owners. They compare native GPU\nbytes with the same backend's production M=1 decode kernel, require non-default\nstreams, and reject a missing `single_grouped_launch` route counter.\n\nThe explicit CUDA and ROCm `RMSNorm` gates each cover 18 positive production\ncells: FP32, BF16, and FP16 at M=2\u002F3\u002F4 for 128-column per-head Q\u002FK normalization\nand 4096-column hidden-state normalization. Those widths cross the narrow and\nwide reduction launch policies. Every cell enters `apply_tensor` on a\nnon-default stream, compares native output bytes with same-backend M=1 decode,\nand requires one `one_block_per_row` \u002F `single_grouped_launch` counter. Three\nadditional negative cells prove that every native format rejects an unbound\ndefault stream without publishing route telemetry.\n\nThe CPU, CUDA, and ROCm `ResidualAdd` gates each cover FP32, BF16, and FP16 at\nM=2\u002F3\u002F4 for 128- and 4096-column rows. They require native byte equality against\nsame-backend M=1 decode and exactly one flat workshare\u002Flaunch counter. GPU gates\nalso require device-only `gpu_data_ptr()` ownership and verify that every format\nrejects an unbound default stream; in particular, this guards ROCm BF16's stream\nsetter, which must remain symmetric with FP32 and FP16.\n\nThe CPU, CUDA, and ROCm `FusedResidualNorm` gates cover the same 18 positive\ncells per backend but enter `FusedResidualNormStage`, the actual graph operation\nat attention and FFN residual boundaries. Both the in-place residual publication\nand normalized output must match independent production M=1 stage executions in\nnative bytes. CUDA and ROCm additionally run one null-stream rejection cell per\nformat and require one device-resident fused launch; this prevents the separate\nResidualAdd\u002FRMSNorm suites from masking broken fused type dispatch or stale host\nownership.\n\nThe standalone `SwiGLU` gates cover M=2\u002F3\u002F4 at 544 and 4864 columns. CUDA and\nROCm sweep FP32\u002FBF16\u002FFP16 with explicit streams and one flat launch; CPU adds\nQ8_1 and requires one native workshare. The 544-column case is deliberately 17\nQ8 blocks wide, so grouped execution cannot pair blocks across a row boundary\nwithout the native-byte oracle noticing. These gates complement, rather than\nduplicate, fused GEMM+SwiGLU-down coverage.\n\nUse the backend-specific all-format sweep as the minimum acceptance gate for a\nnarrow kernel edit, then run the full backend group before claiming that grouped\ndecode is proven for that backend. Model-level prefix\u002FMTP parity and\n`Qwen36_MTPForwardVerifierOperationEquivalence` remain required because they\ncatch cross-stage amplification, but they do not replace the all-format sweeps.\n\nDo not run only the easy backend. If CUDA has a deep PyTorch or layer-by-layer\ntest, ROCm and CPU need the same semantic coverage unless the plan explicitly\nmarks the lane as not implemented.\n\nRefresh the inventory with `ctest --test-dir build_v2_integration -N -R\n\"^V2_Integration_GroupedVerifierRows_\"` when adding tests. Keep every canonical\ntest under that namespace so the precommit, CI, and skill prefix gates include\nit automatically.\n\n## Performance Methodology\n\nStart with real inference, then isolate:\n\n1. Capture a Release benchmark for the relevant lane with fixed d1\u002Fd2\u002Fd3 and\n   dynamic depth.\n2. Enable `LLAMINAR_PERF_STATS_GPU_STAGE_TIMING=1` with JSON\u002FCSV export to rank\n   graph-replay bottlenecks on the production captured topology. The deprecated\n   `LLAMINAR_PROFILING` alias must never disable graph capture or select eager\n   execution.\n3. Split host bridge accounting from producer work. A D2H timer that includes\n   waiting for a producer event is not proof of copy overhead.\n4. Attack the biggest real chunk first. For MTP this is usually verifier forward,\n   LM head, grouped GEMV\u002FGEMM, attention, GDN\u002Fshort-conv, sampling, or state\n   publication.\n5. Microbench candidate kernels with strict parity against serial decode.\n6. Re-run the model-level benchmark and parity suite after each concrete slice.\n7. Update the dashboard with the run directory, speedup, acceptance rate, and\n   current RAG.\n\nUseful benchmark shape:\n\n```bash\nscripts\u002Frun_mtp_iteration_benchmark_matrix.sh \\\n  --devices cuda:0,rocm:0 \\\n  --models dense,moe \\\n  --modes greedy,stochastic \\\n  --variants fixed_d1,fixed_d2,fixed_d3,dynamic \\\n  --decode-tokens 16 \\\n  --perfstats \\\n  --output-dir benchmark_results\u002Fmtp_vllm_style\u002F\u003Ctimestamp>\n```\n\nUse `scripts\u002Fsummarize_mtp_perfstats.py` to compare:\n\n- `decode_step_ms`\n- verifier forward \u002F graph replay time\n- stage GPU time by type\n- sidecar time\n- publish time\n- sampler\u002Freducer time\n- response-ready wait versus actual D2H enqueue\u002Fwait\n- acceptance, rejection, and rollback counts\n\n### Isolated NativeVNNI profiler evidence\n\nNativeVNNI policy training has two physically separate evidence transactions.\nCanonical candidate timing runs first, with production warmups and\nsample-interleaved rounds. Only after those observations and raw timing samples\nare immutable may `profiler_evidence.py` derive per-candidate requests.\n`profiler_collectors.py` then starts one fresh process per request and gathers\nLinux `perf`, Nsight Compute, or rocprofiler metrics from an extra isolated\nlaunch. Profiler replay duration is never a timing label.\n\nEvery supported observation needs one evidence record; unsupported candidates\nneed an explicit non-profile state. CUDA\u002FROCm candidates may be pipelines, so\nretain quantization, producer, reducer, and epilogue dispatches independently\nand in launch order. Optional counters unavailable on one architecture remain\ntyped unavailable fields. A missing tool, raw report, required counter, or\nsupported candidate record blocks production evidence completeness. Production\n`scripts\u002Frefresh_native_vnni_dispatch_tables.sh --profile all` enables this gate\nby default, and `--install --skip-profiler-evidence` is forbidden.\n\nThe required `*_profiler_features.csv` export is an authenticated join of the\ncanonical common-observation timing CSV, request manifest, and evidence\nmanifest. It retains pipeline-level canonical timing alongside one ordered row\nper physical dispatch and that dispatch's own counters. Never train from a\nhand-joined profiler CSV or treat profiler replay duration as canonical\nlatency; a corpus\u002Frequest\u002Fevidence digest mismatch must fail the refresh.\n\n### Immutable Git LFS corpora and turnkey refits\n\nThe canonical cross-backend procedure now lives in\n`.agents\u002Fnativevnni-gemm-tuning\u002FSKILL.md`. Keep this section focused on MTP's\nstrict grouped-row equivalence and its interaction with speculative decode.\n\nUse `scripts\u002Ftrain_native_vnni_dispatch.sh --backend \u003Cbackend> --install` as the\nnormal production entry point for `cuda`, `rocm`, `cpu`, and `cpu-prefill`.\nThe command rebuilds both vendor policy scorers, validates their integration\noracles, benchmarks and profiles only when no matching corpus generation is\npublished, fits and certifies, and atomically installs the generated include.\nAdditional refresh options belong after `--`.\n\nPublished generations live under\n`corpora\u002Fnative_vnni_dispatch\u002F\u003Cbackend>\u002F\u003Carchitecture>\u002F\u003Cshape-digest>-\u003Cconfiguration-digest>\u002F`\nin the optional `Llaminar\u002Fcorpora` submodule. All published corpus families\nbelong in that data repository; the source repository pins only its gitlink.\nInitialize and selectively pull LFS through the canonical tuning skill's\ncorpus workflow, never during ordinary builds or Unit\u002Fpreflight gates.\n`corpus.manifest.json` is ordinary Git metadata there; large timing\u002Fprofiler\npayloads are Git LFS objects. Never hand-edit a sealed generation. The corpus verifier\nmust reject unresolved LFS pointers, partial files, symlinks, changed payload\ndigests, and stale resolved shape inventories. Fit-only replay materializes a\ndisposable workspace and uses `--skip-sweep --reuse-profiler-evidence`; it may\nre-export authenticated profiler features but must launch no candidate kernel\nand no profiler. A failed fit is mined again from the same corpus rather than\ntriggering another timing sweep.\n\nThe final corpus directory suffix also binds forwarded collection arguments.\nDo not pass `--shapes` or `--shape-partition` through the turnkey command;\nproduction overlays belong in the shared inventory so all backends see them.\n\nEvery exact overlay comes from the shared resolved shape inventory consumed by\nthe CPU, CUDA, and ROCm trainers. Backend-private shape lists are forbidden.\nAn overlay addition changes the inventory digest and therefore requires a new\ncorpus generation; exact overlays remain additive to mandatory generic rules.\n\n### GPU-accelerated NativeVNNI policy fitting\n\nThe common policy learner can batch its first two exact leaf keys on CUDA and\nROCm. Build `v2_native_vnni_leaf_primary_scorer_cuda` and\n`v2_native_vnni_leaf_primary_scorer_rocm`; production\n`refresh_native_vnni_dispatch_tables.sh --profile all` auto-discovers both\nvendor inventories and uses isolated one-vendor worker processes. Each physical\ndevice defaults to eight CPU orchestration lanes because tree construction is\nstill host work and the scorer kernels are brief. Tune with `--policy-lanes`,\nor explicitly choose `--policy-accelerators cpu` for the canonical CPU fitter.\n\nEach GPU scorer lane must keep one uploaded regret matrix, non-default stream,\nand growable scratch session alive across all leaf batches for a fit. Do not\nreintroduce per-call stream creation, device allocation, or full-matrix upload.\nSchedule CV\u002Ffinal-fit tasks through the longest-first dynamic device queue and\nrefill whichever lane completes first; restore task-index order before policy\nreduction so scheduling cannot affect generated bytes. Static per-lane task\npartitions are forbidden because heterogeneous folds create a severe idle tail.\nRepresent tree point subsets as arbitrary-width integer masks, cache exact\nthreshold membership masks, and retain ordered point tuples only for canonical\nlater-key\u002Freport materialization. Keep the unit invariant that leaf masks are\ndisjoint, cover the full point inventory, and map exactly to retained ordered\npoints; generated report and request bytes must match before\u002Fafter any beam\nrepresentation optimization.\n\nThe GPU computes maximum regret as a diagnostic and the integer count at or\nabove the strict 5% boundary. Python derives p95 and mean regret and retains\ncandidate-name tie-breaking so report\u002Frequest bytes stay identical to CPU\nfitting. A policy is installable only when measured p95 regret and conservative\np95 regret upper bound are both strictly below 5%; maximum regret is never an\ninstallation gate. Run\n`V2_Integration_NativeVNNILeafPrimaryScorer_CUDA` and `_ROCm`; unit tests must\nremain GPU-free. Once acceleration is explicitly requested, a missing DSO,\ndevice, or worker is a hard failure. Never silently resume on CPU, and never\nconfuse policy-scoring GPU work with separately timed candidate kernels or\nisolated profiler launches.\n\nGPU scorers do not replace backend candidate measurement. In particular, CPU\nkernel timing must remain on CPU. On a multisocket trainer host, split distinct\nshape\u002Fsource\u002FISA jobs across an MPMD MPI launch with one rank per socket. Never\nlaunch the same tuple on both ranks, and give every rank distinct aggregate and\nraw-timing paths. Pair only jobs with identical ordered M inventories. Enable\n`LLAMINAR_CPU_NVNNI_PREFILL_MPI_ROUND_SYNC=1` so every warmup and timing round\nends in an MPI active-rank reduction; a locally converged rank must continue\nunmeasured complete-round pacing until every rank finishes the same M phase.\nWithout that coordination, one rank can advance to a larger M and manufacture\nfrequency or memory-pressure drift in its peer's timing series.\n\nInstallable CPU prefill evidence must authenticate\n`mpi-complete-round-v1`, MPI world size\u002Frank, and global warmup\u002Ftiming round\ncounts. The adapter must reject candidate\u002Fglobal round disagreement and any\nmulti-rank production corpus collected with process-local pacing. Do not fix a\ncross-rank transient by raising the sample ceiling, relaxing the 2% drift gate,\nor selecting a convenient stable tail.\n\nWarmup is elapsed-evidence controlled, not round-count controlled. An M64\ncandidate can legitimately require more than 10,000 launches to accumulate one\nsecond, so do not reintroduce a fixed warmup-round ceiling. Keep the 30-second\nper-complete-round watchdog, require every measured launch to make finite\npositive timer progress, and record total phase wall time plus maximum round\nduration. Long-M phases may legitimately exceed 30 seconds across several\nrounds; retain the per-candidate measured-duration gate as the promotion\nrequirement.\n\nAfter the one-second source preconditioning cell, derive each CPU prefill\ncandidate's M-transition warmup from its first production-route latency probe:\n`max(100 ms, min(2 s, probe_latency * 60))`. Authenticate the policy, probe,\nfloor, multiplier, ceiling, effective budget, and achieved duration in raw\nevidence. A fixed 100 ms budget was insufficient for a real IQ3_S M4096\ntransition whose first roughly 45 timing launches were still elevated. Do not\nrepair this class of failure by filtering the timing tail or relaxing the 2%\nfull-history drift gate.\n\nUse timing protocol `elapsed-stability-interleaved-v13` with ceiling policy\n`samples-and-elapsed-v1`. A stable candidate may still stop at the ordinary\n30-sample floor. An unstable candidate must satisfy both `sample_count >= 180`\nand `timed_duration_us >= 2,000,000` before the trainer can reject it; 180 is\nnot an unconditional maximum. A real cheap M64 route reached 180 samples after\nonly about 203 ms while still settling. The forced zero-drift regression must\ncontinue beyond 180 samples, accumulate the full measured-time budget, flush\nboth evidence files, and fail collectively without hanging its peer.\n\nAll MPMD ranks must make timing rejection collectively after flushing their\naggregate and timing sidecars. A rank-local GTest fatal assertion can strand a\npeer in the next-M barrier or MPI finalization. Reduce the failure decision and\nabort the communicator before any rank advances; retain an asymmetric direct\nregression that proves the failure exits instead of hanging.\n\nFor a production CPU corpus, add `--cpu-format-shards` and bound each invocation\nwith `--cpu-batch-limit N`. Re-run against the same output directory with\n`--resume-cpu-partials`; completed shape\u002Fformat\u002FISA outputs are atomic and must\nnot be measured twice. Never treat `.inprogress` files as evidence, combine a\npartial checkpoint, invoke the learner on it, or install from it.\n\nFor GPU corpora, use `--cuda-measurement-lanes N` and\n`--rocm-measurement-lanes N` to assign disjoint round-robin format shards to\nhomogeneous physical devices. The wrapper must reject excess or heterogeneous\nlanes, keep one aggregate\u002Ftiming pair per lane, and merge only after every lane\nis green. CUDA and ROCm timing transactions may run concurrently when they own\nseparate GPUs, but each concurrent command must restrict\n`--policy-accelerators` to its own backend. Never let CUDA policy fitting borrow\nROCm devices, or vice versa, while the borrowed backend is collecting canonical\ntiming. Profiler replay is a separate launch and must never overlap canonical\ntiming on the same physical device.\n\nTreat the checked-in GPU measurement plan as the physical timing authority;\nthe broader shape manifest is the support inventory. Common development shapes\nmust cover every production geometry and every reviewed feature bucket on all\nformats. Backend\u002Fformat-specific refinements must run only on their declared\nsurface: the v1 `fast-m1-cv-refinement-v5` extension is CUDA + Q4_0 + Fast M1,\nis shape-sharded across CUDA lanes, and must never appear in ROCm, another\nformat, or grouped-verifier evidence. Before a production run, execute\n`test_native_vnni_gpu_measurement_plan.py` and the refresh-wrapper regressions;\nthe analyzers must reject missing and unexpected\n`(contract, M, shape, format, execution mode)` surfaces.\n\nThe CPU ordinary-prefill covering plan must include the minimum-N*K production\ngeometry for every codebook\u002FM\u002Faspect\u002FISA domain. Pairwise feature coverage alone\ncan choose all witnesses from one larger model group, leaving the generic\nlearner without enough independent groups to certify a small-shape decision.\nPlan v7's generic covering array contains 1,583 runtime cells and 1,829\nsource-alias cells. Do not install from that base plan alone. Run the zero-kernel\nproduction route probe in all three build\u002Fruntime ISA regimes and pass its\nmanifests to the planner and analyzer. Route closure expands the blessed host\nplan to 1,820 runtime cells, 2,107 source cells, and 653 process jobs because the\nfinite native-AVX512 serial-K-part family must be timed exactly. Its\nlower-boundary anchors add only about 2.65% estimated GEMM work. When rebasing a\ncheckpoint to a new plan contract, reuse an atomic shard only if its complete M\ninventory exactly matches the new source record; otherwise omit the whole\naggregate and timing pair for recollection.\n\nTreat the C++ route manifest as authoritative for thread count, `k_tiles`, and\nthe full-K versus serial-K-part arithmetic bundle. Do not reproduce the\ncache-aware `computeTileConfig()` heuristic in Python. AVX2 serial-K-part has a\nsingle forceable Pairwise schedule and needs no learned tournament. Native\nAVX512 must measure Pairwise and WideRows over its complete finite production\nfamily; the current route-certified corpus selects Pairwise for `M=2`, where\nWideRows is unavailable, and measured WideRows for `M>=3`. Production `Auto`\nmust consume the generated table and fail hard on an unresolved surface.\n\nKeep certification geometry inside the checked-in manifest's supported\nproduction envelope. The current maximum is `1,271,398,400` weight elements,\nset by the largest supported production projection. CPU timing has a narrower\nchecked-in ceiling of `778,567,680` weight elements, exactly the Qwen2.5 32B\n`152064x5120` LM head; retain explicit 32B attention, QKV, FFN-up, FFN-down,\nand LM-head overlays in that matrix. Do not delete larger runtime geometries\nfrom the shared manifest merely to shorten CPU collection. Do not add larger\nsynthetic lattice points merely to make a sweep look exhaustive; the manifest\nloader must reject them.\n\nKeep MTP grouped-verifier measurements at `M=2..16,31`. The ordinary CPU\nNativeVNNI GEMM\u002Fprefill buckets are\n`M={64,256,1024,2048,4096,8192,16384}`. Cap 32B at `1024`, cap 14B at `4096`,\nand run the full range through `16384` for 9B-and-smaller models. The verifier\nand prefill matrices are separate contracts; do not inflate verifier collection\nwith prefill-only batch sizes or run giant 32B prefills merely for symmetry.\nCUDA and ROCm use the same buckets but directly measure every 14B\u002F32B\nprojection through `8192`; their higher ceiling is a backend-specific economy\nobligation, not permission to weaken the CPU timing target.\n\nQuery the authoritative ordinary-prefill matrix with:\n\n```bash\nPYTHONPATH=tests\u002Fv2\u002Fperformance\u002Fkernels \\\n  python3 -m native_vnni_dispatch.prefill_matrix --records\n```\n\nThe production measurement test is\n`CPUNativeVNNIGemvTest.TrainerCsv_StrongPrefill_AllFormats`. It must emit all\neight registry requests, retain normalized requests as unsupported evidence,\nprove both launches byte-equal to serial M1 rows, and keep isolated Linux\n`perf` collection outside the timing samples.\n\nPaired refinement uses the wrapper-owned `fit-cache` directory. The compact\nsource\u002Fmanifest\u002Fprojection identity, candidate costs, and CV results are\ncontent-addressed; candidate costs and CV are cached independently per\nmode\u002Fcodebook\u002Faspect domain and keyed by only that domain's tournament evidence.\nA new edge must not refit unaffected domains. Formula rows are projected lazily\nonly for a cost-miss or final-fit domain; CV traverses fitted trees directly\nfrom the cost matrix. Never serialize the expanded projected corpus. The\nlearner requests unresolved edges from its complete evaluated CV-model frontier\nin the current timing batch. Keep the cache-hit and domain-invalidation\nunit regressions green whenever changing CV, candidate costs, or paired request\nplanning.\n\nOrdinary NativeVNNI prefill is an independent common-policy surface. On CPU,\ntrain only physical schedules proven by\n`NativeVNNIPrefillFullKAllFormatsRuntimeMMatchesSerialDecode`: the row-chunk\ngrid formula and eligible two-row N-block schedules, each with exactly one\nfull-K tile. Reject K-tiled accumulation candidates whose intermediate FP32\nstores change serial-M1 parenthesization. Require the\n`cpu_native_vnni_prefill_gemm_launch` perfstats route to match the requested\ncandidate before admitting timing evidence.\n\nFor M=1 GEMV, report useful prepared-weight bandwidth as a fraction of an\nempirically measured sustainable HBM roofline, alongside physical profiler\ntraffic. Keep canonical median latency as the dispatch label: launch overhead,\nunpack work, and deterministic K-partition traffic can make bandwidth alone\nchoose the wrong winner. Grouped M>1 reports also need GOPS and arithmetic\nintensity because weight reuse can move the kernel away from the HBM roofline.\n\n## Grouped Kernel Tuning\n\nMTP only becomes economical when grouped verifier work is genuinely grouped.\nWrapping serial decode rows under a grouped API is not enough.\nGrouped decode publication also has a stricter correctness bar than ordinary\nnumeric parity: every grouped output row must be bitwise identical to the\nbackend's serial M=1 decode row for the same codebook\u002Fformat. Treat relaxed\nnumeric metrics as failure breadcrumbs, not success thresholds.\n\n### Verifier Kernel Mode Convention\n\nWhen verifier rows can be published into live MTP\u002FKV\u002FGDN state, stages must request\nbackend verifier modes through `ITensorGemm::beginVerifierDecodeEquivalentScope()`.\nDo not call backend `extern \"C\"` toggles or environment variables directly from\nstage code. CUDA and ROCm use this shared RAII hook to select generated small-M\ndispatch\u002Freduction policies that are reproducible against rowwise serial decode;\nCPU may return a no-op scope. Keep one scope per backend class alive for the whole\nserial replay or grouped publication region, and let destruction restore the\nprevious mode.\n\nFor shared-expert MoE verifier rows, the serial replay oracle must bypass normal\ngrouped shared-expert decode shortcuts unless those shortcuts are themselves\nstrictly proven equivalent. Compare grouped publication against canonical M=1\nGEMM\u002FSwiGLU\u002Fdown replay, not against another unproven grouped shortcut.\n\nPrioritize these paths:\n\n- Quantized GEMV\u002FGEMM for every M through the configured verifier capacity and\n  all Q, K, and IQ codebook families.\n- Fused gate\u002Fup and fused SwiGLU\u002Fdown.\n- LM head target\u002Fbonus rows without unnecessary all-position rows.\n- Attention verifier rows.\n- GDN recurrence\u002Fprojection and short-conv rows.\n- MoE routed experts and shared expert paths, but never fuse routed\u002Fshared\n  logic unless strict parity proves it.\n\nDispatch policy must be trained\u002Fgenerated, not hand hardcoded:\n\n- Sweep representative formats and M values.\n- Train\u002Fselect by codebook family, M, aspect ratio, and work-size buckets.\n- Use exact shape winners only as overlays above the generic policy.\n- Validate generated includes before installing them.\n- Keep CPU, CUDA, and ROCm trainer behavior comparable through the common\n  observation schema, exact oracle, learner, and certification gates.\n\nFor CPU, build ISA and effective runtime ISA are separate policy dimensions.\nTrain all three supported regimes: AVX2 build\u002FAVX2 runtime, AVX512 build\u002Fforced\nAVX2 runtime, and AVX512 build\u002FAVX512 runtime. Thread count is also part of the\nruntime key. Never train only the native ISA of the build and assume forced\nruntime dispatch has identical economics. Keep oneDNN artifacts isolated in\n`external\u002Fonednn\u002Fbuild-avx2` and `external\u002Fonednn\u002Fbuild-avx512` so configuring\none build cannot rewrite the dependency used by the other.\n\nThe canonical CPU production refresh is:\n\n```bash\nscripts\u002Frefresh_native_vnni_dispatch_tables.sh \\\n  --backend cpu \\\n  --profile all \\\n  --cpu-threads 28 \\\n  --cpu-measurement-lanes 2 \\\n  --cpu-avx2-sweep-bin build_v2_release\u002Ftests\u002Fv2\u002Fv2_perf_cpu_native_vnni_gemv \\\n  --cpu-avx512-sweep-bin build_v2_release_avx512\u002Ftests\u002Fv2\u002Fv2_perf_cpu_native_vnni_gemv \\\n  --output-dir benchmark_results\u002Fnative_vnni_dispatch\u002F\u003Crun-id> \\\n  --install\n```\n\nUse the physical cores per socket for `--cpu-threads` and the physical socket\ncount for `--cpu-measurement-lanes` on the blessed training host. The wrapper\nassigns distinct even\u002Fodd shape shards to MPI ranks mapped one per socket and\nruns the AVX512 binary twice with distinct runtime dispatch,\nrequires the complete ISA matrix, and permits `--install` only for a production\nQwen 3.6\u002Fall-shape profile. Retain the aggregate CSV, timing sidecar, common\nobservation CSV, generated include, and summary from every production run.\nAlso retain the profiler request\u002Fevidence manifests, authenticated\n`*_profiler_features.csv`, and raw artifact directory; they are bound to the\nobservation and timing-sample digests and cannot be regenerated from a\ndifferent run.\n\nAfter a CPU refresh, rebuild both binaries and run these gates:\n\n```bash\ncmake --build build_v2_release --parallel --target v2_perf_cpu_native_vnni_gemv\ncmake --build build_v2_release_avx512 --parallel --target v2_perf_cpu_native_vnni_gemv\ncmake --build build_v2_integration --parallel --target v2_integration_cpu_native_vnni_gemv\nctest --test-dir build_v2_integration -R \"^V2_Integration_CPUNativeVNNIVerifierISAResolver$\" --output-on-failure\nctest --test-dir build_v2_integration -R \"^V2_Integration_GroupedVerifierRows_CPU_AllFormats$\" --output-on-failure\nctest --test-dir build_v2_integration -R \"^V2_Integration_CPUNativeVNNI_GEMV$\" --output-on-failure\n```\n\nThe ISA resolver gate must validate production route counters for build ISA,\neffective runtime ISA, thread count, and selected grouped policy. Missing\ncertification is a hard failure; do not add a Pairwise or serial-row fallback.\nThe strong CPU trainer also executes a two-projection fused descriptor bundle\ntwice in every format\u002FM cell. It requires serial-row byte equality, repeat byte\nequality, and the `cpu_native_vnni_fused_verifier_rows_projection_launch`\ncounter with a two-row AVX2 or four-row AVX512 physical K-part tile. This proof\nmust remain enabled in all three CPU regimes; a byte-equal trainer candidate\nalone does not prove the production fused scheduler is economical.\n\nIf user asks whether to tune a single known model shape, do the experiment, but\nconvert any durable result into the general training pipeline before landing it.\n\n## State Ownership And Coherence\n\nMost serious MTP bugs come from split host\u002Fdevice ownership. Prefer device-owned\nlive state:\n\n- KV and shifted MTP KV publication\u002Ftruncation should be explicit and atomic.\n- GDN recurrence and short-conv state should publish accepted rows from device\n  speculative slots.\n- Host mirrors may observe state for logging\u002Ftests, but must not be the source\n  of truth for the hot path.\n- Reset APIs must say whether they clear session state, graph captures, prefix\n  cache, KV\u002FGDN live state, MTP sidecar state, or benchmark-only scratch.\n- Request reuse and `clearCache()` need dedicated regression tests.\n\nWhen fixing coherence bugs, add a test that proves continuation after publication,\nnot just immediate logits.\n\n## Sampling And Stochastic MTP\n\nStochastic support must be production-grade:\n\n- CPU, CUDA, and ROCm samplers should share the same math contract.\n- Temperature-zero greedy must still honor penalties and other applicable\n  sampling parameters.\n- GPU stochastic sampling should be device-resident and graph-capturable where\n  possible.\n- The verifier should avoid host token uploads in the hot path. Host-visible\n  tokens are outputs, not the next-step source of truth.\n- Qwen chat thinking-budget phrase injection must be honored; forcing only a\n  stop token is not sufficient.\n\nTest sampler parity on synthetic hard rows and real Qwen3.6 logits. Tie-breaking\nmust be deterministic and documented.\n\n## Dynamic MTP Depth Controller\n\nThe dynamic controller is a policy layer over fixed-depth economics. Do not tune\nit until fixed d1\u002Fd2\u002Fd3 lanes are healthy.\n\nMaintain or generate controller policy from real data:\n\n- Include short repetitive prompts, long prompts, code-generation prompts, and\n  default benchmark prompts.\n- Compare dynamic against fixed d1, d2, and d3 for each backend\u002Fmodel.\n- Dynamic should asymptotically approach the best fixed depth for a prompt class.\n- If backend preferences differ, first rule out math\u002Fparity drift; then explain\n  the performance reason in the dashboard.\n- Keep generated policy files reproducible and tied to holdout data. Avoid\n  one-off hand tuning.\n\n## Multi-Device Lanes\n\nTrack these modes in the dashboard even when implementation is pending:\n\n- SingleDevice CPU\u002FCUDA\u002FROCm.\n- LocalTP CUDA deg2, ROCm deg2, ROCm deg4.\n- LocalPP CUDA\u002FROCm.\n- NodeTP CPU sockets.\n- ExpertOverlay cases such as GPU hot plus CPU cold and mixed CUDA\u002FROCm\u002FCPU.\n\nMulti-device MTP must use common-prefix\u002Fcommon-accepted-count coordination.\nEvery participant enters collectives in the same order. Participants with no\nwork no-op through the same graph\u002Fcollective sequence.\n\n## Commit And Iteration Discipline\n\nFor each slice:\n\n1. State the targeted bottleneck or correctness bug.\n2. Add or update a regression test before or with the fix.\n3. Run focused tests for the touched path.\n4. Run the relevant MTP\u002Fprefix parity and perf gates.\n5. Update the plan and dashboard.\n6. Before a non-WiP commit, run the broader unit gate requested by the project\n   plan or precommit hook and fix failures rather than bypassing them.\n\nWhen a test sweep is large, resume from the last failure while iterating, then\nrun front-to-back once every listed test has passed at least once.\n",{"name":5,"description":7},"master","454741b1b2228bc6874e46ade75bbf523a8385d5",".agents\u002Fmtp-tuning",4,"https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar","https:\u002F\u002Fllaminar.ai","https:\u002F\u002Fgithub.com\u002FLlaminar","Home of the Llaminar inferencing engine.","2026-11-15 04:04:16",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add Llaminar\u002Fllaminar --skill mtp-tuning",{"tool":58,"command":59},"bunx","bunx skills add Llaminar\u002Fllaminar --skill mtp-tuning",{"tool":61,"command":62},"pnpm","pnpm dlx skills add Llaminar\u002Fllaminar --skill mtp-tuning","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.agents\u002Fmtp-tuning\u002FSKILL.md",true,[66],{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},"agents\u002Fopenai.yaml","REFERENCE","参考文档",209,"https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.agents\u002Fmtp-tuning\u002Fagents\u002Fopenai.yaml",[73,81,86,96,103,108],{"skillNo":74,"name":75,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":38},"01M718P9ZZSG781K5PXM1V3KG2","rocm-tuning","https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.codex\u002Fskills\u002Frocm-tuning\u002FSKILL.md",[],[79,20,80],"rocm tuning","rocm",{"skillNo":82,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":38},"01M718P95WX88GYN9MTSC6AE40","https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.codex\u002Fskills\u002Fmtp-tuning\u002FSKILL.md",[],[19,20,18],{"skillNo":87,"name":88,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":38},"01M718P7JK26A3N6VZYSE2J36T","cuda-kernel-profiling","https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.codex\u002Fskills\u002Fcuda-kernel-profiling\u002FSKILL.md",[],[92,93,94,95],"profiling","cuda kernel profiling","cuda","kernel",{"skillNo":97,"name":98,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":38},"01M718P5YCB9J40NZZ0PRAKS5V","cpu-tuning","https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.codex\u002Fskills\u002Fcpu-tuning\u002FSKILL.md",[],[102,25,20],"cpu tuning",{"skillNo":104,"name":75,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":38},"01M718P57PZ4G3X1B24ZVWR2PQ","https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Frocm-tuning\u002FSKILL.md",[],[79,20,80],{"skillNo":109,"name":110,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":38},"01M718P4GF2X3EHBTY7ZB1Q2T2","nativevnni-gemm-tuning","https:\u002F\u002Fgithub.com\u002FLlaminar\u002Fllaminar\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fnativevnni-gemm-tuning\u002FSKILL.md",[],[20,114],"nativevnni gemm tuning"]