File size: 25,266 Bytes
5769ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
from einops.layers.torch import Rearrange
from einops import rearrange, repeat
import torch
import torch.nn as nn

from risk_biased.models.multi_head_attention import MultiHeadAttention
from risk_biased.models.context_gating import ContextGating
from risk_biased.models.mlp import MLP


class SequenceEncoderMaskedLSTM(nn.Module):
    """MLP followed with a masked LSTM implementation with one layer.

    Args:
        input_dim : dimension of the input variable
        h_dim : dimension of a hidden layer of MLP
    """

    def __init__(self, input_dim: int, h_dim: int) -> None:
        super().__init__()
        self._group_objects = Rearrange("b o ... -> (b o) ...")
        self._embed = nn.Linear(in_features=input_dim, out_features=h_dim)
        self._lstm = nn.LSTMCell(
            input_size=h_dim, hidden_size=h_dim
        )  # expects(batch,seq,features)
        self.h0 = nn.parameter.Parameter(torch.zeros(1, h_dim))
        self.c0 = nn.parameter.Parameter(torch.zeros(1, h_dim))

    def forward(self, input: torch.Tensor, mask_input: torch.Tensor) -> torch.Tensor:
        """Forward function for MapEncoder

        Args:
            input (torch.Tensor): (batch_size, num_objects, seq_len, input_dim) tensor
            mask_input (torch.Tensor): (batch_size, num_objects, seq_len) bool tensor (True if data is good False if data is missing)

        Returns:
            torch.Tensor: (batch_size, num_objects, output_dim) tensor
        """

        batch_size, num_objects, seq_len, _ = input.shape
        split_objects = Rearrange("(b o) f -> b o f", b=batch_size, o=num_objects)

        input = self._group_objects(input)
        mask_input = self._group_objects(mask_input)
        embedded_input = self._embed(input)

        # One to many encoding of the input sequence with masking for missing points
        mask_input = mask_input.float()
        h = mask_input[:, 0, None] * embedded_input[:, 0, :] + (
            1 - mask_input[:, 0, None]
        ) * repeat(self.h0, "b f -> (size b) f", size=batch_size * num_objects)
        c = repeat(self.c0, "b f -> (size b) f", size=batch_size * num_objects)
        for i in range(seq_len):
            new_input = (
                mask_input[:, i, None] * embedded_input[:, i, :]
                + (1 - mask_input[:, i, None]) * h
            )
            h, c = self._lstm(new_input, (h, c))
        return split_objects(h)


class SequenceEncoderLSTM(nn.Module):
    """MLP followed with an LSTM with one layer.

    Args:
        input_dim : dimension of the input variable
        h_dim : dimension of a hidden layer of MLP
    """

    def __init__(self, input_dim: int, h_dim: int) -> None:
        super().__init__()
        self._group_objects = Rearrange("b o ... -> (b o) ...")
        self._embed = nn.Linear(in_features=input_dim, out_features=h_dim)
        self._lstm = nn.LSTM(
            input_size=h_dim,
            hidden_size=h_dim,
            batch_first=True,
        )  # expects(batch,seq,features)
        self.h0 = nn.parameter.Parameter(torch.zeros(1, h_dim))
        self.c0 = nn.parameter.Parameter(torch.zeros(1, h_dim))

    def forward(self, input: torch.Tensor, mask_input: torch.Tensor) -> torch.Tensor:
        """Forward function for MapEncoder

        Args:
            input (torch.Tensor): (batch_size, num_objects, seq_len, input_dim) tensor
            mask_input (torch.Tensor): (batch_size, num_objects, seq_len) bool tensor (True if data is good False if data is missing)

        Returns:
            torch.Tensor: (batch_size, num_objects, output_dim) tensor
        """

        batch_size, num_objects, seq_len, _ = input.shape
        split_objects = Rearrange("(b o) f -> b o f", b=batch_size, o=num_objects)

        input = self._group_objects(input)
        mask_input = self._group_objects(mask_input)
        embedded_input = self._embed(input)

        # One to many encoding of the input sequence with masking for missing points
        mask_input = mask_input.float()
        h = (
            mask_input[:, 0, None] * embedded_input[:, 0, :]
            + (1 - mask_input[:, 0, None])
            * repeat(
                self.h0, "one f -> one size f", size=batch_size * num_objects
            ).contiguous()
        )
        c = repeat(
            self.c0, "one f -> one size f", size=batch_size * num_objects
        ).contiguous()
        _, (h, _) = self._lstm(embedded_input, (h, c))
        # for i in range(seq_len):
        #     new_input = (
        #         mask_input[:, i, None] * embedded_input[:, i, :]
        #         + (1 - mask_input[:, i, None]) * h
        #     )
        #     h, c = self._lstm(new_input, (h, c))
        return split_objects(h.squeeze(0))


class SequenceEncoderMLP(nn.Module):
    """MLP implementation.

    Args:
        input_dim : dimension of the input variable
        h_dim : dimension of a hidden layer of MLP
        num_layers: number of layers to use in the MLP
        sequence_length: dimension of the input sequence
        is_mlp_residual: set to True to add a linear transformation of the input to the output of the MLP
    """

    def __init__(
        self,
        input_dim: int,
        h_dim: int,
        num_layers: int,
        sequence_length: int,
        is_mlp_residual: bool,
    ) -> None:
        super().__init__()
        self._mlp = MLP(
            input_dim * sequence_length, h_dim, h_dim, num_layers, is_mlp_residual
        )

    def forward(self, input: torch.Tensor, mask_input: torch.Tensor) -> torch.Tensor:
        """Forward function for MapEncoder

        Args:
            input (torch.Tensor): (batch_size, num_objects, seq_len, input_dim) tensor
            mask_input (torch.Tensor): (batch_size, num_objects, seq_len) bool tensor (True if data is good False if data is missing)

        Returns:
            torch.Tensor: (batch_size, num_objects, output_dim) tensor
        """

        batch_size, num_objects, _, _ = input.shape
        input = input * mask_input.unsqueeze(-1)
        h = rearrange(input, "b o s f -> (b o) (s f)")
        mask_input = rearrange(mask_input, "b o s -> (b o) s")
        if h.shape[-1] == 0:
            h = h.view(batch_size, 0, h.shape[0])
        else:
            h = self._mlp(h)
            h = rearrange(h, "(b o) f -> b o f", b=batch_size, o=num_objects)

        return h


class SequenceDecoderLSTM(nn.Module):
    """A one to many LSTM implementation with one layer.

    Args:
        h_dim : dimension of a hidden layer
    """

    def __init__(self, h_dim: int) -> None:
        super().__init__()
        self._group_objects = Rearrange("b o f -> (b o) f")
        self._lstm = nn.LSTM(input_size=h_dim, hidden_size=h_dim)
        self._out_layer = nn.Linear(in_features=h_dim, out_features=h_dim)
        self.c0 = nn.parameter.Parameter(torch.zeros(1, h_dim))

    def forward(self, input: torch.Tensor, sequence_length: int) -> torch.Tensor:
        """Forward function for MapEncoder

        Args:
            input (torch.Tensor): (batch_size, num_objects, input_dim) tensor
            sequence_length: output sequence length to create
        Returns:
            torch.Tensor: (batch_size, num_objects, output_dim) tensor
        """

        batch_size, num_objects, _ = input.shape

        h = repeat(input, "b o f -> one (b o) f", one=1).contiguous()
        c = repeat(
            self.c0, "one f -> one size f", size=batch_size * num_objects
        ).contiguous()
        seq_h = repeat(h, "one b f -> (one t) b f", t=sequence_length).contiguous()
        h, (_, _) = self._lstm(seq_h, (h, c))
        h = rearrange(h, "t (b o) f -> b o t f", b=batch_size, o=num_objects)
        return self._out_layer(h)


class SequenceDecoderMLP(nn.Module):
    """A one to many MLP implementation.

    Args:
        h_dim : dimension of a hidden layer
        num_layers: number of layers to use in the MLP
        sequence_length: output sequence length to return
        is_mlp_residual: set to True to add a linear transformation of the input to the output of the MLP
    """

    def __init__(
        self, h_dim: int, num_layers: int, sequence_length: int, is_mlp_residual: bool
    ) -> None:
        super().__init__()
        self._mlp = MLP(
            h_dim, h_dim * sequence_length, h_dim, num_layers, is_mlp_residual
        )

    def forward(self, input: torch.Tensor, sequence_length: int) -> torch.Tensor:
        """Forward function for MapEncoder

        Args:
            input (torch.Tensor): (batch_size, num_objects, input_dim) tensor
            sequence_length: output sequence length to create
        Returns:
            torch.Tensor: (batch_size, num_objects, output_dim) tensor
        """

        batch_size, num_objects, _ = input.shape

        h = rearrange(input, "b o f -> (b o) f")
        h = self._mlp(h)
        h = rearrange(
            h, "(b o) (s f) -> b o s f", b=batch_size, o=num_objects, s=sequence_length
        )
        return h


class AttentionBlock(nn.Module):
    """Block performing agent-map cross attention->ReLU(linear)->+residual->layer_norm->agent-agent attention->ReLU(linear)->+residual->layer_norm
    Args:
        hidden_dim: feature dimension
        num_attention_heads: number of attention heads to use
    """

    def __init__(self, hidden_dim: int, num_attention_heads: int):
        super().__init__()
        self._num_attention_heads = num_attention_heads
        self._agent_map_attention = MultiHeadAttention(
            hidden_dim, num_attention_heads, hidden_dim, hidden_dim
        )
        self._lin1 = nn.Linear(hidden_dim, hidden_dim)
        self._layer_norm1 = nn.LayerNorm(hidden_dim)
        self._agent_agent_attention = MultiHeadAttention(
            hidden_dim, num_attention_heads, hidden_dim, hidden_dim
        )
        self._lin2 = nn.Linear(hidden_dim, hidden_dim)
        self._layer_norm2 = nn.LayerNorm(hidden_dim)
        self._activation = nn.ReLU()

    def forward(
        self,
        encoded_agents: torch.Tensor,
        mask_agents: torch.Tensor,
        encoded_absolute_agents: torch.Tensor,
        encoded_map: torch.Tensor,
        mask_map: torch.Tensor,
    ) -> torch.Tensor:
        """Forward function of the block, returning only the output (no attention matrix)
        Args:
            encoded_agents: (batch_size, num_agents, feature_size) tensor of the encoded agent tracks
            mask_agents: (batch_size, num_agents) tensor True if agent track is good False if it is just padding
            encoded_absolute_agents: (batch_size, num_agents, feature_size) tensor of the encoded absolute agent positions
            encoded_map: (batch_size, num_objects, feature_size) tensor of the encoded map object features
            mask_map: (batch_size, num_objects) tensor True if object is good False if it is just padding
        """

        # Check if map_info is available. If not, don't compute cross-attention with it
        if mask_map.any():
            mask_agent_map = torch.einsum("ba,bo->bao", mask_agents, mask_map)
            h, _ = self._agent_map_attention(
                encoded_agents + encoded_absolute_agents,
                encoded_map,
                encoded_map,
                mask=mask_agent_map,
            )
            h = torch.masked_fill(h, torch.logical_not(mask_agents.unsqueeze(-1)), 0)
            h = torch.sigmoid(self._lin1(h))
            h = self._layer_norm1(encoded_agents + h)
        else:
            h = self._layer_norm1(encoded_agents)

        h_res = h.clone()
        agent_agent_mask = torch.einsum("ba,be->bae", mask_agents, mask_agents)
        h = h + encoded_absolute_agents
        h, _ = self._agent_agent_attention(h, h, h, mask=agent_agent_mask)
        h = torch.masked_fill(h, torch.logical_not(mask_agents.unsqueeze(-1)), 0)
        h = self._activation(self._lin2(h))
        h = self._layer_norm2(h_res + h)
        return h


class CG_block(nn.Module):
    """Block performing context gating agent-map
    Args:
        hidden_dim: feature dimension
        dim_expansion: multiplicative factor on the hidden dimension for the global context representation
        num_layers: number of layers to use in the MLP for context encoding
        is_mlp_residual: set to True to add a linear transformation of the input to the output of the MLP
    """

    def __init__(
        self,
        hidden_dim: int,
        dim_expansion: int,
        num_layers: int,
        is_mlp_residual: bool,
    ):
        super().__init__()
        self._agent_map = ContextGating(
            hidden_dim,
            hidden_dim * dim_expansion,
            num_layers=num_layers,
            is_mlp_residual=is_mlp_residual,
        )
        self._lin1 = nn.Linear(hidden_dim, hidden_dim)
        self._layer_norm1 = nn.LayerNorm(hidden_dim)
        self._agent_agent = ContextGating(
            hidden_dim, hidden_dim * dim_expansion, num_layers, is_mlp_residual
        )
        self._lin2 = nn.Linear(hidden_dim, hidden_dim)
        self._activation = nn.ReLU()

    def forward(
        self,
        encoded_agents: torch.Tensor,
        mask_agents: torch.Tensor,
        encoded_absolute_agents: torch.Tensor,
        encoded_map: torch.Tensor,
        mask_map: torch.Tensor,
        global_context: torch.Tensor,
    ) -> torch.Tensor:
        """Forward function of the block, returning the output and global context
        Args:
            encoded_agents: (batch_size, num_agents, feature_size) tensor of the encoded agent tracks
            mask_agents: (batch_size, num_agents) tensor True if agent track is good False if it is just padding
            encoded_absolute_agents: (batch_size, num_agents, feature_size) tensor of the encoded absolute agent positions
            encoded_map: (batch_size, num_objects, feature_size) tensor of the encoded map object features
            mask_map: (batch_size, num_objects) tensor True if object is good False if it is just padding
            global_context: (batch_size, dim_context) tensor representing the global context
        """

        # Check if map_info is available. If not, don't compute cross-interaction with it
        if mask_map.any():
            s, global_context = self._agent_map(
                encoded_agents + encoded_absolute_agents, encoded_map, global_context
            )
            s = s * mask_agents.unsqueeze(-1)
            s = self._activation(self._lin1(s))
            s = self._layer_norm1(encoded_agents + s)
        else:
            s = self._layer_norm1(encoded_agents)

        s = s + encoded_absolute_agents
        s, global_context = self._agent_agent(s, s, global_context)
        s = s * mask_agents.unsqueeze(-1)
        s = self._lin2(s)
        return s, global_context


class HybridBlock(nn.Module):
    """Block performing agent-map cross context_gating->ReLU(linear)->+residual->layer_norm->agent-agent attention->ReLU(linear)->+residual->layer_norm
    Args:
        hidden_dim: feature dimension
        num_attention_heads: number of attention heads to use
        dim_expansion: multiplicative factor on the hidden dimension for the global context representation
        num_layers: number of layers to use in the MLP for context encoding
        is_mlp_residual: set to True to add a linear transformation of the input to the output of the MLP
    """

    def __init__(
        self,
        hidden_dim: int,
        num_attention_heads: int,
        dim_expansion: int,
        num_layers: int,
        is_mlp_residual: bool,
    ):
        super().__init__()
        self._num_attention_heads = num_attention_heads
        self._agent_map_cg = ContextGating(
            hidden_dim,
            hidden_dim * dim_expansion,
            num_layers=num_layers,
            is_mlp_residual=is_mlp_residual,
        )
        self._lin1 = nn.Linear(hidden_dim, hidden_dim)
        self._layer_norm1 = nn.LayerNorm(hidden_dim)
        self._agent_agent_attention = MultiHeadAttention(
            hidden_dim, num_attention_heads, hidden_dim, hidden_dim
        )
        self._lin2 = nn.Linear(hidden_dim, hidden_dim)
        self._layer_norm2 = nn.LayerNorm(hidden_dim)
        self._activation = nn.ReLU()

    def forward(
        self,
        encoded_agents: torch.Tensor,
        mask_agents: torch.Tensor,
        encoded_absolute_agents: torch.Tensor,
        encoded_map: torch.Tensor,
        mask_map: torch.Tensor,
        global_context: torch.Tensor,
    ) -> torch.Tensor:
        """Forward function of the block, returning the output and the context (no attention matrix)
        Args:
            encoded_agents: (batch_size, num_agents, feature_size) tensor of the encoded agent tracks
            mask_agents: (batch_size, num_agents) tensor True if agent track is good False if it is just padding
            encoded_absolute_agents: (batch_size, num_agents, feature_size) tensor of the encoded absolute agent positions
            encoded_map: (batch_size, num_objects, feature_size) tensor of the encoded map object features
            mask_map: (batch_size, num_objects) tensor True if object is good False if it is just padding
            global_context: (batch_size, dim_context) tensor representing the global context
        """

        # Check if map_info is available. If not, don't compute cross-context gating with it
        if mask_map.any():
            # mask_agent_map = torch.logical_not(
            #     torch.einsum("ba,bo->bao", mask_agents, mask_map)
            # )
            h, global_context = self._agent_map_cg(
                encoded_agents + encoded_absolute_agents, encoded_map, global_context
            )
            h = torch.masked_fill(h, torch.logical_not(mask_agents.unsqueeze(-1)), 0)
            h = self._activation(self._lin1(h))
            h = self._layer_norm1(encoded_agents + h)
        else:
            h = self._layer_norm1(encoded_agents)

        h_res = h.clone()
        agent_agent_mask = torch.einsum("ba,be->bae", mask_agents, mask_agents)
        h = h + encoded_absolute_agents
        h, _ = self._agent_agent_attention(h, h, h, mask=agent_agent_mask)
        h = torch.masked_fill(h, torch.logical_not(mask_agents.unsqueeze(-1)), 0)
        h = self._activation(self._lin2(h))
        h = self._layer_norm2(h_res + h)
        return h, global_context


class MCG(nn.Module):
    """Multiple context encoding blocks
    Args:
        hidden_dim: feature dimension
        dim_expansion: multiplicative factor on the hidden dimension for the global context representation
        num_layers: number of layers to use in the MLP for context encoding
        num_blocks: number of successive context encoding blocks to use in the module
        is_mlp_residual: set to True to add a linear transformation of the input to the output of the MLP
    """

    def __init__(
        self,
        hidden_dim: int,
        dim_expansion: int,
        num_layers: int,
        num_blocks: int,
        is_mlp_residual: bool,
    ):
        super().__init__()
        self.initial_global_context = nn.parameter.Parameter(
            torch.ones(1, hidden_dim * dim_expansion)
        )
        list_cg = []
        for i in range(num_blocks):
            list_cg.append(
                CG_block(hidden_dim, dim_expansion, num_layers, is_mlp_residual)
            )
        self.mcg = nn.ModuleList(list_cg)

    def forward(
        self,
        encoded_agents: torch.Tensor,
        mask_agents: torch.Tensor,
        encoded_absolute_agents: torch.Tensor,
        encoded_map: torch.Tensor,
        mask_map: torch.Tensor,
    ) -> torch.Tensor:
        """Forward function of the block, returning only the output (no context)
        Args:
            encoded_agents: (batch_size, num_agents, feature_size) tensor of the encoded agent tracks
            mask_agents: (batch_size, num_agents) tensor True if agent track is good False if it is just padding
            encoded_absolute_agents: (batch_size, num_agents, feature_size) tensor of the encoded absolute agent positions
            encoded_map: (batch_size, num_objects, feature_size) tensor of the encoded map object features
            mask_map: (batch_size, num_objects) tensor True if object is good False if it is just padding
        """
        s = encoded_agents
        c = self.initial_global_context
        sum_s = s
        sum_c = c
        for i, cg in enumerate(self.mcg):
            s_new, c_new = cg(
                s, mask_agents, encoded_absolute_agents, encoded_map, mask_map, c
            )
            sum_s = sum_s + s_new
            sum_c = sum_c + c_new
            s = (sum_s / (i + 2)).clone()
            c = (sum_c / (i + 2)).clone()
        return s


class MAB(nn.Module):
    """Multiple Attention Blocks
    Args:
        hidden_dim: feature dimension
        num_attention_heads: number of attention heads to use
        num_blocks: number of successive blocks to use in the module.
    """

    def __init__(
        self,
        hidden_dim: int,
        num_attention_heads: int,
        num_blocks: int,
    ):
        super().__init__()
        list_attention = []
        for i in range(num_blocks):
            list_attention.append(AttentionBlock(hidden_dim, num_attention_heads))
        self.attention_blocks = nn.ModuleList(list_attention)

    def forward(
        self,
        encoded_agents: torch.Tensor,
        mask_agents: torch.Tensor,
        encoded_absolute_agents: torch.Tensor,
        encoded_map: torch.Tensor,
        mask_map: torch.Tensor,
    ) -> torch.Tensor:
        """Forward function of the block, returning only the output (no attention matrix)
        Args:
            encoded_agents: (batch_size, num_agents, feature_size) tensor of the encoded agent tracks
            mask_agents: (batch_size, num_agents) tensor True if agent track is good False if it is just padding
            encoded_absolute_agents: (batch_size, num_agents, feature_size) tensor of the encoded absolute agent positions
            encoded_map: (batch_size, num_objects, feature_size) tensor of the encoded map object features
            mask_map: (batch_size, num_objects) tensor True if object is good False if it is just padding
        """
        h = encoded_agents
        sum_h = h
        for i, attention in enumerate(self.attention_blocks):
            h_new = attention(
                h, mask_agents, encoded_absolute_agents, encoded_map, mask_map
            )
            sum_h = sum_h + h_new
            h = (sum_h / (i + 2)).clone()
        return h


class MHB(nn.Module):
    """Multiple Hybrid Blocks
    Args:
        hidden_dim: feature dimension
        num_attention_heads: number of attention heads to use
        dim_expansion: multiplicative factor on the hidden dimension for the global context representation
        num_layers: number of layers to use in the MLP for context encoding
        num_blocks: number of successive blocks to use in the module.
        is_mlp_residual: set to True to add a linear transformation of the input to the output of the MLP
    """

    def __init__(
        self,
        hidden_dim: int,
        num_attention_heads: int,
        dim_expansion: int,
        num_layers: int,
        num_blocks: int,
        is_mlp_residual: bool,
    ):
        super().__init__()
        self.initial_global_context = nn.parameter.Parameter(
            torch.ones(1, hidden_dim * dim_expansion)
        )
        list_hb = []
        for i in range(num_blocks):
            list_hb.append(
                HybridBlock(
                    hidden_dim,
                    num_attention_heads,
                    dim_expansion,
                    num_layers,
                    is_mlp_residual,
                )
            )
        self.hybrid_blocks = nn.ModuleList(list_hb)

    def forward(
        self,
        encoded_agents: torch.Tensor,
        mask_agents: torch.Tensor,
        encoded_absolute_agents: torch.Tensor,
        encoded_map: torch.Tensor,
        mask_map: torch.Tensor,
    ) -> torch.Tensor:
        """Forward function of the block, returning only the output (no attention matrix nor context)
        Args:
            encoded_agents: (batch_size, num_agents, feature_size) tensor of the encoded agent tracks
            mask_agents: (batch_size, num_agents) tensor True if agent track is good False if it is just padding
            encoded_absolute_agents: (batch_size, num_agents, feature_size) tensor of the encoded absolute agent positions
            encoded_map: (batch_size, num_objects, feature_size) tensor of the encoded map object features
            mask_map: (batch_size, num_objects) tensor True if object is good False if it is just padding
        """
        sum_h = encoded_agents
        sum_c = self.initial_global_context
        h = encoded_agents
        c = self.initial_global_context
        for i, hb in enumerate(self.hybrid_blocks):
            h_new, c_new = hb(
                h, mask_agents, encoded_absolute_agents, encoded_map, mask_map, c
            )
            sum_h = sum_h + h_new
            sum_c = sum_c + c_new
            h = (sum_h / (i + 2)).clone()
            c = (sum_c / (i + 2)).clone()
        return h