Skip to content

Add optional calibrated-head mode for Prompt Guard 2 (experimental) - #263

Open
mosafariuk wants to merge 2 commits into
meta-llama:mainfrom
mosafariuk:feat/prompt-guard-calibrated-head
Open

mosafariuk wants to merge 2 commits into
meta-llama:mainfrom
mosafariuk:feat/prompt-guard-calibrated-head

Conversation

@mosafariuk

Copy link
Copy Markdown

Summary

Adds an optional, opt-in calibrated head mode to a Prompt Guard 2 scanner, following
the design discussed in #257. Default behavior is unchanged (native Prompt Guard 2 head);
callers can opt into a more recall-oriented calibrated head backed by their own weights.

Motivation

On an out-of-distribution injection evaluation, PG2-86M's native head recalls ~22.8% at its
default operating point, while its frozen embeddings separate the same examples at
AUC ≈ 0.999 — i.e., the precision-first native head leaves recall on the table. Some
deployments want a more recall-oriented operating point without touching the base model.
Full analysis and reproduction: https://github.com/mosafariuk/prompt-guard-2-frozen-head
(background in #257).

What this PR does

  • New PromptGuardCalibratedScanner in scanners/experimental/.
  • score_mode="native" (default) → identical to PromptGuardScanner (native head + softmax).
  • score_mode="calibrated" → leaves the encoder frozen and scores the pooled (penultimate)
    embedding with a caller-supplied linear head: sigmoid(embedding · w + b) >= tau.
  • Weights are caller-provided via calibrated_head_path (a local NumPy .npz with
    w/b/tau; coef/intercept/threshold aliases accepted). No trained or
    third-party weights are shipped in this repository.
  • Fails with a clear error when score_mode="calibrated" but no valid head is available
    (or set fallback_to_native=True to degrade to native).
  • Registered in experimental/__init__.py (lazy-loaded, like the other experimental scanners).

Tests

tests/test_prompt_guard_calibrated_scanner.py covers native block/allow, calibrated
block/allow (dummy w/b/tau + a stubbed embedding), fail-clear when the head is missing,
and invalid score_mode. The model load and embedding are stubbed, so CI never downloads
the gated meta-llama/Llama-Prompt-Guard-2-86M checkpoint.

Notes

  • This PR adds the mechanism (an optional operating point); the trained weights and their
    evaluation live in the linked external repo.
  • The default path and existing callers are unaffected.
  • CLA: signed.

…tal)

Adds PromptGuardCalibratedScanner with an opt-in score_mode='calibrated' that scores
the frozen encoder's pooled embedding with a caller-supplied linear head
(sigmoid(x . w + b) >= tau). Default remains the native head; no weights are shipped
in-tree. Includes stubbed tests that never download the gated checkpoint. See meta-llama#257.

@alireza-aminzadeh alireza-aminzadeh left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for opening this with the shape we discussed on #257: experimental, opt-in, caller-supplied .npz, no in-tree weights, and tests that stub the load so CI never pulls meta-llama/Llama-Prompt-Guard-2-86M. Putting it on a new experimental scanner — rather than adding flags to PromptGuardScanner — is the right isolation. Existing ScannerType.PROMPT_GUARD callers are untouched.

I walked prompt_guard_calibrated_scanner.py against prompt_guard_scanner.py and promptguard_utils.py. A few things I would like tightened before this is merge-ready. None of them change default behavior for current callers.

1. Native-mode identity. The class docstring says score_mode="native" is identical to PromptGuardScanner. It is not: scan() wraps both modes in except Exception and returns ALLOW + ScanStatus.ERROR. PromptGuardScanner.scan() does not catch. Fail-open on a security scanner is a policy choice, but it should not apply to a path that claims identity with the native scanner. If you keep fail-open for calibrated mode, spell that out in the docstring so callers are not surprised.

2. Pooled embeddings belong on PromptGuard. _embedding reaches into self.pg.model.deberta / base_model / pooler from the scanner. On #257 the idea was to expose the frozen pooler output from PromptGuard itself — same tokenizer, device, and optional _preprocess_text_for_promptguard as get_jailbreak_score — and keep the scanner as sigmoid(x·w + b) >= tau on top. PG2-86M is deberta-v2 with ContextPooler, so this works today, but a 22M checkpoint or a transformers rename should not require editing the scanner.

Please also document that the calibrated path tokenizes the raw string and does not call _preprocess_text_for_promptguard (native get_jailbreak_score does, preprocess=True by default). That matches the extract script in prompt-guard-2-frozen-head, so it is consistent with that head. Callers training their own weights need to know which path they matched. A preprocess: bool on the PromptGuard helper would make that choice explicit.

3. except Exception on head load is too broad for fallback_to_native. A missing file is a reasonable fallback trigger. A corrupt .npz, a KeyError, or a dtype problem should stay fail-clear. Silent fallback to the precision-first native head while the caller thinks they are in recall mode is exactly the failure mode this feature is meant to avoid.

4. block_threshold vs tau. In calibrated mode the decision uses _tau from the file and ignores block_threshold (still default 0.9). Please say so on the constructor so nobody sets block_threshold=0.7 and assumes it applies. A small test that tau=0.99 allows a score of ~0.8 even when block_threshold=0.5 would lock that in.

5. Tests. Native/calibrated block+allow, missing head, fallback, and invalid score_mode are a solid start. Still missing: dim mismatch, coef/intercept/threshold aliases, an assert that native mode actually calls get_jailbreak_score, and the tau vs block_threshold case above.

Nits, non-blocking:

  • 1/(1+exp(-z)) overflows for large |z|; clipping z avoids a new dependency.
  • self.pg.model.eval() before the no-grad forward — DeBERTa ContextPooler includes dropout. from_pretrained usually already evals, but being explicit matches the extract script.
  • Optional: lazy-export from scanners/__init__.py the same way as PIICheckScanner / AlignmentCheckScanner, still without a ScannerType, so create_scanner and default config stay untouched.

I would not add trained weights or a ScannerType in this PR. Mechanism-only is the right split.

Happy to look again once the native-identity, embedding-on-PromptGuard, and fallback-narrowing points are addressed.

- Native mode is now byte-for-byte identical to PromptGuardScanner (removed the
  broad try/except; exceptions propagate, no fail-open on the native path).
- Move pooled-embedding extraction onto PromptGuard.get_pooled_embedding(text,
  preprocess=False) (adds model.eval(); scanner no longer reaches into model
  internals; works across checkpoints/renames).
- Narrow fallback_to_native to a MISSING head file only; a present-but-corrupt
  .npz always fails clear.
- Document that calibrated mode uses tau and ignores block_threshold, and that the
  calibrated path does not preprocess.
- Numerically stable sigmoid (clip z).
- Lazy-export PromptGuardCalibratedScanner from scanners/__init__.py.
- Add tests: dim mismatch, coef/intercept/threshold aliases, native calls
  get_jailbreak_score, tau-vs-block_threshold, corrupt-head-always-raises.

See meta-llama#257.
@mosafariuk

Copy link
Copy Markdown
Author

Thanks for the thorough review — all points addressed in the latest push. Point by point:

1. Native-mode identity. Removed the broad `try/except` from `scan()`. Native mode is now byte-for-byte `PromptGuardScanner` behavior (exceptions propagate, no fail-open). Calibrated errors such as a dim mismatch also propagate rather than silently allowing.

2. Pooled embeddings on `PromptGuard`. Added `PromptGuard.get_pooled_embedding(text, preprocess=False)` — same tokenizer/device as `get_jailbreak_score`, with `model.eval()`. The scanner is now just `sigmoid(x·w + b) >= tau` on top and no longer reaches into `.deberta`/`.pooler`, so a 22M checkpoint or a transformers rename does not require editing the scanner. Documented (helper + scanner) that the calibrated path uses `preprocess=False` and therefore does not call `_preprocess_text_for_promptguard`, so callers know which tokenization their weights must match.

3. Narrowed `fallback_to_native`. Only a missing file triggers fallback now. A present-but-corrupt/invalid `.npz` (KeyError, dtype, empty vector) always fails clear, even with `fallback_to_native=True`. Test added.

4. `block_threshold` vs `tau`. Documented that calibrated mode decides on `tau` and ignores `block_threshold`; added a test where `tau=0.99` allows a ~0.982 score even with `block_threshold=0.5`.

5. Tests. Added dim-mismatch, `coef`/`intercept`/`threshold` aliases, an assertion that native mode actually calls `get_jailbreak_score`, and the tau-vs-threshold case (plus corrupt-head-always-raises).

Nits: sigmoid now clips `z`; `model.eval()` added before the no-grad forward (in the helper); and I lazy-export `PromptGuardCalibratedScanner` from `scanners/init.py` the same way as the other experimental scanners — still no `ScannerType`, so `create_scanner` and the default config stay untouched.

No trained weights or `ScannerType` added — agreed the mechanism-only split is right. Happy to iterate further.

@alireza-aminzadeh alireza-aminzadeh left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 1918a87 against the notes on the first pass. The follow-up covers them:

  1. Native identity. scan() no longer wraps either mode in except Exception. Native errors propagate the same way as PromptGuardScanner.
  2. Embeddings on PromptGuard. get_pooled_embedding(text, preprocess=False) is the shared helper (model.eval(), same tokenizer/device). The scanner is only sigmoid(x·w + b) >= tau and no longer walks .deberta / .pooler.
  3. Fallback. Only a missing file degrades to native. A present-but-invalid .npz stays fail-clear even with fallback_to_native=True.
  4. tau vs block_threshold. Documented and locked in by test_calibrated_uses_tau_not_block_threshold.
  5. Tests. Dim mismatch, coef/intercept/threshold aliases, native calling get_jailbreak_score, and corrupt-head-always-raises are all there.

Nits from last time (clipped sigmoid, eval(), lazy export, no ScannerType / in-tree weights) are in as well.

This is the right split: experimental, opt-in, caller-supplied head. Approved from my side.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants