dsipts.models.timestral package

Submodules

dsipts.models.timestral.config module

Inference configuration for Timestral checkpoints.

Only the fields that change the forward pass at inference are kept. The package implements one family of Timestral models: causal modeling trained with Decoupled Horizon Forecasting (DHF), with monotone quantiles, decoded in the advancing refine frame.

class dsipts.models.timestral.config.TimestralConfig(patch_size: int, d_model: int, num_heads: int, mlp_hidden_dim: int, block_schedule: tuple[str, ...], quantile_knots: tuple[float, ...], block_size: int, context_length: int, rope_theta: float = 10000.0, rope_partial_factor: float = 0.5, norm_eps: float = 1e-06, attn_bias: bool = False, mlp_bias: bool = False, time_attn_gate: str = 'sdpa_sigmoid', variate_attn_gate: str = 'sdpa_sigmoid', minimum_scale: float = 1e-06, use_asinh: bool = True, stabilize_with_global: bool = False, covariate_enabled: bool = True, split_context_horizon_attn: bool = True, attend_missing_patches: bool = True, quantile_width_factor: float = 2.0)

Bases: object

Architecture and decode settings of a Timestral checkpoint.

patch_size

Time steps per patch.

Type:

int

d_model

Model width.

Type:

int

num_heads

Attention heads per attention sublayer.

Type:

int

mlp_hidden_dim

Hidden width of the SwiGLU MLP.

Type:

int

block_schedule

One entry per layer, each one of LAYER_KINDS.

Type:

tuple[str, …]

quantile_knots

Quantile levels of the head, symmetric about 0.5.

Type:

tuple[float, …]

block_size

Trained DHF block size K, the maximum patches decoded per block.

Type:

int

context_length

Trained context length, the default context cap.

Type:

int

quantile_width_factor

Increment scale of the monotone quantile head.

Type:

float

attend_missing_patches: bool = True
attn_bias: bool = False
block_schedule: tuple[str, ...]
block_size: int
context_length: int
covariate_enabled: bool = True
d_model: int
classmethod from_dict(d: dict[str, Any]) → TimestralConfig
property head_dim: int
classmethod load(path: str | Path) → TimestralConfig
property median_index: int
minimum_scale: float = 1e-06
mlp_bias: bool = False
mlp_hidden_dim: int
norm_eps: float = 1e-06
num_heads: int
property num_quantiles: int
patch_size: int
quantile_knots: tuple[float, ...]
quantile_width_factor: float = 2.0
property rope_dim: int

Head dimensions rotated by RoPE; the rest pass through unrotated.

rope_partial_factor: float = 0.5
rope_theta: float = 10000.0
save(path: str | Path) → None
split_context_horizon_attn: bool = True
stabilize_with_global: bool = False
property supports_known_covariates: bool

Whether the layer schedule can route a known covariate’s future to the targets.

Some time op must be followed by at least one more time op and at least one variate op; otherwise the future of a known covariate never reaches a target.

time_attn_gate: str = 'sdpa_sigmoid'
to_dict() → dict[str, Any]
use_asinh: bool = True
variate_attn_gate: str = 'sdpa_sigmoid'

dsipts.models.timestral.covariate_encoding module

Target encoding of categorical covariates.

Timestral was trained on numeric, target-scaled covariates, so a categorical covariate is turned into numbers before it reaches the model. The default is a per-series smoothed mean-target encoding: in series i, category c becomes

(smooth * mean_i + sum_{i,c}) / (smooth + count_{i,c})

over the series’ context, with smooth = 1. Missing values (NaN) form their own category. A category that never occurs in the context (for example a new value in the horizon of a known covariate) resolves to the series mean.

dsipts.models.timestral.covariate_encoding.target_encode(target_context: ndarray, past_codes: ndarray, future_codes: ndarray | None = None, smooth: float = 1.0) → tuple[ndarray, ndarray | None]

Per-series smoothed mean-target encoding.

Parameters:
  • target_context – (T,) target values. Non-finite entries are left out of the means.

  • past_codes – (T,) category codes aligned with target_context; NaN marks a missing value, which is encoded as a category of its own.

  • future_codes – Optional (H,) codes over the horizon (known covariates).

  • smooth – Weight of the series mean in each category mean.

Returns:

(encoded_past, encoded_future) float32 arrays; encoded_future is None when future_codes is None.

dsipts.models.timestral.forecaster module

Probabilistic forecasting with Timestral, including the clampsym test-time augmentation.

TimestralForecaster.forecast takes a context (B, V, T) (series, variates, time; NaN marks a missing value) and returns quantile forecasts (B, V, H, Q). Horizons longer than one decode block are forecast block by block, feeding each block’s median back as context.

Clampsym (both options on by default):

  • Symmetric averaging forecasts the context and its negation, reflects the second forecast back (-Q(1 - p)), and averages the two. Every covariate row is negated with the context: numeric covariates, 0/1 indicators, target encodings and raw codes.

  • Non-negative clipping clamps the forecast at 0 for every series whose observed context is entirely non-negative.

Categorical covariates are target-encoded against the series’ forward-filled context (see timestral.covariate_encoding) and then handled like numeric covariates.

class dsipts.models.timestral.forecaster.Forecast(quantiles: Tensor, quantile_levels: tuple[float, ...])

Bases: object

Quantile forecast.

quantiles

(B, V, H, Q) forecast values, sorted along the quantile axis.

Type:

torch.Tensor

quantile_levels

The Q probability levels.

Type:

tuple[float, …]

property median: Tensor

(B, V, H) median forecast.

quantile(level: float) → Tensor

(B, V, H) forecast at one of the model’s quantile levels.

quantile_levels: tuple[float, ...]
quantiles: Tensor
class dsipts.models.timestral.forecaster.TimestralForecaster(model: TimestralModel, max_context: int | None = None, per_shot_horizon_patches: int = 32, quantile_real_cap_k: float = 10000.0, extreme_value_threshold: float = 1e+30)

Bases: object

Block-autoregressive quantile forecaster around a TimestralModel.

Parameters:
  • model – The network.

  • max_context – Context cap in time steps (most recent kept); defaults to the trained context length.

  • per_shot_horizon_patches – Patches decoded per block, capped at the trained block size.

  • quantile_real_cap_k – Clamp forecasts to [min - k * s, max + k * s] of the observed context, s being the scale of the last context patch. 0 disables.

  • extreme_value_threshold – Fed-back medians at or above this magnitude become 0.

property device: device
forecast(context: Tensor | ndarray, prediction_length: int, observation_mask: Tensor | ndarray | None = None, past_covariates: Tensor | ndarray | None = None, known_covariates: Tensor | ndarray | None = None, categorical_past_covariates: Tensor | ndarray | None = None, categorical_known_covariates: Tensor | ndarray | None = None, symmetric_averaging: bool = True, clip_nonnegative: bool = True) → Forecast

Forecast prediction_length steps after context.

Parameters:
  • context – (B, V, T), (B, T) (one variate) or (T,) (one series). NaN marks a missing value. The variates of a series are forecast jointly.

  • prediction_length – Horizon in time steps.

  • observation_mask – Optional boolean mask shaped like context; False marks additional missing values.

  • past_covariates – (B, C_past, T) covariates known over the context only.

  • known_covariates – (B, C_known, T + prediction_length) covariates known over the context and the horizon.

  • categorical_past_covariates – (B, C, T) category codes (any numbers; NaN marks a missing value) known over the context only.

  • categorical_known_covariates – (B, C, T + prediction_length) category codes known over the context and the horizon. Categorical covariates are target-encoded per series against the forward-filled target context. A series with several target variates has no single target to encode against, so its codes are used as is.

  • symmetric_averaging – Average with the reflected forecast of -context, with every covariate row negated too.

  • clip_nonnegative – Clamp at 0 the series whose observed context is non-negative.

Returns:

A Forecast with quantiles (B, V, prediction_length, Q).

classmethod from_pretrained(path_or_repo_id: str | Path, device: str | device = 'cpu', max_context: int | None = None, per_shot_horizon_patches: int = 32, quantile_real_cap_k: float = 10000.0, revision: str | None = None, cache_dir: str | Path | None = None, token: str | bool | None = None, local_files_only: bool = False) → TimestralForecaster

Load an exported checkpoint (config.json + model.safetensors).

path_or_repo_id is a local directory or a Hugging Face Hub repo id. revision, cache_dir, token and local_files_only only apply to Hub repos.

property patch_size: int
property supports_covariates: bool
property supports_known_covariates: bool
dsipts.models.timestral.forecaster.ffill_with_mask(inputs: Tensor, mask: Tensor) → Tensor

Forward-fill unobserved positions; leading unobserved positions become 0.

dsipts.models.timestral.forecaster.nonnegative_context(inputs: Tensor, observation_mask: Tensor) → Tensor

(B, V): whether every observed context value is non-negative (and one exists).

dsipts.models.timestral.forecaster.pad_to_patch(inputs: Tensor, mask: Tensor, patch_size: int) → tuple[Tensor, Tensor]

Left-pad to a multiple of patch_size; padding is 0 and unobserved.

dsipts.models.timestral.forecaster.replace_extreme_values(x: Tensor, threshold: float, replacement: float = 0.0) → Tensor

dsipts.models.timestral.layers module

Transformer layers for Timestral inference.

Parameter names match the released weights, so they load with strict=True. All tensors use the packed layout: one row per variate of every series in the batch, (R, N, D) with N patches. Time attention runs per row over patches; variate attention runs per patch over the rows of the same series.

class dsipts.models.timestral.layers.Attention(embed_dim: int, num_heads: int, is_time: bool, use_bias: bool, gate: str)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor, mask: Tensor | TwoStreamMask | None, cos: Tensor, sin: Tensor) → Tensor

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class dsipts.models.timestral.layers.FusedSwiGLU(embed_dim: int, hidden_dim: int, use_bias: bool)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor) → Tensor

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class dsipts.models.timestral.layers.RMSNorm(dim: int, eps: float)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor) → Tensor

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class dsipts.models.timestral.layers.ResidualBlock(input_dims: int, hidden_dims: int, output_dims: int, use_bias: bool)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor) → Tensor

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class dsipts.models.timestral.layers.SinCosRoPE(dim: int, base: float, rotary_dim: int)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor, position_ids: Tensor) → tuple[Tensor, Tensor]

Return (cos, sin) tables, each (R, N, head_dim), for integer position_ids (R, N).

inv_freq: Tensor
rebuild_inv_freq() → None

Recompute the table on the buffer’s current device.

A table computed on CPU and then moved could differ in the last bit.

class dsipts.models.timestral.layers.Transformer(block_schedule: tuple[str, ...], embed_dim: int, num_heads: int, mlp_hidden_dim: int, rope_theta: float, rope_dim: int, norm_eps: float, attn_bias: bool, mlp_bias: bool, time_attn_gate: str, variate_attn_gate: str)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor, time_mask: Tensor | TwoStreamMask | None, variate_mask: Tensor | None, positions: Tensor) → Tensor

Run the stack on x (R, N, D) with integer time positions (R, N).

class dsipts.models.timestral.layers.TransformerBlock(kind: str, embed_dim: int, num_heads: int, mlp_hidden_dim: int, norm_eps: float, attn_bias: bool, mlp_bias: bool, time_attn_gate: str, variate_attn_gate: str)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor, time_mask: Tensor | TwoStreamMask | None, variate_mask: Tensor | None, cos: Tensor, sin: Tensor) → Tensor

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

class dsipts.models.timestral.layers.TwoStreamMask(mask: Tensor, enc_len: int)

Bases: object

Time mask over the [Enc ; Dec] sequence plus its split point.

Attention with this mask runs two query passes: context queries [:enc_len] over context keys only, and horizon queries [enc_len:] over all keys. This skips the always-empty context-to-horizon quadrant.

enc_len: int
mask: Tensor

dsipts.models.timestral.loading module

Load exported checkpoints: a directory with config.json and model.safetensors, either on disk or in a Hugging Face Hub repo.

dsipts.models.timestral.loading.load_model(path_or_repo_id: str | Path, device: str | device = 'cpu', dtype: dtype = torch.float32, **hub_kwargs) → TimestralModel

Build the model from config.json and load model.safetensors.

path_or_repo_id is a local directory or a Hugging Face Hub repo id; hub_kwargs go to resolve_checkpoint. Weights load with strict=True. Inference was validated in float32.

dsipts.models.timestral.loading.resolve_checkpoint(path_or_repo_id: str | Path, revision: str | None = None, cache_dir: str | Path | None = None, token: str | bool | None = None, local_files_only: bool = False) → Path

Return a local directory holding config.json and model.safetensors.

An existing directory is used as is. Anything else is a Hugging Face Hub repo id (e.g. org/timestral-108m): its two files are downloaded to the Hub cache, or read from it when local_files_only (or HF_HUB_OFFLINE=1) is set.

dsipts.models.timestral.masks module

Attention masks and time positions for Decoupled Horizon Forecasting (DHF) decoding.

The sequence is [Enc ; Dec]: encoder tokens embed the observed context patches; decoder tokens are forecast queries for the horizon patches. All masks are boolean, True meaning “may attend”.

dsipts.models.timestral.masks.build_forecast_positions(context_len: int, horizon: int, first_obs: Tensor) → Tensor

(R, L+h) time positions 0..L+h-1, anchored at each row’s first observed patch.

dsipts.models.timestral.masks.build_forecast_time_mask(context_len: int, horizon: int, key_valid: Tensor, device: device) → Tensor

(R, 1, L+h, L+h) time mask for one block without covariates.

The encoder is causal; every decoder token reads the whole valid context and its own causal decoder chain; the context never reads the horizon.

dsipts.models.timestral.masks.build_two_stream_positions(n_patches: int, first_obs: Tensor) → Tensor

(R, 2N) positions: encoder and decoder token of the same patch share a time.

dsipts.models.timestral.masks.build_two_stream_time_mask(min_context: Tensor, n_patches: int, block_size: int, key_valid: Tensor, bidirectional_rows: Tensor | None) → Tensor

(R, 1, 2N, 2N) time mask over a full [Enc ; Dec] window (the covariate path).

  • Enc to Enc: causal over valid keys; full (non-causal) for bidirectional_rows, the known-future covariates.

  • Enc to Dec: never.

  • Dec to Enc: a decoder token in the block anchored at b reads valid Enc[j], j < b.

  • Dec to Dec: causal within the same block; every decoder token reads itself.

dsipts.models.timestral.masks.build_two_stream_variate_mask(group_ids: Tensor, enc_key_valid: Tensor, n_dec: int, target_rows: Tensor | None = None, bidirectional_rows: Tensor | None = None) → Tensor | None

(N_enc + N_dec, 1, R, R) variate mask, or None for a single row.

A row reads another row of the same series; on encoder slots the key row must also be a valid key. The firewalls apply on every slot; the diagonal is always open.

dsipts.models.timestral.masks.compute_block_layout(min_context: Tensor, n_patches: int, block_size: int) → tuple[Tensor, Tensor]

Per decoder position: the anchor of its block and whether it is active (p >= s).

dsipts.models.timestral.masks.compute_enc_key_validity(obs_per_patch: Tensor, attend_missing: bool) → Tensor

(R, N) encoder key validity.

A patch is a valid key if it is observed, or if attend_missing is set and the row’s series has started at or before it. Leading all-unobserved patches are left-padding and are never valid keys.

dsipts.models.timestral.masks.enc_causal_mask(key_valid: Tensor) → Tensor

(R, L, L) causal encoder mask over valid keys, with the diagonal always open.

dsipts.models.timestral.masks.group_first_observed_patch(obs_per_patch: Tensor, inverse: Tensor, num_groups: int) → Tensor

(num_groups,) index of the first patch any row of the group observes (0 if none).

dsipts.models.timestral.masks.variate_firewall(r: int, device: device, target_rows: Tensor | None, bidirectional_rows: Tensor | None) → Tensor | None

(R, R) forbidden query-to-key row pairs, or None.

  • A covariate row may not read a target row (covariates are exogenous).

  • A known-future (bidirectional) row may not read a causal row. Without this, a covariate’s view of the future could relay a target’s own future back into it.

dsipts.models.timestral.model module

The Timestral network and its single-block forecast primitive.

The model normalizes each row causally per patch, embeds patches from [values, missing] channels, runs a time/variate transformer over [Enc ; Dec] tokens (context patches followed by learned forecast-query tokens), and reads quantiles for every horizon time step from the decoder tokens.

class dsipts.models.timestral.model.PatchRepresentation(patch_size: int, d_model: int)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forecast_tokens(rows: int, n_patches: int) → Tensor
forward(scaled: Tensor, observed: Tensor) → Tensor

(R, T) normalized values and observation mask to (R, T / patch_size, d_model).

class dsipts.models.timestral.model.QuantileHead(config: TimestralConfig)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x: Tensor) → Tensor

(R, N, D) to normalized quantiles (R, N * patch_size, Q) in at least fp32.

class dsipts.models.timestral.model.TimestralModel(config: TimestralConfig)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

predict_block(inputs: Tensor, observed: Tensor, group_ids: Tensor, horizon_patches: int, role_ids: Tensor | None = None, known_future: Tensor | None = None, known_future_mask: Tensor | None = None) → Tensor

Forecast one block of horizon_patches patches after a packed context.

Parameters:
  • inputs – (R, T) context values, T a multiple of the patch size.

  • observed – (R, T) observation mask.

  • group_ids – (R,) series id per row; rows of one series attend each other.

  • horizon_patches – Number of patches to forecast.

  • role_ids – (R,) row roles (ROLE_TARGET, ROLE_PAST_COV, ROLE_KNOWN_COV), or None when every row is a target.

  • known_future – (R, horizon_patches * patch_size) known-future covariate values over this block; zeros on other rows.

  • known_future_mask – Observation mask for known_future.

Returns:

Raw-space quantiles (R, horizon_patches * patch_size, Q), non-decreasing along Q.

scale(inputs: Tensor, observed: Tensor) → tuple[Tensor, Tensor, Tensor]

Causal per-patch normalization of packed (R, T) rows.

Returns (scaled, loc, scale), each (R, T).

dsipts.models.timestral.model.monotone_quantiles(raw: Tensor, levels: tuple[float, ...], width_factor: float) → Tensor

Non-crossing quantiles from raw head outputs along the last axis (monotone_cumsum).

The median channel is free. The others fan out from it as median -/+ cumsum(width_factor * dp * softplus(raw)), dp being the probability gap to the next level inward, so unequal knot spacing is respected.

dsipts.models.timestral.scaler module

Normalization for Timestral: causal per-patch mean/std scaling with an asinh squash.

Each patch is normalized with the mean and std of every observed value up to the end of that patch, so the context never sees future statistics. Forecasts come back in the normalized (asinh) space of the last context patch and are inverted with sinh.

dsipts.models.timestral.scaler.advancing_block_frames(context: Tensor, observation_mask: Tensor, sinh_median: Tensor, minimum_scale: float) → tuple[Tensor, Tensor]

Per-patch (loc, scale) of a decoded block in the advancing refine frame, each (R, H) float64.

Horizon patch j is normalized with the statistics of the observed context plus the block’s medians of patches 0..j-1, each median denormalized in its own frame before it is folded in. With perfect medians this is causal per-patch normalization of the true series. The statistics are float64 Welford states, accumulated exactly as in training.

Parameters:
  • context – (R, T) block context, T a multiple of the patch size.

  • observation_mask – (R, T).

  • sinh_median – (R, H, patch_size) the block’s median in the last context patch’s frame with the asinh undone, (median - loc) / scale.

  • minimum_scale – Scale floor.

dsipts.models.timestral.scaler.apply_affine_asinh_masked(data: Tensor, loc: Tensor, scale: Tensor, observation_mask: Tensor, use_asinh: bool) → Tensor

asinh((data - loc) / scale) on observed positions; unobserved positions become 0.

dsipts.models.timestral.scaler.causal_patch_loc_scale(data: Tensor, observation_mask: Tensor, patch_size: int, minimum_scale: float, stabilize_with_global: bool) → tuple[Tensor, Tensor]

Per-patch (loc, scale) broadcast back to every time step of the patch.

Each patch uses the causal statistics at its last time step, i.e. everything observed up to the end of that patch.

dsipts.models.timestral.scaler.clamp_nonfinite(vals: Tensor) → Tensor

Map +/-inf (a sinh overflow) to the nearest finite value along the last axis.

A position whose whole last axis is non-finite becomes 0. NaN is left untouched so that real instability still surfaces downstream.

dsipts.models.timestral.scaler.compute_causal_statistics(data: Tensor, observation_mask: Tensor, minimum_scale: float, stabilize_with_global: bool, scale_factor_exponent: float = 10.0) → tuple[Tensor, Tensor]

Causal running mean and std along the last axis (Welford form, in float64).

Returns (means, scales), both shaped like data; position t uses the observed values at positions 0..t only. Unobserved positions get zero weight. The variance uses Bessel’s correction and the std is clamped to minimum_scale after the sqrt.

dsipts.models.timestral.scaler.cumulative_welford(w: Tensor, mean: Tensor, m2: Tensor) → tuple[Tensor, Tensor, Tensor]

Inclusive prefix scan of Welford states along dim 1 (Hillis-Steele, log2(N) merges).

dsipts.models.timestral.scaler.denormalize_quantiles(preds: Tensor, loc: Tensor, scale: Tensor, use_asinh: bool) → Tensor

Invert the normalization and clamp infinities; monotone quantiles stay in order.

dsipts.models.timestral.scaler.instance_norm_stats(values: Tensor, observation_mask: Tensor, minimum_scale: float) → tuple[Tensor, Tensor, Tensor]

Non-causal per-row mean/std over observed positions, for known-future covariates.

Rows whose observed values are all 0 or 1 (indicator covariates) keep loc=0, scale=1. Returns (loc, scale, is_binary), each (R, 1).

dsipts.models.timestral.scaler.invert_affine_asinh(x: Tensor, loc: Tensor, scale: Tensor, use_asinh: bool) → Tensor

Inverse of the forward transform: sinh(x) * scale + loc.

dsipts.models.timestral.scaler.welford_combine(w_a: Tensor, mean_a: Tensor, m2_a: Tensor, w_b: Tensor, mean_b: Tensor, m2_b: Tensor) → tuple[Tensor, Tensor, Tensor]

Merge two Welford states (weight, mean, m2) element-wise; (0, 0, 0) is the identity.

Module contents

Standalone inference for Timestral time-series forecasting models.

class dsipts.models.timestral.Forecast(quantiles: Tensor, quantile_levels: tuple[float, ...])

Bases: object

Quantile forecast.

quantiles

(B, V, H, Q) forecast values, sorted along the quantile axis.

Type:

torch.Tensor

quantile_levels

The Q probability levels.

Type:

tuple[float, …]

property median: Tensor

(B, V, H) median forecast.

quantile(level: float) → Tensor

(B, V, H) forecast at one of the model’s quantile levels.

quantile_levels: tuple[float, ...]
quantiles: Tensor
class dsipts.models.timestral.TimestralConfig(patch_size: int, d_model: int, num_heads: int, mlp_hidden_dim: int, block_schedule: tuple[str, ...], quantile_knots: tuple[float, ...], block_size: int, context_length: int, rope_theta: float = 10000.0, rope_partial_factor: float = 0.5, norm_eps: float = 1e-06, attn_bias: bool = False, mlp_bias: bool = False, time_attn_gate: str = 'sdpa_sigmoid', variate_attn_gate: str = 'sdpa_sigmoid', minimum_scale: float = 1e-06, use_asinh: bool = True, stabilize_with_global: bool = False, covariate_enabled: bool = True, split_context_horizon_attn: bool = True, attend_missing_patches: bool = True, quantile_width_factor: float = 2.0)

Bases: object

Architecture and decode settings of a Timestral checkpoint.

patch_size

Time steps per patch.

Type:

int

d_model

Model width.

Type:

int

num_heads

Attention heads per attention sublayer.

Type:

int

mlp_hidden_dim

Hidden width of the SwiGLU MLP.

Type:

int

block_schedule

One entry per layer, each one of LAYER_KINDS.

Type:

tuple[str, …]

quantile_knots

Quantile levels of the head, symmetric about 0.5.

Type:

tuple[float, …]

block_size

Trained DHF block size K, the maximum patches decoded per block.

Type:

int

context_length

Trained context length, the default context cap.

Type:

int

quantile_width_factor

Increment scale of the monotone quantile head.

Type:

float

attend_missing_patches: bool = True
attn_bias: bool = False
block_schedule: tuple[str, ...]
block_size: int
context_length: int
covariate_enabled: bool = True
d_model: int
classmethod from_dict(d: dict[str, Any]) → TimestralConfig
property head_dim: int
classmethod load(path: str | Path) → TimestralConfig
property median_index: int
minimum_scale: float = 1e-06
mlp_bias: bool = False
mlp_hidden_dim: int
norm_eps: float = 1e-06
num_heads: int
property num_quantiles: int
patch_size: int
quantile_knots: tuple[float, ...]
quantile_width_factor: float = 2.0
property rope_dim: int

Head dimensions rotated by RoPE; the rest pass through unrotated.

rope_partial_factor: float = 0.5
rope_theta: float = 10000.0
save(path: str | Path) → None
split_context_horizon_attn: bool = True
stabilize_with_global: bool = False
property supports_known_covariates: bool

Whether the layer schedule can route a known covariate’s future to the targets.

Some time op must be followed by at least one more time op and at least one variate op; otherwise the future of a known covariate never reaches a target.

time_attn_gate: str = 'sdpa_sigmoid'
to_dict() → dict[str, Any]
use_asinh: bool = True
variate_attn_gate: str = 'sdpa_sigmoid'
class dsipts.models.timestral.TimestralForecaster(model: TimestralModel, max_context: int | None = None, per_shot_horizon_patches: int = 32, quantile_real_cap_k: float = 10000.0, extreme_value_threshold: float = 1e+30)

Bases: object

Block-autoregressive quantile forecaster around a TimestralModel.

Parameters:
  • model – The network.

  • max_context – Context cap in time steps (most recent kept); defaults to the trained context length.

  • per_shot_horizon_patches – Patches decoded per block, capped at the trained block size.

  • quantile_real_cap_k – Clamp forecasts to [min - k * s, max + k * s] of the observed context, s being the scale of the last context patch. 0 disables.

  • extreme_value_threshold – Fed-back medians at or above this magnitude become 0.

property device: device
forecast(context: Tensor | ndarray, prediction_length: int, observation_mask: Tensor | ndarray | None = None, past_covariates: Tensor | ndarray | None = None, known_covariates: Tensor | ndarray | None = None, categorical_past_covariates: Tensor | ndarray | None = None, categorical_known_covariates: Tensor | ndarray | None = None, symmetric_averaging: bool = True, clip_nonnegative: bool = True) → Forecast

Forecast prediction_length steps after context.

Parameters:
  • context – (B, V, T), (B, T) (one variate) or (T,) (one series). NaN marks a missing value. The variates of a series are forecast jointly.

  • prediction_length – Horizon in time steps.

  • observation_mask – Optional boolean mask shaped like context; False marks additional missing values.

  • past_covariates – (B, C_past, T) covariates known over the context only.

  • known_covariates – (B, C_known, T + prediction_length) covariates known over the context and the horizon.

  • categorical_past_covariates – (B, C, T) category codes (any numbers; NaN marks a missing value) known over the context only.

  • categorical_known_covariates – (B, C, T + prediction_length) category codes known over the context and the horizon. Categorical covariates are target-encoded per series against the forward-filled target context. A series with several target variates has no single target to encode against, so its codes are used as is.

  • symmetric_averaging – Average with the reflected forecast of -context, with every covariate row negated too.

  • clip_nonnegative – Clamp at 0 the series whose observed context is non-negative.

Returns:

A Forecast with quantiles (B, V, prediction_length, Q).

classmethod from_pretrained(path_or_repo_id: str | Path, device: str | device = 'cpu', max_context: int | None = None, per_shot_horizon_patches: int = 32, quantile_real_cap_k: float = 10000.0, revision: str | None = None, cache_dir: str | Path | None = None, token: str | bool | None = None, local_files_only: bool = False) → TimestralForecaster

Load an exported checkpoint (config.json + model.safetensors).

path_or_repo_id is a local directory or a Hugging Face Hub repo id. revision, cache_dir, token and local_files_only only apply to Hub repos.

property patch_size: int
property supports_covariates: bool
property supports_known_covariates: bool
class dsipts.models.timestral.TimestralModel(config: TimestralConfig)

Bases: Module

Initialize internal Module state, shared by both nn.Module and ScriptModule.

predict_block(inputs: Tensor, observed: Tensor, group_ids: Tensor, horizon_patches: int, role_ids: Tensor | None = None, known_future: Tensor | None = None, known_future_mask: Tensor | None = None) → Tensor

Forecast one block of horizon_patches patches after a packed context.

Parameters:
  • inputs – (R, T) context values, T a multiple of the patch size.

  • observed – (R, T) observation mask.

  • group_ids – (R,) series id per row; rows of one series attend each other.

  • horizon_patches – Number of patches to forecast.

  • role_ids – (R,) row roles (ROLE_TARGET, ROLE_PAST_COV, ROLE_KNOWN_COV), or None when every row is a target.

  • known_future – (R, horizon_patches * patch_size) known-future covariate values over this block; zeros on other rows.

  • known_future_mask – Observation mask for known_future.

Returns:

Raw-space quantiles (R, horizon_patches * patch_size, Q), non-decreasing along Q.

scale(inputs: Tensor, observed: Tensor) → tuple[Tensor, Tensor, Tensor]

Causal per-patch normalization of packed (R, T) rows.

Returns (scaled, loc, scale), each (R, T).

dsipts.models.timestral.load_model(path_or_repo_id: str | Path, device: str | device = 'cpu', dtype: dtype = torch.float32, **hub_kwargs) → TimestralModel

Build the model from config.json and load model.safetensors.

path_or_repo_id is a local directory or a Hugging Face Hub repo id; hub_kwargs go to resolve_checkpoint. Weights load with strict=True. Inference was validated in float32.