timessm-2-5m / app.py
IUseAMouse's picture
Banner height and link colour
60177a1 verified
Raw History Blame Contribute Delete
31.1 kB
"""TimeSSM-10M demo: zero-shot probabilistic forecasting with RateIN, and a backtest bench.
Pick an example or bring a series, declare its sampling interval, then either forecast from
any point of its history or run a rolling backtest against the seasonal naive.
"""
import base64
import io
import os
import tempfile
from pathlib import Path
import gradio as gr
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import torch
from timessm import from_pretrained
import engine as E
HERE = Path(__file__).parent
MODELS = {"TimeSSM-10M": "IUseAMouse/timessm-10m", "TimeSSM-2.5M": "IUseAMouse/timessm-2.5m"}
DEFAULT_MODEL = "TimeSSM-10M"
MODEL_ID = MODELS[DEFAULT_MODEL]
try: # ZeroGPU hardware, when the Space has it
import spaces # before torch touches CUDA
ZERO_GPU = bool(spaces.config.Config.zero_gpu)
def gpu(seconds: int):
return spaces.GPU(duration=seconds)
except Exception: # CPU Space or local run
ZERO_GPU = False
def gpu(seconds: int):
return lambda fn: fn
DEVICE = "cuda" if ZERO_GPU or torch.cuda.is_available() else "cpu"
ENGINES = {name: E.Engine(from_pretrained(repo).to(DEVICE), device=DEVICE)
for name, repo in MODELS.items()}
MAX_CONTEXT = ENGINES[DEFAULT_MODEL].max_len
MAX_HORIZON = 720
def _engine(name: str) -> E.Engine:
return ENGINES.get(name) or ENGINES[DEFAULT_MODEL]
# label -> (season in steps: the cycle the rate knob is set on, period of the seasonal naive,
# default horizon, seconds per step or None, pandas offset)
FREQS = {
"10 seconds": (360.0, 360, 360, 10, "10s"),
"1 minute": (1440.0, 1440, 240, 60, "1min"),
"5 minutes": (288.0, 288, 288, 300, "5min"),
"10 minutes": (144.0, 144, 144, 600, "10min"),
"15 minutes": (96.0, 96, 96, 900, "15min"),
"30 minutes": (48.0, 48, 96, 1800, "30min"),
"Hourly": (24.0, 24, 168, 3600, "h"),
"Daily (weekly cycle)": (7.0, 7, 30, 86400, "D"),
"Daily (yearly cycle)": (365.0, 1, 30, 86400, "D"),
"Weekly": (365.0 / 7.0, 1, 13, 7 * 86400, "W"),
"Monthly": (12.0, 12, 12, 30.44 * 86400, "MS"),
"Quarterly": (4.0, 4, 8, 91.31 * 86400, "QS"),
"Yearly": (4.0, 1, 6, 365.25 * 86400, "YS"),
}
DEFAULT_FREQ = "Hourly"
# file -> (menu label, sampling interval, horizon)
EXAMPLES = {
"traffic_speed_5min.csv": ("Road traffic speed 路 5 min", "5 minutes", 288),
"weather_temperature_10min.csv": ("Air temperature 路 10 min", "10 minutes", 288),
"electricity_15min.csv": ("Electricity consumption 路 15 min", "15 minutes", 192),
"solar_hourly.csv": ("Solar power 路 hourly", "Hourly", 168),
"m4_hourly.csv": ("M4 路 hourly", "Hourly", 48),
"us_births_daily.csv": ("US births 路 daily", "Daily (weekly cycle)", 60),
"river_flow_daily.csv": ("River flow 路 daily", "Daily (yearly cycle)", 90),
"m4_weekly.csv": ("M4 路 weekly", "Weekly", 13),
"hospital_monthly.csv": ("Hospital patients 路 monthly", "Monthly", 12),
"m4_monthly.csv": ("M4 路 monthly", "Monthly", 18),
"m4_quarterly.csv": ("M4 路 quarterly", "Quarterly", 8),
"m4_yearly.csv": ("M4 路 yearly", "Yearly", 6),
}
EXAMPLE_BY_LABEL = {label: file for file, (label, _, _) in EXAMPLES.items()}
INK, MUTED, GRID = "#e9e6dd", "#9aa3b5", "rgba(233,230,221,0.07)"
HISTORY, FORECAST, ACTUAL, NAIVE = "#cfcbc0", "#ffb237", "#5cc8ff", "#8089a0"
BANDS = ((0, 8, 0.13, "80% interval"), (1, 7, 0.13, "60% interval"),
(2, 6, 0.15, "40% interval"), (3, 5, 0.18, "20% interval"))
# ----------------------------------------------------------------------------- data
def _read_table(text: str = "", path: str = "") -> pd.DataFrame:
if path:
return pd.read_csv(path, sep=None, engine="python")
raw = (text or "").strip()
if not raw:
raise gr.Error("Paste some values or upload a CSV file first.")
tokens = raw.replace(",", " ").replace(";", " ").split()
try: # a bare list of numbers
return pd.DataFrame({"value": [float(t) for t in tokens]})
except ValueError:
pass
first = raw.splitlines()[0]
try:
[float(t) for t in first.replace(",", " ").replace(";", " ").split()]
header = None
except ValueError:
header = "infer"
df = pd.read_csv(io.StringIO(raw), sep=None, engine="python", header=header)
df.columns = [str(c) for c in df.columns]
return df
def _split_columns(df: pd.DataFrame):
"""(timestamps or None, numeric columns). The first column that parses as dates and is
not numeric gives the time axis."""
stamps, numeric = None, []
for col in df.columns:
as_num = pd.to_numeric(df[col], errors="coerce")
if as_num.notna().mean() >= 0.5:
numeric.append(str(col))
continue
if stamps is None:
parsed = pd.to_datetime(df[col], errors="coerce")
if parsed.notna().mean() >= 0.9:
stamps = parsed
return stamps, numeric
def _guess_freq(stamps) -> str:
if stamps is None or len(stamps) < 3:
return ""
step = stamps.diff().dt.total_seconds().median()
if not np.isfinite(step) or step <= 0:
return ""
best = min(FREQS, key=lambda k: abs(np.log(FREQS[k][3] / step)))
if abs(np.log(FREQS[best][3] / step)) > 0.2:
return ""
return "Daily (weekly cycle)" if best.startswith("Daily") else best
def _series(state: dict, column: str):
if not state:
raise gr.Error("Load a series first: pick an example or bring your own data.")
df = state["df"]
column = column if column in df.columns else state["numeric"][0]
y = pd.to_numeric(df[column], errors="coerce").to_numpy(dtype=np.float32)
stamps = state["stamps"]
return y, (None if stamps is None else pd.DatetimeIndex(stamps)), column
def _axis(stamps, n: int, extra: int, freq: str):
"""x values for n observed points followed by `extra` future steps."""
if stamps is None or stamps.isna().any():
return np.arange(n + extra)
if not extra:
return stamps
try:
future = pd.date_range(stamps[-1], periods=extra + 1, freq=FREQS[freq][4])[1:]
if len(stamps) > 2 and abs((future[0] - stamps[-1]) / (stamps[-1] - stamps[-2]) - 1) > 0.5:
raise ValueError
except Exception:
future = stamps[-1] + (stamps[-1] - stamps[-2]) * np.arange(1, extra + 1)
return stamps.append(pd.DatetimeIndex(future))
def load(text: str = "", path: str = "", name: str = "", freq: str = "", horizon: int = 0):
df = _read_table(text, path)
stamps, numeric = _split_columns(df)
if not numeric:
raise gr.Error("No numeric column found in this data.")
state = {"df": df, "stamps": stamps, "numeric": numeric, "name": name or "your series"}
column = numeric[-1]
y = pd.to_numeric(df[column], errors="coerce").to_numpy(dtype=np.float32)
if np.isfinite(y).sum() < E.MIN_HISTORY:
raise gr.Error(f"The series needs at least {E.MIN_HISTORY} observed points.")
guessed = freq or _guess_freq(stamps)
freq = guessed or DEFAULT_FREQ
horizon = int(horizon or min(FREQS[freq][2], max(1, len(y) // 4)))
note = "" if guessed else " Sampling interval not detected: **set it below**."
return (state,
gr.update(choices=numeric, value=column, visible=len(numeric) > 1),
gr.update(value=freq),
gr.update(value=horizon),
gr.update(maximum=max(0, len(y) - E.MIN_HISTORY), value=0),
_summary(state, y, stamps) + note,
overview(y, None if stamps is None else pd.DatetimeIndex(stamps), state["name"]))
def load_example(label: str):
file = EXAMPLE_BY_LABEL[label]
_, freq, horizon = EXAMPLES[file]
return load(path=str(HERE / "examples" / file), name=label, freq=freq, horizon=horizon)
def load_user(text: str, file):
path = "" if file is None else (file if isinstance(file, str) else file.name)
return load(text=text, path=path, name=Path(path).name if path else "pasted series")
def _summary(state, y, stamps) -> str:
missing = int((~np.isfinite(y)).sum())
span = ""
if stamps is not None and not pd.isna(stamps.iloc[0]):
span = f" 路 {stamps.iloc[0]:%Y-%m-%d} to {stamps.iloc[-1]:%Y-%m-%d}"
gaps = f" 路 {missing:,} missing" if missing else ""
return f"**{state['name']}** 路 {len(y):,} points{span}{gaps}"
# ----------------------------------------------------------------------------- figures
def _layout(fig: go.Figure, title: str) -> go.Figure:
fig.update_layout(
title=dict(text=title, font=dict(size=15, color=INK), x=0.01, xanchor="left"),
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
font=dict(family="Ubuntu, system-ui, sans-serif", size=12, color=MUTED),
margin=dict(l=56, r=18, t=58, b=40), height=470, hovermode="x unified",
hoverlabel=dict(bgcolor="#1b2338", bordercolor="#2b3552", font=dict(color=INK)),
legend=dict(orientation="h", y=1.0, yanchor="bottom", x=1.0, xanchor="right",
bgcolor="rgba(0,0,0,0)", font=dict(color=MUTED)),
)
fig.update_xaxes(gridcolor=GRID, zeroline=False, linecolor="#2b3552", showspikes=True,
spikecolor="#55607c", spikethickness=1, spikedash="dot", spikemode="across")
fig.update_yaxes(gridcolor=GRID, zeroline=False, linecolor="#2b3552")
return fig
def overview(y, stamps, name: str) -> go.Figure:
step = max(1, len(y) // 4000)
x = _axis(stamps, len(y), 0, DEFAULT_FREQ)[::step]
fig = go.Figure(go.Scatter(x=x, y=y[::step], mode="lines", name="History",
line=dict(color=HISTORY, width=1.2)))
fig.update_layout(showlegend=False)
return _layout(fig, f"{name}: the full series")
def _fan(fig: go.Figure, x, fan: np.ndarray, legend: bool) -> None:
for lo, hi, alpha, label in BANDS:
fig.add_trace(go.Scatter(x=x, y=fan[:, lo], mode="lines", line=dict(width=0),
hoverinfo="skip", showlegend=False))
fig.add_trace(go.Scatter(x=x, y=fan[:, hi], mode="lines", line=dict(width=0),
fill="tonexty", fillcolor=f"rgba(255,178,55,{alpha})",
hoverinfo="skip", showlegend=legend and lo == 0,
name="10% to 90% quantiles"))
for q, label in ((8, "90% quantile"), (0, "10% quantile")):
fig.add_trace(go.Scatter(x=x, y=fan[:, q], mode="lines", line=dict(width=0), name=label,
showlegend=False, hovertemplate="%{y:,.4~g}"))
fig.add_trace(go.Scatter(x=x, y=fan[:, E.MID], mode="lines", name="Median forecast",
line=dict(color=FORECAST, width=2), showlegend=legend,
hovertemplate="%{y:,.4~g}"))
def figure(y, stamps, windows, h: int, freq: str, shown: int, title: str) -> go.Figure:
"""History, then for each window its fan, what was observed and the seasonal naive."""
first, last = windows[0].origin, windows[-1].origin
extra = max(0, last + h - len(y))
x = _axis(stamps, len(y), extra, freq)
lo = max(0, first - shown)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x[lo:first + 1], y=y[lo:first + 1], mode="lines", name="History",
line=dict(color=HISTORY, width=1.3), hovertemplate="%{y:,.4~g}"))
end = min(len(y), last + h)
if end > first:
fig.add_trace(go.Scatter(x=x[first:end], y=y[first:end], mode="lines", name="Observed",
line=dict(color=ACTUAL, width=1.6), hovertemplate="%{y:,.4~g}"))
for i, w in enumerate(windows):
xs = x[w.origin:w.origin + h]
_fan(fig, xs, w.forecast.fan, legend=i == 0)
fig.add_trace(go.Scatter(x=xs, y=w.naive, mode="lines", name="Seasonal naive",
line=dict(color=NAIVE, width=1.2, dash="dot"),
visible="legendonly", showlegend=i == 0, legendgroup="naive",
hovertemplate="%{y:,.4~g}"))
fig.add_vline(x=x[w.origin], line=dict(color="#55607c", width=1, dash="dash"))
return _layout(fig, title)
# ----------------------------------------------------------------------------- text blocks
def _rate(k: float) -> str:
if k == 1:
return "native rate"
return f"pooled 梅{int(k)}" if k > 1 else f"upsampled 脳{int(round(1 / k))}"
def rates_html(fc: E.Forecast, ratein: bool) -> str:
if not ratein:
return ('<div class="rates"><span class="rates-title">RateIN is off</span>'
'<span class="chip">native rate 路 100%</span></div>')
if not fc.ratios:
return ('<div class="rates"><span class="rates-title">RateIN</span><span class="chip">'
'native rate 路 100%</span><span class="rates-note">history too short to score '
'other rates</span></div>')
chips = "".join(
f'<span class="chip" title="backtest loss {fc.ratios.get(k, 1):.3f} 脳 the native rate">'
f'{_rate(k)} 路 {wk:.0%}</span>'
for k, wk in sorted(fc.weights.items(), key=lambda kv: -kv[1]))
best = min(fc.ratios, key=fc.ratios.get)
gain = 1 - fc.ratios[best]
note = (f"best single rate: {_rate(best)}, {gain:.0%} lower loss on the history"
if best != 1 and gain > 0.005 else "no rate beats the native one on the history")
return (f'<div class="rates"><span class="rates-title">RateIN reads the series at</span>'
f'{chips}<span class="rates-note">{note} 路 {len(fc.ratios)} rates scored</span></div>')
def _card(label: str, value: str, sub: str = "", tone: str = "") -> str:
return (f'<div class="card {tone}"><div class="card-label">{label}</div>'
f'<div class="card-value">{value}</div><div class="card-sub">{sub}</div></div>')
def _versus(ours: float, base: float) -> tuple:
if not (np.isfinite(ours) and np.isfinite(base) and base > 0):
return "", ""
rel = ours / base - 1
return (f"{abs(rel):.0%} {'below' if rel < 0 else 'above'} seasonal naive ({base:.3g})",
"good" if rel < 0 else "bad")
def cards_html(model: E.Score, base: E.Score, extra: str = "") -> str:
if not model.n:
return f'<div class="cards">{extra}</div>'
sub_m, tone_m = _versus(model.mase, base.mase)
sub_c, tone_c = _versus(model.crps, base.crps)
cov = model.coverage
return ('<div class="cards">'
+ _card("MASE", f"{model.mase:.3f}", sub_m, tone_m)
+ _card("CRPS", f"{model.crps:.4f}", sub_c, tone_c)
+ _card("80% interval coverage", f"{cov:.0%}", "of the observed points fall inside; "
"80% is the target")
+ extra + "</div>")
def _csv(frames: list, name: str) -> str:
path = Path(tempfile.mkdtemp()) / name
pd.concat(frames).to_csv(path, index=False)
return str(path)
def _frame(x, w: E.Window, h: int, window: int) -> pd.DataFrame:
df = pd.DataFrame(np.round(w.forecast.fan, 6),
columns=[f"q{int(q * 100):02d}" for q in E.LEVELS])
df.insert(0, "time", list(x[w.origin:w.origin + h]))
df.insert(0, "step", np.arange(1, h + 1))
df.insert(0, "window", window)
df["seasonal_naive"] = np.round(w.naive, 6)
df["observed"] = np.concatenate([w.target, np.full(h - len(w.target), np.nan)])
return df
# ----------------------------------------------------------------------------- actions
def _settings(freq: str, horizon, context):
season, m = FREQS[freq][0], FREQS[freq][1]
return season, m, int(max(1, min(int(horizon), MAX_HORIZON))), int(context)
@gpu(30)
def run_forecast(state, column, freq, horizon, context, ratein, flip, model_name, holdback, shown):
y, stamps, column = _series(state, column)
season, m, h, context = _settings(freq, horizon, context)
origin = len(y) - int(holdback)
if np.isfinite(y[:origin]).sum() < E.MIN_HISTORY:
raise gr.Error("Not enough history before this origin: move it later.")
w = E.scored(_engine(model_name), y, origin, h, season, m, flip, ratein, context)
where = "the end of the series" if not holdback else f"{int(holdback)} points before the end"
fig = figure(y, stamps, [w], h, freq, int(shown),
f"{state['name']}: {h} steps ahead from {where}")
x = _axis(stamps, len(y), max(0, origin + h - len(y)), freq)
return (fig, cards_html(w.model, w.baseline), rates_html(w.forecast, ratein),
_csv([_frame(x, w, h, 1)], "timessm_forecast.csv"))
@gpu(90)
def run_backtest(state, column, freq, horizon, context, ratein, flip, model_name, n_windows, shown,
progress=gr.Progress()):
y, stamps, column = _series(state, column)
season, m, h, context = _settings(freq, horizon, context)
n_windows = int(n_windows)
if np.isfinite(y[:len(y) - n_windows * h]).sum() < E.MIN_HISTORY:
fit = max(0, (len(y) - E.MIN_HISTORY) // h)
raise gr.Error(f"The series is too short for {n_windows} windows of {h} steps "
f"({fit} would fit): lower the horizon or the number of windows.")
progress(0, desc="Backtesting")
windows = E.backtest(_engine(model_name), y, h, season, m, n_windows, flip, ratein, context,
progress=lambda i, n: progress(i / n, desc=f"Window {i} of {n}"))
total, base = E.pooled(windows)
fig = figure(y, stamps, windows, h, freq, int(shown),
f"{state['name']}: {n_windows} rolling forecasts of {h} steps")
x = _axis(stamps, len(y), 0, freq)
rows = []
for i, w in enumerate(windows, 1):
top = max(w.forecast.weights, key=w.forecast.weights.get)
start = x[w.origin]
rows.append({
"#": i,
"Starts at": f"{start:%Y-%m-%d %H:%M}" if isinstance(start, pd.Timestamp) else int(start),
"MASE": round(w.model.mase, 3), "Naive MASE": round(w.baseline.mase, 3),
"CRPS": round(w.model.crps, 4), "Naive CRPS": round(w.baseline.crps, 4),
"80% coverage": f"{w.model.coverage:.0%}",
"Main rate": f"{_rate(top)} ({w.forecast.weights[top]:.0%})"})
wins = sum(w.model.crps < w.baseline.crps for w in windows)
info = _card("Windows won on CRPS", f"{wins} of {n_windows}",
"against the seasonal naive")
frames = [_frame(x, w, h, i) for i, w in enumerate(windows, 1)]
return (fig, cards_html(total, base, info), pd.DataFrame(rows),
_csv(frames, "timessm_backtest.csv"))
@gpu(30)
def api_forecast(values: list[float], interval: str = DEFAULT_FREQ, horizon: int = 48,
ratein: bool = True, flip: bool = True, model: str = DEFAULT_MODEL) -> dict:
"""Forecast a series given as a list of numbers (null for a missing value).
Args:
values: the history, oldest first, at least 16 observed points.
interval: the sampling interval, one of "10 seconds", "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "Hourly", "Daily (weekly cycle)", "Daily (yearly cycle)", "Weekly", "Monthly", "Quarterly", "Yearly".
horizon: steps to forecast, at most 720.
ratein: read the series at several sampling rates and average (RateIN).
flip: average with the mirrored forecast of the negated series.
model: "TimeSSM-10M" (default) or "TimeSSM-2.5M".
Returns:
quantile_levels, quantiles (one row of nine values per step), median, and rates: the weight RateIN gave each sampling rate (1 native, above 1 pooled, below 1 upsampled).
"""
if interval not in FREQS:
raise gr.Error(f"Unknown interval {interval!r}: use one of {list(FREQS)}.")
if model not in ENGINES:
raise gr.Error(f"Unknown model {model!r}: use one of {list(ENGINES)}.")
y = np.array([np.nan if v is None else float(v) for v in values], dtype=np.float32)
h = int(max(1, min(int(horizon), MAX_HORIZON)))
try:
fc = ENGINES[model].forecast(y, h, FREQS[interval][0], flip, ratein)
except ValueError as e:
raise gr.Error(str(e))
return {"quantile_levels": list(E.LEVELS), "quantiles": np.round(fc.fan, 6).tolist(),
"median": np.round(fc.median, 6).tolist(),
"rates": {str(round(k, 4)): round(w, 4) for k, w in fc.weights.items()}}
# ----------------------------------------------------------------------------- interface
def _banner() -> str:
data = base64.b64encode((HERE / "assets" / "timessm_banner.png").read_bytes()).decode()
return (f'<div class="banner"><img alt="TimeSSM, a 10M-parameter forecaster that chooses '
f'its sampling rate" src="data:image/png;base64,{data}"></div>'
'<p class="lede">Zero-shot probabilistic forecasting with '
f'<a href="https://huggingface.co/{MODEL_ID}" target="_blank">TimeSSM</a>. '
'Pick a series, forecast from any point of its history, or backtest the model '
'against the seasonal naive. Nothing is fitted to your data.</p>')
ABOUT = f"""
### What runs here
[TimeSSM-10M](https://huggingface.co/{MODEL_ID}) is a 10M-parameter forecaster: patches of 16
points, four pairs of a diagonal state-space layer (S4D) and causal attention, read twice,
and a head that gives nine quantiles for every future step in one pass. It was trained from
scratch on public series and none of the examples here were in its training data: they come
from [GIFT-Eval](https://huggingface.co/datasets/Salesforce/GiftEval) (Apache-2.0), the
benchmark the model is scored on.
The selector also offers [TimeSSM-2.5M](https://huggingface.co/{MODELS["TimeSSM-2.5M"]}), the
first release: six S4D blocks over one token per time step and a context of 1,024 points.
The demo runs it through the same inference layer as the 10M, which is not exactly the
procedure behind the scores of its own model card.
### RateIN
A forecaster reads a series best when its cycles span a comfortable number of steps. RateIN
is an inference layer that also reads the series at other sampling rates, pooled by 2 to 48
or upsampled by 2 to 4, scores every rate on windows cut from the end of the history, and
averages the forecasts with weights that follow those scores. The chips under the chart
show the rates it kept. The method is described in the
[RateIN paper](https://doi.org/10.5281/zenodo.23868904).
On the benchmark the weights are shared by all the series of a dataset. Here they are
estimated from your single series, on at most four windows, so they are noisier: on a short
or irregular series RateIN can lose to the native rate. The backtest tab shows which is true
for your data, with the switch on and off.
### Reading the scores
MASE is the absolute error of the median, divided by the error of the seasonal naive
forecast on the history. CRPS is the quantile loss summed over the nine quantiles, divided
by the sum of the absolute values. Both follow GIFT-Eval's definitions and lower is better.
The seasonal naive repeats the last cycle (the last value for weekly, yearly and
daily-with-yearly-cycle data). Scores on one series and a few windows are noisy: the
[technical report](https://doi.org/10.5281/zenodo.24202829) gives the full benchmark, where
the model scores 0.4763 in CRPS and 0.6948 in MASE relative to the seasonal naive.
### Limits
One series at a time, read as univariate. At most {MAX_CONTEXT:,} points are read at the
native rate by the 10M and 1,024 by the 2.5M (more through pooled rates) and at most {MAX_HORIZON} steps are forecast. The
sampling interval has to be declared: it sets the model's rate knob.
Code: [github.com/IUseAMouse/TimeSSM](https://github.com/IUseAMouse/TimeSSM) (Apache-2.0).
"""
CSS = """
.gradio-container { max-width: 1320px !important; margin: 0 auto !important; }
.banner { background: #0f1524; border-radius: 14px; overflow: hidden; }
.banner img { width: 100% !important; height: 220px !important; object-fit: contain !important; display: block; }
.lede { color: #aeb4c2; font-size: 1.02rem; margin: 14px 4px 4px; max-width: 70ch; }
.lede a, .prose a { color: #ffb237 !important; }
.cards { display: flex; flex-wrap: wrap; gap: 12px; margin: 4px 0; }
.card { flex: 1 1 190px; background: #0f1524; border: 1px solid #263048; border-radius: 12px;
padding: 12px 14px; }
.card-label { color: #9aa3b5; font-size: .74rem; letter-spacing: .06em; text-transform: uppercase; }
.card-value { color: #f3f0e8; font-size: 1.7rem; font-weight: 500; font-variant-numeric: tabular-nums;
line-height: 1.25; }
.card-sub { color: #9aa3b5; font-size: .82rem; }
.card.good .card-sub { color: #7ddc9a; }
.card.bad .card-sub { color: #ff9a8a; }
.rates { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 2px 0 6px; }
.rates-title { color: #9aa3b5; font-size: .86rem; }
.rates-note { color: #7f889c; font-size: .82rem; }
.chip { background: rgba(255,178,55,.12); color: #ffcf85; border: 1px solid rgba(255,178,55,.35);
border-radius: 999px; padding: 2px 10px; font-size: .84rem; font-variant-numeric: tabular-nums; }
.hint { color: #7f889c; font-size: .84rem; }
"""
THEME = gr.themes.Base(
primary_hue=gr.themes.colors.amber, neutral_hue=gr.themes.colors.slate,
font=[gr.themes.GoogleFont("Ubuntu"), "system-ui", "sans-serif"],
).set(
body_background_fill_dark="#0b101c", background_fill_primary_dark="#141b2d",
background_fill_secondary_dark="#0f1524", block_background_fill_dark="#141b2d",
border_color_primary_dark="#263048", block_border_color_dark="#263048",
input_background_fill_dark="#0f1524", body_text_color_dark="#e9e6dd",
block_label_text_color_dark="#aeb4c2", block_title_text_color_dark="#cfcbc0",
button_primary_background_fill_dark="#ffb237", button_primary_background_fill_hover_dark="#ffc566",
button_primary_text_color_dark="#0f1524", slider_color_dark="#ffb237",
block_radius="14px", button_large_radius="10px",
)
FORCE_DARK = "() => { document.body.classList.add('dark'); }"
with gr.Blocks(title="TimeSSM") as demo:
state = gr.State(None)
gr.HTML(_banner())
with gr.Row(equal_height=False):
with gr.Column(scale=4, min_width=320):
with gr.Tabs():
with gr.Tab("Examples"):
example = gr.Radio(list(EXAMPLE_BY_LABEL), label="Real series the model has never seen",
value=None)
with gr.Tab("Your data"):
upload = gr.File(label="CSV file", file_types=[".csv", ".txt", ".tsv"])
pasted = gr.Textbox(label="or paste values", lines=4,
placeholder="One value per line, comma-separated values, "
"or CSV text with a header")
load_btn = gr.Button("Load this series")
gr.HTML('<div class="hint">A date column is detected and sets the time axis. '
'Missing values can stay empty: the model reads them as missing.</div>')
model_name = gr.Radio(list(MODELS), value=DEFAULT_MODEL, label="Model")
summary = gr.Markdown("Pick an example to start.")
column = gr.Dropdown([], label="Column to forecast", visible=False)
freq = gr.Dropdown(list(FREQS), value=DEFAULT_FREQ, label="Sampling interval",
info="Sets the model's rate knob and the seasonal naive.")
horizon = gr.Slider(1, MAX_HORIZON, value=168, step=1, label="Horizon (steps)")
with gr.Accordion("Inference options", open=False):
ratein = gr.Checkbox(True, label="RateIN",
info="Read the series at several sampling rates and average.")
flip = gr.Checkbox(True, label="Sign-flip averaging",
info="Average with the mirrored forecast of the negated series.")
context = gr.Slider(64, MAX_CONTEXT, value=MAX_CONTEXT, step=64,
label="Context (points read at the native rate)")
shown = gr.Slider(32, 4096, value=512, step=32, label="History shown in the chart")
with gr.Column(scale=9, min_width=480):
with gr.Tabs():
with gr.Tab("Forecast"):
with gr.Row(equal_height=True):
holdback = gr.Slider(0, 1000, value=0, step=1, scale=4,
label="Forecast origin: points held back from the end",
info="0 forecasts the future. Hold points back to "
"compare the forecast with what happened.")
go_btn = gr.Button("Forecast", variant="primary", scale=1, min_width=140)
plot = gr.Plot(show_label=False)
rates = gr.HTML()
cards = gr.HTML()
csv = gr.File(label="Forecast (nine quantiles per step)", visible=True)
with gr.Tab("Backtest"):
with gr.Row(equal_height=True):
n_windows = gr.Slider(1, 12, value=4, step=1, scale=4,
label="Rolling windows",
info="Each window forecasts one horizon from what "
"precedes it; the last one ends the series.")
bt_btn = gr.Button("Run backtest", variant="primary", scale=1, min_width=140)
bt_plot = gr.Plot(show_label=False)
bt_cards = gr.HTML()
bt_table = gr.Dataframe(label="Per window", interactive=False, wrap=True)
bt_csv = gr.File(label="All forecasts of the backtest")
with gr.Tab("About"):
gr.Markdown(ABOUT, elem_classes="prose")
loaded = [state, column, freq, horizon, holdback, summary, plot]
example.change(load_example, example, loaded, api_name=False)
load_btn.click(load_user, [pasted, upload], loaded, api_name=False)
gr.api(api_forecast, api_name="forecast")
freq.input(lambda f: FREQS[f][2], freq, horizon, api_name=False)
model_name.change(lambda name: gr.update(maximum=_engine(name).max_len,
value=_engine(name).max_len),
model_name, context, api_name=False)
common = [state, column, freq, horizon, context, ratein, flip, model_name]
go_btn.click(run_forecast, common + [holdback, shown], [plot, cards, rates, csv],
api_name=False)
bt_btn.click(run_backtest, common + [n_windows, shown], [bt_plot, bt_cards, bt_table, bt_csv],
api_name=False)
if __name__ == "__main__":
demo.queue(default_concurrency_limit=1).launch(theme=THEME, css=CSS, js=FORCE_DARK, mcp_server=True)