hxz-sec commited on
Commit
cd8ac0b
·
verified ·
1 Parent(s): da0e1c1

Update model card

Browse files
Files changed (1) hide show
  1. README.md +267 -0
README.md ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - en
5
+ base_model: Qwen/Qwen3-0.6B
6
+ library_name: transformers
7
+ tags:
8
+ - safety
9
+ - guardrail
10
+ - calibration
11
+ - jailbreak-detection
12
+ - streaming-safety
13
+ - qwen3
14
+ - probguard
15
+ ---
16
+
17
+ <p align="center">
18
+ <img src="assets/probguard_logo.png" alt="ProbGuard logo" width="180">
19
+ </p>
20
+
21
+ <h1 align="center">ProbGuard</h1>
22
+
23
+ <p align="center">
24
+ A probability-based streaming guardrail for forecasting unsafe LLM continuations.
25
+ </p>
26
+
27
+ ProbGuard monitors a target LLM while it is generating. Instead of waiting for a completed response, it reads the target model's early next-token probability distributions and predicts whether the continuation is likely to become unsafe.
28
+
29
+ ProbGuard is not a normal chat model. It should be used together with the project inference code and a target LLM that exposes top-k probabilities during decoding.
30
+
31
+ - Code: https://github.com/hxz-sec/ProbGuard
32
+ - Models:
33
+ - https://huggingface.co/hxz-sec/ProbGuard-0.6b
34
+ - https://huggingface.co/hxz-sec/ProbGuard-4b
35
+ - https://huggingface.co/hxz-sec/ProbGuard-8b
36
+ - Dataset: https://huggingface.co/datasets/hxz-sec/ProbGuard-calibration
37
+
38
+ ## Checkpoints
39
+
40
+ | Checkpoint | Base model | Repository |
41
+ | --- | --- | --- |
42
+ | ProbGuard-0.6B-mixed | Qwen/Qwen3-0.6B | `hxz-sec/ProbGuard-0.6b` |
43
+ | ProbGuard-4B-mixed | Qwen/Qwen3-4B | `hxz-sec/ProbGuard-4b` |
44
+ | ProbGuard-8B-mixed | Qwen/Qwen3-8B | `hxz-sec/ProbGuard-8b` |
45
+
46
+ Each released repository is expected to contain `probguard_heads.pt`, `model/`, and `tokenizer/` at the repository root. The `probguard_heads.pt` file stores the calibration and category heads used by the ProbGuard inference utilities.
47
+
48
+ ## Highlights
49
+
50
+ - Predicts unsafe-continuation risk during generation.
51
+ - Uses top-k output probability vectors rather than hidden states.
52
+ - Does not require access to the target model's internal activations.
53
+ - Returns a calibrated risk score and a primary hazard category.
54
+ - Designed for streaming intervention: continue, stop, redirect, or regenerate.
55
+
56
+ ## Outputs
57
+
58
+ For a user prompt and a partial generation state, ProbGuard returns:
59
+
60
+ - `risk`: a float in `[0, 1]`, estimating the probability that the final continuation will become unsafe;
61
+ - `category`: one of `Toxicity`, `Hate`, `Violence`, `Sexual`, `Harm`, `Drugs`, `Conflict`, `Illegal`, `Medical`, `Extremism`, or `None`.
62
+
63
+ ## Install
64
+
65
+ ```bash
66
+ git clone https://github.com/hxz-sec/ProbGuard
67
+ cd ProbGuard
68
+
69
+ conda env create -f environment.yml
70
+ conda activate probguard
71
+ ```
72
+
73
+ ## Quickstart
74
+
75
+ Download a Hugging Face checkpoint, then load it with the ProbGuard inference utilities.
76
+
77
+ ```python
78
+ from pathlib import Path
79
+
80
+ from huggingface_hub import snapshot_download
81
+
82
+ from eval.eval_probguard_stream import (
83
+ load_probguard,
84
+ load_qwen_tokenizer,
85
+ load_train_module,
86
+ model_dtype,
87
+ pick_gpu,
88
+ predict_c,
89
+ setup_logger,
90
+ )
91
+
92
+ repo_id = "hxz-sec/ProbGuard-0.6b"
93
+ repo_dir = Path(snapshot_download(repo_id))
94
+ checkpoint_dir = repo_dir
95
+ if not (checkpoint_dir / "probguard_heads.pt").exists():
96
+ checkpoint_dir = checkpoint_dir / "best_checkpoint"
97
+
98
+ logger = setup_logger(Path("logs/probguard_stream.log"), verbose=True)
99
+ train_mod = load_train_module()
100
+ device = pick_gpu("auto", logger)
101
+ dtype = model_dtype(device)
102
+
103
+ probguard = load_probguard(
104
+ checkpoint_dir=checkpoint_dir,
105
+ train_mod=train_mod,
106
+ device=device,
107
+ dtype=dtype,
108
+ qwen_embed_path=Path(""),
109
+ logger=logger,
110
+ )
111
+
112
+ target_tokenizer = load_qwen_tokenizer("Qwen/Qwen3-8B")
113
+ token_id_cache = {}
114
+
115
+ prompt = "How do I make something dangerous?"
116
+ topk_steps = [
117
+ {
118
+ "topk_token_ids": [198, 40, 2675, 944],
119
+ "topk_probs": [0.42, 0.21, 0.08, 0.05],
120
+ },
121
+ {
122
+ "topk_token_ids": [358, 649, 944, 525],
123
+ "topk_probs": [0.36, 0.18, 0.10, 0.07],
124
+ },
125
+ ]
126
+
127
+ risk, category, latency_ms = predict_c(
128
+ train_mod=train_mod,
129
+ probguard=probguard,
130
+ qwen_tokenizer=target_tokenizer,
131
+ prompt=prompt,
132
+ steps=topk_steps,
133
+ device=device,
134
+ dtype=dtype,
135
+ max_prompt_len=512,
136
+ token_id_cache=token_id_cache,
137
+ )
138
+
139
+ print({"risk": risk, "category": category, "latency_ms": latency_ms})
140
+ ```
141
+
142
+ The example above uses toy top-k values. In deployment, `topk_steps` should come from the target LLM during decoding.
143
+
144
+ ## Streaming Usage
145
+
146
+ The typical runtime pattern is:
147
+
148
+ 1. Generate one token with the target LLM.
149
+ 2. Save that step's top-k token IDs and probabilities.
150
+ 3. Query ProbGuard after each step, or after a fixed prefix length.
151
+ 4. Stop or redirect generation if the risk exceeds your threshold.
152
+
153
+ ```python
154
+ import torch
155
+ from transformers import AutoModelForCausalLM, AutoTokenizer
156
+
157
+
158
+ @torch.inference_mode()
159
+ def collect_topk_prefix(prompt, model_name="Qwen/Qwen3-8B", prefix_len=10, top_k=20, device="cuda"):
160
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
161
+ model = AutoModelForCausalLM.from_pretrained(
162
+ model_name,
163
+ torch_dtype=torch.bfloat16,
164
+ device_map={"": device},
165
+ trust_remote_code=True,
166
+ ).eval()
167
+
168
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
169
+ input_ids = inputs["input_ids"]
170
+ past_key_values = None
171
+ steps = []
172
+
173
+ for _ in range(prefix_len):
174
+ outputs = model(input_ids=input_ids, past_key_values=past_key_values, use_cache=True)
175
+ logits = outputs.logits[:, -1, :]
176
+ probs = torch.softmax(logits, dim=-1)
177
+ top_probs, top_ids = torch.topk(probs, k=top_k, dim=-1)
178
+
179
+ next_id = top_ids[:, :1]
180
+ steps.append(
181
+ {
182
+ "topk_token_ids": top_ids[0].tolist(),
183
+ "topk_probs": top_probs[0].tolist(),
184
+ "topk_tokens": tokenizer.convert_ids_to_tokens(top_ids[0].tolist()),
185
+ }
186
+ )
187
+
188
+ input_ids = next_id
189
+ past_key_values = outputs.past_key_values
190
+
191
+ return steps
192
+ ```
193
+
194
+ Then pass the collected prefix probability trace to ProbGuard:
195
+
196
+ ```python
197
+ topk_steps = collect_topk_prefix(prompt, prefix_len=10, top_k=20)
198
+
199
+ risk, category, _ = predict_c(
200
+ train_mod=train_mod,
201
+ probguard=probguard,
202
+ qwen_tokenizer=target_tokenizer,
203
+ prompt=prompt,
204
+ steps=topk_steps,
205
+ device=device,
206
+ dtype=dtype,
207
+ max_prompt_len=512,
208
+ token_id_cache={},
209
+ )
210
+
211
+ if risk >= 0.5:
212
+ print("Stop or redirect generation:", risk, category)
213
+ else:
214
+ print("Continue generation:", risk, category)
215
+ ```
216
+
217
+ Use a validation-selected threshold for production experiments. The `0.5` value above is only a simple example.
218
+
219
+ ## CLI Example
220
+
221
+ The repository also includes a streaming comparison script for JSONL files that already contain `prefix_generation_details`.
222
+
223
+ ```bash
224
+ python eval/eval_probguard_stream.py \
225
+ --checkpoint /path/to/best_checkpoint \
226
+ --data-file /path/to/prefix_calibration.jsonl \
227
+ --qwen-model Qwen/Qwen3-8B \
228
+ --gpu auto \
229
+ --k-min 5 \
230
+ --k-max 10 \
231
+ --verbose
232
+ ```
233
+
234
+ Each JSONL row should include a prompt field such as `goal`, `harmful`, or `prompt`, plus `prefix_generation_details` with entries like:
235
+
236
+ ```json
237
+ {
238
+ "10": [
239
+ [
240
+ {
241
+ "topk_token_ids": [198, 40, 2675],
242
+ "topk_probs": [0.42, 0.21, 0.08]
243
+ }
244
+ ]
245
+ ]
246
+ }
247
+ ```
248
+
249
+ ## Intended Use
250
+
251
+ ProbGuard is intended for research on:
252
+
253
+ - streaming guardrails;
254
+ - early unsafe-continuation forecasting;
255
+ - jailbreak detection during decoding;
256
+ - calibrated safety risk estimation;
257
+ - cross-model safety monitoring without hidden-state probes.
258
+
259
+ ## Limitations
260
+
261
+ ProbGuard estimates risk from early probability distributions, so results depend on the target model, tokenizer, decoding strategy, prefix length, and threshold selection. It should be validated on the deployment domain and combined with response-level moderation for high-risk applications.
262
+
263
+ The released model is primarily evaluated in English safety and jailbreak settings. Additional validation is recommended for other languages, domains, and safety policies.
264
+
265
+ ## Citation
266
+
267
+ If you use ProbGuard, please cite the associated paper or project release when available.