|
| 1 | +"""IMF v1 inference endpoint for api.interscript.org (Modal, CPU). |
| 2 | +
|
| 3 | +Serves the shipped models from the secryst-models volume using the |
| 4 | +exact ONNX kv decode the WO03 parity gate verified. Cold start loads |
| 5 | +the fp32 zip (~30-60s); sessions are cached per container. |
| 6 | +
|
| 7 | + modal deploy src/api/inference.py |
| 8 | +
|
| 9 | +Auth: X-API-Key header must match the `api-inference-key` secret. |
| 10 | +""" |
| 11 | + |
| 12 | +import hmac |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +import modal |
| 16 | + |
| 17 | +models_volume = modal.Volume.from_name("secryst-models") |
| 18 | + |
| 19 | +image = ( |
| 20 | + modal.Image.debian_slim(python_version="3.11") |
| 21 | + .pip_install("onnxruntime==1.23.2", "pyyaml>=6.0", "fastapi>=0.115") |
| 22 | + .add_local_dir(str(Path(__file__).resolve().parent.parent), "/root/interscript-ml", copy=True) |
| 23 | + .workdir("/root/interscript-ml") |
| 24 | + .env({"IMAGE_REV": "5"}) |
| 25 | +) |
| 26 | + |
| 27 | +app = modal.App("interscript-inference", image=image) |
| 28 | + |
| 29 | +MAX_INPUT_BYTES = 4000 |
| 30 | +MAX_OUTPUT_TOKENS = 8192 |
| 31 | +ALLOWED_TASKS = ("diacritization", "g2p") |
| 32 | + |
| 33 | +_sessions: dict[str, tuple] = {} |
| 34 | + |
| 35 | + |
| 36 | +def _zip_path(model_id: str) -> Path: |
| 37 | + # model_id arrives from the request body — paths are built ONLY from |
| 38 | + # the server's own volume listing; the user value is used solely in |
| 39 | + # an equality comparison, never in path construction (CWE-22) |
| 40 | + import glob |
| 41 | + |
| 42 | + wanted = f"{model_id}-fp32.zip" |
| 43 | + for z in glob.glob("/v/imf/*/*-fp32.zip"): |
| 44 | + if z.rsplit("/", 1)[1] == wanted: |
| 45 | + return Path(z) |
| 46 | + raise KeyError(model_id) |
| 47 | + |
| 48 | + |
| 49 | +def _get_sessions(model_id: str) -> tuple: |
| 50 | + import sys |
| 51 | + |
| 52 | + sys.path.insert(0, "/root/interscript-ml/src") |
| 53 | + from imf.parity import _sessions_from_zip # the parity-verified loader |
| 54 | + |
| 55 | + if model_id not in _sessions: |
| 56 | + _sessions[model_id] = _sessions_from_zip(_zip_path(model_id)) |
| 57 | + return _sessions[model_id] |
| 58 | + |
| 59 | + |
| 60 | +def _metadata(model_id: str) -> dict: |
| 61 | + import zipfile |
| 62 | + |
| 63 | + import yaml |
| 64 | + |
| 65 | + with zipfile.ZipFile(_zip_path(model_id)) as zf: |
| 66 | + return yaml.safe_load(zf.read("metadata.yaml")) |
| 67 | + |
| 68 | + |
| 69 | +def _decode(tokens: list) -> str: |
| 70 | + # ByT5 token ids are byte+3, with trailing EOS (id 1) |
| 71 | + return bytes(t - 3 for t in tokens if t >= 3).decode("utf-8", "replace") |
| 72 | + |
| 73 | + |
| 74 | +def make_api(): |
| 75 | + import os |
| 76 | + |
| 77 | + from fastapi import FastAPI, HTTPException, Request |
| 78 | + |
| 79 | + api = FastAPI(title="Interscript inference", version="1.0.0") |
| 80 | + |
| 81 | + @api.post("/infer") |
| 82 | + async def infer(request: Request) -> dict: |
| 83 | + |
| 84 | + key = request.headers.get("x-api-key", "") |
| 85 | + if not key or not hmac.compare_digest(key, os.environ.get("API_INFERENCE_KEY") or ""): |
| 86 | + raise HTTPException(401, "invalid or missing X-API-Key") |
| 87 | + try: |
| 88 | + body = await request.json() |
| 89 | + except Exception: |
| 90 | + raise HTTPException(400, "body must be JSON {model, input}") from None |
| 91 | + if not isinstance(body, dict) or not body.get("model") or not body.get("input"): |
| 92 | + raise HTTPException(400, "body must be {model, input}") |
| 93 | + |
| 94 | + return await _run_infer(body) |
| 95 | + |
| 96 | + async def _run_infer(body): |
| 97 | + import sys |
| 98 | + |
| 99 | + models_volume.reload() |
| 100 | + try: |
| 101 | + meta = _metadata(body["model"]) |
| 102 | + except KeyError: |
| 103 | + raise HTTPException(404, f"unknown model {body['model']}") from None |
| 104 | + if meta.get("task") not in ALLOWED_TASKS: |
| 105 | + raise HTTPException(400, f"model {body['model']} task {meta.get('task')} is not served") |
| 106 | + |
| 107 | + if len(body["input"].encode("utf-8")) > MAX_INPUT_BYTES: |
| 108 | + raise HTTPException(413, f"input exceeds {MAX_INPUT_BYTES} bytes") |
| 109 | + |
| 110 | + sys.path.insert(0, "/root/interscript-ml/src") |
| 111 | + from imf.export import onnx_greedy_kv |
| 112 | + |
| 113 | + enc, kv = _get_sessions(body["model"]) |
| 114 | + max_len = min(MAX_OUTPUT_TOKENS, 3 * len(body["input"].encode("utf-8")) + 256) |
| 115 | + output = _decode(onnx_greedy_kv(enc, kv, body["input"], max_len)) |
| 116 | + return { |
| 117 | + "model": body["model"], |
| 118 | + "task": meta["task"], |
| 119 | + "source_script": meta.get("source_script"), |
| 120 | + "input": body["input"], |
| 121 | + "output": output, |
| 122 | + } |
| 123 | + |
| 124 | + @api.get("/health") |
| 125 | + def health() -> dict: |
| 126 | + import glob |
| 127 | + |
| 128 | + models_volume.reload() |
| 129 | + return {"ok": True, "models": len(glob.glob("/v/imf/*/*-fp32.zip"))} |
| 130 | + |
| 131 | + return api |
| 132 | + |
| 133 | + |
| 134 | +@app.function( |
| 135 | + cpu=4, |
| 136 | + memory=8 * 1024, |
| 137 | + timeout=10 * 60, |
| 138 | + volumes={"/v": models_volume}, |
| 139 | + secrets=[modal.Secret.from_name("api-inference-key")], |
| 140 | + # cold starts (~30-60s model load) instead of a 24/7 warm container |
| 141 | + # — money discipline; bump once traffic justifies it |
| 142 | +) |
| 143 | +@modal.asgi_app() |
| 144 | +def web(): |
| 145 | + return make_api() |
0 commit comments