classical-ja-pretrain / code /scripts /inspect_wikisource_tokenization.py
kuramot6f's picture
Initial release (history squashed)
7a088d4
Raw History Blame Contribute Delete
6.68 kB
"""Print a Wikisource sample with token IDs, pieces, and frozen-stream checks."""
import csv
import hashlib
import json
from pathlib import Path
import sqlite3
import numpy as np
from classical_tokenizer import ClassicalTokenizer
ROOT = Path(__file__).resolve().parents[1]
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def main():
output = ROOT / 'runs/wikisource-tokenization-inspection-001'
output.mkdir(exist_ok=False)
# Use the exact reviewed paragraph from the earlier comparison, without its heading.
cases = json.loads((ROOT / 'runs/pretrain-generation-comparison-001/cases.json').read_text())
case = next(r for r in cases if r['id'] == 'case-05')
source_id = case['source_id']
text = case['prompt']
tokenizer_path = ROOT / 'runs/classical-smollm2-trunk/export/tokenizer.model'
tokenizer = ClassicalTokenizer(tokenizer_path)
splits = ROOT / 'unified/training-tokens-v1/build-006'
manifest = json.loads((splits / 'manifest.json').read_text())
assert sha(tokenizer_path) == manifest['tokenizer_sha256']
record = next(r for r in map(json.loads, (splits / 'splits.jsonl').read_text().splitlines()) if r['id'] == source_id)
assert record['source'] == 'wikisource' and record['split'] == 'validation'
with sqlite3.connect('file:' + str(ROOT / 'unified/pretrain-v1/build-002/build.sqlite3') + '?mode=ro', uri=True) as db:
document = db.execute('SELECT text FROM units WHERE id=?', (source_id,)).fetchone()[0]
assert hashlib.sha256(document.encode()).hexdigest() == record['text_sha256']
assert document[case['source_start']:case['source_start']+len(text)] == text
full_ids = [1] + tokenizer.raw_encode(document) + [2]
stream = np.memmap(splits / f"wikisource.{record['split']}.bin", dtype='<u4', mode='r')
saved = stream[record['split_offset']:record['split_offset']+record['tokens']]
assert full_ids == saved.tolist(), 'Frozen document tokens differ from re-encoding'
assert hashlib.sha256(np.asarray(full_ids, dtype='<u4').tobytes()).hexdigest() == record['token_sha256']
ids = tokenizer.raw_encode(text)
hf_ids = tokenizer(text, add_special_tokens=False)['input_ids']
assert ids == hf_ids
assert tokenizer(text)['input_ids'] == [1] + ids
decoded = tokenizer.decode(ids)
assert decoded == text
assert '▁' not in text # Surface offsets below can use the unmodified SentencePiece input.
proto = tokenizer.sp_model.encode(text, out_type='immutable_proto')
assert [p.id for p in proto.pieces] == ids
tokens = []
for i, p in enumerate(proto.pieces):
assert text[p.begin:p.end] == p.surface
tokens.append(dict(index=i, id=p.id, piece=p.piece, surface=p.surface,
begin=p.begin, end=p.end, byte_fallback=tokenizer.sp_model.is_byte(p.id)))
result = dict(title=case['title'], source_id=source_id, split=record['split'],
sample_start=case['source_start'], sample_end=case['source_start']+len(text),
text=text, decoded=decoded, characters=len(text), body_tokens=len(ids),
characters_per_token=len(text)/len(ids), unknown_tokens=ids.count(0),
byte_fallback_tokens=sum(t['byte_fallback'] for t in tokens),
newline_characters=text.count('\n'), roundtrip_exact=decoded == text,
hf_adapter_matches_sentencepiece=True, full_record_matches_saved_pretraining_stream=True,
full_record_tokens=len(full_ids), tokenizer_sha256=sha(tokenizer_path),
input_ids=ids, hf_default_ids=[1]+ids, pretraining_bos_eos_ids=[1]+ids+[2], tokens=tokens)
(output / 'inspection.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
with (output / 'tokens.tsv').open('w', newline='') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(['index', 'id', 'piece_json', 'surface_json', 'begin', 'end', 'byte_fallback'])
for t in tokens:
writer.writerow([t['index'], t['id'], json.dumps(t['piece'], ensure_ascii=False),
json.dumps(t['surface'], ensure_ascii=False), t['begin'], t['end'], t['byte_fallback']])
lines = ['# Wikisourceトークナイズ出力', '', f"作品:{case['title']}", '',
f"source_id:`{source_id}`(validation)。モデルと同じ32,000語彙のtokenizerを使用。", '',
'## 原文', '', '```text', text, '```', '', '## トークン表記(本文のみ)', '',
'各pieceをJSON文字列で表示し、` | `で区切る。`\\n`は改行、`▁`はSentencePieceの空白表記。区切り線と引用符は表示用で入力には含まない。', '',
'```text', ' | '.join(json.dumps(t['piece'], ensure_ascii=False) for t in tokens), '```', '',
'## トークンID(本文のみ)', '', '```json', json.dumps(ids), '```', '',
'## 位置・ID・表記の対応', '', '| 順番 | ID | piece | 原文の文字位置 |', '|---:|---:|---|---|']
for t in tokens:
piece = json.dumps(t['piece'], ensure_ascii=False).replace('|', '\\|')
lines.append(f"| {t['index']} | {t['id']} | `{piece}` | [{t['begin']}, {t['end']}) |")
lines += ['', '## 確認結果', '',
f"- 原文{len(text)}文字、本文{len(ids)}token、{len(text)/len(ids):.3f}文字/token。",
f"- UNK={result['unknown_tokens']}、byte fallback={result['byte_fallback_tokens']}、原文改行={text.count(chr(10))}。",
'- encode→decodeで原文と完全一致。HFアダプタとSentencePieceの本文IDも一致。',
f"- このサンプルを含む元レコード全体{len(full_ids)}tokenを再encodeし、保存済み事前学習用binと全IDが完全一致。token_sha256も一致。",
'- この表示のID列は本文のみ。事前学習データは文書全体にBOS ID 1とEOS ID 2を付ける。試用スクリプトの入力はBOSだけを付け、続きを生成する。',
'- 部分抜粋のtoken分割は切り出し境界の影響を受け得るため、保存済みbinとの照合は元レコード全体で行った。',
'- 1例での確認であり、全作品・外字・byte fallback・特殊文字の網羅検査や、語彙効率の最適性の証明ではない。', '',
'## デコード結果', '', '```text', decoded, '```', '']
(output / 'INSPECTION.md').write_text('\n'.join(lines))
print(json.dumps({k: v for k, v in result.items() if k not in ('tokens', 'hf_default_ids', 'pretraining_bos_eos_ids')}, ensure_ascii=False, indent=2))
print('PIECES:', ' | '.join(json.dumps(t['piece'], ensure_ascii=False) for t in tokens))
if __name__ == '__main__':
main()