Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb79fae5e0
|
||
|
|
cc114cc781
|
@@ -23,7 +23,7 @@
|
||||
use anyhow::Result;
|
||||
use candle_core::{DType, Device, IndexOp, Tensor};
|
||||
|
||||
use super::TextConfig;
|
||||
use super::{RopeParameters, TextConfig};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RotaryEmbedding {
|
||||
@@ -97,8 +97,30 @@ fn mrope_masks(
|
||||
|
||||
impl RotaryEmbedding {
|
||||
pub fn new(dtype: DType, cfg: &TextConfig, dev: &Device) -> Result<Self> {
|
||||
let head_dim = cfg.head_dim;
|
||||
let rope = &cfg.rope_parameters;
|
||||
Self::from_parts(
|
||||
dtype,
|
||||
cfg.head_dim,
|
||||
cfg.max_position_embeddings,
|
||||
&cfg.rope_parameters,
|
||||
dev,
|
||||
)
|
||||
}
|
||||
|
||||
/// Build from the three things the rotary actually reads, rather
|
||||
/// than from a whole config.
|
||||
///
|
||||
/// `qwen4_exp` declares an identical `rope_parameters` block and the
|
||||
/// same `head_dim` (spec §7), so it reuses this module unchanged —
|
||||
/// but it owns a different config type, and fabricating a foreign
|
||||
/// one to pass through here would be a lie the compiler could not
|
||||
/// catch.
|
||||
pub fn from_parts(
|
||||
dtype: DType,
|
||||
head_dim: usize,
|
||||
max_seq_len: usize,
|
||||
rope: &RopeParameters,
|
||||
dev: &Device,
|
||||
) -> Result<Self> {
|
||||
let rotary_dim = (head_dim as f32 * rope.partial_rotary_factor) as usize;
|
||||
if !rotary_dim.is_multiple_of(2) {
|
||||
anyhow::bail!(
|
||||
@@ -113,7 +135,6 @@ impl RotaryEmbedding {
|
||||
rope.partial_rotary_factor
|
||||
);
|
||||
}
|
||||
let max_seq_len = cfg.max_position_embeddings;
|
||||
let inv_freq: Vec<f32> = (0..rotary_dim)
|
||||
.step_by(2)
|
||||
.map(|i| 1f32 / rope.rope_theta.powf(i as f64 / rotary_dim as f64) as f32)
|
||||
|
||||
@@ -84,7 +84,10 @@ impl Attention {
|
||||
o_proj: linear(vb, "o_proj", attn_width, cfg.hidden_size)?,
|
||||
q_norm: Qwen3_5RmsNorm::load(&vb.pp("q_norm"), head_dim, cfg.rms_norm_eps)?,
|
||||
k_norm: Qwen3_5RmsNorm::load(&vb.pp("k_norm"), head_dim, cfg.rms_norm_eps)?,
|
||||
indexer: Indexer::load(vb, cfg)?,
|
||||
// The indexer is a submodule of the attention block, not a
|
||||
// sibling: `self_attn.indexer.index_qk_proj`, per the
|
||||
// checkpoint's own index.
|
||||
indexer: Indexer::load(&vb.pp("indexer"), cfg)?,
|
||||
num_heads,
|
||||
num_kv_heads,
|
||||
num_kv_groups: num_heads / num_kv_heads,
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
//! narrows what it may attend.
|
||||
//! - [`linear_attn`] — the other three layers in four, reused whole
|
||||
//! from `qwen3_5` with two settings corrected.
|
||||
//! - [`model`] — embeddings in, logits out; four streams, one
|
||||
//! n-gram lookup, and no final norm.
|
||||
//! - [`moe`] — the FFN every layer has, loaded from fused expert
|
||||
//! tensors instead of 512 modules.
|
||||
//! - [`ple`] — the hashed n-gram table on layer 1: how its rows
|
||||
@@ -35,6 +37,7 @@ pub mod decoder;
|
||||
pub mod full_attn;
|
||||
pub mod hyper;
|
||||
pub mod linear_attn;
|
||||
pub mod model;
|
||||
pub mod moe;
|
||||
pub mod ple;
|
||||
pub mod qsa;
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
//! `qwen4_exp` end to end: embeddings in, logits out.
|
||||
//!
|
||||
//! ```text
|
||||
//! input_ids ─ embed_tokens ─► x [B,T,2560]
|
||||
//! │ repeated hc_count times
|
||||
//! ▼
|
||||
//! h [B,T,10240] four identical streams
|
||||
//! │
|
||||
//! 48 decoder layers (PLE joins at layer 1)
|
||||
//! │
|
||||
//! hyper_connection_mixer collapses 4 → 1
|
||||
//! ▼
|
||||
//! lm_head
|
||||
//! ```
|
||||
//!
|
||||
//! Three things about this shape are unlike every other model we serve,
|
||||
//! and all three are visible in the checkpoint rather than inferred:
|
||||
//!
|
||||
//! 1. **The residual between layers is `hidden_size * hc_count` wide**,
|
||||
//! initialised as four copies of the token embedding.
|
||||
//! 2. **There is no `model.norm`.** The index has
|
||||
//! `hyper_connection_mixer.{hc_norm, input_mix_weight_down,
|
||||
//! input_mix_weight_up}` and nothing else before `lm_head`, so the
|
||||
//! mixer's own `hc_norm` is the only normalisation the logits see.
|
||||
//! It also has **no `block_inject_weight`** — it collapses the
|
||||
//! streams rather than scattering back into them.
|
||||
//! 3. **The n-gram embedding is computed once per step, not per
|
||||
//! layer.** It depends only on the input ids, and exactly one layer
|
||||
//! consumes it.
|
||||
//!
|
||||
//! The weights hang off two different roots: everything structural is
|
||||
//! under `model.language_model`, but `lm_head` is at the top level.
|
||||
//!
|
||||
//! See `doc/qwen4_exp-port-spec.md`.
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use candle_core::{DType, Device, IndexOp, Module, Tensor};
|
||||
use candle_nn::var_builder::ShardedVarBuilder;
|
||||
use candle_nn::{Embedding, Linear};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::harness::arch::qwen3_5::rope::RotaryEmbedding;
|
||||
|
||||
use super::config::{Config, TextConfig};
|
||||
use super::decoder::DecoderLayer;
|
||||
use super::hyper::HyperConnection;
|
||||
use super::ple::{NGramHasher, NGramTable, ShardedNGramTable};
|
||||
|
||||
/// The hashed n-gram lookup, hoisted to the model because it is a
|
||||
/// function of the input ids alone.
|
||||
struct NGramEmbedding {
|
||||
hasher: NGramHasher,
|
||||
table: Box<dyn NGramTable>,
|
||||
heads: usize,
|
||||
head_dim: usize,
|
||||
/// The previous `ngram_size - 1` ids per batch row, so a decode step
|
||||
/// hashes the same n-grams a prefill would. Upstream keeps this as a
|
||||
/// `(B, 2)` "conv state" on the PLE layer; here it is what it is —
|
||||
/// token ids, not activations.
|
||||
carried: Vec<Vec<i64>>,
|
||||
}
|
||||
|
||||
impl NGramEmbedding {
|
||||
/// `[B, T, heads * head_dim]` for this step's ids.
|
||||
fn forward(&mut self, ids: &[Vec<i64>], device: &Device, dtype: DType) -> Result<Tensor> {
|
||||
let seq_len = ids.first().map_or(0, Vec::len);
|
||||
if self.carried.len() != ids.len() {
|
||||
self.carried = vec![Vec::new(); ids.len()];
|
||||
}
|
||||
let mut rows = Vec::with_capacity(ids.len());
|
||||
for (row, step) in ids.iter().enumerate() {
|
||||
let mut history = self.carried[row].clone();
|
||||
history.extend_from_slice(step);
|
||||
let per_position = self.hasher.rows(&history, step.len())?;
|
||||
let flat: Vec<i64> = per_position.into_iter().flatten().collect();
|
||||
rows.push(
|
||||
self.table
|
||||
.gather(&flat)?
|
||||
.reshape((step.len(), self.heads * self.head_dim))?,
|
||||
);
|
||||
// Keep only what the next step's shifts can still reach.
|
||||
let keep = self.hasher.context_len().min(history.len());
|
||||
self.carried[row] = history[history.len() - keep..].to_vec();
|
||||
}
|
||||
let stacked = Tensor::stack(&rows, 0)?
|
||||
.to_dtype(dtype)?
|
||||
.to_device(device)?;
|
||||
debug_assert_eq!(stacked.dims()[1], seq_len);
|
||||
Ok(stacked)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
for row in &mut self.carried {
|
||||
row.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Qwen4ExpForCausalLM {
|
||||
embed_tokens: Embedding,
|
||||
layers: Vec<DecoderLayer>,
|
||||
/// `hyper_connection_mixer` — `use_combine = false`, so it collapses
|
||||
/// rather than scatters, and there is no final norm beside it.
|
||||
mixer: HyperConnection,
|
||||
lm_head: Linear,
|
||||
ngram: Option<NGramEmbedding>,
|
||||
rotary: Arc<RotaryEmbedding>,
|
||||
hc_count: usize,
|
||||
device: Device,
|
||||
dtype: DType,
|
||||
}
|
||||
|
||||
impl Qwen4ExpForCausalLM {
|
||||
pub fn load(
|
||||
cfg: &Config,
|
||||
dtype: DType,
|
||||
device: &Device,
|
||||
vb: &ShardedVarBuilder,
|
||||
) -> Result<Self> {
|
||||
let text = &cfg.text_config;
|
||||
// `RotaryEmbedding` reads a qwen3_5 config; the rope block is the
|
||||
// same type and the same values (spec §7), so the reuse is real
|
||||
// rather than a coincidence — see `config::tests`.
|
||||
let rotary = Arc::new(rotary_for(text, dtype, device)?);
|
||||
|
||||
let root = vb.pp("model").pp("language_model");
|
||||
let embed_weight = root
|
||||
.pp("embed_tokens")
|
||||
.get((text.vocab_size, text.hidden_size), "weight")
|
||||
.context("load 'model.language_model.embed_tokens.weight'")?;
|
||||
let embed_tokens = Embedding::new(embed_weight, text.hidden_size);
|
||||
|
||||
let layers_vb = root.pp("layers");
|
||||
let mut layers = Vec::with_capacity(text.num_hidden_layers);
|
||||
for i in 0..text.num_hidden_layers {
|
||||
layers.push(
|
||||
DecoderLayer::load(text, rotary.clone(), i, &layers_vb.pp(i))
|
||||
.with_context(|| format!("load decoder layer {i}"))?,
|
||||
);
|
||||
}
|
||||
|
||||
let mixer = HyperConnection::load(
|
||||
&root.pp("hyper_connection_mixer"),
|
||||
text.hidden_size,
|
||||
text.hc_count,
|
||||
text.hc_lowrank,
|
||||
text.rms_norm_eps,
|
||||
// No block_inject_weight in the checkpoint: this one ends
|
||||
// the streams rather than feeding a sublayer.
|
||||
false,
|
||||
)
|
||||
.context("load hyper_connection_mixer")?;
|
||||
|
||||
let lm_head_weight = vb
|
||||
.pp("lm_head")
|
||||
.get((text.vocab_size, text.hidden_size), "weight")
|
||||
.context("load 'lm_head.weight'")?;
|
||||
|
||||
let ngram = match text.ple_layers().first() {
|
||||
Some(layer) => Some(load_ngram(text, &layers_vb.pp(*layer).pp("ple"))?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
embed_tokens,
|
||||
layers,
|
||||
mixer,
|
||||
lm_head: Linear::new(lm_head_weight, None),
|
||||
ngram,
|
||||
rotary,
|
||||
hc_count: text.hc_count,
|
||||
device: device.clone(),
|
||||
dtype,
|
||||
})
|
||||
}
|
||||
|
||||
/// `input_ids` is `(B, T)`; `offset` is the sequence position the
|
||||
/// first of them sits at. Returns logits `(B, T, vocab)`.
|
||||
pub fn forward(&mut self, input_ids: &Tensor, offset: usize) -> Result<Tensor> {
|
||||
let (batch, seq_len) = input_ids.dims2()?;
|
||||
|
||||
// Four identical streams — the residual this architecture
|
||||
// carries between layers, not one.
|
||||
let x = self.embed_tokens.forward(input_ids)?;
|
||||
let mut h = x.repeat((1, 1, self.hc_count))?;
|
||||
|
||||
let (cos, sin) = self.rotary.plain_cos_sin(offset, seq_len)?;
|
||||
let mask = if seq_len > 1 {
|
||||
Some(self.causal_mask(batch, seq_len, offset)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Computed once: it is a function of the ids, and one layer
|
||||
// consumes it.
|
||||
let ngram = match &mut self.ngram {
|
||||
Some(ngram) => {
|
||||
let ids = ids_to_i64(input_ids)?;
|
||||
Some(ngram.forward(&ids, &self.device, self.dtype)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
for (i, layer) in self.layers.iter_mut().enumerate() {
|
||||
h = layer
|
||||
.forward(&h, ngram.as_ref(), mask.as_ref(), &cos, &sin, offset)
|
||||
.with_context(|| format!("layer {i}"))?;
|
||||
}
|
||||
|
||||
// The mixer's hc_norm is the only normalisation before the head.
|
||||
let x = self.mixer.collapse(&h)?;
|
||||
Ok(self.lm_head.forward(&x)?)
|
||||
}
|
||||
|
||||
pub fn clear_kv_cache(&mut self) -> Result<()> {
|
||||
for layer in &mut self.layers {
|
||||
layer.clear_kv_cache()?;
|
||||
}
|
||||
if let Some(ngram) = &mut self.ngram {
|
||||
ngram.reset();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn causal_mask(&self, b: usize, tgt: usize, offset: usize) -> Result<Tensor> {
|
||||
let minf = f32::NEG_INFINITY;
|
||||
let mask: Vec<f32> = (0..tgt)
|
||||
.flat_map(|i| (0..(tgt + offset)).map(move |j| if j <= i + offset { 0. } else { minf }))
|
||||
.collect();
|
||||
Ok(
|
||||
Tensor::from_vec(mask, (b, 1, tgt, tgt + offset), &self.device)?
|
||||
.to_dtype(self.dtype)?,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn load_ngram(cfg: &TextConfig, ple_vb: &ShardedVarBuilder) -> Result<NGramEmbedding> {
|
||||
let vb = ple_vb.pp("ple_embedding");
|
||||
let heads = cfg.ngram_heads();
|
||||
let head_dim = cfg.ngram_head_dim();
|
||||
|
||||
// The three derived buffers ship as I64. Reading them through a
|
||||
// bf16 VarBuilder would silently round multipliers of order 1e13
|
||||
// and prime vocab sizes of 2e7 into nonsense, so the dtype is
|
||||
// forced rather than inherited.
|
||||
let ints = vb.to_dtype(DType::I64);
|
||||
let multipliers = int_vec(&ints, "layer_multipliers", cfg.ngram_size)?;
|
||||
let vocab_sizes = int_vec(&ints, "ngram_heads_vocab_sizes", heads)?;
|
||||
let offsets = int_vec(&ints, "ngram_heads_offsets", heads)?;
|
||||
|
||||
// Total rows: the last head's offset plus its own vocab, rounded up
|
||||
// the way the checkpoint pads it.
|
||||
let declared: i64 = offsets[heads - 1] + vocab_sizes[heads - 1];
|
||||
let pad = cfg.make_ngram_vocab_size_divisible_by.max(1) as i64;
|
||||
let rows = (declared + pad - 1) / pad * pad;
|
||||
let rows = rows as usize;
|
||||
ensure!(
|
||||
rows.is_multiple_of(cfg.split_ngram_parts),
|
||||
"{rows} padded rows do not divide into {} shards",
|
||||
cfg.split_ngram_parts
|
||||
);
|
||||
|
||||
let table = ShardedNGramTable::load(
|
||||
&vb.pp("ngram_embedding"),
|
||||
cfg.split_ngram_parts,
|
||||
rows,
|
||||
head_dim,
|
||||
)?;
|
||||
|
||||
Ok(NGramEmbedding {
|
||||
hasher: NGramHasher::new(
|
||||
cfg.ngram_size,
|
||||
cfg.heads_per_ngram,
|
||||
multipliers,
|
||||
vocab_sizes,
|
||||
offsets,
|
||||
cfg.eos_token_id,
|
||||
)?,
|
||||
table: Box::new(table),
|
||||
heads,
|
||||
head_dim,
|
||||
carried: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn int_vec(vb: &ShardedVarBuilder, name: &str, len: usize) -> Result<Vec<i64>> {
|
||||
let t = vb
|
||||
.get(len, name)
|
||||
.with_context(|| format!("load '{}/{name}'", vb.prefix()))?;
|
||||
Ok(t.to_dtype(DType::I64)?.to_vec1::<i64>()?)
|
||||
}
|
||||
|
||||
fn ids_to_i64(input_ids: &Tensor) -> Result<Vec<Vec<i64>>> {
|
||||
let ids = input_ids.to_dtype(DType::I64)?;
|
||||
let (batch, _) = ids.dims2()?;
|
||||
let mut out = Vec::with_capacity(batch);
|
||||
for row in 0..batch {
|
||||
out.push(ids.i(row)?.to_vec1::<i64>()?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Build the rotary tables from this architecture's config.
|
||||
///
|
||||
/// The rotary reads only `head_dim`, `max_position_embeddings` and the
|
||||
/// `rope_parameters` block, and this checkpoint declares all three
|
||||
/// identically to Qwen3.6 (spec §7) — so `qwen3_5`'s module is reused
|
||||
/// as-is, through the parts it actually needs rather than through a
|
||||
/// fabricated config.
|
||||
fn rotary_for(cfg: &TextConfig, dtype: DType, device: &Device) -> Result<RotaryEmbedding> {
|
||||
RotaryEmbedding::from_parts(
|
||||
dtype,
|
||||
cfg.head_dim,
|
||||
cfg.max_position_embeddings,
|
||||
&cfg.rope_parameters,
|
||||
device,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use candle_nn::var_builder::ShardedSafeTensors;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A model small enough to build in a test and complete enough to
|
||||
/// exercise every loader: two layers so both attention flavours
|
||||
/// appear, PLE on layer 1 because `ple_layer_ids` is one-indexed,
|
||||
/// and a sharded n-gram table with real prime vocab sizes.
|
||||
const TINY: &str = r#"{
|
||||
"model_type": "qwen4_exp",
|
||||
"tie_word_embeddings": false,
|
||||
"text_config": {
|
||||
"vocab_size": 32, "hidden_size": 8, "num_hidden_layers": 2,
|
||||
"num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 4,
|
||||
"max_position_embeddings": 64, "rms_norm_eps": 1e-6,
|
||||
"hidden_act": "silu", "eos_token_id": 3,
|
||||
"full_attention_interval": 2,
|
||||
"rope_parameters": {"rope_theta": 10000.0, "partial_rotary_factor": 0.5},
|
||||
"hc_count": 2, "hc_lowrank": 4,
|
||||
"ple_layer_ids": [2], "ple_embed_dim": 8, "ple_conv_kernel_size": 2,
|
||||
"ngram_size": 3, "heads_per_ngram": 2,
|
||||
"ngram_vocab_size_base": 10,
|
||||
"make_ngram_vocab_size_divisible_by": 4,
|
||||
"split_ngram_parts": 2,
|
||||
"indexer_n_heads": 2, "indexer_kv_heads": 1, "indexer_head_dim": 4,
|
||||
"indexer_budget": 8, "indexer_compress_ratio": 2,
|
||||
"linear_num_key_heads": 1, "linear_key_head_dim": 4,
|
||||
"linear_num_value_heads": 2, "linear_value_head_dim": 4,
|
||||
"linear_conv_kernel_dim": 2,
|
||||
"mamba_ssm_dtype": "float32", "output_gate_type": "sigmoid",
|
||||
"num_experts": 2, "num_experts_per_tok": 1,
|
||||
"moe_intermediate_size": 4, "shared_expert_intermediate_size": 4
|
||||
}
|
||||
}"#;
|
||||
|
||||
/// Per-head vocab sizes and their running offsets, as the checkpoint
|
||||
/// would ship them: four distinct primes, cumulative offsets, padded
|
||||
/// to a multiple of `make_ngram_vocab_size_divisible_by`.
|
||||
const VOCABS: [i64; 4] = [11, 13, 17, 19];
|
||||
const OFFSETS: [i64; 4] = [0, 11, 24, 41];
|
||||
const TABLE_ROWS: usize = 60; // 41 + 19, already a multiple of 4
|
||||
|
||||
fn tensors(cfg: &TextConfig) -> HashMap<String, Tensor> {
|
||||
let dev = Device::Cpu;
|
||||
let mut t: HashMap<String, Tensor> = HashMap::new();
|
||||
// Small non-zero values: zeros would hide a transposed load, and
|
||||
// large ones make the MoE softmax degenerate.
|
||||
let mut seed = 0u32;
|
||||
let mut rand = |shape: Vec<usize>| {
|
||||
let n: usize = shape.iter().product();
|
||||
let v: Vec<f32> = (0..n)
|
||||
.map(|i| {
|
||||
seed = seed
|
||||
.wrapping_mul(1664525)
|
||||
.wrapping_add(1013904223 + i as u32);
|
||||
((seed >> 16) as f32 / 32768.0 - 1.0) * 0.1
|
||||
})
|
||||
.collect();
|
||||
Tensor::from_vec(v, shape, &dev).unwrap()
|
||||
};
|
||||
|
||||
let (h, hc) = (cfg.hidden_size, cfg.hc_count);
|
||||
let wide = h * hc;
|
||||
t.insert("lm_head.weight".to_string(), rand(vec![cfg.vocab_size, h]));
|
||||
let root = "model.language_model";
|
||||
t.insert(
|
||||
format!("{root}.embed_tokens.weight"),
|
||||
rand(vec![cfg.vocab_size, h]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{root}.hyper_connection_mixer.hc_norm.weight"),
|
||||
rand(vec![wide]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{root}.hyper_connection_mixer.input_mix_weight_down.weight"),
|
||||
rand(vec![cfg.hc_lowrank, wide]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{root}.hyper_connection_mixer.input_mix_weight_up.weight"),
|
||||
rand(vec![wide, cfg.hc_lowrank]),
|
||||
);
|
||||
|
||||
for i in 0..cfg.num_hidden_layers {
|
||||
let l = format!("{root}.layers.{i}");
|
||||
for which in ["attn_hyper_connection", "mlp_hyper_connection"] {
|
||||
t.insert(format!("{l}.{which}.hc_norm.weight"), rand(vec![wide]));
|
||||
t.insert(
|
||||
format!("{l}.{which}.input_mix_weight_down.weight"),
|
||||
rand(vec![cfg.hc_lowrank, wide]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{l}.{which}.input_mix_weight_up.weight"),
|
||||
rand(vec![wide, cfg.hc_lowrank]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{l}.{which}.block_inject_weight.weight"),
|
||||
rand(vec![hc, wide]),
|
||||
);
|
||||
}
|
||||
|
||||
if cfg.is_full_attention(i) {
|
||||
let a = format!("{l}.self_attn");
|
||||
let heads = cfg.num_attention_heads * cfg.head_dim;
|
||||
t.insert(format!("{a}.q_proj.weight"), rand(vec![heads * 2, h]));
|
||||
t.insert(
|
||||
format!("{a}.k_proj.weight"),
|
||||
rand(vec![cfg.num_key_value_heads * cfg.head_dim, h]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{a}.v_proj.weight"),
|
||||
rand(vec![cfg.num_key_value_heads * cfg.head_dim, h]),
|
||||
);
|
||||
t.insert(format!("{a}.o_proj.weight"), rand(vec![h, heads]));
|
||||
t.insert(format!("{a}.q_norm.weight"), rand(vec![cfg.head_dim]));
|
||||
t.insert(format!("{a}.k_norm.weight"), rand(vec![cfg.head_dim]));
|
||||
let fused = (cfg.indexer_n_heads + cfg.indexer_kv_heads) * cfg.indexer_head_dim;
|
||||
t.insert(
|
||||
format!("{a}.indexer.index_qk_proj.weight"),
|
||||
rand(vec![fused, h]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{a}.indexer.q_layernorm.weight"),
|
||||
rand(vec![cfg.indexer_head_dim]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{a}.indexer.k_layernorm.weight"),
|
||||
rand(vec![cfg.indexer_head_dim]),
|
||||
);
|
||||
} else {
|
||||
let n = format!("{l}.linear_attn");
|
||||
let key_dim = cfg.linear_num_key_heads * cfg.linear_key_head_dim;
|
||||
let value_dim = cfg.linear_num_value_heads * cfg.linear_value_head_dim;
|
||||
let conv_dim = key_dim * 2 + value_dim;
|
||||
t.insert(format!("{n}.in_proj_qkv.weight"), rand(vec![conv_dim, h]));
|
||||
t.insert(format!("{n}.in_proj_z.weight"), rand(vec![value_dim, h]));
|
||||
t.insert(
|
||||
format!("{n}.in_proj_a.weight"),
|
||||
rand(vec![cfg.linear_num_value_heads, h]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{n}.in_proj_b.weight"),
|
||||
rand(vec![cfg.linear_num_value_heads, h]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{n}.conv1d.weight"),
|
||||
rand(vec![conv_dim, 1, cfg.linear_conv_kernel_dim]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{n}.dt_bias"),
|
||||
rand(vec![cfg.linear_num_value_heads]),
|
||||
);
|
||||
t.insert(format!("{n}.A_log"), rand(vec![cfg.linear_num_value_heads]));
|
||||
t.insert(
|
||||
format!("{n}.norm.weight"),
|
||||
rand(vec![cfg.linear_value_head_dim]),
|
||||
);
|
||||
t.insert(format!("{n}.out_proj.weight"), rand(vec![h, value_dim]));
|
||||
}
|
||||
|
||||
let m = format!("{l}.mlp");
|
||||
t.insert(format!("{m}.gate.weight"), rand(vec![cfg.num_experts, h]));
|
||||
t.insert(
|
||||
format!("{m}.experts.gate_up_proj"),
|
||||
rand(vec![cfg.num_experts, cfg.moe_intermediate_size * 2, h]),
|
||||
);
|
||||
t.insert(
|
||||
format!("{m}.experts.down_proj"),
|
||||
rand(vec![cfg.num_experts, h, cfg.moe_intermediate_size]),
|
||||
);
|
||||
for p in ["gate_proj", "up_proj"] {
|
||||
t.insert(
|
||||
format!("{m}.shared_expert.{p}.weight"),
|
||||
rand(vec![cfg.shared_expert_intermediate_size, h]),
|
||||
);
|
||||
}
|
||||
t.insert(
|
||||
format!("{m}.shared_expert.down_proj.weight"),
|
||||
rand(vec![h, cfg.shared_expert_intermediate_size]),
|
||||
);
|
||||
t.insert(format!("{m}.shared_expert_gate.weight"), rand(vec![1, h]));
|
||||
|
||||
if cfg.ple_layers().contains(&i) {
|
||||
let p = format!("{l}.ple");
|
||||
t.insert(format!("{p}.key_proj.weight"), rand(vec![wide, h]));
|
||||
t.insert(format!("{p}.value_proj.weight"), rand(vec![h, h]));
|
||||
for norm in ["norm_key", "norm_query", "norm_conv"] {
|
||||
t.insert(format!("{p}.{norm}.weight"), rand(vec![wide]));
|
||||
}
|
||||
t.insert(
|
||||
format!("{p}.conv1d.weight"),
|
||||
rand(vec![wide, 1, cfg.ple_conv_kernel_size]),
|
||||
);
|
||||
let e = format!("{p}.ple_embedding");
|
||||
// The three derived buffers, as I64 — the dtype is the
|
||||
// point of this fixture.
|
||||
t.insert(
|
||||
format!("{e}.layer_multipliers"),
|
||||
Tensor::from_vec(vec![7i64, 13, 29], 3, &dev).unwrap(),
|
||||
);
|
||||
t.insert(
|
||||
format!("{e}.ngram_heads_vocab_sizes"),
|
||||
Tensor::from_vec(VOCABS.to_vec(), VOCABS.len(), &dev).unwrap(),
|
||||
);
|
||||
t.insert(
|
||||
format!("{e}.ngram_heads_offsets"),
|
||||
Tensor::from_vec(OFFSETS.to_vec(), OFFSETS.len(), &dev).unwrap(),
|
||||
);
|
||||
let per_shard = TABLE_ROWS / cfg.split_ngram_parts;
|
||||
for s in 0..cfg.split_ngram_parts {
|
||||
t.insert(
|
||||
format!("{e}.ngram_embedding.shard_{s}.weight"),
|
||||
rand(vec![per_shard, cfg.ngram_head_dim()]),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
fn build() -> (tempfile::TempDir, Qwen4ExpForCausalLM) {
|
||||
let cfg = Config::from_config_json(TINY).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("model.safetensors");
|
||||
candle_core::safetensors::save(&tensors(&cfg.text_config), &path).unwrap();
|
||||
let vb =
|
||||
unsafe { ShardedSafeTensors::var_builder(&[&path], DType::F32, &Device::Cpu).unwrap() };
|
||||
let model = Qwen4ExpForCausalLM::load(&cfg, DType::F32, &Device::Cpu, &vb).unwrap();
|
||||
(dir, model)
|
||||
}
|
||||
|
||||
/// Every loader in the architecture, against a checkpoint laid out
|
||||
/// the way the real one is. Tensor names and shapes are the failure
|
||||
/// mode a maths test cannot reach, and finding them on a 360 GB
|
||||
/// download is the expensive way.
|
||||
#[test]
|
||||
fn the_whole_model_loads_and_produces_logits() {
|
||||
let (_dir, mut model) = build();
|
||||
let ids = Tensor::from_vec(vec![5u32, 9, 3, 12, 7], (1, 5), &Device::Cpu).unwrap();
|
||||
|
||||
let logits = model.forward(&ids, 0).unwrap();
|
||||
assert_eq!(logits.dims(), &[1, 5, 32]);
|
||||
let values: Vec<f32> = logits.flatten_all().unwrap().to_vec1().unwrap();
|
||||
assert!(
|
||||
values.iter().all(|v| v.is_finite()),
|
||||
"a wrong stream width or a dead mask row shows up as NaN"
|
||||
);
|
||||
}
|
||||
|
||||
/// A decode step continues the prefill: the caches, the rotary
|
||||
/// offset and PLE's carried ids all have to agree, and any one of
|
||||
/// them being wrong still returns a tensor of the right shape.
|
||||
#[test]
|
||||
fn a_decode_step_follows_a_prefill() {
|
||||
let (_dir, mut model) = build();
|
||||
let prompt = Tensor::from_vec(vec![5u32, 9, 3, 12], (1, 4), &Device::Cpu).unwrap();
|
||||
model.forward(&prompt, 0).unwrap();
|
||||
|
||||
let next = Tensor::from_vec(vec![7u32], (1, 1), &Device::Cpu).unwrap();
|
||||
let logits = model.forward(&next, 4).unwrap();
|
||||
assert_eq!(logits.dims(), &[1, 1, 32]);
|
||||
let values: Vec<f32> = logits.flatten_all().unwrap().to_vec1().unwrap();
|
||||
assert!(values.iter().all(|v| v.is_finite()));
|
||||
|
||||
// And clearing lets the same model serve a fresh request.
|
||||
model.clear_kv_cache().unwrap();
|
||||
assert!(model.forward(&prompt, 0).is_ok());
|
||||
}
|
||||
|
||||
/// The n-gram buffers are I64 in a checkpoint whose activations are
|
||||
/// not. Loading them through the model's dtype would round a prime
|
||||
/// vocab size and a multiplier into nonsense, and the addressing
|
||||
/// would still return rows.
|
||||
#[test]
|
||||
fn the_ngram_buffers_survive_a_non_integer_model_dtype() {
|
||||
let (_dir, model) = build();
|
||||
let ngram = model.ngram.as_ref().expect("layer 1 carries PLE");
|
||||
assert_eq!(ngram.heads, 4);
|
||||
assert_eq!(ngram.head_dim, 2);
|
||||
// The table was sized from offsets + vocab sizes read as I64;
|
||||
// a bf16 round-trip of 41 + 19 would not land on 60.
|
||||
assert_eq!(ngram.table.head_dim(), 2);
|
||||
assert!(ngram.table.gather(&[(TABLE_ROWS - 1) as i64]).is_ok());
|
||||
assert!(ngram.table.gather(&[TABLE_ROWS as i64]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,12 @@
|
||||
//! PLE is three separable pieces. [`NGramHasher`] is the *addressing*:
|
||||
//! token ids to row indices. [`PleBlock`] is the *consumption*: the
|
||||
//! gated mix of the gathered embedding into the four residual streams.
|
||||
//! Between them sits the gather itself, which is where the table lives
|
||||
//! and therefore belongs to #310 — at 27 GB quantised it is not
|
||||
//! device-resident, and nothing above depends on how it is fetched.
|
||||
//! Between them sits the gather, behind the [`NGramTable`] trait —
|
||||
//! *where* those bytes live is #310's decision, and the trait is the
|
||||
//! seam so that decision changes one implementation and nothing else.
|
||||
//! [`ShardedNGramTable`] is the naive reading of the checkpoint, which
|
||||
//! is the baseline that issue measures against rather than its
|
||||
//! answer.
|
||||
//!
|
||||
//! ## Geometry
|
||||
//!
|
||||
@@ -205,6 +208,135 @@ impl NGramHasher {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the n-gram table's rows come from.
|
||||
///
|
||||
/// 320,001,536 rows of 160, and every token needs sixteen of them —
|
||||
/// a few KB per token out of 27 GB quantised. That ratio is why the
|
||||
/// table can live off-device at almost no cost, and why #310 is a
|
||||
/// residency decision rather than an algorithm. Nothing above this
|
||||
/// trait depends on the answer.
|
||||
pub trait NGramTable: Send + Sync {
|
||||
/// Gather `rows`, **in the order given**, as
|
||||
/// `[rows.len(), head_dim]`.
|
||||
fn gather(&self, rows: &[i64]) -> Result<Tensor>;
|
||||
|
||||
/// Width of one row — `ple_embed_dim / ngram_heads`, 160.
|
||||
fn head_dim(&self) -> usize;
|
||||
}
|
||||
|
||||
/// The checkpoint's 128 shards, held wherever they were loaded.
|
||||
///
|
||||
/// The shards are a **flat split of one concatenated table**, not a
|
||||
/// split per head: shard `s` holds rows `[s * rows_per_shard,
|
||||
/// (s+1) * rows_per_shard)`, so a global row index from the hash
|
||||
/// addresses straight into it. They are kept separate rather than
|
||||
/// concatenated because joining 128 tensors of 2,500,012 x 160 would
|
||||
/// need the whole table free a second time.
|
||||
///
|
||||
/// This is the naive residency — the bytes end up wherever the
|
||||
/// VarBuilder put them, which for a 27 GB table is exactly the problem
|
||||
/// #310 exists to solve. It is the control that issue measures its
|
||||
/// host- and NVMe-resident variants against.
|
||||
pub struct ShardedNGramTable {
|
||||
shards: Vec<Tensor>,
|
||||
rows_per_shard: usize,
|
||||
head_dim: usize,
|
||||
}
|
||||
|
||||
impl ShardedNGramTable {
|
||||
/// `vb` should be `.pp(...)`-ed to `ple_embedding.ngram_embedding`.
|
||||
pub fn load(
|
||||
vb: &ShardedVarBuilder,
|
||||
parts: usize,
|
||||
rows: usize,
|
||||
head_dim: usize,
|
||||
) -> Result<Self> {
|
||||
ensure!(parts > 0, "split_ngram_parts must be > 0");
|
||||
ensure!(
|
||||
rows.is_multiple_of(parts),
|
||||
"{rows} rows do not divide evenly into {parts} shards"
|
||||
);
|
||||
let rows_per_shard = rows / parts;
|
||||
let mut shards = Vec::with_capacity(parts);
|
||||
for s in 0..parts {
|
||||
shards.push(
|
||||
vb.pp(format!("shard_{s}"))
|
||||
.get((rows_per_shard, head_dim), "weight")
|
||||
.with_context(|| format!("load '{}/shard_{s}/weight'", vb.prefix()))?,
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
shards,
|
||||
rows_per_shard,
|
||||
head_dim,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_shards(shards: Vec<Tensor>) -> Result<Self> {
|
||||
ensure!(!shards.is_empty(), "need at least one shard");
|
||||
let (rows_per_shard, head_dim) = shards[0].dims2()?;
|
||||
Ok(Self {
|
||||
shards,
|
||||
rows_per_shard,
|
||||
head_dim,
|
||||
})
|
||||
}
|
||||
|
||||
fn shard_of(&self, row: i64) -> usize {
|
||||
row as usize / self.rows_per_shard
|
||||
}
|
||||
}
|
||||
|
||||
impl NGramTable for ShardedNGramTable {
|
||||
fn gather(&self, rows: &[i64]) -> Result<Tensor> {
|
||||
let total = (self.shards.len() * self.rows_per_shard) as i64;
|
||||
if let Some(bad) = rows.iter().find(|r| **r < 0 || **r >= total) {
|
||||
anyhow::bail!("row {bad} is outside the table's 0..{total}");
|
||||
}
|
||||
if rows.is_empty() {
|
||||
let device = self.shards[0].device();
|
||||
return Ok(Tensor::zeros(
|
||||
(0, self.head_dim),
|
||||
self.shards[0].dtype(),
|
||||
device,
|
||||
)?);
|
||||
}
|
||||
|
||||
// Visit each shard once: sort the requests by shard, gather, then
|
||||
// undo the permutation. Getting that inverse wrong hands every
|
||||
// token somebody else's n-gram, which is not a crash.
|
||||
let mut order: Vec<usize> = (0..rows.len()).collect();
|
||||
order.sort_by_key(|&i| (self.shard_of(rows[i]), i));
|
||||
|
||||
let device = self.shards[0].device();
|
||||
let mut parts = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < order.len() {
|
||||
let shard = self.shard_of(rows[order[i]]);
|
||||
let mut within = Vec::new();
|
||||
while i < order.len() && self.shard_of(rows[order[i]]) == shard {
|
||||
within.push((rows[order[i]] as usize - shard * self.rows_per_shard) as u32);
|
||||
i += 1;
|
||||
}
|
||||
let idx = Tensor::from_vec(within.clone(), within.len(), device)?;
|
||||
parts.push(self.shards[shard].index_select(&idx, 0)?);
|
||||
}
|
||||
let gathered = Tensor::cat(&parts, 0)?;
|
||||
|
||||
let mut inverse = vec![0u32; rows.len()];
|
||||
for (position, &original) in order.iter().enumerate() {
|
||||
inverse[original] = position as u32;
|
||||
}
|
||||
let inverse = Tensor::from_vec(inverse, rows.len(), device)?;
|
||||
Ok(gathered.index_select(&inverse, 0)?)
|
||||
}
|
||||
|
||||
fn head_dim(&self) -> usize {
|
||||
self.head_dim
|
||||
}
|
||||
}
|
||||
|
||||
/// The consumption half of PLE: `Qwen4ExpTextPLE` minus the table.
|
||||
///
|
||||
/// Given the gathered n-gram embedding `e` and the four-stream residual
|
||||
@@ -748,4 +880,107 @@ mod tests {
|
||||
"clear_state should return the block to a fresh prefill"
|
||||
);
|
||||
}
|
||||
|
||||
// ---- the table ----
|
||||
|
||||
/// Rows come back in the order asked for, not the order they were
|
||||
/// fetched in. Two shards of three rows, requested out of order and
|
||||
/// across the boundary: the shard-major gather returns them sorted,
|
||||
/// so the inverse permutation is the whole test. Getting it wrong
|
||||
/// hands every token somebody else's n-gram, silently.
|
||||
#[test]
|
||||
fn a_gather_preserves_the_order_it_was_asked_for() {
|
||||
let dev = Device::Cpu;
|
||||
// Row r holds [r, r] so a row is identifiable by its contents.
|
||||
let shard = |base: f32| {
|
||||
Tensor::from_vec(
|
||||
vec![base, base, base + 1.0, base + 1.0, base + 2.0, base + 2.0],
|
||||
(3, 2),
|
||||
&dev,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let table = ShardedNGramTable::from_shards(vec![shard(0.0), shard(3.0)]).unwrap();
|
||||
assert_eq!(table.head_dim(), 2);
|
||||
|
||||
let got: Vec<f32> = table
|
||||
.gather(&[4, 1, 3, 0, 5])
|
||||
.unwrap()
|
||||
.flatten_all()
|
||||
.unwrap()
|
||||
.to_vec1()
|
||||
.unwrap();
|
||||
assert_eq!(got, vec![4.0, 4.0, 1.0, 1.0, 3.0, 3.0, 0.0, 0.0, 5.0, 5.0]);
|
||||
}
|
||||
|
||||
/// Repeated rows are legitimate — sixteen heads can collide — and
|
||||
/// must each come back.
|
||||
#[test]
|
||||
fn a_repeated_row_is_returned_once_per_request() {
|
||||
let dev = Device::Cpu;
|
||||
let shard = Tensor::from_vec(vec![0.0f32, 1.0, 2.0, 3.0], (2, 2), &dev).unwrap();
|
||||
let table = ShardedNGramTable::from_shards(vec![shard]).unwrap();
|
||||
let got: Vec<f32> = table
|
||||
.gather(&[1, 1, 0])
|
||||
.unwrap()
|
||||
.flatten_all()
|
||||
.unwrap()
|
||||
.to_vec1()
|
||||
.unwrap();
|
||||
assert_eq!(got, vec![2.0, 3.0, 2.0, 3.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
/// A row index past the end is a hashing bug upstream, and must not
|
||||
/// become a panic in the middle of a forward.
|
||||
#[test]
|
||||
fn a_row_outside_the_table_is_an_error() {
|
||||
let dev = Device::Cpu;
|
||||
let shard = Tensor::zeros((2, 2), DType::F32, &dev).unwrap();
|
||||
let table = ShardedNGramTable::from_shards(vec![shard]).unwrap();
|
||||
assert!(table.gather(&[0, 1]).is_ok());
|
||||
assert!(table.gather(&[2]).is_err());
|
||||
assert!(table.gather(&[-1]).is_err());
|
||||
assert_eq!(table.gather(&[]).unwrap().dims(), &[0, 2]);
|
||||
}
|
||||
|
||||
/// The hasher and the table meet here: sixteen row indices per
|
||||
/// position, gathered and flattened into the 2560-wide embedding the
|
||||
/// block consumes. The widths have to agree or the projections do
|
||||
/// not fit.
|
||||
#[test]
|
||||
fn hashed_rows_gather_into_one_embedding_per_position() {
|
||||
let dev = Device::Cpu;
|
||||
let heads = 4;
|
||||
let head_dim = 2;
|
||||
let rows = 64;
|
||||
let shard = Tensor::from_vec(
|
||||
(0..rows * head_dim).map(|v| v as f32).collect::<Vec<_>>(),
|
||||
(rows, head_dim),
|
||||
&dev,
|
||||
)
|
||||
.unwrap();
|
||||
let table = ShardedNGramTable::from_shards(vec![shard]).unwrap();
|
||||
|
||||
let hasher = hasher(3, heads / 2);
|
||||
let ids = [7i64, 11, 13];
|
||||
let per_position = hasher.rows(&ids, ids.len()).unwrap();
|
||||
assert_eq!(per_position.len(), 3);
|
||||
assert_eq!(per_position[0].len(), heads);
|
||||
|
||||
let flat: Vec<i64> = per_position
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|r| r.rem_euclid(rows as i64))
|
||||
.collect();
|
||||
let gathered = table.gather(&flat).unwrap();
|
||||
assert_eq!(gathered.dims(), &[ids.len() * heads, head_dim]);
|
||||
// Reshaped per position, that is the ple_embed_dim-wide row.
|
||||
assert_eq!(
|
||||
gathered
|
||||
.reshape((ids.len(), heads * head_dim))
|
||||
.unwrap()
|
||||
.dims(),
|
||||
&[3, heads * head_dim]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,9 +229,9 @@ pub struct Indexer {
|
||||
}
|
||||
|
||||
impl Indexer {
|
||||
/// `vb` should be `.pp(...)`-ed to the attention layer's prefix, so
|
||||
/// the tensors resolve as `index_qk_proj`, `q_layernorm`,
|
||||
/// `k_layernorm`. Every dimension comes from the config rather than
|
||||
/// `vb` should be `.pp(...)`-ed to the **indexer's** prefix —
|
||||
/// `self_attn.indexer`, not `self_attn` — so the tensors resolve as
|
||||
/// `index_qk_proj`, `q_layernorm`, `k_layernorm`. Every dimension comes from the config rather than
|
||||
/// the caller, so a layer cannot be built against a geometry the
|
||||
/// checkpoint does not declare.
|
||||
pub fn load(vb: &ShardedVarBuilder, cfg: &Qwen4ExpTextConfig) -> Result<Self> {
|
||||
|
||||
Reference in New Issue
Block a user