hy4-vision-encoder / validate_local_reference.py
gatilin's picture
Add files using upload-large-folder tool
33ab666 verified
Raw History Blame Contribute Delete
2.97 kB
"""Validate extracted Hy4 visual encoder on two RGB images."""
import hashlib,json,math,sys,time
from pathlib import Path
import torch, torch.nn.functional as F
from PIL import Image
from component import load_model,load_processor
root=Path(__file__).resolve().parent;ex=json.loads((root/'extraction.json').read_text());paths=[Path(p) for p in sys.argv[1:]];assert len(paths)==2
start=time.monotonic();torch.set_num_threads(4);torch.set_grad_enabled(False)
print('LOADING',flush=True);model=load_model(root,dtype=torch.float32);processor=load_processor(root);assert len(model.layers)==40
print('STRICT LOAD OK',flush=True);orig=F.scaled_dot_product_attention;rows=[];features=[]
for path in paths:
im=Image.open(path).convert('RGB');x=processor(images=im,return_tensors='pt');grid=x['image_grid_thw'];t,h,w=grid[0].tolist();assert t==1 and h%2==w%2==0;calls=[0];metrics={}
def wrapper(q,k,v,*a,**kw):
y=orig(q,k,v,*a,**kw);i=calls[0];calls[0]+=1
if i in (0,19,39):
mask=kw.get('attn_mask',a[0] if a else None);assert mask is None;scale=kw.get('scale') or q.shape[-1]**-.5;probs=(q@k.transpose(-2,-1)*scale).softmax(-1);z=probs@v;error=float((z-y).abs().max());assert torch.allclose(y,z,atol=2e-5,rtol=2e-4),error
metrics[str(i)]={'max_abs_error':error,'row_sum_error':float((probs.sum(-1)-1).abs().max()),'mean_normalized_entropy':float((-(probs*probs.clamp_min(1e-30).log()).sum(-1)).mean()/math.log(q.shape[-2]))}
return y
try:
F.scaled_dot_product_attention=wrapper
with torch.inference_mode():o=model(pixel_values=x['pixel_values'],grid_thw=grid)
finally:F.scaled_dot_product_attention=orig
assert calls[0]==40 and len(metrics)==3,(calls,metrics);assert o.last_hidden_state.shape==(1,h*w,1536);assert o.pooler_output.shape==(1,(h//2)*(w//2+1),6144);assert torch.isfinite(o.last_hidden_state).all() and torch.isfinite(o.pooler_output).all();features.append(o.pooler_output)
rows.append({'image':path.name,'input_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'grid_thw':grid.tolist()[0],'patch_features_shape':list(o.last_hidden_state.shape),'projected_features_shape':list(o.pooler_output.shape),'attention_check':metrics});print('VALIDATED',path.name,flush=True)
assert features[0].shape==features[1].shape;delta=float((features[0]-features[1]).abs().mean());assert delta>1e-5
v={'passed':True,'strict_load':True,'num_tensors':ex['tensor_count'],'model_sha256':ex['sha256'],'native_model_layers':40,'dtype_for_test':'float32 CPU; artifact remains BF16','runtime':'Transformers '+__import__('transformers').__version__+' with pinned upstream HYV4VL sources','attention_method':'explicit softmax(QK^T/sqrt(d))V versus native SDPA at layers 0, 19 and 39','images':rows,'different_image_mean_abs_difference':delta,'seconds':round(time.monotonic()-start,1),'limitations':'CPU smoke test only; no full-model or task accuracy comparison.'};(root/'validation.json').write_text(json.dumps(v,indent=2)+'\n');print('VALIDATION PASSED',flush=True)