Last updated: 2026-11-17
Inference Runtime
Forward
Run the inference runtime: decode state, pipeline ownership, and token generation.
This module ties together model state, compute graphs, dispatch helpers, and greedy token sampling for a single active inference engine.
9 exports shown
struct
DecodeState
pub const DecodeState = struct Runtime state for the decode loop.
struct
SamplingParams
pub const SamplingParams = struct Token sampling controls shared by the decode loop and HTTP server.
Methods
1method
SamplingParams.requiresLogitsReadback
pub fn requiresLogitsReadback(self: @This()) bool Return whether the current sampling settings require CPU-visible logits.
(i.e. any path that needs more than just the argmax token index).
function
dequantRow
pub fn dequantRow(raw_data: []const u8, row: u32, cols: u32, quant_type: GGMLType, output: []f32) void Dequantize a single row from a quantized tensor to f32.
Supports F32, F16, Q8_0, Q6_K, Q5_K, Q4_K, Q5_0, and MXFP4 formats.
function
tensorBytes
pub fn tensorBytes(model: *const Model) u64 No public doc comment yet.
struct
InferenceEngine
pub const InferenceEngine = struct Central inference engine that owns the GPU resources for one active model.
Holds the loaded model, all Vulkan pipelines and intermediate activation buffers, KV-cache page pool, SSM recurrent state, and per-request profiling counters. One engine instance maps to one GPU device; it is not thread-safe.
Methods
29method
InferenceEngine.init
pub fn init( model: *Model, instance: *const Instance, gpu_config: GpuConfig, shader_dir: []const u8, allocator: std.mem.Allocator, ) !InferenceEngine Create the runtime objects needed to execute decode-time work on the GPU.
method
InferenceEngine.enableProfiling
pub fn enableProfiling(self: *InferenceEngine) !void Enable full GPU + CPU profiling.
The timestamp query pool is created in `init`, so this just flips the runtime flag. Returns an error if pool creation failed.
method
InferenceEngine.enableValidationDiagnostics
pub fn enableValidationDiagnostics(self: *InferenceEngine) void Enable the expensive CPU-vs-GPU validation readbacks used for debugging kernel correctness.
method
InferenceEngine.enableLogitsReadback
pub fn enableLogitsReadback(self: *InferenceEngine) void Preserve full logits on the host for debug dumps and diagnostic inspection.
method
InferenceEngine.recordProfilingSample
pub fn recordProfilingSample(self: *InferenceEngine) void Read back all timestamps for the current token and fold them into request-wide profiling stats.
method
InferenceEngine.chainedDecodeAvailable
pub fn chainedDecodeAvailable(self: *const InferenceEngine) bool Run a single decode step for one token through all transformer layers.
embed → [per-layer: norm → QKV → RoPE → KV write → attention → O proj → residual → FFN norm → MoE routing → expert DMMVs → residual] → final norm → LM head → logits diagnostic or GPT-OSS embedding-collection paths. Submit the decode command buffer so far, copy `hidden_buf` to host and log its first/last three values and RMS as the output of `layer` at position `pos`, then reopen the command buffer (diagnostic only). Whether decodeChained can stand in for decodeStep + sampleGreedy: GPU argmax, push descriptors, an embedding type embed_gather reads, and no profiling, logits readback, diagnostics or primed NextN/MTP.
method
InferenceEngine.chainDrain
pub fn chainDrain(self: *InferenceEngine) !void Wait for the in-flight chained step, if any, and forget it.
Its KV write sits at state.position, past the committed tokens, and is overwritten by whatever is decoded or prefilled there next.
method
InferenceEngine.decodeChained
pub fn decodeChained(self: *InferenceEngine, state: *DecodeState, token_id: u32) !u32 Greedy decode with the next step always queued behind the current one.
Same contract as decodeStep(state, token_id, true) + sampleGreedy(): consumes token_id at state.position, advances it by one and returns the argmax. When the caller feeds back the returned token, the step for it is already on the GPU; any other token (or any other engine call) first drains the speculative step. Requires chainedDecodeAvailable().
method
InferenceEngine.decodeStep
pub fn decodeStep(self: *InferenceEngine, state: *DecodeState, token_id: u32, collect_output: bool) !void No public doc comment yet.
method
InferenceEngine.prefillBatched
pub fn prefillBatched(self: *InferenceEngine, state: *DecodeState, prompt_tokens: []const u32) !void Experimental batched prompt prefill for the RDNA/Vulkan backend. Gated by `ZINC_BATCHED_PREFILL=1`. This is the Vulkan analogue of `forward_metal.InferenceEngine.prefillBatched`.
Routes to `prefillA3bProduction` or `prefillQwen36DenseFfnPrefix` when the model and prompt length match those specialized paths; otherwise falls back to the `canUseBatchedPrefillRdna`-gated batched body or `prefillBatch` (per-token serial path). Set `ZINC_BATCHED_PREFILL=0` to force the serial fallback or `=validate` to run both paths and diff the last-token logits. Intel Arc Gemma uses the chunked batched path by default; Intel Qwen 3.6 A3B's layer-major path requires ZINC_INTEL_A3B_PRODUCTION=1. Qualified all-Q8 dense Qwen also uses bounded batches by default; other Intel graphs require `ZINC_INTEL_BATCHED_PREFILL=1` to opt in.
method
InferenceEngine.prefillBatch
pub fn prefillBatch(self: *InferenceEngine, state: *DecodeState, prompt_tokens: []const u32) !void Process all prompt tokens sequentially (one token per GPU submission) to populate KV cache and SSM state before the first decode step.
an active KV-page allocation for continuation prefill.
method
InferenceEngine.mtpEnabled
pub fn mtpEnabled(self: *const InferenceEngine) bool No public doc comment yet.
method
InferenceEngine.mtpPrepare
pub fn mtpPrepare(self: *InferenceEngine) !bool Allocate the NextN runtime state (draft input buffers).
Safe to call repeatedly; returns false when MTP is unavailable for this model/runtime.
method
InferenceEngine.mtpDraftStep
pub fn mtpDraftStep(self: *InferenceEngine, state: *DecodeState, token: u32, pos: u32) !u32 One NextN draft step at `pos`: feeds `token` (the token occupying position `pos`) together with the h row in h_input_buf through the appended block (writing its KV at `pos`) and returns the greedy draft for position pos+1.
h_input_buf is replaced by the block's own normalized output so chained draft steps can follow directly.
method
InferenceEngine.mtpLogRequest
pub fn mtpLogRequest(self: *const InferenceEngine) void Emit this request's counters before the next request resets them.
method
InferenceEngine.mtpBeginRequest
pub fn mtpBeginRequest(self: *InferenceEngine) void Reset per-request NextN bookkeeping.
`pending_h` and `resident_context_len` describe what the engine physically holds, not this request, so they survive: a prompt that reuses the resident prefix primes only its suffix (mtpPrimeSuffix). A prefill from position 0 clears them.
method
InferenceEngine.mtpPrime
pub fn mtpPrime(self: *InferenceEngine, state: *DecodeState, prompt_tokens: []const u32) !bool Prime the NextN KV cache over a freshly prefilled prompt (positions 0..N-1).
Requires the prefill capture to hold every prompt row.
method
InferenceEngine.mtpPrimeSuffix
pub fn mtpPrimeSuffix(self: *InferenceEngine, state: *DecodeState, prompt_tokens: []const u32, reused_prefix_len: u32) !bool Prime the NextN block over just the tokens appended after a reused prompt prefix, so a conversation that skipped most of its prefill still gets speculative decoding instead of falling back to ordinary decode.
Sound only when the engine still physically holds that prefix — the caller establishes that (the server reuses a prefix only for the resident conversation) and this checks it against `resident_context_len`, which the NextN catch-up keeps current. Any mismatch returns false and the caller falls back, which is exactly today's behaviour.
Verified on hardware in both thinking modes (2026-09-11): a reused turn primes its appended rows in ~3 ms and decodes at speculative speed with the same answer. ZINC_MTP_REUSE=0 disables it.
method
InferenceEngine.mtpResetCapture
pub fn mtpResetCapture(self: *InferenceEngine) void Forget captured prefill rows so the next prefill's capture starts at row 0; used before a transcript suffix or rebuild prefill inside a request.
method
InferenceEngine.mtpSetPrimeDuringPrefill
pub fn mtpSetPrimeDuringPrefill(self: *InferenceEngine, on: bool) void Whether a chunked prefill primes the draft block as it goes.
method
InferenceEngine.ssmCheckpointTake
pub fn ssmCheckpointTake(self: *InferenceEngine, state: *DecodeState) !bool Snapshot the recurrent state at the current position (see the field doc).
method
InferenceEngine.ssmCheckpointRestore
pub fn ssmCheckpointRestore(self: *InferenceEngine, state: *DecodeState) !bool Roll the recurrent state back to the checkpoint.
The KV rows past it are overwritten by the caller's re-prefill of the canonical suffix.
method
InferenceEngine.ssmCheckpointPosition
pub fn ssmCheckpointPosition(self: *const InferenceEngine) ?u32 No public doc comment yet.
method
InferenceEngine.ssmCheckpointInvalidate
pub fn ssmCheckpointInvalidate(self: *InferenceEngine) void No public doc comment yet.
method
InferenceEngine.mtpPerf
pub fn mtpPerf(self: *const InferenceEngine) MtpPerf No public doc comment yet.
method
InferenceEngine.mtpCycle
pub fn mtpCycle(self: *InferenceEngine, state: *DecodeState, seed: u32, pos: u32, max_drafts: u32, eos_id: u32) !MtpCycleResult One speculative cycle: draft up to `max_drafts` tokens after `seed` (which occupies position `pos`), verify seed + drafts in one target batch, roll the recurrent state back to the accepted boundary, then repair the NextN KV for the committed tokens.
On return the target has consumed `seed` plus `n_accepted` drafts and state.position is advanced accordingly; `next_token` is the target's prediction after them.
method
InferenceEngine.sampleGreedy
pub fn sampleGreedy(self: *const InferenceEngine) u32 No public doc comment yet.
method
InferenceEngine.sample
pub fn sample(self: *const InferenceEngine, state: *const DecodeState, params: SamplingParams, random: std.Random) u32 Sample the next token using greedy argmax or stochastic sampling depending on `params`.
Delegates to `sampleGreedy` when no logit readback is needed; otherwise reads staged logits from the host and applies temperature, top-p, top-k, and repetition penalty.
method
InferenceEngine.deinit
pub fn deinit(self: *InferenceEngine) void Release GPU buffers, graphs, command objects, and dispatch helpers owned by the engine.
constant
mtp_max_draft
pub const mtp_max_draft: u32 = 3 Run single-request inference: prefill the prompt, decode greedily, and return generated token IDs.
struct
MtpCycleResult
pub const MtpCycleResult = struct No public doc comment yet.
struct
MtpPerf
pub const MtpPerf = struct No public doc comment yet.
function
generate
pub fn generate( engine: *InferenceEngine, prompt_tokens: []const u32, max_tokens: u32, eos_token_id: u32, extra_stop_ids: []const u32, allocator: std.mem.Allocator, ) ![]u32 No public doc comment yet.