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
//! Byte Pair Encoding (BPE) tokenizer (GH-128).
//!
//! Provides BPE tokenization for LLMs and speech models:
//! - `HuggingFace` tokenizer loading (tokenizer.json)
//! - Encode text to token IDs
//! - Decode token IDs to text
//! - Special token handling
//!
//! # Architecture
//!
//! ```text
//! Text → Pre-tokenize → BPE Merge → Token IDs
//! ↓
//! vocab.json + merges.txt
//! ```
//!
//! # Merge Algorithm (GH-378)
//!
//! Uses a priority-queue + doubly-linked symbol list, ported from HuggingFace
//! `tokenizers` `word.rs`. Each word is converted to an array of `BpeSymbol` nodes
//! linked by prev/next indices. All valid initial merges are pushed into a
//! `BinaryHeap` keyed by merge rank. The main loop pops the lowest-rank merge,
//! applies it in O(1) via pointer updates, and re-enqueues any new pairs created
//! by the merge. Stale entries (where a symbol was already consumed) are skipped
//! via a length-zero sentinel check.
//!
//! Complexity: O(n + m log m) where n = initial symbols, m = merges applied.
//! The previous greedy-rescan algorithm was O(n * m) due to full-word rescans.
//!
//! Performance: 2.06x speedup (145us → 70us) on Qwen3 151K vocab merge-sort
//! payload. Beats HuggingFace tokenizers v0.22 reference (104us). ~3.76M tokens/sec.
//!
//! # Loading Performance (GH-378)
//!
//! Tokenizer.json loading uses pre-sized HashMaps, owned-string moves, and a
//! fast merge path that skips redundant `merge_ranks` population. Eliminates
//! ~600K String/Vec allocations on Qwen2-scale (151K) vocabularies.
//!
//! - `from_file`: 142ms (1.43x faster than HF v0.22's 204ms)
//! - `from_json`: 136ms (in-memory, no disk I/O)
//!
//! All tokenizer formats (Qwen2, Whisper, GPT-2, LLaMA) share the same
//! optimized `load_from_json` path via `config_from_vocab_size` dispatch.
//!
//! # Example
//!
//! ```rust
//! use aprender::text::bpe::{BpeTokenizer, BpeConfig};
//!
//! // Create tokenizer with empty vocabulary (default)
//! let config = BpeConfig::default();
//! let tokenizer = BpeTokenizer::new(config);
//!
//! // Empty vocab returns empty tokens - real usage requires loading vocab
//! let tokens = tokenizer.encode("Hello");
//! assert!(tokens.is_empty()); // No vocab loaded yet
//!
//! // For real tokenization, load from HuggingFace tokenizer.json:
//! // let tokenizer = BpeTokenizer::from_huggingface("path/to/tokenizer.json")?;
//! // let tokens = tokenizer.encode("Hello world");
//! // assert!(!tokens.is_empty());
//!
//! // Or load from a JSON string directly:
//! // let tokenizer = BpeTokenizer::from_huggingface_json(&json_string)?;
//! ```
//!
//! # References
//!
//! - Sennrich, R., et al. (2016). Neural Machine Translation of Rare Words with Subword Units.
//! - Radford, A., et al. (2019). Language Models are Unsupervised Multitask Learners (GPT-2).
//! - HuggingFace tokenizers `word.rs` — priority-queue merge reference implementation.
//!
//! # PMAT Compliance
//!
//! - Zero `unwrap()` calls
//! - All public APIs return `Result<T, E>` where fallible
use HashMap;
// ============================================================================
// Configuration
// ============================================================================
/// BPE tokenizer configuration.
// ============================================================================
// BPE Merge Rule
// ============================================================================
/// A BPE merge rule (pair → merged token).
// ============================================================================
// BPE Tokenizer
// ============================================================================
/// Byte Pair Encoding tokenizer.
///
/// Implements subword tokenization using BPE algorithm.
pub use *;
pub use *;
// BPE contract falsification (FALSIFY-BPE-001..009)
// Refs: Sennrich et al. (2016), PMAT-347