:param tensor: A 5d tensor of size (batch_size, x, y, z, ch) :return: Positional Encoding Matrix of size (batch_size, x, y, z, ch)
(self, tensor)
| 46 | self.cached_penc = None |
| 47 | |
| 48 | def forward(self, tensor): |
| 49 | """ |
| 50 | :param tensor: A 5d tensor of size (batch_size, x, y, z, ch) |
| 51 | :return: Positional Encoding Matrix of size (batch_size, x, y, z, ch) |
| 52 | """ |
| 53 | if len(tensor.shape) != 5: |
| 54 | raise RuntimeError("The input tensor has to be 5d!") |
| 55 | |
| 56 | if self.cached_penc is not None and self.cached_penc.shape == tensor.shape: |
| 57 | return self.cached_penc |
| 58 | |
| 59 | self.cached_penc = None |
| 60 | batch_size, x, y, z, orig_ch = tensor.shape |
| 61 | pos_x = torch.arange(x, device=tensor.device).type(self.inv_freq.type()) |
| 62 | pos_y = torch.arange(y, device=tensor.device).type(self.inv_freq.type()) |
| 63 | pos_z = torch.arange(z, device=tensor.device).type(self.inv_freq.type()) |
| 64 | sin_inp_x = torch.einsum("i,j->ij", pos_x, self.inv_freq) |
| 65 | sin_inp_y = torch.einsum("i,j->ij", pos_y, self.inv_freq) |
| 66 | sin_inp_z = torch.einsum("i,j->ij", pos_z, self.inv_freq) |
| 67 | emb_x = get_emb(sin_inp_x).unsqueeze(1).unsqueeze(1) |
| 68 | emb_y = get_emb(sin_inp_y).unsqueeze(1) |
| 69 | emb_z = get_emb(sin_inp_z) |
| 70 | emb = torch.zeros((x, y, z, self.channels * 3), device=tensor.device).type( |
| 71 | tensor.type() |
| 72 | ) |
| 73 | emb[:, :, :, : self.channels] = emb_x |
| 74 | emb[:, :, :, self.channels : 2 * self.channels] = emb_y |
| 75 | emb[:, :, :, 2 * self.channels :] = emb_z |
| 76 | |
| 77 | self.cached_penc = emb[None, :, :, :, :orig_ch].repeat(batch_size, 1, 1, 1, 1) |
| 78 | return self.cached_penc |
| 79 | |
| 80 | class PositionEmbeddingSine(nn.Module): |
| 81 | """ |