hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Issue #727 (spill and restore on reclaim) for the Qwen SlotAware worker.
//!
//! With more agent conversations than slots, admission hands a request a
//! slot that still holds another conversation's resumable state. Before this
//! module, that state was discarded, so which conversation later resumed and
//! which recomputed its prefix depended on arrival order. Cold prefill and
//! live-tail resume differ numerically, so the order changed the output.
//!
//! Admission now copies the discarded state into a host spill store: the
//! slot's cache state ([`HybridKvSlotSpill`]) plus exactly the ledger slot
//! affinity reads (the retained token prefix with its speculative boundary,
//! and the prompt anchor). A later request whose prompt matches a spilled
//! ledger better than the slot it was granted, by the same longest-prefix
//! rule affinity applies to idle slots, gets the spill restored into its
//! granted slot. Admission then takes the same live-tail or anchor resume it
//! would have taken had the conversation kept its slot.
//!
//! The store and the reclaim decision ([`plan_reclaim`]) are shared with
//! the Gemma worker (`slot_spill`): a fixed byte budget
//! (`serve.slot_spill_budget`), a fixed entry cap
//! (`SLOT_SPILL_ENTRIES_PER_SLOT` per worker slot) and oldest-stamp
//! eviction, so every outcome is a function of the request sequence alone.
//! A spill runs only when admission would otherwise
//! discard a granted slot's state: the request matches nothing in the slot
//! (cold), a better-matching spill is restored over it, the request starts
//! new content exactly at the slot's anchor (a fork, or another conversation
//! sharing that anchor), or an embedding takes the slot. A conversation's own
//! next turn or retry in its own slot resumes in place (live tail, or its
//! stable anchor plus the shared assistant header) and copies nothing, and
//! the lookup is skipped while the store is empty. A worker whose requests
//! each continue (or retry) the conversation already in their slot, or land
//! in an empty slot, therefore never copies anything.

use anyhow::Context;

use super::slot_spill::{plan_reclaim, ResumePreference, SlotSpillStore, SpillInsert, VictimSpill};
use super::{
    qwen35_anchor_vision_compatible, qwen35_slot_affinity, Qwen35RetainedPrefix,
    Qwen35SlotPreference, SlotId,
};
use crate::inference::models::qwen35::kv_cache::{HybridKvCache, HybridKvSlotSpill};
use crate::serve::api::engine_qwen35::{
    anchor_store::{draft_owned_bytes, DFlash2CheckpointIncompatible, DraftRestore,
        Qwen35Anchor as Qwen35PromptAnchor, Qwen35AnchorStore},
    Qwen35SpecPrefixBoundary,
};
use crate::inference::spec_decode::dflash2::runtime::DFlash2LaneCheckpoint;
use std::sync::Arc;

const LOG_TARGET: &str = "hf2q::serve::api::engine_qwen35::slot_spill";

impl ResumePreference for Qwen35SlotPreference {
    fn cached_tokens(&self) -> usize {
        self.cached_tokens
    }

    fn restores_prompt_anchor(&self) -> bool {
        self.restore_prompt_anchor
    }
}

/// One reclaimed conversation: its slot's cache state and its resume ledger.
pub(super) struct Qwen35SlotSpill {
    source_slot: u32,
    kv: HybridKvSlotSpill,
    retained: Qwen35RetainedPrefix,
    anchor: Qwen35AnchorStore,
    live_draft: Option<Arc<DFlash2LaneCheckpoint>>,
}

pub(super) type Qwen35SlotSpillStore = SlotSpillStore<Qwen35SlotSpill>;

pub(super) fn include_carry_owners(
    store: &Qwen35SlotSpillStore,
    owners: &mut crate::inference::models::qwen35::carry_memory::CarryOwners,
) {
    for (_, entry) in store.newest_first() {
        if let Some(spec) = entry.payload.retained.spec.as_ref() {
            owners.include(&spec.pending_target_hidden);
        }
        if let Some(image) = &entry.payload.live_draft {
            image.include_carry_owners(owners);
        }
        entry.payload.anchor.include_carry_owners(owners);
    }
}

/// The (retained, anchor) prefixes a conversation's ledger offers a request,
/// filtered by vision compatibility exactly as slot affinity filters idle
/// slots: a retained prefix is usable only beside an anchor with the
/// request's vision fingerprint.
pub(super) fn qwen35_resume_candidate<'a>(
    retained: &'a Qwen35RetainedPrefix,
    anchor: Option<&'a Qwen35PromptAnchor>,
    request_vision_fingerprint: Option<[u8; 32]>,
    text_anchor_reuse_limit: Option<usize>,
) -> (&'a [u32], Option<&'a [u32]>) {
    let exact_anchor_matches =
        anchor.is_some_and(|anchor| anchor.vision_fingerprint == request_vision_fingerprint);
    let anchor_matches = anchor.is_some_and(|anchor| {
        qwen35_anchor_vision_compatible(
            anchor.vision_fingerprint,
            anchor.prompt_tokens.len(),
            request_vision_fingerprint,
            text_anchor_reuse_limit,
        )
    });
    (
        if exact_anchor_matches {
            retained.as_slice()
        } else {
            &[]
        },
        anchor
            .filter(|_| anchor_matches)
            .map(|anchor| anchor.prompt_tokens.as_slice()),
    )
}

/// The longest-prefix candidate among `(index, retained, anchor)` ledgers,
/// by slot affinity's rule. Candidates come newest first, so equal matches
/// resolve to the newest. The returned preference's `slot` is meaningless
/// (it carries the index); the caller substitutes the granted slot.
pub(super) fn qwen35_best_ledger_match<'a>(
    candidates: impl IntoIterator<Item = (usize, &'a [u32], Option<&'a [u32]>)>,
    prompt_tokens: &[u32],
) -> Option<(usize, Qwen35SlotPreference)> {
    let preference = qwen35_slot_affinity(
        candidates
            .into_iter()
            .map(|(index, retained, anchor)| (index, retained, anchor, None, false)),
        prompt_tokens,
    )?
    .preference();
    Some((preference.slot.0 as usize, preference))
}

fn best_spill_match(
    store: &Qwen35SlotSpillStore,
    prompt_tokens: &[u32],
    request_vision_fingerprint: Option<[u8; 32]>,
    text_anchor_reuse_limit: Option<usize>,
    require_paired: bool,
) -> Option<(usize, Qwen35SlotPreference)> {
    if store.is_empty() {
        return None;
    }
    qwen35_best_ledger_match(
        store.newest_first().map(|(index, entry)| {
            let anchor = entry.payload.anchor.deepest_prefix_for_route(
                prompt_tokens,
                request_vision_fingerprint,
                text_anchor_reuse_limit,
                require_paired,
            );
            let (retained, anchor) = qwen35_resume_candidate(
                &entry.payload.retained,
                anchor,
                request_vision_fingerprint,
                text_anchor_reuse_limit,
            );
            let retained = if require_paired && !entry.payload.retained.draft_prefix.maintained() {
                &[][..]
            } else { retained };
            (index, retained, anchor)
        }),
        prompt_tokens,
    )
}

fn in_place_for_route(
    slot: SlotId, retained: &Qwen35RetainedPrefix, anchors: &Qwen35AnchorStore,
    prompt: &[u32], vision: Option<[u8; 32]>, text_limit: Option<usize>,
    original: Option<Qwen35SlotPreference>, require_paired: bool,
) -> Option<Qwen35SlotPreference> {
    if !require_paired { return original; }
    let anchor = anchors.deepest_prefix_for_route(prompt, vision, text_limit, true);
    let (live, anchor) = qwen35_resume_candidate(retained, anchor, vision, text_limit);
    let live = if retained.draft_prefix.maintained() { live } else { &[][..] };
    qwen35_best_ledger_match([(slot.0 as usize, live, anchor)], prompt)
        .map(|(_, preference)| Qwen35SlotPreference { slot, ..preference })
}

fn ledger_tokens(retained: &Qwen35RetainedPrefix, anchors: &Qwen35AnchorStore) -> usize {
    retained.len().max(
        anchors
            .committed()
            .iter()
            .map(|anchor| anchor.prompt_tokens.len())
            .max()
            .unwrap_or(0),
    )
}

/// Host-side bytes of a ledger, charged to the spill budget with the cache
/// copy so the store bound covers everything an entry keeps alive.
fn ledger_bytes(retained: &Qwen35RetainedPrefix, anchors: &Qwen35AnchorStore) -> usize {
    let spec = |spec: &Option<Qwen35SpecPrefixBoundary>| {
        spec.as_ref()
            .map_or(0, |spec| spec.pending_target_hidden.byte_len())
    };
    retained
        .len()
        .saturating_mul(std::mem::size_of::<u32>())
        .saturating_add(spec(&retained.spec))
        .saturating_add(anchors.owned_bytes())
}

fn validate_carried_prefixes(
    retained: &Qwen35RetainedPrefix, anchors: &Qwen35AnchorStore,
) -> anyhow::Result<()> {
    for old in anchors.committed().iter().chain(anchors.pending()) {
        if !retained.tokens.starts_with(&old.prompt_tokens) {
            return Err(DFlash2CheckpointIncompatible(
                "carried anchor no longer belongs to the retained live token prefix").into());
        }
    }
    Ok(())
}

/// Spill the conversation that held `slot` (see [`VictimSpill`]). A spill
/// that cannot be taken or stored is logged; the conversation then goes cold
/// exactly as it did before #727.
fn spill_qwen35_victim(
    kv: &HybridKvCache,
    store: &mut Qwen35SlotSpillStore,
    slot: SlotId,
    retained: &mut Qwen35RetainedPrefix,
    anchor: &mut Qwen35AnchorStore,
    mode: VictimSpill,
    mut draft: DraftRestore<'_>,
) -> anyhow::Result<()> {
    if mode == VictimSpill::Keep {
        return Ok(());
    }
    validate_carried_prefixes(retained, anchor)?;
    let tokens = ledger_tokens(retained, anchor);
    let kv_bytes = kv.slot_spill_bytes_with_anchors(
        slot, anchor.committed().iter().chain(anchor.pending()).map(|old| &old.kv))?;
    let eligible = retained.draft_prefix.maintained();
    if eligible && draft.is_none() {
        return Err(DFlash2CheckpointIncompatible("maintained live spill has no runtime").into());
    }
    let shared_draft = if eligible {
        anchor.committed().iter().find(|old| old.prompt_tokens == retained.tokens)
            .and_then(|old| old.draft.clone())
    } else { None };
    let draft_bytes = if eligible && shared_draft.is_none() {
        draft.as_ref().expect("eligible drafter").1.lane_checkpoint_owned_bytes(slot.0 as usize)?
            .checked_add(2 * std::mem::size_of::<usize>())
            .context("Qwen spill draft estimate overflow")?
    } else { 0 };
    let bytes = u64::try_from(kv_bytes.saturating_add(ledger_bytes(retained, anchor))
        .saturating_add(draft_bytes)).unwrap_or(u64::MAX);
    if !store.admits(bytes) {
        tracing::debug!(
            target: LOG_TARGET,
            slot = slot.0,
            tokens,
            bytes,
            "Qwen35 slot spill not stored: entry exceeds the spill budget"
        );
        return Ok(());
    }
    let ticket = anchor.begin_capture()?;
    let snapshot = (|| -> anyhow::Result<_> {
        let live_draft = if eligible {
            let tokens = retained.as_slice();
            if kv.sequence_len_for_slot(slot)? as usize != tokens.len() {
                return Err(DFlash2CheckpointIncompatible("live spill target/token cursor").into());
            }
            match shared_draft {
                Some(image) => Some(image),
                None => {
                    let (device, runtime) = draft.as_mut().expect("eligible drafter");
                    let image = runtime.snapshot_lane_checkpoint(device, slot.0 as usize)?;
                    runtime.validate_lane_checkpoint(slot.0 as usize, &image, tokens)
                        .context(DFlash2CheckpointIncompatible("live spill token binding"))?;
                    Some(Arc::new(image))
                }
            }
        } else { None };
        Ok((live_draft, kv.spill_slot_with_anchors(
            slot, anchor.committed().iter().chain(anchor.pending()).map(|old| &old.kv))?))
    })();
    let closed = anchor.finish_capture(ticket);
    let (live_draft, spilled) = snapshot?;
    closed?;
    let extra_draft_bytes = live_draft.as_ref().map_or(0, |image| {
        if anchor.committed().iter().filter_map(|old| old.draft.as_ref())
            .any(|old| Arc::ptr_eq(image, old)) { 0 } else { draft_owned_bytes(image) }
    });
    let bytes = u64::try_from(kv_bytes.saturating_add(ledger_bytes(retained, anchor))
        .saturating_add(extra_draft_bytes)).unwrap_or(u64::MAX);
    let (retained, anchor) = match mode {
        VictimSpill::Move => {
            let empty = anchor.empty_like();
            (std::mem::take(retained), std::mem::replace(anchor, empty))
        }
        VictimSpill::Copy => (retained.clone(), anchor.clone()),
        VictimSpill::Keep => unreachable!("Keep returned above"),
    };
    let payload = Qwen35SlotSpill {
        source_slot: slot.0,
        kv: spilled,
        retained,
        anchor,
        live_draft,
    };
    match store.insert(bytes, payload) {
        SpillInsert::Stored { stamp, evicted } => {
            for entry in evicted {
                tracing::debug!(
                    target: LOG_TARGET,
                    slot = entry.payload.source_slot,
                    stamp = entry.stamp,
                    tokens = ledger_tokens(&entry.payload.retained, &entry.payload.anchor),
                    bytes = entry.bytes,
                    "Qwen35 slot spill evicted (oldest stamp)"
                );
            }
            tracing::debug!(
                target: LOG_TARGET,
                slot = slot.0,
                stamp,
                tokens,
                bytes,
                copy = mode == VictimSpill::Copy,
                entries = store.len(),
                resident_bytes = store.resident_bytes(),
                "Qwen35 slot spilled"
            );
        }
        SpillInsert::Rejected(_) => unreachable!("admission was checked before the copy"),
    }
    Ok(())
}

/// Spill a slot an embedding request takes over: its ledger is cleared.
pub(super) fn spill_reclaimed_qwen35_slot(
    kv: &HybridKvCache,
    store: &mut Qwen35SlotSpillStore,
    slot: SlotId,
    retained: &mut Qwen35RetainedPrefix,
    anchor: &mut Qwen35AnchorStore,
    draft: DraftRestore<'_>,
) -> anyhow::Result<()> {
    if !retained.is_empty() || !anchor.is_empty() {
        spill_qwen35_victim(kv, store, slot, retained, anchor, VictimSpill::Move, draft)?;
    }
    Ok(())
}

/// Generation admission's reclaim step, run once the scheduler granted
/// `slot`. Spills the slot's previous conversation when this admission
/// discards it, restores the best-matching spilled conversation when it
/// resumes more of the prompt than the slot does in place, and returns the
/// resume preference for the granted slot.
///
/// An `Err` means a restore wrote part of the slot; the caller must reset
/// the slot and clear its ledger.
#[allow(clippy::too_many_arguments)]
pub(super) fn reclaim_qwen35_slot(
    kv: &mut HybridKvCache,
    store: &mut Qwen35SlotSpillStore,
    slot: SlotId,
    retained: &mut Qwen35RetainedPrefix,
    anchor: &mut Qwen35AnchorStore,
    in_place: Option<Qwen35SlotPreference>,
    prompt_tokens: &[u32],
    request_vision_fingerprint: Option<[u8; 32]>,
    text_anchor_reuse_limit: Option<usize>,
    mut draft: DraftRestore<'_>,
    require_paired: bool,
) -> anyhow::Result<Option<Qwen35SlotPreference>> {
    let raw_spill_match = best_spill_match(
        store, prompt_tokens, request_vision_fingerprint, text_anchor_reuse_limit, false);
    let spill_match = if require_paired {
        best_spill_match(store, prompt_tokens, request_vision_fingerprint,
            text_anchor_reuse_limit, true)
    } else { raw_spill_match };
    let selected_in_place = in_place_for_route(slot, retained, anchor, prompt_tokens,
        request_vision_fingerprint, text_anchor_reuse_limit, in_place, require_paired);
    if require_paired && (in_place.is_some() || raw_spill_match.is_some())
        && selected_in_place.is_none() && spill_match.is_none() {
        return Err(DFlash2CheckpointIncompatible(
            "eligible continuation has no compatible paired ancestor").into());
    }
    let plan = plan_reclaim(
        selected_in_place,
        spill_match,
        prompt_tokens,
        retained.as_slice(),
        !retained.is_empty() || !anchor.is_empty(),
    );
    // Take the matched entry before spilling the victim so the victim's
    // insertion can never evict it.
    let restore = plan
        .restore
        .map(|(index, preference)| (store.take(index), preference));
    spill_qwen35_victim(kv, store, slot, retained, anchor, plan.victim,
        draft.as_mut().map(|(device, runtime)| (*device, &mut **runtime)))?;
    let Some((mut entry, preference)) = restore else {
        return Ok(selected_in_place);
    };
    let tokens = ledger_tokens(&entry.payload.retained, &entry.payload.anchor);
    validate_carried_prefixes(&entry.payload.retained, &entry.payload.anchor)?;
    if entry.payload.retained.draft_prefix.maintained()
        && (draft.is_none() || entry.payload.live_draft.is_none()) {
        return Err(DFlash2CheckpointIncompatible("maintained spill has no live draft image/runtime").into());
    }
    if let Some((_, runtime)) = draft.as_mut() {
        for old in entry.payload.anchor.committed().iter().chain(entry.payload.anchor.pending()) {
            if old.draft_prefix.maintained() {
                let image = old.draft.as_ref().ok_or(DFlash2CheckpointIncompatible(
                    "maintained spilled anchor has no draft image"))?;
                runtime.validate_lane_checkpoint(slot.0 as usize, image, &old.prompt_tokens)
                    .context(DFlash2CheckpointIncompatible("spilled anchor token binding or geometry"))?;
            }
        }
        if let Some(image) = entry.payload.live_draft.as_ref() {
            entry.payload.kv.validate_logical_token_boundary(entry.payload.retained.tokens.len())?;
            runtime.prepare_lane_checkpoint_restore(
                slot.0 as usize, image, &entry.payload.retained.tokens)
                .context(DFlash2CheckpointIncompatible("restored spill token binding or geometry"))?;
        } else {
            runtime.prepare_lane_checkpoint_change(slot.0 as usize)?;
        }
    } else if entry.payload.anchor.committed().iter().chain(entry.payload.anchor.pending())
        .any(|old| old.draft_prefix.maintained()) {
        return Err(DFlash2CheckpointIncompatible("maintained spilled anchor has no runtime").into());
    }
    let target_plan = kv.plan_slot_spill_restore(slot, &entry.payload.kv)?;
    for old in entry.payload.anchor.committed().iter().chain(entry.payload.anchor.pending()) {
        target_plan.validate_anchor(&old.kv)?;
    }
    let ticket = entry.payload.anchor.begin_capture()?;
    let restored = (|| -> anyhow::Result<()> {
        let receipt = target_plan.apply()?;
        entry.payload.anchor.rebind_restored_checkpoints(&receipt)?;
        if let (Some((device, runtime)), Some(image)) =
            (draft.as_mut(), entry.payload.live_draft.as_ref()) {
            runtime.restore_lane_checkpoint(device, slot.0 as usize, image)?;
        }
        if entry.payload.live_draft.is_none() {
            if let Some((_, runtime)) = draft.as_mut() {
                runtime.clear_lane(slot.0 as usize)?;
            }
        }
        entry.payload.anchor.finish_capture(ticket)?;
        Ok(())
    })();
    if let Err(error) = restored {
        entry.payload.anchor.poison_and_clear();
        anchor.poison_and_clear();
        retained.clear_all();
        if let Some((_, runtime)) = draft.as_mut() {
            if let Err(invalidation) = runtime.clear_lane(slot.0 as usize) {
                return Err(invalidation.context(format!(
                    "invalidate Qwen draft lane after failed paired spill restore: {error:#}")));
            }
        }
        return Err(error.context("Qwen paired live spill restore"));
    }
    *retained = entry.payload.retained;
    *anchor = entry.payload.anchor;
    anchor.rebind_slot(slot.0 as usize);
    tracing::debug!(
        target: LOG_TARGET,
        slot = slot.0,
        from_slot = entry.payload.source_slot,
        stamp = entry.stamp,
        tokens,
        bytes = entry.bytes,
        cached_tokens = preference.cached_tokens,
        anchor = preference.restore_prompt_anchor,
        "Qwen35 slot spill restored"
    );
    Ok(Some(Qwen35SlotPreference { slot, ..preference }))
}

#[cfg(test)]
#[path = "qwen35_slot_spill_tests.rs"]
mod tests;