#4004·candle

quantized_phi3: partial rotary embeddings fail with "inconsistent last dim size in rope"

Author: czetiCreated Sep 27, 2026Updated Sep 27, 2026

What is the bug?

Loading and running a Phi-3/Phi-4-family GGUF model with partial_rotary_factor < 1.0 through candle-transformers::models::quantized_phi3 panics inside model.forward() with a RoPE dimension assertion. Models with full rotary (partial_rotary_factor = 1.0) are unaffected.

Reproduction

Model: microsoft/Phi-4-mini-instruct (Q4_K_M GGUF, official conversion)

rust
use candle_core::Device;
use candle_transformers::models::quantized_phi3;

let mut file = std::fs::File::open("Phi-4-mini-instruct-Q4_K_M.gguf")?;
let content = candle_core::quantized::gguf_file::Content::read(&mut file)?;
let mut model = quantized_phi3::ModelWeights::from_gguf(
    false, content, &mut file, &Device::Cpu,
)?;

let tokens = candle_core::Tensor::new(&[1u32, 2, 3], &Device::Cpu)?.unsqueeze(0)?;
let logits = model.forward(&tokens, 0)?;

Actual behavior

Error: Internal error: Forward pass: inconsistent last dim size in rope
    [1, 24, 14, 128] [14, 48] [14, 48]

Expected behavior

Forward pass succeeds; logits are produced.

Root cause analysis

Phi-4-mini-instruct has:

  • head_dim = 128
  • partial_rotary_factor = 0.75 → rotary_dim = 96

Candle correctly reads the metadata and builds RoPE cos/sin tables of shape [seq, rotary_dim/2] = [14, 48]. However, in quantized_phi3.rs::forward_attn, the full q/k slices of shape [b, n_head, seq, head_dim] = [1, 24, 14, 128] are passed directly into candle_nn::rotary_emb::rope without first:

  1. Narrowing the last dim to rotary_dim = 96
  2. Applying rope to that slice
  3. Concatenating the un-rotated tail [..., 96:128] back on

Since rope asserts xs.last_dim == cos.last_dim * 2 (i.e. 128 == 96), it fails.

The fix would be, inside forward_attn:

rust
let rotary_dim = cos.dim(1)? * 2;  // 96
let q_rot  = q.narrow(D::Minus1, 0, rotary_dim)?;
let q_pass = q.narrow(D::Minus1, rotary_dim, head_dim - rotary_dim)?;
let q_rot  = candle_nn::rotary_emb::rope(&q_rot, &cos, &sin)?;
let q = Tensor::cat(&[&q_rot, &q_pass], D::Minus1)?;
// same for k

Affected models

Model partial_rotary_factor rotary_dim Affected?
Phi-3-mini-4k 1.0 128 No
Phi-3.5-mini-instruct 1.0 128 No
Phi-4-mini-instruct 0.75 96 Yes
Phi-3.5-MoE 0.5 64 Yes

Any Phi-3/Phi-4-family GGUF whose metadata declares phi3.rope.dimension_count < head_dim will hit this.

Environment

  • candle-core = "0.10.2"
  • candle-transformers = "0.10.2"
  • Rust stable, CPU path (Device::Cpu)