Spaces:
Sleeping
Sleeping
File size: 6,713 Bytes
d8c39f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | """
Kronos Financial Foundation Model — HuggingFace Spaces FastAPI server.
API:
POST /api/load-model {"model_key": "kronos-small"}
POST /api/predict {"k_lines": [[ts_ms,o,h,l,c,v],...],
"prediction_params": {"pred_len": 24}}
Auth: Authorization: Bearer <KRONOS_BEARER_TOKEN>
Set KRONOS_BEARER_TOKEN as a HF Space secret (Settings → Variables and secrets).
"""
from __future__ import annotations
import os
import sys
import time
from contextlib import asynccontextmanager
from typing import Any
import numpy as np
import pandas as pd
import torch
# Kronos ships its own model.py — not available on PyPI
sys.path.insert(0, "/app/kronos")
from model import Kronos, KronosTokenizer, KronosPredictor # noqa: E402
from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
BEARER_TOKEN: str = os.getenv("KRONOS_BEARER_TOKEN", "")
MODEL_REPO: dict[str, str] = {
"kronos-small": "NeoQuasar/Kronos-small",
"kronos-mini": "NeoQuasar/Kronos-mini",
"kronos-base": "NeoQuasar/Kronos-base",
}
TOKENIZER_REPO = "NeoQuasar/Kronos-Tokenizer-base"
DEFAULT_MODEL_KEY = "kronos-small"
# ---------------------------------------------------------------------------
# Global model state
# ---------------------------------------------------------------------------
_predictor: KronosPredictor | None = None
_loaded_model_key: str | None = None
# ---------------------------------------------------------------------------
# Auth
# ---------------------------------------------------------------------------
_security = HTTPBearer(auto_error=False)
def _verify_token(
creds: HTTPAuthorizationCredentials | None = Security(_security),
) -> None:
if not BEARER_TOKEN:
return
if creds is None or creds.credentials != BEARER_TOKEN:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or missing Bearer token",
headers={"WWW-Authenticate": "Bearer"},
)
# ---------------------------------------------------------------------------
# Lifespan
# ---------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
_load_model(DEFAULT_MODEL_KEY)
except Exception as exc:
print(f"WARNING: could not pre-warm model on startup: {exc}")
yield
app = FastAPI(title="Kronos API", lifespan=lifespan)
# ---------------------------------------------------------------------------
# Model loading
# ---------------------------------------------------------------------------
def _load_model(model_key: str) -> None:
global _predictor, _loaded_model_key
if _loaded_model_key == model_key and _predictor is not None:
return
repo_id = MODEL_REPO.get(model_key)
if repo_id is None:
raise ValueError(f"Unknown model_key: {model_key!r}. Valid keys: {list(MODEL_REPO)}")
device = "cuda:0" if torch.cuda.is_available() else "cpu"
tokenizer = KronosTokenizer.from_pretrained(TOKENIZER_REPO)
model = Kronos.from_pretrained(repo_id)
_predictor = KronosPredictor(model, tokenizer, device=device, max_context=512)
_loaded_model_key = model_key
# ---------------------------------------------------------------------------
# Inference
# ---------------------------------------------------------------------------
def _run_kronos(k_lines: list[list[float]], pred_len: int) -> list[list[float]]:
"""
Input: [[ts_ms, open, high, low, close, volume], ...]
Output: [[ts_ms, open, high, low, close], ...]
"""
if _predictor is None:
raise RuntimeError("Model not loaded.")
interval_ms = float(k_lines[1][0] - k_lines[0][0]) if len(k_lines) > 1 else 3_600_000.0
last_ts_ms = float(k_lines[-1][0])
x_timestamps = pd.to_datetime([row[0] for row in k_lines], unit="ms", utc=True)
y_timestamps = pd.to_datetime(
[last_ts_ms + (i + 1) * interval_ms for i in range(pred_len)],
unit="ms",
utc=True,
)
df = pd.DataFrame(k_lines, columns=["ts_ms", "open", "high", "low", "close", "volume"])
df["amount"] = df["close"] * df["volume"]
x_df = df[["open", "high", "low", "close", "volume", "amount"]]
pred_df = _predictor.predict(
df=x_df,
x_timestamp=x_timestamps,
y_timestamp=y_timestamps,
pred_len=pred_len,
T=1.0,
top_p=0.9,
sample_count=1,
)
result: list[list[float]] = []
for i, row in enumerate(pred_df.itertuples(index=False)):
ts = last_ts_ms + (i + 1) * interval_ms
o = float(getattr(row, "open", row[0]))
h = float(getattr(row, "high", row[1]))
l = float(getattr(row, "low", row[2]))
c = float(getattr(row, "close", row[3]))
result.append([ts, o, h, l, c])
return result
# ---------------------------------------------------------------------------
# Request / response schemas
# ---------------------------------------------------------------------------
class LoadModelRequest(BaseModel):
model_key: str = DEFAULT_MODEL_KEY
class PredictRequest(BaseModel):
k_lines: list[list[float]]
prediction_params: dict[str, Any] = {}
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@app.get("/health")
def health():
return {"status": "ok", "model_loaded": _loaded_model_key}
@app.post("/api/load-model", dependencies=[Depends(_verify_token)])
def load_model(req: LoadModelRequest):
try:
t0 = time.time()
_load_model(req.model_key)
return {
"status": "loaded",
"model_key": req.model_key,
"load_time_s": round(time.time() - t0, 2),
}
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
@app.post("/api/predict", dependencies=[Depends(_verify_token)])
def predict(req: PredictRequest):
if _predictor is None:
raise HTTPException(status_code=400, detail="Model not loaded. POST /api/load-model first.")
pred_len: int = int(req.prediction_params.get("pred_len", 24))
try:
prediction_results = _run_kronos(req.k_lines, pred_len)
return {"prediction_results": prediction_results}
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc))
|