configuration_patchtst.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # coding=utf-8
  2. # Copyright 2023 The 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. """PatchTST model configuration"""
  16. from typing import Optional, Union
  17. from transformers.configuration_utils import PretrainedConfig
  18. from transformers.utils import logging
  19. logger = logging.get_logger(__name__)
  20. class PatchTSTConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of an [`PatchTSTModel`]. It is used to instantiate an
  23. PatchTST model according to the specified arguments, defining the model architecture.
  24. [ibm/patchtst](https://huggingface.co/ibm/patchtst) architecture.
  25. Configuration objects inherit from [`PretrainedConfig`] can be used to control the model outputs. Read the
  26. documentation from [`PretrainedConfig`] for more information.
  27. Args:
  28. num_input_channels (`int`, *optional*, defaults to 1):
  29. The size of the target variable which by default is 1 for univariate targets. Would be > 1 in case of
  30. multivariate targets.
  31. context_length (`int`, *optional*, defaults to 32):
  32. The context length of the input sequence.
  33. distribution_output (`str`, *optional*, defaults to `"student_t"`):
  34. The distribution emission head for the model when loss is "nll". Could be either "student_t", "normal" or
  35. "negative_binomial".
  36. loss (`str`, *optional*, defaults to `"mse"`):
  37. The loss function for the model corresponding to the `distribution_output` head. For parametric
  38. distributions it is the negative log likelihood ("nll") and for point estimates it is the mean squared
  39. error "mse".
  40. patch_length (`int`, *optional*, defaults to 1):
  41. Define the patch length of the patchification process.
  42. patch_stride (`int`, *optional*, defaults to 1):
  43. Define the stride of the patchification process.
  44. num_hidden_layers (`int`, *optional*, defaults to 3):
  45. Number of hidden layers.
  46. d_model (`int`, *optional*, defaults to 128):
  47. Dimensionality of the transformer layers.
  48. num_attention_heads (`int`, *optional*, defaults to 4):
  49. Number of attention heads for each attention layer in the Transformer encoder.
  50. share_embedding (`bool`, *optional*, defaults to `True`):
  51. Sharing the input embedding across all channels.
  52. channel_attention (`bool`, *optional*, defaults to `False`):
  53. Activate channel attention block in the Transformer to allow channels to attend each other.
  54. ffn_dim (`int`, *optional*, defaults to 512):
  55. Dimension of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  56. norm_type (`str` , *optional*, defaults to `"batchnorm"`):
  57. Normalization at each Transformer layer. Can be `"batchnorm"` or `"layernorm"`.
  58. norm_eps (`float`, *optional*, defaults to 1e-05):
  59. A value added to the denominator for numerical stability of normalization.
  60. attention_dropout (`float`, *optional*, defaults to 0.0):
  61. The dropout probability for the attention probabilities.
  62. positional_dropout (`float`, *optional*, defaults to 0.0):
  63. The dropout probability in the positional embedding layer.
  64. path_dropout (`float`, *optional*, defaults to 0.0):
  65. The dropout path in the residual block.
  66. ff_dropout (`float`, *optional*, defaults to 0.0):
  67. The dropout probability used between the two layers of the feed-forward networks.
  68. bias (`bool`, *optional*, defaults to `True`):
  69. Whether to add bias in the feed-forward networks.
  70. activation_function (`str`, *optional*, defaults to `"gelu"`):
  71. The non-linear activation function (string) in the Transformer.`"gelu"` and `"relu"` are supported.
  72. pre_norm (`bool`, *optional*, defaults to `True`):
  73. Normalization is applied before self-attention if pre_norm is set to `True`. Otherwise, normalization is
  74. applied after residual block.
  75. positional_encoding_type (`str`, *optional*, defaults to `"sincos"`):
  76. Positional encodings. Options `"random"` and `"sincos"` are supported.
  77. use_cls_token (`bool`, *optional*, defaults to `False`):
  78. Whether cls token is used.
  79. init_std (`float`, *optional*, defaults to 0.02):
  80. The standard deviation of the truncated normal weight initialization distribution.
  81. share_projection (`bool`, *optional*, defaults to `True`):
  82. Sharing the projection layer across different channels in the forecast head.
  83. scaling (`Union`, *optional*, defaults to `"std"`):
  84. Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
  85. scaler is set to "mean".
  86. do_mask_input (`bool`, *optional*):
  87. Apply masking during the pretraining.
  88. mask_type (`str`, *optional*, defaults to `"random"`):
  89. Masking type. Only `"random"` and `"forecast"` are currently supported.
  90. random_mask_ratio (`float`, *optional*, defaults to 0.5):
  91. Masking ratio applied to mask the input data during random pretraining.
  92. num_forecast_mask_patches (`int` or `list`, *optional*, defaults to `[2]`):
  93. Number of patches to be masked at the end of each batch sample. If it is an integer,
  94. all the samples in the batch will have the same number of masked patches. If it is a list,
  95. samples in the batch will be randomly masked by numbers defined in the list. This argument is only used
  96. for forecast pretraining.
  97. channel_consistent_masking (`bool`, *optional*, defaults to `False`):
  98. If channel consistent masking is True, all the channels will have the same masking pattern.
  99. unmasked_channel_indices (`list`, *optional*):
  100. Indices of channels that are not masked during pretraining. Values in the list are number between 1 and
  101. `num_input_channels`
  102. mask_value (`int`, *optional*, defaults to 0):
  103. Values in the masked patches will be filled by `mask_value`.
  104. pooling_type (`str`, *optional*, defaults to `"mean"`):
  105. Pooling of the embedding. `"mean"`, `"max"` and `None` are supported.
  106. head_dropout (`float`, *optional*, defaults to 0.0):
  107. The dropout probability for head.
  108. prediction_length (`int`, *optional*, defaults to 24):
  109. The prediction horizon that the model will output.
  110. num_targets (`int`, *optional*, defaults to 1):
  111. Number of targets for regression and classification tasks. For classification, it is the number of
  112. classes.
  113. output_range (`list`, *optional*):
  114. Output range for regression task. The range of output values can be set to enforce the model to produce
  115. values within a range.
  116. num_parallel_samples (`int`, *optional*, defaults to 100):
  117. The number of samples is generated in parallel for probabilistic prediction.
  118. ```python
  119. >>> from transformers import PatchTSTConfig, PatchTSTModel
  120. >>> # Initializing an PatchTST configuration with 12 time steps for prediction
  121. >>> configuration = PatchTSTConfig(prediction_length=12)
  122. >>> # Randomly initializing a model (with random weights) from the configuration
  123. >>> model = PatchTSTModel(configuration)
  124. >>> # Accessing the model configuration
  125. >>> configuration = model.config
  126. ```"""
  127. model_type = "patchtst"
  128. attribute_map = {
  129. "hidden_size": "d_model",
  130. "num_attention_heads": "num_attention_heads",
  131. "num_hidden_layers": "num_hidden_layers",
  132. }
  133. def __init__(
  134. self,
  135. # time series specific configuration
  136. num_input_channels: int = 1,
  137. context_length: int = 32,
  138. distribution_output: str = "student_t",
  139. loss: str = "mse",
  140. # PatchTST arguments
  141. patch_length: int = 1,
  142. patch_stride: int = 1,
  143. # Transformer architecture configuration
  144. num_hidden_layers: int = 3,
  145. d_model: int = 128,
  146. num_attention_heads: int = 4,
  147. share_embedding: bool = True,
  148. channel_attention: bool = False,
  149. ffn_dim: int = 512,
  150. norm_type: str = "batchnorm",
  151. norm_eps: float = 1e-05,
  152. attention_dropout: float = 0.0,
  153. positional_dropout: float = 0.0,
  154. path_dropout: float = 0.0,
  155. ff_dropout: float = 0.0,
  156. bias: bool = True,
  157. activation_function: str = "gelu",
  158. pre_norm: bool = True,
  159. positional_encoding_type: str = "sincos",
  160. use_cls_token: bool = False,
  161. init_std: float = 0.02,
  162. share_projection: bool = True,
  163. scaling: Optional[Union[str, bool]] = "std",
  164. # mask pretraining
  165. do_mask_input: Optional[bool] = None,
  166. mask_type: str = "random",
  167. random_mask_ratio: float = 0.5,
  168. num_forecast_mask_patches: Optional[Union[list[int], int]] = [2],
  169. channel_consistent_masking: Optional[bool] = False,
  170. unmasked_channel_indices: Optional[list[int]] = None,
  171. mask_value: int = 0,
  172. # head
  173. pooling_type: str = "mean",
  174. head_dropout: float = 0.0,
  175. prediction_length: int = 24,
  176. num_targets: int = 1,
  177. output_range: Optional[list] = None,
  178. # distribution head
  179. num_parallel_samples: int = 100,
  180. **kwargs,
  181. ):
  182. # time series specific configuration
  183. self.context_length = context_length
  184. self.num_input_channels = num_input_channels # n_vars
  185. self.loss = loss
  186. self.distribution_output = distribution_output
  187. self.num_parallel_samples = num_parallel_samples
  188. # Transformer architecture configuration
  189. self.d_model = d_model
  190. self.num_attention_heads = num_attention_heads
  191. self.ffn_dim = ffn_dim
  192. self.num_hidden_layers = num_hidden_layers
  193. self.attention_dropout = attention_dropout
  194. self.share_embedding = share_embedding
  195. self.channel_attention = channel_attention
  196. self.norm_type = norm_type
  197. self.norm_eps = norm_eps
  198. self.positional_dropout = positional_dropout
  199. self.path_dropout = path_dropout
  200. self.ff_dropout = ff_dropout
  201. self.bias = bias
  202. self.activation_function = activation_function
  203. self.pre_norm = pre_norm
  204. self.positional_encoding_type = positional_encoding_type
  205. self.use_cls_token = use_cls_token
  206. self.init_std = init_std
  207. self.scaling = scaling
  208. # PatchTST parameters
  209. self.patch_length = patch_length
  210. self.patch_stride = patch_stride
  211. # Mask pretraining
  212. self.do_mask_input = do_mask_input
  213. self.mask_type = mask_type
  214. self.random_mask_ratio = random_mask_ratio # for random masking
  215. self.num_forecast_mask_patches = num_forecast_mask_patches # for forecast masking
  216. self.channel_consistent_masking = channel_consistent_masking
  217. self.unmasked_channel_indices = unmasked_channel_indices
  218. self.mask_value = mask_value
  219. # general head params
  220. self.pooling_type = pooling_type
  221. self.head_dropout = head_dropout
  222. # For prediction head
  223. self.share_projection = share_projection
  224. self.prediction_length = prediction_length
  225. # For prediction and regression head
  226. self.num_parallel_samples = num_parallel_samples
  227. # Regression
  228. self.num_targets = num_targets
  229. self.output_range = output_range
  230. super().__init__(**kwargs)
  231. __all__ = ["PatchTSTConfig"]