cbert33's picture
Upload calibrated FP8 KV model card and metadata
ff7679d verified
Raw History Blame Contribute Delete
5.65 kB
"""Offline KV-scale calibration only; source checkpoint is immutable and MXFP8."""
import argparse,collections,hashlib,json,os,pathlib,struct,time,traceback
import torch
from safetensors import safe_open
from safetensors.torch import save_file
from transformers import AutoModelForCausalLM
from latent_observer import LatentCacheObserver
p=argparse.ArgumentParser();p.add_argument('--source',required=True);p.add_argument('--inputs',required=True);p.add_argument('--records',required=True);a=p.parse_args()
source=pathlib.Path(a.source);records=pathlib.Path(a.records);records.mkdir(parents=True,exist_ok=True)
input_path=pathlib.Path(a.inputs);expected_sha='c3bec35a3674d12f50a79b3d9bcd4117cbd3f0d54659930136a5cf4122a8b5d9'
assert hashlib.sha256(input_path.read_bytes()).hexdigest()==expected_sha
samples=[json.loads(line) for line in input_path.read_text().splitlines()];assert len(samples)==512
assert sum(len(x['input_ids']) for x in samples)==437514
assert all(0<len(x['input_ids'])<=2048 for x in samples)
start=time.monotonic();state={'phase':'loading','completed_samples':0,'total_samples':512,'completed_tokens':0,'total_tokens':437514,'inputs_sha256':expected_sha}
def progress(**kw):
state.update(kw);state['elapsed_seconds']=time.monotonic()-start
state['meminfo']={k:int(v.split()[0])*1024 for k,v in (line.split(':',1) for line in pathlib.Path('/proc/meminfo').read_text().splitlines()) if k in ('MemAvailable','SwapFree')}
state['cuda_allocated']=torch.cuda.memory_allocated();state['cuda_reserved']=torch.cuda.memory_reserved();state['cuda_peak_allocated']=torch.cuda.max_memory_allocated()
tmp=records/'progress.tmp';tmp.write_text(json.dumps(state,indent=2));tmp.replace(records/'progress.json');print(json.dumps(state),flush=True)
try:
assert torch.cuda.is_available() and torch.cuda.device_count()==1
progress()
model,info=AutoModelForCausalLM.from_pretrained(str(source),trust_remote_code=True,local_files_only=True,dtype=torch.bfloat16,device_map={'':'cuda'},output_loading_info=True)
model.eval();assert not info.get('missing_keys') and not info.get('unexpected_keys') and not info.get('mismatched_keys'),info
index=json.loads((source/'model.safetensors.index.json').read_text());headers={}
for shard in sorted(set(index['weight_map'].values())):
with (source/shard).open('rb') as f:
size=struct.unpack('<Q',f.read(8))[0];h=json.loads(f.read(size))
headers.update({k:v for k,v in h.items() if k!='__metadata__'})
params=model.state_dict()
from load_audit import audit_loaded_parameters, normalize_loading_info
tensor_audit=audit_loaded_parameters(headers,params,records/'load-audit-partial.json')
# Numerical load oracle at early/middle/late expert branches and protected embeddings/norm.
representatives=['model.layers.1.moe.experts.0.gate_proj.weight','model.layers.12.moe.experts.64.up_proj.weight','model.layers.24.moe.experts.127.down_proj.weight','model.layers.1.moe.experts.0.gate_proj.weight_scale_inv','model.layers.12.moe.experts.64.up_proj.weight_scale_inv','model.layers.24.moe.experts.127.down_proj.weight_scale_inv','model.embed_tokens.weight','model.norm.weight']
for name in representatives:
with safe_open(str(source/index['weight_map'][name]),framework='pt',device='cpu') as f:
sliced=f.get_slice(name);shape=sliced.get_shape();selection=tuple(slice(0,1) for _ in shape[:-1])+(slice(0,min(shape[-1],32)),);expected=sliced[selection]
loaded=params[name][selection].detach().cpu()
if name.endswith('weight_scale_inv'):loaded=loaded.view(torch.uint8)
if expected.dtype==torch.float8_e4m3fn:expected=expected.view(torch.uint8);loaded=loaded.view(torch.uint8)
assert torch.equal(expected,loaded),name
audit={**tensor_audit,'representatives_equal':representatives,'loading_info':normalize_loading_info(info),'resident_tensor_bytes':sum(t.numel()*t.element_size() for t in params.values())}
(records/'load-audit.json').write_text(json.dumps(audit,indent=2));del params
# Capture true compressed latent across ALL seven MLA layers; no RDA observers.
observers={}
for n,block in enumerate(model.model.layers):
attn=block.self_attn
if type(attn).__name__=='Raon1MiniMLA':observers[n]=LatentCacheObserver(attn)
assert set(observers)=={3,7,11,15,19,23,24}
progress(phase='calibrating',load_audit=audit)
with torch.inference_mode():
for i,sample in enumerate(samples):
tick=time.monotonic();ids=torch.tensor([sample['input_ids']],dtype=torch.long,device='cuda')
outputs=model.model(input_ids=ids,use_cache=False,output_hidden_states=False,return_dict=True)
del outputs,ids
torch.cuda.synchronize()
assert all(o.calls==i+1 for o in observers.values())
progress(completed_samples=i+1,completed_tokens=state['completed_tokens']+len(sample['input_ids']),last_sample_seconds=time.monotonic()-tick,layer_amax={str(n):o.maximum for n,o in observers.items()})
scales={};evidence={}
for n,observer in observers.items():
assert observer.rows==437514 and observer.calls==512
evidence[str(n)]=observer.numerical_evidence();scale=observer.scale();assert scale>0
for kind in ('k_scale','v_scale'):scales[f'model.layers.{n}.self_attn.{kind}']=torch.tensor(scale,dtype=torch.float32)
observer.close()
save_file(scales,str(records/'kv-cache-scales.safetensors'),metadata={'format':'pt','scheme':'FP8_E4M3FN_SHARED_MLA_LATENT','inputs_sha256':expected_sha})
(records/'scale-evidence.json').write_text(json.dumps(evidence,indent=2))
progress(phase='calibration_complete',scale_tensor_count=len(scales),scales={k:v.item() for k,v in scales.items()})
except BaseException as e:
progress(phase='failed',error=repr(e),traceback=traceback.format_exc());raise