Skip to content

feat: Qwen3.5 hybrid DeltaNet+Attention candle backend - #878

Merged
joelteply merged 2 commits into
mainfrom
feat/qwen35-candle-backend
Apr 13, 2026
Merged

joelteply merged 2 commits into
mainfrom
feat/qwen35-candle-backend

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

First hybrid SSM+attention model in candle. Enables our forged Qwen3.5 models to run natively.

  • 24 DeltaNet layers (linear attention with state-space recurrence)
  • 8 full attention layers (standard MHA with KV cache)
  • Partial RoPE (64 of 256 head dims)
  • Layer type auto-detected from GGUF tensor names

Architecture

Input → tok_embeddings → 32 layers → output_norm → output_head
  Layer 0-6,8-10,12-14,16-18,20-22,24-26,28-30: DeltaNet
  Layer 7,11,15,19,23,27,31: Full Attention

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

  • cargo check — compiles clean
  • GGUF tensor inspection confirms layer type detection works
  • VDD: load qwen3.5-4b-code-forged-Q4_K_M.gguf, run prompt, compare logits against reference
  • Integration: persona inference end-to-end

Notes

  • DeltaNet recurrence math needs VDD validation against llama.cpp or HF reference
  • LoRA not yet supported (needs tensor name mapping for hybrid layers)
  • Conv1d state management is stubbed (conv_state field exists, not wired into recurrence yet)

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.
Copilot AI review requested due to automatic review settings April 13, 2026 04:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ModelBackend implementation wired to load qwen3/qwen35 GGUF 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.

Comment on lines +401 to +409
// 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))?
};

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copilot uses AI. Check for mistakes.
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

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
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

Copilot uses AI. Check for mistakes.
// 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]

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
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]

Copilot uses AI. Check for mistakes.
Comment on lines +352 to +394
// 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]
}

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +341 to +343
// softplus: log(1 + exp(x))
let ones = Tensor::ones_like(&dt)?;
let dt = (dt.exp()? + ones)?.log()?;

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
// softplus: log(1 + exp(x))
let ones = Tensor::ones_like(&dt)?;
let dt = (dt.exp()? + ones)?.log()?;
let dt = candle_nn::ops::softplus(&dt)?;

Copilot uses AI. Check for mistakes.
Comment on lines +531 to +532
// Detect layer type by checking which tensors exist
let is_attention = ct.tensor(reader, &format!("{prefix}.attn_q.weight"), device).is_ok();

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +83 to +91
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}"))?,
);

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
…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
@joelteply
joelteply merged commit 43e22e4 into main Apr 13, 2026
10 checks passed
@joelteply
joelteply deleted the feat/qwen35-candle-backend branch April 13, 2026 05:23
joelteply added a commit that referenced this pull request Apr 13, 2026
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]>
joelteply added a commit that referenced this pull request Apr 13, 2026
…#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants