Class QwenModel
When constructed with a TensorShardSpec, attention / FFN / DeltaNet
projections are locally sized for that TP rank. Embeddings and the LM head
remain replicated (full vocab) on each rank in phase 1.
Construct on CPU, load weights, then call to(Device) to place
parameters and the RoPE frequency table. Install the KV pool afterward via
setKvCachePool(KvCachePool, boolean) when full-attention layers are present.
-
Field Summary
Fields inherited from class LayerBlock
device, dtype, module -
Constructor Summary
ConstructorsConstructorDescriptionQwenModel(QwenModelArgs args, DeltaNetStatePool statePool) Constructs the module graph on CPU.QwenModel(QwenModelArgs args, DeltaNetStatePool statePool, TensorShardSpec shard, TensorParallelGroup tpGroup) Tensor-parallel shard constructor (CPU).QwenModel(QwenModelArgs args, DeltaNetStatePool statePool, TensorShardSpec shard, TensorParallelGroup tpGroup, QwenVisionArgs visionArgs) Multimodal constructor with optional vision tower. -
Method Summary
Modifier and TypeMethodDescriptionvoidReleases CUDA graph resources for this rank.voidReleases verify CUDA graph resources for this rank.Returns the DeltaNet recurrent/conv state pool.embedTokens(Tensor tokens) Token embedding lookup (for multimodal splice).Forward propagation (or forward pass) through the layer.Forward pass.Decode forward with per-row absolute positions (seqLenmust be 1).Decode forward with per-row absolute positions.Decode forward with separate KV write positions and RoPE gather positions (needed for multimodalrope_delta).Forward pass.forwardBatchedVerify(Tensor tokens, int[] startPositions, int[] cacheLengths) Batched eager verify forward for a cohort of concurrent requests that may be at different absolute positions — the multi-request counterpart offorwardVerifyGraph(Tensor, int), which requires a single shared start position across the batch so it can be CUDA-graph-captured (seeVerifyCudaGraph#canGraphVerify).forwardDecodeGraph(Tensor tokens, int[] cachePositions, int[] ropePositions) Uniform decode forward with optional CUDA graph capture / replay.forwardEmbeds(Tensor inputsEmbeds, int startPos, Tensor cos, Tensor sin, boolean allTokenLogits) Prefill from precomputed embeddings (multimodal splice) with optional interleaved mRoPE cos/sin.forwardVerifyGraph(Tensor tokens, int startPos) Uniform MTP window-verify forward (query lengthS = numDrafts + 1, every batch row sharing the same start position) with optional CUDA graph capture / replay.forwardVerifyGraph(Tensor tokens, int[] startPositions) Ragged form offorwardVerifyGraph(Tensor, int): theBrows (concurrent requests) may be at different absolute positions.forwardVerifyGraphCodeEager(Tensor tokens, int startPos) Diagnostic only: runs the exact code a verify CUDA graph captures (forwardVerifyGraphCore(Tensor, int[], Tensor, Tensor, Tensor)with the graph-mode stable buffers and FlashInfer verify kernel) eagerly, so replay output can be compared against identical kernels with no graph involved.forwardVerifyGraphCodeEager(Tensor tokens, int[] startPositions) Ragged form offorwardVerifyGraphCodeEager(Tensor, int).voidDrops captured decode / prefetch CUDA graphs while keeping durable token/RoPE/logits buffers.voidDrops a captured verify CUDA graph while keeping durable token/RoPE/ logits buffers.Returns the KV cache pool for full-attention layers, if installed.Returns the last captured post-final-norm hidden for MTP.layers()Returns the decoder blocks.mtp()Returns the native MTP draft head.Returns the per-request MTP anchor store.intReturns the number of hybrid decoder blocks.params()Returns model hyperparameters.voidsetKvCachePool(KvCachePool pool, boolean closePrevious) Replaces the KV cache pool on every full-attention layer.voidsetMtpAnchorAtWindowPosition(int r) On a partial MTP accept at window positionr(checkpoint-replay path), restores the MTP anchor from the per-position hidden retained inverifyWindowNormalizedBufinstead of a second full-window forward.voidsetMtpAnchorAtWindowPositions(int[] positions) Batched counterpart ofsetMtpAnchorAtWindowPosition(int): restores each rowi's MTP anchor from its own retained window positionpositions[i]— needed when concurrent requests verified together in one round accept different numbers of draft tokens.shard()Returns the tensor-parallel shard description for this rank.static TensorspliceVisionEmbeds(Tensor embeds, int[] inputIds, Tensor visionEmbeds, int imageTokenId, int videoTokenId) Replaces image/video pad rows in text embeddings with vision features.Moves parameters and the RoPE cos/sin tables todevice.to(Device device, ScalarType dtype) Moves parameters and the RoPE cos/sin tables todevice/dtype.inttpRank()Returns this rank's tensor-parallel index.Returns the vision args.visual()Returns the vision tower.Methods inherited from class LayerBlock
add, add, device, dtype, eval, isTraining, load, loadStateDict, module, save, setRequiresGrad, toString, train
-
Constructor Details
-
QwenModel
Constructs the module graph on CPU. Callto(Device)after weight load; thensetKvCachePool(KvCachePool, boolean)when full-attention layers exist.- Parameters:
args- hyperparameters.statePool- DeltaNet state pool (may be null when no linear layers).
-
QwenModel
public QwenModel(QwenModelArgs args, DeltaNetStatePool statePool, TensorShardSpec shard, TensorParallelGroup tpGroup) Tensor-parallel shard constructor (CPU). Callto(Device)after load.- Parameters:
args- hyperparameters.statePool- DeltaNet state pool (may be null when no linear layers).shard- local head / FFN shard description, ornullfor full width.tpGroup- tensor-parallel group, ornullfor single-device.
-
QwenModel
public QwenModel(QwenModelArgs args, DeltaNetStatePool statePool, TensorShardSpec shard, TensorParallelGroup tpGroup, QwenVisionArgs visionArgs) Multimodal constructor with optional vision tower.- Parameters:
args- text hyperparameters.statePool- DeltaNet state pool.shard- TP shard, or null.tpGroup- TP group, or null.visionArgs- vision hyperparameters, ornullfor text-only.
-
-
Method Details
-
to
-
to
Moves parameters and the RoPE cos/sin tables todevice/dtype. RoPE tables stay float32 (device move only).- Specified by:
toin interfaceLayer- Overrides:
toin classLayerBlock- Parameters:
device- the compute device.dtype- the data type.- Returns:
- this layer.
-
params
-
numLayers
public int numLayers()Returns the number of hybrid decoder blocks.- Returns:
- number of hybrid decoder blocks.
-
layers
-
visual
Returns the vision tower.- Returns:
- vision tower, or
nullwhen text-only.
-
visionArgs
Returns the vision args.- Returns:
- vision args, or
nullwhen text-only.
-
embedTokens
-
kvCachePool
Returns the KV cache pool for full-attention layers, if installed.- Returns:
- KV pool, or
nullif unset.
-
deltaNetStatePool
Returns the DeltaNet recurrent/conv state pool.- Returns:
- DeltaNet state pool, or
nullwhen unused.
-
mtpAnchorPool
Returns the per-request MTP anchor store.- Returns:
- anchor pool, or
nullwhenmtp()is null.
-
mtp
Returns the native MTP draft head.- Returns:
- native MTP draft head, or
nullwhen not configured.
-
lastPreNormHidden
Returns the last captured post-final-norm hidden for MTP.- Returns:
- last pre-norm hidden, or
null.
-
setMtpAnchorAtWindowPosition
public void setMtpAnchorAtWindowPosition(int r) On a partial MTP accept at window positionr(checkpoint-replay path), restores the MTP anchor from the per-position hidden retained inverifyWindowNormalizedBufinstead of a second full-window forward.- Parameters:
r- accepted window position (0-indexed).
-
setMtpAnchorAtWindowPositions
public void setMtpAnchorAtWindowPositions(int[] positions) Batched counterpart ofsetMtpAnchorAtWindowPosition(int): restores each rowi's MTP anchor from its own retained window positionpositions[i]— needed when concurrent requests verified together in one round accept different numbers of draft tokens.- Parameters:
positions- accepted window position per row (0-indexed), lengthB.
-
shard
Returns the tensor-parallel shard description for this rank.- Returns:
- shard spec, or
nullfor unsharded models.
-
tpRank
public int tpRank()Returns this rank's tensor-parallel index.- Returns:
- TP rank (
0when unsharded).
-
setKvCachePool
Replaces the KV cache pool on every full-attention layer.- Parameters:
pool- new KV pool (must not benull).closePrevious-trueto close the previous pool when replaced.
-
forward
Forward pass.- Parameters:
tokens- token ids[B, S].startPos- cache start position.- Returns:
- logits
[B, S, V]in float32 (or[B, 1, V]when only the last position is scored — seeforward(Tensor, int, boolean)).
-
forward
Forward pass.- Parameters:
tokens- token ids[B, S].startPos- cache start position.allTokenLogits- whenfalseandS > 1, runlm_headonly on the last hidden state (sampling / decode). Whentrue, score every position (logprobs).- Returns:
- logits in float32.
-
forwardEmbeds
public Tensor forwardEmbeds(Tensor inputsEmbeds, int startPos, Tensor cos, Tensor sin, boolean allTokenLogits) Prefill from precomputed embeddings (multimodal splice) with optional interleaved mRoPE cos/sin. Whencos/sinare null, uses the standard 1D RoPE table slice for[startPos, startPos+S).- Parameters:
inputsEmbeds-[B, S, D]hidden states.startPos- cache start position.cos- optional[S, rotaryDim](or null).sin- optional[S, rotaryDim](or null).allTokenLogits- whether to score every position.- Returns:
- logits in float32.
-
spliceVisionEmbeds
public static Tensor spliceVisionEmbeds(Tensor embeds, int[] inputIds, Tensor visionEmbeds, int imageTokenId, int videoTokenId) Replaces image/video pad rows in text embeddings with vision features.- Parameters:
embeds-[1, S, D]text embeddings (mutated copy returned).inputIds- lengthStoken ids.visionEmbeds-[N, D]vision tokens in pad order.imageTokenId- image pad id.videoTokenId- video pad id.- Returns:
- spliced embeddings
[1, S, D](caller owns).
-
forward
-
forward
-
forward
public Tensor forward(Tensor tokens, int[] cachePositions, int[] ropePositions, boolean allTokenLogits) Decode forward with separate KV write positions and RoPE gather positions (needed for multimodalrope_delta).- Parameters:
tokens- token ids[B, 1].cachePositions- KV write positions.ropePositions- RoPE table gather positions.allTokenLogits- unused forS == 1.- Returns:
- logits in float32.
-
forwardDecodeGraph
Uniform decode forward with optional CUDA graph capture / replay.- Parameters:
tokens- token ids[B, 1].cachePositions- KV write positions (uniform length across rows).ropePositions- RoPE table gather positions.- Returns:
- logits in float32
[B, 1, V](graph path returns persistent buffer).
-
closeDecodeGraph
public void closeDecodeGraph()Releases CUDA graph resources for this rank. -
invalidateDecodeCudaGraphs
public void invalidateDecodeCudaGraphs()Drops captured decode / prefetch CUDA graphs while keeping durable token/RoPE/logits buffers. Required after MTP window verify orKvCachePool.truncateTo(int, int), which rebuild FlashInfer CSR tensors that a captured graph may still reference (replay → illegal memory access). -
forwardVerifyGraph
Uniform MTP window-verify forward (query lengthS = numDrafts + 1, every batch row sharing the same start position) with optional CUDA graph capture / replay.Stage 4 shadow-run: whenever
VerifyCudaGraph.enabled(), every call runs eager through the new stable-buffer / graph-capturable kernel path (seeAttentionContextdispatch inGatedAttention.forwardUniform), and bucket/warmup bookkeeping inverifyGraphSessionruns for real against live traffic shapes — butVerifyCudaGraph.captureEnabled()isfalseuntil Stage 5, sobeginCaptureis never reached. This lets the existing eagerforward(Tensor, int, boolean)path serve as the numeric go/no-go reference for the new kernel/buffer plumbing before Stage 5 adds the (separate) capture/replay risk.- Parameters:
tokens- token ids[B, S].startPos- cache start position (uniform across the batch).- Returns:
- logits in float32
[B, S, V](graph path returns persistent buffer).
-
forwardVerifyGraph
Ragged form offorwardVerifyGraph(Tensor, int): theBrows (concurrent requests) may be at different absolute positions. One graph is captured per(batch, windowLen); per-row positions, RoPE rows, KV write slots and the page-table CSR are rewritten in place before each replay. Falls back to the eager path when graphs are unavailable.- Parameters:
tokens- token ids[B, S].startPositions- KV write position of each row's first window token.- Returns:
- logits in float32
[B, S, V](the graph path returns a persistent buffer).
-
forwardVerifyGraphCodeEager
Diagnostic only: runs the exact code a verify CUDA graph captures (forwardVerifyGraphCore(Tensor, int[], Tensor, Tensor, Tensor)with the graph-mode stable buffers and FlashInfer verify kernel) eagerly, so replay output can be compared against identical kernels with no graph involved. Returns an owned copy of the float logits[B, S, V].- Parameters:
tokens- window token ids[B, S].startPos- cache start position.- Returns:
- owned logits.
-
forwardVerifyGraphCodeEager
Ragged form offorwardVerifyGraphCodeEager(Tensor, int).- Parameters:
tokens- window token ids[B, S].startPositions- per-row cache start position, lengthB.- Returns:
- owned logits.
-
closeVerifyGraph
public void closeVerifyGraph()Releases verify CUDA graph resources for this rank. -
invalidateVerifyCudaGraphs
public void invalidateVerifyCudaGraphs()Drops a captured verify CUDA graph while keeping durable token/RoPE/ logits buffers. Required afterKvCachePool.truncateTo(int, int)rebuilds (not bumps-in-place) the FlashInfer CSR tensors a captured graph may still reference (replay → illegal memory access). -
forwardBatchedVerify
Batched eager verify forward for a cohort of concurrent requests that may be at different absolute positions — the multi-request counterpart offorwardVerifyGraph(Tensor, int), which requires a single shared start position across the batch so it can be CUDA-graph-captured (seeVerifyCudaGraph#canGraphVerify). This always runs eager; heterogeneous-position batched cohorts do not graph-capture (a deliberately deferred fast-follow — see the batching plan).- Parameters:
tokens- token ids[B, windowLen].startPositions- KV write position of the window's first token per row.cacheLengths- inclusive cache length per row (prompt + already-sealed generation).- Returns:
- logits
[B, windowLen, V]in float32.
-
forward
-