"""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='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)