modular_timesfm.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. # coding=utf-8
  2. # Copyright 2025 Google LLC and HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch TimesFM model."""
  16. import math
  17. from collections.abc import Sequence
  18. from dataclasses import dataclass
  19. from typing import Callable, Optional, Union
  20. import torch
  21. import torch.nn as nn
  22. import torch.nn.functional as F
  23. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  24. from ...modeling_outputs import BaseModelOutput
  25. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  26. from ...processing_utils import Unpack
  27. from ...utils import auto_docstring, can_return_tuple, logging
  28. from ..llama.modeling_llama import LlamaRMSNorm
  29. from ..phi4_multimodal.modeling_phi4_multimodal import simple_eager_attention_forward
  30. from .configuration_timesfm import TimesFmConfig
  31. logger = logging.get_logger(__name__)
  32. @dataclass
  33. @auto_docstring
  34. class TimesFmOutput(BaseModelOutput):
  35. r"""
  36. loc (`torch.Tensor` of shape `(batch_size, )`):
  37. The mean of the time series inputs.
  38. scale (`torch.Tensor` of shape `(batch_size,)`):
  39. The scale of the time series inputs.
  40. """
  41. loc: Optional[torch.Tensor] = None
  42. scale: Optional[torch.Tensor] = None
  43. @dataclass
  44. @auto_docstring
  45. class TimesFmOutputForPrediction(BaseModelOutput):
  46. r"""
  47. mean_predictions (`torch.Tensor` of shape `(batch_size, sequence_length)`):
  48. The mean predictions of the time series.
  49. full_predictions (`torch.Tensor` of shape `(batch_size, sequence_length)`):
  50. The full predictions of the time series including the mean and the quantiles.
  51. loss (`torch.Tensor` of shape `(1,)`, *optional*, returned when `future_values` is provided):
  52. The loss of the TimesFM model.
  53. """
  54. mean_predictions: Optional[torch.Tensor] = None
  55. full_predictions: Optional[torch.Tensor] = None
  56. loss: Optional[Union[torch.Tensor, float]] = None
  57. class TimesFmMLP(nn.Module):
  58. """Pax MLP in pytorch."""
  59. def __init__(self, config: TimesFmConfig):
  60. super().__init__()
  61. hidden_size = config.hidden_size
  62. intermediate_size = config.intermediate_size
  63. self.gate_proj = nn.Linear(hidden_size, intermediate_size)
  64. self.down_proj = nn.Linear(intermediate_size, hidden_size)
  65. self.layer_norm = nn.LayerNorm(normalized_shape=hidden_size, eps=1e-6)
  66. def forward(self, x, paddings=None):
  67. gate_inp = self.layer_norm(x)
  68. gate = self.gate_proj(gate_inp)
  69. gate = F.relu(gate)
  70. outputs = self.down_proj(gate)
  71. if paddings is not None:
  72. outputs = outputs * (1.0 - paddings[:, :, None])
  73. return outputs + x
  74. class TimesFmResidualBlock(nn.Module):
  75. """TimesFM residual block."""
  76. def __init__(self, input_dims, hidden_dims, output_dims):
  77. super().__init__()
  78. self.input_dims = input_dims
  79. self.hidden_dims = hidden_dims
  80. self.output_dims = output_dims
  81. self.input_layer = nn.Linear(input_dims, hidden_dims)
  82. self.activation = nn.SiLU()
  83. self.output_layer = nn.Linear(hidden_dims, output_dims)
  84. self.residual_layer = nn.Linear(input_dims, output_dims)
  85. def forward(self, x):
  86. hidden = self.input_layer(x)
  87. hidden = self.activation(hidden)
  88. output = self.output_layer(hidden)
  89. residual = self.residual_layer(x)
  90. return output + residual
  91. class TimesFmRMSNorm(LlamaRMSNorm):
  92. pass
  93. class TimesFmPositionalEmbedding(nn.Module):
  94. """Generates position embedding for a given 1-d sequence."""
  95. def __init__(self, config: TimesFmConfig):
  96. super().__init__()
  97. min_timescale = config.min_timescale
  98. max_timescale = config.max_timescale
  99. self.embedding_dims = config.hidden_size
  100. num_timescales = self.embedding_dims // 2
  101. log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / max(num_timescales - 1, 1)
  102. self.register_buffer(
  103. "inv_timescales",
  104. min_timescale * torch.exp(torch.arange(num_timescales, dtype=torch.float32) * -log_timescale_increment),
  105. )
  106. def forward(self, seq_length=None, position=None):
  107. """Generates a Tensor of sinusoids with different frequencies.
  108. Args:
  109. seq_length: an optional Python int defining the output sequence length.
  110. if the `position` argument is specified.
  111. position: [B, seq_length], optional position for each token in the
  112. sequence, only required when the sequence is packed.
  113. Returns:
  114. [B, seqlen, D] if `position` is specified, else [1, seqlen, D]
  115. """
  116. if position is None and seq_length is None:
  117. raise ValueError("Either position or seq_length must be provided")
  118. if position is None:
  119. # [1, seqlen]
  120. position = torch.arange(seq_length, dtype=torch.float32, device=self.inv_timescales.device).unsqueeze(0)
  121. elif position.ndim != 2:
  122. raise ValueError(f"position must be 2-dimensional, got shape {position.shape}")
  123. scaled_time = position.view(*position.shape, 1) * self.inv_timescales.view(1, 1, -1)
  124. signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=2)
  125. # Padding to ensure correct embedding dimension
  126. signal = F.pad(signal, (0, 0, 0, self.embedding_dims % 2))
  127. return signal
  128. class TimesFmAttention(nn.Module):
  129. """Implements the attention used in TimesFM. One key difference is that there is _per_dim_scaling of the query."""
  130. def __init__(self, config: TimesFmConfig, layer_idx: int):
  131. super().__init__()
  132. self.config = config
  133. self.is_causal = True
  134. self.attention_dropout = config.attention_dropout
  135. self.layer_idx = layer_idx
  136. self.num_heads = config.num_attention_heads
  137. self.hidden_size = config.hidden_size
  138. self.head_dim = config.head_dim
  139. self.q_size = self.num_heads * self.head_dim
  140. self.kv_size = self.num_heads * self.head_dim
  141. self.scaling = nn.Parameter(torch.empty((self.head_dim,)))
  142. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim)
  143. self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim)
  144. self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim)
  145. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size)
  146. def _scale_query(self, query: torch.Tensor) -> torch.Tensor:
  147. scale = F.softplus(self.scaling).mul(1.442695041 / math.sqrt(self.head_dim))
  148. return query * scale[None, None, None, :]
  149. def forward(
  150. self,
  151. hidden_states: torch.Tensor,
  152. attention_mask: Optional[torch.Tensor] = None,
  153. **kwargs: Unpack[FlashAttentionKwargs],
  154. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  155. input_shape = hidden_states.shape[:-1]
  156. hidden_shape = (*input_shape, -1, self.head_dim)
  157. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  158. query_states = self._scale_query(query_states)
  159. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  160. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  161. attention_interface: Callable = simple_eager_attention_forward
  162. if self.config._attn_implementation != "eager":
  163. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  164. attn_output, attn_weights = attention_interface(
  165. self,
  166. query_states,
  167. key_states,
  168. value_states,
  169. attention_mask,
  170. dropout=0.0 if not self.training else self.attention_dropout,
  171. scaling=1.0,
  172. **kwargs,
  173. )
  174. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  175. attn_output = self.o_proj(attn_output)
  176. return attn_output, attn_weights
  177. class TimesFmDecoderLayer(nn.Module):
  178. """Transformer layer."""
  179. def __init__(self, config: TimesFmConfig, layer_idx: int):
  180. super().__init__()
  181. self.self_attn = TimesFmAttention(config, layer_idx=layer_idx)
  182. self.mlp = TimesFmMLP(config)
  183. self.input_layernorm = TimesFmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  184. def forward(
  185. self,
  186. hidden_states: torch.Tensor,
  187. attention_mask: torch.Tensor,
  188. paddings: torch.Tensor,
  189. output_attentions: bool = False,
  190. ) -> tuple[Optional[torch.Tensor], torch.Tensor]:
  191. # Self Attention
  192. residual = hidden_states
  193. hidden_states = self.input_layernorm(hidden_states)
  194. hidden_states, scores = self.self_attn(
  195. hidden_states=hidden_states,
  196. attention_mask=attention_mask,
  197. output_attentions=output_attentions,
  198. )
  199. hidden_states = residual + hidden_states
  200. # MLP
  201. hidden_states = self.mlp(hidden_states, paddings=paddings)
  202. return scores, hidden_states
  203. @auto_docstring
  204. class TimesFmPreTrainedModel(PreTrainedModel):
  205. config: TimesFmConfig
  206. base_model_prefix = "timesfm"
  207. _no_split_modules = ["TimesFmDecoderLayer"]
  208. main_input_name = "past_values"
  209. _supports_sdpa = True
  210. def _init_weights(self, module):
  211. super()._init_weights(module)
  212. if isinstance(module, TimesFmAttention):
  213. # Initialize scaling parameter
  214. nn.init.ones_(module.scaling)
  215. @auto_docstring
  216. class TimesFmModel(TimesFmPreTrainedModel):
  217. def __init__(self, config: TimesFmConfig):
  218. super().__init__(config)
  219. self.config = config
  220. self.input_ff_layer = TimesFmResidualBlock(
  221. input_dims=2 * config.patch_length,
  222. output_dims=config.hidden_size,
  223. hidden_dims=config.intermediate_size,
  224. )
  225. self.freq_emb = nn.Embedding(num_embeddings=config.freq_size, embedding_dim=config.hidden_size)
  226. self.layers = nn.ModuleList(
  227. [TimesFmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  228. )
  229. if self.config.use_positional_embedding:
  230. self.position_emb = TimesFmPositionalEmbedding(config=config)
  231. # Initialize weights and apply final processing
  232. self.post_init()
  233. def _forward_transform(
  234. self, inputs: torch.Tensor, patched_pads: torch.Tensor
  235. ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
  236. """Input is of shape [B, N, P]."""
  237. mu, sigma = self._timesfm_masked_mean_std(inputs, patched_pads)
  238. sigma = torch.where(
  239. sigma < self.config.tolerance,
  240. torch.tensor(1.0, dtype=sigma.dtype, device=sigma.device),
  241. sigma,
  242. )
  243. # Normalize each patch
  244. outputs = (inputs - mu[:, None, None]) / sigma[:, None, None]
  245. outputs = torch.where(
  246. torch.abs(inputs - self.config.pad_val) < self.config.tolerance,
  247. torch.tensor(self.config.pad_val, dtype=outputs.dtype, device=outputs.device),
  248. outputs,
  249. )
  250. return outputs, (mu, sigma)
  251. @can_return_tuple
  252. @auto_docstring
  253. def forward(
  254. self,
  255. past_values: torch.Tensor,
  256. past_values_padding: torch.LongTensor,
  257. freq: torch.Tensor,
  258. output_attentions: bool = False,
  259. output_hidden_states: bool = False,
  260. ) -> TimesFmOutput:
  261. r"""
  262. past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  263. Past values of the time series that serves as input to the model.
  264. past_values_padding (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  265. The padding indicator of the time series.
  266. freq (`torch.LongTensor` of shape `(batch_size,)`):
  267. Frequency indices for the time series data.
  268. """
  269. # Reshape into patches (using view for efficiency)
  270. bsize = past_values.shape[0]
  271. patched_inputs = past_values.view(bsize, -1, self.config.patch_length)
  272. patched_pads = past_values_padding.view(bsize, -1, self.config.patch_length)
  273. patched_inputs = torch.where(
  274. torch.abs(patched_pads - 1.0) < self.config.tolerance,
  275. torch.tensor(0.0, dtype=patched_inputs.dtype, device=patched_inputs.device),
  276. patched_inputs,
  277. )
  278. patched_pads = torch.where(
  279. torch.abs(patched_inputs - self.config.pad_val) < self.config.tolerance,
  280. torch.tensor(1.0, dtype=patched_pads.dtype, device=patched_pads.device),
  281. patched_pads,
  282. )
  283. patched_inputs, stats = self._forward_transform(patched_inputs, patched_pads)
  284. # B x N x D
  285. patched_inputs = patched_inputs * (1.0 - patched_pads)
  286. concat_inputs = torch.cat([patched_inputs, patched_pads], dim=-1)
  287. model_input = self.input_ff_layer(concat_inputs)
  288. # A patch should not be padded even if there is at least one zero.
  289. patched_padding = torch.min(patched_pads, dim=-1)[0] # Get the values from the min result
  290. if self.config.use_positional_embedding:
  291. pos_emb = self.position_emb(model_input.shape[1])
  292. pos_emb = torch.concat([pos_emb] * model_input.shape[0], dim=0)
  293. pos_emb = self._timesfm_shift_padded_seq(patched_padding, pos_emb)
  294. model_input += pos_emb
  295. f_emb = self.freq_emb(freq) # B x 1 x D
  296. model_input += f_emb
  297. # Convert paddings to attention mask and combine with causal mask
  298. hidden_states = model_input
  299. attention_mask = self._prepare_4d_attention_mask(
  300. attention_mask=patched_padding,
  301. sequence_length=hidden_states.shape[1],
  302. dtype=hidden_states.dtype,
  303. device=hidden_states.device,
  304. is_causal=True,
  305. )
  306. all_attentions = []
  307. all_hidden_states = []
  308. for layer in self.layers[: self.config.num_hidden_layers]:
  309. scores, hidden_states = layer(
  310. hidden_states=hidden_states,
  311. attention_mask=attention_mask,
  312. paddings=patched_padding,
  313. output_attentions=output_attentions,
  314. )
  315. if output_attentions:
  316. all_attentions.append(scores)
  317. if output_hidden_states:
  318. all_hidden_states.append(hidden_states)
  319. if output_hidden_states:
  320. all_hidden_states = [model_input] + all_hidden_states
  321. else:
  322. all_hidden_states = None
  323. return TimesFmOutput(
  324. last_hidden_state=hidden_states,
  325. hidden_states=all_hidden_states,
  326. attentions=all_attentions if output_attentions else None,
  327. loc=stats[0],
  328. scale=stats[1],
  329. )
  330. @staticmethod
  331. def _prepare_4d_attention_mask(
  332. attention_mask: Optional[torch.Tensor],
  333. sequence_length: int,
  334. dtype: torch.dtype,
  335. device: torch.device,
  336. is_causal: bool = True,
  337. ) -> Optional[torch.Tensor]:
  338. """
  339. Creates 4D attention mask and combines causal and padding masks if needed.
  340. Args:
  341. attention_mask: Optional tensor of shape (batch_size, seq_length) containing padding mask
  342. sequence_length: Length of the sequence
  343. dtype: Data type of the mask
  344. device: Device of the mask
  345. is_causal: Whether to apply causal masking
  346. Returns:
  347. 4D attention mask of shape (batch_size, 1, seq_length, seq_length)
  348. """
  349. # Get minimum value for the dtype
  350. min_value = torch.finfo(dtype).min if dtype.is_floating_point else torch.iinfo(dtype).min
  351. # Handle padding mask
  352. if attention_mask is not None:
  353. # Convert 2D padding mask to 4D attention mask
  354. attention_mask = attention_mask.view(attention_mask.shape[0], 1, 1, -1)
  355. attention_mask = attention_mask * min_value
  356. # Create causal mask if needed
  357. if is_causal:
  358. causal_mask = torch.triu(
  359. torch.ones((sequence_length, sequence_length), dtype=dtype, device=device) * min_value,
  360. diagonal=1,
  361. )
  362. causal_mask = causal_mask.view(1, 1, sequence_length, sequence_length)
  363. # Combine with padding mask if it exists
  364. if attention_mask is not None:
  365. attention_mask = torch.minimum(attention_mask, causal_mask)
  366. else:
  367. attention_mask = causal_mask
  368. return attention_mask
  369. @staticmethod
  370. def _timesfm_masked_mean_std(inputs: torch.Tensor, padding: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
  371. """Calculates mean and standard deviation of `inputs` across axis 1.
  372. It excludes values where `padding` is 1.
  373. Args:
  374. inputs: A PyTorch tensor of shape [b, n, p].
  375. padding: A PyTorch tensor of shape [b, n, p] with values 0 or 1.
  376. Returns:
  377. A tuple containing the mean and standard deviation.
  378. We return the statistics of the first patch with more than three non-padded values.
  379. """
  380. # Selecting the first patch with more than 3 unpadded values.
  381. def _get_patch_index(arr: torch.Tensor):
  382. indices = torch.argmax((arr >= 3).to(torch.int32), dim=1)
  383. row_sum = (arr >= 3).to(torch.int32).sum(dim=1)
  384. return torch.where(row_sum == 0, arr.shape[1] - 1, indices)
  385. pad_sum = torch.sum(1 - padding, dim=2)
  386. patch_indices = _get_patch_index(pad_sum)
  387. bidxs = torch.arange(inputs.shape[0])
  388. arr = inputs[bidxs, patch_indices, :]
  389. pad = padding[bidxs, patch_indices, :]
  390. # Create a mask where padding is 0
  391. mask = 1 - pad
  392. # Calculate the number of valid elements
  393. num_valid_elements = torch.sum(mask, dim=1)
  394. num_valid_elements = torch.where(
  395. num_valid_elements == 0,
  396. torch.tensor(1, dtype=num_valid_elements.dtype, device=num_valid_elements.device),
  397. num_valid_elements,
  398. )
  399. # Calculate the masked sum and squared sum
  400. masked_sum = torch.sum(arr * mask, dim=1)
  401. masked_squared_sum = torch.sum((arr * mask) ** 2, dim=1)
  402. # Calculate the masked mean and standard deviation
  403. masked_mean = masked_sum / num_valid_elements
  404. masked_var = masked_squared_sum / num_valid_elements - masked_mean**2
  405. masked_var = torch.where(
  406. masked_var < 0.0,
  407. torch.tensor(0.0, dtype=masked_var.dtype, device=masked_var.device),
  408. masked_var,
  409. )
  410. masked_std = torch.sqrt(masked_var)
  411. return masked_mean, masked_std
  412. @staticmethod
  413. def _timesfm_shift_padded_seq(mask: torch.Tensor, seq: torch.Tensor) -> torch.Tensor:
  414. """Shifts rows of seq based on the first 0 in each row of the mask.
  415. Args:
  416. mask: mask tensor of shape [B, N]
  417. seq: seq tensor of shape [B, N, P]
  418. Returns:
  419. The shifted sequence.
  420. """
  421. batch_size, num_seq, feature_dim = seq.shape
  422. new_mask: torch.BoolTensor = mask == 0
  423. # Use argmax to find the first True value in each row
  424. indices = new_mask.to(torch.int32).argmax(dim=1)
  425. # Handle rows with all zeros
  426. indices[~new_mask.any(dim=1)] = -1
  427. # Create index ranges for each sequence in the batch
  428. idx_range = torch.arange(num_seq, device=seq.device).view(1, -1, 1).expand(batch_size, -1, feature_dim)
  429. # Calculate shifted indices for each element in each sequence
  430. shifted_idx = (idx_range - indices[:, None, None]) % num_seq
  431. # Gather values from seq using shifted indices
  432. shifted_seq = seq.gather(1, shifted_idx)
  433. return shifted_seq
  434. class TimesFmModelForPrediction(TimesFmPreTrainedModel):
  435. """TimesFM model for quantile and mean prediction."""
  436. def __init__(self, config: TimesFmConfig):
  437. super().__init__(config)
  438. self.config = config
  439. self.context_len = config.context_length
  440. self.horizon_len = config.horizon_length
  441. self.decoder = TimesFmModel(config)
  442. # quantile and mean output
  443. self.horizon_ff_layer = TimesFmResidualBlock(
  444. input_dims=config.hidden_size,
  445. output_dims=config.horizon_length * (1 + len(config.quantiles)),
  446. hidden_dims=config.intermediate_size,
  447. )
  448. # Initialize weights and apply final processing
  449. self.post_init()
  450. def _preprocess(
  451. self, inputs: Sequence[torch.Tensor], freq: Sequence[int]
  452. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  453. """Formats and pads raw inputs to feed into the model.
  454. This function both pads each time series to match the context length, and
  455. pads the inputs to meet the SPMD shape requirement.
  456. Args:
  457. inputs: A list of 1d Tensors. Each Tensor is the context time series of
  458. a single forecast task.
  459. freq: list of frequencies
  460. Returns:
  461. A tuple of:
  462. - the padded input time series to meet the model required context.
  463. - the padding indicator.
  464. - the number of padded examples for SPMD so that each core has the same
  465. number (a multiple of `batch_size`) of examples.
  466. """
  467. input_ts, input_padding, inp_freq = [], [], []
  468. for i, ts in enumerate(inputs):
  469. input_len = ts.shape[0]
  470. padding = torch.zeros(input_len + self.horizon_len, dtype=ts.dtype, device=ts.device)
  471. if input_len < self.context_len:
  472. num_front_pad = self.context_len - input_len
  473. ts = torch.cat([torch.zeros(num_front_pad, dtype=ts.dtype, device=ts.device), ts], dim=0)
  474. padding = torch.cat([torch.ones(num_front_pad, dtype=ts.dtype, device=padding.device), padding], dim=0)
  475. elif input_len > self.context_len:
  476. ts = ts[-self.context_len :]
  477. padding = padding[-(self.context_len + self.horizon_len) :]
  478. input_ts.append(ts)
  479. input_padding.append(padding)
  480. inp_freq.append(freq[i])
  481. return (
  482. torch.stack(input_ts, dim=0),
  483. torch.stack(input_padding, dim=0),
  484. torch.tensor(inp_freq, dtype=torch.int32).reshape(-1, 1),
  485. )
  486. def _postprocess_output(
  487. self, model_output: torch.Tensor, stats: tuple[torch.Tensor, torch.Tensor]
  488. ) -> torch.Tensor:
  489. """Postprocess output of stacked transformer."""
  490. # B x N x (H.Q)
  491. output_ts = self.horizon_ff_layer(model_output)
  492. # Reshape using view
  493. b, n, _ = output_ts.shape
  494. output_ts = output_ts.view(b, n, self.config.horizon_length, len(self.config.quantiles) + 1)
  495. mu, sigma = stats
  496. return output_ts * sigma[:, None, None, None] + mu[:, None, None, None]
  497. def _quantile_loss(self, predictions: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
  498. losses = []
  499. for i, q in enumerate(self.config.quantiles):
  500. errors = targets - predictions[..., i]
  501. loss = torch.max((q - 1) * errors, q * errors)
  502. losses.append(loss.mean())
  503. return torch.stack(losses).mean()
  504. @can_return_tuple
  505. @auto_docstring
  506. def forward(
  507. self,
  508. past_values: Sequence[torch.Tensor],
  509. freq: Optional[Sequence[Union[torch.Tensor, int]]] = None,
  510. window_size: Optional[int] = None,
  511. future_values: Optional[torch.Tensor] = None,
  512. forecast_context_len: Optional[int] = None,
  513. return_forecast_on_context: bool = False,
  514. truncate_negative: bool = False,
  515. output_attentions: Optional[bool] = None,
  516. output_hidden_states: Optional[bool] = None,
  517. ) -> TimesFmOutputForPrediction:
  518. r"""
  519. past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  520. Past values of the time series that serves as input to the model.
  521. freq (`torch.LongTensor` of shape `(batch_size,)`):
  522. Frequency indices for the time series data.
  523. window_size (`int`, *optional*):
  524. Window size of trend + residual decomposition. If None then we do not do decomposition.
  525. future_values (`torch.Tensor`, *optional*):
  526. Optional future time series values to be used for loss computation.
  527. forecast_context_len (`int`, *optional*):
  528. Optional max context length.
  529. return_forecast_on_context (`bool`, *optional*):
  530. True to return the forecast on the context when available, i.e. after the first input patch.
  531. truncate_negative (`bool`, *optional*):
  532. Truncate to only non-negative values if any of the contexts have non-negative values,
  533. otherwise do nothing.
  534. output_attentions (`bool`, *optional*):
  535. Whether to output the attentions.
  536. output_hidden_states (`bool`, *optional*):
  537. Whether to output the hidden states.
  538. Example:
  539. ```python
  540. >>> from transformers import TimesFmModelForPrediction
  541. >>> model = TimesFmModelForPrediction.from_pretrained("google/timesfm-2.0-500m-pytorch")
  542. >>> forecast_input = [torch.linspace(0, 20, 100).sin(), torch.linspace(0, 20, 200).sin(), torch.linspace(0, 20, 400).sin()]
  543. >>> frequency_input = torch.tensor([0, 1, 2], dtype=torch.long)
  544. >>> # Generate
  545. >>> with torch.no_grad():
  546. >>> outputs = model(past_values=forecast_input, freq=frequency_input, return_dict=True)
  547. >>> point_forecast_conv = outputs.mean_predictions
  548. >>> quantile_forecast_conv = outputs.full_predictions
  549. ```
  550. """
  551. if forecast_context_len is None:
  552. fcontext_len = self.context_len
  553. else:
  554. fcontext_len = forecast_context_len
  555. # Get device from first input tensor
  556. device = past_values[0].device
  557. # Truncate inputs to forecast_context_len
  558. inputs = [ts[-fcontext_len:] for ts in past_values]
  559. inp_min = torch.min(torch.stack([torch.min(ts) for ts in inputs]))
  560. if window_size is not None:
  561. new_inputs = []
  562. new_freqs = []
  563. for i, ts in enumerate(inputs):
  564. new_inputs.extend(self._timesfm_moving_average(ts, window_size))
  565. if freq is not None:
  566. new_freqs.extend([freq[i]] * 2)
  567. inputs = new_inputs
  568. if freq is not None:
  569. freq = new_freqs
  570. if freq is None:
  571. logger.info("No frequency provided via `freq`. Default to high (0).")
  572. freq = [0] * len(inputs)
  573. if output_attentions is None:
  574. output_attentions = self.config.output_attentions
  575. if output_hidden_states is None:
  576. output_hidden_states = self.config.output_hidden_states
  577. input_ts, input_padding, inp_freq = self._preprocess(inputs, freq)
  578. # Move tensors to the same device as input
  579. input_ts = input_ts.to(device)
  580. input_padding = input_padding.to(device)
  581. inp_freq = inp_freq.to(device)
  582. final_out = input_ts
  583. context_len = final_out.shape[1]
  584. full_outputs = []
  585. if input_padding.shape[1] != final_out.shape[1] + self.horizon_len:
  586. raise ValueError(
  587. "Length of paddings must match length of input + horizon_len:"
  588. f" {input_padding.shape[1]} != {final_out.shape[1]} + {self.horizon_len}"
  589. )
  590. output_patch_len = self.config.horizon_length
  591. num_decode_patches = (self.horizon_len + output_patch_len - 1) // output_patch_len
  592. for step_index in range(num_decode_patches):
  593. current_padding = input_padding[:, 0 : final_out.shape[1]]
  594. input_ts = final_out[:, -fcontext_len:]
  595. input_padding = current_padding[:, -fcontext_len:]
  596. decoder_output = self.decoder(
  597. past_values=input_ts,
  598. past_values_padding=input_padding,
  599. freq=inp_freq,
  600. output_attentions=output_attentions,
  601. output_hidden_states=output_hidden_states,
  602. )
  603. fprop_outputs = self._postprocess_output(
  604. decoder_output.last_hidden_state,
  605. (decoder_output.loc, decoder_output.scale),
  606. )
  607. if return_forecast_on_context and step_index == 0:
  608. # For the first decodings step, collect the model forecast on the
  609. # context except the unavailable first input batch forecast.
  610. new_full_ts = fprop_outputs[:, :-1, : self.config.patch_length, :]
  611. # We have to use reshape and not view for non-contiguous memory
  612. new_full_ts = new_full_ts.reshape(new_full_ts.size(0), -1, new_full_ts.size(3))
  613. full_outputs.append(new_full_ts)
  614. # (full batch, last patch, output_patch_len, index of mean forecast = 0)
  615. new_ts = fprop_outputs[:, -1, :output_patch_len, 0]
  616. new_full_ts = fprop_outputs[:, -1, :output_patch_len, :]
  617. # (full batch, last patch, output_patch_len, all output indices)
  618. full_outputs.append(new_full_ts)
  619. final_out = torch.concatenate([final_out, new_ts], axis=-1)
  620. if return_forecast_on_context:
  621. # `full_outputs` indexing starts at after the first input patch.
  622. full_outputs = torch.concatenate(full_outputs, axis=1)[
  623. :, : (context_len - self.config.patch_length + self.horizon_len), :
  624. ]
  625. else:
  626. # `full_outputs` indexing starts at the forecast horizon.
  627. full_outputs = torch.concatenate(full_outputs, axis=1)[:, 0 : self.horizon_len, :]
  628. mean_outputs = full_outputs[:, :, 0]
  629. if window_size is not None:
  630. mean_outputs = mean_outputs[0::2, ...] + mean_outputs[1::2, ...]
  631. full_outputs = full_outputs[0::2, ...] + full_outputs[1::2, ...]
  632. if inp_min >= 0 and truncate_negative:
  633. mean_outputs = torch.maximum(mean_outputs, 0.0)
  634. full_outputs = torch.maximum(full_outputs, 0.0)
  635. loss = None
  636. if future_values is not None:
  637. mse_loss = F.mse_loss(mean_outputs, future_values)
  638. quantile_loss = self._quantile_loss(full_outputs[:, :, 1:], future_values)
  639. loss = mse_loss + quantile_loss
  640. return TimesFmOutputForPrediction(
  641. last_hidden_state=decoder_output.last_hidden_state,
  642. attentions=decoder_output.attentions if output_attentions else None,
  643. hidden_states=decoder_output.hidden_states if output_hidden_states else None,
  644. mean_predictions=mean_outputs,
  645. full_predictions=full_outputs,
  646. loss=loss,
  647. )
  648. @staticmethod
  649. def _timesfm_moving_average(arr: torch.Tensor, window_size: int) -> list[torch.Tensor]:
  650. """Calculates the moving average using PyTorch's convolution function."""
  651. # Pad with zeros to handle initial window positions
  652. arr_padded = F.pad(arr, (window_size - 1, 0), "constant", 0)
  653. # Create a convolution kernel
  654. kernel = torch.ones(window_size, dtype=arr.dtype, device=arr.device) / window_size
  655. # Apply convolution to calculate the moving average
  656. smoothed_arr = F.conv1d(arr_padded.view(1, 1, -1), kernel.view(1, 1, -1)).squeeze()
  657. return [smoothed_arr, arr - smoothed_arr]
  658. __all__ = ["TimesFmModelForPrediction", "TimesFmPreTrainedModel", "TimesFmModel"]