Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/dluth-model/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ pub enum ModelError {
Unsupported(String),
/// A request does not fit the limits the model was opened with.
Capacity(String),
/// The device computing part of the model failed. The text is the device's own. The
/// token being computed was left half done: a model that returned this must be given
/// position 0 (a new sequence) before it is used again.
Device(String),
}

impl ModelError {
Expand All @@ -36,6 +40,7 @@ impl fmt::Display for ModelError {
}
ModelError::Unsupported(m) => write!(f, "unsupported: {m}"),
ModelError::Capacity(m) => write!(f, "over capacity: {m}"),
ModelError::Device(m) => write!(f, "device failure: {m}"),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/dluth-model/src/inkling/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ pub mod model;
pub mod prompt;

pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind};
pub use model::InklingCpu;
pub use model::{CpuProducts, ExpertMatrices, InklingCpu, Products};
288 changes: 206 additions & 82 deletions crates/dluth-model/src/inkling/model.rs

Large diffs are not rendered by default.

65 changes: 65 additions & 0 deletions crates/dluth-model/tests/tiny_inkling_golden.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,68 @@ fn tiny_inkling_matches_reference_greedy_and_logprobs() {
assert_eq!(report.tie_at, None);
}
}

/// Counts the products it is asked for and passes them on to the CPU.
struct Counting {
inner: dluth_model::inkling::CpuProducts,
bf16: std::rc::Rc<std::cell::Cell<usize>>,
expert_jobs: std::rc::Rc<std::cell::Cell<usize>>,
}

impl dluth_model::inkling::Products for Counting {
fn bf16(
&mut self,
w: &[u8],
rows: usize,
cols: usize,
x: &[f32],
out: &mut [f32],
) -> Result<(), dluth_model::error::ModelError> {
self.bf16.set(self.bf16.get() + 1);
self.inner.bf16(w, rows, cols, x, out)
}

fn experts(
&mut self,
m: &dluth_model::inkling::ExpertMatrices,
jobs: &[(usize, &[f32])],
out: &mut [f32],
) -> Result<(), dluth_model::error::ModelError> {
self.expert_jobs.set(self.expert_jobs.get() + jobs.len());
self.inner.experts(m, jobs, out)
}
}

#[test]
fn every_matrix_product_goes_through_the_products_given_to_the_model() {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling");
let weights = Weights::open_dir(&dir).unwrap();
let cfg = load_config(&dir).unwrap();
let (bf16, expert_jobs) = (std::rc::Rc::new(std::cell::Cell::new(0)), std::rc::Rc::new(std::cell::Cell::new(0)));
let counting =
Counting { inner: dluth_model::inkling::CpuProducts, bf16: bf16.clone(), expert_jobs: expert_jobs.clone() };
let passes = cfg.layer_passes();
let per_token = cfg.experts_per_token;
// BF16 products of one token, from the configuration. Every layer pass: query, key,
// value, relative position, sink, output gate, output and router. A global layer also
// computes taps for its key and value convolutions. A looped layer, from its second pass
// on, merges four messages with three products each. And the output table, once.
let mut bf16_per_token = 1;
for layer in 0..cfg.layers {
let times = if cfg.is_looped(layer) { cfg.passes } else { 1 };
bf16_per_token += times * (8 + if cfg.is_local(layer) { 0 } else { 2 });
if cfg.is_looped(layer) {
bf16_per_token += (cfg.passes - 1) * 4 * 3;
}
}
assert!(cfg.passes > 1 && cfg.layers > cfg.local_layers.len(), "the fixture must loop and have global layers");
let mut plain = InklingCpu::new(cfg.clone(), &weights, 16).unwrap();
let mut counted = InklingCpu::with_products(cfg, &weights, 16, Box::new(counting)).unwrap();
for (pos, token) in [5u32, 9, 2].into_iter().enumerate() {
assert_eq!(plain.forward_token(token, pos).unwrap(), counted.forward_token(token, pos).unwrap());
}
// Two expert matrices per chosen expert per layer pass per token, and nothing else.
assert_eq!(expert_jobs.get(), 3 * passes * per_token * 2);
// Exactly the BF16 products counted above: one made directly, past the trait, would be missing.
assert_eq!(bf16.get(), 3 * bf16_per_token);
}
6 changes: 3 additions & 3 deletions tools/mutants/38-inkling-no-sink.patch
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
# weights-env: DLUTH_INKLING2_MINI
# Bug: the model's attention gives the sink no say.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 899fc4b..93d4d61 100644
index 8693fee..24ea6da 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -654,7 +654,7 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs:
@@ -763,7 +763,7 @@ fn attention(
}

let mut sinks = vec![0.0f32; cfg.heads];
- cpu::matvec_bf16(layer.sink, cfg.heads, h, q_in, &mut sinks);
- p.bf16(layer.sink, cfg.heads, h, q_in, &mut sinks)?;
+ sinks.fill(-1e30);

let mut attended = vec![0.0f32; q_width];
Expand Down
12 changes: 6 additions & 6 deletions tools/mutants/40-inkling-shared-history.patch
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
# weights-env: DLUTH_INKLING2_MINI
# Bug: every pass of a looped layer shares one attention history.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 899fc4b..dfd589c 100644
index 8693fee..a6be3d7 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -482,7 +482,8 @@ impl<'w> InklingCpu<'w> {
}
_ => None,
@@ -569,7 +569,8 @@ impl<'w> InklingCpu<'w> {
};
- x = apply_layer(cfg, layer, &mut self.states[index], &x, &mut blocks, messages.as_deref(), pos);
let p = self.products.as_mut();
let at = Arrival { pos, messages: messages.as_deref() };
- x = apply_layer(cfg, p, layer, &mut self.states[index], &x, &mut blocks, at)?;
+ let shared = self.steps.iter().position(|s| s.layer == step.layer).unwrap_or(index);
+ x = apply_layer(cfg, layer, &mut self.states[shared], &x, &mut blocks, messages.as_deref(), pos);
+ x = apply_layer(cfg, p, layer, &mut self.states[shared], &x, &mut blocks, at)?;
}

self.last = x;
6 changes: 3 additions & 3 deletions tools/mutants/41-inkling-value-message.patch
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
# weights-env: DLUTH_INKLING2_MINI
# Bug: the message for the value input is dropped.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 899fc4b..0d4404f 100644
index 8693fee..c856a7f 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -751,7 +751,7 @@ fn apply_layer(
@@ -878,7 +878,7 @@ fn apply_layer(
}
};
// 2. From the second pass on, merge in the previous pass's messages, then normalize.
- for (input, port) in inputs.iter_mut().zip([Port::Query, Port::Key, Port::Value]) {
+ for (input, port) in inputs.iter_mut().zip([Port::Query, Port::Key]) {
*input = merged(port, std::mem::take(input));
*input = merged(p, port, std::mem::take(input))?;
}
let mut normed = [vec![0.0f32; h], vec![0.0f32; h], vec![0.0f32; h]];
10 changes: 5 additions & 5 deletions tools/mutants/45-inkling-router-bias.patch
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
# weights-env: DLUTH_INKLING2_MINI
# Bug: experts are chosen without the routing bias.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 899fc4b..149a2e3 100644
index 8693fee..3caca5c 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -688,7 +688,7 @@ fn experts(cfg: &InklingConfig, layer: &Layer, input: &[f32]) -> Vec<f32> {
@@ -797,7 +797,7 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3
let (h, inner) = (cfg.hidden, cfg.expert_width);
let mut scores = vec![0.0f32; cfg.experts];
cpu::matvec_bf16(layer.router, cfg.experts, h, input, &mut scores);
p.bf16(layer.router, cfg.experts, h, input, &mut scores)?;
- let chosen = router::choose(&scores, &layer.router_bias, cfg.experts_per_token, cfg.route_scale);
+ let chosen = router::choose(&scores, &vec![0.0; cfg.experts], cfg.experts_per_token, cfg.route_scale);

let mut total = vec![0.0f32; h];
let mut both = vec![0.0f32; 2 * inner];
// Every chosen expert's first matrix reads the same input.
let jobs: Vec<(usize, &[f32])> = chosen.iter().map(|&(expert, _)| (expert, input)).collect();
12 changes: 6 additions & 6 deletions tools/mutants/47-inkling-gate-up-swapped.patch
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@
# weights-env: DLUTH_INKLING2_MINI
# Bug: an expert reads its gate and up rows the wrong way round.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 899fc4b..78b6ce7 100644
index 8693fee..4c08d29 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -698,8 +698,8 @@ fn experts(cfg: &InklingConfig, layer: &Layer, input: &[f32]) -> Vec<f32> {
layer.first.apply(expert, input, &mut both);
// Gate and up values alternate.
@@ -809,8 +809,8 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3
let (mut gate, mut up) = (vec![0.0f32; inner], vec![0.0f32; inner]);
for (both, act) in both.chunks_exact(2 * inner).zip(acts.chunks_exact_mut(inner)) {
for (i, pair) in both.as_chunks::<2>().0.iter().enumerate() {
- gate[i] = pair[0];
- up[i] = pair[1];
+ gate[i] = pair[1];
+ up[i] = pair[0];
}
cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, &mut act);
layer.second.apply(expert, &act, &mut out);
cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, act);
}
6 changes: 3 additions & 3 deletions tools/mutants/50-inkling-value-norm.patch
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
# weights-env: DLUTH_INKLING2_MINI
# Bug: values are not normalized per head.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 899fc4b..db58585 100644
index 8693fee..bb13568 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -627,7 +627,7 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs:
let unnormed = project_kv(cfg, layer.wv, &layer.v_conv, &mut state.v_recent, v_in);
@@ -735,7 +735,7 @@ fn attention(
let unnormed = project_kv(cfg, p, layer.wv, &layer.v_conv, &mut state.v_recent, v_in)?;
let mut values = vec![0.0f32; unnormed.len()];
for (out, head) in values.chunks_exact_mut(d).zip(unnormed.chunks_exact(d)) {
- cpu::rmsnorm_plain(head, cfg.eps, out);
Expand Down
8 changes: 4 additions & 4 deletions tools/mutants/51-inkling-output-cap.patch
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
# weights-env: DLUTH_INKLING2_MINI
# Bug: the output scores are not capped.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 899fc4b..eb59bef 100644
index 8693fee..0a783b0 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -505,7 +505,7 @@ impl<'w> InklingCpu<'w> {
@@ -592,7 +592,7 @@ impl<'w> InklingCpu<'w> {
let mut logits = vec![0.0f32; cfg.vocab_out];
cpu::matvec_bf16(&self.unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, &normed, &mut logits);
self.products.bf16(&self.unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, &normed, &mut logits)?;
for l in logits.iter_mut() {
- *l = cpu::softcap(*l, cfg.logit_cap);
+ *l = l.clamp(-1e30, 1e30);
}
logits
Ok(logits)
}
15 changes: 15 additions & 0 deletions tools/mutants/71-inkling-product-past-the-trait.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# test: cargo test -p dluth-model --test tiny_inkling_golden every_matrix_product
# Bug: one product (the attention sink) is computed directly on the CPU, past the Products trait.
diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs
index 8693fee..0874f4d 100644
--- a/crates/dluth-model/src/inkling/model.rs
+++ b/crates/dluth-model/src/inkling/model.rs
@@ -763,7 +763,7 @@ fn attention(
}

let mut sinks = vec![0.0f32; cfg.heads];
- p.bf16(layer.sink, cfg.heads, h, q_in, &mut sinks)?;
+ cpu::matvec_bf16(layer.sink, cfg.heads, h, q_in, &mut sinks);

let mut attended = vec![0.0f32; q_width];
sinkattn::attend(
Loading