File size: 11,539 Bytes
c9b8d8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Resume-safe, bounded-memory creation of actual packed native candidate files."""
import argparse
from dataclasses import asdict
import hashlib
import json
import os
from pathlib import Path
import shutil
import time
import numpy as np
import torch
from filelock import FileLock
from native_scale import NativeScale
from packed_sgd import PackedStore,atomic_json,pack_codes
from stream_train import atomic_torch_save,replace_retry


def file_hash(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block)
    return h.hexdigest()


class NativeTeacher:
    def __init__(self,run,native_source):
        self.run=Path(run)
        self.checkpoint=torch.load(self.run/'checkpoint.pt',map_location='cpu',weights_only=False)
        if self.checkpoint['status']!='PACKED_NATIVE_VISUAL_ENGINEERING_PILOT':
            raise ValueError('A completed owned native packed training checkpoint is required')
        self.config=self.checkpoint['config']['config']
        if file_hash(native_source)!=self.checkpoint['config']['source_sha256']:
            raise ValueError('Native source/normalization provenance differs')
        self.original=torch.load(native_source,map_location='cpu',weights_only=False)
        if self.original.get('architecture')!='motion_residual' or self.original.get('status')!='NATIVE_VISUAL_DYNAMICS_TOY_ONLY':
            raise ValueError('Owned motion-residual visual source required')
        if self.checkpoint['config'].get('uses_llm') or self.checkpoint['config']['bits']!=3:
            raise ValueError('Native 3-bit teacher required')
        self.store=PackedStore(self.run/'weights')
        if any(v['bits']!=3 for v in self.store.info.values()):raise ValueError('Mixed teacher bit widths')
        self.small={k.replace('.block.','.'):v for k,v in self.checkpoint['model'].items() if not k.endswith('.anchor')}
        self.fingerprints=dict(checkpoint=file_hash(self.run/'checkpoint.pt'),native_source=file_hash(native_source),
            matrices={name:{kind:file_hash(self.run/'weights'/value[kind]) for kind in ('data','scale')}
                      for name,value in self.store.info.items()})

    def pattern(self,item,target_width):
        info=self.store.info[item['source']]
        old_rows,old_cols=info['shape']
        target_rows,target_cols=item['shape']
        if target_cols%old_cols:raise ValueError('Nonintegral fan-in replication')
        bits=item['bits']
        if bits==3:
            packed=np.fromfile(self.run/'weights'/info['data'],dtype=np.uint8).reshape(old_rows,old_cols*3//8)
            scale=np.fromfile(self.run/'weights'/info['scale'],dtype='<f4')
        elif bits==2:
            weight=self.store.read_tile(item['source'],0,old_rows,'cpu',torch.float32)[3]
            scale=weight.square().mean(-1).sqrt().clamp_min(1e-8)/2
            code=((weight/scale[:,None]+3)/2).round().clamp(0,3).to(torch.uint8)
            packed=pack_codes(code,2).numpy();scale=scale.numpy()
        else:raise ValueError('Unsupported native initialization bit width')
        def rows(start,count):
            indices=np.arange(start,start+count,dtype=np.int64)
            if item['row_kind']=='qkv':
                old_width=old_rows//3
                indices=(indices//target_width)*old_width+(indices%target_width)%old_width
            else:indices%=old_rows
            data=np.tile(packed[indices],(1,target_cols//old_cols)).tobytes()
            factor=item['gain']/(target_cols//old_cols)
            scales=(scale[indices]*np.float32(factor)).astype('<f4').tobytes()
            return data,scales
        return rows

    def small_state(self,config):
        ratio=config.width//self.config['width'];old_l=self.config['layers']
        state={'input.weight':self.small['input.weight'].repeat(ratio,1),
               'norm.weight':self.small['norm.weight'].repeat(ratio)}
        for i in range(config.layers):
            for norm in ('norm1','norm2'):
                state[f'blocks.{i}.{norm}.weight']=self.small[f'blocks.{i%old_l}.{norm}.weight'].repeat(ratio)
            if i in config.moe_layers:
                key=f'blocks.{i}.ffn.router.weight'
                source=self.small[f'blocks.{i%old_l}.ffn.router.weight']
                state[key]=source.repeat(1,ratio)/ratio
        return state


def initialize_matrix(store,item,rows_fn,reserve_bytes,event,tile_rows=256):
    name=item['name'];rows,cols=item['shape'];bits=item['bits'];row_bytes=cols*bits//8
    key=hashlib.sha256(name.encode()).hexdigest()[:24]
    data=store.root/(key+f'.u{bits}');scale=store.root/(key+'.f32')
    dp=data if data.exists() else data.with_suffix(f'.u{bits}.partial')
    sp=scale if scale.exists() else scale.with_suffix('.f32.partial')
    dr=dp.stat().st_size//row_bytes if dp.exists() else 0
    sr=sp.stat().st_size//4 if sp.exists() else 0
    complete=min(dr,sr)
    if dr>rows or sr>rows:raise ValueError('Unexpected oversized matrix file')
    dh,sh=hashlib.sha256(),hashlib.sha256()
    # Compare every retained row prefix against the deterministic owned teacher.
    if complete:
        with dp.open('rb') as df,sp.open('rb') as sf:
            for start in range(0,complete,tile_rows):
                count=min(tile_rows,complete-start);want_d,want_s=rows_fn(start,count)
                got_d,got_s=df.read(count*row_bytes),sf.read(count*4)
                if got_d!=want_d or got_s!=want_s:raise ValueError(f'Initialization prefix differs: {name}')
                dh.update(got_d);sh.update(got_s)
    with dp.open('r+b' if dp.exists() else 'w+b') as df,sp.open('r+b' if sp.exists() else 'w+b') as sf:
        df.truncate(complete*row_bytes);sf.truncate(complete*4)
        df.seek(complete*row_bytes);sf.seek(complete*4)
        for start in range(complete,rows,tile_rows):
            count=min(tile_rows,rows-start);raw,scales=rows_fn(start,count)
            if shutil.disk_usage(store.root).free-len(raw)-len(scales)<reserve_bytes:
                raise RuntimeError('Native initialization disk reserve reached; complete prefix preserved')
            df.write(raw);sf.write(scales)
            df.flush();os.fsync(df.fileno());sf.flush();os.fsync(sf.fileno())
            dh.update(raw);sh.update(scales)
    if dp!=data:replace_retry(dp,data)
    if sp!=scale:replace_retry(sp,scale)
    entry=dict(shape=[rows,cols],data=data.name,scale=scale.name,bits=bits,
               scale_mode='fixed_teacher_row_scale_with_fan_in_replication',
               initialization_sha256=dict(data=dh.hexdigest(),scale=sh.hexdigest()),
               source_native_matrix=item['source'],initial_residual_gain=item['gain'])
    store.info[name]=entry;atomic_json(store.manifest,store.info)
    event(name,rows*cols)


def main():
    p=argparse.ArgumentParser();p.add_argument('--teacher-run',type=Path,required=True)
    p.add_argument('--native-source',type=Path,required=True)
    p.add_argument('--out',type=Path,required=True);p.add_argument('--report',type=Path,required=True)
    p.add_argument('--config',type=Path);p.add_argument('--reserve-gb',type=float,default=10.)
    a=p.parse_args();a.out.mkdir(parents=True,exist_ok=True);a.report.parent.mkdir(parents=True,exist_ok=True)
    raw=json.loads(a.config.read_text()) if a.config else {}
    if 'moe_layers' in raw:raw['moe_layers']=tuple(raw['moe_layers'])
    config=NativeScale(**raw);teacher=NativeTeacher(a.teacher_run,a.native_source)
    plan=config.plan(teacher.config);audit=config.audit(teacher.config)
    protocol=dict(status='NATIVE_WARM_INITIALIZATION_NOT_TRAINED',scale=asdict(config),
                  teacher_fingerprints=teacher.fingerprints,base_config=teacher.config,
                  scale_source_sha256=file_hash(Path(__file__).parent/'native_scale.py'),
                  initializer_source_sha256=file_hash(__file__),
                  packed_source_sha256=file_hash(Path(__file__).parent/'packed_sgd.py'))
    path=a.out/'initialization-protocol.json'
    if path.exists():
        old=json.loads(path.read_text())
        # JSON encodes tuples as arrays, so compare canonical serialized values.
        if json.dumps(old,sort_keys=True)!=json.dumps(protocol,sort_keys=True):raise ValueError('Initialization configuration/source changed')
    else:atomic_json(path,protocol)
    atomic_json(a.out/'tensor-plan.json',plan)
    reserve=int(a.reserve_gb*1e9);started=time.perf_counter()
    with FileLock(str(a.out/'initialization.lock'),timeout=0):
        store=PackedStore(a.out/'weights',bits=3,reserve_bytes=reserve)
        remaining=sum(item['shape'][0]*(item['shape'][1]*item['bits']//8+4) for item in plan if item['name'] not in store.info)
        if shutil.disk_usage(a.out).free-remaining-audit['small_fp32_bytes']-audit['maximum_expert_undo_bytes']<reserve:
            raise RuntimeError('Insufficient final disk headroom for native weights and undo group')
        def event(name,parameters):
            status=dict(status='NATIVE_WEIGHTS_INITIALIZING_NOT_TRAINED',completed_matrices=len(store.info),
                target_matrices=len(plan),initialized_matrix_parameters=sum(np.prod(v['shape']).item() for v in store.info.values()),
                declared_active_parameters=audit['active_parameters_per_token'],last_matrix=name,
                elapsed_seconds=time.perf_counter()-started,free_disk_bytes=shutil.disk_usage(a.out).free,
                trained_100B_world_model=False)
            atomic_json(a.report,status)
            if len(store.info)%12==0 or len(store.info)==len(plan):print(json.dumps(status),flush=True)
        for item in plan:
            if item['name'] in store.info:
                entry=store.info[item['name']]
                for key in ('data','scale'):
                    f=store.root/entry[key]
                    if file_hash(f)!=entry['initialization_sha256'][key]:raise ValueError('Previously completed tensor changed')
                continue
            initialize_matrix(store,item,teacher.pattern(item,config.width),reserve,event)
        small=teacher.small_state(config)
        atomic_torch_save(dict(status='NATIVE_LARGE_INITIALIZATION_ONLY',small_state=small,
                               normalization_mean=teacher.original['mean'],normalization_std=teacher.original['std'],
                               codec_sha256=teacher.original['codec_sha256'],
                               teacher_checkpoint_sha256=teacher.fingerprints['checkpoint']),a.out/'initial-small-state.pt')
        final=dict(status='ACTUAL_NATIVE_PACKED_FILES_INITIALIZED_NOT_TRAINED',audit=audit,
                   store=store.summary(),initialization_seconds=time.perf_counter()-started,
                   small_state_sha256=file_hash(a.out/'initial-small-state.pt'),
                   target_directory=str(a.out.resolve()),trained_native_100B=False,general_world_model=False,
                   limitations=['Initialization replicates native teacher weights and adds small residual blocks.',
                                'Replicated files do not add new learned information; independent native training and capability evaluation remain.',
                                'No complete large forward/backward or competitive broad evaluation is proved by initialization.'])
        atomic_json(a.out/'initialization-result.json',final);atomic_json(a.report,final)
        print(json.dumps(dict(status=final['status'],matrices=len(store.info),weight_bytes=audit['estimated_weight_bytes'])),flush=True)


if __name__=='__main__':main()