Forward pass through embedding module, transforming sequence of ids to sequence of embeddings. Creates corresponding modality and positional embeddings and adds them to the dict. Args: d (Dict[str, torch.Tensor]): Modality dict, with at least the following keys:
(self, d: Dict[str, torch.Tensor])
| 96 | return set() |
| 97 | |
| 98 | def forward_embed(self, d: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: |
| 99 | """ |
| 100 | Forward pass through embedding module, transforming sequence of ids to sequence of embeddings. |
| 101 | Creates corresponding modality and positional embeddings and adds them to the dict. |
| 102 | |
| 103 | Args: |
| 104 | d (Dict[str, torch.Tensor]): Modality dict, with at least the following keys: |
| 105 | - 'tensor' (torch.Tensor): Token sequence for each batch. Shape (B, L) where B is the batch size and L is the sequence length. |
| 106 | - 'target_mask' (torch.Tensor): Mask for valid tokens in the target sequence (set to 0 for valid tokens and 1 otherwise). Shape (B, L). |
| 107 | |
| 108 | Returns: |
| 109 | Dict[str, torch.Tensor]: Modality dict with added keys: |
| 110 | - 'x' (torch.Tensor): Embedded token sequence. Shape (B, L, D) where D is the embedding dimension. |
| 111 | - 'emb' (torch.Tensor): Sum of positional and modality embeddings for the target sequence. Shape (B, L, D). |
| 112 | - 'ids' (torch.Tensor): Original token sequence from input dict. Shape (B, L). |
| 113 | """ |
| 114 | ids = d['tensor'] |
| 115 | B = ids.shape[0] |
| 116 | assert self.dim_tokens is not None, 'Need to call init(dim_tokens) function first' |
| 117 | |
| 118 | # Map to embedding |
| 119 | x = self.token_emb(ids) |
| 120 | |
| 121 | expanded_pos_emb = repeat(self.pos_emb, "() n d -> b n d", b=B) |
| 122 | |
| 123 | # Target pos encoding |
| 124 | target_mask = d['target_mask'] |
| 125 | target_pos_id = (~target_mask).int().cumsum(dim=1) - 1 |
| 126 | target_pos_id[target_mask] = 0 |
| 127 | # Sometimes target sequence is over max length, it will be truncated in decoder |
| 128 | target_pos_id[target_pos_id >= self.max_length] = 0 |
| 129 | target_pos_emb = torch.gather(expanded_pos_emb, dim=1, index=repeat(target_pos_id, "b n -> b n d", d=expanded_pos_emb.shape[2])) |
| 130 | target_pos_emb[target_mask] = 0 |
| 131 | |
| 132 | x_emb = target_pos_emb + self.mod_emb |
| 133 | |
| 134 | |
| 135 | d['x'] = x |
| 136 | d['emb'] = x_emb |
| 137 | d['ids'] = d['tensor'] |
| 138 | |
| 139 | return d |
| 140 | |
| 141 | def forward_logits(self, x: torch.Tensor) -> torch.Tensor: |
| 142 | """ |
no outgoing calls
no test coverage detected