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
Download positions.py from reflection/Iris-Content-Guard: direct link, hf CLI and curl.
- Browser
- Download file 5.03 kB
-
https://huggingface.co/reflection/Iris-Content-Guard/resolve/main/positions.py
- Command line
-
hf download hf://reflection/Iris-Content-Guard/positions.py
-
curl -L -o positions.py https://huggingface.co/reflection/Iris-Content-Guard/resolve/main/positions.py
5.03 kB
| """Conversation boundary positions for Iris Content Guard.""" | |
| from __future__ import annotations | |
| import dataclasses | |
| from collections.abc import Mapping, Sequence | |
| from typing import cast | |
| import transformers | |
| class IrisContentGuardInputs: | |
| """Token IDs and boundary positions for Iris Content Guard.""" | |
| token_ids: tuple[int, ...] | |
| """All conversation tokens, including message delimiters.""" | |
| request_position: int | |
| """Zero-based index of the final user message's last token.""" | |
| response_position: int | None | |
| """Zero-based index of the assistant reply's last token, or None.""" | |
| def _prepare_messages_and_find_last_user( | |
| messages: Sequence[Mapping[str, object]], | |
| ) -> tuple[list[dict[str, str]], int]: | |
| """Return the messages to render and the last user's index in that list.""" | |
| conversation: list[dict[str, str]] = [] | |
| last_user_index: int | None = None | |
| for index, message in enumerate(messages): | |
| role = message.get("role") | |
| if role == "thinking": | |
| continue | |
| if not isinstance(role, str) or role not in ("user", "assistant"): | |
| raise ValueError(f"message {index} has unsupported role {role!r}") | |
| content = message.get("content") | |
| if not isinstance(content, str): | |
| raise ValueError( | |
| f"message {index} must set string content; use content='' for an empty " | |
| "message, not a generation prompt" | |
| ) | |
| if role == "user": | |
| last_user_index = len(conversation) | |
| conversation.append({"role": role, "content": content}) | |
| if last_user_index is None: | |
| raise ValueError("no user message remains after preparing the conversation") | |
| reply_count = len(conversation) - (last_user_index + 1) | |
| if reply_count > 1: | |
| raise ValueError("at most one assistant reply may follow the final user message") | |
| return conversation, last_user_index | |
| def _check_prefix(prefix: tuple[int, ...], tokens: tuple[int, ...], target: str) -> None: | |
| """Require a stable prefix and at least one token for the target message.""" | |
| if tokens[: len(prefix)] != prefix: | |
| raise ValueError(f"renderer changed the token prefix before the {target}") | |
| if len(tokens) <= len(prefix): | |
| raise ValueError(f"the {target} message rendered no tokens") | |
| def iris_content_guard_positions( | |
| messages: Sequence[Mapping[str, object]], | |
| tokenizer: transformers.PreTrainedTokenizerBase, | |
| *, | |
| max_tokens: int, | |
| ) -> IrisContentGuardInputs: | |
| """Render a conversation for the Iris Content Guard's model. | |
| Earlier turns provide context for the final user request and its optional | |
| single assistant reply. Boundaries include closing delimiters, even for | |
| empty messages and Harmony replies with an empty analysis block. | |
| Args: | |
| messages: User/assistant messages with string content. Thinking-role | |
| messages and extra fields are removed before rendering. | |
| tokenizer: Tokenizer loaded from the classifier checkpoint, including | |
| its chat template. Rendering a prefix must preserve its token IDs | |
| when subsequent messages are appended. | |
| max_tokens: Maximum permitted number of rendered tokens. | |
| Returns: | |
| All tokens and the two boundary positions; `response_position` is None | |
| when the conversation ends with a user message. | |
| Raises: | |
| ValueError: Unsupported roles, invalid content or targets, overflow, | |
| empty token spans, or a renderer that changes preceding tokens. | |
| """ | |
| conversation, request_index = _prepare_messages_and_find_last_user(messages) | |
| has_response = request_index < len(conversation) - 1 | |
| conversations = [conversation] | |
| if has_response: | |
| conversations.append(conversation[: request_index + 1]) | |
| if request_index: | |
| conversations.append(conversation[:request_index]) | |
| tokenized = cast( | |
| list[list[int]], | |
| # Transformers leaves optional template arguments untyped. | |
| tokenizer.apply_chat_template( # pyright: ignore[reportUnknownMemberType] | |
| conversations, | |
| tokenize=True, | |
| return_dict=False, | |
| add_generation_prompt=False, | |
| continue_final_message=False, | |
| padding=False, | |
| truncation=False, | |
| ), | |
| ) | |
| token_ids = tuple(tokenized[0]) | |
| if len(token_ids) > max_tokens: | |
| raise ValueError( | |
| f"conversation has {len(token_ids)} tokens, exceeding max_tokens={max_tokens}" | |
| ) | |
| request_tokens = tuple(tokenized[1]) if has_response else token_ids | |
| context_tokens = tuple(tokenized[-1]) if request_index else () | |
| _check_prefix(context_tokens, request_tokens, "request") | |
| if has_response: | |
| _check_prefix(request_tokens, token_ids, "response") | |
| return IrisContentGuardInputs( | |
| token_ids=token_ids, | |
| request_position=len(request_tokens) - 1, | |
| response_position=len(token_ids) - 1 if has_response else None, | |
| ) | |