civic-backup / src /inference /runtime.py
khiemdztv's picture
Backup source code and docs
cf29045 verified
Raw History Blame Contribute Delete
3.14 kB
"""Nạp model một lần (singleton), chuyển backend torch/ONNX, đo độ trễ từng khối."""
from __future__ import annotations
import time
from pathlib import Path
from typing import Any, Dict, Optional
import numpy as np
from ..common.logging_utils import get_logger
LOG = get_logger("runtime")
class Stopwatch:
def __init__(self) -> None:
self.marks: Dict[str, float] = {}
self._t = time.perf_counter()
def lap(self, name: str) -> None:
now = time.perf_counter()
self.marks[name] = round((now - self._t) * 1000, 2)
self._t = now
def total_ms(self) -> float:
return round(sum(self.marks.values()), 2)
class NLURuntime:
"""Backend torch (mặc định) hoặc onnxruntime (CPU, phục vụ mốc < 100 ms)."""
def __init__(self, model_dir: str, tokenizer, device: str = "cpu",
backend: str = "torch", onnx_path: Optional[str] = None):
self.tok = tokenizer
self.device = device
self.backend = backend
self.model_dir = model_dir
self._ort = None
self._torch_model = None
if backend == "onnx":
import onnxruntime as ort
path = onnx_path or str(Path(model_dir) / "model_int8.onnx")
if not Path(path).exists():
path = str(Path(model_dir) / "model.onnx")
so = ort.SessionOptions()
so.intra_op_num_threads = 4
so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
self._ort = ort.InferenceSession(path, so, providers=["CPUExecutionProvider"])
self.output_names = [o.name for o in self._ort.get_outputs()]
LOG.info("ONNX runtime sẵn sàng: %s", path)
from ..common.registry import Registry
self.reg = Registry.load(model_dir)
else:
import torch
from ..models.civic_nlu import CivicNLUModel
self._torch_model = CivicNLUModel.from_pretrained(model_dir, device)
self.reg = self._torch_model.reg
self.torch = torch
LOG.info("PyTorch runtime sẵn sàng trên %s", device)
def run(self, input_ids, attention_mask) -> Dict[str, np.ndarray]:
if self._ort is not None:
outs = self._ort.run(None, {"input_ids": np.asarray(input_ids, dtype=np.int64),
"attention_mask": np.asarray(attention_mask,
dtype=np.int64)})
return dict(zip(self.output_names, outs))
import torch
with torch.no_grad():
t_in = torch.tensor(input_ids, dtype=torch.long, device=self.device)
t_att = torch.tensor(attention_mask, dtype=torch.long, device=self.device)
out = self._torch_model(t_in, t_att)
return {k: v.float().cpu().numpy() for k, v in out.items()}
def warmup(self, n: int = 3) -> None:
ids = [[self.tok.cls_token_id] + [5] * 30 + [self.tok.sep_token_id]]
att = [[1] * len(ids[0])]
for _ in range(n):
self.run(ids, att)