fromsafetune.hardenimportvaccine_loss,VaccineConfigconfig=VaccineConfig(rho=1e-3)task_loss_fn=lambdam,b:m(**b).lossforbatchindataloader:# your own tokenized batches, with "labels" setoptimizer.zero_grad()loss=vaccine_loss(model,batch,task_loss_fn,config=config)loss.backward()optimizer.step()
@article{vaccine2024,title={Vaccine: Perturbation-Aware Alignment for Large Language Models against Harmful Fine-Tuning},year={2024},note={arXiv:2402.01109},}
Best for: immunizing the model during alignment-stage SFT by perturbing attention-layer hidden states with a globally normalized SAM step before computing the task loss, making representations robust to later harmful fine-tuning.
Trade-offs: adds a forward + autograd pass per step; larger rho increases safety robustness at a small accuracy cost.
@article{vaccine2024,title={Vaccine: Perturbation-Aware Alignment for Large Language Models against Harmful Fine-Tuning},author={Huang, et al.},year={2024},note={NeurIPS 2024, arXiv:2402.01109},}
# Runner-style API (safetune.runner.harden)TVaccineTrainer(model:PreTrainedModel|None=None,tokenizer:PreTrainedTokenizer|None=None,*,rho:float=2.0,top_k_ratio:float=0.5,**kwargs,)
Temperature of the contrastive safety loss \(L_{\text{safe}}\)
The contrastive safety batches (safety_dataloader) are passed to trainer.train(...), not the constructor — see the Full example below. They carry the keys input_ids, attention_mask, chosen_labels, rejected_labels.
Best for: bilevel training with a hidden-state probe that simulates a harmful weight perturbation ΔW_harmful each step and trains the model to keep the safe-useful gap under it.
Trade-offs: requires contrastive safety batches with chosen_labels / rejected_labels.
The separate harmful batch (harmful_dataset) is passed to trainer.train(...), not the constructor — see the Full example below. If absent, the trainer falls back to using the task batch as X_m (documented shortcut).
@article{surgery2026,title={Surgery: Mitigating Harmful Fine-Tuning for Large Language Models via Attention Sink},year={2026},note={arXiv:2602.05228},}