Phase-Technologies commited on
Commit
6684ccb
Β·
verified Β·
1 Parent(s): 5288f34

Add tokenizer component: crayon_wrapper.py

Browse files
Files changed (1) hide show
  1. tokenizer/crayon_wrapper.py +653 -0
tokenizer/crayon_wrapper.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CRAYON Tokenizer Wrapper
3
+ Wraps CrayonVocab into a full-featured tokenizer compatible with FORGE training.
4
+ Exploits CRAYON's 24M+ tok/sec CPU throughput via parallel multi-process pipeline.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import gc
11
+ import math
12
+ import time
13
+ import logging
14
+ import threading
15
+ import multiprocessing as mp
16
+ from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
17
+ from typing import List, Union, Optional, Dict, Any, Iterator, Tuple
18
+ from pathlib import Path
19
+ import queue
20
+
21
+ # Fix Windows console UTF-8 printing issues for external packages (e.g., Crayon print statements with emoji)
22
+ import sys
23
+ import io
24
+ if sys.platform.startswith("win"):
25
+ try:
26
+ sys.stdout.reconfigure(encoding='utf-8')
27
+ sys.stderr.reconfigure(encoding='utf-8')
28
+ except AttributeError:
29
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
30
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
31
+
32
+ import torch
33
+ import numpy as np
34
+
35
+ from crayon import CrayonVocab
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ # ─────────────────────────────────────────────────────────────────────────────
41
+ # THREAD-LOCAL TOKENIZER POOL
42
+ # Each worker thread gets its own CrayonVocab instance to avoid any GIL
43
+ # contention on the underlying C++ DAT engine.
44
+ # ─────────────────────────────────────────────────────────────────────────────
45
+
46
+ _thread_local = threading.local()
47
+ _init_lock = threading.Lock()
48
+
49
+ def _get_thread_local_tokenizer(profile: str = "standard") -> CrayonVocab:
50
+ """Return a thread-local CrayonVocab instance, creating one if needed."""
51
+ if not hasattr(_thread_local, "tokenizer"):
52
+ with _init_lock:
53
+ # CPU is 20Γ— faster than CUDA for CRAYON (23.84M vs 1.22M tok/s)
54
+ _thread_local.tokenizer = CrayonVocab(device="cpu")
55
+ _thread_local.tokenizer.load_profile(profile)
56
+ logger.debug(f"Thread {threading.current_thread().name}: "
57
+ f"CrayonVocab loaded with profile='{profile}'")
58
+ return _thread_local.tokenizer
59
+
60
+
61
+ # ─────────────────────────────────────────────────────────────────────────────
62
+ # SPECIAL TOKEN REGISTRY
63
+ # We manage special tokens separately since CRAYON's vocabulary may not have
64
+ # them natively β€” we append them to the vocab ID space.
65
+ # ─────────────────────────────────────────────────────────────────────────────
66
+
67
+ SPECIAL_TOKENS = {
68
+ "<|pad|>": 0,
69
+ "<|bos|>": 1,
70
+ "<|eos|>": 2,
71
+ "<|sep|>": 3,
72
+ "<|sys|>": 4,
73
+ "<|/sys|>": 5,
74
+ "<|usr|>": 6,
75
+ "<|/usr|>": 7,
76
+ "<|asst|>": 8,
77
+ "<|/asst|>": 9,
78
+ "<|tool|>": 10,
79
+ "<|tool_resp|>": 11,
80
+ "<|unk|>": 12,
81
+ }
82
+
83
+ # For the standard profile: actual vocab starts at ID 13
84
+ # Effective vocab_size = 206,373 (crayon) + 13 (specials) = 206,386 β†’ pad to 206,464
85
+ SPECIAL_TOKEN_OFFSET = len(SPECIAL_TOKENS) # 13
86
+ CRAYON_STANDARD_VOCAB = 206_373
87
+ CRAYON_LITE_VOCAB = 50_000
88
+
89
+ # Reverse mapping for decode
90
+ ID_TO_SPECIAL = {v: k for k, v in SPECIAL_TOKENS.items()}
91
+
92
+
93
+ class ForgeTokenizer:
94
+ """
95
+ Production-grade FORGE tokenizer built on top of CRAYON.
96
+
97
+ Features:
98
+ - Thread-safe, zero-copy multi-threaded tokenization
99
+ - Batched encoding with automatic chunking for throughput
100
+ - Full special token support with chat template
101
+ - Streaming decode
102
+ - Vocabulary size adapter between CRAYON profile and model vocab
103
+ - Offline preprocessing at 24M+ tokens/sec on CPU
104
+
105
+ Usage:
106
+ tokenizer = ForgeTokenizer(profile="standard")
107
+ ids = tokenizer.encode("Hello world")
108
+ text = tokenizer.decode(ids)
109
+
110
+ # Chat format
111
+ ids = tokenizer.encode_chat([
112
+ {"role": "system", "content": "You are helpful."},
113
+ {"role": "user", "content": "What is 2+2?"},
114
+ ])
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ profile: str = "standard",
120
+ device: str = "cpu",
121
+ n_workers: int = None,
122
+ max_length: Optional[int] = None,
123
+ add_bos: bool = True,
124
+ add_eos: bool = True,
125
+ ):
126
+ self.profile = profile
127
+ self.device_str = device # "cpu" recommended for CRAYON throughput
128
+ self.n_workers = n_workers or max(1, mp.cpu_count() - 2)
129
+ self.max_length = max_length
130
+ self.add_bos = add_bos
131
+ self.add_eos = add_eos
132
+
133
+ # Primary tokenizer (used for single-threaded ops)
134
+ self._tokenizer = CrayonVocab(device=device)
135
+ self._tokenizer.load_profile(profile)
136
+
137
+ # Special tokens
138
+ self.special_tokens = SPECIAL_TOKENS.copy()
139
+ self.id_to_special = ID_TO_SPECIAL.copy()
140
+ self.special_token_offset = SPECIAL_TOKEN_OFFSET
141
+
142
+ # Derive vocab size
143
+ if profile == "standard":
144
+ self._crayon_vocab_size = CRAYON_STANDARD_VOCAB
145
+ else:
146
+ self._crayon_vocab_size = CRAYON_LITE_VOCAB
147
+
148
+ # Effective vocab size = specials + crayon tokens
149
+ # Padded to nearest multiple of 128 for efficient matmuls
150
+ raw_vocab = self._crayon_vocab_size + SPECIAL_TOKEN_OFFSET
151
+ self.vocab_size = math.ceil(raw_vocab / 128) * 128
152
+
153
+ # Lock for thread safety on single-instance operations
154
+ self._lock = threading.Lock()
155
+
156
+ # Thread pool for parallel tokenization
157
+ self._thread_pool = ThreadPoolExecutor(
158
+ max_workers=self.n_workers,
159
+ thread_name_prefix="forge_tok"
160
+ )
161
+
162
+ logger.info(
163
+ f"ForgeTokenizer initialized: profile={profile}, "
164
+ f"vocab_size={self.vocab_size} (crayon={self._crayon_vocab_size} "
165
+ f"+ specials={SPECIAL_TOKEN_OFFSET} + padding={self.vocab_size - raw_vocab}), "
166
+ f"n_workers={self.n_workers}, throughput ~24M tok/s (CPU)"
167
+ )
168
+
169
+ # ─────────────────────────────────────────────────────────────────────────
170
+ # TOKEN ID CONVERSION HELPERS
171
+ # CRAYON returns IDs in [0, crayon_vocab_size).
172
+ # We shift them by SPECIAL_TOKEN_OFFSET to [SPECIAL_TOKEN_OFFSET, vocab_size).
173
+ # Special tokens occupy IDs [0, SPECIAL_TOKEN_OFFSET).
174
+ # ─────────────────────────────────────────────────────────────────────────
175
+
176
+ def _shift_crayon_ids(self, ids: List[int]) -> List[int]:
177
+ """Shift CRAYON token IDs to make room for special tokens at the front."""
178
+ return [i + self.special_token_offset for i in ids]
179
+
180
+ def _unshift_crayon_ids(self, ids: List[int]) -> List[int]:
181
+ """Inverse of _shift_crayon_ids for decode path."""
182
+ out = []
183
+ for i in ids:
184
+ if i < self.special_token_offset:
185
+ out.append(None) # special token β€” handled separately
186
+ else:
187
+ out.append(i - self.special_token_offset)
188
+ return out
189
+
190
+ # ─────────────────────────────────────────────────────────────────────────
191
+ # CORE ENCODE / DECODE
192
+ # ─────────────────────────────────────────────────────────────────────────
193
+
194
+ def encode(
195
+ self,
196
+ text: str,
197
+ add_bos: Optional[bool] = None,
198
+ add_eos: Optional[bool] = None,
199
+ truncate: bool = True,
200
+ ) -> List[int]:
201
+ """
202
+ Encode a single string to token IDs.
203
+ Thread-safe via CRAYON's internal lock or thread-local tokenizers.
204
+ """
205
+ add_bos_ = self.add_bos if add_bos is None else add_bos
206
+ add_eos_ = self.add_eos if add_eos is None else add_eos
207
+
208
+ # CRAYON tokenization
209
+ with self._lock:
210
+ raw_ids = self._tokenizer.tokenize(text)
211
+
212
+ # Handle both list and tensor returns from CRAYON
213
+ if isinstance(raw_ids, torch.Tensor):
214
+ raw_ids = raw_ids.tolist()
215
+
216
+ ids = self._shift_crayon_ids(raw_ids)
217
+
218
+ # Prepend/append special tokens
219
+ if add_bos_:
220
+ ids = [self.special_tokens["<|bos|>"]] + ids
221
+ if add_eos_:
222
+ ids = ids + [self.special_tokens["<|eos|>"]]
223
+
224
+ # Truncate if needed
225
+ if truncate and self.max_length is not None:
226
+ ids = ids[:self.max_length]
227
+
228
+ return ids
229
+
230
+ def encode_batch(
231
+ self,
232
+ texts: List[str],
233
+ add_bos: Optional[bool] = None,
234
+ add_eos: Optional[bool] = None,
235
+ pad: bool = True,
236
+ pad_to_multiple_of: int = 8,
237
+ return_tensors: str = "pt",
238
+ ) -> Dict[str, torch.Tensor]:
239
+ """
240
+ Encode a batch of texts in parallel using thread pool.
241
+ Leverages CRAYON's 24M tok/s CPU throughput across all threads.
242
+
243
+ Returns dict with 'input_ids' and 'attention_mask'.
244
+ """
245
+ add_bos_ = self.add_bos if add_bos is None else add_bos
246
+ add_eos_ = self.add_eos if add_eos is None else add_eos
247
+
248
+ # ── Parallel tokenization ──────────────────────────────────────────
249
+ def _tokenize_one(text: str) -> List[int]:
250
+ tok = _get_thread_local_tokenizer(self.profile)
251
+ raw = tok.tokenize(text)
252
+ if isinstance(raw, torch.Tensor):
253
+ raw = raw.tolist()
254
+ ids = self._shift_crayon_ids(raw)
255
+ if add_bos_:
256
+ ids = [self.special_tokens["<|bos|>"]] + ids
257
+ if add_eos_:
258
+ ids = ids + [self.special_tokens["<|eos|>"]]
259
+ if self.max_length is not None:
260
+ ids = ids[:self.max_length]
261
+ return ids
262
+
263
+ if self.n_workers <= 1:
264
+ # Run sequentially on the main thread using the primary tokenizer instance
265
+ # to completely avoid any C++ multi-threading deadlocks.
266
+ all_ids = []
267
+ for t in texts:
268
+ raw = self._tokenizer.tokenize(t)
269
+ if isinstance(raw, torch.Tensor):
270
+ raw = raw.tolist()
271
+ ids = self._shift_crayon_ids(raw)
272
+ if add_bos_:
273
+ ids = [self.special_tokens["<|bos|>"]] + ids
274
+ if add_eos_:
275
+ ids = ids + [self.special_tokens["<|eos|>"]]
276
+ if self.max_length is not None:
277
+ ids = ids[:self.max_length]
278
+ all_ids.append(ids)
279
+ else:
280
+ # Submit all texts to thread pool
281
+ futures = [self._thread_pool.submit(_tokenize_one, t) for t in texts]
282
+ all_ids = [f.result() for f in futures]
283
+
284
+ if not pad or return_tensors is None:
285
+ return {"input_ids": all_ids}
286
+
287
+ # ── Padding ────────────────────────────────────────────────────────
288
+ max_len = max(len(ids) for ids in all_ids)
289
+ # Pad to multiple for efficiency
290
+ if pad_to_multiple_of > 1:
291
+ max_len = math.ceil(max_len / pad_to_multiple_of) * pad_to_multiple_of
292
+
293
+ pad_id = self.special_tokens["<|pad|>"]
294
+ padded_ids = []
295
+ attention_masks = []
296
+
297
+ for ids in all_ids:
298
+ n_pad = max_len - len(ids)
299
+ padded_ids.append(ids + [pad_id] * n_pad)
300
+ attention_masks.append([1] * len(ids) + [0] * n_pad)
301
+
302
+ if return_tensors == "pt":
303
+ return {
304
+ "input_ids": torch.tensor(padded_ids, dtype=torch.long),
305
+ "attention_mask": torch.tensor(attention_masks, dtype=torch.long),
306
+ }
307
+ return {"input_ids": padded_ids, "attention_mask": attention_masks}
308
+
309
+ def decode(
310
+ self,
311
+ ids: Union[List[int], torch.Tensor],
312
+ skip_special_tokens: bool = True,
313
+ ) -> str:
314
+ """Decode token IDs back to text."""
315
+ if isinstance(ids, torch.Tensor):
316
+ ids = ids.tolist()
317
+
318
+ # Separate special tokens from CRAYON tokens
319
+ crayon_ids = []
320
+ special_strs = []
321
+
322
+ for tok_id in ids:
323
+ if tok_id < self.special_token_offset:
324
+ if not skip_special_tokens and tok_id in self.id_to_special:
325
+ special_strs.append(self.id_to_special[tok_id])
326
+ else:
327
+ crayon_ids.append(tok_id - self.special_token_offset)
328
+
329
+ # CRAYON decode
330
+ if crayon_ids:
331
+ with self._lock:
332
+ text = self._tokenizer.decode(crayon_ids)
333
+ else:
334
+ text = ""
335
+
336
+ # Re-insert special tokens if not skipping
337
+ if special_strs and not skip_special_tokens:
338
+ text = " ".join(special_strs) + " " + text
339
+
340
+ return text
341
+
342
+ def decode_batch(
343
+ self,
344
+ batch_ids: Union[List[List[int]], torch.Tensor],
345
+ skip_special_tokens: bool = True,
346
+ ) -> List[str]:
347
+ """Decode a batch in parallel."""
348
+ if isinstance(batch_ids, torch.Tensor):
349
+ batch_ids = batch_ids.tolist()
350
+
351
+ if self.n_workers <= 1:
352
+ return [self.decode(ids, skip_special_tokens) for ids in batch_ids]
353
+
354
+ futures = [
355
+ self._thread_pool.submit(self.decode, ids, skip_special_tokens)
356
+ for ids in batch_ids
357
+ ]
358
+ return [f.result() for f in futures]
359
+
360
+ # ─────────────────────────────────────────────────────────────────────────
361
+ # CHAT TEMPLATE
362
+ # ──────────────────────────────────────────────────────────────────���──────
363
+
364
+ def encode_chat(
365
+ self,
366
+ messages: List[Dict[str, str]],
367
+ add_generation_prompt: bool = False,
368
+ return_as_tensor: bool = True,
369
+ ) -> Union[List[int], torch.Tensor]:
370
+ """
371
+ Encode a conversation using FORGE chat template.
372
+
373
+ Template:
374
+ <|bos|><|sys|>{system}<|/sys|>
375
+ <|usr|>{user}<|/usr|>
376
+ <|asst|>{assistant}<|/asst|>
377
+ ...
378
+
379
+ Args:
380
+ messages: List of {"role": "system|user|assistant", "content": str}
381
+ add_generation_prompt: If True, append <|asst|> at end (inference)
382
+ """
383
+ token_ids = [self.special_tokens["<|bos|>"]]
384
+
385
+ role_to_open = {
386
+ "system": "<|sys|>",
387
+ "user": "<|usr|>",
388
+ "assistant": "<|asst|>",
389
+ }
390
+ role_to_close = {
391
+ "system": "<|/sys|>",
392
+ "user": "<|/usr|>",
393
+ "assistant": "<|/asst|>",
394
+ }
395
+
396
+ for msg in messages:
397
+ role = msg["role"]
398
+ content = msg["content"]
399
+
400
+ # Open tag
401
+ open_tag = role_to_open.get(role, "<|usr|>")
402
+ close_tag = role_to_close.get(role, "<|/usr|>")
403
+
404
+ token_ids.append(self.special_tokens.get(open_tag, self.special_tokens["<|unk|>"]))
405
+
406
+ # Encode content (no bos/eos, no truncation)
407
+ content_ids = self.encode(content, add_bos=False, add_eos=False, truncate=False)
408
+ token_ids.extend(content_ids)
409
+
410
+ token_ids.append(self.special_tokens.get(close_tag, self.special_tokens["<|unk|>"]))
411
+
412
+ if add_generation_prompt:
413
+ token_ids.append(self.special_tokens["<|asst|>"])
414
+
415
+ if self.max_length is not None:
416
+ token_ids = token_ids[:self.max_length]
417
+
418
+ if return_as_tensor:
419
+ return torch.tensor(token_ids, dtype=torch.long)
420
+ return token_ids
421
+
422
+ def encode_chat_with_labels(
423
+ self,
424
+ messages: List[Dict[str, str]],
425
+ loss_on_prompt: bool = False,
426
+ ) -> Dict[str, torch.Tensor]:
427
+ """
428
+ Encode a conversation and produce labels for SFT.
429
+ Labels are -100 (ignored) for non-assistant turns unless loss_on_prompt=True.
430
+
431
+ Returns dict with 'input_ids' and 'labels'.
432
+ """
433
+ input_ids = []
434
+ labels = []
435
+
436
+ input_ids.append(self.special_tokens["<|bos|>"])
437
+ labels.append(-100 if not loss_on_prompt else self.special_tokens["<|bos|>"])
438
+
439
+ role_to_open = {
440
+ "system": "<|sys|>",
441
+ "user": "<|usr|>",
442
+ "assistant": "<|asst|>",
443
+ }
444
+ role_to_close = {
445
+ "system": "<|/sys|>",
446
+ "user": "<|/usr|>",
447
+ "assistant": "<|/asst|>",
448
+ }
449
+
450
+ for msg in messages:
451
+ role = msg["role"]
452
+ content = msg["content"]
453
+ is_assistant = (role == "assistant")
454
+
455
+ open_tag_id = self.special_tokens.get(role_to_open.get(role, "<|usr|>"),
456
+ self.special_tokens["<|unk|>"])
457
+ close_tag_id = self.special_tokens.get(role_to_close.get(role, "<|/usr|>"),
458
+ self.special_tokens["<|unk|>"])
459
+
460
+ content_ids = self.encode(content, add_bos=False, add_eos=False, truncate=False)
461
+
462
+ turn_ids = [open_tag_id] + content_ids + [close_tag_id]
463
+ input_ids.extend(turn_ids)
464
+
465
+ if is_assistant or loss_on_prompt:
466
+ # Compute loss on assistant content + close tag, NOT on open tag
467
+ turn_labels = [-100] + content_ids + [close_tag_id]
468
+ labels.extend(turn_labels)
469
+ else:
470
+ labels.extend([-100] * len(turn_ids))
471
+
472
+ if self.max_length is not None:
473
+ input_ids = input_ids[:self.max_length]
474
+ labels = labels[:self.max_length]
475
+
476
+ return {
477
+ "input_ids": torch.tensor(input_ids, dtype=torch.long),
478
+ "labels": torch.tensor(labels, dtype=torch.long),
479
+ }
480
+
481
+ # ─────────────────────────────────────────────────────────────────────────
482
+ # HIGH-THROUGHPUT OFFLINE PREPROCESSING
483
+ # ─────────────────────────────────────────────────────────────────────────
484
+
485
+ def tokenize_file_streaming(
486
+ self,
487
+ input_path: str,
488
+ output_path: str,
489
+ chunk_size: int = 100_000, # documents per chunk
490
+ seq_len: int = 2048,
491
+ append_eos: bool = True,
492
+ n_processes: int = None,
493
+ ) -> int:
494
+ """
495
+ High-throughput offline tokenization of a large text file.
496
+
497
+ Architecture:
498
+ - Producer process reads text lines
499
+ - N worker processes each run their own CrayonVocab instance
500
+ - Consumer aggregates and packs sequences
501
+
502
+ Throughput: ~5-10GB/min depending on hardware.
503
+ Returns: total number of tokens written.
504
+ """
505
+ n_processes = n_processes or max(1, mp.cpu_count() - 2)
506
+ total_tokens = 0
507
+
508
+ logger.info(f"Offline tokenization: {input_path} β†’ {output_path}, "
509
+ f"n_processes={n_processes}, seq_len={seq_len}")
510
+
511
+ # We use process-based parallelism to bypass GIL fully
512
+ with ProcessPoolExecutor(max_workers=n_processes) as pool:
513
+ with open(input_path, "r", encoding="utf-8", errors="replace") as fin:
514
+ chunk_buffer = []
515
+ futures = []
516
+
517
+ for line in fin:
518
+ chunk_buffer.append(line.strip())
519
+ if len(chunk_buffer) >= chunk_size:
520
+ futures.append(
521
+ pool.submit(
522
+ _tokenize_chunk_worker,
523
+ chunk_buffer.copy(),
524
+ self.profile,
525
+ self.special_token_offset,
526
+ SPECIAL_TOKENS["<|eos|>"] if append_eos else None,
527
+ )
528
+ )
529
+ chunk_buffer.clear()
530
+
531
+ # Submit remaining
532
+ if chunk_buffer:
533
+ futures.append(
534
+ pool.submit(
535
+ _tokenize_chunk_worker,
536
+ chunk_buffer,
537
+ self.profile,
538
+ self.special_token_offset,
539
+ SPECIAL_TOKENS["<|eos|>"] if append_eos else None,
540
+ )
541
+ )
542
+
543
+ # Collect and pack
544
+ token_stream = []
545
+ packed_sequences = []
546
+
547
+ for future in as_completed(futures):
548
+ chunk_tokens = future.result() # List[int]
549
+ token_stream.extend(chunk_tokens)
550
+
551
+ # Pack into fixed-length sequences
552
+ while len(token_stream) >= seq_len:
553
+ packed_sequences.append(token_stream[:seq_len])
554
+ token_stream = token_stream[seq_len:]
555
+ total_tokens += seq_len
556
+
557
+ # Flush to disk in chunks
558
+ if len(packed_sequences) >= 10_000:
559
+ _flush_to_disk(packed_sequences, output_path, total_tokens)
560
+ packed_sequences.clear()
561
+
562
+ # Flush remaining
563
+ if packed_sequences:
564
+ _flush_to_disk(packed_sequences, output_path, total_tokens)
565
+
566
+ logger.info(f"Tokenization complete: {total_tokens:,} tokens written to {output_path}")
567
+ return total_tokens
568
+
569
+ def __repr__(self) -> str:
570
+ return (f"ForgeTokenizer(profile={self.profile!r}, "
571
+ f"vocab_size={self.vocab_size:,}, "
572
+ f"n_workers={self.n_workers})")
573
+
574
+ def save_pretrained(self, path: str):
575
+ """Save tokenizer config for later loading."""
576
+ import json
577
+ os.makedirs(path, exist_ok=True)
578
+ config = {
579
+ "profile": self.profile,
580
+ "device": self.device_str,
581
+ "vocab_size": self.vocab_size,
582
+ "special_tokens": self.special_tokens,
583
+ "special_token_offset": self.special_token_offset,
584
+ "add_bos": self.add_bos,
585
+ "add_eos": self.add_eos,
586
+ "max_length": self.max_length,
587
+ }
588
+ with open(os.path.join(path, "tokenizer_config.json"), "w") as f:
589
+ json.dump(config, f, indent=2)
590
+ logger.info(f"Tokenizer config saved to {path}")
591
+
592
+ @classmethod
593
+ def from_pretrained(cls, path: str) -> "ForgeTokenizer":
594
+ import json
595
+ with open(os.path.join(path, "tokenizer_config.json")) as f:
596
+ config = json.load(f)
597
+ return cls(
598
+ profile=config["profile"],
599
+ device=config.get("device", "cpu"),
600
+ max_length=config.get("max_length"),
601
+ add_bos=config.get("add_bos", True),
602
+ add_eos=config.get("add_eos", True),
603
+ )
604
+
605
+ def __del__(self):
606
+ """Graceful cleanup of thread pool."""
607
+ try:
608
+ self._thread_pool.shutdown(wait=False)
609
+ except Exception:
610
+ pass
611
+
612
+
613
+ # ─────────────────────────────────────────────────────────────────────────────
614
+ # WORKER FUNCTIONS (must be module-level for pickling with ProcessPoolExecutor)
615
+ # ─────────────────────────────────────────────────────────────────────────────
616
+
617
+ def _tokenize_chunk_worker(
618
+ texts: List[str],
619
+ profile: str,
620
+ offset: int,
621
+ eos_id: Optional[int],
622
+ ) -> List[int]:
623
+ """
624
+ Worker function for parallel tokenization.
625
+ Runs in a separate process with its own CrayonVocab instance.
626
+ """
627
+ tok = CrayonVocab(device="cpu")
628
+ tok.load_profile(profile)
629
+
630
+ all_ids = []
631
+ for text in texts:
632
+ if not text:
633
+ continue
634
+ raw = tok.tokenize(text)
635
+ if isinstance(raw, torch.Tensor):
636
+ raw = raw.tolist()
637
+ ids = [i + offset for i in raw]
638
+ if eos_id is not None:
639
+ ids.append(eos_id)
640
+ all_ids.extend(ids)
641
+
642
+ return all_ids
643
+
644
+
645
+ def _flush_to_disk(sequences: List[List[int]], output_path: str, offset: int):
646
+ """Append packed sequences to a memory-mapped numpy file."""
647
+ arr = np.array(sequences, dtype=np.uint32)
648
+ mode = "ab" # append binary
649
+ with open(output_path + ".npy", mode) as f:
650
+ np.save(f, arr)
651
+ # Also write offset index for random access
652
+ with open(output_path + ".idx", "ab") as f:
653
+ np.save(f, np.array([offset], dtype=np.int64))