Download src/openthai_systemone_onnx/client.py from imtk/OpenThai-SystemOne-ONNX: direct link, hf CLI and curl.
- Browser
- Download file 7.88 kB
-
https://huggingface.co/imtk/OpenThai-SystemOne-ONNX/resolve/main/src/openthai_systemone_onnx/client.py
- Command line
-
hf download hf://imtk/OpenThai-SystemOne-ONNX/src/openthai_systemone_onnx/client.py
-
curl -L -o client.py https://huggingface.co/imtk/OpenThai-SystemOne-ONNX/resolve/main/src/openthai_systemone_onnx/client.py
7.88 kB
| """ONNX implementation of the upstream local client. | |
| Only initialization and ``_run`` differ from the pinned upstream client. All | |
| formatting, permutation planning, decoding, confidence calculation, response | |
| models, and token accounting remain upstream code. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| from typing import Optional, Sequence | |
| import numpy as np | |
| import onnxruntime as ort | |
| import torch | |
| from huggingface_hub import snapshot_download | |
| from openthai_systemone.client import SystemOneClient | |
| from openthai_systemone.formatting import Encoded, Formatter, collate | |
| from openthai_systemone.modeling import QTYPE_INDEX | |
| from transformers import AutoTokenizer | |
| from .constants import ABSTAIN_SLOT, MAX_POSITION_EMBEDDINGS, REQUIRED_ORT_VERSION | |
| VARIANT_GRAPH_NAMES = { | |
| "fp32": "model.onnx", | |
| "int8": "model.int8.onnx", | |
| "int4": "model.int4.onnx", | |
| } | |
| def _resolve_artifact(model_path: str, precision: str = "fp32") -> tuple[Path, Path, dict]: | |
| """Return ``(repository_root, onnx_path, manifest)`` for a local path or HF id.""" | |
| candidate = Path(model_path).expanduser() | |
| if candidate.exists(): | |
| if candidate.is_file(): | |
| resolved = candidate.resolve() | |
| root = resolved.parent.parent if resolved.parent.name == "onnx" else resolved.parent | |
| else: | |
| root = candidate.resolve() | |
| else: | |
| graph_name = VARIANT_GRAPH_NAMES.get(precision) | |
| if graph_name is None: | |
| raise ValueError(f"precision must be one of: {', '.join(VARIANT_GRAPH_NAMES)}") | |
| root = Path( | |
| snapshot_download( | |
| repo_id=model_path, | |
| allow_patterns=[ | |
| f"onnx/{graph_name}", | |
| f"onnx/{graph_name}.data", | |
| "artifact-manifest.json", | |
| "tokenizer*", | |
| "special_tokens_map.json", | |
| "chat_template.jinja", | |
| ], | |
| ) | |
| ) | |
| manifest_path = root / "artifact-manifest.json" | |
| if not manifest_path.is_file(): | |
| raise FileNotFoundError(f"artifact manifest not found: {manifest_path}") | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| variants = manifest.get("variants") or { | |
| "fp32": {"graph": manifest.get("graph", "onnx/model.onnx")} | |
| } | |
| if precision not in variants: | |
| available = ", ".join(sorted(variants)) | |
| raise ValueError(f"precision must be one of the artifact variants: {available}") | |
| onnx_path = root / variants[precision]["graph"] | |
| if not onnx_path.is_file(): | |
| raise FileNotFoundError(f"ONNX graph for precision={precision!r} not found: {onnx_path}") | |
| return root, onnx_path, manifest | |
| class OnnxSystemOneClient(SystemOneClient): | |
| """A drop-in ``SystemOneClient`` backed by one ONNX Runtime graph.""" | |
| def __init__( | |
| self, | |
| model_path: str, | |
| *, | |
| device: Optional[str] = None, | |
| dtype: Optional[torch.dtype] = None, | |
| max_total_tokens: int = 65536, | |
| max_state_tokens: int = 32768, | |
| model_name: str = "openthai-systemone", | |
| precision: str = "fp32", | |
| ): | |
| if dtype is not None and dtype is not torch.float32: | |
| raise TypeError( | |
| "OpenThai-SystemOne-ONNX uses FP32 inputs and outputs; dtype must be None or torch.float32" | |
| ) | |
| if max_total_tokens < 1 or max_total_tokens > MAX_POSITION_EMBEDDINGS: | |
| raise ValueError( | |
| f"max_total_tokens must be in 1..{MAX_POSITION_EMBEDDINGS:,}, got {max_total_tokens:,}" | |
| ) | |
| if max_state_tokens < 1 or max_state_tokens > MAX_POSITION_EMBEDDINGS: | |
| raise ValueError( | |
| f"max_state_tokens must be in 1..{MAX_POSITION_EMBEDDINGS:,}, got {max_state_tokens:,}" | |
| ) | |
| normalized_device = "cpu" if device is None else str(device).lower() | |
| provider_for_device = { | |
| "cpu": "CPUExecutionProvider", | |
| "cuda": "CUDAExecutionProvider", | |
| } | |
| if normalized_device not in provider_for_device: | |
| raise ValueError("device must be None, 'cpu', or 'cuda'; MPS and other ONNX providers are unsupported") | |
| provider = provider_for_device[normalized_device] | |
| available = ort.get_available_providers() | |
| if provider not in available: | |
| raise RuntimeError( | |
| f"{provider} is not installed; available ONNX Runtime providers: {available}" | |
| ) | |
| if ort.__version__ != REQUIRED_ORT_VERSION: | |
| raise RuntimeError( | |
| f"This artifact requires onnxruntime=={REQUIRED_ORT_VERSION}; found {ort.__version__}" | |
| ) | |
| normalized_precision = str(precision).lower() | |
| root, onnx_path, manifest = _resolve_artifact(model_path, normalized_precision) | |
| artifact_limit = int(manifest.get("max_position_embeddings", 0)) | |
| if artifact_limit != MAX_POSITION_EMBEDDINGS: | |
| raise ValueError( | |
| f"artifact max_position_embeddings is {artifact_limit}, expected {MAX_POSITION_EMBEDDINGS}" | |
| ) | |
| self.device = normalized_device | |
| self.dtype = torch.float32 | |
| self.precision = normalized_precision | |
| self.manifest = manifest | |
| self.tok = AutoTokenizer.from_pretrained(root, local_files_only=True) | |
| self.fmt = Formatter( | |
| self.tok, | |
| max_total_tokens=max_total_tokens, | |
| max_state_tokens=max_state_tokens, | |
| ) | |
| self.model_name = model_name | |
| self.max_position_embeddings = artifact_limit | |
| pad = self.tok.pad_token_id | |
| self.pad_id = pad if pad is not None else (self.tok.eos_token_id or 0) | |
| # The inherited decoder reads only model.config.abstain_slot. | |
| self.model = SimpleNamespace(config=SimpleNamespace(abstain_slot=ABSTAIN_SLOT)) | |
| options = ort.SessionOptions() | |
| options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL | |
| self.session = ort.InferenceSession(str(onnx_path), sess_options=options, providers=[provider]) | |
| expected_inputs = {"input_ids", "attention_mask", "answer_positions", "option_counts", "qtypes"} | |
| actual_inputs = {item.name for item in self.session.get_inputs()} | |
| if actual_inputs != expected_inputs: | |
| raise ValueError( | |
| f"unexpected ONNX input contract: expected {sorted(expected_inputs)}, got {sorted(actual_inputs)}" | |
| ) | |
| def _run(self, encs: Sequence[Encoded]) -> torch.Tensor: | |
| if not encs: | |
| return torch.empty((0, 0, 256), dtype=torch.float32) | |
| longest = max(enc.n_tokens for enc in encs) | |
| if longest > self.max_position_embeddings: | |
| raise ValueError( | |
| f"encoded input has {longest:,} tokens; the backbone limit is " | |
| f"{self.max_position_embeddings:,}" | |
| ) | |
| batch = collate(encs, self.pad_id) | |
| qtypes = torch.full_like(batch["option_counts"], -1) | |
| for batch_index, encoded in enumerate(encs): | |
| for question_index, spec in enumerate(encoded.specs): | |
| qtypes[batch_index, question_index] = QTYPE_INDEX[spec.qtype] | |
| feeds = { | |
| "input_ids": batch["input_ids"].numpy().astype(np.int64, copy=False), | |
| "attention_mask": batch["attention_mask"].numpy().astype(np.int64, copy=False), | |
| "answer_positions": batch["answer_positions"].numpy().astype(np.int64, copy=False), | |
| "option_counts": batch["option_counts"].numpy().astype(np.int64, copy=False), | |
| "qtypes": qtypes.numpy().astype(np.int64, copy=False), | |
| } | |
| probabilities = self.session.run(["probabilities"], feeds)[0] | |
| return torch.from_numpy(np.asarray(probabilities, dtype=np.float32)) | |