(self, z)
| 343 | return back.reshape(ishape) |
| 344 | |
| 345 | def forward(self, z): |
| 346 | # reshape z -> (batch, height, width, channel) and flatten |
| 347 | z = z.permute(0, 2, 3, 1).contiguous() |
| 348 | z_flattened = z.view(-1, self.vq_embed_dim) |
| 349 | |
| 350 | # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z |
| 351 | min_encoding_indices = torch.argmin(torch.cdist(z_flattened, self.embedding.weight), dim=1) |
| 352 | |
| 353 | z_q = self.embedding(min_encoding_indices).view(z.shape) |
| 354 | perplexity = None |
| 355 | min_encodings = None |
| 356 | |
| 357 | # compute loss for embedding |
| 358 | if not self.legacy: |
| 359 | loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + torch.mean((z_q - z.detach()) ** 2) |
| 360 | else: |
| 361 | loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean((z_q - z.detach()) ** 2) |
| 362 | |
| 363 | # preserve gradients |
| 364 | z_q = z + (z_q - z).detach() |
| 365 | |
| 366 | # reshape back to match original input shape |
| 367 | z_q = z_q.permute(0, 3, 1, 2).contiguous() |
| 368 | |
| 369 | if self.remap is not None: |
| 370 | min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis |
| 371 | min_encoding_indices = self.remap_to_used(min_encoding_indices) |
| 372 | min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten |
| 373 | |
| 374 | if self.sane_index_shape: |
| 375 | min_encoding_indices = min_encoding_indices.reshape(z_q.shape[0], z_q.shape[2], z_q.shape[3]) |
| 376 | |
| 377 | return z_q, loss, (perplexity, min_encodings, min_encoding_indices) |
| 378 | |
| 379 | def get_codebook_entry(self, indices, shape): |
| 380 | # shape specifying (batch, height, width, channel) |
nothing calls this directly
no test coverage detected