Upload onnx/fp32/infer.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Self-contained runner, copied into each ONNX bundle as infer.py.
python infer.py --context "Find last quarter's sales" --options search database
Requires numpy, transformers and onnxruntime (onnxruntime-gpu for FP16).This file deliberately has no imports from zesyde or torch."""import argparseimport jsonfrom pathlib import Path
import numpy as np
def prepare_inputs(tokenizer, context, question, options, max_length=512): """Match train_modal.py's sequence template and track absolute markers.""" if not options: raise ValueError("At least one option is required") marker = tokenizer.mask_token_id if marker is None: marker = tokenizer.convert_tokens_to_ids("[MASK]") if marker is None or marker == tokenizer.unk_token_id: raise ValueError("Bundle tokenizer is missing its trained option marker") cls_id = tokenizer.cls_token_id or tokenizer.bos_token_id or 0 sep_id = tokenizer.sep_token_id or tokenizer.eos_token_id or 2 ctx = tokenizer.encode(context.strip(), add_special_tokens=False) query = tokenizer.encode(question, add_special_tokens=False) if question else [] option_ids, positions = [], [] for option in options: positions.append(len(option_ids)) option_ids.append(marker) option_ids.extend(tokenizer.encode(option, add_special_tokens=False)) budget = max_length - 4 - len(query) - len(option_ids) if budget < 0: raise ValueError("Question and options exceed max_length; shorten them or raise the limit") prefix = [cls_id] + ctx[:budget] + [sep_id] + query + [sep_id] ids = np.asarray([prefix + option_ids + [sep_id]], dtype=np.int64) return { "input_ids": ids, "attention_mask": np.ones_like(ids), "marker_positions": np.asarray([[p + len(prefix) for p in positions]], dtype=np.int64), }
def decode_outputs(logits, act_logit, options, calibration, question_type="choice", threshold=0.1): temperatures = calibration.get("temperatures", calibration) temperature = float(temperatures.get( f"{question_type}|{len(options)}", temperatures.get( f"{question_type}|0", temperatures.get("*|0", temperatures.get("default", 1.0)) ) )) if not np.isfinite(temperature) or temperature <= 0: raise ValueError("Calibration temperature must be finite and positive") scores = np.asarray(logits, dtype=np.float64) / temperature probs = np.exp(scores - scores.max()) probs /= probs.sum() act = float(act_logit) # Stable sigmoid, including very large act logits. escalation = float(1 / (1 + np.exp(-act))) if act >= 0 else float(np.exp(act) / (1 + np.exp(act))) choice = int(probs.argmax()) return { "selected_option": options[choice], "confidence": float(probs[choice]), "probabilities": probs.tolist(), "options": options, "escalate_probability": escalation, "should_escalate": escalation > threshold, }
def main(): import onnxruntime as ort from transformers import AutoTokenizer
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bundle", type=Path, default=Path(__file__).resolve().parent) parser.add_argument("--context", default="") parser.add_argument("--question", default="Select the best option:") parser.add_argument("--options", nargs="+", required=True) parser.add_argument("--question-type", default="choice") parser.add_argument("--max-length", type=int, default=512) parser.add_argument("--escalation-threshold", type=float, default=0.1) args = parser.parse_args() manifest = json.loads((args.bundle / "manifest.json").read_text(encoding="utf-8")) providers = ["CPUExecutionProvider"] if manifest["format"] == "fp16": if hasattr(ort, "preload_dlls"): ort.preload_dlls() if "CUDAExecutionProvider" not in ort.get_available_providers(): raise RuntimeError("FP16 requires onnxruntime-gpu with a working CUDA provider") providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] tokenizer = AutoTokenizer.from_pretrained(str(args.bundle), local_files_only=True) inputs = prepare_inputs(tokenizer, args.context, args.question, args.options, args.max_length) session = ort.InferenceSession(str(args.bundle / "model.onnx"), providers=providers) if manifest["format"] == "fp16" and session.get_providers()[0] != "CUDAExecutionProvider": raise RuntimeError("ONNX Runtime could not initialize the CUDA provider") logits, act_logits = session.run(["logits", "act_logits"], inputs) calibration = json.loads((args.bundle / "calibration.json").read_text(encoding="utf-8")) result = decode_outputs(logits[0], act_logits[0], args.options, calibration, args.question_type, args.escalation_threshold) print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == "__main__": main()onnx/fp32/infer.pyAdded+102