(self, z: torch.FloatTensor)
| 715 | return back.reshape(ishape) |
| 716 | |
| 717 | def forward(self, z: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, Tuple]: |
| 718 | # reshape z -> (batch, height, width, channel) and flatten |
| 719 | z = z.permute(0, 2, 3, 1).contiguous() |
| 720 | z_flattened = z.view(-1, self.vq_embed_dim) |
| 721 | |
| 722 | # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z |
| 723 | min_encoding_indices = torch.argmin(torch.cdist(z_flattened, self.embedding.weight), dim=1) |
| 724 | |
| 725 | z_q = self.embedding(min_encoding_indices).view(z.shape) |
| 726 | perplexity = None |
| 727 | min_encodings = None |
| 728 | |
| 729 | # compute loss for embedding |
| 730 | if not self.legacy: |
| 731 | loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + torch.mean((z_q - z.detach()) ** 2) |
| 732 | else: |
| 733 | loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean((z_q - z.detach()) ** 2) |
| 734 | |
| 735 | # preserve gradients |
| 736 | z_q: torch.FloatTensor = z + (z_q - z).detach() |
| 737 | |
| 738 | # reshape back to match original input shape |
| 739 | z_q = z_q.permute(0, 3, 1, 2).contiguous() |
| 740 | |
| 741 | if self.remap is not None: |
| 742 | min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis |
| 743 | min_encoding_indices = self.remap_to_used(min_encoding_indices) |
| 744 | min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten |
| 745 | |
| 746 | if self.sane_index_shape: |
| 747 | min_encoding_indices = min_encoding_indices.reshape(z_q.shape[0], z_q.shape[2], z_q.shape[3]) |
| 748 | |
| 749 | return z_q, loss, (perplexity, min_encodings, min_encoding_indices) |
| 750 | |
| 751 | def get_codebook_entry(self, indices: torch.LongTensor, shape: Tuple[int, ...]) -> torch.FloatTensor: |
| 752 | # shape specifying (batch, height, width, channel) |
nothing calls this directly
no test coverage detected