Download appendix/code/inference_core.py from BradJu/attribute-ownership-negative-experiments: direct link, hf CLI and curl.
- Browser
- Download file 1.23 kB
-
https://huggingface.co/datasets/BradJu/attribute-ownership-negative-experiments/resolve/main/appendix/code/inference_core.py
- Command line
-
hf download hf://datasets/BradJu/attribute-ownership-negative-experiments/appendix/code/inference_core.py
-
curl -L -o inference_core.py https://huggingface.co/datasets/BradJu/attribute-ownership-negative-experiments/resolve/main/appendix/code/inference_core.py
1.23 kB
| """Portable inference helpers, copied from the regression runner.""" | |
| import json | |
| import environment | |
| def load_model(base,adapter=None,device='cuda'): | |
| import torch | |
| from transformers import AutoModelForCausalLM | |
| model=AutoModelForCausalLM.from_pretrained(base,dtype=torch.bfloat16 if device=='cuda' else torch.float32,device_map={'':device},attn_implementation='sdpa') | |
| if adapter: | |
| from peft import PeftModel | |
| model=PeftModel.from_pretrained(model,adapter,is_trainable=False) | |
| model.eval();model.requires_grad_(False);return model | |
| def evaluate(model,tok,rows,plan,checkpoint): | |
| import torch | |
| results=[] | |
| def generate(messages): | |
| ids=tok.apply_chat_template(messages,tokenize=True,add_generation_prompt=True,return_tensors='pt',return_dict=True)['input_ids'].to(model.device) | |
| if ids.shape[-1]>plan['max_context']:raise ValueError('context limit') | |
| with torch.inference_mode(): | |
| output=model.generate(input_ids=ids,attention_mask=torch.ones_like(ids),do_sample=False,max_new_tokens=plan['max_new_tokens'],pad_token_id=tok.eos_token_id) | |
| return tok.decode(output[0,ids.shape[-1]:],skip_special_tokens=True) | |
| for row in rows: | |
| result=environment.execute(row,generate);results.append(result);checkpoint(results) | |
| return results | |