Download appendix/code/training.py from BradJu/attribute-ownership-negative-experiments: direct link, hf CLI and curl.
- Browser
- Download file 3.49 kB
-
https://huggingface.co/datasets/BradJu/attribute-ownership-negative-experiments/resolve/main/appendix/code/training.py
- Command line
-
hf download hf://datasets/BradJu/attribute-ownership-negative-experiments/appendix/code/training.py
-
curl -L -o training.py https://huggingface.co/datasets/BradJu/attribute-ownership-negative-experiments/resolve/main/appendix/code/training.py
3.49 kB
| """Pinned teacher-distillation implementation, shared by job and CPU smoke.""" | |
| import json,sys | |
| from pathlib import Path | |
| sys.modules['vllm']=None | |
| def trajectories(rows): | |
| from agenttune.agentic.events import Event,EventKind,EventLog | |
| logs=[] | |
| for row in rows: | |
| log=EventLog(tier='full');log.append(Event(EventKind.OBSERVATION,{'text':row['initial_prompt']})) | |
| for i,c in enumerate(row['calls']): | |
| log.append(Event(EventKind.TEXT,{'text':json.dumps(c['action'],sort_keys=True)})) | |
| if i<len(row['calls'])-1:log.append(Event(EventKind.OBSERVATION,{'text':json.dumps({'tool_result':c['result']},sort_keys=True)})) | |
| logs.append(log) | |
| return logs | |
| def assistant_labels(tokenizer,messages): | |
| ids=tokenizer.apply_chat_template(messages,tokenize=True,return_dict=True)['input_ids'];labels=[-100]*len(ids) | |
| for i,message in enumerate(messages): | |
| if message['role']!='assistant':continue | |
| prefix=tokenizer.apply_chat_template(messages[:i],tokenize=True,add_generation_prompt=True,return_dict=True)['input_ids'] | |
| full=tokenizer.apply_chat_template(messages[:i+1],tokenize=True,return_dict=True)['input_ids'] | |
| assert ids[:len(prefix)]==prefix and ids[:len(full)]==full | |
| labels[len(prefix):len(full)]=ids[len(prefix):len(full)] | |
| return tuple(labels) | |
| def train(student,rows,output,config): | |
| import torch,trl | |
| from transformers import AutoTokenizer | |
| from agenttune.agentic.distill_trainer import create_distill_trainer | |
| tok=AutoTokenizer.from_pretrained(student);logs=trajectories(rows) | |
| trainer=create_distill_trainer(student=str(student),trajectories=logs,output_dir=str(output),lora_r=16,lora_alpha=32,lora_dropout=.05,lora_targets=['q_proj','k_proj','v_proj','o_proj'],max_steps=config['max_steps'],per_device_train_batch_size=1,gradient_accumulation_steps=config['gradient_accumulation_steps'],learning_rate=2e-4,seed=20261104,bf16=config['bf16'],gradient_checkpointing=config['gradient_checkpointing'],report_to='none',assistant_only_loss=True,save_strategy='no',max_length=config['max_length'],device_map={'':'cuda'} if config['bf16'] else None) | |
| expected={assistant_labels(tok,row['messages']) for row in trainer.sft_dataset()};assert all(any(v!=-100 for v in e) for e in expected) | |
| assert max(map(len,expected))<=config['max_length'],'No truncation permitted' | |
| seen=[];original=trl.SFTTrainer.compute_loss | |
| def check(self,model,inputs,*a,**k): | |
| cfg=self.args | |
| assert cfg.assistant_only_loss and cfg.learning_rate==2e-4 and cfg.max_steps==config['max_steps'] | |
| assert cfg.gradient_accumulation_steps==config['gradient_accumulation_steps'] and cfg.per_device_train_batch_size==1 and cfg.seed==20261104 | |
| assert cfg.bf16==config['bf16'] and cfg.gradient_checkpointing==config['gradient_checkpointing'] | |
| lora=model.peft_config['default'];assert lora.r==16 and lora.lora_alpha==32 and set(lora.target_modules)=={'q_proj','k_proj','v_proj','o_proj'} | |
| for labels in inputs['labels']: | |
| values=tuple(labels.tolist());assert any(values[:len(e)]==e and all(v==-100 for v in values[len(e):]) for e in expected),'Loss mask mismatch' | |
| seen.append(1);return original(self,model,inputs,*a,**k) | |
| trl.SFTTrainer.compute_loss=check | |
| try:trainer.train() | |
| finally:trl.SFTTrainer.compute_loss=original | |
| assert seen | |
| path=Path(output)/'adapter';trainer.trainer_factory.sft_trainer.model.save_pretrained(path) | |
| assert (path/'adapter_model.safetensors').exists() and (path/'adapter_config.json').exists() | |
| return trainer,{'verified_batches':len(seen),'training_rows':len(rows),'saved_adapter':True} | |