"""Self-contained Iris Content Guard pipeline bundled with converted checkpoints.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Any, cast import torch from transformers.pipelines import base from transformers.utils import chat_template_utils, generic # Explicit relative imports let Transformers bundle this dependency on the Hub. from .positions import iris_content_guard_positions class IrisContentGuardPipeline(base.Pipeline): """Score the final user request and optional assistant reply. Load with `pipeline("token-classification", model=checkpoint, trust_remote_code=True)`. Earlier messages provide context. Results contain independent sigmoid probabilities in `request.category_harm_probabilities` and `response.category_harm_probabilities`; `response` is None without an assistant reply. """ def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) # PretrainedConfig normalizes label IDs to integers when loading JSON. id2label = cast(dict[int, str], self.model.config.id2label) labels = [id2label[index] for index in range(self.model.config.num_labels or 0)] self.categories = [label.removeprefix("request/") for label in labels[:14]] expected: list[str] = [] for side in ("request", "response"): expected.extend(f"{side}/{category}" for category in self.categories) if ( self.model.config.num_labels != 28 or len(set(self.categories)) != 14 or labels != expected ): raise ValueError( "Iris Content Guard requires 14 request/ labels followed by " "matching response/ labels" ) self.model.eval() def _from_oai_to_icg_format( self, oai_messages: Sequence[Mapping[str, object]], ) -> list[dict[str, str]]: icg_messages: list[dict[str, str]] = [] for message in oai_messages: role = message.get("role") if not isinstance(role, str) or role not in ("user", "assistant"): continue tool_calls = message.get("tool_calls") if role == "assistant" and isinstance(tool_calls, list) and tool_calls: continue content = message.get("content") if isinstance(content, list): content = cast(list[object], content) text_parts: list[str] = [] for part in content: if isinstance(part, Mapping): part = cast(Mapping[str, object], part) if part.get("type") == "text" and isinstance(text := part.get("text"), str): text_parts.append(text) content = "".join(text_parts) if text_parts else None if not isinstance(content, str): continue icg_messages.append({"role": role, "content": content}) if not icg_messages: raise ValueError("no user message remains after preparing the conversation") return icg_messages def __call__(self, inputs: Any, *args: Any, **kwargs: Any) -> Any: """Prepare Chat Completions messages before Transformers validates the chat.""" if isinstance(inputs, (list, tuple)): if not inputs or isinstance(inputs[0], dict): inputs = self._from_oai_to_icg_format(inputs) elif isinstance(inputs[0], (list, tuple)): inputs = [self._from_oai_to_icg_format(chat) for chat in inputs] return super().__call__(inputs, *args, **kwargs) def _sanitize_parameters( self, **pipeline_parameters: object ) -> tuple[dict[str, object], dict[str, object], dict[str, object]]: if pipeline_parameters: raise TypeError( f"Unsupported Iris Content Guard options: {sorted(pipeline_parameters)}" ) return {}, {}, {} def preprocess( self, input_: object, **preprocess_parameters: object ) -> dict[str, base.GenericTensor]: """Render one conversation and retain its two boundary positions.""" del preprocess_parameters # No preprocessing options. if isinstance(input_, (list, tuple)): messages = self._from_oai_to_icg_format(input_) elif isinstance(input_, chat_template_utils.Chat): messages = list(input_.messages) else: raise ValueError("Iris Content Guard expects a list of role/content messages") if self.tokenizer is None: raise ValueError("Iris Content Guard requires its tokenizer and chat template") positions = iris_content_guard_positions( messages, self.tokenizer, max_tokens=self.model.config.max_position_embeddings, ) input_ids = torch.tensor([positions.token_ids], dtype=torch.long) return { "input_ids": input_ids, "attention_mask": torch.ones_like(input_ids), "readout_positions": torch.tensor( [ [ positions.request_position, positions.response_position if positions.response_position is not None else -1, ] ], dtype=torch.long, ), } def _forward( self, input_tensors: dict[str, base.GenericTensor], **forward_parameters: object ) -> generic.ModelOutput: del forward_parameters # No forward options. model_inputs = cast(dict[str, torch.Tensor], input_tensors) positions = model_inputs.pop("readout_positions") has_response = positions[:, 1] >= 0 attention_mask = model_inputs["attention_mask"] model_inputs["position_ids"] = (attention_mask.cumsum(-1) - 1).clamp_min(0) positions = positions + attention_mask.argmax(-1)[:, None] logits = self.model(**model_inputs, use_cache=False).logits batch_indices = torch.arange(logits.shape[0], device=logits.device)[:, None] return generic.ModelOutput( logits=logits[batch_indices, positions.clamp_min(0)], has_response=has_response ) def postprocess( self, model_outputs: generic.ModelOutput, **postprocess_parameters: object ) -> dict[str, object]: """Return independent probabilities from the selected `(2, 28)` logits.""" del postprocess_parameters # No postprocessing options. logits = model_outputs["logits"][0] request_probabilities = logits[0, :14].float().sigmoid().tolist() response = None if model_outputs["has_response"][0].item(): response_probabilities = logits[1, 14:].float().sigmoid().tolist() response = { "category_harm_probabilities": dict( zip(self.categories, response_probabilities, strict=True) ) } return { "request": { "category_harm_probabilities": dict( zip(self.categories, request_probabilities, strict=True) ) }, "response": response, }