modeling_patchtsmixer.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121
  1. # Copyright 2023 IBM and HuggingFace Inc. team. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """PyTorch PatchTSMixer model."""
  15. import math
  16. from collections.abc import Callable
  17. from dataclasses import dataclass
  18. import torch
  19. import torch.nn as nn
  20. from transformers.modeling_utils import PreTrainedModel
  21. from transformers.utils import ModelOutput
  22. from ... import initialization as init
  23. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  24. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
  25. from ...processing_utils import Unpack
  26. from ...time_series_utils import NegativeBinomialOutput, NormalOutput, StudentTOutput
  27. from ...utils import TransformersKwargs, auto_docstring, logging
  28. from .configuration_patchtsmixer import PatchTSMixerConfig
  29. logger = logging.get_logger(__name__)
  30. class PatchTSMixerGatedAttention(nn.Module):
  31. """
  32. Module that applies gated attention to input data.
  33. Args:
  34. in_size (`int`): The input size.
  35. out_size (`int`): The output size.
  36. """
  37. def __init__(self, in_size: int, out_size: int):
  38. super().__init__()
  39. self.attn_layer = nn.Linear(in_size, out_size)
  40. self.attn_softmax = nn.Softmax(dim=-1)
  41. def forward(self, inputs):
  42. attn_weight = self.attn_softmax(self.attn_layer(inputs))
  43. inputs = inputs * attn_weight
  44. return inputs
  45. # Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTBatchNorm with PatchTST->PatchTSMixer
  46. class PatchTSMixerBatchNorm(nn.Module):
  47. """
  48. Compute batch normalization over the sequence length (time) dimension.
  49. """
  50. def __init__(self, config: PatchTSMixerConfig):
  51. super().__init__()
  52. self.batchnorm = nn.BatchNorm1d(config.d_model, eps=config.norm_eps)
  53. def forward(self, inputs: torch.Tensor):
  54. """
  55. Parameters:
  56. inputs (`torch.Tensor` of shape `(batch_size, sequence_length, d_model)`):
  57. input for Batch norm calculation
  58. Returns:
  59. `torch.Tensor` of shape `(batch_size, sequence_length, d_model)`
  60. """
  61. output = inputs.transpose(1, 2) # output: (batch_size, d_model, sequence_length)
  62. output = self.batchnorm(output)
  63. return output.transpose(1, 2)
  64. class PatchTSMixerPositionalEncoding(nn.Module):
  65. """
  66. Class for positional encoding
  67. """
  68. def __init__(self, config: PatchTSMixerConfig):
  69. super().__init__()
  70. # positional encoding: [num_patches x d_model]
  71. if config.use_positional_encoding:
  72. self.position_enc = self._init_pe(config)
  73. else:
  74. self.position_enc = nn.Parameter(torch.zeros(config.num_patches, config.d_model))
  75. @staticmethod
  76. def _init_pe(config: PatchTSMixerConfig) -> nn.Parameter:
  77. # Positional encoding
  78. if config.positional_encoding_type == "random":
  79. position_enc = nn.Parameter(torch.randn(config.num_patches, config.d_model), requires_grad=True)
  80. elif config.positional_encoding_type == "sincos":
  81. position_enc = torch.zeros(config.num_patches, config.d_model)
  82. position = torch.arange(0, config.num_patches).unsqueeze(1)
  83. div_term = torch.exp(torch.arange(0, config.d_model, 2) * -(math.log(10000.0) / config.d_model))
  84. position_enc[:, 0::2] = torch.sin(position * div_term)
  85. position_enc[:, 1::2] = torch.cos(position * div_term)
  86. position_enc = position_enc - position_enc.mean()
  87. position_enc = position_enc / (position_enc.std() * 10)
  88. position_enc = nn.Parameter(position_enc, requires_grad=False)
  89. else:
  90. raise ValueError(
  91. f"{config.positional_encoding_type} is not a valid positional encoder. Available types are 'random' and 'sincos'."
  92. )
  93. return position_enc
  94. def forward(self, patch_input: torch.Tensor):
  95. # hidden_state: [bs x num_channels x num_patches x d_model]
  96. hidden_state = patch_input + self.position_enc
  97. return hidden_state
  98. class PatchTSMixerNormLayer(nn.Module):
  99. """Normalization block
  100. Args:
  101. config (`PatchTSMixerConfig`):
  102. Configuration.
  103. """
  104. def __init__(self, config: PatchTSMixerConfig):
  105. super().__init__()
  106. self.norm_mlp = config.norm_mlp
  107. if "batch" in config.norm_mlp.lower():
  108. self.norm = PatchTSMixerBatchNorm(config)
  109. else:
  110. self.norm = nn.LayerNorm(config.d_model, eps=config.norm_eps)
  111. def forward(self, inputs: torch.Tensor):
  112. """
  113. Args:
  114. inputs (`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`):
  115. Input to the normalization layer.
  116. Returns:
  117. `torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`
  118. """
  119. if "batch" in self.norm_mlp.lower():
  120. # reshape the data
  121. inputs_reshaped = torch.reshape(
  122. inputs,
  123. (
  124. inputs.shape[0] * inputs.shape[1],
  125. inputs.shape[2],
  126. inputs.shape[3],
  127. ),
  128. ) # inputs_reshaped: [batch_size*num_channels, num_patches, d_model]
  129. # inputs_reshaped: [batch_size*num_channels, num_patches, d_model]
  130. inputs_reshaped = self.norm(inputs_reshaped)
  131. # put back data to the original shape
  132. inputs = torch.reshape(inputs_reshaped, inputs.shape)
  133. else:
  134. inputs = self.norm(inputs)
  135. return inputs
  136. class PatchTSMixerMLP(nn.Module):
  137. def __init__(self, in_features, out_features, config):
  138. super().__init__()
  139. num_hidden = in_features * config.expansion_factor
  140. self.fc1 = nn.Linear(in_features, num_hidden)
  141. self.dropout1 = nn.Dropout(config.dropout)
  142. self.fc2 = nn.Linear(num_hidden, out_features)
  143. self.dropout2 = nn.Dropout(config.dropout)
  144. def forward(self, inputs: torch.Tensor):
  145. """
  146. Args:
  147. inputs (`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`):
  148. Input to the MLP layer.
  149. Returns:
  150. `torch.Tensor` of the same shape as `inputs`
  151. """
  152. inputs = self.dropout1(nn.functional.gelu(self.fc1(inputs)))
  153. inputs = self.fc2(inputs)
  154. inputs = self.dropout2(inputs)
  155. return inputs
  156. class PatchTSMixerChannelFeatureMixerBlock(nn.Module):
  157. """This module mixes the features in the channel dimension.
  158. Args:
  159. config (`PatchTSMixerConfig`):
  160. Configuration.
  161. """
  162. def __init__(self, config: PatchTSMixerConfig):
  163. super().__init__()
  164. self.norm = PatchTSMixerNormLayer(config)
  165. self.gated_attn = config.gated_attn
  166. self.mlp = PatchTSMixerMLP(
  167. in_features=config.num_input_channels,
  168. out_features=config.num_input_channels,
  169. config=config,
  170. )
  171. if config.gated_attn:
  172. self.gating_block = PatchTSMixerGatedAttention(
  173. in_size=config.num_input_channels, out_size=config.num_input_channels
  174. )
  175. def forward(self, inputs: torch.Tensor):
  176. """
  177. Args:
  178. inputs (`torch.Tensor` of shape `((batch_size, num_channels, num_patches, d_model))`):
  179. input to the MLP layer
  180. Returns:
  181. `torch.Tensor` of the same shape as `inputs`
  182. """
  183. residual = inputs
  184. inputs = self.norm(inputs)
  185. inputs = inputs.permute(0, 3, 2, 1)
  186. if self.gated_attn:
  187. inputs = self.gating_block(inputs)
  188. inputs = self.mlp(inputs)
  189. inputs = inputs.permute(0, 3, 2, 1)
  190. out = inputs + residual
  191. return out
  192. # Copied from transformers.models.bert.modeling_bert.eager_attention_forward
  193. def eager_attention_forward(
  194. module: nn.Module,
  195. query: torch.Tensor,
  196. key: torch.Tensor,
  197. value: torch.Tensor,
  198. attention_mask: torch.Tensor | None,
  199. scaling: float | None = None,
  200. dropout: float = 0.0,
  201. **kwargs: Unpack[TransformersKwargs],
  202. ):
  203. if scaling is None:
  204. scaling = query.size(-1) ** -0.5
  205. # Take the dot product between "query" and "key" to get the raw attention scores.
  206. attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
  207. if attention_mask is not None:
  208. attn_weights = attn_weights + attention_mask
  209. attn_weights = nn.functional.softmax(attn_weights, dim=-1)
  210. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  211. attn_output = torch.matmul(attn_weights, value)
  212. attn_output = attn_output.transpose(1, 2).contiguous()
  213. return attn_output, attn_weights
  214. # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Attention with Wav2Vec2->PatchTSMixer
  215. class PatchTSMixerAttention(nn.Module):
  216. """Multi-headed attention from 'Attention Is All You Need' paper"""
  217. def __init__(
  218. self,
  219. embed_dim: int,
  220. num_heads: int,
  221. dropout: float = 0.0,
  222. is_decoder: bool = False,
  223. bias: bool = True,
  224. is_causal: bool = False,
  225. config: PatchTSMixerConfig | None = None,
  226. ):
  227. super().__init__()
  228. self.embed_dim = embed_dim
  229. self.num_heads = num_heads
  230. self.dropout = dropout
  231. self.head_dim = embed_dim // num_heads
  232. self.config = config
  233. if (self.head_dim * num_heads) != self.embed_dim:
  234. raise ValueError(
  235. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
  236. f" and `num_heads`: {num_heads})."
  237. )
  238. self.scaling = self.head_dim**-0.5
  239. self.is_decoder = is_decoder
  240. self.is_causal = is_causal
  241. self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  242. self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  243. self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  244. self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  245. def forward(
  246. self,
  247. hidden_states: torch.Tensor,
  248. key_value_states: torch.Tensor | None = None,
  249. attention_mask: torch.Tensor | None = None,
  250. output_attentions: bool | None = False,
  251. # TODO: we need a refactor so that the different attention modules can get their specific kwargs
  252. # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
  253. **kwargs: Unpack[FlashAttentionKwargs],
  254. ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
  255. """Input shape: Batch x Time x Channel"""
  256. # if key_value_states are provided this layer is used as a cross-attention layer
  257. # for the decoder
  258. is_cross_attention = key_value_states is not None
  259. # determine input shapes
  260. input_shape = hidden_states.shape[:-1]
  261. hidden_shape = (*input_shape, -1, self.head_dim)
  262. # get query proj
  263. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  264. current_states = key_value_states if is_cross_attention else hidden_states
  265. kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
  266. key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2)
  267. value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2)
  268. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  269. self.config._attn_implementation, eager_attention_forward
  270. )
  271. attn_output, attn_weights = attention_interface(
  272. self,
  273. query_states,
  274. key_states,
  275. value_states,
  276. attention_mask,
  277. dropout=0.0 if not self.training else self.dropout,
  278. scaling=self.scaling,
  279. output_attentions=output_attentions,
  280. **kwargs,
  281. )
  282. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  283. attn_output = self.out_proj(attn_output)
  284. return attn_output, attn_weights, None
  285. class PatchMixerBlock(nn.Module):
  286. """This module mixes the patch dimension.
  287. Args:
  288. config (`PatchTSMixerConfig`):
  289. Configuration.
  290. """
  291. def __init__(self, config: PatchTSMixerConfig):
  292. super().__init__()
  293. self.norm = PatchTSMixerNormLayer(config)
  294. self.self_attn = config.self_attn
  295. self.gated_attn = config.gated_attn
  296. self.mlp = PatchTSMixerMLP(
  297. in_features=config.num_patches,
  298. out_features=config.num_patches,
  299. config=config,
  300. )
  301. if config.gated_attn:
  302. self.gating_block = PatchTSMixerGatedAttention(in_size=config.num_patches, out_size=config.num_patches)
  303. if config.self_attn:
  304. self.self_attn_layer = PatchTSMixerAttention(
  305. embed_dim=config.d_model,
  306. num_heads=config.self_attn_heads,
  307. dropout=config.dropout,
  308. config=config,
  309. )
  310. self.norm_attn = PatchTSMixerNormLayer(config)
  311. def forward(self, hidden_state):
  312. """
  313. Args:
  314. hidden_state (`torch.Tensor`): Input tensor.
  315. Returns:
  316. `torch.Tensor`: Transformed tensor.
  317. """
  318. residual = hidden_state
  319. hidden_state = self.norm(hidden_state)
  320. if self.self_attn:
  321. batch_size, n_vars, num_patches, d_model = hidden_state.shape
  322. hidden_state_reshaped = hidden_state.reshape(batch_size * n_vars, num_patches, d_model)
  323. x_attn, _, _ = self.self_attn_layer(hidden_state_reshaped, output_attentions=False)
  324. x_attn = x_attn.reshape(batch_size, n_vars, num_patches, d_model)
  325. # Transpose so that num_patches is the last dimension
  326. hidden_state = hidden_state.transpose(2, 3)
  327. hidden_state = self.mlp(hidden_state)
  328. if self.gated_attn:
  329. hidden_state = self.gating_block(hidden_state)
  330. # Transpose back
  331. hidden_state = hidden_state.transpose(2, 3)
  332. if self.self_attn:
  333. hidden_state = self.norm_attn(hidden_state + x_attn)
  334. out = hidden_state + residual
  335. return out
  336. class FeatureMixerBlock(nn.Module):
  337. """This module mixes the hidden feature dimension.
  338. Args:
  339. config (`PatchTSMixerConfig`):
  340. Configuration.
  341. """
  342. def __init__(self, config: PatchTSMixerConfig):
  343. super().__init__()
  344. self.norm = PatchTSMixerNormLayer(config)
  345. self.gated_attn = config.gated_attn
  346. self.mlp = PatchTSMixerMLP(
  347. in_features=config.d_model,
  348. out_features=config.d_model,
  349. config=config,
  350. )
  351. if config.gated_attn:
  352. self.gating_block = PatchTSMixerGatedAttention(in_size=config.d_model, out_size=config.d_model)
  353. def forward(self, hidden: torch.Tensor):
  354. """
  355. Args:
  356. hidden (`torch.Tensor` of shape `(batch_size, num_patches, d_model)`):
  357. Input tensor to the layer.
  358. Returns:
  359. `torch.Tensor`: Transformed tensor.
  360. """
  361. residual = hidden
  362. hidden = self.norm(hidden)
  363. hidden = self.mlp(hidden)
  364. if self.gated_attn:
  365. hidden = self.gating_block(hidden)
  366. out = hidden + residual
  367. return out
  368. class PatchTSMixerLayer(nn.Module):
  369. """
  370. The `PatchTSMixer` layer that does all three kinds of mixing.
  371. Args:
  372. config (`PatchTSMixerConfig`):
  373. Configuration.
  374. """
  375. def __init__(self, config: PatchTSMixerConfig):
  376. super().__init__()
  377. self.patch_mixer = PatchMixerBlock(config=config)
  378. self.feature_mixer = FeatureMixerBlock(config=config)
  379. self.mode = config.mode
  380. if config.mode == "mix_channel":
  381. self.channel_feature_mixer = PatchTSMixerChannelFeatureMixerBlock(config=config)
  382. def forward(self, hidden: torch.Tensor):
  383. """
  384. Args:
  385. hidden (`torch.Tensor` of shape `(batch_size, num_patches, d_model)`):
  386. Input tensor to the layer.
  387. Returns:
  388. `torch.Tensor`: Transformed tensor.
  389. """
  390. if self.mode == "mix_channel":
  391. hidden = self.channel_feature_mixer(hidden)
  392. hidden = self.patch_mixer(hidden)
  393. hidden = self.feature_mixer(hidden) # hidden: (batch_size x num_patches x d_model)
  394. return hidden
  395. class PatchTSMixerBlock(nn.Module):
  396. """The main computing framework of the `PatchTSMixer` model.
  397. Args:
  398. config (`PatchTSMixerConfig`):
  399. Configuration.
  400. """
  401. def __init__(self, config: PatchTSMixerConfig):
  402. super().__init__()
  403. num_layers = config.num_layers
  404. self.mixers = nn.ModuleList([PatchTSMixerLayer(config=config) for _ in range(num_layers)])
  405. def forward(self, hidden_state, output_hidden_states: bool = False):
  406. """
  407. Args:
  408. hidden_state (`torch.Tensor`): The input tensor.
  409. output_hidden_states (`bool`, *optional*, defaults to False.):
  410. Whether to output the hidden states as well.
  411. Returns:
  412. `torch.Tensor`: The embedding. `list`: List of all hidden states if `output_hidden_states` is set to
  413. `True`.
  414. """
  415. all_hidden_states = []
  416. embedding = hidden_state
  417. for mod in self.mixers:
  418. embedding = mod(embedding)
  419. if output_hidden_states:
  420. all_hidden_states.append(embedding)
  421. if output_hidden_states:
  422. return embedding, all_hidden_states
  423. else:
  424. return embedding, None
  425. class PatchTSMixerForPredictionHead(nn.Module):
  426. """Prediction Head for Forecasting
  427. Args:
  428. config (`PatchTSMixerConfig`):
  429. Configuration.
  430. """
  431. def __init__(self, config: PatchTSMixerConfig, distribution_output=None):
  432. super().__init__()
  433. self.prediction_channel_indices = config.prediction_channel_indices
  434. if self.prediction_channel_indices is not None:
  435. self.prediction_channel_indices.sort()
  436. self.dropout_layer = nn.Dropout(config.head_dropout)
  437. if distribution_output is None:
  438. self.base_forecast_block = nn.Linear((config.num_patches * config.d_model), config.prediction_length)
  439. else:
  440. self.base_forecast_block = distribution_output.get_parameter_projection(
  441. config.num_patches * config.d_model
  442. )
  443. self.flatten = nn.Flatten(start_dim=-2)
  444. def forward(self, hidden_features):
  445. """
  446. Args:
  447. hidden_features (`torch.Tensor` of shape `(batch_size, num_patch, d_model)` in `flatten` mode
  448. or `(batch_size, n_vars, num_patch, d_model)` in `common_channel`/`mix_channel` mode.): Input hidden
  449. features.
  450. Returns:
  451. `torch.Tensor` of shape `(batch_size, prediction_length, nvars)`.
  452. """
  453. hidden_features = self.flatten(hidden_features) # [batch_size x n_vars x num_patch * d_model]
  454. hidden_features = self.dropout_layer(hidden_features) # [batch_size x n_vars x num_patch * d_model]
  455. forecast = self.base_forecast_block(hidden_features) # [batch_size x n_vars x prediction_length]
  456. if isinstance(forecast, tuple):
  457. forecast = tuple(z.transpose(-1, -2) for z in forecast)
  458. else:
  459. forecast = forecast.transpose(-1, -2) # [batch_size x prediction_length x n_vars]
  460. if self.prediction_channel_indices is not None:
  461. if isinstance(forecast, tuple):
  462. forecast = tuple(z[..., self.prediction_channel_indices] for z in forecast)
  463. else:
  464. forecast = forecast[..., self.prediction_channel_indices] # [batch_size x prediction_length x n_vars]
  465. return forecast
  466. class PatchTSMixerLinearHead(nn.Module):
  467. """Linear head for Classification and Regression.
  468. Args:
  469. config (`PatchTSMixerConfig`):
  470. Configuration.
  471. """
  472. def __init__(self, config: PatchTSMixerConfig, distribution_output=None):
  473. super().__init__()
  474. self.head_aggregation = config.head_aggregation
  475. self.output_range = config.output_range
  476. if config.head_aggregation is None:
  477. mul_factor = config.num_patches
  478. else:
  479. mul_factor = 1
  480. self.distribution_output = distribution_output
  481. if distribution_output is None:
  482. self.projection = nn.Linear(
  483. config.d_model * config.num_input_channels * mul_factor,
  484. config.num_targets,
  485. )
  486. else:
  487. self.projection = distribution_output.get_parameter_projection(
  488. config.d_model * config.num_input_channels * mul_factor
  489. )
  490. if config.head_aggregation is None:
  491. self.flatten = nn.Flatten(start_dim=-3)
  492. else:
  493. self.flatten = nn.Flatten(start_dim=-2)
  494. self.dropout = nn.Dropout(config.head_dropout)
  495. def forward(self, hidden_features):
  496. """
  497. Args:
  498. hidden_features (`torch.Tensor` of shape `(batch_size x num_patch x d_model)` in `flatten` mode
  499. or `(batch_size x n_vars x num_patch x d_model)` in `common_channel`/`mix_channel` mode.): Input hidden
  500. features.
  501. Returns:
  502. `torch.Tensor` of shape `(batch_size x num_targets)`.
  503. """
  504. # batch_size x d_model x num_patch or batch_size x n_vars x d_model x num_patch
  505. hidden_features = hidden_features.transpose(-1, -2)
  506. if self.head_aggregation == "use_last":
  507. # batch_size x d_model (flatten) or # batch_size x n_vars x d_model (common_channel)
  508. hidden_features = hidden_features[..., -1]
  509. elif self.head_aggregation == "max_pool":
  510. # batch_size x n_vars x d_model or batch_size x d_model
  511. hidden_features = hidden_features.max(dim=-1).values
  512. elif self.head_aggregation == "avg_pool":
  513. # batch_size x n_vars x d_model or batch_size x d_model
  514. hidden_features = hidden_features.mean(dim=-1)
  515. if self.flatten:
  516. hidden_features = self.flatten(hidden_features)
  517. hidden_features = self.dropout(hidden_features)
  518. hidden_features = self.projection(hidden_features) # batch_size x num_targets
  519. if (self.distribution_output is None) and (self.output_range is not None):
  520. hidden_features = (
  521. torch.sigmoid(hidden_features) * (self.output_range[1] - self.output_range[0]) + self.output_range[0]
  522. )
  523. return hidden_features
  524. @auto_docstring
  525. class PatchTSMixerPreTrainedModel(PreTrainedModel):
  526. # Weight initialization
  527. config: PatchTSMixerConfig
  528. base_model_prefix = "model"
  529. main_input_name = "past_values"
  530. input_modalities = ("time",)
  531. supports_gradient_checkpointing = False
  532. @torch.no_grad()
  533. def _init_weights(self, module):
  534. """Initialize weights"""
  535. if isinstance(module, PatchTSMixerPositionalEncoding):
  536. # initialize positional encoding
  537. if self.config.positional_encoding_type == "random":
  538. init.normal_(module.position_enc, mean=0.0, std=0.1)
  539. elif isinstance(module, (nn.LayerNorm, nn.BatchNorm1d)):
  540. init.zeros_(module.bias)
  541. init.ones_(module.weight)
  542. if getattr(module, "running_mean", None) is not None:
  543. init.zeros_(module.running_mean)
  544. init.ones_(module.running_var)
  545. init.zeros_(module.num_batches_tracked)
  546. elif isinstance(module, PatchTSMixerBatchNorm):
  547. init.zeros_(module.batchnorm.bias)
  548. init.ones_(module.batchnorm.weight)
  549. elif isinstance(module, nn.Linear):
  550. init.normal_(module.weight, mean=0.0, std=self.config.init_std)
  551. if module.bias is not None:
  552. init.zeros_(module.bias)
  553. class PatchTSMixerPretrainHead(nn.Module):
  554. """Pretraining head.
  555. Args:
  556. config (`PatchTSMixerConfig`):
  557. Configuration.
  558. """
  559. def __init__(self, config: PatchTSMixerConfig):
  560. super().__init__()
  561. self.dropout_layer = nn.Dropout(config.head_dropout)
  562. self.base_pt_block = nn.Linear(config.d_model, config.patch_length)
  563. def forward(self, hidden_features):
  564. """
  565. Args:
  566. hidden_features (`torch.Tensor` of shape `(batch_size x num_patch x d_model)` in `flatten` mode
  567. or `(batch_size x n_vars x num_patch x d_model)` in `common_channel`/`mix_channel` mode.): Input hidden
  568. features.
  569. Returns:
  570. `torch.Tensor` of shape `(batch_size x n_vars x num_patch x patch_length)`.
  571. """
  572. hidden_features = self.dropout_layer(hidden_features)
  573. forecast = self.base_pt_block(hidden_features) # [batch_size x n_vars x num_patch x patch_length]
  574. return forecast
  575. # Copied from transformers.models.patchtst.modeling_patchtst.random_masking
  576. def random_masking(
  577. inputs: torch.Tensor,
  578. mask_ratio: float,
  579. unmasked_channel_indices: list | None = None,
  580. channel_consistent_masking: bool = False,
  581. mask_value: int = 0,
  582. ):
  583. """random_masking: Mask the input considering the control variables.
  584. Args:
  585. inputs (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, num_features)`):
  586. The input tensor to mask.
  587. mask_ratio (`float`):
  588. Masking ratio applied to mask the input data during random pretraining. It is the number between 0 and 1.
  589. unmasked_channel_indices (list, *optional*):
  590. Indices of channels that will not be masked.
  591. channel_consistent_masking (bool, *optional*, defaults to `False`):
  592. When true, masking will be same across all channels of a timeseries. Otherwise, masking positions will vary
  593. across channels.
  594. mask_value (int, *optional*, defaults to 0):
  595. Define the value of masked patches for pretraining.
  596. Returns:
  597. `tuple(torch.Tensor)`: inputs_mask, masked input, same shape as input Tensor and mask tensor of shape [bs x c x
  598. n]
  599. """
  600. if mask_ratio < 0 or mask_ratio >= 1:
  601. raise ValueError(f"Mask ratio {mask_ratio} has to be between 0 and 1.")
  602. batch_size, num_channels, sequence_length, num_features = inputs.shape
  603. device = inputs.device
  604. len_keep = int(sequence_length * (1 - mask_ratio))
  605. if channel_consistent_masking:
  606. noise = torch.rand(batch_size, 1, sequence_length, device=device) # noise in [0, 1], bs x 1 x L
  607. noise = noise.repeat(1, num_channels, 1) # bs x num_channels x time
  608. else:
  609. # noise in [0, 1], bs x num_channels x L
  610. noise = torch.rand(batch_size, num_channels, sequence_length, device=device)
  611. # mask: [bs x num_channels x num_patch]
  612. mask = torch.ones(batch_size, num_channels, sequence_length, device=device)
  613. mask[:, :, :len_keep] = 0
  614. # sort noise for each sample
  615. ids_shuffle = torch.argsort(noise, dim=-1) # ascend: small is keep, large is remove
  616. ids_restore = torch.argsort(ids_shuffle, dim=-1) # ids_restore: [bs x num_channels x L]
  617. mask = torch.gather(mask, dim=-1, index=ids_restore)
  618. mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patches x patch_length]
  619. if unmasked_channel_indices is not None:
  620. mask[:, unmasked_channel_indices, :, :] = 0
  621. inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
  622. return inputs_mask, mask[..., 0]
  623. # Copied from transformers.models.patchtst.modeling_patchtst.forecast_masking
  624. def forecast_masking(
  625. inputs: torch.Tensor,
  626. num_forecast_mask_patches: list | int,
  627. unmasked_channel_indices: list | None = None,
  628. mask_value: int = 0,
  629. ):
  630. """Forecast masking that masks the last K patches where K is from the num_forecast_mask_patches.
  631. If num_forecast_mask_patches is a list, samples in the batch will be randomly masked by numbers defined in the list.
  632. Parameters:
  633. inputs (`torch.Tensor`):
  634. Input of shape `(bs, num_channels, num_patch, patch_length)`
  635. num_forecast_mask_patches (`list`):
  636. Number of patches to be masked at the end of each batch sample. e.g. 4 or [3, 5].
  637. unmasked_channel_indices (`list`, *optional*):
  638. Indices of channels that are not masked.
  639. mask_value (`int`, *optional*, defaults to 0):
  640. Values in the masked patches will be filled by `mask_value`.
  641. Returns:
  642. `tuple(torch.Tensor)`: inputs_mask, masked input, same shape as inputs Tensor and Mask tensor of shape `(bs,
  643. num_channels , num_patch)` or `(bs, tsg1, tsg2, num_channels, num_patch)`
  644. """
  645. if isinstance(num_forecast_mask_patches, int):
  646. num_forecast_mask_patches = [num_forecast_mask_patches]
  647. forecast_mask_ratios = [1 for _ in num_forecast_mask_patches]
  648. batch_size, num_channels, sequence_length, num_features = inputs.shape
  649. mask = torch.zeros(batch_size, num_channels, sequence_length, device=inputs.device)
  650. t_list = []
  651. total_length = 0
  652. total_ratio = sum(forecast_mask_ratios)
  653. for patch_length, ratio in zip(num_forecast_mask_patches, forecast_mask_ratios):
  654. if patch_length <= 0 or patch_length >= sequence_length:
  655. raise ValueError(
  656. f"num_forecast_mask_patches {patch_length} should be greater than 0 and less than total patches."
  657. )
  658. temp_len = int(batch_size * ratio / total_ratio)
  659. t_list.append([patch_length, ratio, temp_len])
  660. total_length += temp_len
  661. t_list = sorted(t_list, key=lambda x: x[2])
  662. if total_length < batch_size:
  663. t_list[0][2] = t_list[0][2] + (batch_size - total_length)
  664. elif total_length > batch_size:
  665. t_list[-1][2] = t_list[-1][2] + (total_length - batch_size)
  666. batch1 = 0
  667. for patch_len, _, temp_len in t_list:
  668. batch2 = batch1 + temp_len
  669. mask[batch1:batch2, :, -patch_len:] = 1
  670. batch1 = batch2
  671. perm = torch.randperm(mask.shape[0])
  672. mask = mask[perm]
  673. mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patch x patch_len]
  674. if unmasked_channel_indices is not None:
  675. mask[:, unmasked_channel_indices, :, :] = 0
  676. inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
  677. return inputs_mask, mask[..., 0]
  678. # Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTPatchify with PatchTST->PatchTSMixer
  679. class PatchTSMixerPatchify(nn.Module):
  680. """
  681. A class to patchify the time series sequence into different patches
  682. Returns:
  683. `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
  684. """
  685. def __init__(self, config: PatchTSMixerConfig):
  686. super().__init__()
  687. self.sequence_length = config.context_length
  688. self.patch_length = config.patch_length
  689. self.patch_stride = config.patch_stride
  690. if self.sequence_length <= self.patch_length:
  691. raise ValueError(
  692. f"Sequence length ({self.sequence_length}) has to be greater than the patch length ({self.patch_length})"
  693. )
  694. # get the number of patches
  695. self.num_patches = (max(self.sequence_length, self.patch_length) - self.patch_length) // self.patch_stride + 1
  696. new_sequence_length = self.patch_length + self.patch_stride * (self.num_patches - 1)
  697. self.sequence_start = self.sequence_length - new_sequence_length
  698. def forward(self, past_values: torch.Tensor):
  699. """
  700. Parameters:
  701. past_values (`torch.Tensor` of shape `(batch_size, sequence_length, num_channels)`, *required*):
  702. Input for patchification
  703. Returns:
  704. `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
  705. """
  706. sequence_length = past_values.shape[-2]
  707. if sequence_length != self.sequence_length:
  708. raise ValueError(
  709. f"Input sequence length ({sequence_length}) doesn't match model configuration ({self.sequence_length})."
  710. )
  711. # output: [bs x new_sequence_length x num_channels]
  712. output = past_values[:, self.sequence_start :, :]
  713. # output: [bs x num_patches x num_input_channels x patch_length]
  714. output = output.unfold(dimension=-2, size=self.patch_length, step=self.patch_stride)
  715. # output: [bs x num_input_channels x num_patches x patch_length]
  716. output = output.transpose(-2, -3).contiguous()
  717. return output
  718. # Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTMasking with PatchTST->PatchTSMixer
  719. class PatchTSMixerMasking(nn.Module):
  720. """
  721. Class to perform random or forecast masking.
  722. Parameters:
  723. config (`PatchTSMixerConfig`): model config
  724. Returns:
  725. x_mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
  726. Masked patched input
  727. mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
  728. Bool tensor indicating True on masked points
  729. """
  730. def __init__(self, config: PatchTSMixerConfig):
  731. super().__init__()
  732. self.random_mask_ratio = config.random_mask_ratio
  733. self.channel_consistent_masking = config.channel_consistent_masking
  734. self.mask_type = config.mask_type
  735. self.num_forecast_mask_patches = config.num_forecast_mask_patches
  736. self.unmasked_channel_indices = config.unmasked_channel_indices
  737. self.mask_value = config.mask_value
  738. if self.unmasked_channel_indices is not None:
  739. self.unmasked_channel_indices = sorted(self.unmasked_channel_indices)
  740. def forward(self, patch_input: torch.Tensor):
  741. """
  742. Parameters:
  743. patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
  744. Patch input
  745. Return:
  746. masked_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
  747. Masked patched input
  748. mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
  749. Bool tensor indicating True on masked points
  750. """
  751. if self.mask_type == "random":
  752. masked_input, mask = random_masking(
  753. inputs=patch_input,
  754. mask_ratio=self.random_mask_ratio,
  755. unmasked_channel_indices=self.unmasked_channel_indices,
  756. channel_consistent_masking=self.channel_consistent_masking,
  757. mask_value=self.mask_value,
  758. )
  759. elif self.mask_type == "forecast":
  760. masked_input, mask = forecast_masking(
  761. inputs=patch_input,
  762. num_forecast_mask_patches=self.num_forecast_mask_patches,
  763. unmasked_channel_indices=self.unmasked_channel_indices,
  764. mask_value=self.mask_value,
  765. )
  766. else:
  767. raise ValueError(f"Invalid mask type {self.mask_type}.")
  768. # mask: [bs x num_input_channels x num_patch]
  769. mask = mask.bool()
  770. return masked_input, mask
  771. # Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTStdScaler with PatchTST->PatchTSMixer
  772. class PatchTSMixerStdScaler(nn.Module):
  773. """
  774. Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
  775. subtracting from the mean and dividing by the standard deviation.
  776. """
  777. def __init__(self, config: PatchTSMixerConfig):
  778. super().__init__()
  779. self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
  780. self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
  781. self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5
  782. def forward(
  783. self, data: torch.Tensor, observed_indicator: torch.Tensor
  784. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  785. """
  786. Parameters:
  787. data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
  788. input for Batch norm calculation
  789. observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
  790. Calculating the scale on the observed indicator.
  791. Returns:
  792. tuple of `torch.Tensor` of shapes
  793. (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
  794. `(batch_size, 1, num_input_channels)`)
  795. """
  796. denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim)
  797. denominator = denominator.clamp_min(1.0)
  798. loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator
  799. variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
  800. scale = torch.sqrt(variance + self.minimum_scale)
  801. return (data - loc) / scale, loc, scale
  802. # Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTMeanScaler with PatchTST->PatchTSMixer
  803. class PatchTSMixerMeanScaler(nn.Module):
  804. """
  805. Computes a scaling factor as the weighted average absolute value along the first dimension, and scales the data
  806. accordingly.
  807. """
  808. def __init__(self, config: PatchTSMixerConfig):
  809. super().__init__()
  810. self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
  811. self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
  812. self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-10
  813. self.default_scale = config.default_scale if hasattr(config, "default_scale") else None
  814. def forward(
  815. self, data: torch.Tensor, observed_indicator: torch.Tensor
  816. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  817. """
  818. Parameters:
  819. data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
  820. input for Batch norm calculation
  821. observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
  822. Calculating the scale on the observed indicator.
  823. Returns:
  824. tuple of `torch.Tensor` of shapes
  825. (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
  826. `(batch_size, 1, num_input_channels)`)
  827. """
  828. ts_sum = (data * observed_indicator).abs().sum(self.dim, keepdim=True)
  829. num_observed = observed_indicator.sum(self.dim, keepdim=True)
  830. scale = ts_sum / torch.clamp(num_observed, min=1)
  831. # If `default_scale` is provided, we use it, otherwise we use the scale
  832. # of the batch.
  833. if self.default_scale is None:
  834. batch_sum = ts_sum.sum(dim=0)
  835. batch_observations = torch.clamp(num_observed.sum(0), min=1)
  836. default_scale = torch.squeeze(batch_sum / batch_observations)
  837. else:
  838. default_scale = self.default_scale * torch.ones_like(scale)
  839. # apply default scale where there are no observations
  840. scale = torch.where(num_observed > 0, scale, default_scale)
  841. # ensure the scale is at least `self.minimum_scale`
  842. scale = torch.clamp(scale, min=self.minimum_scale)
  843. scaled_data = data / scale
  844. if not self.keepdim:
  845. scale = scale.squeeze(dim=self.dim)
  846. return scaled_data, torch.zeros_like(scale), scale
  847. # Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTNOPScaler with PatchTST->PatchTSMixer
  848. class PatchTSMixerNOPScaler(nn.Module):
  849. """
  850. Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data.
  851. """
  852. def __init__(self, config: PatchTSMixerConfig):
  853. super().__init__()
  854. self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
  855. self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
  856. def forward(
  857. self, data: torch.Tensor, observed_indicator: torch.Tensor | None = None
  858. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  859. """
  860. Parameters:
  861. data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
  862. input for Batch norm calculation
  863. Returns:
  864. tuple of `torch.Tensor` of shapes
  865. (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
  866. `(batch_size, 1, num_input_channels)`)
  867. """
  868. scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
  869. loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
  870. return data, loc, scale
  871. @dataclass
  872. @auto_docstring(
  873. custom_intro="""
  874. Base class for `PatchTSMixerEncoderOutput`, with potential hidden states.
  875. """
  876. )
  877. class PatchTSMixerEncoderOutput(ModelOutput):
  878. r"""
  879. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, d_model)`):
  880. Hidden-state at the output of the last layer of the model.
  881. hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  882. Hidden-states of the model at the output of each layer.
  883. """
  884. last_hidden_state: torch.FloatTensor | None = None
  885. hidden_states: tuple[torch.FloatTensor] | None = None
  886. class PatchTSMixerEncoder(PatchTSMixerPreTrainedModel):
  887. """
  888. Encoder for PatchTSMixer which inputs patched time-series and outputs patched embeddings.
  889. Args:
  890. config (`PatchTSMixerConfig`):
  891. Configuration.
  892. """
  893. def __init__(self, config: PatchTSMixerConfig):
  894. super().__init__(config)
  895. self.return_dict = config.return_dict
  896. self.patcher = nn.Linear(config.patch_length, config.d_model)
  897. if config.use_positional_encoding:
  898. self.positional_encoder = PatchTSMixerPositionalEncoding(config=config)
  899. else:
  900. self.positional_encoder = None
  901. self.mlp_mixer_encoder = PatchTSMixerBlock(config=config)
  902. # Initialize weights and apply final processing
  903. self.post_init()
  904. @auto_docstring
  905. def forward(
  906. self,
  907. past_values: torch.Tensor,
  908. output_hidden_states: bool | None = False,
  909. return_dict: bool | None = None,
  910. **kwargs,
  911. ) -> tuple | PatchTSMixerEncoderOutput:
  912. r"""
  913. past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
  914. Context values of the time series. For a pretraining task, this denotes the input time series to
  915. predict the masked portion. For a forecasting task, this denotes the history/past time series values.
  916. Similarly, for classification or regression tasks, it denotes the appropriate context values of the
  917. time series.
  918. For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series,
  919. it is greater than 1.
  920. Returns:
  921. `torch.FloatTensor` of shape `(batch_size, n_vars, num_patches, d_model)`
  922. """
  923. return_dict = return_dict if return_dict is not None else self.return_dict
  924. # flatten [bs x num_patch x d_model]. common_channel/mix_channel: [bs x n_vars x num_patch x d_model]
  925. patches = self.patcher(past_values)
  926. # add positional encoder
  927. if self.positional_encoder is not None:
  928. patches = self.positional_encoder(patches)
  929. last_hidden_state, hidden_states = self.mlp_mixer_encoder(patches, output_hidden_states=output_hidden_states)
  930. if not return_dict:
  931. return tuple(
  932. v
  933. for v in [
  934. last_hidden_state,
  935. hidden_states,
  936. ]
  937. )
  938. return PatchTSMixerEncoderOutput(last_hidden_state=last_hidden_state, hidden_states=hidden_states)
  939. @dataclass
  940. @auto_docstring(
  941. custom_intro="""
  942. Base class for model's outputs, with potential hidden states.
  943. """
  944. )
  945. class PatchTSMixerModelOutput(ModelOutput):
  946. r"""
  947. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, d_model)`):
  948. Hidden-state at the output of the last layer of the model.
  949. hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  950. Hidden-states of the model at the output of each layer.
  951. patch_input (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
  952. Patched input data to the model.
  953. mask (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches)`, *optional*):
  954. Bool Tensor indicating True in masked patches and False otherwise.
  955. loc (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
  956. Gives the mean of the context window per channel. Used for revin denorm outside the model, if revin
  957. enabled.
  958. scale (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
  959. Gives the std dev of the context window per channel. Used for revin denorm outside the model, if revin
  960. enabled.
  961. """
  962. last_hidden_state: torch.FloatTensor | None = None
  963. hidden_states: tuple[torch.FloatTensor] | None = None
  964. patch_input: torch.FloatTensor | None = None
  965. mask: torch.FloatTensor | None = None
  966. loc: torch.FloatTensor | None = None
  967. scale: torch.FloatTensor | None = None
  968. @auto_docstring(
  969. custom_intro="""
  970. The PatchTSMixer Model for time-series forecasting.
  971. """
  972. )
  973. class PatchTSMixerModel(PatchTSMixerPreTrainedModel):
  974. def __init__(self, config: PatchTSMixerConfig, mask_input: bool = False):
  975. r"""
  976. mask_input (bool, *optional*, defaults to `False`):
  977. Whether to mask the input using the [`PatchTSMixerMasking`] module.
  978. """
  979. super().__init__(config)
  980. self.return_dict = config.return_dict
  981. self.encoder = PatchTSMixerEncoder(config)
  982. self.patching = PatchTSMixerPatchify(config)
  983. if mask_input is True:
  984. self.masking = PatchTSMixerMasking(config)
  985. else:
  986. self.masking = None
  987. if config.scaling == "mean":
  988. self.scaler = PatchTSMixerMeanScaler(config)
  989. elif config.scaling == "std" or config.scaling is True:
  990. self.scaler = PatchTSMixerStdScaler(config)
  991. else:
  992. self.scaler = PatchTSMixerNOPScaler(config)
  993. # Initialize weights and apply final processing
  994. self.post_init()
  995. @auto_docstring
  996. def forward(
  997. self,
  998. past_values: torch.Tensor,
  999. observed_mask: torch.Tensor | None = None,
  1000. output_hidden_states: bool | None = False,
  1001. return_dict: bool | None = None,
  1002. **kwargs,
  1003. ) -> PatchTSMixerModelOutput:
  1004. r"""
  1005. past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
  1006. Context values of the time series. For a pretraining task, this denotes the input time series to predict
  1007. the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
  1008. for classification or regression tasks, it denotes the appropriate context values of the time series.
  1009. For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
  1010. greater than 1.
  1011. observed_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
  1012. Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
  1013. in `[0, 1]`:
  1014. - 1 for values that are **observed**,
  1015. - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
  1016. """
  1017. return_dict = return_dict if return_dict is not None else self.return_dict
  1018. mask = None
  1019. if observed_mask is None:
  1020. observed_mask = torch.ones_like(past_values)
  1021. scaled_past_values, loc, scale = self.scaler(past_values, observed_mask)
  1022. patched_x = self.patching(scaled_past_values) # [batch_size x num_input_channels x num_patch x patch_length
  1023. enc_input = patched_x
  1024. if self.masking is not None:
  1025. enc_input, mask = self.masking(patched_x)
  1026. # enc_input: [batch_size x num_input_channels x num_patch x patch_length]
  1027. # mask: [batch_size x num_input_channels x num_patch]
  1028. encoder_output = self.encoder(
  1029. enc_input,
  1030. output_hidden_states=output_hidden_states,
  1031. return_dict=return_dict,
  1032. )
  1033. if isinstance(encoder_output, tuple):
  1034. encoder_output = PatchTSMixerEncoderOutput(*encoder_output)
  1035. if not return_dict:
  1036. return tuple(
  1037. v
  1038. for v in [
  1039. encoder_output.last_hidden_state,
  1040. encoder_output.hidden_states,
  1041. patched_x,
  1042. mask,
  1043. loc,
  1044. scale,
  1045. ]
  1046. )
  1047. return PatchTSMixerModelOutput(
  1048. last_hidden_state=encoder_output.last_hidden_state,
  1049. hidden_states=encoder_output.hidden_states,
  1050. patch_input=patched_x,
  1051. mask=mask,
  1052. loc=loc,
  1053. scale=scale,
  1054. )
  1055. @dataclass
  1056. @auto_docstring(
  1057. custom_intro="""
  1058. Output type of [`PatchTSMixerForPreTrainingOutput`].
  1059. """
  1060. )
  1061. class PatchTSMixerForPreTrainingOutput(ModelOutput):
  1062. r"""
  1063. loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
  1064. Total loss
  1065. prediction_outputs (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, patch_length)`):
  1066. Prediction output from the pretrain head.
  1067. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
  1068. Backbone embeddings before passing through the head.
  1069. hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  1070. Hidden-states of the model at the output of each layer.
  1071. """
  1072. loss: torch.FloatTensor | None = None
  1073. prediction_outputs: torch.FloatTensor | None = None
  1074. last_hidden_state: torch.FloatTensor | None = None
  1075. hidden_states: tuple[torch.FloatTensor] | None = None
  1076. @auto_docstring(
  1077. custom_intro="""
  1078. `PatchTSMixer` for mask pretraining.
  1079. """
  1080. )
  1081. class PatchTSMixerForPretraining(PatchTSMixerPreTrainedModel):
  1082. def __init__(self, config: PatchTSMixerConfig):
  1083. super().__init__(config)
  1084. self.model = PatchTSMixerModel(config, mask_input=True)
  1085. self.head = PatchTSMixerPretrainHead(config=config)
  1086. self.masked_loss = config.masked_loss
  1087. self.return_dict = config.return_dict
  1088. # Initialize weights and apply final processing
  1089. self.post_init()
  1090. @auto_docstring
  1091. def forward(
  1092. self,
  1093. past_values: torch.Tensor,
  1094. observed_mask: torch.Tensor | None = None,
  1095. output_hidden_states: bool | None = False,
  1096. return_loss: bool = True,
  1097. return_dict: bool | None = None,
  1098. **kwargs,
  1099. ) -> PatchTSMixerForPreTrainingOutput:
  1100. r"""
  1101. past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
  1102. Context values of the time series. For a pretraining task, this denotes the input time series to predict
  1103. the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
  1104. for classification or regression tasks, it denotes the appropriate context values of the time series.
  1105. For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
  1106. greater than 1.
  1107. observed_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
  1108. Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
  1109. in `[0, 1]`:
  1110. - 1 for values that are **observed**,
  1111. - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
  1112. return_loss (`bool`, *optional*):
  1113. Whether to return the loss in the `forward` call.
  1114. """
  1115. return_dict = return_dict if return_dict is not None else self.return_dict
  1116. if self.masked_loss is True:
  1117. loss = torch.nn.MSELoss(reduction="none")
  1118. else:
  1119. loss = torch.nn.MSELoss(reduction="mean")
  1120. # past_values: tensor [batch_size x context_length x num_input_channels]
  1121. model_output = self.model(
  1122. past_values,
  1123. observed_mask=observed_mask,
  1124. output_hidden_states=output_hidden_states,
  1125. return_dict=return_dict,
  1126. ) # x.last_hidden_state: [batch_size x nvars x num_patch x d_model]
  1127. if isinstance(model_output, tuple):
  1128. model_output = PatchTSMixerModelOutput(*model_output)
  1129. x_hat = self.head(model_output.last_hidden_state) # tensor [batch_size x nvars x num_patch x patch_length]
  1130. if return_loss is True:
  1131. loss_val = loss(x_hat, model_output.patch_input)
  1132. else:
  1133. loss_val = None
  1134. # calculate masked_loss
  1135. if self.masked_loss is True and loss_val is not None:
  1136. loss_val = (loss_val.mean(dim=-1) * model_output.mask).sum() / (model_output.mask.sum() + 1e-10)
  1137. if not return_dict:
  1138. return tuple(
  1139. v
  1140. for v in [
  1141. loss_val,
  1142. x_hat,
  1143. model_output.last_hidden_state,
  1144. model_output.hidden_states,
  1145. ]
  1146. )
  1147. return PatchTSMixerForPreTrainingOutput(
  1148. loss=loss_val,
  1149. prediction_outputs=x_hat, # tensor [batch_size x nvars x num_patch x patch_length]
  1150. last_hidden_state=model_output.last_hidden_state, # x: [batch_size x nvars x num_patch x d_model]
  1151. hidden_states=model_output.hidden_states,
  1152. )
  1153. @dataclass
  1154. @auto_docstring(
  1155. custom_intro="""
  1156. Output type of [`PatchTSMixerForPredictionOutput`].
  1157. """
  1158. )
  1159. class PatchTSMixerForPredictionOutput(ModelOutput):
  1160. r"""
  1161. loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
  1162. Total loss.
  1163. prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_input_channels)`):
  1164. Prediction output from the forecast head.
  1165. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
  1166. Backbone embeddings before passing through the head.
  1167. hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  1168. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
  1169. loc (`torch.FloatTensor`, *optional* of shape `(batch_size, 1, num_input_channels)`):
  1170. Input mean
  1171. scale (`torch.FloatTensor`, *optional* of shape `(batch_size, 1, num_input_channels)`):
  1172. Input std dev
  1173. """
  1174. loss: torch.FloatTensor | None = None
  1175. prediction_outputs: torch.FloatTensor | None = None
  1176. last_hidden_state: torch.FloatTensor | None = None
  1177. hidden_states: tuple[torch.FloatTensor] | None = None
  1178. loc: torch.FloatTensor | None = None
  1179. scale: torch.FloatTensor | None = None
  1180. @dataclass
  1181. @auto_docstring(
  1182. custom_intro="""
  1183. Base class for time series model's predictions outputs that contains the sampled values from the chosen
  1184. distribution.
  1185. """
  1186. )
  1187. class SamplePatchTSMixerPredictionOutput(ModelOutput):
  1188. r"""
  1189. sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length, number_channels)`):
  1190. Sampled values from the chosen distribution.
  1191. """
  1192. sequences: torch.FloatTensor | None = None
  1193. @dataclass
  1194. @auto_docstring(
  1195. custom_intro="""
  1196. Base class for time series model's predictions outputs that contains the sampled values from the chosen
  1197. distribution.
  1198. """
  1199. )
  1200. class SamplePatchTSMixerRegressionOutput(ModelOutput):
  1201. r"""
  1202. sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length, number_channels)`):
  1203. Sampled values from the chosen distribution.
  1204. """
  1205. sequences: torch.FloatTensor | None = None
  1206. # Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.nll
  1207. def nll(input: torch.distributions.Distribution, target: torch.Tensor) -> torch.Tensor:
  1208. """
  1209. Computes the negative log likelihood loss from input distribution with respect to target.
  1210. """
  1211. return -input.log_prob(target)
  1212. # Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.weighted_average
  1213. def weighted_average(input_tensor: torch.Tensor, weights: torch.Tensor | None = None, dim=None) -> torch.Tensor:
  1214. """
  1215. Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
  1216. meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
  1217. Args:
  1218. input_tensor (`torch.FloatTensor`):
  1219. Input tensor, of which the average must be computed.
  1220. weights (`torch.FloatTensor`, *optional*):
  1221. Weights tensor, of the same shape as `input_tensor`.
  1222. dim (`int`, *optional*):
  1223. The dim along which to average `input_tensor`.
  1224. Returns:
  1225. `torch.FloatTensor`: The tensor with values averaged along the specified `dim`.
  1226. """
  1227. if weights is not None:
  1228. weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
  1229. sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
  1230. return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
  1231. else:
  1232. return input_tensor.mean(dim=dim)
  1233. class PatchTSMixerForPrediction(PatchTSMixerPreTrainedModel):
  1234. r"""
  1235. `PatchTSMixer` for forecasting application.
  1236. Args:
  1237. config (`PatchTSMixerConfig`):
  1238. Configuration.
  1239. Returns:
  1240. `None`.
  1241. """
  1242. def __init__(self, config: PatchTSMixerConfig):
  1243. super().__init__(config)
  1244. self.loss = config.loss
  1245. self.return_dict = config.return_dict
  1246. self.prediction_channel_indices = config.prediction_channel_indices
  1247. self.num_parallel_samples = config.num_parallel_samples
  1248. if config.loss == "mse":
  1249. self.distribution_output = None
  1250. else:
  1251. dim = config.prediction_length
  1252. distribution_output_map = {
  1253. "student_t": StudentTOutput,
  1254. "normal": NormalOutput,
  1255. "negative_binomial": NegativeBinomialOutput,
  1256. }
  1257. output_class = distribution_output_map.get(config.distribution_output)
  1258. if output_class is not None:
  1259. self.distribution_output = output_class(dim=dim)
  1260. else:
  1261. raise ValueError(f"Unknown distribution output {config.distribution_output}")
  1262. self.model = PatchTSMixerModel(config)
  1263. self.head = PatchTSMixerForPredictionHead(
  1264. config=config,
  1265. distribution_output=self.distribution_output,
  1266. )
  1267. # Initialize weights and apply final processing
  1268. self.post_init()
  1269. @auto_docstring
  1270. def forward(
  1271. self,
  1272. past_values: torch.Tensor,
  1273. observed_mask: torch.Tensor | None = None,
  1274. future_values: torch.Tensor | None = None,
  1275. output_hidden_states: bool | None = False,
  1276. return_loss: bool = True,
  1277. return_dict: bool | None = None,
  1278. **kwargs,
  1279. ) -> PatchTSMixerForPredictionOutput:
  1280. r"""
  1281. past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
  1282. Context values of the time series. For a pretraining task, this denotes the input time series to predict
  1283. the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
  1284. for classification or regression tasks, it denotes the appropriate context values of the time series.
  1285. For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
  1286. greater than 1.
  1287. observed_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
  1288. Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
  1289. in `[0, 1]`:
  1290. - 1 for values that are **observed**,
  1291. - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
  1292. future_values (`torch.FloatTensor` of shape `(batch_size, target_len, num_input_channels)` for forecasting,:
  1293. `(batch_size, num_targets)` for regression, or `(batch_size,)` for classification, *optional*):
  1294. Target values of the time series, that serve as labels for the model. The `future_values` is what the
  1295. Transformer needs during training to learn to output, given the `past_values`. Note that, this is NOT
  1296. required for a pretraining task.
  1297. For a forecasting task, the shape is be `(batch_size, target_len, num_input_channels)`. Even if we want
  1298. to forecast only specific channels by setting the indices in `prediction_channel_indices` parameter,
  1299. pass the target data with all channels, as channel Filtering for both prediction and target will be
  1300. manually applied before the loss computation.
  1301. return_loss (`bool`, *optional*):
  1302. Whether to return the loss in the `forward` call.
  1303. """
  1304. if self.loss == "mse":
  1305. loss = nn.MSELoss(reduction="mean")
  1306. elif self.loss == "nll":
  1307. loss = nll
  1308. else:
  1309. raise ValueError("Invalid loss function: Allowed values: mse and nll")
  1310. return_dict = return_dict if return_dict is not None else self.return_dict
  1311. # past_values: tensor [batch_size x context_length x num_input_channels]
  1312. model_output = self.model(
  1313. past_values,
  1314. observed_mask=observed_mask,
  1315. output_hidden_states=output_hidden_states,
  1316. return_dict=return_dict,
  1317. ) # model_output: [batch_size x nvars x num_patch x d_model]
  1318. if isinstance(model_output, tuple):
  1319. model_output = PatchTSMixerModelOutput(*model_output)
  1320. # tensor [batch_size x prediction_length x num_input_channels]
  1321. y_hat = self.head(model_output.last_hidden_state)
  1322. loss_val = None
  1323. if self.prediction_channel_indices is not None:
  1324. if self.distribution_output:
  1325. distribution = self.distribution_output.distribution(
  1326. y_hat,
  1327. loc=model_output.loc[..., self.prediction_channel_indices],
  1328. scale=model_output.scale[..., self.prediction_channel_indices],
  1329. )
  1330. if future_values is not None and return_loss is True:
  1331. loss_val = loss(
  1332. distribution,
  1333. future_values[..., self.prediction_channel_indices],
  1334. )
  1335. # take average of the loss
  1336. loss_val = weighted_average(loss_val)
  1337. else:
  1338. y_hat = (
  1339. y_hat * model_output.scale[..., self.prediction_channel_indices]
  1340. + model_output.loc[..., self.prediction_channel_indices]
  1341. )
  1342. if future_values is not None and return_loss is True:
  1343. loss_val = loss(y_hat, future_values[..., self.prediction_channel_indices])
  1344. else:
  1345. if self.distribution_output:
  1346. distribution = self.distribution_output.distribution(
  1347. y_hat, loc=model_output.loc, scale=model_output.scale
  1348. )
  1349. if future_values is not None and return_loss is True:
  1350. loss_val = loss(distribution, future_values)
  1351. loss_val = weighted_average(loss_val)
  1352. else:
  1353. y_hat = y_hat * model_output.scale + model_output.loc
  1354. if future_values is not None and return_loss is True:
  1355. loss_val = loss(y_hat, future_values)
  1356. if self.prediction_channel_indices is not None:
  1357. loc = model_output.loc[..., self.prediction_channel_indices]
  1358. scale = model_output.scale[..., self.prediction_channel_indices]
  1359. else:
  1360. loc = model_output.loc
  1361. scale = model_output.scale
  1362. if not return_dict:
  1363. return tuple(
  1364. v
  1365. for v in [
  1366. loss_val,
  1367. y_hat,
  1368. model_output.last_hidden_state,
  1369. model_output.hidden_states,
  1370. loc,
  1371. scale,
  1372. ]
  1373. )
  1374. return PatchTSMixerForPredictionOutput(
  1375. loss=loss_val,
  1376. prediction_outputs=y_hat, # tensor [batch_size x prediction_length x num_input_channels]
  1377. last_hidden_state=model_output.last_hidden_state, # x: [batch_size x nvars x num_patch x d_model]
  1378. hidden_states=model_output.hidden_states,
  1379. loc=loc,
  1380. scale=scale,
  1381. )
  1382. @torch.no_grad()
  1383. def generate(
  1384. self,
  1385. past_values: torch.Tensor,
  1386. observed_mask: torch.Tensor | None = None,
  1387. ) -> SamplePatchTSMixerPredictionOutput:
  1388. """
  1389. Generate sequences of sample predictions from a model with a probability distribution head.
  1390. Args:
  1391. past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
  1392. Past values of the time series that serves as context in order to predict the future.
  1393. observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
  1394. Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
  1395. in `[0, 1]`:
  1396. - 1 for values that are **observed**,
  1397. - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
  1398. Return:
  1399. [`SamplePatchTSMixerPredictionOutput`] where the outputs `sequences` tensor will have shape `(batch_size,
  1400. number of samples, prediction_length, num_input_channels)`.
  1401. """
  1402. # get number of samples
  1403. num_parallel_samples = self.num_parallel_samples
  1404. # get model output
  1405. outputs = self(
  1406. past_values=past_values,
  1407. future_values=None,
  1408. observed_mask=observed_mask,
  1409. output_hidden_states=False,
  1410. )
  1411. # get distribution
  1412. distribution = self.distribution_output.distribution(
  1413. outputs.prediction_outputs, loc=outputs.loc, scale=outputs.scale
  1414. )
  1415. # get samples: list of [batch_size x prediction_length x num_channels]
  1416. samples = [distribution.sample() for _ in range(num_parallel_samples)]
  1417. # stack tensors
  1418. samples = torch.stack(samples, dim=1) # [batch_size x num_samples x prediction_length x num_channels]
  1419. return SamplePatchTSMixerPredictionOutput(sequences=samples)
  1420. @dataclass
  1421. @auto_docstring(
  1422. custom_intro="""
  1423. Output type of [`PatchTSMixerForTimeSeriesClassificationOutput`].
  1424. """
  1425. )
  1426. class PatchTSMixerForTimeSeriesClassificationOutput(ModelOutput):
  1427. r"""
  1428. loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
  1429. Total loss.
  1430. prediction_outputs (`torch.FloatTensor` of shape `(batch_size, num_labels)`):
  1431. Prediction output from the classification head.
  1432. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
  1433. Backbone embeddings before passing through the head.
  1434. hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  1435. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
  1436. """
  1437. loss: torch.FloatTensor | None = None
  1438. prediction_outputs: torch.FloatTensor | None = None
  1439. last_hidden_state: torch.FloatTensor | None = None
  1440. hidden_states: tuple[torch.FloatTensor] | None = None
  1441. class PatchTSMixerForTimeSeriesClassification(PatchTSMixerPreTrainedModel):
  1442. r"""
  1443. `PatchTSMixer` for classification application.
  1444. Args:
  1445. config (`PatchTSMixerConfig`):
  1446. Configuration.
  1447. Returns:
  1448. `None`.
  1449. """
  1450. def __init__(self, config: PatchTSMixerConfig):
  1451. super().__init__(config)
  1452. self.model = PatchTSMixerModel(config)
  1453. self.head = PatchTSMixerLinearHead(
  1454. config=config,
  1455. )
  1456. self.return_dict = config.return_dict
  1457. if config.scaling in ["std", "mean", True]:
  1458. self.inject_scale = InjectScalerStatistics4D(d_model=config.d_model, num_patches=config.num_patches)
  1459. else:
  1460. self.inject_scale = None
  1461. # Initialize weights and apply final processing
  1462. self.post_init()
  1463. @auto_docstring
  1464. def forward(
  1465. self,
  1466. past_values: torch.Tensor,
  1467. target_values: torch.Tensor | None = None,
  1468. output_hidden_states: bool | None = False,
  1469. return_loss: bool = True,
  1470. return_dict: bool | None = None,
  1471. **kwargs,
  1472. ) -> PatchTSMixerForTimeSeriesClassificationOutput:
  1473. r"""
  1474. past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
  1475. Context values of the time series. For a pretraining task, this denotes the input time series to predict
  1476. the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
  1477. for classification or regression tasks, it denotes the appropriate context values of the time series.
  1478. For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
  1479. greater than 1.
  1480. target_values (`torch.FloatTensor` of shape `(batch_size, target_len, num_input_channels)` for forecasting,
  1481. `(batch_size, num_targets)` for regression, or `(batch_size,)` for classification, *optional*):
  1482. Target
  1483. values of the time series, that serve as labels for the model. The `target_values` is what the
  1484. Transformer needs during training to learn to output, given the `past_values`. Note that, this is NOT
  1485. required for a pretraining task.
  1486. For a forecasting task, the shape is be `(batch_size, target_len, num_input_channels)`. Even if we want
  1487. to forecast only specific channels by setting the indices in `prediction_channel_indices` parameter,
  1488. pass the target data with all channels, as channel Filtering for both prediction and target will be
  1489. manually applied before the loss computation.
  1490. For a classification task, it has a shape of `(batch_size,)`.
  1491. For a regression task, it has a shape of `(batch_size, num_targets)`.
  1492. return_loss (`bool`, *optional*):
  1493. Whether to return the loss in the `forward` call.
  1494. """
  1495. loss = torch.nn.CrossEntropyLoss()
  1496. return_dict = return_dict if return_dict is not None else self.return_dict
  1497. model_output = self.model(
  1498. past_values,
  1499. output_hidden_states=output_hidden_states,
  1500. return_dict=return_dict,
  1501. ) # x: [batch_size x nvars x num_patch x d_model]
  1502. if isinstance(model_output, tuple):
  1503. model_output = PatchTSMixerModelOutput(*model_output)
  1504. if self.inject_scale is not None:
  1505. model_output.last_hidden_state = self.inject_scale(
  1506. model_output.last_hidden_state,
  1507. loc=model_output.loc,
  1508. scale=model_output.scale,
  1509. ) # x: [batch_size x nvars x num_patch x d_model]
  1510. y_hat = self.head(model_output.last_hidden_state) # tensor [batch_size x n_labels]
  1511. if target_values is not None and return_loss is True:
  1512. loss_val = loss(y_hat, target_values)
  1513. else:
  1514. loss_val = None
  1515. if not return_dict:
  1516. return tuple(
  1517. v
  1518. for v in [
  1519. loss_val,
  1520. y_hat,
  1521. model_output.last_hidden_state,
  1522. model_output.hidden_states,
  1523. ]
  1524. )
  1525. return PatchTSMixerForTimeSeriesClassificationOutput(
  1526. loss=loss_val,
  1527. prediction_outputs=y_hat, # tensor [batch_size x n_labels]
  1528. last_hidden_state=model_output.last_hidden_state, # x: [batch_size x nvars x num_patch x d_model]
  1529. hidden_states=model_output.hidden_states,
  1530. )
  1531. @dataclass
  1532. @auto_docstring(
  1533. custom_intro="""
  1534. Output type of [`PatchTSMixerForRegressionOutput`].
  1535. """
  1536. )
  1537. class PatchTSMixerForRegressionOutput(ModelOutput):
  1538. r"""
  1539. loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
  1540. Total loss.
  1541. regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
  1542. Prediction output from the regression head.
  1543. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`):
  1544. Backbone embeddings before passing through the head.
  1545. hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  1546. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
  1547. """
  1548. loss: torch.FloatTensor | None = None
  1549. regression_outputs: torch.FloatTensor | None = None
  1550. last_hidden_state: torch.FloatTensor | None = None
  1551. hidden_states: tuple[torch.FloatTensor] | None = None
  1552. class InjectScalerStatistics4D(nn.Module):
  1553. def __init__(self, d_model: int, num_patches: int, expansion: int = 2):
  1554. super().__init__()
  1555. self.inverse_trans_expansion = nn.Linear(d_model + 2, expansion * d_model)
  1556. self.inverse_trans_compression = nn.Linear(expansion * d_model, d_model)
  1557. self.map_scale_expansion = nn.Linear(2, 2 * expansion)
  1558. self.map_scale_compression = nn.Linear(2 * expansion, 2)
  1559. self.num_patches = num_patches
  1560. def forward(self, inputs: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor):
  1561. """
  1562. Args:
  1563. inputs (`torch.Tensor` of shape `(batch_size, num_input_channels, num_patch, d_model)`)
  1564. loc (`torch.Tensor` of shape `(batch_size, 1, num_input_channels)`)
  1565. scale (`torch.Tensor` of shape `(batch_size, 1, num_input_channels)`)
  1566. Returns:
  1567. `torch.Tensor` of shape `(batch_size, num_input_channels, num_patch, d_model)`
  1568. """
  1569. mean = loc.transpose(-1, -2) # [batch_size x n_channels x 1 ]
  1570. mean = mean.unsqueeze(-2) # [batch_size x n_channels x 1 x 1]
  1571. mean = mean.repeat(1, 1, self.num_patches, 1) # [batch_size x n_channels x num_patch x 1]
  1572. stdev = scale.transpose(-1, -2) # [batch_size x n_channels x 1 ]
  1573. stdev = stdev.unsqueeze(-2) # [batch_size x n_channels x 1 x 1]
  1574. stdev = stdev.repeat(1, 1, self.num_patches, 1) # [batch_size x n_channels x num_patch x 1]
  1575. concat_stats = torch.cat([mean, stdev], dim=-1) # [batch_size x n_channels x num_patch x 2]
  1576. concat_stats = self.map_scale_expansion(concat_stats) # [batch_size x n_channels x num_patch x (2*expansion)]
  1577. concat_stats = self.map_scale_compression(concat_stats) # [batch_size x n_channels x num_patch x 2]
  1578. inputs = torch.cat([inputs, concat_stats], dim=-1) # [batch_size x channels x num_patch x d_model+2]
  1579. inputs = self.inverse_trans_expansion(inputs) # [batch_size x channels x num_patch x (expansion*d_model)]
  1580. inputs = self.inverse_trans_compression(inputs) # [batch_size x channels x num_patch x d_model]
  1581. return inputs
  1582. @auto_docstring(
  1583. custom_intro="""
  1584. `PatchTSMixer` for regression application.
  1585. """
  1586. )
  1587. class PatchTSMixerForRegression(PatchTSMixerPreTrainedModel):
  1588. def __init__(self, config: PatchTSMixerConfig):
  1589. super().__init__(config)
  1590. self.model = PatchTSMixerModel(config)
  1591. self.loss = config.loss
  1592. self.distribution_output = config.distribution_output
  1593. self.return_dict = config.return_dict
  1594. self.num_parallel_samples = config.num_parallel_samples
  1595. if config.loss == "mse":
  1596. self.distribution_output = None
  1597. else:
  1598. distribution_output_map = {
  1599. "student_t": StudentTOutput,
  1600. "normal": NormalOutput,
  1601. "negative_binomial": NegativeBinomialOutput,
  1602. }
  1603. output_class = distribution_output_map.get(config.distribution_output)
  1604. if output_class is not None:
  1605. self.distribution_output = output_class(dim=config.num_targets)
  1606. else:
  1607. raise ValueError(f"Unknown distribution output {config.distribution_output}")
  1608. if config.scaling in ["std", "mean", True]:
  1609. self.inject_scale = InjectScalerStatistics4D(d_model=config.d_model, num_patches=config.num_patches)
  1610. else:
  1611. self.inject_scale = None
  1612. self.head = PatchTSMixerLinearHead(
  1613. config=config,
  1614. distribution_output=self.distribution_output,
  1615. )
  1616. # Initialize weights and apply final processing
  1617. self.post_init()
  1618. @auto_docstring
  1619. def forward(
  1620. self,
  1621. past_values: torch.Tensor,
  1622. target_values: torch.Tensor | None = None,
  1623. output_hidden_states: bool | None = False,
  1624. return_loss: bool = True,
  1625. return_dict: bool | None = None,
  1626. **kwargs,
  1627. ) -> PatchTSMixerForRegressionOutput:
  1628. r"""
  1629. past_values (`torch.FloatTensor` of shape `(batch_size, seq_length, num_input_channels)`):
  1630. Context values of the time series. For a pretraining task, this denotes the input time series to predict
  1631. the masked portion. For a forecasting task, this denotes the history/past time series values. Similarly,
  1632. for classification or regression tasks, it denotes the appropriate context values of the time series.
  1633. For univariate time series, `num_input_channels` dimension should be 1. For multivariate time series, it is
  1634. greater than 1.
  1635. target_values (`torch.FloatTensor` of shape `(batch_size, target_len, num_input_channels)` for forecasting,
  1636. `(batch_size, num_targets)` for regression, or `(batch_size,)` for classification, *optional*):
  1637. Target values of the time series, that serve as labels for the model. The `target_values` is what the
  1638. Transformer needs during training to learn to output, given the `past_values`. Note that, this is NOT
  1639. required for a pretraining task.
  1640. For a forecasting task, the shape is be `(batch_size, target_len, num_input_channels)`. Even if we want
  1641. to forecast only specific channels by setting the indices in `prediction_channel_indices` parameter,
  1642. pass the target data with all channels, as channel Filtering for both prediction and target will be
  1643. manually applied before the loss computation.
  1644. For a classification task, it has a shape of `(batch_size,)`.
  1645. For a regression task, it has a shape of `(batch_size, num_targets)`.
  1646. return_loss (`bool`, *optional*):
  1647. Whether to return the loss in the `forward` call.
  1648. """
  1649. if self.loss == "mse":
  1650. loss = nn.MSELoss(reduction="mean")
  1651. elif self.loss == "nll":
  1652. loss = nll
  1653. else:
  1654. raise ValueError("Invalid loss function: Allowed values: mse and nll")
  1655. return_dict = return_dict if return_dict is not None else self.return_dict
  1656. model_output = self.model(
  1657. past_values,
  1658. output_hidden_states=output_hidden_states,
  1659. return_dict=return_dict,
  1660. ) # model_output: [batch_size x nvars x num_patch x d_model]
  1661. if isinstance(model_output, tuple):
  1662. model_output = PatchTSMixerModelOutput(*model_output)
  1663. if self.inject_scale is not None:
  1664. model_output.last_hidden_state = self.inject_scale(
  1665. model_output.last_hidden_state,
  1666. loc=model_output.loc,
  1667. scale=model_output.scale,
  1668. ) # x: [batch_size x nvars x num_patch x d_model]
  1669. y_hat = self.head(model_output.last_hidden_state) # [batch_size x num_targets]
  1670. if target_values is not None and return_loss is True:
  1671. if self.distribution_output:
  1672. if self.distribution_output == "negative_binomial" and torch.any(target_values < 0):
  1673. raise Exception("target_values cannot be negative for negative_binomial distribution.")
  1674. distribution = self.distribution_output.distribution(y_hat)
  1675. # y_hat should be a 2-tuple, each with dimension [bs, num_targets]
  1676. y_hat = tuple(item.view(-1, self.config.num_targets) for item in y_hat)
  1677. loss_val = loss(distribution, target_values)
  1678. # take average of the loss
  1679. loss_val = weighted_average(loss_val)
  1680. else:
  1681. loss_val = loss(y_hat, target_values)
  1682. else:
  1683. loss_val = None
  1684. if not return_dict:
  1685. return tuple(
  1686. v
  1687. for v in [
  1688. loss_val,
  1689. y_hat,
  1690. model_output.last_hidden_state,
  1691. model_output.hidden_states,
  1692. ]
  1693. )
  1694. return PatchTSMixerForRegressionOutput(
  1695. loss=loss_val,
  1696. regression_outputs=y_hat, # tensor [batch_size x num_targets]
  1697. last_hidden_state=model_output.last_hidden_state, # [batch_size x nvars x num_patch x d_model]
  1698. hidden_states=model_output.hidden_states,
  1699. )
  1700. @torch.no_grad()
  1701. def generate(
  1702. self,
  1703. past_values: torch.Tensor,
  1704. ) -> SamplePatchTSMixerRegressionOutput:
  1705. """
  1706. Generate sequences of sample predictions from a model with a probability distribution head.
  1707. Args:
  1708. past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
  1709. Past values of the time series that serves as context in order to predict the target values.
  1710. Return:
  1711. [`SamplePatchTSMixerRegressionOutput`] where the outputs `sequences` tensor will have shape `(batch_size,
  1712. number of samples, num_targets)`.
  1713. """
  1714. # get number of samples
  1715. num_parallel_samples = self.num_parallel_samples
  1716. # get model output
  1717. outputs = self(
  1718. past_values=past_values,
  1719. target_values=None,
  1720. output_hidden_states=False,
  1721. )
  1722. # get distribution
  1723. distribution = self.distribution_output.distribution(outputs.regression_outputs)
  1724. # get samples
  1725. samples = [
  1726. distribution.sample() for _ in range(num_parallel_samples)
  1727. ] # samples: list of [batch_size x num_targets]
  1728. # stack tensors
  1729. # [batch_size x num_samples x num_targets]
  1730. samples = torch.stack(samples, dim=1).view(-1, num_parallel_samples, self.config.num_targets)
  1731. return SamplePatchTSMixerRegressionOutput(sequences=samples)
  1732. __all__ = [
  1733. "PatchTSMixerPreTrainedModel",
  1734. "PatchTSMixerModel",
  1735. "PatchTSMixerForPretraining",
  1736. "PatchTSMixerForPrediction",
  1737. "PatchTSMixerForTimeSeriesClassification",
  1738. "PatchTSMixerForRegression",
  1739. ]