Add the Mila self-harm output guardrail; only include it in Run all for mental-health policies
Browse files- app.py +31 -4
- utils/constants.py +26 -0
- utils/helpers.py +18 -0
- utils/model_interface.py +67 -0
app.py
CHANGED
|
@@ -200,6 +200,21 @@ def _run_one_model(model, test_input, current_policy, structured_rules, reasonin
|
|
| 200 |
return [model["name"], verdict, note]
|
| 201 |
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
def handle_run_all_models(test_input, current_policy, structured_rules, reasoning_effort,
|
| 204 |
max_tokens, temperature, top_p, system_prompt_val, response_format_val,
|
| 205 |
oauth_token: gr.OAuthToken | None = None):
|
|
@@ -221,10 +236,22 @@ def handle_run_all_models(test_input, current_policy, structured_rules, reasonin
|
|
| 221 |
if hf_token is None:
|
| 222 |
raise gr.Error("Please log in or set tokens to use Inference Providers. Check the sidebar.")
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
# Start every model at once; show them all as "running" immediately so the table
|
| 225 |
# isn't blank while the slow reasoning models work.
|
| 226 |
-
status = {m["name"]: "⏳ running…" for m in
|
| 227 |
-
notes = {m["name"]: "" for m in
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
order = [m["name"] for m in MODELS]
|
| 229 |
|
| 230 |
def table():
|
|
@@ -232,12 +259,12 @@ def handle_run_all_models(test_input, current_policy, structured_rules, reasonin
|
|
| 232 |
|
| 233 |
yield table(), gr.update(visible=True)
|
| 234 |
|
| 235 |
-
with ThreadPoolExecutor(max_workers=len(
|
| 236 |
futures = {
|
| 237 |
executor.submit(
|
| 238 |
_run_one_model, m, test_input, current_policy, structured_rules, reasoning_effort,
|
| 239 |
max_tokens, temperature, top_p, system_prompt_val, response_format_val, hf_token,
|
| 240 |
-
): m for m in
|
| 241 |
}
|
| 242 |
from concurrent.futures import as_completed
|
| 243 |
for fut in as_completed(futures):
|
|
|
|
| 200 |
return [model["name"], verdict, note]
|
| 201 |
|
| 202 |
|
| 203 |
+
def _is_mental_health_policy(policy_text, structured_rules) -> bool:
|
| 204 |
+
"""Is the policy under test a mental-health one?
|
| 205 |
+
|
| 206 |
+
Checked first against the preset each rule came from (an "MH-P1 · …" tag), which
|
| 207 |
+
is exact, then against the policy text for a hand-written policy that was never
|
| 208 |
+
loaded from a preset.
|
| 209 |
+
"""
|
| 210 |
+
for rule in (structured_rules or []):
|
| 211 |
+
source = (rule.get("source") or "").strip().casefold()
|
| 212 |
+
if source.startswith("mh-") or "mental health" in source:
|
| 213 |
+
return True
|
| 214 |
+
text = (policy_text or "").casefold()
|
| 215 |
+
return any(k in text for k in ("self-harm", "self harm", "suicide", "suicidal"))
|
| 216 |
+
|
| 217 |
+
|
| 218 |
def handle_run_all_models(test_input, current_policy, structured_rules, reasoning_effort,
|
| 219 |
max_tokens, temperature, top_p, system_prompt_val, response_format_val,
|
| 220 |
oauth_token: gr.OAuthToken | None = None):
|
|
|
|
| 236 |
if hf_token is None:
|
| 237 |
raise gr.Error("Please log in or set tokens to use Inference Providers. Check the sidebar.")
|
| 238 |
|
| 239 |
+
# Fixed-policy, single-harm models only earn a row when the policy is about their
|
| 240 |
+
# harm. The Mila guardrail answers "does this enable self-harm?" whatever you load,
|
| 241 |
+
# so next to a scams policy it would sit in the comparison answering a different
|
| 242 |
+
# question from every other row — which reads as the models disagreeing.
|
| 243 |
+
mental_health = _is_mental_health_policy(current_policy, structured_rules)
|
| 244 |
+
to_run = [m for m in MODELS if mental_health or not m.get("mental_health_only")]
|
| 245 |
+
skipped = [m for m in MODELS if m not in to_run]
|
| 246 |
+
|
| 247 |
# Start every model at once; show them all as "running" immediately so the table
|
| 248 |
# isn't blank while the slow reasoning models work.
|
| 249 |
+
status = {m["name"]: "⏳ running…" for m in to_run}
|
| 250 |
+
notes = {m["name"]: "" for m in to_run}
|
| 251 |
+
# Skipped models stay visible with a reason, rather than vanishing from the table.
|
| 252 |
+
for m in skipped:
|
| 253 |
+
status[m["name"]] = "➖ Not run"
|
| 254 |
+
notes[m["name"]] = "Only runs on a mental-health policy (fixed self-harm policy, cannot be steered)."
|
| 255 |
order = [m["name"] for m in MODELS]
|
| 256 |
|
| 257 |
def table():
|
|
|
|
| 259 |
|
| 260 |
yield table(), gr.update(visible=True)
|
| 261 |
|
| 262 |
+
with ThreadPoolExecutor(max_workers=len(to_run)) as executor:
|
| 263 |
futures = {
|
| 264 |
executor.submit(
|
| 265 |
_run_one_model, m, test_input, current_policy, structured_rules, reasoning_effort,
|
| 266 |
max_tokens, temperature, top_p, system_prompt_val, response_format_val, hf_token,
|
| 267 |
+
): m for m in to_run
|
| 268 |
}
|
| 269 |
from concurrent.futures import as_completed
|
| 270 |
for fut in as_completed(futures):
|
utils/constants.py
CHANGED
|
@@ -52,6 +52,20 @@ MODELS = [
|
|
| 52 |
"supports_reasoning_level": False,
|
| 53 |
"is_classifier": True,
|
| 54 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
]
|
| 56 |
|
| 57 |
# --- Dedicated-endpoint classifier config ---------------------------------
|
|
@@ -106,6 +120,18 @@ COPE_B_MODEL_ID = "zentropi-ai/cope-b-s1"
|
|
| 106 |
COPE_B_SERVED_MODEL_NAME = "zentropi-ai/cope-b-s1"
|
| 107 |
COPE_B_THRESHOLD = 0.5
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
# Reasoning effort levels for GPT-OSS
|
| 110 |
REASONING_EFFORTS = ["Low", "Medium", "High"]
|
| 111 |
|
|
|
|
| 52 |
"supports_reasoning_level": False,
|
| 53 |
"is_classifier": True,
|
| 54 |
},
|
| 55 |
+
# Fixed-policy model: it scores against its own built-in self-harm policy and
|
| 56 |
+
# ignores the room's. mental_health_only keeps it out of "Run all models" unless
|
| 57 |
+
# a mental-health policy is loaded, where its verdict is the only one that means
|
| 58 |
+
# anything — against a scams or hate-speech policy it would answer a different
|
| 59 |
+
# question from every other row and read as a disagreement.
|
| 60 |
+
{
|
| 61 |
+
"name": "Mila Suicide Prevention Guardrail",
|
| 62 |
+
"id": "mila-ai4h/Mila-Suicide-Prevention-Output-Guardrail",
|
| 63 |
+
"is_thinking": False,
|
| 64 |
+
"supports_reasoning_level": False,
|
| 65 |
+
"is_classifier": True,
|
| 66 |
+
"ignores_policy": True,
|
| 67 |
+
"mental_health_only": True,
|
| 68 |
+
},
|
| 69 |
]
|
| 70 |
|
| 71 |
# --- Dedicated-endpoint classifier config ---------------------------------
|
|
|
|
| 120 |
COPE_B_SERVED_MODEL_NAME = "zentropi-ai/cope-b-s1"
|
| 121 |
COPE_B_THRESHOLD = 0.5
|
| 122 |
|
| 123 |
+
# Mila Suicide Prevention Output Guardrail: a small mmBERT classifier with a single
|
| 124 |
+
# logit, sigmoid(logit) = p(unsafe), default operating point 0.5 from the model card.
|
| 125 |
+
# Unlike every other model here it takes NO policy — it scores against its own fixed
|
| 126 |
+
# policy (the MLCommons AILuminate "Suicide and Self-Harm" category), so the room's
|
| 127 |
+
# policy text is not sent and cannot change its answer. It is also an *output*
|
| 128 |
+
# guardrail: trained on assistant replies, not user posts.
|
| 129 |
+
# Served via roosttools/mila-selfharm-endpoint, a thin custom-handler repo — the model
|
| 130 |
+
# cannot be deployed directly (its tokenizer_config names a tokenizer class the
|
| 131 |
+
# inference image does not have). See that repo's handler.py.
|
| 132 |
+
MILA_MODEL_ID = "mila-ai4h/Mila-Suicide-Prevention-Output-Guardrail"
|
| 133 |
+
MILA_THRESHOLD = 0.5
|
| 134 |
+
|
| 135 |
# Reasoning effort levels for GPT-OSS
|
| 136 |
REASONING_EFFORTS = ["Low", "Medium", "High"]
|
| 137 |
|
utils/helpers.py
CHANGED
|
@@ -135,6 +135,24 @@ def get_cope_b_config() -> tuple[str | None, str | None, str]:
|
|
| 135 |
return endpoint_url, token, served_name
|
| 136 |
|
| 137 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
def get_policylm_config() -> tuple[str | None, str | None]:
|
| 139 |
"""
|
| 140 |
Get PolicyLM dedicated-endpoint config from Space secrets / .env.
|
|
|
|
| 135 |
return endpoint_url, token, served_name
|
| 136 |
|
| 137 |
|
| 138 |
+
def get_mila_config() -> tuple[str | None, str | None]:
|
| 139 |
+
"""
|
| 140 |
+
Get the Mila self-harm guardrail endpoint config from Space secrets / .env.
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
Tuple of (endpoint_url, token); either is None if not configured.
|
| 144 |
+
"""
|
| 145 |
+
endpoint_url = os.getenv("MILA_ENDPOINT_URL") or _load_token_from_env("MILA_ENDPOINT_URL")
|
| 146 |
+
# Falls back to the shared org inference token rather than needing its own secret:
|
| 147 |
+
# the endpoint lives in the same org, so there is no second credential to manage.
|
| 148 |
+
token = (
|
| 149 |
+
os.getenv("MILA_INFERENCE_TOKEN")
|
| 150 |
+
or _load_token_from_env("MILA_INFERENCE_TOKEN")
|
| 151 |
+
or get_org_token()
|
| 152 |
+
)
|
| 153 |
+
return endpoint_url, token
|
| 154 |
+
|
| 155 |
+
|
| 156 |
def get_policylm_config() -> tuple[str | None, str | None]:
|
| 157 |
"""
|
| 158 |
Get PolicyLM dedicated-endpoint config from Space secrets / .env.
|
utils/model_interface.py
CHANGED
|
@@ -26,6 +26,8 @@ from utils.constants import (
|
|
| 26 |
MODELS,
|
| 27 |
COPE_B_MODEL_ID,
|
| 28 |
COPE_B_THRESHOLD,
|
|
|
|
|
|
|
| 29 |
SHIELDSTRAL_MODEL_ID,
|
| 30 |
SHIELDSTRAL_SYSTEM_PROMPT,
|
| 31 |
SHIELDSTRAL_USER_TEMPLATE,
|
|
@@ -351,6 +353,68 @@ def run_cope_b(test_input: str, policy: str) -> dict:
|
|
| 351 |
return {"content": f"```json\n{result_content}\n```", "reasoning": reasoning}
|
| 352 |
|
| 353 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
def run_test(
|
| 355 |
model_id: str,
|
| 356 |
test_input: str,
|
|
@@ -406,6 +470,9 @@ def run_test(
|
|
| 406 |
return run_policylm(test_input, policy, structured_rules)
|
| 407 |
if model_id == COPE_B_MODEL_ID:
|
| 408 |
return run_cope_b(test_input, policy)
|
|
|
|
|
|
|
|
|
|
| 409 |
|
| 410 |
messages = make_messages(test_input, policy, model_id, reasoning_effort, system_prompt, response_format)
|
| 411 |
|
|
|
|
| 26 |
MODELS,
|
| 27 |
COPE_B_MODEL_ID,
|
| 28 |
COPE_B_THRESHOLD,
|
| 29 |
+
MILA_MODEL_ID,
|
| 30 |
+
MILA_THRESHOLD,
|
| 31 |
SHIELDSTRAL_MODEL_ID,
|
| 32 |
SHIELDSTRAL_SYSTEM_PROMPT,
|
| 33 |
SHIELDSTRAL_USER_TEMPLATE,
|
|
|
|
| 353 |
return {"content": f"```json\n{result_content}\n```", "reasoning": reasoning}
|
| 354 |
|
| 355 |
|
| 356 |
+
def run_mila(test_input: str) -> dict:
|
| 357 |
+
"""
|
| 358 |
+
Run the Mila Suicide Prevention Output Guardrail against its dedicated endpoint.
|
| 359 |
+
|
| 360 |
+
Takes no policy, by design: this model scores against its own fixed policy (the
|
| 361 |
+
MLCommons AILuminate "Suicide and Self-Harm" category) and has no way to be
|
| 362 |
+
steered by the room's. It is also commission-based — it flags text that *enables
|
| 363 |
+
or encourages* self-harm, not text expressing distress — so on a policy that asks
|
| 364 |
+
for distress to be routed to support it will legitimately disagree with the other
|
| 365 |
+
models rather than be wrong.
|
| 366 |
+
"""
|
| 367 |
+
import gradio as gr
|
| 368 |
+
import requests
|
| 369 |
+
|
| 370 |
+
from utils.helpers import get_mila_config
|
| 371 |
+
|
| 372 |
+
endpoint_url, token = get_mila_config()
|
| 373 |
+
if not endpoint_url or not token:
|
| 374 |
+
raise gr.Error(
|
| 375 |
+
"Mila endpoint not configured. Set the MILA_ENDPOINT_URL and "
|
| 376 |
+
"MILA_INFERENCE_TOKEN Space secrets (see README)."
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
try:
|
| 380 |
+
resp = requests.post(
|
| 381 |
+
endpoint_url.rstrip("/"),
|
| 382 |
+
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
| 383 |
+
json={"inputs": test_input, "parameters": {"threshold": MILA_THRESHOLD}},
|
| 384 |
+
timeout=120,
|
| 385 |
+
)
|
| 386 |
+
resp.raise_for_status()
|
| 387 |
+
payload = resp.json()
|
| 388 |
+
except Exception as e:
|
| 389 |
+
raise gr.Error(f"Mila inference failed: {e}. Check the endpoint is running and the token is valid.")
|
| 390 |
+
|
| 391 |
+
if isinstance(payload, list):
|
| 392 |
+
payload = payload[0] if payload else {}
|
| 393 |
+
score = payload.get("p_unsafe", payload.get("score"))
|
| 394 |
+
if not isinstance(score, (int, float)):
|
| 395 |
+
raise gr.Error(
|
| 396 |
+
f"Mila endpoint returned an unexpected response (expected a p_unsafe score): {payload}"
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
label = 1 if score >= MILA_THRESHOLD else 0
|
| 400 |
+
result_content = json.dumps({
|
| 401 |
+
"label": label,
|
| 402 |
+
"categories": [{
|
| 403 |
+
"category": "Enables or encourages suicide or self-harm",
|
| 404 |
+
"reasoning": f"p(unsafe) {score:.4f} (threshold {MILA_THRESHOLD})",
|
| 405 |
+
}],
|
| 406 |
+
})
|
| 407 |
+
reasoning = (
|
| 408 |
+
f"Mila p(unsafe): {score:.4f} (threshold {MILA_THRESHOLD}).\n"
|
| 409 |
+
"Scored against the model's own fixed self-harm policy (MLCommons AILuminate), "
|
| 410 |
+
"NOT the policy loaded in this app — that text is not sent to this model.\n"
|
| 411 |
+
"It flags only content that enables, encourages or endorses self-harm; expressions "
|
| 412 |
+
"of distress and help-seeking are 'safe' by its policy even when your policy would "
|
| 413 |
+
"route them to support."
|
| 414 |
+
)
|
| 415 |
+
return {"content": f"```json\n{result_content}\n```", "reasoning": reasoning}
|
| 416 |
+
|
| 417 |
+
|
| 418 |
def run_test(
|
| 419 |
model_id: str,
|
| 420 |
test_input: str,
|
|
|
|
| 470 |
return run_policylm(test_input, policy, structured_rules)
|
| 471 |
if model_id == COPE_B_MODEL_ID:
|
| 472 |
return run_cope_b(test_input, policy)
|
| 473 |
+
if model_id == MILA_MODEL_ID:
|
| 474 |
+
# No policy argument: this model cannot be steered by one.
|
| 475 |
+
return run_mila(test_input)
|
| 476 |
|
| 477 |
messages = make_messages(test_input, policy, model_id, reasoning_effort, system_prompt, response_format)
|
| 478 |
|