Download code/modal/qwen_gpu_validation.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 6.44 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/modal/qwen_gpu_validation.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/modal/qwen_gpu_validation.py
-
curl -L -o qwen_gpu_validation.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/modal/qwen_gpu_validation.py
6.44 kB
| """Bounded GPU equivalence validation, not a behavioral pilot.""" | |
| import os | |
| import json | |
| from pathlib import Path | |
| import modal | |
| app = modal.App('modelclinic-qwen-validation') | |
| volume = modal.Volume.from_name(os.environ.get("MODELCLINIC_MODAL_VOLUME", "modelclinic-cache"), create_if_missing=False) | |
| image = (modal.Image.debian_slim(python_version='3.11') | |
| .pip_install('torch==2.8.0') | |
| .pip_install('transformers==5.20.2','accelerate==1.12.0','huggingface-hub==2.4.0','safetensors==0.8.0') | |
| .add_local_file('code/src/interventions.py', '/root/project/interventions.py')) | |
| REPOS = [('Qwen/Qwen3.5-0.8B','2fc06364715b967f1860aea9cf38778875588b17','base','04b1c301231dd422b8860db31311ab2721511346a32cb1e079c4c4e5f1fe4696'), | |
| ('RikiyaT/Qwen3.5-0.8B-weight-space-programming','d1671a178705bcab7644806d23c535517f35723b','edited','fd1e42acdd118ac1b300d37500fd2885e75f5a09de3a33010d802bf7f737b553')] | |
| def prepare(): | |
| import hashlib,time | |
| from huggingface_hub import snapshot_download | |
| start=time.time(); result=[] | |
| for repo,rev,name,expected in REPOS: | |
| dst=f'/cache/modelclinic/{name}-{rev}' | |
| snapshot_download(repo_id=repo,revision=rev,local_dir=dst,allow_patterns=['*.json','*.jinja','*.txt','*.safetensors'],token=False,max_workers=4) | |
| p=Path(dst)/'model.safetensors-00001-of-00001.safetensors';h=hashlib.sha256() | |
| with p.open('rb') as f: | |
| for chunk in iter(lambda:f.read(4*1024*1024),b''):h.update(chunk) | |
| digest=h.hexdigest() | |
| if digest != expected: raise ValueError(f'{name} checkpoint SHA-256 mismatch') | |
| result.append({'repo':repo,'revision':rev,'sha256':digest,'size':p.stat().st_size,'path':dst}) | |
| volume.commit() | |
| return {'checkpoints':result,'seconds':time.time()-start} | |
| def validate(): | |
| import sys,time,gc,torch | |
| from contextlib import ExitStack | |
| from transformers import AutoTokenizer,Qwen3_5ForConditionalGeneration | |
| sys.path.insert(0,'/root/project') | |
| from interventions import additive_hook,replacement_hook | |
| volume.reload(); torch.manual_seed(123); torch.set_grad_enabled(False) | |
| assert torch.cuda.is_available() and torch.cuda.is_bf16_supported() | |
| start=time.time(); base=f'/cache/modelclinic/base-{REPOS[0][1]}'; edited=f'/cache/modelclinic/edited-{REPOS[1][1]}' | |
| tok=AutoTokenizer.from_pretrained(base,local_files_only=True) | |
| prompts=['What is 2 + 2?','Give the next number: 1, 4, 9,','A rectangle has sides 3 and 5. Find its area.'] | |
| inputs=[] | |
| for prompt in prompts: | |
| v=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,add_generation_prompt=True,enable_thinking=True,return_tensors='pt') | |
| inputs.append((v['input_ids'] if hasattr(v,'keys') else v).to('cuda')) | |
| def load(path): return Qwen3_5ForConditionalGeneration.from_pretrained(path,dtype=torch.bfloat16,local_files_only=True).eval().to('cuda') | |
| def layers(model):return [model.model.language_model.layers[i].mlp.down_proj for i in (15,19)] | |
| def forward(model,ids): | |
| captures=[]; handles=[m.register_forward_hook(lambda _m,_a,out: captures.append(out.detach().float().cpu())) for m in layers(model)] | |
| try: | |
| with torch.inference_mode(): out=model(input_ids=ids,use_cache=False,output_hidden_states=True) | |
| return captures,[v.detach().float().cpu() for v in out.hidden_states],out.logits.detach().float().cpu() | |
| finally: | |
| for h in handles:h.remove() | |
| edited_model=load(edited); edited_weights=[x.weight.detach().cpu().clone() for x in layers(edited_model)] | |
| reference=[forward(edited_model,x) for x in inputs] | |
| del edited_model;gc.collect();torch.cuda.empty_cache() | |
| model=load(base); mods=layers(model); deltas=[(e.float()-m.weight.detach().float().cpu()).to('cuda') for e,m in zip(edited_weights,mods)] | |
| def compare(a,b): | |
| d=(a-b).abs(); denom=torch.linalg.vector_norm(a).item() | |
| return {'max_abs':float(d.max()),'mean_abs':float(d.mean()),'relative_l2':float(torch.linalg.vector_norm(d))/max(denom,1e-30),'exact':bool(torch.equal(a,b))} | |
| data=[] | |
| for prompt,ids,ref in zip(prompts,inputs,reference): | |
| base_out=forward(model,ids) | |
| with ExitStack() as s: | |
| for m,d in zip(mods,deltas):s.enter_context(replacement_hook(m,delta=d)) | |
| rec=forward(model,ids) | |
| with ExitStack() as s: | |
| for m,d in zip(mods,deltas):s.enter_context(additive_hook(m,'delta',delta=d)) | |
| add=forward(model,ids) | |
| def summ(x):return {'layers':[compare(a,b) for a,b in zip(ref[0],x[0])],'hidden':[compare(a,b) for a,b in zip(ref[1],x[1])],'logits':compare(ref[2],x[2])} | |
| data.append({'prompt':prompt,'input_ids':ids[0].tolist(),'edited_logits_shape':list(ref[2].shape),'base_logits_shape':list(base_out[2].shape),'replacement':summ(rec),'additive':summ(add)}) | |
| with ExitStack() as s: | |
| for m,d in zip(mods,deltas):s.enter_context(replacement_hook(m,delta=d)) | |
| with torch.inference_mode(): generated=model.generate(input_ids=inputs[0],max_new_tokens=4,do_sample=False,use_cache=True,pad_token_id=tok.eos_token_id) | |
| tail=generated[0,inputs[0].shape[-1]:].tolist();torch.cuda.synchronize(); free,total=torch.cuda.mem_get_info() | |
| return {'hardware':{'gpu':torch.cuda.get_device_name(),'total_vram_bytes':total,'free_vram_bytes':free,'peak_allocated_bytes':torch.cuda.max_memory_allocated(),'torch':torch.__version__,'cuda':torch.version.cuda,'bf16':torch.cuda.is_bf16_supported()},'precision':'bfloat16','model_class':type(model).__name__,'tokenizer_class':type(tok).__name__,'generation':{'max_new_tokens':4,'token_ids':tail,'text':tok.decode(tail)},'prefixes':data,'seconds':time.time()-start} | |
| def main(): | |
| prep=prepare.remote();Path('results/checkpoint_analysis/modal_checkpoint_preparation.json').write_text(json.dumps(prep,indent=2)); print('Pinned checkpoint preparation complete',flush=True) | |
| result=validate.remote();Path('results/checkpoint_analysis/modal_qwen_validation.json').write_text(json.dumps(result,indent=2));print('Validation results saved',flush=True) | |