Serve Timestral as an autoscaling FastAPI app that batches concurrent requests into shared forward passes.
Online forecasting API
Code available on GitHub. See Time series models for setup, the container image, and model loading.
This tutorial serves Timestral over HTTP as a Flyte app. A client posts a history and a horizon, and gets back the median and the quantiles it asked for. The app:
- loads the checkpoint once per replica, before the replica takes traffic,
- coalesces concurrent requests into batched forward passes with
DynamicBatcher, - keeps one replica warm and adds replicas as requests pile up, and
- can serve whichever checkpoint the latest batch forecasting run picked.
flowchart LR
C1[client] --> A
C2[client] --> A
C3[client] --> A
subgraph R["replica (1 to 4) · CPU"]
A["POST /forecast"] --> Q[DynamicBatcher]
Q -- "one forward pass<br/>per batch" --> M[Timestral]
end
P[(latest batch_forecasting run)] -. "champion model id" .-> R
Deploy it
Serve a fixed checkpoint:
python forecast_api.py --model mistralai/Timestral-28MOr serve the checkpoint the latest batch forecasting run picked:
python forecast_api.py --championThe command prints the app URL. Open <app-url>/docs for the interactive OpenAPI page.
Request and response
A request carries the history, oldest first, with null for missing values. It can add known-future and past-only covariates. Quantile levels must be among Timestral’s 21 levels.
class ForecastRequest(BaseModel):
values: list[float | None] = Field(
..., min_length=2, description="History, oldest first. null marks a missing value."
)
horizon: int = Field(24, ge=1, le=2048)
quantiles: list[float] = Field(default=[0.1, 0.5, 0.9])
known_covariates: list[list[float | None]] | None = Field(
None,
description="Covariates known over history and horizon: (n_covariates, len(values) + horizon).",
)
past_covariates: list[list[float | None]] | None = Field(
None, description="Covariates known over history only: (n_covariates, len(values))."
)
class ForecastResponse(BaseModel):
model: str
horizon: int
median: list[float]
quantiles: dict[str, list[float]]
curl -X POST <app-url>/forecast -H 'content-type: application/json' \
-d '{"values": [12.1, 13.4, null, 15.0, 14.2, 13.9, 15.8, 16.1], "horizon": 4, "quantiles": [0.05, 0.95]}'{
"model": "mistralai/Timestral-28M",
"horizon": 4,
"median": [15.8622, 15.5827, 15.4699, 15.4071],
"quantiles": {
"0.05": [12.5678, 11.6371, 10.858, 10.2948],
"0.95": [18.5677, 19.5193, 20.8784, 22.1719]
}
}Batch concurrent requests
One request is one series, but a batched forward pass is much cheaper per series: on a laptop CPU, Timestral-28M forecasts 64 series of 1,024 steps about 5 times faster in one batch than one at a time. DynamicBatcher starts a batch with the first waiting request, adds requests that arrive in the next 10 ms, up to 64, and hands them to _process as one batch. Each caller awaits a future for its own result.
class TimestralService:
"""Owns the model and the batcher for one app replica."""
def __init__(self, model_id: str):
self.model_id = model_id
self.forecaster = load_forecaster(model_id, API_CPUS)
# One forward pass at a time: torch already uses every core of the replica.
self.lock = asyncio.Lock()
self.batcher = DynamicBatcher(
process_fn=self._process,
max_batch_size=64,
batch_timeout_s=0.01, # wait at most 10 ms for more requests to join
)
async def _run(self, **kwargs):
async with self.lock:
return await asyncio.to_thread(self.forecaster.forecast, **kwargs)
async def _process(self, batch: list[ForecastRequest]) -> list:
"""Forecast a batch of plain (no-covariate) requests, one pass per horizon."""
import numpy as np
results: list = [None] * len(batch)
by_horizon: dict[int, list[int]] = {}
for i, request in enumerate(batch):
by_horizon.setdefault(request.horizon, []).append(i)
for horizon, indices in by_horizon.items():
histories = [batch[i].values[-MAX_CONTEXT:] for i in indices]
length = max(len(h) for h in histories)
# Left-pad shorter histories with NaN; Timestral treats NaN as missing.
context = np.full((len(indices), length), np.nan, dtype="float32")
for row, history in enumerate(histories):
context[row, length - len(history) :] = [
np.nan if v is None else v for v in history
]
forecast = await self._run(context=context, prediction_length=horizon)
quantiles = forecast.quantiles[:, 0].numpy() # (batch, horizon, 21)
for row, i in enumerate(indices):
results[i] = quantiles[row]
return results
async def forecast(self, request: ForecastRequest):
"""Return a (horizon, 21) quantile array for one request."""
import numpy as np
if request.known_covariates is None and request.past_covariates is None:
future = await self.batcher.submit(request)
return await future
# Requests with covariates have their own shapes, so they skip the batcher.
# Check the shapes before allocating anything, and trim the history to
# MAX_CONTEXT like the batched path does.
n_values = len(request.values)
known = request.known_covariates or []
past = request.past_covariates or []
if len(known) + len(past) > MAX_COVARIATES:
raise ValueError(f"At most {MAX_COVARIATES} covariates per request")
if any(len(row) != n_values + request.horizon for row in known):
raise ValueError("Each known covariate needs len(values) + horizon entries")
if any(len(row) != n_values for row in past):
raise ValueError("Each past covariate needs len(values) entries")
drop = max(0, n_values - MAX_CONTEXT)
def as_array(rows):
if rows is None:
return None
return np.array(
[[np.nan if v is None else v for v in row[drop:]] for row in rows],
dtype="float32",
)[None]
values = np.array(
[np.nan if v is None else v for v in request.values[drop:]], dtype="float32"
)
forecast = await self._run(
context=values[None],
prediction_length=request.horizon,
known_covariates=as_array(request.known_covariates),
past_covariates=as_array(request.past_covariates),
)
return forecast.quantiles[0, 0].numpy()
Histories differ in length, so _process left-pads the shorter ones with NaN. Timestral reads NaN as missing, so the padding doesn’t change the forecast. Requests with covariates have their own shapes and go straight to the model. That path checks each covariate row’s length, allows at most 16 rows, and trims the history to MAX_CONTEXT like the batched path. A lock keeps forward passes one at a time, because PyTorch already uses every CPU the replica requests.
The app
FastAPI’s lifespan hook loads the checkpoint and starts the batcher before the replica reports ready. A new replica doesn’t receive requests until the model is in memory.
service: TimestralService | None = None
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the checkpoint once per replica, before the replica reports ready.
global service
service = TimestralService(os.environ.get("TIMESTRAL_MODEL", "mistralai/Timestral-28M"))
await service.batcher.start()
yield
await service.batcher.stop()
app = FastAPI(title="Timestral forecasting API", lifespan=lifespan)
@app.get("/health")
async def health() -> dict:
return {"status": "ok", "model": service.model_id if service else None}
@app.post("/forecast", response_model=ForecastResponse)
async def forecast(request: ForecastRequest) -> ForecastResponse:
unknown = sorted(set(request.quantiles) - set(QUANTILE_LEVELS))
if unknown:
raise HTTPException(
422, f"Unsupported quantile levels {unknown}; choose from {QUANTILE_LEVELS}"
)
try:
quantiles = await service.forecast(request)
except (AssertionError, ValueError) as e:
raise HTTPException(422, str(e)) from e
def pick(level: float) -> list[float]:
return quantiles[:, QUANTILE_LEVELS.index(level)].astype(float).round(4).tolist()
return ForecastResponse(
model=service.model_id,
horizon=request.horizon,
median=pick(0.5),
quantiles={f"{level:g}": pick(level) for level in request.quantiles},
)
FastAPIAppEnvironment serves the app. The checkpoint comes in through a parameter, exposed to the process as the TIMESTRAL_MODEL environment variable.
app_env = FastAPIAppEnvironment(
name="timestral-forecast-api",
app=app,
image=timestral_image.with_pip_packages("fastapi", "uvicorn"),
resources=flyte.Resources(cpu=API_CPUS, memory="8Gi"),
parameters=[
flyte.app.Parameter(
name="model", value="mistralai/Timestral-28M", env_var="TIMESTRAL_MODEL"
),
],
# Keep one replica warm, add a replica for every 32 requests in flight (up to
# four), and scale back down after five idle minutes.
scaling=flyte.app.Scaling(
replicas=(1, 4),
metric=flyte.app.Scaling.Concurrency(val=32),
scaledown_after=300,
),
# requires_auth=False makes the endpoint public, so forecast_client.py can call
# it without a token. Anyone with the URL can then send requests and scale up
# replicas. Beyond a demo, keep the default (requires_auth=True).
requires_auth=False,
)
flyte.app.Scaling sets the replica policy:
| Setting | Value | Effect |
|---|---|---|
replicas |
(1, 4) |
One replica is always warm, so the first request never waits for a cold start. Up to four serve a spike. |
metric |
Scaling.Concurrency(val=32) |
A replica is added when each replica has more than 32 requests in flight. |
scaledown_after |
300 |
Extra replicas are removed after five idle minutes. |
If a replica crashes, the platform replaces it, and the others keep serving in the meantime.
The example sets requires_auth=False so you can call it with curl and forecast_client.py. That deploys a public, unauthenticated endpoint: anyone with the URL can send requests and scale the app up to four replicas. Beyond a demo, remove that line to require a Flyte token on every request.
Test it without deploying
smoke_test runs the service once as a task, through both the batched and the covariate paths, without deploying the app. It runs in the app’s image, so it needs nothing beyond the setup install:
flyte run forecast_api.py smoke_testTo run it on your machine instead, with --local, first install PyTorch and Timestral, pinned to the same commit as the image:
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install "timestral @ git+https://github.com/mistralai/timestral.git@a534bdbd244d64f3d9d743f46c7bf6fc330ed4ff"
flyte run --local forecast_api.py smoke_testServe the champion from the pipeline
--champion swaps the literal model ID for a flyte.app.RunOutput. At deploy time, it resolves to the first output of the latest successful run of forecast_pipeline, the champion’s Hugging Face repo ID. If no run of the pipeline has succeeded, the deploy fails.
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--model", default="mistralai/Timestral-28M")
parser.add_argument(
"--champion",
action="store_true",
help="Serve the model picked by the latest batch_forecasting.py run.",
)
args = parser.parse_args()
if args.champion:
# Resolved at deploy time to the first output of the latest pipeline run.
model = flyte.app.RunOutput(
type="string", task_name="timestral-batch-driver.forecast_pipeline"
)
else:
model = args.model
app_env.parameters = [
flyte.app.Parameter(name="model", value=model, env_var="TIMESTRAL_MODEL")
]
flyte.init_from_config(root_dir=Path(__file__).parent)
deployed = flyte.serve(app_env)
print(f"Forecast API: {deployed.url}")
print(f"OpenAPI docs: {deployed.url}/docs")
Re-run the batch pipeline when new data arrives, then redeploy with --champion. The API serves whichever checkpoint scored best on the latest data.
Load-test it
forecast_client.py sends concurrent requests with synthetic hourly histories of different lengths and reports throughput and latency:
def synthetic_history(rng: np.random.Generator, length: int) -> list[float]:
"""An hourly series with daily and weekly cycles plus noise."""
t = np.arange(length)
daily = 10 * np.sin(2 * np.pi * t / 24)
weekly = 5 * np.sin(2 * np.pi * t / 168)
return (100 + daily + weekly + rng.normal(0, 2, length)).round(3).tolist()
async def main(url: str, n_requests: int, horizon: int) -> None:
rng = np.random.default_rng(0)
async with httpx.AsyncClient(base_url=url, timeout=60) as client:
print((await client.get("/health")).json())
async def one() -> float:
body = {
"values": synthetic_history(rng, int(rng.integers(500, 3000))),
"horizon": horizon,
"quantiles": [0.1, 0.5, 0.9],
}
start = time.perf_counter()
response = await client.post("/forecast", json=body)
response.raise_for_status()
return time.perf_counter() - start
start = time.perf_counter()
latencies = await asyncio.gather(*(one() for _ in range(n_requests)))
elapsed = time.perf_counter() - start
print(f"{n_requests} forecasts in {elapsed:.2f}s ({n_requests / elapsed:.0f}/s)")
print(
f"p50 latency {1000 * np.percentile(latencies, 50):.0f} ms, p95 {1000 * np.percentile(latencies, 95):.0f} ms"
)
python forecast_client.py <app-url> --requests 500Throughput depends on the checkpoint, the history lengths, and the replica’s CPUs. Larger checkpoints and longer histories cost more per forecast, so size resources and Scaling for the checkpoint you serve. Keep more than 32 requests per replica in flight and the app adds replicas, which you can watch in the UI.