Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

## 📖 Overview

We provide efficient and streamlined implementations of the TOFU, MUSE and WMDP unlearning benchmarks while supporting 17+ unlearning methods, 5+ datasets, 10+ evaluation metrics, and 7+ LLM architectures. Each of these can be easily extended to incorporate more variants.
We provide efficient and streamlined implementations of the TOFU, MUSE and WMDP unlearning benchmarks while supporting 18+ unlearning methods, 5+ datasets, 10+ evaluation metrics, and 7+ LLM architectures. Each of these can be easily extended to incorporate more variants.

We invite the LLM unlearning community to collaborate by adding new benchmarks, unlearning methods, datasets and evaluation metrics here to expand OpenUnlearning's features, gain feedback from wider usage and drive progress in the field.

Expand Down Expand Up @@ -84,7 +84,7 @@ We provide several variants for each of the components in the unlearning pipelin
| **Component** | **Available Options** |
|------------------------|----------------------|
| **Benchmarks** | [TOFU](https://arxiv.org/abs/2401.06121), [MUSE](https://muse-bench.github.io/), [WMDP](https://www.wmdp.ai/), [DUET](https://arxiv.org/abs/2602.19612) |
| **Unlearning Methods** | GradAscent, GradDiff, NPO, SimNPO, DPO, RMU, UNDIAL, AltPO, SatImp, WGA, CE-U, PDU, AdaPop, T3, PALU, K-FORGE, BalDRO |
| **Unlearning Methods** | GradAscent, GradDiff, NPO, SimNPO, DPO, RMU, UNDIAL, AltPO, SatImp, WGA, CE-U, PDU, AdaPop, T3, PALU, K-FORGE, BalDRO, RepSelect |
| **Evaluation Metrics** | Verbatim Probability, Verbatim ROUGE, Knowledge QA-ROUGE, Model Utility, Forget Quality, TruthRatio, Extraction Strength, Exact Memorization, 6 MIA attacks, [Unlearning Depth Score](https://arxiv.org/abs/2605.24614), [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) |
| **Datasets** | MUSE-News (BBC), MUSE-Books (Harry Potter), TOFU (different splits), WMDP-Bio, WMDP-Cyber, [DUET](https://huggingface.co/datasets/SwetieePawsss/DUET) (rare / popular Wikidata facts) |
| **Model Families** | TOFU: Llama-3.2, Llama-3.1, Llama-2; MUSE: Llama-2; DUET: Llama-3.1, Qwen2.5, Gemma; Additional: Phi-3.5, Phi-1.5, Gemma, Zephyr |
Expand Down
76 changes: 76 additions & 0 deletions community/methods/RepSelect/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# RepSelect: Robust LLM Unlearning via Representation Selectivity

- Authors: Filip Sondej, Yushi Yang, Adam Mahdi
- Paper: https://arxiv.org/abs/2606.17168
- Code: https://github.com/filyp/RepSelect

Unlearning methods that follow the raw forget gradient also edit representations that the forget set shares with the retain set.
Those edits disrupt general capabilities, and they are the ones that fine-tuning attacks restore most easily.
RepSelect keeps only the part of the forget gradient that is specific to the forget set, and applies it as a single update of the MLP weights.

For each MLP weight matrix (`gate_proj`, `up_proj`, `down_proj` of every layer):

1. One pass over the retain set accumulates the weight gradient, and its top `n_pcs` singular triplets `U, S, V` are computed.
2. One pass over the forget set accumulates the weight gradient.
3. The forget gradient is collapsed along the retain singular vectors, on the input side (`V`) and on the output side (`U`): its component along each vector is divided by `S^2`. The rest of the gradient is left as is.
4. The collapsed gradient is subtracted from the weight once, scaled by `strength`.

There is no optimizer and no training loop: the whole method is one pass over the data and one SVD per weight matrix.

Optionally (`lora_learning_rate`), a LoRA is first trained for one pass to lower the forget loss, and is kept active while the two gradients are computed.
It is removed before the update.
This elicitation is off by default.

Note: the main results in the paper use an older RepSelect variant, while this implementation in open-unlearning is the recommended better variant, based on follow-up results (see Appendix A in the paper). Changes: 1. we now compute SVD on the retain, not the forget distribution; 2. during the collapse, we now divide by the *squared* singular values; 3. for simplicity LoRA elicitation is off by default.

# Setup

- **Hyperparameters:**
- `trainer.method_args.strength` (default 2.5): the size of the single update step, and the main parameter to tune. It trades forgetting against utility.
- `trainer.method_args.n_pcs` (default 512): the number of retain singular vectors to collapse along, per side.
- `trainer.method_args.lora_learning_rate` (default `null`): SGD learning rate of the LoRA elicitation, e.g. 0.01; `null` skips it. Needs `peft`.
- **Computational Setup:** One GPU. The method needs one pass (forward and backward) over the retain batches and one over the forget batches, plus one low-rank SVD per MLP weight matrix. The elicitation adds one more pass over the forget batches.
- **Other Minor Details:** The model has to expose its blocks as `model.model.layers[i].mlp` with `gate_proj`, `up_proj`, `down_proj` (Llama, Qwen, Gemma, Mistral/Zephyr), or with transformers' fused MoE `experts` module. The retain pass covers the whole retain set, unlike other methods here, which sample one retain example per forget example. For huge retain sets, you may cap it in the data config, e.g. `data.retain.TOFU_QA_retain.args.hf_args.split='"train[:10000]"'`.

# Results

Run `community/methods/RepSelect/run_with_relearning_attack.sh` to reproduce the table below, or `community/methods/RepSelect/run.sh` for plain unlearning and the standard TOFU evaluation.

RepSelect's purpose is robustness to attacks, so we evaluate it under a relearning attack, with held-out evaluation as in [Deeb & Roger (2024)](https://arxiv.org/abs/2410.08827).
Each model is unlearned on all of TOFU `forget10`, then the attacker fine-tunes it for one epoch on the first half of `forget10` (10 authors), and we evaluate on the second half (the other 10 authors).
The attacker never sees the evaluated questions, so what comes back on them was still in the weights.

Llama-3.2-1B-Instruct, values are pre-attack → post-attack on the held-out half, `model_utility` is pre-attack, one run per row:

| model | forget_Q_A_Prob | forget_Q_A_ROUGE | extraction_strength | model_utility |
| --------------------------------- | --------------- | ---------------- | ------------------- | ------------- |
| Target model (no unlearning) | 0.885 → 0.875 | 0.829 → 0.779 | 0.729 → 0.689 | 0.597 |
| Retain model (never saw forget10) | 0.123 → 0.210 | 0.378 → 0.369 | 0.061 → 0.071 | 0.590 |
| NPO | 0.106 → 0.484 | 0.291 → 0.429 | 0.100 → 0.177 | 0.574 |
| RepSelect, strength 2.5 | 0.477 → 0.562 | 0.476 → 0.498 | 0.209 → 0.234 | 0.597 |
| RepSelect, strength 5 | 0.284 → 0.421 | 0.421 → 0.433 | 0.119 → 0.156 | 0.590 |
| RepSelect, strength 10 | 0.149 → 0.298 | 0.376 → 0.408 | 0.086 → 0.099 | 0.573 |

- RepSelect uses `n_pcs=512` and no LoRA elicitation.
- NPO uses the repository's default hyperparameters for 250 steps.
- The retain model was never trained on `forget10`: its row shows how much the attack raises the scores on its own.
- The attack's learning rate (1e-5, batch size 8) is the value from {1e-6, 3e-6, 1e-5, 3e-5, 1e-4, 3e-4} that recovers the most forget probability on RepSelect (strength 5). It was not tuned against NPO.

Note: in TOFU, the knowledge to forget was added to the model by a short fine-tuning.
[Deeb & Roger (2024)](https://arxiv.org/abs/2410.08827) found that such recently added knowledge is easier to unlearn robustly than knowledge learned during pretraining.
So the numbers above, for every method, likely overestimate robustness on real pretrained knowledge.

The results of each run are written to `saves/unlearn/<task_name>/evals_heldout/TOFU_SUMMARY.json` (pre-attack) and `saves/finetune/<task_name>_relearned/evals_heldout/TOFU_SUMMARY.json` (post-attack).


# Citation

```bibtex
@inproceedings{sondej2027repselect,
title={RepSelect: Robust LLM Unlearning via Representation Selectivity},
author={Sondej, Filip and Yang, Yushi and Mahdi, Adam},
booktitle={Proceedings of the Conference of the European Chapter of the Association for Computational Linguistics (EACL)},
year={2027},
note={To appear. arXiv:2606.17168}
}
```
47 changes: 47 additions & 0 deletions community/methods/RepSelect/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/bin/bash
# RepSelect on TOFU (Llama-3.2-1B-Instruct): unlearn, then evaluate.
#
# strength is the size of RepSelect's single update step. Several values are run, to
# trace the forgetting / utility trade-off.

model="Llama-3.2-1B-Instruct"
forget_retain_splits=(
"forget10 retain90"
)
strengths=(2.5 5 10)

for split in "${forget_retain_splits[@]}"; do
forget_split=$(echo $split | cut -d' ' -f1)
retain_split=$(echo $split | cut -d' ' -f2)
for strength in "${strengths[@]}"; do
task_name=tofu_${model}_${forget_split}_RepSelect_strength${strength}
model_path=open-unlearning/tofu_${model}_full

# Unlearn
CUDA_VISIBLE_DEVICES=0 \
python src/train.py --config-name=unlearn.yaml \
experiment=unlearn/tofu/default.yaml \
trainer=RepSelect \
task_name=${task_name} \
model=${model} \
forget_split=${forget_split} \
retain_split=${retain_split} \
model.model_args.pretrained_model_name_or_path=${model_path} \
retain_logs_path=saves/eval/tofu_${model}_${retain_split}/TOFU_EVAL.json \
trainer.method_args.strength=${strength} \
trainer.method_args.n_pcs=512 \
trainer.args.do_eval=False \
trainer.args.eval_strategy=no \
trainer.args.eval_on_start=False

# Eval
CUDA_VISIBLE_DEVICES=0 python src/eval.py \
experiment=eval/tofu/default.yaml \
forget_split=${forget_split} \
model=${model} \
task_name=${task_name} \
model.model_args.pretrained_model_name_or_path=saves/unlearn/${task_name} \
paths.output_dir=saves/unlearn/${task_name}/evals \
retain_logs_path=saves/eval/tofu_${model}_${retain_split}/TOFU_EVAL.json
done
done
107 changes: 107 additions & 0 deletions community/methods/RepSelect/run_with_relearning_attack.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
#!/bin/bash
# RepSelect and NPO on TOFU (Llama-3.2-1B-Instruct) under a relearning attack, evaluated
# on forget samples that the attacker does not have (as in arxiv.org/abs/2410.08827).
#
# For each run:
# 1. unlearn the whole forget split
# 2. evaluate on the second half of the forget split (pre-attack)
# 3. attack: fine-tune for one epoch on the first half of the forget split
# 4. evaluate on the second half again (post-attack)
#
# forget10 is 20 authors x 20 questions, in order, so the two halves are disjoint
# sets of 10 authors. The attacker never sees the evaluated questions: what comes
# back on them was still in the weights.
#
# The last two runs are references under the same attack, without any unlearning:
# the target model, and the retain model, which never saw the forget split. The
# retain model shows how much the attack teaches on its own.
#
# Results: saves/unlearn/<task>/evals_heldout/TOFU_SUMMARY.json (pre-attack) and
# saves/finetune/<task>_relearned/evals_heldout/TOFU_SUMMARY.json (post-attack);
# for the references, the pre-attack one is in saves/finetune/<task>/evals_heldout/

model="Llama-3.2-1B-Instruct"
forget_split="forget10"
retain_split="retain90"
relearn_subset='"train[:50%]"' # the attacker's half of the forget split
heldout_subset='"train[50%:]"' # the evaluated half
relearn_lr=1e-5 # of the grid 1e-6 ... 3e-4, the one that recovers the most on RepSelect

target_model=open-unlearning/tofu_${model}_full

evaluate() { # <model path> <output dir>
CUDA_VISIBLE_DEVICES=0 python src/eval.py \
experiment=eval/tofu/default.yaml \
eval=tofu_forget_subset \
"eval.tofu.forget_subset=${heldout_subset}" \
forget_split=${forget_split} \
model=${model} \
task_name=heldout_eval \
model.model_args.pretrained_model_name_or_path=$1 \
paths.output_dir=$2
}

relearn() { # <model path> <task name>; saves to saves/finetune/<task name>
CUDA_VISIBLE_DEVICES=0 python src/train.py --config-name=train.yaml \
experiment=finetune/tofu/default.yaml \
task_name=$2 \
model=${model} \
model.model_args.pretrained_model_name_or_path=$1 \
data/datasets@data.train=TOFU_QA_forget \
data.train.TOFU_QA_forget.args.hf_args.name=${forget_split} \
"data.train.TOFU_QA_forget.args.hf_args.split=${relearn_subset}" \
trainer.args.learning_rate=${relearn_lr} \
trainer.args.num_train_epochs=1 \
trainer.args.gradient_accumulation_steps=1 \
trainer.args.warmup_epochs=0 \
+trainer.args.lr_scheduler_type=constant \
trainer.args.do_eval=False \
trainer.args.eval_strategy=no \
trainer.args.eval_on_start=False
}

unlearn_attack_eval() { # <task name> <trainer overrides ...>
task_name=$1
shift

CUDA_VISIBLE_DEVICES=0 python src/train.py --config-name=unlearn.yaml \
experiment=unlearn/tofu/default.yaml \
task_name=${task_name} \
model=${model} \
forget_split=${forget_split} \
retain_split=${retain_split} \
model.model_args.pretrained_model_name_or_path=${target_model} \
trainer.args.do_eval=False \
trainer.args.eval_strategy=no \
trainer.args.eval_on_start=False \
"$@"

evaluate saves/unlearn/${task_name} saves/unlearn/${task_name}/evals_heldout
relearn saves/unlearn/${task_name} ${task_name}_relearned
evaluate saves/finetune/${task_name}_relearned saves/finetune/${task_name}_relearned/evals_heldout
}

for strength in 2.5 5 10; do
unlearn_attack_eval tofu_${model}_${forget_split}_RepSelect_strength${strength} \
trainer=RepSelect \
trainer.method_args.strength=${strength} \
trainer.method_args.n_pcs=512
done

# NPO with the repository's default hyperparameters, for 250 steps
# (batch 4 x 8 accumulation steps: the default effective batch of 32, fits in 16 GB)
unlearn_attack_eval tofu_${model}_${forget_split}_NPO \
trainer=NPO \
+trainer.args.max_steps=250 \
trainer.args.per_device_train_batch_size=4 \
trainer.args.gradient_accumulation_steps=8

# references under the same attack, without any unlearning:
# the target model, and the retain model, which never saw the forget split
for reference in full ${retain_split}; do
task_name=tofu_${model}_${reference}_reference
reference_model=open-unlearning/tofu_${model}_${reference}
evaluate ${reference_model} saves/finetune/${task_name}/evals_heldout
relearn ${reference_model} ${task_name}_relearned
evaluate saves/finetune/${task_name}_relearned saves/finetune/${task_name}_relearned/evals_heldout
done
38 changes: 38 additions & 0 deletions configs/eval/tofu_forget_subset.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# @package eval.tofu
# NOTE: the above line is not a comment, but sets the package for config.

# The TOFU evaluation with the forget metrics computed on a slice of the forget split
# (forget_subset) instead of all of it. Used to evaluate on forget samples held out
# from a relearning attack: relearn on "train[:50%]", evaluate on "train[50%:]".
# forget_quality and privleak are left out: their reference logs cover the full split.

defaults:
- tofu_metrics:
- forget_Truth_Ratio
- forget_Q_A_Prob
- forget_Q_A_ROUGE
- extraction_strength
- model_utility

handler: TOFUEvaluator
output_dir: ${paths.output_dir} # set to default eval directory
metrics:
forget_Q_A_Prob:
datasets: {TOFU_QA_forget: {args: {hf_args: {split: "${eval.tofu.forget_subset}"}}}}
forget_Q_A_ROUGE:
datasets: {TOFU_QA_forget: {args: {hf_args: {split: "${eval.tofu.forget_subset}"}}}}
extraction_strength:
datasets: {TOFU_QA_forget: {args: {hf_args: {split: "${eval.tofu.forget_subset}"}}}}
forget_truth_ratio:
pre_compute:
forget_Q_A_PARA_Prob:
datasets: {TOFU_QA_forget_para: {args: {hf_args: {split: "${eval.tofu.forget_subset}"}}}}
forget_Q_A_PERT_Prob:
datasets: {TOFU_QA_forget_pert: {args: {hf_args: {split: "${eval.tofu.forget_subset}"}}}}
overwrite: false
forget_split: forget10
forget_subset: "train[50%:]"
holdout_split: holdout10
retain_logs_path: null
question_key: "question"
batch_size: 32
8 changes: 8 additions & 0 deletions configs/trainer/RepSelect.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
defaults:
- finetune

handler: RepSelect
method_args:
strength: 2.5 # the size of the single update step (trainer.args.learning_rate is not used)
n_pcs: 512 # retain singular vectors to collapse along, per side of each weight
lora_learning_rate: null # null: no LoRA elicitation (default); else its SGD learning rate (e.g. 0.01)
1 change: 1 addition & 0 deletions docs/links.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Links to research papers and resources corresponding to implemented features in
| PALU | Paper[📄](https://arxiv.org/abs/2601.03190), Code [🐙](https://github.com/nxZhai/PALU) |
| K-FORGE | Findings of IJCNLP-AACL 2026, Code [🐙](https://github.com/etomoscow/kron_unlearn) |
| BalDRO | Paper[📄](https://arxiv.org/abs/2601.09172), Code [🐙](https://github.com/nxZhai/BalDRO) |
| RepSelect | Paper[📄](https://arxiv.org/abs/2606.17168), Code [🐙](https://github.com/filyp/RepSelect) |


---
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@ tensorboard==2.18.0
scikit-learn==1.5.2
deepspeed==0.15.4
wandb==0.21.4
# for the optional LoRA elicitation of RepSelect:
peft==0.18.1
# for Qwen3.5 speedup:
flash-linear-attention==0.4.2
4 changes: 2 additions & 2 deletions src/evals/metrics/mia/min_k_plus_plus.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ def compute_batch_values(self, batch):

def compute_score(self, sample_stats):
"""Score using min-k negative log probs scores with vocab-wise normalization."""
all_probs = sample_stats["vocab_log_probs"]
target_prob = sample_stats["token_log_probs"]
all_probs = sample_stats["vocab_log_probs"].float()
target_prob = sample_stats["token_log_probs"].float()

if len(target_prob) == 0:
return 0
Expand Down
6 changes: 3 additions & 3 deletions src/evals/metrics/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def evaluate_probability(model, batch):
batch = {k: v.to(model.device) for k, v in batch.items()}
with torch.no_grad():
output = model(**batch)
logits = output.logits
logits = output.logits.float()
labels = batch["labels"]
shifted_labels = labels[..., 1:].contiguous()
logits = logits[..., :-1, :].contiguous()
Expand Down Expand Up @@ -115,7 +115,7 @@ def tokenwise_logprobs(model, batch, grad=False, return_labels=False):
with torch.set_grad_enabled(grad):
output = model(**batch)

logits = output.logits
logits = output.logits.float()
bsz, seq_len, V = logits.shape
log_probs = torch.nn.functional.log_softmax(logits, dim=-1)[:, :-1, :]
# ^ we don't predict next token for last token, bsz x seq_len-1 x V
Expand Down Expand Up @@ -158,7 +158,7 @@ def tokenwise_vocab_logprobs(model, batch, grad=False, return_labels=False):
with torch.set_grad_enabled(grad):
output = model(**batch)

logits = output.logits
logits = output.logits.float()
bsz, seq_len, V = logits.shape
log_probs = torch.nn.functional.log_softmax(logits, dim=-1)[
:, :-1, :
Expand Down
2 changes: 2 additions & 0 deletions src/trainer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from trainer.unlearn.t3 import T3
from trainer.unlearn.palu import PALU
from trainer.unlearn.kforge import KFORGE
from trainer.unlearn.repselect import RepSelect


import logging
Expand Down Expand Up @@ -121,3 +122,4 @@ def load_trainer(
_register_trainer(GroupNPO)
_register_trainer(GroupSimNPO)
_register_trainer(GroupSatImp)
_register_trainer(RepSelect)
Loading
Loading