"""MLX network with NumPy forecasting adapter (Apache-2.0; see NOTICE).""" import numpy as np import mlx.core as mx import mlx.nn as nn from .layers import ResidualBlock, Transformer from .masks import key_validity, forecast_time_mask, two_stream_time_mask, variate_mask, first_observed from .scaler import causal_patch_loc_scale, apply_affine_asinh_masked, instance_norm_stats, denormalize_quantiles ROLE_TARGET, ROLE_PAST_COV, ROLE_KNOWN_COV = 0, 1, 2 class PatchRepresentation(nn.Module): def __init__(self, c): super().__init__() self.patch_proj = ResidualBlock(2 * c.patch_size, 4 * c.d_model, c.d_model, True) self.forecast_query = mx.zeros((c.d_model,)) self.patch_size = c.patch_size def __call__(self, scaled, observed): r, t = scaled.shape values = scaled.reshape(r, t // self.patch_size, self.patch_size) missing = (~observed).reshape(values.shape).astype(scaled.dtype) return self.patch_proj(mx.concatenate([values, missing], axis=-1)) class QuantileHead(nn.Module): def __init__(self, c): super().__init__() self._config = c self.projection = ResidualBlock(c.d_model, 4 * c.d_model, c.patch_size * c.num_quantiles, False) def __call__(self, x): c = self._config r, n, _ = x.shape raw = self.projection(x).reshape(r, n * c.patch_size, c.num_quantiles).astype(mx.float32) m = c.median_index gaps = [c.quantile_knots[i+1] - c.quantile_knots[i] if i < m else (c.quantile_knots[i] - c.quantile_knots[i-1] if i > m else 0) for i in range(c.num_quantiles)] inc = c.quantile_width_factor * mx.array(gaps, dtype=raw.dtype) * nn.softplus(raw) median = raw[..., m:m+1] up = mx.cumsum(inc[..., m+1:], axis=-1) down = mx.cumsum(inc[..., :m][..., ::-1], axis=-1)[..., ::-1] return mx.clip(mx.concatenate([median-down, median, median+up], axis=-1), -np.finfo(np.float32).max, np.finfo(np.float32).max) class TimestralModel(nn.Module): def __init__(self, config): super().__init__() self.config = config self.representation = PatchRepresentation(config) self.transformer = Transformer(config) self.head = QuantileHead(config) def scale(self, inputs, observed): c = self.config loc, scale = causal_patch_loc_scale(inputs, observed, c.patch_size, c.minimum_scale, c.stabilize_with_global) return apply_affine_asinh_masked(inputs, loc, scale, observed, c.use_asinh), loc, scale def _run_two_stream(self, scaled, observed, n_dec, time_mask, var_mask, positions): x_enc = self.representation(mx.array(scaled), mx.array(observed)) x_dec = mx.broadcast_to(self.representation.forecast_query[None, None], (scaled.shape[0], n_dec, self.config.d_model)) enc_len = x_enc.shape[1] x = mx.concatenate([x_enc, x_dec], axis=1) hidden = self.transformer(x, mx.array(time_mask), None if var_mask is None else mx.array(var_mask), mx.array(positions), enc_len if self.config.split_context_horizon_attn else None) out = self.head(hidden[:, enc_len:]) mx.eval(out) return np.array(out) def predict_block(self, inputs, observed, group_ids, horizon_patches, role_ids=None, known_future=None, known_future_mask=None): c = self.config ps = c.patch_size r, t = inputs.shape if t % ps or not 1 <= horizon_patches <= c.block_size: raise ValueError("context must align to patches and horizon must fit the trained block") length = t // ps with_cov = role_ids is not None and c.covariate_enabled and np.any(role_ids != ROLE_TARGET) if with_cov: hlen = horizon_patches * ps if known_future is None: known_future = np.zeros((r, hlen), inputs.dtype) known_future_mask = np.zeros((r, hlen), bool) if known_future_mask is None or known_future.shape != (r, hlen) or known_future_mask.shape != (r, hlen): raise ValueError("known future values and mask must match the decode block") values = np.concatenate([inputs, known_future], axis=-1) obs = np.concatenate([observed, known_future_mask], axis=-1) scaled, loc, scale = self.scale(values, obs) known = role_ids == ROLE_KNOWN_COV loc_c, scale_c, binary = instance_norm_stats(values, obs, c.minimum_scale) normalized = apply_affine_asinh_masked(values, loc_c, scale_c, obs, False) if c.use_asinh: normalized = np.where(obs & ~binary, np.arcsinh(normalized), normalized) scaled = np.where(known[:, None], normalized, scaled) n = length + horizon_patches per_patch = obs.reshape(r, n, ps).any(-1) valid = key_validity(per_patch, c.attend_missing_patches) tm = two_stream_time_mask(np.full(r, length), n, c.block_size, valid, known) vm = variate_mask(group_ids, valid, n, role_ids == ROLE_TARGET, known) p = np.arange(n)[None] - first_observed(per_patch, group_ids)[:, None] positions = np.concatenate([p, p], axis=-1) preds = self._run_two_stream(scaled, obs, n, tm, vm, positions)[:, t:] else: scaled, loc, scale = self.scale(inputs, observed) per_patch = observed.reshape(r, length, ps).any(-1) valid = key_validity(per_patch, c.attend_missing_patches) tm = forecast_time_mask(length, horizon_patches, valid) vm = variate_mask(group_ids, valid, horizon_patches) positions = np.arange(length + horizon_patches)[None] - first_observed(per_patch, group_ids)[:, None] preds = self._run_two_stream(scaled, observed, horizon_patches, tm, vm, positions) anchor = (length - 1) * ps return denormalize_quantiles(preds, loc[:, anchor:anchor+1, None], scale[:, anchor:anchor+1, None], c.use_asinh)