1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! Exact multi-row prompt steps for DeepSeek-V4 token-wise prompt work.
//!
//! The recovery tail (the last `RECOVERY_TAIL_TOKENS` prompt tokens after the
//! rollback anchor) and cached suffixes shorter than the matrix floor run as
//! one-token verifier steps. A rows step advances one cache by up to
//! [`MAX_JOINT_DECODE_ROWS`] consecutive tokens in one layer-major
//! transaction built from the joint-decode graph: every product stays on its
//! one-token route (independent-row F16 and Q8_0 products, `mv_id` experts)
//! and the cache-dependent cores run per row, in row order, on the one cache
//! ([`RowCaches::Sequential`]). Layer `L` of token `p + 1` reads only layer-`L`
//! cache entries of tokens `<= p + 1`, so layer-major order gives every row
//! the inputs of the token-major one-token steps: each row's state and every
//! cache byte equal `rows` successive `forward_verifier_one` calls.
//!
//! Serving runs it by default (v0.1.30, the DeepSeek-V4 release-gate
//! configuration); `HF2Q_DEEPSEEK_TAIL_ROWS_STEP=0` (read once at model load)
//! is the kill switch.
use anyhow::{ensure, Context, Result};
use mlx_native::MlxBuffer;
use super::cache::Deepseek4Cache;
use super::forward_support::{begin_decode_pool_token, end_decode_pool_token};
use super::joint_decode::MAX_JOINT_DECODE_ROWS;
use super::joint_decode_core::RowCaches;
use super::Deepseek4Model;
use crate::inference::models::route_default::Resolved;
/// Serving switch for exact rows steps over token-wise prompt work.
///
/// `Default` is [`Self::Off`], the value fixtures build with; the serving
/// default is [`Self::resolve`] of an unset switch ([`Self::On`]).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TailRowsStep {
/// One `forward_verifier_one` transaction per token-wise prompt token,
/// as in every release through v0.1.29 (kill switch).
#[default]
Off,
/// Token-wise prompt tokens run as rows steps of at most
/// [`MAX_JOINT_DECODE_ROWS`] tokens when the joint-decode routes are
/// available for this artifact and process.
On,
}
impl TailRowsStep {
/// Process switch read by [`Self::from_env`].
pub const ENV: &'static str = "HF2Q_DEEPSEEK_TAIL_ROWS_STEP";
/// `HF2Q_DEEPSEEK_TAIL_ROWS_STEP`: unset or `1` selects [`Self::On`]
/// (the release-gate route), `0` [`Self::Off`] (kill switch); anything
/// else is an error.
pub(crate) fn from_env() -> Result<Resolved<Self>> {
Self::resolve(std::env::var_os(Self::ENV).as_deref())
}
/// Resolution rule of [`Self::from_env`].
pub(crate) fn resolve(value: Option<&std::ffi::OsStr>) -> Result<Resolved<Self>> {
super::route_defaults::resolve_zero_one(Self::ENV, value, Self::Off, Self::On)
}
}
/// Tokens per transaction for token-wise prompt work: `1` (one-token steps)
/// unless rows steps are enabled and available.
pub(crate) fn token_wise_step_rows(switch: TailRowsStep, unavailable: Option<&str>) -> usize {
match (switch, unavailable) {
(TailRowsStep::On, None) => MAX_JOINT_DECODE_ROWS,
_ => 1,
}
}
/// Publish a drained rows step: prevalidate the span, then the supervisor
/// gate, then advance the cursor infallibly. Any rejection poisons the cache.
fn publish_rows_step_after_gate(
cache: &mut Deepseek4Cache,
start: usize,
rows: usize,
commit_gate: impl FnOnce() -> Result<()>,
) -> Result<()> {
let ticket = match cache.validate_prefill_commit(start, rows) {
Ok(ticket) => ticket,
Err(error) => {
cache.poison();
return Err(error).context("prevalidate DeepSeek-V4 rows step publication");
}
};
if let Err(error) = commit_gate() {
cache.poison();
return Err(error).context("DeepSeek-V4 rows step rejected before cache publication");
}
cache.publish_prefill_end(ticket);
Ok(())
}
impl Deepseek4Model {
/// Tokens per transaction for this model's token-wise prompt work.
pub(crate) fn token_wise_step_rows(&self) -> usize {
token_wise_step_rows(
self.tail_rows_step,
self.joint_decode_unavailable_reason().as_deref(),
)
}
/// Advance `cache` by `token_ids.len()` (2..=[`MAX_JOINT_DECODE_ROWS`])
/// consecutive tokens and return their `[rows, hc, hidden]` final states
/// in token order (see the module doc for the exactness argument). The
/// cache publishes every row at once after the drain and `commit_gate`;
/// a submitted failure poisons it.
pub(crate) fn forward_verifier_rows_step_with_commit_gate(
&mut self,
token_ids: &[u32],
cache: &mut Deepseek4Cache,
commit_gate: impl FnOnce() -> Result<()>,
) -> Result<MlxBuffer> {
let rows = token_ids.len();
ensure!(
(2..=MAX_JOINT_DECODE_ROWS).contains(&rows),
"DeepSeek-V4 rows step requires 2..={MAX_JOINT_DECODE_ROWS} tokens, got {rows}"
);
if let Some(reason) = self.joint_decode_unavailable_reason() {
anyhow::bail!("DeepSeek-V4 rows step unavailable: {reason}");
}
let start = cache.position();
let steps = (start..start + rows)
.map(|position| {
cache
.plan_step_at(position)
.context("plan DeepSeek-V4 rows step cache transaction")
})
.collect::<Result<Vec<_>>>()?;
let (result, submitted_any) = {
let views = vec![&*cache; rows];
begin_decode_pool_token();
let outcome = self.forward_verifier_rows_uncommitted(
token_ids,
&views,
&steps,
RowCaches::Sequential,
);
end_decode_pool_token();
outcome
};
match result {
Ok(state) => {
publish_rows_step_after_gate(cache, start, rows, commit_gate)?;
Ok(state)
}
Err(error) => {
if submitted_any {
cache.poison();
}
Err(error).context("DeepSeek-V4 rows step transaction failed")
}
}
}
#[cfg(test)]
pub(super) fn forward_verifier_rows_step(
&mut self,
token_ids: &[u32],
cache: &mut Deepseek4Cache,
) -> Result<MlxBuffer> {
self.forward_verifier_rows_step_with_commit_gate(token_ids, cache, || Ok(()))
}
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use super::*;
#[test]
fn switch_defaults_on_and_parses_zero_one_and_rejects_anything_else() {
assert_eq!(
TailRowsStep::resolve(None).unwrap(),
Resolved::default_value(TailRowsStep::On)
);
assert_eq!(
TailRowsStep::resolve(Some(OsStr::new("0"))).unwrap(),
Resolved::environment(TailRowsStep::Off)
);
assert_eq!(
TailRowsStep::resolve(Some(OsStr::new("1"))).unwrap(),
Resolved::environment(TailRowsStep::On)
);
for bad in ["", "2", "on", "true", " 1"] {
assert!(TailRowsStep::resolve(Some(OsStr::new(bad))).is_err(), "{bad:?}");
}
// Fixtures build with the pre-promotion value.
assert_eq!(TailRowsStep::default(), TailRowsStep::Off);
}
#[test]
fn token_wise_rows_need_the_switch_and_available_joint_routes() {
assert_eq!(token_wise_step_rows(TailRowsStep::Off, None), 1);
assert_eq!(token_wise_step_rows(TailRowsStep::Off, Some("x")), 1);
assert_eq!(token_wise_step_rows(TailRowsStep::On, Some("x")), 1);
assert_eq!(
token_wise_step_rows(TailRowsStep::On, None),
MAX_JOINT_DECODE_ROWS
);
assert_eq!(MAX_JOINT_DECODE_ROWS, 8, "the recovery tail is one rows step");
}
}