A professional Python library for machine unlearning of Large Language Models.
Project description
Forgetium
Machine unlearning for Large Language Models — without retraining.
Forgetium is a professional, research-grade Python library for post-hoc machine unlearning of HuggingFace causal language models. When your model memorized something it shouldn't — a fact, a copyrighted passage, a piece of PII, a hazardous procedure — Forgetium gives you principled, peer-reviewed algorithms to make it forget, without retraining from scratch.
Install
pip install forgetium
The 3-line example
from forgetium import unlearn
result = unlearn(
model="Qwen/Qwen2.5-0.5B-Instruct",
forget="What is the capital of France?",
)
print("Before:", result.before["What is the capital of France?"])
print("After: ", result.after["What is the capital of France?"])
Output:
Before: The capital of France is Paris.
After: I'm not sure about that.
That's it. No dataset preparation, no hyperparameter tuning, no method picking. Forgetium loads the model, builds a retain set automatically by self-prompting the model with diverse questions, picks an appropriate method and hyperparameters based on the model size, runs unlearning, and hands you back the modified model.
The model in result.model is a regular transformers.PreTrainedModel you can save with result.save("./out"), push with result.push_to_hub("you/repo"), or use directly.
What it actually does in the background
When you call unlearn(model=..., forget=...):
- Loads the model and tokenizer from HuggingFace (or accepts a pre-loaded model + your
hf_tokenfor gated models). - Normalizes the forget input:
- questions → asks the model and uses its own answer as the response to forget;
- facts → uses the model to invent a question that the fact would answer;
- explicit
(prompt, response)pairs → uses them as-is.
- Builds the retain set automatically by self-prompting the model on a curated bank of ~180 diverse questions, with a topic-overlap filter so retain anchors are guaranteed orthogonal to the forget topic.
- Auto-picks hyperparameters: learning rate, epochs, batch size, mixed precision (bf16 / fp16 / fp32), method (
preference_optimizationfor clean refusals,npofor genuine knowledge removal),retain_weight, and whether to use LoRA (default for ≥1B-param models) or full fine-tuning. - Captures
beforeanswers for every forget prompt. - Runs unlearning with a progress log.
- Captures
afteranswers so you can sanity-check immediately. - Returns an
UnlearnResultwith.model,.tokenizer,.history,.metrics,.retain_records,.before,.after,.test(),.save(),.push_to_hub(), and.summary().
More common patterns
Forget multiple facts and push to the Hub
result = unlearn(
model="Qwen/Qwen2.5-0.5B-Instruct",
forget=[
"What is the capital of France?",
"Who painted the Mona Lisa?",
],
push_to_hub="ziadsalama95/qwen-no-paris-monalisa",
)
Genuine knowledge removal (NPO) instead of surface refusal
result = unlearn(
model="Qwen/Qwen2.5-0.5B-Instruct",
forget="What is the capital of France?",
mode="knowledge", # → uses NPO under the hood
)
Test arbitrary prompts after unlearning
print(result.test("Tell me about Paris")) # forgotten
print(result.test("Who wrote Hamlet?")) # still works
Built-in evaluation metrics
result = unlearn(..., evaluate=True)
print(result.metrics)
# {'forget_perplexity': 15.7, 'retain_perplexity': 5.4,
# 'forget_truth_ratio': 0.09, 'mia_loss_auroc_distinguishability': 1.0, ...}
Override anything
result = unlearn(
model="Qwen/Qwen2.5-0.5B-Instruct",
forget="...",
method="kl_minimization", # any of the 5 built-in methods
use_lora=False, # force full fine-tune
n_retain=100, # bigger anchor
config_overrides={"learning_rate": 5e-5},
method_kwargs={"kl_weight": 0.5},
)
Advanced usage (research-grade, low-level API)
If you're writing a thesis chapter or running ablations, the original low-level API is still there. You construct the dataset, pick the method explicitly, and have full control over every hyperparameter.
from transformers import AutoModelForCausalLM, AutoTokenizer
from forgetium import (
NPOUnlearner, UnlearningConfig,
QADataset, ForgetRetainDataset, Evaluator, compare_methods,
)
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
forget = QADataset.from_pairs([("What is the capital of France?", "Paris.")])
retain = QADataset.from_pairs([("What is 2+2?", "Four."), ("Who wrote Hamlet?", "Shakespeare.")])
config = UnlearningConfig(num_epochs=4, learning_rate=2e-5,
retain_oversample=4, logging_steps=1)
unlearner = NPOUnlearner(model, tok, config, beta=0.1, retain_weight=1.0)
unlearner.fit(ForgetRetainDataset(forget, retain))
See docs for full method-by-method coverage.
The 5 built-in unlearning methods
| Method | Class | Reference | Best for |
|---|---|---|---|
| Gradient Ascent | GradientAscentUnlearner |
Jang et al., ACL 2023 | Baseline / sanity-check |
| Gradient Difference | GradientDifferenceUnlearner |
Liu 2022; Maini 2024 | Strong baseline; preserves utility |
| NPO (Negative Preference Optimization) | NPOUnlearner |
Zhang, COLM 2024 | State-of-the-art for factual & copyright unlearning |
| KL Minimization | KLMinimizationUnlearner |
Maini 2024 | Stable, strong utility preservation |
| Preference Optimization (PO / IDK) | PreferenceOptimizationUnlearner |
Maini 2024 | Most natural-looking refusals |
All five share the same interface — swap one for another by changing a single class name.
Built-in benchmarks
from forgetium.data.benchmarks import load_tofu, load_wmdp, load_muse
dataset = load_tofu("forget05") # TOFU 5% forget split + perturbations
dataset = load_wmdp("bio") # WMDP biosecurity MCQ
dataset = load_muse("news") # MUSE BBC News
Documentation
Full docs (built with MkDocs Material) live at https://ziadsalama95.github.io/forgetium.
To build locally:
pip install "forgetium[docs]"
mkdocs serve --config-file docs/mkdocs.yml
Citation
@software{forgetium2026,
title = {Forgetium: A Python Library for Machine Unlearning of Large Language Models},
author = {Salama, Ziad},
year = {2026},
url = {https://github.com/ziadsalama95/forgetium},
note = {Apache-2.0},
}
Author
Ziad Salama
- GitHub: @ziadsalama95
- LinkedIn: ziadsalama
- Email: ziadsalama95@gmail.com
Forgetium was developed as a graduation project. If you find the library useful for your research or production work, a star on GitHub is much appreciated.
License
Apache 2.0 — see LICENSE.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file forgetium-0.2.0.tar.gz.
File metadata
- Download URL: forgetium-0.2.0.tar.gz
- Upload date:
- Size: 74.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
74bee726a6c650d91af9cff2fbee29912d963aa819d8247325ffef427b932382
|
|
| MD5 |
33e8305f8e76f2e27a855296670154a1
|
|
| BLAKE2b-256 |
916bc4bff58e19aa3f361d493a93a4d915b45e4e315a6467091e373ddc88b7e9
|
File details
Details for the file forgetium-0.2.0-py3-none-any.whl.
File metadata
- Download URL: forgetium-0.2.0-py3-none-any.whl
- Upload date:
- Size: 78.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
108f675e4d382631820a3329338c57f6f55f975401ad56d54f678df932b775a8
|
|
| MD5 |
0a71a0d655654ac5163c5ebfb688bb99
|
|
| BLAKE2b-256 |
b04327cb1fe27aad08394667948076653778e7f8048b640eceea35e7838c8a50
|