import json from pathlib import Path from threading import Lock import numpy as np from . import MODEL_VERSION from .encoding import CandidateEncoder, candidates from .schemas import NoulQuestion, ChoiceQuestion, NoulAnswer, ChoiceAnswer, ScoreAnswer, DecisionResponse, Usage from .settings import TEMPLATE_VERSION, ENCODER_ID, ENCODER_REVISION class ModelNotReady(RuntimeError): pass HEAD_TYPES = ('noul', 'choice', 'score') def assemble_answer(question, probabilities): p = np.asarray(probabilities, dtype=float) ids, descriptions = candidates(question) if p.shape != (len(ids),) or not np.isfinite(p).all() or (p < 0).any() or (p > 1).any() or not np.isclose(p.sum(), 1, atol=1e-6): raise ValueError("Некоректний розподіл імовірностей.") if isinstance(question, NoulQuestion): return NoulAnswer(noul=float(p[1])) values = {key: float(value) for key, value in zip(ids, p, strict=True)} if isinstance(question, ChoiceQuestion): return ChoiceAnswer(choice=ids[int(p.argmax())], probabilities=values, confidence=float(p.max())) return ScoreAnswer(score=float(np.dot(np.arange(len(p)), p)), confidence=float(p.max()), probabilities=values, legend=dict(zip(ids, descriptions, strict=True))) class PredictionService: def __init__(self, encoder, weight, temperatures, model_version=MODEL_VERSION): self.encoder = encoder self.weight = np.asarray(weight, dtype=np.float32) if self.weight.shape not in {(encoder.hidden_size,), (3, encoder.hidden_size)} or not np.isfinite(self.weight).all(): raise ModelNotReady("Несумісна логістична голова.") if set(temperatures) != {"noul", "choice", "score"} or any(not np.isfinite(t) or t <= 0 for t in temperatures.values()): raise ModelNotReady("Некоректні параметри калібрування.") self.temperatures = temperatures self.model_version = model_version self.lock = Lock() @classmethod def load(cls, path, device="cpu"): from safetensors.numpy import load_file from .artifacts import verify_bundle path = Path(path) manifest = verify_bundle(path) if manifest.get("stage") != "evaluated": raise ModelNotReady("Спочатку потрібно завершити калібрування та оцінювання моделі.") if manifest["template_version"] != TEMPLATE_VERSION or manifest["model_version"] not in {'decision-1.0.0',MODEL_VERSION}: raise ModelNotReady("Версія артефактів не відповідає сервісу.") if manifest["encoder_id"] != ENCODER_ID or manifest["encoder_revision"] != ENCODER_REVISION: raise ModelNotReady("Артефакти використовують інший encoder або ревізію.") calibration = json.loads((path / "calibration.json").read_text(encoding="utf-8")) metrics = json.loads((path / "metrics.json").read_text(encoding="utf-8")) if metrics.get("stage") != "evaluated" or calibration.get("status") != "fitted" or calibration.get("fitted_on") != "calibration": raise ModelNotReady("Не підтверджено завершене калібрування й оцінювання.") encoder = CandidateEncoder(manifest["encoder_id"], manifest["encoder_revision"], device=device) if manifest["hidden_size"] != encoder.hidden_size: raise ModelNotReady("Розмір encoder не відповідає manifest.") if manifest.get('encoder_delta'): from .adaptation import apply_encoder_delta apply_encoder_delta(encoder,path/'encoder_delta.safetensors',manifest['encoder_delta']) weight = load_file(str(path / "head.safetensors"))["weight"] layout = manifest.get('head_layout', 'shared') if layout == 'per-type': if manifest.get('head_types') != list(HEAD_TYPES) or weight.shape != (3, encoder.hidden_size): raise ModelNotReady('Несумісна структура голів за типами.') elif layout != 'shared' or weight.shape != (encoder.hidden_size,): raise ModelNotReady('Несумісна структура логістичної голови.') return cls(encoder, weight, calibration["temperatures"], manifest["model_version"]) def predict(self, request): if request.model not in {'decision-latest',self.model_version}: raise ModelNotReady('Запитана зафіксована версія моделі зараз не завантажена.') answers, total = {}, 0 with self.lock: for key, question in request.questions.items(): encoded = self.encoder.encode(request.state, question) weight = self.weight if self.weight.ndim == 1 else self.weight[HEAD_TYPES.index(question.type)] logits = encoded.features @ weight / self.temperatures[question.type] logits = logits - logits.max() p = np.exp(logits.astype(np.float64)) p /= p.sum() answers[key] = assemble_answer(question, p) total += encoded.input_tokens return DecisionResponse(model=self.model_version, answers=answers, usage=Usage(input_tokens=total))