MaTaylor commited on
Commit
8dec344
·
verified ·
1 Parent(s): c701170

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +2 -1
  2. requirements.txt +3 -0
  3. service.py +234 -137
Dockerfile CHANGED
@@ -6,10 +6,11 @@ ENV PORT=7860
6
  ENV CUDA_VISIBLE_DEVICES=""
7
  ENV TRANSFORMERS_NO_ADVISORY_WARNINGS=1
8
  ENV HF_HUB_DISABLE_TELEMETRY=1
9
- ENV CHRONOS_BACKEND=baseline_cpu
10
  ENV CHRONOS_MAX_CONTEXT_LENGTH=512
11
  ENV CHRONOS_MAX_HORIZON_STEP=288
12
  ENV CHRONOS_MIN_REQUIRED_POINTS=32
 
13
  ENV UV_SYSTEM_PYTHON=1
14
 
15
  WORKDIR /app
 
6
  ENV CUDA_VISIBLE_DEVICES=""
7
  ENV TRANSFORMERS_NO_ADVISORY_WARNINGS=1
8
  ENV HF_HUB_DISABLE_TELEMETRY=1
9
+ ENV CHRONOS_BACKEND=hf_cpu
10
  ENV CHRONOS_MAX_CONTEXT_LENGTH=512
11
  ENV CHRONOS_MAX_HORIZON_STEP=288
12
  ENV CHRONOS_MIN_REQUIRED_POINTS=32
13
+ ENV CHRONOS_ALLOW_BASELINE_FALLBACK=false
14
  ENV UV_SYSTEM_PYTHON=1
15
 
16
  WORKDIR /app
requirements.txt CHANGED
@@ -1,3 +1,6 @@
1
  fastapi==0.115.12
2
  uvicorn==0.34.0
3
  pydantic==2.11.3
 
 
 
 
1
  fastapi==0.115.12
2
  uvicorn==0.34.0
3
  pydantic==2.11.3
4
+ numpy>=2.2.0
5
+ torch>=2.6.0
6
+ chronos-forecasting>=2.0.0
service.py CHANGED
@@ -1,137 +1,234 @@
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
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """HF Space service wrapper for Chronos-2."""
13
+
14
+ def __init__(self) -> None:
15
+ self.model_id = "chronos"
16
+ self.model_name = os.getenv(
17
+ "CHRONOS_MODEL_NAME",
18
+ "amazon/chronos-2",
19
+ )
20
+ self.backend = os.getenv("CHRONOS_BACKEND", "hf_cpu").strip() or "hf_cpu"
21
+ self.device = "cpu"
22
+ self.max_context_length = int(os.getenv("CHRONOS_MAX_CONTEXT_LENGTH", "512"))
23
+ self.max_horizon_step = int(os.getenv("CHRONOS_MAX_HORIZON_STEP", "288"))
24
+ self.confidence_floor = float(os.getenv("CHRONOS_CONFIDENCE_FLOOR", "0.16"))
25
+ self.confidence_ceiling = float(os.getenv("CHRONOS_CONFIDENCE_CEILING", "0.80"))
26
+ self.min_required_points = int(os.getenv("CHRONOS_MIN_REQUIRED_POINTS", "32"))
27
+ self.num_samples = int(os.getenv("CHRONOS_NUM_SAMPLES", "20"))
28
+ self.allow_baseline_fallback = os.getenv("CHRONOS_ALLOW_BASELINE_FALLBACK", "false").lower() == "true"
29
+
30
+ self.ready = False
31
+ self.load_error = ""
32
+ self._torch = None
33
+ self._pipeline = None
34
+
35
+ self._initialize_backend()
36
+
37
+ def health(self) -> HealthResponse:
38
+ return HealthResponse(
39
+ status="ok" if self.ready else "degraded",
40
+ model=self.model_name,
41
+ model_id=self.model_id,
42
+ backend=self.backend,
43
+ device=self.device,
44
+ ready=self.ready,
45
+ max_context_length=self.max_context_length,
46
+ max_horizon_step=self.max_horizon_step,
47
+ )
48
+
49
+ def predict(self, payload: PredictRequest) -> PredictResponse:
50
+ self._validate_request(payload)
51
+ closes = payload.close_prices[-payload.context_length :]
52
+
53
+ if self.backend == "hf_cpu":
54
+ if not self.ready:
55
+ raise RuntimeError(self.load_error or "chronos backend not ready")
56
+ predictions = self._predict_with_hf(closes, payload.horizons)
57
+ else:
58
+ predictions = self._predict_with_baseline(closes, payload.horizons)
59
+
60
+ return PredictResponse(model_id=self.model_id, predictions=predictions)
61
+
62
+ def _initialize_backend(self) -> None:
63
+ if self.backend == "baseline_cpu":
64
+ self.ready = True
65
+ return
66
+ if self.backend != "hf_cpu":
67
+ raise ValueError(f"unsupported CHRONOS_BACKEND={self.backend}")
68
+
69
+ try:
70
+ self._load_hf_model()
71
+ self.ready = True
72
+ except Exception as exc:
73
+ self.load_error = f"chronos hf load failed: {exc}"
74
+ if self.allow_baseline_fallback:
75
+ self.backend = "baseline_cpu"
76
+ self.ready = True
77
+ else:
78
+ self.ready = False
79
+
80
+ def _load_hf_model(self) -> None:
81
+ import torch
82
+ from chronos import Chronos2Pipeline
83
+
84
+ self._torch = torch
85
+ torch.set_num_threads(max(1, int(os.getenv("CHRONOS_TORCH_THREADS", "2"))))
86
+ self._pipeline = Chronos2Pipeline.from_pretrained(
87
+ self.model_name,
88
+ device_map="cpu",
89
+ )
90
+
91
+ def _predict_with_hf(
92
+ self, close_prices: list[float], horizons: list[int]
93
+ ) -> list[PredictionItem]:
94
+ assert self._torch is not None
95
+ assert self._pipeline is not None
96
+
97
+ torch = self._torch
98
+ context = torch.tensor(close_prices[-self.max_context_length :], dtype=torch.float32)
99
+ forecast = self._pipeline.predict(
100
+ context,
101
+ prediction_length=self.max_horizon_step,
102
+ num_samples=self.num_samples,
103
+ )
104
+
105
+ dense_mean, dense_conf = self._extract_forecast(forecast)
106
+ if len(dense_mean) < max(horizons):
107
+ raise RuntimeError(
108
+ f"Chronos output horizon {len(dense_mean)} is shorter than requested {max(horizons)}"
109
+ )
110
+
111
+ predictions: list[PredictionItem] = []
112
+ for step in horizons:
113
+ predictions.append(
114
+ PredictionItem(
115
+ step=step,
116
+ pred_price=round(max(0.00000001, float(dense_mean[step - 1])), 8),
117
+ pred_confidence=round(dense_conf[step - 1], 4),
118
+ )
119
+ )
120
+ return predictions
121
+
122
+ def _extract_forecast(self, forecast: Any) -> tuple[list[float], list[float]]:
123
+ assert self._torch is not None
124
+ torch = self._torch
125
+
126
+ if hasattr(forecast, "detach"):
127
+ tensor = forecast.detach().cpu()
128
+ else:
129
+ tensor = torch.as_tensor(forecast)
130
+
131
+ if tensor.ndim == 3:
132
+ samples = tensor[0]
133
+ mean_forecast = samples.mean(dim=0).tolist()
134
+ std_forecast = samples.std(dim=0).tolist()
135
+ elif tensor.ndim == 2:
136
+ mean_forecast = tensor[0].tolist()
137
+ std_forecast = [0.0 for _ in mean_forecast]
138
+ else:
139
+ raise RuntimeError(f"unexpected Chronos forecast shape: {tuple(tensor.shape)}")
140
+
141
+ confidence: list[float] = []
142
+ for pred, std in zip(mean_forecast, std_forecast):
143
+ dispersion = abs(float(std)) / max(abs(float(pred)), 1e-6)
144
+ raw = 1.0 / (1.0 + dispersion)
145
+ confidence.append(max(self.confidence_floor, min(self.confidence_ceiling, raw)))
146
+ return [float(item) for item in mean_forecast], confidence
147
+
148
+ def _validate_request(self, payload: PredictRequest) -> None:
149
+ if payload.context_length > self.max_context_length:
150
+ raise ValueError(
151
+ f"context_length {payload.context_length} exceeds "
152
+ f"CHRONOS_MAX_CONTEXT_LENGTH={self.max_context_length}"
153
+ )
154
+ if payload.context_length > len(payload.close_prices):
155
+ raise ValueError("context_length must not exceed len(close_prices)")
156
+ if len(payload.close_prices) < self.min_required_points:
157
+ raise ValueError(
158
+ f"at least {self.min_required_points} close prices are required "
159
+ "for Chronos stability"
160
+ )
161
+ if any(step > self.max_horizon_step for step in payload.horizons):
162
+ raise ValueError(
163
+ f"horizons contain values above CHRONOS_MAX_HORIZON_STEP={self.max_horizon_step}"
164
+ )
165
+
166
+ def _predict_with_baseline(
167
+ self, close_prices: list[float], horizons: list[int]
168
+ ) -> list[PredictionItem]:
169
+ last_price = close_prices[-1]
170
+ short_window = close_prices[-min(10, len(close_prices)) :]
171
+ mid_window = close_prices[-min(24, len(close_prices)) :]
172
+ long_window = close_prices[-min(64, len(close_prices)) :]
173
+
174
+ short_mean = mean(short_window)
175
+ mid_mean = mean(mid_window)
176
+ long_mean = mean(long_window)
177
+ momentum = 0.0 if short_mean == 0 else (last_price - short_mean) / short_mean
178
+ mean_reversion = 0.0 if long_mean == 0 else (mid_mean - long_mean) / long_mean
179
+ local_trend = self._slope(mid_window)
180
+
181
+ predictions: list[PredictionItem] = []
182
+ for step in horizons:
183
+ horizon_scale = min(1.0, math.log(step + 1.0) / 3.8)
184
+ expected_return = momentum * 0.35 + mean_reversion * 0.30 + local_trend * 0.35
185
+ expected_return *= horizon_scale
186
+
187
+ pred_price = max(0.00000001, last_price * (1.0 + expected_return))
188
+ confidence = self._baseline_confidence(close_prices, step, abs(expected_return))
189
+ predictions.append(
190
+ PredictionItem(
191
+ step=step,
192
+ pred_price=round(pred_price, 8),
193
+ pred_confidence=round(confidence, 4),
194
+ )
195
+ )
196
+ return predictions
197
+
198
+ def _baseline_confidence(
199
+ self, close_prices: list[float], step: int, expected_move_abs: float
200
+ ) -> float:
201
+ if len(close_prices) < 3:
202
+ return self.confidence_floor
203
+
204
+ changes: list[float] = []
205
+ for previous, current in zip(close_prices[:-1], close_prices[1:]):
206
+ if previous <= 0:
207
+ continue
208
+ changes.append(abs((current - previous) / previous))
209
+
210
+ realized_vol = mean(changes[-min(64, len(changes)) :]) if changes else 0.0
211
+ stability = max(0.0, 1.0 - min(realized_vol * 18.0, 1.0))
212
+ horizon_decay = 1.0 / (1.0 + math.log(step + 1.0))
213
+ raw = 0.20 + min(expected_move_abs / (realized_vol + 1e-9), 2.0) * 0.18
214
+ raw += stability * 0.20 + horizon_decay * 0.22
215
+ return max(self.confidence_floor, min(self.confidence_ceiling, raw))
216
+
217
+ @staticmethod
218
+ def _slope(values: list[float]) -> float:
219
+ if len(values) < 2 or values[0] == 0:
220
+ return 0.0
221
+ return (values[-1] - values[0]) / values[0]
222
+
223
+ def describe_runtime(self) -> dict[str, Any]:
224
+ return {
225
+ "model_id": self.model_id,
226
+ "model_name": self.model_name,
227
+ "backend": self.backend,
228
+ "device": self.device,
229
+ "ready": self.ready,
230
+ "load_error": self.load_error,
231
+ "max_context_length": self.max_context_length,
232
+ "max_horizon_step": self.max_horizon_step,
233
+ "min_required_points": self.min_required_points,
234
+ }