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
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
¶
Source code in unaiverse/modules/cnu/layers.py
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
¶
Source code in unaiverse/modules/cnu/layers.py
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
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
¶
Source code in unaiverse/modules/cnu/layers.py
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.