Maple728 commited on
Commit
62f1812
1 Parent(s): edd5845

Initial commit

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