chat-mlx 0.0.0

Local-inference chat-rs provider (and CLI) for MiniCPM5 / Llama / Qwen models on Apple Silicon via MLX.
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
//! Incremental JSON-prefix validator and a logit-mask constraint built on it.
//!
//! The validator answers, given the output so far, "could feeding this string
//! keep us on track to a well-formed JSON value?" — used to mask the vocabulary
//! each decode step so only tokens preserving valid JSON can be sampled. It
//! enforces JSON *syntax* (the schema's types/required fields are still checked
//! on the typed deserialize); it is sound (never accepts a token that would make
//! the output unparseable) but may be slightly conservative.

use std::sync::Arc;

use mlx_rs::{Array, error::Exception};

use crate::engine::constraint::LogitMask;

fn is_ws(c: char) -> bool {
    matches!(c, ' ' | '\t' | '\n' | '\r')
}

#[derive(Clone, Copy)]
enum Num {
    NeedInt,            // just saw '-'
    Zero,               // saw a leading 0
    Int,                // integer digits
    NeedFrac,           // saw '.', need a digit
    Frac,               // fractional digits
    NeedExpSignOrDigit, // saw e/E
    NeedExpDigit,       // saw e/E then sign
    Exp,                // exponent digits
}

fn num_complete(n: Num) -> bool {
    matches!(n, Num::Zero | Num::Int | Num::Frac | Num::Exp)
}

enum NumStep {
    Cont(Num),
    EndReprocess, // number finished; the current char belongs to the enclosing context
    Invalid,
}

fn num_feed(n: Num, c: char) -> NumStep {
    use Num::*;
    use NumStep::*;
    match n {
        NeedInt => match c {
            '0' => Cont(Zero),
            '1'..='9' => Cont(Int),
            _ => Invalid,
        },
        Zero => match c {
            '.' => Cont(NeedFrac),
            'e' | 'E' => Cont(NeedExpSignOrDigit),
            _ => EndReprocess,
        },
        Int => match c {
            '0'..='9' => Cont(Int),
            '.' => Cont(NeedFrac),
            'e' | 'E' => Cont(NeedExpSignOrDigit),
            _ => EndReprocess,
        },
        NeedFrac => match c {
            '0'..='9' => Cont(Frac),
            _ => Invalid,
        },
        Frac => match c {
            '0'..='9' => Cont(Frac),
            'e' | 'E' => Cont(NeedExpSignOrDigit),
            _ => EndReprocess,
        },
        NeedExpSignOrDigit => match c {
            '+' | '-' => Cont(NeedExpDigit),
            '0'..='9' => Cont(Exp),
            _ => Invalid,
        },
        NeedExpDigit => match c {
            '0'..='9' => Cont(Exp),
            _ => Invalid,
        },
        Exp => match c {
            '0'..='9' => Cont(Exp),
            _ => EndReprocess,
        },
    }
}

#[derive(Clone)]
enum St {
    Start,
    Done,
    ExpectValue,
    ArrStart,
    ObjStart,
    ObjKey,
    Str { esc: bool, key: bool, hex: u8 },
    ExpectColon,
    Num(Num),
    Lit { lit: &'static str, i: usize },
    AfterObj,
    AfterArr,
}

/// Incremental JSON validator. `stack` is the container nesting (`true` =
/// object, `false` = array).
#[derive(Clone)]
pub struct JsonState {
    stack: Vec<bool>,
    st: St,
}

impl Default for JsonState {
    fn default() -> Self {
        Self::new()
    }
}

impl JsonState {
    pub fn new() -> Self {
        Self {
            stack: Vec::new(),
            st: St::Start,
        }
    }

    /// Feed one char; returns false if it cannot extend to valid JSON.
    pub fn feed(&mut self, c: char) -> bool {
        loop {
            match self.st {
                St::Str { esc, key, hex } => return self.feed_string(c, esc, key, hex),
                St::Lit { lit, i } => return self.feed_lit(c, lit, i),
                St::Num(n) => match num_feed(n, c) {
                    NumStep::Cont(n2) => {
                        self.st = St::Num(n2);
                        return true;
                    }
                    NumStep::Invalid => return false,
                    NumStep::EndReprocess => {
                        self.complete_value();
                        continue; // re-process c in the enclosing context
                    }
                },
                _ => {}
            }

            // Whitespace is allowed (and ignored) between structural tokens,
            // including trailing whitespace after a complete value.
            if is_ws(c) {
                return true;
            }

            return match self.st {
                St::Start | St::ExpectValue => self.begin_value(c),
                St::ArrStart => {
                    if c == ']' {
                        self.close_container();
                        true
                    } else {
                        self.begin_value(c)
                    }
                }
                St::ObjStart => match c {
                    '}' => {
                        self.close_container();
                        true
                    }
                    '"' => {
                        self.st = St::Str {
                            esc: false,
                            key: true,
                            hex: 0,
                        };
                        true
                    }
                    _ => false,
                },
                St::ObjKey => {
                    if c == '"' {
                        self.st = St::Str {
                            esc: false,
                            key: true,
                            hex: 0,
                        };
                        true
                    } else {
                        false
                    }
                }
                St::ExpectColon => {
                    if c == ':' {
                        self.st = St::ExpectValue;
                        true
                    } else {
                        false
                    }
                }
                St::AfterObj => match c {
                    ',' => {
                        self.st = St::ObjKey;
                        true
                    }
                    '}' => {
                        self.close_container();
                        true
                    }
                    _ => false,
                },
                St::AfterArr => match c {
                    ',' => {
                        self.st = St::ExpectValue;
                        true
                    }
                    ']' => {
                        self.close_container();
                        true
                    }
                    _ => false,
                },
                St::Done => false,
                // String/Lit/Num handled above.
                _ => false,
            };
        }
    }

    /// Whether the output so far is a complete top-level JSON value (so EOS is
    /// allowed).
    pub fn can_terminate(&self) -> bool {
        if !self.stack.is_empty() {
            return false;
        }
        match self.st {
            St::Done => true,
            St::Num(n) => num_complete(n),
            _ => false,
        }
    }

    /// Would feeding `s` (from the current state) stay valid? Non-mutating.
    pub fn allows(&self, s: &str) -> bool {
        let mut probe = self.clone();
        s.chars().all(|c| probe.feed(c))
    }

    fn begin_value(&mut self, c: char) -> bool {
        self.st = match c {
            '"' => St::Str {
                esc: false,
                key: false,
                hex: 0,
            },
            '{' => {
                self.stack.push(true);
                St::ObjStart
            }
            '[' => {
                self.stack.push(false);
                St::ArrStart
            }
            '-' => St::Num(Num::NeedInt),
            '0' => St::Num(Num::Zero),
            '1'..='9' => St::Num(Num::Int),
            't' => St::Lit { lit: "true", i: 1 },
            'f' => St::Lit { lit: "false", i: 1 },
            'n' => St::Lit { lit: "null", i: 1 },
            _ => return false,
        };
        true
    }

    fn complete_value(&mut self) {
        self.st = match self.stack.last() {
            None => St::Done,
            Some(true) => St::AfterObj,
            Some(false) => St::AfterArr,
        };
    }

    fn close_container(&mut self) {
        self.stack.pop();
        self.complete_value();
    }

    fn feed_string(&mut self, c: char, esc: bool, key: bool, hex: u8) -> bool {
        if hex > 0 {
            if c.is_ascii_hexdigit() {
                self.st = St::Str {
                    esc: false,
                    key,
                    hex: hex - 1,
                };
                true
            } else {
                false
            }
        } else if esc {
            match c {
                '"' | '\\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' => {
                    self.st = St::Str {
                        esc: false,
                        key,
                        hex: 0,
                    };
                    true
                }
                'u' => {
                    self.st = St::Str {
                        esc: false,
                        key,
                        hex: 4,
                    };
                    true
                }
                _ => false,
            }
        } else {
            match c {
                '\\' => {
                    self.st = St::Str {
                        esc: true,
                        key,
                        hex: 0,
                    };
                    true
                }
                '"' => {
                    if key {
                        self.st = St::ExpectColon;
                    } else {
                        self.complete_value();
                    }
                    true
                }
                c if (c as u32) < 0x20 => false,
                _ => true,
            }
        }
    }

    fn feed_lit(&mut self, c: char, lit: &'static str, i: usize) -> bool {
        if lit.as_bytes().get(i).copied() != Some(c as u8) {
            return false;
        }
        let next = i + 1;
        if next == lit.len() {
            self.complete_value();
        } else {
            self.st = St::Lit { lit, i: next };
        }
        true
    }
}

/// A [`LogitMask`] that restricts sampling to tokens keeping the output a valid
/// JSON prefix, and allows EOS only once a complete value has been produced.
pub struct JsonConstraint {
    state: JsonState,
    token_strings: Arc<Vec<String>>,
    eos: Vec<u32>,
}

impl JsonConstraint {
    pub fn new(token_strings: Arc<Vec<String>>, eos: Vec<u32>) -> Self {
        Self {
            state: JsonState::new(),
            token_strings,
            eos,
        }
    }
}

impl LogitMask for JsonConstraint {
    fn mask(&self, logits: &Array) -> Result<Array, Exception> {
        let vocab = self.token_strings.len();
        let mut add = vec![f32::NEG_INFINITY; vocab];
        for (id, s) in self.token_strings.iter().enumerate() {
            if self.state.allows(s) {
                add[id] = 0.0;
            }
        }
        let stop = self.state.can_terminate();
        for &e in &self.eos {
            if let Some(slot) = add.get_mut(e as usize) {
                *slot = if stop { 0.0 } else { f32::NEG_INFINITY };
            }
        }
        let mask = Array::from_slice(&add, &[vocab as i32]);
        logits.add(&mask)
    }

    fn accept(&mut self, token: u32) {
        if let Some(s) = self.token_strings.get(token as usize) {
            for c in s.chars() {
                let _ = self.state.feed(c);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn accepts(s: &str) -> bool {
        let mut st = JsonState::new();
        s.chars().all(|c| st.feed(c)) && st.can_terminate()
    }

    fn prefix_ok(s: &str) -> bool {
        let mut st = JsonState::new();
        s.chars().all(|c| st.feed(c))
    }

    #[test]
    fn accepts_well_formed() {
        assert!(accepts(r#"{"name":"Ada","age":36,"tags":["a","b"],"ok":true}"#));
        assert!(accepts(r#"[1,2,3]"#));
        assert!(accepts(r#""hello\nthere""#));
        assert!(accepts(r#"-12.5e3"#));
        assert!(accepts(r#"{ "k" : null }"#));
    }

    #[test]
    fn rejects_malformed() {
        assert!(!prefix_ok(r#"{"a":1,}"#)); // trailing comma
        assert!(!prefix_ok(r#"{'a':1}"#)); // single quotes
        assert!(!prefix_ok(r#"[1,,2]"#)); // empty element
        assert!(!prefix_ok(r#"01"#)); // leading zero
        assert!(!prefix_ok(r#"tru e"#)); // broken literal
    }

    #[test]
    fn partial_is_a_valid_prefix_but_not_terminable() {
        assert!(prefix_ok(r#"{"name":"#));
        assert!(!accepts(r#"{"name":"#)); // incomplete
        assert!(prefix_ok(r#"{"n"#));
        assert!(prefix_ok(r#"-12."#)); // valid prefix, needs a digit
        assert!(!accepts(r#"-12."#));
    }
}