Constitutional toxic content classifier fine-tuned on synthetic safety data,
inspired by Anthropic's
Constitutional Classifiers paper.
1from transformers import AutoTokenizer, AutoModelForSequenceClassification
2from peft import PeftModel
3import torch
4
5BASE_MODEL = "google/gemma-2b"
6ADAPTER_REPO = "secllmuser/constitutional-toxic-classifier-gemma"
7
8# 1. Load base Gemma + LoRA adapters
9tokenizer = AutoTokenizer.from_pretrained(ADAPTER_REPO)
10base = AutoModelForSequenceClassification.from_pretrained(
11 BASE_MODEL,
12 num_labels=2,
13 torch_dtype=torch.float16, # use float32 on CPU
14 trust_remote_code=True,
15)
16model = PeftModel.from_pretrained(base, ADAPTER_REPO)
17model.eval()
18
19# 2. Run inference
20text = "I will hurt you"
21inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=256)
22with torch.no_grad():
23 logits = model(**inputs).logits
24
25label_id = logits.argmax(-1).item()
26labels = {0: "safe", 1: "toxic"}
27print(f"{text!r} → {labels[label_id]}")
1texts = [
2 "Have a great day!",
3 "I will destroy you",
4 "Thanks for your help",
5 "You are worthless",
6]
7inputs = tokenizer(
8 texts,
9 return_tensors="pt",
10 padding=True,
11 truncation=True,
12 max_length=256,
13)
14with torch.no_grad():
15 logits = model(**inputs).logits
16
17labels = {0: "safe", 1: "toxic"}
18for text, pred in zip(texts, logits.argmax(-1).tolist()):
19 print(f"{labels[pred]:5s} {text!r}")
1@article{sharma2025constitutional,
2 title={Constitutional Classifiers: Defending against Universal Jailbreaks},
3 author={Sharma, Mrinank and others},
4 journal={arXiv preprint arXiv:2501.18837},
5 year={2025}
6}