j_r_r_token 1.2.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +51 -0
- data/Cargo.lock +42 -37
- data/README.md +96 -14
- data/ext/j_r_r_token/Cargo.toml +3 -2
- data/ext/j_r_r_token/src/lib.rs +273 -35
- data/j_r_r_token.gemspec +1 -1
- data/lib/j_r_r_token/version.rb +1 -1
- data/lib/j_r_r_token.rb +429 -13
- data/sig/j_r_r_token.rbs +49 -1
- metadata +4 -4
data/ext/j_r_r_token/src/lib.rs
CHANGED
|
@@ -1,52 +1,290 @@
|
|
|
1
|
-
use
|
|
1
|
+
use std::{collections::HashSet, sync::OnceLock};
|
|
2
|
+
|
|
3
|
+
use magnus::{function, method, prelude::*, Error, RString, Ruby};
|
|
4
|
+
use regex::Regex;
|
|
2
5
|
use tiktoken_rs::{
|
|
3
|
-
|
|
6
|
+
bpe_for_tokenizer,
|
|
4
7
|
tokenizer::{get_tokenizer, Tokenizer},
|
|
5
8
|
CoreBPE,
|
|
6
9
|
};
|
|
7
10
|
|
|
8
|
-
// Resolves a model name (or bare encoding name) to a
|
|
11
|
+
// Resolves a model name (or bare encoding name) to a tokenizer.
|
|
9
12
|
// Model -> tokenizer dispatch is delegated to `tiktoken_rs::tokenizer::get_tokenizer`,
|
|
10
13
|
// which is kept in sync with upstream OpenAI tiktoken. It handles `ft:` prefix
|
|
11
|
-
// stripping, GPT-5/4.5/4.1/4o families, o1/o3/o4 reasoning models, gpt-oss
|
|
14
|
+
// stripping, GPT-5/4.5/4.1/4o families, o1/o3/o4-mini reasoning models, gpt-oss
|
|
12
15
|
// (harmony), codex-mini, and all legacy aliases.
|
|
13
|
-
fn
|
|
14
|
-
|
|
16
|
+
fn tokenizer_for(model: &str) -> Option<Tokenizer> {
|
|
17
|
+
match model {
|
|
15
18
|
// Bare encoding names — callers may pass these directly.
|
|
16
|
-
"o200k_harmony" =>
|
|
17
|
-
"o200k_base" =>
|
|
18
|
-
"cl100k_base" =>
|
|
19
|
-
"p50k_base" =>
|
|
20
|
-
"p50k_edit" =>
|
|
21
|
-
"r50k_base" =>
|
|
22
|
-
_ =>
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
19
|
+
"o200k_harmony" => Some(Tokenizer::O200kHarmony),
|
|
20
|
+
"o200k_base" => Some(Tokenizer::O200kBase),
|
|
21
|
+
"cl100k_base" => Some(Tokenizer::Cl100kBase),
|
|
22
|
+
"p50k_base" => Some(Tokenizer::P50kBase),
|
|
23
|
+
"p50k_edit" => Some(Tokenizer::P50kEdit),
|
|
24
|
+
"r50k_base" => Some(Tokenizer::R50kBase),
|
|
25
|
+
_ => get_tokenizer(model),
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Canonical encoding name. `Gpt2` is an alias tiktoken-rs keeps for r50k_base.
|
|
30
|
+
fn encoding_name(tokenizer: Tokenizer) -> &'static str {
|
|
31
|
+
match tokenizer {
|
|
32
|
+
Tokenizer::O200kHarmony => "o200k_harmony",
|
|
33
|
+
Tokenizer::O200kBase => "o200k_base",
|
|
34
|
+
Tokenizer::Cl100kBase => "cl100k_base",
|
|
35
|
+
Tokenizer::P50kBase => "p50k_base",
|
|
36
|
+
Tokenizer::P50kEdit => "p50k_edit",
|
|
37
|
+
Tokenizer::R50kBase | Tokenizer::Gpt2 => "r50k_base",
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
fn unsupported_model(ruby: &Ruby, model: &str) -> Error {
|
|
42
|
+
Error::new(
|
|
43
|
+
ruby.exception_arg_error(),
|
|
44
|
+
format!("Model '{}' not supported.", model),
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Returns the special tokens allowed when encoding (all of the encoding's special
|
|
49
|
+
// tokens, matching `encode_with_special_tokens`). The set is built once per encoding
|
|
50
|
+
// and cached: `CoreBPE::special_tokens()` allocates a fresh set on every call, which
|
|
51
|
+
// is noticeable for o200k_harmony (~1,100 special tokens).
|
|
52
|
+
fn allowed_special(tokenizer: Tokenizer, bpe: &'static CoreBPE) -> &'static HashSet<&'static str> {
|
|
53
|
+
static SETS: [OnceLock<HashSet<&'static str>>; 6] = [const { OnceLock::new() }; 6];
|
|
54
|
+
SETS[cache_slot(tokenizer)].get_or_init(|| bpe.special_tokens())
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Matches any of the encoding's special tokens, for `special_tokens: :raise`. Built once
|
|
58
|
+
// per encoding. Longest tokens come first so an overlapping match reports the full token.
|
|
59
|
+
// (The regex crate compiles a literal alternation like this to an Aho-Corasick search.)
|
|
60
|
+
fn special_token_regex(tokenizer: Tokenizer, bpe: &'static CoreBPE) -> &'static Regex {
|
|
61
|
+
static REGEXES: [OnceLock<Regex>; 6] = [const { OnceLock::new() }; 6];
|
|
62
|
+
REGEXES[cache_slot(tokenizer)].get_or_init(|| {
|
|
63
|
+
let mut tokens: Vec<&str> = allowed_special(tokenizer, bpe).iter().copied().collect();
|
|
64
|
+
tokens.sort_by(|a, b| b.len().cmp(&a.len()).then(a.cmp(b)));
|
|
65
|
+
let pattern = tokens
|
|
66
|
+
.iter()
|
|
67
|
+
.map(|token| regex::escape(token))
|
|
68
|
+
.collect::<Vec<_>>()
|
|
69
|
+
.join("|");
|
|
70
|
+
Regex::new(&pattern).expect("special token alternation is a valid regex")
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Per-encoding cache index. Gpt2 resolves to the same r50k_base singleton.
|
|
75
|
+
fn cache_slot(tokenizer: Tokenizer) -> usize {
|
|
76
|
+
match tokenizer {
|
|
77
|
+
Tokenizer::O200kHarmony => 0,
|
|
78
|
+
Tokenizer::O200kBase => 1,
|
|
79
|
+
Tokenizer::Cl100kBase => 2,
|
|
80
|
+
Tokenizer::P50kBase => 3,
|
|
81
|
+
Tokenizer::P50kEdit => 4,
|
|
82
|
+
Tokenizer::R50kBase | Tokenizer::Gpt2 => 5,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// A tokenizer for one encoding, exposed to Ruby as `JRRToken::Tokenizer`.
|
|
87
|
+
///
|
|
88
|
+
/// Instances only hold the encoding; the heavy `CoreBPE` is the process-wide singleton
|
|
89
|
+
/// from `bpe_for_tokenizer`, so instances are cheap. The Ruby side builds one frozen
|
|
90
|
+
/// instance per encoding and hands those out from `Tokenizer.for_model`.
|
|
91
|
+
#[magnus::wrap(class = "JRRToken::Tokenizer", free_immediately, size)]
|
|
92
|
+
struct RbTokenizer {
|
|
93
|
+
tokenizer: Tokenizer,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
impl RbTokenizer {
|
|
97
|
+
// Private constructor, `Tokenizer._build(encoding_name)`.
|
|
98
|
+
fn build(ruby: &Ruby, encoding: String) -> Result<Self, Error> {
|
|
99
|
+
let tokenizer = match encoding.as_str() {
|
|
100
|
+
"o200k_harmony" | "o200k_base" | "cl100k_base" | "p50k_base" | "p50k_edit"
|
|
101
|
+
| "r50k_base" => tokenizer_for(&encoding),
|
|
102
|
+
_ => None,
|
|
103
|
+
}
|
|
104
|
+
.ok_or_else(|| {
|
|
105
|
+
Error::new(
|
|
106
|
+
ruby.exception_arg_error(),
|
|
107
|
+
format!("Unknown encoding '{}'.", encoding),
|
|
108
|
+
)
|
|
109
|
+
})?;
|
|
110
|
+
Ok(Self { tokenizer })
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
fn bpe(&self, ruby: &Ruby) -> Result<&'static CoreBPE, Error> {
|
|
114
|
+
// `bpe_for_tokenizer` returns a process-wide `&'static CoreBPE` singleton, so the
|
|
115
|
+
// vocabulary is decoded and the regexes are compiled once per encoding, not on
|
|
116
|
+
// every call. It currently never returns `Err` (a failed build panics inside
|
|
117
|
+
// tiktoken-rs's lazy static); the `map_err` only guards against future changes.
|
|
118
|
+
bpe_for_tokenizer(self.tokenizer)
|
|
119
|
+
.map_err(|e| Error::new(ruby.exception_runtime_error(), e.to_string()))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
fn encoding(&self) -> &'static str {
|
|
123
|
+
encoding_name(self.tokenizer)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Encodes `text`. With `allow_special`, special-token strings (e.g. "<|endoftext|>")
|
|
127
|
+
// become their special token ids; otherwise they're encoded as ordinary text.
|
|
128
|
+
//
|
|
129
|
+
// Both paths use the fallible `CoreBPE::encode` (with an empty allowed set for plain
|
|
130
|
+
// text) rather than `encode_with_special_tokens` / `encode_ordinary`, which unwrap
|
|
131
|
+
// tokenizer regex failures and would panic (Ruby `fatal`) on pathological input.
|
|
132
|
+
fn encode_ranks(&self, ruby: &Ruby, text: &str, allow_special: bool) -> Result<Vec<u32>, Error> {
|
|
133
|
+
let bpe = self.bpe(ruby)?;
|
|
134
|
+
let none = HashSet::new();
|
|
135
|
+
let allowed = if allow_special {
|
|
136
|
+
allowed_special(self.tokenizer, bpe)
|
|
137
|
+
} else {
|
|
138
|
+
&none
|
|
139
|
+
};
|
|
140
|
+
bpe.encode(text, allowed)
|
|
141
|
+
.map(|(tokens, _)| tokens)
|
|
142
|
+
.map_err(|e| Error::new(ruby.exception_runtime_error(), e.to_string()))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// `Tokenizer#_count(text, allow_special)`
|
|
146
|
+
fn count(ruby: &Ruby, rb_self: &Self, text: String, allow_special: bool) -> Result<usize, Error> {
|
|
147
|
+
rb_self.encode_ranks(ruby, &text, allow_special).map(|tokens| tokens.len())
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// `Tokenizer#_encode(text, allow_special)`
|
|
151
|
+
fn encode(
|
|
152
|
+
ruby: &Ruby,
|
|
153
|
+
rb_self: &Self,
|
|
154
|
+
text: String,
|
|
155
|
+
allow_special: bool,
|
|
156
|
+
) -> Result<Vec<u32>, Error> {
|
|
157
|
+
rb_self.encode_ranks(ruby, &text, allow_special)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// `Tokenizer#_split(text, allow_special)`: the text of each token, 1:1 with `encode`.
|
|
161
|
+
// Bytes of a multi-byte character split across tokens (common for emoji and CJK) can't
|
|
162
|
+
// be shown on their own, so they become U+FFFD; use encode + decode_bytes for exact
|
|
163
|
+
// bytes.
|
|
164
|
+
fn split(
|
|
165
|
+
ruby: &Ruby,
|
|
166
|
+
rb_self: &Self,
|
|
167
|
+
text: String,
|
|
168
|
+
allow_special: bool,
|
|
169
|
+
) -> Result<Vec<String>, Error> {
|
|
170
|
+
let tokens = rb_self.encode_ranks(ruby, &text, allow_special)?;
|
|
171
|
+
tokens
|
|
172
|
+
.iter()
|
|
173
|
+
.map(|token| {
|
|
174
|
+
rb_self
|
|
175
|
+
.decode_to_bytes(ruby, std::slice::from_ref(token))
|
|
176
|
+
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
|
|
177
|
+
})
|
|
178
|
+
.collect()
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// `Tokenizer#_find_special(text)`: the first special-token string in `text`, or nil.
|
|
182
|
+
fn find_special(ruby: &Ruby, rb_self: &Self, text: String) -> Result<Option<String>, Error> {
|
|
183
|
+
let bpe = rb_self.bpe(ruby)?;
|
|
184
|
+
Ok(special_token_regex(rb_self.tokenizer, bpe)
|
|
185
|
+
.find(&text)
|
|
186
|
+
.map(|m| m.as_str().to_owned()))
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// `Tokenizer#_truncate(text, max_tokens, allow_special)`: `text` cut at a token
|
|
190
|
+
// boundary, i.e. the text of the first `max_tokens` tokens of its encoding (the
|
|
191
|
+
// `decode(encode(text)[..n])` idiom). This is not necessarily the longest prefix that
|
|
192
|
+
// fits: a slightly longer prefix can sometimes re-encode within budget, but finding it
|
|
193
|
+
// would need a character-level search (token count isn't monotonic in prefix length).
|
|
194
|
+
// Cost is one full encode of `text`, plus a re-encode of the result.
|
|
195
|
+
//
|
|
196
|
+
// Decoding the first `max_tokens` tokens yields a byte prefix of `text`; if the cut
|
|
197
|
+
// lands inside a multi-byte character, the partial character is dropped so the result
|
|
198
|
+
// is valid UTF-8. BPE boundaries can shift when a prefix is re-encoded, so the result
|
|
199
|
+
// is re-counted and shortened one token at a time until it fits; this guarantees
|
|
200
|
+
// `count(result) <= max_tokens`. It's almost always a single pass.
|
|
201
|
+
fn truncate(
|
|
202
|
+
ruby: &Ruby,
|
|
203
|
+
rb_self: &Self,
|
|
204
|
+
text: String,
|
|
205
|
+
max_tokens: usize,
|
|
206
|
+
allow_special: bool,
|
|
207
|
+
) -> Result<String, Error> {
|
|
208
|
+
let tokens = rb_self.encode_ranks(ruby, &text, allow_special)?;
|
|
209
|
+
if tokens.len() <= max_tokens {
|
|
210
|
+
return Ok(text);
|
|
211
|
+
}
|
|
212
|
+
let mut keep = max_tokens;
|
|
213
|
+
loop {
|
|
214
|
+
let bytes = rb_self.decode_to_bytes(ruby, &tokens[..keep])?;
|
|
215
|
+
let valid_len = match std::str::from_utf8(&bytes) {
|
|
216
|
+
Ok(_) => bytes.len(),
|
|
217
|
+
Err(e) => e.valid_up_to(),
|
|
218
|
+
};
|
|
219
|
+
// A prefix of the decoded token bytes is a prefix of `text` (tokens concatenate
|
|
220
|
+
// to the original bytes), so slicing `text` keeps the caller's exact characters.
|
|
221
|
+
let prefix = text.get(..valid_len).ok_or_else(|| {
|
|
222
|
+
Error::new(
|
|
223
|
+
ruby.exception_runtime_error(),
|
|
224
|
+
"truncate: decoded tokens are not a prefix of the input text",
|
|
225
|
+
)
|
|
226
|
+
})?;
|
|
227
|
+
if keep == 0 || rb_self.encode_ranks(ruby, prefix, allow_special)?.len() <= max_tokens {
|
|
228
|
+
return Ok(prefix.to_owned());
|
|
34
229
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
230
|
+
keep -= 1;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
fn decode_to_bytes(&self, ruby: &Ruby, tokens: &[u32]) -> Result<Vec<u8>, Error> {
|
|
235
|
+
let bpe = self.bpe(ruby)?;
|
|
236
|
+
bpe.decode_bytes(tokens).map_err(|e| {
|
|
237
|
+
Error::new(
|
|
238
|
+
ruby.exception_arg_error(),
|
|
239
|
+
format!("Invalid token {} for {}.", e.token, self.encoding()),
|
|
240
|
+
)
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// `Tokenizer#_decode(tokens)`. Bytes that aren't valid UTF-8 (a token slice that cuts
|
|
245
|
+
// a multi-byte character) become U+FFFD, matching Python tiktoken's default
|
|
246
|
+
// `errors="replace"`. Unknown token ids raise ArgumentError.
|
|
247
|
+
fn decode(ruby: &Ruby, rb_self: &Self, tokens: Vec<u32>) -> Result<String, Error> {
|
|
248
|
+
let bytes = rb_self.decode_to_bytes(ruby, &tokens)?;
|
|
249
|
+
Ok(String::from_utf8_lossy(&bytes).into_owned())
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// `Tokenizer#_decode_bytes(tokens)`: the exact bytes as a binary (ASCII-8BIT) String.
|
|
253
|
+
fn decode_bytes(ruby: &Ruby, rb_self: &Self, tokens: Vec<u32>) -> Result<RString, Error> {
|
|
254
|
+
let bytes = rb_self.decode_to_bytes(ruby, &tokens)?;
|
|
255
|
+
Ok(ruby.str_from_slice(&bytes))
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// `JRRToken.context_size(model)`: the model's context window in tokens, from tiktoken-rs's
|
|
260
|
+
// model table, or nil if the model isn't in it. Accepts `ft:` fine-tune names.
|
|
261
|
+
fn context_size(model: String) -> Option<usize> {
|
|
262
|
+
tiktoken_rs::model::get_context_size(&model)
|
|
38
263
|
}
|
|
39
264
|
|
|
40
|
-
//
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
265
|
+
// `Tokenizer._encoding_for(model)`: resolves a model or encoding name to the canonical
|
|
266
|
+
// encoding name, raising ArgumentError for unsupported models.
|
|
267
|
+
fn encoding_for(ruby: &Ruby, model: String) -> Result<&'static str, Error> {
|
|
268
|
+
tokenizer_for(&model)
|
|
269
|
+
.map(encoding_name)
|
|
270
|
+
.ok_or_else(|| unsupported_model(ruby, &model))
|
|
45
271
|
}
|
|
46
272
|
|
|
47
273
|
#[magnus::init]
|
|
48
|
-
fn init() -> Result<(), Error> {
|
|
49
|
-
let module = define_module("JRRToken")?;
|
|
50
|
-
module.
|
|
274
|
+
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
275
|
+
let module = ruby.define_module("JRRToken")?;
|
|
276
|
+
module.define_singleton_method("context_size", function!(context_size, 1))?;
|
|
277
|
+
let class = module.define_class("Tokenizer", ruby.class_object())?;
|
|
278
|
+
// Instances are only created through `_build` (and handed out by `for_model`).
|
|
279
|
+
class.undef_default_alloc_func();
|
|
280
|
+
class.define_singleton_method("_build", function!(RbTokenizer::build, 1))?;
|
|
281
|
+
class.define_singleton_method("_encoding_for", function!(encoding_for, 1))?;
|
|
282
|
+
class.define_private_method("_count", method!(RbTokenizer::count, 2))?;
|
|
283
|
+
class.define_private_method("_encode", method!(RbTokenizer::encode, 2))?;
|
|
284
|
+
class.define_private_method("_find_special", method!(RbTokenizer::find_special, 1))?;
|
|
285
|
+
class.define_private_method("_truncate", method!(RbTokenizer::truncate, 3))?;
|
|
286
|
+
class.define_private_method("_split", method!(RbTokenizer::split, 2))?;
|
|
287
|
+
class.define_private_method("_decode", method!(RbTokenizer::decode, 1))?;
|
|
288
|
+
class.define_private_method("_decode_bytes", method!(RbTokenizer::decode_bytes, 1))?;
|
|
51
289
|
Ok(())
|
|
52
290
|
}
|
data/j_r_r_token.gemspec
CHANGED
|
@@ -9,7 +9,7 @@ Gem::Specification.new do |spec|
|
|
|
9
9
|
spec.email = ["loganbbres@gmail.com"]
|
|
10
10
|
|
|
11
11
|
spec.summary = "Ruby wrapper for the tiktoken Rust library, providing fast tokenization for OpenAI models."
|
|
12
|
-
spec.description = "JRRToken is a Ruby gem that wraps the tiktoken Rust library, enabling fast and efficient tokenization for OpenAI models. It supports
|
|
12
|
+
spec.description = "JRRToken is a Ruby gem that wraps the tiktoken Rust library, enabling fast and efficient tokenization for OpenAI models. It supports the o200k_harmony, o200k_base, cl100k_base, p50k_base, p50k_edit, and r50k_base encodings."
|
|
13
13
|
spec.homepage = "https://github.com/LoganBresnahan/j_r_r_token"
|
|
14
14
|
spec.license = "MIT"
|
|
15
15
|
spec.required_ruby_version = ">= 3.0.0"
|
data/lib/j_r_r_token/version.rb
CHANGED