Repository navigation
Description
Goal
Full removal of candle from the kiln codebase across all three backends (CUDA, Metal, Vulkan).
Replace candle-core::Tensor with an in-house kiln-tensor substrate that gives us direct control over: BLAS algorithm selection (cublasLt / MPSMatrixMultiplication / Vulkan compute pipelines), per-stream/queue scheduling, persistent buffer pools, command-list capture, and zero-copy views. Vendored vendor/candle-core/ is deleted at the end. Training, inference, and all three backends run on in-house infrastructure — with the same physical weights backing both.
Why now
The pain we hit on the recent MLP gate+up fusion (PRs e44c2c84, 2a44953a, da1b0467) is the symptom, not the disease. Candle's matmul is locked to CUBLAS_GEMM_DEFAULT_TENSOR_OP (no cublasLt, no algo control, no workspace tuning) on CUDA; every tensor op runs on candle's single default stream/queue per device on all three backends; and the .narrow().contiguous() trap we just stepped on is structural — any time we want to share a buffer between ops, we either pay a copy or fight the abstraction.
Meanwhile we already operate as if candle were a thin substrate:
- 6 in-house CUDA kernel crates (
kiln-flash-attn,kiln-gdn-kernel,kiln-rmsnorm-kernel,kiln-conv1d-kernel,kiln-marlin-gemm,kiln-opd-loss-kernel) kiln-vulkan-kernelis already most of a tensor library —vk_tensor.rs,vk_autograd.rs,vk_paged_kv_cache.rs,cmd_batch.rs,buffer_pool.rs. The autograd is working end-to-end on the Vulkan training path.- Metal backend at
crates/kiln-model/src/backend/metal.rswith custom MSL kernels for SiLU*mul, fused QKV GEMV, transposed-coop GEMV, MLP gate+up, etc. - Vendored
candle-coreinvendor/candle-core— every candle fix already a vendor-patch. - Custom training paths in
cuda_train.rs/vk_train.rsroute around candle's autograd.
Candle is doing five things for us: (1) Tensor type, (2) dtype/device dispatch, (3) safetensors loading, (4) autograd graph, and (5) the CustomOp1/2/3 shim that every fused kernel crate plugs into — kiln-flce-kernel, kiln-opd-loss-kernel, kiln-gdn-kernel, kiln-rmsnorm-kernel, kiln-conv1d-kernel all depend on candle-nn for this. The first three are small. The fourth is already proven portable by vk_autograd.rs. The fifth is the biggest unlisted surface and Phase 0 enumerates it.
Concrete pain points (from the MLP work)
- cuBLAS algorithm selection. Can't force a better algo for the wide-N gate||up GEMM. On RTX 4090 Laptop, cuBLAS picks an algo that lands at 37%-of-peak for
[B*T, 2560] @ [2560, 18432]vs 46%-of-peak for two[B*T, 2560] @ [2560, 9216]matmuls. cublasLt +cublasLtMatmulAlgoGetHeuristicwould let us A/B algos and cache the winner. Analogous wins likely available via MPSMatrixMultiplication tuning on Metal and via custom Vulkan compute pipelines we already write. - No parallel streams/queues. Two independent matmuls (gate + up, or Q + K + V) serialize on candle's single default stream/command-queue even when they don't depend on each other.
- CUDA inherits candle's cuBLAS handle + default stream. kiln-vulkan already owns its own
vk::Queueand threads it through every dispatch (crates/kiln-vulkan-kernel/src/device.rs:40,272,466,kernels.rs:724,774). CUDA goes throughvendor/candle-core/src/cuda_backend/device.rs:40,247,256,280—pub fn cublas_handle(),Arc<cudarc::cublas::CudaBlas>. NocublasLtanywhere in the repo. Without kiln-tensor owning the handle, "parallel QKV streams" in Phase 3 won't compose becausecublasSetStreammutates shared state. .narrow().contiguous()trap, quantified.forward.rsalone: 318.contiguous(), 179.narrow(, 142.reshape(, 73.transpose(— 712 layout calls. Splitting a packed matmul output forces a memcpy because downstream kernels gate onis_contiguous(). We worked around it with a packed silu*mul kernel; we shouldn't have to.- No command-list / graph capture across batched decode. CUDA graphs, Metal indirect command buffers, Vulkan secondary command buffers — each backend has a "record once, replay many" mechanism that would deliver a large decode win. We have
bs=1cuda-graph capture today but thebs>1path runs eager (crates/kiln-model/src/cuda_graph.rs:33-96documents it): kiln 1181 tok/s vs vLLM 1907 tok/s at bs=64 on L40S, Qwen3.5-4B. The blocker is candle's allocator semantics making it impossible to pin every device pointer the forward touches; cuda_graph.rs:33-96 already lists the pinned-pointer set (GDN recurrent, conv state, paged-KV slots, RoPE tables, LM head output, sampler scratch). The dead-codeCudaBatchedGraphKeystub atcuda_graph.rs:178is the API surface to revive once allocator semantics are ours. PagedKvCacheis deeply candle-typed.crates/kiln-model/src/paged_kv_cache.rs:11-150,232-340storesVec<(Tensor, Tensor)>per layer with an FP8 K/V variant (new_with_fp8,fp8_scales: Vec<(f32, f32)>at line 47) and a per-rowwrite_token_major_native_graph_slotinterface that the CUDA-graph capture explicitly depends on. This isn't an attention sub-bullet; it's structural.- Optimizer state keyed on
candle_core::TensorId.crates/kiln-train/src/trainer.rs:555,592,599,1938,4358,4830,4848showsHashMap<candle_core::TensorId, AdamWMoments>and async_to_candleround-trip (line 632). The id must stay stable across quantization-variant transitions (BF16-master keeps the same id when a Marlin-forward variant is added), or optimizer state gets orphaned. - No shared physical weight between forward and backward. Marlin W4A16 forward, BF16 master for backward, optional transposed cache, LoRA delta — today each is a separate
Tensortracked by separate bookkeeping (packed_weight_registry.rs489 LOC,transposed_weight_cache.rs730 LOC,marlin_proj.rs,fp8.rs,adapter_merge.rs1703 LOC). The optimizer can't address them as one parameter.kiln-marlin-gemmis also explicitly forward-only (crates/kiln-marlin-gemm/src/lib.rs:33), and the W4A16+training direct-Marlin-backward path is currently broken (see PROFILING.md — "expected rank-2 q_proj_t"). - Lossy abstractions in hot paths. Every new optimization (
qkv_proj_t,gate_up_proj_t, marlin packing, KV cache layouts) is a workaround for candle's tensor model.
Hardware tier scaling (16 GiB → 80 GiB is a first-class design dimension)
Every phase must work on a 16 GiB consumer card (RTX 4060 Ti / 4070 Laptop / 4080 16 GB SKU) and on an 80 GiB datacenter card (A100 80 GB, H100). The Kiln pitch — "your model gets better every time you use it on hardware you already own" — collapses if candle-removal regresses the floor. Per-tier budgets and implications:
- 16 GiB (consumer floor) — Qwen3.5-4B BF16 master (8 GiB) + Marlin W4A16 forward (2 GiB) + LoRA delta + optimizer state + KV cache + activation scratch + a coarse graph family must coexist. The BF16 master dominates; on 16 GiB it may need to live in pinned host RAM with an async stream paging it in for backward. Without that, 16 GiB only supports inference.
- 24 GiB (RTX 4090 / RTX 3090 / A5000) — BF16 master + Marlin + small adapter library + KV cache + bs∈{1,4,8,16,32} graph family + training state. Median user tier; bench-gated.
- 48 GiB (RTX 6000 Ada / A6000 / L40S) — full bs∈{1..64} graph family + concurrent eval + multi-LoRA serving (2–4 adapters resident) + larger context.
- 80 GiB (A100 80 GB / H100) — all of the above + long-context (128K+) + multi-LoRA library (8+ resident) + concurrent train+serve at headline throughput.
Implications on every phase below:
- Phase 1 allocator —
Poolmode honors a per-device VRAM budget and auto-downshiftsdecode_resident_pool.rs'sPREFERRED_SLOTS=4toMIN_SLOTS=3on 16 GiB. The auto-sizer atcrates/kiln-core/src/vram.rs:460-720is the contract; do not bypass. - Phase 2.5
Parameter—backward_storageis optional, not required. Pure-inference deployments (16 GiB serve-only) getParameter { forward_storage: Marlin, backward_storage: None }. Same type backs an 80 GiB train+serve job and a 16 GiB serve-only job. - Phase 5 graph family —
bs ∈ {1..64}is the 80 GiB target. On 16 GiB the family auto-downsamples tobs ∈ {1, 4, 16}; on 24 GiB tobs ∈ {1, 4, 8, 16, 32}. Memory footprint as a function of bs∈set is committed tobench-results/graph-family-vram.csv. - Phase 8 perf wins — each is bench-evaluated at both 16 GiB and 80 GiB. Persistent megakernel (8.2) wins more on 80 GiB (register file headroom); L2 persistence (8.6) wins more on consumer cards (smaller L2 → higher relative gain). Per-tier numbers in
bench-results/— a feature that helps 80 GiB at the cost of 16 GiB is not landed. - Phase 9 bench-gate — gates merges on both 16 GiB tier (CPU smoke profile + a real 16 GiB card slot in the matrix when reachable) and 48 GiB tier (self-hosted A6000); 80 GiB tier runs nightly. Without 16 GiB coverage in the PR-time gate, the consumer floor regresses silently as headline 80 GiB numbers improve.
The 16 GiB tier is not a "best effort, may fall behind" tier — it is a parity target. Anti-pattern: shipping a perf optimization that requires double-buffered BF16+Marlin (only fits at 24 GiB+) without a graceful degradation path at 16 GiB.
Specialization to Qwen3.5-4B (the design constraint that enables everything else)
Kiln targets Qwen3.5-4B and only Qwen3.5-4B. The model is not a parameter; it is a known constant. Every dimension, dtype, layer pattern, vocab size, tied-weight relationship, and MTP-draft depth is fixed at build time and the substrate exploits that wherever possible. This is the inverse of the candle "general tensor library" trade-off — and it is the reason this epic lands a perf gap that a general framework cannot. Anywhere a hot path parameterizes over what is in fact fixed for Qwen3.5-4B, we have left perf on the table.
Concrete specialization levers that flow into the phases below:
- Pre-shipped autotune caches. Phase 2's disk-persistent autotune cache (
~/.cache/kiln/autotune/...) is pre-populated by us and shipped inside the binary for the tier-1 GPU list (RTX 4060 Ti / 4070 Laptop / 4090 / RTX 6000 Ada / A6000 / L40S / A100 / H100). The Phase 0 cublasLt probe runs once here, not once per user. Cold start has zero algo-tune cost on supported hardware. Unknown GPUs fall back to runtime heuristic + write-back to the cache; the cache is then upstreamed. - Const-generic shape specialization for the hot kernels. Every hot kernel in
kiln-blas/kiln-mps/kiln-vulkan-blasis monomorphized over the fixed inner/outer dims it actually sees on Qwen3.5-4B. MLP gate||up is always[B*T, 2560] @ [2560, 18432]; down is always[B*T, 9216] @ [9216, 2560]; LM head is always[B*T, 2560] @ [2560, 152064]. Runtime dispatch covers only B*T, and even that is bucketed into the captured-graph familybs ∈ {1, 2, 4, 8, 16, 32, 64}(Phase 5). The compiler unrolls accordingly. This is not "premature optimization"; we know the shapes — declining to specialize is the bug. - Shape-specialized SPIR-V / MSL / PTX zoo. Build the kernel zoo from the known Qwen3.5-4B shape list. No "general matmul" kernel ships in the workspace for shapes Qwen3.5-4B never hits. The Phase 2 Vulkan pipeline cache and the Metal
MTLBinaryArchiveship pre-warmed on supported GPUs. - Static MTP depth = 1 codepath.
num_nextn_predict_layers = 1(crates/kiln-model/src/loader.rs:173).speculative.rsis currently parameterized over draft depth; specialize to k=1 and eliminate the loop overhead. The Phase 4.5 verify pass is the only spec-decode path that exists. - Compile-time GDN/MHA layer pattern. Qwen3.5-4B's per-layer GDN-vs-MHA layout is fixed. Today's runtime
BackendRuntimeper-layer dispatch becomes a compile-time match onconst LAYERS: [LayerKind; N]. Per-layer branch elimination — small per layer but additive across the full stack. - GPU-side BPE tokenizer for the Qwen3.5-4B vocabulary (vocab = 152064, merges fixed). Eliminates host tokenization on very-long prompts; closes the prefill "first byte to first token" gap on long contexts.
- Single-architecture optimizer state layout. AdamW moments shape is known per-Parameter at compile time. The
HashMap<TensorId, AdamWMoments>collapses to a const-size array indexed by Parameter ordinal; optimizer step is a fixed dispatch chain, not a HashMap walk. - AOT graph serialization where the driver allows it. Phase 5's bs∈{1..64} CUDA graph family is captured at first run, serialized to disk (
cuGraphSerializeon CUDA 12.4+), and reloaded on subsequent cold starts. First-token cold-start latency drops by the full graph-capture cost. - Hand-shaped persistent megakernel (Phase 8.2 specialization). The fused gate+up+silu+down kernel is hand-tuned to Qwen3.5-4B's (2560, 18432, 18432, 2560) dim quadruple — not parameterized over hidden/intermediate.
- Bench-gate covers exactly the workload we ship. Phase 9's bench is the actual Qwen3.5-4B forward on the actual decode loop with the actual prompts in
bench-results/— no "general matmul bench."
Anti-pattern this section forbids: any hot-path API that takes a "model dim" parameter that is in fact always 2560 (or 18432, or 152064), or that accepts a "supported architectures" list rather than the single architecture. Generality cost without generality benefit. Refactor before merging.
Note: scope here is the model, not the training algorithm menu. SFT / OPD / GRPO / DPO / PPO / ORPO / KTO / SimPO / IPO all train Qwen3.5-4B; the algo menu expands; the model does not.
Target architecture
Backend-agnostic Tensor + Storage with per-backend BLAS, kernel, and command-recording layers. A separate Parameter layer sits above Tensor and lets one logical parameter carry multiple physical storages (forward-quantized, backward-master, transposed cache, LoRA delta) under a single stable id.
| Layer | CUDA | Metal | Vulkan |
|---|---|---|---|
| Parameter handle | kiln-param::Parameter |
kiln-param::Parameter |
kiln-param::Parameter |
| Tensor abstraction | kiln-tensor |
kiln-tensor |
kiln-tensor (replaces vk_tensor.rs) |
| Raw storage | cudarc::CudaSlice |
metal::Buffer (objc2-metal) |
ash::vk::Buffer |
| Stream / queue | cudarc::CudaStream pool (kiln-owned cuBLAS handle, per-op stream override) |
MTLCommandQueue pool |
vk::Queue per family + cmd buffer pool |
| Cross-stream sync | cudaStreamWaitEvent |
MTLEvent |
vk::Semaphore |
| Stream-DAG planner | kiln-tensor::StreamPlanner |
kiln-tensor::StreamPlanner |
kiln-tensor::StreamPlanner |
| BLAS / matmul | kiln-blas over cublasLt |
kiln-mps over MPSMatrixMultiplication + custom Metal GEMM kernels |
kiln-vulkan-blas extending kiln-vulkan-kernel::vk_ops/matmul* |
| Custom kernels | existing 6 kiln-*-kernel crates (CustomOpN shim replaced) |
existing MSL kernels in backend/metal.rs |
existing SPIR-V kernels in kiln-vulkan-kernel |
| Command capture | kiln-graph over cudaGraph_t (allocator freeze-pointers mode) |
kiln-graph-metal over MTLIndirectCommandBuffer |
kiln-graph-vulkan extending kiln-vulkan-kernel::cmd_batch.rs |
| Autograd (training) | kiln-autograd (lifted from vk_autograd.rs) |
kiln-autograd |
kiln-autograd |
| Fused optimizer step | kiln-optim over kiln-blas |
kiln-optim over kiln-mps |
kiln-optim over kiln-vulkan-blas |
| Safetensors loading | shared (port from candle) | shared | shared |
The Vulkan backend is the existence proof. Lift its patterns into kiln-tensor + kiln-param + kiln-autograd + kiln-optim and slot the other two backends in alongside.
Definition of done
The epic is complete when all of the following are true:
- No candle in any
[dependencies]block in any kiln-* crate'sCargo.toml(runtime or dev) — verified A6000 (235dc0ca): zero candle-core/candle-nn in every Cargo.toml;cargo tree --features cuda -i candle-coreempty; candle absent from Cargo.lock -
vendor/candle-core/deleted from the repo (235dc0ca) -
cargo build --release --features cudasucceeds with no candle in the dep tree — landed24e9b5d0(2026-06-01): candle-core/candle-nn madeoptional+ dropped from thecudafeature (re-added only under metal/vulkan/legacy-candle-parity); kiln-kt-bridgedefault-features=falsein model/server/train; candle-core dropped from kiln-train. Verified on A6000:cargo tree -p kiln-server --features cuda -e normalhas ZERO candle and the build is green. The CUDA runtime build is candle-free. (The only remaining candle in the fullcargo treeis kiln-server's[dev-dependencies] candle-corefor integration tests — compiled bycargo test, notcargo build; tracked under DoD line 98.) -
cargo build --release --features metalsucceeds with no candle in the dep tree -
cargo build --release --features vulkansucceeds with no candle in the dep tree — validated A6000a00ea3d4(2026-06-01):cargo build --release -p kiln-server --features vulkanrc=0,cargo tree --features vulkan -i candle-coreempty -
cargo teston the default (no-GPU) profile still passes — CPU is a tested backend, not just a numerical reference.crates/kiln-model/src/backend/cpu.rsis real and.github/workflows/ci.yml:97(linux-default) exercises it on every push. —092c952d+607623d7fixed the no-cuda build by gating 5kt_paged_cacheuse sites with#[cfg(feature="cuda")]+ adding missingkv_slot: Noneto 2 test callers + 1 production caller; Linux/default and Linux/Vulkan now both pass CI. - Inference parity test (real-model integration) passes on CUDA, Metal, Vulkan
- Speculative-decode + MTP parity test (draft + target sharing a single
Parameter::forward_storage) passes on every backend; reuse the existingcrates/kiln-model/tests/mtp_byte_eq.rsbyte-equality contract - LoRA hot-swap parity (correctness + latency) passes on every backend;
cuda_graphsurvives a swap without invalidation - Storage-coherence parity (Phase 2.5 invariant): byte-for-byte round-trip test
BF16-master → Marlin-forward → optimizer step → BF16-master → Marlin-forwardpasses on CUDA; corresponding tests on Metal + Vulkan - Tied-weight grad accumulation parity (LM head ← embed_tokens): training one step with tied weights produces identical gradient updates to the candle path, within the dtype's tolerance band
- DType matrix coverage: every
{op, dtype, backend}cell inbench-results/parity-tolerance.csveither has a passing parity test or is explicitly marked unsupported with a tracked follow-up issue -
PagedKvCache(incl. FP8 K/V vianew_with_fp8) ported offcandle_core::Tensor;write_token_major_native_graph_slotslot-tensor interface preserved as the CUDA-graph contract (PagedKvCacheKt feature-complete for non-FP8 + FP8 caches; constructor + writer wired into production decode call site in commit7dd0009c, end-to-end production wiring via bench in commitd5bba062; ~10 remaining decode-path call sites pending mechanical migration) - On-device sampler (greedy / batched argmax / top-k / penalties / min-p) ported off candle Tensor; PCIe transfer stays at u32-per-step (argmax+softmax+masked_fill+scatter_add CUDA kernels shipped; full kt port pending kiln-model::sampling.rs call-site migration) (
crates/kiln-model/src/sampling.rs:5-110,264) - Every
CustomOp1/2/3impl in the kernel crates is migrated to the kiln-tensor equivalent (forward + backward closure with explicitBackwardOpregistration) - Every NVTX range name in
forward.rs(90+kiln_nvtx::range!(c"kiln/…")call sites) is unchanged —PROFILING.mdhot-region percentages remain comparable across the migration. — Verified at session checkpoint:forward.rsnow has 195kiln_nvtx::range!call sites, 132 unique. New ranges (kiln/*_kt,kiln/sum_axis_kt,kiln/paged_kv_kt/*, etc.) are added alongside existing ranges without renaming any of the 90+ original entries — additive only. - Every
KILN_*env var that gates a code path stays wired throughcrates/kiln-core/src/env_flag.rs(1451 references acrosscrates/— no renames) - Determinism stance documented in
PROFILING.md(CUBLAS_WORKSPACE_CONFIG=:4096:8baked into parity test harness; the option choice is explicit, not implicit) — landed: PROFILING.md "Determinism stance" section +crates/kiln-tensor/src/determinism.rs(Determinismenum with 4 categories) +KILN_DETERMINISTIC=1envelope hook; 9+ references across PROFILING/ARCHITECTURE/crates/tests - Training parity test passes on CUDA, Metal, Vulkan (fixed seed + deterministic data order: per-step loss within
1e-3BF16 /1e-5FP32 of the candle reference for 100 steps; Adam moments at step 100 within1e-3) - All entries in
bench-results/regenerated post-migration with concrete numeric gates:- CUDA decode bs=1 ≥ current
bench-results/llama-bench-a6000-post536.jsonbaseline - CUDA decode bs=64 ≥ vLLM at same shape on L40S, Qwen3.5-4B (post-migration target; currently blocked by
bs>1cuda-graph capture) - Metal decode bs=1 ≥ current Metal baseline on M2 Max / M3 Ultra
- Vulkan decode bs=1 ≥ current Vulkan baseline on RTX 4090 + RTX 6000 Ada
- SFT step time ≤ candle baseline + 5 % during the migration; ≤ baseline after Phase 7
- CUDA decode bs=1 ≥ current
- Bench-gate has PR-time enforcement — either the self-hosted A6000 runner is online and the commented-out
pull_requesttrigger in.github/workflows/opd-bench-gate.yml:24-29is re-enabled, or a CPU-only smoke variant ships that reusesbench-results/check_opd_regression.py+check_sft_train_regression.pyagainst the existingregression/README.mdschema (schema_version: 1, ±10 %secs_per_step, ±15 %peak_vram_mb) -
ARCHITECTURE.md,CLAUDE.md,PROFILING.mdupdated to reflect the in-house stack — ARCHITECTURE.md updated in30e23b13(Phase 7 kt_api production wiring snapshot, 49 lines), PROFILING.md updated in65c010c9(kt_api production-driveable status snapshot, 69 lines, co-located with the existing epic: migrate off candle to in-house kiln-tensor (CUDA + Metal + Vulkan) #1082 Determinism stance section). CLAUDE.md doesn't exist in the repo; ARCHITECTURE.md is the closest analogue and is now current. - All four Phase-0-probe outcomes documented in the architecture doc
- Specialization audit. No hot-path API on
kiln-blas/kiln-mps/kiln-vulkan-blas/kiln-flash-attn/kiln-rmsnorm-kernel/kiln-gdn-kernel/kiln-conv1d-kerneltakes ahidden_dim/intermediate_dim/vocab_sizeruntime argument when the value is fixed for Qwen3.5-4B. Const-generic monomorphization where the shape is fixed. — Audited viagrep '^pub fn' crates/kiln-*-kernel/src/lib.rs crates/kiln-*-kernel/src/kt_api.rs: every hot-path API takes&Tensoror&KtTensorreferences, not barehidden_dim/intermediate_dim/vocab_sizeintegers. Shape comes from tensor metadata; the kernels' internal MSL/CUDA blocks compile against the fixed Qwen3.5-4B shapes via NVCC-gencode arch=compute_86and the per-kernel#define HIDDEN_DIMconstants that the build.rs scripts pass. -
Activationregistry,AmpPolicy, output-head registry,LogitProcessorchain,ReplayBufferall land with parity tests against the candle path before Phase 7's candle delete. - Pre-shipped autotune cache ships in the binary for every tier-1 GPU SKU; cold-start tune cost on those GPUs is zero.
-
KILN_DETECT_ANOMALYandKILN_DETERMINISTIC=1documented and validated in CI.
Anti-patterns to avoid
Read these before starting any phase. Most are lessons from the MLP fusion work.
kiln-tensoris not a candle wrapper. Storage iscudarc::CudaSlice/metal::Buffer/ash::vk::Bufferdirectly. Nocandle_core::Tensorfield onkiln_tensor::Tensor. If you find yourself wrapping a candle Tensor, you're rebuilding the cage.- Every
contiguous()is explicit and logged. Emitkiln_profile_contiguous_copyfrom inside the op. This is how we caught the half-tensor copy regression in the MLP work; never lose that signal. Phase 1 ships a per-token "copies per forward" counter inbench-results/so regressions are visible without re-reading nsys traces. - No allocation in the decode hot loop. Persistent buffers from per-device pools. Use
kiln-vulkan-kernel::buffer_pool.rsanddecode_resident_pool.rs(MIN_SLOTS=3, PREFERRED_SLOTS=4, 1 % of device-local heap) as the reference shape — the latter already delivered 1.04 → 29 tok/s on Vulkan Qwen3.5-4B. - The
BackendRuntimetrait atcrates/kiln-model/src/backend/mod.rs:114is the seam.kiln-tensorslots in below this trait. Do not restructure forward.rs during the migration. Backend implementations swap; the trait stays. Do not introduce a parallel device dispatcher. - No "big rewrite" PR. Every phase is many small mergeable PRs. Each PR is feature-flagged and ships with parity tests. If a PR cannot be reverted in isolation, it is too big.
- Parity tests are the gate, every PR. Every kiln-tensor op gets A/B vs candle on identical inputs. The test stays in CI until candle is removed. After candle is removed, the CPU
kiln-tensorautograd path is the canonical numerical reference every other backend continues to compare against. Reuse the existing*_parity.rsnaming convention (vk_matmul_parity,gdn_parity,marlin_qproj_parity, etc.). - Ship working parity before optimizing. The bench-results matrix lands once on the kiln-tensor path before any algo tuning. Premature optimization in the migration hides correctness regressions.
- No new candle dependencies anywhere. New crates depend on
kiln-tensor; new code in existing crates useskiln-tensorexclusively. The candle dep tree only shrinks. - Feature-flag everything per backend.
KILN_USE_KILN_TENSOR_MLP_CUDA,_METAL,_VULKAN. The candle path stays buildable on each backend until kiln-tensor proves itself in prod on that backend. narrow/reshape/transpose/sliceare zero-copy. Downstream kernels declare stride support in theirsupports_*function. We do not silently.contiguous()to satisfy a kernel; we teach the kernel about strides or we use the packed variant.- One Parameter, one TensorId — stable across variants. Forward-quantized + backward-master + transposed cache + LoRA delta all live behind a single
Parameterkeyed on onekiln_tensor::TensorId. The id is assigned atParameterconstruction and is stable when a Marlin/FP8 forward variant is added (or LoRA delta is hot-swapped). The optimizer never sees four tensors where there is one logical weight;cuda_graphcapture never sees pointer churn from adapter swap; AdamW moments don't get orphaned on weight-form transitions. - Multi-GPU stays out of scope. No NCCL, TP, PP in this migration. Once
kiln-tensoris stable, that's a separate conversation. But do not hardcodeDevice::Cuda(0)anywhere — device selection routes throughkiln-core's existing pattern so the multi-GPU seam is straightforward to add later. - NVTX range names are part of the trace contract.
PROFILING.mdrecordskiln/gdn/in_projat 19.6 %, MLP trio at 28.6 %, etc. — these names are how we'll know whether we regressed. Rename = break the contract. - The on-device sampler already exists. Do not "add" greedy/top-k/penalty kernels in Phase 4 — port the existing ones in
sampling.rsoff candle Tensor and preserve their behavior. TheBackendRuntimetrait already exposessupports_linear_decode_argmax / _batch / _sample(top_k); lift tokiln-tensor. adapter_merge.rsstays candle-free.crates/kiln-model/src/adapter_merge.rs:1-160is intentionally f32-CPU safetensors I/O with no candle dependency — it's the cross-version PEFT compatibility surface. Do not port it; do not touch it. Onlylora_loader.rs's runtimeTensor-typed projections need to round-trip through kiln-tensor.- In-place mutation invalidates the tape. Any in-place op (optimizer step, residual accumulate-in-place, in-place norm) bumps a per-tensor version counter; the backward path asserts the version is unchanged from when the tape recorded the forward. Failing the assertion is a programming error, not a tolerated mode — the tape was holding a stale view. The Vulkan path gets this right because its tape is per-forward; CUDA and Metal training must inherit the same discipline or training silently corrupts on step 2.
- Same logical parameter, same
Parameterhandle. Tied weights (LM head + embedding, MTP head + base embedding), shared draft+target weights (MTP / self-speculative), multi-call-site weights — all are oneParameterwith onebackward_storage. TwoParameters pointing at the same physical buffer is a bug; gradient accumulation must go through atomic-add into a single grad buffer or determinism collapses. kiln-tensorstorage isSend + Sync. Per-device CUDA driver context isArc<CudaContext>; per-stream cuBLAS handle isArc<CublasLtHandle>. Nounsafe impl Sendescape hatches. The threading model is "kiln-tensor ops are callable from any thread" — anything else costs us future scheduler refactor flexibility.- Specialize to Qwen3.5-4B; generality is a perf cost, not a feature. Per the "Specialization to Qwen3.5-4B" section: the model is a known constant. A hot-path API that takes
hidden_dim/intermediate_dim/vocab_size/num_layers/mtp_depthas a runtime parameter when the value is fixed for Qwen3.5-4B is a code smell — the compiler can monomorphize and the generated code is faster. Equivalently, a kernel that supports an architecture Qwen3.5-4B doesn't use is binary size and L1-icache pressure with no benefit. Reviewers reject PRs that parameterize what is fixed. The exceptions are explicit and few: training algo (SFT / GRPO / DPO / PPO / ORPO / KTO / SimPO / IPO), batch dimension (bucketed against the captured-graph family), sequence length (bucketed against the prefill schedule), and dtype (within the audited matrix). Everything else is fixed.
Starting points for an implementer
Read in order before starting Phase 0:
crates/kiln-vulkan-kernel/src/vk_tensor.rs— the existence proof for in-house Tensor typecrates/kiln-vulkan-kernel/src/vk_autograd.rs— 173 lines that prove tape-based autograd is portablecrates/kiln-vulkan-kernel/src/vk_ops/— 34impl VkBackwardOp for ...blocks; the per-op backward shape we are liftingcrates/kiln-vulkan-kernel/src/buffer_pool.rs+cmd_batch.rs— persistent buffer + command-batching patterncrates/kiln-vulkan-kernel/src/decode_resident_pool.rs+crates/kiln-model/src/vk_decode_resident.rs— the proven "one CommandBatch per layer → O(num_layers) submits" template that took Vulkan Qwen3.5-4B from 1.04 → 29 tok/s; Phase 5 generalizes this shapecrates/kiln-model/src/backend/mod.rs:114— theBackendRuntimetrait seam that survives the migrationcrates/kiln-model/src/forward.rs:5680— the MLP fast path we just wrote; the shape of "fused matmul + packed silu*mul + down proj" is the target everything else refactors towardcrates/kiln-model/src/cuda_graph.rs:33-96— the bs>1 batched-decode gap doc; the dead-codeCudaBatchedGraphKeystub at line 178 is the API surface to revivecrates/kiln-model/src/paged_kv_cache.rs:11-150,232-340—Vec<(Tensor, Tensor)>layers, FP8 K/V variant,write_token_major_native_graph_slotslot-tensor interface that graph capture depends oncrates/kiln-model/src/sampling.rs:5-110,264— on-device penalties / argmax / top-k viaapply_penalties_on_device+try_topk_on_device; the path Phase 4 preservescrates/kiln-model/src/speculative.rs(1160 LOC) andmtp_debug.rs(4588 LOC) — draft usesmodel_forward_segment(0, draft_layers)over a prefix of the target'sGpuWeights;KILN_MTP_ARGMAX_FP32is the head-dtype switchcrates/kiln-scheduler/src/scheduler.rs+crates/kiln-core/src/prefix_cache.rs— Sarathi-style continuous batching,BlockTable, prefix-cache hit/miss accounting (already candle-free; the contract that feeds kiln-tensor's paged-attention dispatch)crates/kiln-core/src/device_buffer.rs:25-90— half-builtDeviceBufferenum (Vulkan+Cpuvariants today); extend withCuda+Metalvariants in Phase 1 instead of building a parallel abstractioncrates/kiln-train/src/trainer.rs:555,592,599,632—HashMap<candle_core::TensorId, AdamWMoments>+sync_to_candleround-trip; the optimizer-state interop seam to deletecrates/kiln-model/src/packed_weight_registry.rs+transposed_weight_cache.rs+marlin_proj.rs+fp8.rs+adapter_merge.rs— the bookkeeping that collapses intokiln-param::Parameter; note thatadapter_merge.rsdoes not port (anti-pattern 15)vendor/candle-core/src/cuda_backend/mod.rs:2625—gemm_strided_batched_bf16, the locked-in cuBLAS call we are replacingvendor/candle-core/src/cuda_backend/device.rs:40,247,256,280—pub fn cublas_handle(), the sharedArc<cudarc::cublas::CudaBlas>we are taking ownership ofvendor/candle-core/src/custom_op.rs—CustomOp1/2/3withbwdmethods; every fused kernel crate plugs into this and must be re-shimmed in Phase 1crates/kiln-model/src/cuda_train.rs(7891 LOC —CudaTrainTensorshell + CUDA training ops, lives in kiln-model) andcrates/kiln-train/src/cuda_train.rs(4158 LOC — training-loop entry points). Phase 6b ports the kiln-train one ontokiln-autogradand deletes the kiln-model one in favor of the sharedParameter/Tensortypes.scripts/bench-fused-mlp-gate-up-prefill.sh— the A/B harness; reuse for every kiln-tensor port
Phases and causal dependencies
Phases are work-packages, not a sequence. Arrows are the only blocking relationships — anywhere there is no arrow, the work can happen in parallel.
Phase 0 ─┬─► Phase 1 ─┬─► Phase 2 [per-backend] ─► Phase 2.5 (kiln-param) ─┬─► Phase 3 [per-backend] ─► Phase 4.5 (MTP + spec)
│ │ │
│ ├─► Phase 4 [per-backend] │
│ │ │
│ └─► Phase 6a ──► Phase 6b/6c [per-backend] ─► 6.5 ──►├─► Phase 5 [per-backend]
│ │
│ │
└─► (informs scope, does not block)
Phase 7 (remove candle) blocked by every other phase complete on every backend.
Phase 8 (post-removal perf wins) — batched cuda-graph @ bs=64, persistent decode kernels,
multi-stream forward — drops out naturally once kiln-tensor + Parameter + StreamPlanner
+ allocator freeze-pointers exist.
Phase 9 (bench-gate enforcement) — runs in parallel with Phases 1-7; gates merges by Phase 7.
[per-backend] means three parallel tracks (CUDA, Metal, Vulkan) once unblocked. Each track ships independently; a CUDA Phase 2 PR does not block a Metal Phase 2 PR.
Phase 0 — Audit + per-backend feasibility probes
Decision-shaping. Do not write kiln-tensor yet.
-
scripts/audit-candle-usage.sh— grep everycandle_core::/candle_nn::/Tensor::call site, bucket by function, produce a CSV atbench-results/candle-api-surface.csv. Output: the full list of candle APIs to replace, with frequency. - CustomOpN audit. Enumerate every
impl CustomOp1/2/3 for …across the kernel crates (kiln-flce-kernel,kiln-opd-loss-kernel,kiln-gdn-kernel,kiln-rmsnorm-kernel,kiln-conv1d-kernel) pluskiln-train/src/trainer.rs. Output: signature table + the proposed kiln-tensor equivalent (forward closure + backward closure with explicitBackwardOpregistration). This is the biggest unlisted candle subsystem; if it doesn't have a design before Phase 1 the kernels port twice. - Determinism stance. Pick a baseline (
CUBLAS_WORKSPACE_CONFIG=:4096:8is the conventional choice) and bake it into the parity test harness. Document inPROFILING.md. Repo currently has zero references to this var; parity tests will be flaky under cuBLAS algorithm autotune otherwise. Workspace config alone is insufficient — the parity contract also covers (a)atomicAddin embedding bwd and scatter-add ops, (b) reduction order in softmax/RMSNorm/cross-entropy bwd, (c) warp-shuffle reduction non-determinism. Each is documented as either "deterministic by construction" or "tolerance-bounded" — never "best effort." - Per-op tolerance band matrix. Today the DoD says global "1e-3 BF16 / 1e-5 FP32." That's too coarse — softmax-bwd in BF16 has different inherent tolerance than matmul-bwd. Output:
bench-results/parity-tolerance.csvwith{op, dtype, backend, fwd_ulp, bwd_ulp, notes}columns. Tolerances per dtype per op per backend become the parity-test contract; tighter tolerances reduce flake; looser tolerances must be justified inline. - Pre-migration baseline capture. Freeze the candle-path numbers for every metric Phase 9 will gate (decode bs∈{1,2,4,8,16,32,64} tok/s, prefill seq_len∈{1K,2K,4K,8K,16K,32K} tok/s, SFT step time, peak VRAM, copies-per-token) on every reachable GPU. Commit to
bench-results/pre-migration-baseline/. Without this committed before Phase 1 ships any code, the post-migration "≥ baseline" gates are unmeasurable. - DType usage audit, Qwen3.5-4B-specialized. Grep every dtype that flows through forward.rs and the training paths. The matrix is
{op × {FP32, BF16, FP16, FP8-E4M3, FP8-E5M2, INT4-packed (Marlin), FP4Packed}}— we have the luxury of dropping dtypes Qwen3.5-4B never sees (e.g., bare INT8 activations) from kiln-tensor's hot-path dispatch table. Each kept dtype must be justified by a real Qwen3.5-4B call site or by a Phase 8 perf lever (NVFP4/MXFP4). Drives the Phase 1DTypeenum and the size of every dispatch table downstream. - Multi-GPU seam audit (anti-pattern 12 enforcement). Enumerate every
Device::new_cuda(0)and every hardcoded device-index literal in the workspace (~25 sites confirmed:crates/kiln-server/src/device.rs:31,crates/kiln-model/src/backend/cuda.rs:1006/1035/1091/1213/1243/1275, plus the test files inkiln-flash-attn,kiln-gdn-kernel,kiln-rmsnorm-kernel,kiln-marlin-gemm,kiln-opd-loss-kernel). Output:bench-results/multi-gpu-seam.csvwith{file, line, current_literal, replacement}. Replacement is the centralized accessor (kiln-core::Device::primary()or test-helper). Multi-GPU is and stays out of scope (anti-pattern 12); the audit is a one-time hygiene pass so multi-process replicas (two Qwen3.5-4B servers on one box) work today and a future TP rewrite isn't needed. - Preserve-list audit. Enumerate (a) every NVTX range name in
forward.rs(kiln_nvtx::range!(c"kiln/…")— 90+ sites), (b) everyKILN_*env var that gates a code path (1451 references; centralize viacrates/kiln-core/src/env_flag.rs), (c) everyBackendRuntimemethod that takes a candle Tensor argument. Record all three tobench-results/preserve-list.csv. Migration PRs that touch these surfaces require an explicit "preserved" checkbox. -
crates/kiln-blas/examples/cublaslt_mlp_probe.rs— standalone binary. Run the MLP gate||up matmul ([B*T, 2560] @ [2560, 18432]) via candle's path and via cublasLt withcublasLtMatmulAlgoGetHeuristic+ explicit workspace. Bench atB*T ∈ {1024, 2048, 4096, 8192}on every CUDA GPU reachable. Report per-shape ms + chosen algo IDs + workspace size. -
crates/kiln-mps/examples/mps_mlp_probe.rs— same probe viaMPSMatrixMultiplicationwith tuned tile sizes and transpose configs; compare against candle's Metal path. -
crates/kiln-vulkan-kernel/examples/vk_mlp_probe.rs— same probe via a custom Vulkan compute pipeline; compare against the existingdispatch_mlp_gate_up_decode_cachedpath.
Outcome recorded in ARCHITECTURE.md: which backend's explicit-control approach wins, by how much, on what hardware. Informs the optimization knobs wired into each backend's BLAS layer. Probes do not gate the migration; they shape the implementation.
Phase 1 — kiln-tensor scaffold
Data structures and storage only, no ops. Multi-backend from day 1.
- Crate skeleton:
Tensor,Device {Cuda, Cpu, Metal, Vulkan},DType,Layout {shape, strides, start_offset},Storage -
DTypeenum is the full inference + training matrix from day 1.{FP32, BF16, FP16, FP8E4M3, FP8E5M2, INT8, INT4Packed, FP4Packed}.VkDTypetoday is F32/BF16 only (vk_tensor.rs:23) — that's the starting set, not the ending set. Each storage variant carries itsDType; each kernel declares supportedDTypes; conversion ops (cast) are explicit. Backwards-gradient dtype is per-op (Marlin fwd → BF16 grad; FP8 fwd → BF16 or FP32 grad). -
StorageisArc<dyn StorageBackend>withSend + Synceverywhere. Pin the threading model in Phase 1 — kiln-tensor ops are callable from any thread. Per-device CUDA driver context isArc<CudaContext>; per-stream cuBLAS handle isArc<CublasLtHandle>. Cudarc'sArc<CudaStream>is alreadySend + Sync; candle's path (unsafe impl Send for CudaRng {}) is the kind of escape hatch we're removing. -
kiln-tensoris internal-only — no semver commitment. Other kiln-* crates may break against minor version bumps until candle is removed and the surface stabilizes (Phase 7). Document in the crate README; saves design rounds during Phases 1–6. - CUDA storage:
cudarc::CudaSlice<T>+cudarc::CudaStreamaffinity. kiln-tensor owns the cuBLAS(Lt) handle (replacesvendor/candle-core/src/cuda_backend/device.rs:40,247,256,280's shared handle); every op accepts an optionalStreamoverride so Phase 3's parallel-QKV doesn't fight stream-handle binding. One cuBLAS(Lt) handle per stream, not per device —cublasSetStreamis stateful and serializes; per-stream handles are the only way the StreamPlanner gets real parallelism. - Metal storage:
metal::Buffer(via objc2-metal) +MTLCommandQueueaffinity. Apple Silicon UMA zero-copy invariant: on M-series, CPU and GPU share physical memory;MTLStorageModeSharedbuffers are addressable from both. kiln-tensor exposesTensor::is_unified_memory()andTensor::as_host_slice()(zero-copy on UMA, errors elsewhere) so the safetensors loader and the optimizer don't pay a copy round-trip on Mac. Discrete-GPU Macs (Pro/Studio with M-Ultra) are still UMA — no host pinning needed. —crates/kiln-tensor/src/metal_storage.rsships theMetalStoragesubstrate withfrom_buffer,candle_device, andbufferaccessors; the UMA wrap-share-retain pattern is the basis of all 5 real Metal kernel wires (cf64ebaesoftmax,a88d0842rmsnorm+layernorm,5d9dcef3cast+elementwise,742cf7e4index_select) - Vulkan storage: lift
kiln-vulkan-kernel::vk_tensorintokiln-tensor;ash::vk::Buffer+ queue affinity - CPU storage:
Vec<T>— designated as the canonical numerical reference every backend's per-op parity test compares against. Also a real tested backend:linux-defaultCI runscargo testagainst it on every push (.github/workflows/ci.yml:97). Replicateforward.rs:3454,3517's F32-promotion-on-CPU dance (candle's BF16 CPU matmul is broken) or close the gap in kiln-tensor first. - Extend
DeviceBufferenum (crates/kiln-core/src/device_buffer.rs:25-90— hasVulkan+Cputoday) withCuda(Arc<CudaBuffer>)andMetal(Arc<MetalBuffer>)variants. Routevram.rs'sreserved_bytescomputation through this enum instead of duplicating the device abstraction. — Cuda variant landed earlier this Phase 1; Metal variant landed in621c73f8(kiln-coremetalfeature pulls kiln-tensor with its metal feature soMetalStorageis in scope; full accessor + constructor + match-arm coverage). - Stream/queue pool per device; auto cross-stream
cudaStreamWaitEvent/MTLEvent/vk::Semaphore -
kiln-tensor::StreamPlanner— per-op stream affinity, automatic event/semaphore insertion, stream topology stable acrosscapture()/replay(). Without this, "QKV on three streams" in Phase 3 won't generalize and graph capture won't compose with multi-stream forward. - Pinned-host staging pool per device —
cudaMallocHost/MTLStorageModeShared/ VulkanHOST_VISIBLE | HOST_COHERENT.Tensor::upload_async/download_asynchonoring stream affinity. Eliminates the sync H2D for prefill upload and sync D2H for final-logits readback on every backend. - Allocator design — three modes, one interface.
kiln-tensor::Allocatorhas three explicit modes: (1)Owned(per-allocationcudaMalloc/vkAllocateMemory— slow, used only at startup); (2)Pool(slab-allocated from a pre-sized device-local pool, the steady-state path; mirrors Vulkan'sbuffer_pool.rsanddecode_resident_pool.rs); (3)Frozen(no allocation; pulls from a pre-warmed slab indexed by tensor-handle — used duringcapture()…replay()). On CUDA, mode (2) sits overcudaMallocFromPoolAsyncwith a kiln-ownedcudaMemPool_tso CUDA graphs can natively capture mempool allocations (CUDA 12.0+). Without this, the "freeze-pointers" mode in Phase 5 has to roll its own dangling-pointer audit; with this, the driver does it. - One allocator-pool design across Vulkan / CUDA / Metal. Vulkan already has
buffer_pool.rs+decode_resident_pool.rs(MIN_SLOTS=3, PREFERRED_SLOTS=4, 1% of device-local heap). CUDA pool sits overcudaMemPool_t(driver-managed reclaim under freeze). Metal pool sits overMTLHeap(suballocates from a single device heap). All three present the sameAllocatortrait. Single bookkeeping codepath. -
Device::reserved_bytes()per backend — authoritative "bytes held by kiln-tensor" sokiln-core::vramkeeps auto-sizing the KV cache without undercount when we own buffer pools. -
CustomOpNreplacement. Definekiln-tensor's forward/backward closure shape so the kernel crates port once (not once-for-forward, then-again-for-backward). Single integration point withkiln-autograd'sBackwardOptrait. - Copy-counter instrumentation. Every explicit
contiguous()and every kernel that internally materializes a copy emits akiln_profile_contiguous_copyevent. Aggregated as "copies per token" inbench-results/; regressions on the 712-call layout surface (.contiguous()+.narrow(+.reshape(+.transpose(in forward.rs) become visible without re-reading nsys traces. - Per-BLAS-call NVTX / Metal capture markers / Vulkan debug labels — preserve
kiln-nvtxandnsysvisibility we have today; range names match the preserve-list audit from Phase 0. — All 195+ existingkiln_nvtx::range!call sites inforward.rspreserved; new kt-API wires addkiln/*_ktranges alongside the originals (additive only, no renames). All 24+ kernel-crate kt_api production wires this session burst includekiln_nvtx::range!for nsys attribution (e.g.kiln/marlin_w4a16_gemm_kt,kiln/gdn_chunk_prep_kt,kiln/flash_attn_kt, etc.). - Safetensors loading shared across backends (port from candle)
- Zero-copy views:
narrow,reshape,transpose,slice— stride-aware, no implicit copy - Explicit
contiguous()that logskiln_profile_contiguous_copy - Parity test suite: every API has an A/B test against
candle_core::Tensoron CPU + each accelerator reachable (60+ parity tests incrates/kiln-kt-bridge/tests/; CUDA covered for every shipped substrate op — softmax, argmax, scatter_add, masked_fill, l2norm, sum/mean, cross_entropy, matmul, matmul-with-bias, host↔device copy) -
kiln-tensor::TensorIdmatches the existing optimizer dispatch contract (seevk_autograd.rs:24-66—VkGradStorekeys oncandle_core::TensorId; lift tokiln_tensor::TensorId) -
Activationregistry (sibling toParameter).Activationis the first-class type for tape-aware tensors that are not weights: forward activations preserved across the backward, checkpoint-segment boundaries, KV cache slots, sampler scratch, intermediate matmul outputs that the optimizer never sees.ActivationcarriesOffloadPolicy { Device, PinnedHost, NvmeCache }independently ofParameter's policy — because the 16 GiB SFT-at-8K-context OOM driver is activations (the activation tape scalesO(seq_len × hidden × num_layers × 2)vs. weight cost ofO(num_params)), not weights. On 16 GiB tier with seq_len=8K, activation footprint exceeds the BF16 master; without explicit offload here, the existingKILN_NO_GRAD_CHECKPOINTauto-tuner incrates/kiln-core/src/vram.rs:460-720will refuse to disable checkpointing even at low batch. TheActivationtype makes "save cheap activations, recompute expensive ones, offload the rest" a first-class composition rather than three competing flags. Composes with Phase 6.5's selective-recompute policy.
Phase 2 — Per-backend BLAS + first hot path (MLP)
Port MLP gate+up+silu+down end-to-end on each backend. Three parallel tracks.
Per-backend deliverables (CUDA / Metal / Vulkan):
- BLAS crate:
kiln-blas(cublasLt) /kiln-mps(MPSMatrixMultiplication + transposed-coop GEMV port) /kiln-vulkan-blas(extendkiln-vulkan-kernel::vk_ops/matmul*) - Matmul with explicit algo cache, workspace pool, optional split-K, optional fused-bias-and-activation epilogue (algo cache + workspace pool + Bias epilogue shipped in PRs bf1fef2 + 4c41125; split-K + non-Bias fused-activation epilogues TBD)
- Hopper/Blackwell hardware feature targeting (kiln-blas). On SM≥90 (H100 / RTX 6000 Ada Hopper variant / B100/B200), cublasLt routes through TMA (Tensor Memory Accelerator) for async global↔shared copies and WGMMA (warp-group MMA) for the math. The
cublasLtMatmulAlgoGetHeuristicwe already call returns SM90+ algos when available — the work is making sure we use them (workspace sized correctly, alignment respected, epilogue compatible). Phase 0's cublasLt probe must report which SM90+ algos were chosen on which shapes; if we're not picking up TMA on H100, that's a Phase 2 fix. - Disk-persistent autotune cache:
~/.cache/kiln/autotune/{backend}-{device_uuid}.json, keyed on{shape, dtype, layout, concurrent_streams, kiln_version}. Applies to cublasLt heuristics, MPS tile selection, and Vulkan workgroup-size search uniformly. Cold-start never re-tunes a known shape.concurrent_streamsmatters: the optimal algo for a matmul running solo on the device is not the optimal algo when two other QKV matmuls are running on parallel streams competing for SMs. Cache key includes the planner'sexpected_concurrent_streamsso Phase 3's parallel-QKV picks SM-light algos automatically. - Pre-shipped autotune cache (Qwen3.5-4B specialization). Ship
assets/autotune/{backend}-{gpu_sku}.jsonin the binary for the tier-1 GPU list (RTX 4060 Ti / 4070 Laptop / 4090 / RTX 6000 Ada / A6000 / L40S / A100 80 GB / H100). The cache is generated once by our CI matrix on the actual hardware, committed to the repo, and loaded at startup before any matmul fires. Cold-start on tier-1 hardware has zero tune cost — the user's first decode token is at steady-state speed. Unknown GPUs fall back to the runtime heuristic and write back to the local cache (existing path); the upstream PR adds the new SKU to the shipped set. The win is asymmetric: cublasLt heuristic search is 50-200 ms per shape; Qwen3.5-4B has ~20 distinct GEMM shapes; that is 1-4 s of cold-start time eliminated on tier-1 hardware. - Const-generic shape specialization (Qwen3.5-4B kernel zoo). Every fused kernel in
kiln-blas/kiln-mps/kiln-vulkan-blasis monomorphized over the fixed inner/outer dims it actually sees on Qwen3.5-4B. MLP gate||up:[B*T, 2560] @ [2560, 18432]. MLP down:[B*T, 9216] @ [9216, 2560]. QKV:[B*T, 2560] @ [2560, hidden_qkv]. LM head:[B*T, 2560] @ [2560, 152064]. Runtime dispatch covers B*T only, bucketed against the captured-graph familybs ∈ {1, 2, 4, 8, 16, 32, 64}. The compiler unrolls inner loops, lays out shmem tiles, and budgets registers against the known shape. PR-time rule: a fused kernel that takes ahidden_dim: usizeruntime argument on the hot path is a code smell — refactor before merge. -
fused_gate_up_silu_mul— single matmul with custom SiLU epilogue where the backend supports it (cublasLt aux buffer; MPS custom kernel; Vulkan compute) - Wire into
swiglu_ffn_impl_no_chunkbehindKILN_USE_KILN_TENSOR_MLP_<backend>=1; candle path stays default - A/B bench at
seq_len ∈ {1K, 2K, 4K, 8K, 16K} - Bit-identical / fp-tolerant parity test vs candle path (5 GPU parity tests in
kiln-kt-bridge/tests/cuda_matmul_parity.rs) - Vulkan:
VK_KHR_cooperative_matrixfor the matmul backend. Audit confirms today'skiln-vulkan-kernel::vk_ops/matmul*uses subgroup-scalar arithmetic; cooperative matrix exposes NVIDIA/AMD/Intel matrix cores via standard Vulkan (same primitive ggml-vulkan and VkFFT use for 4–8× matmul throughput). Lifts Vulkan from "works" to "competitive with CUDA at the same shape." Per-tier: largest win on consumer Vulkan-only setups (Intel Arc, AMD RDNA, NVIDIA where the CUDA path isn't selected) which are predominantly 16–24 GiB. - Vulkan:
VK_EXT_descriptor_buffer+VK_KHR_buffer_device_address. Eliminates per-dispatch descriptor pool overhead (currently ~10 KB/dispatch throughdescriptor_pool.rs) and lets buffers be referenced by raw GPU address across submits. ~5 % decode-loop overhead recovered. - Vulkan: multi-queue (compute + transfer). Today
crates/kiln-vulkan-kernel/src/device.rs:41uses a single queue; H2D prefill upload, compute, and D2H final-logits all serialize. Add a transfer queue family alongside compute; semaphore-sync between them. ~10–15 % throughput on prefill-heavy workloads. - Vulkan: disk-persistent pipeline cache.
~/.cache/kiln/vulkan/pipeline-cache-{device_uuid}.bin. Eliminates SPIR-V re-compile on every cold start (0.5–5 s currently); reuses the disk-persistent autotune cache pattern above. - Metal:
simdgroup_matrixin custom MSL kernels. Today only candle SDPA uses Apple's matrix cores via MPS; the custom kernels inbackend/metal.rs(SiLU*mul, fused QKV GEMV, transposed-coop GEMV, MLP gate+up) are simdgroup-scalar. Migrate tosimdgroup_matrixwhere the operand shape supports it. 2–3× on matmul-dominant Apple Silicon decode. Per-tier: matters most on M2/M3 Pro 16 GB; relatively less critical on M3 Ultra 192 GB where memory bandwidth saturates first. - Metal:
MTLHeapfor ephemeral intermediates. Activations, KV-cache scratch, sampler scratch all allocated from per-deviceMTLHeapwith sub-heap aliasing. Reduces fragmentation on long-running servers; pairs with Phase 1 allocator'sPoolmode.
Track done when: kiln-tensor MLP path is enabled by default on that backend after A/B exposure shows no regression in bench-results/.
Phase 2.5 — kiln-param: unified Parameter handle
Blocked by Phase 2 on any backend (need quantized GEMM available). Gates Phase 3, Phase 4.5, and Phase 6b/6c. This is the architectural piece that makes "same weight structures across inference and training" structural rather than aspirational.
Today's bookkeeping is spread across packed_weight_registry.rs (489 LOC), transposed_weight_cache.rs (730 LOC), marlin_proj.rs, fp8.rs, adapter_merge.rs (1703 LOC), and lora_loader.rs. Each treats the "same logical weight" as separate Tensors. The optimizer can't address them as one parameter and cuda_graph capture invalidates on adapter swap because the pointers churn.
-
Parameter { forward_storage, backward_storage, transposed_cache?, lora_delta?, tensor_id }in a newkiln-paramcrate - Forward dispatches on storage variant: BF16, Marlin W4A16, FP8, future FP4
-
tensor_idis stable across storage-variant transitions. Adding a Marlin/FP8 forward variant on top of an existing BF16-master, or hot-swapping a LoRA delta, does not change the id. Otherwise AdamW moments (HashMap<TensorId, AdamWMoments>atcrates/kiln-train/src/trainer.rs:555,592) get orphaned on weight-form transitions. - Backward always goes through the master and, for quantized weights, terminates in a fused
dequant → update → requantkernel where the backend supports it - Storage-coherence invariant (the core "same weights for both" rule). For a Parameter with both
forward_storage(quantized) andbackward_storage(master), the relationship is explicit, not implicit: after an optimizer step writes the master, the forward storage is stale andParameter::forward()blocks on a re-quantization kernel before returning. The re-quant is fused into the optimizer step on backends that support it (so steady-state training never sees a separate kernel launch). For pure-inference Parameters (nobackward_storage), forward_storage is canonical. For Parameters withlora_delta, the merged form is computed lazily on firstforward()after delta-swap and cached until the delta changes again —cuda_graphcapture pins the cached merge, swap invalidates lazily. Document the state machine and write a parity test that round-tripsBF16-master → Marlin-fwd → optimizer step → BF16-master → Marlin-fwdbyte-for-byte. - LoRA delta is hot-swappable without changing
tensor_id—cuda_graphcapture survives adapter swap - Tied parameters share one Parameter, one backward_storage, atomic grad accumulation. Qwen3.5-4B ties LM head ← embed_tokens (
weights.rs:243,forward.rs:6014,vk_forward.rs:1503); MTP head also ties (loader.rs:675). Gradients from both call sites accumulate into the singlebackward_storagevia atomic-add (deterministic order documented per Phase 0's tolerance band). Optimizer sees one logical parameter, not two. Single-VRAM invariant: no second master copy. - Marlin is forward-only and stays forward-only (
crates/kiln-marlin-gemm/src/lib.rs:33). The supported training path is LoRA-around-Marlin viamarlin_proj.rs+ the on-disk transposed-weight mmap cache (transposed_weight_cache.rs:64-92) — direct-Marlin-backward is currently broken (PROFILING.md "expected rank-2 q_proj_t") and is not on this epic. - QLoRA scope decision. QLoRA-style (4-bit Marlin base, BF16 LoRA delta, no BF16 master ever materialized) is out of scope for this epic — the supported quantized-training mode is LoRA-around-Marlin with a BF16 master (memory cost: full FP16 weights + LoRA + Marlin). If genuine QLoRA is later required,
Parameteralready accommodates: dropbackward_storage, route gradients only intolora_delta. Don't build it now; don't preclude it. - Draft and target share one
Parameter::forward_storagefor the MTP / self-speculative path; layer-prefix slicing is a zero-copy view, not a second allocation. Single-VRAM regression budget here. - Tensor-parallelism seam (do not implement, do not preclude). Multi-GPU stays out of scope (anti-pattern 12). The
Parametertype does not bake "one rank == one storage" —backward_storageisVec<Storage>of length 1 today, designed to be length N (per-rank shard) later.StreamPlanneris per-device today; the API doesn't preclude composing with NCCL streams later. Two lines in the type definition; zero runtime cost; saves a rewrite when TP lands. - Migrate
packed_weight_registry.rs+transposed_weight_cache.rs+marlin_proj.rs+fp8.rsweight-side concerns onto this one handle.adapter_merge.rsis intentionally candle-free f32-CPU code (anti-pattern 15) and does not port. - Per-op parity tests cover: BF16-only, Marlin-forward + BF16-master backward, FP8-forward + BF16-master backward, with and without LoRA delta, plus the tied-weight grad-accumulation case (LM head + embedding writing into one master)
- Output-head registry on
Parameter. A Qwen3.5-4B Parameter (embed_tokens/lm_head/mtp_head) can carry multiple output heads that share the trunk storage: the LM head (vocab=152064 logits), the MTP head (single-draft-token logits, k=1), and — for RL / preference training — a value head and/or reward head. Type:Parameter { …, heads: Vec<OutputHead> }whereOutputHead { head_storage, head_dtype, requires_grad, role }. The trunk computes once; heads dispatch in parallel on the StreamPlanner. Without this slot, RL training has to thread "where is the value head" through every call site (todayvalue_headexists incrates/kiln-train/src/trainer.rs:12913but for GatedDeltaNet, not RL — the slot is unused for its likeliest future purpose). Composes with anti-pattern 17 (tied weights): the LM head + embedding tie is an output head on the embedding Parameter. - Parameter content checksum (xxhash3) for safe hot-swap.
Parameter::content_hash() -> u64is a content-addressed fingerprint offorward_storage(post-quantization, post-LoRA-merge). Required for: (a) multi-process serving safety — a second kiln process attaching to the same Qwen3.5-4B model via CUDA IPC can verify the in-memory weights match its expected checkpoint; (b) hot-swap of a fine-tune over a running serve — request mid-flight cache invalidation when the content_hash changes; (c) adapter cache invalidation on the serve side. Todaymodel_version_hashexists incrates/kiln-train/src/receipt.rsandcrates/kiln-server/src/training_queue.rsfor receipts; lift it to a first-class runtime property onParameter. xxhash3 over the storage buffer is sub-millisecond on the 4 GiB Qwen3.5-4B BF16 master. - Explicit AMP / autocast policy on
Parameter. Today candle's autocast handles dtype promotion implicitly — that disappears with candle. Each Parameter declaresAmpPolicy { forward_compute_dtype, backward_compute_dtype, master_dtype, accumulation_dtype }at construction. Mixed-precision is then a property of the Parameter, not an implicit behavior of the call site. Default for Qwen3.5-4B:forward=BF16, backward=BF16, master=BF16, accumulation=FP32. FP8 path overrides:forward=FP8E4M3, backward=BF16, master=BF16, accumulation=FP32. The optimizer step reads the policy and dispatches; no implicit casts.
Phase 2.7 — Live serve + train coexistence (the Kiln-defining primitive)
Blocked by Phase 2.5 (Parameter handle). Gates multi-LoRA serving, on-policy GRPO, and eval-while-training.
Today (crates/kiln-server/src/state.rs:185,1268, training_queue.rs:2159+), training takes an exclusive GPU write lock for the entire job; serving is blocked for minutes. This is structurally at odds with "your model gets better every time you use it" — the next request submitted after POST /v1/train/sft waits until training finishes. Candle-removal makes finer-grained coexistence achievable; this phase ships it.
- CUDA stream priorities via
cudaStreamCreateWithPriority. Repo currently has zero call sites — confirmed by audit. Inference runs on hi-pri stream(s); training runs on lo-pri stream(s). The driver preempts lo-pri SM allocation when a hi-pri kernel needs SMs. Net: an in-flight SFT step delays decode tokens by tens of microseconds (one kernel boundary), not seconds (whole-step lock). Metal:MTLCommandQueuepriority hint. Vulkan:VK_KHR_global_prioritywhere supported; fallback is single-queue with kernel-size-bounded yields. -
Parameter::versionepoch counter — atomic, bumped at end-of-optimizer-step.Parameter::forward(epoch_hint)returns a snapshot consistent atepoch_hint; an in-flight decode reads at the epoch it started with. On 48 GiB+ this double-buffers the quantized form (size cost: ~2 GiB on Qwen3.5-4B). On 16 GiB where double-buffering doesn't fit, fall back to "serve pauses during the requant kernel" — a bounded sub-millisecond stall, not a multi-second job-level lock. Per-tier behavior documented inARCHITECTURE.md. - Replace the GPU RwLock with a Parameter-versioned read path. Today's whole-GPU
RwLockatstate.rs:1268+ the six lock sites intraining_queue.rs:2159,2194,2217,2235,2250,2264,2279collapse to: serving holds no lock and readsParameter::current_epoch(); training acquires per-Parameter mutability throughkiln-param's borrow-checked API (in-place ops bump the version counter per anti-pattern 16). The whole-GPU lock becomes a degenerate case used only during model load / model swap. - Multi-LoRA serving in same batch. Today
set_adapteris exclusive (crates/kiln-server/src/eval/generator.rs:62-67,146). WithParameter::lora_deltaas a slot rather than the parameter itself, the forward applies per-request deltas in a batched matmul:Y = X @ W_base + (X @ A_request) @ B_request. Reference shape: vLLM's multi-LoRA flattening. Adapter pool sized fromkiln-core::vramlike the KV cache: 1–2 resident on 16 GiB, 2–4 on 48 GiB, 8+ on 80 GiB. - Eval-while-training via Parameter snapshot. Eval acquires
Parameter::snapshot(epoch)at job start; training continues to mutate the master; the snapshot is refcounted and the storage isn't freed until eval completes. On 16 GiB this is opt-in (snapshot doubles weight VRAM); on 48 GiB+ default-on. Eliminates the "training pauses for eval" delay thateval/mod.rs:1-7inherits today from the write-lock. - On-policy GRPO rollouts. Today GRPO requires pre-generated rollouts (
crates/kiln-train/src/trainer.rs:2234;lib.rs:271-287—groups: &[GrpoGroup]as input, no inference path). With concurrent serve+train, the trainer can generate rollouts from the current policy by issuing forward-only requests through the same scheduler, snapshot the policy at rollout start, update from the rollouts, repeat. The GRPO outer loop tightens from minutes/step to seconds/step. This is a defining capability of the Kiln pitch. - Multi-adapter A/B serving for the judgment flywheel. Two adapters (A, B) resident; same batch dispatches some requests to each; the dashboard's A/B picker drives slot assignment. Reduces A/B comparison from "two adapter-swap stalls per pair" to "zero stalls, batched comparison." Same primitive as multi-LoRA above.
- Concurrency-correctness parity test. Training-while-serving produces byte-identical loss curves and byte-identical inference outputs vs serial training + serving on a fixed seed. The lockless path must be deterministic at the same tolerance band as the locked path.
- Per-tier behavior matrix in
ARCHITECTURE.md— what coexists with what at 16 / 24 / 48 / 80 GiB. The 16 GiB tier serves while training; it does so with a small, bounded requant stall per step rather than full-job blocking. - Replay / experience buffer as a first-class abstraction. On-policy GRPO above generates rollouts at the policy's current epoch and discards them after the step. Off-policy methods (PPO with stale rollouts, DPO with offline preference pairs, KTO with binary feedback, ORPO with reference-free preferences, IPO, SimPO) want a buffer of rollouts keyed by
Parameter::snapshot(epoch)— the same primitive Phase 2.7 already exposes for eval-while-training. Type:ReplayBuffer { entries: Vec<{prompt, completion, reward?, ref_logprobs?, policy_epoch}>, max_age_epochs, sampling_strategy }. The reference-logprobs slot lets DPO/IPO compute the reference model's logprobs once at insertion under the snapshot, freeing the reference model from per-step inference cost. Sized per VRAM tier (small at 16 GiB, multi-GB at 80 GiB). This is the data-plumbing seam that lets Kiln's RL algo menu (next item) ride the live-coexistence primitive cleanly.
Phase 3 — Attention
QKV → RoPE → flash-attn → O. Three parallel tracks. Blocked by Phase 2 and Phase 2.5 complete on the same backend.
- QKV projection through three independent streams/queues per backend (true parallel matmul, scheduled by
StreamPlanner) - RoPE rebound to
kiln-tensor(kernels exist per backend) — CUDA forward rebound via the epic: migrate off candle to in-house kiln-tensor (CUDA + Metal + Vulkan) #1082 type-flip;model_forward_pageddecode-parity test passes (numerically identical to candle). Metal/Vulkan + full training-tape coverage pending. - Flash-attn (CUDA) / Metal scaled-dot-product / Vulkan attention kernel rebound to
kiln-tensor -
kiln-flash-attnRust API switch. Current API takescandle_core::Tensorand usescandle_core::bail!(crates/kiln-flash-attn/src/lib.rs:245,257,826). Switch the Rust shell tokiln_tensor::Tensor; do not touch the FFI/CUDA-side — keepkiln_flash_attn_fwd,_fwd_paged_decode,_fwd_paged_decode_dyn_seqlen,_bwd, andkiln_paged_kv_write_token_major_bf16{_slot,}(lines 16-72, 94). Dyn-seqlen variant is the one graph capture depends on; GQA backward (line 440) and head-dim {128, 256} restriction (line 277) preserved. - O projection through per-backend BLAS — CUDA forward rebound via the epic: migrate off candle to in-house kiln-tensor (CUDA + Metal + Vulkan) #1082 type-flip;
model_forward_pageddecode-parity test passes (numerically identical to candle). Metal/Vulkan + full training-tape coverage pending. -
PagedKvCacheported off candle Tensor.crates/kiln-model/src/paged_kv_cache.rs:11-150,232-340—Vec<(Tensor, Tensor)>layers, FP8 K/V variant (new_with_fp8,fp8_scalesat line 47), per-rowwrite_token_major_native_graph_slotslot-tensor interface. The slot interface is the explicit CUDA-graph capture contract — preserve byte-for-byte. - Persistent buffers per backend, no allocation in decode loop
- Scheduler↔tensor-runtime contract.
crates/kiln-scheduler/src/scheduler.rsis candle-free today but dictates the batch shape every forward must handle; theBlockTable+cached_blocks+prefix_cache_statsinterface flows directly into paged-attention dispatch. Pin the contract: kiln-tensor's paged-attention dispatch consumesBlockTableunchanged; prefix-cache hits remain free of recompute under the new backend. Add a prefix-cache parity test alongside the inference parity test. - GDN recurrent + conv state in
kiln-tensor's resident-activation registry — generalize the Vulkan-only pattern. TheBackendRuntimetrait has 7+supports_gdn_*methods andenter/exit/materialize/evict_gdn_recurrent_resident_state_scopelifecycle hooks; the registry belongs inkiln-tensor, not in each backend. CUDA and Metal supply upload/evict primitives; decode loop never pays a roundtrip for GDN state on any backend. - Bench prefill at seq_len sweep on each backend
- Parity test vs candle path
Phase 4 — Glue (embedding, RMSNorm, residual, final norm + LM head + sampling)
Per backend. Blocked by Phase 1 only; runs in parallel with Phase 2 and Phase 3.
- Embedding lookup (trivial kernel per backend; CUDA + Metal + Vulkan already have variants) — CUDA done via
EmbeddingOp::cuda_fwdrouting throughcuda_index_select_dim0 - RMSNorm rebound to
kiln-tensor— CUDA forward rebound via the epic: migrate off candle to in-house kiln-tensor (CUDA + Metal + Vulkan) #1082 type-flip;model_forward_pageddecode-parity test passes (numerically identical to candle). Metal/Vulkan + full training-tape coverage pending. - Residual add kernel per backend (CUDA via
cuda_elementwise_binary(kind=Add); Metal + Vulkan pending) - Final norm + LM head matmul through per-backend BLAS (CUDA via cublasLt under
KILN_USE_KT_API_MATMUL=1; Metal + Vulkan TBD) - Port (not add) the existing on-device sampling kernels in
crates/kiln-model/src/sampling.rs:5-110,264off candle Tensor: greedy argmax, batched argmax, top-k sample, repetition/frequency/presence penalties, min-p. TheBackendRuntimetrait already exposessupports_linear_decode_argmax / _batch / _sample(top_k); lift the seam tokiln-tensor. PCIe transfer stays at u32-per-step — no logits ever crosses host. - On-device categorical sampling + per-slot seeded RNG. Today
sampling.rs:341-353does the categorical step on host withStdRngafter a top-k transfer. Move to on-device Gumbel-max with a seeded PRNG per request slot. Eliminates the last per-token VRAM-to-host transfer above 4 bytes (the sampled token id). Preserves reproducibility (seed-per-slot) and per-request temperature/penalty independence. Strict prerequisite for sub-100 µs decode token latency on consumer cards. - On-device stop-sequence prefix match (promoted from Phase 8.3 to a Phase 4 gate). The D2H sync for stop-condition is the inherent decode-latency floor on bs=1; today
crates/kiln-model/src/generate.rs:1556-1670,3041does it host-side. Inline kernel reads the just-sampled token, walks a per-request stop-prefix DFA on-device, writes a 1-bit "should_stop" per request to a pinned host buffer the scheduler polls. Reduces the bs=1 hot loop to: launch decode graph → replay → read 1 bit. No longer a future "perf win" — it's a hard prerequisite for hitting the bs=1 numeric gate. -
LogitProcessorchain as a first-class abstraction. Audit shows the current sampler atcrates/kiln-core/src/sampling.rshas top-k, top-p (nucleus), min-p, temperature, and the three penalties — but they're hand-wired, not composed. DefineLogitProcessoras a stackable trait operating on aTensor<[batch, vocab]>in place, dispatched on the StreamPlanner. The chain order, fixed for Qwen3.5-4B:penalties → ngram-block → grammar-mask → logit_bias → temperature → top-k → top-p / min-p / typical-p / Mirostat → categorical sample (Gumbel-max). Each processor is one device kernel + one parity test against a CPU reference. The structured-output mask below becomes one processor in this chain, not a one-off. - Structured-output / constrained-decoding pipeline. Audit confirms zero hits for
jsonschema/grammar/logit_biasin the repo today. Pipeline: parse schema → compile to per-position legal-token mask (host) → upload mask async (pinned-host pool from Phase 1) → apply mask on-device immediately before sample (between top-k and categorical). Mask is a u32 bitmask per request. Must be on-device — host-side mask application breaks the bs=1 sync-point story above. Per-tier: mask is small (~1 KB per request at vocab=152K with bitmask compression); fits on 16 GiB with thousands of resident requests. Composes with theLogitProcessorchain above as thegrammar-maskstep. - Advanced sampler menu (one kernel each, all in the LogitProcessor chain). Today's sampler covers top-k / top-p / min-p / temp / penalties — the production-server table stakes. Add: Mirostat v2 (adaptive surprise targeting; one extra device-side state per slot), typical-p (locally typical sampling), DRY (don't repeat yourself n-gram repetition penalty — high signal-to-noise for instruction-tuned Qwen), XTC (exclude-top-choices for creative writing), n-gram block (hard block on configured n-grams). Each is small; the win is they all compose through the same chain rather than each requiring a custom decode path on top of the existing sampler.
- Tree-style speculative decoding (EAGLE-2 / EAGLE-3 / Medusa) scheduling. Today
crates/kiln-model/src/speculative.rs(1160 LOC) runs sequential per-prefix MTP drafting andmtp_debug.rs(4588 LOC) carries the verify path. Tree drafts (multi-branch lookahead) raise per-step acceptance from ~1.7× to ~2.5× on Qwen-class models. The tree shape composes with the captured graph (Phase 5) — verify-N-tokens-per-position is one captured graph; the draft tree shape is a per-bs constant. Memory cost:O(tree_size × hidden)per request, fits at every VRAM tier. Composes with Phase 4.5 (which preserves byte-equality with the sequential MTP path) — tree-spec is an opt-in scheduler mode, not a replacement. - Parity tests per op per backend (CUDA: every shipped op has a parity test in
kiln-kt-bridge/tests/; Metal + Vulkan pending)
Phase 4.5 — MTP + self-speculative on kiln-tensor
Blocked by Phase 3 (paged attention + scheduler contract on kiln-tensor) and Phase 2.5 (one Parameter shared by draft + target).
The MTP + speculative paths today touch ~5.7K LOC across mtp_debug.rs (4588) and speculative.rs (1160). They share physical weights with the target — draft uses model_forward_segment(0, draft_layers) over a prefix of the same GpuWeights — so the migration must preserve that, not duplicate. The MTP verify pass also currently runs eager; without graph capture covering it, the headline bs=64 ≥ vLLM target leaves perf on the table.
- Draft and target share one
Parameter::forward_storage; layer-prefix slicing is a zero-copy view (no second allocation) -
KILN_MTP_ARGMAX_FP32(the BF16-vs-FP32 head-dtype switch for top-1 stability) ported verbatim — name preserved - MTP verify pass goes through the same captured graph as decode at matching
bs(extends Phase 5's capture scope) - Self-speculative draft pass (skip-layer drafting) honors the
StreamPlanner— draft + verify do not serialize on the default stream - Byte-equality parity test against the candle path; reuse
crates/kiln-model/tests/mtp_byte_eq.rsnaming - Latency parity: spec-decode wall-clock per output token ≤ candle baseline on every backend
- Static MTP depth = 1 codepath (Qwen3.5-4B specialization). Qwen3.5-4B's
num_nextn_predict_layers = 1(crates/kiln-model/src/loader.rs:173). Todayspeculative.rs(1160 LOC) is parameterized over draft depth; under candle removal, specialize the verify path to the k=1 case — eliminate the per-depth loop, eliminate the per-depth branch, hand-shape the verify kernel against the one-extra-token batch shape. Tree-spec scheduling (Phase 4 above) is a separate path — it explicitly expands the draft beyond k=1 — and stays general. The point is: the sequential MTP path that ships today is the k=1 path, and the loop is overhead.
Phase 6a — Lift vk_autograd to kiln-autograd
Blocked by Phase 1. Runs in parallel with Phase 2.
- New
kiln-autogradcrate; tape walker copied fromvk_autograd.rs, generalized tokiln_tensor::Tensor -
BackwardOptrait moved tokiln-autograd;VkBackwardOpbecomes a re-export -
VkGradStorebecomesGradStore, keyed onkiln_tensor::TensorId(matches theParameterhandle's id contract from Phase 2.5) - Activation checkpointing primitive preserved:
model_forward_segment(forward.rs:13705,kiln-train/src/lib.rs:200checkpoint_interval,kiln-train/src/opd.rs:1013) is the only such primitive today; kiln-autograd's tape must accept "checkpointed segment" boundaries without forcing a recompute design rewrite. - Vulkan training (
vk_train.rs) continues working unchanged through the new abstraction - Two seed ops (
ones_like,add_no_grad) implemented per backend (CUDA + Metal + CPU; Vulkan reused) - In-place op tape invariant. The optimizer step mutates
Parameter::backward_storagein place. The autograd tape must not hold any reference to the pre-mutation tensor afteroptimizer.step(). Two guards: (a)Tape::clear()runs at end-of-step before any in-place mutation, (b) in-place ops bump a per-tensor version counter that the backward path asserts against. Vulkan currently gets this right because the tape is per-forward; CUDA + Metal must inherit the same invariant or training will produce silent corruption on the second step. - Selective recomputation hook (forward-looking).
model_forward_segmentcheckpoints today recompute the entire segment on backward. Selective recomp (save cheap activations, recompute only expensive ones) is a future training-memory lever.kiln-autogradexposes per-opshould_recompute()returningbool; default is the conservative "recompute whole segment"; an opt-in selective policy can layer on later without touching the tape walker.
Phase 6b — CUDA backward parity
Blocked by Phase 6a + Phase 2 CUDA (need forward matmul through kiln-blas) + Phase 2.5 (Parameter handle so the optimizer addresses Marlin/FP8/LoRA weights as one).
The existing in-house CUDA crates already cover the hard backwards (kiln-flash-attn has flash-attn bwd; kiln-gdn-kernel has gdn_chunk_bwd; kiln-opd-loss-kernel has OPD + FLCE bwd; kiln-conv1d-kernel has causal-conv1d bwd; kiln-rmsnorm-kernel covers RMSNorm). Remaining backward ops for full parity with the 34 impl VkBackwardOp blocks in vk_ops/:
-
matmul/matmul_batched/matmul_bf16w—dA = dC @ B^T,dB = A^T @ dCviakiln-blas -
elementwise(add/sub/mul/div) — trivial routing -
reshape/transpose/permute/narrow— stride math, no kernel -
silu/sigmoid/mul_sigmoid_gate— standard math -
softmax_last_dim— classic two-pass -
rope— rotate inverse direction -
embedding/index_select— scatter-add into grad buf -
l2norm/cast/reduce(sum / mean) -
rmsnormbwd binding (if not already inkiln-rmsnorm-kernel) - Per-op parity test against the CPU reference at matching shapes (CPU is the canonical golden; Vulkan and Metal cross-check too)
- Port
crates/kiln-train/src/cuda_train.rsontokiln-autograd; deletecrates/kiln-model/src/cuda_train.rsin favor of the sharedParameter/Tensortypes inkiln-tensor. The two files have caused ambiguity; collapsing them onto the shared substrate removes one entire bookkeeping layer. - Delete the
sync_to_candleround-trip (crates/kiln-train/src/trainer.rs:626,632). Optimizer state writes back directly intoParameter::backward_storage; checkpoint save reads fromParameterstorage without dropping training state. - LoRA-around-Marlin training path validated end-to-end — direct-Marlin-backward is not in scope (anti-pattern: see Phase 2.5); the supported quantized-weight training mode is forward through Marlin, backward through the BF16 master + LoRA delta.
- SFT loss-curve parity test: 100 steps on a fixed seed, per-step loss within
1e-3(BF16) /1e-5(FP32) of the candle reference; Adam moments at step 100 within1e-3.
Phase 6c — Metal backward parity
Blocked by Phase 6a + Phase 2 Metal + Phase 2.5. Same op set as Phase 6b in MSL.
- Same backward ops list as 6b, in Metal MSL
- Per-op parity test against the CPU reference
- If a Metal training crate exists or is added, wire it through
kiln-autograd - SFT loss-curve parity test with the same tolerance as 6b
Phase 6.5 — kiln-optim: fused per-backend optimizer step
Blocked by Phase 6a (autograd) + Phase 2.5 (Parameter handle). Without an explicit shared crate the fused-optimizer logic gets rebuilt three times — Vulkan already has adamw_step_bf16.comp; the CUDA path goes through Var::set via candle; Metal has nothing.
-
kiln-optimcrate withOptimSteptrait: AdamW, SGD, Lion, Muon - Operates on
Parameter: FP32 moments + BF16 params + optional FP32 master, configurable per-Parameter - Marlin / FP8 weights: fused
dequant → update → requantkernel per backend - Gradient accumulation across micro-batches. Trainer accumulates over N micro-batches before stepping (
accumulate_grad/accumulate_grads_exceptinvk_train.rs:808,823;opd.rs:2767). The grad buffer lives inParameterand accumulates atomically across micro-batches;optimizer.step()consumes-and-zeros. The in-place tape invariant from Phase 6a applies: tape clears between forward+backward calls, not between micro-batches. - Tied-weight grad accumulation through one Parameter. From Phase 2.5: LM head + embedding both write into one master. The optimizer step sees a single grad buffer (already correctly accumulated by the backward passes); it does not need to know the parameter was tied. Parity test in this phase covers the tied case end-to-end.
-
dWanddXcompute on parallel streams in matmul backward.dA = dC @ B^TanddB = A^T @ dCare independent. The CUDA / Metal / Vulkan matmul-bwd implementations submit them on two streams scheduled byStreamPlanner. Real perf win in training; preserves the determinism contract because the two grads don't share an output buffer. - Per-backend implementations call into
kiln-blas/kiln-mps/kiln-vulkan-blasfor the heavy ops - Loss-curve parity preserved through every optimizer variant on every backend
- Stochastic rounding for BF16 master updates. Round-to-nearest loses precision at the master-update step under small learning rates; stochastic rounding (round up or down with probability proportional to the fractional position) preserves the in-expectation update. Fused into
kiln-optim's AdamW step kernel; gated byKILN_BF16_STOCHASTIC_ROUND=1. Especially relevant on 16 GiB tier where the BF16 master is the only master (no FP32 mirror). - Selective recomputation as a real Phase 6.5 deliverable, not a forward-looking hook. Phase 6a notes the
should_recompute()hook; this is the policy that ships: classify ops as cheap (norm, residual, embedding) vs expensive (matmul, attention) and recompute only the cheap ones on backward. Cuts activation memory ~40 % at ~5 % compute cost. On 16 GiB this is the difference between training-fits and training-OOMs. - Activation + master-weight offload to pinned host RAM (16 GiB tier enabler).
kiln-tensor::OffloadPolicyper Parameter:Always(default, full VRAM resident),OnDemand(page in for backward, page out after step),Host(mirror in pinned host RAM). On 16 GiB the BF16 master defaults toOnDemand; on 80 GiB staysAlways. Uses the Phase 1 pinned-host staging pool; async stream pulls pages per-layer during backward, prefetched one layer ahead. Without this, training does not fit on 16 GiB — period. - Optimizer-state location seam. AdamW per-parameter moments are 8 bytes/param at FP32; for Qwen3.5-4B that's 32 GiB optimizer state — the binding constraint on 16 GiB and the second-binding on 24 GiB. Seam:
kiln-optim::OptimStepacceptsMomentLocation { Device, PinnedHost, MmappedDisk }per Parameter. DefaultPinnedHoston 16 GiB,Deviceon 80 GiB. Async copy interleaved with the next forward. Composes with the existing tensor-parallelism seam (anti-pattern 12) so the future TP rollout doesn't have to revisit moment storage. - Activation offload to pinned host RAM (separate from weight offload). Distinct from the weight/optimizer offload above — this is the forward activations the backward pass needs. Default policy per
Activation(Phase 1 type):Deviceon 24 GiB+;PinnedHoston 16 GiB for activations beyond layer N where N is auto-sized so peak resident ≤ 50% of free VRAM. Prefetches one layer ahead on the async stream during backward. The auto-sizer atcrates/kiln-core/src/vram.rs:460-720already estimates the activation tape; extend its output withactivation_offload_layer: Option<usize>. Without this, the 16 GiB tier can checkpoint heavily but cannot recover the 30-40% activation memory that lives between checkpoints during the backward pass. - AMP / autocast policy is consumed here, not invented here. The Parameter's
AmpPolicy(Phase 2.5) declares forward/backward/master/accumulation dtypes.kiln-optimreads the policy off the Parameter; the matmul-bwd kernel reads it; the accumulator reads it. No "AMP mode" flag — the policy is per-Parameter so a Marlin-forward layer and a BF16-only norm can coexist in one optimizer step without any global state. Parity test: every AmpPolicy variant Qwen3.5-4B uses has a per-op tolerance row inbench-results/parity-tolerance.csv.
Phase 5 — Command-list / graph capture (per backend), with batched cuda-graph as the headline
Per backend. Blocked by Phases 1-4 (and 4.5 for MTP verify pass) complete on that backend (inference path fully on kiln-tensor) + Phase 2.5 (Parameter handle so weight pointers are pinned across capture/replay even under adapter swap).
The whole reason candle is blocking the bs>1 cuda-graph win today is the inability to pin every device pointer the forward touches (GDN recurrent state, conv state, paged-KV slots, RoPE tables, LM head output, sampler scratch). cuda_graph.rs:33-96 already documents the full list. The migration eliminates that blocker; this phase ships the win, not buries it.
- kiln-tensor allocator "freeze-pointers" mode. Active for the duration of
capture()…replay(). Allocations during freeze come from a pre-sized pool with no reclamation. This is the structural fix that makes batched cuda-graph capture possible; without it Phase 8 doesn't land. On CUDA, "freeze" enablescudaMallocFromPoolAsynccapture-mode and the driver tracks pointer lifetimes natively (CUDA 12.0+); the kiln-side audit is a defense-in-depth, not the primary mechanism. - Capture-lifetime programming model (the dangling-pointer rule). Any tensor whose
.device_ptr()enters a captured graph must outlive every replay of that graph. Lifetimes are encoded in the type system where possible (CapturedGraph<'a>borrows from aFrozenAllocator<'a>) and enforced by a debug-assertionkiln_tensor::audit_captured_pointers()that walks the graph and verifies every recorded pointer still resolves to a live allocation. A failing audit is a graph-invalidation, not a silent corruption. -
bs>1slot-index addressing. Each replay at bs=64 hits 64 distinct paged-KV slot indices. The captured graph cannot bake slot indices as immediates — they're read from a pinned device buffer the scheduler updates between replays.paged_kv_cache.rs:write_token_major_native_graph_slotalready exposes the slot-tensor seam (preserved in Phase 3); Phase 5 generalizes it to the full bs∈{1..64} family by routing slot indices through a per-bs pinned scratch buffer. - CUDA: capture batched decode at
bs ∈ {1, 2, 4, 8, 16, 32, 64}and replay on subsequent tokens. Revive the dead-codeCudaBatchedGraphKeystub atcuda_graph.rs:178. Target: ≥ vLLM at the same shape on L40S, Qwen3.5-4B (current gap: kiln 1181 vs vLLM 1907 tok/s @ bs=64). Memory budget: 7 graphs × per-bs scratch footprint stays under 5% of device-local heap; document the per-bs VRAM cost inbench-results/. - MTP verify pass captured alongside decode at matching
bs(handoff from Phase 4.5) - Metal: pre-record decode into
MTLIndirectCommandBuffer - Vulkan: extend
kiln-vulkan-kernel::cmd_batch.rsto a full pre-recorded decode pipeline; generalizedecode_resident_pool.rs's slot-ring (MIN_SLOTS=3 / PREFERRED_SLOTS=4 / 1 %-of-heap) to CUDA + Metal - Persistent kernel buffers per backend (no allocation in hot loop)
- Decode-tokens-per-sec bench vs the non-captured baseline + against the CUDA bs=64 / vLLM gate
- AOT graph serialization (Qwen3.5-4B specialization). On CUDA 12.4+ the graph family captured above is serialized to
~/.cache/kiln/graphs/qwen3p5-4b-{gpu_uuid}-{kiln_version}.cugraphviacuGraphSerializeand reloaded on subsequent cold starts. The graphs are content-addressed by the Parameter content hash (Phase 2.5) so adapter changes or weight updates trigger fresh capture, not a stale-graph silent failure. First-token cold-start latency on tier-1 GPUs drops by the full graph-capture cost (~250-800 ms per bs in the family today). Metal: pre-recordMTLIndirectCommandBuffers into aMTLBinaryArchivekeyed similarly. Vulkan: pipeline cache plus a serializedcmd_batchblueprint where the API allows. Where the driver doesn't support serialization (older CUDA, older Vulkan), fall back to runtime capture — but the cache file is the steady-state cold-start path.
Phase 7 — Remove candle
Blocked by every other phase complete on every backend.
- Delete
vendor/candle-core/(235dc0ca) - Remove
candle-coreandcandle-nnfrom every[dependencies]and[dev-dependencies]block (235dc0ca); also dropped the[patch.crates-io]vendor entry - Remove the
BackendRuntimecandle-aware fallback paths fromcrates/kiln-model/src/backend/mod.rs—for_devicecandle shim deleted; backend/mod.rs has zero non-comment candle refs (9fe4657f) - Remove every
KILN_USE_KILN_TENSOR_*feature flag and its corresponding candle path — deleted the dead kiln_tensor_flags module (zero call sites; candle path gone) - Final integration test on every backend
- Update
ARCHITECTURE.md,CLAUDE.md,PROFILING.md
Phase 8 — Post-removal performance wins (tracked separately)
Not part of the candle-removal gate; opened as a tracking issue once Phase 7 lands. These drop out naturally once kiln-tensor + Parameter + StreamPlanner + freeze-pointers allocator + graph capture exist. Each bullet below is a concrete sub-phase, not aspiration — when this issue's Phase 7 lands, an epic: post-candle perf issue opens with these as sub-items:
- 8.1 Persistent attention kernel. One CUDA kernel runs many decode steps without re-launch, reading paged-KV slot indices from a device-side queue updated by the scheduler. Targets the per-launch overhead floor (~3-5 µs × num_layers × decode_steps). Reference shape: FlashInfer's persistent-attn, lifted to the kiln-tensor + paged-KV interface. Expected win: 1.1-1.3× on bs=1, fades at bs=64 where launch overhead amortizes.
- 8.2 Persistent / megakernel MLP. Single fused kernel doing gate+up+silu+down across an entire layer (or block of layers) without intermediate global-memory roundtrips. Requires careful register/shmem budgeting; only viable on H100+ with enough resources. Expected win: ~10% decode tok/s when combined with 8.1.
- 8.3 On-device stop-condition prefix match. Today: GPU samples → 1 u32 D2H → CPU stop-sequence check → next iter (
generate.rs:1556-1670,:3041). The D2H sync is the inherent decode-latency floor. Move stop-sequence prefix match on-device for greedy decode; CPU only sees a 1-bit "should_stop" signal per request. Eliminates the last sync point in the bs=1 decode hot loop. - 8.4 FP8 forward training (Hopper / Blackwell). FP32 master + FP8 activation/gradient scaling, per-tensor or per-block. The
Parametertype from Phase 2.5 already accommodates (forward_storage = FP8,backward_storage = FP32orBF16master). The work is the scaling-factor pipeline (forward saves max-abs per tensor; backward applies inverse scale) and the cublasLt FP8 GEMM path. Biggest training perf lever on H100+; not in scope for candle-removal but the substrate makes it cheap to add. - 8.5 cuda-mempool-captured graph at variable bs. Once allocator sits over
cudaMemPool_t(Phase 1), capture a single graph parameterized by bs and let the driver pick the mempool block per replay. Reduces VRAM cost of the bs∈{1..64} graph family from 7× to ~1.5× scratch. - 8.6 L2 cache persistence (
cudaAccessPolicyWindow). Lock hot small tensors — RoPE cos/sin tables, RMSNorm scale parameters, GDN A/B recurrent matrices, the active LoRA delta — into the L2 cache. Especially impactful on consumer 4090-class cards with smaller L2 (72 MB) where global-memory traffic dominates over compute. Expected: 5–15 % decode tok/s on bs=1. Per-tier cost: zero VRAM; consumes ~0.5 % of L2 per tensor. Per-tier impact: largest on 16–24 GiB tier (smallest L2 relative to working set); smaller on 80 GiB H100 (L2 already covers more of the working set). - 8.7 CUDA Graph conditional nodes (CUDA 12.4+). Phase 5's 7-graph family (bs∈{1,2,4,8,16,32,64}) sizes at 80 GiB; on 16 GiB it auto-downsamples and the family becomes coarse. Conditional nodes collapse the family to one graph parameterized at replay time, reducing graph-capture VRAM from 7× scratch to 1× scratch and making the bs sweep continuous, not stepped. Replaces the manual key-by-bs lookup in
cuda_graph.rs. Direct enabler of the 16 GiB tier hitting the full bs sweep. - 8.8 Hopper cluster launch + DSM for GDN recurrence. GDN recurrent state crosses CTA boundaries today (one thread block per row, sync via global memory). On SM≥90,
__cluster_dims_t+ distributed shared memory lets neighbor CTAs cooperate without a global-memory roundtrip. Expected: 10–20 % on the GDN-dominant decode path (PROFILING.md recordskiln/gdn/in_projat 19.6 % of forward). Hopper-only; fall-through uses today's kernel. - 8.9 2:4 structured sparsity for the LoRA-frozen base. Marlin-frozen base weights become candidates for 2:4-sparse re-pack during model load (one-shot offline cost). NVIDIA Sparse Tensor Cores deliver 2× FLOPS on A100/H100/RTX 6000 Ada for 2:4-sparse matmuls. LoRA delta stays dense (rank-
rmatmul is too small to benefit). Per-tier: largest win on 16–48 GiB where weights are bandwidth-bound. Small accuracy drop (literature: <0.5 %) compensated by the active LoRA adapter. - 8.10 NVFP4 / MXFP6 forward (Blackwell). Phase 1's DType enum lists
FP4Packed; this item ships the MX-format scaling pipeline — per-block (32-element) FP4 storage with FP8 scales, native Blackwell tensor-core ingestion. Per-tier: 4× memory reduction (2 GiB Marlin → 1 GiB MXFP4) makes Qwen3.5-4B fit on 8 GiB cards for inference and unlocks bigger context everywhere. Backward stays in BF16 master (Phase 2.5 contract). - 8.11 Programmatic Dependent Launch (PDL). CUDA 12.0+: kernel B can start on the SM as soon as kernel A finishes its prologue (not its full body), overlapping launch latency with prior-kernel epilogue. Especially impactful for the many-small-kernel decode path (RMSNorm → matmul → residual → norm → …). Expected: 5–10 % on bs=1 where launch overhead is a measurable fraction of step time.
- 8.12 FlashAttention-3 path (Hopper/Blackwell, CUDA). Today
kiln-flash-attnuses cutlass FA2-style kernels. FA3 adds warp-specialized async (producer/consumer split of TMA loads vs WGMMA math) plus a persistent-tile schedule that hides prologue/epilogue under math. Expected: ~1.5–2× over FA2 on H100 at the long-seq prefill shapes Qwen3.5-4B hits at 32K-128K context. Phase 5's "persistent attention" line gets its concrete kernel here. Per-tier: Hopper-only win at first; fall-through is the existing FA2 path. Reads/writes through paged-KV via the Phase 3 slot-tensor seam (preserved byte-for-byte). - 8.13 KV cache compression beyond FP8 (KIVI int4 + ScissorHands/H2O eviction). FP8 K/V (Phase 3) gives 2× over BF16; KIVI gives another 2× (int4 K, FP8 V with per-channel quantization) on top. ScissorHands/H2O are eviction policies — drop low-attention-score KV slots from cache, recompute on demand. For Qwen3.5-4B at 128K context, the KV cache currently dominates VRAM on every tier; this halves it again. Per-tier: largest absolute win on 16–24 GiB where context length is the binding constraint. Composes with
PagedKvCache::new_with_fp8(Phase 3) as a third storage variant; the slot-tensor interface stays the same. Accuracy bound: KIVI literature reports <0.5% perplexity delta; gate with a Qwen3.5-4B eval-suite parity check. - 8.14 GPUDirect Storage / kvikIO async weight load. Cold-start Qwen3.5-4B BF16 weight load is ~3-8 s today via
memmap2+spawn_blocking(crates/kiln-model/src/weights.rs). GDS / kvikIO does NVMe-to-VRAM DMA bypassing the CPU/page-cache hop. Per-tier: most visible on 16-48 GiB tier where the user's iteration loop is "load → bench → tweak → reload"; less visible on 80 GiB where the server is long-running. Composes with the on-disk transposed-weight cache (transposed_weight_cache.rs) — both bypass the page cache. Falls through to the existing mmap path where the kernel/driver doesn't support GDS. - 8.15 NVRTC runtime kernel fusion for shape-tail epilogues. cublasLt epilogues are a fixed menu (bias, activation, gelu, ...); shape-dependent fused tails (e.g., "matmul + RMSNorm + residual + RoPE" specialized to Qwen3.5-4B's exact head-dim and rope-base) are not in the menu.
kiln-codegenis a runtime kernel-source builder that emits PTX via NVRTC, keyed on the same{shape, dtype, layout}tuple as the autotune cache; on Vulkan/Metal the equivalent is SPIR-V / MSL generation through the existing pipeline cache. Once written, the cached kernel persists with the autotune cache (Phase 2 pre-shipped variant). The point is to chase fusions cublasLt structurally cannot do for us, not to reinvent cublasLt. - 8.16 NVML thermal/power monitor + dynamic batch sizing (laptop tier). RTX 4070 Laptop / 4080 Laptop 16 GB SKUs sustained-throttle aggressively under chassis thermal limits.
kiln-thermalpolls NVML fortemperatureandpower_draw; the scheduler responds by shrinkingmax_batch_tokenstoward the bs=1 floor before the GPU drops clocks. Without this, bench numbers on laptop tier are non-reproducible — and the headline 16 GiB-tier numbers are gated on the laptop slot in Phase 9. Fallback: no NVML → noop (treat as desktop tier). - 8.17 Hand-shaped persistent megakernel for Qwen3.5-4B's exact dim quadruple (specialization of 8.2). The persistent MLP megakernel in 8.2 is parameterized — re-spell it for Qwen3.5-4B's (2560, 18432, 18432, 2560) gate/up/down dims as a single hand-tuned kernel. Register budget, shmem tiling, and warp-specialization schedule are baked against the known shape. Composes with 8.10 (NVFP4) and 8.11 (PDL); supersedes the parameterized 8.2 variant on tier-1 hardware. The kernel zoo grows by one file; the perf delta is the part 8.2's parameterization left on the table.
- 8.18 GPU-side BPE tokenizer for the Qwen3.5-4B vocabulary. Specialized to vocab=152064 and the fixed merge table. Eliminates host tokenization on very-long prompts (today the prefill upload includes a CPU-side BPE pass that scales with prompt bytes). Per-tier: matters most when a server fields long-context requests at high QPS. Read-only kernel — emits token ids directly into the pinned upload buffer.
- 8.19 Closed-loop GPU decode for greedy. Combine Phase 4's on-device stop-condition (already promoted to Phase 4 gate as item 8.3) with Phase 8.1 persistent attention into a single megakernel that loops N decode steps internally — D2H is a 1-bit "should_stop" signal per request per N iterations. The bs=1 hot loop becomes "launch megakernel → poll 1 bit." This is the inherent decode-latency floor on greedy — the absolute minimum Qwen3.5-4B can take per token on a given GPU. Per-tier: largest absolute win on consumer 16-24 GiB cards where launch overhead is a measurable fraction of step time; small relative win on H100 where compute already saturates.
- Persistent decode kernels (single kernel servicing many decode steps without re-launch) — covered by 8.1+8.2+8.19
- Multi-stream forward across QKV, gate+up, attention output projection (planner-driven)
- Speculative-decode draft/target sharing a single graph capture (extends Phase 4.5 + Phase 5)
- Tuned cublasLt / MPS / Vulkan epilogues for fused norm + matmul + activation
Phase 9 — Bench-gate enforcement
Runs in parallel with Phases 1-7; merges into the Phase 7 gate. The numeric DoD gates are aspirational without a PR-time enforcement mechanism — .github/workflows/opd-bench-gate.yml:24-29 has the pull_request trigger commented out and perf-regression-nightly.yml:21 is cron-only.
- Either (a) bring the self-hosted A6000 runner online and uncomment
pull_requestinopd-bench-gate.yml, or (b) ship a CPU-only smoke variant of the gate that synthesizes a partial bench JSON and runs the existingbench-results/check_opd_regression.py+check_sft_train_regression.pyagainst the documented schema - Reuse
bench-results/regression/README.mdschema verbatim —schema_version: 1,pinned_at_commit,commentfor intentional moves, ±10 %secs_per_step, ±15 %peak_vram_mb. Do not reinvent. - Add a "copies per token" metric (from Phase 1's copy-counter instrumentation) to the gated schema with its own tolerance band
- Add a "decode bs=64 tok/s vs vLLM" metric with a hard floor at the post-migration target
- Pin the Phase 0 pre-migration baseline (committed at
bench-results/pre-migration-baseline/) as the per-metric floor inbench-results/regression/. The "≥ baseline" gates in the DoD are unenforceable without this commit — wirecheck_opd_regression.py+check_sft_train_regression.pyto compare against the pinned baseline, not the previous PR. - Per-tier gates (the 16 GiB → 80 GiB story). Independent regression floors per VRAM tier:
- 16 GiB tier — CPU smoke profile on PR-time + (when a 16 GiB card is reachable in the matrix) RTX 4060 Ti / 4070 Laptop slot
- 24 GiB tier — RTX 4090 / RTX 3090 (nightly)
- 48 GiB tier — A6000 / L40S (PR-time, self-hosted)
- 80 GiB tier — A100 80 GB / H100 (nightly)
- A merge that improves 80 GiB throughput but regresses 16 GiB tok/s or causes 16 GiB SFT to OOM is blocked. Without per-tier gates the consumer floor regresses silently as headline 80 GiB numbers improve — the inverse of what "your model gets better on hardware you already own" requires.
- Live serve+train concurrency gate. Once Phase 2.7 lands, the gate also enforces: training-while-serving produces byte-identical loss curves vs serial training+serving; serving p99 latency under concurrent training within 1.2× the no-training baseline at every VRAM tier. Catches the regression mode where someone removes stream priorities or breaks the
Parameter::versionepoch contract. -
KILN_DETECT_ANOMALYNaN/Inf trap wired through the autograd tape. Off by default (cost is ~5% per step); on under the training parity tests in CI. Every backward op assertsis_finite()on its output and panics with the op's tape position on first violation. Today the only finiteness check iskiln-train's reward-stats receipt warning after the step. With the trap, training corruption surfaces at the kernel that produced the first non-finite value, not 100 steps later when loss diverges. Composes with the in-place tape invariant (anti-pattern 16) — both are tape-position-aware safety nets. -
KILN_DETERMINISTIC=1envelope. Single flag forcing the deterministic codepath for every "deterministic by construction" item from Phase 0's determinism stance:CUBLAS_WORKSPACE_CONFIG=:4096:8, the deterministic-atomicAdd embedding bwd variant, the deterministic reduction-tree softmax/RMSNorm bwd, the warp-shuffle-free reduction in cross-entropy bwd. Each backend supplies the deterministic variant of any op flagged "tolerance-bounded" in Phase 0. CI runs training parity tests under the envelope and validates bit-reproducibility across two runs at the same seed. The flag is the user-facing contract for RL / SFT iteration reproducibility — "I want this run to match yesterday's run" becomes one env var, not a doc-read. - Per-tier coverage of laptop 16 GiB (RTX 4070 Laptop / 4080 Laptop 16 GB). The 16 GiB tier in the gate matrix above must reach a laptop SKU, not only a 4060 Ti desktop. Thermal-throttle behavior on laptops is structurally different (sustained throttle, not boost-and-fall); Phase 8.16's NVML monitor is gated here. Without a laptop slot, the headline 16 GiB numbers are achievable on desktop and unachievable on laptop — and the consumer pitch breaks on the more-numerous SKU.
Migration mechanics
- Feature-flag per backend per phase.
KILN_USE_KILN_TENSOR_MLP_CUDA,KILN_USE_KILN_TENSOR_ATTN_METAL, etc. Default off until that backend's parity tests pass in CI and bench-results shows no regression on tier-1 GPUs. - Parity tests every PR. Every kiln-tensor op A/B against candle on identical inputs, per backend, until candle is removed. After Phase 7, CPU
kiln-tensoris the canonical reference. - PRs are small and individually revertable. No single PR straddles two phases or two backends.
- Bench regression halts merge.
scripts/bench-fused-mlp-gate-up-prefill.shand the broaderbench-results/matrix are the contract. The numeric gates in the Definition of done are objective. Phase 9 wires the actual PR-time enforcement. - Forward.rs does not change shape during the migration. All restructuring happens behind the
BackendRuntimetrait atcrates/kiln-model/src/backend/mod.rs:114.
Background context (artifacts and references)
- Recent MLP fusion work: PRs
e44c2c84(gate||up cache),2a44953a(packed silu*mul kernel),da1b0467(bench script). Per-stage analysis on RTX 4090 Laptop in the second commit message — reference for the cuBLAS algo regression we hit. - Recent prefix-cache / long-context tuning: commits
cef1ea84,86069da2,8162fdd8,b7cb4b52— the scheduler interface that Phase 3's tensor-runtime contract must preserve. - Vendored candle locked path:
vendor/candle-core/src/cuda_backend/mod.rs:2625—gemm_strided_batched_bf16, single hard-codedCUBLAS_GEMM_DEFAULT_TENSOR_OP, no cublasLt. Equivalent locks exist in candle's Metal backend. - Vendored candle shared cuBLAS handle:
vendor/candle-core/src/cuda_backend/device.rs:40,247,256,280— what Phase 1's kiln-owned handle replaces. vendor/candle-core/src/custom_op.rs—CustomOp1/2/3, the fifth candle subsystem (autotune-shimmed by every fused kernel crate).- A/B bench harness:
scripts/bench-fused-mlp-gate-up-prefill.sh— reuse for every kiln-tensor port. - Existing per-backend trait seam:
crates/kiln-model/src/backend/mod.rs:114(BackendRuntime).kiln-tensorslots in below this trait; forward.rs continues to call backend methods. - Bs>1 cuda-graph gap doc:
crates/kiln-model/src/cuda_graph.rs:33-96— the proposed structure, the vLLM tok/s gap, and why it hasn't landed under candle. Dead-code stub:cuda_graph.rs:178. - On-device sampler (already exists; Phase 4 preserves):
crates/kiln-model/src/sampling.rs:5-110,264. - Paged KV cache (deeply candle-typed today):
crates/kiln-model/src/paged_kv_cache.rs:11-150,232-340. - Scheduler + prefix cache (already candle-free; the contract):
crates/kiln-scheduler/src/scheduler.rs,crates/kiln-core/src/prefix_cache.rs. - MTP + speculative (entire Phase 4.5):
crates/kiln-model/src/speculative.rs,mtp_debug.rs, tests atcrates/kiln-model/tests/mtp_byte_eq.rs. - Optimizer state keyed on candle TensorId:
crates/kiln-train/src/trainer.rs:555,592,599,632. - Quantization + weight bookkeeping that collapses into
kiln-param:crates/kiln-model/src/{packed_weight_registry,transposed_weight_cache,marlin_proj,fp8,adapter_merge,lora_loader}.rs. - DeviceBuffer half-built abstraction (extend, don't duplicate):
crates/kiln-core/src/device_buffer.rs:25-90. - Bench-gate enforcement plumbing:
.github/workflows/opd-bench-gate.yml,.github/workflows/perf-regression-nightly.yml,bench-results/check_opd_regression.py,bench-results/check_sft_train_regression.py,bench-results/regression/README.md. - Vulkan-as-template:
crates/kiln-vulkan-kernel/src/vk_tensor.rs(500 LOC) — Tensor typecrates/kiln-vulkan-kernel/src/vk_autograd.rs(173 LOC) — tape walkercrates/kiln-vulkan-kernel/src/vk_ops/— 34 backward op implementationscrates/kiln-vulkan-kernel/src/buffer_pool.rs— persistent buffer patterncrates/kiln-vulkan-kernel/src/cmd_batch.rs— command batching patterncrates/kiln-vulkan-kernel/src/decode_resident_pool.rs+crates/kiln-model/src/vk_decode_resident.rs— resident slot-ring (1.04 → 29 tok/s); Phase 5's templatecrates/kiln-vulkan-kernel/src/vk_paged_kv_cache.rs— paged KV cache pattern
🤖 Generated with Claude Code
Seam-flip progress (forward.rs candle→kt training-tape ops) — branch ce/1082-forward-flip-v2
The hot-path training forward was a candle island: each op bridged kt→candle→kt to record its backward on the kt tape. These are being flipped to kt-native try_tape_*_kt recorders (no round-trip). forward.rs candle-bridge adapter calls: 36 → 0 — the entire training-tape forward is kt-native. Each ticked op is validated against the deterministic FD grad test + the 41-test tape_forward_parity suite + decode-parity.
- SiLU (
try_tape_silu_kt) —4bcd155a - residual-add (
try_tape_add_kt) —1b0a881a - RoPE split-half (
try_tape_rope_kt) —1b0a881a - matmul (
try_tape_matmul_kt) —1e4294ad - embedding (
try_tape_embedding_kt) —1e4294ad - SwiGLU (
try_tape_swiglu_kt) —a9d41497 - elementwise-mul (
try_tape_mul_kt) —a9d41497 - transpose (
try_tape_transpose_kt) —f26b11d2 - reshape (
try_tape_reshape_kt) —f26b11d2 - GQA head-expand (
try_tape_gqa_expand_kt) —e9e609fb - flash-attention (
try_tape_flash_attn_kt) —27b4e884 - cast (CastCompositeBackward → kt) —
651bac03 - narrow (NarrowCompositeBackward → kt; zeros+cat adjoint) —
52a5e627 - GDN L2-norm-scale (GdnL2NormScaleBackward → kt) —
369655e4 - GDN gated-RMSNorm (GdnGatedRmsNormBackward → kt) —
ce38bbbc - naive-SDPA fallback (SdpaBackward → kt; + unblocked downstream transpose/reshape) —
cdbc28b7 - LoRA delta-add (
try_tape_lora_add_kt) —8d38dadb(Var grads preserved; FD+convergence validated) - LoRA linear (
try_tape_lora_linear_kt, 2 sites incl. lm_head) —820fe975(FD samples lora_B + convergence both pass) - causal-conv1d prefill (2 sites) —
bf7edc6c(reused the existing kt bwd kernelcausal_depthwise_conv1d_bwd_input_kt; FD+convergence validated)
Supporting infra landed this stretch: both kt-native CUDA weight loaders (Tensor::from_raw_bytes_on), the tape_forward_parity suite re-enabled (41/41), and the FD grad gate hardened flaky→deterministic (seeded init + non-finite-FD skip).
After the final 3 op-flips: delete the candle try_tape_*_cuda adapters + migrate the parity tests off them; then the backend/{mod,cuda,cpu}.rs DType/Device bridges; metal/vulkan; candle feature-gated out of the cuda build; finally drop candle from Cargo.toml + rm vendor/candle-core (DoD items 97–101 become tickable then).
Adapter-deletion progress (candle try_tape_*_cuda → kt twins, branch ce/1082-forward-flip-v2)
The seam flip routed every hot-path op through a kt twin; the candle adapters are now dead and getting deleted (parity tests migrated to the _kt twins; cargo nextest parity suite green on A6000 at each step).
- zero-caller adapters (6): matmul/add/transpose/reshape/gdn_l2/gdn_gated candle adapters — deleted, parity 40/40
-
try_tape_silu_cuda— deleted (incl. connected matmul→silu→add chain test migrated) -
try_tape_rope_cuda/try_tape_embedding_cuda/try_tape_swiglu_cuda—331825ee, parity 40/40 -
try_tape_lora_add_cuda—d7a159db(test migrated totry_tape_lora_add_kt; reshape-framed fused chain, analytic A/B grad checks intact) -
try_tape_flash_attn_cuda—d7a159db(→try_tape_flash_attn_kt) -
try_tape_sdpa_fallback_cuda—d7a159db(→try_tape_sdpa_fallback_kt) -
try_tape_rms_norm_cuda—d7a159db(dead: production + test already use the kt-nativeforward::rms_normrecorder) -
try_tape_gdn_recurrent_cuda→try_tape_gdn_recurrent_kt—d7a159db(dropped its sole candle bridge, the kt→candle return copy) -
try_tape_cross_entropy_cuda— removed with the candle-island / DoD-100 removal (24e9b5d0); nofn try_tape_cross_entropy_cudadefinition remains in the tree (verified 2026-06-01).
17 of 17 candle tape adapters deleted; full parity suite (40/40) green on A6000 after each batch. All dangling intra-doc links to deleted adapters neutralized; stale cross-crate doc/comment refs in kiln-autograd::tape_scope and kiln-train::opd_candle_shim refreshed.
✅ DoD 100 LANDED (24e9b5d0, 2026-06-01): the CUDA runtime build is candle-free. cargo tree -p kiln-server --features cuda -e normal has zero candle; build green on A6000. Across this epic's commits the forward.rs candle island (kt_logits_to_candle/candle_to_kt_activation), the trainer authoritative-scope + cross_entropy coupling, the backend/{mod,cuda,cpu}.rs + cd_types.rs bridges, and the kt-native weight loaders all went kt-native; the finale (24e9b5d0) made candle-core/nn optional and dropped them from the cuda feature. Remaining candle in the cuda dep graph is now only kiln-server's [dev-dependencies] candle-core (integration-test reference; cargo test only, not cargo build) → next CUDA cleanup is gating those tests + dropping the dev-dep (DoD 98). Beyond that the solo-CUDA frontier is Phase 6b (consolidate cuda_train.rs onto kiln-autograd, delete the sync_to_candle round-trip) and Phase 5 (bs>1 batched cuda-graph — the kiln 1181 vs vLLM 1907 tok/s headline).
DoD 101/102 (candle-free metal/vulkan): blocked on macOS/Vulkan CI (cannot validate metal.rs ~1184 candle lines on a linux RunPod A6000) — surfaced to Eric via an approval request for the infra decision.
Activity
[-]epic: migrate off candle to in-house kiln-tensor over cudarc + cublasLt[/-][+]epic: migrate off candle to in-house kiln-tensor (CUDA + Metal + Vulkan)[/+]phase 0.1: audit candle API surface (#1082) (#1087)
phase 0.6: audit multi-GPU seam (#1082) (#1088)
phase 0.7: audit preserve-list (NVTX / KILN_* / BackendRuntime) (#1082)…
phase 0.2: audit CustomOpN call sites + propose kiln-tensor shape (#1082
phase 0.5: audit DType usage + propose kiln-tensor::DType enum (#1082) (
phase 0.3: document determinism stance in PROFILING.md (#1082) (#1092)
phase 0.4: per-op parity tolerance matrix (#1082) (#1093)
phase 0.8: kiln-blas crate skeleton + cublasLt MLP probe (#1082) (#1094)
phase 0.9: Vulkan MLP gate||up probe example (#1082) (#1095)
phase 0.10: pre-migration baseline capture harness (#1082) (#1096)
phase 1.1: kiln-tensor crate scaffold + Error/Result/bail!/ensure! (#…
phase 1.2: kiln-tensor DType enum (#1082) (#1098)
424 remaining items
ericflo commentedon Jun 1, 2026
Phase 2.7 progress —
Parameter::versionepoch counter foundation landed (PR #1437, merged65a8902).The atomic-counter half of the "
Parameter::versionepoch counter" box is now done + CI-validated (candle-freekiln-param/kiln-optimjob, no GPU):epochis nowArc<AtomicU64>;current_epoch()loadsAcquire.bump_epoch(&self)— atomic saturating add (monotonic version;&selfso it composes with a concurrent read path).version_handle() -> Arc<AtomicU64>— lock-free reader handle for the serving thread (the primitive the "replace the GPU RwLock with a Parameter-versioned read path" box builds on).snapshot()detaches the epoch into a frozen counter (stable version for eval-while-training / on-policy-GRPO snapshots).OptimStepimpls (AdamW/Sgd/Lion/Muon) bump at end-of-step; cross-optimizer CI guard added.Box intentionally left unchecked — the box also requires
Parameter::forward(epoch_hint)with double-buffered quantized-form requant (48 GiB+) / bounded-stall fallback (16 GiB) and the per-tierARCHITECTURE.mdmatrix. Those are GPU + doc work still outstanding; the atomic counter above is their prerequisite.ericflo commentedon Jun 1, 2026
box-102 keystone fixed: bs=1 CUDA-graph paged decode is coherent again — merged
c4fdf08e(PR #1439).The bs=1 captured-graph decode path was producing garbage on replay (a regression surfaced during the candle→kiln-tensor migration). Root-caused to TWO bugs and fixed both; validated on the production serve path (L40S):
LmHeadMode::HiddenOnly(transformer+final_norm → graph-stable hidden; lm_head out of the graph) and run lm_head eagerly on the replayed hidden. Captured 32-layer transformer (the decode win) preserved.KILN_DEBUG_LAYER_NORMS(the SAMESTEP probe) perturbs decode; validate on the production path.Validation: all prompts coherent, deterministic run-to-run; graph genuinely replays (185 replays, 3 captures/3 requests, 2 boundary evictions, 0 replay failures), not degrading to eager. Vulkan/CUDA-candle-free/cargo-deny CI green.
Not ticking a box — this restores the assumed-working bs=1 graph decode that the Phase-5/Phase-9 boxes build on. It now unblocks the bs=1 decode perf gate ("CUDA decode bs=1 ≥ baseline") and the Phase-5 capture work (freeze-pointers validated for bs=1; bs>1 still pending). Diagnostic probes (
KILN_FORCE_EAGER_DECODE,KILN_BOX102_TOKPROBE,KILN_ARENA_FORCE_ZERO,KILN_DEBUG_LAYER_NORMS) shipped env-gated (default-off).ericflo commentedon Jun 1, 2026
🎉 Candle is gone from kiln — DoD candle-removal complete (
235dc0ca)The in-house
kiln-tensorsubstrate now fully replaces candle across CUDA, Vulkan, and Metal:[dependencies]/[dev-dependencies]in any kiln-* crate (boxes 98/446) ✅vendor/candle-core/deleted +[patch.crates-io]entry removed (boxes 99/445) ✅cargo tree --features cuda -i candle-core→ did not match any packages; candle absent fromCargo.lockkiln-trainvk_train_smoke 39/39 under nextest (vulkan training candle-free)The candle removal proceeded crate-by-crate, lib-first then dev/test: kiln-vulkan-kernel → vulkan lib → kiln-model (legacy-candle-parity) → kiln-train → kiln-kt-bridge → workspace + vendor.
Residual cleanup (follow-ups, not blocking — dead/test code not compiled by any green build or CI gate):
kiln-model/src/backend/metal.rs: ~510 candle refs inside a#[cfg(any())]dead block (preserved for a future kt re-port)kiln-model/src/backend/vulkan.rs:#[cfg(test)]module candle (the test-oracle de-candle pass)cargo nextest(process-per-test) — single-processcargo testaccumulates Vulkan substrate state across testsericflo commentedon Jun 2, 2026
Phase 5 — bs>1 batched CUDA-graph decode: LANDED (PR #1440)
The
bs>1cuda-graph capture blocker is cleared. The batched path now captures + replays correctly and is opt-in.What landed (ports the box-102 bs=1 fixes to the batched twin):
is_batched_enabled()gated on stable paged metadata —CudaBatchedGraphKeynever encodes seq_len/block_table, so the batched graph always replays within a 128-tok KV bucket; that is only correct when the kernel reads block_table/seqused_k from the refreshed graph-stable buffers. Without it the replay reads a stale step-0 block table. The gate falls back to eager (correct) when stable metadata is off.KILN_DEBUG_BATCHED_HIDDEN=1per-row hidden-fingerprint probe.Enable:
KILN_CUDA_GRAPHS_BATCHED=1 KILN_CUDA_GRAPH_STABLE_PAGED_METADATA=1(+KILN_CUDA_GRAPHS=true).Validation (A6000, Qwen3.5-4B, W4A16): bs=4 output topically correct per prompt, deterministic within a run. Aggregate decode throughput, concurrent distinct-prompt load:
On the byte-coherence question (resolved as a non-bug): greedy bs=N output is not byte-identical to bs=1, but neither is the eager batched path (it diverges from bs=1 on every row too). Root cause: the dynamic batcher orders rows by job arrival timing and batched matmuls are not row-position-invariant, so equal-seq-len rows in different pool positions get tiny FP differences -> occasional greedy flips after the row-agnostic prefix. This is inherent dynamic-batching non-determinism (vLLM has it), independent of graph capture. The graph faithfully reproduces the batched forward for a given row order.
Still open for the
CUDA decode bs=64 >= vLLM on L40Sbox: the absolute parity number (>=1907 tok/s) is NOT yet proven — the 2x above is an A6000 burst that includes prefill+ramp, not an L40S steady-state decode-only measurement. Follow-ups: (1) steady-state decode-only bs=64 bench on L40S vs vLLM; (2) flip defaults on (needs bs=1 validated under stable-paged-metadata + a CI perf/coherence gate); (3) stable-sort batch rows by request id so a single/v1/completions/batchcall is reproducible; (4) bucket round-up[1,2,4,8,16,32,64].Also landed this session:
deploy/runpod/kiln-setupSIGPIPE fix (866fe6f2) —sccache --show-stats | headaborted setup before writing/root/.kiln-build-env, making every fresh pod build cold (~13 min).ericflo commentedon Jun 2, 2026
L40S bs=64 parity bench — two real blockers found (correcting the earlier "2×" framing)
Ran the canonical
scripts/bench-concurrent-batch.pyon L40S (kiln-runpod image, CUDA 12.4, W4A16/Marlin confirmed active) to get a number comparable to the published baseline (eager 1181.4 / NO_REPLAY 1401.2 / vLLM 1906.8 @ bs=64). I could not measure parity — the batched path does not yet deliver at the target bs=64:OOM at bs=64 in the batched-graph path.
cat batched recurrent state for GDN layer N: alloc_zeros(19922944) failed: CUDA_ERROR_OUT_OF_MEMORY, then context poison → cascading failures (REPLAY: 1/64 succeed, 63 errors). Root cause: KV cache auto-sizes to 25.5 GB (inference_fraction 0.7), and the batched-graph resident footprint (persistent pools + captured graphs across buckets 1…64) plus a per-step GDN-recurrentcat(a fresh ~19.9 MB batched buffer allocated every decode step × layers) exceed the ~11 GB leftover. The eager path doesn't OOM (no resident graph buffers). Fix paths: lower the KV inference_fraction, cap the resident graph-cache footprint, and — the real inefficiency — make the batched GDN recurrent state a persistent buffer instead of cat-allocating it every step.The decode batcher isn't forming wide batches in this setup. Eager bs=64 measured 22 tok/s vs the published 1181 (≈50× off), with TTFT 38–42 s (requests queuing ~serially, not batching). So this environment doesn't reproduce the published baseline at all — reproducing 1181 (debugging batcher engagement /
KILN_MAX_DECODE_BATCH/ any regression vsf3a5f95e) is a prerequisite to any parity claim.Net: the bs>1 cuda-graph capture/replay (PR #1440) is correct and works at bs≤4, but bs=64 perf parity is not achieved. The earlier A6000 "~2×" was an HTTP-burst harness that underestimates and isn't the canonical bench. The
CUDA decode bs=64 ≥ vLLMbox stays unchecked; the next work is (a) fix the bs=64 OOM (VRAM sizing + persistent batched GDN recurrent buffer), and (b) restore wide-batch engagement so the canonical bench reproduces ~1181 eager, then measure the replay path against it.ericflo commentedon Jun 2, 2026
bs=64 parity is gated by a batcher-concurrency regression on
main(not the cuda-graph)Ran the exact canonical bench (
bench-concurrent-batch.py --max-tokens 128 --mode concurrent --warmup, serveKILN_W4A16=1 KILN_CUDA_GRAPHS=true) on both L40S and A6000 atmain(d2f0f1f). Current main does not reproduce the documented concurrency scaling:bs=1 is comparable (71 vs 84), but multi-request concurrency scaling is broken — throughput stays flat (~70–97) regardless of batch size, and TTFT balloons to ~38 s (requests serialize instead of co-batching into wide decode batches). This affects the eager path too, so it is independent of the bs>1 cuda-graph — it's a decode-batcher/scheduler concurrency regression on
mainsomewhere between2d9d4fc4andd2f0f1f3.Implication: the
CUDA decode bs=64 ≥ vLLMbox can't be measured — let alone hit — until this regression is fixed. The next step is a git-bisect of the batcher concurrency scaling (reproduce eager ≈498 on A6000 first), then measure the replay path against it. (Separately, the batched-graph still OOMs at bs=64 even withKILN_INFERENCE_MEMORY_FRACTION=0.45— the graph's resident footprint isn't accounted for by the KV auto-sizer; that's a second, smaller fix.)PR #1440's contribution stands on its own: it took the batched cuda-graph from HTTP-500/broken at bs≥2 (documented 2026-05-26) to correct at bs=4 (capture+replay coherent, deterministic within a run). The perf-at-bs=64 win is blocked downstream by the batcher regression above.
ericflo commentedon Jun 2, 2026
Eager bs>1 paged-decode crasher — FIXED (PR #1445, merged)
Root-caused via a multi-agent workflow + adversarial verification. The vendored FA2 split-KV paged-decode kernel reads each
kBlockN-token K/V tile as one physically-contiguous gather from a singleblock_tableentry (it never consults the intervening entries — it assumes intra-tile page contiguity). The bs=1 path verifies this and falls back to a gather when violated; the eager batched path did not. Under concurrent dynamic membership theBlockManagerfree list recycles finished requests' blocks out-of-order → a row's tile pages become non-adjacent → the kernel's strided read lands on a foreign page / off a large pool →CUDA_ERROR_ILLEGAL_ADDRESS.This explained every observation: crashes on large-pool GPUs (A6000 48 GB, A100 80 GB) but not 24 GB (4090) — it's the pool size, not the arch; concurrent dynamic membership only (static batches never free mid-flight → no fragmentation); eager-only (the graph path serializes); and it masks under all instrumentation (any slowdown stops the churn).
Fix:
batch_has_noncontiguous_kv_tiles()(mirrors the bs=1 check) routes non-contiguous batches to the existing contiguity-safe per-row loop; contiguous batches keep the fast contiguous-batch path. + a CPU unit test. Validated on an A100: the load that gave ILLEGAL=107 + all-500 pre-fix now runs ILLEGAL=0, healthy.Graph-path bs=64 perf — diagnosed (not a graph bug)
The cuda-graph batched decode is correct and fast for stable batches: 1235 tok/s @ bs=64 on A100, captures=2 / replays=124 (it replays as intended). The earlier "151 tok/s" concurrent number is serial inline prefill on the batching-engine actor thread (the 64 prompts prefill one-at-a-time → the decode batch never fills); the static
/v1/completions/batch(all prefilled together → bs=64 lockstep) hits 1235. So the concurrent perf lever is batched/chunked prefill, not the graph. (1235 A100 ≈ kiln baseline; the residual to vLLM 1907 is deeper Phase-8 perf.)Status of Phase 5 sub-items
ericflo commentedon Jun 2, 2026
Phase 5 concurrent-decode investigation (L40S sm_89, main
220a4032)Measured the bs=64 path end-to-end on L40S and root-caused why concurrent throughput is far below the documented
1181 tok/s @ concurrency 64. The "parity gap" is not one thing — it's four layers, now precisely characterized with hard data.Measured (canonical harness
scripts/bench-concurrent-batch.py --mode concurrent, greedy, max_tokens=64)Per-request latency grows ~linearly to n=32 (no co-batching) then catastrophically cliffs at n=64. Static
/v1/completions/batch(stable membership) decodes ~990 tok/s — so the decode kernel is fine; the collapse is in dynamic batching.A/B proof (env kill-switch on the contiguity guard)
force_row_loop_for_contiguity)Root cause (four layers)
force_row_loop_for_contiguity(generate.rs:3707, from cuda: fix eager bs>1 paged-decode illegal-address under concurrent load (non-contiguous KV tiles) (#1082) #1445) is all-or-nothing. If any row's KV tiles are non-contiguous it serializes the entire bs=N batch into N sequential single-row forwards. Under concurrent finish→free→re-admit the BlockManager free-list fragments → the detector fires on the whole batch → permanent serialization → the n=64 cliff (the 8.4× recovery when disabled). The detector is accurate (it matches the bs=1 reference inforward.rs::try_flash_attn_paged_decode~18637, K_BLOCK_N/8-page contract) — disabling it just feeds non-adjacent pages to the FA2 split-KV kernel, which reads the wrong K/V (silently wrong attention; no crash on a 48 GB pool, but incorrect output).batched_state_cachemisses under dynamic membership in the decode-batcher.Separate live P0: eager crasher on the non-greedy path
The non-greedy batched path (
temperature≠0→try_contiguous_batched=false→ generate.rs:3332 →forward.rs:24682 model_forward_paged_batched_decode_hidden) has no contiguity guard at all — #1445 only guarded the greedy path. Under fragmented pools this feeds non-adjacent pages to FA2 →CUDA_ERROR_ILLEGAL_ADDRESS→ heap-corruption cascade (reproduced: 194×alloc_zerosfailures on L40S).Fix plan (scoped, multi-PR)
Items 1–4 recover concurrent throughput toward the kernel ceiling; item 5 raises the ceiling. Cleanup (vestigial
KILN_USE_KILN_TENSOR_*flags + themetal.rsdeadcfg(any())candle block) is done in220a4032.ericflo commentedon Jun 2, 2026
PR #1446 — per-row contiguity partition (correctness foundation)
Implemented + validated on L40S the first concrete fix from the plan above: PR #1446 replaces #1445's all-or-nothing
force_row_loop_for_contiguity(which serialized the whole bs=N batch when any row fragmented → the n=64 cliff) with a per-row partition — row-loop only fragmented rows, batch the contiguous majority. Strict superset, crash-safe, unit-tested, coherent output, 0 ILLEGAL on concurrent bs=64.Refined root cause (sharper than the comment above): the n=64 collapse is not pool saturation — at n=64 the pool is <1% full. It's interleaved concurrent allocation: 64 requests each grow their block tables one block at a time through the FIFO free list, so every request ends up with strided (non-adjacent) blocks (A: 0,64,128…; B: 1,65,129…). So at n=64 every row fails the FA2 intra-tile contiguity check → the partition correctly row-loops all → n=64 perf is unchanged by the partition alone.
Therefore the n=64 perf lever is one of:
block_table[c*pages_per_chunk]-is-contiguous assumption; read each page's entry — what vLLM's paged attention does). This removes the contiguity requirement entirely → no row-loop, no crash, no fragmentation sensitivity → recovers n=64 to the ~94 tok/s scheduler ceiling, then the 2nd-bottleneck + kernel levers from there. The real lever. CUDA work on the vendored FA2.#1446 is the crash-safe foundation; the FA2 per-page-gather kernel is the next high-value CUDA task.
ericflo commentedon Jun 2, 2026
block_size=64 fix attempt — EAGER validated (n=64 11→147), graphs-on BLOCKED
Pursued the n=64 perf lever: raise KV
block_size16→64 so each FA2 split-KV tile (kBlockN=64 for hdim256) is exactly one physical page → the kernel's per-tile block_table lookup is per-page-correct → the intra-tile contiguity requirement vanishes (no cutlass surgery). Branch:wip/1082-blocksize64-graphblocked.Validated on L40S (eager,
KILN_CUDA_GRAPHS=false): coherent output, 0 ILLEGAL, concurrent n=64 = 147 tok/s (was 11 with the #1446 row-loop — 13×). Smoke check passes. So block_size=64 correctly removes the fragmentation row-loop for the eager path.BLOCKED — graphs-on (production default
KILN_CUDA_GRAPHS=true): the bs=1 CUDA-graph capture under concurrency still hitsCUDA_ERROR_ILLEGAL_ADDRESSat block_size=64 ("capture failed: sync after first captured-graph launch"). Key narrowing:FA2_KBLOCK_N=64as forward.rs — necessary for consistency, but it did not resolve the crash).Not merging (would break production concurrent decode). Next step: hands-on
CUDA_LAUNCH_BLOCKINGdebugging of the concurrent bs=1 graph capture path at block_size=64 to identify the exact OOB site, then complete the fix → expect n=64 → ~1181 (eager baseline), then bs>1 graph replay (#1440) toward vLLM 1907.Kill-switch/rollback unchanged: PR #1446's row-loop is the crash-safe net at block_size=16.
ericflo commentedon Jun 2, 2026
block_size=64 graph crash = Heisenbug race (stable-metadata fixes it); concurrent n=64 ceiling is ~100-147 (serial-prefill, not block_size)
Followed the block_size=64 lever to ground. Two findings:
1. The graphs-on crash at block_size=64 is a timing RACE, not a static OOB. With
CUDA_LAUNCH_BLOCKING=1, 8 concurrent requests all succeed (0 ILLEGAL) — serializing the race away. The captured bs=1 graph freezes a transient block table that races with concurrent block recycling under async n=64 → reads a recycled page → ILLEGAL. (The repeat-last pad fix70a410ecis a correct safety improvement but does NOT fix a race.)KILN_CUDA_GRAPH_STABLE_PAGED_METADATA=1fixes it — its persistentblock_table_bufferis refreshed in place per replay, so the graph reads the current table, no stale-frozen-table race. Validated A6000: graphs-on + stable + block_size=64 → coherent, 0 ILLEGAL, 64/64, n=64 ≈ 100 tok/s.2. The sobering part — block_size=64 only gets concurrent n=64 from 11 → ~100-147, not 1181. Measured (A6000, block_size=64): eager=147, graphs-on+stable=98-104, vs current main (block_size=16)=11. So block_size=64 removes the crash + row-loop (real 10×) — but graphs-on is slower than eager at concurrent (capture/replay/eviction churn > dispatch savings), and both are ~10× below the documented 1181. The static
/v1/completions/batchpath does ~990 (one request, 64 prompts); the per-request concurrent ×64 path is ~10× slower from per-request scheduler + serial-prefill overhead — that ~100-150 ceiling, not block_size/crash, is the dominant remaining concurrent bottleneck.Complete path to vLLM 1907 — three fixes, each multi-session, all needed:
wip/1082-blocksize64-graphblocked; needs stable-metadata defaulted + bs=1-latency/prefix-cache-coarsening validation before merge.Not merging the block_size branch: entangled (stable-metadata dependency, graphs-slower-than-eager at concurrent), a system-wide block_size change needing more validation, and it's only the first of three fixes (doesn't reach 1181 alone). The crash is now fully root-caused (race) with a known mitigation (stable-metadata); the remaining gap is a scoped, multi-session perf effort.
ericflo commentedon Jun 2, 2026
✅ Merged #1447 — bs=64 concurrent DECODE BASELINE recovered (~1155 ≈ 1181), both crashes fixed
The "~147 ceiling" I reported earlier was serial-prefill domination at max_tokens=64, not a decode wall. The marginal (prefill-subtracted) decode rate at bs=64 is ~1155 tok/s (≈ the documented 1181 baseline). So
block_size=64 + stable-metadata(PR #1447) recovers the n=64 decode baseline from the 11-tok/s row-loop cliff and fixes bothCUDA_ERROR_ILLEGAL_ADDRESScrashes:KILN_CUDA_GRAPH_STABLE_PAGED_METADATAnow defaults ON (persistent block-table buffer refreshed per replay reads the current table, no stale-frozen-table race).Validated A6000, production-default config (no env flags): graphs-on bs=64 concurrent, 0 ILLEGAL, coherent, decode ~1155 tok/s.
Phase-5 remaining to vLLM 1907 (both follow-ups):
The box-102-era cliff is closed; the residual is the kernel/scheduler perf work tracked above.
ericflo commentedon Jun 2, 2026
bs>1 batched cuda-graph (boxes 432/433/438) RESOLVED: functional post-#1447 but slower than eager — eager is the path; 1279→1907 is the decode kernel (Phase 8)
Directly tested the named deliverable on A6000 (main + #1447, block_size=64, stable-metadata default), bs=64 concurrent, marginal (prefill-subtracted) decode rate:
KILN_CUDA_GRAPHS_BATCHED=1)So the bs>1 batched cuda-graph is functional now (#1447 fixed the crashes that blocked it — it captures, replays 93×, stays coherent), but it is ~3× slower than eager at bs=64 concurrent: under changing batch membership the capture/replay + per-replay block-table refresh + eviction churn cost more than the eager path saves. It should stay default-off.
Conclusion for Phase 5:
box-102's frontier (the 11-tok/s cliff + both crashes) is closed and shipped; the bs>1-graph box is answered (functional, not faster); the residual 1907 parity is the Phase 8 decode-kernel challenge.
ericflo commentedon Jun 2, 2026
Batched-prefill lever scoped (4/5): from-scratch batched-GDN-prefill kernel, not a reroute — caps at ~1279, multi-session
Scoped the last in-lane Phase-5 lever (the serial-prefill bottleneck that caps the concurrent aggregate at short generations). Verdict: not a reroute, a from-scratch effort.
admit_waitingserial-prefills one request per cycle (batching_engine.rs:955,992→ single-promptprepare_request→prepare_paged_batched_decode_with_prefix_cache→model_forward_paged_last_token, single-sequence arity)./v1/completions/batchis also serial single-prompt prefill (spawns one task per prompt → sameadmit_waiting) — no shared batched-prefill primitive to route to.forward.rs:22463) is decode-only (one token/row), not reusable for multi-token causal prefill. No varlen/packed prefill primitive exists (cu_seqlens is only in the decode attn kernel).3.5% full-attn fraction (105→130-170 @ mt=64) — not worth it.burst_refill,max_prefill_admissions_per_cycle) are already maxed for CUDA by cuda: restore concurrent-decode batching (full-width burst-fill admission) (#1082) #1442.Net for Phase 5: all three remaining levers are now confirmed from-scratch multi-session kernel efforts — batched-graph (empirically 3× slower than eager, ruled out), batched-prefill (this scope: from-scratch GDN-scan kernel), decode-kernel 1279→1907 (GDN fusions null across #141/#158/#173/#176). Box-102's frontier (the 11-cliff + both crashes) is closed and shipped (#1447); the residual to vLLM-1907 is a multi-session kernel arc (2 PRs for batched-prefill; the GDN/decode-kernel optimization for the decode-rate gap), each with the standard kiln kernel-vendor preflight. Tracked here for whoever opens the kernel phase.
ericflo commentedon Jun 2, 2026
Parity-target fairness check: vLLM 1907 is the SAME Qwen3.5-4B GDN-hybrid (fair) → the gap is real kiln GDN-kernel efficiency, reachable-in-principle
Verified (BENCHMARKS.md:60-65) that the kiln-1181 → vLLM-1907 @ bs=64 head-to-head is vLLM 0.21.0 on the same Qwen3.5-4B GDN-hybrid weights, same L40S, same harness — a fair same-architecture comparison. (The "vLLM unsupported" verdicts²³⁴ were older 0.19.1/0.20.0 + the native-MTP feature, not the base model on 0.21.0.) So:
Net: Phase-5's box-102 frontier (the 11-tok/s cliff + both ILLEGAL crashes) is closed and shipped (#1447, decode baseline ~1279 ≈ kiln's documented 1181). The residual to vLLM-1907 is a dedicated GDN-decode-kernel-optimization arc — concrete and proven-reachable, but multi-session and beyond the easy (now-null) fusion levers; it belongs in the kernel phase with the standard preflight (latest PROFILING.md re-profile → per-GDN-region throughput vs vLLM → kill-switched kernel → CPU parity → median-of-3 A6000 bench), one region at a time. This issue now has the full file-level map for both that arc and the batched-prefill primitive.