Download statickd_inference.py from obikastanya/statickd-iptc-compact: direct link, hf CLI and curl.
- Browser
- Download file 3.69 kB
-
https://huggingface.co/obikastanya/statickd-iptc-compact/resolve/main/statickd_inference.py
- Command line
-
hf download hf://obikastanya/statickd-iptc-compact/statickd_inference.py
-
curl -L -o statickd_inference.py https://huggingface.co/obikastanya/statickd-iptc-compact/resolve/main/statickd_inference.py
3.69 kB
| """Standalone inference for StaticKD IPTC news-topic classifiers. | |
| Requirements: numpy, tokenizers, safetensors. | |
| The model is a table with 17 topic logits per token. A text is classified by | |
| tokenizing it, averaging the table rows of its tokens, adding a bias vector, | |
| and applying softmax. | |
| Usage from Python: | |
| from statickd_inference import StaticKDClassifier | |
| model = StaticKDClassifier("path/to/model/folder") | |
| model.predict(["Title and body of a news article ..."]) | |
| Usage from the command line: | |
| python statickd_inference.py "Title and body of a news article ..." | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| from safetensors.numpy import load_file | |
| from tokenizers import Tokenizer | |
| def softmax(logits: np.ndarray) -> np.ndarray: | |
| z = np.asarray(logits, dtype=np.float64) | |
| z = z - z.max(axis=-1, keepdims=True) | |
| p = np.exp(z) | |
| return p / p.sum(axis=-1, keepdims=True) | |
| class StaticKDClassifier: | |
| """Loads config.json, model.safetensors and tokenizer.json from one folder.""" | |
| def __init__(self, path: str | Path = "."): | |
| path = Path(path) | |
| self.config = json.loads((path / "config.json").read_text(encoding="utf-8")) | |
| tensors = load_file(str(path / self.config["weights"]["file"])) | |
| self.table = tensors["token_table"] # (vocab_size, 17), float16 | |
| self.bias = tensors["bias"] # (17,), float32 | |
| tok_cfg = self.config["tokenizer"] | |
| self.tokenizer = Tokenizer.from_file(str(path / tok_cfg["file"])) | |
| self.unk_id = self.tokenizer.token_to_id(tok_cfg["unk_token"]) | |
| self.empty_id = int(tok_cfg["empty_input_token_id"]) | |
| self.max_tokens = int(self.config["max_tokens"]) | |
| self.labels = [self.config["id2label"][str(i)] for i in range(self.config["num_labels"])] | |
| def token_ids(self, texts: list[str]) -> list[np.ndarray]: | |
| """Token ids per text: no special tokens, first max_tokens ids, unknown tokens removed.""" | |
| out = [] | |
| for enc in self.tokenizer.encode_batch(list(texts), add_special_tokens=False): | |
| ids = np.asarray(enc.ids[: self.max_tokens], dtype=np.int64) | |
| if self.unk_id is not None: | |
| ids = ids[ids != self.unk_id] | |
| out.append(ids if len(ids) else np.full(1, self.empty_id, dtype=np.int64)) | |
| return out | |
| def logits(self, texts: list[str]) -> np.ndarray: | |
| """Array of shape (len(texts), 17): mean of the token rows plus the bias.""" | |
| if isinstance(texts, str): | |
| texts = [texts] | |
| ids = self.token_ids(texts) | |
| x = np.stack([self.table[i].mean(axis=0, dtype=np.float32) for i in ids]) | |
| return x + self.bias | |
| def predict_proba(self, texts: list[str]) -> np.ndarray: | |
| """Array of shape (len(texts), 17) with label probabilities in the order of self.labels.""" | |
| return softmax(self.logits(texts)) | |
| def predict(self, texts: list[str], top_k: int = 1) -> list[list[tuple[str, float]]]: | |
| """For every text, the top_k (label, probability) pairs, highest first.""" | |
| probs = self.predict_proba(texts) | |
| order = np.argsort(-probs, axis=1, kind="stable")[:, :top_k] | |
| return [[(self.labels[j], float(p[j])) for j in row] for p, row in zip(probs, order)] | |
| if __name__ == "__main__": | |
| if len(sys.argv) < 2: | |
| sys.exit('usage: python statickd_inference.py "text" ["text" ...]') | |
| model = StaticKDClassifier(Path(__file__).resolve().parent) | |
| for text, top in zip(sys.argv[1:], model.predict(sys.argv[1:], top_k=3)): | |
| print(text[:60].replace("\n", " ")) | |
| for label, prob in top: | |
| print(f" {prob:.3f} {label}") | |