ferrum-sampler 0.8.9

Sampling strategies for Ferrum LLM inference engine
Documentation
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! A single grammar owns reasoning, protocol framing, and either a final
//! schema value or an explicit automatic tool call. Tokens may span rules.
use super::*;
use ferrum_types::{ApiChatRequest, ModelOutputProtocol};

mod compiler;
#[cfg(test)]
mod tests;

#[derive(Clone)]
struct Header {
    bytes: Vec<u8>,
    reasoning: bool,
}

impl Header {
    fn result(text: &str) -> Self {
        Self {
            bytes: text.as_bytes().to_vec(),
            reasoning: false,
        }
    }
    fn reasoning(text: &str) -> Self {
        Self {
            bytes: text.as_bytes().to_vec(),
            reasoning: true,
        }
    }
}

struct Plan {
    headers: Vec<Header>,
    following_headers: Vec<Header>,
    reasoning_close: Vec<u8>,
    wire_token_bytes: Arc<[Vec<u8>]>,
    marker_bytes: HashMap<u32, Vec<u8>>,
    boundary_controls: HashSet<u32>,
    native_terminals: HashSet<u32>,
    native: bool,
}

#[derive(Clone, Copy)]
enum Domain {
    Header { offset: usize, following: bool },
    Reasoning { offset: usize, search_from: usize },
    Result { offset: usize },
}

pub(super) struct ComposedState {
    plan: Arc<Plan>,
    initial_matcher: Matcher,
    final_validator: Arc<jsonschema::Validator>,
    wire: Vec<u8>,
    token_ends: Vec<usize>,
    domain: Domain,
    reasoning_start: Option<usize>,
    reasoning_end: Option<usize>,
    terminal_seen: bool,
}

impl ComposedState {
    pub(super) fn reset(&mut self) {
        self.wire.clear();
        self.token_ends.clear();
        self.domain = Domain::Header {
            offset: 0,
            following: false,
        };
        self.reasoning_start = None;
        self.reasoning_end = None;
        self.terminal_seen = false;
        self.observe_domain();
    }

    pub(super) fn is_native(&self) -> bool {
        self.plan.native
    }

    pub(super) fn fresh_matcher(&self) -> Matcher {
        self.initial_matcher.deep_clone()
    }

    pub(super) fn complete_text_len(&self) -> usize {
        self.wire.len()
            - self
                .wire
                .iter()
                .rev()
                .take_while(|byte| byte.is_ascii_whitespace())
                .count()
    }

    fn bytes(&self, token: u32) -> &[u8] {
        self.plan
            .marker_bytes
            .get(&token)
            .map(Vec::as_slice)
            .or_else(|| {
                self.plan
                    .wire_token_bytes
                    .get(token as usize)
                    .map(Vec::as_slice)
            })
            .unwrap_or_default()
    }

    fn token_at(&self, byte_offset: usize) -> usize {
        self.token_ends.partition_point(|end| *end <= byte_offset)
    }

    fn observe(&mut self, token: u32) {
        let bytes = self.bytes(token).to_vec();
        self.wire.extend_from_slice(&bytes);
        self.token_ends.push(self.wire.len());
        self.observe_domain();
    }

    fn observe_domain(&mut self) {
        loop {
            match self.domain {
                Domain::Header { offset, following } => {
                    let candidates = if following {
                        &self.plan.following_headers
                    } else {
                        &self.plan.headers
                    };
                    let remaining = &self.wire[offset..];
                    let Some(header) = candidates
                        .iter()
                        .find(|header| remaining.starts_with(&header.bytes))
                    else {
                        return;
                    };
                    let end = offset + header.bytes.len();
                    if header.reasoning {
                        self.reasoning_start = Some(end);
                        self.domain = Domain::Reasoning {
                            offset: end,
                            search_from: end,
                        };
                    } else {
                        self.domain = Domain::Result { offset: end };
                    }
                }
                Domain::Reasoning {
                    offset,
                    search_from,
                } => {
                    let close = &self.plan.reasoning_close;
                    if close.is_empty() {
                        return;
                    }
                    if let Some(position) = self.wire[search_from..]
                        .windows(close.len())
                        .position(|bytes| bytes == close)
                    {
                        let start = search_from + position;
                        let end = start + close.len();
                        self.reasoning_end = Some(start);
                        self.domain = if self.plan.native {
                            Domain::Header {
                                offset: end,
                                following: true,
                            }
                        } else {
                            Domain::Result { offset: end }
                        };
                    } else {
                        self.domain = Domain::Reasoning {
                            offset,
                            search_from: self
                                .wire
                                .len()
                                .saturating_sub(close.len().saturating_sub(1))
                                .max(offset),
                        };
                        return;
                    }
                }
                Domain::Result { .. } => return,
            }
        }
    }

    pub(super) fn result_start(&self) -> Option<usize> {
        match self.domain {
            Domain::Result { offset } => Some(self.token_at(offset)),
            _ => None,
        }
    }

    fn reasoning_tokens(&self) -> usize {
        self.reasoning_start.map_or(0, |start| {
            let end = self
                .reasoning_end
                .map(|end| self.token_at(end))
                .unwrap_or(self.token_ends.len());
            end.saturating_sub(self.token_at(start))
        })
    }

    fn forcing_suffix(&self, budget: Option<StructuredOutputBudgetPlan>) -> Option<&[u8]> {
        let Domain::Reasoning { offset, .. } = self.domain else {
            return None;
        };
        if !budget.is_some_and(|budget| self.reasoning_tokens() >= budget.reasoning_token_limit) {
            return None;
        }
        let close = &self.plan.reasoning_close;
        let tail = &self.wire[offset..];
        let prefix = (1..close.len().min(tail.len() + 1))
            .rev()
            .find(|length| tail.ends_with(&close[..*length]))
            .unwrap_or(0);
        Some(&close[prefix..])
    }
}

pub(super) fn compile(
    factory: &StructuredOutputFactory,
    response_format: &ResponseFormat,
    start: &StructuredOutputStart,
    max_tokens: usize,
    stop_ids: &HashSet<u32>,
    stop_texts: &[String],
    chat: &ApiChatRequest,
    protocol: ModelOutputProtocol,
) -> Result<StructuredOutputProcessor> {
    let compiled = compiler::build(
        factory,
        response_format,
        start,
        max_tokens,
        stop_ids,
        stop_texts,
        chat,
        protocol,
    )?;
    let matcher = cached_matcher(factory, compiled.grammar)?;
    let final_validator = cached_final_validator(factory, response_format)?;
    let mut composed = ComposedState {
        plan: Arc::new(compiled.plan),
        initial_matcher: matcher.deep_clone(),
        final_validator,
        wire: Vec::new(),
        token_ends: Vec::new(),
        domain: Domain::Header {
            offset: 0,
            following: false,
        },
        reasoning_start: None,
        reasoning_end: None,
        terminal_seen: false,
    };
    composed.observe_domain();
    let grammar_start = composed.result_start();
    Ok(StructuredOutputProcessor {
        state: Mutex::new(ProcessorState {
            matcher,
            activation: Activation::Active,
            initial_activation: Activation::Active,
            consumed: 0,
            boundary_forced: false,
            boundary_start: None,
            grammar_start,
            trailing_grammar_token_id: None,
            trailing_identical_token_count: 0,
            liveness_intervention_count: 0,
            last_liveness_intervention_at: None,
            composed: Some(composed),
        }),
        vocab_size: factory.vocab_size,
        defined_token_ids: Arc::clone(&factory.defined_token_ids),
        json_token_classes: Arc::clone(&factory.json_token_classes),
        budget: compiled.budget,
        liveness: StructuredOutputLivenessPolicy::for_request(max_tokens, compiled.budget),
    })
}

fn cached_matcher(factory: &StructuredOutputFactory, grammar: TopLevelGrammar) -> Result<Matcher> {
    let key = format!(
        "automatic-tools:{}",
        serde_json::to_string(&grammar).map_err(|error| {
            FerrumError::invalid_request(format!("serialize structured tool grammar: {error}"))
        })?
    );
    let mut cache = factory.grammar_templates.lock();
    if let Some(matcher) = cache.get(&key) {
        return Ok(matcher.deep_clone());
    }
    let parser = factory
        .parser_factory
        .create_parser(grammar)
        .map_err(|error| {
            FerrumError::invalid_request(format!("unsupported structured tool grammar: {error}"))
        })?;
    let matcher = Matcher::new(Ok(parser));
    if cache.len() >= MAX_CACHED_GRAMMARS {
        cache.clear();
    }
    cache.insert(key, matcher.deep_clone());
    Ok(matcher)
}

fn acceptance(matcher: &mut Matcher) -> Result<bool> {
    matcher
        .is_accepting()
        .map_err(|error| FerrumError::model(format!("structured tool acceptance failed: {error}")))
}

fn cached_final_validator(
    factory: &StructuredOutputFactory,
    response_format: &ResponseFormat,
) -> Result<Arc<jsonschema::Validator>> {
    let schema = match response_format {
        ResponseFormat::JsonObject => serde_json::json!({"type": "object"}),
        ResponseFormat::JsonSchema(schema) => serde_json::from_str(schema).map_err(|error| {
            FerrumError::invalid_request(format!(
                "response_format.schema is not valid JSON: {error}"
            ))
        })?,
        ResponseFormat::Text => {
            return Err(FerrumError::internal(
                "automatic tool grammar requires a structured response format",
            ));
        }
    };
    let key = serde_json::to_string(&schema).map_err(|error| {
        FerrumError::invalid_request(format!("serialize structured final schema: {error}"))
    })?;
    let mut cache = factory.schema_validators.lock();
    if let Some(validator) = cache.get(&key) {
        return Ok(Arc::clone(validator));
    }
    // Match the server's full-schema validator. The sampling compiler's ordered
    // properties and whitespace policy must not change a value's final/tool role.
    let validator = Arc::new(jsonschema::validator_for(&schema).map_err(|error| {
        FerrumError::invalid_request(format!("invalid structured final schema: {error}"))
    })?);
    if cache.len() >= MAX_CACHED_GRAMMARS {
        cache.clear();
    }
    cache.insert(key, Arc::clone(&validator));
    Ok(validator)
}

pub(super) fn classify(
    state: &mut ProcessorState,
    generated: &[TokenId],
    terminals: &HashSet<u32>,
) -> Result<Option<(ferrum_types::StructuredOutputBranch, String)>> {
    advance(state, generated, Some(terminals))?;
    if !acceptance(&mut state.matcher)? {
        return Ok(None);
    }
    let composed = state.composed.as_ref().expect("composed processor");
    if composed.is_native() {
        return Ok(None);
    }
    let Domain::Result { offset } = composed.domain else {
        return Err(FerrumError::internal(
            "complete structured tool grammar has no result boundary",
        ));
    };
    let payload = std::str::from_utf8(&composed.wire[offset..composed.complete_text_len()])
        .map_err(|error| FerrumError::model(format!("structured result is not UTF-8: {error}")))?
        .to_string();
    // The union has already accepted a complete root. Prefer semantic final
    // schema membership even when the tool branch supplied its generation path.
    let branch = if serde_json::from_str::<serde_json::Value>(&payload)
        .is_ok_and(|value| composed.final_validator.is_valid(&value))
    {
        ferrum_types::StructuredOutputBranch::Final
    } else {
        ferrum_types::StructuredOutputBranch::ToolCall
    };
    Ok(Some((branch, payload)))
}

pub(super) fn advance(
    state: &mut ProcessorState,
    generated: &[TokenId],
    terminals: Option<&HashSet<u32>>,
) -> Result<()> {
    if state.consumed > generated.len() {
        return Err(FerrumError::internal(
            "structured-output token history moved backwards without reset",
        ));
    }
    let composed = state.composed.as_mut().expect("composed processor");
    for token in &generated[state.consumed..] {
        if composed.terminal_seen {
            return Err(FerrumError::model(
                "structured tool result continued after its terminal",
            ));
        }
        // Ordinary EOS is external framing after a complete text/XML root.
        // Harmony handoff/return are grammar-owned and must be consumed.
        if !composed.plan.native
            && terminals.is_some_and(|ids| ids.contains(&token.get()))
            && acceptance(&mut state.matcher)?
        {
            composed.terminal_seen = true;
            composed.token_ends.push(composed.wire.len());
        } else {
            state.matcher.consume_token(token.get()).map_err(|error| {
                FerrumError::model(format!(
                    "structured-output token {} violated the tool/final grammar: {error}",
                    token.get()
                ))
            })?;
            composed.observe(token.get());
        }
        let result_start = composed.result_start();
        if state.grammar_start != result_start {
            state.trailing_grammar_token_id = None;
            state.trailing_identical_token_count = 0;
        }
        state.grammar_start = result_start;
        if state.grammar_start.is_some() {
            if state.trailing_grammar_token_id == Some(token.get()) {
                state.trailing_identical_token_count += 1;
            } else {
                state.trailing_grammar_token_id = Some(token.get());
                state.trailing_identical_token_count = 1;
            }
        }
        state.boundary_start = composed
            .reasoning_end
            .map(|offset| composed.token_at(offset));
    }
    state.consumed = generated.len();
    Ok(())
}

pub(super) fn mask(
    processor: &StructuredOutputProcessor,
    state: &mut ProcessorState,
    logits: &mut [f32],
    generated: &[TokenId],
    terminals: Option<&HashSet<u32>>,
    hidden_controls: Option<&HashSet<u32>>,
) -> Result<StructuredOutputMaskOutcome> {
    advance(state, generated, terminals)?;
    let accepting = acceptance(&mut state.matcher)?;
    let grammar_mask = state
        .matcher
        .compute_mask_or_eos()
        .map_err(|error| FerrumError::model(format!("structured tool mask failed: {error}")))?;
    let composed = state.composed.as_ref().expect("composed processor");
    let forcing = composed.forcing_suffix(processor.budget);
    state.boundary_forced |= forcing.is_some();
    let mut finite = 0usize;
    let mut forced_candidate = None;
    let mut native_terminal = None;
    let mut delimiter_candidates = Vec::new();
    for (index, logit) in logits.iter_mut().enumerate() {
        let id = index as u32;
        let external_terminal =
            !composed.plan.native && accepting && terminals.is_some_and(|ids| ids.contains(&id));
        let mut allowed = processor
            .defined_token_ids
            .get(index)
            .copied()
            .unwrap_or(false)
            && (grammar_mask.is_allowed(id) || external_terminal);
        if hidden_controls.is_some_and(|controls| controls.contains(&id))
            && !composed.plan.boundary_controls.contains(&id)
            && !external_terminal
        {
            allowed = false;
        }
        if let Some(suffix) = forcing {
            let bytes = composed.bytes(id);
            allowed &=
                !bytes.is_empty() && (suffix.starts_with(bytes) || bytes.starts_with(suffix));
        }
        if allowed {
            if composed.plan.native_terminals.contains(&id) && !accepting {
                if native_terminal.replace(id).is_some() {
                    return Err(FerrumError::internal(
                        "structured tool grammar allowed ambiguous native terminals",
                    ));
                }
            }
            if composed.plan.boundary_controls.contains(&id)
                && !composed.plan.native_terminals.contains(&id)
            {
                delimiter_candidates.push(id);
            }
            if forcing.is_some() && forced_candidate.is_none() {
                forced_candidate = Some(index);
            }
            if logit.is_finite() {
                finite += 1;
            }
        } else {
            *logit = f32::NEG_INFINITY;
        }
    }
    if finite == 0 {
        if let Some(index) = forced_candidate {
            logits[index] = 0.0;
            finite = 1;
        } else {
            return Err(FerrumError::model(
                "structured tool/final grammar has no legal finite token",
            ));
        }
    }
    let liveness_intervention = if state.grammar_start.is_some()
        && !accepting
        && state.trailing_identical_token_count >= processor.liveness.max_identical_token_run
    {
        state
            .trailing_grammar_token_id
            .and_then(|id| logits.get_mut(id as usize))
            .is_some_and(|logit| {
                if logit.is_finite() && finite > 1 {
                    *logit = f32::NEG_INFINITY;
                    if state.last_liveness_intervention_at != Some(generated.len()) {
                        state.liveness_intervention_count += 1;
                        state.last_liveness_intervention_at = Some(generated.len());
                    }
                    true
                } else {
                    false
                }
            })
    } else {
        false
    };
    Ok(StructuredOutputMaskOutcome {
        phase: if state.grammar_start.is_some() {
            StructuredOutputPhase::EnforcingGrammar
        } else if forcing.is_some() {
            StructuredOutputPhase::ForcingDelimiter
        } else {
            StructuredOutputPhase::WaitingForDelimiter
        },
        accepting,
        liveness_intervention,
        grammar_start_token_index: state.grammar_start,
        required_delimiter_token_id: (delimiter_candidates.len() == 1)
            .then(|| delimiter_candidates[0]),
        grammar_owned_terminal_token_id: native_terminal,
    })
}

pub(super) fn progress(
    processor: &StructuredOutputProcessor,
    state: &mut ProcessorState,
    generated: &[TokenId],
    terminals: Option<&HashSet<u32>>,
) -> Result<StructuredOutputProgress> {
    advance(state, generated, terminals)?;
    let accepting = acceptance(&mut state.matcher)?;
    let composed = state.composed.as_ref().expect("composed processor");
    let forcing = composed.forcing_suffix(processor.budget).is_some();
    state.boundary_forced |= forcing;
    let grammar_tokens = state
        .grammar_start
        .and_then(|index| generated.get(index..))
        .unwrap_or_default();
    let trailing = grammar_tokens.last().map(|token| token.get());
    let class_of = |token: u32| {
        processor
            .json_token_classes
            .get(token as usize)
            .copied()
            .unwrap_or(StructuredOutputTokenClass::Undefined)
    };
    let class = trailing.map(class_of);
    let class_count = class.map_or(0, |class| {
        grammar_tokens
            .iter()
            .rev()
            .take_while(|token| class_of(token.get()) == class)
            .count()
    });
    Ok(StructuredOutputProgress {
        phase: if state.grammar_start.is_some() {
            StructuredOutputPhase::EnforcingGrammar
        } else if forcing {
            StructuredOutputPhase::ForcingDelimiter
        } else {
            StructuredOutputPhase::WaitingForDelimiter
        },
        generated_token_count: generated.len(),
        consumed_token_count: state.consumed,
        delimiter_token_count: processor.budget.map(|budget| budget.boundary_token_count),
        delimiter_prefix_token_count: match composed.domain {
            Domain::Header { offset, .. } => composed.token_ends.len() - composed.token_at(offset),
            Domain::Reasoning { offset, .. } => {
                let close = &composed.plan.reasoning_close;
                let tail = &composed.wire[offset..];
                let prefix_bytes = (1..close.len().min(tail.len() + 1))
                    .rev()
                    .find(|length| tail.ends_with(&close[..*length]))
                    .unwrap_or(0);
                composed.token_ends.len() - composed.token_at(composed.wire.len() - prefix_bytes)
            }
            Domain::Result { .. } => 0,
        },
        reasoning_token_count: processor.budget.map(|_| composed.reasoning_tokens()),
        boundary_forced: state.boundary_forced,
        budget: processor.budget,
        grammar_token_count: grammar_tokens.len(),
        trailing_token_class: class,
        trailing_token_class_count: class_count,
        trailing_token_id: trailing,
        trailing_identical_token_count: trailing.map_or(0, |id| {
            grammar_tokens
                .iter()
                .rev()
                .take_while(|token| token.get() == id)
                .count()
        }),
        liveness_identical_token_limit: processor.liveness.max_identical_token_run,
        liveness_intervention_count: state.liveness_intervention_count,
        accepting,
    })
}