File size: 18,451 Bytes
f7d1bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bc32b2
 
f7d1bd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
tokenmax.py โ€” Deterministic token-maxing post-processor for compressed think blocks.

Applies ONLY substitutions that are verified to save tokens on the Qwen 248K tokenizer
(OmniCoder-9B / Qwen3.5). Every substitution was tested in-context (not isolation) to
confirm real token savings without boundary interference.

Design:
  - LLM does semantic compression (what to keep vs drop)
  - This code enforces consistent notation deterministically
  - GUARD: only returns the processed version if ntok(result) < ntok(original)
  - Idempotent: safe to run multiple times

Usage:
    from caveman.compress.tokenmax import tokenmax, tokenmax_with_stats
    compressed = tokenmax(think_text, tokenizer)
    compressed, stats = tokenmax_with_stats(think_text, tokenizer)

Verified: 2026-05-31 on Qwen 248K vocab. 27/28 substitutions save in-context.
Zero false positives. One zero-effect (่ดชๅฟƒ for "greedy" โ€” boundary-dependent).
"""

import re
from typing import Optional

# โ”€โ”€ Phase 1: Filler drops โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Phrases that carry zero information in compressed reasoning.
# Only patterns that are NEVER load-bearing in a think block.
_FILLER_PATTERNS = [
    # Metacognition (the model narrating its own process)
    r"\bI need to\b",
    r"\bwe need to\b",
    r"\bI will\b",
    r"\bI'll\b",
    r"\blet me\b",
    r"\blet's\b",
    r"\bI want to\b",
    r"\bI should\b",
    r"\bwe should\b",
    # Hedging
    r"\bprobably\b",
    r"\bbasically\b",
    r"\bessentially\b",
    r"\bit seems like\b",
    # Filler transitions
    r"\bin order to\b",
    r"\bfirst of all\b",
    r"\bin other words\b",
    r"\bon the other hand\b",
    r"\bmore specifically\b",
    r"\bto be more precise\b",
    r"\band so on\b",
    # Conversational padding (require word boundary at end to avoid "Greatest", "Perfectly")
    r"\bGreat\b[,!.]?\s*",
    r"\bPerfect\b[,!.]?\s*",
    # Obvious statements
    r"\bAs (?:we|you) can see\b",
    r"\bAs mentioned (?:above|earlier|before)\b",
]

# โ”€โ”€ Phase 2: Phrase โ†’ cheapest token โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Ordered LONGEST FIRST to prevent partial matches.
# Each entry: (regex_pattern, replacement, category)
# Categories: 'cjk', 'symbol', 'abbrev' โ€” for stats tracking.
_SUBSTITUTIONS = [
    # โ”€โ”€ COMPOUND PATTERNS FIRST (must fire before their components) โ”€โ”€

    # Verbose comparison phrases (+5t savings)
    (r'\bis\s+greater\s+than\s+or\s+equal\s+to\b', 'โ‰ฅ', 'symbol'),   # +5t
    (r'\bis\s+less\s+than\s+or\s+equal\s+to\b', 'โ‰ค', 'symbol'),      # +5t

    # Verbose discourse phrases (+3t savings)
    (r'\bwe\s+can\s+see\s+that\b', 'ๅฏ็Ÿฅ', 'cjk'),                    # +3t
    (r'\bat\s+the\s+same\s+time\b', 'ๅŒๆ—ถ', 'cjk'),                   # +3t
    (r'\bthat\s+is\s+to\s+say\b', 'ๅณ', 'cjk'),                      # +3t

    # Multi-word phrases (+2t savings)
    (r'\bin\s+this\s+case\b', 'ๆญคๆ—ถ', 'cjk'),                         # +2t
    (r'\bthe\s+number\s+of\b', 'ไธชๆ•ฐ', 'cjk'),                        # +2t
    (r'\bis\s+equal\s+to\b', '็ญ‰ไบŽ', 'cjk'),                          # +2t

    # Complexity boilerplate (biggest per-occurrence savings)
    (r'[Oo]\(n\)\s*time[,;]?\s*[Oo]\(n\)\s*space\.?', 'O(n|n).', 'abbrev'),
    (r'[Oo]\(n\)\s*time[,;]?\s*[Oo]\(1\)\s*space\.?', 'O(n|1).', 'abbrev'),
    (r'[Oo]\(n\s*log\s*n\)\s*time[,;]?\s*[Oo]\(n\)\s*space', 'O(nใ’n|n)', 'abbrev'),
    (r'[Oo]\(n\s*log\s*n\)\s*time[,;]?\s*[Oo]\(1\)\s*space', 'O(nใ’n|1)', 'abbrev'),
    (r'[Tt]ime\s*complexity[:\s]+', 'T=', 'abbrev'),
    (r'[Ss]pace\s*complexity[:\s]+', 'S=', 'abbrev'),

    # Multi-word compounds (BEFORE their single-word components)
    (r'\bassume without loss of generality\b', '่ฎพ ไธๅฆจ', 'cjk'),  # before "assume"
    (r'\bproof by contradiction\b', 'ๅ่ฏ', 'cjk'),                # before "proof", "contradiction"
    (r'\bnecessary and sufficient\b', 'ๅ……่ฆ', 'cjk'),              # before "sufficient"
    (r'\bnot equal(?:\s+to)?\b', 'โ‰ ', 'symbol'),                  # before "is not", "does not"
    (r'\bif and only if\b', 'iff', 'abbrev'),                     # before "for all"
    (r'\bmuch greater than\b', 'โ‰ซ', 'symbol'),                    # before "greater than"
    (r'\bkeep track(?:\s+of)?\b', '่ฎฐๅฝ•', 'cjk'),                 # before article strip
    (r'\bin ascending order\b', 'asc', 'abbrev'),
    (r'\bin descending order\b', 'desc', 'abbrev'),
    (r'\bmaximum value\b', 'ๆœ€ๅคงๅ€ผ', 'cjk'),
    (r'\bminimum value\b', 'ๆœ€ๅฐๅ€ผ', 'cjk'),
    (r'\breturn value\b', '่ฟ”ๅ›žๅ€ค', 'cjk'),
    (r'\brather than\b', '่€Œ้ž', 'cjk'),
    (r'\baccording to\b', 'ๆŒ‰็…ง', 'cjk'),

    # DS compounds (before components)
    (r'\bdoubly linked list\b', 'DLL', 'abbrev'),      # BEFORE "linked list"
    (r'\bbinary indexed tree\b', 'BIT', 'abbrev'),     # BEFORE "binary"
    (r'\bminimum spanning tree\b', 'MST', 'abbrev'),
    (r'\bdepth[- ]first search\b', 'DFS', 'abbrev'),
    (r'\bbreadth[- ]first search\b', 'BFS', 'abbrev'),
    (r'\bdynamic programming\b', 'DP', 'abbrev'),
    (r'\bdivide and conquer\b', 'ๅˆ†ๆฒป', 'cjk'),
    (r'\bmonot(?:onic|one)\s*stack\b', 'ๅ•่ฐƒๆ ˆ', 'cjk'),
    (r'\btime limit exceeded\b', '่ถ…ๆ—ถ', 'cjk'),
    (r'\bout of bounds\b', '่ถŠ็•Œ', 'cjk'),
    (r'\bremove duplicates?\b', 'ๅŽป้‡', 'cjk'),
    (r'\benumerate all\b', '็ฉทไธพ', 'cjk'),
    (r'\bbinary search\b', 'ไบŒๅˆ†', 'cjk'),
    (r'\bsliding window\b', 'sw', 'abbrev'),
    (r'\bunion[- ]find\b', 'UF', 'abbrev'),
    (r'\btopological sort\b', 'ๆ‹“ๆ‰‘ๅบ', 'cjk'),
    (r'\bshortest path\b', 'sp', 'abbrev'),
    (r'\blinked list\b', 'LL', 'abbrev'),
    (r'\bpriority queue\b', 'heap', 'abbrev'),
    (r'\bprefix sum\b', 'ps', 'abbrev'),
    (r'\bbrute force\b', 'ๆšดๅŠ›', 'cjk'),
    (r'\bno solution\b', 'ๆ— ่งฃ', 'cjk'),
    (r'\bedge cases?\b', '่พน็•Œ', 'cjk'),
    (r'\bbase case\b', 'bc', 'abbrev'),
    (r'\bworst case\b', 'wc', 'abbrev'),

    # โ”€โ”€ SINGLE-WORD SUBSTITUTIONS (safe after compounds consumed) โ”€โ”€

    # +4t savings
    (r'\bobviously\b', 'ๆ˜พ็„ถ', 'cjk'),
    # +3t savings
    (r'\bredundant\b', 'ๅ†—ไฝ™', 'cjk'),
    (r'\bsatisf(?:y|ies|ied)\b', 'ๆปก่ถณ', 'cjk'),            # +2t, 333x in data
    (r'\bunsorted\b', 'ๆ— ๅบ', 'cjk'),
    (r'\bdue to\b', '็”ฑไบŽ', 'cjk'),
    (r'\bhence\b', 'ๆ•…', 'cjk'),
    (r'\bnamely\b', 'ๅณ', 'cjk'),
    (r'\bassume\b', '่ฎพ', 'cjk'),
    (r'\bsuppose\b', '่ฎพ', 'cjk'),
    (r'\bderive\b', 'ๆŽจๅฏผ', 'cjk'),
    # +2t savings
    (r'\bmonotone\b', 'ๅ•่ฐƒ', 'cjk'),
    (r'\bconvergent\b', 'ๆ”ถๆ•›', 'cjk'),
    (r'\bdivergent\b', 'ๅ‘ๆ•ฃ', 'cjk'),
    (r'\bcommutative\b', 'ไบคๆข', 'cjk'),
    (r'\bdeterministic\b', '็กฎๅฎš', 'cjk'),
    (r'\bprobabilistic\b', 'ๆฆ‚็އ', 'cjk'),
    (r'\bprove\b', '่ฏๆ˜Ž', 'cjk'),
    (r'\bproof\b', '่ฏๆ˜Ž', 'cjk'),
    (r'\bflip\b', '็ฟป่ฝฌ', 'cjk'),
    (r'\bsorted\b(?!\s*[=(\[])', 'ๆœ‰ๅบ', 'cjk'),  # not before = ( [ (assignment/call)
    # +1t savings
    (r'\bbacktrack(?:ing)?\b', 'ๅ›žๆบฏ', 'cjk'),
    (r'\btravers(?:e|al|ing)\b', '้ๅކ', 'cjk'),
    (r'\brecursi(?:on|ve|vely)\b', '้€’ๅฝ’', 'cjk'),
    (r'\bcontradiction\b', '็Ÿ›็›พ', 'cjk'),
    (r'\bsufficient\b', 'ๅ……ๅˆ†', 'cjk'),
    (r'\bequivalent\b', '็ญ‰ไปท', 'cjk'),
    (r'\bsymmetric\b', 'ๅฏน็งฐ', 'cjk'),
    (r'\binvariant\b', 'ไธๅ˜', 'cjk'),
    (r'\bexponential\b', 'ๆŒ‡ๆ•ฐ', 'cjk'),
    (r'\bpermutation\b', 'ๆŽ’ๅˆ—', 'cjk'),
    (r'\badjacent\b', '็›ธ้‚ป', 'cjk'),
    (r'\boptimal\b', 'ๆœ€ไผ˜', 'cjk'),
    (r'\bfeasible\b', 'ๅฏ่กŒ', 'cjk'),
    (r'\binduction\b', 'ๅฝ’็บณ', 'cjk'),
    (r'\bmaintain\b', '็ปดๆŠค', 'cjk'),
    (r'\bswap\b(?!\s*[=(\[])', 'ไบคๆข', 'cjk'),  # not before = ( [ (assignment/call)
    (r'\bcumulative\b', '็ดฏ็งฏ', 'cjk'),
    (r'\bquotient\b', 'ๅ•†', 'cjk'),
    (r'\bmemoiz(?:ation|e)\b', 'memo', 'abbrev'),
    # +2t savings (mined from v19 data)
    (r'\bmathematical\b', 'ๆ•ฐๅญฆ', 'cjk'),
    (r'\bcorresponding(?:ly)?\b', 'ๅฏนๅบ”', 'cjk'),
    (r'\brequirement\b', '้œ€ๆฑ‚', 'cjk'),
    # +1t savings (mined from v19 data)
    (r'\bcomplexity\b', 'ๅคๆ‚ๅบฆ', 'cjk'),
    (r'\bsimilarly\b', 'ๅŒ็†', 'cjk'),
    (r'\bsubstitut(?:e|ion)\b', 'ไปฃๅ…ฅ', 'cjk'),
    (r'\bincreasing(?:ly)?\b', '้€’ๅขž', 'cjk'),
    (r'\bdecreasing(?:ly)?\b', '้€’ๅ‡', 'cjk'),
    (r'\brespectively\b', 'ๅˆ†ๅˆซ', 'cjk'),
    (r'\bnecessarily\b', 'ๅฟ…็„ถ', 'cjk'),
    (r'\btransformation\b', 'ๅ˜ๆข', 'cjk'),
    (r'\bprerequisite\b', 'ๅ‰ๆ', 'cjk'),
    (r'\bconsequently\b', 'ไปŽ่€Œ', 'cjk'),
    (r'\boverlapping\b', '้‡ๅ ', 'cjk'),
    (r'\bcontribut(?:e|ion)\b', '่ดก็Œฎ', 'cjk'),
    (r'\bindependent(?:ly)?\b', '็‹ฌ็ซ‹', 'cjk'),
    (r'\bimpossible\b', 'ไธๅฏ่ƒฝ', 'cjk'),
    (r'\biterat(?:e|ion|ing)\b', '่ฟญไปฃ', 'cjk'),
    (r'\benumerat(?:e|ion|ing)\b', 'ๆžšไธพ', 'cjk'),

    # โ”€โ”€ LOGIC SYMBOLS โ”€โ”€
    (r'\btherefore\b', 'โ‡’', 'symbol'),
    (r'\bthus\b', 'โ‡’', 'symbol'),
    (r'\bsuch that\b', 'st', 'abbrev'),
    (r'\bthere exists?\b', 'โˆƒ', 'symbol'),
    (r'\bfor each\b', 'โˆ€', 'symbol'),
    (r'\bfor every\b', 'โˆ€', 'symbol'),
    (r'\bfor all\b', 'โˆ€', 'symbol'),
    (r'\bdoes not\b', 'ยฌ', 'symbol'),
    (r"\bdoesn't\b", 'ยฌ', 'symbol'),
    (r'\bis not\b(?!\s+(?:None|null|undefined|empty|zero|0))', '้ž', 'cjk'),  # protect "is not None" etc
    (r'\bat least\b', 'โ‰ฅ', 'symbol'),
    (r'\bat most\b', 'โ‰ค', 'symbol'),
    (r'\bgreater than\b', '>', 'symbol'),
    (r'\bless than\b', '<', 'symbol'),

    # โ”€โ”€ ARTICLE STRIPPING (last โ€” lowest priority) โ”€โ”€
    (r'\bthe\b\s+(?!(?:same|only|first|last|next|other)\b)', '', 'filler'),  # protect "the same", "the only" etc
    (r'\ba\b\s+(?=[bcdfghjklmnpqrstvwxyz])', '', 'filler'),
    (r'\ban\b\s+', '', 'filler'),
]

# โ”€โ”€ Compile once โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
_FILLER_COMPILED = [(re.compile(p, re.IGNORECASE), '') for p in _FILLER_PATTERNS]
_SUBS_COMPILED = [(re.compile(p, re.IGNORECASE), r, cat) for p, r, cat in _SUBSTITUTIONS]


def _ntok(text: str, tokenizer) -> int:
    """Token count using the provided tokenizer."""
    return len(tokenizer.encode(text, add_special_tokens=False))


def _protect_code_fences(text: str) -> tuple[str, list]:
    """Extract code-fenced blocks, replace with placeholders.
    Returns (text_with_placeholders, list_of_extracted_blocks)."""
    blocks = []
    def _replace(m):
        blocks.append(m.group(0))
        return f'\x00CODEFENCE{len(blocks)-1}\x00'
    # Match ```...``` and inline `...` (non-greedy)
    protected = re.sub(r'```.*?```|`[^`\n]+`', _replace, text, flags=re.DOTALL)
    return protected, blocks


def _restore_code_fences(text: str, blocks: list) -> str:
    """Restore code-fenced blocks from placeholders."""
    for i, block in enumerate(blocks):
        text = text.replace(f'\x00CODEFENCE{i}\x00', block)
    return text


def _apply_subs(text: str) -> tuple[str, dict]:
    """Apply all substitutions, return (result, stats).
    Code fences (``` and inline `) are protected from substitution."""
    stats = {'filler_drops': 0, 'cjk': 0, 'symbol': 0, 'abbrev': 0, 'total_subs': 0}

    # Phase 0: protect code fences from substitution
    text, code_blocks = _protect_code_fences(text)

    # Phase 1: filler drops
    for pat, repl in _FILLER_COMPILED:
        text, n = pat.subn(repl, text)
        if n:
            stats['filler_drops'] += n
            stats['total_subs'] += n

    # Phase 2: substitutions
    for pat, repl, cat in _SUBS_COMPILED:
        text, n = pat.subn(repl, text)
        if n:
            stats[cat] = stats.get(cat, 0) + n
            stats['total_subs'] += n

    # Phase 3: restore code fences
    text = _restore_code_fences(text, code_blocks)

    # Phase 4: whitespace normalization
    text = re.sub(r'[ \t]+', ' ', text)
    text = re.sub(r'\n{3,}', '\n\n', text)
    text = re.sub(r' *\n *', '\n', text)
    text = text.strip()

    return text, stats


def tokenmax(text: str, tokenizer, force_cjk: bool = False) -> str:
    """Apply token-maxing. Returns original if no savings achieved.

    Args:
        text: The think block content (without <think> tags).
        tokenizer: A HuggingFace tokenizer with .encode() method.
        force_cjk: If True, always return the processed version when CJK
            substitutions were applied, even if total token count increased.
            Use this to maximize CJK adoption in training data.

    Returns:
        The token-maxed text, or the original if processing didn't save tokens
        (unless force_cjk=True and CJK subs were applied).
    """
    if not text or not text.strip():
        return text

    original_tokens = _ntok(text, tokenizer)
    result, stats = _apply_subs(text)
    result_tokens = _ntok(result, tokenizer)

    # GUARD: only return processed version if it actually saves tokens
    # OVERRIDE: force_cjk bypasses the guard when CJK substitutions were made
    if result_tokens < original_tokens:
        return result
    if force_cjk and stats.get('cjk', 0) > 0:
        return result
    return text


def tokenmax_with_stats(text: str, tokenizer, force_cjk: bool = False) -> tuple[str, dict]:
    """Like tokenmax() but also returns substitution statistics.

    Args:
        force_cjk: If True, always apply when CJK substitutions were made,
            even if total token count increased. Prioritizes CJK adoption
            over token savings.

    Returns:
        (processed_text, stats_dict) where stats_dict contains:
          - original_tokens: token count before processing
          - result_tokens: token count after processing
          - saved: tokens saved (negative = token increase; check forced_cjk)
          - applied: whether the processed version was used
          - forced_cjk: True when force_cjk override caused acceptance despite no savings
          - filler_drops, cjk, symbol, abbrev: substitution counts by category
          - total_subs: total substitutions applied
    """
    if not text or not text.strip():
        return text, {'original_tokens': 0, 'result_tokens': 0, 'saved': 0,
                      'applied': False, 'forced_cjk': False, 'total_subs': 0}

    original_tokens = _ntok(text, tokenizer)
    result, stats = _apply_subs(text)
    result_tokens = _ntok(result, tokenizer)
    saved = original_tokens - result_tokens

    stats['original_tokens'] = original_tokens
    stats['result_tokens'] = result_tokens
    stats['saved'] = saved
    stats['forced_cjk'] = False

    if saved > 0:
        stats['applied'] = True
        return result, stats
    if force_cjk and stats.get('cjk', 0) > 0:
        stats['applied'] = True
        stats['forced_cjk'] = True
        return result, stats
    stats['applied'] = False
    return text, stats


# โ”€โ”€ CLI: batch process a JSONL file โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
if __name__ == '__main__':
    import json, sys, argparse
    from transformers import AutoTokenizer

    parser = argparse.ArgumentParser(description='Token-max post-processor for think blocks')
    parser.add_argument('--input', required=True, help='Input JSONL (messages format)')
    parser.add_argument('--output', help='Output JSONL (default: dry run, stats only)')
    parser.add_argument('--tokenizer', default='ZelligeAI/tessera-compressor',
                        help='HF repo id or local path of the tokenizer to count savings under')
    parser.add_argument('--force-cjk', action='store_true',
                        help='Force CJK substitutions even if total tokens increase. '
                             'Prioritizes CJK adoption over token savings.')
    args = parser.parse_args()

    tok = AutoTokenizer.from_pretrained(args.tokenizer, trust_remote_code=True)

    total_before = total_after = applied = skipped = forced = 0

    out_lines = []
    with open(args.input) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            rec = json.loads(line)
            for m in rec.get('messages', rec.get('conversations', [])):
                role = m.get('role', m.get('from', ''))
                if role not in ('assistant', 'gpt'):
                    continue
                content_key = 'content' if 'content' in m else 'value'
                c = m.get(content_key, '') or ''
                if '<think>' not in c or '</think>' not in c:
                    continue

                # Extract think content, preserving prefix before <think> and suffix after </think>
                think_start = c.index('<think>') + len('<think>')
                think_end = c.index('</think>')
                prefix = c[:think_start - len('<think>')]
                think = c[think_start:think_end]
                suffix = c[think_end + len('</think>'):]

                maxed, stats = tokenmax_with_stats(think, tok, force_cjk=args.force_cjk)

                total_before += stats['original_tokens']
                if stats['applied']:
                    applied += 1
                    total_after += stats['result_tokens']
                    m[content_key] = f'{prefix}<think>{maxed}</think>{suffix}'
                    if stats.get('forced_cjk'):
                        forced += 1
                else:
                    skipped += 1
                    total_after += stats['original_tokens']

            out_lines.append(json.dumps(rec, ensure_ascii=False))

    if args.output:
        with open(args.output, 'w') as f:
            for line in out_lines:
                f.write(line + '\n')

    total = applied + skipped
    saved = total_before - total_after
    if total > 0:
        print(f'Processed {total} think blocks')
        print(f'  Applied: {applied} ({100*applied/total:.0f}%)')
        if forced:
            print(f'  Forced CJK: {forced} (applied despite no token savings)')
        print(f'  Skipped (no savings): {skipped}')
        pct = f'{100*saved/total_before:.1f}' if total_before > 0 else '0.0'
        print(f'  Tokens: {total_before} โ†’ {total_after} = {saved:+d} ({pct}%)')
    else:
        print(f'No think blocks found in {args.input}')