Frontier: deep learning and foundation models for time series
Move from local time-series models to global and foundation forecasting. Study DeepAR, N-BEATS, transformers, linear baselines, zero-shot exposure, benchmarks and critical evaluation, with local experiments.
After this lesson you can
- Implement and train a global DeepAR-style probabilistic model and N-BEATS on local GPU.
- Reproduce a linear-versus-transformer long-horizon benchmark comparison and analyze it.
- Run zero-shot foundation models locally and compare against ETS, SARIMA and global models with an honest protocol.
- Detect evaluation leakage when test series occur in foundation-model pretraining.
- Critically read forecasting papers for baselines, metrics, aggregation and possible biases.
Before you start
- 26Proper scoring rulesContinuous ranked probability scoreRolling-origin evaluationForecasting baselinesScaled error metricsETS innovations state space modelsQuantile forecasting and pinball loss
- 17LSTM cellTeacher forcing
- 18Transformer blockSinusoidal positional encodingCausal mask
- 20BPE trainingCausal language modeling objectiveSliding-window perplexity
- 15Micro framework to PyTorch correspondence
- 00Canonical training and evaluation loopDevice placement and CPU-GPU transfers
From one series to thousands
A new store has few observed sales; another has operated for years. Fitting one model per series gives each its own parameters, but a short history limits what can be learned. A global model shares parameters across many series and receives series-specific context. Sharing information can help, though it can also mix incompatible patterns.
The M4 and M5 competitions offer different contexts to test that idea. M4 gathered 100,000 series and 61 methods; its best results included combinations and hybrid methods, a reason to measure strong baselines rather than compare isolated architectures alone. M5 includes grouped sales and exogenous variables, so how forecasts are aggregated and evaluated matters. An identity embedding lets a shared function learn features of an observed series. A new series does not automatically have a trained vector: it needs an attribute representation, an unknown identity or adaptation using available data, and that case must be evaluated separately.
The comparison must keep training, validation and test separate, including horizons. If each series has a different scale, normalize it using only information available at the forecast origin. A future variable can be used only if actually known at that origin: a calendar may be available; future sales are not. A global model does not remove the need for a well-fitted local baseline.
The figure comes from a short run on real monthly M4 series: two origins per series, contexts of 24 and 96 observations, and global models trained for only 250 steps. Cases are paired across contexts and methods. Explore series and metrics without turning this small trial into a conclusion about the whole competition: in particular, it does not assume the global model wins with a short history.
With 24 months of history, mean MASE across 24 series-origin pairs is 1.661 for the DeepAR-style model, 0.992 for N-BEATS, 0.963 for seasonal naive and 0.595 for ETS. With 96 months it is 1.649, 1.099, 0.963 and 0.614 respectively. This run does not demonstrate the global advantage one might expect with little history: both local baselines beat the probabilistic model here. Values come from the cell and were reproduced twice with the same seed on this machine; they are not published results.
Global likelihood and trajectories
A global forecasting model shares a parameterized function across series , with history and available covariates . For deep probabilistic forecasting, take , where included future covariates are known at the origin. The chain rule factorizes the future law through a recurrent model:
During training, a common implementation feeds previous observed values and minimizes summed negative log-likelihoods. At inference those future values are unknown: it samples one, feeds it into the next step and repeats. This yields joint trajectories, not only independent quantiles by horizon. Observation type matters: Student t allows heavy tails on real values; negative binomial suits nonnegative counts. DeepAR trains a shared autoregressive network on related series and reports roughly 15% improvement over its baselines on the datasets considered; this is not a universal guarantee.
A common scale is in the context. Dividing inputs and forecasts by it prevents large series dominating purely by unit; to reconstruct, multiply output by the same scale. If history is all zero, an explicit convention is needed, such as . That convention makes the transformation not strictly equivariant in the degenerate case: distinguish the algebraic property for from the zero policy.
Residuals, bases and attention
In N-BEATS, each block receives a history residual and produces a backcast that is subtracted and a forecast added to the others. In the interpretable variant, learned coefficients are projected onto trend and seasonal bases; the generic architecture uses learned projections. A named decomposition does not prove causality or necessarily identify unique components.
The N-BEATS paper reports improvements of 11% over a statistical baseline and 3% over the M4 winner in its evaluation. These are results for its datasets and metrics, not figures measured here. Temporal Fusion Transformer combines variable selection, recurrent components, attention and quantile losses; its weights help inspect the model, but large attention alone is not a causal explanation. See the TFT paper.
Informer modifies self-attention with ProbSparse and emits the horizon at once; Autoformer incorporates progressive decomposition and an autocorrelation mechanism aggregating subseries by periodicities. Both are architectural proposals with specific comparisons, not guarantees of superiority over every baseline.
Patches or discrete values
Patch tokenization groups observation windows into vectors before projecting them to embeddings. In PatchTST, channels share weights and are treated separately; fewer tokens reduce attention-matrix size, but patch coverage and size matter. The paper describes both elements and evaluates eight datasets, including four ETT datasets (PatchTST).
Original Chronos uses another representation: it scales by the context mean absolute value and quantizes values to uniform centers. The paper uses a vocabulary of 4096 symbols including PAD and EOS, centers between −15 and 15, context 512 and training horizon 64. Extremes saturate; quantization loses resolution and may limit strong trends. The figure uses fewer centers and another range to make loss visible; it does not reproduce the model’s exact identifiers.
The linear-baseline debate
Comparison with linear models forces us to ask what really changes. DLinear separates a moving average from a residual and applies linear projections to both. Zeng and colleagues reported their linear family outperformed the compared transformers on nine datasets in their study. That does not prove every transformer is inferior: architectures, protocols and horizons vary. PatchTST is a later response with patches and shared weights; consult tables and conditions before comparing values.
An independent evaluation must separate scale fitting, hyperparameter selection and test in time. Using the full-series mean or deviation before splitting leaks future information. Changing context, normalization and budget simultaneously prevents attributing a difference to architecture. The short runs checked here show the programs work; they do not automatically reproduce a paper’s budget.
For example, in Zeng’s table 2 for multivariate ETTh1 at horizon 96, DLinear obtains MSE 0.375 and FEDformer 0.376; at horizon 720 they obtain 0.472 and 0.506 respectively. The authors propose that compared architectures do not exploit temporal order well and explore sensitivity to context; this interpretation is a study hypothesis, not a general impossibility of attention. In our short ETTh1 trial, mean MASE over seven channels is 1.579 for DLinear and 1.338 for PatchTransformer. One epoch and 256 windows do not reproduce the paper’s protocol: the observed ranking does not settle the debate.
To examine a later architecture, table 14 of PatchTST reports ETTh1, horizon 96 and supervised PatchTST/42 MSE of across seeds. That variant uses context 336, patches of 16 and stride 8; the figure should not be compared directly with Zeng’s context-96 figure or our reduced MASE. The paper compares different contexts and budgets and finds its model benefits from longer windows on the datasets studied.
Foundation models and leakage risk
A time-series foundation model is pretrained on many sources and can forecast a new series without updating weights. Chronos uses quantized tokens and a language model; TimesFM uses a decoder with patches; Moirai handles multivariate sets with an architecture for a variable number of channels; Lag-Llama and TiRex represent other architecture and training choices. See the original papers on Chronos, TimesFM, Moirai, Lag-Llama and TiRex. Different model versions may change interface, scale and training data.
Chronos supplements real data with KernelSynth: it combines Gaussian-process kernels to generate trends, smooth variations and periodic patterns. In its Chronos-T5 Small analysis, the most consistent improvement appears around 10% synthetic data; increasing that proportion can worsen results. This percentage belongs to its experiment and is not a rule for every domain.
Zero-shot evaluation requires distinguishing no task-specific fitting from no exposure during pretraining. If the model saw the test series, a score does not measure generalization to an unseen source. The Chronos paper separates 15 datasets present in its corpus and 27 unused for training; it also warns that absence of exact overlap does not eliminate all risks of temporal leakage or related content.
GIFT-Eval describes 23 datasets, over 144,000 series, 177 million observations and 17 baselines in the cited version. A benchmark is a concrete protocol, not a definitive list of winners. For an independent evaluation, document pretraining provenance when known, split by date or source and use your own series or series generated after the cutoff as an exposure control. A synthetic series generated for the experiment tests generalization to that synthetic distribution; it does not replace a real benchmark.
Metrics, aggregation and cost
For horizon and seasonal period , calculate MASE by series and origin:
The denominator uses only the origin’s past. If zero, MASE is undefined: report the case and do not turn it into an artificial win with an arbitrary denominator. CRPS scores a full distribution; for predictive samples , a pairwise estimate is . A point forecast treated as point mass has CRPS equal to absolute error, but that does not supply probabilistic calibration.
Arithmetic mean of errors, geometric mean of positive ratios and mean rank answer different questions. A geometric mean does not accept zero or negative values without a justified convention. Report spread by series and horizon, and choose aggregation before looking at the winner. Normalized MSE can help compare scales, but should be accompanied by errors in original units and probabilistic scores.
The next figure uses a real short run on the same 16 ETTh1 windows and seven channels. In this comparison the MASE denominator is fixed from the initial training partition rather than expanded with each origin’s past; it is identical across methods and does not use test data. Horizons overlap and the subset covers only the beginning of test; models trained for one epoch have not necessarily converged. ETTh1 may appear in foundation-model pretraining, so this comparison does not demonstrate clean zero-shot evaluation. To compare distributions with homogeneous information, the CRPS shown corresponds to an equally weighted discrete distribution formed from three quantiles: it is a coarse approximation, not exact CRPS of each continuous forecast.
With all seven channels selected, TimesFM leads all 12 combinations of four metrics and three available aggregations. The interactive shows that result as it occurred: changing criteria does not guarantee a different winner. If only channel MULL and MASE are selected, Chronos obtains 1.011 versus TimesFM’s 1.069 and moves into first place. That comparison uses the same short windows and does not prove general superiority.
Also measure memory and time with the device synchronized, stating what measurement includes, sample count and batch size. Times depend on hardware, transfers, load and version; a marginal gain may not justify a more expensive model. Do not confuse lack of calibration with point inaccuracy or extrapolate one table to a regime change.
Open questions remain: whether future covariates are actually available, how to evaluate cross-channel dependence without leaking information, how the model degrades after a regime change and whether intervals retain coverage. A local baseline may remain preferable when its error and cost meet requirements; compare recalibration and resources as well as a single mean.
Local lab: DeepAR and N-BEATS
The code downloads official M4 monthly series and reserves two origins after training windows. It trains a global LSTM with Student-t output and a reduced N-BEATS with trend and seasonal bases; both share parameters across series and use only available context. Student t is a teaching variant: DeepAR also permits other likelihoods. They are compared with seasonal naive and local ETS on the same series-origin pairs.
In ORYON_SHORT=1 mode the workflow is checked with 12 series, 250 steps and 48 samples per horizon. The reader’s run uses more series, steps and samples. Both context lengths share the MASE denominator, calculated from each origin’s entire past; if ETS fails, the whole pair is excluded from both comparisons and reported. Point-predictor CRPS values correspond to point masses, not calibrated distributions.
Short-run diagnosis. Across 24 evaluations with 24 months of history, DeepAR absolute error divided by the seasonal denominator averages 0.915 at the first horizon, 1.495 at the ninth and 2.200 at the eighteenth. Signed bias, defined as forecast minus observation divided by the same denominator, is −0.087, −0.943 and −1.276 respectively. In this sample error grows with horizon and the forecast ends below observations on average. The cell uses a small network, 250 updates and autoregressive paths; it does not explicitly include seasonal lags or calendar. These factors are possible explanations, not demonstrated causes. Compare seeds, separate validation data and budgets before attributing the difference to one of them. Horizon data for this check are kept alongside the widget in deepar-diagnostico.json.
"""M4 mensual: modelos globales sencillos y evaluación temporal sin fuga.
Instala: pip install numpy pandas scipy statsmodels torch
ORYON_SHORT=1 reduce series, pasos y muestras para comprobar el flujo.
ORYON_OUTPUT selecciona la carpeta de salida; por defecto m4_l30_resultados.
"""
import csv
import io
import json
import os
import urllib.request
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from statsmodels.tsa.holtwinters import ExponentialSmoothing
SHORT = os.environ.get('ORYON_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_OUTPUT', 'm4_l30_resultados'))
OUT.mkdir(parents=True, exist_ok=True)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
MAX_SERIES = 12 if SHORT else 160
TRAIN_STEPS = 250 if SHORT else 1500
BATCH = 24 if SHORT else 64
N_SAMPLES = 48 if SHORT else 256
CONTEXT, HORIZON, PERIOD = 96, 18, 12
HISTORIES = (24, 96)
SEED = 2630
rng = np.random.default_rng(SEED)
torch.manual_seed(SEED)
if DEVICE.type == 'cuda':
torch.cuda.manual_seed_all(SEED)
print('dispositivo, series, pasos, muestras:', DEVICE, MAX_SERIES, TRAIN_STEPS, N_SAMPLES)
BASE = 'https://raw.githubusercontent.com/Mcompetitions/M4-methods/master/Dataset'
TRAIN_URL = BASE + '/Train/Monthly-train.csv'
TEST_URL = BASE + '/Test/Monthly-test.csv'
def read_m4(url, wanted=None, limit=None):
"""Lee CSV oficial en streaming, conserva identificadores y omite huecos finales."""
result = {}
with urllib.request.urlopen(url, timeout=60) as response:
reader = csv.reader(io.TextIOWrapper(response, encoding='utf-8', newline=''))
next(reader)
for row in reader:
key = row[0].strip()
if wanted is not None and key not in wanted:
continue
values = [float(v) for v in row[1:] if v.strip() and v.strip().lower() != 'nan']
if wanted is None and len(values) < CONTEXT + 2 * HORIZON + PERIOD:
continue
result[key] = np.asarray(values, dtype=np.float64)
if limit is not None and len(result) >= limit:
break
if wanted is not None and len(result) == len(wanted):
break
return result
train_raw = read_m4(TRAIN_URL, limit=MAX_SERIES)
test_raw = read_m4(TEST_URL, wanted=set(train_raw))
ids = [key for key in train_raw if key in test_raw and len(test_raw[key]) == HORIZON]
if len(ids) < 8:
raise RuntimeError('No se obtuvo un número suficiente de series M4 válidas')
series = {key: train_raw[key] for key in ids}
print('M4 mensual: series utilizadas', len(ids), 'primer ID', ids[0], 'último ID', ids[-1])
print('Subconjunto por orden de archivo; no representa toda la competición.')
def encode_history(history):
h = np.asarray(history[-CONTEXT:], dtype=np.float64)
scale = max(float(np.mean(np.abs(h))), 1e-8)
level = float(h[-1])
values = np.zeros(CONTEXT, dtype=np.float32)
mask = np.zeros(CONTEXT, dtype=np.float32)
values[-len(h):] = (h - level) / scale
mask[-len(h):] = 1.0
return values, mask, scale, level
def training_batch(batch):
past = np.zeros((batch, CONTEXT), dtype=np.float32)
mask = np.zeros_like(past)
future = np.zeros((batch, HORIZON), dtype=np.float32)
for i in range(batch):
key = ids[int(rng.integers(len(ids)))]
# El primer origen evaluado empieza en len(train)-18.
cutoff = len(series[key]) - HORIZON
available = HISTORIES[int(rng.integers(len(HISTORIES)))]
end = int(rng.integers(available, cutoff - HORIZON + 1))
past[i], mask[i], scale, level = encode_history(series[key][end-available:end])
future[i] = (series[key][end:end+HORIZON] - level) / scale
return tuple(torch.as_tensor(a, device=DEVICE) for a in (past, mask, future))
class DeepARTipo(torch.nn.Module):
"""LSTM global autorregresivo con verosimilitud Student-t y máscara histórica."""
def __init__(self):
super().__init__()
hidden = 32 if SHORT else 64
self.rnn = torch.nn.LSTM(2, hidden, batch_first=True)
self.head = torch.nn.Linear(hidden, 3)
def params(self, states):
raw = self.head(states)
return (2.0 + torch.nn.functional.softplus(raw[..., 0]),
raw[..., 1], 0.001 + torch.nn.functional.softplus(raw[..., 2]))
def loss(self, past, mask, future):
inp = torch.cat((past, future[:, :-1]), dim=1)
available = torch.cat((mask, torch.ones_like(future[:, :-1])), dim=1)
states, _ = self.rnn(torch.stack((inp, available), dim=-1))
df, loc, scale = self.params(states[:, CONTEXT-1:])
return -torch.distributions.StudentT(df, loc, scale).log_prob(future).mean()
@torch.no_grad()
def sample(self, past, mask, samples):
_, state = self.rnn(torch.stack((past[:, :-1], mask[:, :-1]), dim=-1))
state = tuple(s.repeat_interleave(samples, dim=1) for s in state)
last = past[:, -1].repeat_interleave(samples)
lastmask = mask[:, -1].repeat_interleave(samples)
result = []
for _ in range(HORIZON):
h, state = self.rnn(torch.stack((last, lastmask), dim=-1)[:, None, :], state)
df, loc, scale = self.params(h[:, 0])
last = torch.distributions.StudentT(df, loc, scale).sample()
lastmask = torch.ones_like(last)
result.append(last.reshape(len(past), samples))
return torch.stack(result, dim=-1)
def bases():
t = torch.arange(-CONTEXT+1, HORIZON+1, dtype=torch.float32)
trend = t / CONTEXT
columns = [torch.ones_like(t), trend, trend**2]
for harmonic in (1, 2):
angle = 2 * torch.pi * harmonic * t / PERIOD
columns.extend((torch.cos(angle), torch.sin(angle)))
all_basis = torch.stack(columns, dim=0)
return all_basis[:, :CONTEXT], all_basis[:, CONTEXT:]
class BasisBlock(torch.nn.Module):
def __init__(self):
super().__init__()
width = 64 if SHORT else 128
self.net = torch.nn.Sequential(torch.nn.Linear(2*CONTEXT, width), torch.nn.ReLU(),
torch.nn.Linear(width, width), torch.nn.ReLU())
self.back = torch.nn.Linear(width, 7)
self.fore = torch.nn.Linear(width, 7)
back_basis, forecast_basis = bases()
self.register_buffer('back_basis', back_basis)
self.register_buffer('forecast_basis', forecast_basis)
def forward(self, residual, mask):
hidden = self.net(torch.cat((residual, mask), dim=-1))
return self.back(hidden) @ self.back_basis, self.fore(hidden) @ self.forecast_basis
class NBeatsBasico(torch.nn.Module):
"""Tres bloques de expansión con bases de tendencia y estacionalidad."""
def __init__(self):
super().__init__()
self.blocks = torch.nn.ModuleList([BasisBlock() for _ in range(3)])
def forward(self, past, mask):
residual = past * mask
forecast = torch.zeros((len(past), HORIZON), device=past.device)
for block in self.blocks:
back, contribution = block(residual, mask)
residual = (residual - back) * mask
forecast = forecast + contribution
return forecast
deep = DeepARTipo().to(DEVICE)
nbeats = NBeatsBasico().to(DEVICE)
optimizer_deep = torch.optim.Adam(deep.parameters(), lr=1e-3)
optimizer_nbeats = torch.optim.Adam(nbeats.parameters(), lr=1e-3)
deep.train(); nbeats.train()
for step in range(TRAIN_STEPS):
past, mask, future = training_batch(BATCH)
optimizer_deep.zero_grad(set_to_none=True)
loss_deep = deep.loss(past, mask, future)
if not torch.isfinite(loss_deep):
raise RuntimeError('Pérdida DeepAR no finita')
loss_deep.backward()
torch.nn.utils.clip_grad_norm_(deep.parameters(), 5.0)
optimizer_deep.step()
optimizer_nbeats.zero_grad(set_to_none=True)
loss_nbeats = torch.nn.functional.l1_loss(nbeats(past, mask), future)
if not torch.isfinite(loss_nbeats):
raise RuntimeError('Pérdida N-BEATS no finita')
loss_nbeats.backward()
torch.nn.utils.clip_grad_norm_(nbeats.parameters(), 5.0)
optimizer_nbeats.step()
if step in (0, TRAIN_STEPS - 1) or (step + 1) % 250 == 0:
print('paso, NLL Student-t, MAE normalizado:', step+1, float(loss_deep.detach()), float(loss_nbeats.detach()))
def crps_samples(samples, y):
"""CRPS del conjunto empírico; samples tiene forma muestras x horizontes."""
s = np.sort(np.asarray(samples, dtype=float), axis=0)
count = len(s)
first = np.mean(np.abs(s - y[None, :]), axis=0)
coeff = (2*np.arange(1, count+1) - count - 1)[:, None]
pair_term = np.sum(coeff*s, axis=0) / count**2
return first - pair_term
def seasonal_naive(history):
return np.resize(history[-PERIOD:], HORIZON)
def fit_ets(history):
"""ETS local aditivo; rechaza optimización no convergente y no la sustituye."""
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fitted = ExponentialSmoothing(history, trend='add', seasonal='add',
seasonal_periods=PERIOD,
initialization_method='estimated').fit(optimized=True)
if fitted.mle_retvals is not None and not fitted.mle_retvals.get('success', False):
return None
prediction = np.asarray(fitted.forecast(HORIZON), dtype=float)
return prediction if np.all(np.isfinite(prediction)) else None
except (ValueError, np.linalg.LinAlgError, FloatingPointError):
return None
tasks = []
for key in ids:
full = np.concatenate((series[key], test_raw[key]))
for origin_number, origin in enumerate((len(series[key])-HORIZON, len(series[key])), 1):
for history_size in HISTORIES:
history = full[origin-history_size:origin]
actual = full[origin:origin+HORIZON]
values, mask, scale, level = encode_history(history)
# El denominador usa todo el pasado disponible en el origen y es idéntico
# para las dos longitudes de contexto, sin introducir futuro en el modelo.
prior = full[:origin]
denominator = np.mean(np.abs(prior[PERIOD:] - prior[:-PERIOD]))
tasks.append(dict(key=key, origin=origin, origin_number=origin_number,
history_size=history_size, history=history, actual=actual,
values=values, mask=mask, scale=scale, level=level, denominator=denominator))
deep.eval(); nbeats.eval()
prediction_rows = []
score_rows = []
zero_scales = 0
bad_pairs = set()
fail_ets = 0
for task in tasks:
task['ets'] = fit_ets(task['history'])
if task['ets'] is None:
fail_ets += 1
bad_pairs.add((task['key'], task['origin_number']))
tasks = [task for task in tasks if (task['key'], task['origin_number']) not in bad_pairs]
if not tasks:
raise RuntimeError('Ningún par de contextos ha superado el ajuste ETS')
for start in range(0, len(tasks), 16):
batch = tasks[start:start+16]
past = torch.as_tensor(np.stack([a['values'] for a in batch]), device=DEVICE)
mask = torch.as_tensor(np.stack([a['mask'] for a in batch]), device=DEVICE)
with torch.no_grad():
samples = deep.sample(past, mask, N_SAMPLES).cpu().numpy()
nbeats_forecast = nbeats(past, mask).cpu().numpy()
for i, task in enumerate(batch):
y, history, scale, level = task['actual'], task['history'], task['scale'], task['level']
draws = samples[i] * scale + level
deep_point = np.median(draws, axis=0)
forecasts = {'DeepAR_tipo': (deep_point, crps_samples(draws, y)),
'N_BEATS_bases': (nbeats_forecast[i] * scale + level, None),
'Ingenuo_estacional': (seasonal_naive(history), None)}
forecasts['ETS_aditivo'] = (task['ets'], None)
denom = task['denominator']
if denom <= 1e-12:
zero_scales += 1
for model, (point, crps) in forecasts.items():
point = np.asarray(point, dtype=float)
if crps is None:
crps = np.abs(point-y) # CRPS de distribución puntual, no incertidumbre calibrada.
absolute = np.abs(point-y)
mase = float(np.mean(absolute)/denom) if denom > 1e-12 else np.nan
mse = float(np.mean((point-y)**2))
scaled_mse = mse / denom**2 if denom > 1e-12 else np.nan
scaled_crps = float(np.mean(crps)/denom) if denom > 1e-12 else np.nan
score_rows.append(dict(serie=task['key'], origen=task['origin'],
numero_origen=task['origin_number'], historia=task['history_size'],
modelo=model, mase=mase, crps=float(np.mean(crps)), crps_escalado=scaled_crps,
mse=mse, mse_escalado=scaled_mse,
denominador_mase=denom))
for h in range(HORIZON):
prediction_rows.append(dict(serie=task['key'], origen=task['origin'],
numero_origen=task['origin_number'], historia=task['history_size'],
modelo=model, horizonte=h+1, observado=float(y[h]),
pronostico=float(point[h]), crps=float(crps[h]),
error_cuadratico=float((point[h]-y[h])**2),
escala_historia=scale, denominador_mase=denom))
scores = pd.DataFrame(score_rows)
predictions = pd.DataFrame(prediction_rows)
scores.to_csv(OUT / 'metricas_por_serie.csv', index=False, encoding='utf-8')
predictions.to_csv(OUT / 'predicciones_por_horizonte.csv', index=False, encoding='utf-8')
summary = scores.groupby(['historia', 'modelo'], as_index=False).agg(
mase=('mase', 'mean'), crps=('crps', 'mean'), crps_escalado=('crps_escalado', 'mean'),
mse=('mse', 'mean'), mse_escalado=('mse_escalado', 'mean'), evaluaciones=('serie', 'size'))
summary.to_csv(OUT / 'resumen.csv', index=False, encoding='utf-8')
metadata = dict(fuente_entrenamiento=TRAIN_URL, fuente_prueba=TEST_URL,
seleccion='primeras series con al menos 144 observaciones y prueba mensual de 18 valores',
ids=ids, semilla=SEED, modo_corto=SHORT, dispositivo=str(DEVICE),
version_torch=torch.__version__, pasos_entrenamiento=TRAIN_STEPS,
muestras_probabilisticas=N_SAMPLES, historias=HISTORIES, horizonte=HORIZON,
fallos_ets=fail_ets, pares_excluidos_por_ets=len(bad_pairs),
protocolo='dos orígenes: 18 valores anteriores al final del entrenamiento M4 y final del entrenamiento M4',
escala='centrado en el último valor y escala media absoluta del contexto; MASE y MSE escalados por error estacional del pasado completo previo al origen')
(OUT / 'procedencia.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding='utf-8')
print('fallos de ETS, pares serie-origen excluidos, denominadores MASE nulos:', fail_ets, len(bad_pairs), zero_scales)
print('La tabla excluye ambos contextos y todos los modelos si falla ETS en uno, para emparejar la comparación.')
print(summary.to_string(index=False))
print('CRPS determinista es error absoluto: no equivale a una distribución calibrada.')
print('Escala por contexto; denominador MASE común a ambos contextos y calculado con todo el pasado del origen, sin futuro.')
print('Los dos orígenes de cada serie no son muestras independientes.')
print('Resultados breves son una verificación, no un benchmark representativo; no hay garantía de que un modelo gane.')
print('Archivos escritos en:', OUT.resolve())
del deep, nbeats, optimizer_deep, optimizer_nbeats
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.The history figure uses series-origin results saved by the previous cell. This extraction retains required columns and transforms the origin number, not its absolute time index. It writes the file beside the results; it does not need this lesson’s working data.
import json
import os
from pathlib import Path
import pandas as pd
folder=Path(os.environ.get("ORYON_OUTPUT","m4_l30_resultados"))
table=pd.read_csv(folder/"metricas_por_serie.csv")
columns=["serie","numero_origen","historia","modelo","mase","crps_escalado","mse_escalado"]
records=table[columns].rename(columns={"numero_origen":"origen"}).to_dict(orient="records")
destination=folder/"global-local-resultados.json"
destination.write_text(json.dumps(records,ensure_ascii=False),encoding="utf-8")
print("Filas por serie, origen, historia y modelo:",len(records),"archivo:",destination)npm run lab and open the connection link.Local lab: foundation models
Generate your own series in this cell and evaluate three rolling origins without updating Chronos or TimesFM weights. The short check uses two series and two origins; the full reader run uses 24 series. These are synthetic realizations created by the program with explicit seed and distribution: the result measures this family of series, not a conclusive real-data comparison. Each origin’s prefix is the only history each predictor receives.
Install the indicated versions in a local environment with compatible PyTorch and CUDA. Checkpoints download to the Hugging Face cache. Naive and ETS use normal approximations for residual spread; SARIMA uses its forecast deviation. Empirical coverage and mean pinball describe specific quantiles and do not equal exact CRPS. Bootstrap groups by series because origins within a series are correlated.
"""Forecasting zero-shot: Chronos-T5 y TimesFM 2.5 frente a tres baselines.
Dependencias: chronos-forecasting==2.3.2, timesfm==2.0.2, torch,
numpy, scipy, statsmodels. Los pesos se descargan una vez en caché de HF.
Para una prueba breve configura la variable de entorno ORYON_SHORT=1.
"""
import gc
import os
import time
import warnings
import numpy as np
import torch
from scipy.stats import norm
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from statsmodels.tsa.statespace.sarimax import SARIMAX
from chronos import ChronosPipeline
import timesfm
torch.set_num_threads(1)
np.set_printoptions(precision=6, suppress=True)
short = os.environ.get('ORYON_SHORT') == '1'
device = 'cuda' if torch.cuda.is_available() else 'cpu'
num_series = 2 if short else 24
origins = [108, 120] if short else [108, 120, 132]
horizon, season = 12, 12
quantiles = np.array([.1, .5, .9])
print('Configuración:', {'device':device,'series':num_series,'origenes':origins,
'horizonte':horizon,'semilla_datos':261130}, flush=True)
# Las trayectorias se crean aquí a partir de innovaciones nuevas. El prefijo de
# cada origen es el único dato que recibe cada predictor; no se ajusta nada al test.
rng = np.random.default_rng(261130)
def create_series():
t = np.arange(144)
result = []
for _ in range(num_series):
level = rng.uniform(20, 80)
amplitude = rng.uniform(3, 12)
phase = rng.uniform(0, 2*np.pi)
slope = rng.uniform(-.03, .06)
noise = np.zeros(len(t))
innovations = rng.normal(0, rng.uniform(.8, 2.5), len(t))
for k in range(1, len(t)):
noise[k] = .55*noise[k-1] + innovations[k]
result.append(level + slope*t + amplitude*np.sin(2*np.pi*t/season+phase) + noise)
return np.asarray(result)
series = create_series()
cases = []
for i, values in enumerate(series):
for origin in origins:
history = values[:origin].copy()
target = values[origin:origin+horizon].copy()
scale = np.mean(np.abs(history[season:] - history[:-season]))
if len(target) != horizon or scale <= 0:
raise ValueError('Horizonte o escala MASE inválidos')
cases.append((i, origin, history, target, scale))
def metrics(point, q_pred, target, scale):
point = np.asarray(point, dtype=float)
q_pred = np.asarray(q_pred, dtype=float)
if point.shape != (horizon,) or q_pred.shape != (3,horizon):
raise ValueError(f'Formas de pronóstico inválidas: {point.shape}, {q_pred.shape}')
if not np.isfinite(point).all() or not np.isfinite(q_pred).all():
raise ValueError('Pronóstico no finito')
residual = target[None,:] - q_pred
pinball = np.maximum(quantiles[:,None]*residual, (quantiles[:,None]-1)*residual)
return float(np.mean(np.abs(point-target))/scale), float(np.mean(pinball)/scale), float(np.mean((target>=q_pred[0]) & (target<=q_pred[2])))
def baseline(history, name):
if name == 'Ingenuo estacional':
point = history[-season:]
sigma = np.std(history[season:]-history[:-season], ddof=1)
spread = np.full(horizon, sigma)
elif name == 'ETS aditivo':
fit = ExponentialSmoothing(history, trend='add', seasonal='add', seasonal_periods=season,
initialization_method='estimated').fit(optimized=True)
if not fit.mle_retvals.success:
raise RuntimeError('ETS no convergió; revisa la ventana y el ajuste antes de comparar')
point = fit.forecast(horizon)
# Aproximación normal con dispersión residual fija, no distribución exacta ETS.
spread = np.full(horizon, np.std(fit.resid, ddof=1))
elif name == 'SARIMA':
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fit = SARIMAX(history, order=(1,0,0), seasonal_order=(0,1,0,season), trend='n').fit(disp=False, maxiter=100)
if not fit.mle_retvals.get('converged', False):
print('Aviso: SARIMA no convergió en una ventana', flush=True)
forecast = fit.get_forecast(horizon)
point = np.asarray(forecast.predicted_mean)
spread = np.asarray(forecast.se_mean)
else:
raise ValueError(name)
return np.asarray(point), np.asarray(point)[None,:] + norm.ppf(quantiles)[:,None]*spread[None,:]
records = {}
for name in ('Ingenuo estacional','ETS aditivo','SARIMA'):
before = time.perf_counter()
rows = []
for _, _, history, target, scale in cases:
point, q_pred = baseline(history, name)
rows.append(metrics(point, q_pred, target, scale))
records[name] = np.array(rows)
print(name, 'MASE, pinball escalado, cobertura 80 %:', records[name].mean(axis=0),
'segundos CPU, todas las ventanas:', time.perf_counter()-before, flush=True)
def sync():
if device == 'cuda':
torch.cuda.synchronize()
def gpu_peak_reset():
if device == 'cuda':
sync(); torch.cuda.reset_peak_memory_stats()
def gpu_peak():
return torch.cuda.max_memory_allocated()/2**20 if device == 'cuda' else None
torch.manual_seed(261130)
pipe = ChronosPipeline.from_pretrained('amazon/chronos-t5-tiny', device_map=device, dtype=torch.float32)
pipe.predict(torch.tensor(cases[0][2],dtype=torch.float32), prediction_length=horizon, num_samples=8)
gpu_peak_reset(); before=time.perf_counter(); rows=[]
for _, _, history, target, scale in cases:
draws=pipe.predict(torch.tensor(history,dtype=torch.float32), prediction_length=horizon,
num_samples=32 if short else 100)[0].numpy()
q_pred=np.quantile(draws, quantiles, axis=0)
rows.append(metrics(q_pred[1],q_pred,target,scale))
sync(); chronos_seconds=time.perf_counter()-before
records['Chronos T5 tiny']=np.array(rows)
print('Chronos T5 tiny MASE, pinball escalado, cobertura 80 %:',records['Chronos T5 tiny'].mean(axis=0),
'segundos con sincronización:',chronos_seconds,'pico CUDA MiB:',gpu_peak(),flush=True)
del pipe, draws, q_pred
gc.collect()
if device == 'cuda': torch.cuda.empty_cache()
model=timesfm.TimesFM_2p5_200M_torch.from_pretrained('google/timesfm-2.5-200m-pytorch',torch_compile=False)
model.compile(timesfm.ForecastConfig(max_context=160,max_horizon=horizon,per_core_batch_size=1,
normalize_inputs=True,use_continuous_quantile_head=True,
force_flip_invariance=False,infer_is_positive=False,fix_quantile_crossing=True))
model.forecast(horizon=horizon,inputs=[cases[0][2].astype(np.float32)])
gpu_peak_reset(); before=time.perf_counter(); rows=[]
for _, _, history, target, scale in cases:
point, all_q=model.forecast(horizon=horizon,inputs=[history.astype(np.float32)])
# Canal cero: media; canales 1 a 9: cuantiles .1 a .9.
q_pred=all_q[0,:, [1,5,9]]
rows.append(metrics(q_pred[1],q_pred,target,scale))
sync(); timesfm_seconds=time.perf_counter()-before
records['TimesFM 2.5']=np.array(rows)
print('TimesFM 2.5 MASE, pinball escalado, cobertura 80 %:',records['TimesFM 2.5'].mean(axis=0),
'segundos con sincronización:',timesfm_seconds,'pico CUDA MiB:',gpu_peak(),flush=True)
del model, point, all_q, q_pred
gc.collect()
if device == 'cuda': torch.cuda.empty_cache()
# Los orígenes de una misma serie están correlacionados: para comparar métodos,
# promediamos diferencias por serie y remuestreamos series completas.
reference=records['Ingenuo estacional'][:,0].reshape(num_series,len(origins)).mean(axis=1)
resampler=np.random.default_rng(261131)
for name in ('ETS aditivo','SARIMA','Chronos T5 tiny','TimesFM 2.5'):
delta=records[name][:,0].reshape(num_series,len(origins)).mean(axis=1)-reference
print(name,'diferencia MASE frente a ingenuo estacional:',delta.mean(),flush=True)
if num_series >= 8:
draws=delta[resampler.integers(0,num_series,size=(1000,num_series))].mean(axis=1)
print('intervalo bootstrap por serie, 95 %:',np.quantile(draws,[.025,.975]),flush=True)
print('La comparación describe estas series sintéticas, no es una clasificación universal.',flush=True)npm run lab and open the connection link.Local lab: DLinear versus patches
Download ETTh1 from the original repository, check its SHA-256 hash and split targets into chronological blocks of 12, 4 and 4 thirty-day blocks. Validation or test history may include known earlier observations, but each horizon belongs entirely to its partition. Fit global mean and deviation only on training; the per-window alternative uses only context. The MASE denominator is fixed from training so it is common across origins.
The full sweep compares contexts, normalizations and three seeds, chooses the epoch by validation and retains denormalized predictions by channel and origin. In ORYON_SHORT=1 mode it uses one epoch and a small chronological subset. The patch transformer is a small implementation inspired by PatchTST, not its official configuration; the short result does not reproduce the papers’ training.
"""Comparación propia de DLinear y un transformer de parches en ETTh1.
Uso completo: python linear_patch_etth1.py
Comprobación corta: ORYON_SHORT=1 python linear_patch_etth1.py
ORYON_DATA_DIR y ORYON_OUTPUT_DIR permiten elegir carpetas de datos y salida.
Requiere numpy, pandas y torch. Descarga ETTh1 de su repositorio oficial.
Los resultados son de este protocolo, no una reproducción exacta de los artículos.
"""
import copy
import hashlib
import json
import os
import random
import urllib.request
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
URL = "https://raw.githubusercontent.com/zhouhaoyi/ETDataset/main/ETT-small/ETTh1.csv"
TRAIN_END = 12 * 30 * 24
VAL_END = 16 * 30 * 24
TEST_END = 20 * 30 * 24
HORIZON = 96
PERIOD = 24
def load_data(path):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
with urllib.request.urlopen(URL, timeout=60) as response:
payload = response.read()
path.write_bytes(payload)
payload = path.read_bytes()
frame = pd.read_csv(path)
dates = pd.to_datetime(frame.pop("date"), errors="raise")
assert len(frame) >= TEST_END and len(frame.columns) == 7
assert dates.is_monotonic_increasing and not dates.duplicated().any()
assert (dates.diff().iloc[1:] == pd.Timedelta(hours=1)).all()
values = frame.to_numpy(dtype=np.float32)
assert np.isfinite(values).all()
return values, list(frame.columns), hashlib.sha256(payload).hexdigest(), dates
class Windows(Dataset):
def __init__(self, values, origins, context):
self.values = torch.from_numpy(values)
self.origins = np.asarray(origins, dtype=np.int64)
self.context = context
def __len__(self):
return len(self.origins)
def __getitem__(self, i):
t = int(self.origins[i])
return self.values[t-self.context:t], self.values[t:t+HORIZON]
def origins_for(context, end, start=None, quick=False):
# El objetivo [t,t+H) pertenece íntegramente a su partición; el contexto
# de validación y prueba puede usar observaciones anteriores disponibles.
start = context if start is None else max(start, context)
origins = np.arange(start, end - HORIZON + 1)
if quick and len(origins) > 256:
# Subconjunto fijo y distribuido cronológicamente, sin seleccionar por error.
origins = origins[np.linspace(0, len(origins)-1, 256, dtype=int)]
assert len(origins) > 0 and origins.min() >= context
assert origins.min() >= start and origins.max() + HORIZON <= end
return origins
class DLinear(nn.Module):
def __init__(self, context):
super().__init__()
self.avg = nn.AvgPool1d(25, stride=1)
self.seasonal = nn.Linear(context, HORIZON)
self.trend = nn.Linear(context, HORIZON)
def forward(self, x):
# x tiene forma lote, tiempo, canal; ambas proyecciones se comparten por canal.
x = x.transpose(1, 2)
extended = torch.cat((x[..., :1].expand(-1, -1, 12), x,
x[..., -1:].expand(-1, -1, 12)), dim=-1)
trend = self.avg(extended)
return (self.seasonal(x - trend) + self.trend(trend)).transpose(1, 2)
class PatchTransformer(nn.Module):
def __init__(self, context, patch=16, stride=8):
super().__init__()
self.patch, self.stride = patch, stride
count = (context - patch) // stride + 1
assert count > 0 and (context - patch) % stride == 0
self.embed = nn.Linear(patch, 32)
self.position = nn.Parameter(torch.zeros(1, count, 32))
layer = nn.TransformerEncoderLayer(32, 4, 64, dropout=0.1,
batch_first=True, norm_first=False)
self.encoder = nn.TransformerEncoder(layer, num_layers=2)
self.head = nn.Linear(count * 32, HORIZON)
def forward(self, x):
batch, _, channels = x.shape
# Un canal por secuencia; embedding y transformer compartidos entre canales.
patches = x.transpose(1, 2).reshape(batch * channels, -1).unfold(-1, self.patch, self.stride)
z = self.encoder(self.embed(patches) + self.position)
return self.head(z.flatten(start_dim=1)).reshape(batch, channels, HORIZON).transpose(1, 2)
class Forecast(nn.Module):
def __init__(self, model, norm):
super().__init__()
self.model, self.norm = model, norm
def forward(self, x):
if self.norm == "window":
# Solo se utilizan datos del contexto de cada origen y canal.
center = x.mean(dim=1, keepdim=True)
scale = x.std(dim=1, keepdim=True, unbiased=False).clamp_min(1e-5)
return self.model((x - center) / scale) * scale + center
return self.model(x)
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def score(model, loader, device, scales, baseline=None, collect=False):
# Totales por canal en unidades normalizadas y originales, sobre todos los
# horizontes y orígenes, que pueden solaparse.
sq = np.zeros(len(scales), dtype=np.float64)
ab = np.zeros(len(scales), dtype=np.float64)
n = 0
predicted, observed = [], []
model.eval() if model is not None else None
with torch.no_grad():
for x, y in loader:
x, y = x.to(device), y.to(device)
if baseline == "persistencia":
pred = x[:, -1:, :].expand(-1, HORIZON, -1)
elif baseline == "estacional_24":
pred = x[:, -PERIOD:, :].repeat(1, (HORIZON + PERIOD - 1) // PERIOD, 1)[:, :HORIZON, :]
else:
pred = model(x)
if collect:
predicted.append(pred.cpu().numpy())
observed.append(y.cpu().numpy())
delta = (pred - y).double()
sq += delta.square().sum(dim=(0, 1)).cpu().numpy()
ab += delta.abs().sum(dim=(0, 1)).cpu().numpy()
n += y.shape[0] * HORIZON
mse = sq / n
result = {"mse_normalized": mse.tolist(), "mse_original": (mse * scales**2).tolist(),
"mae_original": (ab / n * scales).tolist(), "mse_mean": float(mse.mean()),
"origins": n // HORIZON}
return (result, np.concatenate(predicted), np.concatenate(observed)) if collect else result
def main():
# No se usa sys.argv: el ejecutor de celdas puede añadir su propia ruta.
quick = os.environ.get("ORYON_SHORT") == "1"
data_path = Path(os.environ.get("ORYON_DATA_DIR", "data")) / "ETTh1.csv"
output_dir = Path(os.environ.get("ORYON_OUTPUT_DIR", "."))
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / "resultados_etth1.json"
torch.set_num_threads(2)
values, channels, sha, dates = load_data(data_path)
mu = values[:TRAIN_END].mean(axis=0, dtype=np.float64).astype(np.float32)
scale = values[:TRAIN_END].std(axis=0, dtype=np.float64).astype(np.float32)
mase_scale = np.abs(values[PERIOD:TRAIN_END] - values[:TRAIN_END-PERIOD]).mean(axis=0, dtype=np.float64)
assert np.all(scale > 0)
assert np.all(mase_scale > 0)
data = ((values - mu) / scale).astype(np.float32)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
contexts = [96, 336]
norms = ["global", "window"]
seeds = [7, 19] if quick else [7, 19, 29]
epochs = 1 if quick else 6
records = []
archive = {}
def save_record(record, pred, actual, origins):
key = f"r{len(records):03d}"
# Almacenamos escala original; cada eje es origen, horizonte, canal.
archive[key + "_prediction"] = (pred * scale + mu).astype(np.float32)
archive[key + "_observed"] = (actual * scale + mu).astype(np.float32)
archive[key + "_origins"] = origins
record["archive_key"] = key
record["mase"] = (np.asarray(record["mae_original"]) / mase_scale).tolist()
records.append(record)
print("Dispositivo:", device, "SHA256 ETTh1:", sha, flush=True)
print("Cortes de destino:", dates.iloc[0], dates.iloc[TRAIN_END], dates.iloc[VAL_END], dates.iloc[TEST_END-1], flush=True)
for context in contexts:
train_idx = origins_for(context, TRAIN_END, quick=quick)
val_idx = origins_for(context, VAL_END, TRAIN_END, quick)
test_idx = origins_for(context, TEST_END, VAL_END, quick)
train = Windows(data, train_idx, context)
val_loader = DataLoader(Windows(data, val_idx, context), batch_size=128)
test_loader = DataLoader(Windows(data, test_idx, context), batch_size=128)
for baseline in ("persistencia", "estacional_24"):
metrics, pred, actual = score(None, test_loader, device, scale, baseline, collect=True)
save_record(dict(model=baseline, context=context, norm="global", seed=None, **metrics), pred, actual, test_idx)
print(baseline, context, "MSE normalizado", metrics["mse_mean"], flush=True)
for norm in norms:
for seed in seeds:
for name in ("DLinear", "PatchTransformer"):
set_seed(seed)
model = Forecast(DLinear(context) if name == "DLinear" else PatchTransformer(context), norm).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
generator = torch.Generator().manual_seed(seed)
loader = DataLoader(train, batch_size=64, shuffle=True, generator=generator)
best, best_state, best_epoch = float("inf"), None, 0
for epoch in range(1, epochs+1):
model.train()
for x, y in loader:
x, y = x.to(device), y.to(device)
optimizer.zero_grad(set_to_none=True)
loss = (model(x) - y).square().mean()
loss.backward()
optimizer.step()
val_mse = score(model, val_loader, device, scale)["mse_mean"]
if val_mse < best:
best, best_epoch = val_mse, epoch
best_state = copy.deepcopy(model.state_dict())
print(name, context, norm, seed, "época", epoch, "validación", round(val_mse, 6), flush=True)
model.load_state_dict(best_state)
metrics, pred, actual = score(model, test_loader, device, scale, collect=True)
save_record(dict(model=name, context=context, norm=norm, seed=seed,
best_epoch=best_epoch, validation_mse=best, **metrics), pred, actual, test_idx)
print(name, context, norm, seed, "prueba MSE", round(metrics["mse_mean"], 6), flush=True)
del model, optimizer, best_state
if device.type == "cuda":
torch.cuda.empty_cache()
output = {"dataset": "ETTh1", "source": URL, "sha256": sha,
"channels": channels, "train_end": TRAIN_END, "validation_end": VAL_END,
"test_end": TEST_END, "horizon": HORIZON, "period": PERIOD,
"train_mean": mu.tolist(), "train_scale": scale.tolist(),
"mase_train_seasonal_mae": mase_scale.tolist(),
"forecast_file": str(output_path.with_suffix('.npz')),
"archive_axes": ["origin", "horizon", "channel"],
"quick": quick, "records": records}
np.savez_compressed(output_path.with_suffix('.npz'), **archive)
output_path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding="utf-8")
print("Guardado:", os.path.abspath(output_path), flush=True)
if __name__ == "__main__":
main()npm run lab and open the connection link.Compare forecasts on the same windows
Run the ETTh1 lab first: this cell loads its results and uses the same origins, channels, context and horizon. Fit ETS in each context and evaluate Chronos and TimesFM on the same windows. Short mode takes 16 origins; full mode up to 64. These 96-hour windows overlap, and ETTh1 is public: foundation models may have seen it in pretraining, so the comparison is not clean zero-shot.
Chronos-T5 chains blocks when asked for 96 steps, beyond its native horizon of 64. Chronos CRPS is calculated from its samples; for TimesFM a marginal distribution is approximated using its nine quantiles and flat tails. ETS is evaluated both as a point forecast and via a normal residual approximation. The interactive table uses point ETS and three common quantile representatives for all models. For MASE and MSE it uses Chronos and TimesFM medians as point forecasts; with finite second moment, predictive mean minimizes expected squared loss and could give another MSE.
"""Diagnóstico ETTh1 con los archivos del laboratorio DLinear anterior.
NO es zero-shot limpio: esta serie pública puede aparecer en preentrenamiento.
Requiere chronos-forecasting==2.3.2, timesfm==2.0.2, statsmodels y torch.
El laboratorio anterior deja ETTh1.csv en ORYON_DATA_DIR (por defecto data)
y resultados_etth1.json/.npz en ORYON_OUTPUT_DIR (por defecto directorio actual).
ORYON_SHORT=1 usa 16 orígenes; la ejecución del lector usa hasta 64.
"""
import gc
import json
import os
import time
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from scipy.special import ndtr
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from chronos import ChronosPipeline
import timesfm
torch.set_num_threads(1)
torch.manual_seed(261130)
data_dir=Path(os.environ.get('ORYON_DATA_DIR','data'))
output_dir=Path(os.environ.get('ORYON_OUTPUT_DIR','.'))
meta=json.loads((output_dir/'resultados_etth1.json').read_text(encoding='utf-8'))
archive=np.load(output_dir/'resultados_etth1.npz')
raw=pd.read_csv(data_dir/'ETTh1.csv')[meta['channels']].to_numpy(dtype=np.float64)
count=16 if os.environ.get('ORYON_SHORT')=='1' else 64
origins=archive['r000_origins'][:count]
if len(origins)==0:
raise ValueError('El archivo anterior no contiene orígenes de evaluación')
truth=archive['r000_observed'][:len(origins)]
context,horizon,season=96,96,24
histories=np.stack([raw[o-context:o].T for o in origins])
observed=np.stack([raw[o:o+horizon] for o in origins])
if histories.shape!=(len(origins),len(meta['channels']),context) or not np.allclose(observed,truth,rtol=1e-6,atol=1e-5):
raise ValueError('Las ventanas no coinciden con las observaciones del laboratorio anterior')
print('ETTh1, posible exposición en preentrenamiento:',len(origins),'orígenes, contexto y horizonte',context,horizon,flush=True)
# Revisión ETS en los mismos prefijos que reciben los modelos fundacionales.
# La incertidumbre es una aproximación normal con desviación residual fija.
ets_point=np.empty_like(observed,dtype=np.float64)
ets_sigma=np.empty((len(origins),len(meta['channels'])),dtype=np.float64)
for i,window in enumerate(histories):
for j,history in enumerate(window):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fit=ExponentialSmoothing(history,trend=None,seasonal='add',seasonal_periods=season,
initialization_method='estimated').fit(optimized=True)
if hasattr(fit.mle_retvals,'success') and not fit.mle_retvals.success:
print('Aviso: ETS no convergió, origen/canal:',i,j,flush=True)
ets_point[i,:,j]=fit.forecast(horizon)
ets_sigma[i,j]=np.std(fit.resid,ddof=1)
if not np.isfinite(ets_sigma[i,j]) or ets_sigma[i,j]<=0:
raise ValueError('La desviación residual ETS no es positiva y finita')
print('ETS origen',i+1,'/',len(origins),flush=True)
device='cuda' if torch.cuda.is_available() else 'cpu'
pipe=ChronosPipeline.from_pretrained('amazon/chronos-t5-tiny',device_map=device,dtype=torch.float32)
print('Chronos: H=96 supera su horizonte nativo 64; la biblioteca enlaza bloques con la mediana.',flush=True)
chronos_samples=[]
start=time.perf_counter()
for i,window in enumerate(histories):
draw=pipe.predict(torch.tensor(window,dtype=torch.float32),prediction_length=horizon,num_samples=32).numpy()
if draw.shape!=(len(meta['channels']),32,horizon) or not np.isfinite(draw).all():
raise ValueError('Muestras Chronos inválidas')
chronos_samples.append(draw)
print('Chronos origen',i+1,'/',len(origins),flush=True)
if device=='cuda': torch.cuda.synchronize()
print('Chronos: segundos totales sin carga del modelo:',time.perf_counter()-start,flush=True)
chronos_samples=np.stack(chronos_samples)
chronos_quantiles=np.quantile(chronos_samples,[.1,.5,.9],axis=2).transpose(1,0,3,2)
chronos_point=chronos_quantiles[:,1,:,:]
del pipe
gc.collect()
if device=='cuda': torch.cuda.empty_cache()
model=timesfm.TimesFM_2p5_200M_torch.from_pretrained('google/timesfm-2.5-200m-pytorch',torch_compile=False)
model.compile(timesfm.ForecastConfig(max_context=context,max_horizon=horizon,per_core_batch_size=7,
normalize_inputs=True,use_continuous_quantile_head=True,
force_flip_invariance=False,infer_is_positive=False,fix_quantile_crossing=True))
timesfm_quantiles=[]
start=time.perf_counter()
for i,window in enumerate(histories):
_,out=model.forecast(horizon=horizon,inputs=[a.astype(np.float32) for a in window])
if out.shape!=(len(meta['channels']),horizon,10) or not np.isfinite(out).all():
raise ValueError('Cuantiles TimesFM inválidos')
# Canal cero es media; los siguientes nueve son cuantiles .1, ..., .9.
timesfm_quantiles.append(out[:,:,1:].transpose(2,1,0))
print('TimesFM origen',i+1,'/',len(origins),flush=True)
if device=='cuda': torch.cuda.synchronize()
print('TimesFM: segundos totales sin carga del modelo:',time.perf_counter()-start,flush=True)
timesfm_quantiles=np.stack(timesfm_quantiles)
timesfm_point=timesfm_quantiles[:,4,:,:]
del model
gc.collect()
if device=='cuda': torch.cuda.empty_cache()
scale=np.asarray(meta['mase_train_seasonal_mae'])
std=np.asarray(meta['train_scale'])
if np.any(scale<=0) or np.any(std<=0):
raise ValueError('Escala de entrenamiento nula')
def point_metrics(pred):
error=pred-observed
return np.mean(np.abs(error),axis=1)/scale, np.mean(error**2,axis=1)/std**2
# CRPS de la normal aproximada de ETS; desviación igual para todos los horizontes.
z=(observed-ets_point)/ets_sigma[:,None,:]
ets_crps=np.mean(ets_sigma[:,None,:]*(z*(2*ndtr(z)-1)+2*np.exp(-z*z/2)/np.sqrt(2*np.pi)-1/np.sqrt(np.pi)),axis=1)
# CRPS empírico exacto de las 32 muestras de Chronos en cada horizonte.
target_by_channel=observed.transpose(0,2,1)[:,:,None,:]
ordered=np.sort(chronos_samples,axis=2)
weights=(2*np.arange(1,33)-33)[None,None,:,None]
chronos_crps=np.mean(np.mean(np.abs(chronos_samples-target_by_channel),axis=2)-np.sum(weights*ordered,axis=2)/32**2,axis=2)
# Cuadratura de pinball con nueve cuantiles de TimesFM y colas planas: aproximación,
# no CRPS exacto de una distribución cuya cola no ha sido publicada.
levels=np.linspace(0,1,11)
grid=np.concatenate([timesfm_quantiles[:,:1],timesfm_quantiles,timesfm_quantiles[:,-1:]],axis=1)
residual=observed[:,None,:,:]-grid
loss=np.maximum(levels[None,:,None,None]*residual,(levels[None,:,None,None]-1)*residual)
areas=((loss[:,:-1]+loss[:,1:])*np.diff(levels)[None,:,None,None]).sum(axis=1)
timesfm_crps_approx=np.mean(areas,axis=1)
payload={'origins':origins,'observed':observed,'context':histories,
'ets_prediction':ets_point,'ets_sigma':ets_sigma,'ets_crps_normal':ets_crps,
'chronos_prediction':chronos_point,'chronos_samples':chronos_samples,
'chronos_quantiles':chronos_quantiles,'chronos_crps_empirical':chronos_crps,
'timesfm_prediction':timesfm_point,'timesfm_quantiles':timesfm_quantiles,
'timesfm_crps_approx':timesfm_crps_approx}
for key,pred in [('ets',ets_point),('chronos',chronos_point),('timesfm',timesfm_point)]:
if not np.isfinite(pred).all(): raise ValueError('Predicción no finita')
payload[key+'_mase'],payload[key+'_mse_normalized']=point_metrics(pred)
print(key,'MASE medio:',payload[key+'_mase'].mean(),
'MSE normalizado medio:',payload[key+'_mse_normalized'].mean(),flush=True)
outfile=output_dir/'resultados_fundacionales_etth1.npz'
np.savez_compressed(outfile,**payload)
print('Guardado:',outfile,flush=True)
print('CRPS: ETS normal residual; Chronos empírico de 32 muestras; TimesFM cuadratura aproximada de 9 cuantiles con colas planas.',flush=True)npm run lab and open the connection link.Rebuild the table
This cell uses outputs from the previous two labs to calculate the four scores by channel and save data and hashes in the results directory. It selects the first 16 comparison origins; to reproduce the specific trial shown, run both cells in short mode with the stated versions and seeds. A full run or differences in version and hardware can generate different values.
"""Reconstruye datos de clasificación desde las dos celdas locales anteriores.
ORYON_OUTPUT_DIR indica la carpeta que contiene resultados_etth1.json/.npz y
resultados_fundacionales_etth1.npz; por defecto se usa el directorio actual.
Guarda benchmark-data.json y benchmark-provenance.json en esa carpeta.
"""
import hashlib
import json
import os
from pathlib import Path
import numpy as np
def main():
folder = Path(os.environ.get('ORYON_OUTPUT_DIR', '.'))
meta = json.loads((folder / 'resultados_etth1.json').read_text(encoding='utf-8'))
linear = np.load(folder / 'resultados_etth1.npz')
foundation = np.load(folder / 'resultados_fundacionales_etth1.npz')
assert len(foundation['origins']) >= 16
origins = foundation['origins'][:16]
y = foundation['observed'][:16].astype(np.float64)
assert y.shape == (16, 96, 7)
scale = np.asarray(meta['mase_train_seasonal_mae'])
std = np.asarray(meta['train_scale'])
assert (scale > 0).all() and (std > 0).all()
qs = np.array([0.1, 0.5, 0.9])[None, :, None, None]
def linear_pred(model, seed=None):
matches = [r for r in meta['records'] if r['model'] == model and r['context'] == 96
and (seed is None or (r['seed'] == seed and r['norm'] == 'window'))]
assert len(matches) == 1
key = matches[0]['archive_key']
assert np.array_equal(origins, linear[key + '_origins'][:16])
assert np.allclose(y, linear[key + '_observed'][:16], atol=1e-5, rtol=1e-6)
return linear[key + '_prediction'][:16].astype(np.float64)
def point(p):
return np.repeat(p[:, None, :, :], 3, axis=1)
def scores(q):
assert q.shape == (16, 3, 96, 7) and np.isfinite(q).all()
assert np.all(q[:, :-1] <= q[:, 1:] + 1e-7)
residual = y[:, None] - q
pinball = np.maximum(qs * residual, (qs - 1) * residual).mean(axis=(0, 1, 2)) / scale
first = np.abs(q - y[:, None]).mean(axis=1)
pair = np.abs(q[:, :, None] - q[:, None, :]).mean(axis=(1, 2)) / 2
discrete_crps = (first - pair).mean(axis=(0, 1)) / scale
return np.stack([np.abs(y - q[:, 1]).mean(axis=(0, 1)) / scale,
((y - q[:, 1])**2).mean(axis=(0, 1)) / std**2,
pinball, discrete_crps])
sources = [
('Ingenuo estacional', [point(linear_pred('estacional_24'))]),
('ETS', [point(foundation['ets_prediction'][:16])]),
('DLinear', [point(linear_pred('DLinear', seed)) for seed in (7, 19)]),
('PatchTransformer', [point(linear_pred('PatchTransformer', seed)) for seed in (7, 19)]),
('Chronos T5 tiny', [foundation['chronos_quantiles'][:16].astype(np.float64)]),
('TimesFM 2.5', [foundation['timesfm_quantiles'][:16, [0, 4, 8]].astype(np.float64)]),
]
rows = []
for name, draws in sources:
value = np.mean([scores(q) for q in draws], axis=0)
assert value.shape == (4, 7) and np.isfinite(value).all() and (value >= 0).all()
rows.append({'name': name, 'scores': value.tolist()})
output = {'channels': meta['channels'], 'origins': origins.tolist(), 'horizon': 96,
'context': 96, 'levels': [0.1, 0.5, 0.9], 'datasetSha256': meta['sha256'],
'models': rows}
output_path = folder / 'benchmark-data.json'
output_path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
files = ('resultados_etth1.json', 'resultados_etth1.npz', 'resultados_fundacionales_etth1.npz')
provenance = {'sha256_entradas': {name: hashlib.sha256((folder / name).read_bytes()).hexdigest() for name in files},
'sha256_salida': hashlib.sha256(output_path.read_bytes()).hexdigest(),
'numpy': np.__version__, 'datos': meta['sha256'], 'ejecucion_corta': meta['quick'],
'fuentes': 'Semillas 7 y 19 con normalización por ventana; ETS y modelos fundacionales de la celda anterior.',
'puntuaciones': 'MASE, MSE normalizado, pinball y CRPS de tres masas equiprobables; agregadas por canal.'}
(folder / 'benchmark-provenance.json').write_text(json.dumps(provenance, ensure_ascii=False, indent=2), encoding='utf-8')
for row in rows:
print(row['name'], 'medias por métrica:', np.mean(row['scores'], axis=1))
print('Guardados:', output_path, 'y benchmark-provenance.json')
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
import numpy as np
def normalize_series(x):
pass
def denormalize_series(z,scale):
passimport numpy as np
def quantize_series(x,centers):
pass
def decode_series(ids,centers,scale):
pass
def reconstruction_rmse(x,ids,centers,scale):
passComparing global and foundation models requires strong baselines, clean splits and distribution-appropriate metrics. Architecture, data exposure and budget are distinct factors. Number tokenization connects these decisions to language models; a strong baseline permits more careful attribution of improvements. For intervals under temporal change, also study adaptive conformal inference and its assumptions without assuming exchangeability.