Nested Learning Experiment: Background & Breakthrough


1. Background

1.1 The Stability-Plasticity Dilemma in Continual Learning

A central challenge in machine learning is building models that can learn sequentially, acquiring new knowledge without erasing what they already know. This tension is classically framed as the stability-plasticity dilemma: a model must be *plastic* enough to absorb new information, yet *stable* enough to retain prior knowledge under gradient updates from new data.

Standard neural networks trained with gradient descent fail dramatically at this. When a model trained on one task is subsequently trained on a new task, its parameters are updated to minimize loss on the new data, with no mechanism to protect what was previously learned. The result is catastrophic forgetting: near-complete erasure of the original task's performance. Importantly, this is not a matter of insufficient capacity. Rather, it is a structural consequence of gradient-based learning operating over a single, uniform update frequency.

Momentum-based optimizers like Adam partially mitigate this by accumulating a running average of past gradients, but this memory is shallow. With a typical decay term of $\beta = 0.9$, the last $\sim$43 gradients account for 99% of the momentum's cumulative influence, meaning that knowledge from earlier in training contributes less than 1% to the optimizer's current state. As soon as the gradient direction shifts under new task data, the optimizer's memory of the old gradient subspace is effectively lost, and parameter updates proceed unconstrained into the prior task's solution space.

1.2 Architectures as Single-Frequency Systems

The standard view of a neural network treats it as a monolithic computational graph in which all parameters receive gradient updates at the same timescale, through the same backward pass, at every training step. Under this design, the entire model is exposed to each new batch of data equally, and there is no component that updates slowly enough to act as a long-term anchor for prior knowledge.

Behrouz et al. (2024) formalize this limitation through the lens of associative memory. Specifically, a linear layer trained with backpropagation can be understood as a memory module that maps input data to the local surprise signal of its predictions. Training, under this view, is a compression process in which the model's parameters summarize the gradient history of everything it has seen. In a single-frequency system, this compression is total and sequential: each new task's gradient flow overwrites the compressed representation of prior tasks, because all parameters are available to be updated at every step.

1.3 The Need for Multi-Timescale Memory

*Figure 1: Multi-timescale updates in the brain and analogy to NL (from Behrouz et al., 2025).*

To understand why multi-timescale memory might help, the neuroscientific analogy is instructive. The human brain does not operate on a single clock. Brain waves span a wide frequency spectrum, ranging from delta waves ($\sim$0.5–4 Hz) associated with deep consolidation to gamma waves ($\sim$30–100 Hz) associated with rapid, local processing. Memory consolidation across sleep cycles involves the slow-frequency replay of high-frequency experiences, compressing them into more durable long-term representations. This multi-timescale structure is precisely what allows humans to learn new tasks without erasing prior ones.

Building on this motivation, Behrouz et al. (2024) ask whether this principle can be operationalized in a neural architecture. Concretely, can a model be designed so that some components update quickly to handle fast adaptation to new data, while others update slowly to preserve compressed knowledge from prior tasks?


2. The Breakthrough: Nested Learning and the Continuum Memory System

2.1 The Nested Learning Paradigm

*Figure 2: Nested Learning paradigm representing a model as a system of nested optimization problems, where each level has its own context and gradient flow (Behrouz et al., 2025).*

This figure illustrates the core idea of Nested Learning (NL). Unlike traditional deep learning, where a model is viewed as a single computational graph trained with one global gradient flow, NL decomposes the system into multiple levels of optimization.

Each “box” represents an independent optimization problem:

The key insight is that learning does not occur in a single pass, but through a hierarchy of interacting memory systems. Lower levels adapt quickly to incoming data, while higher levels update more slowly, storing more stable and long-term knowledge. This hierarchical structure introduces a new notion of computational depth not through stacking layers, but through stacking optimization processes.

In response to the limitations described above, Behrouz et al. (2024) introduce Nested Learning (NL) as a unifying framework that reconceptualizes machine learning models as systems of nested, multi-level optimization problems, each operating with its own *context flow* and *update frequency*. Rather than treating a model as a flat collection of parameters updated in lockstep, NL decomposes the model into a hierarchy of components ordered by how frequently they update.

More formally, the *update frequency* of a component $A$ is defined as the number of parameter updates it receives per unit of time. Components with higher frequency update rapidly and are responsible for fast adaptation; components with lower frequency update slowly and are responsible for retaining compressed knowledge over longer timescales. This ordering gives rise to a natural hierarchy of *levels*, where the slowest-updating components form the most durable memory of the model.

A key insight of the NL framework is that this hierarchy is not a new invention. In fact, it is already latent in existing architectures. Backpropagation itself is an associative memory process; momentum in Adam is an associative memory that compresses gradient history; and attention layers in Transformers are fast non-parametric memories while their MLP blocks are slow parametric ones. NL makes this structure explicit and argues that it can be deliberately engineered to unlock continual learning capabilities.

2.2 The Continuum Memory System (CMS)

The concrete architectural contribution of the paper is the Continuum Memory System (CMS): a multi-frequency memory architecture composed exclusively of MLP blocks, where each block is assigned a distinct update frequency and context flow.

In contrast to the binary long-term/short-term distinction in prior memory systems, CMS operates along a *spectrum* of frequencies. In its simplest two-level instantiation:

The mechanism by which CMS resists catastrophic forgetting follows directly from this design. When the high-frequency level is updated on new task data and begins to forget prior knowledge, that knowledge is still compressed in the low-frequency level, which has not yet been updated. Furthermore, because the initial state of each level is meta-learned through backpropagation at the lowest frequency, knowledge transfer between levels can effectively circle back forgotten information, creating a form of temporal redundancy across the memory hierarchy.

Critically, Section 7.1 of the paper specifies that the CMS update rule is compatible with any arbitrary optimizer, as it accepts the error component of any optimizer at each level. This means the multi-timescale memory structure is a property of the architecture itself, independent of the specific optimization algorithm used.

2.3 Why This Matters for the Experiment

Taken together, the NL framework leads to a clear theoretical claim: catastrophic forgetting is a structural consequence of single-frequency gradient flows, not a failure of optimization or model capacity. The standard MLP, with all parameters exposed to the same gradient signal at every step, is maximally vulnerable to forgetting. In contrast, the CMS distributes memory across multiple update frequencies and thereby structurally limits how much any single retraining episode can overwrite prior knowledge.

This experiment is designed to test that claim in its purest form. By holding optimizer (Adam), parameter count, epoch count, and random seed constant across a standard MLP and a two-level CMS model, the only independent variable is the multi-frequency update structure. As a result, any observed difference in stability on the original task after retraining must be attributable to the architecture alone.

The experiment uses MNIST as a controlled, minimal testbed, not because MNIST is a challenging benchmark, but because its simplicity makes the forgetting dynamics legible. Digits 0–4 serve as Task 1 and digits 5–9 serve as Task 2. The prediction is that the standard MLP will exhibit severe forgetting of Task 1 after Task 2 retraining, while the CMS model will retain meaningfully higher accuracy on Task 1. Comparable Task 2 acquisition in both models would then confirm that the stability difference is architectural rather than a plasticity tradeoff.


Preliminaries: Imports and Setup

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import random
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, Subset, Dataset
from torchvision import transforms
from torchvision.datasets import MNIST
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

3. Model Architecture

This notebook implements three model architectures: a baseline StandardMLP and two interpretations of the Continuum Memory System (CMS) introduced in Behrouz et al., *Nested Learning: The Illusion of Deep Learning Architecture* (NeurIPS 2025).

The CMS is designed around a key idea: different parts of a network should update at different frequencies, with high-frequency components handling fast adaptation and low-frequency components preserving long-term knowledge (§7.1 of the paper).

Our two CMS variants — CMSModelV1 and CMSModelV2 — represent two distinct interpretations of how to implement multi-frequency updates in a minimal MLP-only setting. Both are intentionally simple, with no attention, no convolutions, and no normalization layers, in order to isolate the multi-frequency mechanism as the only architectural variable distinguishing them from the baseline MLP

Throughout this section, we use block to refer to a self-contained MLP within a larger architecture.

3.1 Baseline: StandardMLP

The baseline is a fully-connected three-layer perceptron with ReLU activations: 784 → 256 → 256 → 10. It serves two roles in this notebook:

1. As the experimental control. Every result we report for a CMS model is paired with a StandardMLP result. Differences between the two models in Phase 2 stability and plasticity are then attributable to architectural choices in the CMS, not to optimizer or training-procedure differences.

2. As the building block of CMSModelV1. The first CMS variant uses two StandardMLP instances internally as its high- and low-frequency components, so reading this class first makes the V1 forward pass easier to follow.

The forward pass flattens the 28×28 MNIST input (an image) to a 784-dimensional vector before applying the linear layers. Output is raw logits — the cross-entropy loss applies the softmax internally during training.

# =======================================
#     Standard MLP Model Architecture
# =======================================
class StandardMLP(nn.Module):
    def __init__(self, input_size=784, hidden_size=256, num_classes=10):
        super().__init__()
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.layer2 = nn.Linear(hidden_size, hidden_size)
        self.layer3 = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        x = torch.flatten(x, start_dim=1)  # [batch_size, 1, 28, 28] --> [batch_size, 784]
        z1 = self.layer1(x)
        h1 = F.relu(z1)
        z2 = self.layer2(h1)
        h2 = F.relu(z2)
        z3 = self.layer3(h2)
        return z3

3.2 Version 1: CMSModelV1 — Parallel Mixing

Our first CMS interpretation runs two StandardMLP blocks in parallel on the same input and combines their outputs through a learned mixing coefficient alpha (α):

$$ \mathbf{y} = \alpha \cdot \text{block1}(\mathbf{x}) + (1 - \alpha) \cdot \text{block2}(\mathbf{x}) $$

The intent: Block 1 and block 2 are structurally identical, but they are trained at different update frequencies (see "Training Infrastructure" below): block 1's parameters update every batch, while Block 2's parameters update only on chunk boundaries. The hope is that block 2 effectively becomes a slower-moving "memory" of past gradient signals, while block 1 adapts quickly to new data — and that the network learns through α to weight them appropriately for the current task.

Why α is parameterized through a sigmoid: We storee α as alpha_raw (an unconstrained nn.Parameter initialized at 0.0) and apply torch.sigmoid in the forward pass to obtain the actual mixing coefficient.

$$ \alpha = \sigma(\text{alpha\_raw}) $$

This guarantees α ∈ (0, 1) for all training updates, while still allowing gradient descent to optimize over an unconstrained scalar. At initialization, sigmoid(0.0) = 0.5, so the network begins by averaging the two blocks equally.

$$ \alpha = \sigma(0.0) = 0.5 $$

Note on hidden size: Both blocks use hidden_size = 143 rather than the baseline's value of 256. This is a deliberate choice to roughly match the V1 model's total parameter total parameter count to the baseline StandardMLP, ensuring that any observed performance differences cannot be attributed simply to V1 having more capacity.

Relation to the paper: This parallel-mixing structure is a deliberate simplification of the CMS formulation. The paper describes a *chained* composition (we discuss this in the CMSModelV2 section below). In contrast, V1 explores what happens if we treat the two frequency levels as competing predictors that are averaged together.

# =======================================
#    CMS Model Architecture (Version 1)
# =======================================
class CMSModelV1(nn.Module):
    def __init__(self, hidden_size=143):
        super().__init__()
        self.alpha_raw = nn.Parameter(torch.tensor(0.0))  # sigmoid(0.0) = 0.5

        self.block1 = StandardMLP(hidden_size=hidden_size)
        self.block2 = StandardMLP(hidden_size=hidden_size)

    def forward(self, x):
        alpha = torch.sigmoid(self.alpha_raw)

        # Block 1
        out_1 = self.block1(x)

        # Block 2
        out_2 = self.block2(x)

        y = alpha * out_1 + (1 - alpha) * out_2
        return y

3.3 Version 2: CMSModelV2 — Chained Composition

Our second CMS interpretation realizes the paper's chain structure directly. §7.1 of *Nested Learning* defines the CMS forward pass as a composition of MLPs at progressively lower frequencies:

$$ \mathbf{y}_t = \text{MLP}^{(f_k)}\big(\text{MLP}^{(f_{k-1})}\big(\cdots \text{MLP}^{(f_1)}(\mathbf{o}_t)\big)\big) $$

For the simplest non-trivial case where \( k = 2 \):

$$ \mathbf{y} = \text{block2}\big(\text{block1}(\mathbf{x})\big) $$

where block 1 is updated at the higher frequency $f_1$ and block 2 is updated at the lower frequency $f_2$.

Architectural roles: In CMSModelV2, the two blocks have different jobs rather than competing on the same task:

This division of labor is the structural difference from CMSModelV1. In V1, both blocks output 10-dim logits and the network *averaged* them. In V2, the blocks are chained: block 1 produces a representation for block 2 to classify from. The slow component now sits at the classification head, where catastrophic forgetting tends to be concentrated.

Why α is gone? V1 used α to mix two parallel branches. V2's blocks are sequential, not parallel, so there is nothing to mix. The architecture's inductive bias (block 1 extracts features, block 2 classifies them) replaces what α was attempting to express through a learned scalar.

Note on hidden size: V2's blocks use hidden_size=202, chosen to roughly match V2's total parameter count to both the baseline and V1. This ensures that any observed performance differences between the three architectures cannot be attributed to capacity asymmetries.

Relation to the paper. V2 is closer to the paper's CMS formulation than V1, but it is still simplified: the paper's full chain admits arbitrary depth $k$ and uses normalization and convolution layers in its full HOPE configuration (§8.3). We restrict to $k = 2$ with no auxiliary layers in order to keep the minimum working example small enough to train on a CPU and easy to read end-to-end.

# =======================================
#    CMS Model Architecture (Version 2)
# =======================================
class CMSModelV2(nn.Module):
    def __init__(self, hidden_size=202, latent_size=64):
        super().__init__()
        # Block 1: input --> latent representation (fast component)
        self.block1 = nn.Sequential(
            nn.Linear(784, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, latent_size),
        )
        # Block 2: latent representation --> class logits (slow component)
        self.block2 = nn.Sequential(
            nn.Linear(latent_size, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, 10),
        )

    def forward(self, x):
        x = torch.flatten(x, start_dim=1)   # [batch_size, 1, 28, 28] --> [batch_size, 784]
        z = self.block1(x)                  # fast block produces a latent
        y = self.block2(z)                  # slow block classifies from the latent
        return y

3.4 Parameter Count Comparison

def count_params(model):
    return sum(p.numel() for p in model.parameters())

print(f"StandardMLP:    {count_params(StandardMLP()):>8,} parameters")
print(f"CMSModelV1:     {count_params(CMSModelV1()):>8,} parameters")
print(f"CMSModelV2:     {count_params(CMSModelV2()):>8,} parameters")
StandardMLP:     269,322 parameters
CMSModelV1:      268,575 parameters
CMSModelV2:      268,734 parameters

4. Training Infrastructure

This section walks through the data pipeline, the two training loops (one for the baseline MLP, one for the CMS), and the evaluation utilities. The most distinctive piece is train_one_epoch_cms, which implements the multi-frequency update mechanism that distinguishes the CMS architecture from a standard model.

4.1 Dataset: FilteredMNIST and get_mnist_dataloader

For our class-incremental learning experiment, we need to train each model on a *subset* of MNIST classes (digits 0–4) and then later retrain on a different subset (digits 5–9). PyTorch's standard MNIST dataset returns all 10 classes by default, so we wrap it in FilteredMNIST, which accepts a list of digits and exposes only the examples whose labels are in that list.

The filtering happens once at construction time: we take the targets tensor from the underlying MNIST dataset, build a boolean mask indicating which examples have a label in digits, and store the indices of the matching examples. __getitem__ then translates an external index into an internal index via this stored list. This keeps memory usage minimal — we never copy the actual image data, just the index pointers.

The get_mnist_dataloader helper wraps FilteredMNIST in a standard PyTorch DataLoader. It shuffles only when train=True, which is the standard convention: training shuffles to decorrelate consecutive batches, while evaluation uses the natural order so results are reproducible.

Important: the labels are *not* remapped. When we filter to digits 5–9, an example of the digit 7 is still labeled 7, not 2. This matters because the model's output layer always has 10 logits, and we want a true 7 to require predicting class 7, not class 2. The 0–4 labels remain valid output targets even when only 5–9 examples are being trained on — they are simply never the correct answer in that phase.

# =======================================
#          Data Utilities
# =======================================
class FilteredMNIST(Dataset):
    def __init__(self, digits, train, data_root="./data"):
        transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.1307,), (0.3081,))
        ])

        self.base_dataset = MNIST(
            root=data_root,
            train=train,
            transform=transform,
            download=True
        )

        if isinstance(digits, torch.Tensor):
            digits_tensor = digits.clone().detach()
        else:
            digits_tensor = torch.tensor(digits, dtype=torch.long)

        mask = torch.isin(self.base_dataset.targets, digits_tensor)
        self.indices = torch.where(mask)[0]

    def __len__(self):
        return len(self.indices)

    def __getitem__(self, idx):
        x, y = self.base_dataset[self.indices[idx]]

        return x, y
def get_mnist_dataloader(digits, train, batch_size, data_root="./data"):
    """
    Returns a DataLoader over MNIST examples whose label is in `digits`.
    """
    filtered_dataset = FilteredMNIST(digits=digits, train=train, data_root=data_root)

    loader = DataLoader(
        dataset=filtered_dataset,
        batch_size=batch_size,
        shuffle=train  # Only shuffles training set
    )

    return loader

4.2 Baseline Training Loop: train_one_epoch

The baseline training function is a textbook supervised learning loop and serves as a reference point for understanding the more complex CMS variant that follows.

For each batch in the dataloader:

1. Forward pass. Compute the model's predictions on the batch and the cross-entropy loss against the targets. 2. Backward pass. Call loss.backward() to compute gradients of the loss with respect to every learnable parameter. PyTorch's autograd engine accumulates these gradients into each parameter's .grad attribute. 3. Zero gradients. Call optimizer.zero_grad() to clear the previous step's gradients before the next iteration. PyTorch accumulates gradients by default — without this call, gradients from prior batches would compound into the current step. 4. Optimizer step. Call optimizer.step() to apply the Adam update rule to every parameter the optimizer is responsible for, using the gradients just computed.

The model is set to training mode (model.train()) at the start, which enables behaviors like dropout if present (we do not use dropout in this notebook, but the convention is universal). The function tracks the running loss across all batches and returns the per-batch average.

**This function is the *baseline* against which we compare CMS training.** Every parameter in the model is updated on every batch at the same rate. The contrast with the CMS training loop, where different parameters update at different rates, is the architectural point we are testing.

def train_one_epoch(model, dataloader, optimizer, criterion, device):
    """
    Executes one complete training pass (epoch) over the entire dataset.
    """
    model.train()  # Set model to training mode

    total_loss = 0
    N = len(dataloader)  # N = num_batches

    # Loops through each batch (batch_size definied in dataloader)
    for inputs, targets in dataloader:
        # Moving inputs and targets to same device
        inputs, targets = inputs.to(device), targets.to(device)

        # === Training Iteration ===
        # Forward pass
        predictions = model(inputs)
        loss = criterion(predictions, targets)
        total_loss += loss.item()  # Updating loss

        # Backpropagation
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

    avg_loss = total_loss / N

    return avg_loss

4.3 Multi-frequency Training Loop: train_one_epoch_cms

This is the function where the CMS architecture's central idea becomes concrete. The forward pass and the loss computation are unchanged from the baseline; what differs is how the gradients are applied to the parameters once they've been computed.

The model has been partitioned at the optimizer level. Two separate Adam optimizers are constructed externally and passed in:

These two optimizers maintain independent internal state (their own momentum buffers, second-moment estimates, and step counters), and a step on one does not affect the parameters managed by the other. This independence is what makes multi-frequency updates possible.

The update schedule. For every batch, after loss.backward() populates gradients on every parameter, the function makes two decisions:

1. The fast optimizer always steps. Its parameters (block 1, plus α in V1) update on every batch. This is the high-frequency level $f_1$ from the paper's formulation. 2. The slow optimizer steps only on chunk boundaries. When batch_idx % chunk_size == 0 and batch_idx >= chunk_size, it applies an Adam step to block 2's parameters. Otherwise it does nothing — block 2's .grad attributes simply accumulate over the chunk and get applied as a single integrated update at the next boundary. This is the low-frequency level $f_2$.

The batch_idx >= chunk_size guard prevents a slow step from firing on the very first batch (where batch_idx = 0 would otherwise satisfy 0 % chunk_size == 0). With chunk_size=50, the slow optimizer fires on batches 50, 100, 150, and so on.

Why gradient accumulation matters. Because we never call optimizer_slow.zero_grad() between chunk boundaries, block 2's gradients are the *sum* of the gradients from all the batches in the current chunk. When the chunk-boundary step finally fires, Adam sees an integrated gradient signal representing the entire chunk's worth of training data, rather than just the gradient from one isolated batch. This is conceptually closer to what "low-frequency update" means in the paper: a slow component that integrates information over a long window before changing, not a slow component that updates rarely on individual data points.

Continuity across phases. The function takes a start_batch_idx argument and threads batch_idx through the iteration counter. Because the batch counter is preserved across both Phase 1 and Phase 2 (batch_counter is a top-level variable that the experiment cell updates after each phase), the chunk boundaries align continuously through the whole experiment — there is no discontinuity at the phase transition. This matters because we want the slow component's update rhythm to be a property of the model, not of when training happens to start or stop.

Note: The optional slow_step_log parameter, if provided, accumulates the batch indices at which slow steps actually fire. We use this to verify that the slow update mechanism is firing as expected (~93 times across both phases of training, given our chunk_size=50) and to confirm that no chunk-boundary edge cases have caused steps to be missed.

def train_one_epoch_cms(model, dataloader, optimizer_fast, optimizer_slow,
                        chunk_size, criterion, device, start_batch_idx,
                        slow_step_log=None):
    model.train()  # Set model to training mode
    N = len(dataloader)  # N = num_batches
    total_loss = 0

    # Loops through each batch (batch_size definied in dataloader)
    for batch_idx, (inputs, targets) in enumerate(dataloader, start=start_batch_idx):
        # Moving inputs and targets to same device
        inputs, targets = inputs.to(device), targets.to(device)

        # === Training Iteration ===
        # Forward Pass
        logits = model(inputs)
        loss = criterion(logits, targets)
        total_loss += loss.item()  # Updating loss

        # Backward Pass (Backpropagation)
        loss.backward()

        # Block 1: update every batch
        optimizer_fast.step()
        optimizer_fast.zero_grad()

        # Block 2: updates only on chunk boundaries
        if batch_idx % chunk_size == 0 and batch_idx >= chunk_size:
            optimizer_slow.step()
            optimizer_slow.zero_grad()
            if slow_step_log is not None:
                slow_step_log.append(batch_idx)

    avg_loss = total_loss / N
    end_batch_idx = start_batch_idx + N

    return (avg_loss, end_batch_idx)

4.4 Evaluation Utilities: evaluate_model and get_predictions

We need two distinct evaluation functions because we use evaluation outputs in two different ways: to track aggregate performance during training, and to generate per-sample predictions for confusion matrix analysis.

evaluate_model computes two scalar metrics over a dataloader: average loss and accuracy percentage. It runs in inference mode (model.eval(), torch.no_grad()) to disable dropout/batch-norm training behavior and to avoid building the autograd graph (saving memory and time). Predictions are computed via argmax over the logits dimension — the standard "pick the highest-scoring class" decision rule for multi-class classification. This function is called once per epoch on each test set to produce the per-epoch accuracy printouts.

def evaluate_model(model, dataloader, criterion, device):
    model.eval()  # Set model to evaluation mode

    total_loss = 0
    num_correct = 0
    num_samples = 0

    N = len(dataloader)  # N = num_batches

    # Stop PyTorch from building CG in block
    with torch.no_grad():
        for inputs, targets in dataloader:
            # Moving inputs and targets to same device
            inputs, targets = inputs.to(device), targets.to(device)

            # Count correct preds and update num_correct to find accuracy
            logits = model(inputs)
            preds = torch.argmax(logits, dim=1)  # Scans 10 columns for highest value and returns index
            mask = preds == targets
            num_correct += torch.sum(mask).item()

            # Calculate Loss
            loss = criterion(logits, targets)
            total_loss += loss.item()

            num_samples += len(targets)

    avg_loss = total_loss / N
    accuracy = (num_correct / num_samples) * 100

    return avg_loss, accuracy

get_predictions does no metric computation at all. It just runs the model over a dataloader and returns two lists: the true labels and the model's predicted labels for every sample, in order. We use these lists to build confusion matrices. Returning raw predictions (rather than aggregate metrics) is the right interface for confusion analysis because we need to know not just *how many* the model got wrong, but *which wrong class* each error landed on.

def get_predictions(model, dataloader, device):
    model.eval()

    all_targets = []
    all_preds = []

    with torch.no_grad():
        for inputs, targets in dataloader:
            inputs = inputs.to(device)

            logits = model(inputs)
            preds = torch.argmax(logits, dim=1).cpu()

            all_targets.extend(targets.tolist())
            all_preds.extend(preds.tolist())

    return all_targets, all_preds

Both functions iterate the dataloader with model.eval() and torch.no_grad() context, ensuring that calling them does not affect the model's parameters or training trajectory. This is important because we call them inside training loops, between epochs and even between batches in some diagnostic experiments — they are read-only probes into the model's current state.


5. Experiment 1: Parallel Mixing (CMSModelV1) vs StandardMLP

This experiment serves as our minimum working example (MWE) of the CMS architecture and tests its central claim — that multi-frequency parameter updates produce stability against catastrophic forgetting — using the simplest possible setup that can run on a CPU laptop.

Setup: We train two models in parallel: a standard MLP baseline and our CMSModelV1 (the parallel-mixing interpretation). Both have approximately the same parameter count (~269k), are optimized with Adam at the same base learning rate, and use the same random seed. The only meaningful difference between the two models is the multi-frequency update structure of V1's two blocks.

Task: We use a class-incremental MNIST setup adapted from §9.1 of the *Nested Learning* paper, simplified for CPU-scale experimentation:

After Phase 2, we evaluate each model on both digit ranges. A model that exhibits stability retains some ability to classify digits 0–4 even though it never saw them during Phase 2; a model that exhibits plasticity successfully learns to classify the new digits 5–9. The CMS architectural claim is that the slow-updating block 2 should provide stability while the fast-updating block 1 provides plasticity. The standard MLP, with all parameters updating uniformly, has no architectural mechanism for stability and is expected to forget catastrophically.

Reproducibility: Random seeds are fixed at the top of every experiment cell so that runs are deterministic up to GPU-level nondeterminism in CUDA operations (which we observe to produce variations of less than 0.5% in final accuracies).

# === Reproducibility ===
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# === Standard MLP Model: ===
mlp = StandardMLP().to(device)
optimizer_mlp = optim.Adam(mlp.parameters(), lr=0.001)

# === CMS Model: ===
cms = CMSModelV1().to(device)

# Partition parameters across two optimizers (fast & slow)
fast_params = list(cms.block1.parameters()) + [cms.alpha_raw]
opt_fast = optim.Adam(fast_params, lr=0.001)
opt_slow = optim.Adam(cms.block2.parameters(), lr=0.001)

criterion = nn.CrossEntropyLoss()
train_loader_04 = get_mnist_dataloader(digits=[0,1,2,3,4], train=True, batch_size=64)
test_loader_04 = get_mnist_dataloader(digits=[0,1,2,3,4], train=False, batch_size=64)

epochs = 5  
chunk_size = 50  
batch_counter = 0  # Don't change!

slow_step_log = []  # Accumulates across BOTH phases!

5.1 Phase 1: Pre-training on Digits 0–4

We train each model for 5 epochs on the MNIST training set restricted to digits 0–4. After each epoch, we evaluate the model on the corresponding test set and print training loss, test loss, and test accuracy.

For the CMS model, we additionally print the current value of α (the V1 mixing coefficient), parameterized internally as the sigmoid of alpha_raw. Watching α evolve is an indirect way of observing whether the model is developing a preference between the fast and slow blocks — a value drifting away from 0.5 would indicate specialization.

Two test sets are loaded at this stage: digits 0–4 (the target task) and digits 5–9 (the future task). Evaluating on digits 5–9 during Phase 1 is intentional and serves to establish a random-chance baseline: since the model has never seen digits 5–9, its accuracy on them tells us what "untrained" performance looks like in this label space. We use this number as the starting point against which Phase 2 plasticity is measured.

Expected behavior: Both models should achieve high accuracy (> 98%) on digits 0–4. Both models should achieve near-zero accuracy on digits 5–9 (chance is 10% for 10-class classification, but our models are biased to predict only 0–4, so the achieved number is typically below 10%). The CMS model's α value should remain close to 0.5, since neither block has any reason to specialize during single-task training.

# ===============
# === PHASE 1 ===
# ===============

# === Training & Evaluation (digits 0-4): ===

mlp_train_loss_04_p1 = []
mlp_test_loss_04_p1 = []
mlp_test_accuracy_04_p1 = []
cms_train_loss_04_p1 = []
cms_test_loss_04_p1 = []
cms_test_accuracy_04_p1 = []
alpha_vals_p1 = []

print("Standard MLP training metrics:")
for epoch in range(epochs):
    # Training Standard MLP Model
    mlp_train_loss = train_one_epoch(mlp, train_loader_04, optimizer_mlp, criterion, device)
    mlp_test_loss, mlp_test_accuracy = evaluate_model(mlp, test_loader_04, criterion, device)
    print(f"    Epoch: {epoch + 1}: train_loss={mlp_train_loss:.4f}, test_loss={mlp_test_loss:.4f}, "
        f"test_accuracy={mlp_test_accuracy:.2f}%")

    # Update MLP logs
    mlp_train_loss_04_p1.append(mlp_train_loss)
    mlp_test_loss_04_p1.append(mlp_test_loss)
    mlp_test_accuracy_04_p1.append(mlp_test_accuracy)

print("\nCMS training metrics:")
for epoch in range(epochs):
    # Training CMS Model:
    cms_train_loss, batch_counter = train_one_epoch_cms(
        cms, train_loader_04, opt_fast, opt_slow, chunk_size=chunk_size,
        criterion=criterion, device=device, start_batch_idx=batch_counter,
        slow_step_log=slow_step_log
    )

    cms_test_loss, cms_test_accuracy = evaluate_model(cms, test_loader_04, criterion, device)
    alpha_val = torch.sigmoid(cms.alpha_raw).item()
    print(f"    Epoch: {epoch + 1}: train_loss={cms_train_loss:.4f}, test_loss={cms_test_loss:.4f}, "
        f"test_accuracy={cms_test_accuracy:.2f}%, a={alpha_val:.5f}")

    # Update CMS logs
    cms_train_loss_04_p1.append(cms_train_loss)
    cms_test_loss_04_p1.append(cms_test_loss)
    cms_test_accuracy_04_p1.append(cms_test_accuracy)

    alpha_vals_p1.append(alpha_val)

# Evaluating both models on digits 5-9
test_loader_59 = get_mnist_dataloader(digits=[5,6,7,8,9], train=False, batch_size=64)

# Final accuracies for MLP and CMS models
mlp_final_loss_04_p1, mlp_final_acc_04_p1 = evaluate_model(mlp, test_loader_04, criterion, device)
cms_final_loss_04_p1, cms_final_acc_04_p1 = evaluate_model(cms, test_loader_04, criterion, device)
mlp_final_loss_59_p1, mlp_final_acc_59_p1 = evaluate_model(mlp, test_loader_59, criterion, device)
cms_final_loss_59_p1, cms_final_acc_59_p1 = evaluate_model(cms, test_loader_59, criterion, device)
final_alpha_val_p1 = alpha_vals_p1[-1]

print(f"\nPhase 1 endpoint, evaluated on 0-4:")
print(f"  MLP: {mlp_final_acc_04_p1:.2f}%")
print(f"  CMS: {cms_final_acc_04_p1:.2f}%")
print(f"\nPhase 1 endpoint, evaluated on 5-9:")
print(f"  MLP: {mlp_final_acc_59_p1:.2f}%")
print(f"  CMS: {cms_final_acc_59_p1:.2f}%")
print(f"\nAlpha: a={final_alpha_val_p1:.5f}")
Standard MLP training metrics:
    Epoch: 1: train_loss=0.1206, test_loss=0.0334, test_accuracy=98.85%
    Epoch: 2: train_loss=0.0409, test_loss=0.0323, test_accuracy=99.05%
    Epoch: 3: train_loss=0.0272, test_loss=0.0171, test_accuracy=99.36%
    Epoch: 4: train_loss=0.0172, test_loss=0.0217, test_accuracy=99.24%
    Epoch: 5: train_loss=0.0137, test_loss=0.0284, test_accuracy=99.16%

CMS training metrics:
    Epoch: 1: train_loss=0.1638, test_loss=0.0546, test_accuracy=98.27%, a=0.51308
    Epoch: 2: train_loss=0.0570, test_loss=0.0388, test_accuracy=98.74%, a=0.52289
    Epoch: 3: train_loss=0.0351, test_loss=0.0273, test_accuracy=99.07%, a=0.53073
    Epoch: 4: train_loss=0.0243, test_loss=0.0364, test_accuracy=98.83%, a=0.53766
    Epoch: 5: train_loss=0.0155, test_loss=0.0268, test_accuracy=99.24%, a=0.54644

Phase 1 endpoint, evaluated on 0-4:
  MLP: 99.16%
  CMS: 99.24%

Phase 1 endpoint, evaluated on 5-9:
  MLP: 0.00%
  CMS: 0.00%

Alpha: a=0.54644

- Plot of Learning Curve on Digits 0–4

We examine how both models learn the initial task during Phase 1. The plot below shows test accuracy on digits 0–4 across epochs.

def plot_phase1_curve(epochs, mlp_acc, cms_acc):
    plt.figure(figsize=(8,5))
    plt.plot(epochs, mlp_acc, marker='o', label='Standard MLP')
    plt.plot(epochs, cms_acc, marker='o', label='CMS Model')

    plt.xlabel("Epoch")
    plt.ylabel("Accuracy (%)")
    plt.title("Phase 1 Learning Curve (Digits 0–4)")
    plt.legend()
    plt.grid(True)
    plt.show()

plot_phase1_curve(
    [1,2,3,4,5],
    mlp_test_accuracy_04_p1,
    cms_test_accuracy_04_p1
)

Analysis (Phase 1 Learning Curve)

Both models demonstrate strong and stable learning behavior during Phase 1. Accuracy on digits 0–4 increases rapidly within the first few epochs and saturates above 99% for both the StandardMLP and CMSModelV1.

The learning trajectories of the two models are very similar, with only minor fluctuations. The StandardMLP slightly outperforms the CMS model in the final epoch, but the difference is negligible (less than 0.2%). This indicates that the CMS architecture does not introduce any meaningful degradation in standard supervised learning performance.

Importantly, no specialization behavior is observed in this phase. Since both models are trained on a single task, there is no incentive for the CMS model to differentiate between its fast and slow components. As a result, both architectures effectively behave like standard feedforward networks during Phase 1.

Overall, this phase confirms that both models start Phase 2 from an equivalent and strong baseline, which is critical for a fair comparison in the continual learning setting.

5.2 Phase 2: Continual Learning on Digits 5–9

This is the experiment's core test. We continue training both models — preserving all weights from Phase 1 — for 5 more epochs on the MNIST training set restricted to digits 5–9. No examples from digits 0–4 are shown during Phase 2. This is what makes the experiment a continual learning test: the model must learn the new task purely from new data, without any rehearsal of the old.

After each Phase 2 epoch, we evaluate each model on both test sets — digits 0–4 and digits 5–9 — to track stability and plasticity over the course of retraining. The two metrics we care about are:

For the CMS model, we also continue tracking α to see whether retraining causes any meaningful shift in the mixing coefficient — if the architecture were genuinely developing different roles for its two blocks, we might expect α to move noticeably during the phase transition.

Continuity of the slow update mechanism. The batch_counter variable, threaded through both phases of the CMS training loop, ensures that the slow-frequency update boundaries continue uninterrupted across the phase transition. We log the exact batch indices at which slow steps fire (slow_step_log) and report the total count after Phase 2 — this serves as a sanity check that the multi-frequency mechanism is operating as designed, not as a special metric.

Expected behavior. The standard MLP, having no stability mechanism, is expected to exhibit substantial forgetting on digits 0–4. The CMS, if its architectural claim holds, should retain at least some accuracy on digits 0–4 — an advantage attributable to its slow-updating block 2.

# ===============
# === PHASE 2 ===
# ===============

# === Training & Evaluation (digits 5-9): ===

train_loader_59 = get_mnist_dataloader([5,6,7,8,9], train=True, batch_size=64)

# Digits 0-4 metrics
mlp_test_loss_04_p2 = [mlp_final_loss_04_p1]
mlp_test_accuracy_04_p2 = [mlp_final_acc_04_p1]
cms_test_loss_04_p2 = [cms_final_loss_04_p1]
cms_test_accuracy_04_p2 = [cms_final_acc_04_p1]

# Digits 5-9 metrics
mlp_train_loss_59_p2 = []
mlp_test_loss_59_p2 = [mlp_final_loss_59_p1]
mlp_test_accuracy_59_p2 = [mlp_final_acc_59_p1]
cms_train_loss_59_p2 = []
cms_test_loss_59_p2 = [cms_final_loss_59_p1]
cms_test_accuracy_59_p2 = [cms_final_acc_59_p1]

alpha_vals_p2 = [final_alpha_val_p1]

print("Standard MLP training metrics:")
for epoch in range(epochs):
    # Retraining Standard MLP model:
    mlp_train_loss = train_one_epoch(mlp, train_loader_59, optimizer_mlp, criterion, device)

    # Two evaluations per epoch, one per digit group
    mlp_test_loss_04, mlp_test_accuracy_04 = evaluate_model(mlp, test_loader_04, criterion, device)
    mlp_test_loss_59, mlp_test_accuracy_59 = evaluate_model(mlp, test_loader_59, criterion, device)

    print(f"    Epoch: {epoch + 1}: train_loss={mlp_train_loss:.4f}, "
        f"acc_04={mlp_test_accuracy_04:.2f}%, acc_59={mlp_test_accuracy_59:.2f}%")

    # Update MLP logs
    mlp_test_loss_04_p2.append(mlp_test_loss_04)
    mlp_test_accuracy_04_p2.append(mlp_test_accuracy_04)

    mlp_train_loss_59_p2.append(mlp_train_loss)
    mlp_test_loss_59_p2.append(mlp_test_loss_59)
    mlp_test_accuracy_59_p2.append(mlp_test_accuracy_59)

print("\nCMS training metrics:")
for epoch in range(epochs):
    # Retraining CMS Model:
    cms_train_loss, batch_counter = train_one_epoch_cms(
        cms, train_loader_59, opt_fast, opt_slow, chunk_size=chunk_size,
        criterion=criterion, device=device, start_batch_idx=batch_counter,
        slow_step_log=slow_step_log
    )
    # Two evaluations per epoch, one per digit group
    cms_test_loss_04, cms_test_accuracy_04 = evaluate_model(cms, test_loader_04, criterion, device)
    cms_test_loss_59, cms_test_accuracy_59 = evaluate_model(cms, test_loader_59, criterion, device)
    alpha_val = torch.sigmoid(cms.alpha_raw).item()

    print(f"    Epoch: {epoch + 1}: train_loss={cms_train_loss:.4f}, "
      f"acc_04={cms_test_accuracy_04:.2f}%, acc_59={cms_test_accuracy_59:.2f}%, "
      f"a={alpha_val:.5f}")

    # Update CMS logs
    cms_test_loss_04_p2.append(cms_test_loss_04)
    cms_test_accuracy_04_p2.append(cms_test_accuracy_04)

    cms_train_loss_59_p2.append(cms_train_loss)
    cms_test_loss_59_p2.append(cms_test_loss_59)
    cms_test_accuracy_59_p2.append(cms_test_accuracy_59)

    alpha_vals_p2.append(alpha_val)

# Final accuracies for MLP and CMS models
mlp_final_loss_04_p2, mlp_final_acc_04_p2 = evaluate_model(mlp, test_loader_04, criterion, device)
cms_final_loss_04_p2, cms_final_acc_04_p2 = evaluate_model(cms, test_loader_04, criterion, device)
mlp_final_loss_59_p2, mlp_final_acc_59_p2 = evaluate_model(mlp, test_loader_59, criterion, device)
cms_final_loss_59_p2, cms_final_acc_59_p2 = evaluate_model(cms, test_loader_59, criterion, device)

mlp_acc_change_04 = mlp_final_acc_04_p2 - mlp_final_acc_04_p1
mlp_acc_change_59 = mlp_final_acc_59_p2 - mlp_final_acc_59_p1
cms_acc_change_04 = cms_final_acc_04_p2 - cms_final_acc_04_p1
cms_acc_change_59 = cms_final_acc_59_p2 - cms_final_acc_59_p1
final_alpha_val_p2 = alpha_vals_p2[-1]

print(f"\nSlow steps fired at batches: {slow_step_log}")
print(f"Total slow steps across both phases: {len(slow_step_log)}")

print("\nPhase 1 --> Phase 2 Summary:")
print(f"  MLP: 0-4 accuracy: {mlp_final_acc_04_p1:.2f}% --> {mlp_final_acc_04_p2:.2f}% (Δ = {mlp_acc_change_04:+.2f})")
print(f"       5-9 accuracy: {mlp_final_acc_59_p1:.2f}% --> {mlp_final_acc_59_p2:.2f}% (Δ = {mlp_acc_change_59:+.2f})")
print(f"  CMS: 0-4 accuracy: {cms_final_acc_04_p1:.2f}% --> {cms_final_acc_04_p2:.2f}% (Δ = {cms_acc_change_04:+.2f})")
print(f"       5-9 accuracy: {cms_final_acc_59_p1:.2f}% --> {cms_final_acc_59_p2:.2f}% (Δ = {cms_acc_change_59:+.2f})")
print(f"  \nAlpha: {final_alpha_val_p1:.5f} --> {final_alpha_val_p2:.5f}")
Standard MLP training metrics:
    Epoch: 1: train_loss=0.2716, acc_04=0.00%, acc_59=96.61%
    Epoch: 2: train_loss=0.0702, acc_04=0.00%, acc_59=97.82%
    Epoch: 3: train_loss=0.0495, acc_04=0.00%, acc_59=97.86%
    Epoch: 4: train_loss=0.0347, acc_04=0.00%, acc_59=98.19%
    Epoch: 5: train_loss=0.0285, acc_04=0.00%, acc_59=98.03%

CMS training metrics:
    Epoch: 1: train_loss=0.3217, acc_04=0.00%, acc_59=96.24%, a=0.54120
    Epoch: 2: train_loss=0.0836, acc_04=0.00%, acc_59=97.35%, a=0.54384
    Epoch: 3: train_loss=0.0618, acc_04=0.00%, acc_59=97.57%, a=0.54638
    Epoch: 4: train_loss=0.0484, acc_04=0.00%, acc_59=97.55%, a=0.54917
    Epoch: 5: train_loss=0.0377, acc_04=0.00%, acc_59=97.26%, a=0.55373

Slow steps fired at batches: [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750, 1800, 1850, 1900, 1950, 2000, 2050, 2100, 2150, 2200, 2250, 2300, 2350, 2400, 2450, 2500, 2550, 2600, 2650, 2700, 2750, 2800, 2850, 2900, 2950, 3000, 3050, 3100, 3150, 3200, 3250, 3300, 3350, 3400, 3450, 3500, 3550, 3600, 3650, 3700, 3750, 3800, 3850, 3900, 3950, 4000, 4050, 4100, 4150, 4200, 4250, 4300, 4350, 4400, 4450, 4500, 4550, 4600, 4650]
Total slow steps across both phases: 93

Phase 1 --> Phase 2 Summary:
  MLP: 0-4 accuracy: 99.16% --> 0.00% (Δ = -99.16)
       5-9 accuracy: 0.00% --> 98.03% (Δ = +98.03)
  CMS: 0-4 accuracy: 99.24% --> 0.00% (Δ = -99.24)
       5-9 accuracy: 0.00% --> 97.26% (Δ = +97.26)
  
Alpha: 0.54644 --> 0.55373

- Plot of Continual Learning on Digits 5–9

We now continue training both models on digits 5–9 without showing any examples from digits 0–4.

We evaluate two metrics after each epoch:

def plot_phase2_curve(phase2_epochs, mlp_04, mlp_59, cms_04, cms_59):
    plt.figure(figsize=(8, 5))

    plt.plot(phase2_epochs, mlp_04, marker='o', linestyle='--', label='MLP on digits 0–4')
    plt.plot(phase2_epochs, mlp_59, marker='o', linestyle='-', label='MLP on digits 5–9')

    plt.plot(phase2_epochs, cms_04, marker='s', linestyle='--', label='CMS on digits 0–4')
    plt.plot(phase2_epochs, cms_59, marker='s', linestyle='-', label='CMS on digits 5–9')

    plt.xlabel("Phase 2 Epoch")
    plt.ylabel("Accuracy (%)")
    plt.title("Phase 2 Stability vs Plasticity")
    plt.axvline(x=0, linestyle='--', alpha=0.5)
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()


phase2_epochs = list(range(len(mlp_test_accuracy_04_p2)))

plot_phase2_curve(
    phase2_epochs,
    mlp_test_accuracy_04_p2,
    mlp_test_accuracy_59_p2,
    cms_test_accuracy_04_p2,
    cms_test_accuracy_59_p2
)

Analysis (Phase 2 Stability vs Plasticity)

The Phase 2 curve reveals the core result of the experiment.

Both models exhibit a sharp and immediate drop in accuracy on digits 0–4, falling from approximately 99% to 0% after the first epoch of retraining. This indicates complete catastrophic forgetting, with no residual ability to classify the original task.

At the same time, both models rapidly achieve high accuracy on digits 5–9, reaching above 97% within a single epoch and continuing to improve slightly thereafter. This demonstrates strong plasticity, as both models can quickly adapt to the new task.

The CMS model closely mirrors the behavior of the StandardMLP across both metrics. There is no observable delay in forgetting, nor any partial retention of the original task. The stability curve (digits 0–4) collapses immediately for both models, while the plasticity curve (digits 5–9) rises similarly.

This suggests that the multi-frequency update mechanism implemented in CMSModelV1 does not provide any measurable stability advantage in this configuration. The slow-updating component does not retain useful information about the original task, and the model behaves similarly to a standard network undergoing full parameter overwriting.

Overall, the results show that both architectures achieve strong plasticity but fail entirely in maintaining stability, indicating that multi-frequency updates alone are insufficient to prevent catastrophic forgetting in this setting.

5.3 Combined Performance Across Both Phases

We now visualize the entire experiment in a single plot, combining Phase 1 and Phase 2.

This provides a unified view of:

By plotting both phases together, we can clearly observe how model performance evolves over time and how abruptly forgetting occurs.

def plot_combined_curve(
    phase1_epochs,
    phase2_epochs,
    mlp_04_p1, cms_04_p1,
    mlp_04_p2, cms_04_p2,
    mlp_59_p2, cms_59_p2
):
    # Combine x-axis
    x1 = phase1_epochs
    x2 = [phase1_epochs[-1] + e for e in phase2_epochs]

    plt.figure(figsize=(9,5))

    # Phase 1 (0–4 only)
    plt.plot(x1, mlp_04_p1, 'o-', label="MLP (0–4, Phase 1)")
    plt.plot(x1, cms_04_p1, 's-', label="CMS (0–4, Phase 1)")

    # Phase 2 (0–4 collapse)
    plt.plot(x2, mlp_04_p2[1:], 'o--', label="MLP (0–4, Phase 2)")
    plt.plot(x2, cms_04_p2[1:], 's--', label="CMS (0–4, Phase 2)")

    # Phase 2 (5–9 learning)
    plt.plot(x2, mlp_59_p2[1:], 'o-', label="MLP (5–9)")
    plt.plot(x2, cms_59_p2[1:], 's-', label="CMS (5–9)")

    # Vertical line at transition
    plt.axvline(x=phase1_epochs[-1], linestyle='--', alpha=0.6)
    plt.text(phase1_epochs[-1]+0.1, 50, "Phase Transition", rotation=90)

    plt.xlabel("Epoch")
    plt.ylabel("Accuracy (%)")
    plt.title("Combined Learning Dynamics (Phase 1 → Phase 2)")
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()


plot_combined_curve(
    phase1_epochs=[1,2,3,4,5],
    phase2_epochs=[1,2,3,4,5],
    mlp_04_p1=mlp_test_accuracy_04_p1,
    cms_04_p1=cms_test_accuracy_04_p1,
    mlp_04_p2=mlp_test_accuracy_04_p2,
    cms_04_p2=cms_test_accuracy_04_p2,
    mlp_59_p2=mlp_test_accuracy_59_p2,
    cms_59_p2=cms_test_accuracy_59_p2
)

Analysis

The combined plot highlights the most important behavior of the experiment.

During Phase 1, both models learn the original task (digits 0–4) effectively, reaching high accuracy. At the phase transition, a sharp and immediate drop occurs: accuracy on digits 0–4 collapses to 0% for both models after just one epoch of retraining.

At the same time, accuracy on digits 5–9 rises rapidly, indicating successful learning of the new task.

This creates a clear visual signature of catastrophic forgetting:

Importantly, the CMS model follows nearly the exact same trajectory as the StandardMLP. There is no observable delay in forgetting, nor any partial retention of the original task.

This suggests that the multi-frequency update mechanism does not provide stability in this configuration. The slow component does not prevent the overwriting of previously learned representations.

5.4 Confusion matrices: Diagnosing what happened

The Phase 2 summary numbers — 0.00% accuracy on digits 0–4 for both models — are striking but quantitatively limited. A scalar accuracy doesn't tell us *what kind* of failure we're looking at. To diagnose the failure mode, we generate confusion matrices for each model on each test set.

The confusion matrices break down the predictions row-by-row by true label and column-by-column by predicted label. The diagonal contains correct predictions; off-diagonal entries reveal *which* incorrect class each error landed on. This per-class structure is essential for distinguishing between failure modes that all happen to score 0%:

What to look for. The confusion matrices that follow should answer three questions:

1. Did either model retain *any* ability to predict digits 0–4? (Look for nonzero entries in columns 0–4.) 2. If predictions all collapse into 5–9, is the *structure* of the misclassifications meaningful? (For instance, does true 4 → predicted 9 dominate? That would suggest the network's *features* are intact even though the *output assignments* have been overwritten.) 3. Do the MLP and CMS confusion matrices look meaningfully different from each other? (Differences would suggest the architecture is doing something distinct, even if both still score 0%.)

def plot_confusion_matrix_for_model(model, dataloader, device, class_labels, title):
    y_true, y_pred = get_predictions(model, dataloader, device)
    cm = confusion_matrix(y_true, y_pred, labels=class_labels)

    disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=class_labels)
    disp.plot(values_format='d')
    plt.title(title)
    plt.tight_layout()
    plt.show()

# === Numerical breakdown: where do predictions actually land? ===
def prediction_distribution(model, dataloader, device, model_name, eval_set_name):
    y_true, y_pred = get_predictions(model, dataloader, device)
    y_pred = np.array(y_pred)

    print(f"\n=== {model_name} — evaluated on {eval_set_name} ===")
    print(f"Total samples: {len(y_pred)}")
    print(f"Prediction distribution (which class did the model output?):")
    unique, counts = np.unique(y_pred, return_counts=True)
    for c, n in zip(unique, counts):
        pct = 100 * n / len(y_pred)
        print(f"  predicted class {c}: {n:5d}  ({pct:5.2f}%)")

    # How many predictions landed in the "old" range vs the "new" range?
    in_04 = np.sum((y_pred >= 0) & (y_pred <= 4))
    in_59 = np.sum((y_pred >= 5) & (y_pred <= 9))
    print(f"  --> predictions in 0–4 range: {in_04} ({100*in_04/len(y_pred):.2f}%)")
    print(f"  --> predictions in 5–9 range: {in_59} ({100*in_59/len(y_pred):.2f}%)")


# === Numerical summary of overall performance ===
def overall_accuracy_breakdown(model, dataloader, device, model_name):
    y_true, y_pred = get_predictions(model, dataloader, device)
    y_true = np.array(y_true)
    y_pred = np.array(y_pred)

    total = len(y_true)
    correct = np.sum(y_true == y_pred)
    overall = 100 * correct / total

    # Per-class accuracy
    print(f"\n=== {model_name} — full 0–9 evaluation ===")
    print(f"Overall accuracy: {overall:.2f}% ({correct}/{total})")
    print(f"Per-class accuracy:")
    for c in range(10):
        mask = (y_true == c)
        if mask.sum() == 0:
            continue
        class_correct = np.sum(y_pred[mask] == c)
        class_total = mask.sum()
        class_acc = 100 * class_correct / class_total
        print(f"  class {c}: {class_correct:5d}/{class_total:5d} ({class_acc:6.2f}%)")
# =================================
#    Full 0-9 Confusion Matrices
# =================================

# Build a test loader that includes all digits 0–9
test_loader_09 = get_mnist_dataloader(digits=list(range(10)), train=False, batch_size=64)

all_classes = list(range(10))

# === Combined-task confusion matrices ===
plot_confusion_matrix_for_model(
    mlp, test_loader_09, device, all_classes,
    title="Standard MLP — Phase 2 — All digits 0–9"
)
plot_confusion_matrix_for_model(
    cms, test_loader_09, device, all_classes,
    title="CMS Model (V1) — Phase 2 — All digits 0–9"
)

Prediction distribution: where do predictions on digits 0–4 actually land?

The confusion matrices show *which* wrong class each prediction lands on, but the prediction distribution makes the headline summary unmistakable in a single number. For each model, we report the count of predictions across all 10 classes when evaluated on the digits 0–4 test set, plus the total fraction of predictions falling into the 0–4 vs. 5–9 label ranges.

prediction_distribution(mlp, test_loader_04, device, "Standard MLP", "digits 0–4")
prediction_distribution(cms, test_loader_04, device, "CMS Model (V1)",   "digits 0–4")
=== Standard MLP — evaluated on digits 0–4 ===
Total samples: 5139
Prediction distribution (which class did the model output?):
  predicted class 5:   729  (14.19%)
  predicted class 6:   463  ( 9.01%)
  predicted class 7:   549  (10.68%)
  predicted class 8:  1540  (29.97%)
  predicted class 9:  1858  (36.15%)
  --> predictions in 0–4 range: 0 (0.00%)
  --> predictions in 5–9 range: 5139 (100.00%)

=== CMS Model (V1) — evaluated on digits 0–4 ===
Total samples: 5139
Prediction distribution (which class did the model output?):
  predicted class 5:   939  (18.27%)
  predicted class 6:   921  (17.92%)
  predicted class 7:  1169  (22.75%)
  predicted class 8:  1122  (21.83%)
  predicted class 9:   988  (19.23%)
  --> predictions in 0–4 range: 0 (0.00%)
  --> predictions in 5–9 range: 5139 (100.00%)

Per-class accuracy across all 10 classes.

The previous outputs focused on Phase 2 evaluation against digits 0–4 alone. Here we evaluate both models on the full 0–9 test set and report per-class accuracy, which makes the asymmetric collapse (some classes at near-zero, others at near-perfect accuracy) directly visible.

overall_accuracy_breakdown(mlp, test_loader_09, device, "Standard MLP")
overall_accuracy_breakdown(cms, test_loader_09, device, "CMS Model (V1)")
=== Standard MLP — full 0–9 evaluation ===
Overall accuracy: 47.65% (4765/10000)
Per-class accuracy:
  class 0:     0/  980 (  0.00%)
  class 1:     0/ 1135 (  0.00%)
  class 2:     0/ 1032 (  0.00%)
  class 3:     0/ 1010 (  0.00%)
  class 4:     0/  982 (  0.00%)
  class 5:   873/  892 ( 97.87%)
  class 6:   939/  958 ( 98.02%)
  class 7:   996/ 1028 ( 96.89%)
  class 8:   959/  974 ( 98.46%)
  class 9:   998/ 1009 ( 98.91%)

=== CMS Model (V1) — full 0–9 evaluation ===
Overall accuracy: 47.28% (4728/10000)
Per-class accuracy:
  class 0:     0/  980 (  0.00%)
  class 1:     0/ 1135 (  0.00%)
  class 2:     0/ 1032 (  0.00%)
  class 3:     0/ 1010 (  0.00%)
  class 4:     0/  982 (  0.00%)
  class 5:   878/  892 ( 98.43%)
  class 6:   948/  958 ( 98.96%)
  class 7:  1022/ 1028 ( 99.42%)
  class 8:   925/  974 ( 94.97%)
  class 9:   955/ 1009 ( 94.65%)

What the diagnostics reveal

Returning to the three questions posed at the start of this section:

1. Did either model retain any ability to predict digits 0–4? No. Looking at the confusion matrices, columns 0–4 are completely empty for both models. The prediction distribution makes this unambiguous: 100.00% of predictions on the digits 0–4 test set land in the 5–9 range for both the MLP and the V1 CMS. This is a clean instance of output-space collapse — the failure mode where new-task gradients have driven the old-task output logits below the new-task logits, so no input can produce a top-1 prediction in the 0–4 range regardless of what features the network extracts. The 0% accuracy on 0–4 is not "the model getting most predictions wrong" — it's the model being mechanically incapable of producing those labels at all.

2. Is the structure of the misclassifications meaningful? Yes, and this is the most informative finding from the matrices. The off-diagonal patterns within the upper-right 5×5 block are not random — they follow visual similarities the network learned during Phase 1. True 4s are most often predicted as 9s (closed loop above a vertical stroke). True 1s are most often predicted as 7s (thin vertical strokes). True 3s are most often predicted as 5s (similar bottom curve). These mappings indicate that the feature extraction learned during Phase 1 survived Phase 2 retraining — the network still "sees" the digits correctly. What it can no longer do is *route* those features to the correct output class, because the classification head's per-class biases have been overwritten. Catastrophic forgetting in this setup is concentrated in the output layer, not in the feature extractor.

3. Do the MLP and CMS confusion matrices look meaningfully different? Marginally. The two matrices have similar overall structure — same dead columns, similar off-diagonal patterns, comparable magnitudes. CMS V1 spreads its predictions across the surviving 5–9 outputs slightly differently than the MLP does. But these differences are within the magnitude of run-to-run variation and do not constitute a stability advantage. Both models reach the same Phase 2 endpoint: ~0% on the old task, ~98% on the new task, ~48% overall on the combined 0–9 test set.

Summary of Experiment 1. The parallel-mixing CMS interpretation, when trained on a class-incremental MNIST task with full retraining on a disjoint label set, behaves indistinguishably from a standard MLP at the level of headline metrics. The α mixing coefficient remained near 0.5 throughout training (drifting from 0.547 at the end of Phase 1 to 0.554 at the end of Phase 2), indicating that the model never expressed a meaningful preference between its fast and slow blocks for either task. This raises a natural follow-up question that motivates Experiment 2: was the failure a property of the CMS idea itself, or a property of our specific parallel-mixing simplification of it?

6. Experiment 2: Chained Composition (CMSModelV2) vs. Standard MLP

Experiment 1 produced an unambiguous result: both V1 and the baseline MLP collapsed to 0% accuracy on digits 0–4 after Phase 2 retraining. The CMS architecture, in its parallel-mixing interpretation, did not provide stability against catastrophic forgetting in this setup.

That result raises a natural follow-up question. The parallel-mixing interpretation in V1 is a *simplification* of the paper's actual CMS formulation — Section 7.1 describes a chain of MLPs at progressively lower frequencies, not two parallel branches averaged together. Was V1's failure a property of the CMS idea itself, or a property of our specific simplification? Experiment 2 addresses this question directly by re-implementing the CMS using CMSModelV2, which realizes the chained composition described in the paper.

What's different from Experiment 1. Experiment 2 is structurally a re-run of Experiment 1 with CMSModelV1 swapped for CMSModelV2. Everything else — random seed, training procedure, optimizer hyperparameters, chunk size, dataset, evaluation procedure — is held fixed. This isolates the architectural change as the only variable distinguishing the two experiments. Three notable consequences of moving to V2:

1. The α parameter is removed (chained composition has no parallel branches to mix). 2. The slow-updating block 2 is now positioned at the classification head rather than alongside block 1, placing the multi-frequency mechanism directly at the location where catastrophic forgetting tends to be concentrated.

The hypothesis under test. If V1's failure was an artifact of the parallel-mixing simplification, V2's chained composition should produce a meaningfully different result — at minimum, some non-zero stability on digits 0–4 in Phase 2. If V2 also collapses to 0%, the result extends our finding from "the parallel-mixing CMS doesn't help here" to "neither tested interpretation of the CMS architecture provides stability in this setup," which is a substantially stronger claim about the limits of pure-architecture interventions in class-incremental learning.

We do not preview the result here. The reader should encounter the Phase 2 numbers freshly and form their own interpretation before we synthesize across both experiments at the end of the section.

# === Reproducibility ===
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# === Standard MLP Model: ===
mlp = StandardMLP().to(device)
optimizer_mlp = optim.Adam(mlp.parameters(), lr=0.001)

# === CMS_V2 Model: ===
cms = CMSModelV2().to(device)

# Partition parameters across two optimizers (fast & slow)
opt_fast = optim.Adam(cms.block1.parameters(), lr=0.001)
opt_slow = optim.Adam(cms.block2.parameters(), lr=0.001)

criterion = nn.CrossEntropyLoss()
train_loader_04 = get_mnist_dataloader(digits=[0,1,2,3,4], train=True, batch_size=64)
test_loader_04 = get_mnist_dataloader(digits=[0,1,2,3,4], train=False, batch_size=64)

epochs = 5  
chunk_size = 50  
batch_counter = 0  # Don't change!

slow_step_log = []  # Accumulates across BOTH phases!

6.1 Phase 1: Pre-training on digits 0–4 (V2)

The structure of Phase 1 is identical to Experiment 1: 5 epochs of training on digits 0–4, with end-of-epoch evaluation on both digits 0–4 and digits 5–9. The only differences are the model class (CMSModelV2 instead of CMSModelV1) and the absence of α tracking.

We expect both models to reach approximately the same 99% baseline on digits 0–4 that we observed in Experiment 1, since the task and training procedure are unchanged.

# ===============
# === PHASE 1 ===
# ===============

# === Training & Evaluation (digits 0-4): ===

mlp_train_loss_04_p1 = []
mlp_test_loss_04_p1 = []
mlp_test_accuracy_04_p1 = []
cms_train_loss_04_p1 = []
cms_test_loss_04_p1 = []
cms_test_accuracy_04_p1 = []

print("Standard MLP training metrics:")
for epoch in range(epochs):
    # Training Standard MLP Model
    mlp_train_loss = train_one_epoch(mlp, train_loader_04, optimizer_mlp, criterion, device)
    mlp_test_loss, mlp_test_accuracy = evaluate_model(mlp, test_loader_04, criterion, device)
    print(f"    Epoch: {epoch + 1}: train_loss={mlp_train_loss:.4f}, test_loss={mlp_test_loss:.4f}, "
        f"test_accuracy={mlp_test_accuracy:.2f}%")

    # Update MLP logs
    mlp_train_loss_04_p1.append(mlp_train_loss)
    mlp_test_loss_04_p1.append(mlp_test_loss)
    mlp_test_accuracy_04_p1.append(mlp_test_accuracy)

print("\nCMS training metrics:")
for epoch in range(epochs):
    # Training CMS Model:
    cms_train_loss, batch_counter = train_one_epoch_cms(
        cms, train_loader_04, opt_fast, opt_slow, chunk_size=chunk_size,
        criterion=criterion, device=device, start_batch_idx=batch_counter,
        slow_step_log=slow_step_log
    )

    cms_test_loss, cms_test_accuracy = evaluate_model(cms, test_loader_04, criterion, device)
    print(f"    Epoch: {epoch + 1}: train_loss={cms_train_loss:.4f}, test_loss={cms_test_loss:.4f}, "
        f"test_accuracy={cms_test_accuracy:.2f}%")

    # Update CMS logs
    cms_train_loss_04_p1.append(cms_train_loss)
    cms_test_loss_04_p1.append(cms_test_loss)
    cms_test_accuracy_04_p1.append(cms_test_accuracy)

# Evaluating both models on digits 5-9
test_loader_59 = get_mnist_dataloader(digits=[5,6,7,8,9], train=False, batch_size=64)

# Final accuracies for MLP and CMS models
mlp_final_loss_04_p1, mlp_final_acc_04_p1 = evaluate_model(mlp, test_loader_04, criterion, device)
cms_final_loss_04_p1, cms_final_acc_04_p1 = evaluate_model(cms, test_loader_04, criterion, device)
mlp_final_loss_59_p1, mlp_final_acc_59_p1 = evaluate_model(mlp, test_loader_59, criterion, device)
cms_final_loss_59_p1, cms_final_acc_59_p1 = evaluate_model(cms, test_loader_59, criterion, device)

print(f"\nPhase 1 endpoint, evaluated on 0-4:")
print(f"  MLP: {mlp_final_acc_04_p1:.2f}%")
print(f"  CMS: {cms_final_acc_04_p1:.2f}%")
print(f"\nPhase 1 endpoint, evaluated on 5-9:")
print(f"  MLP: {mlp_final_acc_59_p1:.2f}%")
print(f"  CMS: {cms_final_acc_59_p1:.2f}%")
Standard MLP training metrics:
    Epoch: 1: train_loss=0.1189, test_loss=0.0427, test_accuracy=98.70%
    Epoch: 2: train_loss=0.0420, test_loss=0.0229, test_accuracy=99.30%
    Epoch: 3: train_loss=0.0260, test_loss=0.0375, test_accuracy=98.77%
    Epoch: 4: train_loss=0.0208, test_loss=0.0297, test_accuracy=99.12%
    Epoch: 5: train_loss=0.0140, test_loss=0.0244, test_accuracy=99.32%

CMS training metrics:
    Epoch: 1: train_loss=0.2262, test_loss=0.0582, test_accuracy=98.15%
    Epoch: 2: train_loss=0.0643, test_loss=0.0402, test_accuracy=98.56%
    Epoch: 3: train_loss=0.0415, test_loss=0.0331, test_accuracy=99.05%
    Epoch: 4: train_loss=0.0280, test_loss=0.0306, test_accuracy=99.14%
    Epoch: 5: train_loss=0.0204, test_loss=0.0299, test_accuracy=99.09%

Phase 1 endpoint, evaluated on 0-4:
  MLP: 99.32%
  CMS: 99.09%

Phase 1 endpoint, evaluated on 5-9:
  MLP: 0.00%
  CMS: 0.00%

- Plot of Learning Curve on Digits 0–4 (CMSModelV2)

plot_phase1_curve(
    [1,2,3,4,5],
    mlp_test_accuracy_04_p1,
    cms_test_accuracy_04_p1
)

Analysis (Phase 1 Learning Curve — CMSModelV2)

Both models demonstrate strong learning performance on digits 0–4, reaching approximately 99% accuracy within five epochs. The StandardMLP shows a slightly smoother and more consistent upward trend, while CMSModelV2 starts lower but quickly catches up by the third epoch.

The gap between the two models remains small throughout training (within ~0.2–0.3%), indicating that the chained CMS architecture does not significantly impact learning capability on a single-task setting. Minor fluctuations in both curves are expected due to stochastic training dynamics.

Overall, CMSModelV2 achieves comparable performance to the baseline, confirming that the architectural change does not degrade standard supervised learning and provides a fair starting point for evaluating continual learning behavior in Phase 2.

6.2 Phase 2: Continual Learning on Digits 5–9 (V2)

The structure mirrors Experiment 1: 5 epochs of training on digits 5–9 with no rehearsal of digits 0–4, evaluating both stability and plasticity at every epoch.

The interesting comparison here is not between Phase 1 and Phase 2 within Experiment 2 (we already understand what catastrophic forgetting looks like from Experiment 1), but between Experiment 2's V2 results and Experiment 1's V1 results. Specifically: does the chained composition produce meaningfully different per-epoch stability and plasticity curves than the parallel mixing did? Does V2 retain *any* accuracy on digits 0–4 where V1 did not?

We will examine these questions in detail using the confusion matrices below. For now, the per-epoch printouts give us a first read on whether the architectural change has produced any qualitatively different training dynamics.

# ===============
# === PHASE 2 ===
# ===============

# === Training & Evaluation (digits 5-9): ===

train_loader_59 = get_mnist_dataloader([5,6,7,8,9], train=True, batch_size=64)

# Digits 0-4 metrics
mlp_test_loss_04_p2 = [mlp_final_loss_04_p1]
mlp_test_accuracy_04_p2 = [mlp_final_acc_04_p1]
cms_test_loss_04_p2 = [cms_final_loss_04_p1]
cms_test_accuracy_04_p2 = [cms_final_acc_04_p1]

# Digits 5-9 metrics
mlp_train_loss_59_p2 = []
mlp_test_loss_59_p2 = [mlp_final_loss_59_p1]
mlp_test_accuracy_59_p2 = [mlp_final_acc_59_p1]
cms_train_loss_59_p2 = []
cms_test_loss_59_p2 = [cms_final_loss_59_p1]
cms_test_accuracy_59_p2 = [cms_final_acc_59_p1]

print("Standard MLP training metrics:")
for epoch in range(epochs):
    # Retraining Standard MLP model:
    mlp_train_loss = train_one_epoch(mlp, train_loader_59, optimizer_mlp, criterion, device)

    # Two evaluations per epoch, one per digit group
    mlp_test_loss_04, mlp_test_accuracy_04 = evaluate_model(mlp, test_loader_04, criterion, device)
    mlp_test_loss_59, mlp_test_accuracy_59 = evaluate_model(mlp, test_loader_59, criterion, device)

    print(f"    Epoch: {epoch + 1}: train_loss={mlp_train_loss:.4f}, "
        f"acc_04={mlp_test_accuracy_04:.2f}%, acc_59={mlp_test_accuracy_59:.2f}%")

    # Update MLP logs
    mlp_test_loss_04_p2.append(mlp_test_loss_04)
    mlp_test_accuracy_04_p2.append(mlp_test_accuracy_04)

    mlp_train_loss_59_p2.append(mlp_train_loss)
    mlp_test_loss_59_p2.append(mlp_test_loss_59)
    mlp_test_accuracy_59_p2.append(mlp_test_accuracy_59)

print("\nCMS training metrics:")
for epoch in range(epochs):
    # Retraining CMS Model:
    cms_train_loss, batch_counter = train_one_epoch_cms(
        cms, train_loader_59, opt_fast, opt_slow, chunk_size=chunk_size,
        criterion=criterion, device=device, start_batch_idx=batch_counter,
        slow_step_log=slow_step_log
    )
    # Two evaluations per epoch, one per digit group
    cms_test_loss_04, cms_test_accuracy_04 = evaluate_model(cms, test_loader_04, criterion, device)
    cms_test_loss_59, cms_test_accuracy_59 = evaluate_model(cms, test_loader_59, criterion, device)

    print(f"    Epoch: {epoch + 1}: train_loss={cms_train_loss:.4f}, "
      f"acc_04={cms_test_accuracy_04:.2f}%, acc_59={cms_test_accuracy_59:.2f}%")

    # Update CMS logs
    cms_test_loss_04_p2.append(cms_test_loss_04)
    cms_test_accuracy_04_p2.append(cms_test_accuracy_04)

    cms_train_loss_59_p2.append(cms_train_loss)
    cms_test_loss_59_p2.append(cms_test_loss_59)
    cms_test_accuracy_59_p2.append(cms_test_accuracy_59)

# Final accuracies for MLP and CMS models
mlp_final_loss_04_p2, mlp_final_acc_04_p2 = evaluate_model(mlp, test_loader_04, criterion, device)
cms_final_loss_04_p2, cms_final_acc_04_p2 = evaluate_model(cms, test_loader_04, criterion, device)
mlp_final_loss_59_p2, mlp_final_acc_59_p2 = evaluate_model(mlp, test_loader_59, criterion, device)
cms_final_loss_59_p2, cms_final_acc_59_p2 = evaluate_model(cms, test_loader_59, criterion, device)

mlp_acc_change_04 = mlp_final_acc_04_p2 - mlp_final_acc_04_p1
mlp_acc_change_59 = mlp_final_acc_59_p2 - mlp_final_acc_59_p1
cms_acc_change_04 = cms_final_acc_04_p2 - cms_final_acc_04_p1
cms_acc_change_59 = cms_final_acc_59_p2 - cms_final_acc_59_p1

print(f"\nSlow steps fired at batches: {slow_step_log}")
print(f"Total slow steps across both phases: {len(slow_step_log)}")

print("\nPhase 1 --> Phase 2 Summary:")
print(f"  MLP: 0-4 accuracy: {mlp_final_acc_04_p1:.2f}% --> {mlp_final_acc_04_p2:.2f}% (Δ = {mlp_acc_change_04:+.2f})")
print(f"       5-9 accuracy: {mlp_final_acc_59_p1:.2f}% --> {mlp_final_acc_59_p2:.2f}% (Δ = {mlp_acc_change_59:+.2f})")
print(f"  CMS: 0-4 accuracy: {cms_final_acc_04_p1:.2f}% --> {cms_final_acc_04_p2:.2f}% (Δ = {cms_acc_change_04:+.2f})")
print(f"       5-9 accuracy: {cms_final_acc_59_p1:.2f}% --> {cms_final_acc_59_p2:.2f}% (Δ = {cms_acc_change_59:+.2f})")
Standard MLP training metrics:
    Epoch: 1: train_loss=0.2730, acc_04=0.00%, acc_59=96.96%
    Epoch: 2: train_loss=0.0642, acc_04=0.00%, acc_59=98.05%
    Epoch: 3: train_loss=0.0450, acc_04=0.00%, acc_59=97.84%
    Epoch: 4: train_loss=0.0326, acc_04=0.00%, acc_59=98.03%
    Epoch: 5: train_loss=0.0260, acc_04=0.00%, acc_59=98.21%

CMS training metrics:
    Epoch: 1: train_loss=0.4974, acc_04=0.00%, acc_59=95.70%
    Epoch: 2: train_loss=0.1068, acc_04=0.00%, acc_59=96.34%
    Epoch: 3: train_loss=0.0764, acc_04=0.00%, acc_59=96.75%
    Epoch: 4: train_loss=0.0567, acc_04=0.00%, acc_59=97.20%
    Epoch: 5: train_loss=0.0447, acc_04=0.00%, acc_59=97.35%

Slow steps fired at batches: [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750, 1800, 1850, 1900, 1950, 2000, 2050, 2100, 2150, 2200, 2250, 2300, 2350, 2400, 2450, 2500, 2550, 2600, 2650, 2700, 2750, 2800, 2850, 2900, 2950, 3000, 3050, 3100, 3150, 3200, 3250, 3300, 3350, 3400, 3450, 3500, 3550, 3600, 3650, 3700, 3750, 3800, 3850, 3900, 3950, 4000, 4050, 4100, 4150, 4200, 4250, 4300, 4350, 4400, 4450, 4500, 4550, 4600, 4650]
Total slow steps across both phases: 93

Phase 1 --> Phase 2 Summary:
  MLP: 0-4 accuracy: 99.32% --> 0.00% (Δ = -99.32)
       5-9 accuracy: 0.00% --> 98.21% (Δ = +98.21)
  CMS: 0-4 accuracy: 99.09% --> 0.00% (Δ = -99.09)
       5-9 accuracy: 0.00% --> 97.35% (Δ = +97.35)

- Plot of Continual Learning on Digits 5–9 (CMSModelV2)

plot_phase2_curve(
    phase2_epochs,
    mlp_test_accuracy_04_p2,
    mlp_test_accuracy_59_p2,
    cms_test_accuracy_04_p2,
    cms_test_accuracy_59_p2
)

Analysis (Phase 2 Stability vs Plasticity — CMSModelV2)

The plot clearly shows the stability–plasticity tradeoff during Phase 2.

At epoch 0 (before retraining), both models retain near-perfect accuracy on digits 0–4 and have 0% accuracy on digits 5–9. Immediately after the first epoch of retraining, accuracy on digits 0–4 collapses to 0% for both models and remains there for the rest of training. This indicates complete catastrophic forgetting with no partial retention.

At the same time, both models rapidly learn the new task. Accuracy on digits 5–9 jumps to around 95–97% after the first epoch and continues to stabilize near 98%. This demonstrates strong plasticity.

Importantly, the CMSModelV2 follows almost exactly the same trajectory as the StandardMLP. There is no observable delay in forgetting, no residual accuracy on digits 0–4, and no improvement in the stability–plasticity tradeoff.

Overall, the chained composition in V2 does not produce a qualitatively different behavior from V1. The model still exhibits immediate forgetting and rapid adaptation, suggesting that the CMS architecture, even in its chained form, does not provide stability in this setting.

6.3 Confusion matrices: Diagnosing what happened

Following the same diagnostic procedure as Experiment 1, we generate confusion matrices, prediction distributions, and per-class accuracy breakdowns for V2. The reading framework is identical: matrices reveal *which* class each prediction lands on, prediction distributions quantify output-space collapse explicitly, and per-class accuracy makes asymmetric collapse visible across the full 0–9 label space.

The same three diagnostic questions apply.

# =================================
#    Full 0-9 Confusion Matrices
# =================================

# Build a test loader that includes all digits 0–9
test_loader_09 = get_mnist_dataloader(digits=list(range(10)), train=False, batch_size=64)

all_classes = list(range(10))

# === Combined-task confusion matrices ===
plot_confusion_matrix_for_model(
    mlp, test_loader_09, device, all_classes,
    title="Standard MLP — Phase 2 — All digits 0–9"
)
plot_confusion_matrix_for_model(
    cms, test_loader_09, device, all_classes,
    title="CMS Model (V2) — Phase 2 — All digits 0–9"
)

Prediction distribution: where do predictions on digits 0–4 actually land?

Same diagnostic as Experiment 1. We report each model's full per-class prediction distribution on the digits 0–4 test set, plus the fraction of predictions falling into the 0–4 vs. 5–9 ranges.

prediction_distribution(mlp, test_loader_04, device, "Standard MLP", "digits 0–4")
prediction_distribution(cms, test_loader_04, device, "CMS Model (V2)",   "digits 0–4")
=== Standard MLP — evaluated on digits 0–4 ===
Total samples: 5139
Prediction distribution (which class did the model output?):
  predicted class 5:   827  (16.09%)
  predicted class 6:  1133  (22.05%)
  predicted class 7:   937  (18.23%)
  predicted class 8:  1358  (26.43%)
  predicted class 9:   884  (17.20%)
  --> predictions in 0–4 range: 0 (0.00%)
  --> predictions in 5–9 range: 5139 (100.00%)

=== CMS Model (V2) — evaluated on digits 0–4 ===
Total samples: 5139
Prediction distribution (which class did the model output?):
  predicted class 5:  1086  (21.13%)
  predicted class 6:   642  (12.49%)
  predicted class 7:   550  (10.70%)
  predicted class 8:  1695  (32.98%)
  predicted class 9:  1166  (22.69%)
  --> predictions in 0–4 range: 0 (0.00%)
  --> predictions in 5–9 range: 5139 (100.00%)

Per-class accuracy across all 10 classes.

We evaluate both models on the full 0–9 test set and report per-class accuracy, paralleling Experiment 1.

overall_accuracy_breakdown(mlp, test_loader_09, device, "Standard MLP")
overall_accuracy_breakdown(cms, test_loader_09, device, "CMS Model (V2)")
=== Standard MLP — full 0–9 evaluation ===
Overall accuracy: 47.74% (4774/10000)
Per-class accuracy:
  class 0:     0/  980 (  0.00%)
  class 1:     0/ 1135 (  0.00%)
  class 2:     0/ 1032 (  0.00%)
  class 3:     0/ 1010 (  0.00%)
  class 4:     0/  982 (  0.00%)
  class 5:   872/  892 ( 97.76%)
  class 6:   949/  958 ( 99.06%)
  class 7:  1013/ 1028 ( 98.54%)
  class 8:   964/  974 ( 98.97%)
  class 9:   976/ 1009 ( 96.73%)

=== CMS Model (V2) — full 0–9 evaluation ===
Overall accuracy: 47.32% (4732/10000)
Per-class accuracy:
  class 0:     0/  980 (  0.00%)
  class 1:     0/ 1135 (  0.00%)
  class 2:     0/ 1032 (  0.00%)
  class 3:     0/ 1010 (  0.00%)
  class 4:     0/  982 (  0.00%)
  class 5:   868/  892 ( 97.31%)
  class 6:   939/  958 ( 98.02%)
  class 7:  1005/ 1028 ( 97.76%)
  class 8:   946/  974 ( 97.13%)
  class 9:   974/ 1009 ( 96.53%)

What the diagnostics reveal

Returning to the three questions:

1. Did V2 retain any ability to predict digits 0–4? No. Like V1, V2 produces complete output-space collapse — 100.00% of predictions on the digits 0–4 test set land in the 5–9 range, with empty columns 0–4 in the matrix. This holds despite V2's slow component sitting directly at the classification head, exactly where Experiment 1 identified the failure as being concentrated. The targeted architectural intervention did not produce stability.

2. Does the structure of misclassifications match Experiment 1? Yes. The same visual-similarity mappings dominate the off-diagonal entries (true 4s → 9s, true 1s → 7s or 8s, true 3s → 5s). Phase 1's feature extractor survived Phase 2 in V2 just as it did in V1; the failure is again in the classification head's class assignments, not in feature extraction.

3. Does V2's matrix look meaningfully different from V1's? Marginally. The two matrices differ in *which* surviving 5–9 class each error gets routed to, but the overall shape, magnitudes, and dead-column structure are essentially the same. Architectural variation without functional difference.

Cross-experiment synthesis. Across two CMS interpretations — parallel mixing in V1 and chained composition in V2 — and against the standard MLP baseline, all four model runs reach the same Phase 2 endpoint:

| Model | Phase 1 acc on 0–4 | Phase 2 acc on 0–4 | Phase 2 acc on 5–9 | |---|---|---|---| | Standard MLP (Exp. 1) | 99.16% | 0.00% | 98.03% | | CMS V1 (Exp. 1) | 99.24% | 0.00% | 97.26% | | Standard MLP (Exp. 2) | 99.32% | 0.00% | 98.21% | | CMS V2 (Exp. 2) | 99.09% | 0.00% | 97.35% |

Two independent runs with two distinct CMS implementations, against two independently-initialized MLP baselines, all converge on the same outcome: the CMS does not provide a stability advantage over the standard MLP in this setup.

A careful interpretation of this finding. It would be a mistake to read this as "the CMS doesn't work" or "the *Nested Learning* paper's claims are wrong." Our experiment is a deliberately minimal CPU-scale instantiation that simplifies the paper's setup in several ways:

What our experiment *does* establish, within these limitations, is that the multi-frequency update mechanism on its own — without the rest of the HOPE configuration, without task structures favorable to slow integration, and without per-architecture hyperparameter tuning — is not sufficient to defend against catastrophic forgetting at this scale. The slow component slows down *how fast* parameters drift in response to new-task gradients, but it does not change the *direction* those gradients push the parameters. Across 5 epochs of disjoint-label training, that distinction matters: the slow component still drifts to favor the new task, just more gradually, and the eventual endpoint is the same as the fast component's endpoint.

This is a meaningful observation about the paper's first contribution. Architecture-only stability isn't "free" — it requires either (a) supporting mechanisms that explicitly resist parameter drift in a defended direction, (b) task structures where the slow-frequency timescale matches the rate of distribution shift, or (c) integration with replay or regularization methods that change the gradient signal itself. The CMS in §7.1 is the first of three contributions in *Nested Learning*; our experiment suggests it works *alongside* the other contributions, not on its own.

7. Discussion and Future Work

This project explored the Nested Learning paradigm through the implementation of CMSModelV1 and CMSModelV2. Unlike traditional feedforward architectures that rely on a single optimization pathway, these models attempt to separate fast and slow learning components. This approach draws inspiration from biological systems, where short-term and long-term memory processes interact across different time scales rather than being updated uniformly.

The results showed that CMSModelV1 and CMSModelV2 did not prevent catastrophic forgetting in the class-incremental MNIST setting. After retraining on digits 5–9, both CMS models collapsed to 0.0% accuracy on digits 0–4, identical to the StandardMLP baseline. In this minimal working example, the slow component failed to preserve previously learned information, and there was no evidence that chained memory composition improved retention over the simpler baseline. This suggests that, at this scale, architecture-only memory separation mechanisms were not sufficient to mitigate catastrophic forgetting.

Architectural changes and adjustments to update frequency produced no meaningful differences in performance. All models (CMSModelV1, CMSModelV2, and StandardMLP) converged in Phase 1 in roughly the same number of epochs. Rather than revealing optimization instability, this negative result indicates that simply introducing nested memory components without stronger learning constraints is insufficient for continual learning benefits. Preserving knowledge in this setting likely requires more than structural separation alone and may depend on explicit memory-preservation objectives or improved optimization strategies.

Limitations

One major limitation of this project is that the implementation represents a simplified version of the full Nested Learning framework proposed by Behrouz et al. (2025). Due to time and computational constraints, the full experimental setup described in the original paper could not be reproduced. Instead, the focus was placed on capturing the core CMS-inspired architecture and validating its behavior in a smaller-scale continual learning setting.

Our evaluation focused specifically on class-incremental MNIST, a vision classification task. The original paper evaluates CMS across a broader range of tasks, including continual language learning, in-context question answering, and long-context reasoning. As a result, the conclusions from this project apply only to the class-incremental vision setting and cannot be generalized to the broader domains explored in the full framework.

Hyperparameter exploration was also limited. Nested Learning introduces additional design decisions beyond standard deep learning models, including memory hierarchy depth, update schedules, and cross-level optimization behavior. A more exhaustive search across these parameters would allow the architecture’s behavior to be characterized more precisely under different settings.

Future Work

Future work should focus on scaling the continual learning setup used in this project. Testing CMS-inspired architectures with more classes, additional training phases, and larger continual learning datasets would help determine whether the observed collapse is specific to this minimal example or reflects a broader limitation of the architecture. Expanding beyond the 0–4 and 5–9 split would provide clearer insights.

Additional ablation studies would strengthen the analysis. Separately measuring the contribution of each memory level, update frequency, and chaining mechanism would improve interpretability and help identify which components of the CMS design are useful or require revision.

Another important direction is integrating stronger continual learning objectives beyond architecture alone. Regularization methods, replay mechanisms, or explicit parameter protection strategies could be combined with CMS-style memory separation to test whether hierarchical memory is more effective when paired with direct forgetting-prevention techniques.

Ultimately, this experiment leaves open the question of whether multi-timescale memory mechanisms can reliably defend against catastrophic forgetting. Our results did not provide strong evidence that CMSModelV1 or CMSModelV2 improved retention over a standard MLP in this setting, but they also do not fully refute the broader Nested Learning framework. The promise of multi-timescale memory may depend heavily on scale, task complexity, and the interaction between architecture and optimization. Further investigation is needed before strong conclusions can be drawn about its practical effectiveness.


References

[Primary Source] Behrouz, A., Razaviyayn, M., Zhong, P., and Mirrokni, V. "Nested Learning: The Illusion of Deep Learning Architecture." *arXiv preprint arXiv:2512.24695* (2024).

[Neuroscience] Buzsaki, G. and Draguhn, A. "Neuronal oscillations in cortical networks." *Science* 304.5679 (2004), pp. 1926–1929.

[Neuroscience] Diekelmann, S. and Born, J. "The memory function of sleep." *Nature Reviews Neuroscience* 11.2 (2010), pp. 114–126.

[Adam Optimizer] Kingma, D.P. and Ba, J. "Adam: A method for stochastic optimization." *arXiv preprint arXiv:1412.6980* (2014).

[Continual Learning] Kirkpatrick, J., Pascanu, R., Rabinowitz, N., et al. "Overcoming catastrophic forgetting in neural networks." *Proceedings of the National Academy of Sciences* 114.13 (2017), pp. 3521–3526.

[Backpropagation] Rumelhart, D.E., Hinton, G.E., and Williams, R.J. "Learning representations by back-propagating errors." *Nature* 323.6088 (1986), pp. 533–536.