Skip to content

unaiverse.modules.cnu.psi

A layer of Continual Neural Units (CNUs) compares its input with a set of keys before it picks the memories that become its weights (see cnus). The keys live in a space of fixed size key_size. The input of a layer, on the other hand, can be a vector of any length or a batch of images. This module holds the projection ψ that maps the input to the key space. CNUs.compute_weights calls psi on every forward pass with normalize=True. A developer calls these functions directly only to check that a given input shape reaches a given key_size before building a layer.

import torch
from unaiverse.modules.cnu.psi import psi

x = torch.randn(8, 3, 32, 32)                     # A batch of 8 RGB images
k = psi(x, "resize2d", key_size=75)               # Shape [8, 75], each row of unit L2 norm

psi

psi(x, mode, key_size, normalize=True)
Source code in unaiverse/modules/cnu/psi.py
def psi(x, mode, key_size, normalize=True):
    if mode == "identity":
        o = x.flatten(start_dim=1)
    elif mode == "sign":
        o = torch.sign(x.flatten(start_dim=1))
    elif mode == "resize1d":
        o = resize1d(x, key_size)
    elif mode == "resize2d":
        o = resize2d(x, key_size)
    elif mode == "resize2d_sign":
        o = torch.sign(resize2d(x, key_size))
    else:
        raise NotImplementedError
    assert o.shape[1] == key_size, \
        "The selected psi function (" \
        + str(mode) + ") cannot map data to the target " \
                      "key_size (data_size: " + str(o.shape[1]) + ", key_size: " + str(key_size) + ")"
    if normalize:
        o = F.normalize(o, p=2.0, dim=1, eps=1e-12, out=None)
    return o

Maps a batch x to a matrix of shape [b, key_size] with the projection named by mode and returns it.

Argument Type Default Meaning
x torch.Tensor required The batch whose first dimension is the batch size b. The modes resize1d and resize2d need the shapes [b, n] and [b, c, h, w] respectively.
mode str required The projection, one of the five values below.
key_size int required The number of columns of the result.
normalize bool True True divides every row by its L2 norm (torch.nn.functional.normalize with eps=1e-12).
mode Result before normalization
"identity" x.flatten(start_dim=1). The flattened input must already have key_size elements.
"sign" torch.sign of the flattened input. The flattened input must already have key_size elements.
"resize1d" The output of resize1d(x, key_size).
"resize2d" The output of resize2d(x, key_size).
"resize2d_sign" torch.sign of the output of resize2d(x, key_size).

Any other mode raises NotImplementedError. The default psi_fn="reduce2d" of layers.Conv2d is such an unknown mode. The function checks the width of the result with an assert and raises AssertionError with the message The selected psi function (...) cannot map data to the target key_size (data_size: ..., key_size: ...) when the width differs from key_size.

resize1d

resize1d(I, key_size)
Source code in unaiverse/modules/cnu/psi.py
def resize1d(I, key_size):
    if I.shape[1] == key_size:
        pass
    else:
        I = F.interpolate(I.unsqueeze(1), size=key_size, mode="linear").squeeze(1)
    return I

Resizes a batch of vectors I of shape [b, n] to shape [b, key_size] with linear interpolation (torch.nn.functional.interpolate with mode="linear"). An input that already has key_size columns comes back unchanged as the same tensor object. The function does not normalize.

resize2d

resize2d(I, key_size)
Source code in unaiverse/modules/cnu/psi.py
def resize2d(I, key_size):
    b, c, h, w = I.shape
    assert c > 0
    spatial_key_size = key_size // c
    ratio = float(spatial_key_size) / float(w * h)
    w = max(1, int(round(math.sqrt(ratio) * w)))
    h = spatial_key_size // w
    remainder = key_size - (c * h * w)
    o = F.interpolate(I, size=(h, w), mode="bilinear").flatten(start_dim=1)
    if h * w < spatial_key_size:
        o = torch.cat([o, torch.zeros((b, remainder), device=o.device, dtype=o.dtype)], dim=1)
    return o

Resizes a batch of images I of shape [b, c, h, w] with bilinear interpolation and flattens the result to [b, c · h' · w']. The target grid keeps the aspect ratio of the input as far as the integer sizes allow:

  1. The number of pixels per channel is spatial_key_size = key_size // c.
  2. The grid has width w' = max(1, round(sqrt(spatial_key_size / (w · h)) · w)) and height h' = spatial_key_size // w'.
  3. The function appends key_size - c · h' · w' zero columns when h' · w' is smaller than spatial_key_size.

The zero padding covers the pixels lost by the integer division of step 2 but never the remainder of step 1. A key_size that is not a multiple of c combined with an exact grid (h' · w' == spatial_key_size) therefore gives a result narrower than key_size and psi fails on its assert. For example, psi(torch.randn(2, 3, 8, 8), "resize2d", 50) raises AssertionError (48 columns against 50). A key_size that is a multiple of the number of channels avoids the problem. The function raises AssertionError for an input with zero channels.