Skip to content

epic: migrate off candle to in-house kiln-tensor (CUDA + Metal + Vulkan) #1082

Closed

Description

@ericflo

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-kernel is 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.rs with custom MSL kernels for SiLU*mul, fused QKV GEMV, transposed-coop GEMV, MLP gate+up, etc.
  • Vendored candle-core in vendor/candle-core — every candle fix already a vendor-patch.
  • Custom training paths in cuda_train.rs / vk_train.rs route 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 + cublasLtMatmulAlgoGetHeuristic would 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::Queue and threads it through every dispatch (crates/kiln-vulkan-kernel/src/device.rs:40,272,466, kernels.rs:724,774). CUDA goes through vendor/candle-core/src/cuda_backend/device.rs:40,247,256,280 — pub fn cublas_handle(), Arc<cudarc::cublas::CudaBlas>. No cublasLt anywhere in the repo. Without kiln-tensor owning the handle, "parallel QKV streams" in Phase 3 won't compose because cublasSetStream mutates shared state.
  • .narrow().contiguous() trap, quantified. forward.rs alone: 318 .contiguous(), 179 .narrow(, 142 .reshape(, 73 .transpose( — 712 layout calls. Splitting a packed matmul output forces a memcpy because downstream kernels gate on is_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=1 cuda-graph capture today but the bs>1 path runs eager (crates/kiln-model/src/cuda_graph.rs:33-96 documents 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-code CudaBatchedGraphKey stub at cuda_graph.rs:178 is the API surface to revive once allocator semantics are ours.
  • PagedKvCache is deeply candle-typed. crates/kiln-model/src/paged_kv_cache.rs:11-150,232-340 stores Vec<(Tensor, Tensor)> per layer with an FP8 K/V variant (new_with_fp8, fp8_scales: Vec<(f32, f32)> at line 47) and a per-row write_token_major_native_graph_slot interface 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,4848 shows HashMap<candle_core::TensorId, AdamWMoments> and a sync_to_candle round-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 Tensor tracked by separate bookkeeping (packed_weight_registry.rs 489 LOC, transposed_weight_cache.rs 730 LOC, marlin_proj.rs, fp8.rs, adapter_merge.rs 1703 LOC). The optimizer can't address them as one parameter. kiln-marlin-gemm is 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:

  1. Phase 1 allocator — Pool mode honors a per-device VRAM budget and auto-downshifts decode_resident_pool.rs's PREFERRED_SLOTS=4 to MIN_SLOTS=3 on 16 GiB. The auto-sizer at crates/kiln-core/src/vram.rs:460-720 is the contract; do not bypass.
  2. Phase 2.5 Parameter — backward_storage is optional, not required. Pure-inference deployments (16 GiB serve-only) get Parameter { forward_storage: Marlin, backward_storage: None }. Same type backs an 80 GiB train+serve job and a 16 GiB serve-only job.
  3. Phase 5 graph family — bs ∈ {1..64} is the 80 GiB target. On 16 GiB the family auto-downsamples to bs ∈ {1, 4, 16}; on 24 GiB to bs ∈ {1, 4, 8, 16, 32}. Memory footprint as a function of bs∈set is committed to bench-results/graph-family-vram.csv.
  4. 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.
  5. 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:

  1. 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.
  2. Const-generic shape specialization for the hot kernels. Every hot kernel in kiln-blas/kiln-mps/kiln-vulkan-blas is 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 family bs ∈ {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.
  3. 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 MTLBinaryArchive ship pre-warmed on supported GPUs.
  4. Static MTP depth = 1 codepath. num_nextn_predict_layers = 1 (crates/kiln-model/src/loader.rs:173). speculative.rs is 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.
  5. Compile-time GDN/MHA layer pattern. Qwen3.5-4B's per-layer GDN-vs-MHA layout is fixed. Today's runtime BackendRuntime per-layer dispatch becomes a compile-time match on const LAYERS: [LayerKind; N]. Per-layer branch elimination — small per layer but additive across the full stack.
  6. 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.
  7. 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.
  8. 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 (cuGraphSerialize on CUDA 12.4+), and reloaded on subsequent cold starts. First-token cold-start latency drops by the full graph-capture cost.
  9. 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.
  10. 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's Cargo.toml (runtime or dev) — verified A6000 (235dc0ca): zero candle-core/candle-nn in every Cargo.toml; cargo tree --features cuda -i candle-core empty; candle absent from Cargo.lock
  • vendor/candle-core/ deleted from the repo (235dc0ca)
  • cargo build --release --features cuda succeeds with no candle in the dep tree — landed 24e9b5d0 (2026-06-01): candle-core/candle-nn made optional + dropped from the cuda feature (re-added only under metal/vulkan/legacy-candle-parity); kiln-kt-bridge default-features=false in model/server/train; candle-core dropped from kiln-train. Verified on A6000: cargo tree -p kiln-server --features cuda -e normal has ZERO candle and the build is green. The CUDA runtime build is candle-free. (The only remaining candle in the full cargo tree is kiln-server's [dev-dependencies] candle-core for integration tests — compiled by cargo test, not cargo build; tracked under DoD line 98.)
  • cargo build --release --features metal succeeds with no candle in the dep tree
  • cargo build --release --features vulkan succeeds with no candle in the dep tree — validated A6000 a00ea3d4 (2026-06-01): cargo build --release -p kiln-server --features vulkan rc=0, cargo tree --features vulkan -i candle-core empty
  • cargo test on the default (no-GPU) profile still passes — CPU is a tested backend, not just a numerical reference. crates/kiln-model/src/backend/cpu.rs is real and .github/workflows/ci.yml:97 (linux-default) exercises it on every push. — 092c952d + 607623d7 fixed the no-cuda build by gating 5 kt_paged_cache use sites with #[cfg(feature="cuda")] + adding missing kv_slot: None to 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 existing crates/kiln-model/tests/mtp_byte_eq.rs byte-equality contract
  • LoRA hot-swap parity (correctness + latency) passes on every backend; cuda_graph survives 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-forward passes 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 in bench-results/parity-tolerance.csv either has a passing parity test or is explicitly marked unsupported with a tracked follow-up issue
  • PagedKvCache (incl. FP8 K/V via new_with_fp8) ported off candle_core::Tensor; write_token_major_native_graph_slot slot-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 commit 7dd0009c, end-to-end production wiring via bench in commit d5bba062; ~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/3 impl in the kernel crates is migrated to the kiln-tensor equivalent (forward + backward closure with explicit BackwardOp registration)
  • Every NVTX range name in forward.rs (90+ kiln_nvtx::range!(c"kiln/…") call sites) is unchanged — PROFILING.md hot-region percentages remain comparable across the migration. — Verified at session checkpoint: forward.rs now has 195 kiln_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 through crates/kiln-core/src/env_flag.rs (1451 references across crates/ — no renames)
  • Determinism stance documented in PROFILING.md (CUBLAS_WORKSPACE_CONFIG=:4096:8 baked into parity test harness; the option choice is explicit, not implicit) — landed: PROFILING.md "Determinism stance" section + crates/kiln-tensor/src/determinism.rs (Determinism enum with 4 categories) + KILN_DETERMINISTIC=1 envelope 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-3 BF16 / 1e-5 FP32 of the candle reference for 100 steps; Adam moments at step 100 within 1e-3)
  • All entries in bench-results/ regenerated post-migration with concrete numeric gates:
    • CUDA decode bs=1 ≥ current bench-results/llama-bench-a6000-post536.json baseline
    • CUDA decode bs=64 ≥ vLLM at same shape on L40S, Qwen3.5-4B (post-migration target; currently blocked by bs>1 cuda-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
  • Bench-gate has PR-time enforcement — either the self-hosted A6000 runner is online and the commented-out pull_request trigger in .github/workflows/opd-bench-gate.yml:24-29 is re-enabled, or a CPU-only smoke variant ships that reuses bench-results/check_opd_regression.py + check_sft_train_regression.py against the existing regression/README.md schema (schema_version: 1, ±10 % secs_per_step, ±15 % peak_vram_mb)
  • ARCHITECTURE.md, CLAUDE.md, PROFILING.md updated to reflect the in-house stack — ARCHITECTURE.md updated in 30e23b13 (Phase 7 kt_api production wiring snapshot, 49 lines), PROFILING.md updated in 65c010c9 (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-kernel takes a hidden_dim / intermediate_dim / vocab_size runtime argument when the value is fixed for Qwen3.5-4B. Const-generic monomorphization where the shape is fixed. — Audited via grep '^pub fn' crates/kiln-*-kernel/src/lib.rs crates/kiln-*-kernel/src/kt_api.rs: every hot-path API takes &Tensor or &KtTensor references, not bare hidden_dim/intermediate_dim/vocab_size integers. Shape comes from tensor metadata; the kernels' internal MSL/CUDA blocks compile against the fixed Qwen3.5-4B shapes via NVCC -gencode arch=compute_86 and the per-kernel #define HIDDEN_DIM constants that the build.rs scripts pass.
  • Activation registry, AmpPolicy, output-head registry, LogitProcessor chain, ReplayBuffer all 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_ANOMALY and KILN_DETERMINISTIC=1 documented and validated in CI.

Anti-patterns to avoid

Read these before starting any phase. Most are lessons from the MLP fusion work.

  1. kiln-tensor is not a candle wrapper. Storage is cudarc::CudaSlice / metal::Buffer / ash::vk::Buffer directly. No candle_core::Tensor field on kiln_tensor::Tensor. If you find yourself wrapping a candle Tensor, you're rebuilding the cage.
  2. Every contiguous() is explicit and logged. Emit kiln_profile_contiguous_copy from 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 in bench-results/ so regressions are visible without re-reading nsys traces.
  3. No allocation in the decode hot loop. Persistent buffers from per-device pools. Use kiln-vulkan-kernel::buffer_pool.rs and decode_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.
  4. The BackendRuntime trait at crates/kiln-model/src/backend/mod.rs:114 is the seam. kiln-tensor slots 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.
  5. 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.
  6. 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-tensor autograd path is the canonical numerical reference every other backend continues to compare against. Reuse the existing *_parity.rs naming convention (vk_matmul_parity, gdn_parity, marlin_qproj_parity, etc.).
  7. 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.
  8. No new candle dependencies anywhere. New crates depend on kiln-tensor; new code in existing crates uses kiln-tensor exclusively. The candle dep tree only shrinks.
  9. 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.
  10. narrow / reshape / transpose / slice are zero-copy. Downstream kernels declare stride support in their supports_* function. We do not silently .contiguous() to satisfy a kernel; we teach the kernel about strides or we use the packed variant.
  11. One Parameter, one TensorId — stable across variants. Forward-quantized + backward-master + transposed cache + LoRA delta all live behind a single Parameter keyed on one kiln_tensor::TensorId. The id is assigned at Parameter construction 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_graph capture never sees pointer churn from adapter swap; AdamW moments don't get orphaned on weight-form transitions.
  12. Multi-GPU stays out of scope. No NCCL, TP, PP in this migration. Once kiln-tensor is stable, that's a separate conversation. But do not hardcode Device::Cuda(0) anywhere — device selection routes through kiln-core's existing pattern so the multi-GPU seam is straightforward to add later.
  13. NVTX range names are part of the trace contract. PROFILING.md records kiln/gdn/in_proj at 19.6 %, MLP trio at 28.6 %, etc. — these names are how we'll know whether we regressed. Rename = break the contract.
  14. The on-device sampler already exists. Do not "add" greedy/top-k/penalty kernels in Phase 4 — port the existing ones in sampling.rs off candle Tensor and preserve their behavior. The BackendRuntime trait already exposes supports_linear_decode_argmax / _batch / _sample(top_k); lift to kiln-tensor.
  15. adapter_merge.rs stays candle-free. crates/kiln-model/src/adapter_merge.rs:1-160 is 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. Only lora_loader.rs's runtime Tensor-typed projections need to round-trip through kiln-tensor.
  16. 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.
  17. Same logical parameter, same Parameter handle. Tied weights (LM head + embedding, MTP head + base embedding), shared draft+target weights (MTP / self-speculative), multi-call-site weights — all are one Parameter with one backward_storage. Two Parameters pointing at the same physical buffer is a bug; gradient accumulation must go through atomic-add into a single grad buffer or determinism collapses.
  18. kiln-tensor storage is Send + Sync. Per-device CUDA driver context is Arc<CudaContext>; per-stream cuBLAS handle is Arc<CublasLtHandle>. No unsafe impl Send escape hatches. The threading model is "kiln-tensor ops are callable from any thread" — anything else costs us future scheduler refactor flexibility.
  19. 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_depth as 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 type
  • crates/kiln-vulkan-kernel/src/vk_autograd.rs — 173 lines that prove tape-based autograd is portable
  • crates/kiln-vulkan-kernel/src/vk_ops/ — 34 impl VkBackwardOp for ... blocks; the per-op backward shape we are lifting
  • crates/kiln-vulkan-kernel/src/buffer_pool.rs + cmd_batch.rs — persistent buffer + command-batching pattern
  • crates/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 shape
  • crates/kiln-model/src/backend/mod.rs:114 — the BackendRuntime trait seam that survives the migration
  • crates/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 toward
  • crates/kiln-model/src/cuda_graph.rs:33-96 — the bs>1 batched-decode gap doc; the dead-code CudaBatchedGraphKey stub at line 178 is the API surface to revive
  • crates/kiln-model/src/paged_kv_cache.rs:11-150,232-340 — Vec<(Tensor, Tensor)> layers, FP8 K/V variant, write_token_major_native_graph_slot slot-tensor interface that graph capture depends on
  • crates/kiln-model/src/sampling.rs:5-110,264 — on-device penalties / argmax / top-k via apply_penalties_on_device + try_topk_on_device; the path Phase 4 preserves
  • crates/kiln-model/src/speculative.rs (1160 LOC) and mtp_debug.rs (4588 LOC) — draft uses model_forward_segment(0, draft_layers) over a prefix of the target's GpuWeights; KILN_MTP_ARGMAX_FP32 is the head-dtype switch
  • crates/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-built DeviceBuffer enum (Vulkan + Cpu variants today); extend with Cuda + Metal variants in Phase 1 instead of building a parallel abstraction
  • crates/kiln-train/src/trainer.rs:555,592,599,632 — HashMap<candle_core::TensorId, AdamWMoments> + sync_to_candle round-trip; the optimizer-state interop seam to delete
  • crates/kiln-model/src/packed_weight_registry.rs + transposed_weight_cache.rs + marlin_proj.rs + fp8.rs + adapter_merge.rs — the bookkeeping that collapses into kiln-param::Parameter; note that adapter_merge.rs does 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 replacing
  • vendor/candle-core/src/cuda_backend/device.rs:40,247,256,280 — pub fn cublas_handle(), the shared Arc<cudarc::cublas::CudaBlas> we are taking ownership of
  • vendor/candle-core/src/custom_op.rs — CustomOp1/2/3 with bwd methods; every fused kernel crate plugs into this and must be re-shimmed in Phase 1
  • crates/kiln-model/src/cuda_train.rs (7891 LOC — CudaTrainTensor shell + CUDA training ops, lives in kiln-model) and crates/kiln-train/src/cuda_train.rs (4158 LOC — training-loop entry points). Phase 6b ports the kiln-train one onto kiln-autograd and deletes the kiln-model one in favor of the shared Parameter / Tensor types.
  • 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 every candle_core:: / candle_nn:: / Tensor:: call site, bucket by function, produce a CSV at bench-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) plus kiln-train/src/trainer.rs. Output: signature table + the proposed kiln-tensor equivalent (forward closure + backward closure with explicit BackwardOp registration). 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:8 is the conventional choice) and bake it into the parity test harness. Document in PROFILING.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) atomicAdd in 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.csv with {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 1 DType enum 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 in kiln-flash-attn, kiln-gdn-kernel, kiln-rmsnorm-kernel, kiln-marlin-gemm, kiln-opd-loss-kernel). Output: bench-results/multi-gpu-seam.csv with {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) every KILN_* env var that gates a code path (1451 references; centralize via crates/kiln-core/src/env_flag.rs), (c) every BackendRuntime method that takes a candle Tensor argument. Record all three to bench-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 with cublasLtMatmulAlgoGetHeuristic + explicit workspace. Bench at B*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 via MPSMatrixMultiplication with 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 existing dispatch_mlp_gate_up_decode_cached path.

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
  • DType enum is the full inference + training matrix from day 1. {FP32, BF16, FP16, FP8E4M3, FP8E5M2, INT8, INT4Packed, FP4Packed}. VkDType today is F32/BF16 only (vk_tensor.rs:23) — that's the starting set, not the ending set. Each storage variant carries its DType; each kernel declares supported DTypes; conversion ops (cast) are explicit. Backwards-gradient dtype is per-op (Marlin fwd → BF16 grad; FP8 fwd → BF16 or FP32 grad).
  • Storage is Arc<dyn StorageBackend> with Send + Sync everywhere. Pin the threading model in Phase 1 — kiln-tensor ops are callable from any thread. Per-device CUDA driver context is Arc<CudaContext>; per-stream cuBLAS handle is Arc<CublasLtHandle>. Cudarc's Arc<CudaStream> is already Send + Sync; candle's path (unsafe impl Send for CudaRng {}) is the kind of escape hatch we're removing.
  • kiln-tensor is 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::CudaStream affinity. kiln-tensor owns the cuBLAS(Lt) handle (replaces vendor/candle-core/src/cuda_backend/device.rs:40,247,256,280's shared handle); every op accepts an optional Stream override so Phase 3's parallel-QKV doesn't fight stream-handle binding. One cuBLAS(Lt) handle per stream, not per device — cublasSetStream is stateful and serializes; per-stream handles are the only way the StreamPlanner gets real parallelism.
  • Metal storage: metal::Buffer (via objc2-metal) + MTLCommandQueue affinity. Apple Silicon UMA zero-copy invariant: on M-series, CPU and GPU share physical memory; MTLStorageModeShared buffers are addressable from both. kiln-tensor exposes Tensor::is_unified_memory() and Tensor::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.rs ships the MetalStorage substrate with from_buffer, candle_device, and buffer accessors; the UMA wrap-share-retain pattern is the basis of all 5 real Metal kernel wires (cf64ebae softmax, a88d0842 rmsnorm+layernorm, 5d9dcef3 cast+elementwise, 742cf7e4 index_select)
  • Vulkan storage: lift kiln-vulkan-kernel::vk_tensor into kiln-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-default CI runs cargo test against it on every push (.github/workflows/ci.yml:97). Replicate forward.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 DeviceBuffer enum (crates/kiln-core/src/device_buffer.rs:25-90 — has Vulkan + Cpu today) with Cuda(Arc<CudaBuffer>) and Metal(Arc<MetalBuffer>) variants. Route vram.rs's reserved_bytes computation through this enum instead of duplicating the device abstraction. — Cuda variant landed earlier this Phase 1; Metal variant landed in 621c73f8 (kiln-core metal feature pulls kiln-tensor with its metal feature so MetalStorage is 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 across capture() / 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 / Vulkan HOST_VISIBLE | HOST_COHERENT. Tensor::upload_async / download_async honoring 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::Allocator has three explicit modes: (1) Owned (per-allocation cudaMalloc / vkAllocateMemory — slow, used only at startup); (2) Pool (slab-allocated from a pre-sized device-local pool, the steady-state path; mirrors Vulkan's buffer_pool.rs and decode_resident_pool.rs); (3) Frozen (no allocation; pulls from a pre-warmed slab indexed by tensor-handle — used during capture() … replay()). On CUDA, mode (2) sits over cudaMallocFromPoolAsync with a kiln-owned cudaMemPool_t so 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 over cudaMemPool_t (driver-managed reclaim under freeze). Metal pool sits over MTLHeap (suballocates from a single device heap). All three present the same Allocator trait. Single bookkeeping codepath.
  • Device::reserved_bytes() per backend — authoritative "bytes held by kiln-tensor" so kiln-core::vram keeps auto-sizing the KV cache without undercount when we own buffer pools.
  • CustomOpN replacement. Define kiln-tensor's forward/backward closure shape so the kernel crates port once (not once-for-forward, then-again-for-backward). Single integration point with kiln-autograd's BackwardOp trait.
  • Copy-counter instrumentation. Every explicit contiguous() and every kernel that internally materializes a copy emits a kiln_profile_contiguous_copy event. Aggregated as "copies per token" in bench-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-nvtx and nsys visibility we have today; range names match the preserve-list audit from Phase 0. — All 195+ existing kiln_nvtx::range! call sites in forward.rs preserved; new kt-API wires add kiln/*_kt ranges alongside the originals (additive only, no renames). All 24+ kernel-crate kt_api production wires this session burst include kiln_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 logs kiln_profile_contiguous_copy
  • Parity test suite: every API has an A/B test against candle_core::Tensor on CPU + each accelerator reachable (60+ parity tests in crates/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::TensorId matches the existing optimizer dispatch contract (see vk_autograd.rs:24-66 — VkGradStore keys on candle_core::TensorId; lift to kiln_tensor::TensorId)
  • Activation registry (sibling to Parameter). Activation is 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. Activation carries OffloadPolicy { Device, PinnedHost, NvmeCache } independently of Parameter's policy — because the 16 GiB SFT-at-8K-context OOM driver is activations (the activation tape scales O(seq_len × hidden × num_layers × 2) vs. weight cost of O(num_params)), not weights. On 16 GiB tier with seq_len=8K, activation footprint exceeds the BF16 master; without explicit offload here, the existing KILN_NO_GRAD_CHECKPOINT auto-tuner in crates/kiln-core/src/vram.rs:460-720 will refuse to disable checkpointing even at low batch. The Activation type 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 (extend kiln-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 cublasLtMatmulAlgoGetHeuristic we 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_streams matters: 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's expected_concurrent_streams so Phase 3's parallel-QKV picks SM-light algos automatically.
  • Pre-shipped autotune cache (Qwen3.5-4B specialization). Ship assets/autotune/{backend}-{gpu_sku}.json in 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-blas is 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 family bs ∈ {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 a hidden_dim: usize runtime 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_chunk behind KILN_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_matrix for the matmul backend. Audit confirms today's kiln-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 through descriptor_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:41 uses 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_matrix in custom MSL kernels. Today only candle SDPA uses Apple's matrix cores via MPS; the custom kernels in backend/metal.rs (SiLU*mul, fused QKV GEMV, transposed-coop GEMV, MLP gate+up) are simdgroup-scalar. Migrate to simdgroup_matrix where 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: MTLHeap for ephemeral intermediates. Activations, KV-cache scratch, sampler scratch all allocated from per-device MTLHeap with sub-heap aliasing. Reduces fragmentation on long-running servers; pairs with Phase 1 allocator's Pool mode.

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 new kiln-param crate
  • Forward dispatches on storage variant: BF16, Marlin W4A16, FP8, future FP4
  • tensor_id is 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> at crates/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 → requant kernel where the backend supports it
  • Storage-coherence invariant (the core "same weights for both" rule). For a Parameter with both forward_storage (quantized) and backward_storage (master), the relationship is explicit, not implicit: after an optimizer step writes the master, the forward storage is stale and Parameter::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 (no backward_storage), forward_storage is canonical. For Parameters with lora_delta, the merged form is computed lazily on first forward() after delta-swap and cached until the delta changes again — cuda_graph capture pins the cached merge, swap invalidates lazily. Document the state machine and write a parity test that round-trips BF16-master → Marlin-fwd → optimizer step → BF16-master → Marlin-fwd byte-for-byte.
  • LoRA delta is hot-swappable without changing tensor_id — cuda_graph capture 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 single backward_storage via 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 via marlin_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, Parameter already accommodates: drop backward_storage, route gradients only into lora_delta. Don't build it now; don't preclude it.
  • Draft and target share one Parameter::forward_storage for 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 Parameter type does not bake "one rank == one storage" — backward_storage is Vec<Storage> of length 1 today, designed to be length N (per-rank shard) later. StreamPlanner is 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.rs weight-side concerns onto this one handle. adapter_merge.rs is 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> } where OutputHead { 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 (today value_head exists in crates/kiln-train/src/trainer.rs:12913 but 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() -> u64 is a content-addressed fingerprint of forward_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. Today model_version_hash exists in crates/kiln-train/src/receipt.rs and crates/kiln-server/src/training_queue.rs for receipts; lift it to a first-class runtime property on Parameter. 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 declares AmpPolicy { 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: MTLCommandQueue priority hint. Vulkan: VK_KHR_global_priority where supported; fallback is single-queue with kernel-size-bounded yields.
  • Parameter::version epoch counter — atomic, bumped at end-of-optimizer-step. Parameter::forward(epoch_hint) returns a snapshot consistent at epoch_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 in ARCHITECTURE.md.
  • Replace the GPU RwLock with a Parameter-versioned read path. Today's whole-GPU RwLock at state.rs:1268 + the six lock sites in training_queue.rs:2159,2194,2217,2235,2250,2264,2279 collapse to: serving holds no lock and reads Parameter::current_epoch(); training acquires per-Parameter mutability through kiln-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_adapter is exclusive (crates/kiln-server/src/eval/generator.rs:62-67,146). With Parameter::lora_delta as 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 from kiln-core::vram like 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 that eval/mod.rs:1-7 inherits 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_paged decode-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-attn Rust API switch. Current API takes candle_core::Tensor and uses candle_core::bail! (crates/kiln-flash-attn/src/lib.rs:245,257,826). Switch the Rust shell to kiln_tensor::Tensor; do not touch the FFI/CUDA-side — keep kiln_flash_attn_fwd, _fwd_paged_decode, _fwd_paged_decode_dyn_seqlen, _bwd, and kiln_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_paged decode-parity test passes (numerically identical to candle). Metal/Vulkan + full training-tape coverage pending.
  • PagedKvCache ported 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_scales at line 47), per-row write_token_major_native_graph_slot slot-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.rs is candle-free today but dictates the batch shape every forward must handle; the BlockTable + cached_blocks + prefix_cache_stats interface flows directly into paged-attention dispatch. Pin the contract: kiln-tensor's paged-attention dispatch consumes BlockTable unchanged; 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. The BackendRuntime trait has 7+ supports_gdn_* methods and enter/exit/materialize/evict_gdn_recurrent_resident_state_scope lifecycle hooks; the registry belongs in kiln-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_fwd routing through cuda_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_paged decode-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,264 off candle Tensor: greedy argmax, batched argmax, top-k sample, repetition/frequency/presence penalties, min-p. The BackendRuntime trait already exposes supports_linear_decode_argmax / _batch / _sample(top_k); lift the seam to kiln-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-353 does the categorical step on host with StdRng after 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,3041 does 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.
  • LogitProcessor chain as a first-class abstraction. Audit shows the current sampler at crates/kiln-core/src/sampling.rs has top-k, top-p (nucleus), min-p, temperature, and the three penalties — but they're hand-wired, not composed. Define LogitProcessor as a stackable trait operating on a Tensor<[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_bias in 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 the LogitProcessor chain above as the grammar-mask step.
  • 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 and mtp_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.rs naming
  • 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). Today speculative.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-autograd crate; tape walker copied from vk_autograd.rs, generalized to kiln_tensor::Tensor
  • BackwardOp trait moved to kiln-autograd; VkBackwardOp becomes a re-export
  • VkGradStore becomes GradStore, keyed on kiln_tensor::TensorId (matches the Parameter handle's id contract from Phase 2.5)
  • Activation checkpointing primitive preserved: model_forward_segment (forward.rs:13705, kiln-train/src/lib.rs:200 checkpoint_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_storage in place. The autograd tape must not hold any reference to the pre-mutation tensor after optimizer.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_segment checkpoints today recompute the entire segment on backward. Selective recomp (save cheap activations, recompute only expensive ones) is a future training-memory lever. kiln-autograd exposes per-op should_recompute() returning bool; 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 @ dC via kiln-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)
  • rmsnorm bwd binding (if not already in kiln-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.rs onto kiln-autograd; delete crates/kiln-model/src/cuda_train.rs in favor of the shared Parameter / Tensor types in kiln-tensor. The two files have caused ambiguity; collapsing them onto the shared substrate removes one entire bookkeeping layer.
  • Delete the sync_to_candle round-trip (crates/kiln-train/src/trainer.rs:626,632). Optimizer state writes back directly into Parameter::backward_storage; checkpoint save reads from Parameter storage 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 within 1e-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-optim crate with OptimStep trait: AdamW, SGD, Lion, Muon
  • Operates on Parameter: FP32 moments + BF16 params + optional FP32 master, configurable per-Parameter
  • Marlin / FP8 weights: fused dequant → update → requant kernel per backend
  • Gradient accumulation across micro-batches. Trainer accumulates over N micro-batches before stepping (accumulate_grad / accumulate_grads_except in vk_train.rs:808,823; opd.rs:2767). The grad buffer lives in Parameter and 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.
  • dW and dX compute on parallel streams in matmul backward. dA = dC @ B^T and dB = A^T @ dC are independent. The CUDA / Metal / Vulkan matmul-bwd implementations submit them on two streams scheduled by StreamPlanner. 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-blas for 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 by KILN_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::OffloadPolicy per 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 to OnDemand; on 80 GiB stays Always. 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::OptimStep accepts MomentLocation { Device, PinnedHost, MmappedDisk } per Parameter. Default PinnedHost on 16 GiB, Device on 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): Device on 24 GiB+; PinnedHost on 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 at crates/kiln-core/src/vram.rs:460-720 already estimates the activation tape; extend its output with activation_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-optim reads 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 in bench-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" enables cudaMallocFromPoolAsync capture-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 a FrozenAllocator<'a>) and enforced by a debug-assertion kiln_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>1 slot-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_slot already 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-code CudaBatchedGraphKey stub at cuda_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 in bench-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.rs to a full pre-recorded decode pipeline; generalize decode_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}.cugraph via cuGraphSerialize and 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-record MTLIndirectCommandBuffers into a MTLBinaryArchive keyed similarly. Vulkan: pipeline cache plus a serialized cmd_batch blueprint 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-core and candle-nn from every [dependencies] and [dev-dependencies] block (235dc0ca); also dropped the [patch.crates-io] vendor entry
  • Remove the BackendRuntime candle-aware fallback paths from crates/kiln-model/src/backend/mod.rs — for_device candle 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 Parameter type from Phase 2.5 already accommodates (forward_storage = FP8, backward_storage = FP32 or BF16 master). 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 records kiln/gdn/in_proj at 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-r matmul 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-attn uses 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-codegen is 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-thermal polls NVML for temperature and power_draw; the scheduler responds by shrinking max_batch_tokens toward 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_request in opd-bench-gate.yml, or (b) ship a CPU-only smoke variant of the gate that synthesizes a partial bench JSON and runs the existing bench-results/check_opd_regression.py + check_sft_train_regression.py against the documented schema
  • Reuse bench-results/regression/README.md schema verbatim — schema_version: 1, pinned_at_commit, comment for 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 in bench-results/regression/. The "≥ baseline" gates in the DoD are unenforceable without this commit — wire check_opd_regression.py + check_sft_train_regression.py to 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::version epoch contract.
  • KILN_DETECT_ANOMALY NaN/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 asserts is_finite() on its output and panics with the op's tape position on first violation. Today the only finiteness check is kiln-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=1 envelope. 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-tensor is 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.sh and the broader bench-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 BackendRuntime trait at crates/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-coded CUBLAS_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-tensor slots 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 at crates/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 type
    • crates/kiln-vulkan-kernel/src/vk_autograd.rs (173 LOC) — tape walker
    • crates/kiln-vulkan-kernel/src/vk_ops/ — 34 backward op implementations
    • crates/kiln-vulkan-kernel/src/buffer_pool.rs — persistent buffer pattern
    • crates/kiln-vulkan-kernel/src/cmd_batch.rs — command batching pattern
    • crates/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 template
    • crates/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 kernel causal_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 to try_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-native forward::rms_norm recorder)
  • 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); no fn try_tape_cross_entropy_cuda definition 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

  1. added
    enhancement
    on May 23, 2026
  2. changed the title [-]epic: migrate off candle to in-house kiln-tensor over cudarc + cublasLt[/-] [+]epic: migrate off candle to in-house kiln-tensor (CUDA + Metal + Vulkan)[/+] on May 23, 2026
  3. 424 remaining items

  4. ericflo commented on Jun 1, 2026

    @ericflo
    OwnerAuthor

    Phase 2.7 progress — Parameter::version epoch counter foundation landed (PR #1437, merged 65a8902).

    The atomic-counter half of the "Parameter::version epoch counter" box is now done + CI-validated (candle-free kiln-param/kiln-optim job, no GPU):

    • epoch is now Arc<AtomicU64>; current_epoch() loads Acquire.
    • bump_epoch(&self) — atomic saturating add (monotonic version; &self so 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).
    • All four OptimStep impls (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-tier ARCHITECTURE.md matrix. Those are GPU + doc work still outstanding; the atomic counter above is their prerequisite.

  5. ericflo commented on Jun 1, 2026

    @ericflo
    OwnerAuthor

    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):

    • BUG-A — the captured cublasLt lm_head GEMV (vocab N=151936) computed wrong logits under graph replay despite a bit-identical input → deterministic token-doubling. Fix: capture as 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.
    • BUG-B — the captured bs=1 graph was reused across requests (stable-metadata key zeros block_table/seq_len) while carrying the prior request's GDN recurrent/conv state → deterministic garbage on every request after the first. Fix: detect the request boundary (seq_len contiguity + first KV block) and evict so each request re-captures with its own state.
    • Methodology note: 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).

  6. ericflo commented on Jun 1, 2026

    @ericflo
    OwnerAuthor

    🎉 Candle is gone from kiln — DoD candle-removal complete (235dc0ca)

    The in-house kiln-tensor substrate now fully replaces candle across CUDA, Vulkan, and Metal:

    • No candle in any [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 from Cargo.lock
    • Validated on A6000: cuda release build, vulkan check, default check all green candle-free; kiln-train vk_train_smoke 39/39 under nextest (vulkan training candle-free)
    • Metal lanes (kt-tape SFT + GRPO) landed candle-free by the Metal agent

    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)
    • GPU test suites should run under cargo nextest (process-per-test) — single-process cargo test accumulates Vulkan substrate state across tests
  7. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    Phase 5 — bs>1 batched CUDA-graph decode: LANDED (PR #1440)

    The bs>1 cuda-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):

    • HiddenOnly capture + eager lm_head (box-102 BUG2: the large-N lm_head GEMV is not replay-safe).
    • Seed + scatter the persistent GDN pool slot on the capture path (captured first token runs on the caller's post-prefill recurrent/conv history).
    • is_batched_enabled() gated on stable paged metadata — CudaBatchedGraphKey never 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.
    • Gated KILN_DEBUG_BATCHED_HIDDEN=1 per-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:

    concurrency graph ON graph OFF (eager) speedup
    32 150.8 tok/s 91.3 1.65x
    64 336.1 tok/s 164.0 2.05x

    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 L40S box: 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/batch call is reproducible; (4) bucket round-up [1,2,4,8,16,32,64].

    Also landed this session: deploy/runpod/kiln-setup SIGPIPE fix (866fe6f2) — sccache --show-stats | head aborted setup before writing /root/.kiln-build-env, making every fresh pod build cold (~13 min).

  8. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    L40S bs=64 parity bench — two real blockers found (correcting the earlier "2×" framing)

    Ran the canonical scripts/bench-concurrent-batch.py on 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:

    1. 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-recurrent cat (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.

    2. 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 vs f3a5f95e) 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 ≥ vLLM box 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.

  9. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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, serve KILN_W4A16=1 KILN_CUDA_GRAPHS=true) on both L40S and A6000 at main (d2f0f1f). Current main does not reproduce the documented concurrency scaling:

    concurrency documented A6000 eager (2d9d4fc, 2026-05-26) this run A6000 (d2f0f1f)
    1 84 71
    8 449 97
    32 483 71
    64 498 OOM / fails

    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 main somewhere between 2d9d4fc4 and d2f0f1f3.

    Implication: the CUDA decode bs=64 ≥ vLLM box 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 with KILN_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.

  10. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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 single block_table entry (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 the BlockManager free 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

  11. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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)

    concurrency p50 latency aggregate tok/s
    1 1.24s 51 (normal bs=1)
    8 7.86s 65
    32 24.2s 84
    64 366s 11

    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)

    n=8 n=32 n=64 crash
    guard ON (force_row_loop_for_contiguity) 74 84 11 (p50 366s) 0 ILLEGAL
    guard OFF 79 88 94 (p50 43.5s) 0 ILLEGAL

    Root cause (four layers)

    1. 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 in forward.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).
    2. Underneath it: BlockManager fragmentation. The vendored FA2 paged-decode kernel requires each K_BLOCK_N-token tile to be physically-contiguous pages. The free-list recycles finished requests' blocks out-of-order, so live rows get non-adjacent tile pages. This is the actual root — fix the allocation and the guard never fires.
    3. A second scheduler bottleneck caps concurrent at ~94 tok/s flat (n=8/32/64 all ~80–94) even with the guard off, vs ~990 static. Suspect per-step batched-GDN-state re-assembly / batched_state_cache misses under dynamic membership in the decode-batcher.
    4. The decode kernel itself is ~990 static vs vLLM BF16 1907 — a ~2× kernel-throughput gap (GDN regions ~69% of decode, the Phase-8 levers).

    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_zeros failures on L40S).

    Fix plan (scoped, multi-PR)

    1. BlockManager: prefer physically-contiguous within-tile page runs on allocation (the root fix — makes the guard a no-op at n=64). Primary.
    2. Per-row partition at generate.rs:3707 (batch the contiguous rows via the fast path, row-loop only the genuinely-fragmented minority) — a crash-safe Pareto improvement for the partial-fragmentation regime; complements Add tokenizer integration (HuggingFace tokenizers crate) #1.
    3. Guard the non-greedy path (generate.rs:3332) with the same mechanism — closes the production crasher.
    4. Profile + fix the ~94-tok/s scheduler ceiling (per-step state re-assembly).
    5. Phase-8 kernel levers (cublasLt autotune, GDN fusion) for the residual 990→1907.

    Items 1–4 recover concurrent throughput toward the kernel ceiling; item 5 raises the ceiling. Cleanup (vestigial KILN_USE_KILN_TENSOR_* flags + the metal.rs dead cfg(any()) candle block) is done in 220a4032.

  12. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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:

    1. FA2 split-KV kernel gathers per-page (drop the 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.
    2. Contiguous per-request block allocation — conflicts with prefix-cache block sharing on the prompt span (the prompt→decode boundary tile straddles a shared run and a per-request run).

    #1446 is the crash-safe foundation; the FA2 per-page-gather kernel is the next high-value CUDA task.

  13. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    block_size=64 fix attempt — EAGER validated (n=64 11→147), graphs-on BLOCKED

    Pursued the n=64 perf lever: raise KV block_size 16→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 hits CUDA_ERROR_ILLEGAL_ADDRESS at block_size=64 ("capture failed: sync after first captured-graph launch"). Key narrowing:

    • A single bs=1 request does NOT crash (ILLEGAL=0, LAUNCH_BLOCKING). Only concurrent decode with graphs-on does.
    • So it's a graph-capture-under-concurrency bug at block_size=64, not the cuda_graph.rs block-table sizing (I made cuda_graph.rs use the same FA2_KBLOCK_N=64 as forward.rs — necessary for consistency, but it did not resolve the crash).
    • Eager (graphs off) is unaffected → the kernel + block_size=64 math are sound; the issue is in the concurrent graph capture/replay path (likely the request-boundary eviction/recapture churn interacting with the block_size=64 captured block-table).

    Not merging (would break production concurrent decode). Next step: hands-on CUDA_LAUNCH_BLOCKING debugging 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.

  14. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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 fix 70a410ec is a correct safety improvement but does NOT fix a race.) KILN_CUDA_GRAPH_STABLE_PAGED_METADATA=1 fixes it — its persistent block_table_buffer is 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/batch path 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:

    1. block_size=64 + stable-metadata (crash + row-loop → 11→~100-147). Done on branch wip/1082-blocksize64-graphblocked; needs stable-metadata defaulted + bs=1-latency/prefix-cache-coarsening validation before merge.
    2. serial-prefill → batched/chunked-prefill primitive — THE dominant concurrent bottleneck (~100-150 → ~990). Substantial scheduler work (the engine prefills concurrent admits one-at-a-time).
    3. kernel + bs>1 graph replay (bs>1 batched CUDA-graph decode: HiddenOnly capture + eager lm_head, GDN seed, stable-metadata gate (#1082 Phase 5) #1440) → ~990 → 1907 (Phase 8 GDN levers + replay).

    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.

  15. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    ✅ 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 both CUDA_ERROR_ILLEGAL_ADDRESS crashes:

    • eager batched bs>1 crasher — block_size=64 makes each FA2 tile one page → no intra-tile contiguity requirement.
    • bs=1 graph-capture race (Heisenbug, async-only) — KILN_CUDA_GRAPH_STABLE_PAGED_METADATA now 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):

    1. Serial-prefill → batched/chunked-prefill primitive — the engine prefills concurrent admits one-at-a-time; this caps the aggregate tok/s at short generations (105 @ mt=64 → 499 @ mt=512). Closing the aggregate to ~1181 needs a multi-prompt prefill primitive.
    2. Decode kernel gap ~1155 → 1907 (≈1.9×) — Phase 8 GDN levers (gates/gated_norm/qk_norm ≈ 69% of decode) + bs>1 graph replay (bs>1 batched CUDA-graph decode: HiddenOnly capture + eager lm_head, GDN seed, stable-metadata gate (#1082 Phase 5) #1440).

    The box-102-era cliff is closed; the residual is the kernel/scheduler perf work tracked above.

  16. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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:

    config decode tok/s crash graph
    BATCHED off (eager contiguous-batch) 1279 0 ILLEGAL —
    BATCHED on (KILN_CUDA_GRAPHS_BATCHED=1) 408 0 ILLEGAL captures=1, replays=93, coherent

    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.

  17. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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_waiting serial-prefills one request per cycle (batching_engine.rs:955,992 → single-prompt prepare_request → prepare_paged_batched_decode_with_prefix_cache → model_forward_paged_last_token, single-sequence arity).
    • /v1/completions/batch is also serial single-prompt prefill (spawns one task per prompt → same admit_waiting) — no shared batched-prefill primitive to route to.
    • The existing N-way batched forward (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).
    • The killer is GDN (24 layers, ~69% of compute): its recurrent scan is sequential per-token-per-sequence; a batched prefill needs a new batched-GDN-scan kernel with sequence-boundary resets — exactly the bug class that produced the bs>1 coherence drift earlier in this issue. The session-shippable slice (batched FA-2 + serial GDN) recovers only the 3.5% full-attn fraction (105→130-170 @ mt=64) — not worth it.
    • Even fully built, it caps at the ~1279 decode rate, NOT 1907 (1907 is the orthogonal decode-kernel gap).
    • Scheduler knobs (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.

  18. ericflo commented on Jun 2, 2026

    @ericflo
    OwnerAuthor

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions