4️⃣ Superposition & Deep Double Descent
Learning Objectives
- Understand and characterise the deep double descent phenomenon
- Relate the different phases of double descent to the idea of superposition
- Practice replicating results from a paper in a more unguided way
Note - this is less of a structured exercise set, and more of a guided replication. If you're interested in improving your ability to replicate papers (especially those concerning toy models and some low level maths & ML) then we recommend you try them. If you're more interested in moving through exercise sets with fast feedback loops & learning all you can about superposition & SAEs, then you might just want to read the key results from this section (or skip it altogether).
For this suggested replication, we'll look at the Anthropic paper on Double Descent & superposition. This paper ties the phenomena of double descent to models of superposition. The theory posed by this paper goes roughly as follows:
- Initially, the model learns a memorising solution where datapoints are represented in superposition. This doesn't generalize, so we get low training loss but high test loss.
- Later, the model learns a generalizing solution where features are learned and represented in superposition. This generalizes, so we get low training loss and low test loss.
- The spike in loss between these two happens when the model transitions between the memorising and generalizing solutions.

What does it mean to represent datapoints in superposition? If you've done the exercises on correlated / anticorrelated features in an earlier section, you'll know that anticorrelated features are easier to represent in superposition because they don't interfere with each other. This is especially true if features aren't just anticorrelated but are mutually exclusive. From the Anthropic paper:
Consider the case of a language model which verbatim memorizes text. How can it do this? One naive idea is that it might use neurons to create a lookup table mapping sequences to arbitrary continuations. For every sequence of tokens it wishes to memorize, it could dedicate one neuron to detecting that sequence, and then implement arbitrary behavior when it fires. The problem with this approach is that it's extremely inefficient – but it seems like a perfect candidate for superposition, since each case is mutually exclusive and can't interfere.
We'll study this theory in the context of a toy model. Specifically, we'll use the toy model that we worked with in the first section of these exercises, but we'll train it in a very particular way: by generating a random batch of data, and then using that same batch for the entire training process. Since the model only ever sees this one batch, the batch is the whole training set, so we'll call its size the data size. We'll see what happens when the data size changes, but the number of features stays the same. According to our theory, the model should represent datapoints in superposition when the data size is smaller than the number of features, and it should represent features in superposition when the data size is larger than the number of features.
Rather than giving you a set of exercises to complete, we're leaving this section open-ended. You should consider it more as a paper replication than a set of structured exercises. However, we will give you a few tips:
- Rather than using the Adam optimizer, the paper recommends AdamW, with a default weight decay of
WEIGHT_DECAY = 1e-2.- Weight decay constrains the norm of weights, so that they don't grow too large. With no weight decay, we could in theory memorize an arbitrarily large number of datapoints and represent them evenly spaced around the unit circle; then we can perfectly reconstruct them as long as we have a large enough weight vector to project them onto.
- The paper uses a learning rate schedule consisting of a linear warmup over 2500 steps (i.e. we increase the learning rate linearly from zero up to
1e-3), followed by cosine decay until the end of training at 50,000 steps. We use the same schedule shape but a much shorter run:NUM_WARMUP_STEPS = 200andNUM_BATCH_UPDATES = 8000, with a higher peak learning rate ofLEARNING_RATE = 3e-3. - The paper uses 10,000 features with sparsity 0.999. Marius Hobbhahn's replication used 1,000 features with sparsity 0.99, and we go smaller again:
N_FEATURES = 400withSPARSITY = 0.975. All three keep about 10 nonzero features per datapoint on average, which matters: if you shrink the number of features without lowering the sparsity, most datapoints have only 0-2 nonzero features and the pattern disappears. The transition between the two regimes happens at a data size that scales with the number of features (around 300-500 for 1,000 features, around 100-200 for 400 features), so our data sizes only go up to 500. You should still see fundamentally the same patterns. - When generating the batch of data, you should normalize it (so each vector for a given batch index & instance has unit norm). The rest of the data generation process should be the same as in the first section of this notebook.
- Technically you only need one instance per data size. However, we recommend using a few (e.g. 5-10) so you can pick the instance with lowest loss at the end of training. This is because (thanks to our best friend randomness) not all instances will necessarily learn the optimal solution. In our implementation (code below), we rewrite the
optimizefunction to return a list of(batch_inst, W_inst)pairs at the end, one per data size, wherebatch_instis the batch of the instance which had the lowest loss by the end of training, andW_instare the learned weights for that same instance. This is precisely the data you'll need to make the 2D feature plots featured in the paper. - You don't need a separate training run for each data size. Our models are tiny, so most of the time in a training step goes on overhead rather than computation, and it's much faster to train many data sizes at once in a single model, using the instance dimension: give each data size its own block of instances. Each instance's batch gets padded with zeros up to the largest data size, and you mask the padding out of the loss (otherwise the zero rows would count as datapoints too). Padding is wasted work, so it's worth splitting the data sizes into a couple of groups (e.g. up to 100, and above 100), each trained as its own model.
- You can repurpose the function to calculate dimensionality from the section on feature geometry. See the paper for a discussion of a generalized dimensionality function, which doesn't just measure dimensionality of features, but also of datapoints.
To get you started, here are some constants which you might find useful:
NUM_WARMUP_STEPS = 200
NUM_BATCH_UPDATES = 8000
WEIGHT_DECAY = 1e-2
LEARNING_RATE = 3e-3
DATA_SIZES = [3, 4, 5, 6, 8, 10, 15, 20, 30, 50, 100, 200, 300, 500]
N_FEATURES = 400
N_INSTANCES = 10 # per data size
D_HIDDEN = 2
SPARSITY = 0.975
FEATURE_PROBABILITY = 1 - SPARSITY
Also, if you want some help with the visualisation, the code below will produce the 2D feature visualisations like those found at the bottom of this figure, for all data sizes stacked horizontally, assuming:
features_listis a list of detachedW-matrices for single instances, i.e. each has shape(2, n_features)(these will be used to produce the blue plots on the first row)hidden_representations_listis a list of the projections of our batch of data onto the hidden directions of that same instance, i.e. each has shape(2, data_size)(these will be used to produce the red plots on the second row)
A demonstration is given below (the values are meaningless, they've just been randomly generated to illustrate how to use this function).
features_list = [t.randn(size=(2, 100)) for _ in DATA_SIZES]
hidden_representations_list = [t.randn(size=(2, data_size)) for data_size in DATA_SIZES]
utils.plot_features_in_2d(
features_list + hidden_representations_list,
colors=[["blue"] for _ in range(len(DATA_SIZES))] + [["red"] for _ in range(len(DATA_SIZES))],
title="Double Descent & Superposition (num features = 100, n = data size)",
subplot_titles=[f"Features (n={ds})" for ds in DATA_SIZES] + [f"Datapoints (n={ds})" for ds in DATA_SIZES],
allow_different_limits_across_subplots=True,
n_rows=2,
)
We've provided an implementation below, although we recommend that you give it a go yourself first before looking at too much of the code. You can use the different dropdowns to get different degrees of hints, if you're struggling. Our solution trains all the data sizes in under half a minute on a GPU.
# YOUR CODE HERE - replicate the results from the Superposition & Deep Double Descent paper!
The first 4 hints give you specific bits of code, if there's any particular part of the implementation you're struggling with:
Hint (basic setup code)
Basic imports and constants:
import math
from typing import Any
import pandas as pd
import plotly.express as px
NUM_WARMUP_STEPS = 200
NUM_BATCH_UPDATES = 8000
WEIGHT_DECAY = 1e-2
LEARNING_RATE = 3e-3
DATA_SIZES = [3, 4, 5, 6, 8, 10, 15, 20, 30, 50, 100, 200, 300, 500]
N_FEATURES = 400
N_INSTANCES = 10 # per data size
D_HIDDEN = 2
SPARSITY = 0.975
FEATURE_PROBABILITY = 1 - SPARSITY
Our new schedulers, in line with Anthropic's writeup (but shorter):
def linear_warmup_lr(step, steps):
"""Increases linearly from 0 to 1."""
return step / steps
def anthropic_lr(step, steps):
"""As in the paper (but shorter): linear warmup for NUM_WARMUP_STEPS steps, then cosine decay to zero."""
if step < NUM_WARMUP_STEPS:
return linear_warmup_lr(step, NUM_WARMUP_STEPS)
else:
return cosine_decay_lr(step - NUM_WARMUP_STEPS, steps - NUM_WARMUP_STEPS)
Hint (code for new version of ToyModel class)
class DoubleDescentModel(ToyModel):
W: Float[Tensor, "inst d_hidden feats"]
b_final: Float[Tensor, "inst feats"]
# Our linear map (for a single instance) is x -> ReLU(W.T @ W @ x + b_final)
# We train every data size at once: the instance dimension holds `N_INSTANCES` instances for each
# data size (instance `i` is trained on a dataset of size `self.inst_data_size[i]`). Every
# instance's batch is padded with zeros up to the largest data size, and the padding is masked
# out of the loss.
def __init__(self, cfg: ToyModelConfig, data_sizes: list[int], feature_probability: float, device=device):
super().__init__(cfg, feature_probability=feature_probability, device=device)
assert cfg.n_inst % len(data_sizes) == 0, "Need the same number of instances for each data size"
self.data_sizes = data_sizes
self.n_inst_per_data_size = cfg.n_inst // len(data_sizes)
self.inst_data_size = t.tensor(data_sizes, device=device).repeat_interleave(self.n_inst_per_data_size)
# mask[b, i] = 1 if row b is a real datapoint for instance i, 0 if it's padding
self.mask = (t.arange(max(data_sizes), device=device)[:, None] < self.inst_data_size).float()
@classmethod
def dimensionality(cls, data: Float[Tensor, "... batch d_hidden"]) -> Float[Tensor, "... batch"]:
"""
Calculates dimensionalities of data. Assumes data is of shape ... batch d_hidden, i.e. if
it's 2D then it's a batch of vectors of length `d_hidden` and we return the dimensionality
as a 1D tensor of length `batch`. If it has more dimensions at the start, we assume this
means separate calculations for each of these dimensions (i.e. they are independent batches
of vectors).
"""
# Compute the norms of each vector (this will be the numerator)
squared_norms = einops.reduce(data.pow(2), "... batch d_hidden -> ... batch", "sum")
# Compute the denominator (i.e. get the dot product then sum over j)
data_normed = data / data.norm(dim=-1, keepdim=True)
interference = einops.einsum(
data_normed, data, "... batch_i d_hidden, ... batch_j d_hidden -> ... batch_i batch_j"
)
polysemanticity = einops.reduce(interference.pow(2), "... batch_i batch_j -> ... batch_i", "sum")
assert squared_norms.shape == polysemanticity.shape
return squared_norms / polysemanticity
def generate_batch(self) -> Float[Tensor, "batch inst feats"]:
"""
Generates each instance's (normalized) dataset, padded with zeros up to the largest data size.
"""
# Get batch from prev method
batch = super().generate_batch(max(self.data_sizes))
# Normalize the batch (i.e. so each vector for a particular batch & instance has norm 1)
# (need to be careful about vectors with norm zero)
norms = batch.norm(dim=-1, keepdim=True)
norms = t.where(norms.abs() < 1e-6, t.ones_like(norms), norms)
batch_normed = batch / norms
# Zero out the padding rows
return batch_normed * self.mask[..., None]
def calculate_loss(
self,
out: Float[Tensor, "batch inst feats"],
batch: Float[Tensor, "batch inst feats"],
per_inst: bool = False,
) -> Float[Tensor, " inst"]:
"""
New function to calculate loss: it ignores padding rows, and has a "loss per instance" option
so we can find the best instance at the end of our optimization.
"""
error = self.importance * ((batch - out) ** 2)
error = einops.reduce(error, "batch inst feats -> batch inst", "mean") * self.mask
loss = error.sum(0) / self.inst_data_size # mean over each instance's real datapoints
return loss if per_inst else loss.sum()
def optimize(
self,
steps: int = NUM_BATCH_UPDATES,
log_freq: int = 100,
lr: float = LEARNING_RATE,
lr_scale: Callable[[int, int], float] = anthropic_lr,
weight_decay: float = WEIGHT_DECAY,
) -> list[tuple[Tensor, Tensor]]:
"""
Trains all instances, then returns `(batch, W)` for the best instance of each data size.
"""
optimizer = t.optim.AdamW(list(self.parameters()), lr=lr, weight_decay=weight_decay)
progress_bar = tqdm(range(steps))
# Same batch for each step
batch = self.generate_batch() # [max_data_size inst n_features]
for step in progress_bar:
# Update learning rate
step_lr = lr * lr_scale(step, steps)
for group in optimizer.param_groups:
group["lr"] = step_lr
# Optimize
optimizer.zero_grad()
out = self.forward(batch)
loss = self.calculate_loss(out, batch)
loss.backward()
optimizer.step()
# Display progress bar
if (step % log_freq == 0) or (step + 1 == steps):
progress_bar.set_postfix(loss=loss.item() / self.cfg.n_inst, lr=step_lr)
# For each data size, pick out the instance with the lowest loss
with t.inference_mode():
out = self.forward(batch)
loss_per_inst = self.calculate_loss(out, batch, per_inst=True)
best_insts = loss_per_inst.view(len(self.data_sizes), -1).argmin(-1)
results = []
for k, (data_size, best_inst) in enumerate(zip(self.data_sizes, best_insts.tolist())):
inst = k * self.n_inst_per_data_size + best_inst
results.append((batch[:data_size, inst], self.W[inst].detach()))
return results
Hint (code to train models & replicate 2D feature plots)
# One model for the small data sizes and one for the large ones, with N_INSTANCES instances for each
# data size. (Each model pads its batches up to its own largest data size, so splitting them avoids
# padding the small data sizes all the way up to 500.) Optimize, and get the best batch & weight
# matrix for each data size
results = []
for data_sizes in [[ds for ds in DATA_SIZES if ds <= 100], [ds for ds in DATA_SIZES if ds > 100]]:
cfg = ToyModelConfig(n_features=N_FEATURES, n_inst=len(data_sizes) * N_INSTANCES, d_hidden=D_HIDDEN)
model = DoubleDescentModel(cfg, data_sizes=data_sizes, feature_probability=FEATURE_PROBABILITY)
results.extend(model.optimize())
# Calculate the hidden representations of each batch, and add both this and the weight matrix to
# our lists of data
features_list = []
hidden_representations_list = []
for batch_inst, W_inst in results:
with t.inference_mode():
hidden = einops.einsum(batch_inst, W_inst, "batch features, hidden features -> hidden batch")
features_list.append(W_inst.cpu())
hidden_representations_list.append(hidden.cpu())
Visualising the 2D feature plots:
utils.plot_features_in_2d(
features_list + hidden_representations_list,
colors=[["blue"] for _ in range(len(DATA_SIZES))] + [["red"] for _ in range(len(DATA_SIZES))],
title=f"Double Descent & Superposition (num features = {N_FEATURES}, n = data size)",
subplot_titles=[f"Features (n={ds})" for ds in DATA_SIZES] + [f"Datapoints (n={ds})" for ds in DATA_SIZES],
allow_different_limits_across_subplots=True,
n_rows=2,
)
You should get something like this:

Hint (code to replicate the dimensionality plot)
df_data = {"Data size": [], "Dimensionality": [], "Data": []}
for data_size, model_W, hidden in zip(DATA_SIZES, features_list, hidden_representations_list):
# Get x-axis data (data size), and color (blue or red)
df_data["Data size"].extend([data_size] * (N_FEATURES + data_size))
df_data["Data"].extend(["features"] * N_FEATURES + ["hidden"] * data_size)
# Calculate dimensionality of model.W[inst].T, which has shape [d_hidden=2 N_FEATURES]
feature_dim = DoubleDescentModel.dimensionality(model_W.T)
assert feature_dim.shape == (N_FEATURES,)
# Calculate dimensionality of model's batch data hidden representation.
# This has shape [d_hidden=2 data_size]
data_dim = DoubleDescentModel.dimensionality(hidden.T)
assert data_dim.shape == (data_size,)
# Add them both to the data
df_data["Dimensionality"].extend(feature_dim.tolist() + data_dim.tolist())
df = pd.DataFrame(df_data)
eps = 0.01
xline1, xline2 = (100 * 200) ** 0.5, (200 * 300) ** 0.5
vrect_kwargs: dict[str, Any] = dict(opacity=0.5, layer="below", line_width=0)
xrange = [math.log10(2), math.log10(700)]
fig = (
px.strip(
df,
x="Data size",
y="Dimensionality",
color="Data",
color_discrete_sequence=["rgba(0,0,255,0.3)", "rgba(255,0,0,0.3)"],
log_x=True,
template="simple_white",
width=1000,
height=600,
title="Dimensionality of features & hidden representation of training examples",
)
.update_traces(marker=dict(opacity=0.5))
.update_layout(
xaxis=dict(range=xrange, tickmode="array", tickvals=DATA_SIZES),
yaxis=dict(range=[-0.05, 1.0]),
)
.add_vrect(x0=1, x1=(1 - eps) * xline1, fillcolor="#ddd", **vrect_kwargs)
.add_vrect(x0=(1 + eps) * xline1, x1=(1 - eps) * xline2, fillcolor="#ccc", **vrect_kwargs)
.add_vrect(x0=(1 + eps) * xline2, x1=10_000, fillcolor="#bbb", **vrect_kwargs)
.add_scatter(
x=DATA_SIZES,
y=[2 / ds for ds in DATA_SIZES],
mode="lines",
line=dict(shape="spline", dash="dot", color="#333", width=1),
name="d_hidden / data_size",
)
)
fig.show()
You should get something like this:
Lastly, you can get the full solution code here:
Solution (full)
import math
from typing import Any
import pandas as pd
import plotly.express as px
NUM_WARMUP_STEPS = 200
NUM_BATCH_UPDATES = 8000
WEIGHT_DECAY = 1e-2
LEARNING_RATE = 3e-3
DATA_SIZES = [3, 4, 5, 6, 8, 10, 15, 20, 30, 50, 100, 200, 300, 500]
N_FEATURES = 400
N_INSTANCES = 10 # per data size
D_HIDDEN = 2
SPARSITY = 0.975
FEATURE_PROBABILITY = 1 - SPARSITY
def linear_warmup_lr(step, steps):
"""Increases linearly from 0 to 1."""
return step / steps
def anthropic_lr(step, steps):
"""As in the paper (but shorter): linear warmup for NUM_WARMUP_STEPS steps, then cosine decay to zero."""
if step < NUM_WARMUP_STEPS:
return linear_warmup_lr(step, NUM_WARMUP_STEPS)
else:
return cosine_decay_lr(step - NUM_WARMUP_STEPS, steps - NUM_WARMUP_STEPS)
class DoubleDescentModel(ToyModel):
W: Float[Tensor, "inst d_hidden feats"]
b_final: Float[Tensor, "inst feats"]
# Our linear map (for a single instance) is x -> ReLU(W.T @ W @ x + b_final)
# We train every data size at once: the instance dimension holds `N_INSTANCES` instances for each
# data size (instance `i` is trained on a dataset of size `self.inst_data_size[i]`). Every
# instance's batch is padded with zeros up to the largest data size, and the padding is masked
# out of the loss.
def __init__(self, cfg: ToyModelConfig, data_sizes: list[int], feature_probability: float, device=device):
super().__init__(cfg, feature_probability=feature_probability, device=device)
assert cfg.n_inst % len(data_sizes) == 0, "Need the same number of instances for each data size"
self.data_sizes = data_sizes
self.n_inst_per_data_size = cfg.n_inst // len(data_sizes)
self.inst_data_size = t.tensor(data_sizes, device=device).repeat_interleave(self.n_inst_per_data_size)
# mask[b, i] = 1 if row b is a real datapoint for instance i, 0 if it's padding
self.mask = (t.arange(max(data_sizes), device=device)[:, None] < self.inst_data_size).float()
@classmethod
def dimensionality(cls, data: Float[Tensor, "... batch d_hidden"]) -> Float[Tensor, "... batch"]:
"""
Calculates dimensionalities of data. Assumes data is of shape ... batch d_hidden, i.e. if
it's 2D then it's a batch of vectors of length `d_hidden` and we return the dimensionality
as a 1D tensor of length `batch`. If it has more dimensions at the start, we assume this
means separate calculations for each of these dimensions (i.e. they are independent batches
of vectors).
"""
# Compute the norms of each vector (this will be the numerator)
squared_norms = einops.reduce(data.pow(2), "... batch d_hidden -> ... batch", "sum")
# Compute the denominator (i.e. get the dot product then sum over j)
data_normed = data / data.norm(dim=-1, keepdim=True)
interference = einops.einsum(
data_normed, data, "... batch_i d_hidden, ... batch_j d_hidden -> ... batch_i batch_j"
)
polysemanticity = einops.reduce(interference.pow(2), "... batch_i batch_j -> ... batch_i", "sum")
assert squared_norms.shape == polysemanticity.shape
return squared_norms / polysemanticity
def generate_batch(self) -> Float[Tensor, "batch inst feats"]:
"""
Generates each instance's (normalized) dataset, padded with zeros up to the largest data size.
"""
# Get batch from prev method
batch = super().generate_batch(max(self.data_sizes))
# Normalize the batch (i.e. so each vector for a particular batch & instance has norm 1)
# (need to be careful about vectors with norm zero)
norms = batch.norm(dim=-1, keepdim=True)
norms = t.where(norms.abs() < 1e-6, t.ones_like(norms), norms)
batch_normed = batch / norms
# Zero out the padding rows
return batch_normed * self.mask[..., None]
def calculate_loss(
self,
out: Float[Tensor, "batch inst feats"],
batch: Float[Tensor, "batch inst feats"],
per_inst: bool = False,
) -> Float[Tensor, " inst"]:
"""
New function to calculate loss: it ignores padding rows, and has a "loss per instance" option
so we can find the best instance at the end of our optimization.
"""
error = self.importance * ((batch - out) ** 2)
error = einops.reduce(error, "batch inst feats -> batch inst", "mean") * self.mask
loss = error.sum(0) / self.inst_data_size # mean over each instance's real datapoints
return loss if per_inst else loss.sum()
def optimize(
self,
steps: int = NUM_BATCH_UPDATES,
log_freq: int = 100,
lr: float = LEARNING_RATE,
lr_scale: Callable[[int, int], float] = anthropic_lr,
weight_decay: float = WEIGHT_DECAY,
) -> list[tuple[Tensor, Tensor]]:
"""
Trains all instances, then returns `(batch, W)` for the best instance of each data size.
"""
optimizer = t.optim.AdamW(list(self.parameters()), lr=lr, weight_decay=weight_decay)
progress_bar = tqdm(range(steps))
# Same batch for each step
batch = self.generate_batch() # [max_data_size inst n_features]
for step in progress_bar:
# Update learning rate
step_lr = lr * lr_scale(step, steps)
for group in optimizer.param_groups:
group["lr"] = step_lr
# Optimize
optimizer.zero_grad()
out = self.forward(batch)
loss = self.calculate_loss(out, batch)
loss.backward()
optimizer.step()
# Display progress bar
if (step % log_freq == 0) or (step + 1 == steps):
progress_bar.set_postfix(loss=loss.item() / self.cfg.n_inst, lr=step_lr)
# For each data size, pick out the instance with the lowest loss
with t.inference_mode():
out = self.forward(batch)
loss_per_inst = self.calculate_loss(out, batch, per_inst=True)
best_insts = loss_per_inst.view(len(self.data_sizes), -1).argmin(-1)
results = []
for k, (data_size, best_inst) in enumerate(zip(self.data_sizes, best_insts.tolist())):
inst = k * self.n_inst_per_data_size + best_inst
results.append((batch[:data_size, inst], self.W[inst].detach()))
return results
# ! Results, part 1/2
# One model for the small data sizes and one for the large ones, with N_INSTANCES instances for each
# data size. (Each model pads its batches up to its own largest data size, so splitting them avoids
# padding the small data sizes all the way up to 500.) Optimize, and get the best batch & weight
# matrix for each data size
results = []
for data_sizes in [[ds for ds in DATA_SIZES if ds <= 100], [ds for ds in DATA_SIZES if ds > 100]]:
cfg = ToyModelConfig(n_features=N_FEATURES, n_inst=len(data_sizes) * N_INSTANCES, d_hidden=D_HIDDEN)
model = DoubleDescentModel(cfg, data_sizes=data_sizes, feature_probability=FEATURE_PROBABILITY)
results.extend(model.optimize())
# Calculate the hidden representations of each batch, and add both this and the weight matrix to
# our lists of data
features_list = []
hidden_representations_list = []
for batch_inst, W_inst in results:
with t.inference_mode():
hidden = einops.einsum(batch_inst, W_inst, "batch features, hidden features -> hidden batch")
features_list.append(W_inst.cpu())
hidden_representations_list.append(hidden.cpu())
utils.plot_features_in_2d(
features_list + hidden_representations_list,
colors=[["blue"] for _ in range(len(DATA_SIZES))] + [["red"] for _ in range(len(DATA_SIZES))],
title=f"Double Descent & Superposition (num features = {N_FEATURES}, n = data size)",
subplot_titles=[f"Features (n={ds})" for ds in DATA_SIZES] + [f"Datapoints (n={ds})" for ds in DATA_SIZES],
allow_different_limits_across_subplots=True,
n_rows=2,
)
# ! Results, part 2/2
df_data = {"Data size": [], "Dimensionality": [], "Data": []}
for data_size, model_W, hidden in zip(DATA_SIZES, features_list, hidden_representations_list):
# Get x-axis data (data size), and color (blue or red)
df_data["Data size"].extend([data_size] * (N_FEATURES + data_size))
df_data["Data"].extend(["features"] * N_FEATURES + ["hidden"] * data_size)
# Calculate dimensionality of model.W[inst].T, which has shape [d_hidden=2 N_FEATURES]
feature_dim = DoubleDescentModel.dimensionality(model_W.T)
assert feature_dim.shape == (N_FEATURES,)
# Calculate dimensionality of model's batch data hidden representation.
# This has shape [d_hidden=2 data_size]
data_dim = DoubleDescentModel.dimensionality(hidden.T)
assert data_dim.shape == (data_size,)
# Add them both to the data
df_data["Dimensionality"].extend(feature_dim.tolist() + data_dim.tolist())
df = pd.DataFrame(df_data)
eps = 0.01
xline1, xline2 = (100 * 200) ** 0.5, (200 * 300) ** 0.5
vrect_kwargs: dict[str, Any] = dict(opacity=0.5, layer="below", line_width=0)
xrange = [math.log10(2), math.log10(700)]
fig = (
px.strip(
df,
x="Data size",
y="Dimensionality",
color="Data",
color_discrete_sequence=["rgba(0,0,255,0.3)", "rgba(255,0,0,0.3)"],
log_x=True,
template="simple_white",
width=1000,
height=600,
title="Dimensionality of features & hidden representation of training examples",
)
.update_traces(marker=dict(opacity=0.5))
.update_layout(
xaxis=dict(range=xrange, tickmode="array", tickvals=DATA_SIZES),
yaxis=dict(range=[-0.05, 1.0]),
)
.add_vrect(x0=1, x1=(1 - eps) * xline1, fillcolor="#ddd", **vrect_kwargs)
.add_vrect(x0=(1 + eps) * xline1, x1=(1 - eps) * xline2, fillcolor="#ccc", **vrect_kwargs)
.add_vrect(x0=(1 + eps) * xline2, x1=10_000, fillcolor="#bbb", **vrect_kwargs)
.add_scatter(
x=DATA_SIZES,
y=[2 / ds for ds in DATA_SIZES],
mode="lines",
line=dict(shape="spline", dash="dot", color="#333", width=1),
name="d_hidden / data_size",
)
)
fig.show()