File size: 3,144 Bytes
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""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)