aisamdasu commited on
Commit
ead2c27
·
verified ·
1 Parent(s): 4382ed7

Update tokenizer folder

Browse files
tokenizer/DATASET_USAGE.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tokenizer
2
+
3
+ ## Recommended Tokenizer
4
+
5
+ Use a byte-level BPE tokenizer with explicit FIM and metadata tokens. The
6
+ current local tokenizer uses Hugging Face `tokenizers` JSON format.
7
+
8
+ Required special tokens:
9
+
10
+ - `<|fim_prefix|>`
11
+ - `<|fim_suffix|>`
12
+ - `<|fim_middle|>`
13
+ - `<|fim_pad|>`
14
+ - `<|repo|>`
15
+ - `<|file|>`
16
+ - `<|lang|>`
17
+ - `<|endoftext|>`
18
+ - `<|pad|>`
19
+
20
+ ## Usage Rules
21
+
22
+ - Encode with `add_special_tokens=False` when the record text already contains
23
+ FIM markers.
24
+ - Decode audits with `skip_special_tokens=False`.
25
+ - Preserve indentation, tabs, newlines, comments, and Korean text.
26
+ - Do not lowercase or normalize code whitespace.
27
+ - Append EOS between JSONL records during training.
28
+
29
+ ## Quality Checks
30
+
31
+ Audit tokenizer quality with:
32
+
33
+ - Special tokens remain atomic.
34
+ - Round-trip decode has no byte loss.
35
+ - FIM markers remain visible in decoded samples.
36
+ - Code chars/token is stable across Python, Rust, C++, JavaScript, and Java.
tokenizer/README.md CHANGED
@@ -1,36 +1,160 @@
1
- # Tokenizer
2
 
3
- ## Recommended Tokenizer
4
 
5
- Use a byte-level BPE tokenizer with explicit FIM and metadata tokens. The
6
- current local tokenizer uses Hugging Face `tokenizers` JSON format.
7
 
8
- Required special tokens:
9
 
10
- - `<|fim_prefix|>`
11
- - `<|fim_suffix|>`
12
- - `<|fim_middle|>`
13
- - `<|fim_pad|>`
14
- - `<|repo|>`
15
- - `<|file|>`
16
- - `<|lang|>`
17
- - `<|endoftext|>`
18
- - `<|pad|>`
19
 
20
- ## Usage Rules
21
 
22
- - Encode with `add_special_tokens=False` when the record text already contains
23
- FIM markers.
24
- - Decode audits with `skip_special_tokens=False`.
25
- - Preserve indentation, tabs, newlines, comments, and Korean text.
26
- - Do not lowercase or normalize code whitespace.
27
- - Append EOS between JSONL records during training.
28
 
29
- ## Quality Checks
 
 
 
 
 
 
 
 
 
 
30
 
31
- Audit tokenizer quality with:
32
 
33
- - Special tokens remain atomic.
34
- - Round-trip decode has no byte loss.
35
- - FIM markers remain visible in decoded samples.
36
- - Code chars/token is stable across Python, Rust, C++, JavaScript, and Java.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BPE 토크나이저 (MoE 모델 전용)
2
 
3
+ 디렉토리는 checkpoint/curated JSONL에서 round-robin 샘플링으로 학습된 Byte-level BPE 토크나이저를 포함합니다.
4
 
5
+ ---
 
6
 
7
+ ## 파일 구성
8
 
9
+ | 파일 | 설명 |
10
+ |---|---|
11
+ | `tokenizer.json` | 학습 완료된 토크나이저 (HuggingFace `tokenizers` 포맷) |
12
+ | `train_tokenizer.py` | BPE 학습 스크립트 (재학습 시 사용) |
13
+ | `encode_demo.py` | 도메인별 인코딩·디코딩 검증 스크립트 |
14
+ | `audit_tokenizer.py` | 압축률, roundtrip, special token, context 초과율 감사 |
 
 
 
15
 
16
+ ---
17
 
18
+ ## 특수토큰 의미
 
 
 
 
 
19
 
20
+ | 토큰 | ID | 의미 |
21
+ |---|---|---|
22
+ | `<\|fim_prefix\|>` | 0 | FIM (Fill-In-the-Middle): 접두 컨텍스트 시작 마커 |
23
+ | `<\|fim_suffix\|>` | 1 | FIM: 접미 컨텍스트 시작 마커 |
24
+ | `<\|fim_middle\|>` | 2 | FIM: 모델이 생성해야 할 중간 영역 시작 마커 |
25
+ | `<\|endoftext\|>` | 3 | 텍스트 종료 마커 (문서 경계, 패킹 시 사용) |
26
+ | `<\|pad\|>` | 4 | 패딩 토큰 (배치 정렬 시 사용) |
27
+ | `<\|fim_pad\|>` | 5 | FIM 전용 padding/마스킹 확장 |
28
+ | `<\|repo\|>` | 6 | 저장소 컨텍스트 마커 |
29
+ | `<\|file\|>` | 7 | 파일 경로 컨텍스트 마커 |
30
+ | `<\|lang\|>` | 8 | 언어 컨텍스트 마커 |
31
 
32
+ 특수토큰은 vocab에서 ID 0~8을 차지하며, BPE merge 대상에서 제외됩니다.
33
 
34
+ ---
35
+
36
+ ## FIM 토큰 사용법
37
+
38
+ FIM(Fill-In-the-Middle)은 코드 중간 삽입 학습을 위한 포맷입니다. `code_fim` 도메인 데이터가 이 포맷을 사용합니다.
39
+
40
+ ```
41
+ <|fim_prefix|>접두 컨텍스트<|fim_suffix|>접미 컨텍스트<|fim_middle|>모델 생성 영역<|endoftext|>
42
+ ```
43
+
44
+ 예시:
45
+
46
+ ```python
47
+ text = "<|fim_prefix|>def add(a, b):\n <|fim_suffix|>\n return result<|fim_middle|>result = a + b<|endoftext|>"
48
+ encoded = tokenizer.encode(text)
49
+ decoded = tokenizer.decode(encoded.ids, skip_special_tokens=False) # 특수토큰 보존
50
+ ```
51
+
52
+ 주의: `tokenizer.decode()` 호출 시 반드시 `skip_special_tokens=False`를 지정해야 원문이 완벽히 복원됩니다.
53
+
54
+ ---
55
+
56
+ ## Vocab 크기 근거
57
+
58
+ | 항목 | 값 |
59
+ |---|---|
60
+ | 총 vocab 크기 | 32,000 |
61
+ | 특수토큰 예약 | 9 (ID 0~8) |
62
+ | BPE 병합 학습 토큰 | 31,991 |
63
+
64
+ **32,000으로 선택한 이유:**
65
+ - 16k는 code_fim 감사 샘플에서 2.72 chars/token 수준이라 컨텍스트 낭비가 컸다.
66
+ - 64k는 압축률은 더 좋아질 수 있지만 MoE+MTP의 vocab projection/head 파라미터가 과도하게 커진다.
67
+ - 32k는 코드 압축률과 MTP head 비용 사이의 균형점이다.
68
+ - 2026-06-11 감사 기준 5,000개 샘플에서 3.49 chars/token, roundtrip failure 0, missing special token 0.
69
+
70
+ ---
71
+
72
+ ## 도메인별 평균 토큰 통계 (1,000개 샘플 기준)
73
+
74
+ | 도메인 | 평균 토큰 수 | 평균 문자 수 | 압축률 (chars/token) |
75
+ |---|---|---|---|
76
+ | arithmetic | 16.0 | 41.0 | 2.57 |
77
+ | code_fim | 1235.3 | 4306.6 | 3.49 |
78
+ | code_gen | 87.3 | 311.6 | 3.57 |
79
+ | translation | 23.6 | 77.4 | 3.28 |
80
+
81
+ ---
82
+
83
+ ## Byte-level BPE vs Char-level BPE 비교
84
+
85
+ | 항목 | Byte-level BPE (채택) | Char-level BPE |
86
+ |---|---|---|
87
+ | 한글 처리 | 바이트 분해 후 병합 → 안전 | 직접 char 단위 → 가능 |
88
+ | 코드 심볼(`{`, `\n`, 들여쓰기) | 바이트 단위로 정확히 보존 | char 단위로 가능하나 공백 처리 복잡 |
89
+ | OOV(미지 문자) | 없음 (256 바이트로 모든 텍스트 표현) | 희귀 유니코드 문자 미포함 가능 |
90
+ | 라운드트립 보장 | 완벽 보장 (`skip_special_tokens=False`) | 완벽 보장 |
91
+ | HuggingFace `tokenizers` 호환 | `ByteLevel` pre-tokenizer 공식 지원 | `CharDelimiterSplit` 등 별도 설정 필요 |
92
+ | 참고 모델 | GPT-2, GPT-NeoX, Llama | BPE-dropout, 일부 인코더 모델 |
93
+
94
+ Byte-level BPE를 채택한 핵심 이유: 한글·코드·수식이 혼재하는 데이터에서 OOV 없이 모든 입력을 처리해야 하기 때문입니다.
95
+
96
+ ---
97
+
98
+ ## 토크나이저 재학습 방법
99
+
100
+ 데이터가 추가된 후 토크나이저를 재학습하는 명령:
101
+
102
+ ```bash
103
+ # 기본: checkpoint/curated/raw JSONL을 round-robin으로 샘플링
104
+ python3 tokenizer/train_tokenizer.py
105
+
106
+ # 현재 권장 32k 재학습
107
+ python3 tokenizer/train_tokenizer.py --vocab-size 32000 --lines-per-file 3000 --max-total-lines 180000
108
+
109
+ # 더 큰 실험용 64k. MoE+MTP head 파라미터가 크게 늘어나므로 ablation으로만 권장
110
+ python3 tokenizer/train_tokenizer.py --vocab-size 64000 --lines-per-file 5000 --max-total-lines 300000
111
+ ```
112
+
113
+ 재학습 후에는 반드시 검증을 실행하세요:
114
+
115
+ ```bash
116
+ python3 tokenizer/encode_demo.py
117
+ python3 tokenizer/audit_tokenizer.py --max-records 5000
118
+ ```
119
+
120
+ 라운드트립 결과가 `OK`인지 확인합니다.
121
+
122
+ ---
123
+
124
+ ## Python 코드에서 사용하기
125
+
126
+ ```python
127
+ from tokenizers import Tokenizer
128
+
129
+ # 로드
130
+ tokenizer = Tokenizer.from_file("tokenizer/tokenizer.json")
131
+
132
+ # 인코딩
133
+ text = "def hello():\n print('안녕')"
134
+ encoded = tokenizer.encode(text)
135
+ print(encoded.ids) # 토큰 ID 리스트
136
+ print(encoded.tokens) # 토큰 문자열 리스트
137
+
138
+ # 디코딩 (특수토큰 포함 복원)
139
+ decoded = tokenizer.decode(encoded.ids, skip_special_tokens=False)
140
+
141
+ # 배치 인코딩
142
+ texts = ["text1", "text2"]
143
+ encoded_batch = tokenizer.encode_batch(texts)
144
+
145
+ # 특수토큰 ID 조회
146
+ vocab = tokenizer.get_vocab()
147
+ pad_id = vocab["<|pad|>"] # 4
148
+ eos_id = vocab["<|endoftext|>"] # 3
149
+ fim_prefix_id = vocab["<|fim_prefix|>"] # 0
150
+ ```
151
+
152
+ ---
153
+
154
+ ## 학습 환경
155
+
156
+ - OS: macOS (Apple M4, 48GB)
157
+ - Python: 3.x
158
+ - tokenizers: 0.23.1
159
+ - 학습 데이터: `data/curated_upload/*.jsonl` 60개 파일에서 파일당 3,000개, 총 180,000 샘플
160
+ - 학습 시간: 약 30초 내외 (M4, 32k smoke 기준)
tokenizer/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff