File size: 30,402 Bytes
b3d361d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
"""
data/tokenize_extra.py β€” λŒ€μš©λŸ‰ korean_extra/ 데이터셋 병렬 토큰화

HuggingFace datasets disk 포맷(arrow), parquet, jsonl λ“± μ„Έ κ°€μ§€ 포맷을
μžλ™ κ°μ§€ν•˜μ—¬ SentencePiece ν† ν¬λ‚˜μ΄μ €λ‘œ ν† ν°ν™”ν•˜κ³ , κ²°κ³Όλ₯Ό uint16 memmap
(.bin) 파일둜 μ €μž₯ν•œλ‹€.  881 GB μ΄μƒμ˜ λŒ€μš©λŸ‰ 데이터도 슀트리밍·청크 λ°©μ‹μœΌλ‘œ
μ²˜λ¦¬ν•œλ‹€.

좜λ ₯ 포맷은 data/dataset.py PackedDataset / TextDataset κ³Ό μ™„μ „νžˆ ν˜Έν™˜λ˜λŠ”
numpy uint16 ν”Œλž« 배열이닀.

μ‚¬μš© μ˜ˆμ‹œ:
    # 단일 디렉토리
    python data/tokenize_extra.py \
        --input_dir data/korean_extra/fineweb2_edu_ko \
        --output    data/fineweb2_train.bin \
        --num_proc  8

    # korean_extra/ 전체 μ„œλΈŒλ””λ ‰ν† λ¦¬ 일괄 처리
    python data/tokenize_extra.py \
        --input_dir data/korean_extra \
        --auto_scan \
        --output_dir data \
        --num_proc 8

    # 곡개 검증
    python -c "
    import numpy as np
    d = np.memmap('data/fineweb2_train.bin', dtype='uint16', mode='r')
    print(f'총 토큰: {len(d):,}')
    "
"""

from __future__ import annotations

import argparse
import json
import math
import multiprocessing as mp
import os
import struct
import sys
import time
from pathlib import Path
from typing import Generator, Iterable, Iterator

import numpy as np
from tqdm import tqdm

# ---------------------------------------------------------------------------
# SentencePiece μž„ν¬νŠΈ (선택적 β€” μ—†μœΌλ©΄ 였λ₯˜ λ©”μ‹œμ§€ 좜λ ₯ ν›„ μ’…λ£Œ)
# ---------------------------------------------------------------------------
try:
    import sentencepiece as spm
except ImportError:
    print(
        "ERROR: sentencepiece νŒ¨ν‚€μ§€κ°€ μ„€μΉ˜λ˜μ–΄ μžˆμ§€ μ•ŠμŠ΅λ‹ˆλ‹€.\n"
        "       pip install sentencepiece  둜 μ„€μΉ˜ ν›„ μž¬μ‹€ν–‰ν•˜μ„Έμš”.",
        file=sys.stderr,
    )
    sys.exit(1)

# ---------------------------------------------------------------------------
# datasets μž„ν¬νŠΈ
# ---------------------------------------------------------------------------
try:
    import datasets as hf_datasets
except ImportError:
    print(
        "ERROR: datasets νŒ¨ν‚€μ§€κ°€ μ„€μΉ˜λ˜μ–΄ μžˆμ§€ μ•ŠμŠ΅λ‹ˆλ‹€.\n"
        "       pip install datasets  둜 μ„€μΉ˜ ν›„ μž¬μ‹€ν–‰ν•˜μ„Έμš”.",
        file=sys.stderr,
    )
    sys.exit(1)


# ===========================================================================
# μƒμˆ˜
# ===========================================================================

UINT16_MAX      = 65535           # uint16 μ˜€λ²„ν”Œλ‘œ 경계
MIN_TOKENS      = 100             # μ΅œμ†Œ 토큰 수 (미만이면 버림)
MAX_TOKENS      = 32_768          # μ΅œλŒ€ 토큰 수 (μ΄ˆκ³ΌλΆ„μ€ 버림)
HANGUL_RE_THRESHOLD = 0.10        # ν•œκΈ€ λΉ„μœ¨ μ΅œμ†Œ κΈ°μ€€ (이 미만이고 ν•œκΈ€ μ•„λ‹Œ 경우 버림)
CHUNK_TOKENS    = 500_000         # memmap 청크 λ‹¨μœ„ (tokens)
EOS_TOKEN_PLACEHOLDER = 1         # EOS id β€” SP κΈ°λ³Έκ°’, μ‹€μ œ idλŠ” λͺ¨λΈμ—μ„œ 읽음

# ---------------------------------------------------------------------------
# ν•œκΈ€ λΉ„μœ¨ ν•„ν„°
# ---------------------------------------------------------------------------
# ord λ²”μœ„: κ°€(AC00) ~ 힣(D7A3), γ„±(3131) ~ γ…£(3163)
_HANGUL_START = 0xAC00
_HANGUL_END   = 0xD7A3


def _has_enough_korean_or_english(text: str) -> bool:
    """
    ν•œκΈ€ 문자 λΉ„μœ¨μ΄ HANGUL_RE_THRESHOLD μ΄μƒμ΄κ±°λ‚˜,
    ASCII μ•ŒνŒŒλ²³ λΉ„μœ¨μ΄ 0.3 이상이면 True λ°˜ν™˜.
    λ‘˜ λ‹€ μ•„λ‹Œ 경우 False (쀑ꡭ어, μΌλ³Έμ–΄λ§Œ μžˆλŠ” λ“±).
    """
    if not text:
        return False
    total = len(text)
    hangul_cnt = sum(1 for ch in text if _HANGUL_START <= ord(ch) <= _HANGUL_END)
    if hangul_cnt / total >= HANGUL_RE_THRESHOLD:
        return True
    ascii_alpha = sum(1 for ch in text if ch.isascii() and ch.isalpha())
    if ascii_alpha / total >= 0.30:
        return True
    return False


# ===========================================================================
# ν† ν¬λ‚˜μ΄μ € 래퍼 (ν”„λ‘œμ„ΈμŠ€ κ°„ 곡유 λΆˆκ°€ β€” 각 μ›Œμ»€μ—μ„œ reload)
# ===========================================================================

class SPTokenizer:
    """SentencePiece λͺ¨λΈμ„ wrappingν•œ κ°„λ‹¨ν•œ ν† ν¬λ‚˜μ΄μ €."""

    def __init__(self, model_path: str) -> None:
        self._model_path = model_path
        self._sp: spm.SentencePieceProcessor | None = None

    # ν”„λ‘œμ„ΈμŠ€ fork ν›„ _spκ°€ None인 경우 lazy load
    def _ensure_loaded(self) -> None:
        if self._sp is None:
            sp = spm.SentencePieceProcessor()
            sp.Load(self._model_path)
            self._sp = sp

    @property
    def eos_id(self) -> int:
        self._ensure_loaded()
        return self._sp.eos_id()

    @property
    def vocab_size(self) -> int:
        self._ensure_loaded()
        return self._sp.GetPieceSize()

    def encode(self, text: str) -> list[int]:
        self._ensure_loaded()
        return self._sp.EncodeAsIds(text)


# ===========================================================================
# 포맷 감지 & μ΄ν„°λ ˆμ΄ν„°
# ===========================================================================

def _detect_format(input_dir: Path) -> str:
    """
    디렉토리 λ‚΄μš©μ„ 보고 포맷을 μžλ™ κ°μ§€ν•œλ‹€.

    λ°˜ν™˜κ°’:
        "hf_arrow"  β€” HuggingFace datasets disk 포맷 (dataset_info.json 쑴재)
        "parquet"   β€” .parquet 파일이 있음
        "jsonl"     β€” .jsonl λ˜λŠ” .json 파일이 있음
        "unknown"   β€” μ•Œ 수 μ—†μŒ
    """
    if not input_dir.is_dir():
        raise NotADirectoryError(f"μž…λ ₯ κ²½λ‘œκ°€ 디렉토리가 μ•„λ‹™λ‹ˆλ‹€: {input_dir}")

    # HF arrow 포맷 νŒλ³„ β€” dataset_info.json λ˜λŠ” state.json이 있으면 HF 포맷
    if (input_dir / "dataset_info.json").exists():
        return "hf_arrow"
    if (input_dir / "state.json").exists():
        return "hf_arrow"
    # μ„œλΈŒ 디렉토리 μ•ˆμ— dataset_info.json이 μžˆλŠ” 경우 (split 포함)
    for child in input_dir.iterdir():
        if child.is_dir() and (child / "dataset_info.json").exists():
            return "hf_arrow"

    # parquet 파일 확인
    parquets = list(input_dir.rglob("*.parquet"))
    if parquets:
        return "parquet"

    # jsonl / json 파일 확인
    jsonls = list(input_dir.rglob("*.jsonl")) + list(input_dir.rglob("*.json"))
    if jsonls:
        return "jsonl"

    return "unknown"


def _iter_hf_arrow(
    input_dir: Path,
    text_col: str,
    num_proc: int,
) -> Iterator[str]:
    """HuggingFace datasets disk ν¬λ§·μ—μ„œ ν…μŠ€νŠΈλ₯Ό μŠ€νŠΈλ¦¬λ°ν•œλ‹€."""
    print(f"  [포맷] HuggingFace arrow (disk): {input_dir}")
    try:
        ds = hf_datasets.load_from_disk(str(input_dir))
    except Exception as exc:
        # DatasetDict일 수 있음 β€” 'train' split μ‹œλ„
        try:
            ds_dict = hf_datasets.load_from_disk(str(input_dir))
            if isinstance(ds_dict, hf_datasets.DatasetDict):
                splits = list(ds_dict.keys())
                print(f"  DatasetDict 감지. splits={splits}, 'train' split μ‚¬μš©.")
                ds = ds_dict.get("train", ds_dict[splits[0]])
            else:
                raise exc
        except Exception:
            raise RuntimeError(
                f"HF arrow 포맷 λ‘œλ“œ μ‹€νŒ¨: {input_dir}\n원인: {exc}"
            ) from exc

    # μ‹€μ œ ν…μŠ€νŠΈ 컬럼 이름 μΆ”μ •
    col = _resolve_text_col(list(ds.column_names), text_col)
    print(f"  ν…μŠ€νŠΈ 컬럼: '{col}', 총 ν–‰ 수: {len(ds):,}")

    for row in ds:
        yield row[col]


def _iter_parquet(input_dir: Path, text_col: str) -> Iterator[str]:
    """parquet νŒŒμΌμ—μ„œ ν…μŠ€νŠΈλ₯Ό μŠ€νŠΈλ¦¬λ°ν•œλ‹€."""
    try:
        import pyarrow.parquet as pq  # type: ignore
    except ImportError:
        # datasets둜 fallback
        print("  [κ²½κ³ ] pyarrow λ―Έμ„€μΉ˜, datasets둜 parquet λ‘œλ“œ μ‹œλ„...")
        files = sorted(input_dir.rglob("*.parquet"))
        print(f"  [포맷] parquet ({len(files)} 파일): {input_dir}")
        ds = hf_datasets.load_dataset(
            "parquet",
            data_files={"train": [str(f) for f in files]},
            split="train",
            streaming=True,
        )
        col = _resolve_text_col(list(ds.column_names), text_col)
        print(f"  ν…μŠ€νŠΈ 컬럼: '{col}'")
        for row in ds:
            yield row[col]
        return

    files = sorted(input_dir.rglob("*.parquet"))
    print(f"  [포맷] parquet ({len(files)} 파일): {input_dir}")
    for fpath in files:
        pf = pq.ParquetFile(str(fpath))
        cols = pf.schema_arrow.names
        col = _resolve_text_col(cols, text_col)
        for batch in pf.iter_batches(batch_size=1000, columns=[col]):
            for val in batch.column(col):
                yield val.as_py() or ""


def _iter_jsonl(input_dir: Path, text_col: str) -> Iterator[str]:
    """jsonl / json νŒŒμΌμ—μ„œ ν…μŠ€νŠΈλ₯Ό μŠ€νŠΈλ¦¬λ°ν•œλ‹€."""
    files = sorted(input_dir.rglob("*.jsonl")) + sorted(input_dir.rglob("*.json"))
    # json 파일 쀑 jsonl이 μ•„λ‹Œ 것 제거 (파일 μžμ²΄κ°€ dict인 경우)
    print(f"  [포맷] jsonl ({len(files)} 파일): {input_dir}")
    for fpath in files:
        try:
            with open(fpath, "r", encoding="utf-8", errors="replace") as fh:
                for line in fh:
                    line = line.strip()
                    if not line:
                        continue
                    try:
                        obj = json.loads(line)
                    except json.JSONDecodeError:
                        continue
                    if isinstance(obj, str):
                        yield obj
                    elif isinstance(obj, dict):
                        text = (
                            obj.get(text_col)
                            or obj.get("text")
                            or obj.get("content")
                            or obj.get("document")
                            or ""
                        )
                        yield str(text)
        except Exception as exc:
            print(f"  [κ²½κ³ ] 파일 읽기 μ‹€νŒ¨: {fpath} β€” {exc}", file=sys.stderr)


def _resolve_text_col(columns: list[str], preferred: str) -> str:
    """
    μ§€μ •λœ 컬럼이 없을 경우, 일반적인 ν…μŠ€νŠΈ 컬럼 이름을 μˆœμ„œλŒ€λ‘œ νƒμƒ‰ν•œλ‹€.
    """
    if preferred in columns:
        return preferred
    for candidate in ("text", "content", "document", "body", "passage"):
        if candidate in columns:
            print(
                f"  [INFO] 컬럼 '{preferred}' 미쑴재 β†’ '{candidate}' μ‚¬μš©. "
                f"(전체 컬럼: {columns[:10]})"
            )
            return candidate
    # λ§ˆμ§€λ§‰ μˆ˜λ‹¨: 첫 번째 λ¬Έμžμ—΄ 컬럼
    print(
        f"  [κ²½κ³ ] ν…μŠ€νŠΈ μ»¬λŸΌμ„ μ°Ύμ§€ λͺ»ν•¨. 첫 번째 컬럼 '{columns[0]}' μ‚¬μš©.",
        file=sys.stderr,
    )
    return columns[0]


def get_text_iterator(
    input_dir: Path,
    text_col: str,
    num_proc: int,
) -> tuple[str, Iterator[str]]:
    """
    포맷을 μžλ™ κ°μ§€ν•˜κ³  μ•Œλ§žμ€ ν…μŠ€νŠΈ μ΄ν„°λ ˆμ΄ν„°λ₯Ό λ°˜ν™˜ν•œλ‹€.

    Returns:
        (fmt, iterator)  fmt은 κ°μ§€λœ 포맷 λ¬Έμžμ—΄
    """
    fmt = _detect_format(input_dir)
    if fmt == "hf_arrow":
        return fmt, _iter_hf_arrow(input_dir, text_col, num_proc)
    elif fmt == "parquet":
        return fmt, _iter_parquet(input_dir, text_col)
    elif fmt == "jsonl":
        return fmt, _iter_jsonl(input_dir, text_col)
    else:
        raise RuntimeError(
            f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” ν¬λ§·μ΄κ±°λ‚˜ 인식할 수 μ—†μŠ΅λ‹ˆλ‹€: {input_dir}\n"
            f"지원 포맷: HuggingFace arrow, parquet, jsonl"
        )


# ===========================================================================
# 단일 ν”„λ‘œμ„ΈμŠ€ 토큰화 μ›Œμ»€ (multiprocessing.Poolμ—μ„œ 호좜)
# ===========================================================================

# μ „μ—­ ν† ν¬λ‚˜μ΄μ € β€” 각 μ›Œμ»€ ν”„λ‘œμ„ΈμŠ€μ—μ„œ ν•œ 번만 μ΄ˆκΈ°ν™”
_g_sp: SPTokenizer | None = None
_g_model_path: str = ""


def _worker_init(model_path: str) -> None:
    """μ›Œμ»€ μ΄ˆκΈ°ν™” ν•¨μˆ˜: SentencePiece λͺ¨λΈ λ‘œλ“œ."""
    global _g_sp, _g_model_path
    _g_model_path = model_path
    _g_sp = SPTokenizer(model_path)
    _g_sp._ensure_loaded()


def _worker_tokenize_batch(texts: list[str]) -> list[list[int]]:
    """
    ν…μŠ€νŠΈ 배치λ₯Ό ν† ν°ν™”ν•˜κ³  ν’ˆμ§ˆ ν•„ν„°λ₯Ό μ μš©ν•œλ‹€.

    λ°˜ν™˜κ°’: μœ νš¨ν•œ 토큰 리슀트 λͺ©λ‘ (ν•„ν„° ν†΅κ³Όν•œ κ²ƒλ§Œ)
    """
    global _g_sp
    results: list[list[int]] = []
    for text in texts:
        if not text or not isinstance(text, str):
            continue
        # ν’ˆμ§ˆ ν•„ν„°: μ–Έμ–΄
        if not _has_enough_korean_or_english(text):
            continue
        try:
            ids = _g_sp.encode(text)
        except Exception:
            continue
        # 길이 ν•„ν„°
        if len(ids) < MIN_TOKENS:
            continue
        if len(ids) > MAX_TOKENS:
            ids = ids[:MAX_TOKENS]
        results.append(ids)
    return results


# ===========================================================================
# memmap 청크 기반 기둝기
# ===========================================================================

class MemmapWriter:
    """
    uint16 numpy memmap νŒŒμΌμ— 토큰을 청크 λ‹¨μœ„λ‘œ κΈ°λ‘ν•˜λŠ” 래퍼.

    μ΄ˆκΈ°μ— μž‘μ€ 크기둜 μƒμ„±ν•˜κ³ , ν•„μš”ν•  λ•Œ resizeν•œλ‹€.
    μ΅œμ’…μ μœΌλ‘œ μ‹€μ œ 기둝된 크기둜 truncateν•˜μ—¬ μ €μž₯ν•œλ‹€.
    """

    def __init__(self, path: Path, initial_size: int = CHUNK_TOKENS) -> None:
        self.path = path
        path.parent.mkdir(parents=True, exist_ok=True)
        self._alloc = max(initial_size, CHUNK_TOKENS)
        self._mm = np.memmap(
            str(path), dtype="uint16", mode="w+", shape=(self._alloc,)
        )
        self._pos = 0

    def write(self, tokens: Iterable[int]) -> int:
        """tokensλ₯Ό κΈ°λ‘ν•˜κ³  기둝된 토큰 수λ₯Ό λ°˜ν™˜ν•œλ‹€."""
        arr = np.asarray(list(tokens), dtype=np.uint16)
        n = len(arr)
        if n == 0:
            return 0
        needed = self._pos + n
        if needed > self._alloc:
            # 두 λ°° λ˜λŠ” ν•„μš”ν•œ 크기 쀑 큰 κ°’μœΌλ‘œ ν™•μž₯
            new_alloc = max(self._alloc * 2, needed + CHUNK_TOKENS)
            self._mm.flush()
            del self._mm
            self._alloc = new_alloc
            self._mm = np.memmap(
                str(self.path), dtype="uint16", mode="r+", shape=(self._alloc,)
            )
        self._mm[self._pos : self._pos + n] = arr
        self._pos += n
        return n

    def finalize(self) -> int:
        """기둝된 μ‹€μ œ 크기둜 νŒŒμΌμ„ truncateν•˜κ³  λ‹«λŠ”λ‹€. 총 토큰 수λ₯Ό λ°˜ν™˜ν•œλ‹€."""
        self._mm.flush()
        del self._mm
        # μ‹€μ œ 기둝된 크기둜 truncate
        final_bytes = self._pos * 2  # uint16 = 2 bytes
        with open(str(self.path), "r+b") as fh:
            fh.truncate(final_bytes)
        return self._pos


# ===========================================================================
# 핡심 토큰화 νŒŒμ΄ν”„λΌμΈ
# ===========================================================================

def tokenize_directory(
    input_dir: Path,
    output_path: Path,
    tokenizer_path: str,
    text_col: str = "text",
    num_proc: int = 8,
    batch_size: int = 512,
    eos_between_docs: bool = True,
    val_split: float = 0.002,
    seed: int = 42,
) -> dict:
    """
    단일 디렉토리λ₯Ό ν† ν°ν™”ν•˜μ—¬ .bin 파일(λ“€)둜 μ €μž₯ν•œλ‹€.

    Args:
        input_dir:       μž…λ ₯ 디렉토리 (포맷 μžλ™ 감지)
        output_path:     좜λ ₯ .bin 파일 경둜 (ν›ˆλ ¨ μ…‹)
        tokenizer_path:  SentencePiece .model 파일 경둜
        text_col:        ν…μŠ€νŠΈ 컬럼 이름 (arrow/parquetμ—μ„œ μ‚¬μš©)
        num_proc:        병렬 μ›Œμ»€ 수
        batch_size:      μ›Œμ»€λ‹Ή 배치 크기
        eos_between_docs: λ¬Έμ„œ 사이에 EOS 토큰 μ‚½μž… μ—¬λΆ€
        val_split:       검증 뢄리 λΉ„μœ¨ (0 이면 val 파일 생성 μ•ˆ 함)
        seed:            μž¬ν˜„μ„± μ‹œλ“œ

    Returns:
        톡계 dict (total_tokens, train_tokens, val_tokens, skipped, elapsed_s)
    """
    t_start = time.time()

    # ─── ν† ν¬λ‚˜μ΄μ € λ‘œλ“œ (메인 ν”„λ‘œμ„ΈμŠ€: EOS id 확인) ─────────────────────
    sp_main = SPTokenizer(tokenizer_path)
    eos_id = sp_main.eos_id
    vocab_size = sp_main.vocab_size
    print(f"  ν† ν¬λ‚˜μ΄μ €: {tokenizer_path}")
    print(f"  vocab_size={vocab_size:,}, eos_id={eos_id}")
    if vocab_size > UINT16_MAX:
        print(
            f"  [κ²½κ³ ] vocab_size({vocab_size}) > {UINT16_MAX} "
            f"β€” uint16 μ˜€λ²„ν”Œλ‘œ κ°€λŠ₯. 65535 μ΄ν•˜ id만 μ•ˆμ „.",
            file=sys.stderr,
        )

    # ─── 포맷 감지 & μ΄ν„°λ ˆμ΄ν„° 생성 ─────────────────────────────────────
    fmt, text_iter = get_text_iterator(input_dir, text_col, num_proc)
    print(f"  포맷: {fmt}")

    # ─── 좜λ ₯ 경둜 μ„€μ • ────────────────────────────────────────────────────
    train_path = output_path
    val_path: Path | None = None
    if val_split > 0:
        stem = output_path.stem
        if "train" in stem:
            val_path = output_path.parent / output_path.name.replace("train", "val")
        else:
            val_path = output_path.with_name(stem + "_val" + output_path.suffix)

    print(f"  좜λ ₯(train): {train_path}")
    if val_path:
        print(f"  좜λ ₯(val):   {val_path}")

    # ─── memmap 기둝기 μ΄ˆκΈ°ν™” ─────────────────────────────────────────────
    writer = MemmapWriter(train_path)
    val_writer: MemmapWriter | None = MemmapWriter(val_path) if val_path else None

    # ─── multiprocessing Pool 생성 ────────────────────────────────────────
    pool = mp.Pool(
        processes=num_proc,
        initializer=_worker_init,
        initargs=(tokenizer_path,),
    )

    total_docs = 0
    skipped    = 0
    total_toks = 0

    # numpy rng for deterministic val split
    rng = np.random.default_rng(seed)

    def _submit_batch(batch_texts: list[str]) -> None:
        nonlocal total_docs, skipped, total_toks
        # 동기 map (배치 λ‹¨μœ„, μ›Œμ»€λ³„ μ„œλΈŒλ°°μΉ˜λ‘œ λΆ„ν• )
        sub_size = max(1, len(batch_texts) // num_proc)
        sub_batches = [
            batch_texts[i : i + sub_size]
            for i in range(0, len(batch_texts), sub_size)
        ]
        results_list = pool.map(_worker_tokenize_batch, sub_batches)

        for results in results_list:
            for ids in results:
                total_docs += 1
                n = len(ids)
                total_toks += n
                # EOS 토큰 μ‚½μž…
                if eos_between_docs:
                    ids_out = ids + [eos_id]
                else:
                    ids_out = ids

                # val split: λ¬΄μž‘μœ„λ‘œ val_split λΉ„μœ¨λ§ŒνΌ val 파일둜
                if val_writer is not None and rng.random() < val_split:
                    val_writer.write(ids_out)
                else:
                    writer.write(ids_out)

            skipped_in_batch = sum(1 for _ in results) - len(results)

    # ─── 배치 μˆ˜μ§‘ & tqdm μ§„ν–‰λ₯  ─────────────────────────────────────────
    batch_buf: list[str] = []
    pbar = tqdm(desc=f"토큰화 [{input_dir.name}]", unit="doc", dynamic_ncols=True)

    for text in text_iter:
        batch_buf.append(text)
        if len(batch_buf) >= batch_size * num_proc:
            _submit_batch(batch_buf)
            pbar.update(len(batch_buf))
            pbar.set_postfix(
                tokens=f"{total_toks:,}",
                docs=f"{total_docs:,}",
                refresh=False,
            )
            batch_buf = []

    # λ§ˆμ§€λ§‰ μž”μ—¬ 배치 처리
    if batch_buf:
        _submit_batch(batch_buf)
        pbar.update(len(batch_buf))

    pbar.close()
    pool.close()
    pool.join()

    # ─── 파일 마무리 ──────────────────────────────────────────────────────
    train_tokens = writer.finalize()
    val_tokens   = val_writer.finalize() if val_writer else 0

    elapsed = time.time() - t_start
    total_toks_with_eos = train_tokens + val_tokens

    print()
    print(f"  μ™„λ£Œ: {elapsed:.1f}초")
    print(f"  처리 λ¬Έμ„œ: {total_docs:,}")
    print(f"  총 토큰(EOS 포함): {total_toks_with_eos:,}")
    print(f"    train: {train_tokens:,}  ({train_tokens*2/1e9:.2f} GB)")
    if val_tokens:
        print(f"    val:   {val_tokens:,}  ({val_tokens*2/1e9:.2f} GB)")
    throughput = total_toks_with_eos / elapsed if elapsed > 0 else 0
    print(f"  처리율: {throughput/1e6:.2f} M token/s")

    return {
        "total_docs"   : total_docs,
        "total_tokens" : total_toks_with_eos,
        "train_tokens" : train_tokens,
        "val_tokens"   : val_tokens,
        "elapsed_s"    : elapsed,
        "train_path"   : str(train_path),
        "val_path"     : str(val_path) if val_path else None,
    }


# ===========================================================================
# μ„œλΈŒλ””λ ‰ν† λ¦¬ μžλ™ μŠ€μΊ” λͺ¨λ“œ
# ===========================================================================

def auto_scan_and_tokenize(
    root_dir: Path,
    output_dir: Path,
    tokenizer_path: str,
    text_col: str,
    num_proc: int,
    batch_size: int,
    val_split: float,
    seed: int,
) -> list[dict]:
    """
    root_dir 의 직접 μžμ‹ 디렉토리λ₯Ό μŠ€μΊ”ν•˜μ—¬ 각각 ν† ν°ν™”ν•œλ‹€.

    각 μ„œλΈŒλ””λ ‰ν† λ¦¬μ— λŒ€ν•΄:
        output_dir/korean_extra_{subdir_name}_train.bin 을 μƒμ„±ν•œλ‹€.
    """
    children = sorted(p for p in root_dir.iterdir() if p.is_dir())
    if not children:
        raise RuntimeError(f"μ„œλΈŒλ””λ ‰ν† λ¦¬κ°€ μ—†μŠ΅λ‹ˆλ‹€: {root_dir}")

    print(f"μžλ™ μŠ€μΊ”: {len(children)}개 μ„œλΈŒλ””λ ‰ν† λ¦¬ 발견")
    for ch in children:
        print(f"  - {ch.name}")
    print()

    all_stats = []
    for child in children:
        print("=" * 60)
        print(f"처리 쀑: {child}")
        print("=" * 60)
        safe_name = child.name.replace("/", "_").replace(" ", "_")
        out_name  = f"korean_extra_{safe_name}_train.bin"
        out_path  = output_dir / out_name
        try:
            stats = tokenize_directory(
                input_dir      = child,
                output_path    = out_path,
                tokenizer_path = tokenizer_path,
                text_col       = text_col,
                num_proc       = num_proc,
                batch_size     = batch_size,
                val_split      = val_split,
                seed           = seed,
            )
            stats["source"] = child.name
            all_stats.append(stats)
        except Exception as exc:
            print(f"  [였λ₯˜] {child.name} 처리 μ‹€νŒ¨: {exc}", file=sys.stderr)
            all_stats.append({"source": child.name, "error": str(exc)})
        print()

    return all_stats


# ===========================================================================
# CLI
# ===========================================================================

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "korean_extra/ λŒ€μš©λŸ‰ 데이터셋을 병렬 ν† ν°ν™”ν•˜μ—¬ uint16 memmap(.bin) 둜 μ €μž₯. "
            "HuggingFace arrow, parquet, jsonl 포맷 μžλ™ 감지."
        ),
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    # μž…λ ₯
    parser.add_argument(
        "--input_dir",
        required=True,
        help="토큰화할 디렉토리 경둜. --auto_scan μ‹œμ—λŠ” 루트 디렉토리.",
    )
    parser.add_argument(
        "--auto_scan",
        action="store_true",
        help=(
            "input_dir 의 직접 μžμ‹ 디렉토리λ₯Ό λͺ¨λ‘ 순차 처리. "
            "이 경우 --output_dir 을 μ§€μ •ν•΄μ•Ό 함."
        ),
    )
    parser.add_argument(
        "--text_col",
        default="text",
        help="ν…μŠ€νŠΈ 컬럼 이름 (arrow/parquet/jsonl). μžλ™ μΆ”μ • κ°€λŠ₯.",
    )

    # 좜λ ₯
    out_group = parser.add_mutually_exclusive_group()
    out_group.add_argument(
        "--output",
        default=None,
        help="좜λ ₯ .bin 파일 경둜 (단일 디렉토리 처리 μ‹œ μ‚¬μš©).",
    )
    out_group.add_argument(
        "--output_dir",
        default=None,
        help="좜λ ₯ .bin νŒŒμΌλ“€μ„ μ €μž₯ν•  디렉토리 (--auto_scan μ‹œ μ‚¬μš©).",
    )

    # ν† ν¬λ‚˜μ΄μ €
    parser.add_argument(
        "--tokenizer",
        default=(
            "/PROJECT/0325120031_A/ghong/taketimes/llm-bang"
            "/tokenizer/korean_64k.model"
        ),
        help="SentencePiece .model 파일 경둜.",
    )

    # 처리 μ˜΅μ…˜
    parser.add_argument(
        "--num_proc",
        type=int,
        default=8,
        help="병렬 μ›Œμ»€ 수 (multiprocessing.Pool).",
    )
    parser.add_argument(
        "--batch_size",
        type=int,
        default=512,
        help="μ›Œμ»€λ‹Ή 배치 크기 (λ¬Έμ„œ 수).",
    )
    parser.add_argument(
        "--val_split",
        type=float,
        default=0.002,
        help="검증 뢄리 λΉ„μœ¨ (0.0 이면 val 파일 미생성).",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=42,
        help="μž¬ν˜„μ„± μ‹œλ“œ.",
    )
    parser.add_argument(
        "--no_eos",
        action="store_true",
        help="λ¬Έμ„œ 사이에 EOS 토큰을 μ‚½μž…ν•˜μ§€ μ•ŠλŠ”λ‹€.",
    )

    args = parser.parse_args()

    # 검증
    if not args.auto_scan and args.output is None:
        # μžλ™ 좜λ ₯ 경둜 생성
        input_name = Path(args.input_dir).name
        args.output = str(
            Path(args.input_dir).parent.parent
            / f"korean_extra_{input_name}_train.bin"
        )
        print(f"[INFO] --output λ―Έμ§€μ • β†’ μžλ™ μ„€μ •: {args.output}")

    if args.auto_scan and args.output_dir is None:
        parser.error("--auto_scan μ‚¬μš© μ‹œ --output_dir 을 μ§€μ •ν•΄μ•Ό ν•©λ‹ˆλ‹€.")

    return args


def main() -> None:
    args = parse_args()

    tokenizer_path = args.tokenizer
    if not Path(tokenizer_path).exists():
        # fallback: μƒλŒ€κ²½λ‘œ μ‹œλ„
        fallback = Path(
            "/PROJECT/0325120031_A/ghong/taketimes/llm-bang"
            "/tokenizer/korean_64k.model"
        )
        if fallback.exists():
            tokenizer_path = str(fallback)
        else:
            print(
                f"ERROR: ν† ν¬λ‚˜μ΄μ € νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€: {tokenizer_path}",
                file=sys.stderr,
            )
            sys.exit(1)

    print("=" * 60)
    print(" LLM-Bang tokenize_extra.py")
    print("=" * 60)
    print(f"  μž…λ ₯:        {args.input_dir}")
    print(f"  ν† ν¬λ‚˜μ΄μ €:  {tokenizer_path}")
    print(f"  num_proc:    {args.num_proc}")
    print(f"  batch_size:  {args.batch_size}")
    print(f"  val_split:   {args.val_split}")
    print(f"  seed:        {args.seed}")
    print(f"  eos:         {not args.no_eos}")
    print()

    if args.auto_scan:
        stats_list = auto_scan_and_tokenize(
            root_dir       = Path(args.input_dir),
            output_dir     = Path(args.output_dir),
            tokenizer_path = tokenizer_path,
            text_col       = args.text_col,
            num_proc       = args.num_proc,
            batch_size     = args.batch_size,
            val_split      = args.val_split,
            seed           = args.seed,
        )
        print("=" * 60)
        print(" 전체 μš”μ•½")
        print("=" * 60)
        grand_train = 0
        grand_val   = 0
        for s in stats_list:
            if "error" in s:
                print(f"  {s['source']:40s} ERROR: {s['error']}")
            else:
                t = s.get("train_tokens", 0)
                v = s.get("val_tokens", 0)
                grand_train += t
                grand_val   += v
                print(
                    f"  {s['source']:40s} "
                    f"train={t:>14,}  val={v:>12,}  "
                    f"({s['elapsed_s']:.0f}s)"
                )
        print("-" * 60)
        print(
            f"  {'합계':40s} "
            f"train={grand_train:>14,}  val={grand_val:>12,}"
        )
        print(
            f"\n  총 토큰: {grand_train + grand_val:,}  "
            f"({(grand_train + grand_val) * 2 / 1e9:.2f} GB)"
        )

    else:
        stats = tokenize_directory(
            input_dir      = Path(args.input_dir),
            output_path    = Path(args.output),
            tokenizer_path = tokenizer_path,
            text_col       = args.text_col,
            num_proc       = args.num_proc,
            batch_size     = args.batch_size,
            eos_between_docs = not args.no_eos,
            val_split      = args.val_split,
            seed           = args.seed,
        )
        print()
        print("=" * 60)
        print(" κ²°κ³Ό μš”μ•½")
        print("=" * 60)
        print(f"  train .bin : {stats['train_path']}")
        if stats.get("val_path"):
            print(f"  val .bin   : {stats['val_path']}")
        print(f"  train 토큰 : {stats['train_tokens']:,}")
        print(f"  val 토큰   : {stats['val_tokens']:,}")
        print(f"  처리 λ¬Έμ„œ  : {stats['total_docs']:,}")
        print(f"  μ†Œμš” μ‹œκ°„  : {stats['elapsed_s']:.1f}초")

        # 검증: memmap λ‘œλ“œ ν…ŒμŠ€νŠΈ
        print()
        print("  [검증] memmap λ‘œλ“œ ν…ŒμŠ€νŠΈ...")
        try:
            d = np.memmap(stats["train_path"], dtype="uint16", mode="r")
            print(f"  memmap shape: {d.shape}  dtype: {d.dtype}")
            print(f"  첫 10 토큰: {d[:10].tolist()}")
        except Exception as exc:
            print(f"  [κ²½κ³ ] memmap λ‘œλ“œ μ‹€νŒ¨: {exc}", file=sys.stderr)


if __name__ == "__main__":
    main()