gapfuzz 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gapfuzz/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """gapfuzz: a guardrail blind-spot mapper, finding payloads that work but are not flagged.
2
+
3
+ Pipeline:
4
+ decide() - uniform guardrail contract (Stage 1)
5
+ attribute() - which input parts drive the 'unsafe' verdict (Stage 2, saliency)
6
+ EvasionFuzzer - attribution-guided search that evades while staying a real attack (Stage 3-4)
7
+ BlindSpotMapper- aggregate evasions across a corpus into a weakness map (Stage 5)
8
+ """
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ from .decision import Decision, Label
13
+ from .base import Guardrail
14
+ from .registry import register, get_guardrail, list_guardrails, decide, unload
15
+ from .tokenize import Span, tokenize
16
+ from .attribution import Attribution, TokenSalience, attribute
17
+ from .mutators import (
18
+ Mutator, default_mutators, semantic_mutators,
19
+ lexicon_synonyms, wordnet_synonyms,
20
+ )
21
+ from .oracle import ValidityOracle, FunctionOracle, always_valid
22
+ from .evasion import EvasionFuzzer, EvasionResult
23
+ from .mapping import BlindSpotMapper, BlindSpotReport
24
+ from .corpus import load_seeds
25
+
26
+ __all__ = [
27
+ # Stage 1: contract
28
+ "Decision", "Label", "Guardrail",
29
+ "register", "get_guardrail", "list_guardrails", "decide", "unload",
30
+ # Stage 2: attribution
31
+ "Span", "tokenize", "Attribution", "TokenSalience", "attribute",
32
+ # Stage 3: mutation + oracle
33
+ "default_mutators", "semantic_mutators", "lexicon_synonyms", "wordnet_synonyms",
34
+ "Mutator", "ValidityOracle", "FunctionOracle", "always_valid",
35
+ # Stage 4: evasion
36
+ "EvasionFuzzer", "EvasionResult",
37
+ # Stage 5: blind-spot mapping
38
+ "BlindSpotMapper", "BlindSpotReport", "load_seeds",
39
+ ]
gapfuzz/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """Concrete guardrail adapters."""
@@ -0,0 +1,60 @@
1
+ """Offline deterministic fake guardrail.
2
+
3
+ No model download and no torch dependency at call time: a keyword heuristic that
4
+ returns a well-formed :class:`Decision` so the `decide()` contract can be
5
+ exercised in any environment (CI, air-gapped, gated-model unavailable).
6
+
7
+ CLEARLY NOT A REAL GUARDRAIL. It exists only to test plumbing. Do not draw
8
+ any research conclusion from its outputs.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from typing import List
15
+
16
+ from ..base import Guardrail
17
+ from ..decision import Decision, Label
18
+
19
+ # Crude injection cues, enough to make the contract test meaningful. Kept mutually
20
+ # non-overlapping: a cue that contains another ("reveal your system prompt" vs "system prompt")
21
+ # would score one phrase twice and distort the pseudo-logit below.
22
+ _INJECTION_CUES = (
23
+ "ignore all previous",
24
+ "ignore previous instructions",
25
+ "disregard",
26
+ "system prompt",
27
+ "you are now",
28
+ "jailbreak",
29
+ "developer mode",
30
+ "override",
31
+ )
32
+
33
+
34
+ class FakeGuardrail(Guardrail):
35
+ name = "fake"
36
+
37
+ def decide(self, prompt: str) -> Decision:
38
+ p = prompt.lower()
39
+ hits = sum(1 for cue in _INJECTION_CUES if cue in p)
40
+ # map hit count to a pseudo-logit for the positive class
41
+ pos_logit = -4.0 + 4.0 * hits
42
+ neg_logit = -pos_logit
43
+ logits: List[float] = [neg_logit, pos_logit]
44
+ # softmax
45
+ m = max(logits)
46
+ exps = [math.exp(x - m) for x in logits]
47
+ s = sum(exps)
48
+ probs = [e / s for e in exps]
49
+ score = probs[1]
50
+ label = Label.INJECTION if score >= 0.5 else Label.BENIGN
51
+ return Decision(
52
+ label=label,
53
+ score=score,
54
+ logits=logits,
55
+ prompt=prompt,
56
+ guardrail=self.name,
57
+ raw_label="INJECTION" if label.is_positive() else "SAFE",
58
+ probs=probs,
59
+ extra={"model_id": "fake://keyword-heuristic", "hits": hits},
60
+ )
@@ -0,0 +1,143 @@
1
+ """Generic adapter over a HF `AutoModelForSequenceClassification` guardrail.
2
+
3
+ This is the workhorse: any binary (or multi-class) HF sequence classifier that
4
+ flags unsafe prompts can be wrapped by pointing at its model id and saying which
5
+ class index is the "unsafe/positive" one.
6
+
7
+ Model loading is lazy: nothing is downloaded or instantiated until the first
8
+ `decide()` call. The tokenizer and model are cached on the instance so that
9
+ attribution stages can reach them (via `.model` / `.tokenizer`) and re-run a
10
+ forward pass *with gradients enabled* later. `decide()` itself runs under
11
+ `torch.no_grad()` for speed and returns the raw logits regardless.
12
+
13
+ `decide_batch` is overridden to run one padded forward pass per `batch_size`
14
+ prompts rather than the base class's loop. Occlusion attribution scores one
15
+ variant per token of the input, once per beam member per search step, so this
16
+ is the pipeline's hot path.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import List, Optional
22
+
23
+ from ..base import Guardrail
24
+ from ..decision import Decision, Label
25
+
26
+
27
+ class HFClassifierGuardrail(Guardrail):
28
+ def __init__(
29
+ self,
30
+ name: str,
31
+ model_id: str,
32
+ positive_index: int,
33
+ positive_label: Label,
34
+ max_length: int = 512,
35
+ device: Optional[str] = None,
36
+ hf_token: Optional[str] = None,
37
+ batch_size: int = 16,
38
+ ):
39
+ self.name = name
40
+ self.model_id = model_id
41
+ self.positive_index = positive_index
42
+ self.positive_label = positive_label
43
+ self.max_length = max_length
44
+ # DeBERTa-style disentangled attention is O(seq^2) in memory; keep this modest.
45
+ self.batch_size = batch_size
46
+ self._device = device
47
+ self._hf_token = hf_token
48
+ self._tokenizer = None
49
+ self._model = None
50
+
51
+ # --- lazy loading -----------------------------------------------------
52
+ def _ensure_loaded(self) -> None:
53
+ if self._model is not None:
54
+ return
55
+ import torch
56
+ from transformers import (
57
+ AutoTokenizer,
58
+ AutoModelForSequenceClassification,
59
+ )
60
+
61
+ if self._device is None:
62
+ self._device = "cuda" if torch.cuda.is_available() else "cpu"
63
+
64
+ kwargs = {}
65
+ if self._hf_token:
66
+ kwargs["token"] = self._hf_token
67
+
68
+ self._tokenizer = AutoTokenizer.from_pretrained(self.model_id, **kwargs)
69
+ self._model = (
70
+ AutoModelForSequenceClassification.from_pretrained(
71
+ self.model_id, **kwargs
72
+ )
73
+ .to(self._device)
74
+ .eval()
75
+ )
76
+
77
+ @property
78
+ def model(self):
79
+ """The underlying HF model (loads on first access). For attribution."""
80
+ self._ensure_loaded()
81
+ return self._model
82
+
83
+ @property
84
+ def tokenizer(self):
85
+ self._ensure_loaded()
86
+ return self._tokenizer
87
+
88
+ # --- inference --------------------------------------------------------
89
+ def decide(self, prompt: str) -> Decision:
90
+ return self.decide_batch([prompt])[0]
91
+
92
+ def decide_batch(self, prompts: List[str]) -> List[Decision]:
93
+ import torch
94
+
95
+ if not prompts:
96
+ return []
97
+ self._ensure_loaded()
98
+
99
+ id2label = getattr(self._model.config, "id2label", {}) or {}
100
+ out: List[Decision] = []
101
+
102
+ for i in range(0, len(prompts), self.batch_size):
103
+ chunk = prompts[i : i + self.batch_size]
104
+ enc = self._tokenizer(
105
+ chunk,
106
+ return_tensors="pt",
107
+ truncation=True,
108
+ max_length=self.max_length,
109
+ padding=True,
110
+ ).to(self._device)
111
+
112
+ with torch.no_grad():
113
+ logits = self._model(**enc).logits
114
+ probs = torch.softmax(logits, dim=-1)
115
+
116
+ batch_logits: List[List[float]] = logits.float().cpu().tolist()
117
+ batch_probs: List[List[float]] = probs.float().cpu().tolist()
118
+ preds: List[int] = torch.argmax(logits, dim=-1).cpu().tolist()
119
+
120
+ for prompt, lg, pr, pred_idx in zip(chunk, batch_logits, batch_probs, preds):
121
+ raw_label = id2label.get(pred_idx, str(pred_idx))
122
+ out.append(
123
+ Decision(
124
+ label=(
125
+ self.positive_label
126
+ if pred_idx == self.positive_index
127
+ else Label.BENIGN
128
+ ),
129
+ score=float(pr[self.positive_index]),
130
+ logits=lg,
131
+ prompt=prompt,
132
+ guardrail=self.name,
133
+ raw_label=str(raw_label),
134
+ probs=pr,
135
+ extra={
136
+ "model_id": self.model_id,
137
+ "id2label": {int(k): v for k, v in id2label.items()},
138
+ "positive_index": self.positive_index,
139
+ "device": self._device,
140
+ },
141
+ )
142
+ )
143
+ return out
@@ -0,0 +1,70 @@
1
+ """Meta Prompt Guard 2 adapter.
2
+
3
+ Not the project's reference model. Both repos are `gated: manual`, so access needs a Meta
4
+ review rather than just a licence click, and nothing here can be reproduced by someone waiting
5
+ on that. The non-gated classifiers in the registry are the reference targets; this adapter
6
+ stays because Prompt Guard 2 is still worth measuring once access lands.
7
+
8
+ Model cards:
9
+ - meta-llama/Llama-Prompt-Guard-2-86M
10
+ - meta-llama/Llama-Prompt-Guard-2-22M
11
+
12
+ Both are binary sequence classifiers with id2label = {0: "LABEL_0" (benign),
13
+ 1: "LABEL_1" (malicious / injection)}; the positive class (index 1) is the
14
+ "malicious"/"jailbreak" flag.
15
+
16
+ =====================================================================
17
+ GATING / AUTH - READ THIS
18
+ =====================================================================
19
+ These repos are **gated** on the Hugging Face Hub. Loading them requires:
20
+ 1. An HF account that has accepted Meta's license on the model page, AND
21
+ 2. An auth token exposed to `transformers`, e.g.:
22
+ export HF_TOKEN=hf_xxx
23
+ (or pass `hf_token=` to the constructor).
24
+
25
+ In THIS environment there is no HF token and the license has not been
26
+ accepted, so `from_pretrained` fails with:
27
+ OSError: You are trying to access a gated repo ... 401 Client Error.
28
+
29
+ This adapter therefore loads lazily and will only work once a token with
30
+ license acceptance is present. Until then, use the non-gated real classifier
31
+ `protectai-deberta` or the offline `fake` guardrail, both of which implement
32
+ the identical `decide()` contract. See registry.py.
33
+ =====================================================================
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import os
39
+ from typing import Optional
40
+
41
+ from .hf_classifier import HFClassifierGuardrail
42
+ from ..decision import Label
43
+
44
+ _SIZES = {
45
+ "22M": "meta-llama/Llama-Prompt-Guard-2-22M",
46
+ "86M": "meta-llama/Llama-Prompt-Guard-2-86M",
47
+ }
48
+
49
+
50
+ class PromptGuard2Guardrail(HFClassifierGuardrail):
51
+ """Prompt Guard 2, wrapped behind the uniform Guardrail contract."""
52
+
53
+ def __init__(self, size: str = "22M", hf_token: Optional[str] = None, **kwargs):
54
+ if size not in _SIZES:
55
+ raise ValueError(f"size must be one of {list(_SIZES)}, got {size!r}")
56
+ # fall back to the standard env vars transformers itself honours
57
+ token = (
58
+ hf_token
59
+ or os.environ.get("HF_TOKEN")
60
+ or os.environ.get("HUGGING_FACE_HUB_TOKEN")
61
+ )
62
+ super().__init__(
63
+ name=f"prompt-guard-2-{size}",
64
+ model_id=_SIZES[size],
65
+ positive_index=1, # LABEL_1 == malicious / injection
66
+ positive_label=Label.MALICIOUS,
67
+ hf_token=token,
68
+ **kwargs,
69
+ )
70
+ self.size = size
gapfuzz/attribution.py ADDED
@@ -0,0 +1,111 @@
1
+ """Stage 2: attribution (the saliency in gapfuzz).
2
+
3
+ Which parts of an input make the guardrail say "malicious"? That map is what guides the evasion
4
+ search: perturb what the detector leans on, not random bytes.
5
+
6
+ Two backends behind one `Attribution` result:
7
+
8
+ - **occlusion** (default, model-agnostic): remove each token and measure how far the unsafe
9
+ score drops. Needs only `decide()`, so it works for *any* guardrail, including non-
10
+ differentiable ones. O(n) scored variants per input, sent through `decide_batch`.
11
+ - **gradient** (optional, HF only): one backward pass, gradient·embedding summed per token.
12
+ Fast and fine-grained, but needs a differentiable model exposing `.model`/`.tokenizer`.
13
+
14
+ Positive salience = that span pushes the verdict toward unsafe (removing it lowers the score).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+ from typing import List, Optional
21
+
22
+ from .base import Guardrail
23
+ from .tokenize import Span, tokenize
24
+
25
+
26
+ @dataclass
27
+ class TokenSalience:
28
+ span: Span
29
+ salience: float # baseline_score - score_without_this_token (occlusion); grad magnitude otherwise
30
+
31
+
32
+ @dataclass
33
+ class Attribution:
34
+ prompt: str
35
+ baseline_score: float
36
+ tokens: List[TokenSalience]
37
+ method: str
38
+
39
+ def ranked(self, include_space: bool = False) -> List[TokenSalience]:
40
+ """Tokens most responsible for the 'unsafe' verdict first."""
41
+ xs = [t for t in self.tokens if include_space or not t.span.is_space]
42
+ return sorted(xs, key=lambda t: -t.salience)
43
+
44
+ def top_spans(self, k: int = 3) -> List[Span]:
45
+ return [t.span for t in self.ranked()[:k]]
46
+
47
+
48
+ def occlusion_attribution(prompt: str, guardrail: Guardrail) -> Attribution:
49
+ """Remove each token in turn; salience = drop in unsafe score. Batched where the guardrail
50
+ supports it. Content tokens only are perturbed (whitespace spans get 0 salience)."""
51
+ spans = tokenize(prompt)
52
+ baseline = guardrail.decide(prompt).score
53
+
54
+ content_idx = [i for i, s in enumerate(spans) if not s.is_space]
55
+ variants = [prompt[: spans[i].start] + prompt[spans[i].end :] for i in content_idx]
56
+ decisions = guardrail.decide_batch(variants) if variants else []
57
+ drop = {i: baseline - d.score for i, d in zip(content_idx, decisions)}
58
+
59
+ tokens = [TokenSalience(span=s, salience=float(drop.get(i, 0.0))) for i, s in enumerate(spans)]
60
+ return Attribution(prompt=prompt, baseline_score=float(baseline), tokens=tokens, method="occlusion")
61
+
62
+
63
+ def gradient_attribution(prompt: str, guardrail: Guardrail) -> Attribution:
64
+ """gradient·embedding saliency over subword tokens, re-aligned to character spans.
65
+
66
+ Requires a HF-style guardrail exposing `.model`, `.tokenizer`, and `positive_index`.
67
+ Subword saliences are mapped back onto our word spans via offset overlap so the result has
68
+ the same shape as occlusion and feeds the same search."""
69
+ import torch
70
+
71
+ model, tok = guardrail.model, guardrail.tokenizer # type: ignore[attr-defined]
72
+ pos = getattr(guardrail, "positive_index", 1)
73
+ baseline = guardrail.decide(prompt).score
74
+
75
+ enc = tok(prompt, return_tensors="pt", truncation=True,
76
+ max_length=getattr(guardrail, "max_length", 512),
77
+ return_offsets_mapping=True)
78
+ offsets = enc.pop("offset_mapping")[0].tolist()
79
+ enc = {k: v.to(model.device) for k, v in enc.items()}
80
+
81
+ emb_layer = model.get_input_embeddings()
82
+ inputs_embeds = emb_layer(enc["input_ids"]).detach().clone().requires_grad_(True)
83
+ fwd = {k: v for k, v in enc.items() if k != "input_ids"}
84
+ logits = model(inputs_embeds=inputs_embeds, **fwd).logits[0]
85
+ # Backprop from the positive-class LOGIT, not its softmax prob: a confident guardrail
86
+ # saturates softmax (prob≈1), where ∂prob/∂input vanishes and every saliency collapses to 0.
87
+ # The pre-softmax logit keeps a usable gradient.
88
+ logits[pos].backward()
89
+
90
+ # per-subword saliency = L2 of grad·embedding
91
+ g = (inputs_embeds.grad[0] * inputs_embeds[0]).norm(dim=-1).detach().cpu().tolist()
92
+
93
+ spans = tokenize(prompt)
94
+ tokens: List[TokenSalience] = []
95
+ for s in spans:
96
+ if s.is_space:
97
+ tokens.append(TokenSalience(span=s, salience=0.0))
98
+ continue
99
+ total = sum(val for val, (a, b) in zip(g, offsets)
100
+ if not (b <= s.start or a >= s.end) and b > a)
101
+ tokens.append(TokenSalience(span=s, salience=float(total)))
102
+ return Attribution(prompt=prompt, baseline_score=float(baseline), tokens=tokens, method="gradient")
103
+
104
+
105
+ def attribute(prompt: str, guardrail: Guardrail, method: str = "occlusion") -> Attribution:
106
+ """Attribute `prompt` under `guardrail`. method='occlusion' (universal) | 'gradient' (HF)."""
107
+ if method == "occlusion":
108
+ return occlusion_attribution(prompt, guardrail)
109
+ if method == "gradient":
110
+ return gradient_attribution(prompt, guardrail)
111
+ raise ValueError(f"unknown attribution method {method!r} (use 'occlusion' or 'gradient')")
gapfuzz/base.py ADDED
@@ -0,0 +1,32 @@
1
+ """Guardrail interface: everything downstream depends only on this."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import List
7
+
8
+ from .decision import Decision
9
+
10
+
11
+ class Guardrail(ABC):
12
+ """A prompt-injection / safety guardrail behind a uniform contract.
13
+
14
+ Concrete adapters must implement :meth:`decide`. Model loading should be
15
+ lazy (deferred to first `decide()` call) so that constructing / registering
16
+ a guardrail is cheap and import-time has no heavy side effects.
17
+ """
18
+
19
+ #: short, registry-facing name
20
+ name: str = "base"
21
+
22
+ @abstractmethod
23
+ def decide(self, prompt: str) -> Decision:
24
+ """Classify a single prompt and return a :class:`Decision`."""
25
+ raise NotImplementedError
26
+
27
+ def decide_batch(self, prompts: List[str]) -> List[Decision]:
28
+ """Default batch = loop. Adapters may override for efficiency."""
29
+ return [self.decide(p) for p in prompts]
30
+
31
+ def __call__(self, prompt: str) -> Decision:
32
+ return self.decide(prompt)