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

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.

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

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)

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

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.

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.

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

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

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.

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.

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.