Module bioiain.machine.layers

Classes

class Codebook (n_tokens=20, latent_dims=2, commitment=0.25)
Expand source code
class Codebook(nn.Module):
    def __init__(self, n_tokens=20, latent_dims=2, commitment=0.25):
        super().__init__()
        log(1, "Initialising codebook...")
        self.commitment = commitment
        self.n_tokens = n_tokens
        self.latent_dims = latent_dims
        self.codebook = nn.Embedding(n_tokens, latent_dims)
        self.codebook.weight.data.uniform_(-1/self.n_tokens, 1/self.n_tokens)
        self.MSE = nn.MSELoss()
        self.last_loss = None
        self.last_index = None

        log(2,"Codebook:", self.codebook)
        #print("weight:")
        #print(self.codebook.weight)



    def forward(self, x):
        #print("forward")
        #print(x)
        # Calculate distances between z and the codebook embeddings |a-b|²
        distances = (
            torch.sum(x ** 2, dim=-1, keepdim=True)                 # a²
            + torch.sum(self.codebook.weight.t() ** 2, dim=0, keepdim=True)  # b²
            - 2 * torch.matmul(x, self.codebook.weight.t())        # -2ab
        )
        #print(distances)
        closest_index = torch.argmin(distances, dim=1)
        closest_tensor = self.codebook(closest_index)

        #print("closest:", closest_index, "distance:", distances[0][closest_index])
        #print(closest_tensor)
        loss = self.MSE(closest_tensor, x.detach()) + self.commitment * self.MSE(closest_tensor.detach(), x)

        closest_tensor = x + (closest_tensor - x).detach()
        self.last_loss = loss
        #print(closest_index)
        self.last_index = closest_index

        return closest_tensor

Base class for all neural network modules.

Your models should also subclass this class.

Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes::

import torch.nn as nn
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:to, etc.

Note

As per the example above, an __init__() call to the parent class must be made before assignment on the child.

:ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Ancestors

  • torch.nn.modules.module.Module

Methods

def forward(self, x) ‑> Callable[..., typing.Any]
Expand source code
def forward(self, x):
    #print("forward")
    #print(x)
    # Calculate distances between z and the codebook embeddings |a-b|²
    distances = (
        torch.sum(x ** 2, dim=-1, keepdim=True)                 # a²
        + torch.sum(self.codebook.weight.t() ** 2, dim=0, keepdim=True)  # b²
        - 2 * torch.matmul(x, self.codebook.weight.t())        # -2ab
    )
    #print(distances)
    closest_index = torch.argmin(distances, dim=1)
    closest_tensor = self.codebook(closest_index)

    #print("closest:", closest_index, "distance:", distances[0][closest_index])
    #print(closest_tensor)
    loss = self.MSE(closest_tensor, x.detach()) + self.commitment * self.MSE(closest_tensor.detach(), x)

    closest_tensor = x + (closest_tensor - x).detach()
    self.last_loss = loss
    #print(closest_index)
    self.last_index = closest_index

    return closest_tensor

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the :class:Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.