Cheat sheets

AI Safety and Red Teaming

Name the attack, detect it, measure refusals, gate the output and audit alignment. Phase 18 and 19 lessons.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Three checkpoint safety gate#

passstreamcompleteearly stopUser promptPre-gen detectorrules on promptModel stream4 token chunksDuring-gen filter2 chunk bufferPost-gen checksclassifier, rules engineAggregatemax severityFinal actionRequestTracepassstreamcompleteearly stopUserpromptPre-gendetectorrules onpromptModelstream4 tokenchunksDuring-genfilter2 chunkbufferPost-genchecksclassifier,rulesengineAggregatemaxseverityFinalactionRequestTrace

From Lesson 19.87, 19.87 code/safety_gate.py

PAIR attack loop#

1Attacker Areads the goal G and the history of prompt andresponse pairs.2Attacker Awrites a new prompt $p_k$.3Target Tanswers with the response $r_k$.4Judge Jscores $(p_k, r_k)$ against the goal.5Halta score at or above the threshold is ajailbreak.6Repeatelse append the pair to the history, up tobudget K.

From Lesson 18.12

Jailbreak taxonomy#

CategoryTrust boundary abused
role-playthe assistant's persona
instruction-overridethe system prompt's authority
context-smugglingthe gap between user content and instruction content
multi-turn-rampthe conversation history as a contract
encoding-trickthe surface form of forbidden tokens
prefix-injectionthe assistant's next-token decision

From Lesson 19.82

Tasks in code#

TaskCode
Run a capstone demopython3 main.py
Add a detector rule{"name": "debug-mode", "category": "instruction-override", "score": 0.80, "substring": "debug mode"}
Score a promptv = self.detector.analyze(prompt)
Try a rot13 decodecandidate = codecs.encode(text, "rot_13")
Spot a refusalclassify_refusal(response)
Route an outputaction = self.classifier_router.run(output)
Fix rule violationsredacted = self.rules_fixer.apply(redacted, violations)
Run one requesttrace = gate.handle(prompt)

From Lesson 19.82, 19.83 code/rules.py, 19.83 code/main.py, 19.84 code/main.py, 19.87 code/safety_gate.py, 19.87 code/main.py

Aggregate the signals#

if pre.category != "benign":
if pre.confidence >= self.block_confidence:0.85 is high
signals.append(("pre", SEVERITY_RANK["high"]))
elif pre.confidence >= self.note_confidence:0.5 is medium
signals.append(("pre", SEVERITY_RANK["medium"]))
if during.terminated_early:stream cut early
signals.append(("during", SEVERITY_RANK["medium"]))
if post is not None:classifier and rules
signals.append(("post.classifier", SEVERITY_RANK.get(post.classifier_severity, 0)))
max_rank = max(rank for _, rank in signals)
if max_rank >= SEVERITY_RANK["high"]:
return "block"return a refusal
if max_rank >= SEVERITY_RANK["medium"]:
return "redact"then warn on low, else allow

From 19.87 code/safety_gate.py

Metrics#

Precision
TP / (TP + FP), the fraction of fires that are correct.
Recall
TP / (TP + FN), the fraction of attacks the detector catches.
F1
2 P R / (P + R) per category.
Under-refusal
the model answered a prompt labeled unsafe.
Over-refusal
the model refused a prompt labeled safe.
Accuracy
(TP + TN) / \text{total} for the safe or unsafe decision.
ECE
bins of tenths, mean of \lvert \text{conf} - \text{accuracy} \rvert weighted by bin size.
ASR
attack success rate. Report it with the query budget and the judge.

From Lesson 19.83, 19.83 code/main.py, Lesson 19.84, Lesson 18.12

Alignment failure modes#

Goodhart
a strong optimizer finds inputs where proxy and target differ.
Over-optimization
proxy reward climbs, gold reward peaks then falls as KL grows.
Sycophancy
agrees with the user's stated premise regardless of truth.
Trigger persistence
a backdoor survives the training meant to remove it.
Alignment faking
a compliance gap between monitored and unmonitored conditions.
Constitutional AI
critique and revise SFT, then RL from AI feedback.
AI control
trusted model T edits untrusted U. Human H audits ambiguous outputs.
PGR
(\text{fine-tuned} - \text{weak}) / (\text{ceiling} - \text{weak}). 1.0 is fully closed.

From Lesson 18.02, Lesson 18.04, Lesson 18.05, Lesson 18.07, Lesson 18.09, Lesson 18.10, Lesson 18.11

Defaults and numbers#

SettingDefaultNote
block_confidence0.85pre-gen detector score that blocks
note_confidence0.5pre-gen score that adds a medium signal
buffer_cap2chunks the during-gen filter holds
n_bins10ECE bins
Leakage threshold0.55trigram overlap with the system prompt
max_words800the bounded-length rule
PAIR budget K20queries per goal
MSJ shot count256reliable attack on violent and deceitful content

From 19.87 code/safety_gate.py, 19.84 code/main.py, 19.85 code/classifiers.py, 19.86 code/rules.yml, Lesson 18.12, Lesson 18.13

Troubleshooting#

SymptomCauseFix
Regex misses a paraphraseone pattern, no measurementregex families, normalize pass, precision and recall
Agent obeys an emailfilter checks only user inputlabel untrusted content, ratify its actions
Defense reports near zero ASRstatic attacks onlyevaluate with adaptive attacks
Model refuses chemistry homeworkonly harmful prompts measuredmeasure over-refusal on safe prompts
Prefix injection gets throughgate checks only after generationadd the during-gen stream filter
ASR numbers do not comparedifferent query budgetsmatch budgets, name the judge
Attack works at 256 shotslong context pattern followingclassifier over the full context
Encoding attack passes input checkinput moderation onlymoderate input and output

From Lesson 19.83, Lesson 19.84, Lesson 19.87, Lesson 18.12, Lesson 18.13, Lesson 18.15, Lesson 18.29

Abbreviations#

PAIR
Prompt Automatic Iterative Refinement. Attacker LLM and judge LLM loop.
GCG
white box gradient search for adversarial token suffixes.
TAP
Tree of attacks. PAIR with branching and pruning.
MSJ
many-shot jailbreak. Hundreds of fake compliance pairs in context.
ArtPrompt
masks safety words with ASCII art renderings.
IPI
indirect prompt injection. Payload in content the user did not write.
IFC
information flow control. Untrusted content needs trusted ratification.
ECE
Expected Calibration Error. Stated confidence versus accuracy.

From Lesson 18.12, Lesson 18.13, Lesson 18.14, Lesson 18.15, Lesson 19.84

Questions#

Why a taxonomy first?
Labels turn an attack stream into a histogram and a coverage chart.
Why classify outputs too?
An attack family the input checks miss lands on the user.
Which action wins?
The maximum severity. Block wins. Redact and warn becomes redact.
Why is PAIR cheaper than GCG?
It is black box and learns from each rejection in context.
Why is MSJ hard to block?
It uses the same mechanism as in-context learning.

From Lesson 19.82, Lesson 19.85, Lesson 18.12, Lesson 18.13

Tips#

  • Log a taxonomy id with every finding.
  • Normalize first: strip zero-width characters, decode base64, rot13 and hex. Keep the raw prompt.
  • Keep the constitution in YAML under version control with its own review.
  • Put a guard classifier on both sides of the model.
  • Run single turn probes nightly and multi-turn campaigns before release.
  • Score each successful jailbreak with CVSS 4.0.

From Lesson 19.82, Lesson 19.83, Lesson 19.86, Lesson 19.15, Lesson 18.15, Lesson 18.16