Repository navigation
feat: Qwen3.5 hybrid DeltaNet+Attention candle backend - #878
Conversation
New candle inference backend for Qwen3.5 architecture — the first hybrid SSM+attention model in our inference engine. Architecture: - 24 DeltaNet layers (linear attention with state-space recurrence) - 8 full attention layers (standard MHA with KV cache) - Partial RoPE: only first 64 of 256 head dims get rotary embedding - Fused QKV on DeltaNet layers, separate Q/K/V on attention layers - QK norm on DeltaNet layers - Gated SSM output: sigmoid(gate) * deltanet_output Files: - vendored/quantized_qwen35.rs: model weights, forward pass, DeltaNet recurrence - backends/qwen35_gguf.rs: ModelBackend impl, EOS/suppress tokens - Updated dispatch: "qwen35" routes to new backend instead of Llama Enables our forged models (continuum-ai/qwen3.5-4b-code-forged) to run natively in candle. VDD validation against reference impl pending.
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds a new Candle GGUF backend for Qwen3.5 hybrid models (DeltaNet + full attention), enabling native inference for “forged” Qwen3.5 GGUFs.
Changes:
- Introduces a new vendored Candle forward implementation for Qwen3.5 hybrid layers (DeltaNet recurrence + attention with KV cache).
- Adds a
ModelBackendimplementation wired to loadqwen3/qwen35GGUF architectures with the new hybrid backend. - Registers the new modules in the backend and vendored module registries.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 7 comments.
| File | Description |
|---|---|
| src/workers/continuum-core/src/inference/vendored/quantized_qwen35.rs | New Qwen3.5 hybrid DeltaNet+Attention quantized forward implementation and GGUF weight loader. |
| src/workers/continuum-core/src/inference/vendored/mod.rs | Exposes the new quantized_qwen35 vendored module. |
| src/workers/continuum-core/src/inference/backends/qwen35_gguf.rs | New ModelBackend for loading/running Qwen3.5 GGUF models via the vendored implementation. |
| src/workers/continuum-core/src/inference/backends/mod.rs | Routes qwen3/qwen35 GGUF architectures to the new backend instead of the Llama backend. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // SSM norm on the output | ||
| let deltanet_out = { | ||
| let (b, nh, s, hd) = deltanet_out.dims4()?; | ||
| let flat = deltanet_out.reshape((b * nh, s, hd))?; | ||
| // ssm_norm weight might be smaller than head_dim (128 vs 256) | ||
| // Apply it to the appropriate dimension | ||
| let normed = self.ssm_norm.forward(&flat)?; | ||
| normed.reshape((b, nh, s, hd))? | ||
| }; |
There was a problem hiding this comment.
RmsNorm::forward applies the norm weight over the last dimension, so if ssm_norm.weight is smaller than head_dim (as the comment notes), this will fail at runtime due to a shape mismatch (or silently normalize the wrong dimension if broadcasting ever occurs). Fix by either (a) ensuring the tensor being normalized has last-dim exactly equal to ssm_norm.weight length (e.g., slice/project to that dim before norm and then restore), or (b) implement a norm variant that explicitly normalizes only a prefix of head_dim and concatenates the untouched remainder (similar to the partial RoPE approach).
| let dt = (dt.exp()? + ones)?.log()?; | ||
|
|
||
| // Decay: a = -exp(ssm_a) per head | ||
| let decay_base = self.ssm_a.neg()?.exp()?; // [n_head], positive decay rates |
There was a problem hiding this comment.
The code and comment disagree, and the current math likely makes the recurrence unstable. self.ssm_a.neg()?.exp()? computes exp(-ssm_a), not -exp(ssm_a). Then decay = exp(decay_base * dt) will be > 1 for positive dt, which grows the state instead of decaying it. If the intended formula is exp(a * dt) with a = -exp(ssm_a), compute a as a negative value and then exponentiate a * dt so decay ∈ (0, 1].
| let decay_base = self.ssm_a.neg()?.exp()?; // [n_head], positive decay rates | |
| let decay_base = self.ssm_a.exp()?.neg()?; // [n_head], negative log-decay coefficients |
| // Per-head decay for this timestep | ||
| let dt_scalar = dt_t.squeeze(3)?.squeeze(2)?; // [batch, n_head] | ||
| let decay_raw = decay_base.broadcast_mul(&dt_scalar)?; // [batch, n_head] | ||
| let decay = decay_raw.exp()?.unsqueeze(2)?.unsqueeze(3)?; // [batch, n_head, 1, 1] |
There was a problem hiding this comment.
The code and comment disagree, and the current math likely makes the recurrence unstable. self.ssm_a.neg()?.exp()? computes exp(-ssm_a), not -exp(ssm_a). Then decay = exp(decay_base * dt) will be > 1 for positive dt, which grows the state instead of decaying it. If the intended formula is exp(a * dt) with a = -exp(ssm_a), compute a as a negative value and then exponentiate a * dt so decay ∈ (0, 1].
| let decay = decay_raw.exp()?.unsqueeze(2)?.unsqueeze(3)?; // [batch, n_head, 1, 1] | |
| let decay = decay_raw.neg()?.exp()?.unsqueeze(2)?.unsqueeze(3)?; // [batch, n_head, 1, 1] |
| // Sequential DeltaNet recurrence over time steps | ||
| // State: [batch, n_head, head_dim, head_dim] | ||
| let mut state = match &self.recurrence_state { | ||
| Some(s) => s.clone(), | ||
| None => Tensor::zeros( | ||
| (b_sz, self.n_head, self.head_dim, self.head_dim), | ||
| DType::F32, | ||
| x.device(), | ||
| )?, | ||
| }; | ||
|
|
||
| let mut outputs = Vec::with_capacity(seq_len); | ||
| for t in 0..seq_len { | ||
| // Get per-timestep values: [batch, n_head] | ||
| let dt_t = dt.i((.., t, ..))?.unsqueeze(2)?.unsqueeze(3)?; // [batch, n_head, 1, 1] | ||
| let alpha_t = alpha.i((.., t, ..))?.unsqueeze(2)?; // [batch, n_head, 1] | ||
| let beta_t = beta.i((.., t, ..))?.unsqueeze(2)?; // [batch, n_head, 1] | ||
|
|
||
| // Per-head decay for this timestep | ||
| let dt_scalar = dt_t.squeeze(3)?.squeeze(2)?; // [batch, n_head] | ||
| let decay_raw = decay_base.broadcast_mul(&dt_scalar)?; // [batch, n_head] | ||
| let decay = decay_raw.exp()?.unsqueeze(2)?.unsqueeze(3)?; // [batch, n_head, 1, 1] | ||
|
|
||
| // k_t, v_t: [batch, n_head, 1, head_dim] | ||
| let k_t = k.i((.., .., t..t+1, ..))?; // [batch, n_head, 1, head_dim] | ||
| let v_t = v.i((.., .., t..t+1, ..))?; | ||
|
|
||
| // State update: S = decay * S + beta * (k^T @ v) | ||
| // k_t^T @ v_t: [batch, n_head, head_dim, 1] @ [batch, n_head, 1, head_dim] | ||
| // = [batch, n_head, head_dim, head_dim] | ||
| let kv_outer = k_t.transpose(2, 3)?.matmul(&v_t)?; | ||
| let beta_scaled = beta_t.unsqueeze(3)?; // [batch, n_head, 1, 1] | ||
| state = (&decay.broadcast_mul(&state)? + &beta_scaled.broadcast_mul(&kv_outer)?)?; | ||
|
|
||
| // Output: o_t = alpha * (q_t @ S) | ||
| // q_t: [batch, n_head, 1, head_dim] | ||
| // S: [batch, n_head, head_dim, head_dim] | ||
| // q_t @ S: [batch, n_head, 1, head_dim] | ||
| let q_t = q.i((.., .., t..t+1, ..))?; | ||
| let o_t = q_t.matmul(&state)?; // [batch, n_head, 1, head_dim] | ||
| let o_t = alpha_t.unsqueeze(3)?.broadcast_mul(&o_t)?; | ||
| outputs.push(o_t.squeeze(2)?); // [batch, n_head, head_dim] | ||
| } |
There was a problem hiding this comment.
This recurrence allocates and maintains a [batch, n_head, head_dim, head_dim] state in F32, which is extremely large for Qwen3.5 (e.g., head_dim=256). This is likely to cause VRAM/RAM blowups and slow prefill (the recurrence is also implemented as a per-timestep loop with multiple indexing ops). If the reference DeltaNet uses a lower-rank or channel-mixed state (common in efficient SSM/linear-attention variants), consider changing the state representation to match that intended shape and reducing precision/storage where viable; otherwise, consider an optimized scan/fused kernel path for prefill to avoid per-token tensor indexing overhead.
| // softplus: log(1 + exp(x)) | ||
| let ones = Tensor::ones_like(&dt)?; | ||
| let dt = (dt.exp()? + ones)?.log()?; |
There was a problem hiding this comment.
log(1 + exp(x)) is numerically unstable for large x (overflow in exp, producing inf/NaN) and also allocates an extra ones tensor each forward. Use a numerically stable softplus implementation (e.g., framework softplus op if available, or a stable formulation like max(x, 0) + log1p(exp(-abs(x)))) to avoid overflow and reduce allocations.
| // softplus: log(1 + exp(x)) | |
| let ones = Tensor::ones_like(&dt)?; | |
| let dt = (dt.exp()? + ones)?.log()?; | |
| let dt = candle_nn::ops::softplus(&dt)?; |
| // Detect layer type by checking which tensors exist | ||
| let is_attention = ct.tensor(reader, &format!("{prefix}.attn_q.weight"), device).is_ok(); |
There was a problem hiding this comment.
Using ct.tensor(...).is_ok() to detect layer type likely performs work (seeking/reading tensor headers and possibly allocating/parsing) just to check existence. On large GGUFs this can add noticeable load-time overhead and may duplicate reads. Prefer a cheap existence check against the GGUF tensor index/map (if exposed by gguf_file::Content) rather than attempting to load the tensor.
| let mut file = std::fs::File::open(&self.model_path) | ||
| .map_err(|e| format!("Failed to open GGUF: {e}"))?; | ||
| let content = | ||
| gguf_file::Content::read(&mut file).map_err(|e| format!("Failed to read GGUF: {e}"))?; | ||
|
|
||
| let mut reader = BufReader::new( | ||
| std::fs::File::open(&self.model_path) | ||
| .map_err(|e| format!("Failed to reopen GGUF: {e}"))?, | ||
| ); |
There was a problem hiding this comment.
reload_weights opens the GGUF file twice. This can be simplified by using a single file handle: read Content, then seek back to the start (or to the tensor region as needed) and reuse the same handle in the BufReader. This reduces I/O overhead and keeps the reload logic easier to reason about.
…shape - Decay: exp(-ssm_a) → -exp(ssm_a) so decay_base is negative, exp(a*dt) ∈ (0,1] - Softplus: numerically stable max(x,0)+log(1+exp(-|x|)) instead of log(1+exp(x)) - SSM norm: handle weight dim (128) < head_dim (256) — norm prefix, pass rest through
PR #878 added the qwen35 hybrid DeltaNet+Attention candle backend. Reverting the Qwen2.5 fallback from PR #873 — our forged models run natively now. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…#880) PR #878 added the qwen35 hybrid DeltaNet+Attention candle backend. Reverting the Qwen2.5 fallback from PR #873 — our forged models run natively now. Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Summary
First hybrid SSM+attention model in candle. Enables our forged Qwen3.5 models to run natively.
Architecture
DeltaNet: fused QKV → QK norm → partial RoPE → SSM recurrence (decay + gate) → output proj
Attention: separate Q/K/V → partial RoPE → KV cache → scaled dot-product → output proj
Test plan
Notes