modul-x / app /ml /local_scorer.py
Z User
v3.1.0: Part B architecture migration — eliminate Hugging Face inference credit dependency
6c516b6
Raw History Blame Contribute Delete
5.5 kB
"""Local risk scorer — in-process transformers inference, zero credits.
Part B architecture migration (Change 2). Replaces the Hugging Face Inference
API path: model weights are downloaded ONCE from the public HF Hub (a free,
unmetered operation) and then every inference runs in-process via a
transformers pipeline. No InferenceClient, no api-inference / router endpoint,
no token, no credit consumption — the metered dependency of the old design is
gone by construction.
Design notes (spec §5.3 / Part B):
- The model identifier is CONFIGURED (settings.ai_scorer_model), never
hard-coded, so it can be swapped without redeploying the orchestrator.
- Default is a DistilBERT-class NLI checkpoint (§5.3: "A DistilBERT-class
model is sufficient; larger models do not improve accuracy on this feature
set enough to justify the cost"). On a 2-vCPU Space host bart-large-mnli
costs ~4x the latency for the same feature string.
- device=-1 (CPU) per the doc; inference is offloaded to a worker thread by
the caller (risk_scorer) so the event loop is never blocked.
- First load pulls the checkpoint from the Hub (~260MB) unless it was baked
into the image at build time (Dockerfile pre-seeds HF_HOME). Every
subsequent load is disk-cache-only: no network, no token.
- Fail-open: `load()` returns False on ANY failure and the caller degrades to
the rule-based heuristic (spec §2.3 — a degraded engine must never starve
the pipeline).
"""
from __future__ import annotations
import logging
import threading
from typing import Optional
logger = logging.getLogger(__name__)
DEFAULT_LOCAL_MODEL = "typeform/distilbert-base-uncased-mnli"
RISK_LABELS = ["low_risk", "medium_risk", "high_risk"]
class LocalRiskScorer:
"""Zero-shot classification pipeline over the PII-free feature string.
The candidate labels ARE the risk taxonomy, so any served NLI checkpoint
can score the feature string (same contract the old remote zero-shot mode
used — the response mapping logic is unchanged).
"""
def __init__(
self,
model_name: Optional[str] = None,
device: int = -1,
zero_shot: bool = True,
):
self.model_name = model_name or DEFAULT_LOCAL_MODEL
self.device = device
self.zero_shot = zero_shot
self._pipeline = None
self._loaded = False
self.last_error: Optional[str] = None
self._lock = threading.Lock()
@property
def loaded(self) -> bool:
return self._loaded
def load(self) -> bool:
"""Load the pipeline. Returns False on ANY failure (fail-open)."""
with self._lock:
if self._loaded:
return True
try:
import transformers # lazy: the API must boot without torch
if self.zero_shot:
self._pipeline = transformers.pipeline(
"zero-shot-classification",
model=self.model_name,
device=self.device,
)
else:
self._pipeline = transformers.pipeline(
"text-classification",
model=self.model_name,
device=self.device,
top_k=3,
)
self._loaded = True
logger.info("Local scorer loaded: %s", self.model_name)
return True
except Exception as exc:
self._pipeline = None
self._loaded = False
self.last_error = f"{type(exc).__name__}: {exc}"
logger.warning("Local scorer failed to load: %s", self.last_error)
return False
def score(self, feature_text: str, labels: Optional[list[str]] = None) -> dict:
"""Classify one feature string.
Returns {"label", "score", "all_scores"} where `score` is the
confidence of the winning label. Raises only if the pipeline was never
loaded — the caller (AIRiskScorer._infer) checks `load()` first.
"""
if not self._loaded or self._pipeline is None:
raise RuntimeError("local scorer not loaded")
result = self._pipeline(
feature_text, candidate_labels=labels or RISK_LABELS
)
# zero-shot shape: {"labels": [...], "scores": [...]}
if isinstance(result, dict) and result.get("labels"):
top_label = result["labels"][0]
top_score = float(result["scores"][0] or 0.0)
all_scores = {
str(l): float(s or 0.0)
for l, s in zip(result["labels"], result["scores"])
}
else:
# text-classification shape: [{"label", "score"}, ...] or [[...]]
rows = result if isinstance(result, list) else [result]
flat = rows[0] if rows and isinstance(rows[0], list) else rows
pairs = [
(str(e.get("label", "")), float(e.get("score", 0) or 0))
for e in flat or []
if isinstance(e, dict)
]
if not pairs:
raise ValueError("empty local scorer output")
pairs.sort(key=lambda p: p[1], reverse=True)
top_label, top_score = pairs[0]
all_scores = dict(pairs)
return {
"label": top_label,
"score": round(top_score, 4),
"all_scores": all_scores,
}