TL;DR
Fine-tuning safety-aligned large language models (LLMs) on downstream datasets often inadvertently erodes their safety guardrails. This paper introduces Safety Optimal Transport (SOT), a framework that reframes data purification from an instance-level filtering problem into a distribution-level alignment task. By geometrically "pulling" the fine-tuning data distribution toward a trusted safe anchor and "pushing" it away from a harmful reference, SOT successfully blocks toxic content without sacrificing downstream model utility.
What Problem Does This Paper Address?
Before deployment, foundation LLMs undergo rigorous safety alignment (via techniques like RLHF or DPO) to ensure they refuse harmful requests. However, recent studies show that subsequent custom fine-tuning can easily break these safeguards—a vulnerability known as safety erosion. Remarkably, this can happen even when the downstream dataset appears entirely benign or contains only a tiny fraction of toxic examples.
Existing defenses typically try to clean the fine-tuning data using heuristic, instance-level filtering. These methods suffer from two main flaws:
- They evaluate data points in isolation, completely ignoring the global geometric structure of the data manifold.
- They follow a single-reference paradigm, focusing only on attracting the model to safe examples while failing to explicitly use harmful data as a negative reference for active repulsion.
As a result, clever adversarial attacks or "hard negatives" (harmful data camouflaged as benign tasks) easily slip through.
Methods
The authors introduce Safety Optimal Transport (SOT), a two-stage framework that leverages the mathematics of Optimal Transport (OT) to clean and weight training data globally.
Stage 1: Dual-Reference Distributional Weight Learning
Instead of making independent binary decisions on whether to keep or drop a sample, SOT models the downstream dataset as a continuous empirical distribution with learnable sample weights. It then optimizes these weights using an entropy-regularized OT objective guided by a "push-pull" dynamic:
- The Pull Force: Minimizes the OT distance between the custom dataset and a small, verified task-specific safe anchor distribution ($Q$). This ensures the model prioritizes safe, utility-preserving samples.
- The Push Force: Maximizes the OT distance between the custom dataset and a general harmful reference distribution ($M$). This acts as a discriminator to penalize samples that semantically resemble toxic patterns.
To compute the underlying transport cost matrix, SOT extracts the last-layer hidden state representations of the data using a frozen, pre-aligned LLM, decoupling the weight-learning phase from the model being fine-tuned.
Stage 2: Safety-Aware Fine-Tuning
Once the optimal weights are learned, SOT applies a two-pronged strategy:
- Hard Denoising (Top-K Selection): It truncates the data, completely discarding the lowest-weighted samples (the toxic tail) to eliminate severe adversarial risks.
- Soft Emphasis (Weighted SFT): It re-normalizes the weights of the remaining safe subset and uses them to modulate the gradient magnitude of each sample during standard Supervised Fine-Tuning (SFT) with LoRA.
Datasets
The authors evaluated SOT across several distinct downstream tasks and reference datasets:
- Downstream Fine-Tuning Tasks: SLIMORCA (general instruction), MetaMathQA & GSM8K (mathematical reasoning), AGNews (classification), and LegalBench-QA (specialized legal domain).
- Harmful Contamination: To simulate real-world vulnerabilities, the fine-tuning datasets were artificially contaminated with a subset of the Anthropic HH (red-team-attempts) dataset.
- SOT Reference Anchors: The general harmful reference ($M$) was built using 5,000 samples from the BeaverTails dataset. The safe reference ($Q$) required only 50 verified samples from the respective target downstream task.
Key Insights and Ideas
- The Necessity of Dual Forces: A key "aha moment" from the paper's ablation studies is that the "Push" and "Pull" objectives are mutually indispensable. Relying only on "Pull" correctly identifies safe data but fails to suppress harmful outliers due to distribution overlap. Relying only on "Push" avoids toxicity but causes "semantic drift," where the model loses downstream task coherence.
- Asymmetric Data Efficiency: SOT exhibits a fascinating asymmetry in its data requirements. The safe "Pull" anchor saturates rapidly, meaning the framework achieves near-optimal guidance with as few as 10 to 50 clean samples. Conversely, the harmful "Push" mechanism scales with more data, as it needs to map a much wider, high-variance manifold of potential human toxicity.
- Defeating Camouflaged Harm: By looking at the global geometry rather than surface-level keywords, SOT successfully identifies complex adversarial edge cases. For instance, it correctly down-weights explicit sexual content that has been masked as a simple lowercase formatting task—an exploit that standard instance-level filters frequently miss.
Key Results
SOT consistently achieved a superior safety-utility trade-off compared to competitive baselines like DSIR, SAFT, and SEAL across multiple model families (including Llama-3.1-8B, Qwen3-8B, and Gemma-3-4B).
- Simultaneous Safety and Utility Gains: When fine-tuning Meta-Llama-3.1-8B-Instruct on the SLIMORCA dataset, SOT slashed the Harmfulness Score (HmS) from 0.426 (Standard SFT) to 0.197, while simultaneously boosting the Helpfulness Score (HpS) from 3.764 to 3.895.
- Robustness to High Contamination: Even when the training data was heavily corrupted with up to 20% harmful samples, SOT maintained a stable, high overall performance profile, whereas baseline methods suffered catastrophic safety degradation.
- Domain Generalization: On the highly specialized LegalBench-QA dataset, SOT secured the highest average score (0.834) and the lowest harmfulness score (0.105) among all tested methods, proving its viability for high-stakes, specialized deployment.
Limitations and Future Work
The authors candidly point out a few limitations of the current SOT framework:
- Static Reference Constraints: SOT assumes that the reference distributions are static. It may struggle to defend against rapidly evolving, novel adversarial vectors (such as multilingual jailbreaks or cryptographic attacks) unless the reference datasets are continuously updated.
- Lack of Explainability: While SOT provides precise quantitative weights for data filtering, it operates as a geometric black box and cannot output natural language explanations detailing * why* a specific sample was flagged as harmful.
- Proxy Evaluation Bias: The evaluation relies heavily on LLM-as-a-judge metrics (using models like DeepSeek-V3), which can introduce inherent model biases compared to gold-standard human evaluation.
Summary updated