anchovy Maple728 commited on
Commit
408592d
0 Parent(s):

Duplicate from Maple728/TimeMoE-50M

Browse files

Co-authored-by: Xiaoming Shi <[email protected]>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: time-series-forecasting
4
+ ---
5
+ # Model Card for TimeMoE
6
+
7
+ This repository contains the weights of the TimeMoE-50M model of the paper [Time-MoE: Billion-Scale Time Series Foundation Models with Mixture of Experts](https://huggingface.co/papers/2409.16040).
8
+
9
+
10
+ For details on how to use this model, please visit our [GitHub page](https://github.com/time-moe/time-moe).
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "time_moe_50m",
3
+ "apply_aux_loss": true,
4
+ "architectures": [
5
+ "TimeMoeForPrediction"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_time_moe.TimeMoeConfig",
9
+ "AutoModelForCausalLM": "modeling_time_moe.TimeMoeForPrediction"
10
+ },
11
+ "attention_dropout": 0.0,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 384,
14
+ "horizon_lengths": [
15
+ 1,
16
+ 8,
17
+ 32,
18
+ 64
19
+ ],
20
+ "initializer_range": 0.02,
21
+ "input_size": 1,
22
+ "intermediate_size": 1536,
23
+ "max_position_embeddings": 4096,
24
+ "model_type": "time_moe",
25
+ "num_attention_heads": 12,
26
+ "num_experts": 8,
27
+ "num_experts_per_tok": 2,
28
+ "num_hidden_layers": 12,
29
+ "num_key_value_heads": 12,
30
+ "rms_norm_eps": 1e-06,
31
+ "rope_theta": 10000,
32
+ "router_aux_loss_factor": 0.02,
33
+ "tie_word_embeddings": false,
34
+ "torch_dtype": "bfloat16",
35
+ "transformers_version": "4.40.1",
36
+ "use_cache": true,
37
+ "use_dense": false
38
+ }
configuration_time_moe.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class TimeMoeConfig(PretrainedConfig):
6
+ model_type = "time_moe"
7
+ keys_to_ignore_at_inference = ["past_key_values"]
8
+
9
+ def __init__(
10
+ self,
11
+ input_size: int = 1,
12
+ hidden_size: int = 4096,
13
+ intermediate_size: int = 22016,
14
+ horizon_lengths: List[int] = 1,
15
+ num_hidden_layers: int = 32,
16
+ num_attention_heads: int = 32,
17
+ num_key_value_heads: int = None,
18
+ hidden_act: str = "silu",
19
+ num_experts_per_tok: int = 2,
20
+ num_experts: int = 1,
21
+ max_position_embeddings: int = 32768,
22
+ initializer_range: float = 0.02,
23
+ rms_norm_eps: float = 1e-6,
24
+ use_cache: bool = True,
25
+ use_dense: bool = False,
26
+ rope_theta: int = 10000,
27
+ attention_dropout: float = 0.0,
28
+ apply_aux_loss: bool = True,
29
+ router_aux_loss_factor: float = 0.02,
30
+ tie_word_embeddings: bool = False,
31
+ **kwargs,
32
+ ):
33
+ self.input_size = input_size
34
+ self.hidden_size = hidden_size
35
+ self.intermediate_size = intermediate_size
36
+ self.max_position_embeddings = max_position_embeddings
37
+ self.num_hidden_layers = num_hidden_layers
38
+ self.num_attention_heads = num_attention_heads
39
+
40
+ if num_key_value_heads is None:
41
+ num_key_value_heads = num_attention_heads
42
+
43
+ self.num_key_value_heads = num_key_value_heads
44
+ self.hidden_act = hidden_act
45
+ if isinstance(horizon_lengths, int):
46
+ horizon_lengths = [horizon_lengths]
47
+ self.horizon_lengths = horizon_lengths # Predict horizon length for each prediction.
48
+ self.num_experts_per_tok = num_experts_per_tok
49
+ self.num_experts = num_experts
50
+ self.initializer_range = initializer_range
51
+ self.rms_norm_eps = rms_norm_eps
52
+ self.use_cache = use_cache
53
+ self.use_dense = use_dense
54
+ self.rope_theta = rope_theta
55
+ self.attention_dropout = attention_dropout
56
+ self.apply_aux_loss = apply_aux_loss
57
+ self.router_aux_loss_factor = router_aux_loss_factor
58
+
59
+ assert self.use_dense ^ self.apply_aux_loss, 'Both use_dense and apply_aux_loss cannot be set to True or False at the same time.'
60
+
61
+ kwargs.pop('tie_word_embeddings', None)
62
+ super().__init__(
63
+ tie_word_embeddings=tie_word_embeddings,
64
+ **kwargs,
65
+ )
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.40.1"
4
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0127209833663df6f5ae3cf1c3316f739a8dd1dae27e59036268bbfdb48f91a4
3
+ size 226760264
modeling_time_moe.py ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Tuple, List, Union
3
+ import warnings
4
+
5
+ import torch
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+ from transformers import PreTrainedModel, Cache, DynamicCache, StaticCache
9
+ from transformers.activations import ACT2FN
10
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
11
+ from transformers.modeling_outputs import MoeModelOutputWithPast, MoeCausalLMOutputWithPast
12
+ from transformers.utils import logging, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10
13
+
14
+ from .configuration_time_moe import TimeMoeConfig
15
+ from .ts_generation_mixin import TSGenerationMixin
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+ # if is_flash_attn_2_available():
20
+ # from flash_attn import flash_attn_func, flash_attn_varlen_func
21
+ # from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
22
+ try:
23
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
24
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
25
+ except:
26
+ pass
27
+
28
+
29
+ def _get_unpad_data(attention_mask):
30
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
31
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
32
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
33
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
34
+ return (
35
+ indices,
36
+ cu_seqlens,
37
+ max_seqlen_in_batch,
38
+ )
39
+
40
+
41
+ def load_balancing_loss_func(
42
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], List[torch.Tensor]],
43
+ top_k: int,
44
+ num_experts: int = None,
45
+ attention_mask: Optional[torch.Tensor] = None
46
+ ) -> torch.Tensor:
47
+ r"""
48
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
49
+
50
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
51
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
52
+ experts is too unbalanced.
53
+
54
+ Args:
55
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor], List[torch.Tensor]):
56
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
57
+ shape [batch_size X sequence_length, num_experts].
58
+ top_k (`int`)
59
+ Selected Top k over the experts.
60
+ attention_mask (`torch.Tensor`, None):
61
+ The attention_mask used in forward function
62
+ shape [batch_size X sequence_length] if not None.
63
+ num_experts (`int`, *optional*):
64
+ Number of experts
65
+
66
+ Returns:
67
+ The auxiliary loss.
68
+ """
69
+ if gate_logits is None or not isinstance(gate_logits, (tuple, list)) or gate_logits[0] is None:
70
+ return 0.0
71
+
72
+ compute_device = gate_logits[0].device
73
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
74
+
75
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
76
+
77
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
78
+
79
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
80
+
81
+ if attention_mask is None:
82
+ # Compute the percentage of tokens routed to each expert
83
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
84
+
85
+ # Compute the average probability of routing to these experts
86
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
87
+ else:
88
+ batch_size, sequence_length = attention_mask.shape
89
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
90
+
91
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
92
+ expert_attention_mask = (
93
+ attention_mask[None, :, :, None, None]
94
+ .expand((num_hidden_layers, batch_size, sequence_length, 2, num_experts))
95
+ .reshape(-1, 2, num_experts)
96
+ .to(compute_device)
97
+ )
98
+
99
+ # Compute the percentage of tokens routed to each experts
100
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
101
+ expert_attention_mask, dim=0
102
+ )
103
+
104
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
105
+ router_per_expert_attention_mask = (
106
+ attention_mask[None, :, :, None]
107
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
108
+ .reshape(-1, num_experts)
109
+ .to(compute_device)
110
+ )
111
+
112
+ # Compute the average probability of routing to these experts
113
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
114
+ router_per_expert_attention_mask, dim=0
115
+ )
116
+
117
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(dim=0))
118
+
119
+ return overall_loss * num_experts
120
+
121
+
122
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
123
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
124
+ """
125
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
126
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
127
+ """
128
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
129
+ if n_rep == 1:
130
+ return hidden_states
131
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
132
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
133
+
134
+
135
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
136
+ def rotate_half(x):
137
+ """Rotates half the hidden dims of the input."""
138
+ x1 = x[..., : x.shape[-1] // 2]
139
+ x2 = x[..., x.shape[-1] // 2:]
140
+ return torch.cat((-x2, x1), dim=-1)
141
+
142
+
143
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
144
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
145
+ """Applies Rotary Position Embedding to the query and key tensors.
146
+
147
+ Args:
148
+ q (`torch.Tensor`): The query tensor.
149
+ k (`torch.Tensor`): The key tensor.
150
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
151
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
152
+ position_ids (`torch.Tensor`):
153
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
154
+ used to pass offsetted position ids when working with a KV-cache.
155
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
156
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
157
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
158
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
159
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
160
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
161
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
162
+ Returns:
163
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
164
+ """
165
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
166
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
167
+ q_embed = (q * cos) + (rotate_half(q) * sin)
168
+ k_embed = (k * cos) + (rotate_half(k) * sin)
169
+ return q_embed, k_embed
170
+
171
+
172
+ class TimeMoeInputEmbedding(nn.Module):
173
+ """
174
+ Use a mlp layer to embedding the time-series.
175
+ """
176
+
177
+ def __init__(self, config: TimeMoeConfig):
178
+ super().__init__()
179
+ self.config = config
180
+ self.input_size = config.input_size # default 1
181
+ self.hidden_size = config.hidden_size
182
+ self.emb_layer = nn.Linear(self.input_size, self.hidden_size, bias=False)
183
+ self.gate_layer = nn.Linear(self.input_size, self.hidden_size, bias=False)
184
+ self.act_fn = ACT2FN[config.hidden_act]
185
+
186
+ def forward(self, x):
187
+ emb = self.act_fn(self.gate_layer(x)) * self.emb_layer(x)
188
+ return emb
189
+
190
+
191
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->TimeMOE
192
+ class TimeMoeRotaryEmbedding(torch.nn.Module):
193
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
194
+ super().__init__()
195
+
196
+ self.dim = dim
197
+ self.max_position_embeddings = max_position_embeddings
198
+ self.base = base
199
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
200
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
201
+
202
+ # Build here to make `torch.jit.trace` work.
203
+ self._set_cos_sin_cache(
204
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
205
+ )
206
+
207
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
208
+ self.max_seq_len_cached = seq_len
209
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
210
+
211
+ freqs = torch.outer(t, self.inv_freq)
212
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
213
+ emb = torch.cat((freqs, freqs), dim=-1)
214
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
215
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
216
+
217
+ def forward(self, x, seq_len=None):
218
+ # x: [bs, num_attention_heads, seq_len, head_size]
219
+ if seq_len > self.max_seq_len_cached:
220
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
221
+
222
+ return (
223
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
224
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
225
+ )
226
+
227
+
228
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->TimeMOE
229
+ class TimeMoeRMSNorm(torch.nn.Module):
230
+ def __init__(self, hidden_size, eps=1e-6):
231
+ super().__init__()
232
+ self.weight = nn.Parameter(torch.ones(hidden_size))
233
+ self.variance_epsilon = eps
234
+
235
+ def forward(self, hidden_states):
236
+ input_dtype = hidden_states.dtype
237
+ hidden_states = hidden_states.to(torch.float32)
238
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
239
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
240
+ return self.weight * hidden_states.to(input_dtype)
241
+
242
+
243
+ class TimeMoeTemporalBlock(nn.Module):
244
+ def __init__(self, hidden_size: int, intermediate_size: int, hidden_act: str):
245
+ super().__init__()
246
+ self.hidden_size = hidden_size
247
+ self.intermediate_size = intermediate_size
248
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
249
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
250
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
251
+ self.act_fn = ACT2FN[hidden_act]
252
+
253
+ def forward(self, hidden_state):
254
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
255
+
256
+
257
+ class TimeMoeMLP(TimeMoeTemporalBlock):
258
+ def __init__(self, hidden_size: int, intermediate_size: int, hidden_act: str):
259
+ super().__init__(hidden_size, intermediate_size, hidden_act)
260
+
261
+ def forward(self, hidden_state):
262
+ return super().forward(hidden_state), None
263
+
264
+
265
+ class TimeMoeSparseExpertsLayer(nn.Module):
266
+ def __init__(self, config):
267
+ super().__init__()
268
+ self.config = config
269
+ self.top_k = config.num_experts_per_tok
270
+ self.hidden_size = config.hidden_size
271
+ self.num_experts = config.num_experts
272
+ self.norm_topk_prob = False
273
+
274
+ moe_intermediate_size = self.config.intermediate_size // self.top_k
275
+
276
+ # gating
277
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
278
+ self.experts = nn.ModuleList(
279
+ [TimeMoeTemporalBlock(
280
+ hidden_size=self.config.hidden_size,
281
+ intermediate_size=moe_intermediate_size,
282
+ hidden_act=self.config.hidden_act,
283
+ ) for _ in range(self.num_experts)]
284
+ )
285
+
286
+ self.shared_expert = TimeMoeTemporalBlock(
287
+ hidden_size=self.config.hidden_size,
288
+ intermediate_size=self.config.intermediate_size,
289
+ hidden_act=self.config.hidden_act,
290
+ )
291
+ self.shared_expert_gate = torch.nn.Linear(config.hidden_size, 1, bias=False)
292
+
293
+ def forward(self, hidden_states: torch.Tensor):
294
+ """ """
295
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
296
+ hidden_states = hidden_states.view(-1, hidden_dim)
297
+ # router_logits -> (batch * sequence_length, n_experts)
298
+ router_logits = self.gate(hidden_states)
299
+
300
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
301
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
302
+ if self.norm_topk_prob:
303
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
304
+ # we cast back to the input dtype
305
+ routing_weights = routing_weights.to(hidden_states.dtype)
306
+
307
+ final_hidden_states = torch.zeros(
308
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
309
+ )
310
+
311
+ # One hot encode the selected experts to create an expert mask
312
+ # this will be used to easily index which expert is going to be sollicitated
313
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
314
+
315
+ # Loop over all available experts in the model and perform the computation on each expert
316
+ for expert_idx in range(self.num_experts):
317
+ expert_layer = self.experts[expert_idx]
318
+ idx, top_x = torch.where(expert_mask[expert_idx])
319
+
320
+ # Index the correct hidden states and compute the expert hidden state for
321
+ # the current expert. We need to make sure to multiply the output hidden
322
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
323
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
324
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
325
+
326
+ # However `index_add_` only support torch tensors for indexing so we'll use
327
+ # the `top_x` tensor here.
328
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
329
+
330
+ shared_expert_output = self.shared_expert(hidden_states)
331
+ shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states)) * shared_expert_output
332
+
333
+ final_hidden_states = final_hidden_states + shared_expert_output
334
+
335
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
336
+ return final_hidden_states, router_logits
337
+
338
+
339
+ # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2Attention with Qwen2->TimeMoe
340
+ class TimeMoeAttention(nn.Module):
341
+ """
342
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
343
+ and "Generating Long Sequences with Sparse Transformers".
344
+ """
345
+
346
+ def __init__(self, config: TimeMoeConfig, layer_idx: Optional[int] = None):
347
+ super().__init__()
348
+ self.config = config
349
+ self.layer_idx = layer_idx
350
+ if layer_idx is None:
351
+ logger.warning_once(
352
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
353
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
354
+ "when creating this class."
355
+ )
356
+
357
+ self.hidden_size = config.hidden_size
358
+ self.num_heads = config.num_attention_heads
359
+ self.head_dim = self.hidden_size // self.num_heads
360
+ self.num_key_value_heads = config.num_key_value_heads
361
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
362
+ self.max_position_embeddings = config.max_position_embeddings
363
+ self.rope_theta = config.rope_theta
364
+ self.is_causal = True
365
+ self.attention_dropout = config.attention_dropout
366
+
367
+ if (self.head_dim * self.num_heads) != self.hidden_size:
368
+ raise ValueError(
369
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
370
+ f" and `num_heads`: {self.num_heads})."
371
+ )
372
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
373
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
374
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
375
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
376
+
377
+ self.rotary_emb = TimeMoeRotaryEmbedding(
378
+ self.head_dim,
379
+ max_position_embeddings=self.max_position_embeddings,
380
+ base=self.rope_theta,
381
+ )
382
+
383
+ def forward(
384
+ self,
385
+ hidden_states: torch.Tensor,
386
+ attention_mask: Optional[torch.Tensor] = None,
387
+ position_ids: Optional[torch.LongTensor] = None,
388
+ past_key_value: Optional[Cache] = None,
389
+ output_attentions: bool = False,
390
+ **kwargs,
391
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
392
+ if "padding_mask" in kwargs:
393
+ warnings.warn(
394
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
395
+ )
396
+ bsz, q_len, _ = hidden_states.size()
397
+
398
+ query_states = self.q_proj(hidden_states)
399
+ key_states = self.k_proj(hidden_states)
400
+ value_states = self.v_proj(hidden_states)
401
+
402
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
403
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
404
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
405
+
406
+ kv_seq_len = key_states.shape[-2]
407
+ if past_key_value is not None:
408
+ if self.layer_idx is None:
409
+ raise ValueError(
410
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
411
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
412
+ "with a layer index."
413
+ )
414
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
415
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
416
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
417
+
418
+ if past_key_value is not None:
419
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
420
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
421
+
422
+ # repeat k/v heads if n_kv_heads < n_heads
423
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
424
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
425
+
426
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
427
+
428
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
429
+ raise ValueError(
430
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
431
+ f" {attn_weights.size()}"
432
+ )
433
+
434
+ if attention_mask is not None:
435
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
436
+ raise ValueError(
437
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
438
+ )
439
+
440
+ attn_weights = attn_weights + attention_mask
441
+
442
+ # upcast attention to fp32
443
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
444
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
445
+ attn_output = torch.matmul(attn_weights, value_states)
446
+
447
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
448
+ raise ValueError(
449
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
450
+ f" {attn_output.size()}"
451
+ )
452
+
453
+ attn_output = attn_output.transpose(1, 2).contiguous()
454
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
455
+
456
+ attn_output = self.o_proj(attn_output)
457
+
458
+ if not output_attentions:
459
+ attn_weights = None
460
+
461
+ return attn_output, attn_weights, past_key_value
462
+
463
+
464
+ class TimeMoeFlashAttention2(TimeMoeAttention):
465
+
466
+ def __init__(self, *args, **kwargs):
467
+ super().__init__(*args, **kwargs)
468
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
469
+
470
+ def forward(
471
+ self,
472
+ hidden_states: torch.Tensor,
473
+ attention_mask: Optional[torch.LongTensor] = None,
474
+ position_ids: Optional[torch.LongTensor] = None,
475
+ past_key_value: Optional[Cache] = None,
476
+ output_attentions: bool = False,
477
+ use_cache: bool = False,
478
+ cache_position: Optional[torch.LongTensor] = None,
479
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
480
+ if isinstance(past_key_value, StaticCache):
481
+ raise ValueError(
482
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
483
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
484
+ )
485
+
486
+ output_attentions = False
487
+
488
+ bsz, q_len, _ = hidden_states.size()
489
+
490
+ query_states = self.q_proj(hidden_states)
491
+ key_states = self.k_proj(hidden_states)
492
+ value_states = self.v_proj(hidden_states)
493
+
494
+ # Flash attention requires the input to have the shape
495
+ # batch_size x seq_length x head_dim x hidden_dim
496
+ # therefore we just need to keep the original shape
497
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
498
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
499
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
500
+
501
+ kv_seq_len = key_states.shape[-2]
502
+ if past_key_value is not None:
503
+ if self.layer_idx is None:
504
+ raise ValueError(
505
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
506
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
507
+ "with a layer index."
508
+ )
509
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
510
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
511
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
512
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
513
+
514
+ if past_key_value is not None:
515
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
516
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
517
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
518
+
519
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
520
+ # to be able to avoid many of these transpose/reshape/view.
521
+ query_states = query_states.transpose(1, 2)
522
+ key_states = key_states.transpose(1, 2)
523
+ value_states = value_states.transpose(1, 2)
524
+
525
+ dropout_rate = self.attention_dropout if self.training else 0.0
526
+
527
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
528
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
529
+ # cast them back in the correct dtype just to be sure everything works as expected.
530
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
531
+ # in fp32. (LlamaRMSNorm handles it correctly)
532
+
533
+ input_dtype = query_states.dtype
534
+ if input_dtype == torch.float32:
535
+
536
+ if torch.is_autocast_enabled():
537
+ target_dtype = torch.get_autocast_gpu_dtype()
538
+ # Handle the case where the model is quantized
539
+ elif hasattr(self.config, "_pre_quantization_dtype"):
540
+ target_dtype = self.config._pre_quantization_dtype
541
+ else:
542
+ target_dtype = self.q_proj.weight.dtype
543
+
544
+ logger.warning_once(
545
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
546
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
547
+ f" {target_dtype}."
548
+ )
549
+
550
+ query_states = query_states.to(target_dtype)
551
+ key_states = key_states.to(target_dtype)
552
+ value_states = value_states.to(target_dtype)
553
+
554
+ attn_output = self._flash_attention_forward(
555
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
556
+ )
557
+
558
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
559
+ attn_output = self.o_proj(attn_output)
560
+
561
+ if not output_attentions:
562
+ attn_weights = None
563
+
564
+ return attn_output, attn_weights, past_key_value
565
+
566
+ def _flash_attention_forward(
567
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
568
+ ):
569
+ """
570
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
571
+ first unpad the input, then computes the attention scores and pad the final attention scores.
572
+
573
+ Args:
574
+ query_states (`torch.Tensor`):
575
+ Input query states to be passed to Flash Attention API
576
+ key_states (`torch.Tensor`):
577
+ Input key states to be passed to Flash Attention API
578
+ value_states (`torch.Tensor`):
579
+ Input value states to be passed to Flash Attention API
580
+ attention_mask (`torch.Tensor`):
581
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
582
+ position of padding tokens and 1 for the position of non-padding tokens.
583
+ dropout (`float`):
584
+ Attention dropout
585
+ softmax_scale (`float`, *optional*):
586
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
587
+ """
588
+ if not self._flash_attn_uses_top_left_mask:
589
+ causal = self.is_causal
590
+ else:
591
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
592
+ causal = self.is_causal and query_length != 1
593
+
594
+ origin_dtype = query_states.dtype
595
+ if origin_dtype not in [torch.bfloat16, torch.float16]:
596
+ query_states = query_states.to(dtype=torch.bfloat16)
597
+ key_states = key_states.to(dtype=torch.bfloat16)
598
+ value_states = value_states.to(dtype=torch.bfloat16)
599
+
600
+ # without attention mask to faster speed
601
+ attn_output = flash_attn_func(
602
+ query_states,
603
+ key_states,
604
+ value_states,
605
+ dropout,
606
+ softmax_scale=softmax_scale,
607
+ causal=causal
608
+ )
609
+ if origin_dtype not in [torch.bfloat16, torch.float16]:
610
+ return attn_output.to(origin_dtype)
611
+ else:
612
+ return attn_output
613
+
614
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
615
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
616
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
617
+
618
+ key_layer = index_first_axis(
619
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
620
+ )
621
+ value_layer = index_first_axis(
622
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
623
+ )
624
+ if query_length == kv_seq_len:
625
+ query_layer = index_first_axis(
626
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
627
+ )
628
+ cu_seqlens_q = cu_seqlens_k
629
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
630
+ indices_q = indices_k
631
+ elif query_length == 1:
632
+ max_seqlen_in_batch_q = 1
633
+ cu_seqlens_q = torch.arange(
634
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
635
+ ) # There is a memcpy here, that is very bad.
636
+ indices_q = cu_seqlens_q[:-1]
637
+ query_layer = query_layer.squeeze(1)
638
+ else:
639
+ # The -q_len: slice assumes left padding.
640
+ attention_mask = attention_mask[:, -query_length:]
641
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
642
+
643
+ return (
644
+ query_layer,
645
+ key_layer,
646
+ value_layer,
647
+ indices_q,
648
+ (cu_seqlens_q, cu_seqlens_k),
649
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
650
+ )
651
+
652
+
653
+ TIME_MOE_ATTENTION_CLASSES = {
654
+ "eager": TimeMoeAttention,
655
+ 'flash_attention_2': TimeMoeFlashAttention2,
656
+ }
657
+
658
+
659
+ class TimeMoeDecoderLayer(nn.Module):
660
+ def __init__(self, config: TimeMoeConfig, layer_idx: int):
661
+ super().__init__()
662
+ self.config = config
663
+ self.hidden_size = config.hidden_size
664
+
665
+ self.self_attn = TIME_MOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
666
+
667
+ if self.config.use_dense:
668
+ self.ffn_layer = TimeMoeMLP(
669
+ hidden_size=self.config.hidden_size,
670
+ intermediate_size=self.config.intermediate_size,
671
+ hidden_act=self.config.hidden_act,
672
+ )
673
+ else:
674
+ self.ffn_layer = TimeMoeSparseExpertsLayer(config)
675
+ self.input_layernorm = TimeMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
676
+ self.post_attention_layernorm = TimeMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
677
+
678
+ def forward(
679
+ self,
680
+ hidden_states: torch.Tensor,
681
+ attention_mask: Optional[torch.Tensor] = None,
682
+ position_ids: Optional[torch.LongTensor] = None,
683
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
684
+ output_attentions: Optional[bool] = False,
685
+ use_cache: Optional[bool] = False,
686
+ **kwargs,
687
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor, Optional[torch.FloatTensor], Optional[torch.FloatTensor]]:
688
+ if "padding_mask" in kwargs:
689
+ warnings.warn(
690
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
691
+ "Please make sure use `attention_mask` instead.`"
692
+ )
693
+ """
694
+ Args:
695
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
696
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
697
+ `(batch, sequence_length)` where padding elements are indicated by 0.
698
+ output_attentions (`bool`, *optional*):
699
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
700
+ returned tensors for more detail.
701
+ use_cache (`bool`, *optional*):
702
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
703
+ (see `past_key_values`).
704
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
705
+ """
706
+
707
+ residual = hidden_states
708
+
709
+ hidden_states = self.input_layernorm(hidden_states)
710
+
711
+ # Self Attention
712
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
713
+ hidden_states=hidden_states,
714
+ attention_mask=attention_mask,
715
+ position_ids=position_ids,
716
+ past_key_value=past_key_value,
717
+ output_attentions=output_attentions,
718
+ use_cache=use_cache,
719
+ )
720
+ hidden_states = residual + hidden_states
721
+
722
+ # Fully Connected
723
+ residual = hidden_states
724
+ hidden_states = self.post_attention_layernorm(hidden_states)
725
+ hidden_states, router_logits = self.ffn_layer(hidden_states)
726
+ hidden_states = residual + hidden_states
727
+
728
+ if not output_attentions:
729
+ self_attn_weights = None
730
+
731
+ if not use_cache:
732
+ present_key_value = None
733
+ return hidden_states, self_attn_weights, present_key_value, router_logits
734
+
735
+
736
+ class TimeMoePreTrainedModel(PreTrainedModel):
737
+ config_class = TimeMoeConfig
738
+ base_model_prefix = "model"
739
+ supports_gradient_checkpointing = True
740
+ _no_split_modules = ["TimeMoeDecoderLayer"]
741
+ _skip_keys_device_placement = "past_key_values"
742
+ _supports_flash_attn_2 = True
743
+ _supports_sdpa = False
744
+ _supports_cache_class = True
745
+
746
+ def _init_weights(self, module):
747
+ std = self.config.initializer_range
748
+ if isinstance(module, torch.nn.Linear):
749
+ module.weight.data.normal_(mean=0.0, std=std)
750
+ if module.bias is not None:
751
+ module.bias.data.zero_()
752
+ elif isinstance(module, torch.nn.Embedding):
753
+ module.weight.data.normal_(mean=0.0, std=std)
754
+ if module.padding_idx is not None:
755
+ module.weight.data[module.padding_idx].zero_()
756
+
757
+
758
+ class TimeMoeModel(TimeMoePreTrainedModel):
759
+ """
760
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TimeMoeDecoderLayer`]
761
+
762
+ Args:
763
+ config: TimeMoeConfig
764
+ """
765
+
766
+ def __init__(self, config: TimeMoeConfig):
767
+ super().__init__(config)
768
+ self.embed_layer = TimeMoeInputEmbedding(config)
769
+ self.layers = nn.ModuleList(
770
+ [TimeMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
771
+ )
772
+ self._attn_implementation = config._attn_implementation
773
+ self.norm = TimeMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
774
+
775
+ self.gradient_checkpointing = False
776
+ # Initialize weights and apply final processing
777
+ self.post_init()
778
+
779
+ def forward(
780
+ self,
781
+ input_ids: torch.FloatTensor = None,
782
+ attention_mask: Optional[torch.Tensor] = None,
783
+ position_ids: Optional[torch.LongTensor] = None,
784
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
785
+ inputs_embeds: Optional[torch.FloatTensor] = None,
786
+ use_cache: Optional[bool] = None,
787
+ output_attentions: Optional[bool] = None,
788
+ output_hidden_states: Optional[bool] = None,
789
+ return_dict: Optional[bool] = None,
790
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
791
+ # input_ids is the input of time series, its shape is [batch_size, seq_len, input_size]
792
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
793
+ output_hidden_states = (
794
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
795
+ )
796
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
797
+
798
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
799
+
800
+ # retrieve input_ids and inputs_embeds
801
+ if input_ids is not None and inputs_embeds is not None:
802
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
803
+ elif input_ids is not None:
804
+ if len(input_ids.shape) == 2:
805
+ input_ids.unsqueeze_(dim=-1)
806
+ batch_size, seq_length, _ = input_ids.shape
807
+ elif inputs_embeds is not None:
808
+ batch_size, seq_length, _ = inputs_embeds.shape
809
+ else:
810
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
811
+
812
+ if self.gradient_checkpointing and self.training:
813
+ if use_cache:
814
+ logger.warning_once(
815
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
816
+ )
817
+ use_cache = False
818
+
819
+ past_key_values_length = 0
820
+
821
+ if use_cache:
822
+ use_legacy_cache = not isinstance(past_key_values, Cache)
823
+ if use_legacy_cache:
824
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
825
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
826
+
827
+ if position_ids is None:
828
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
829
+ position_ids = torch.arange(
830
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
831
+ )
832
+ # position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
833
+ position_ids = position_ids.view(-1, seq_length)
834
+ else:
835
+ position_ids = position_ids.view(-1, seq_length).long()
836
+
837
+ if inputs_embeds is None:
838
+ inputs_embeds = self.embed_layer(input_ids)
839
+
840
+ # 4d mask is passed through the layers
841
+ attention_mask = _prepare_4d_causal_attention_mask(
842
+ attention_mask,
843
+ (batch_size, seq_length),
844
+ inputs_embeds,
845
+ past_key_values_length,
846
+ sliding_window=None,
847
+ )
848
+
849
+ hidden_states = inputs_embeds
850
+
851
+ # decoder layers
852
+ all_hidden_states = () if output_hidden_states else None
853
+ all_self_attns = () if output_attentions else None
854
+ all_router_logits = ()
855
+ next_decoder_cache = None
856
+
857
+ for decoder_layer in self.layers:
858
+ if output_hidden_states:
859
+ all_hidden_states += (hidden_states,)
860
+
861
+ if self.gradient_checkpointing and self.training:
862
+ layer_outputs = self._gradient_checkpointing_func(
863
+ decoder_layer.__call__,
864
+ hidden_states,
865
+ attention_mask,
866
+ position_ids,
867
+ past_key_values,
868
+ output_attentions,
869
+ use_cache,
870
+ )
871
+ else:
872
+ layer_outputs = decoder_layer(
873
+ hidden_states,
874
+ attention_mask=attention_mask,
875
+ position_ids=position_ids,
876
+ past_key_value=past_key_values,
877
+ output_attentions=output_attentions,
878
+ use_cache=use_cache,
879
+ )
880
+
881
+ hidden_states = layer_outputs[0]
882
+
883
+ all_router_logits += (layer_outputs[-1],)
884
+
885
+ if output_attentions:
886
+ all_self_attns += (layer_outputs[1],)
887
+
888
+ if use_cache:
889
+ next_decoder_cache = layer_outputs[2]
890
+
891
+ hidden_states = self.norm(hidden_states)
892
+
893
+ # add hidden states from the last decoder layer
894
+ if output_hidden_states:
895
+ all_hidden_states += (hidden_states,)
896
+
897
+ next_cache = None
898
+ if use_cache:
899
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
900
+
901
+ if not return_dict:
902
+ return tuple(
903
+ v
904
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
905
+ if v is not None
906
+ )
907
+ return MoeModelOutputWithPast(
908
+ last_hidden_state=hidden_states,
909
+ past_key_values=next_cache,
910
+ hidden_states=all_hidden_states,
911
+ attentions=all_self_attns,
912
+ router_logits=all_router_logits
913
+ )
914
+
915
+
916
+ class TimeMoeOutputLayer(nn.Module):
917
+
918
+ def __init__(self, hidden_size: int, horizon_length: int, input_size: int = 1):
919
+ super().__init__()
920
+
921
+ self.out_layer = nn.Linear(
922
+ hidden_size,
923
+ input_size * horizon_length,
924
+ bias=False,
925
+ )
926
+
927
+ def forward(self, x):
928
+ """
929
+
930
+ Args:
931
+ x (torch.FloatTensor): with shape [B, seq_len, hidden_size]
932
+
933
+ Returns:
934
+ ` torch.FloatTensor: final prediction with shape [B, seq_len, input_size]
935
+ """
936
+ return self.out_layer(x)
937
+
938
+
939
+ class TimeMoeForPrediction(TimeMoePreTrainedModel, TSGenerationMixin):
940
+
941
+ def __init__(self, config: TimeMoeConfig):
942
+ super().__init__(config)
943
+ self.config = config
944
+ self.apply_aux_loss = config.apply_aux_loss
945
+ self.num_experts_per_tok = config.num_experts_per_tok
946
+ self.router_aux_loss_factor = config.router_aux_loss_factor
947
+
948
+ self.model = TimeMoeModel(config)
949
+ # output layer
950
+ lm_head_list = []
951
+ self.horizon_length_map = {}
952
+ for i, horizon_length in enumerate(config.horizon_lengths):
953
+ lm_head_list.append(
954
+ TimeMoeOutputLayer(
955
+ hidden_size=self.config.hidden_size,
956
+ input_size=self.config.input_size,
957
+ horizon_length=horizon_length,
958
+ )
959
+ )
960
+ self.horizon_length_map[horizon_length] = i
961
+ self.lm_heads = nn.ModuleList(lm_head_list)
962
+
963
+ self.loss_function = torch.nn.HuberLoss(reduction='none', delta=2.0)
964
+
965
+ # Initialize weights and apply final processing
966
+ self.post_init()
967
+
968
+ def set_decoder(self, decoder):
969
+ self.model = decoder
970
+
971
+ def get_decoder(self):
972
+ return self.model
973
+
974
+ def forward(
975
+ self,
976
+ input_ids: torch.FloatTensor = None,
977
+ attention_mask: Optional[torch.Tensor] = None,
978
+ position_ids: Optional[torch.LongTensor] = None,
979
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
980
+ inputs_embeds: Optional[torch.FloatTensor] = None,
981
+ labels: Optional[torch.FloatTensor] = None,
982
+ loss_masks: Optional[torch.FloatTensor] = None,
983
+ use_cache: Optional[bool] = None,
984
+ output_attentions: Optional[bool] = None,
985
+ output_hidden_states: Optional[bool] = None,
986
+ return_dict: Optional[bool] = None,
987
+ max_horizon_length: Optional[int] = None,
988
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
989
+
990
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
991
+ output_hidden_states = (
992
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
993
+ )
994
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
995
+
996
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
997
+ outputs = self.model(
998
+ input_ids=input_ids,
999
+ attention_mask=attention_mask,
1000
+ position_ids=position_ids,
1001
+ past_key_values=past_key_values,
1002
+ inputs_embeds=inputs_embeds,
1003
+ use_cache=use_cache,
1004
+ output_attentions=output_attentions,
1005
+ output_hidden_states=output_hidden_states,
1006
+ return_dict=return_dict,
1007
+ )
1008
+
1009
+ hidden_states = outputs[0]
1010
+ predictions = None
1011
+
1012
+ loss = None
1013
+ aux_loss = None
1014
+ if labels is not None:
1015
+ # AutoRegressive loss
1016
+ ar_loss = 0.0
1017
+ for lm_head, horizon_length in zip(self.lm_heads, self.config.horizon_lengths):
1018
+ one_predictions = lm_head(hidden_states)
1019
+ one_loss = self.calc_ar_loss(one_predictions, labels, loss_masks, horizon_length)
1020
+ ar_loss += one_loss
1021
+ if predictions is None:
1022
+ predictions = one_predictions
1023
+ loss = ar_loss / len(self.config.horizon_lengths)
1024
+
1025
+ if self.apply_aux_loss:
1026
+ router_logits = outputs.router_logits if return_dict else outputs[-1]
1027
+
1028
+ temporal_aux_loss = load_balancing_loss_func(
1029
+ router_logits,
1030
+ top_k=self.num_experts_per_tok,
1031
+ num_experts=self.config.num_experts,
1032
+ attention_mask=attention_mask
1033
+ )
1034
+ loss += self.router_aux_loss_factor * temporal_aux_loss.to(loss.device)
1035
+ else:
1036
+ if max_horizon_length is None:
1037
+ horizon_length = self.config.horizon_lengths[0]
1038
+ max_horizon_length = horizon_length
1039
+ else:
1040
+ horizon_length = self.config.horizon_lengths[0]
1041
+ for h in self.config.horizon_lengths[1:]:
1042
+ if h > max_horizon_length:
1043
+ break
1044
+ else:
1045
+ horizon_length = h
1046
+ lm_head = self.lm_heads[self.horizon_length_map[horizon_length]]
1047
+ predictions = lm_head(hidden_states)
1048
+ if horizon_length > max_horizon_length:
1049
+ predictions = predictions[:, :, : self.config.input_size * max_horizon_length]
1050
+
1051
+ if not return_dict:
1052
+ output = (predictions,) + outputs[1:]
1053
+ return (loss, aux_loss) + output if loss is not None else output
1054
+
1055
+ return MoeCausalLMOutputWithPast(
1056
+ loss=loss,
1057
+ aux_loss=aux_loss,
1058
+ logits=predictions,
1059
+ past_key_values=outputs.past_key_values,
1060
+ hidden_states=outputs.hidden_states,
1061
+ attentions=outputs.attentions,
1062
+ )
1063
+
1064
+ def calc_ar_loss(self, predictions, labels, loss_masks, horizon_length):
1065
+ if len(labels.shape) == 2:
1066
+ labels.unsqueeze_(dim=-1)
1067
+ # enable model parallelism
1068
+ labels = labels.to(predictions.device)
1069
+ if loss_masks is not None and len(loss_masks.shape) == 2:
1070
+ loss_masks.unsqueeze_(dim=-1)
1071
+ # enable model parallelism
1072
+ loss_masks = loss_masks.to(predictions.device)
1073
+
1074
+ if horizon_length > 1:
1075
+ batch_size, seq_len, output_size = predictions.shape
1076
+ shift_predictions = predictions.view(batch_size, seq_len, horizon_length, -1)
1077
+
1078
+ # pad to the same length with predictions
1079
+ # shape -> [B, input_size, seq_len + horizon_length -1]
1080
+ labels = F.pad(labels.transpose(-1, -2), (0, horizon_length - 1), mode='constant', value=0)
1081
+
1082
+ # shape -> [B, input_size, seq_len, horizon_length]
1083
+ shift_labels = labels.unfold(dimension=-1, size=horizon_length, step=1)
1084
+ shift_labels = shift_labels.permute(0, 2, 3, 1)
1085
+
1086
+ if loss_masks is not None:
1087
+ # pad to the same length with predictions
1088
+ loss_masks = F.pad(loss_masks.transpose(-1, -2), (0, horizon_length - 1), mode='constant', value=0)
1089
+
1090
+ loss_masks = loss_masks.unfold(dimension=-1, size=horizon_length, step=1)
1091
+ loss_masks = loss_masks.permute(0, 2, 3, 1)
1092
+
1093
+ else:
1094
+ shift_predictions = predictions
1095
+ shift_labels = labels
1096
+
1097
+ # Calculate loss with mask
1098
+ losses = self.loss_function(shift_predictions, shift_labels)
1099
+
1100
+ if loss_masks is not None:
1101
+ losses = losses * loss_masks
1102
+ loss = losses.sum() / loss_masks.sum()
1103
+ else:
1104
+ loss = torch.mean(losses)
1105
+
1106
+ return loss
1107
+
1108
+ def prepare_inputs_for_generation(
1109
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1110
+ ):
1111
+ # Omit tokens covered by past_key_values
1112
+ if past_key_values is not None:
1113
+ if isinstance(past_key_values, Cache):
1114
+ cache_length = past_key_values.get_seq_length()
1115
+ if isinstance(past_key_values, DynamicCache):
1116
+ past_length = past_key_values.seen_tokens
1117
+ else:
1118
+ past_length = cache_length
1119
+
1120
+ max_cache_length = past_key_values.get_max_length()
1121
+ else:
1122
+ cache_length = past_length = past_key_values[0][0].shape[2]
1123
+ max_cache_length = None
1124
+
1125
+ # Keep only the unprocessed tokens:
1126
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1127
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1128
+ # input)
1129
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1130
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1131
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1132
+ # input_ids based on the past_length.
1133
+ elif past_length < input_ids.shape[1]:
1134
+ input_ids = input_ids[:, past_length:]
1135
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1136
+
1137
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1138
+ if (
1139
+ max_cache_length is not None
1140
+ and attention_mask is not None
1141
+ and cache_length + input_ids.shape[1] > max_cache_length
1142
+ ):
1143
+ attention_mask = attention_mask[:, -max_cache_length:]
1144
+
1145
+ position_ids = kwargs.get("position_ids", None)
1146
+ if attention_mask is not None and position_ids is None:
1147
+ # create position_ids on the fly for batch generation
1148
+ position_ids = attention_mask.long().cumsum(-1) - 1
1149
+ position_ids.masked_fill_(attention_mask == 0, 1)
1150
+ if past_key_values:
1151
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1152
+
1153
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1154
+ if inputs_embeds is not None and past_key_values is None:
1155
+ logger.info('Use input_embedding')
1156
+ model_inputs = {"inputs_embeds": inputs_embeds}
1157
+ else:
1158
+ model_inputs = {"input_ids": input_ids}
1159
+
1160
+ model_inputs.update(
1161
+ {
1162
+ "position_ids": position_ids,
1163
+ "past_key_values": past_key_values,
1164
+ "use_cache": kwargs.get("use_cache"),
1165
+ "attention_mask": attention_mask,
1166
+ }
1167
+ )
1168
+ return model_inputs
1169
+
1170
+ @staticmethod
1171
+ def _reorder_cache(past_key_values, beam_idx):
1172
+ reordered_past = ()
1173
+ for layer_past in past_key_values:
1174
+ reordered_past += (
1175
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1176
+ )
1177
+ return reordered_past
ts_generation_mixin.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ import torch
5
+
6
+ from transformers import GenerationMixin, LogitsProcessorList, StoppingCriteriaList
7
+ from transformers.generation import validate_stopping_criteria, EosTokenCriteria
8
+ from transformers.generation.utils import GenerateNonBeamOutput, GenerateEncoderDecoderOutput, GenerateDecoderOnlyOutput
9
+ from transformers.utils import ModelOutput
10
+
11
+
12
+ class TSGenerationMixin(GenerationMixin):
13
+
14
+ def _greedy_search(
15
+ self,
16
+ input_ids: torch.Tensor,
17
+ logits_processor: Optional[LogitsProcessorList] = None,
18
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
19
+ max_length: Optional[int] = None,
20
+ pad_token_id: Optional[int] = None,
21
+ eos_token_id: Optional[Union[int, List[int]]] = None,
22
+ output_attentions: Optional[bool] = None,
23
+ output_hidden_states: Optional[bool] = None,
24
+ output_scores: Optional[bool] = None,
25
+ output_logits: Optional[bool] = None,
26
+ return_dict_in_generate: Optional[bool] = None,
27
+ synced_gpus: bool = False,
28
+ streamer: Optional["BaseStreamer"] = None,
29
+ **model_kwargs,
30
+ ) -> Union[GenerateNonBeamOutput, torch.Tensor]:
31
+ input_ids_origin_device = input_ids.device
32
+ input_ids = input_ids.to(self.device)
33
+ if len(input_ids.shape) == 2:
34
+ batch_size, cur_len = input_ids.shape
35
+ else:
36
+ raise ValueError('Input shape must be: [batch_size, seq_len]')
37
+ # init values
38
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
39
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
40
+ if max_length is not None:
41
+ warnings.warn(
42
+ "`max_length` is deprecated in this function, use"
43
+ " `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.",
44
+ UserWarning,
45
+ )
46
+ stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)
47
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
48
+ if eos_token_id is not None:
49
+ stopping_criteria.append(EosTokenCriteria(eos_token_id=eos_token_id))
50
+ else:
51
+ # remove when the method is totally private
52
+ # need to get `eos_token_id` and add stopping criteria, so that generation does not go forever
53
+ eos_token_id = [
54
+ criteria.eos_token_id.tolist() for criteria in stopping_criteria if hasattr(criteria, "eos_token_id")
55
+ ]
56
+ eos_token_id = eos_token_id[0] if eos_token_id else None
57
+ if eos_token_id is None and self.generation_config.eos_token_id is not None:
58
+ eos_token_id = self.generation_config.eos_token_id
59
+ stopping_criteria.append(EosTokenCriteria(eos_token_id=eos_token_id))
60
+
61
+ if isinstance(eos_token_id, int):
62
+ eos_token_id = [eos_token_id]
63
+ output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
64
+ output_attentions = (
65
+ output_attentions if output_attentions is not None else self.generation_config.output_attentions
66
+ )
67
+ output_hidden_states = (
68
+ output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
69
+ )
70
+ return_dict_in_generate = (
71
+ return_dict_in_generate
72
+ if return_dict_in_generate is not None
73
+ else self.generation_config.return_dict_in_generate
74
+ )
75
+
76
+ # init attention / hidden states / scores tuples
77
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
78
+ scores = () if (return_dict_in_generate and output_scores) else None
79
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
80
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
81
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
82
+
83
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
84
+ if return_dict_in_generate and self.config.is_encoder_decoder:
85
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
86
+ encoder_hidden_states = (
87
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
88
+ )
89
+
90
+ # keep track of which sequences are already finished
91
+ if "inputs_embeds" in model_kwargs:
92
+ cur_len = model_kwargs["inputs_embeds"].shape[1]
93
+ this_peer_finished = False
94
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
95
+ model_kwargs["cache_position"] = torch.arange(cur_len, device=input_ids.device)
96
+
97
+ max_length = stopping_criteria.max_length
98
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
99
+ # prepare model inputs
100
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
101
+
102
+ input_length = input_ids.shape[1]
103
+
104
+ # forward pass to get next token
105
+ outputs = self(
106
+ **model_inputs,
107
+ return_dict=True,
108
+ output_attentions=output_attentions,
109
+ output_hidden_states=output_hidden_states,
110
+ max_horizon_length=max_length - input_length,
111
+ )
112
+
113
+ if synced_gpus and this_peer_finished:
114
+ continue # don't waste resources running the code we don't need
115
+
116
+ next_token_logits = outputs.logits[:, -1, :]
117
+
118
+ # pre-process distribution
119
+ next_tokens_scores = logits_processor(input_ids, next_token_logits)
120
+
121
+ # Store scores, attentions and hidden_states when required
122
+ if return_dict_in_generate:
123
+ if output_scores:
124
+ scores += (next_tokens_scores,)
125
+ if output_logits:
126
+ raw_logits += (next_token_logits,)
127
+ if output_attentions:
128
+ decoder_attentions += (
129
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
130
+ )
131
+ if self.config.is_encoder_decoder:
132
+ cross_attentions += (outputs.cross_attentions,)
133
+
134
+ if output_hidden_states:
135
+ decoder_hidden_states += (
136
+ (outputs.decoder_hidden_states,)
137
+ if self.config.is_encoder_decoder
138
+ else (outputs.hidden_states,)
139
+ )
140
+
141
+ # argmax
142
+ # next_tokens = torch.argmax(next_tokens_scores, dim=-1)
143
+ next_tokens = next_tokens_scores
144
+
145
+ # finished sentences should have their next token be a padding token
146
+ if eos_token_id is not None:
147
+ if pad_token_id is None:
148
+ raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
149
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
150
+
151
+ # update generated ids, model inputs, and length for next step
152
+ next_tokens = next_tokens.reshape(batch_size, -1, self.config.input_size)
153
+ horizon_length = next_tokens.shape[1]
154
+
155
+ input_ids = torch.cat([input_ids, next_tokens], dim=-2)
156
+ if streamer is not None:
157
+ streamer.put(next_tokens.cpu())
158
+ model_kwargs = self._update_model_kwargs_for_generation(
159
+ outputs,
160
+ model_kwargs,
161
+ horizon_length=horizon_length,
162
+ is_encoder_decoder=self.config.is_encoder_decoder,
163
+ )
164
+
165
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids[..., 0], scores)
166
+ this_peer_finished = unfinished_sequences.max() == 0
167
+
168
+ if input_ids.shape[1] > max_length:
169
+ input_ids = input_ids[:, :max_length]
170
+
171
+ if streamer is not None:
172
+ streamer.end()
173
+
174
+ input_ids.squeeze_(dim=-1).to(input_ids_origin_device)
175
+ if return_dict_in_generate:
176
+ if self.config.is_encoder_decoder:
177
+ return GenerateEncoderDecoderOutput(
178
+ sequences=input_ids,
179
+ scores=scores,
180
+ logits=raw_logits,
181
+ encoder_attentions=encoder_attentions,
182
+ encoder_hidden_states=encoder_hidden_states,
183
+ decoder_attentions=decoder_attentions,
184
+ cross_attentions=cross_attentions,
185
+ decoder_hidden_states=decoder_hidden_states,
186
+ past_key_values=model_kwargs.get("past_key_values"),
187
+ )
188
+ else:
189
+ return GenerateDecoderOnlyOutput(
190
+ sequences=input_ids,
191
+ scores=scores,
192
+ logits=raw_logits,
193
+ attentions=decoder_attentions,
194
+ hidden_states=decoder_hidden_states,
195
+ past_key_values=model_kwargs.get("past_key_values"),
196
+ )
197
+ else:
198
+ return input_ids
199
+
200
+ def _update_model_kwargs_for_generation(
201
+ self,
202
+ outputs: ModelOutput,
203
+ model_kwargs: Dict[str, Any],
204
+ horizon_length: int = 1,
205
+ is_encoder_decoder: bool = False,
206
+ standardize_cache_format: bool = False,
207
+ ) -> Dict[str, Any]:
208
+ # update past_key_values
209
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
210
+ outputs, standardize_cache_format=standardize_cache_format
211
+ )
212
+ if getattr(outputs, "state", None) is not None:
213
+ model_kwargs["state"] = outputs.state
214
+
215
+ # update token_type_ids with last value
216
+ if "token_type_ids" in model_kwargs:
217
+ token_type_ids = model_kwargs["token_type_ids"]
218
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
219
+
220
+ if not is_encoder_decoder:
221
+ # update attention mask
222
+ if "attention_mask" in model_kwargs:
223
+ attention_mask = model_kwargs["attention_mask"]
224
+ model_kwargs["attention_mask"] = torch.cat(
225
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], horizon_length))], dim=-1
226
+ )
227
+ else:
228
+ # update decoder attention mask
229
+ if "decoder_attention_mask" in model_kwargs:
230
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
231
+ model_kwargs["decoder_attention_mask"] = torch.cat(
232
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], horizon_length))],
233
+ dim=-1,
234
+ )
235
+
236
+ if "cache_position" in model_kwargs and model_kwargs["cache_position"] is not None:
237
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + horizon_length
238
+ # model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + 1
239
+
240
+ return model_kwargs