models/HyperIMTS.py SHA256 4ddea84189bec648df73d92eef687402d91a73abc02f0d58f13d6141fbd7ee8f
1: # Code from: https://github.com/Ladbaby/PyOmniTS
2: import math
3: 
4: import torch
5: import torch.nn as nn
6: import torch.nn.functional as F
7: from einops import *
8: from torch import Tensor
9: 
10: from utils.ExpConfigs import ExpConfigs
11: from utils.globals import logger
12: 
13: 
14: class Model(nn.Module):
15:     '''
16:     - paper: "HyperIMTS: Hypergraph Neural Network for Irregular Multivariate Time Series Forecasting" (ICML 2025)
17:     - paper link: https://openreview.net/forum?id=u8wRbX2r2V
18:     - code adapted from: https://github.com/Ladbaby/PyOmniTS
19: 
20:     Note: HyperIMTS expects the unpadded input the same as SeFT and GraFITi, so we refer to some of the codes from these models when converting padded samples to unpadded ones and doing attention on flattened tensors. 
21: 
22:     Since PyOmniTS v2.0.0: The model runs at 2.9X the previous speed.
23:     '''
24:     def __init__(
25:         self,
26:         configs: ExpConfigs
27:     ):
28:         super().__init__()
29:         self.configs = configs
30:         self.enc_in = configs.enc_in
31:         self.d_model = configs.d_model
32:         self.n_layers = configs.n_layers
33:         self.n_heads = configs.n_heads
34: 
35:         seq_len = configs.seq_len_max_irr or configs.seq_len
36:         pred_len = configs.pred_len_max_irr or configs.pred_len
37:         self.hypergraph_encoder = HypergraphEncoder(
38:             enc_in=self.enc_in,
39:             time_length=seq_len + pred_len,
40:             d_model=self.d_model
41:         )
42:         self.hypergraph_learner = HypergraphLearner(
43:             n_layers=self.n_layers,
44:             d_model=self.d_model,
45:             n_heads=self.n_heads,
46:             time_length=seq_len + pred_len,
47:         )
48: 
49:         self.hypergraph_decoder = nn.Linear(3*self.d_model, 1)
50: 
51:     def forward(
52:         self, 
53:         x: Tensor, 
54:         x_mark: Tensor | None = None, 
55:         x_mask: Tensor | None = None, 
56:         y: Tensor | None = None, 
57:         y_mark: Tensor | None = None, 
58:         y_mask: Tensor | None = None,
59:         x_L_flattened: Tensor | None = None,
60:         x_y_mask_flattened: Tensor | None = None,
61:         y_L_flattened: Tensor | None = None,
62:         y_mask_L_flattened: Tensor | None = None,
63:         exp_stage: str = "train", 
64:         **kwargs
65:     ):
66:         # adaptor for unified pipeline input shape
67:         # BEGIN adaptor
68:         BATCH_SIZE, SEQ_LEN, ENC_IN = x.shape
69:         Y_LEN = self.configs.pred_len if self.configs.pred_len != 0 else SEQ_LEN
70:         if x_mark is None:
71:             x_mark = repeat(torch.arange(end=x.shape[1], dtype=x.dtype, device=x.device) / x.shape[1], "L -> B L 1", B=x.shape[0])
72:         if x_mask is None:
73:             x_mask = torch.ones_like(x, device=x.device, dtype=x.dtype)
74:         if y is None:
75:             logger.warning(f"y is missing for the model input. This is only reasonable when the model is testing flops!")
76:             y = torch.ones((BATCH_SIZE, Y_LEN, ENC_IN), dtype=x.dtype, device=x.device)
77:         if y_mark is None:
78:             y_mark = repeat(torch.arange(end=y.shape[1], dtype=y.dtype, device=y.device) / y.shape[1], "L -> B L 1", B=y.shape[0])
79:         if y_mask is None:
80:             y_mask = torch.ones_like(y, device=y.device, dtype=y.dtype)
81: 
82:         BATCH_SIZE, SEQ_LEN, ENC_IN = x.shape
83:         _, PRED_LEN, _ = y.shape
84:         L = SEQ_LEN + PRED_LEN
85: 
86:         x_mark = x_mark[:, :, :1]
87:         y_mark = y_mark[:, :, :1]
88: 
89:         if self.configs.task_name in ["short_term_forecast", "long_term_forecast", "classification", "representation_learning"]:
90:             x_zeros = torch.zeros_like(y, dtype=x.dtype, device=x.device) # fill unknown forecast targets with zeros for input
91:             y_zeros = torch.zeros_like(x, dtype=y.dtype, device=y.device)
92:             x_y_mark = torch.cat([x_mark, y_mark], dim=1) # (BATCH_SIZE, L, 1)
93:             x_L = torch.cat([x, x_zeros], dim=1)
94:             x_y_mask = torch.cat([x_mask, y_mask], dim=1)
95:             y_L = torch.cat([y_zeros, y], dim=1)
96:             y_mask_L = torch.cat([y_zeros, y_mask], dim=1)
97:         elif self.configs.task_name in ["imputation"]:
98:             x_y_mark = x_mark
99:             x_L = x
100:             x_y_mask = x_mask + y_mask
101:             y_L = y
102:             y_mask_L = y_mask
103:         else:
104:             raise NotImplementedError()
105:         # END adaptor
106: 
107:         time_indices = torch.cumsum(torch.ones_like(x_L).to(torch.int64), dim=1) - 1  # (BATCH_SIZE, L, ENC_IN) init for time indices. 0, 1, 2...
108:         variable_indices = torch.cumsum(torch.ones_like(x_L).to(torch.int64), dim=-1) - 1  # (BATCH_SIZE, L, ENC_IN) init for variable indices. 0, 1, 2...
109:         x_y_mask_bool = x_y_mask.to(torch.bool)  # (BATCH_SIZE, L, ENC_IN)
110: 
111:         # adaptor for extensibility, if the input is padded (e.g., MTS), we flatten it
112:         # BEGIN adaptor
113: 
114:         # get total number of observations in each sample, and take max
115:         N_OBSERVATIONS_MAX = torch.max(x_y_mask.sum((1, 2))).to(torch.int64)
116:         N_OBSERVATIONS_MIN = torch.min(x_y_mask.sum((1, 2))).to(torch.int64)
117:         is_regular = (N_OBSERVATIONS_MAX == N_OBSERVATIONS_MIN == L * ENC_IN) # determine if input is fully observed. Fully observed data can use faster implementation when flattening
118: 
119:         if (x_L_flattened or x_y_mask_flattened or y_L_flattened or y_mask_L_flattened) is None:
120:             if is_regular:
121:                 # regular time series input
122:                 x_L_flattened = x_L.reshape(BATCH_SIZE, L * ENC_IN)
123:                 x_y_mask_flattened = x_y_mask.reshape(BATCH_SIZE, L * ENC_IN)
124:                 y_L_flattened = y_L.reshape(BATCH_SIZE, L * ENC_IN)
125:                 y_mask_L_flattened = y_mask_L.reshape(BATCH_SIZE, L * ENC_IN)
126:             else:
127:                 # flatten everything, from (L, ENC_IN) to (N_OBSERVATIONS_MAX), where observations belonging to the same timestep are nearby
128:                 # note that r[m] won't keep the original tensor shape by default, thus flattened
129:                 x_L_flattened = self.pad_and_flatten(x_L, x_y_mask_bool, N_OBSERVATIONS_MAX) # (BATCH_SIZE, L, ENC_IN) -> (BATCH_SIZE, N_OBSERVATIONS_MAX)
130:                 x_y_mask_flattened = self.pad_and_flatten(x_y_mask, x_y_mask_bool, N_OBSERVATIONS_MAX) # (BATCH_SIZE, L, ENC_IN) -> (BATCH_SIZE, N_OBSERVATIONS_MAX)
131:                 y_L_flattened = self.pad_and_flatten(y_L, x_y_mask_bool, N_OBSERVATIONS_MAX) # (BATCH_SIZE, L, ENC_IN) -> (BATCH_SIZE, N_OBSERVATIONS_MAX)
132:                 y_mask_L_flattened = self.pad_and_flatten(y_mask_L, x_y_mask_bool, N_OBSERVATIONS_MAX) # (BATCH_SIZE, L, ENC_IN) -> (BATCH_SIZE, N_OBSERVATIONS_MAX)
133:         # END adaptor
134: 
135:         if is_regular:
136:             time_indices_flattened = time_indices.reshape(BATCH_SIZE, L * ENC_IN)
137:             variable_indices_flattened = variable_indices.reshape(BATCH_SIZE, L * ENC_IN)
138:         else:
139:             time_indices_flattened = self.pad_and_flatten(time_indices, x_y_mask_bool, N_OBSERVATIONS_MAX) # (BATCH_SIZE, L, ENC_IN) -> (BATCH_SIZE, N_OBSERVATIONS_MAX)
140:             variable_indices_flattened = self.pad_and_flatten(variable_indices, x_y_mask_bool, N_OBSERVATIONS_MAX) # (BATCH_SIZE, L, ENC_IN) -> (BATCH_SIZE, N_OBSERVATIONS_MAX)
141: 
142:         # IMTS to hypergraph
143:         (
144:             observation_nodes, 
145:             temporal_hyperedges, 
146:             variable_hyperedges, 
147:             temporal_incidence_matrix, 
148:             variable_incidence_matrix
149:         ) = self.hypergraph_encoder(
150:             x_L_flattened=x_L_flattened,
151:             x_y_mask_flattened=x_y_mask_flattened,
152:             y_mask_L_flattened=y_mask_L_flattened,
153:             x_y_mark=x_y_mark,
154:             variable_indices_flattened=variable_indices_flattened,
155:             time_indices_flattened=time_indices_flattened,
156:             N_OBSERVATIONS_MAX=N_OBSERVATIONS_MAX
157:         )
158: 
159:         # hypergraph learning
160:         (
161:             observation_nodes, 
162:             temporal_hyperedges, 
163:             variable_hyperedges
164:         ) = self.hypergraph_learner(
165:             observation_nodes=observation_nodes, 
166:             temporal_hyperedges=temporal_hyperedges, 
167:             variable_hyperedges=variable_hyperedges,
168:             time_indices_flattened=time_indices_flattened,
169:             variable_indices_flattened=variable_indices_flattened,
170:             temporal_incidence_matrix=temporal_incidence_matrix, 
171:             variable_incidence_matrix=variable_incidence_matrix,
172:             x_y_mask_flattened=x_y_mask_flattened,
173:             x_y_mask=x_y_mask,
174:             y_mask_L_flattened=y_mask_L_flattened
175:         )
176: 
177:         if self.configs.task_name in ['long_term_forecast', 'short_term_forecast', "imputation"]:
178:             # hypergraph to IMTS
179:             pred_flattened = self.hypergraph_decoder(
180:                 torch.cat([
181:                     observation_nodes, 
182:                     temporal_hyperedges.gather(dim=1, index=repeat(
183:                         time_indices_flattened,
184:                         "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
185:                         D=self.d_model
186:                     )), 
187:                     variable_hyperedges.gather(dim=1, index=repeat(
188:                         variable_indices_flattened,
189:                         "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
190:                         D=self.d_model
191:                     )),
192:                 ], dim=-1)
193:             ).squeeze(-1)
194: 
195:             # use these codes for faster speed during training, but can affect compatibility with some loss functions
196:             # if exp_stage in ["train", "val"]:
197:             #     return {
198:             #         "pred": pred_flattened,
199:             #         "true": y_L_flattened,
200:             #         "mask": y_mask_L_flattened
201:             #     }
202:             # else:
203: 
204:             # convert unpadded tensor back to shape [batch_size, seq_len + pred_len, enc_in] to align with the pipeline's unified api when testing
205:             pred = self.unpad_and_reshape(
206:                 tensor_flattened=pred_flattened,
207:                 original_mask=torch.cat([x_mask, y_mask], dim=1),
208:                 original_shape=(BATCH_SIZE, SEQ_LEN + PRED_LEN, ENC_IN)
209:             )
210:             f_dim = -1 if self.configs.features == 'MS' else 0
211:             return {
212:                 "pred": pred[:, -PRED_LEN:, f_dim:],
213:                 "true": y[:, :, f_dim:],
214:                 "mask": y_mask[:, :, f_dim:],
215:             }
216:         else:
217:             raise NotImplementedError()
218: 
219:     def pad_and_flatten(self, tensor: Tensor, mask: Tensor, max_len: int) -> Tensor:
220:         """
221:         Speed optimized since PyOmniTS v2.0.0
222:         Much faster than looping through batch with list comprehension.
223:         """
224:         batch_size = tensor.shape[0]
225:         device = tensor.device
226:         dtype = tensor.dtype
227: 
228:         # 1. Flatten both to (B, -1)
229:         tensor_flat = tensor.view(batch_size, -1)
230:         mask_flat = mask.view(batch_size, -1)
231: 
232:         # 2. Use cumsum to find the destination column index for every element
233:         # We subtract 1 to make it 0-indexed.
234:         # [0, 1, 0, 1] -> cumsum -> [0, 1, 1, 2] -> minus 1 -> [-1, 0, 0, 1]
235:         dest_indices = torch.cumsum(mask_flat, dim=1) - 1
236: 
237:         # 3. Create a filter for valid elements that fit within max_len
238:         # Elements must be in the mask AND their destination index must be < max_len
239:         keep_mask = (mask_flat == 1) & (dest_indices < max_len)
240: 
241:         # 4. Prepare the output buffer
242:         result = torch.zeros((batch_size, max_len), dtype=dtype, device=device)
243: 
244:         # 5. Advanced Indexing: 
245:         # We need row indices for every element we are keeping
246:         row_indices = torch.arange(batch_size, device=device).unsqueeze(1).expand_as(mask_flat)
247:         
248:         # Filter the indices and values
249:         rows = row_indices[keep_mask]
250:         cols = dest_indices[keep_mask]
251:         values = tensor_flat[keep_mask]
252: 
253:         # 6. Scatter the values into the result
254:         result[rows, cols] = values
255: 
256:         return result
257: 
258:     def unpad_and_reshape(
259:         self, 
260:         tensor_flattened: Tensor, 
261:         original_mask: Tensor, 
262:         original_shape: tuple
263:     ):
264:         original_mask = original_mask.bool()
265:         device = tensor_flattened.device
266:         # Initialize the result tensor on the correct device
267:         result = torch.zeros(original_shape, dtype=tensor_flattened.dtype, device=device)
268: 
269:         # 1. Calculate how many valid elements exist per batch item
270:         # This replaces len(masked_indices) for every row at once
271:         # Supports masks of shape (B, L) or (B, H, W)
272:         counts = original_mask.sum(dim=tuple(range(1, original_mask.dim())))
273: 
274:         # 2. Create a boolean mask for the 'tensor_flattened' source
275:         # We need to pick the first 'n' elements from each row of tensor_flattened
276:         batch_size, max_len = tensor_flattened.shape[:2]
277:         # Creates a grid of indices: [[0,1,2...], [0,1,2...]]
278:         steps = torch.arange(max_len, device=device).expand(batch_size, max_len)
279:         src_mask = steps < counts.unsqueeze(-1)
280: 
281:         # 3. Vectorized Assignment
282:         # result[original_mask] automatically maps to the flattened valid elements
283:         # tensor_flattened[src_mask] extracts only the unpadded elements
284:         result[original_mask] = tensor_flattened[src_mask]
285: 
286:         return result
287: 
288:     def get_pred_repr_obs(
289:         self, 
290:         tensor_flattened: Tensor, 
291:         original_mask: Tensor, 
292:     ):
293:         BATCH_SIZE, L, ENC_IN = original_mask.shape
294:         D_MODEL = tensor_flattened.shape[-1]
295:         result = torch.zeros((BATCH_SIZE, L, ENC_IN, D_MODEL), dtype=tensor_flattened.dtype, device=tensor_flattened.device)
296: 
297:         for i in range(BATCH_SIZE):
298:             masked_indices = original_mask[i].unsqueeze(-1).repeat(1, 1, 1, D_MODEL).view(-1).nonzero(as_tuple=True)[0]
299:             tensor_flattened_viewed = tensor_flattened.reshape(BATCH_SIZE, -1)[i][:len(masked_indices)]
300:             result[i].view(-1)[masked_indices] = tensor_flattened_viewed
301: 
302:         return result # (B L ENC_IN D_MODEL)
303:     
304: class HypergraphEncoder(nn.Module):
305:     '''
306:     IMTS to Hypergraph nodes and hyperedges
307:     - observed values -> nodes
308:     - timestamps -> temporal hyperedges
309:     - variables -> variable hyperedges
310:     '''
311:     def __init__(
312:         self,
313:         enc_in,
314:         time_length,
315:         d_model
316:     ):
317:         super().__init__()
318:         self.enc_in = enc_in
319:         self.time_length = time_length
320:         self.d_model = d_model
321: 
322:         self.variable_hyperedge_weights = nn.Parameter(
323:             torch.randn(enc_in, d_model),
324:             requires_grad=True
325:         )
326: 
327:         self.relu = nn.ReLU()
328:         self.observation_node_encoder = nn.Linear(2, d_model)
329:         self.temporal_hyperedge_encoder = nn.Linear(1, d_model)
330: 
331:     def forward(
332:         self,
333:         x_L_flattened: Tensor,
334:         x_y_mask_flattened: Tensor,
335:         y_mask_L_flattened: Tensor,
336:         x_y_mark: Tensor,
337:         variable_indices_flattened: Tensor,
338:         time_indices_flattened: Tensor,
339:         N_OBSERVATIONS_MAX: int
340:     ):
341:         BATCH_SIZE = x_L_flattened.shape[0]
342:         ENC_IN = self.enc_in
343:         L = x_y_mark.shape[1]
344: 
345:         # add indicator for forecast targets
346:         x_L_flattened = torch.stack(
347:             [
348:                 x_L_flattened, 
349:                 1 - x_y_mask_flattened + y_mask_L_flattened
350:             ],
351:             dim=-1
352:         ) # (BATCH_SIZE, N_OBSERVATIONS_MAX) -> (BATCH_SIZE, N_OBSERVATIONS_MAX, 2)
353: 
354:         # (BATCH_SIZE, L, N_OBSERVATIONS_MAX)
355:         # indicate for every temporal hyperedge, which observation connected to it
356:         temporal_incidence_matrix = repeat(
357:             time_indices_flattened,
358:             "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE L N_OBSERVATIONS_MAX",
359:             L=L
360:         )
361:         temporal_incidence_matrix = (temporal_incidence_matrix == repeat(
362:             torch.ones(BATCH_SIZE, L).to(x_L_flattened.device).cumsum(dim=1),
363:             "BATCH_SIZE L -> BATCH_SIZE L N_OBSERVATIONS_MAX",
364:             N_OBSERVATIONS_MAX=N_OBSERVATIONS_MAX
365:         ) - 1).to(torch.float32)
366:         temporal_incidence_matrix = temporal_incidence_matrix * repeat(
367:             x_y_mask_flattened,
368:             "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE L N_OBSERVATIONS_MAX", 
369:             L=L
370:         ) # remove non-observed values at tail
371: 
372:         
373:         # (BATCH_SIZE, ENC_IN, N_OBSERVATIONS_MAX)
374:         # indicate for every variable hyperedge, which observation connected to it
375:         variable_incidence_matrix = repeat(
376:             torch.ones([BATCH_SIZE, ENC_IN]).cumsum(dim=1).to(x_L_flattened.device) - 1,
377:             "BATCH_SIZE ENC_IN -> BATCH_SIZE ENC_IN N_OBSERVATIONS_MAX", 
378:             N_OBSERVATIONS_MAX=N_OBSERVATIONS_MAX
379:         )
380:         variable_incidence_matrix = (variable_incidence_matrix == repeat(
381:             variable_indices_flattened, 
382:             "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE ENC_IN N_OBSERVATIONS_MAX", 
383:             ENC_IN=ENC_IN
384:         )).to(torch.float32)
385:         variable_incidence_matrix = variable_incidence_matrix * repeat(
386:             x_y_mask_flattened,
387:             "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE ENC_IN N_OBSERVATIONS_MAX", 
388:             ENC_IN=ENC_IN
389:         ) # remove non-observed values at tail
390: 
391:         # init observation nodes (BATCH_SIZE, N_OBSERVATIONS_MAX, 2) -> (BATCH_SIZE, N_OBSERVATIONS_MAX, d_model)
392:         observation_nodes = self.relu(self.observation_node_encoder(x_L_flattened)) * repeat(
393:             x_y_mask_flattened,
394:             "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
395:             D=self.d_model
396:         )
397:         # init temporal hyperedges (BATCH_SIZE, L, d_model) 
398:         temporal_hyperedges = torch.sin(self.temporal_hyperedge_encoder(x_y_mark))  
399:         # init variable hyperedges (BATCH_SIZE, ENC_IN, d_model) 
400:         variable_hyperedges = self.relu(
401:             repeat(
402:                 self.variable_hyperedge_weights.to(x_L_flattened.device), 
403:                 "ENC_IN D_MODEL -> BATCH_SIZE ENC_IN D_MODEL",
404:                 BATCH_SIZE=BATCH_SIZE
405:             )
406:         )
407: 
408:         return (
409:             observation_nodes, 
410:             temporal_hyperedges, 
411:             variable_hyperedges,
412:             temporal_incidence_matrix,
413:             variable_incidence_matrix
414:         )
415:             
416: 
417: class HypergraphLearner(nn.Module):
418:     '''
419:     Message passing:
420: 
421:     - nodes-to-hyperedge
422:     - hyperedge-to-hyperedge
423:     - hyperedge-to-node
424: 
425:     implemented via attention
426:     '''
427:     def __init__(
428:         self,
429:         n_layers: int,
430:         d_model: int,
431:         n_heads: int,
432:         time_length: int,
433:     ):
434:         super().__init__()
435:         self.n_layers = n_layers
436:         self.d_model = d_model
437: 
438:         self.activation = nn.ReLU()
439: 
440:         self.node2variable_hyperedge = nn.ModuleList(
441:             MultiHeadAttentionBlock(
442:                 dim_Q=d_model, 
443:                 dim_K=2*d_model, 
444:                 dim_V=2*d_model,
445:                 n_dim=d_model, 
446:                 num_heads=n_heads
447:             ) for _ in range(self.n_layers)
448:         )
449:         self.node2temporal_hyperedge = nn.ModuleList(
450:             MultiHeadAttentionBlock(
451:                 dim_Q=d_model, 
452:                 dim_K=2*d_model, 
453:                 dim_V=2*d_model,
454:                 n_dim=d_model, 
455:                 num_heads=n_heads
456:             ) for _ in range(self.n_layers)
457:         )
458:         self.node_self_update = nn.ModuleList(
459:             MultiHeadAttentionBlock(
460:                 dim_Q=d_model, 
461:                 dim_K=3*d_model, 
462:                 dim_V=3*d_model,
463:                 n_dim=d_model, 
464:                 num_heads=n_heads
465:             ) for _ in range(self.n_layers)
466:         )
467:         self.variable_hyperedge2variable_hyperedge = IrregularityAwareAttention(
468:             d_model=d_model
469:         )
470:         self.hyperedge2node = nn.ModuleList(
471:             nn.Linear(3*d_model, d_model) for _ in range(self.n_layers)
472:         )
473: 
474:         self.hyperedge2hyperedge_layers = [
475:             n_layers - 1
476:         ]
477:         self.scale = 1 / time_length
478:         self.oom_flag = False
479: 
480:     def forward(
481:         self,
482:         observation_nodes: Tensor, 
483:         temporal_hyperedges: Tensor, 
484:         variable_hyperedges: Tensor,
485:         time_indices_flattened: Tensor,
486:         variable_indices_flattened: Tensor,
487:         temporal_incidence_matrix: Tensor, 
488:         variable_incidence_matrix: Tensor,
489:         x_y_mask_flattened: Tensor,
490:         x_y_mask: Tensor,
491:         y_mask_L_flattened: Tensor
492:     ):
493:         for i in range(self.n_layers):
494:             if i == 0:
495:                 mask_temp = 1 - repeat(y_mask_L_flattened, "B N -> B L N", L=temporal_incidence_matrix.shape[1])
496:                 mask_temp[mask_temp == 0] = 1e-8
497:             # observation nodes to temporal hyperedges
498:             temporal_hyperedges_updated = self.node2temporal_hyperedge[i](
499:                 temporal_hyperedges, 
500:                 torch.cat([
501:                     variable_hyperedges.gather(dim=1, index=repeat(
502:                         variable_indices_flattened,
503:                         "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
504:                         D=self.d_model
505:                     )),
506:                     observation_nodes
507:                 ], -1), 
508:                 temporal_incidence_matrix if i != 0 else temporal_incidence_matrix * mask_temp
509:             )    
510:             if i == 0:
511:                 mask_temp = 1 - repeat(y_mask_L_flattened, "B N -> B ENC_IN N", ENC_IN=variable_incidence_matrix.shape[1])
512:                 mask_temp[mask_temp == 0] = 1e-8
513:             # observation nodes to variable hyperedges
514:             variable_hyperedges_updated = self.node2variable_hyperedge[i](
515:                 variable_hyperedges, 
516:                 torch.cat([
517:                     temporal_hyperedges.gather(dim=1, index=repeat(
518:                         time_indices_flattened,
519:                         "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
520:                         D=self.d_model
521:                     )), 
522:                     observation_nodes
523:                 ], -1), 
524:                 variable_incidence_matrix if i != 0 else variable_incidence_matrix * mask_temp
525:             )
526:             variable_hyperedges = variable_hyperedges_updated
527:             temporal_hyperedges = temporal_hyperedges_updated
528: 
529:             # hyperedge-to-node update
530:             temporal_hyperedges_gathered = temporal_hyperedges.gather(
531:                 dim=1, 
532:                 index=repeat(
533:                     time_indices_flattened,
534:                     "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
535:                     D=self.d_model
536:                 )
537:             )
538:             variable_hyperedges_gathered = variable_hyperedges.gather(
539:                 dim=1, 
540:                 index=repeat(
541:                     variable_indices_flattened,
542:                     "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
543:                     D=self.d_model
544:                 )
545:             ) # (BATCH_SIZE, N_OBSERVATIONS_MAX, d_model)
546:             if not self.oom_flag:
547:                 try:
548:                     observation_nodes_updated = self.node_self_update[i](
549:                         observation_nodes, 
550:                         torch.cat([temporal_hyperedges_gathered, variable_hyperedges_gathered, observation_nodes], -1), 
551:                         x_y_mask_flattened.unsqueeze(2) * x_y_mask_flattened.unsqueeze(1)
552:                     )
553:                     observation_nodes = self.activation(
554:                         (observation_nodes + self.hyperedge2node[i](torch.cat([observation_nodes_updated, temporal_hyperedges_gathered, variable_hyperedges_gathered], dim=-1))) * \
555:                         repeat(
556:                             x_y_mask_flattened,
557:                             "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
558:                             D=self.d_model
559:                         )
560:                     )
561:                 except:
562:                     self.oom_flag = True
563:                     logger.warning("CUDA out of memory detected. Try changing calculation method...")
564: 
565:             if self.oom_flag:
566:                 observation_nodes = self.activation(
567:                     (observation_nodes + self.hyperedge2node[i](torch.cat([observation_nodes, temporal_hyperedges_gathered, variable_hyperedges_gathered], dim=-1))) * \
568:                     repeat(
569:                         x_y_mask_flattened,
570:                         "BATCH_SIZE N_OBSERVATIONS_MAX -> BATCH_SIZE N_OBSERVATIONS_MAX D",
571:                         D=self.d_model
572:                     )
573:                 )
574: 
575:             if i in self.hyperedge2hyperedge_layers:
576:                 # perform hyperedge-to-hyperedge message passing after fully learned in previous layers
577:                 sync_mask = x_y_mask
578:                 query_and_key = self.get_fine_grained_embedding(observation_nodes, sync_mask)
579:                 merge_coefficients = sync_mask.transpose(-1, -2) @ sync_mask
580:                 n_observations_per_variable = merge_coefficients.diagonal(offset=0, dim1=-2, dim2=-1)
581:                 merge_coefficients[n_observations_per_variable != 0] = (merge_coefficients / repeat(n_observations_per_variable, "B ENC_IN -> B ENC_IN ENC_IN_2", ENC_IN_2=sync_mask.shape[-1]))[n_observations_per_variable != 0]
582:                 variable_hyperedges_updated = variable_hyperedges_updated + self.variable_hyperedge2variable_hyperedge(
583:                     x=variable_hyperedges_updated,
584:                     query_aux=query_and_key,
585:                     key_aux=query_and_key,
586:                     merge_coefficients=merge_coefficients
587:                 )
588:                 variable_hyperedges = variable_hyperedges_updated
589: 
590:         return (
591:             observation_nodes,
592:             temporal_hyperedges,
593:             variable_hyperedges,
594:         )
595: 
596:     def get_fine_grained_embedding(
597:         self, 
598:         tensor_flattened: Tensor, 
599:         target_shape: Tensor, 
600:     ):
601:         """
602:         Speed optimized since PyOmniTS v2.0.0
603:         """
604:         BATCH_SIZE, L, ENC_IN = target_shape.shape
605:         D_MODEL = tensor_flattened.shape[-1]
606:         
607:         # Vectorized Slicing
608:         new_d_model = max(1, int(D_MODEL * self.scale))
609:         tensor_flattened = tensor_flattened[:, :, :new_d_model]
610:         
611:         # Create the mask (Vectorized)
612:         # target_shape: (B, L, ENC_IN) -> (B, L, ENC_IN, 1) -> (B, L, ENC_IN, D_MODEL_SCALED)
613:         # .expand() creates a view, it doesn't allocate new memory like .repeat()
614:         mask = (target_shape > 0).unsqueeze(-1).expand(-1, -1, -1, new_d_model)
615:         
616:         # Initialize result and scatter
617:         result = torch.zeros((BATCH_SIZE, L, ENC_IN, new_d_model), 
618:                             dtype=tensor_flattened.dtype, 
619:                             device=tensor_flattened.device)
620:         
621:         # masked_scatter_ fills 'result' with elements from 'tensor_flattened' 
622:         # where 'mask' is True. It is highly optimized for GPU.
623:         result.masked_scatter_(mask, tensor_flattened)
624: 
625:         return rearrange(
626:             result,
627:             "B L ENC_IN D_MODEL_SCALED -> B ENC_IN (L D_MODEL_SCALED)"
628:         )
629: 
630: class MultiHeadAttentionBlock(nn.Module):
631:     '''
632:     adapted from GraFITi
633:     '''
634:     def __init__(self, dim_Q, dim_K, dim_V, n_dim, num_heads, ln=False):
635:         super(MultiHeadAttentionBlock, self).__init__()
636:         self.dim_V = dim_V
637:         self.num_heads = num_heads
638:         self.n_dim = n_dim
639:         self.fc_q = nn.Linear(dim_Q, n_dim)
640:         self.fc_k = nn.Linear(dim_K, n_dim)
641:         self.fc_v = nn.Linear(dim_K, n_dim)
642:         if ln:
643:             self.ln0 = nn.LayerNorm(dim_V)
644:             self.ln1 = nn.LayerNorm(dim_V)
645:         self.fc_o = nn.Linear(n_dim, n_dim)
646: 
647:     def forward(
648:         self, 
649:         Q: Tensor, 
650:         K: Tensor, 
651:         mask: Tensor | None = None
652:     ):
653:         Q = self.fc_q(Q)
654:         K, V = self.fc_k(K), self.fc_v(K)
655: 
656:         dim_split = self.n_dim // self.num_heads
657:         Q_ = torch.cat(Q.split(dim_split, dim=2), dim=0)
658:         K = torch.cat(K.split(dim_split, dim=2), dim=0)
659:         V = torch.cat(V.split(dim_split, dim=2), dim=0)
660: 
661:         Att_mat = Q_.bmm(K.transpose(1, 2))/math.sqrt(self.n_dim) # (B * num_heads, enc_in, n_observations_max)
662: 
663:         if mask is not None:
664:             Att_mat = Att_mat.masked_fill(
665:                 mask.repeat(self.num_heads, 1, 1) == 0, -10e9)
666:         A = torch.softmax(Att_mat, 2)
667:         O = torch.cat((Q_ + A.bmm(V)).split(Q.size(0), dim=0), 2)
668:         O = O if getattr(self, 'ln0', None) is None else self.ln0(O)
669:         O = O + F.relu(self.fc_o(O))
670:         O = O if getattr(self, 'ln1', None) is None else self.ln1(O)
671:         return O
672: 
673: class IrregularityAwareAttention(nn.Module):
674:     def __init__(self, d_model):
675:         super().__init__()
676:         
677:         self.query_proj = nn.Linear(d_model, d_model)
678:         self.key_proj = nn.Linear(d_model, d_model)
679:         self.value_proj = nn.Linear(d_model, d_model)
680:         
681:         self.scale = d_model ** 0.5
682: 
683:         self.threshold = nn.Parameter(torch.tensor(0.5), requires_grad=True)
684:     
685:     def forward(
686:         self, 
687:         x: Tensor, 
688:         query_aux: Tensor | None = None,
689:         key_aux: Tensor | None = None,
690:         adjacency_mask: Tensor | None = None,
691:         merge_coefficients: Tensor | None = None,
692:     ):
693:         batch_size, n_variables, hidden_dim = x.shape
694:         
695:         query = self.query_proj(x) 
696:         key = self.key_proj(x)     
697:         value = self.value_proj(x) 
698:         
699:         attention_scores = torch.matmul(query, key.transpose(-2, -1)) / self.scale
700:         mask_value = torch.finfo(attention_scores.dtype).min
701: 
702:         if query_aux is not None and key_aux is not None:
703:             query_aux = query_aux
704:             key_aux = key_aux
705: 
706:             attention_scores_aux = torch.matmul(query_aux, key_aux.transpose(-2, -1)) / (key_aux.shape[-1] ** 0.5)
707:             
708:             non_zero_mask = (attention_scores_aux != 0)
709:             positive_mask = (attention_scores > self.threshold)
710: 
711:             mask = positive_mask & non_zero_mask
712: 
713:             attention_scores[mask]  = ((1 - merge_coefficients) * attention_scores + merge_coefficients * attention_scores_aux)[mask]
714:         
715:         # If adjacency mask is provided, apply it to attention scores
716:         if adjacency_mask is not None:
717:             assert adjacency_mask.shape == (batch_size, n_variables, n_variables), \
718:                 f"Adjacency mask shape must be {(batch_size, n_variables, n_variables)}, " \
719:                 f"got {adjacency_mask.shape}"
720:             
721:             masked_attention_scores = attention_scores.masked_fill(
722:                 adjacency_mask == 0, mask_value
723:             )
724:         else:
725:             masked_attention_scores = attention_scores
726:         
727:         # Apply softmax to get attention weights
728:         attention_weights = torch.softmax(masked_attention_scores, dim=-1) # (batch_size, n_variables, n_variables)
729: 
730:         # Apply attention weights to values
731:         attended_values = torch.matmul(attention_weights, value)
732: 
733:         return attended_values