configuration_patchtsmixer.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # coding=utf-8
  2. # Copyright 2023 IBM and HuggingFace Inc. team. All Rights Reserved.
  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. """PatchTSMixer model configuration"""
  16. from typing import List, Optional, Union
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class PatchTSMixerConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`PatchTSMixerModel`]. It is used to instantiate a
  23. PatchTSMixer model according to the specified arguments, defining the model architecture. Instantiating a
  24. configuration with the defaults will yield a similar configuration to that of the PatchTSMixer
  25. [ibm/patchtsmixer-etth1-pretrain](https://huggingface.co/ibm/patchtsmixer-etth1-pretrain) architecture.
  26. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  27. documentation from [`PretrainedConfig`] for more information.
  28. Args:
  29. context_length (`int`, *optional*, defaults to 32):
  30. The context/history length for the input sequence.
  31. patch_length (`int`, *optional*, defaults to 8):
  32. The patch length for the input sequence.
  33. num_input_channels (`int`, *optional*, defaults to 1):
  34. Number of input variates. For Univariate, set it to 1.
  35. patch_stride (`int`, *optional*, defaults to 8):
  36. Determines the overlap between two consecutive patches. Set it to patch_length (or greater), if we want
  37. non-overlapping patches.
  38. num_parallel_samples (`int`, *optional*, defaults to 100):
  39. The number of samples to generate in parallel for probabilistic forecast.
  40. d_model (`int`, *optional*, defaults to 8):
  41. Hidden dimension of the model. Recommended to set it as a multiple of patch_length (i.e. 2-5X of
  42. patch_length). Larger value indicates more complex model.
  43. expansion_factor (`int`, *optional*, defaults to 2):
  44. Expansion factor to use inside MLP. Recommended range is 2-5. Larger value indicates more complex model.
  45. num_layers (`int`, *optional*, defaults to 3):
  46. Number of layers to use. Recommended range is 3-15. Larger value indicates more complex model.
  47. dropout (`float`, *optional*, defaults to 0.2):
  48. The dropout probability the `PatchTSMixer` backbone. Recommended range is 0.2-0.7
  49. mode (`str`, *optional*, defaults to `"common_channel"`):
  50. Mixer Mode. Determines how to process the channels. Allowed values: "common_channel", "mix_channel". In
  51. "common_channel" mode, we follow Channel-independent modelling with no explicit channel-mixing. Channel
  52. mixing happens in an implicit manner via shared weights across channels. (preferred first approach) In
  53. "mix_channel" mode, we follow explicit channel-mixing in addition to patch and feature mixer. (preferred
  54. approach when channel correlations are very important to model)
  55. gated_attn (`bool`, *optional*, defaults to `True`):
  56. Enable Gated Attention.
  57. norm_mlp (`str`, *optional*, defaults to `"LayerNorm"`):
  58. Normalization layer (BatchNorm or LayerNorm).
  59. self_attn (`bool`, *optional*, defaults to `False`):
  60. Enable Tiny self attention across patches. This can be enabled when the output of Vanilla PatchTSMixer with
  61. gated attention is not satisfactory. Enabling this leads to explicit pair-wise attention and modelling
  62. across patches.
  63. self_attn_heads (`int`, *optional*, defaults to 1):
  64. Number of self-attention heads. Works only when `self_attn` is set to `True`.
  65. use_positional_encoding (`bool`, *optional*, defaults to `False`):
  66. Enable the use of positional embedding for the tiny self-attention layers. Works only when `self_attn` is
  67. set to `True`.
  68. positional_encoding_type (`str`, *optional*, defaults to `"sincos"`):
  69. Positional encodings. Options `"random"` and `"sincos"` are supported. Works only when
  70. `use_positional_encoding` is set to `True`
  71. scaling (`string` or `bool`, *optional*, defaults to `"std"`):
  72. Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
  73. scaler is set to "mean".
  74. loss (`string`, *optional*, defaults to `"mse"`):
  75. The loss function for the model corresponding to the `distribution_output` head. For parametric
  76. distributions it is the negative log likelihood ("nll") and for point estimates it is the mean squared
  77. error "mse".
  78. init_std (`float`, *optional*, defaults to 0.02):
  79. The standard deviation of the truncated normal weight initialization distribution.
  80. post_init (`bool`, *optional*, defaults to `False`):
  81. Whether to use custom weight initialization from `transformers` library, or the default initialization in
  82. `PyTorch`. Setting it to `False` performs `PyTorch` weight initialization.
  83. norm_eps (`float`, *optional*, defaults to 1e-05):
  84. A value added to the denominator for numerical stability of normalization.
  85. mask_type (`str`, *optional*, defaults to `"random"`):
  86. Type of masking to use for Masked Pretraining mode. Allowed values are "random", "forecast". In Random
  87. masking, points are masked randomly. In Forecast masking, points are masked towards the end.
  88. random_mask_ratio (`float`, *optional*, defaults to 0.5):
  89. Masking ratio to use when `mask_type` is `random`. Higher value indicates more masking.
  90. num_forecast_mask_patches (`int` or `list`, *optional*, defaults to `[2]`):
  91. Number of patches to be masked at the end of each batch sample. If it is an integer, all the samples in the
  92. batch will have the same number of masked patches. If it is a list, samples in the batch will be randomly
  93. masked by numbers defined in the list. This argument is only used for forecast pretraining.
  94. mask_value (`float`, *optional*, defaults to `0.0`):
  95. Mask value to use.
  96. masked_loss (`bool`, *optional*, defaults to `True`):
  97. Whether to compute pretraining loss only at the masked portions, or on the entire output.
  98. channel_consistent_masking (`bool`, *optional*, defaults to `True`):
  99. When true, masking will be same across all channels of a timeseries. Otherwise, masking positions will vary
  100. across channels.
  101. unmasked_channel_indices (`list`, *optional*):
  102. Channels that are not masked during pretraining.
  103. head_dropout (`float`, *optional*, defaults to 0.2):
  104. The dropout probability the `PatchTSMixer` head.
  105. distribution_output (`string`, *optional*, defaults to `"student_t"`):
  106. The distribution emission head for the model when loss is "nll". Could be either "student_t", "normal" or
  107. "negative_binomial".
  108. prediction_length (`int`, *optional*, defaults to 16):
  109. Number of time steps to forecast for a forecasting task. Also known as the Forecast Horizon.
  110. prediction_channel_indices (`list`, *optional*):
  111. List of channel indices to forecast. If None, forecast all channels. Target data is expected to have all
  112. channels and we explicitly filter the channels in prediction and target before loss computation.
  113. num_targets (`int`, *optional*, defaults to 3):
  114. Number of targets (dimensionality of the regressed variable) for a regression task.
  115. output_range (`list`, *optional*):
  116. Output range to restrict for the regression task. Defaults to None.
  117. head_aggregation (`str`, *optional*, defaults to `"max_pool"`):
  118. Aggregation mode to enable for classification or regression task. Allowed values are `None`, "use_last",
  119. "max_pool", "avg_pool".
  120. Example:
  121. ```python
  122. >>> from transformers import PatchTSMixerConfig, PatchTSMixerModel
  123. >>> # Initializing a default PatchTSMixer configuration
  124. >>> configuration = PatchTSMixerConfig()
  125. >>> # Randomly initializing a model (with random weights) from the configuration
  126. >>> model = PatchTSMixerModel(configuration)
  127. >>> # Accessing the model configuration
  128. >>> configuration = model.config
  129. ```"""
  130. model_type = "patchtsmixer"
  131. attribute_map = {
  132. "hidden_size": "d_model",
  133. "num_hidden_layers": "num_layers",
  134. }
  135. def __init__(
  136. self,
  137. # Time series specific configuration
  138. context_length: int = 32,
  139. patch_length: int = 8,
  140. num_input_channels: int = 1,
  141. patch_stride: int = 8,
  142. num_parallel_samples: int = 100,
  143. # General model configuration
  144. d_model: int = 8,
  145. expansion_factor: int = 2,
  146. num_layers: int = 3,
  147. dropout: float = 0.2,
  148. mode: str = "common_channel",
  149. gated_attn: bool = True,
  150. norm_mlp: str = "LayerNorm",
  151. self_attn: bool = False,
  152. self_attn_heads: int = 1,
  153. use_positional_encoding: bool = False,
  154. positional_encoding_type: str = "sincos",
  155. scaling: Optional[Union[str, bool]] = "std",
  156. loss: str = "mse",
  157. init_std: float = 0.02,
  158. post_init: bool = False,
  159. norm_eps: float = 1e-5,
  160. # Pretrain model configuration
  161. mask_type: str = "random",
  162. random_mask_ratio: float = 0.5,
  163. num_forecast_mask_patches: Optional[Union[List[int], int]] = [2],
  164. mask_value: int = 0,
  165. masked_loss: bool = True,
  166. channel_consistent_masking: bool = True,
  167. unmasked_channel_indices: Optional[List[int]] = None,
  168. # General head configuration
  169. head_dropout: float = 0.2,
  170. distribution_output: str = "student_t",
  171. # Prediction head configuration
  172. prediction_length: int = 16,
  173. prediction_channel_indices: list = None,
  174. # Classification/Regression configuration
  175. num_targets: int = 3,
  176. output_range: list = None,
  177. head_aggregation: str = "max_pool",
  178. **kwargs,
  179. ):
  180. self.num_input_channels = num_input_channels
  181. self.context_length = context_length
  182. self.patch_length = patch_length
  183. self.patch_stride = patch_stride
  184. self.d_model = d_model
  185. self.expansion_factor = expansion_factor
  186. self.num_layers = num_layers
  187. self.dropout = dropout
  188. self.mode = mode
  189. self.gated_attn = gated_attn
  190. self.norm_mlp = norm_mlp
  191. self.scaling = scaling
  192. self.head_dropout = head_dropout
  193. self.num_patches = (max(context_length, patch_length) - patch_length) // patch_stride + 1
  194. self.mask_type = mask_type
  195. self.random_mask_ratio = random_mask_ratio
  196. self.num_forecast_mask_patches = num_forecast_mask_patches
  197. self.mask_value = mask_value
  198. self.channel_consistent_masking = channel_consistent_masking
  199. self.masked_loss = masked_loss
  200. self.patch_last = True
  201. self.use_positional_encoding = use_positional_encoding
  202. self.positional_encoding_type = positional_encoding_type
  203. self.prediction_length = prediction_length
  204. self.prediction_channel_indices = prediction_channel_indices
  205. self.num_targets = num_targets
  206. self.output_range = output_range
  207. self.head_aggregation = head_aggregation
  208. self.self_attn = self_attn
  209. self.self_attn_heads = self_attn_heads
  210. self.init_std = init_std
  211. self.post_init = post_init
  212. self.distribution_output = distribution_output
  213. self.loss = loss
  214. self.num_parallel_samples = num_parallel_samples
  215. self.unmasked_channel_indices = unmasked_channel_indices
  216. self.norm_eps = norm_eps
  217. super().__init__(**kwargs)