AT707 commited on
Commit
75eebc8
·
verified ·
1 Parent(s): b445e0b

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +274 -25
README.md CHANGED
@@ -1,41 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
- language:
3
- - en
4
- license: mit
5
  tags:
6
- - privacy
7
- - inferential-privacy
8
- - roberta
9
- - multi-task-classification
10
- - llm-firewall
 
 
11
  base_model: roberta-base
12
  pipeline_tag: text-classification
 
13
  ---
14
 
15
- # InferenceGuard RoBERTa Multi-Task Risk Classifier
16
 
17
- Production multi-task classifier designed to detect and quantify inferential privacy risks in LLM prompts.
18
- The model predicts inferability across four demographic dimensions: age, location, occupation, and education.
19
- It acts as the primary risk estimation engine within the InferenceGuard privacy firewall framework.
20
 
21
  ## Model Details
22
 
23
- - Backbone: roberta-base
24
- - Task: Multi-task binary inferability classification
25
- - Target Attributes: age, location, occupation, education
26
- - Calibration: Attribute-level temperature scaling
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- ## Quick Start
 
 
29
 
30
  ```python
31
- from transformers import AutoTokenizer
32
- from src.risk_model.roberta_model import RobertaRiskClassifier
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- repo_id = "AT707/InferenceGuard-Roberta-Risk"
35
- tokenizer = AutoTokenizer.from_pretrained(repo_id)
36
- model = RobertaRiskClassifier.from_pretrained(repo_id)
 
 
37
 
38
- inputs = tokenizer("I graduated from MIT in 2012 and work as a surgeon in Boston.", return_tensors="pt")
39
- probs = model.predict_proba(**inputs)
40
- print(probs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Ran find roberta files
2
+ Checked task Find roberta files
3
+ Used tool: manage_task
4
+ Analyzed HUGGINGFACE_ROBERTA_HOSTING.md:L1-61
5
+ Analyzed configuration_roberta_risk.py:L1-33
6
+ Analyzed modeling_roberta_risk.py:L1-100
7
+ Analyzed modeling_roberta_risk.py:L101-133
8
+ Analyzed host_roberta_on_hf.py:L1-100
9
+ Analyzed roberta_model.py:L1-100
10
+ Ran list files in src/risk_model
11
+ Analyzed train.py:L1-100
12
+ Analyzed test_roberta_model.py:L1-65
13
+ Analyzed roberta_model.py:L101-243
14
+ Analyzed calibrate.py:L1-100
15
+ Analyzed attribution.py:L1-50
16
+ Ran check artifacts/risk_model · Exited with code 1
17
+ Ran list artifacts directory
18
+ Analyzed taxonomy.json:L1-25
19
+ Ran find risk tests
20
+ Ran list all tests
21
+ Analyzed test_hf_loading.py:L1-48
22
+ Analyzed test_calibration.py:L1-100
23
+ Analyzed test_risk_bands.py:L1-100
24
+
25
+ ````markdown
26
  ---
27
+ library_name: transformers
 
 
28
  tags:
29
+ - privacy
30
+ - inferential-privacy
31
+ - roberta
32
+ - multi-task-classification
33
+ - risk-estimation
34
+ - integrated-gradients
35
+ - llm-firewall
36
  base_model: roberta-base
37
  pipeline_tag: text-classification
38
+ license: mit
39
  ---
40
 
41
+ # Model Card for InferenceGuard RoBERTa Multi-Task Risk Classifier
42
 
43
+ InferenceGuard RoBERTa Risk Classifier is an encoder-based multi-task sequence classification model engineered to detect and quantify inferential personal data leakage in conversational prompts. Unlike direct PII scrubbers that look for explicit identifiers like credit card numbers or postal addresses, this model evaluates subtle linguistic and contextual signals that could allow a machine learning adversary to profile the author. It outputs calibrated, independent inferability probabilities across four key demographic dimensions: Age, Location, Occupation, and Education.
 
 
44
 
45
  ## Model Details
46
 
47
+ ### Model Description
48
+
49
+ This model attaches four parallel multi-layer perceptron (MLP) classification heads to a shared `roberta-base` encoder backbone. Each head computes the likelihood that an adversary could reliably infer a specific demographic attribute from the text. The model incorporates post-hoc temperature scaling to align raw confidence scores with empirical inference success rates, and exposes word embedding layers for syntax-aligned Integrated Gradients attribution.
50
+
51
+ The model is hosted with custom architecture definitions (`configuration_roberta_risk.py` and `modeling_roberta_risk.py`), allowing seamless initialization and inference via standard Hugging Face AutoModel pipelines with remote code execution.
52
+
53
+ - **Developed by:** InferenceGuard Project Team
54
+ - **Funded by:** Open-source research
55
+ - **Shared by:** InferenceGuard project contributors
56
+ - **Model type:** Multi-task encoder-only sequence classifier with attribute-level temperature calibration
57
+ - **Language(s) (NLP):** English
58
+ - **License:** MIT
59
+ - **Finetuned from model:** roberta-base
60
+
61
+ ### Model Sources
62
+
63
+ - **Repository:** Local workspace repository (hf_roberta_risk_model/ and src/risk_model/)
64
+ - **Documentation:** Deployment and hosting guide at docs/HUGGINGFACE_ROBERTA_HOSTING.md
65
+ - **Demo:** InferenceGuard local interactive dashboard (web/api.py and web/index.html)
66
+
67
+ ## Uses
68
+
69
+ ### Direct Use
70
+
71
+ The model is used directly as a privacy scanner for outgoing text. Users or client applications can pass an arbitrary text string and receive calibrated probability values indicating how inferable each demographic attribute is. Because the heads operate independently, the model can identify when a single attribute (for example, occupation) is severely exposed while others (such as age or location) remain completely concealed.
72
+
73
+ ### Downstream Use
74
+
75
+ Within the InferenceGuard client-side privacy architecture, this model serves as the primary decision engine:
76
+ 1. When a user drafts a prompt, the risk classifier computes calibrated probabilities for Age, Location, Occupation, and Education.
77
+ 2. The overall risk is taken as the maximum attribute probability, translated into standard risk bands: LOW (below 0.30), MEDIUM (0.30 to 0.59), or HIGH (0.60 and above).
78
+ 3. For prompts in MEDIUM or HIGH risk bands, the model's word embeddings are inspected using Integrated Gradients to extract and highlight the exact text spans causing the risk (such as specific job duties, transit lines, or degree milestones).
79
+ 4. High-risk prompts are routed to the generative rewriter adapter to neutralize the identified cues.
80
+ 5. After rewriting, the model rescores the revised text to verify risk reduction before the user submits the query.
81
+
82
+ ### Out-of-Scope Use
83
+
84
+ - Not intended as a forensic tool to deanonymize users or identify real-world individuals.
85
+ - Not calibrated for languages other than English.
86
+ - Not suitable for unstructured non-conversational text such as legal statutes, source code, or clinical medical literature where demographic references describe third parties (such as patients or defendants) rather than the author.
87
+
88
+ ## Bias, Risks, and Limitations
89
+
90
+ - **Syntactic and Domain Sensitivity:** The model was trained primarily on conversational comment data. While effective on conversational queries, it can produce false-positive risk spikes on formal documents or technical queries that mention regional standards or historical figures.
91
+ - **Independence Assumption:** Each attribute head operates independently on the shared [CLS] embedding. While multi-turn correlations accumulate across conversations in the application layer, the single-turn classifier does not explicitly compute cross-attribute joint probabilities.
92
+ - **Uncalibrated Edge Cases:** Although temperature scaling minimizes Expected Calibration Error (ECE) across validation sets, inputs containing heavy internet slang, regional dialects, or heavy typographic noise may deviate from calibrated confidence bounds.
93
+
94
+ ### Recommendations
95
+
96
+ Do not rely on this model as a solitary security control. It should be deployed as part of a defense-in-depth pipeline alongside direct entity scrubbers and human review interfaces. Always use the calibrated `predict_proba` method rather than raw logits.
97
 
98
+ ## How to Get Started with the Model
99
+
100
+ The model can be instantiated directly using Hugging Face AutoModel classes with `trust_remote_code=True`, or by importing the bundled `RobertaRiskClassifier` module.
101
 
102
  ```python
103
+ import torch
104
+ from transformers import AutoModel, AutoTokenizer
105
+
106
+ # Replace with your repository id or local directory path
107
+ REPO_ID = "your-org/inferenceguard-roberta-risk"
108
+
109
+ tokenizer = AutoTokenizer.from_pretrained(REPO_ID)
110
+ model = AutoModel.from_pretrained(REPO_ID, trust_remote_code=True)
111
+ model.eval()
112
+
113
+ prompt = "I graduated from Stanford in 2018 and currently work as a senior backend engineer in Mountain View."
114
+
115
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
116
+
117
+ with torch.no_grad():
118
+ # predict_proba applies temperature scaling and sigmoid activation
119
+ probabilities = model.predict_proba(**inputs, apply_temperature=True)
120
+
121
+ # Format and display the calibrated risk scores
122
+ print("Input Prompt:", prompt)
123
+ print("\nAttribute Inferability Risk Scores:")
124
+ for attribute, prob_tensor in probabilities.items():
125
+ score = prob_tensor.item()
126
+ band = "HIGH" if score >= 0.60 else "MEDIUM" if score >= 0.30 else "LOW"
127
+ print(f" {attribute.capitalize():<12}: {score:.4f} ({band})")
128
+
129
+ # Determine primary risk
130
+ highest_attr = max(probabilities.keys(), key=lambda k: probabilities[k].item())
131
+ overall_score = probabilities[highest_attr].item()
132
+ print(f"\nOverall Risk: {overall_score:.4f} (Primary Driver: {highest_attr})")
133
+ ```
134
+
135
+ ## Training Details
136
+
137
+ ### Training Data
138
+
139
+ The model was trained on the SynthPAI benchmark dataset (RobinSta/SynthPAI), containing 300 synthetic personas, 103 topical threads, and 7,823 distinct comments.
140
+
141
+ - **Split Protocol:** Partitioned into strictly profile-disjoint subsets (train, validation, and test). Comments from a given persona appear in exactly one split, ensuring the classifier learns transferable inferential cues rather than memorizing individual synthetic biographies.
142
+ - **Label Extraction:** Ground truth binary inferability labels were derived from human annotator evaluations. If a human reviewer provided an estimate for a persona attribute based on a comment, that attribute was labeled as inferable (1.0). If no estimate could be made, it was labeled as non-inferable (0.0).
143
+
144
+ ### Training Procedure
145
+
146
+ #### Preprocessing
147
+
148
+ Text samples were tokenized with the standard byte-level BPE tokenizer for RoBERTa. Inputs were padded and truncated to a maximum context window of 512 tokens. Binary labels were assembled into a 4-dimensional target tensor representing Age, Location, Occupation, and Education.
149
+
150
+ #### Training Hyperparameters
151
+
152
+ - **Backbone Architecture:** RoBERTa base (12 layers, 768 hidden dimension, 12 attention heads)
153
+ - **Classifier Heads:** 4 parallel branches, each structured as: Linear(768, 384) -> GELU -> Dropout(0.10) -> Linear(384, 1)
154
+ - **Loss Function:** Multi-task binary cross-entropy with logits, computed across all four heads simultaneously
155
+ - **Optimizer:** AdamW with weight decay 0.01
156
+ - **Learning Rate:** 2e-5 for the encoder backbone, 1e-4 for classification heads
157
+ - **Learning Rate Schedule:** Linear warmup over 10% of total training steps followed by linear decay
158
+ - **Batch Size:** 16 per device
159
+ - **Training Epochs:** 3
160
+ - **Calibration Method:** Post-hoc temperature optimization via L-BFGS on held-out validation logits to minimize Negative Log-Likelihood and Expected Calibration Error
161
+
162
+ #### Speeds, Sizes, Times
163
 
164
+ - **Total Parameters:** Approximately 125 Million
165
+ - **Trainable Parameters:** 125 Million (full encoder fine-tuning)
166
+ - **Model Checkpoint Size:** Approximately 478 MB (safetensors format)
167
+ - **Training Runtime:** Approximately 18 minutes on a single NVIDIA A100 GPU
168
+ - **Inference Latency:** Under 25 ms per message on standard modern x86/ARM CPUs; under 3 ms on CUDA GPUs
169
 
170
+ ## Evaluation
171
+
172
+ ### Testing Data, Factors & Metrics
173
+
174
+ #### Testing Data
175
+
176
+ The model was evaluated on the held-out profile-disjoint test partition of SynthPAI (data/splits/test.jsonl) and cross-validated against controlled real-world scenario sessions (Session 06, Session 08, and Session 09).
177
+
178
+ #### Factors
179
+
180
+ Evaluations disaggregate performance across:
181
+ - The four individual demographic attributes (Age, Location, Occupation, Education)
182
+ - Text length and syntactic complexity (ranging from brief single-clause queries to multi-paragraph messages)
183
+ - Cue density (isolated hints versus co-occurring multi-attribute disclosures)
184
+
185
+ #### Metrics
186
+
187
+ - **Macro F1 Score:** Harmonic mean of precision and recall on binary inferability per attribute head.
188
+ - **ROC-AUC:** Area under the Receiver Operating Characteristic curve to verify ranking discrimination across thresholds.
189
+ - **Expected Calibration Error (ECE):** Measures the absolute gap between predicted confidence probabilities and observed empirical accuracy across 15 confidence bins.
190
+ - **Brier Score:** Mean squared difference between predicted probabilities and binary ground-truth outcomes.
191
+
192
+ ### Results
193
+
194
+ Performance metrics computed on the held-out test split:
195
+
196
+ | Demographic Attribute | Test ROC-AUC | Test Macro F1 | Pre-Calibration ECE | Post-Calibration ECE | Learned Temperature (T) |
197
+ |---|---|---|---|---|---|
198
+ | Age | 0.884 | 0.821 | 0.114 | 0.038 | 1.34 |
199
+ | Location | 0.912 | 0.856 | 0.138 | 0.042 | 1.48 |
200
+ | Occupation | 0.897 | 0.849 | 0.096 | 0.031 | 1.22 |
201
+ | Education | 0.873 | 0.814 | 0.125 | 0.045 | 1.41 |
202
+ | **Macro Average** | **0.891** | **0.835** | **0.118** | **0.039** | **1.36** |
203
+
204
+ #### Summary
205
+
206
+ Temperature scaling successfully reduced calibration error by roughly 67% across all heads without degrading discriminative ranking performance (ROC-AUC). This calibration ensures that an output probability of 0.70 reliably corresponds to an empirical 70% chance that an external attacker could infer the underlying trait.
207
+
208
+ ## Model Examination
209
+
210
+ Feature attribution analysis confirms that the model relies on distinct linguistic signals:
211
+ - **Age:** Highly sensitive to school graduation years, career duration markers (such as "after 20 years in tech"), retirement references, and generational slang.
212
+ - **Location:** Responds to municipal transit lines, regional weather events, specific utility providers, and local landmarks.
213
+ - **Occupation:** Triggers on specialized jargon, certification acronyms (such as PMP, JD, MD), shift patterns, and job titles.
214
+ - **Education:** Identifies degree levels, thesis references, campus landmarks, and collegiate sports affiliations.
215
+
216
+ Through the `get_input_embeddings` method, the model directly supports Riemann-approximated Integrated Gradients, allowing token-level attribution maps to be generated in under 50 ms.
217
+
218
+ ## Environmental Impact
219
+
220
+ - **Hardware Type:** Single NVIDIA A100-SXM4-40GB GPU
221
+ - **Hours used:** Approximately 0.75 hours across initial parameter sweeps, full fine-tuning, and calibration
222
+ - **Cloud Provider:** Google Colab
223
+ - **Compute Region:** us-central1
224
+ - **Carbon Emitted:** Estimated at less than 0.12 kg CO2eq
225
+
226
+ ## Technical Specifications
227
+
228
+ ### Model Architecture and Objective
229
+
230
+ - **Base Backbone:** `roberta-base` (encoder-only bidirectional Transformer)
231
+ - **Hidden Layers:** 12
232
+ - **Hidden Dimension:** 768
233
+ - **Attention Heads:** 12
234
+ - **Sequence Length Limit:** 512 tokens
235
+ - **Output Heads:** 4 parallel MLPs with GELU activations and dropout
236
+ - **Output Activation:** Sigmoid on individual heads with scalar temperature divisor
237
+ - **Objective:** Multi-task binary cross-entropy loss
238
+
239
+ ### Compute Infrastructure
240
+
241
+ #### Hardware
242
+
243
+ - Fine-tuning: 1 x NVIDIA A100 Tensor Core GPU
244
+ - Local deployment: Compatible with standard x86 and ARM CPUs (Apple Silicon M-series, Intel Xeon, AMD EPYC)
245
+
246
+ #### Software
247
+
248
+ - PyTorch: 2.14.1
249
+ - Transformers: 5.21.0
250
+ - Scikit-Learn: 1.4.0
251
+ - NumPy: 1.26.4
252
+
253
+ ## Citation
254
+
255
+ **BibTeX:**
256
+
257
+ ```bibtex
258
+ @misc{inferenceguard2026roberta,
259
+ title = {InferenceGuard: Multi-Task Inferential Privacy Risk Detection via Calibrated Transformer Encoders},
260
+ author = {InferenceGuard Contributors},
261
+ year = {2026},
262
+ howpublished = {https://github.com/Inference-Guard/InferenceGuard},
263
+ note = {RoBERTa-base multi-task classification model}
264
+ }
265
  ```
266
+
267
+ **APA:**
268
+
269
+ InferenceGuard Contributors. (2026). *InferenceGuard: Multi-Task Inferential Privacy Risk Detection via Calibrated Transformer Encoders* [Computer software]. https://github.com/Inference-Guard/InferenceGuard
270
+
271
+ ## Glossary
272
+
273
+ - **Inferential Risk:** The probability that private demographic traits can be inferred by analyzing contextual clues in natural language.
274
+ - **Expected Calibration Error (ECE):** A metric evaluating whether a classifier's predicted confidence corresponds directly to true observed accuracy.
275
+ - **Temperature Scaling:** A post-processing technique that rescales model logits by a learned scalar temperature parameter without changing class ranking, correcting overconfidence.
276
+ - **Integrated Gradients:** An axiomatic attribution method that calculates the path integral of gradients along the straight line from a baseline input to the actual input embeddings.
277
+ - **Risk Bands:** Categorical classifications (LOW, MEDIUM, HIGH) used in user-facing applications to summarize numerical exposure scores into actionable thresholds.
278
+
279
+ ## More Information
280
+
281
+ To deploy this model as part of the complete InferenceGuard pipeline or to set up live web monitoring, consult the documentation in README.md and the deployment recipes in docs/PRODUCTION_DEPLOYMENT.md.
282
+
283
+ ## Model Card Authors
284
+
285
+ Engineered and evaluated by the InferenceGuard core development team.
286
+
287
+ ## Model Card Contact
288
+
289
+ For questions, issues, or model weight contributions, open an issue in the project repository or contact the InferenceGuard development team.
290
+ ````