Spaces:
Running on Zero
Running on Zero
File size: 1,583 Bytes
baa274b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | """Run Iris Content Guard on ZeroGPU and return probabilities for the turn plots."""
import spaces
import torch
import transformers
CATEGORIES = (
'cyber',
'fraud',
'privacy',
'bio_weapons',
'chem_weapons',
'rn_weapons',
'child_safety_non_csae',
'violence',
'self_harm',
'grooming',
'sex_crimes',
'sex_content',
'illegal_activities',
'hate',
)
type TurnScores = dict[str, dict[str, float] | None]
classifier = transformers.pipeline(
'token-classification',
model='reflection/Iris-Content-Guard',
trust_remote_code=True,
# ZeroGPU stages tensors placed on CUDA at startup.
device='cuda',
)
def _category_scores(side: dict[str, dict[str, float]]) -> dict[str, float]:
probabilities = side['category_harm_probabilities']
scores = {category: probabilities[category] for category in CATEGORIES}
if not all(
type(value) in (float, int) and 0 <= value <= 1 for value in scores.values()
):
raise ValueError('Invalid Iris Content Guard probabilities')
return scores
@spaces.GPU(size='xlarge')
def score_conversation(messages: list[dict[str, str]]) -> TurnScores:
"""Score the latest user request and its visible reply in conversation context."""
with torch.inference_mode():
result = classifier(messages)
reply = result['response']
if (reply is not None) != (messages[-1]['role'] == 'assistant'):
raise ValueError('Iris Content Guard reply does not match the conversation')
return {
'request': _category_scores(result['request']),
'response': _category_scores(reply) if reply is not None else None,
}
|