FILE models/TimeDART.py LINES 20-43
20: class FlattenHead(nn.Module):
21:     def __init__(
22:         self,
23:         seq_len: int,
24:         d_model: int,
25:         pred_len: int,
26:         dropout: float,
27:     ):
28:         super(FlattenHead, self).__init__()
29:         self.pred_len = pred_len
30:         self.flatten = nn.Flatten(start_dim=-2)
31:         self.forecast_head = nn.Linear(seq_len * d_model, pred_len)
32:         self.dropout = nn.Dropout(dropout)
33: 
34:     def forward(self, x: torch.Tensor) -> torch.Tensor:
35:         """
36:         :param x: [batch_size, num_features, seq_len, d_model]
37:         :return: [batch_size, pred_len, num_features]
38:         """
39:         x = self.flatten(x)  # (batch_size, num_features, seq_len * d_model)
40:         x = self.forecast_head(x)  # (batch_size, num_features, pred_len)
41:         x = self.dropout(x)  # (batch_size, num_features, pred_len)
42:         x = x.permute(0, 2, 1)  # (batch_size, pred_len, num_features)
43:         return x

FILE models/TimeDART.py LINES 113-133
113:         if self.task_name == "pretrain":
114:             self.denoising_patch_decoder = DenoisingPatchDecoder(
115:                 d_model=args.d_model,
116:                 num_layers=args.d_layers,
117:                 num_heads=args.n_heads,
118:                 feedforward_dim=args.d_ff,
119:                 dropout=args.dropout,
120:                 mask_ratio=args.mask_ratio,
121:             )
122: 
123:             self.projection = FlattenHead(
124:                 seq_len=self.seq_len,
125:                 d_model=self.d_model,
126:                 pred_len=args.input_len,
127:                 dropout=args.head_dropout,
128:             )
129:             # self.projection = ARFlattenHead(
130:             #     d_model=self.d_model,
131:             #     patch_len=self.patch_len,
132:             #     dropout=args.head_dropout,
133:             # )

FILE models/TimeDART.py LINES 143-208
143:     def pretrain(self, x):
144:         # [batch_size, input_len, num_features]
145:         batch_size, input_len, num_features = x.size()
146:         if self.use_norm:
147:             # Instance Normalization
148:             means = torch.mean(
149:                 x, dim=1, keepdim=True
150:             ).detach()  # [batch_size, 1, num_features], detach from gradient
151:             x = x - means  # [batch_size, input_len, num_features]
152:             stdevs = torch.sqrt(
153:                 torch.var(x, dim=1, keepdim=True, unbiased=False) + 1e-5
154:             ).detach()  # [batch_size, 1, num_features]
155:             x = x / stdevs  # [batch_size, input_len, num_features]
156: 
157:         # Channel Independence
158:         x = self.channel_independence(x)  # [batch_size * num_features, input_len, 1]
159:         # Patch
160:         x_patch = self.patch(x)  # [batch_size * num_features, seq_len, patch_len]
161: 
162:         # For Casual Transformer
163:         x_embedding = self.enc_embedding(
164:             x_patch
165:         )  # [batch_size * num_features, seq_len, d_model]
166:         x_embedding_bias = self.add_sos_token_and_drop_last(
167:             x_embedding
168:         )  # [batch_size * num_features, seq_len, d_model]
169:         x_embedding_bias = self.positional_encoding(x_embedding_bias)
170:         x_out = self.encoder(
171:             x_embedding_bias,
172:             is_mask=True,
173:         )  # [batch_size * num_features, seq_len, d_model]
174: 
175:         # Noising Diffusion
176:         noise_x_patch, noise, t = self.diffusion(
177:             x_patch
178:         )  # [batch_size * num_features, seq_len, patch_len]
179:         noise_x_embedding = self.enc_embedding(
180:             noise_x_patch
181:         )  # [batch_size * num_features, seq_len, d_model]
182:         noise_x_embedding = self.positional_encoding(noise_x_embedding)
183: 
184:         # For Denoising Patch Decoder
185:         predict_x = self.denoising_patch_decoder(
186:             query=noise_x_embedding,
187:             key=x_out,
188:             value=x_out,
189:             is_tgt_mask=True,
190:             is_src_mask=True,
191:         )  # [batch_size * num_features, seq_len, d_model]
192: 
193:         # For Decoder
194:         predict_x = predict_x.reshape(
195:             batch_size, num_features, -1, self.d_model
196:         )  # [batch_size, num_features, seq_len, d_model]
197:         predict_x = self.projection(predict_x)  # [batch_size, input_len, num_features]
198: 
199:         # Instance Denormalization
200:         if self.use_norm:
201:             predict_x = predict_x * (stdevs[:, 0, :].unsqueeze(1)).repeat(
202:                 1, input_len, 1
203:             )  # [batch_size, input_len, num_features]
204:             predict_x = predict_x + (means[:, 0, :].unsqueeze(1)).repeat(
205:                 1, input_len, 1
206:             )  # [batch_size, input_len, num_features]
207: 
208:         return predict_x

FILE models/TimeDART.py LINES 210-241
210:     def forecast(self, x):
211:         batch_size, _, num_features = x.size()
212:         if self.use_norm:
213:             means = torch.mean(x, dim=1, keepdim=True).detach()
214:             x = x - means
215:             stdevs = torch.sqrt(
216:             torch.var(x, dim=1, keepdim=True, unbiased=False) + 1e-5
217:             ).detach()
218:             x = x / stdevs
219: 
220:         x = self.channel_independence(x)  # [batch_size * num_features, input_len, 1]
221:         x = self.patch(x)  # [batch_size * num_features, seq_len, patch_len]
222:         x = self.enc_embedding(x)  # [batch_size * num_features, seq_len, d_model]
223:         x = self.positional_encoding(x)  # [batch_size * num_features, seq_len, d_model]
224:         x = self.encoder(
225:             x,
226:             is_mask=False,
227:         )  # [batch_size * num_features, seq_len, d_model]
228:         x = x.reshape(
229:             batch_size, num_features, -1, self.d_model
230:         )  # [batch_size, num_features, seq_len, d_model]
231: 
232:         # forecast
233:         x = self.head(x)  # [bs, pred_len, n_vars]
234: 
235:         # denormalization
236:         if self.use_norm:
237:             x = x * (stdevs[:, 0, :].unsqueeze(1)).repeat(1, self.pred_len, 1)
238:             x = x + (means[:, 0, :].unsqueeze(1)).repeat(1, self.pred_len, 1)
239: 
240:         return x
241:     

FILE layers/TimeDART_EncDec.py LINES 24-42
24: class AddSosTokenAndDropLast(nn.Module):
25:     def __init__(self, sos_token: torch.Tensor):
26:         super(AddSosTokenAndDropLast, self).__init__()
27:         assert sos_token.dim() == 3
28:         self.sos_token = sos_token
29: 
30:     def forward(self, x):
31:         """
32:         :param x: [batch_size * num_features, seq_len, d_model]
33:         :return: [batch_size * num_features, seq_len, d_model]
34:         """
35:         sos_token_expanded = self.sos_token.expand(
36:             x.size(0), -1, -1
37:         )  # [batch_size * num_features, 1, d_model]
38:         x = torch.cat(
39:             [sos_token_expanded, x], dim=1
40:         )  # [batch_size * num_features, seq_len + 1, d_model]
41:         x = x[:, :-1, :]  # [batch_size * num_features, seq_len, d_model]
42:         return x

FILE layers/TimeDART_EncDec.py LINES 103-163
103:     def forward(self, x, is_mask=True):
104:         # x: [batch_size * num_features, seq_len, d_model]
105:         seq_len = x.size(1)
106:         mask = generate_causal_mask(seq_len).to(x.device) if is_mask else None
107:         for layer in self.layers:
108:             x = layer(x, mask)
109: 
110:         x = self.norm(x)
111:         return x
112: 
113: 
114: class Diffusion(nn.Module):
115:     def __init__(
116:         self,
117:         time_steps: int,
118:         device: torch.device,
119:         scheduler: str = "cosine",
120:     ):
121:         super(Diffusion, self).__init__()
122:         self.device = device
123:         self.time_steps = time_steps
124: 
125:         if scheduler == "cosine":
126:             self.betas = self._cosine_beta_schedule().to(self.device)
127:         elif scheduler == "linear":
128:             self.betas = self._linear_beta_schedule().to(self.device)
129:         else:
130:             raise ValueError(f"Invalid scheduler: {scheduler=}")
131: 
132:         self.alpha = 1 - self.betas
133:         self.gamma = torch.cumprod(self.alpha, dim=0).to(self.device)
134: 
135:     def _cosine_beta_schedule(self, s=0.008):
136:         steps = self.time_steps + 1
137:         x = torch.linspace(0, self.time_steps, steps)
138:         alphas_cumprod = (
139:             torch.cos(((x / self.time_steps) + s) / (1 + s) * torch.pi * 0.5) ** 2
140:         )
141:         alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
142:         betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
143:         return torch.clip(betas, 0, 0.999)
144: 
145:     def _linear_beta_schedule(self, beta_start=1e-4, beta_end=0.02):
146:         betas = torch.linspace(beta_start, beta_end, self.time_steps)
147:         return betas
148: 
149:     def sample_time_steps(self, shape):
150:         return torch.randint(0, self.time_steps, shape, device=self.device)
151: 
152:     def noise(self, x, t):
153:         noise = torch.randn_like(x)
154:         gamma_t = self.gamma[t].unsqueeze(-1)  # [batch_size * num_features, seq_len, 1]
155:         # x_t = sqrt(gamma_t) * x + sqrt(1 - gamma_t) * noise
156:         noisy_x = torch.sqrt(gamma_t) * x + torch.sqrt(1 - gamma_t) * noise
157:         return noisy_x, noise
158: 
159:     def forward(self, x):
160:         # x: [batch_size * num_features, seq_len, patch_len]
161:         t = self.sample_time_steps(x.shape[:2])  # [batch_size * num_features, seq_len]
162:         noisy_x, noise = self.noise(x, t)
163:         return noisy_x, noise, t

FILE layers/TimeDART_EncDec.py LINES 189-244
189:     def forward(self, query, key, value, tgt_mask, src_mask):
190:         """
191:         :param query: [batch_size * num_features, seq_len, d_model]
192:         :param key: [batch_size * num_features, seq_len, d_model]
193:         :param value: [batch_size * num_features, seq_len, d_model]
194:         :param mask: [1, 1, seq_len, seq_len]
195:         :return: [batch_size * num_features, seq_len, d_model]
196:         """
197:         # Self-attention
198:         attn_output, _ = self.self_attention(query, query, query, attn_mask=tgt_mask)
199:         query = self.norm1(query + self.dropout(attn_output))
200: 
201:         # Encoder attention
202:         attn_output, _ = self.encoder_attention(query, key, value, attn_mask=src_mask)
203:         query = self.norm2(query + self.dropout(attn_output))
204: 
205:         # Feed-forward network
206:         ff_output = self.ff(query)
207:         x = self.norm3(query + self.dropout(ff_output))
208: 
209:         return x
210: 
211: 
212: class DenoisingPatchDecoder(nn.Module):
213:     def __init__(
214:         self,
215:         d_model: int,
216:         num_heads: int,
217:         num_layers: int,
218:         feedforward_dim: int,
219:         dropout: float,
220:         mask_ratio: float,
221:     ):
222:         super(DenoisingPatchDecoder, self).__init__()
223: 
224:         self.layers = nn.ModuleList(
225:             [
226:                 TransformerDecoderBlock(d_model, num_heads, feedforward_dim, dropout)
227:                 for _ in range(num_layers)
228:             ]
229:         )
230:         self.norm = nn.LayerNorm(d_model)
231:         self.mask_ratio = mask_ratio
232: 
233:     def forward(self, query, key, value, is_tgt_mask=True, is_src_mask=True):
234:         seq_len = query.size(1)
235:         tgt_mask = (
236:             generate_partial_mask(seq_len, self.mask_ratio).to(query.device) if is_tgt_mask else None
237:         )
238:         src_mask = (
239:             generate_partial_mask(seq_len, self.mask_ratio).to(query.device) if is_src_mask else None
240:         )
241:         for layer in self.layers:
242:             query = layer(query, key, value, tgt_mask, src_mask)
243:         x = self.norm(query)
244:         return x

FILE layers/TimeDART_EncDec.py LINES 398-419
398: class ARFlattenHead(nn.Module):
399:     def __init__(
400:         self,
401:         d_model: int,
402:         patch_len: int,
403:         dropout: float,
404:     ):
405:         super(ARFlattenHead, self).__init__()
406:         self.flatten = nn.Flatten(start_dim=-2)
407:         self.forecast_head = nn.Linear(d_model, patch_len)
408:         self.dropout = nn.Dropout(dropout)
409: 
410:     def forward(self, x: torch.Tensor) -> torch.Tensor:
411:         """
412:         :param x: [batch_size, num_features, seq_len, d_model]
413:         :return: [batch_size, seq_len * patch_len, num_features]
414:         """
415:         x = self.forecast_head(x)  # (batch_size, num_features, seq_len, patch_len)
416:         x = self.dropout(x)  # (batch_size, num_features, seq_len, patch_len)
417:         x = self.flatten(x)  # (batch_size, num_features, seq_len * patch_len)
418:         x = x.permute(0, 2, 1)  # (batch_size, seq_len * patch_len, num_features)
419:         return x

FILE utils/masking.py LINES 29-70
29: def generate_causal_mask(seq_len):
30:     mask = torch.triu(torch.ones(seq_len, seq_len, dtype=torch.bool), diagonal=1)
31:     # in nn.MultiheadAttention
32:     # binary mask is used and True means not allowed to attend
33:     # so we use triu instead of tril
34:     return mask
35: 
36: 
37: def generate_self_only_mask(seq_len):
38:     # Initialize a matrix with all True values (no attention allowed)
39:     mask = torch.ones(seq_len, seq_len, dtype=torch.bool)
40:     # Set the diagonal to False (allow self-attention)
41:     mask.fill_diagonal_(False)
42:     return mask
43: 
44: def generate_partial_mask(seq_len, mask_ratio):
45:     """Generate a partial mask with given mask ratio for the lower triangular part.
46:     
47:     Args:
48:         seq_len: Length of the sequence
49:         mask_ratio: Float between 0 and 1, portion of lower triangular elements to mask
50:                    0 -> causal mask (no masking in lower triangular)
51:                    1 -> self-only mask (all lower triangular masked)
52:     
53:     Returns:
54:         torch.Tensor: Boolean mask where True indicates positions to be masked
55:     """
56:     # Start with causal mask (upper triangular is True)
57:     mask = torch.triu(torch.ones(seq_len, seq_len, dtype=torch.bool), diagonal=1)
58:     
59:     # Get lower triangular indices (excluding diagonal)
60:     lower_indices = torch.tril_indices(seq_len, seq_len, offset=-1)
61:     
62:     # Randomly select positions to mask in lower triangular part
63:     num_lower = lower_indices.shape[1]
64:     num_to_mask = int(num_lower * mask_ratio)
65:     mask_indices = torch.randperm(num_lower)[:num_to_mask]
66:     
67:     # Set selected lower triangular positions to True (masked)
68:     mask[lower_indices[0][mask_indices], lower_indices[1][mask_indices]] = True
69:     
70:     return mask

FILE exp/exp_timedart.py LINES 68-81
68:     def _select_criterion(self):
69:         if self.args.task_name == "finetune" and self.args.downstream_task == "classification":
70:             criterion = nn.CrossEntropyLoss()
71:             print("Using CrossEntropyLoss")
72:         else:
73:             criterion = nn.MSELoss()
74:             print("Using MSELoss")
75:         return criterion
76: 
77:     def pretrain(self):
78: 
79:         # data preparation
80:         train_data, train_loader = self._get_data(flag="train")
81:         vali_data, vali_loader = self._get_data(flag="val")

FILE exp/exp_timedart.py LINES 165-205
165: 
166:     def pretrain_one_epoch(self, train_loader, model_optim, model_scheduler):
167:         train_loss = []
168:         model_criterion = self._select_criterion()
169: 
170:         self.model.train()
171:         for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(
172:             train_loader
173:         ):
174:             model_optim.zero_grad()
175: 
176:             batch_x = batch_x.float().to(self.device)
177:             batch_y = batch_y.float().to(self.device)
178: 
179:             pred_x = self.model(batch_x)
180:             diff_loss = model_criterion(pred_x, batch_x)
181:             diff_loss.backward()
182: 
183:             model_optim.step()
184:             train_loss.append(diff_loss.item())
185: 
186:         model_scheduler.step()
187:         train_loss = np.mean(train_loss)
188: 
189:         return train_loss
190: 
191:     def valid_one_epoch(self, vali_loader):
192:         vali_loss = []
193:         model_criterion = self._select_criterion()
194: 
195:         self.model.eval()
196:         with torch.no_grad():
197:             for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(
198:                 vali_loader
199:             ):
200:                 batch_x = batch_x.float().to(self.device)
201:                 batch_y = batch_y.float().to(self.device)
202: 
203:                 pred_x = self.model(batch_x)
204:                 diff_loss = model_criterion(pred_x, batch_x)
205:                 vali_loss.append(diff_loss.item())

FILE scripts/pretrain/ETTh2.sh LINES 1-40
1: python -u run.py \
2:     --task_name pretrain \
3:     --root_path ./datasets/ETT-small/ \
4:     --data_path ETTh2.csv \
5:     --model_id ETTh2 \
6:     --model TimeDART \
7:     --data ETTh2 \
8:     --features M \
9:     --input_len 336 \
10:     --e_layers 2 \
11:     --d_layers 1 \
12:     --enc_in 7 \
13:     --dec_in 7 \
14:     --c_out 7 \
15:     --n_heads 8 \
16:     --d_model 8 \
17:     --d_ff 32 \
18:     --patch_len 2 \
19:     --stride 2 \
20:     --head_dropout 0.1 \
21:     --dropout 0.2 \
22:     --time_steps 1000 \
23:     --scheduler cosine \
24:     --lr_decay 0.95 \
25:     --learning_rate 0.0005 \
26:     --batch_size 16 \
27:     --train_epochs 50 \
28:     --gpu 0