unaiverse.modules.cnu.cnus
What this module does 🔴
Implements the core Conditional Neural Units (CNUs) module: a key-addressable memory bank with top-k attention, key normalization, and scrambling logic for dynamically generating layer weights.
cnus
¶
█████ █████ ██████ █████ █████ █████ █████ ██████████ ███████████ █████████ ██████████
░░███ ░░███ ░░██████ ░░███ ░░███ ░░███ ░░███ ░░███░░░░░█░░███░░░░░███ ███░░░░░███░░███░░░░░█
░███ ░███ ░███░███ ░███ ██████ ░███ ░███ ░███ ░███ █ ░ ░███ ░███ ░███ ░░░ ░███ █ ░
░███ ░███ ░███░░███░███ ░░░░░███ ░███ ░███ ░███ ░██████ ░██████████ ░░█████████ ░██████
░███ ░███ ░███ ░░██████ ███████ ░███ ░░███ ███ ░███░░█ ░███░░░░░███ ░░░░░░░░███ ░███░░█
░███ ░███ ░███ ░░█████ ███░░███ ░███ ░░░█████░ ░███ ░ █ ░███ ░███ ███ ░███ ░███ ░ █
░░████████ █████ ░░█████░░████████ █████ ░░███ ██████████ █████ █████░░█████████ ██████████
░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░ ░░░░░ ░░░ ░░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░░ ░░░░░░░░░░
A Collectionless AI Project (https://collectionless.ai)
Registration/Login: https://unaiverse.io
Code Repositories: https://github.com/collectionlessai/
Main Developers: Stefano Melacci (Project Leader), Christian Di Maio, Tommaso Guidi
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
Contextual Neural Units: an attention-based key-value memory module for PyTorch.
Each CNUs layer holds q neurons. Every neuron maintains a bank of m
learnable keys (each of size d) and m corresponding memory units (each of
size u). At inference time the module maps an input vector to the key space via a
configurable projection function psi, computes dot-product attention scores
against all keys, selects the top-delta winning keys, and blends the associated
memory units by their softmax attention weights to produce a u-dimensional output
per neuron.
Two complementary learning regimes are supported:
upd_k="ad_hoc_WTA"-- keys are updated online without backpropagation through the key-matching step: the winning key is nudged toward the current input bybeta_k. An optional scrambling mechanism (scramble=True) replaces under-used, stale keys with fresh inputs sampled from the current mini-batch.upd_k="grad_WTA"/upd_k=None-- keys are standardnn.Parametertensors trained by gradient descent through the full module.
Memory units (self.M) are always nn.Parameter tensors optimised by the
surrounding optimizer, regardless of the key-update strategy.
Attributes:
| Name | Type | Description |
|---|---|---|
q |
Number of neurons. |
|
d |
Dimensionality of each key vector. |
|
m |
Number of key-memory pairs per neuron. |
|
u |
Dimensionality of each memory unit (and of the per-neuron output). |
|
delta |
Number of top attention responses to select (top- |
|
gamma_alpha |
Softmax temperature applied to the top- |
|
tau_alpha |
Attention-score threshold below which scrambling may be triggered. |
|
tau_mu |
Usage count threshold; keys used fewer than |
|
tau_eta |
Age threshold; keys whose age exceeds |
|
scramble |
Whether the key/memory scrambling routine is active. |
|
upd_m |
Memory update strategy ( |
|
upd_k |
Key update strategy ( |
|
beta_k |
Learning rate used by the |
|
psi_fn |
Name of the projection function used to map inputs to the key space. |
|
M |
Memory tensor of shape |
|
K |
Key tensor of shape |
|
mu |
Per-neuron usage counters of shape |
|
eta |
Per-neuron age counters of shape |
|
scrambling_count |
Number of scrambling operations performed per neuron,
shape |
|
reset_memories |
If |
Examples:
Create a CNUs layer with 2 neurons, 8 keys, and 16-dimensional memories,
using the default ad-hoc WTA key-update strategy:
>>> import torch
>>> from unaiverse.modules.cnu.cnus import CNUs
>>> layer = CNUs(q=2, d=4, m=8, u=16, 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=True)
>>> layer
CNUs()
Initialize the CNUs layer and allocate all keys, memories, and counters.
Parameters are validated with assertions before any tensor allocation takes
place. Keys are initialised uniformly in [-1/sqrt(d), 1/sqrt(d)] and then
L2-normalized along the key dimension. Memories are initialised uniformly in
[-1/sqrt(u), 1/sqrt(u)]. Usage counters mu are zeroed and age counters
eta are set to tau_eta so that all keys are immediately considered
available for scrambling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
Number of neurons. Defaults to 1. |
1
|
|
d
|
Dimensionality of each key vector. Defaults to 2. |
2
|
|
m
|
Number of key-memory pairs per neuron. Defaults to 3. |
3
|
|
u
|
Dimensionality of each memory unit (and of the per-neuron output). Defaults to 4. |
4
|
|
delta
|
Number of top-scoring keys to select at each forward step.
Clamped to |
3
|
|
gamma_alpha
|
Softmax temperature applied to the top- |
0.1
|
|
tau_alpha
|
Threshold on the top-1 attention response below which
scrambling is considered (requires |
0.5
|
|
tau_mu
|
Usage count threshold. Keys whose cumulative usage count is below this value are deemed under-used. Defaults to 100. |
100
|
|
tau_eta
|
Age threshold in steps. Keys older than this value are deemed stale. Defaults to 100. |
100
|
|
upd_m
|
Memory update strategy. Must be |
'WTA'
|
|
upd_k
|
Key update strategy. Must be |
'ad_hoc_WTA'
|
|
beta_k
|
Learning rate for the |
0.001
|
|
psi_fn
|
Name of the function (from |
'identity'
|
|
scramble
|
Whether to enable the key/memory scrambling routine. When
|
False
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If |
AssertionError
|
If |
AssertionError
|
If |
Examples:
>>> import torch
>>> from unaiverse.modules.cnu.cnus import CNUs
>>> layer = CNUs(q=1, d=4, m=8, u=16)
>>> x = torch.randn(32, 4) # batch of 32, input dim 4
Source code in unaiverse/modules/cnu/cnus.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
reset_parameters
¶
Reset all learnable parameters and internal counters to their initial state.
Keys are re-initialized uniformly in [-1/sqrt(d), 1/sqrt(d)] and
L2-normalized. Memories are re-initialized uniformly in
[-1/sqrt(u), 1/sqrt(u)] only when reset_memories is True. Usage
counters mu and age counters eta are reset to their construction-time
defaults (zero and tau_eta respectively).
Note
Memory re-initialization is conditional on self.reset_memories so that
callers can preserve learned memories while refreshing only keys and
counters.
Source code in unaiverse/modules/cnu/cnus.py
compute_weights
¶
Compute the attention-weighted memory blend for each neuron given an input batch.
The input x is first projected to the key space by psi, then
dot-product attention is computed against all m keys of each neuron. The
top-delta responses are selected and passed through a scaled softmax to
obtain attention weights alpha. The corresponding memory units are blended
by these weights to produce the per-neuron output.
When upd_k="ad_hoc_WTA" the input is detached from the computational graph
before key-matching, so no gradient flows to layers below through this step.
When training with upd_k="ad_hoc_WTA", the keys and their counters are
updated in-place before the final memory blend is computed.
When upd_m="WTA", the top-1 memory is scaled by its own attention weight
(with a live gradient) and the remaining top-(delta-1) memories are blended
from a detached copy of M. When upd_m=None all memories are blended
with live gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input tensor of shape |
required |
Returns:
| Type | Description |
|---|---|
|
A tensor of shape |
|
|
is the attention-weighted blend of the |
|
|
neuron |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
Examples:
>>> import torch
>>> from unaiverse.modules.cnu.cnus import CNUs
>>> layer = CNUs(q=2, d=4, m=8, u=16, upd_m=None, upd_k=None)
>>> x = torch.randn(32, 4)
>>> W = layer.compute_weights(x) # shape: (32, 2, 16)
Source code in unaiverse/modules/cnu/cnus.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
forward
¶
Perform the forward pass.
CNUs is an abstract base class. Concrete subclasses must override this
method to define how the attention-weighted memory blends produced by
compute_weights are combined into the final module output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input tensor passed through the module. |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, because |
Source code in unaiverse/modules/cnu/cnus.py
reset_counter
¶
Reset the debug key-usage counter to zero.
When self.debug is True, key_counter accumulates how many times
each key has been selected as the top-1 winner across forward passes. This
method zeros that buffer so counts can be measured over a fresh window.
Note
This method has no effect when self.debug is False.