Last updated: 2026-11-17

Inference Runtime

Forward

All API Sections

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 32 methods src/compute/forward.zig

9 exports shown

struct

DecodeState

#
pub const DecodeState = struct

Runtime state for the decode loop.

src/compute/forward.zig:182

Methods

2

method

DecodeState.init

#
pub fn init(allocator: std.mem.Allocator) DecodeState

Initialize decode state for a fresh generation request.

Parameters
allocator
Allocator used for the generated token list.
Returns

A DecodeState positioned at token index zero with an empty output buffer.

src/compute/forward.zig:195

method

DecodeState.deinit

#
pub fn deinit(self: *DecodeState) void

Release the generated token buffer owned by the decode state.

Parameters
self
Decode state to tear down in place.
Notes

After this call the state is invalid and should not be reused.

src/compute/forward.zig:207

struct

SamplingParams

#
pub const SamplingParams = struct

Token sampling controls shared by the decode loop and HTTP server.

src/compute/forward.zig:214

Methods

1

method

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

Returns

`true` when temperature, top-p, or repetition-penalty are active

src/compute/forward.zig:223

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.

src/compute/forward.zig:427

function

tensorBytes

#
pub fn tensorBytes(model: *const Model) u64

No public doc comment yet.

src/compute/forward.zig:885

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.

src/compute/forward.zig:1231

Methods

29

method

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.

Parameters
model
Loaded model weights and metadata.
instance
Active Vulkan instance and logical device.
gpu_config
Derived GPU tuning parameters for the selected device.
shader_dir
Directory containing compiled SPIR-V shader binaries.
allocator
Allocator used for graphs, staging state, and temporary setup structures.
Returns

An initialized inference engine ready to prefill prompts and run decode steps.

Notes

This allocates shared descriptor pools, staging buffers, intermediate activations, and dispatch wrappers up front.

src/compute/forward.zig:2012

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.

src/compute/forward.zig:4317

method

InferenceEngine.enableValidationDiagnostics

#
pub fn enableValidationDiagnostics(self: *InferenceEngine) void

Enable the expensive CPU-vs-GPU validation readbacks used for debugging kernel correctness.

src/compute/forward.zig:4324

method

InferenceEngine.enableLogitsReadback

#
pub fn enableLogitsReadback(self: *InferenceEngine) void

Preserve full logits on the host for debug dumps and diagnostic inspection.

src/compute/forward.zig:4329

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.

src/compute/forward.zig:4811

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.

Parameters
state
Decode state carrying the current token position and generated token history.
token_id
Vocabulary index of the token to embed and feed forward.
collect_output
When `true`, the engine accumulates layer outputs needed by
Returns

`error.ContextLengthExceeded` when `state.position` is at capacity.

src/compute/forward.zig:7515

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.

src/compute/forward.zig:7539

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().

src/compute/forward.zig:7583

method

InferenceEngine.decodeStep

#
pub fn decodeStep(self: *InferenceEngine, state: *DecodeState, token_id: u32, collect_output: bool) !void

No public doc comment yet.

src/compute/forward.zig:7708

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.

Parameters
state
Decode state for the current request.
prompt_tokens
Tokenized prompt sequence to prefill.

src/compute/forward.zig:29164

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.

Parameters
state
Decode state; must start at position 0 for a fresh request or have
prompt_tokens
Tokenized input sequence to prefill. No-op when empty.
Notes

This is the per-token serial path. For the experimental batched variant see `prefillBatched`.

src/compute/forward.zig:30132

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.

src/compute/forward.zig:31000

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.

src/compute/forward.zig:31300

method

InferenceEngine.mtpLogRequest

#
pub fn mtpLogRequest(self: *const InferenceEngine) void

Emit this request's counters before the next request resets them.

src/compute/forward.zig:31375

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.

src/compute/forward.zig:31391

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.

src/compute/forward.zig:31902

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.

src/compute/forward.zig:31959

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.

src/compute/forward.zig:32034

method

InferenceEngine.mtpSetPrimeDuringPrefill

#
pub fn mtpSetPrimeDuringPrefill(self: *InferenceEngine, on: bool) void

Whether a chunked prefill primes the draft block as it goes.

src/compute/forward.zig:32040

method

InferenceEngine.ssmCheckpointTake

#
pub fn ssmCheckpointTake(self: *InferenceEngine, state: *DecodeState) !bool

Snapshot the recurrent state at the current position (see the field doc).

src/compute/forward.zig:32049

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.

src/compute/forward.zig:32092

method

InferenceEngine.ssmCheckpointPosition

#
pub fn ssmCheckpointPosition(self: *const InferenceEngine) ?u32

No public doc comment yet.

src/compute/forward.zig:32125

method

InferenceEngine.ssmCheckpointInvalidate

#
pub fn ssmCheckpointInvalidate(self: *InferenceEngine) void

No public doc comment yet.

src/compute/forward.zig:32129

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.

src/compute/forward.zig:32150

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.

Parameters
state
Decode state supplying the generated-token history for repetition penalty.
params
Sampling hyper-parameters controlling temperature and nucleus filtering.
random
Random source for stochastic sampling; unused on the greedy path.
Returns

The sampled vocabulary token index.

src/compute/forward.zig:32351

method

InferenceEngine.deinit

#
pub fn deinit(self: *InferenceEngine) void

Release GPU buffers, graphs, command objects, and dispatch helpers owned by the engine.

src/compute/forward.zig:32840

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.

Parameters

engine
Initialized inference engine.
prompt_tokens
Tokenized prompt that seeds the prefill pass.
max_tokens
Maximum number of decode tokens to emit after prefill.
allocator
Allocator used for transient decode state and the returned token slice.

Returns

A heap-allocated slice containing only the generated continuation tokens.

Notes

Generation stops early when the sampled token equals `eos_token_id`.

src/compute/forward.zig:33028

struct

MtpCycleResult

#
pub const MtpCycleResult = struct

No public doc comment yet.

src/compute/forward.zig:33031

struct

MtpPerf

#
pub const MtpPerf = struct

No public doc comment yet.

src/compute/forward.zig:33038

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.

src/compute/forward.zig:33299