toktrie 1.3.0

LLM Token Trie library
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
use std::{
    fmt::Debug,
    hash::Hash,
    ops::{Index, RangeInclusive},
};

pub type TokenId = u32;

#[derive(Clone)]
pub struct SimpleVob {
    data: Vec<u32>,
    size: usize,
}

impl Hash for SimpleVob {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.size.hash(state);
        self.data.hash(state);
    }
}

impl PartialEq for SimpleVob {
    fn eq(&self, other: &Self) -> bool {
        self.size == other.size && self.data == other.data
    }
}

impl Eq for SimpleVob {}

impl Debug for SimpleVob {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SimpleVob")
            .field("len", &self.len())
            .finish()
    }
}

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

impl From<SimpleVob> for Vec<u32> {
    fn from(val: SimpleVob) -> Self {
        val.data
    }
}

const BITS: usize = 32;

impl SimpleVob {
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            size: 0,
        }
    }

    pub fn from_slice(bits: &[bool]) -> Self {
        let mut r = Self::alloc(bits.len());
        for (idx, b) in bits.iter().enumerate() {
            r.set(idx, *b);
        }
        r
    }

    pub fn alloc(size: usize) -> Self {
        let mut r = Self::new();
        r.resize(size);
        r
    }

    pub fn alloc_ones(size: usize) -> Self {
        let mut r = Self::alloc(size);
        r.set_all(true);
        r
    }

    pub fn alloc_with_capacity(size: usize, capacity: usize) -> Self {
        let mut r = Self::new();
        assert!(size <= capacity);
        r.resize(capacity);
        r.size = size;
        r
    }

    pub fn len(&self) -> usize {
        self.size
    }

    pub fn is_empty(&self) -> bool {
        self.size == 0
    }

    pub fn num_set(&self) -> usize {
        self.data.iter().map(|x| x.count_ones() as usize).sum()
    }

    fn clear_excessive_bits(&mut self) {
        for i in self.size..(self.data.len() * 32) {
            // disallow tokens that are out of range
            self.disallow_token(i as TokenId);
        }
    }

    pub fn to_bin_string(&self) -> String {
        let mut s = String::new();
        for i in 0..self.size {
            s.push(if self.is_allowed(i as TokenId) {
                '1'
            } else {
                '0'
            });
        }
        s
    }

    pub fn negated(&self) -> Self {
        let mut r = Self::new();
        r.data = self.data.iter().map(|x| !x).collect();
        r.size = self.size;
        r.clear_excessive_bits();
        r
    }

    pub fn as_ptr(&self) -> *const u32 {
        self.data.as_ptr()
    }

    pub fn as_slice(&self) -> &[u32] {
        &self.data
    }

    #[inline(always)]
    pub fn iter_set_entries(&self, mut f: impl FnMut(usize)) {
        let numelts = self.size;
        let max_len = numelts / 32;
        for (idx, &d) in self.as_slice()[..max_len].iter().enumerate() {
            // optimize for the two common cases
            if d == 0 {
                continue;
            } else if d == u32::MAX {
                for bit in 0..32 {
                    f(idx * 32 + bit);
                }
            } else {
                for bit in 0..32 {
                    if d & (1 << bit) != 0 {
                        f(idx * 32 + bit);
                    }
                }
            }
        }
        // final few elts
        for idx in (max_len * 32)..numelts {
            if self.is_allowed(idx as TokenId) {
                f(idx);
            }
        }
    }

    #[inline(always)]
    pub fn iter_unset_entries(&self, mut f: impl FnMut(usize)) {
        let numelts = self.size;
        let max_len = numelts / 32;
        for (idx, &d) in self.as_slice()[..max_len].iter().enumerate() {
            // optimize for the two common cases
            if d == 0 {
                for bit in 0..32 {
                    f(idx * 32 + bit);
                }
            } else if d == u32::MAX {
                continue;
            } else {
                for bit in 0..32 {
                    if d & (1 << bit) == 0 {
                        f(idx * 32 + bit);
                    }
                }
            }
        }
        // final few elts
        for idx in (max_len * 32)..numelts {
            if !self.is_allowed(idx as TokenId) {
                f(idx);
            }
        }
    }

    #[inline(always)]
    pub fn iter_entries(&self, mut f: impl FnMut(bool, usize)) {
        let numelts = self.size;
        let max_len = numelts / 32;
        for (idx, &d) in self.as_slice()[..max_len].iter().enumerate() {
            // optimize for the two common cases
            if d == 0 {
                for bit in 0..32 {
                    f(false, idx * 32 + bit);
                }
            } else if d == u32::MAX {
                for bit in 0..32 {
                    f(true, idx * 32 + bit);
                }
            } else {
                for bit in 0..32 {
                    f(d & (1 << bit) != 0, idx * 32 + bit);
                }
            }
        }
        // final few elts
        for idx in (max_len * 32)..numelts {
            f(self.is_allowed(idx as TokenId), idx);
        }
    }

    pub fn write_to(&self, buf: &mut [u8]) {
        assert!(buf.len() <= self.data.len() * (BITS / 8));
        buf.copy_from_slice(&bytemuck::cast_slice(&self.data)[..buf.len()]);
    }

    #[inline(always)]
    pub fn allow_token(&mut self, tok: TokenId) {
        self.set(tok as usize, true)
    }

    #[inline(always)]
    pub fn disallow_token(&mut self, tok: TokenId) {
        self.set(tok as usize, false)
    }

    #[inline(always)]
    pub fn set(&mut self, idx: usize, val: bool) {
        let byte_idx = idx / BITS;
        let bit_idx = idx % BITS;
        if val {
            self.data[byte_idx] |= 1 << bit_idx;
        } else {
            self.data[byte_idx] &= !(1 << bit_idx);
        }
    }

    pub fn allow_range(&mut self, range: RangeInclusive<TokenId>) {
        assert!(*range.end() < self.size as TokenId);
        let start = *range.start() as usize;
        let end = *range.end() as usize;
        if start > end {
            return;
        }
        let start_word = start / BITS;
        let end_word = end / BITS;
        let start_mask = !0u32 << (start % BITS);
        let end_bit = end % BITS;
        let end_mask = !0u32 >> (BITS - 1 - end_bit);
        if start_word == end_word {
            let mask = start_mask & end_mask;
            self.data[start_word] |= mask;
        } else {
            self.data[start_word] |= start_mask;
            for w in (start_word + 1)..end_word {
                self.data[w] = !0u32;
            }
            self.data[end_word] |= end_mask;
        }
    }

    pub fn resize(&mut self, size: usize) {
        let new_size = size / BITS + 1;
        assert!(new_size >= self.data.len());
        self.data.resize(new_size, 0);
        self.size = size;
    }

    #[inline(always)]
    pub fn get(&self, idx: usize) -> bool {
        let byte_idx = idx / 32;
        let bit_idx = idx % 32;
        (self.data[byte_idx] & (1 << bit_idx)) != 0
    }

    #[inline(always)]
    pub fn is_allowed(&self, tok: TokenId) -> bool {
        self.get(tok as usize)
    }

    pub fn set_all(&mut self, val: bool) {
        let bits = if val { !0 } else { 0 };
        self.data.iter_mut().for_each(|x| *x = bits);
        if val {
            self.clear_excessive_bits();
        }
    }

    pub fn apply_to(&self, logits: &mut [f32]) {
        for (idx, v) in self.data.iter().enumerate() {
            if *v == 0 {
                continue;
            }
            let idx = idx * BITS;
            for bit_idx in 0..BITS {
                if v & (1 << bit_idx) != 0 {
                    logits[idx + bit_idx] = 0.0;
                }
            }
        }
    }

    pub fn iter(&self) -> SimpleVobIter<'_> {
        SimpleVobIter { vob: self, idx: 0 }
    }

    pub fn set_from(&mut self, other: &SimpleVob) {
        assert_eq!(self.size, other.size);
        self.data.copy_from_slice(&other.data);
    }

    pub fn or(&mut self, other: &SimpleVob) {
        assert!(self.size >= other.size);
        for (idx, v) in self.data.iter_mut().zip(other.data.iter()) {
            *idx |= *v;
        }
    }

    pub fn trim_trailing_zeros(&mut self) {
        let mut idx = self.data.len();
        while idx > 0 && self.data[idx - 1] == 0 {
            idx -= 1;
        }
        if self.data.len() != idx {
            self.data.truncate(idx);
            self.size = self.data.len() * BITS;
        }
    }

    /// self |= other & !minus
    pub fn or_minus(&mut self, other: &SimpleVob, minus: &SimpleVob) {
        assert_eq!(self.size, other.size);
        assert_eq!(self.size, minus.size);
        for ((slf, oth), mn) in self
            .data
            .iter_mut()
            .zip(other.data.iter())
            .zip(minus.data.iter())
        {
            *slf |= *oth & !*mn;
        }
    }

    pub fn and(&mut self, other: &SimpleVob) {
        assert_eq!(self.size, other.size);
        for (idx, v) in self.data.iter_mut().zip(other.data.iter()) {
            *idx &= *v;
        }
    }

    pub fn is_zero(&self) -> bool {
        self.data.iter().all(|x| *x == 0)
    }

    pub fn and_is_zero(&self, other: &SimpleVob) -> bool {
        assert_eq!(self.size, other.size);
        self.data
            .iter()
            .zip(other.data.iter())
            .all(|(a, b)| *a & *b == 0)
    }

    pub fn sub(&mut self, other: &SimpleVob) {
        assert_eq!(self.size, other.size);
        for (idx, v) in self.data.iter_mut().zip(other.data.iter()) {
            *idx &= !*v;
        }
    }

    pub fn first_bit_set_here_and_in(&self, other: &SimpleVob) -> Option<usize> {
        assert_eq!(self.size, other.size);
        for (idx, (a, b)) in self.data.iter().zip(other.data.iter()).enumerate() {
            let v = *a & *b;
            if v != 0 {
                return Some(idx * BITS + v.trailing_zeros() as usize);
            }
        }
        None
    }

    pub fn first_bit_set(&self) -> Option<usize> {
        for (idx, v) in self.data.iter().enumerate() {
            if *v != 0 {
                return Some(idx * BITS + v.trailing_zeros() as usize);
            }
        }
        None
    }

    pub fn to_list(&self) -> Vec<u32> {
        let mut r = Vec::new();
        self.iter_set_entries(|x| r.push(x as u32));
        r
    }
}

pub struct SimpleVobIter<'a> {
    vob: &'a SimpleVob,
    idx: usize,
}

impl Iterator for SimpleVobIter<'_> {
    type Item = u32;

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        let mut bitoff = self.idx % BITS;
        let mut dataoff = self.idx / BITS;
        let data = &self.vob.data;
        while dataoff < data.len() {
            let d = data[dataoff] >> bitoff;
            if d != 0 {
                let idx = dataoff * BITS + d.trailing_zeros() as usize + bitoff;
                self.idx = idx + 1;
                return Some(idx as u32);
            }
            bitoff = 0;
            dataoff += 1;
        }
        None
    }
}

impl Index<usize> for SimpleVob {
    type Output = bool;

    fn index(&self, index: usize) -> &Self::Output {
        if self.is_allowed(index as TokenId) {
            &true
        } else {
            &false
        }
    }
}