File size: 16,444 Bytes
7a088d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read-only efficiency audit of frozen vocabulary and source/work-balanced text samples."""
import argparse
import collections
import hashlib
import json
import math
from pathlib import Path
import sqlite3
import time
import unicodedata

from sentencepiece_unigram import Tokenizer

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / 'unified/training-tokens-v1/build-006'
MODEL = ROOT / 'runs/classical-smollm2-trunk/export/tokenizer.model'


def sha(path):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        for b in iter(lambda: f.read(1 << 20), b''):
            h.update(b)
    return h.hexdigest()


def write(path, value):
    Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n')


def rank(value):
    return hashlib.sha256(('efficiency-20261027:' + value).encode()).hexdigest()


def category(text):
    if text.isspace():
        return 'whitespace'
    if all(unicodedata.category(c)[0] in 'PS' for c in text):
        return 'punctuation_symbols'
    if all(('\u3400' <= c <= '\u9fff') or ('\U00020000' <= c <= '\U000323af') or ('\uf900' <= c <= '\ufaff') for c in text):
        return 'kanji_only'
    if all('\u3040' <= c <= '\u30ff' for c in text):
        return 'kana_only'
    if any('\u3040' <= c <= '\u30ff' for c in text):
        return 'contains_kana_mixed'
    return 'other'


class MinimumTokens:
    """Exact shortest reversible token sequence with current regular/byte pieces.

    This is a compression bound, not the probability-optimal Unigram objective.
    Whitespace uses the model's existing identity normalizer and U+2581 rule.
    """
    def __init__(self, tokenizer):
        self.tokenizer = tokenizer
        self.trie = {}
        sp = tokenizer.sp
        self.byte_ids = [sp.piece_to_id(f'<0x{i:02X}>') for i in range(256)]
        for i in range(sp.vocab_size()):
            if sp.is_byte(i) or sp.is_control(i) or sp.is_unknown(i) or sp.is_unused(i):
                continue
            surface = sp.id_to_piece(i).replace('▁', ' ')
            if not surface:
                continue
            node = self.trie
            for c in surface:
                node = node.setdefault(c, {})
            node[None] = i

    def encode(self, text):
        n = len(text)
        costs = [10**9] * (n + 1)
        previous = [None] * (n + 1)
        costs[0] = 0
        for start in range(n):
            # Every Unicode scalar has a reversible UTF-8 byte fallback.
            fallback = [self.byte_ids[b] for b in text[start].encode()]
            if costs[start] + len(fallback) < costs[start + 1]:
                costs[start + 1] = costs[start] + len(fallback)
                previous[start + 1] = (start, fallback)
            node = self.trie
            end = start
            while end < n and text[end] in node:
                node = node[text[end]]
                end += 1
                if None in node and costs[start] + 1 < costs[end]:
                    costs[end] = costs[start] + 1
                    previous[end] = (start, [node[None]])
        parts, end = [], n
        while end:
            begin, ids = previous[end]
            parts.append(ids)
            end = begin
        ids = [i for part in reversed(parts) for i in part]
        if self.tokenizer.decode(ids) != text:
            raise ValueError('Minimum-token path does not round-trip')
        return ids


def select():
    groups = collections.defaultdict(list)
    with (DATA / 'splits.jsonl').open() as f:
        for line in f:
            row = json.loads(line)
            if row['split'] in ('train', 'validation'):
                groups[row['source'], row['split'], row['group']].append(row)
    by_partition = collections.defaultdict(list)
    for (source, split, group), rows in groups.items():
        by_partition[source, split].append((group, min(rows, key=lambda r: rank(r['id']))))
    selected = []
    for partition in sorted(by_partition):
        works = sorted(by_partition[partition], key=lambda p: rank(p[0]))[:128]
        selected.extend(row for _, row in works)
    return selected


def summarize(rows):
    counts = collections.Counter()
    for row in rows:
        for key in ('characters', 'nonwhitespace_characters', 'tokens', 'regular_tokens',
                    'one_character_regular_tokens', 'one_character_content_tokens',
                    'content_regular_tokens', 'byte_tokens', 'newline_byte_tokens', 'unknown_tokens',
                    'minimum_tokens', 'no_lf_tokens', 'newline_characters'):
            counts[key] += row[key]
    chars, tokens = counts['characters'], counts['tokens']
    cpt = sorted(r['characters']/r['tokens'] for r in rows)
    return dict(samples=len(rows), works=len({r['group'] for r in rows}), **dict(counts),
        characters_per_token=chars/tokens, tokens_per_100_characters=100*tokens/chars,
        median_document_characters_per_token=cpt[len(cpt)//2],
        p10_document_characters_per_token=cpt[int((len(cpt)-1)*.1)],
        p90_document_characters_per_token=cpt[int((len(cpt)-1)*.9)],
        one_character_regular_fraction=counts['one_character_regular_tokens']/max(1, counts['regular_tokens']),
        one_character_content_fraction=counts['one_character_content_tokens']/max(1, counts['content_regular_tokens']),
        byte_token_fraction=counts['byte_tokens']/tokens,
        non_lf_byte_fraction=(counts['byte_tokens']-counts['newline_byte_tokens'])/tokens,
        minimum_token_reduction_fraction=1-counts['minimum_tokens']/tokens,
        no_lf_token_reduction_fraction=1-counts['no_lf_tokens']/tokens)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', default='runs/tokenization-efficiency-audit-002')
    args = parser.parse_args()
    output = ROOT / args.output
    output.mkdir(exist_ok=False)
    started = time.monotonic()
    tok = Tokenizer(MODEL)
    sp = tok.sp
    manifest = json.loads((DATA / 'manifest.json').read_text())
    assert sha(MODEL) == manifest['tokenizer_sha256']
    optimal = MinimumTokens(tok)
    selected = select()
    rows = []
    usage = collections.defaultdict(collections.Counter)
    examples = []
    db = sqlite3.connect('file:' + str(ROOT / 'unified/pretrain-v1/build-002/build.sqlite3') + '?mode=ro', uri=True)
    newline_id = sp.piece_to_id('<0x0A>')
    with (output / 'samples.jsonl').open('w') as f:
        for index, r in enumerate(selected):
            document = db.execute('SELECT text FROM units WHERE id=?', (r['id'],)).fetchone()[0]
            assert hashlib.sha256(document.encode()).hexdigest() == r['text_sha256']
            start = max(0, (len(document)-2048)//2)
            text = document[start:start+2048]
            ids = tok.encode(text)
            assert ids and tok.decode(ids) == text
            shortest = optimal.encode(text)
            assert len(shortest) <= len(ids)
            no_lf = tok.encode(text.replace('\n', ''))
            regular = [sp.id_to_piece(i).replace('▁', ' ') for i in ids if not sp.is_byte(i) and not sp.is_control(i) and not sp.is_unknown(i)]
            content = [p for p in regular if category(p) not in ('whitespace', 'punctuation_symbols')]
            row = dict(source=r['source'], split=r['split'], id=r['id'], group=r['group'],
                title=r['title'], era=r['era'], text_sha256=r['text_sha256'], start=start, end=start+len(text),
                characters=len(text), nonwhitespace_characters=sum(not c.isspace() for c in text), tokens=len(ids),
                regular_tokens=len(regular), one_character_regular_tokens=sum(len(p)==1 for p in regular),
                content_regular_tokens=len(content), one_character_content_tokens=sum(len(p)==1 for p in content),
                byte_tokens=sum(sp.is_byte(i) for i in ids), newline_byte_tokens=ids.count(newline_id),
                unknown_tokens=ids.count(0), minimum_tokens=len(shortest), no_lf_tokens=len(no_lf),
                newline_characters=text.count('\n'), roundtrip_exact=True)
            rows.append(row)
            f.write(json.dumps(row, ensure_ascii=False) + '\n')
            usage[r['source']].update(ids)
            if r['source'] == 'wikisource':
                examples.append(dict(id=r['id'], split=r['split'], title=r['title'],
                    original_tokens=len(ids), minimum_tokens=len(shortest),
                    gain=1-len(shortest)/len(ids), text=text[:256],
                    first_128_characters=text[:128],
                    current_pieces=[sp.id_to_piece(i) for i in tok.encode(text[:128])],
                    minimum_pieces=[sp.id_to_piece(i) for i in optimal.encode(text[:128])]))
            if (index+1) % 100 == 0:
                print(json.dumps(dict(samples=index+1, total=len(selected), seconds=time.monotonic()-started)), flush=True)
    db.close()
    report = {'by_source': {}, 'by_source_split': {}, 'wikisource_by_era': {}}
    for source in sorted({r['source'] for r in rows}):
        report['by_source'][source] = summarize([r for r in rows if r['source']==source])
        for split in ('train', 'validation'):
            rs = [r for r in rows if r['source']==source and r['split']==split]
            if rs:
                report['by_source_split'][source+'/'+split] = summarize(rs)
    for era in sorted({r['era'] for r in rows if r['source']=='wikisource'}):
        report['wikisource_by_era'][era] = summarize([r for r in rows if r['source']=='wikisource' and r['era']==era])
    # Keep all fixed, previously reviewed styles as a separate diagnostic, not pooled into work samples.
    styles = json.loads((ROOT / 'runs/pretrain-generation-comparison-001/cases.json').read_text())
    report['reviewed_styles'] = []
    for case in styles:
        text = case['prompt'] + case['reference']
        ids = tok.encode(text)
        shortest = optimal.encode(text)
        report['reviewed_styles'].append(dict(id=case['id'], source=case['source'], title=case['title'],
            style=case['style'], characters=len(text), tokens=len(ids), minimum_tokens=len(shortest),
            characters_per_token=len(text)/len(ids), minimum_token_reduction_fraction=1-len(shortest)/len(ids)))
    vocab = collections.Counter()
    for i in range(sp.vocab_size()):
        if sp.is_byte(i):
            vocab['byte'] += 1
        elif sp.is_control(i) or sp.is_unknown(i):
            vocab['special'] += 1
        else:
            surface = sp.id_to_piece(i).replace('▁', ' ')
            vocab[category(surface)] += 1
            vocab['single_character' if len(surface)==1 else 'multiple_characters'] += 1
    sampling = json.loads((ROOT / 'unified/tokenizer-v1/build-001/sampling.json').read_text())
    total = sum(r['sampled_characters'] for r in sampling['by_source'].values())
    report['tokenizer_training_sample_character_shares'] = {s:r['sampled_characters']/total for s,r in sampling['by_source'].items()}
    report['vocabulary_categories_overlapping_length_counts'] = dict(vocab)
    report['top_one_character_content_pieces'] = {}
    for source, counts in usage.items():
        report['top_one_character_content_pieces'][source] = [dict(piece=sp.id_to_piece(i), id=i, count=n)
            for i,n in counts.most_common() if not sp.is_byte(i) and len(sp.id_to_piece(i))==1
            and category(sp.id_to_piece(i)) not in ('whitespace', 'punctuation_symbols')][:30]
    write(output / 'report.json', report)
    write(output / 'wikisource-examples.json', sorted(examples, key=lambda e:e['gain'], reverse=True))
    write(output / 'manifest.json', dict(complete=True, source_splits=['train','validation'], test_read=False,
        selection='128 groups per source/split by fixed SHA256 rank, one document per group, middle up to 2048 Unicode characters',
        tokenizer_sha256=sha(MODEL), script_sha256=sha(__file__), splits_sha256=sha(DATA/'splits.jsonl'),
        samples=len(rows), independent_global_groups=len({r['group'] for r in rows}),
        roundtrip_matches=len(rows), unknown_tokens=sum(r['unknown_tokens'] for r in rows),
        minimum_paths_verified=len(rows), elapsed_seconds=time.monotonic()-started,
        caveat='Tokenizer predates LLM splitting; samples are not tokenizer-unseen. Compression bound does not optimize language-model quality.'))
    lines = ['# トークナイズ分割効率の診断', '',
        f'{len(rows)}出典内作品サンプル(独立global groupは{len({r["group"] for r in rows})})から各1レコードの中央最大2,048文字を採用。train/validationのみ。tokenizerは作品分割より前に作成済みなので、tokenizer未知作品への評価ではない。', '',
        '| 出典 | 作品数 | 文字/token ↑ | 100文字のtoken数 ↓ | 内容token中の1文字比 | byte比 | byte比(LF以外) | 同一語彙での最短化削減率 |',
        '|---|---:|---:|---:|---:|---:|---:|---:|']
    for s,r in report['by_source'].items():
        lines.append(f"| {s} | {r['samples']} | {r['characters_per_token']:.3f} | {r['tokens_per_100_characters']:.1f} | {r['one_character_content_fraction']:.1%} | {r['byte_token_fraction']:.2%} | {r['non_lf_byte_fraction']:.2%} | {r['minimum_token_reduction_fraction']:.3%} |")
    lines += ['', '文字/tokenはUnicode文字数(空白・改行を含む)÷本文token数。BOS/EOS/PADを除外。内容tokenは通常語彙のうち空白・句読点・記号だけのpieceを除いたもの。語の正しさを測る指標ではない。', '',
        '最短化は現行32,000語彙の通常pieceとUTF-8 byte piecesだけで原文を完全復元する最少token列を動的計画法で計算した比較上限。全サンプルで復元一致を確認した。Unigramの確率を最大化する通常encodeとは目的が違い、最短分割を既存LLMへそのまま入力する提案ではない。', '',
        '## train/validation別', '', '| 区分 | 作品数 | 文字/token | 同一語彙最短化削減率 |', '|---|---:|---:|---:|']
    for k,r in report['by_source_split'].items():
        lines.append(f"| {k} | {r['samples']} | {r['characters_per_token']:.3f} | {r['minimum_token_reduction_fraction']:.3%} |")
    lines += ['', '## 固定文体例', '', '| 作品・文体 | 文字数 | token数 | 文字/token | 同一語彙最短化削減率 |', '|---|---:|---:|---:|---:|']
    for r in report['reviewed_styles']:
        lines.append(f"| {r['title']}・{r['style']} | {r['characters']} | {r['tokens']} | {r['characters_per_token']:.3f} | {r['minimum_token_reduction_fraction']:.3%} |")
    lines += ['', '## 改行の診断', '', '| 出典 | LF文字数 | LF削除によるtoken数削減率 |', '|---|---:|---:|']
    for s,r in report['by_source'].items():
        lines.append(f"| {s} | {r['newline_characters']} | {r['no_lf_token_reduction_fraction']:.1%} |")
    lines += ['', 'LF削除はtoken負荷の感度診断だけであり、原文を変更する操作。語の結合による変化も含む。実データには適用せず、恣意的な改行の一律削除は提案しない。', '',
        '## tokenizer学習時の出典配分(文字数)', '']
    for s,v in report['tokenizer_training_sample_character_shares'].items():
        lines.append(f'- {s}: {v:.2%}')
    lines += ['', 'NDLは和文・漢文等を含むため、出典だけから言語比率とは見なさない。', '',
        '## 語彙と使用例', '', '```json', json.dumps(dict(vocab), ensure_ascii=False, indent=2), '```', '',
        '語彙の長さ別カウントは文字種別と重複する。文字種判定は簡易Unicode規則で、形態素や言語の厳密判定ではない。', '',
        'report.jsonに出典別頻出1文字piece、Wikisourceの時代別数値を保存。wikisource-examples.jsonには同一原文での通常分割と最短分割を保存。サンプルの作品・位置・原文hash・数値はsamples.jsonl。', '',
        '## 解釈の限界', '',
        '文字/tokenだけで他言語・異なるtokenizerの優劣やモデル品質は判断しない。同語彙最短化は語彙固定での圧縮余地を示すが、より良い語彙を再学習した場合の改善幅は未測定。既存モデル・tokenizer・学習用binは変更していない。', '']
    (output/'REPORT.md').write_text('\n'.join(lines))
    print(json.dumps(report['by_source'], ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()