razmars commited on
Commit
1e413b5
·
verified ·
1 Parent(s): e792fee

Update modeling_super_linear.py

Browse files
Files changed (1) hide show
  1. modeling_super_linear.py +97 -178
modeling_super_linear.py CHANGED
@@ -1,19 +1,22 @@
 
1
  from typing import Optional, Tuple
2
  import torch, torch.nn as nn, torch.nn.functional as F
3
 
4
  from transformers import (PreTrainedModel,GenerationMixin,AutoConfig,AutoModelForCausalLM,)
5
  from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
6
  from .configuration_super_linear import SuperLinearConfig
7
- from torch.nn.functional import interpolate
8
-
9
- import datetime
10
-
11
 
 
 
 
12
  import numpy as np
 
 
13
  import matplotlib.pyplot as plt
14
  import os
15
- import numpy as np
16
 
 
17
 
18
  "-------------------------------------------------------------------------------------------------------------------"
19
  class RevIN(nn.Module):
@@ -99,7 +102,6 @@ class moving_avg(nn.Module):
99
  self.kernel_size = kernel_size
100
  self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0)
101
 
102
-
103
  def forward(self, x):
104
  # x: [Batch, Input length]
105
  # padding on the both ends of time series
@@ -147,8 +149,12 @@ class Linear(nn.Module):
147
 
148
  def forward(self, x):
149
  # x: [Batch*Channel, Input length]
150
- x = x.clone()
151
- x = self.Linear(x).clone()
 
 
 
 
152
  return x # to [Batch, Output length, Channel]
153
 
154
  class Naive(nn.Module):
@@ -159,7 +165,11 @@ class Naive(nn.Module):
159
 
160
  def forward(self, x):
161
  # x: [Batch*Channel, Input length]
 
 
162
  x = x[:,-1].unsqueeze(1).repeat(1, self.output_len)
 
 
163
  return x # to [Batch, Output length, Channel]
164
 
165
  class Mean(nn.Module):
@@ -169,7 +179,9 @@ class Mean(nn.Module):
169
 
170
  def forward(self, x):
171
  # x: [Batch*Channel, Input length]
 
172
  x = x.mean(dim=1).unsqueeze(1).repeat(1, self.output_len)
 
173
  return x # to [Batch, Output length, Channel]
174
 
175
 
@@ -179,74 +191,31 @@ class NLinear(nn.Module):
179
  self.Linear = nn.Linear(input_len, output_len)
180
 
181
  def forward(self, x):
182
- # x: [Batch, Input length,Channel]
183
  seq_last = x[:,-1:].detach()
184
  x = x - seq_last
185
  x = self.Linear(x)
186
- return x+seq_last # to [Batch, Output length, Channel]
 
 
187
 
188
 
189
-
190
  class RLinear(nn.Module):
191
  def __init__(self, input_len, output_len):
192
  super(RLinear, self).__init__()
193
- self.Linear = nn.Linear(input_len, output_len)
194
- self.seq_len = input_len
195
- self.horizon = output_len
196
- self.revin_layer = RevIN(num_features = None, affine=False, norm_type = None, subtract_last = False)
197
- self.zero_shot_Linear = None
198
-
199
- def transform_model(self,new_lookback,mode):
200
- if mode == 1:
201
- W = self.Linear.weight.detach()
202
- new_W = W[:, -new_lookback:]
203
- original_norm = torch.norm(W, p=2)
204
- new_norm = torch.norm(new_W, p=2)
205
- final_scaling = original_norm / new_norm if new_norm.item() != 0 else 1.0
206
- new_W = new_W * final_scaling
207
-
208
- self.zero_shot_Linear = new_W
209
- elif mode ==2:
210
- W = self.Linear.weight.detach()
211
- W4d = W.unsqueeze(0).unsqueeze(0) # (1, 1, out, in)
212
-
213
- # resize H → self.horizon and W → new_lookback
214
- new_W = F.interpolate(
215
- W4d,
216
- size=(self.horizon, new_lookback), # (H_out, W_out)
217
- mode='bilinear',
218
- align_corners=False
219
- )[0, 0] # drop the two singleton dims
220
-
221
- self.zero_shot_Linear = new_W # shape (self.horizon, new_lookback)
222
- else:
223
- W = self.Linear.weight.detach()
224
- m = nn.AdaptiveAvgPool1d(new_lookback)
225
- self.zero_shot_Linear = m(W)
226
-
227
 
228
  def forward(self, x):
229
  # x: [Batch, Input length,Channel]
230
  x_shape = x.shape
231
- ''''if x.shape[1] < self.seq_len:
232
- #if self.zero_shot_Linear is None:
233
- #print(F"new Lookkback : {x.shape[1]}")
234
-
235
- self.transform_model(x.shape[1],1)
236
- x = self.revin_layer(x, 'norm')
237
- x = F.linear(x, self.zero_shot_Linear)
238
- x = self.revin_layer(x, 'denorm')
239
- return x'''
240
-
241
-
242
  if len(x_shape) == 2:
243
  x = x.unsqueeze(-1)
244
-
245
  x = x.clone()
246
  x = self.revin_layer(x, 'norm')
 
247
  x = self.Linear(x.permute(0,2,1)).permute(0,2,1).clone()
248
  x = self.revin_layer(x, 'denorm')
249
-
250
  if len(x_shape) == 2:
251
  x = x.squeeze(-1)
252
  return x # to [Batch, Output length, Channel]
@@ -254,23 +223,27 @@ class RLinear(nn.Module):
254
  "-------------------------------------------------------------------------------------------------------------------"
255
  class SparseNoisyMoE(nn.Module):
256
  def __init__(self, configs, experts=None):
257
- self.i = 0
258
  super(SparseNoisyMoE, self).__init__()
259
  input_dim = configs.seq_len
260
- self.lookback = configs.seq_len
261
  output_dim = configs.pred_len
262
- self.k = configs.top_k_experts
263
  self.noise_std = configs.noisy_gating_std
264
  self.noise_std_decay = configs.noisy_gating_std_decay
265
  self.experts = nn.ModuleList(experts)
266
  self.num_experts = len(experts)
267
- self.ker_len = configs.ker_len
268
- self.con = configs.con
 
 
 
 
269
  self.d_model = configs.d_model
270
  self.mlp_gating = configs.mlp_gating
271
  self.moe_temp = configs.moe_temp
272
  self.use_fft = configs.use_fft
273
  self.fft_len = configs.fft_len
 
 
274
 
275
  if self.use_fft:
276
  if self.mlp_gating:
@@ -279,12 +252,18 @@ class SparseNoisyMoE(nn.Module):
279
  nn.ReLU(),
280
  nn.Linear(self.d_model, self.num_experts)
281
  )
 
282
  else:
283
  self.gating_network = nn.Linear(self.fft_len//2, self.num_experts, bias=True)
284
  else:
285
  self.gating_network = nn.Linear(input_dim, self.num_experts, bias=True)
286
 
287
- def get_periodogram(self, inputs, ker_len=50, con=1, n=10000):
 
 
 
 
 
288
  if inputs.dim() == 2:
289
  x_0 = inputs.unsqueeze(2)
290
  else:
@@ -292,19 +271,6 @@ class SparseNoisyMoE(nn.Module):
292
  x_0 = x_0 - torch.mean(x_0, dim=1, keepdim=True)
293
 
294
  v = torch.arange(0, n) / n
295
- if con:
296
- if ker_len is None:
297
- ker_len = n // 4
298
- ker_len = min(ker_len, 50)
299
-
300
- x_0 = x_0.permute(0, 2, 1)
301
- ker = (torch.ones(1, 1, ker_len) / ker_len).to(x_0.device)
302
- x_c = F.conv1d(x_0, ker, padding="same")
303
- x_c[:, :, :ker_len // 2] = x_c[:, :, ker_len // 2:ker_len // 2 + 1]
304
- x_c[:, :, -ker_len // 2:] = x_c[:, :, -ker_len // 2 - 1:-ker_len // 2]
305
- x_0 = x_0 - x_c
306
- x_0 = x_0.permute(0, 2, 1)
307
-
308
  dft = torch.fft.fft(x_0, dim=1, n=n) / np.sqrt(n)
309
  dft = dft[:, :n//2, :]
310
  I = torch.abs(dft) ** 2
@@ -322,40 +288,35 @@ class SparseNoisyMoE(nn.Module):
322
 
323
  return I
324
 
325
-
326
- def fourier_interp_dim1(self,x, target_len: int = 512):
327
-
328
- L = x.size(1)
329
- X = torch.fft.rfft(x, dim=1) # (..., 25, ...)
330
- pad = target_len // 2 + 1 - X.size(1)
331
- X_pad = torch.cat([X, X.new_zeros(*X.shape[:-1], pad)], dim=1)
332
- y = torch.fft.irfft(X_pad, n=target_len, dim=1)
333
- return y
334
-
335
  def forward(self, x, get_prob=False):
336
  if self.use_fft:
337
- x_0 = self.get_periodogram(x, ker_len=self.ker_len, n=self.fft_len, con=self.con)
 
338
  else:
339
  x_0 = x
340
 
341
- self.gate_outputs = self.gating_network(x_0)
342
- #print(self.gate_outputs.shape)
 
 
 
 
343
 
344
  if not self.training:
345
  self.gate_outputs = self.gate_outputs / self.moe_temp
346
-
 
347
  noise = torch.randn_like(self.gate_outputs).to(x.device) * self.noise_std
348
  if self.training:
349
  noisy_gate_outputs = self.gate_outputs + noise
350
- self.topk_values, topk_indices = torch.topk(noisy_gate_outputs, self.k, dim=1)
351
  else:
352
  self.topk_values, topk_indices = torch.topk(self.gate_outputs, self.k, dim=1)
353
 
 
354
  self.topk_gates = F.softmax(self.topk_values, dim=1)
355
-
356
  batch_size = x.size(0)
357
- '''if x.shape[1] < 512:
358
- x = self.fourier_interp_dim1(x)'''
359
  expert_outputs = torch.stack([self.experts[i](x) for i in range(self.num_experts)], dim=1)
360
 
361
  topk_indices_expanded = topk_indices.unsqueeze(-1).expand(-1, -1, expert_outputs.size(2))
@@ -364,10 +325,9 @@ class SparseNoisyMoE(nn.Module):
364
  output = torch.sum(self.topk_gates.unsqueeze(2) * sparse_expert_outputs, dim=1)
365
 
366
  load_balancing_loss = self.calculate_load_balancing_loss(self.gate_outputs, batch_size)
367
-
368
  if get_prob:
369
  expert_probs = F.softmax(self.gate_outputs, dim=1)
370
- print(expert_probs.shape)
371
  return output, load_balancing_loss, expert_probs
372
 
373
  return output, load_balancing_loss
@@ -387,6 +347,7 @@ class SparseNoisyMoE(nn.Module):
387
  return load_balancing_loss
388
 
389
 
 
390
  class superLinear(nn.Module):
391
  def __init__(self, configs):
392
  super(superLinear, self).__init__()
@@ -399,13 +360,14 @@ class superLinear(nn.Module):
399
  self.auto_regressive = configs.auto_regressive
400
  self.n_experts = configs.moe_n_experts
401
  self.moe = configs.moe
 
402
 
403
  if configs.freq_experts == "":
404
  self.freq_experts = None
405
  else:
406
  self.freq_experts = configs.freq_experts.split('_')
407
 
408
-
409
 
410
  self.moe_loss = None
411
  self.top_k_experts = configs.top_k_experts
@@ -415,9 +377,9 @@ class superLinear(nn.Module):
415
  self.layer_type = configs.layer_type
416
  self.model_name = "SuperLinear"
417
 
418
-
419
  self.layer_dict = {'DLinear': DLinear, 'Linear': Linear, 'NLinear': NLinear, 'RLinear': RLinear}
420
- path = configs.linear_checkpoints_path + configs.linear_checkpoints_dir + "/"
421
  dirs = os.listdir(path)
422
  checkpoints_paths = [path + "/" + d + "/" + "checkpoint.pth" for d in dirs]
423
 
@@ -462,12 +424,38 @@ class superLinear(nn.Module):
462
 
463
  self.manual_moe = configs.manual_moe
464
 
465
- if configs.misc_moe == 1:
466
- self.experts["misc"] = self.layer_dict[self.layer_type](self.seq_len, self.pred_len)
 
 
 
 
 
 
 
 
 
 
 
467
 
468
  self.moe = SparseNoisyMoE(configs, experts=self.experts.values())
469
  self.dropout = nn.Dropout(configs.dropout)
470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  def map_to_cycle(self, freq):
472
  if "/" in freq:
473
  cycle = int(freq.split("/")[1])
@@ -502,7 +490,7 @@ class superLinear(nn.Module):
502
  return cycle
503
 
504
 
505
- def forward(self, x_enc, x_mark_enc=None, x_dec=None, x_mark_dec=None, mask=None, freq=[None], get_prob=False, inf_pred_len=None):
506
 
507
  if inf_pred_len is None:
508
  inf_pred_len = self.inf_pred_len
@@ -511,13 +499,12 @@ class superLinear(nn.Module):
511
  x = x_enc.permute(0, 2, 1)
512
  B, V, L = x.shape
513
  else:
514
- x = x_enc
515
- x_enc = x_enc.unsqueeze(-1)
516
  B, L = x.shape
517
  V = 1
518
 
519
  short_lookback = False
520
- if L < self.seq_len:
521
  # print("test!")
522
  #ceil - very bad heuristic!
523
  scale_factor = self.seq_len / L
@@ -527,13 +514,12 @@ class superLinear(nn.Module):
527
  inf_pred_len = inf_pred_len*scale_factor
528
  x = interpolate(x_enc.permute(0, 2, 1), scale_factor=scale_factor, mode='linear')
529
 
530
-
531
  x = x[:,: , -self.seq_len:]
532
  orig_L = L
533
  L = self.seq_len
534
 
535
  short_lookback = True
536
-
537
  x = x.reshape(B * V, L)
538
 
539
  expert_probs = None
@@ -556,8 +542,7 @@ class superLinear(nn.Module):
556
 
557
  if short_lookback:
558
  out = interpolate(out, scale_factor=1/scale_factor, mode='linear')
559
- # print(out.shape)
560
- out = out[:, :,:orig_pred_len]
561
  result = out.permute(0, 2, 1)
562
  if get_prob:
563
  expert_probs = expert_probs.reshape(B, V, expert_probs.shape[-1])
@@ -576,64 +561,9 @@ class SuperLinearForCausalLM(PreTrainedModel, GenerationMixin):
576
  backbone_cfg = type("Cfg", (), config.to_dict())()
577
  self.args = backbone_cfg
578
  self.backbone = superLinear(backbone_cfg)
579
- self.revin_layer = RevIN(num_features = None, affine=False, norm_type = None, subtract_last = False)
580
  self.post_init()
581
 
582
 
583
-
584
- def fourier_interp_dim1(self,x, target_len: int = 512):
585
-
586
- L = x.size(1)
587
-
588
- X = torch.fft.rfft(x, dim=1) # (..., 25, ...)
589
- pad = target_len // 2 + 1 - X.size(1)
590
- X_pad = torch.cat([X, X.new_zeros(*X.shape[:-1], pad)], dim=1)
591
- y = torch.fft.irfft(X_pad, n=target_len, dim=1)
592
- return y
593
-
594
-
595
- def fourier_downsample_dim1(self,x,target_len: int):
596
-
597
- L = x.size(1)
598
- # 1. Forward real FFT along dim-1
599
- X = torch.fft.rfft(x, dim=1) # shape (..., L//2 + 1, ...)
600
-
601
- # 2. Keep only the low-frequency bins needed for the shorter series
602
- keep = target_len // 2 + 1 # rfft size for the target grid
603
- X_crop = X[..., :keep] # ideal brick-wall low-pass
604
-
605
- # 3. Inverse FFT to the shorter grid
606
- y = torch.fft.irfft(X_crop, n=target_len, dim=1)
607
-
608
-
609
- return y
610
-
611
- def upsample_interpolate(self, x, scale_factor, target_len: int = 512, mode='bicubic'):
612
- was_2d = x.dim() == 2
613
-
614
- if was_2d: # [B, L] -> [B, 1, L]
615
- x = x.unsqueeze(1)
616
- else: # [B, L, C] -> [B, C, L]
617
- x = x.permute(0, 2, 1)
618
-
619
- # Add support for bicubic interpolation by adding an extra dimension
620
- if mode == 'bicubic':
621
- x = x.unsqueeze(2) # [B, C, 1, L]
622
- x_up = F.interpolate(x, size=(1, target_len), mode='bicubic', align_corners=False)
623
- x_up = x_up.squeeze(2) # [B, C, L]
624
- else:
625
- x_up = F.interpolate(x, size=target_len, mode=mode, align_corners=False)
626
-
627
- x_up = x_up * scale_factor
628
-
629
- # Restore original layout
630
- if was_2d: # back to [B, target_len]
631
- return x_up.squeeze(1).float()
632
- else: # back to [B, target_len, C]
633
- return x_up.permute(0, 2, 1).float()
634
-
635
-
636
-
637
  def forward(self,
638
  inputs_embeds: torch.Tensor = None,
639
  attention_mask: Optional[torch.Tensor] = None,
@@ -647,19 +577,7 @@ class SuperLinearForCausalLM(PreTrainedModel, GenerationMixin):
647
  raise ValueError("Pass the time‑series as `inputs_embeds`")
648
 
649
  # backbone expects (B, C, L)
650
- x_enc = inputs_embeds
651
-
652
-
653
- if x_enc.shape[1] < 512:
654
- '''scale_factor = int(np.ceil(512/x_enc.shape[-1]))
655
- x_enc = self.upsample_interpolate(x_enc,scale_factor,512)
656
- self.backbone.inf_pred_len = 96*scale_factor
657
- preds = self.backbone(x_enc)
658
- preds = self.upsample_interpolate(preds,1/scale_factor,96)'''
659
- preds = self.backbone(x_enc)
660
- else:
661
- preds = self.backbone(x_enc)
662
-
663
  return CausalLMOutputWithCrossAttentions(loss=None,logits=preds,past_key_values=None,hidden_states=None,attentions=None,)
664
 
665
 
@@ -673,3 +591,4 @@ class SuperLinearForCausalLM(PreTrainedModel, GenerationMixin):
673
  return past # backbone keeps no KV cache
674
 
675
 
 
 
1
+
2
  from typing import Optional, Tuple
3
  import torch, torch.nn as nn, torch.nn.functional as F
4
 
5
  from transformers import (PreTrainedModel,GenerationMixin,AutoConfig,AutoModelForCausalLM,)
6
  from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
7
  from .configuration_super_linear import SuperLinearConfig
 
 
 
 
8
 
9
+ from layers.Linear_layers import DLinear, Linear, NLinear, RLinear, Naive, Mean
10
+ import math
11
+ import torch
12
  import numpy as np
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
  import matplotlib.pyplot as plt
16
  import os
17
+ from torch.nn.functional import interpolate
18
 
19
+ import datetime
20
 
21
  "-------------------------------------------------------------------------------------------------------------------"
22
  class RevIN(nn.Module):
 
102
  self.kernel_size = kernel_size
103
  self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0)
104
 
 
105
  def forward(self, x):
106
  # x: [Batch, Input length]
107
  # padding on the both ends of time series
 
149
 
150
  def forward(self, x):
151
  # x: [Batch*Channel, Input length]
152
+ x_shape = x.shape
153
+ if len(x_shape) == 2:
154
+ x = x.unsqueeze(-1)
155
+ x = self.Linear(x)
156
+ if len(x_shape) == 2:
157
+ x = x.squeeze(-1)
158
  return x # to [Batch, Output length, Channel]
159
 
160
  class Naive(nn.Module):
 
165
 
166
  def forward(self, x):
167
  # x: [Batch*Channel, Input length]
168
+
169
+
170
  x = x[:,-1].unsqueeze(1).repeat(1, self.output_len)
171
+
172
+
173
  return x # to [Batch, Output length, Channel]
174
 
175
  class Mean(nn.Module):
 
179
 
180
  def forward(self, x):
181
  # x: [Batch*Channel, Input length]
182
+
183
  x = x.mean(dim=1).unsqueeze(1).repeat(1, self.output_len)
184
+
185
  return x # to [Batch, Output length, Channel]
186
 
187
 
 
191
  self.Linear = nn.Linear(input_len, output_len)
192
 
193
  def forward(self, x):
194
+ # x: [Batch* Input length,Channel]
195
  seq_last = x[:,-1:].detach()
196
  x = x - seq_last
197
  x = self.Linear(x)
198
+
199
+ x = x + seq_last
200
+ return x
201
 
202
 
 
203
  class RLinear(nn.Module):
204
  def __init__(self, input_len, output_len):
205
  super(RLinear, self).__init__()
206
+ self.Linear = nn.Linear(input_len, output_len)
207
+ self.revin_layer = RevIN(num_features = None, affine=False, norm_type = None, subtract_last = False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
  def forward(self, x):
210
  # x: [Batch, Input length,Channel]
211
  x_shape = x.shape
 
 
 
 
 
 
 
 
 
 
 
212
  if len(x_shape) == 2:
213
  x = x.unsqueeze(-1)
 
214
  x = x.clone()
215
  x = self.revin_layer(x, 'norm')
216
+
217
  x = self.Linear(x.permute(0,2,1)).permute(0,2,1).clone()
218
  x = self.revin_layer(x, 'denorm')
 
219
  if len(x_shape) == 2:
220
  x = x.squeeze(-1)
221
  return x # to [Batch, Output length, Channel]
 
223
  "-------------------------------------------------------------------------------------------------------------------"
224
  class SparseNoisyMoE(nn.Module):
225
  def __init__(self, configs, experts=None):
 
226
  super(SparseNoisyMoE, self).__init__()
227
  input_dim = configs.seq_len
 
228
  output_dim = configs.pred_len
229
+
230
  self.noise_std = configs.noisy_gating_std
231
  self.noise_std_decay = configs.noisy_gating_std_decay
232
  self.experts = nn.ModuleList(experts)
233
  self.num_experts = len(experts)
234
+ self.k = configs.top_k_experts
235
+ if self.k > self.num_experts:
236
+ print(f"Warning: k ({self.k}) is greater than the number of experts ({self.num_experts}). Setting k to {self.num_experts}.")
237
+ self.k = self.num_experts
238
+ # self.ker_len = configs.ker_len
239
+ #self.con = configs.con
240
  self.d_model = configs.d_model
241
  self.mlp_gating = configs.mlp_gating
242
  self.moe_temp = configs.moe_temp
243
  self.use_fft = configs.use_fft
244
  self.fft_len = configs.fft_len
245
+ self.moe_norm = configs.moe_norm
246
+
247
 
248
  if self.use_fft:
249
  if self.mlp_gating:
 
252
  nn.ReLU(),
253
  nn.Linear(self.d_model, self.num_experts)
254
  )
255
+
256
  else:
257
  self.gating_network = nn.Linear(self.fft_len//2, self.num_experts, bias=True)
258
  else:
259
  self.gating_network = nn.Linear(input_dim, self.num_experts, bias=True)
260
 
261
+ if self.moe_norm:
262
+ self.batch_norm = nn.BatchNorm1d(self.num_experts)
263
+
264
+
265
+
266
+ def get_periodogram(self, inputs, n=10000):
267
  if inputs.dim() == 2:
268
  x_0 = inputs.unsqueeze(2)
269
  else:
 
271
  x_0 = x_0 - torch.mean(x_0, dim=1, keepdim=True)
272
 
273
  v = torch.arange(0, n) / n
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  dft = torch.fft.fft(x_0, dim=1, n=n) / np.sqrt(n)
275
  dft = dft[:, :n//2, :]
276
  I = torch.abs(dft) ** 2
 
288
 
289
  return I
290
 
 
 
 
 
 
 
 
 
 
 
291
  def forward(self, x, get_prob=False):
292
  if self.use_fft:
293
+ # x_0 = self.get_periodogram(x, ker_len=self.ker_len, n=self.fft_len, con=self.con)
294
+ x_0 = self.get_periodogram(x, n=self.fft_len)
295
  else:
296
  x_0 = x
297
 
298
+ self.gate_outputs = self.gating_network(x_0) # g(X)
299
+ if self.moe_norm:
300
+ # self.gate_outputs = self.batch_norm(self.gate_outputs)
301
+ self.gate_outputs = self.batch_norm(self.gate_outputs)
302
+
303
+ #
304
 
305
  if not self.training:
306
  self.gate_outputs = self.gate_outputs / self.moe_temp
307
+
308
+ # original
309
  noise = torch.randn_like(self.gate_outputs).to(x.device) * self.noise_std
310
  if self.training:
311
  noisy_gate_outputs = self.gate_outputs + noise
312
+ self.topk_values, topk_indices = torch.topk(noisy_gate_outputs, self.k, dim=1) # N = 35, k=6,12,20
313
  else:
314
  self.topk_values, topk_indices = torch.topk(self.gate_outputs, self.k, dim=1)
315
 
316
+
317
  self.topk_gates = F.softmax(self.topk_values, dim=1)
318
+
319
  batch_size = x.size(0)
 
 
320
  expert_outputs = torch.stack([self.experts[i](x) for i in range(self.num_experts)], dim=1)
321
 
322
  topk_indices_expanded = topk_indices.unsqueeze(-1).expand(-1, -1, expert_outputs.size(2))
 
325
  output = torch.sum(self.topk_gates.unsqueeze(2) * sparse_expert_outputs, dim=1)
326
 
327
  load_balancing_loss = self.calculate_load_balancing_loss(self.gate_outputs, batch_size)
328
+
329
  if get_prob:
330
  expert_probs = F.softmax(self.gate_outputs, dim=1)
 
331
  return output, load_balancing_loss, expert_probs
332
 
333
  return output, load_balancing_loss
 
347
  return load_balancing_loss
348
 
349
 
350
+
351
  class superLinear(nn.Module):
352
  def __init__(self, configs):
353
  super(superLinear, self).__init__()
 
360
  self.auto_regressive = configs.auto_regressive
361
  self.n_experts = configs.moe_n_experts
362
  self.moe = configs.moe
363
+ self.model_name = "SuperLinear"
364
 
365
  if configs.freq_experts == "":
366
  self.freq_experts = None
367
  else:
368
  self.freq_experts = configs.freq_experts.split('_')
369
 
370
+ print("self.freq_experts:", self.freq_experts)
371
 
372
  self.moe_loss = None
373
  self.top_k_experts = configs.top_k_experts
 
377
  self.layer_type = configs.layer_type
378
  self.model_name = "SuperLinear"
379
 
380
+ print("self.layer_type", self.layer_type)
381
  self.layer_dict = {'DLinear': DLinear, 'Linear': Linear, 'NLinear': NLinear, 'RLinear': RLinear}
382
+ path = configs.linear_checkpoints_path + configs.linear_checkpoints_dir
383
  dirs = os.listdir(path)
384
  checkpoints_paths = [path + "/" + d + "/" + "checkpoint.pth" for d in dirs]
385
 
 
424
 
425
  self.manual_moe = configs.manual_moe
426
 
427
+
428
+ if configs.misc_moe>0:
429
+ if configs.misc_moe == 1:
430
+ print("Creating misc expert")
431
+ self.experts["misc"] = self.layer_dict[self.layer_type](self.seq_len, self.pred_len)
432
+ else:
433
+ for i in range(configs.misc_moe):
434
+ print(f"Creating misc expert {i}")
435
+ self.experts["misc_"+str(i)] = self.layer_dict[self.layer_type](self.seq_len, self.pred_len)
436
+ if configs.misc_moe2==1:
437
+ print("Creating misc expert")
438
+ self.experts["misc2"] = self.layer_dict[self.layer_type](self.seq_len, self.pred_len)
439
+
440
 
441
  self.moe = SparseNoisyMoE(configs, experts=self.experts.values())
442
  self.dropout = nn.Dropout(configs.dropout)
443
 
444
+ if configs.load_weights:
445
+ print(f"Loading weights from {path}")
446
+ path = configs.load_weights_path + "" + configs.load_weights_dir + "/" + "checkpoint.pth"
447
+ if os.path.exists(path):
448
+ # print(f"Loading weights from {path}")
449
+ checkpoint = torch.load(path)
450
+ print(len(self.experts.keys()))
451
+ print(self.experts.keys())
452
+ print(self.state_dict().keys())
453
+ print(checkpoint.keys())
454
+ self.load_state_dict(checkpoint)
455
+ else:
456
+ print(f"Path {path} does not exist. Skipping loading weights.")
457
+
458
+
459
  def map_to_cycle(self, freq):
460
  if "/" in freq:
461
  cycle = int(freq.split("/")[1])
 
490
  return cycle
491
 
492
 
493
+ def forward(self, x_enc, x_mark_enc=None, x_dec=None, x_mark_dec=None, mask=None, freq=[None], get_prob=False):
494
 
495
  if inf_pred_len is None:
496
  inf_pred_len = self.inf_pred_len
 
499
  x = x_enc.permute(0, 2, 1)
500
  B, V, L = x.shape
501
  else:
502
+ x = x_enc
 
503
  B, L = x.shape
504
  V = 1
505
 
506
  short_lookback = False
507
+ if L<self.seq_len:
508
  # print("test!")
509
  #ceil - very bad heuristic!
510
  scale_factor = self.seq_len / L
 
514
  inf_pred_len = inf_pred_len*scale_factor
515
  x = interpolate(x_enc.permute(0, 2, 1), scale_factor=scale_factor, mode='linear')
516
 
 
517
  x = x[:,: , -self.seq_len:]
518
  orig_L = L
519
  L = self.seq_len
520
 
521
  short_lookback = True
522
+
523
  x = x.reshape(B * V, L)
524
 
525
  expert_probs = None
 
542
 
543
  if short_lookback:
544
  out = interpolate(out, scale_factor=1/scale_factor, mode='linear')
545
+ out = out[:, :,:orig_pred_len]
 
546
  result = out.permute(0, 2, 1)
547
  if get_prob:
548
  expert_probs = expert_probs.reshape(B, V, expert_probs.shape[-1])
 
561
  backbone_cfg = type("Cfg", (), config.to_dict())()
562
  self.args = backbone_cfg
563
  self.backbone = superLinear(backbone_cfg)
 
564
  self.post_init()
565
 
566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567
  def forward(self,
568
  inputs_embeds: torch.Tensor = None,
569
  attention_mask: Optional[torch.Tensor] = None,
 
577
  raise ValueError("Pass the time‑series as `inputs_embeds`")
578
 
579
  # backbone expects (B, C, L)
580
+ preds = self.backbone(inputs_embeds)
 
 
 
 
 
 
 
 
 
 
 
 
581
  return CausalLMOutputWithCrossAttentions(loss=None,logits=preds,past_key_values=None,hidden_states=None,attentions=None,)
582
 
583
 
 
591
  return past # backbone keeps no KV cache
592
 
593
 
594
+