Skip to content

unaiverse.modules.cnu.layers

The two layers of this module behave as torch.nn.Linear and torch.nn.Conv2d from the outside. Inside, their weights are not fixed parameters: for every sample of the batch, a bank of Continual Neural Units (see cnus) compares the input with its keys and blends the memories attached to the best keys into the weight matrix of that sample. Different regions of the input space therefore use different weights. This lets the layer learn a new region without overwriting what it learned on another. The ready-made processors CNNCNU, SingleLayerCNU and ResNetCNU of networks and the CTE and CTBE networks with cnu_memories > 0 use LinearCNU (see Models).

import torch
from unaiverse.modules.cnu.layers import LinearCNU

layer = LinearCNU(16, 4, key_mem_units=8)       # 8 keys, 8 memories of 4 x 17 values each
y = layer(torch.randn(32, 16))                  # y has shape [32, 4]

Both layers forward the extra keyword arguments to CNUs (delta, gamma_alpha, tau_alpha, tau_mu, tau_eta, upd_m, upd_k, beta_k, scramble). The layer computes q, d, m and u by itself and raises AssertionError when one of them is passed.

LinearCNU

LinearCNU(in_features, out_features, bias=True, device=None, shared_keys=True, key_mem_units=2, psi_fn='identity', key_size=None, **kwargs)

Bases: CNUs

Source code in unaiverse/modules/cnu/layers.py
def __init__(self, in_features, out_features, bias=True, device=None,
             shared_keys=True, key_mem_units=2, psi_fn='identity', key_size=None, **kwargs):
    self.in_features = in_features
    self.out_features = out_features
    self.bias = bias
    self.shared_keys = shared_keys

    if kwargs is not None:
        assert 'q' not in kwargs, "The number of CNUs is automatically determined, do not set argument 'q'"
        assert 'd' not in kwargs, "The size of each key can be specified with argument 'key_size', " \
                                  "do not set argument 'd'"
        assert 'm' not in kwargs, "The number of keys and memory units can be specified with argument " \
                                  "'key_mem_units', do not set argument 'm'"
        assert 'u' not in kwargs, "Size of each memory unit is automatically determined, do not set argument 'u'"

    # Number of keys/memory units
    kwargs['m'] = key_mem_units

    # Size of each key
    kwargs['d'] = in_features if key_size is None else key_size

    # Function used to compare input against keys
    kwargs['psi_fn'] = psi_fn

    if not shared_keys:

        # Each neuron is an independent cnu, with its own keys and its own memory units
        kwargs['q'] = self.out_features
        kwargs['u'] = self.in_features + (1 if self.bias else 0)
    else:

        # All the CNUs of the layer share the same keys, thus their memory units are concatenated
        kwargs['q'] = 1
        kwargs['u'] = self.out_features * (self.in_features + (1 if self.bias else 0))

    # Creating neurons
    super(LinearCNU, self).__init__(**kwargs)

    # Switching device
    if device is not None:
        self.to(device)

    # Clearing
    if not self.bias:
        self.bias = None

A fully connected layer whose weight matrix and bias come from a bank of CNUs.

Argument Type Default Meaning
in_features int required The size of each input sample.
out_features int required The size of each output sample.
bias bool True True adds a learned bias that the layer reads from the memories like the weights. With False the attribute bias of the layer becomes None after construction.
device torch.device or str or None None The device of the layer after construction. None leaves it on the CPU.
shared_keys bool True True builds one unit (q=1) whose keys select the weights of all the output neurons together. Each memory then holds out_features · (in_features + bias) values. False builds one unit per output neuron (q=out_features), each with its own keys and memories of in_features + bias values.
key_mem_units int 2 The number of keys and memories of each unit (m).
psi_fn str "identity" The projection of the input on the key space (see psi). "identity" needs key_size == in_features.
key_size int or None None The size of each key (d). None uses in_features.
**kwargs Forwarded to CNUs.

The default delta=3 of CNUs is capped at key_mem_units. With the defaults of this class each sample blends the two memories of its unit.

forward

forward(x)
Source code in unaiverse/modules/cnu/layers.py
def forward(self, x):

    # Getting weights
    W = self.compute_weights(x)

    # Ensuring the shape is right (needed when neurons share the same keys)
    W = W.reshape((x.shape[0], self.out_features, -1))  # [b,q,1] => [b, out_features,(in_features + 1-if-bias)]

    # Splitting into weights and biases
    if self.bias:
        weights = W[:, :, :-1]  # [b,out_features,in_features]
        bias = W[:, :, -1]  # [b,out_features]
    else:
        weights = W  # [b,out_features,in_features]
        bias = None

    # Batched linear projection: matmul([b,out_features,in_features], [b,in_features,1]) = [b,out_features,1]
    # that we squeeze to [b,out_features]
    o = torch.matmul(weights, x.unsqueeze(2)).squeeze(2)  # [b,out_features]
    if bias is not None:
        o += bias
    return o

Takes x of shape [b, in_features] and returns a tensor of shape [b, out_features]. The method asks compute_weights for one weight matrix of shape [out_features, in_features] (plus a bias vector when bias is on) per sample and applies it with a batched matrix product. In training mode with the default upd_k="ad_hoc_WTA" the call also moves the winning keys towards the input (see CNUs.compute_weights).

reset_parameters

reset_parameters()
Source code in unaiverse/modules/cnu/layers.py
def reset_parameters(self):
    self.reset_memories = False
    super().reset_parameters()

    # We ensure that memories M are initialized as Pytorch does for the classic linear layer
    q = self.M.shape[0]
    m = self.M.shape[1]
    self.M.data.zero_()  # Ensures we don’t keep old values

    for j in range(q):
        for i in range(m):

            # Initialize weight and bias separately for each memory
            weight = torch.empty(self.out_features if self.shared_keys else 1, self.in_features)
            torch.nn.init.kaiming_uniform_(weight, a=math.sqrt(5))  # Computes fan in

            if self.bias:
                bias = torch.empty(self.out_features if self.shared_keys else 1)
                bound = 1 / math.sqrt(self.in_features)
                torch.nn.init.uniform_(bias, -bound, bound)
                weight_bias = torch.cat([weight, bias.unsqueeze(1)], dim=1)
            else:
                weight_bias = weight

            # Store the flattened weight_bias into self.M[i]
            self.M.data[j, i, :] = weight_bias.flatten()

Initializes the keys as CNUs.reset_parameters does and the memories as PyTorch initializes torch.nn.Linear: every memory receives its own weight matrix drawn with kaiming_uniform_(a=sqrt(5)) and its own bias drawn uniformly in [-1/sqrt(in_features), 1/sqrt(in_features)]. The constructor of CNUs calls it. A later call draws all keys and memories again and resets the usage counters.

Conv2d

Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, padding_mode='zeros', dilation=1, groups=1, bias=True, device=None, shared_keys=True, key_mem_units=2, psi_fn='reduce2d', key_size=None, **kwargs)

Bases: CNUs

Source code in unaiverse/modules/cnu/layers.py
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, padding_mode='zeros',
             dilation=1, groups=1, bias=True, device=None,
             shared_keys=True, key_mem_units=2, psi_fn='reduce2d', key_size=None, **kwargs):
    self.in_channels = in_channels
    self.out_channels = out_channels
    self.kernel_size = kernel_size if isinstance(kernel_size, Iterable) else (kernel_size, kernel_size)
    self.stride = stride if isinstance(stride, Iterable) else (stride, stride)
    self.padding = padding
    self.padding_mode = padding_mode
    self.dilation = dilation if isinstance(dilation, Iterable) else (dilation, dilation)
    self.groups = groups
    self.bias = bias
    self.in_features = math.prod(self.kernel_size) * self.in_channels

    valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'}
    if padding_mode not in valid_padding_modes:
        raise ValueError("padding_mode must be one of {}, but got padding_mode='{}'".format(valid_padding_modes,
                                                                                            padding_mode))
    if isinstance(padding, str):
        self.__reversed_padding_repeated_twice = [0, 0] * len(self.kernel_size)
        if padding == 'same':
            for d, k, i in zip(self.dilation, self.kernel_size,
                               range(len(self.kernel_size) - 1, -1, -1)):
                total_padding = d * (k - 1)
                left_pad = total_padding // 2
                self.__reversed_padding_repeated_twice[2 * i] = left_pad
                self.__reversed_padding_repeated_twice[2 * i + 1] = (total_padding - left_pad)
    else:
        self.padding = padding if isinstance(padding, Iterable) else (padding, padding)
        self.__reversed_padding_repeated_twice = tuple(x for x in reversed(self.padding) for _ in range(2))

    if kwargs is not None:
        assert 'q' not in kwargs, "The number of CNUs is automatically determined, do not set argument 'q'"
        assert 'd' not in kwargs, "The size of each key can be specified with argument 'key_size', " \
                                  "do not set argument 'd'"
        assert 'm' not in kwargs, "The number of keys and memory units can be specified with argument " \
                                  "'key_mem_units', do not set argument 'm'"
        assert 'u' not in kwargs, "Size of each memory unit is automatically determined, do not set argument 'u'"

    # Number of keys/memory units
    kwargs['m'] = key_mem_units

    # Size of each key
    if key_size is not None:
        if isinstance(key_size, (tuple, list)):
            key_size = math.prod(key_size)
        kwargs['d'] = key_size
    else:
        kwargs['d'] = (5 * 5 * self.in_channels)

    # Function used to compare input against keys
    kwargs['psi_fn'] = psi_fn

    if not shared_keys:

        # Each neuron is an independent cnu, with its own keys and its own memory units
        kwargs['q'] = self.out_channels
        kwargs['u'] = self.in_features + (1 if self.bias else 0)
    else:

        # All the CNUs of the layer share the same keys, thus their memory units are concatenated
        kwargs['q'] = 1
        kwargs['u'] = self.out_channels * (self.in_features + (1 if self.bias else 0))

    # Creating neurons
    super(Conv2d, self).__init__(**kwargs)

    # Switching device
    if device is not None:
        self.to(device)

A 2D convolution that reads one set of kernels and one bias per sample from a bank of CNUs.

The default psi_fn fails

The default psi_fn="reduce2d" is not a projection that psi knows. The constructor accepts it and the first forward call raises NotImplementedError. Pass psi_fn="resize2d" (or "resize2d_sign") explicitly.

Argument Type Default Meaning
in_channels int required The channels of the input images.
out_channels int required The channels of the output. Each output channel has its own kernel.
kernel_size int or tuple required The kernel size. An integer k means (k, k).
stride int or tuple 1 As in torch.nn.Conv2d.
padding int, tuple or str 0 As in torch.nn.Conv2d. The strings "same" and "valid" work too.
padding_mode str "zeros" One of "zeros", "reflect", "replicate" and "circular". Any other value raises ValueError.
dilation int or tuple 1 As in torch.nn.Conv2d.
groups int 1 Only 1 works. With groups > 1 the kernels keep all in_channels and forward raises RuntimeError from torch.nn.functional.conv2d.
bias bool True True reads a bias per output channel from the memories.
device torch.device or str or None None The device of the layer after construction.
shared_keys bool True As in LinearCNU once out_channels replaces out_features and kernel_h · kernel_w · in_channels replaces in_features.
key_mem_units int 2 The number of keys and memories of each unit.
psi_fn str "reduce2d" The projection of the input images on the key space. See the warning above.
key_size int, tuple, list or None None The size of each key. A tuple or list stands for the product of its elements. None uses 5 · 5 · in_channels.
**kwargs Forwarded to CNUs.

The attribute in_features holds kernel_h · kernel_w · in_channels. The memories keep the uniform initialization of CNUs in [-1/sqrt(u), 1/sqrt(u)] because this class does not override reset_parameters.

import torch
from unaiverse.modules.cnu.layers import Conv2d

conv = Conv2d(3, 8, 3, padding="same", psi_fn="resize2d")
y = conv(torch.randn(2, 3, 10, 10))             # y has shape [2, 8, 10, 10]

forward

forward(x)
Source code in unaiverse/modules/cnu/layers.py
def forward(self, x):

    # Shortcuts
    b, c, h, w = x.shape

    # Getting weights
    W = self.compute_weights(x)

    # Ensuring the shape is right (needed when neurons share the same keys)
    W = W.reshape((b, self.out_channels, -1))  # [b,q,1] => [b,out_channels,(in_features + 1-if-bias)]

    # Splitting into weights and biases
    if self.bias:
        weights = W[:, :, :-1]  # [b,out_channels,in_features]
        bias = W[:, :, -1]  # [b,out_channels]
    else:
        weights = W  # [b,out_channels,in_features]
        bias = None

    # Creating tensor with convolutional filters
    kernels = self.__mat2filters(weights)

    # Stack all images along the channels
    x = x.view(1, b * c, h, w)

    # Convolution
    if self.padding_mode != 'zeros':
        x = F.conv2d(F.pad(x, self.__reversed_padding_repeated_twice, mode=self.padding_mode),
                     kernels, bias.flatten() if bias is not None else None, self.stride,
                     (0, 0), self.dilation, groups=(b * self.groups))
    else:
        x = F.conv2d(x, kernels, bias.flatten() if bias is not None else None, self.stride,
                     self.padding, self.dilation, groups=(b * self.groups))

    return x.view(b, self.out_channels, x.shape[2], x.shape[3])

Takes x of shape [b, in_channels, h, w] and returns [b, out_channels, h_out, w_out] with the output size of torch.nn.Conv2d. The method computes the kernels of each sample with compute_weights, stacks the batch along the channels and runs a single grouped convolution with b groups. A padding_mode other than "zeros" pads the input with torch.nn.functional.pad before the convolution.