Repository navigation
expert_cache+prefill: SSD expert streaming protections (prefill cache protection, next-layer NVMe prefetch, cold-expert release) #108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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") { | ||
| let protect = mode != "0"; | ||
| let prompt_cap = if protect { 0.25 * self.steady } else { f32::INFINITY }; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 agentReply |
||
| 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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 agentReply |
||
| } 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]; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Prompt for your AI agentReply |
||
| 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); } | ||
|
|
@@ -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. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 agentReply |
||
| 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]); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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)); | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 agentReply |
||
| 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 | ||
|
|
@@ -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); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 agentReply |
||
| i += run.len(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 agentReply |
||
| } | ||
| } | ||
|
|
||
There was a problem hiding this comment.
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
ifshort-circuits andcountsnever 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
Reply
/dismiss(optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.