Spaces:
Running
Running
Update service.py
Browse files- service.py +137 -137
service.py
CHANGED
|
@@ -1,137 +1,137 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import math
|
| 4 |
-
import os
|
| 5 |
-
from statistics import mean
|
| 6 |
-
from typing import Any
|
| 7 |
-
|
| 8 |
-
from schemas import HealthResponse, PredictRequest, PredictResponse, PredictionItem
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
class ChronosService:
|
| 12 |
-
"""CPU-first HF Space service wrapper for Chronos.
|
| 13 |
-
|
| 14 |
-
This scaffold is designed for HuggingFace free CPU Spaces and keeps the
|
| 15 |
-
serving contract aligned with `tsf-bridge`. The default backend is a
|
| 16 |
-
deterministic CPU baseline rather than real Chronos inference.
|
| 17 |
-
"""
|
| 18 |
-
|
| 19 |
-
def __init__(self) -> None:
|
| 20 |
-
self.model_id = "chronos"
|
| 21 |
-
self.model_name = os.getenv(
|
| 22 |
-
"CHRONOS_MODEL_NAME",
|
| 23 |
-
"amazon/chronos-
|
| 24 |
-
)
|
| 25 |
-
self.backend = os.getenv("CHRONOS_BACKEND", "baseline_cpu").strip() or "baseline_cpu"
|
| 26 |
-
self.device = "cpu"
|
| 27 |
-
self.ready = True
|
| 28 |
-
self.max_context_length = int(os.getenv("CHRONOS_MAX_CONTEXT_LENGTH", "512"))
|
| 29 |
-
self.max_horizon_step = int(os.getenv("CHRONOS_MAX_HORIZON_STEP", "288"))
|
| 30 |
-
self.confidence_floor = float(os.getenv("CHRONOS_CONFIDENCE_FLOOR", "0.16"))
|
| 31 |
-
self.confidence_ceiling = float(os.getenv("CHRONOS_CONFIDENCE_CEILING", "0.80"))
|
| 32 |
-
self.min_required_points = int(os.getenv("CHRONOS_MIN_REQUIRED_POINTS", "32"))
|
| 33 |
-
|
| 34 |
-
def health(self) -> HealthResponse:
|
| 35 |
-
return HealthResponse(
|
| 36 |
-
status="ok",
|
| 37 |
-
model=self.model_name,
|
| 38 |
-
model_id=self.model_id,
|
| 39 |
-
backend=self.backend,
|
| 40 |
-
device=self.device,
|
| 41 |
-
ready=self.ready,
|
| 42 |
-
max_context_length=self.max_context_length,
|
| 43 |
-
max_horizon_step=self.max_horizon_step,
|
| 44 |
-
)
|
| 45 |
-
|
| 46 |
-
def predict(self, payload: PredictRequest) -> PredictResponse:
|
| 47 |
-
self._validate_request(payload)
|
| 48 |
-
closes = payload.close_prices[-payload.context_length :]
|
| 49 |
-
predictions = self._predict_with_baseline(closes, payload.horizons)
|
| 50 |
-
return PredictResponse(model_id=self.model_id, predictions=predictions)
|
| 51 |
-
|
| 52 |
-
def _validate_request(self, payload: PredictRequest) -> None:
|
| 53 |
-
if payload.context_length > self.max_context_length:
|
| 54 |
-
raise ValueError(
|
| 55 |
-
f"context_length {payload.context_length} exceeds "
|
| 56 |
-
f"CHRONOS_MAX_CONTEXT_LENGTH={self.max_context_length}"
|
| 57 |
-
)
|
| 58 |
-
if payload.context_length > len(payload.close_prices):
|
| 59 |
-
raise ValueError("context_length must not exceed len(close_prices)")
|
| 60 |
-
if len(payload.close_prices) < self.min_required_points:
|
| 61 |
-
raise ValueError(
|
| 62 |
-
f"at least {self.min_required_points} close prices are required "
|
| 63 |
-
"for CPU baseline stability"
|
| 64 |
-
)
|
| 65 |
-
if any(step > self.max_horizon_step for step in payload.horizons):
|
| 66 |
-
raise ValueError(
|
| 67 |
-
f"horizons contain values above CHRONOS_MAX_HORIZON_STEP={self.max_horizon_step}"
|
| 68 |
-
)
|
| 69 |
-
|
| 70 |
-
def _predict_with_baseline(
|
| 71 |
-
self, close_prices: list[float], horizons: list[int]
|
| 72 |
-
) -> list[PredictionItem]:
|
| 73 |
-
last_price = close_prices[-1]
|
| 74 |
-
short_window = close_prices[-min(10, len(close_prices)) :]
|
| 75 |
-
mid_window = close_prices[-min(24, len(close_prices)) :]
|
| 76 |
-
long_window = close_prices[-min(64, len(close_prices)) :]
|
| 77 |
-
|
| 78 |
-
short_mean = mean(short_window)
|
| 79 |
-
mid_mean = mean(mid_window)
|
| 80 |
-
long_mean = mean(long_window)
|
| 81 |
-
momentum = 0.0 if short_mean == 0 else (last_price - short_mean) / short_mean
|
| 82 |
-
mean_reversion = 0.0 if long_mean == 0 else (mid_mean - long_mean) / long_mean
|
| 83 |
-
local_trend = self._slope(mid_window)
|
| 84 |
-
|
| 85 |
-
predictions: list[PredictionItem] = []
|
| 86 |
-
for step in horizons:
|
| 87 |
-
horizon_scale = min(1.0, math.log(step + 1.0) / 3.8)
|
| 88 |
-
expected_return = momentum * 0.35 + mean_reversion * 0.30 + local_trend * 0.35
|
| 89 |
-
expected_return *= horizon_scale
|
| 90 |
-
|
| 91 |
-
pred_price = max(0.00000001, last_price * (1.0 + expected_return))
|
| 92 |
-
confidence = self._confidence(close_prices, step, abs(expected_return))
|
| 93 |
-
predictions.append(
|
| 94 |
-
PredictionItem(
|
| 95 |
-
step=step,
|
| 96 |
-
pred_price=round(pred_price, 8),
|
| 97 |
-
pred_confidence=round(confidence, 4),
|
| 98 |
-
)
|
| 99 |
-
)
|
| 100 |
-
return predictions
|
| 101 |
-
|
| 102 |
-
def _confidence(
|
| 103 |
-
self, close_prices: list[float], step: int, expected_move_abs: float
|
| 104 |
-
) -> float:
|
| 105 |
-
if len(close_prices) < 3:
|
| 106 |
-
return self.confidence_floor
|
| 107 |
-
|
| 108 |
-
changes: list[float] = []
|
| 109 |
-
for previous, current in zip(close_prices[:-1], close_prices[1:]):
|
| 110 |
-
if previous <= 0:
|
| 111 |
-
continue
|
| 112 |
-
changes.append(abs((current - previous) / previous))
|
| 113 |
-
|
| 114 |
-
realized_vol = mean(changes[-min(64, len(changes)) :]) if changes else 0.0
|
| 115 |
-
stability = max(0.0, 1.0 - min(realized_vol * 18.0, 1.0))
|
| 116 |
-
horizon_decay = 1.0 / (1.0 + math.log(step + 1.0))
|
| 117 |
-
raw = 0.20 + min(expected_move_abs / (realized_vol + 1e-9), 2.0) * 0.18
|
| 118 |
-
raw += stability * 0.20 + horizon_decay * 0.22
|
| 119 |
-
return max(self.confidence_floor, min(self.confidence_ceiling, raw))
|
| 120 |
-
|
| 121 |
-
@staticmethod
|
| 122 |
-
def _slope(values: list[float]) -> float:
|
| 123 |
-
if len(values) < 2 or values[0] == 0:
|
| 124 |
-
return 0.0
|
| 125 |
-
return (values[-1] - values[0]) / values[0]
|
| 126 |
-
|
| 127 |
-
def describe_runtime(self) -> dict[str, Any]:
|
| 128 |
-
return {
|
| 129 |
-
"model_id": self.model_id,
|
| 130 |
-
"model_name": self.model_name,
|
| 131 |
-
"backend": self.backend,
|
| 132 |
-
"device": self.device,
|
| 133 |
-
"ready": self.ready,
|
| 134 |
-
"max_context_length": self.max_context_length,
|
| 135 |
-
"max_horizon_step": self.max_horizon_step,
|
| 136 |
-
"min_required_points": self.min_required_points,
|
| 137 |
-
}
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
from statistics import mean
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from schemas import HealthResponse, PredictRequest, PredictResponse, PredictionItem
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ChronosService:
|
| 12 |
+
"""CPU-first HF Space service wrapper for Chronos.
|
| 13 |
+
|
| 14 |
+
This scaffold is designed for HuggingFace free CPU Spaces and keeps the
|
| 15 |
+
serving contract aligned with `tsf-bridge`. The default backend is a
|
| 16 |
+
deterministic CPU baseline rather than real Chronos inference.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self) -> None:
|
| 20 |
+
self.model_id = "chronos"
|
| 21 |
+
self.model_name = os.getenv(
|
| 22 |
+
"CHRONOS_MODEL_NAME",
|
| 23 |
+
"amazon/chronos-2",
|
| 24 |
+
)
|
| 25 |
+
self.backend = os.getenv("CHRONOS_BACKEND", "baseline_cpu").strip() or "baseline_cpu"
|
| 26 |
+
self.device = "cpu"
|
| 27 |
+
self.ready = True
|
| 28 |
+
self.max_context_length = int(os.getenv("CHRONOS_MAX_CONTEXT_LENGTH", "512"))
|
| 29 |
+
self.max_horizon_step = int(os.getenv("CHRONOS_MAX_HORIZON_STEP", "288"))
|
| 30 |
+
self.confidence_floor = float(os.getenv("CHRONOS_CONFIDENCE_FLOOR", "0.16"))
|
| 31 |
+
self.confidence_ceiling = float(os.getenv("CHRONOS_CONFIDENCE_CEILING", "0.80"))
|
| 32 |
+
self.min_required_points = int(os.getenv("CHRONOS_MIN_REQUIRED_POINTS", "32"))
|
| 33 |
+
|
| 34 |
+
def health(self) -> HealthResponse:
|
| 35 |
+
return HealthResponse(
|
| 36 |
+
status="ok",
|
| 37 |
+
model=self.model_name,
|
| 38 |
+
model_id=self.model_id,
|
| 39 |
+
backend=self.backend,
|
| 40 |
+
device=self.device,
|
| 41 |
+
ready=self.ready,
|
| 42 |
+
max_context_length=self.max_context_length,
|
| 43 |
+
max_horizon_step=self.max_horizon_step,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
def predict(self, payload: PredictRequest) -> PredictResponse:
|
| 47 |
+
self._validate_request(payload)
|
| 48 |
+
closes = payload.close_prices[-payload.context_length :]
|
| 49 |
+
predictions = self._predict_with_baseline(closes, payload.horizons)
|
| 50 |
+
return PredictResponse(model_id=self.model_id, predictions=predictions)
|
| 51 |
+
|
| 52 |
+
def _validate_request(self, payload: PredictRequest) -> None:
|
| 53 |
+
if payload.context_length > self.max_context_length:
|
| 54 |
+
raise ValueError(
|
| 55 |
+
f"context_length {payload.context_length} exceeds "
|
| 56 |
+
f"CHRONOS_MAX_CONTEXT_LENGTH={self.max_context_length}"
|
| 57 |
+
)
|
| 58 |
+
if payload.context_length > len(payload.close_prices):
|
| 59 |
+
raise ValueError("context_length must not exceed len(close_prices)")
|
| 60 |
+
if len(payload.close_prices) < self.min_required_points:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
f"at least {self.min_required_points} close prices are required "
|
| 63 |
+
"for CPU baseline stability"
|
| 64 |
+
)
|
| 65 |
+
if any(step > self.max_horizon_step for step in payload.horizons):
|
| 66 |
+
raise ValueError(
|
| 67 |
+
f"horizons contain values above CHRONOS_MAX_HORIZON_STEP={self.max_horizon_step}"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def _predict_with_baseline(
|
| 71 |
+
self, close_prices: list[float], horizons: list[int]
|
| 72 |
+
) -> list[PredictionItem]:
|
| 73 |
+
last_price = close_prices[-1]
|
| 74 |
+
short_window = close_prices[-min(10, len(close_prices)) :]
|
| 75 |
+
mid_window = close_prices[-min(24, len(close_prices)) :]
|
| 76 |
+
long_window = close_prices[-min(64, len(close_prices)) :]
|
| 77 |
+
|
| 78 |
+
short_mean = mean(short_window)
|
| 79 |
+
mid_mean = mean(mid_window)
|
| 80 |
+
long_mean = mean(long_window)
|
| 81 |
+
momentum = 0.0 if short_mean == 0 else (last_price - short_mean) / short_mean
|
| 82 |
+
mean_reversion = 0.0 if long_mean == 0 else (mid_mean - long_mean) / long_mean
|
| 83 |
+
local_trend = self._slope(mid_window)
|
| 84 |
+
|
| 85 |
+
predictions: list[PredictionItem] = []
|
| 86 |
+
for step in horizons:
|
| 87 |
+
horizon_scale = min(1.0, math.log(step + 1.0) / 3.8)
|
| 88 |
+
expected_return = momentum * 0.35 + mean_reversion * 0.30 + local_trend * 0.35
|
| 89 |
+
expected_return *= horizon_scale
|
| 90 |
+
|
| 91 |
+
pred_price = max(0.00000001, last_price * (1.0 + expected_return))
|
| 92 |
+
confidence = self._confidence(close_prices, step, abs(expected_return))
|
| 93 |
+
predictions.append(
|
| 94 |
+
PredictionItem(
|
| 95 |
+
step=step,
|
| 96 |
+
pred_price=round(pred_price, 8),
|
| 97 |
+
pred_confidence=round(confidence, 4),
|
| 98 |
+
)
|
| 99 |
+
)
|
| 100 |
+
return predictions
|
| 101 |
+
|
| 102 |
+
def _confidence(
|
| 103 |
+
self, close_prices: list[float], step: int, expected_move_abs: float
|
| 104 |
+
) -> float:
|
| 105 |
+
if len(close_prices) < 3:
|
| 106 |
+
return self.confidence_floor
|
| 107 |
+
|
| 108 |
+
changes: list[float] = []
|
| 109 |
+
for previous, current in zip(close_prices[:-1], close_prices[1:]):
|
| 110 |
+
if previous <= 0:
|
| 111 |
+
continue
|
| 112 |
+
changes.append(abs((current - previous) / previous))
|
| 113 |
+
|
| 114 |
+
realized_vol = mean(changes[-min(64, len(changes)) :]) if changes else 0.0
|
| 115 |
+
stability = max(0.0, 1.0 - min(realized_vol * 18.0, 1.0))
|
| 116 |
+
horizon_decay = 1.0 / (1.0 + math.log(step + 1.0))
|
| 117 |
+
raw = 0.20 + min(expected_move_abs / (realized_vol + 1e-9), 2.0) * 0.18
|
| 118 |
+
raw += stability * 0.20 + horizon_decay * 0.22
|
| 119 |
+
return max(self.confidence_floor, min(self.confidence_ceiling, raw))
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _slope(values: list[float]) -> float:
|
| 123 |
+
if len(values) < 2 or values[0] == 0:
|
| 124 |
+
return 0.0
|
| 125 |
+
return (values[-1] - values[0]) / values[0]
|
| 126 |
+
|
| 127 |
+
def describe_runtime(self) -> dict[str, Any]:
|
| 128 |
+
return {
|
| 129 |
+
"model_id": self.model_id,
|
| 130 |
+
"model_name": self.model_name,
|
| 131 |
+
"backend": self.backend,
|
| 132 |
+
"device": self.device,
|
| 133 |
+
"ready": self.ready,
|
| 134 |
+
"max_context_length": self.max_context_length,
|
| 135 |
+
"max_horizon_step": self.max_horizon_step,
|
| 136 |
+
"min_required_points": self.min_required_points,
|
| 137 |
+
}
|