File size: 5,760 Bytes
a4709f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# Copyright 2026 Cobuild Tech Private Limited
# SPDX-License-Identifier: Apache-2.0
"""InDIM intent classifier: a voice-assistant style request in 7 Indian languages in, one of 60 intents out.

    from cbx_intent import IntentClassifier
    clf = IntentClassifier(".")                          # folder with the model files; CPU or GPU
    clf.classify("कल सुबह सात बजे का अलार्म लगा दो")

`classify` takes one text (returns one result) or a list (returns a list). A result:

    {"label": "alarm_set", "scores": {"alarm_set": 0.98, "alarm_query": 0.01, ...}, "truncated": False}

"label" is the label with the highest score, unless cbx_config.json has a "decision" rule: then the first label in
the rule whose score reaches its threshold wins, otherwise the rule's fallback label (thresholds tuned on validation;
see the model card). When cbx_config.json lists "operating_points" (named rules), pick one with
`IntentClassifier(".", operating_point="<name>")` or `clf.use_operating_point("<name>")`; the default is "decision". "scores" are softmax probabilities that sum to 1. The model reads at most 96 tokens;
longer text is cut ("truncated": True).
"""
import json
from pathlib import Path

import torch
import torch.nn as nn
from safetensors.torch import load_file
from transformers import AutoConfig, AutoModel, AutoTokenizer


class _Net(nn.Module):
    def __init__(self, path, cfg):
        super().__init__()
        self.backbone = AutoModel.from_config(AutoConfig.from_pretrained(path), attn_implementation="sdpa")
        h = self.backbone.config.hidden_size
        if cfg.get("embedding_rank"):           # factorised word table (smaller sizes)
            self.backbone.embeddings.tok_embeddings = nn.Sequential(
                nn.Embedding(self.backbone.config.vocab_size, cfg["embedding_rank"]),
                nn.Linear(cfg["embedding_rank"], h, bias=False))
        self.head = nn.Linear(h, len(cfg["labels"]))

    def forward(self, input_ids, attention_mask):
        hs = self.backbone(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state.float()
        m = attention_mask.unsqueeze(-1).float()
        return self.head((hs[:, 0] + (hs * m).sum(1) / m.sum(1).clamp(min=1)) / 2)


class IntentClassifier:
    def __init__(self, path=".", device=None, operating_point=None):
        path = Path(path)
        self.cfg = json.loads((path / "cbx_config.json").read_text())
        if operating_point is not None:
            self.use_operating_point(operating_point)
        self.labels = self.cfg["labels"]
        self.max_len = self.cfg["max_len"]
        self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
        self.tok = AutoTokenizer.from_pretrained(path)
        self.net = _Net(path, self.cfg)
        self.net.load_state_dict(load_file(str(path / "model.safetensors")))
        self.net.to(self.device).eval()

    @torch.inference_mode()
    def logits(self, texts, max_tokens=16384):
        """Raw logits [n][labels] in input order, and a truncated flag per text."""
        texts = list(texts)
        full = [len(x) for x in self.tok(texts, verbose=False)["input_ids"]]
        enc = self.tok(texts, truncation=True, max_length=self.max_len, verbose=False)["input_ids"]
        out = [None] * len(enc)
        order = sorted(range(len(enc)), key=lambda i: len(enc[i]))
        i = 0
        while i < len(order):
            j, n = i, 0
            while j < len(order) and (j - i + 1) * max(n, len(enc[order[j]])) <= max_tokens:
                n = max(n, len(enc[order[j]]))
                j += 1
            j = max(j, i + 1)
            idx = order[i:j]
            n = max(len(enc[k]) for k in idx)
            ids = torch.full((len(idx), n), self.tok.pad_token_id, dtype=torch.long)
            mask = torch.zeros((len(idx), n), dtype=torch.long)
            for r, k in enumerate(idx):
                ids[r, :len(enc[k])] = torch.tensor(enc[k])
                mask[r, :len(enc[k])] = 1
            lg = self.net(ids.to(self.device), mask.to(self.device)).float().cpu().tolist()
            for r, k in enumerate(idx):
                out[k] = lg[r]
            i = j
        return out, [f > self.max_len for f in full]

    def use_operating_point(self, name):
        """Switch the decision rule to a named operating point from cbx_config.json (see the model card)."""
        pts = self.cfg.get("operating_points") or {}
        if name not in pts:
            raise ValueError(f"unknown operating point {name!r}; available: {sorted(pts)}")
        self.cfg["decision"] = {**pts[name], "operating_point": name}

    def decide(self, probs):
        """Label indices from probability rows: the decision rule if the config has one, else the argmax."""
        rule = (self.cfg.get("decision") or {}).get("rule")
        out = []
        for p in probs:
            k = max(range(len(p)), key=p.__getitem__)
            if rule:
                k = self.labels.index(self.cfg["decision"]["fallback"])
                for lab, t in rule:
                    if p[self.labels.index(lab)] >= t:
                        k = self.labels.index(lab)
                        break
            out.append(k)
        return out

    def classify(self, texts):
        single = isinstance(texts, str)
        texts = [texts] if single else list(texts)
        lg, tr = self.logits(texts)
        out = []
        probs = [torch.softmax(torch.tensor(row), -1).tolist() for row in lg]
        for p, k, t in zip(probs, self.decide(probs), tr):
            out.append({"label": self.labels[k], "scores": {l: round(v, 4) for l, v in zip(self.labels, p)},
                        "truncated": t})
        return out[0] if single else out