File size: 8,295 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
"""Create corpus/token derivatives excluding the audited unknown-era Kanripo IDs."""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import shutil

import numpy as np

from sentencepiece_unigram import now, read_json, sha, write_json


def excluded(row):
    return row['source']=='kanripo' and row['date_evidence'].get('dynasty')=='時代不明'


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--input',type=Path,default=Path('unified/pretrain-v1/build-002'))
    p.add_argument('--tokens',type=Path,default=Path('unified/tokens-v1/build-001'))
    p.add_argument('--audit',type=Path,default=Path('kanripo/unknown-era-audit/run-001'))
    p.add_argument('--output',type=Path,default=Path('unified/pretrain-v1/build-003'))
    p.add_argument('--token-output',type=Path,default=Path('unified/tokens-v1/build-002'))
    a=p.parse_args()
    cm,tm,am=(read_json(a.input/'manifest.json'),read_json(a.tokens/'manifest.json'),read_json(a.audit/'report.json'))
    if not all(m['complete'] for m in (cm,tm,am)):
        raise ValueError('Incomplete inputs')
    src=a.input/'pretrain.jsonl'
    if sha(src)!=cm['output_sha256'][src.name] or tm['input_sha256']!=cm['output_sha256'][src.name] or am['input_sha256']!=tm['input_sha256']:
        raise ValueError('Input identity mismatch')
    for name,expected in tm['files'].items():
        if sha(a.tokens/name)!=expected:
            raise ValueError('Token input hash mismatch: '+name)
    with (a.audit/'documents.jsonl').open() as f:
        audit_ids={json.loads(l)['id'] for l in f}
    if len(audit_ids)!=6674:
        raise ValueError('Expected exactly 6674 audited exclusion IDs')
    a.output.mkdir(parents=True,exist_ok=False)
    a.token_output.mkdir(parents=True,exist_ok=False)
    manifest=dict(complete=False,started=now(),input=str(a.input.resolve()),
                  input_manifest_sha256=sha(a.input/'manifest.json'),
                  input_sha256=tm['input_sha256'],audit_report_sha256=sha(a.audit/'report.json'),
                  policy='Exclude exactly audited Kanripo files with unknown catalog dynasty; preserve all other rows verbatim',
                  script_sha256=sha(__file__))
    write_json(a.output/'manifest.json',manifest)
    token_manifest=dict(complete=False,started=now(),parent=str(a.tokens.resolve()),
                        parent_manifest_sha256=sha(a.tokens/'manifest.json'),
                        tokenizer_sha256=tm['tokenizer_sha256'],vocab_size=tm['vocab_size'],dtype=tm['dtype'],
                        script_sha256=sha(__file__),encoding=tm['encoding'],
                        policy='Copy retained document token slices exactly; no re-encoding')
    write_json(a.token_output/'manifest.json',token_manifest)
    original=np.memmap(a.tokens/'tokens.bin',dtype='<u4',mode='r')
    kept,removed,token_counts,chars=Counter(),Counter(),Counter(),Counter()
    removed_ids,removed_works=set(),set()
    offset=0
    parent_offset=0
    with src.open('rb') as source, (a.tokens/'documents.jsonl').open() as metadata, \
            (a.output/'pretrain.jsonl').open('wb') as corpus, \
            (a.output/'excluded.jsonl').open('w') as exclusions, \
            (a.token_output/'documents.jsonl').open('w') as documents, \
            (a.token_output/'tokens.bin').open('wb') as tokens:
        for raw in source:
            r,m=json.loads(raw),json.loads(next(metadata))
            if r['id']!=m['id'] or r['text_sha256']!=m['text_sha256'] or m['offset']!=parent_offset:
                raise ValueError('Source/token metadata alignment failed')
            parent_offset+=m['tokens']
            if excluded(r)!=(r['id'] in audit_ids):
                raise ValueError('Exclusion policy does not match audited IDs')
            if excluded(r):
                removed[r['source']]+=1
                removed_ids.add(r['id']);removed_works.add(r['source_document_id'])
                exclusions.write(json.dumps(dict(id=r['id'],source=r['source'],title=r['title'],
                    source_document_id=r['source_document_id'],text_sha256=r['text_sha256'],
                    tokens=m['tokens'],reason='user_excluded_kanripo_unknown_dynasty'),ensure_ascii=False)+'\n')
                continue
            if hashlib.sha256(r['text'].encode()).hexdigest()!=r['text_sha256']:
                raise ValueError('Source document hash mismatch')
            corpus.write(raw)
            ids=original[m['offset']:m['offset']+m['tokens']]
            if len(ids)!=m['tokens'] or ids[0]!=1 or ids[-1]!=2:
                raise ValueError('Invalid retained tokens')
            tokens.write(ids.tobytes())
            m['offset']=offset
            documents.write(json.dumps(m,ensure_ascii=False)+'\n')
            kept[r['source']]+=1;token_counts[r['source']]+=m['tokens'];chars[r['source']]+=len(r['text'])
            offset+=m['tokens']
        if next(metadata,None) is not None or parent_offset!=len(original):
            raise ValueError('Incomplete source coverage')
    if removed_ids!=audit_ids or len(removed_works)!=1881:
        raise ValueError('Excluded IDs/work count mismatch')
    if sum(kept.values())!=tm['documents']-6674:
        raise ValueError('Kept count mismatch')
    for name in ('tokenizer.model','tokenizer_wrapper.py'):
        shutil.copyfile(a.tokens/name,a.token_output/name)
    # Independently compare every persisted slice and metadata row to its parent.
    copied=np.memmap(a.token_output/'tokens.bin',dtype='<u4',mode='r')
    verified=0
    with (a.tokens/'documents.jsonl').open() as old, (a.token_output/'documents.jsonl').open() as new:
        for line in old:
            before=json.loads(line)
            if before['id'] in audit_ids:
                continue
            after=json.loads(next(new))
            old_offset,new_offset=before.pop('offset'),after.pop('offset')
            if before!=after:
                raise ValueError('Retained token metadata changed')
            length=before['tokens']
            if not np.array_equal(original[old_offset:old_offset+length],copied[new_offset:new_offset+length]):
                raise ValueError('Retained token IDs changed')
            verified+=1
        if next(new,None) is not None:
            raise ValueError('Unexpected retained rows')
    # Re-read corpus and confirm exact retained source bytes and exclusion absence.
    with src.open('rb') as old, (a.output/'pretrain.jsonl').open('rb') as new:
        for line in old:
            if json.loads(line)['id'] not in audit_ids and line!=next(new):
                raise ValueError('Retained corpus bytes changed')
        if next(new,None) is not None:
            raise ValueError('Unexpected corpus rows')
    verification=dict(complete=True,excluded_files=len(removed_ids),excluded_works=len(removed_works),
                      kept_files=verified,kept_tokens=offset,all_retained_text_bytes_identical=True,
                      all_retained_token_ids_identical=True,excluded_id_overlap=0)
    write_json(a.output/'verification.json',verification)
    write_json(a.token_output/'verification.json',verification)
    report=dict(kept_units=sum(kept.values()),kept_characters=sum(chars.values()),tokens=offset,
                excluded_files=len(removed_ids),excluded_works=len(removed_works),
                removed_tokens=tm['tokens']-offset,
                counts={s:dict(kept_units=n,kept_chars=chars[s],tokens=token_counts[s]) for s,n in kept.items()})
    write_json(a.output/'report.json',report)
    corpus_sha=sha(a.output/'pretrain.jsonl')
    manifest.update(complete=True,finished=now(),output_sha256={p.name:sha(p) for p in a.output.iterdir() if p.name!='manifest.json'})
    write_json(a.output/'manifest.json',manifest)
    token_manifest.update(complete=True,finished=now(),input=str((a.output/'pretrain.jsonl').resolve()),
                          input_sha256=corpus_sha,documents=verified,tokens=offset,by_source=dict(token_counts),
                          files={p.name:sha(p) for p in a.token_output.iterdir() if p.name!='manifest.json'})
    write_json(a.token_output/'manifest.json',token_manifest)
    print(json.dumps(report,ensure_ascii=False,indent=2),flush=True)


if __name__=='__main__':
    main()