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
59 changes: 54 additions & 5 deletions src/expert_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,23 +227,56 @@ impl ExpertCache {
}

/// After a prefill: the prompt's routing joins `counts`, scaled back to steady-state size, and the placement
/// follows. A long prompt still decides the placement the reply starts with, but its thousands of tokens no
/// longer outweigh the reply's: the reply's own routing moves the placement as fast as in any other run.
/// follows. Under `STRATA_PREFILL_PROTECT` (default on; `"0"` for legacy full flush, `"strict"` for 0 swaps),
/// a long prompt blends gently (25% of steady state) and swaps at most 10% of each pool's slots so it does not
/// flush the hot decode cache.
pub fn settle(&mut self, m: &Model, gpu: &dyn Backend) -> anyhow::Result<()> {
let n = self.n_expert;
if self.profile.is_some() {
let mode = std::env::var("STRATA_PREFILL_PROTECT").unwrap_or_default();
if self.profile.is_some() && !mode.eq_ignore_ascii_case("strict") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 8

Strict mode skips the whole blend, so prompt routing never reaches counts, though the doc says strict only means zero swaps. With STRATA_PREFILL_PROTECT=strict and a profile present, the if short-circuits and counts never receives prompt routing. The placement after prefill ignores the prompt entirely, which contradicts the doc comment saying strict means 0 swaps.

Prompt for your AI agent
File: src/expert_cache.rs
Line: 236
Symbol: settle
Issue: Strict mode skips the whole blend, so prompt routing never reaches counts, though the doc says strict only means zero swaps. With STRATA_PREFILL_PROTECT=strict and a profile present, the `if` short-circuits and `counts` never receives prompt routing. The placement after prefill ignores the prompt entirely, which contradicts the doc comment saying strict means 0 swaps.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

let protect = mode != "0";
let prompt_cap = if protect { 0.25 * self.steady } else { f32::INFINITY };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 2 of 8

prompt_cap is 0 when steady is 0 or unset, which silently zeroes all prompt contributions. If steady has not been set (0.0), prompt_cap is 0. Any non-empty prompt then gets pscale = 0/psum = 0, so no prompt routing is counted and placement ignores the prompt with no warning.

Prompt for your AI agent
File: src/expert_cache.rs
Line: 238
Symbol: settle
Issue: prompt_cap is 0 when steady is 0 or unset, which silently zeroes all prompt contributions. If steady has not been set (0.0), prompt_cap is 0. Any non-empty prompt then gets pscale = 0/psum = 0, so no prompt routing is counted and placement ignores the prompt with no warning.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

for il in 0..self.layers.len() {
let r = il * n..(il + 1) * n;
for i in r.clone() { self.counts[i] += self.prompt[i]; }
let psum: f32 = self.prompt[r.clone()].iter().sum();
let pscale = if psum > prompt_cap { prompt_cap / psum } else { 1.0 };
for i in r.clone() { self.counts[i] += self.prompt[i] * pscale; }
let sum = self.counts[r.clone()].iter().sum::<f32>();
if sum > self.steady { for i in r { self.counts[i] *= self.steady / sum; } }
}
self.swap(m, gpu, usize::MAX)?;
let max_swaps = if protect {
let min_pool = self.pools.iter().map(|p| p.owner.len()).filter(|&l| l > 0).min().unwrap_or(0);
(min_pool / 10).max(1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 3 of 8

max_swaps is a single global budget, not the per-pool 10% the doc promises. The budget is min_pool/10 applied to the whole swap call. If swaps concentrate in one pool, that pool can lose far more than 10% of its slots, contrary to the doc comment's per-pool guarantee against flushing the decode cache.

Prompt for your AI agent
File: src/expert_cache.rs
Line: 249
Symbol: settle
Issue: max_swaps is a single global budget, not the per-pool 10% the doc promises. The budget is min_pool/10 applied to the whole swap call. If swaps concentrate in one pool, that pool can lose far more than 10% of its slots, contrary to the doc comment's per-pool guarantee against flushing the decode cache.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

} else {
usize::MAX
};
self.swap(m, gpu, max_swaps)?;
}
self.prompt.fill(0.0);
Ok(())
}

/// Top `top_k` hottest non-resident experts of `next_il` (by short-term `counts`, falling back to `long`),
/// returned as `(ptr, len)` mmap byte ranges for asynchronous NVMe read-ahead (`Prefetch::send`) while layer
/// `il` computes on the GPU.
pub fn cold_ranges_for_next(&self, m: &Model, next_il: usize, top_k: usize) -> Vec<(usize, usize)> {
let Some(lx) = self.layers.get(next_il).and_then(|l| l.as_ref()) else { return Vec::new() };
let n = self.n_expert;
let base = next_il * n;
let mut cands: Vec<usize> = (0..n).filter(|&e| lx.table[e] < 0).collect();
if cands.is_empty() { return Vec::new(); }
let score = |e: usize| self.counts[base + e] + 0.01 * self.long[base + e];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Correctness · 4 of 8

cold_ranges_for_next may not truncate cands to top_k if smallest only reorders. If smallest partitions in place without truncating, cands keeps every non-resident expert. The loop then emits ranges for all of them, up to 3 * n reads per layer, instead of the 16 that the call site asks for.

Prompt for your AI agent
File: src/expert_cache.rs
Line: 268
Symbol: cold_ranges_for_next
Issue: cold_ranges_for_next may not truncate cands to top_k if smallest only reorders. If `smallest` partitions in place without truncating, cands keeps every non-resident expert. The loop then emits ranges for all of them, up to 3 * n reads per layer, instead of the 16 that the call site asks for.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

smallest(&mut cands, top_k, |&a, &b| score(b).total_cmp(&score(a)));
let mut rs = Vec::with_capacity(cands.len() * 3);
for (name, mat) in MATS.iter().zip(&lx.mats) {
let Ok(w) = m.w.layer(next_il, name) else { continue };
for &e in &cands {
rs.push((w.data.as_ptr() as usize + e * mat.bytes, mat.bytes));
}
}
rs
}

/// Forget the short-term routing counts: the prompt's thousands of tokens no longer outweigh the reply's first
/// tokens, so `adapt` follows the text being decoded instead of the prompt that produced it.
pub fn reset_counts(&mut self) { self.counts.fill(0.0); }
Expand Down Expand Up @@ -400,4 +433,20 @@ mod tests {
let longer = profile_update(&existing, 4, &[1.0; 12], &[true, false, true]);
assert_eq!(longer.len(), 12, "a longer profile grows without losing the file's counts");
}

#[test]
fn prefill_protect_blends_gently_and_preserves_hot_decode_counts() {
let mut c = fake(1, 4, 2, None);
// Simulate hot decode experts 0 and 1, then a huge prompt hitting cold experts 2 and 3.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 8 of 8

New test re-implements the blend inline and never calls settle(), so it does not test production code. The test duplicates the pscale arithmetic. If settle() changes, for example by a wrong cap or a broken strict path, the test still passes, so it gives false confidence about the protection.

Prompt for your AI agent
File: src/expert_cache.rs
Line: 440
Symbol: prefill_protect_blends_gently_and_preserves_hot_decode_counts
Issue: New test re-implements the blend inline and never calls settle(), so it does not test production code. The test duplicates the pscale arithmetic. If settle() changes, for example by a wrong cap or a broken strict path, the test still passes, so it gives false confidence about the protection.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

c.counts = vec![40.0, 40.0, 0.0, 0.0];
c.steady = 80.0;
c.record_prompt(0, &[2, 2, 2, 2, 3, 3, 3, 3]);
// Under default protection, prompt contribution is capped at 0.25 * steady = 20.0 total (10 each),
// so hot decode experts 0 and 1 stay strictly hotter than cold prompt experts 2 and 3.
let psum: f32 = c.prompt[..4].iter().sum();
let cap = 0.25 * c.steady;
let pscale = if psum > cap { cap / psum } else { 1.0 };
for i in 0..4 { c.counts[i] += c.prompt[i] * pscale; }
assert!(c.counts[0] > c.counts[2] && c.counts[1] > c.counts[3]);
}
}
14 changes: 11 additions & 3 deletions src/gpu_model/prefill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,13 @@ impl GpuModel<'_> {
let missed: Vec<usize> = (0..c.n_expert).filter(used).filter(|&e| cache.slot(il, e) < 0).collect();
if let Some(pre) = &pre {
let w: Vec<_> = MATS.iter().map(|name| self.m.w.layer(il, name)).collect::<anyhow::Result<_>>()?;
pre.send(missed.chunks(STAGE).flat_map(|grp| w.iter().zip(&lx.mats).flat_map(move |(w, mat)| grp.chunk_by(|a, b| *b == a + 1)
.map(move |run| (w.data.as_ptr() as usize + run[0] * mat.bytes, run.len() * mat.bytes)))).collect());
let mut rs: Vec<(usize, usize)> = missed.chunks(STAGE).flat_map(|grp| w.iter().zip(&lx.mats).flat_map(move |(w, mat)| grp.chunk_by(|a, b| *b == a + 1)
.map(move |run| (w.data.as_ptr() as usize + run[0] * mat.bytes, run.len() * mat.bytes)))).collect();
// Overlap NVMe read-ahead for the next MoE layer's hottest cold experts behind this layer's GEMMs.
if let Some(next_il) = (il + 1..c.n_layer).find(|&j| cache.layer(j).is_some()) {
rs.extend(cache.cold_ranges_for_next(self.m, next_il, 16));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 5 of 8

Next-layer NVMe prefetch of 16 experts runs unconditionally, even when the prefill will not need them. Every prefill layer reads the top 16 cold experts of the next layer. Many of those may never be selected for the prompt, so bandwidth is spent on reads that go unused and compete with the real streamed reads.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 587
Symbol: prefill_chunk
Issue: Next-layer NVMe prefetch of 16 experts runs unconditionally, even when the prefill will not need them. Every prefill layer reads the top 16 cold experts of the next layer. Many of those may never be selected for the prompt, so bandwidth is spent on reads that go unused and compete with the real streamed reads.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

pre.send(rs);
}
// Staged groups of at most STAGE missed experts, group j in staging third j % 3. Staging holds
// each matrix in its own section (all gates, then ups, then downs), so experts with consecutive
Expand Down Expand Up @@ -656,7 +661,10 @@ impl GpuModel<'_> {
let mut i = 0;
for run in grp.chunk_by(|a, b| b.0 == a.0 + 1) {
let e = run[0].0;
g.htod(&w.data[e * mat.bytes..(e + run.len()) * mat.bytes], &pf.staging, half(j) + STAGE * mat.off + i * mat.bytes)?;
let slice = &w.data[e * mat.bytes..(e + run.len()) * mat.bytes];
g.htod(slice, &pf.staging, half(j) + STAGE * mat.off + i * mat.bytes)?;
// Release cold streamed prefill experts from OS page cache when the model exceeds RAM.
crate::weights::cold(slice);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 6 of 8

cold() is called unconditionally, though the comment says it applies only when the model exceeds RAM. The comment says release happens when the model exceeds RAM, but the code calls cold(slice) on every streamed run. On machines where the model fits in RAM, the released pages must be re-read from SSD on each later chunk and layer, slowing prefill.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 667
Symbol: prefill_chunk
Issue: cold() is called unconditionally, though the comment says it applies only when the model exceeds RAM. The comment says release happens when the model exceeds RAM, but the code calls cold(slice) on every streamed run. On machines where the model fits in RAM, the released pages must be re-read from SSD on each later chunk and layer, slowing prefill.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

i += run.len();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Correctness · 7 of 8

cold(slice) may be applied to non-page-aligned or heap-backed memory, risking zeroed weights or EINVAL. The slice starts at e * mat.bytes, which is not page-aligned. If cold() forwards this to madvise(MADV_DONTNEED) and the weights are heap-backed, the call can return EINVAL or, for anonymous memory, discard the data so later reads see zeros.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 668
Symbol: prefill_chunk
Issue: cold(slice) may be applied to non-page-aligned or heap-backed memory, risking zeroed weights or EINVAL. The slice starts at e * mat.bytes, which is not page-aligned. If cold() forwards this to madvise(MADV_DONTNEED) and the weights are heap-backed, the call can return EINVAL or, for anonymous memory, discard the data so later reads see zeros.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

}
}
Expand Down
Loading