|
| 1 | +import datetime |
| 2 | +import json |
| 3 | +import os |
| 4 | +import tarfile |
| 5 | +import uuid |
| 6 | +from typing import Dict, List, Optional |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import onnxruntime as ort |
| 10 | +from tokenizers import Tokenizer |
| 11 | + |
| 12 | +from . import storage |
| 13 | + |
| 14 | +client = storage.storage.get_instance() |
| 15 | + |
| 16 | +MODEL_ARCHIVE = "bert-tiny-onnx.tar.gz" |
| 17 | +MODEL_DIRECTORY = "/tmp/bert_language_model" |
| 18 | +MODEL_SUBDIR = "bert-tiny-onnx" |
| 19 | + |
| 20 | +_session: Optional[ort.InferenceSession] = None |
| 21 | +_tokenizer: Optional[Tokenizer] = None |
| 22 | +_labels: Optional[Dict[int, str]] = None |
| 23 | + |
| 24 | + |
| 25 | +def _ensure_model(bucket: str, model_prefix: str): |
| 26 | + """ |
| 27 | + Lazily download and initialize the ONNX model and tokenizer. |
| 28 | + """ |
| 29 | + global _session, _tokenizer, _labels |
| 30 | + |
| 31 | + model_path = os.path.join(MODEL_DIRECTORY, MODEL_SUBDIR) |
| 32 | + model_download_begin = datetime.datetime.now() |
| 33 | + model_download_end = model_download_begin |
| 34 | + |
| 35 | + if _session is None or _tokenizer is None or _labels is None: |
| 36 | + if not os.path.exists(model_path): |
| 37 | + os.makedirs(MODEL_DIRECTORY, exist_ok=True) |
| 38 | + archive_path = os.path.join("/tmp", f"{uuid.uuid4()}-{MODEL_ARCHIVE}") |
| 39 | + client.download(bucket, os.path.join(model_prefix, MODEL_ARCHIVE), archive_path) |
| 40 | + model_download_end = datetime.datetime.now() |
| 41 | + |
| 42 | + with tarfile.open(archive_path, "r:gz") as tar: |
| 43 | + tar.extractall(MODEL_DIRECTORY) |
| 44 | + os.remove(archive_path) |
| 45 | + else: |
| 46 | + model_download_begin = datetime.datetime.now() |
| 47 | + model_download_end = model_download_begin |
| 48 | + |
| 49 | + model_process_begin = datetime.datetime.now() |
| 50 | + tokenizer_path = os.path.join(model_path, "tokenizer.json") |
| 51 | + _tokenizer = Tokenizer.from_file(tokenizer_path) |
| 52 | + _tokenizer.enable_truncation(max_length=128) |
| 53 | + _tokenizer.enable_padding(length=128) |
| 54 | + |
| 55 | + label_map_path = os.path.join(model_path, "label_map.json") |
| 56 | + with open(label_map_path, "r") as f: |
| 57 | + raw_labels = json.load(f) |
| 58 | + _labels = {int(idx): label for idx, label in raw_labels.items()} |
| 59 | + |
| 60 | + onnx_path = os.path.join(model_path, "model.onnx") |
| 61 | + |
| 62 | + available = ort.get_available_providers() |
| 63 | + if "CUDAExecutionProvider" not in available: |
| 64 | + raise RuntimeError(f"CUDAExecutionProvider unavailable (have: {available})") |
| 65 | + |
| 66 | + _session = ort.InferenceSession(onnx_path, providers=["CUDAExecutionProvider"]) |
| 67 | + model_process_end = datetime.datetime.now() |
| 68 | + else: |
| 69 | + model_process_begin = datetime.datetime.now() |
| 70 | + model_process_end = model_process_begin |
| 71 | + |
| 72 | + model_download_time = (model_download_end - model_download_begin) / datetime.timedelta( |
| 73 | + microseconds=1 |
| 74 | + ) |
| 75 | + model_process_time = (model_process_end - model_process_begin) / datetime.timedelta( |
| 76 | + microseconds=1 |
| 77 | + ) |
| 78 | + |
| 79 | + return model_download_time, model_process_time |
| 80 | + |
| 81 | + |
| 82 | +def _prepare_inputs(sentences: List[str]): |
| 83 | + assert _tokenizer is not None |
| 84 | + |
| 85 | + encodings = _tokenizer.encode_batch(sentences) |
| 86 | + |
| 87 | + input_ids = np.array([enc.ids for enc in encodings], dtype=np.int64) |
| 88 | + attention_mask = np.array([enc.attention_mask for enc in encodings], dtype=np.int64) |
| 89 | + token_type_ids = np.array( |
| 90 | + [enc.type_ids if enc.type_ids else [0] * len(enc.ids) for enc in encodings], |
| 91 | + dtype=np.int64, |
| 92 | + ) |
| 93 | + |
| 94 | + return { |
| 95 | + "input_ids": input_ids, |
| 96 | + "attention_mask": attention_mask, |
| 97 | + "token_type_ids": token_type_ids, |
| 98 | + } |
| 99 | + |
| 100 | + |
| 101 | +def _softmax(logits: np.ndarray) -> np.ndarray: |
| 102 | + shifted = logits - np.max(logits, axis=1, keepdims=True) |
| 103 | + exp = np.exp(shifted) |
| 104 | + return exp / np.sum(exp, axis=1, keepdims=True) |
| 105 | + |
| 106 | + |
| 107 | +def handler(event): |
| 108 | + bucket = event.get("bucket", {}).get("bucket") |
| 109 | + model_prefix = event.get("bucket", {}).get("model") |
| 110 | + text_prefix = event.get("bucket", {}).get("text") |
| 111 | + text_key = event.get("object", {}).get("input") |
| 112 | + |
| 113 | + download_begin = datetime.datetime.now() |
| 114 | + text_download_path = os.path.join("/tmp", f"{uuid.uuid4()}-{os.path.basename(text_key)}") |
| 115 | + client.download(bucket, os.path.join(text_prefix, text_key), text_download_path) |
| 116 | + download_end = datetime.datetime.now() |
| 117 | + |
| 118 | + model_download_time, model_process_time = _ensure_model(bucket, model_prefix) |
| 119 | + assert _session is not None and _labels is not None and _tokenizer is not None |
| 120 | + |
| 121 | + with open(text_download_path, "r") as f: |
| 122 | + sentences = [json.loads(line)["text"] for line in f if line.strip()] |
| 123 | + |
| 124 | + os.remove(text_download_path) |
| 125 | + |
| 126 | + inference_begin = datetime.datetime.now() |
| 127 | + inputs = _prepare_inputs(sentences) |
| 128 | + outputs = _session.run(None, inputs) |
| 129 | + logits = outputs[0] |
| 130 | + probabilities = _softmax(logits) |
| 131 | + inference_end = datetime.datetime.now() |
| 132 | + |
| 133 | + results = [] |
| 134 | + for sentence, probs in zip(sentences, probabilities): |
| 135 | + label_idx = int(np.argmax(probs)) |
| 136 | + label = _labels.get(label_idx, str(label_idx)) |
| 137 | + results.append( |
| 138 | + { |
| 139 | + "text": sentence, |
| 140 | + "label": label, |
| 141 | + "confidence": float(probs[label_idx]), |
| 142 | + "raw_scores": probs.tolist(), |
| 143 | + } |
| 144 | + ) |
| 145 | + |
| 146 | + download_time = (download_end - download_begin) / datetime.timedelta(microseconds=1) |
| 147 | + compute_time = (inference_end - inference_begin) / datetime.timedelta(microseconds=1) |
| 148 | + |
| 149 | + return { |
| 150 | + "result": {"predictions": results}, |
| 151 | + "measurement": { |
| 152 | + "download_time": download_time + model_download_time, |
| 153 | + "compute_time": compute_time + model_process_time, |
| 154 | + "model_time": model_process_time, |
| 155 | + "model_download_time": model_download_time, |
| 156 | + }, |
| 157 | + } |
0 commit comments