Skip to content

unaiverse.modules.cnu.cnus

A Continual Neural Unit (CNU) is a neuron whose weights depend on the input. It owns m keys and m memories. On every sample it projects the input on the key space, scores the keys by cosine similarity, keeps the delta best ones and returns a blend of their memories with the weights of a softmax over the scores. A layer built on CNUs therefore applies different weights to different regions of the input space and learns a new region mostly by changing the memories of its keys. In the default configuration the keys themselves move towards the inputs that select them without any gradient.

CNUs is the base class of a bank of q such units. The class holds the keys, the memories and the counters and computes the blended weights. It leaves forward undefined: the layers of layers (LinearCNU, Conv2d) subclass it and turn the blended weights into a linear map or a convolution. A developer builds those layers and passes the parameters of this page through their **kwargs. The research context is in Models.

The shapes below use b for the batch size and the names of the constructor: q units, m keys and memories per unit, keys of size d and memories of size u.

CNUs

CNUs(q=1, d=2, m=3, u=4, delta=3, gamma_alpha=0.1, tau_alpha=0.5, tau_mu=100, tau_eta=100, upd_m='WTA', upd_k='ad_hoc_WTA', beta_k=0.001, psi_fn='identity', scramble=False)

Bases: Module

Source code in unaiverse/modules/cnu/cnus.py
def __init__(self, q=1, d=2, m=3, u=4, delta=3,
             gamma_alpha=0.1, tau_alpha=0.5, tau_mu=100, tau_eta=100,
             upd_m="WTA", upd_k="ad_hoc_WTA",
             beta_k=0.001,
             psi_fn="identity",
             scramble=False):
    """
    :param q: number of neurons
    :param d: size of each key
    :param m: number of keys/memory units
    :param u: size of each memory unit
    :param gamma_alpha: softmax temperature (key matching)
    :param tau_alpha: threshold on the attention score of the winning key, to eventually trigger scrambling
    :param tau_mu: number of steps below which a key is considered to be not-used enough
    :param tau_eta: number of steps after which a key is considered old
    :param delta: number of top attention responses to select (top-delta)
    :param upd_m: update memory strategy (None, 'WTA')
    :param upd_k: update key strategy (None, 'ad_hoc_WTA', 'grad_WTA')
    :param beta_k: learning rate for key-update purposes when upd_k is 'ad_hoc_WTA'
    :param psi_fn: function to project the neuron input onto the key space
    :param scramble: triggers the key/memory scrambling routine when upd_k is 'ad_hoc_WTA'
    """

    super(CNUs, self).__init__()
    assert upd_m in (None, 'WTA'), "Unknown value for upd_m, it must be None or 'WTA'"
    assert upd_k in (None, 'ad_hoc_WTA', 'grad_WTA'), "Unknown value for upd_k, it must be " \
                                                      "None, 'ad_hoc_WTA', or 'grad_WTA'"
    assert upd_m is None or (upd_m == 'WTA' and upd_k is not None), \
        "If upd_m is 'WTA', then upd_k must be ad_hoc_WTA or grad_WTA (it cannot be None)"
    self.q = q
    self.d = d
    self.m = m
    self.u = u
    self.gamma_alpha = gamma_alpha
    self.tau_alpha = tau_alpha
    self.tau_mu = tau_mu
    self.tau_eta = tau_eta
    self.scramble = scramble
    self.delta = min(delta, self.m)
    self.upd_m = upd_m
    self.upd_k = upd_k
    self.beta_k = beta_k
    self.psi_fn = psi_fn
    self.debug = False  # Temporarily used
    self.reset_memories = True

    # Creating keys (self.K) and memories (self.M)
    self.M = torch.nn.Parameter(torch.empty((self.q, self.m, self.u), dtype=torch.float32))
    if self.upd_k == "ad_hoc_WTA":
        self.register_buffer('K', torch.zeros((self.q, self.m, self.d)))
    else:
        self.K = torch.nn.Parameter(torch.empty((self.q, self.m, self.d), dtype=torch.float32))

    # Buffers for ad_hoc_WTA key updates (average usefulness register buffer "mu" and age "eta")
    if self.upd_k == "ad_hoc_WTA":
        self.register_buffer('mu', torch.zeros(self.q, m, dtype=torch.float))
        self.register_buffer('eta', torch.ones((self.q, m), dtype=torch.float) * self.tau_eta)
        if self.debug:
            self.register_buffer('key_counter', torch.zeros(self.q, m, dtype=torch.float))
    else:
        self.mu = None
        self.eta = None

    # Scrambling stats
    self.register_buffer('scrambling_count', torch.zeros(self.q, dtype=torch.long))

    # Initializing memories and keys
    self.reset_parameters()

A torch.nn.Module holding q CNUs.

Argument Type Default Meaning
q int 1 The number of units.
d int 2 The size of each key.
m int 3 The number of keys of each unit. Each unit has as many memories as keys.
u int 4 The size of each memory. It is the number of weights that one unit returns.
delta int 3 The number of best keys whose memories are blended. Values above m are capped at m.
gamma_alpha float 0.1 The scale of the scores in the softmax. The scores are multiplied by gamma_alpha / sqrt(d) before the softmax.
tau_alpha float 0.5 Scrambling threshold on the score of the winning key.
tau_mu float 100 A key used fewer than tau_mu times counts as weak for scrambling.
tau_eta float 100 A key that has not won for at least tau_eta samples counts as old for scrambling.
upd_m str or None "WTA" How the memories learn. None lets the gradient reach all the delta blended memories. "WTA" (winner takes all) lets it reach only the memory of the winning key.
upd_k str or None "ad_hoc_WTA" How the keys learn. "ad_hoc_WTA" moves the winning key towards the input in training mode without any gradient. "grad_WTA" and None make the keys a torch.nn.Parameter updated by the optimizer. "grad_WTA" with upd_m="WTA" also stops the gradient through the scores of the keys that did not win.
beta_k float 0.001 The step of the ad hoc key update.
psi_fn str "identity" The mode of psi that projects the input on the key space.
scramble bool False True enables scrambling (below). It has an effect only with upd_k="ad_hoc_WTA".

The constructor raises AssertionError for an unknown upd_m or upd_k and for upd_m="WTA" together with upd_k=None.

Attribute Kind Shape Content
M torch.nn.Parameter [q, m, u] The memories.
K buffer with "ad_hoc_WTA", torch.nn.Parameter otherwise [q, m, d] The keys, each of unit L2 norm.
mu buffer with "ad_hoc_WTA", None otherwise [q, m] How many samples each key has won.
eta buffer with "ad_hoc_WTA", None otherwise [q, m] How many samples have passed since each key last won. It starts at tau_eta.
scrambling_count buffer, torch.long [q] How many scrambling operations each unit performed.
reset_memories bool True lets reset_parameters initialize M. LinearCNU turns it off to apply its own initialization.

Scrambling replaces a key that nobody uses with a new input. On a training step with scramble=True, a unit scrambles when the weakest top-1 score of the batch is below tau_alpha and the unit has at least one weak and old key (mu < tau_mu and eta >= tau_eta). The oldest such key becomes the projected sample with the weakest score, its memory becomes a copy of the memory of the key that the sample had selected before the scrambling, its usage mu restarts from zero and the sample counts as won by the new key. At most one key per unit changes per call.

reset_parameters

reset_parameters()
Source code in unaiverse/modules/cnu/cnus.py
def reset_parameters(self):
    self.__reset_keys()
    if self.reset_memories:
        self.__reset_memories()
    self.__reset_counters()

Draws the keys uniformly in [-1/sqrt(d), 1/sqrt(d)] and normalizes each one to unit L2 norm. When reset_memories is True, it also draws the memories uniformly in [-1/sqrt(u), 1/sqrt(u)]. It then zeroes mu and fills eta with tau_eta. The constructor calls it and subclasses override it to initialize the memories their own way.

compute_weights

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

    # Shortcuts (notice that "self.delta" is called "k" in shortcuts, while "self.delta-1" is called "z")
    q, m, u, d, k = self.q, self.m, self.u, self.d, self.delta
    b = x.shape[0]
    M_qmu = self.M

    # Ensuring keys are normalized (not needed with ad_hoc_WTA updates)
    if self.upd_k != 'ad_hoc_WTA':
        self.__normalize_keys()
    else:
        x = x.detach()  # In ad-hoc WTA, no gradient is propagated to the layers below through key-matching

    # Mapping the input to the key space using the psi function
    x_bd = psi(x, self.psi_fn, key_size=d, normalize=True)

    # Finding the top responses and indices for the attention procedure
    top_responses_bqk, top_indices_bqk = self.__top_k_attention(x_bd)

    # Probabilities
    top_alpha_bqk = torch.softmax((self.gamma_alpha / math.sqrt(d)) * top_responses_bqk, dim=2)

    if self.debug:

        # Getting the top-1 indices for the current mini-batch
        top1_indices_qb = top_indices_bqk[..., 0].t()
        self.key_counter.data.scatter_add_(dim=1,
                                           index=top1_indices_qb,
                                           src=torch.ones_like(top1_indices_qb, dtype=self.key_counter.dtype))

    # Updating keys with the ad-hoc scheme (also refreshing top-stuff: responses, indices, alpha)
    if self.training and self.upd_k == 'ad_hoc_WTA':
        top_responses_bqk, top_indices_bqk, top_alpha_bqk = \
            self.__update_keys_and_counters(x_bd, top_responses_bqk, top_indices_bqk, top_alpha_bqk)

    # Reading memories and blending them
    if self.upd_m is None:

        # Preparing to read memory units and to blend them
        M_exp_bqmu = M_qmu.view(1, q, m, u).expand(b, q, m, u)

        # Getting top memory units
        top_M_bqku = torch.gather(M_exp_bqmu, dim=2,
                                  index=top_indices_bqk.view(b, q, k, 1).expand(b, q, k, u))

        # Mixing memory units by attention scores
        # -> top_alpha_bqk: [b,q,k], that we un-squeeze to [b,q,1,k]
        # -> top_M_bqku: [b,q,k,u]
        # -> W_bqu: matmul([(b,q),1,k], [(b,q),k,u]) = [b,q,1,u] that we squeeze to [b,q,u]
        W_bqu = torch.matmul(top_alpha_bqk.view(b, q, 1, k), top_M_bqku).squeeze(2)

    elif self.upd_m == 'WTA':

        # Preparing to read memory units and to blend them
        M_exp_bqmu = M_qmu.view(1, q, m, u).expand(b, q, m, u)

        # Dealing with top-1 stuff
        top1_M_exp_bq1u = torch.gather(M_exp_bqmu, dim=2,
                                       index=top_indices_bqk[..., 0:1].view(b, q, 1, 1).expand(b, q, 1, u))

        # Mixing memory units by attention scores
        # -> top1_alpha_bqk: [b,q,k], that we select to [b,k,1] un-squeeze to [b,q,1,1]
        # -> top1_M_exp_bq1u: [b,q,1,u]
        # -> W_bqu: [b,q,1,1] * [b,q,1,u] = [b,q,1,u] that we squeeze to [b,q,u]
        top1_W_bqu = (top_alpha_bqk[..., 0:1].view(b, q, 1, 1) * top1_M_exp_bq1u).squeeze(2)

        # Dealing with top-2-and-following stuff
        top2on_M_exp_bqzu = torch.gather(M_exp_bqmu.detach(), dim=2,
                                         index=top_indices_bqk[..., 1:].view(b, q, k-1, 1).expand(b, q, k-1, u))
        top2on_alpha_bqz = top_alpha_bqk[:, :, 1:]
        if self.upd_k == 'grad_WTA':
            top2on_alpha_bqz = top2on_alpha_bqz.detach()

        # Mixing memory units by attention scores
        # -> top2on_alpha_bqz: [b,q,k-1], that we un-squeeze to [b,q,1,k-1]
        # -> top2on_M_exp_bqzu: [b,q,k-1,u]
        # -> W_bqu: matmul([(b,q),1,k-1], [(b,q),k-1,u]) = [b,q,1,u] that we squeeze to [b,q,u]
        top2on_W_bqu = torch.matmul(top2on_alpha_bqz.view(b, q, 1, k-1), top2on_M_exp_bqzu).squeeze(2)

        # Merging top1 and top-2-and-following stuff
        W_bqu = top1_W_bqu + top2on_W_bqu

    else:

        # What is going on?
        raise NotImplementedError

    return W_bqu

Returns the blended memories for a batch x as a tensor of shape [b, q, u]. The subclasses call it from forward. The steps are these:

  1. The method normalizes the keys in place when upd_k is not "ad_hoc_WTA". With "ad_hoc_WTA" it detaches x for the key matching and no gradient reaches the layers below through the scores.
  2. psi(x, psi_fn, key_size=d, normalize=True) maps the batch to [b, d].
  3. The scores are the dot products with all the keys. The method keeps the delta largest scores of each unit in decreasing order and turns them into the weights alpha = softmax(gamma_alpha / sqrt(d) · scores).
  4. In training mode with "ad_hoc_WTA" it runs scrambling (when enabled), adds beta_k · psi(x) to the winning key of every sample, normalizes the keys again and recomputes the scores and alpha. It then resets eta of the winning keys to zero, adds one to their mu and adds b to eta of every key.
  5. It blends the memories of the selected keys with alpha. With upd_m="WTA" the memories of the keys that did not win enter the blend detached from the graph.

The key update of step 4 happens only when the module is in training mode (module.train()). In evaluation mode the keys and the counters do not change.

forward

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

Raises NotImplementedError. CNUs is a base class and every subclass defines its own forward.

reset_counter

reset_counter()
Source code in unaiverse/modules/cnu/cnus.py
def reset_counter(self):
    if self.debug:
        self.key_counter.data = torch.zeros_like(self.key_counter)

Zeroes the debugging counter of the winning keys when the attribute debug is True and does nothing otherwise. The counter exists only when debug is True at construction. Because the constructor always starts with debug = False, the method has no effect in the current version.