kute-engine 0.2.0__tar.gz → 0.3.0__tar.gz

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.
Files changed (50) hide show
  1. {kute_engine-0.2.0 → kute_engine-0.3.0}/Cargo.toml +12 -10
  2. {kute_engine-0.2.0 → kute_engine-0.3.0}/PKG-INFO +1 -1
  3. {kute_engine-0.2.0 → kute_engine-0.3.0}/bindings/python/Cargo.lock +9 -9
  4. {kute_engine-0.2.0 → kute_engine-0.3.0}/bindings/python/Cargo.toml +1 -1
  5. {kute_engine-0.2.0 → kute_engine-0.3.0}/bindings/python/src/lib.rs +1 -0
  6. {kute_engine-0.2.0 → kute_engine-0.3.0}/bindings/python/tests/test_kute.py +1 -1
  7. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute/src/lib.rs +110 -15
  8. kute_engine-0.3.0/crates/kute/tests/conformance.rs +66 -0
  9. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute/tests/mvp.rs +9 -3
  10. kute_engine-0.3.0/crates/kute/tests/open_world.rs +135 -0
  11. kute_engine-0.3.0/crates/kute/tests/streaming.rs +112 -0
  12. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-adapters/src/lib.rs +6 -6
  13. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-algorithms/src/lib.rs +4 -4
  14. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-algorithms/src/table.rs +1 -1
  15. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bench/src/lib.rs +47 -0
  16. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bpe/src/byte.rs +3 -2
  17. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bpe/src/lib.rs +3 -3
  18. kute_engine-0.3.0/crates/kute-bpe/src/sequence.rs +458 -0
  19. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-core/src/lib.rs +76 -6
  20. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/src/config.rs +24 -0
  21. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/src/input.rs +89 -4
  22. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/src/lib.rs +1 -1
  23. {kute_engine-0.2.0 → kute_engine-0.3.0}/pyproject.toml +1 -1
  24. kute_engine-0.2.0/crates/kute-bpe/src/sequence.rs +0 -258
  25. {kute_engine-0.2.0 → kute_engine-0.3.0}/README.md +0 -0
  26. {kute_engine-0.2.0 → kute_engine-0.3.0}/bindings/python/README.md +0 -0
  27. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute/Cargo.toml +0 -0
  28. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute/README.md +0 -0
  29. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-adapters/Cargo.toml +0 -0
  30. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-adapters/README.md +0 -0
  31. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-algorithms/Cargo.toml +0 -0
  32. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-algorithms/README.md +0 -0
  33. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bench/Cargo.toml +0 -0
  34. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bench/README.md +0 -0
  35. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bench/build.rs +0 -0
  36. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bench/src/data.rs +0 -0
  37. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bench/src/suite.rs +0 -0
  38. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bpe/Cargo.toml +0 -0
  39. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bpe/README.md +0 -0
  40. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-bpe/src/merge.rs +0 -0
  41. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-core/Cargo.toml +0 -0
  42. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-core/README.md +0 -0
  43. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/Cargo.toml +0 -0
  44. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/README.md +0 -0
  45. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/src/error.rs +0 -0
  46. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/src/id.rs +0 -0
  47. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-types/src/vocab.rs +0 -0
  48. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-vocab/Cargo.toml +0 -0
  49. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-vocab/README.md +0 -0
  50. {kute_engine-0.2.0 → kute_engine-0.3.0}/crates/kute-vocab/src/lib.rs +0 -0
@@ -6,7 +6,7 @@ members = ["crates/*", "plugins/hrm"]
6
6
  exclude = ["bindings/python", "backends/rustbpe"]
7
7
 
8
8
  [workspace.package]
9
- version = "0.2.0"
9
+ version = "0.3.0"
10
10
  edition = "2021"
11
11
  license = "MIT OR Apache-2.0"
12
12
  rust-version = "1.80"
@@ -17,15 +17,17 @@ keywords = ["tokenizer", "bpe", "tokenization", "vocabulary"]
17
17
  categories = ["text-processing", "encoding"]
18
18
 
19
19
  [workspace.dependencies]
20
- kute-types = { path = "crates/kute-types", version = "0.2.0" }
21
- kute-core = { path = "crates/kute-core", version = "0.2.0" }
22
- kute-vocab = { path = "crates/kute-vocab", version = "0.2.0" }
23
- kute-bpe = { path = "crates/kute-bpe", version = "0.2.0" }
24
- kute-algorithms = { path = "crates/kute-algorithms", version = "0.2.0" }
25
- kute-adapters = { path = "crates/kute-adapters", version = "0.2.0" }
26
- kute-bench = { path = "crates/kute-bench", version = "0.2.0" }
27
- kute-hrm = { path = "plugins/hrm", version = "0.2.0" }
28
- kute = { package = "kute-engine", path = "crates/kute", version = "0.2.0" }
20
+ kute-types = { path = "crates/kute-types", version = "0.3.0" }
21
+ kute-core = { path = "crates/kute-core", version = "0.3.0" }
22
+ kute-vocab = { path = "crates/kute-vocab", version = "0.3.0" }
23
+ kute-bpe = { path = "crates/kute-bpe", version = "0.3.0" }
24
+ kute-algorithms = { path = "crates/kute-algorithms", version = "0.3.0" }
25
+ kute-adapters = { path = "crates/kute-adapters", version = "0.3.0" }
26
+ kute-bench = { path = "crates/kute-bench", version = "0.3.0" }
27
+ kute-hrm = { path = "plugins/hrm", version = "0.3.0" }
28
+ kute-discover = { path = "crates/kute-discover", version = "0.3.0" }
29
+ kute-protocol = { path = "crates/kute-protocol", version = "0.3.0" }
30
+ kute = { package = "kute-engine", path = "crates/kute", version = "0.3.0" }
29
31
 
30
32
  serde = { version = "1", features = ["derive"] }
31
33
  serde_json = "1"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kute-engine
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Programming Language :: Python :: 3
@@ -183,7 +183,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
183
183
 
184
184
  [[package]]
185
185
  name = "kute-adapters"
186
- version = "0.2.0"
186
+ version = "0.3.0"
187
187
  dependencies = [
188
188
  "kute-core",
189
189
  "kute-types",
@@ -192,7 +192,7 @@ dependencies = [
192
192
 
193
193
  [[package]]
194
194
  name = "kute-algorithms"
195
- version = "0.2.0"
195
+ version = "0.3.0"
196
196
  dependencies = [
197
197
  "kute-core",
198
198
  "kute-types",
@@ -202,7 +202,7 @@ dependencies = [
202
202
 
203
203
  [[package]]
204
204
  name = "kute-bench"
205
- version = "0.2.0"
205
+ version = "0.3.0"
206
206
  dependencies = [
207
207
  "flate2",
208
208
  "kute-engine",
@@ -214,7 +214,7 @@ dependencies = [
214
214
 
215
215
  [[package]]
216
216
  name = "kute-bpe"
217
- version = "0.2.0"
217
+ version = "0.3.0"
218
218
  dependencies = [
219
219
  "fancy-regex",
220
220
  "kute-core",
@@ -227,7 +227,7 @@ dependencies = [
227
227
 
228
228
  [[package]]
229
229
  name = "kute-core"
230
- version = "0.2.0"
230
+ version = "0.3.0"
231
231
  dependencies = [
232
232
  "kute-types",
233
233
  "sha2",
@@ -235,7 +235,7 @@ dependencies = [
235
235
 
236
236
  [[package]]
237
237
  name = "kute-engine"
238
- version = "0.2.0"
238
+ version = "0.3.0"
239
239
  dependencies = [
240
240
  "kute-adapters",
241
241
  "kute-algorithms",
@@ -249,7 +249,7 @@ dependencies = [
249
249
 
250
250
  [[package]]
251
251
  name = "kute-python"
252
- version = "0.2.0"
252
+ version = "0.3.0"
253
253
  dependencies = [
254
254
  "kute-bench",
255
255
  "kute-engine",
@@ -260,7 +260,7 @@ dependencies = [
260
260
 
261
261
  [[package]]
262
262
  name = "kute-types"
263
- version = "0.2.0"
263
+ version = "0.3.0"
264
264
  dependencies = [
265
265
  "base64",
266
266
  "flate2",
@@ -273,7 +273,7 @@ dependencies = [
273
273
 
274
274
  [[package]]
275
275
  name = "kute-vocab"
276
- version = "0.2.0"
276
+ version = "0.3.0"
277
277
  dependencies = [
278
278
  "kute-types",
279
279
  "serde",
@@ -1,7 +1,7 @@
1
1
  [package]
2
2
  name = "kute-python"
3
3
  description = "Python bindings for the Kannaka Universal Tokenization Engine"
4
- version = "0.2.0"
4
+ version = "0.3.0"
5
5
  edition = "2021"
6
6
  license = "MIT OR Apache-2.0"
7
7
  rust-version = "1.80"
@@ -290,6 +290,7 @@ impl Engine {
290
290
  modality: v.manifest.modality,
291
291
  adapter: v.adapter.as_ref().map(|a| a.name.clone()),
292
292
  ids: tokens,
293
+ escapes: Vec::new(),
293
294
  };
294
295
  py.detach(|| self.inner.decode_raw(tokenizer.as_ref().as_ref(), &sequence)).map_err(err)
295
296
  }
@@ -28,7 +28,7 @@ def vocab(engine):
28
28
 
29
29
 
30
30
  def test_module_surface(engine):
31
- assert kute.__version__ == "0.2.0"
31
+ assert kute.__version__ == "0.3.0"
32
32
  assert kute.KVF_VERSION == "0.1"
33
33
  assert {"bpe", "bytes", "char", "dictionary", "sequence-bpe"} <= set(engine.algorithms())
34
34
  assert {"binary", "text", "json", "jsonl", "jsonl-events"} <= set(engine.adapters())
@@ -26,7 +26,7 @@ pub use kute_adapters as adapters;
26
26
  pub use kute_algorithms as algorithms;
27
27
  pub use kute_bpe as bpe;
28
28
  pub use kute_core::{
29
- check_sequence, AdapterCapabilities, CorpusSource, FnCorpus, ModalityAdapter, Registry, Representation,
29
+ check_sequence, decoded_units, AdapterCapabilities, CorpusSource, FnCorpus, ModalityAdapter, Registry, Representation,
30
30
  RepresentationBackend, Tokenizer, VecCorpus,
31
31
  };
32
32
  pub use kute_types::*;
@@ -64,9 +64,10 @@ impl Engine {
64
64
  /// An engine with every built-in algorithm and adapter registered.
65
65
  pub fn new() -> Self {
66
66
  let mut registry = Registry::new();
67
- kute_bpe::register(&mut registry);
68
- kute_algorithms::register(&mut registry);
69
- kute_adapters::register(&mut registry);
67
+ // The built-in names are distinct, so these cannot collide.
68
+ kute_bpe::register(&mut registry).expect("built-in algorithm names are unique");
69
+ kute_algorithms::register(&mut registry).expect("built-in algorithm names are unique");
70
+ kute_adapters::register(&mut registry).expect("built-in adapter names are unique");
70
71
  Self { registry }
71
72
  }
72
73
 
@@ -95,14 +96,29 @@ impl Engine {
95
96
  adapter_config: &AdapterConfig,
96
97
  documents: &[Vec<u8>],
97
98
  config: &TrainingConfig,
99
+ ) -> Result<Vocabulary> {
100
+ let mut next = documents.iter();
101
+ self.train_stream(algorithm, adapter, adapter_config, config, &mut || Ok(next.next().map(std::borrow::Cow::Borrowed)))
102
+ }
103
+
104
+ /// Train on documents that are produced one at a time. Only the
105
+ /// document being read is held, so a corpus larger than memory can be
106
+ /// trained on as long as each document fits.
107
+ pub fn train_stream<'a>(
108
+ &self,
109
+ algorithm: &str,
110
+ adapter: &str,
111
+ adapter_config: &AdapterConfig,
112
+ config: &TrainingConfig,
113
+ documents: &mut dyn FnMut() -> Result<Option<std::borrow::Cow<'a, Vec<u8>>>>,
98
114
  ) -> Result<Vocabulary> {
99
115
  let adapter_impl = self.registry.adapter(adapter)?;
100
116
  let mut tokenizer = self.registry.tokenizer(algorithm)?;
101
- let mut records = Vec::with_capacity(documents.len());
102
- for doc in documents {
103
- records.push(adapter_impl.ingest(doc, adapter_config)?);
104
- }
105
- let mut vocabulary = tokenizer.train(&mut VecCorpus::new(records), config)?;
117
+ let mut corpus = FnCorpus(|| match documents()? {
118
+ Some(doc) => adapter_impl.ingest(&doc, adapter_config).map(Some),
119
+ None => Ok(None),
120
+ });
121
+ let mut vocabulary = tokenizer.train(&mut corpus, config)?;
106
122
  vocabulary.adapter = Some(adapter_impl.spec(adapter_config));
107
123
  vocabulary.manifest.modality = adapter_impl.modality();
108
124
  vocabulary.seal()?;
@@ -123,16 +139,34 @@ impl Engine {
123
139
  paths: &[PathBuf],
124
140
  config: &TrainingConfig,
125
141
  ) -> Result<Vocabulary> {
126
- let mut documents = Vec::new();
142
+ let mut files = Vec::new();
127
143
  for path in paths {
128
- for file in collect_files(path)? {
129
- documents.push(std::fs::read(&file)?);
130
- }
144
+ files.extend(collect_files(path)?);
131
145
  }
132
- if documents.is_empty() {
146
+ if files.is_empty() {
133
147
  return Err(KuteError::InvalidInput("no input files found".into()));
134
148
  }
135
- self.train(algorithm, adapter, adapter_config, &documents, config)
149
+ if config.stream_bytes.is_some() && adapter == kute_adapters::JSON {
150
+ return Err(KuteError::InvalidConfig("the json adapter reads whole documents and cannot be streamed in pieces".into()));
151
+ }
152
+ // Files are read one at a time, or one piece at a time, so memory
153
+ // does not grow with the size of the corpus.
154
+ let line_cut = adapter != kute_adapters::BINARY;
155
+ let mut files = files.into_iter();
156
+ let mut open: Option<Pieces> = None;
157
+ self.train_stream(algorithm, adapter, adapter_config, config, &mut || loop {
158
+ if let Some(pieces) = open.as_mut() {
159
+ if let Some(piece) = pieces.next_piece()? {
160
+ return Ok(Some(std::borrow::Cow::Owned(piece)));
161
+ }
162
+ open = None;
163
+ }
164
+ let Some(file) = files.next() else { return Ok(None) };
165
+ match config.stream_bytes {
166
+ Some(size) => open = Some(Pieces::open(&file, size, line_cut)?),
167
+ None => return Ok(Some(std::borrow::Cow::Owned(std::fs::read(&file)?))),
168
+ }
169
+ })
136
170
  }
137
171
 
138
172
  /// A tokenizer with `vocabulary` installed.
@@ -160,6 +194,24 @@ impl Engine {
160
194
  tokenizer.encode(&adapter.ingest(raw, &config)?)
161
195
  }
162
196
 
197
+ /// Raw bytes to tokens under an explicit policy for unknown symbols.
198
+ pub fn encode_raw_open(&self, tokenizer: &dyn Tokenizer, raw: &[u8], policy: UnknownPolicy) -> Result<TokenSequence> {
199
+ let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
200
+ let (adapter, config) = self.adapter_of(vocabulary)?;
201
+ tokenizer.encode_open(&adapter.ingest(raw, &config)?, policy)
202
+ }
203
+
204
+ /// Like [`Engine::decode_raw`], but refuses before decoding when the
205
+ /// sequence would expand to more than `max_units` bytes or symbols.
206
+ pub fn decode_raw_bounded(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence, max_units: u64) -> Result<Vec<u8>> {
207
+ let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
208
+ let units = kute_core::decoded_units(vocabulary, tokens)?;
209
+ if units > max_units {
210
+ return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units; the budget is {max_units}")));
211
+ }
212
+ self.decode_raw(tokenizer, tokens)
213
+ }
214
+
163
215
  /// Tokens back to raw bytes, through the vocabulary's adapter.
164
216
  pub fn decode_raw(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence) -> Result<Vec<u8>> {
165
217
  let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
@@ -205,6 +257,49 @@ impl Engine {
205
257
  }
206
258
  }
207
259
 
260
+ /// A file read in pieces of about `size` bytes. With `line_cut`, a piece ends
261
+ /// after the last line feed within `size` bytes, or runs on to the next line
262
+ /// feed when a single line is longer than that, so no line is ever split.
263
+ struct Pieces {
264
+ reader: std::io::BufReader<std::fs::File>,
265
+ size: usize,
266
+ line_cut: bool,
267
+ carry: Vec<u8>,
268
+ done: bool,
269
+ }
270
+
271
+ impl Pieces {
272
+ fn open(path: &Path, size: usize, line_cut: bool) -> Result<Self> {
273
+ Ok(Self { reader: std::io::BufReader::new(std::fs::File::open(path)?), size, line_cut, carry: Vec::new(), done: false })
274
+ }
275
+
276
+ fn next_piece(&mut self) -> Result<Option<Vec<u8>>> {
277
+ use std::io::{BufRead, Read};
278
+ if self.done && self.carry.is_empty() {
279
+ return Ok(None);
280
+ }
281
+ let mut piece = std::mem::take(&mut self.carry);
282
+ if !self.done && piece.len() < self.size {
283
+ let want = (self.size - piece.len()) as u64;
284
+ if (&mut self.reader).take(want).read_to_end(&mut piece)? < want as usize {
285
+ self.done = true;
286
+ }
287
+ }
288
+ if self.line_cut && !self.done {
289
+ match piece.iter().rposition(|&b| b == b'\n') {
290
+ Some(at) => self.carry = piece.split_off(at + 1),
291
+ None => {
292
+ // One line longer than a piece: finish the line.
293
+ if self.reader.read_until(b'\n', &mut piece)? == 0 || piece.last() != Some(&b'\n') {
294
+ self.done = true;
295
+ }
296
+ }
297
+ }
298
+ }
299
+ Ok(if piece.is_empty() { None } else { Some(piece) })
300
+ }
301
+ }
302
+
208
303
  /// Files under `path`, recursively, in sorted order. A file path is returned
209
304
  /// as is. Hidden entries (leading dot) inside directories are skipped.
210
305
  pub fn collect_files(path: &Path) -> Result<Vec<PathBuf>> {
@@ -0,0 +1,66 @@
1
+ //! The files in `specifications/kvf/vectors` are fixed. Every build must
2
+ //! read them, agree with their recorded digests, and decode the sequences to
3
+ //! the recorded bytes. The `v0.2.0` directory was written by the released
4
+ //! v0.2.0 binary, so this is also the backward-compatibility check.
5
+ //! `conformance/kvf_digest.py` checks the same digests without any KUTE code.
6
+
7
+ use kute::{Engine, TokenSequence};
8
+ use std::path::{Path, PathBuf};
9
+
10
+ fn vectors() -> PathBuf {
11
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../specifications/kvf/vectors")
12
+ }
13
+
14
+ fn files(dir: &Path, extension: &str) -> Vec<PathBuf> {
15
+ let mut found: Vec<PathBuf> = std::fs::read_dir(dir)
16
+ .unwrap()
17
+ .map(|e| e.unwrap().path())
18
+ .filter(|p| p.extension().is_some_and(|e| e == extension))
19
+ .collect();
20
+ found.sort();
21
+ found
22
+ }
23
+
24
+ #[test]
25
+ fn vocabularies_load_verify_and_keep_their_digests() {
26
+ let engine = Engine::new();
27
+ let mut seen = 0;
28
+ for dir in [vectors(), vectors().join("v0.2.0")] {
29
+ for path in files(&dir, "kvf") {
30
+ let vocabulary = kute::vocab::load(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
31
+ let recorded = vocabulary.integrity.as_ref().expect("vectors carry a digest").digest.clone();
32
+ assert_eq!(vocabulary.compute_digest().unwrap(), recorded, "{}", path.display());
33
+ let report = engine.verify(&vocabulary).unwrap();
34
+ assert!(report.ok(), "{}: {:?}", path.display(), report.failures);
35
+ // Writing the vocabulary again must not change its identity.
36
+ let rewritten = kute::vocab::from_slice(&kute::vocab::to_vec(&vocabulary).unwrap()).unwrap();
37
+ assert_eq!(rewritten.digest().unwrap(), recorded);
38
+ seen += 1;
39
+ }
40
+ }
41
+ assert_eq!(seen, 6);
42
+ }
43
+
44
+ #[test]
45
+ fn sequences_decode_to_the_recorded_bytes() {
46
+ let engine = Engine::new();
47
+ let mut seen = 0;
48
+ for dir in [vectors(), vectors().join("v0.2.0")] {
49
+ let vocabularies: Vec<_> = files(&dir, "kvf").iter().map(|p| kute::vocab::load(p).unwrap()).collect();
50
+ for path in files(&dir, "kute") {
51
+ let sequence = TokenSequence::from_bytes(&std::fs::read(&path).unwrap()).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
52
+ let vocabulary = vocabularies
53
+ .iter()
54
+ .find(|v| v.digest().unwrap() == sequence.vocabulary_digest)
55
+ .unwrap_or_else(|| panic!("{}: no vector vocabulary has its digest", path.display()));
56
+ let tokenizer = engine.tokenizer(vocabulary.clone()).unwrap();
57
+ let decoded = engine.decode_raw(tokenizer.as_ref(), &sequence).unwrap();
58
+ // `text-z.kute` and `text.kute` share `text.expected`.
59
+ let stem = path.file_stem().unwrap().to_string_lossy().trim_end_matches("-z").to_string();
60
+ let expected = std::fs::read(dir.join(format!("{stem}.expected"))).unwrap();
61
+ assert_eq!(decoded, expected, "{}", path.display());
62
+ seen += 1;
63
+ }
64
+ }
65
+ assert_eq!(seen, 7);
66
+ }
@@ -496,7 +496,11 @@ fn third_party_algorithm_registers_without_core_changes() {
496
496
  }
497
497
 
498
498
  let mut engine = Engine::new();
499
- engine.registry_mut().register_algorithm("reverse-bytes", || Box::new(Reverse::default()));
499
+ engine.registry_mut().register_algorithm("reverse-bytes", || Box::new(Reverse::default())).unwrap();
500
+ // A name can be taken once; replacing is a separate, explicit call.
501
+ assert!(engine.registry_mut().register_algorithm("reverse-bytes", || Box::new(Reverse::default())).is_err());
502
+ assert!(engine.registry_mut().register_algorithm("bpe", || Box::new(Reverse::default())).is_err());
503
+ engine.registry_mut().replace_algorithm("reverse-bytes", || Box::new(Reverse::default()));
500
504
  assert!(engine.registry().algorithm_names().contains(&"reverse-bytes".to_string()));
501
505
  let mut tokenizer = engine.registry().tokenizer("reverse-bytes").unwrap();
502
506
  tokenizer.train(&mut kute::VecCorpus::new(vec![]), &config("thirdparty:reverse", 256)).unwrap();
@@ -524,9 +528,11 @@ fn hrm_adapter_contract() {
524
528
  // Repeatable.
525
529
  assert_eq!(a, vector(&vocab, 300));
526
530
  // Unit energy; distinct tokens are close to orthogonal.
527
- let (norm, _) = inner_product(&a, &a);
531
+ let (norm, _) = inner_product(&a, &a).unwrap();
528
532
  assert!((norm - 1.0).abs() < 1e-4, "norm {norm}");
529
- let (re, im) = inner_product(&a, &vector(&vocab, 301));
533
+ let (re, im) = inner_product(&a, &vector(&vocab, 301)).unwrap();
534
+ // Vectors from mappings of different dimensions have no inner product.
535
+ assert!(inner_product(&a, &a[..255]).is_err());
530
536
  assert!((re * re + im * im).sqrt() < 0.3);
531
537
  // Content-addressed: the same payload maps to the same vector in another
532
538
  // vocabulary, whatever id it has there.
@@ -0,0 +1,135 @@
1
+ //! Development directive v0.2, D03 and D05: a frozen vocabulary meets
2
+ //! symbols it has never seen, sequences from untrusted sources are bounded
3
+ //! before decoding, and private corpora stay out of published vocabularies.
4
+
5
+ use kute::{AdapterConfig, Engine, KuteError, Payload, TokenSequence, TrainingConfig, UnknownPolicy, VocabularyId};
6
+
7
+ fn events(names: &[&str]) -> Vec<u8> {
8
+ names.iter().map(|n| format!("{{\"tag\":\"{n}\"}}\n")).collect::<String>().into_bytes()
9
+ }
10
+
11
+ fn trained(engine: &Engine, embed: bool) -> kute::Vocabulary {
12
+ let mut log = Vec::new();
13
+ for _ in 0..30 {
14
+ log.extend(events(&["MOTOR_START", "CURRENT_HIGH", "MOTOR_TRIP", "OPERATOR_ACK"]));
15
+ }
16
+ let mut config = TrainingConfig::new(VocabularyId::parse("test:open-world:events").unwrap(), 16);
17
+ config.embed_test_vectors = embed;
18
+ engine.train("sequence-bpe", "jsonl-events", &AdapterConfig::default().with("field", "tag"), &[log], &config).unwrap()
19
+ }
20
+
21
+ /// Gate: "Frozen vocabulary encodes previously unseen symbols reversibly
22
+ /// with escape mode; strict mode rejects them."
23
+ #[test]
24
+ fn escape_round_trips_unseen_symbols_and_strict_rejects_them() {
25
+ let engine = Engine::new();
26
+ let vocabulary = trained(&engine, true);
27
+ let digest = vocabulary.digest().unwrap();
28
+ let table = vocabulary.len() as u32;
29
+ let tokenizer = engine.tokenizer(vocabulary).unwrap();
30
+ let names = ["MOTOR_START", "CURRENT_HIGH", "VALVE_7_OPEN", "MOTOR_TRIP", "OPERATOR_ACK", "VALVE_7_OPEN", "naïve ✓", "MOTOR_START", "CURRENT_HIGH", "MOTOR_TRIP"];
31
+ let raw = events(&names);
32
+
33
+ let strict = engine.encode_raw_open(tokenizer.as_ref(), &raw, UnknownPolicy::Strict);
34
+ assert!(matches!(strict, Err(KuteError::UnknownSymbol(s)) if s == "VALVE_7_OPEN"));
35
+ assert!(matches!(engine.encode_raw(tokenizer.as_ref(), &raw), Err(KuteError::UnknownSymbol(_))));
36
+
37
+ let open = engine.encode_raw_open(tokenizer.as_ref(), &raw, UnknownPolicy::Escape).unwrap();
38
+ // Each distinct unknown symbol is stored once; the vocabulary is untouched.
39
+ assert_eq!(open.escapes, ["VALVE_7_OPEN", "naïve ✓"]);
40
+ assert_eq!(open.vocabulary_digest, digest);
41
+ assert_eq!(tokenizer.vocabulary().unwrap().len() as u32, table);
42
+ assert_eq!(open.ids.iter().filter(|&&id| id >= table).count(), 3);
43
+ // Known runs on both sides of an escape are still merged.
44
+ assert!(open.ids.len() < names.len());
45
+
46
+ let Payload::Symbols(decoded) = tokenizer.decode(&open).unwrap().payload else { panic!("expected symbols") };
47
+ assert_eq!(decoded, names);
48
+ // The escape table survives both container formats.
49
+ for bytes in [open.to_bytes().unwrap(), open.to_bytes_compressed().unwrap()] {
50
+ let back = TokenSequence::from_bytes(&bytes).unwrap();
51
+ assert_eq!(back, open);
52
+ let Payload::Symbols(again) = tokenizer.decode(&back).unwrap().payload else { panic!("expected symbols") };
53
+ assert_eq!(again, names);
54
+ }
55
+
56
+ // With nothing unknown, escape mode gives exactly the strict encoding.
57
+ let known = events(&["MOTOR_START", "CURRENT_HIGH", "MOTOR_TRIP"]);
58
+ let a = engine.encode_raw(tokenizer.as_ref(), &known).unwrap();
59
+ let b = engine.encode_raw_open(tokenizer.as_ref(), &known, UnknownPolicy::Escape).unwrap();
60
+ assert_eq!(a, b);
61
+
62
+ // An id past the escape table is an error, not a guess.
63
+ let mut forged = open.clone();
64
+ forged.ids.push(table + 2);
65
+ assert!(matches!(tokenizer.decode(&forged), Err(KuteError::UnknownToken(_))));
66
+ }
67
+
68
+ /// Byte-level algorithms never meet an unknown symbol, so both policies
69
+ /// agree. Table algorithms without escape support say so.
70
+ #[test]
71
+ fn policies_on_other_algorithms() {
72
+ let engine = Engine::new();
73
+ let config = TrainingConfig::new(VocabularyId::parse("test:open-world:text").unwrap(), 300);
74
+ let text = b"the quick brown fox jumps over the lazy dog. ".repeat(40);
75
+ let bpe = engine.train("bpe", "text", &AdapterConfig::default(), &[text], &config).unwrap();
76
+ let tokenizer = engine.tokenizer(bpe).unwrap();
77
+ let unseen = "zażółć gęślą jaźń \u{1F980}".as_bytes();
78
+ let strict = engine.encode_raw(tokenizer.as_ref(), unseen).unwrap();
79
+ let open = engine.encode_raw_open(tokenizer.as_ref(), unseen, UnknownPolicy::Escape).unwrap();
80
+ assert_eq!(strict, open);
81
+ assert!(open.escapes.is_empty());
82
+ assert_eq!(engine.decode_raw(tokenizer.as_ref(), &open).unwrap(), unseen);
83
+
84
+ let mut config = TrainingConfig::new(VocabularyId::parse("test:open-world:dictionary").unwrap(), 8);
85
+ config.dictionary = vec!["OPEN".into(), "CLOSE".into()];
86
+ let adapter = AdapterConfig::default().with("field", "tag");
87
+ let dictionary = engine.train("dictionary", "jsonl-events", &adapter, &[events(&["OPEN", "CLOSE"])], &config).unwrap();
88
+ let tokenizer = engine.tokenizer(dictionary).unwrap();
89
+ let raw = events(&["OPEN", "JAMMED"]);
90
+ assert!(matches!(engine.encode_raw_open(tokenizer.as_ref(), &raw, UnknownPolicy::Strict), Err(KuteError::UnknownSymbol(_))));
91
+ assert!(matches!(engine.encode_raw_open(tokenizer.as_ref(), &raw, UnknownPolicy::Escape), Err(KuteError::Unsupported(_))));
92
+ }
93
+
94
+ /// A short sequence can stand for a very large output. The budget check
95
+ /// runs on the token table, before any output is built.
96
+ #[test]
97
+ fn decode_budget_is_checked_before_decoding() {
98
+ let engine = Engine::new();
99
+ let config = TrainingConfig::new(VocabularyId::parse("test:open-world:budget").unwrap(), 400);
100
+ let text = b"abcdefgh".repeat(4000);
101
+ let vocabulary = engine.train("bpe", "binary", &AdapterConfig::default(), &[text], &config).unwrap();
102
+ let longest = vocabulary.tokens.iter().max_by_key(|t| t.payload.len()).unwrap();
103
+ assert!(longest.payload.len() >= 64);
104
+ let tokenizer = engine.tokenizer(vocabulary.clone()).unwrap();
105
+ let mut bomb = engine.encode_raw(tokenizer.as_ref(), b"a").unwrap();
106
+ bomb.ids = vec![longest.id; 10_000];
107
+ let units = kute::decoded_units(&vocabulary, &bomb).unwrap();
108
+ assert_eq!(units, 10_000 * longest.payload.len() as u64);
109
+ assert!(matches!(engine.decode_raw_bounded(tokenizer.as_ref(), &bomb, units - 1), Err(KuteError::LimitExceeded(_))));
110
+ assert_eq!(engine.decode_raw_bounded(tokenizer.as_ref(), &bomb, units).unwrap().len() as u64, units);
111
+ }
112
+
113
+ /// Embedded test vectors are verbatim excerpts of the corpus. Turning them
114
+ /// off must leave no corpus text in the published file.
115
+ #[test]
116
+ fn private_corpora_are_not_embedded_when_asked() {
117
+ let engine = Engine::new();
118
+ let with = String::from_utf8(kute::vocab::to_vec(&trained(&engine, true)).unwrap()).unwrap();
119
+ let without_vocab = trained(&engine, false);
120
+ assert!(without_vocab.test_vectors.is_empty());
121
+ assert!(engine.verify(&without_vocab).unwrap().ok());
122
+ let without = String::from_utf8(kute::vocab::to_vec(&without_vocab).unwrap()).unwrap();
123
+ assert!(with.contains("\"ids\""));
124
+ assert!(!without.contains("\"ids\""));
125
+
126
+ let secret = b"account 4417 belongs to the confidential ledger. ".repeat(50);
127
+ let mut config = TrainingConfig::new(VocabularyId::parse("test:open-world:private").unwrap(), 280);
128
+ config.embed_test_vectors = false;
129
+ let vocabulary = engine.train("bpe", "text", &AdapterConfig::default(), &[secret], &config).unwrap();
130
+ assert!(vocabulary.test_vectors.is_empty());
131
+ // Learned tokens still reveal frequent fragments; that is inherent to a
132
+ // vocabulary and is documented. No whole sentence is stored.
133
+ let longest = vocabulary.tokens.iter().map(|t| t.payload.len()).max().unwrap();
134
+ assert!(longest < 49, "a token holds the whole secret sentence");
135
+ }