inkling-2-small-vision-encoder / validate_local_reference.py
gatilin's picture
Add files using upload-large-folder tool
1f25247 verified
Raw History Blame Contribute Delete
2.81 kB
import hashlib,importlib.util,json,sys,time
from pathlib import Path
import numpy as np,torch
from PIL import Image
root=Path(__file__).resolve().parent;torch.set_num_threads(4);start=time.monotonic();sp=importlib.util.spec_from_file_location('_inkling2_visual',root/'component.py');mod=importlib.util.module_from_spec(sp);sys.modules[sp.name]=mod;sp.loader.exec_module(mod);ex=json.loads((root/'extraction.json').read_text());mapping=json.loads((root/'tensor_mapping.json').read_text());assert len(mapping)==ex['tensor_count']==422 and len(set(mod.convert_name(k) for k in mapping))==422
print('LOAD model',flush=True);model=mod.load_model(root,dtype=torch.float32);proc=mod.load_processor(root);assert len(model.layers)==23 and all(torch.isfinite(x).all() for x in model.state_dict().values());print('MODEL READY',flush=True)
assert len(sys.argv)==3, 'Usage: python validate_local_reference.py IMAGE1 IMAGE2'
images=[Path(x) for x in sys.argv[1:]];outputs=[];records=[]
for image in images:
b=proc(images=Image.open(image).convert('RGB'),return_tensors='pt');g=b['image_grid_thw'];t,h,w=g[0].tolist();assert g.shape==(1,3) and b['pixel_values'].shape==(t*h*w,40,40,3)
with torch.inference_mode():x=model(pixel_values=b['pixel_values'],image_grid_thw=g);y=model(pixel_values=b['pixel_values'],image_grid_thw=g)
a=x.last_hidden_state;z=x.pooler_output;assert a.shape==(t*h*w*4+1,1024) and z.shape==(t*h*w,4608),(a.shape,z.shape,g);assert torch.isfinite(a).all() and torch.isfinite(z).all();err=float((z-y.pooler_output).abs().max());assert err<1e-6;outputs.append(z);records.append({'image':image.name,'sha256':hashlib.sha256(image.read_bytes()).hexdigest(),'image_grid_thw':g.tolist()[0],'patch_features_shape':list(a.shape),'projected_features_shape':list(z.shape),'output_rms':float(z.square().mean().sqrt()),'repeat_max_abs_error':err});print('VALIDATED',image.name,flush=True)
assert outputs[0].shape==outputs[1].shape;delta=float((outputs[0]-outputs[1]).abs().mean());assert delta>1e-5
v={'passed':True,'source_revision':ex['source_revision'],'model_sha256':ex['sha256'],'tensor_count':422,'strict_load':True,'native_model_layers':23,'dtype_for_test':'CPU float32; artifact retains original BF16','runtime':'Local Transformers version '+__import__('transformers').__version__,'mapping':'Upstream v5.23.0 vision key renaming only, original weight-file names unchanged','processor':'Official Inkling2ImageProcessor from source processor_config.json','images':records,'different_image_mean_abs_difference':delta,'limitations':'Two real COCO128 images, repeat and input sensitivity only; no task performance or full multimodal pipeline.','seconds':round(time.monotonic()-start,2)};(root/'validation_local.json').write_text(json.dumps(v,indent=2)+'\n');print('VALIDATION PASSED',json.dumps(v),flush=True)