"""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 ('
Zero-shot probabilistic forecasting with ' f'TimeSSM. ' 'Pick a series, forecast from any point of its history, or backtest the model ' 'against the seasonal naive. Nothing is fitted to your data.
') 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('