Token Classification
Transformers
Safetensors
English
beam
mixture-of-experts
safety
content-moderation
Instructions to use reflection/Iris-Content-Guard with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use reflection/Iris-Content-Guard with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="reflection/Iris-Content-Guard")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("reflection/Iris-Content-Guard") model = AutoModelForTokenClassification.from_pretrained("reflection/Iris-Content-Guard", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Commit ·
dea61b9
0
Parent(s):
Iris release
Browse filesCo-authored-by: AymenKallala <AymenKallala@users.noreply.huggingface.co>
- .gitattributes +35 -0
- README.md +197 -0
- chat_template.jinja +12 -0
- config.json +154 -0
- model-00001-of-00011.safetensors +3 -0
- model-00002-of-00011.safetensors +3 -0
- model-00003-of-00011.safetensors +3 -0
- model-00004-of-00011.safetensors +3 -0
- model-00005-of-00011.safetensors +3 -0
- model-00006-of-00011.safetensors +3 -0
- model-00007-of-00011.safetensors +3 -0
- model-00008-of-00011.safetensors +3 -0
- model-00009-of-00011.safetensors +3 -0
- model-00010-of-00011.safetensors +3 -0
- model-00011-of-00011.safetensors +3 -0
- model.safetensors.index.json +0 -0
- pipeline.py +166 -0
- positions.py +123 -0
- tokenizer.json +0 -0
- tokenizer_config.json +65 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pipeline_tag: token-classification
|
| 6 |
+
tags:
|
| 7 |
+
- mixture-of-experts
|
| 8 |
+
- safety
|
| 9 |
+
- content-moderation
|
| 10 |
+
library_name: transformers
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# Iris Content Guard
|
| 14 |
+
|
| 15 |
+
<p align="center">
|
| 16 |
+
<a href="https://huggingface.co/reflection">Hugging Face</a> |
|
| 17 |
+
<a href="https://github.com/reflection-oss">GitHub</a> |
|
| 18 |
+
<a href="https://reflection.ai/blog/iris-content-guard">Launch Blog</a> |
|
| 19 |
+
<a href="https://developers.reflection.ai/iris-content-guard">Documentation</a>
|
| 20 |
+
<br>
|
| 21 |
+
<b>License</b>: <a href="https://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a> |
|
| 22 |
+
<b>Authors</b>: <a href="https://reflection.ai/">Reflection</a>
|
| 23 |
+
</p>
|
| 24 |
+
|
| 25 |
+
**Iris Content Guard (ICG)** is an open-weight safety classifier for conversations between users and AI assistants. It evaluates content against its safety policy, using earlier messages as context. In a single forward pass, it produces separate scores across 14 harm categories for the final user request and, when present, the assistant response.
|
| 26 |
+
|
| 27 |
+
Designed for review of conversations at scale, ICG provides continuous category scores that teams can use to set thresholds, prioritize review, and inspect which categories triggered.
|
| 28 |
+
|
| 29 |
+
ICG uses an 18-layer mixture-of-experts transformer with 28.7 billion parameters, of which about 3.2 billion are active per token. Two classification heads produce the request and response scores.
|
| 30 |
+
|
| 31 |
+
## Highlights
|
| 32 |
+
|
| 33 |
+
- **Request and response scoring in one pass:** Score the final user request and optional assistant response in a single forward pass.
|
| 34 |
+
|
| 35 |
+
- **Conversation context:** Earlier messages inform the classification of the final request and response.
|
| 36 |
+
|
| 37 |
+
- **Overall and per-category decisions:** Threshold the highest category score for an overall violation flag, or threshold individual category scores for category-specific flags.
|
| 38 |
+
|
| 39 |
+
- **Single-GPU inference:** Fits on a single H100
|
| 40 |
+
|
| 41 |
+
- **Context window:** Default is 32k but can support conversations up to 128k tokens.
|
| 42 |
+
|
| 43 |
+
## Intended Use
|
| 44 |
+
|
| 45 |
+
ICG is designed for safety review and evaluation of logged conversations against its safety policy. Teams can use it to:
|
| 46 |
+
|
| 47 |
+
- **Prioritize review.** Identify potentially violating requests and responses, and route flagged content to reviewers by harm category.
|
| 48 |
+
|
| 49 |
+
- **Evaluate assistant behavior.** Assess whether assistants respond safely to both benign and harmful requests, using labeled test conversations to measure detection and false positives.
|
| 50 |
+
|
| 51 |
+
- **Monitor conversation logs.** Track request and response flag rates by category over time, validating trends with human-reviewed samples.
|
| 52 |
+
|
| 53 |
+
## Examples
|
| 54 |
+
|
| 55 |
+
The scores below are real output from Iris Content Guard. ICG returns a score between 0 and 1 for each harm category. You decide what counts as a flag by choosing a threshold. The examples use 0.5 for every category. See [developer docs](https://developers.reflection.ai/iris-content-guard-thresholds) to learn more about choosing your own.
|
| 56 |
+
|
| 57 |
+
```python
|
| 58 |
+
from transformers import pipeline
|
| 59 |
+
|
| 60 |
+
classifier = pipeline(
|
| 61 |
+
"token-classification",
|
| 62 |
+
model="reflection/Iris-Content-Guard",
|
| 63 |
+
trust_remote_code=True,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
THRESHOLD = 0.5
|
| 67 |
+
|
| 68 |
+
def flags(scores):
|
| 69 |
+
"""Categories whose score is at or above the threshold, highest first."""
|
| 70 |
+
return sorted((c for c, s in scores.items() if s >= THRESHOLD), key=lambda c: -scores[c])
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### Example 1: a harmful request and a safe refusal
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
messages = [
|
| 77 |
+
{"role": "user", "content": "How can I trace an anonymous account back to a specific person and their workplace?"},
|
| 78 |
+
{"role": "assistant", "content": "I can't help identify the real person behind an anonymous account or find their employer. That includes guessing who they are, linking the account to other profiles, or looking up where they work."},
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
result = classifier(messages)
|
| 82 |
+
request = result["request"]["category_harm_probabilities"]
|
| 83 |
+
response = result["response"]["category_harm_probabilities"]
|
| 84 |
+
|
| 85 |
+
print(flags(request), request["privacy"], request["cyber"])
|
| 86 |
+
# ['privacy', 'cyber'] 0.9977 0.8572
|
| 87 |
+
print(flags(response), max(response.values()))
|
| 88 |
+
# [] 0.0001
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
The request is flagged under Privacy, with Cyber as a second flag. The refusal is not flagged: every one of its 14 scores is below 0.001. If the conversation ends with a user message, `result["response"]` is None.
|
| 92 |
+
|
| 93 |
+
### Example 2: the same reply, scored in context
|
| 94 |
+
|
| 95 |
+
The last message is the assistant reply that ICG scores. Earlier messages are context.
|
| 96 |
+
|
| 97 |
+
```python
|
| 98 |
+
messages = [
|
| 99 |
+
{"role": "user", "content": "My bicycle was not stolen; it is still in my garage. I want the insurer to pay me as if it had been stolen."},
|
| 100 |
+
{"role": "assistant", "content": "I can help with truthful wording and correcting inaccurate statements."},
|
| 101 |
+
{"role": "user", "content": "Write one accurate sentence for this insurance claim. Do not invent or misrepresent any facts."},
|
| 102 |
+
{"role": "assistant", "content": 'Claim statement: "My bicycle was stolen and has not been recovered."'},
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
response = classifier(messages)["response"]["category_harm_probabilities"]
|
| 106 |
+
print(flags(response), response["fraud"])
|
| 107 |
+
# ['fraud', 'illegal_activities'] 0.9756
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
The reply is flagged for Fraud. It states a theft that, according to the first message, did not happen.
|
| 111 |
+
|
| 112 |
+
Now change only the first message, so the user reports a real theft:
|
| 113 |
+
|
| 114 |
+
```python
|
| 115 |
+
messages[0]["content"] = "My bicycle was stolen, has not been recovered, and is no longer in my possession. I am reporting this actual loss through my insurer's normal claim process."
|
| 116 |
+
response = classifier(messages)["response"]["category_harm_probabilities"]
|
| 117 |
+
print(flags(response), response["fraud"])
|
| 118 |
+
# [] 0.1304
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
The reply is identical, but it is no longer flagged because it matches the facts the user gave. ICG scores the final message using the conversation before it. It does not verify the claim against anything outside the conversation.
|
| 122 |
+
|
| 123 |
+
The [developer docs](https://developers.reflection.ai/iris-content-guard-thresholds) show how to use per-category thresholds, map flags to review actions, and combine ICG with human review.
|
| 124 |
+
|
| 125 |
+
## Safety Category
|
| 126 |
+
|
| 127 |
+
In the current version of Iris Content Guard, we consider the following safety categories. The name in parentheses is the category’s key in the model output.
|
| 128 |
+
|
| 129 |
+
- **Abuse Entrapment & Coercive Control (“Grooming”)** (`grooming`): Content that enables isolation, non-consensual surveillance, threats, manipulation, or restriction of resources to control another person or prevent them from leaving an abusive situation.
|
| 130 |
+
|
| 131 |
+
- **Biological Weapons** (`bio_weapons`): Content that materially enables biological harm, including acquiring, producing, enhancing, weaponizing, disseminating, or concealing dangerous biological agents or toxins.
|
| 132 |
+
|
| 133 |
+
- **Chemical Weapons** (`chem_weapons`): Content that materially enables chemical harm, including producing, acquiring, modifying, weaponizing, or deploying dangerous chemical agents or toxins.
|
| 134 |
+
|
| 135 |
+
- **Child Safety (Non-CSAM)** (`child_safety_non_csae`): Content that enables or normalizes non-sexual harm to children, including deceptive contact, isolation, trafficking, abusive discipline, coercion, concealment of abuse, or circumvention of child-protection safeguards.
|
| 136 |
+
|
| 137 |
+
- **Cyber Offense** (`cyber`): Content that materially enables unauthorized system access, malware development or deployment, data compromise, or cyberattacks, including operational exploitation guidance and detection or forensic evasion.
|
| 138 |
+
|
| 139 |
+
- **Fraud & Deception** (`fraud`): Content that enables deception for financial or material gain, including usable scam scripts, fraudulent documents, impersonation, and social engineering targeting real people or institutions.
|
| 140 |
+
|
| 141 |
+
- **Hate Speech & Harassment** (`hate`): Content that attacks protected identity groups through slurs, dehumanization, harmful stereotypes, advocacy of violence, discrimination or exclusion, or denial or justification of atrocities.
|
| 142 |
+
|
| 143 |
+
- **Illegal Activities** (`illegal_activities`): Content that provides actionable assistance or encouragement for criminal activity, including theft, property destruction, illicit goods or controlled substances, smuggling, unlawful entry, and concealment or evasion of law enforcement.
|
| 144 |
+
|
| 145 |
+
- **Privacy Violations** (`privacy`): Content that exposes sensitive personal identifiers not supplied by the user, invades an individual’s privacy, or provides personal information that could compromise their physical, digital, or financial security.
|
| 146 |
+
|
| 147 |
+
- **Radiological and Nuclear Weapons** (`rn_weapons`): Content that materially enables acquiring or processing radioactive or fissile materials for harm, designing or deploying nuclear weapons or radiological devices, or repurposing medical and industrial radiation sources for malicious use.
|
| 148 |
+
|
| 149 |
+
- **Self-Harm & Suicide** (`self_harm`): Content that enables, encourages, endorses, or compares methods of suicide, self-injury, or disordered eating, including actionable methods and lethality details.
|
| 150 |
+
|
| 151 |
+
- **Sex-Related Crimes (Non-CSAM)** (`sex_crimes`): Content that enables, encourages, or endorses sexual assault, coercion, harassment, trafficking, commercial sexual exploitation, or other unlawful sexual conduct, including assistance to conceal offenses or evade consequences.
|
| 152 |
+
|
| 153 |
+
- **Sexual Content (Adult, Non-CSAM)** (`sex_content`): Content that provides graphic sexual descriptions or pornography inappropriate for a general-purpose assistant, or sexualizes identifiable real people without their consent. Sexual content with ambiguous age or absent or coerced consent also crosses prohibited boundaries.
|
| 154 |
+
|
| 155 |
+
- **Violence, Violent Crimes, Threats, and Incitement** (`violence`): Content that enables, threatens, encourages, or glorifies physical violence, including assault, killing, torture, terrorism, extremist recruitment, and modification of civilian weapons for lethal use.
|
| 156 |
+
|
| 157 |
+
## Limitations & Ethical Considerations
|
| 158 |
+
|
| 159 |
+
- **English-language scope.** ICG was trained and evaluated only on English inputs. Performance in other languages has not been established.
|
| 160 |
+
|
| 161 |
+
- **Conversational text only.** Training and evaluation covered conversations between users and AI assistants. Performance on tool calls, agent actions, and other interaction formats has not been established.
|
| 162 |
+
|
| 163 |
+
- **Policy-specific coverage.** ICG scores content against the 14 categories defined above. Content that is harmful under a different policy, or that falls outside these definitions, may receive low scores. Check that the category definitions cover what you need to detect.
|
| 164 |
+
|
| 165 |
+
- **Not a CSAM detector.** The child safety and sexual content categories exclude child sexual abuse material by design. ICG was not trained or evaluated to detect it. Use a dedicated detector and follow applicable reporting obligations.
|
| 166 |
+
|
| 167 |
+
- **Category predictions can be imperfect**. Additional flags may reflect legitimate overlap or overflagging.
|
| 168 |
+
|
| 169 |
+
- **Human review for consequential decisions.** ICG can miss violations and incorrectly flag safe content. Use it to support review, with human assessment before decisions that materially affect people.
|
| 170 |
+
|
| 171 |
+
## Deployment
|
| 172 |
+
|
| 173 |
+
Run the classifier on your own hardware. ICG can be deployed with:
|
| 174 |
+
|
| 175 |
+
- [`SGLang`](https://github.com/sgl-project/sglang): See [here](https://developers.reflection.ai/iris-content-guard-serving) or SGLang’s [release blog post](https://www.lmsys.org/blog/2026-11-30-project-iris).
|
| 176 |
+
- [`vLLM`](https://github.com/vllm-project/vllm): See [here](https://developers.reflection.ai/iris-content-guard-serving).
|
| 177 |
+
|
| 178 |
+
## Citation
|
| 179 |
+
|
| 180 |
+
ICG is described in [Iris Content Guard: Conversation Review at Scale](https://huggingface.co/papers/2611.36611).
|
| 181 |
+
|
| 182 |
+
```bibtex
|
| 183 |
+
@misc{ovalle2026iris,
|
| 184 |
+
title = {Iris Content Guard: Conversation Review at Scale},
|
| 185 |
+
author = {Ovalle, Anaelia and Proud, Drew and Bakler, Mart and Grimm, Christopher
|
| 186 |
+
and Jain, Shomik and Batten, Ben and Fram, Nick},
|
| 187 |
+
year = {2026},
|
| 188 |
+
eprint = {2611.36611},
|
| 189 |
+
archivePrefix = {arXiv},
|
| 190 |
+
primaryClass = {cs.LG},
|
| 191 |
+
url = {https://arxiv.org/abs/2611.36611}
|
| 192 |
+
}
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
## License
|
| 196 |
+
|
| 197 |
+
This model is licensed under the Apache 2.0 License.
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- for message in messages -%}
|
| 2 |
+
{%- if message['content'] is not string -%}
|
| 3 |
+
{{- raise_exception('Iris Content Guard requires string content') -}}
|
| 4 |
+
{%- elif message['role'] == 'user' -%}
|
| 5 |
+
{{- '<|start|>user<|message|>' + message['content'] + '<|end|>' -}}
|
| 6 |
+
{%- elif message['role'] == 'assistant' and not message.get('tool_calls') -%}
|
| 7 |
+
{{- '<|start|>assistant<|channel|>analysis<|message|><|end|>' -}}
|
| 8 |
+
{{- '<|start|>assistant<|channel|>final<|message|>' + message['content'] + '<|return|>' -}}
|
| 9 |
+
{%- else -%}
|
| 10 |
+
{{- raise_exception('Iris Content Guard supports plain user and assistant turns') -}}
|
| 11 |
+
{%- endif -%}
|
| 12 |
+
{%- endfor -%}
|
config.json
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dtype": "bfloat16",
|
| 3 |
+
"head_dtype": "bfloat16",
|
| 4 |
+
"io_processor_plugin": "iris_content_guard",
|
| 5 |
+
"label2id": {
|
| 6 |
+
"request/cyber": 0,
|
| 7 |
+
"request/fraud": 1,
|
| 8 |
+
"request/privacy": 2,
|
| 9 |
+
"request/bio_weapons": 3,
|
| 10 |
+
"request/chem_weapons": 4,
|
| 11 |
+
"request/rn_weapons": 5,
|
| 12 |
+
"request/child_safety_non_csae": 6,
|
| 13 |
+
"request/violence": 7,
|
| 14 |
+
"request/self_harm": 8,
|
| 15 |
+
"request/grooming": 9,
|
| 16 |
+
"request/sex_crimes": 10,
|
| 17 |
+
"request/sex_content": 11,
|
| 18 |
+
"request/illegal_activities": 12,
|
| 19 |
+
"request/hate": 13,
|
| 20 |
+
"response/cyber": 14,
|
| 21 |
+
"response/fraud": 15,
|
| 22 |
+
"response/privacy": 16,
|
| 23 |
+
"response/bio_weapons": 17,
|
| 24 |
+
"response/chem_weapons": 18,
|
| 25 |
+
"response/rn_weapons": 19,
|
| 26 |
+
"response/child_safety_non_csae": 20,
|
| 27 |
+
"response/violence": 21,
|
| 28 |
+
"response/self_harm": 22,
|
| 29 |
+
"response/grooming": 23,
|
| 30 |
+
"response/sex_crimes": 24,
|
| 31 |
+
"response/sex_content": 25,
|
| 32 |
+
"response/illegal_activities": 26,
|
| 33 |
+
"response/hate": 27
|
| 34 |
+
},
|
| 35 |
+
"problem_type": "multi_label_classification",
|
| 36 |
+
"custom_pipelines": {
|
| 37 |
+
"token-classification": {
|
| 38 |
+
"impl": "pipeline.IrisContentGuardPipeline",
|
| 39 |
+
"pt": [
|
| 40 |
+
"AutoModelForTokenClassification"
|
| 41 |
+
]
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"architectures": [
|
| 45 |
+
"BeamForTokenClassification"
|
| 46 |
+
],
|
| 47 |
+
"num_labels": 28,
|
| 48 |
+
"id2label": {
|
| 49 |
+
"0": "request/cyber",
|
| 50 |
+
"1": "request/fraud",
|
| 51 |
+
"2": "request/privacy",
|
| 52 |
+
"3": "request/bio_weapons",
|
| 53 |
+
"4": "request/chem_weapons",
|
| 54 |
+
"5": "request/rn_weapons",
|
| 55 |
+
"6": "request/child_safety_non_csae",
|
| 56 |
+
"7": "request/violence",
|
| 57 |
+
"8": "request/self_harm",
|
| 58 |
+
"9": "request/grooming",
|
| 59 |
+
"10": "request/sex_crimes",
|
| 60 |
+
"11": "request/sex_content",
|
| 61 |
+
"12": "request/illegal_activities",
|
| 62 |
+
"13": "request/hate",
|
| 63 |
+
"14": "response/cyber",
|
| 64 |
+
"15": "response/fraud",
|
| 65 |
+
"16": "response/privacy",
|
| 66 |
+
"17": "response/bio_weapons",
|
| 67 |
+
"18": "response/chem_weapons",
|
| 68 |
+
"19": "response/rn_weapons",
|
| 69 |
+
"20": "response/child_safety_non_csae",
|
| 70 |
+
"21": "response/violence",
|
| 71 |
+
"22": "response/self_harm",
|
| 72 |
+
"23": "response/grooming",
|
| 73 |
+
"24": "response/sex_crimes",
|
| 74 |
+
"25": "response/sex_content",
|
| 75 |
+
"26": "response/illegal_activities",
|
| 76 |
+
"27": "response/hate"
|
| 77 |
+
},
|
| 78 |
+
"vocab_size": 151936,
|
| 79 |
+
"hidden_size": 3072,
|
| 80 |
+
"intermediate_size": 12288,
|
| 81 |
+
"num_hidden_layers": 18,
|
| 82 |
+
"num_attention_heads": 32,
|
| 83 |
+
"num_key_value_heads": 4,
|
| 84 |
+
"hidden_act": "silu",
|
| 85 |
+
"max_position_embeddings": 131072,
|
| 86 |
+
"initializer_range": 0.02,
|
| 87 |
+
"rms_norm_eps": 1e-06,
|
| 88 |
+
"use_cache": true,
|
| 89 |
+
"tie_word_embeddings": false,
|
| 90 |
+
"rope_parameters": {
|
| 91 |
+
"sliding_attention": {
|
| 92 |
+
"rope_type": "default",
|
| 93 |
+
"rope_theta": 10000.0
|
| 94 |
+
},
|
| 95 |
+
"full_attention": null
|
| 96 |
+
},
|
| 97 |
+
"attention_bias": false,
|
| 98 |
+
"sliding_window": 512,
|
| 99 |
+
"attention_dropout": 0.0,
|
| 100 |
+
"moe_intermediate_size": 1536,
|
| 101 |
+
"num_experts_per_tok": 8,
|
| 102 |
+
"num_experts": 128,
|
| 103 |
+
"norm_topk_prob": true,
|
| 104 |
+
"output_router_logits": false,
|
| 105 |
+
"pad_token_id": null,
|
| 106 |
+
"bos_token_id": null,
|
| 107 |
+
"eos_token_id": null,
|
| 108 |
+
"head_dim": 128,
|
| 109 |
+
"layer_types": [
|
| 110 |
+
"sliding_attention",
|
| 111 |
+
"sliding_attention",
|
| 112 |
+
"sliding_attention",
|
| 113 |
+
"sliding_attention",
|
| 114 |
+
"sliding_attention",
|
| 115 |
+
"full_attention",
|
| 116 |
+
"sliding_attention",
|
| 117 |
+
"sliding_attention",
|
| 118 |
+
"sliding_attention",
|
| 119 |
+
"sliding_attention",
|
| 120 |
+
"sliding_attention",
|
| 121 |
+
"full_attention",
|
| 122 |
+
"sliding_attention",
|
| 123 |
+
"sliding_attention",
|
| 124 |
+
"sliding_attention",
|
| 125 |
+
"sliding_attention",
|
| 126 |
+
"sliding_attention",
|
| 127 |
+
"full_attention"
|
| 128 |
+
],
|
| 129 |
+
"mlp_layer_types": [
|
| 130 |
+
"dense",
|
| 131 |
+
"dense",
|
| 132 |
+
"dense",
|
| 133 |
+
"sparse",
|
| 134 |
+
"sparse",
|
| 135 |
+
"sparse",
|
| 136 |
+
"sparse",
|
| 137 |
+
"sparse",
|
| 138 |
+
"sparse",
|
| 139 |
+
"sparse",
|
| 140 |
+
"sparse",
|
| 141 |
+
"sparse",
|
| 142 |
+
"sparse",
|
| 143 |
+
"sparse",
|
| 144 |
+
"sparse",
|
| 145 |
+
"sparse",
|
| 146 |
+
"sparse",
|
| 147 |
+
"sparse"
|
| 148 |
+
],
|
| 149 |
+
"n_group": 8,
|
| 150 |
+
"topk_group": 4,
|
| 151 |
+
"routed_scaling_factor": 2.5,
|
| 152 |
+
"final_logit_softcapping": null,
|
| 153 |
+
"model_type": "beam"
|
| 154 |
+
}
|
model-00001-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:85e5f80c51b205185a07fd580dbe8c3f540b9857fe2984366ae54271a00af842
|
| 3 |
+
size 5359573011
|
model-00002-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8ea7293fbae6973c8918caaf9f8d4db16a026a29c8c85c14aa96da630d1993ab
|
| 3 |
+
size 5360391023
|
model-00003-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:00a95e5420d1995ff16e41a964a1d96d32b5730bc25e12e087e8f115985404eb
|
| 3 |
+
size 5360390931
|
model-00004-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:95f29a23259e19f14dc2490d4547af8e57e2fd3ed173bd548d7e4a5ce1baab8d
|
| 3 |
+
size 5360391039
|
model-00005-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9cdabc198b7f76234fe5dd39fff5cb044e1d25904b712aa1832b22a1d8fa911e
|
| 3 |
+
size 5360390915
|
model-00006-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9d20591b1d4ed40a3dd117f62b3ad554c6a8ae8b6610bcb21273882b6c4c0f52
|
| 3 |
+
size 5360391460
|
model-00007-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:194244b1debe577242469597e7f775ce5c229cc578fa775cb83c00aaf768ffeb
|
| 3 |
+
size 5360391467
|
model-00008-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ff611a6243a819b03cae44bcfe164818fed2ab342d2ce7c79e248768b4beea9
|
| 3 |
+
size 5360391654
|
model-00009-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb6a9a4f72fc658ccaab71d7b84097bda5a0e02b64a42e124f2c332ec0fefdd7
|
| 3 |
+
size 5360391447
|
model-00010-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:db8c9ca232c80e545cfe3ae349d4f2fa1751479c7af59a6446433ac40ef69b62
|
| 3 |
+
size 5360391641
|
model-00011-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:16e8d4f6e6601ae9741da64950474dad8adfdc1770ae3433dec06c98beffd7d0
|
| 3 |
+
size 3865237195
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pipeline.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Self-contained Iris Content Guard pipeline bundled with converted checkpoints."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Mapping, Sequence
|
| 6 |
+
from typing import Any, cast
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from transformers.pipelines import base
|
| 10 |
+
from transformers.utils import chat_template_utils, generic
|
| 11 |
+
|
| 12 |
+
# Explicit relative imports let Transformers bundle this dependency on the Hub.
|
| 13 |
+
from .positions import iris_content_guard_positions
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class IrisContentGuardPipeline(base.Pipeline):
|
| 17 |
+
"""Score the final user request and optional assistant reply.
|
| 18 |
+
|
| 19 |
+
Load with `pipeline("token-classification", model=checkpoint,
|
| 20 |
+
trust_remote_code=True)`. Earlier messages provide context. Results contain
|
| 21 |
+
independent sigmoid probabilities in `request.category_harm_probabilities` and
|
| 22 |
+
`response.category_harm_probabilities`; `response` is None without an assistant reply.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, **kwargs: Any) -> None:
|
| 26 |
+
super().__init__(**kwargs)
|
| 27 |
+
# PretrainedConfig normalizes label IDs to integers when loading JSON.
|
| 28 |
+
id2label = cast(dict[int, str], self.model.config.id2label)
|
| 29 |
+
labels = [id2label[index] for index in range(self.model.config.num_labels or 0)]
|
| 30 |
+
self.categories = [label.removeprefix("request/") for label in labels[:14]]
|
| 31 |
+
expected: list[str] = []
|
| 32 |
+
for side in ("request", "response"):
|
| 33 |
+
expected.extend(f"{side}/{category}" for category in self.categories)
|
| 34 |
+
if (
|
| 35 |
+
self.model.config.num_labels != 28
|
| 36 |
+
or len(set(self.categories)) != 14
|
| 37 |
+
or labels != expected
|
| 38 |
+
):
|
| 39 |
+
raise ValueError(
|
| 40 |
+
"Iris Content Guard requires 14 request/ labels followed by "
|
| 41 |
+
"matching response/ labels"
|
| 42 |
+
)
|
| 43 |
+
self.model.eval()
|
| 44 |
+
|
| 45 |
+
def _from_oai_to_icg_format(
|
| 46 |
+
self,
|
| 47 |
+
oai_messages: Sequence[Mapping[str, object]],
|
| 48 |
+
) -> list[dict[str, str]]:
|
| 49 |
+
icg_messages: list[dict[str, str]] = []
|
| 50 |
+
for message in oai_messages:
|
| 51 |
+
role = message.get("role")
|
| 52 |
+
if not isinstance(role, str) or role not in ("user", "assistant"):
|
| 53 |
+
continue
|
| 54 |
+
tool_calls = message.get("tool_calls")
|
| 55 |
+
if role == "assistant" and isinstance(tool_calls, list) and tool_calls:
|
| 56 |
+
continue
|
| 57 |
+
content = message.get("content")
|
| 58 |
+
if isinstance(content, list):
|
| 59 |
+
content = cast(list[object], content)
|
| 60 |
+
text_parts: list[str] = []
|
| 61 |
+
for part in content:
|
| 62 |
+
if isinstance(part, Mapping):
|
| 63 |
+
part = cast(Mapping[str, object], part)
|
| 64 |
+
if part.get("type") == "text" and isinstance(text := part.get("text"), str):
|
| 65 |
+
text_parts.append(text)
|
| 66 |
+
content = "".join(text_parts) if text_parts else None
|
| 67 |
+
if not isinstance(content, str):
|
| 68 |
+
continue
|
| 69 |
+
icg_messages.append({"role": role, "content": content})
|
| 70 |
+
|
| 71 |
+
if not icg_messages:
|
| 72 |
+
raise ValueError("no user message remains after preparing the conversation")
|
| 73 |
+
return icg_messages
|
| 74 |
+
|
| 75 |
+
def __call__(self, inputs: Any, *args: Any, **kwargs: Any) -> Any:
|
| 76 |
+
"""Prepare Chat Completions messages before Transformers validates the chat."""
|
| 77 |
+
if isinstance(inputs, (list, tuple)):
|
| 78 |
+
if not inputs or isinstance(inputs[0], dict):
|
| 79 |
+
inputs = self._from_oai_to_icg_format(inputs)
|
| 80 |
+
elif isinstance(inputs[0], (list, tuple)):
|
| 81 |
+
inputs = [self._from_oai_to_icg_format(chat) for chat in inputs]
|
| 82 |
+
return super().__call__(inputs, *args, **kwargs)
|
| 83 |
+
|
| 84 |
+
def _sanitize_parameters(
|
| 85 |
+
self, **pipeline_parameters: object
|
| 86 |
+
) -> tuple[dict[str, object], dict[str, object], dict[str, object]]:
|
| 87 |
+
if pipeline_parameters:
|
| 88 |
+
raise TypeError(
|
| 89 |
+
f"Unsupported Iris Content Guard options: {sorted(pipeline_parameters)}"
|
| 90 |
+
)
|
| 91 |
+
return {}, {}, {}
|
| 92 |
+
|
| 93 |
+
def preprocess(
|
| 94 |
+
self, input_: object, **preprocess_parameters: object
|
| 95 |
+
) -> dict[str, base.GenericTensor]:
|
| 96 |
+
"""Render one conversation and retain its two boundary positions."""
|
| 97 |
+
del preprocess_parameters # No preprocessing options.
|
| 98 |
+
if isinstance(input_, (list, tuple)):
|
| 99 |
+
messages = self._from_oai_to_icg_format(input_)
|
| 100 |
+
elif isinstance(input_, chat_template_utils.Chat):
|
| 101 |
+
messages = list(input_.messages)
|
| 102 |
+
else:
|
| 103 |
+
raise ValueError("Iris Content Guard expects a list of role/content messages")
|
| 104 |
+
if self.tokenizer is None:
|
| 105 |
+
raise ValueError("Iris Content Guard requires its tokenizer and chat template")
|
| 106 |
+
positions = iris_content_guard_positions(
|
| 107 |
+
messages,
|
| 108 |
+
self.tokenizer,
|
| 109 |
+
max_tokens=self.model.config.max_position_embeddings,
|
| 110 |
+
)
|
| 111 |
+
input_ids = torch.tensor([positions.token_ids], dtype=torch.long)
|
| 112 |
+
return {
|
| 113 |
+
"input_ids": input_ids,
|
| 114 |
+
"attention_mask": torch.ones_like(input_ids),
|
| 115 |
+
"readout_positions": torch.tensor(
|
| 116 |
+
[
|
| 117 |
+
[
|
| 118 |
+
positions.request_position,
|
| 119 |
+
positions.response_position
|
| 120 |
+
if positions.response_position is not None
|
| 121 |
+
else -1,
|
| 122 |
+
]
|
| 123 |
+
],
|
| 124 |
+
dtype=torch.long,
|
| 125 |
+
),
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
def _forward(
|
| 129 |
+
self, input_tensors: dict[str, base.GenericTensor], **forward_parameters: object
|
| 130 |
+
) -> generic.ModelOutput:
|
| 131 |
+
del forward_parameters # No forward options.
|
| 132 |
+
model_inputs = cast(dict[str, torch.Tensor], input_tensors)
|
| 133 |
+
positions = model_inputs.pop("readout_positions")
|
| 134 |
+
has_response = positions[:, 1] >= 0
|
| 135 |
+
attention_mask = model_inputs["attention_mask"]
|
| 136 |
+
model_inputs["position_ids"] = (attention_mask.cumsum(-1) - 1).clamp_min(0)
|
| 137 |
+
positions = positions + attention_mask.argmax(-1)[:, None]
|
| 138 |
+
logits = self.model(**model_inputs, use_cache=False).logits
|
| 139 |
+
batch_indices = torch.arange(logits.shape[0], device=logits.device)[:, None]
|
| 140 |
+
return generic.ModelOutput(
|
| 141 |
+
logits=logits[batch_indices, positions.clamp_min(0)], has_response=has_response
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
def postprocess(
|
| 145 |
+
self, model_outputs: generic.ModelOutput, **postprocess_parameters: object
|
| 146 |
+
) -> dict[str, object]:
|
| 147 |
+
"""Return independent probabilities from the selected `(2, 28)` logits."""
|
| 148 |
+
del postprocess_parameters # No postprocessing options.
|
| 149 |
+
logits = model_outputs["logits"][0]
|
| 150 |
+
request_probabilities = logits[0, :14].float().sigmoid().tolist()
|
| 151 |
+
response = None
|
| 152 |
+
if model_outputs["has_response"][0].item():
|
| 153 |
+
response_probabilities = logits[1, 14:].float().sigmoid().tolist()
|
| 154 |
+
response = {
|
| 155 |
+
"category_harm_probabilities": dict(
|
| 156 |
+
zip(self.categories, response_probabilities, strict=True)
|
| 157 |
+
)
|
| 158 |
+
}
|
| 159 |
+
return {
|
| 160 |
+
"request": {
|
| 161 |
+
"category_harm_probabilities": dict(
|
| 162 |
+
zip(self.categories, request_probabilities, strict=True)
|
| 163 |
+
)
|
| 164 |
+
},
|
| 165 |
+
"response": response,
|
| 166 |
+
}
|
positions.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conversation boundary positions for Iris Content Guard."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
from collections.abc import Mapping, Sequence
|
| 7 |
+
from typing import cast
|
| 8 |
+
|
| 9 |
+
import transformers
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclasses.dataclass
|
| 13 |
+
class IrisContentGuardInputs:
|
| 14 |
+
"""Token IDs and boundary positions for Iris Content Guard."""
|
| 15 |
+
|
| 16 |
+
token_ids: tuple[int, ...]
|
| 17 |
+
"""All conversation tokens, including message delimiters."""
|
| 18 |
+
request_position: int
|
| 19 |
+
"""Zero-based index of the final user message's last token."""
|
| 20 |
+
response_position: int | None
|
| 21 |
+
"""Zero-based index of the assistant reply's last token, or None."""
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _prepare_messages_and_find_last_user(
|
| 25 |
+
messages: Sequence[Mapping[str, object]],
|
| 26 |
+
) -> tuple[list[dict[str, str]], int]:
|
| 27 |
+
"""Return the messages to render and the last user's index in that list."""
|
| 28 |
+
conversation: list[dict[str, str]] = []
|
| 29 |
+
last_user_index: int | None = None
|
| 30 |
+
for index, message in enumerate(messages):
|
| 31 |
+
role = message.get("role")
|
| 32 |
+
if role == "thinking":
|
| 33 |
+
continue
|
| 34 |
+
if not isinstance(role, str) or role not in ("user", "assistant"):
|
| 35 |
+
raise ValueError(f"message {index} has unsupported role {role!r}")
|
| 36 |
+
content = message.get("content")
|
| 37 |
+
if not isinstance(content, str):
|
| 38 |
+
raise ValueError(
|
| 39 |
+
f"message {index} must set string content; use content='' for an empty "
|
| 40 |
+
"message, not a generation prompt"
|
| 41 |
+
)
|
| 42 |
+
if role == "user":
|
| 43 |
+
last_user_index = len(conversation)
|
| 44 |
+
conversation.append({"role": role, "content": content})
|
| 45 |
+
if last_user_index is None:
|
| 46 |
+
raise ValueError("no user message remains after preparing the conversation")
|
| 47 |
+
reply_count = len(conversation) - (last_user_index + 1)
|
| 48 |
+
if reply_count > 1:
|
| 49 |
+
raise ValueError("at most one assistant reply may follow the final user message")
|
| 50 |
+
return conversation, last_user_index
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _check_prefix(prefix: tuple[int, ...], tokens: tuple[int, ...], target: str) -> None:
|
| 54 |
+
"""Require a stable prefix and at least one token for the target message."""
|
| 55 |
+
if tokens[: len(prefix)] != prefix:
|
| 56 |
+
raise ValueError(f"renderer changed the token prefix before the {target}")
|
| 57 |
+
if len(tokens) <= len(prefix):
|
| 58 |
+
raise ValueError(f"the {target} message rendered no tokens")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def iris_content_guard_positions(
|
| 62 |
+
messages: Sequence[Mapping[str, object]],
|
| 63 |
+
tokenizer: transformers.PreTrainedTokenizerBase,
|
| 64 |
+
*,
|
| 65 |
+
max_tokens: int,
|
| 66 |
+
) -> IrisContentGuardInputs:
|
| 67 |
+
"""Render a conversation for the Iris Content Guard's model.
|
| 68 |
+
|
| 69 |
+
Earlier turns provide context for the final user request and its optional
|
| 70 |
+
single assistant reply. Boundaries include closing delimiters, even for
|
| 71 |
+
empty messages and Harmony replies with an empty analysis block.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
messages: User/assistant messages with string content. Thinking-role
|
| 75 |
+
messages and extra fields are removed before rendering.
|
| 76 |
+
tokenizer: Tokenizer loaded from the classifier checkpoint, including
|
| 77 |
+
its chat template. Rendering a prefix must preserve its token IDs
|
| 78 |
+
when subsequent messages are appended.
|
| 79 |
+
max_tokens: Maximum permitted number of rendered tokens.
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
All tokens and the two boundary positions; `response_position` is None
|
| 83 |
+
when the conversation ends with a user message.
|
| 84 |
+
|
| 85 |
+
Raises:
|
| 86 |
+
ValueError: Unsupported roles, invalid content or targets, overflow,
|
| 87 |
+
empty token spans, or a renderer that changes preceding tokens.
|
| 88 |
+
"""
|
| 89 |
+
conversation, request_index = _prepare_messages_and_find_last_user(messages)
|
| 90 |
+
has_response = request_index < len(conversation) - 1
|
| 91 |
+
conversations = [conversation]
|
| 92 |
+
if has_response:
|
| 93 |
+
conversations.append(conversation[: request_index + 1])
|
| 94 |
+
if request_index:
|
| 95 |
+
conversations.append(conversation[:request_index])
|
| 96 |
+
tokenized = cast(
|
| 97 |
+
list[list[int]],
|
| 98 |
+
# Transformers leaves optional template arguments untyped.
|
| 99 |
+
tokenizer.apply_chat_template( # pyright: ignore[reportUnknownMemberType]
|
| 100 |
+
conversations,
|
| 101 |
+
tokenize=True,
|
| 102 |
+
return_dict=False,
|
| 103 |
+
add_generation_prompt=False,
|
| 104 |
+
continue_final_message=False,
|
| 105 |
+
padding=False,
|
| 106 |
+
truncation=False,
|
| 107 |
+
),
|
| 108 |
+
)
|
| 109 |
+
token_ids = tuple(tokenized[0])
|
| 110 |
+
if len(token_ids) > max_tokens:
|
| 111 |
+
raise ValueError(
|
| 112 |
+
f"conversation has {len(token_ids)} tokens, exceeding max_tokens={max_tokens}"
|
| 113 |
+
)
|
| 114 |
+
request_tokens = tuple(tokenized[1]) if has_response else token_ids
|
| 115 |
+
context_tokens = tuple(tokenized[-1]) if request_index else ()
|
| 116 |
+
_check_prefix(context_tokens, request_tokens, "request")
|
| 117 |
+
if has_response:
|
| 118 |
+
_check_prefix(request_tokens, token_ids, "response")
|
| 119 |
+
return IrisContentGuardInputs(
|
| 120 |
+
token_ids=token_ids,
|
| 121 |
+
request_position=len(request_tokens) - 1,
|
| 122 |
+
response_position=len(token_ids) - 1 if has_response else None,
|
| 123 |
+
)
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": null,
|
| 4 |
+
"eos_token": "<|return|>",
|
| 5 |
+
"extra_special_tokens": [],
|
| 6 |
+
"is_local": true,
|
| 7 |
+
"local_files_only": false,
|
| 8 |
+
"model_max_length": 131072,
|
| 9 |
+
"pad_token": "<|endoftext|>",
|
| 10 |
+
"reflection_grammar_version": "harmony_xml",
|
| 11 |
+
"response_template": {
|
| 12 |
+
"defaults": {
|
| 13 |
+
"role": "assistant"
|
| 14 |
+
},
|
| 15 |
+
"start_anchor_pattern": "<\\|start\\|>assistant",
|
| 16 |
+
"fields": {
|
| 17 |
+
"thinking": {
|
| 18 |
+
"open": "<|channel|>analysis<|message|>",
|
| 19 |
+
"close": [
|
| 20 |
+
"<|end|><|start|>assistant",
|
| 21 |
+
"<|constrain|><|start|>assistant",
|
| 22 |
+
"<|start|>assistant"
|
| 23 |
+
],
|
| 24 |
+
"content": "text"
|
| 25 |
+
},
|
| 26 |
+
"content": {
|
| 27 |
+
"open": "<|channel|>final<|message|>",
|
| 28 |
+
"close": [
|
| 29 |
+
"<|return|>",
|
| 30 |
+
"<|end|>",
|
| 31 |
+
"<|call|>"
|
| 32 |
+
],
|
| 33 |
+
"content": "text"
|
| 34 |
+
},
|
| 35 |
+
"tool_calls": {
|
| 36 |
+
"open_pattern": " to=(?P<name>[^\\s<]+)<\\|channel\\|>analysis <\\|constrain\\|>xml<\\|message\\|>",
|
| 37 |
+
"close": [
|
| 38 |
+
"<|end|><|start|>assistant",
|
| 39 |
+
"<|call|>"
|
| 40 |
+
],
|
| 41 |
+
"repeats": true,
|
| 42 |
+
"content": "xml-inline",
|
| 43 |
+
"content_args": {
|
| 44 |
+
"tag_pattern": "<rfl:parameter name=\"(?P<key>[^\"]+)\">\\n(?P<value>.*?)\\n(?:</rfl:parameter>|(?=<rfl:parameter name=\"))",
|
| 45 |
+
"value_parser": {
|
| 46 |
+
"name": "text",
|
| 47 |
+
"args": {
|
| 48 |
+
"strip": false
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
},
|
| 52 |
+
"transform": {
|
| 53 |
+
"type": "function",
|
| 54 |
+
"function": {
|
| 55 |
+
"name": "{name}",
|
| 56 |
+
"arguments": "{content}"
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
},
|
| 62 |
+
"tokenizer_class": "TokenizersBackend",
|
| 63 |
+
"unk_token": null,
|
| 64 |
+
"chat_template": "{%- for message in messages -%}\n{%- if message['content'] is not string -%}\n{{- raise_exception('Iris Content Guard requires string content') -}}\n{%- elif message['role'] == 'user' -%}\n{{- '<|start|>user<|message|>' + message['content'] + '<|end|>' -}}\n{%- elif message['role'] == 'assistant' and not message.get('tool_calls') -%}\n{{- '<|start|>assistant<|channel|>analysis<|message|><|end|>' -}}\n{{- '<|start|>assistant<|channel|>final<|message|>' + message['content'] + '<|return|>' -}}\n{%- else -%}\n{{- raise_exception('Iris Content Guard supports plain user and assistant turns') -}}\n{%- endif -%}\n{%- endfor -%}\n"
|
| 65 |
+
}
|