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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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#!/usr/bin/env python3
"""
Atom Validation Harness β€” Tests fast_split atoms against canonical HF tokenizer patterns.

This harness:
1. Loads canonical pre_tokenizer configs from known model families
2. Tests tokenization parity between HF reference and fast_split atoms
3. Reports coverage gaps and mismatches

Usage:
    python atom_validation_harness.py --fetch-canonical  # Download configs from HF
    python atom_validation_harness.py --test-local       # Test against local fast_split
    python atom_validation_harness.py --report         # Generate coverage report
"""

import json
import os
import sys
import subprocess
import tempfile
import urllib.request
from dataclasses import dataclass
from typing import Optional, List, Dict, Tuple
from collections import defaultdict
import argparse

# ── Canonical Model Registry ─────────────────────────────────────────────

@dataclass
class CanonicalConfig:
    """A canonical tokenizer configuration representing a model family."""
    family: str                      # e.g., "llama3", "cl100k", "bert"
    model_id: str                    # HF model ID to fetch from
    atom_shape: str                 # Expected atom: A1_split, A2_class_runs, A3_cl100k, A4_deepseek, A5_byte_level, A6_script_run
    description: str
    test_cases: List[str]           # Representative test strings
    gated: bool = False             # Whether model requires auth
    alternative_models: Optional[List[str]] = None  # Fallback models if primary unavailable

# Registry of canonical patterns
CANONICAL_REGISTRY: List[CanonicalConfig] = [
    # ── A3: cl100k family (GPT-4, Claude) ──
    CanonicalConfig(
        family="cl100k_base",
        model_id="openai-community/gpt2",  # GPT-2 is byte-level, but cl100k uses same pattern
        atom_shape="A3_cl100k",
        description="OpenAI cl100k_base (GPT-4 tokenizer)",
        test_cases=[
            "Hello world",
            "don't",  # contraction
            "a1234",  # number cap
            "  hi",   # whitespace rules
            "cafΓ©",  # unicode
            "a, b",   # punctuation
        ],
        alternative_models=["ggml-org/gpt-4o-2024-08-06-tokenizer"]
    ),
    
    # ── A4: DeepSeek family ──
    CanonicalConfig(
        family="deepseek_v3",
        model_id="deepseek-ai/deepseek-v3",
        atom_shape="A4_deepseek",
        description="DeepSeek-V3 Sequence tokenizer",
        test_cases=[
            "abcδΈ­def",  # CJK isolation
            "abc123",      # digits {1,3}
            "_abc",        # ASCII punct + letters
            "hello world", # word splitting
            "!!!",         # punctuation run
        ],
        gated=True,
    ),
    
    # ── A5: ByteLevel family (Llama 3, Qwen, etc.) ──
    CanonicalConfig(
        family="llama3",
        model_id="unsloth/llama-3-8b-bnb-4bit",  # Not gated
        atom_shape="A5_byte_level",
        description="Llama 3 / GPT-2 style ByteLevel with regex",
        test_cases=[
            "Hello world",
            "don't split contractions",
            "numbers 123 and 4567",
            "unicode: δΈ–η•Œ русский",
        ],
        alternative_models=["NousResearch/Meta-Llama-3-8B"]
    ),
    
    CanonicalConfig(
        family="qwen2",
        model_id="Qwen/Qwen2-7B",
        atom_shape="A5_byte_level",
        description="Qwen2 (similar to Llama 3)",
        test_cases=[
            "δ½ ε₯½δΈ–η•Œ",  # Chinese
            "Hello δΈ–η•Œ",   # Mixed
            "12345",         # Numbers
        ],
    ),
    
    CanonicalConfig(
        family="mistral",
        model_id="mistralai/Mistral-7B-v0.1",
        atom_shape="A1_split",  # Metaspace
        description="Mistral Metaspace tokenizer",
        test_cases=[
            "Hello world",
            "Test with spaces",
        ],
    ),
    
    CanonicalConfig(
        family="gemma",
        model_id="google/gemma-2-2b",
        atom_shape="A1_split",  # Metaspace
        description="Gemma Metaspace tokenizer",
        test_cases=[
            "Hello world",
        ],
        gated=True,
    ),
    
    # ── A2: BERT family ──
    CanonicalConfig(
        family="bert",
        model_id="google-bert/bert-base-uncased",
        atom_shape="A2_class_runs",
        description="BERT BertPreTokenizer",
        test_cases=[
            "Hello, world! How are you?",
            "Testing punctuation. And more...",
            "123 numbers 456",
        ],
    ),
    
    CanonicalConfig(
        family="roberta",
        model_id="FacebookAI/roberta-base",
        atom_shape="A5_byte_level",
        description="RoBERTa (ByteLevel, not BERT)",
        test_cases=[
            "Hello world",
            "Don't split",
        ],
    ),
    
    # ── A1: Simple splits ──
    CanonicalConfig(
        family="whitespace_split",
        model_id="",
        atom_shape="A1_split",
        description="WhitespaceSplit standalone",
        test_cases=["Hello world test"],
    ),
    
    # ── null: SentencePiece (T5, Llama 1/2) ──
    CanonicalConfig(
        family="t5",
        model_id="google-t5/t5-small",
        atom_shape="null",
        description="T5 (SentencePiece, no pre_tokenizer)",
        test_cases=[
            "This is a test sentence.",
            "Another example with numbers: 42",
        ],
    ),
    
    # ── UnicodeScripts ──
    CanonicalConfig(
        family="unicode_scripts",
        model_id="",
        atom_shape="A6_script_run",
        description="UnicodeScripts preprocessor (TODO in PR)",
        test_cases=["Hello Ω…Ψ±Ψ­Ψ¨Ψ§ δΈ–η•Œ"],  # Latin + Arabic + Chinese
    ),
]

# ── Test Harness Core ─────────────────────────────────────────────

class AtomValidationHarness:
    """Main test harness for validating fast_split atoms."""
    
    def __init__(self, cache_dir: str = ".tokenizers_cache"):
        self.cache_dir = cache_dir
        self.results: Dict[str, Dict] = {}
        os.makedirs(cache_dir, exist_ok=True)
        
    def fetch_tokenizer_config(self, config: CanonicalConfig) -> Optional[Dict]:
        """Fetch tokenizer.json from HF, using cache if available."""
        cache_path = os.path.join(self.cache_dir, f"{config.family}.json")
        
        # Check cache
        if os.path.exists(cache_path):
            with open(cache_path) as f:
                return json.load(f)
        
        # Try to fetch
        models_to_try = [config.model_id]
        if config.alternative_models:
            models_to_try.extend(config.alternative_models)
        
        for model_id in models_to_try:
            if not model_id:
                continue
            url = f"https://huggingface.co/{model_id}/resolve/main/tokenizer.json"
            try:
                req = urllib.request.Request(url, headers={"User-Agent": "atom-harness/1.0"})
                with urllib.request.urlopen(req, timeout=30) as resp:
                    data = json.load(resp)
                # Cache it
                with open(cache_path, "w") as f:
                    json.dump(data, f)
                return data
            except urllib.error.HTTPError as e:
                if e.code == 401:
                    print(f"  [SKIP] {model_id}: gated (401)")
                elif e.code == 404:
                    print(f"  [SKIP] {model_id}: no tokenizer.json (404)")
                else:
                    print(f"  [SKIP] {model_id}: HTTP {e.code}")
            except Exception as e:
                print(f"  [SKIP] {model_id}: {e}")
        
        return None
    
    def extract_pre_tokenizer_signature(self, tokenizer_json: Dict) -> Tuple[str, Dict]:
        """Extract canonical signature from tokenizer.json pre_tokenizer."""
        pt = tokenizer_json.get("pre_tokenizer")
        if pt is None:
            return "null", {}
        
        t = pt.get("type", "unknown")
        
        if t == "Sequence":
            parts = [p.get("type", "?") for p in pt.get("pretokenizers", [])]
            # Check for known sequences
            if parts == ["Split", "ByteLevel"]:
                return "Split+ByteLevel", pt
            if len(parts) == 4 and parts[0] == "Split" and parts[3] == "ByteLevel":
                return "DeepSeek-Sequence", pt
            return f"Sequence({','.join(parts)})", pt
        
        if t == "Split":
            pat = pt.get("pattern", {})
            pat_type = list(pat.keys())[0] if pat else "none"
            if pat_type == "Regex":
                regex = pat.get("Regex", "")
                # Classify regex
                if "N}{1,3}" in regex:
                    return "Split(Regex-cl100k)", pt
                if "\u4e00" in regex or "4e00" in regex.lower():
                    return "Split(Regex-CJK)", pt
                return f"Split(Regex:{pat_type})", pt
            return f"Split({pat_type})", pt
        
        return t, pt
    
    def reference_tokenize(self, text: str, tokenizer_json: Dict) -> List[str]:
        """Tokenize using HF tokenizers library (reference implementation)."""
        try:
            from tokenizers import Tokenizer
            # Create temp file for tokenizer.json
            with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
                json.dump(tokenizer_json, f)
                tmp_path = f.name
            
            tok = Tokenizer.from_file(tmp_path)
            encoding = tok.encode(text)
            os.unlink(tmp_path)
            return encoding.tokens
        except ImportError:
            print("  [WARN] tokenizers library not installed, using mock")
            return [text]  # Mock fallback
        except Exception as e:
            print(f"  [WARN] Tokenization failed: {e}")
            return [text]
    
    def fast_split_tokenize(self, text: str, atom_shape: str, pre_tokenizer: Dict) -> List[str]:
        """Tokenize using fast_split atoms (TODO: integrate with Rust)."""
        # This is a placeholder - would need to call the Rust implementation
        # For now, return mock based on expected behavior
        return self._mock_fast_split(text, atom_shape, pre_tokenizer)
    
    def _mock_fast_split(self, text: str, atom_shape: str, pre_tokenizer: Dict) -> List[str]:
        """Mock fast_split behavior for testing harness structure."""
        # Simple mock implementations
        if atom_shape == "null":
            return [text]
        elif atom_shape == "A1_split":
            # Whitespace split
            return text.split()
        elif atom_shape == "A2_class_runs":
            # Bert-style: split on punctuation and whitespace
            import re
            return re.findall(r"\w+|[^\w\s]", text)
        elif atom_shape == "A5_byte_level":
            # GPT-2 style: roughly word-based
            import re
            return re.findall(r"\w+|[^\w\s]", text)
        return [text]
    
    def test_family(self, config: CanonicalConfig) -> Dict:
        """Test a single canonical family."""
        print(f"\n── Testing: {config.family} ──" + "─" * 40)
        print(f"  Expected atom: {config.atom_shape}")
        print(f"  Description: {config.description}")
        
        result = {
            "family": config.family,
            "expected_atom": config.atom_shape,
            "config_available": False,
            "signature_match": False,
            "test_passed": False,
            "errors": [],
            "details": {}
        }
        
        # Fetch config
        tokenizer_json = self.fetch_tokenizer_config(config)
        if tokenizer_json is None:
            if config.alternative_models:
                print(f"  [SKIP] All model sources unavailable (gated or no tokenizer.json)")
                result["errors"].append("All sources unavailable")
                return result
            else:
                # For families without models (like standalone configs), use embedded
                print(f"  [INFO] Using embedded mock config for {config.family}")
                tokenizer_json = {"pre_tokenizer": None}  # Mock
        
        result["config_available"] = True
        
        # Extract signature
        sig, pt_config = self.extract_pre_tokenizer_signature(tokenizer_json)
        result["signature"] = sig
        print(f"  Detected signature: {sig}")
        
        # Check if signature matches expected atom
        expected_sigs = {
            "A3_cl100k": ["Split(Regex-cl100k)"],
            "A4_deepseek": ["DeepSeek-Sequence"],
            "A5_byte_level": ["Split+ByteLevel", "ByteLevel"],
            "A2_class_runs": ["BertPreTokenizer", "Whitespace", "WhitespaceSplit"],
            "A1_split": ["Metaspace", "WhitespaceSplit", "Punctuation", "Digits"],
            "null": ["null"],
            "A6_script_run": ["UnicodeScripts"],
        }
        
        expected_list = expected_sigs.get(config.atom_shape, [])
        if sig in expected_list or any(e in sig for e in expected_list):
            result["signature_match"] = True
            print(f"  [βœ“] Signature matches expected atom")
        else:
            print(f"  [!] Signature mismatch: expected {expected_list}, got {sig}")
            result["errors"].append(f"Signature mismatch: {sig} not in {expected_list}")
        
        # Run test cases
        print(f"\n  Testing {len(config.test_cases)} cases:")
        all_pass = True
        for tc in config.test_cases:
            ref_tokens = self.reference_tokenize(tc, tokenizer_json)
            fast_tokens = self.fast_split_tokenize(tc, config.atom_shape, pt_config)
            
            match = ref_tokens == fast_tokens
            status = "βœ“" if match else "βœ—"
            print(f"    {status} '{tc[:30]}...' -> {len(ref_tokens)} tokens")
            if not match:
                print(f"        REF:  {ref_tokens}")
                print(f"        FAST: {fast_tokens}")
                all_pass = False
        
        result["test_passed"] = all_pass
        return result
    
    def run_all(self, families: Optional[List[str]] = None) -> None:
        """Run tests for all or selected families."""
        to_test = CANONICAL_REGISTRY
        if families:
            to_test = [c for c in CANONICAL_REGISTRY if c.family in families]
        
        print(f"\n{'='*80}")
        print(f"ATOM VALIDATION HARNESS")
        print(f"Testing {len(to_test)} canonical tokenizer families")
        print(f"{'='*80}")
        
        results = []
        for config in to_test:
            result = self.test_family(config)
            results.append(result)
            self.results[config.family] = result
        
        self.print_summary(results)
    
    def print_summary(self, results: List[Dict]) -> None:
        """Print final summary report."""
        print(f"\n\n{'='*80}")
        print("SUMMARY REPORT")
        print(f"{'='*80}")
        
        by_atom = defaultdict(list)
        for r in results:
            by_atom[r["expected_atom"]].append(r)
        
        print("\nBy Atom Shape:")
        for atom, rs in sorted(by_atom.items()):
            ok = sum(1 for r in rs if r["test_passed"])
            total = len(rs)
            print(f"  {atom:<20}: {ok}/{total} passed")
            for r in rs:
                status = "βœ“" if r["test_passed"] else "βœ—"
                avail = "Y" if r["config_available"] else "N"
                print(f"      [{status}] {r['family']:<20} (config={avail})")
        
        # Coverage gaps
        print("\n\nCOVERAGE GAPS:")
        uncovered = [r for r in results if not r["test_passed"] or not r["config_available"]]
        if uncovered:
            for r in uncovered:
                reason = "unavailable" if not r["config_available"] else "mismatch"
                print(f"  - {r['family']}: {reason} (expected {r['expected_atom']})")
        else:
            print("  None - all canonical families covered!")
        
        # Unique patterns count
        unique_sigs = set(r.get("signature", "unknown") for r in results if r["config_available"])
        print(f"\n\nUNIQUE SIGNATURES DETECTED: {len(unique_sigs)}")
        for sig in sorted(unique_sigs):
            families = [r["family"] for r in results if r.get("signature") == sig]
            print(f"  - {sig:<40} ({', '.join(families)})")

# ── CLI ─────────────────────────────────────────────────────────────
def main():
    parser = argparse.ArgumentParser(description="Atom Validation Harness")
    parser.add_argument("--fetch-canonical", action="store_true", help="Fetch canonical configs")
    parser.add_argument("--test-local", action="store_true", help="Test against local fast_split")
    parser.add_argument("--report", action="store_true", help="Generate coverage report")
    parser.add_argument("--families", nargs="+", help="Test only specific families")
    parser.add_argument("--cache-dir", default=".tokenizers_cache", help="Cache directory")
    
    args = parser.parse_args()
    
    harness = AtomValidationHarness(cache_dir=args.cache_dir)
    
    if args.report:
        # Just print the registry for documentation
        print("# Canonical Tokenizer Registry\n")
        for c in CANONICAL_REGISTRY:
            print(f"## {c.family}")
            print(f"- Expected atom: `{c.atom_shape}`")
            print(f"- Description: {c.description}")
            print(f"- Primary model: `{c.model_id}`")
            print(f"- Test cases: {c.test_cases}")
            print()
        return
    
    # Default: run tests
    harness.run_all(families=args.families)

if __name__ == "__main__":
    main()