Groking in Neural Networks
Deep Learning Theory: Spline Interpretation, Grokking, and Beyond
Understanding Neural Networks as Splines
The Spline Theory of Deep Networks
A neural network composed of alternating affine operations (dense layers or convolutions) and piecewise linear nonlinearities (ReLU, leaky ReLU, max pooling, sawtooth, etc.) produces an input-output mapping that is itself a continuous piecewise affine spline. This means the entire input space—which can be extremely high-dimensional, such as the space of images—is partitioned into convex polytopal regions. Within each region, the network acts as a simple affine mapping (a linear transformation plus a bias). The overall mapping remains continuous, but the behavior changes only when crossing region boundaries.
The network effectively performs an elastic origami: it takes the input domain and warps it (stretches and folds) into a new space, then draws a linear hyperplane in that warped space to separate classes. The last layer's linear decision boundary cuts through this folded geometry.
Each region corresponds to a unique pattern of neuron activations. The number and arrangement of these regions reflect how the network allocates its representational capacity.
The partition and the affine mappings are tied together through the network weights. Learning one automatically adjusts the other during gradient descent.
Why Piecewise Linear Is Powerful
A classic result in spline function approximation (well-studied for 1D-to-1D regression) states that when designing a spline, one must choose both the partition of the space and the degree of the polynomial used on each region. It turns out that positioning the regions correctly is far more important than increasing the polynomial degree. Even with simple piecewise linear (degree 1) mappings per region, extremely good approximation power can be achieved if the partition adapts well to the data. This is exactly what deep networks do: they adapt the partition during training to concentrate regions where they are most needed.
Most regions become concentrated near training points, and the network also extrapolates according to rules given by the architecture.
In parts of the space far from training data or far from the extrapolation rule, regions are much sparser — leading to coarser approximations.
Visualizing the Geometry
A random 2D slice through the high-dimensional input space reveals a honeycomb-like structure of region boundaries. This geometry can be visualized to understand how the network behaves for different samples.
If a sample lies in a region with many nearby boundaries (high density of partition regions), the network is more nonlinear around that point — the function is more complex there.
Such high-density regions are also more vulnerable to adversarial attacks: a small perturbation can push the input across many boundaries, changing many activations and potentially flipping the prediction.
Conversely, wide regions (few boundaries) mean the network is nearly linear in that neighborhood, making it more robust to noise.
Grokking and Delayed Generalization
What Is Grokking?
Grokking refers to a phenomenon observed in certain neural network training setups where the training metric (e.g., accuracy) plateaus early, but if training continues far longer than usual, the test metric suddenly improves — often dramatically — long after the training metric stopped changing. This is a form of delayed generalization: the network initially memorizes training data, then later reorganizes its weights to extrapolate better to test samples.
Early observations were in very specific settings: particular tasks, model architectures, and weight initializations.
In more general settings (e.g., CIFAR image classification with convolutional networks / ResNets), clean training accuracy and clean test accuracy tend to plateau at roughly the same time. However, if one looks at test accuracy under adversarial noise, a clear grokking-like emergence of robustness occurs much later.
Adversarial Grokking
Adversarial robustness is the ability of a network to maintain correct predictions when small, intentionally crafted perturbations (adversarial examples) are added to inputs. A standard white-box attack uses gradient information to find the direction of noise that maximally changes the network's output while being imperceptible.
Normally, networks are extremely brittle: a tiny perturbation can reduce accuracy from near 100% to random guessing.
Adversarial grokking: after very long training (much longer than needed for clean accuracy to plateau), the network naturally becomes robust to adversarial attacks — without any explicit adversarial training. This robustness emerges as a consequence of the network reaching a specific geometric configuration.
Two Stages of Training Dynamics
Stage 1: Memorization and Local Complexity
At the start of training, the network aggressively concentrates regions around the training points. This is a memorization phase:
The partition is dense near each training sample (many small regions).
The network fits the training data very precisely but does not simplify anywhere.
This state yields high clean accuracy but no adversarial robustness — the network is highly nonlinear around each point, making it easy to push a sample across a boundary.
Stage 2: Decomplexification and Decision Boundary Focusing
If training continues far beyond the plateau of clean accuracy, a second phase begins:
Regions migrate away from the training and test points and concentrate near the decision boundary instead.
Around the data points, regions become larger (wider radius), meaning the mapping becomes more linear (or even constant) in those neighborhoods.
The network transitions from a uniformly smooth mapping to a piecewise constant mapping (theoretical limit of convergence).
Because the regions near points are wide, small perturbations no longer cross many boundaries — hence adversarial robustness emerges naturally.
This transition can be viewed as a form of local decomplexification: the network stops wasting capacity on remembering exact point locations and instead uses its resources to carve out the decision boundary precisely.
Connection to Double Descent
The dynamics parallel double descent but viewed through the geometry of the partition, not parameter count:
First ascent/descent: regions concentrate near points, clean accuracy rises.
Second descent: regions migrate to the boundary, robustness emerges.
The local complexity measure (number of nearby regions) is a more sensitive metric than train/test accuracy. It starts decreasing well before adversarial grokking appears, making it a useful early indicator.
The Local Complexity Measure
What It Measures
A local complexity measure quantifies how many region boundaries exist near a specific point in input space. This is roughly equivalent to the amount of information (bits) the network stores about that neighborhood.
A practical proxy: per layer, count the number of vertices of the partition that fall within an epsilon-ball around the point. This can be computed efficiently even for very large models.
This metric shows distinct dynamics during training:
It increases rapidly during the memorization phase.
It peaks and then starts decreasing well before adversarial grokking is observed.
It is much more sensitive to the geometric evolution than accuracy curves.
Applications
Early stopping: by monitoring the local complexity measure, one can determine when the network has finished the first phase of training without needing to compute train/test accuracy.
Neural architecture search: some researchers have used partition statistics directly to choose architectures without full training.
Understanding algorithmic bias: if certain samples (e.g., from a demographic group) lie in regions with lower complexity (fewer regions), the network is assigning less expressivity to those areas — revealing potential algorithmic bias.
Regularization and Its Effect on Grokking
Implicit vs. Explicit Regularization
Many common regularization techniques actually fight the emergence of the sparse, robust solution:
Batch normalization: tends to concentrate regions around training points, delaying or preventing the migration to decision boundaries.
Weight decay: encourages smoothness in the L2 sense, which is opposite to the piecewise constant solution that yields adversarial robustness.
Strong regularization can make adversarial grokking happen much later (or not at all).
Conversely, using no biases in the network constrains the partition to be central (regions are cones from the origin), which naturally pushes toward the later-stage geometry.
Designing Regularizers to Accelerate Grokking
Because the partition is differentiable with respect to parameters, one can design geometrically inspired regularizers:
Compute the distance from a point to the nearest region boundary (this quantity is differentiable and fast to obtain).
Use this distance as a regularizer to explicitly encourage wider regions around data points.
Alternatively, design architectures that inherently constrain the partition to the desired form (e.g., no biases, or specific weight parameterizations).
These approaches could allow practitioners to achieve adversarial robustness in fewer training steps, making the benefit accessible without enormous compute budgets.
Learning by Reconstruction vs. Contrastive Learning
The Problem with Reconstruction-Based Representations
Autoencoders and other reconstruction-based methods (e.g., training with mean squared error in pixel space) inherit a strong bias from the data distribution. The key finding: low-frequency image features dominate the gradient during reconstruction because they have the highest energy (largest eigenvalues in the power spectrum). The network learns these first, but they are often not useful for perception tasks (classification, detection, etc.).
Example: low-frequency features produce blurry images that are hard to classify; high-frequency features (edges, textures) are much more discriminative.
There is a misalignment between reconstruction quality and representation quality for downstream tasks: even if reconstructed images look good by eye, the representation may still be suboptimal.
This bias is dataset-dependent: on simple datasets like MNIST or SVHN, all information is useful for both reconstruction and perception, so alignment is good. On realistic datasets (ImageNet), the mismatch is severe.
Denoising and Masking as a Workaround
Denoising autoencoders (e.g., Masked Autoencoders, MAE) add noise to the input before reconstruction. By carefully designing the noise distribution, one can counteract the dataset bias:
Masking large blocks of an image forces the network to rely on high-frequency context to fill in missing parts.
This shifts the learning focus toward features useful for perception.
However, designing the optimal noise strategy requires prior knowledge about which frequencies are task-relevant — a form of weak supervision.
Why Contrastive Methods Work Better
Reconstruction-free self-supervised learning methods (contrastive or non-contrastive) operate in an embedding space, not pixel space:
They take different views of the same input (via data augmentation, adjacent video frames, different viewpoints) and bring their embeddings closer together.
Because they never compare the original input to a reconstruction, they naturally disregard many low-level details (background, texture variations) that are not needed for the task.
The embedding space allows the network to focus on the high-level semantic features that are invariant to irrelevant transformations.
This is a more efficient and controllable way to learn useful representations.
Characterizing LLM Geometry for Toxicity Detection
Spline Features from the MLP Block
Every layer of a large language model (LLM) consists of a multi-head attention block followed by an MLP block. The MLP block, when it uses piecewise linear activations (ReLU, SwiGLU, etc.), is itself a spline. Thus, one can extract geometric features from the partition created by each MLP layer for a given input prompt.
Seven simple features per MLP layer characterize the region in which the prompt's representation falls (e.g., distance to boundaries, size of region, etc.).
For a 70B parameter model with ~80 layers, this yields only about 500 features total — a very compact description of the prompt.
These features are differentiable and can be computed quickly on the fly.
Clustering and Downstream Utility
When these features are visualized using t-SNE (unsupervised dimensionality reduction to 2D), they naturally cluster by:
Prompt modality: mathematical, legal, medical, etc.
Toxicity: toxic prompts form distinct clusters from non-toxic ones.
By training a simple linear probe (or random forest) on these features, one can perform toxicity detection with:
Higher accuracy than dedicated toxicity detection models (e.g., 99.18% AUC on the OxiToxic dataset using Llama 2 7B, vs ~73.5% for a widely-downloaded detector).
Low latency: using only the first few layers' features can trade some accuracy for speed.
Model-agnostic: works with any pre-trained LLM without retraining.
Comparison to Existing Methods
Standard approaches fine-tune entire LLMs or use black-box detectors, requiring large training sets and suffering from high computational cost.
The spline feature method requires only a few hundred features for the linear probe, making it effective even with small labeled sets.
It is interpretable: one can see which layers contribute most to the detection.
Intrinsic Dimension and RLHF Jailbreaking
Intrinsic Dimension of a Prompt
The multi-head attention part of an LLM also gives geometric information. The intrinsic dimension of the subspace in which a prompt's tokens live can be derived from the sparsity of the attention matrix. This is a scalar that characterizes how many independent directions the attention mechanism is using.
Training prompts have a characteristic intrinsic dimension distribution.
By artificially increasing the intrinsic dimension (e.g., by adding related-context tokens), one can move the input into parts of the space that were not covered during reinforcement learning from human feedback (RLHF) training.
Jailbreaking via Context Length
RLHF attempts to align the model to avoid generating toxic content. However, RLHF only controls behavior in the regions of space where training prompts resided. If one can craft a prompt whose intrinsic dimension is larger than what was seen during RLHF, the model may extrapolate incorrectly and produce toxic outputs even though it was fine-tuned to refuse.
Increasing context length with random tokens can increase intrinsic dimension.
Even more effective: add related concepts in the extra context (e.g., natural English sentences semantically connected to the toxic prompt). This reduces attention sparsity and pushes the model further into uncharted territory.
The attack is hard to detect because the added tokens look like normal text.
Fundamental Challenge for Alignment
This reveals a fundamental problem: controlling a deep network in a high-dimensional space is impossible by only observing a finite set of training points. RLHF cannot guarantee behavior everywhere. The same issue applies to concept scrubbing and other alignment techniques: as models become more complex, they find ways to bypass constraints.
Possible solutions: better parameterization of the network so that extrapolation from few examples is more predictable, or provable guarantees on behavior in unseen regions (e.g., using spline theory to bound generalization).
The intrinsic dimension approach provides a geometric tool to detect and potentially defend against such jailbreaks.
Future Directions in Deep Learning Theory
Need for Accessible Theory
Many theoretical frameworks for deep learning require heavy mathematical background. The spline formulation is advantageous because:
It is visually interpretable — even non-experts can look at partition figures and understand why one geometry is better.
It provides actionable insights: one can derive new regularizers, architectures, or training strategies from geometric understanding.
It applies across modalities (images, text, graphs) and architectures (convolutional, transformer) as long as the network is composed of affine layers and piecewise linear nonlinearities.
Promising Research Avenues
Provable guarantees for robustness, generalization, and alignment using geometric properties.
Cross-pollination between vision and language domains — insights from splines in computer vision transfer directly to LLMs.
Combining spline theory with other approaches (e.g., neural collapse, double descent, neural tangent kernel) to build a unified understanding.
Automatic design of noise strategies for masked autoencoders, or automatic design of architectures that inherently produce desirable partitions (like KAN — Kolmogorov-Arnold Networks — which hardcode spline activations for low-dimensional problems).
Key Takeaways
Neural networks are piecewise linear splines. The input space is cut into convex regions, and within each region the network is linear.
Training has two distinct phases: first memorization (dense regions near points, no robustness), then a delayed decomplexification that moves regions to decision boundaries, yielding adversarial robustness naturally.
Regularization can help or hinder this emergence — weight decay and batch normalization often slow it down, while geometry-aware regularizers can accelerate it.
Reconstruction learning inherits dataset biases (low-frequency dominance) that hurt downstream tasks; contrastive methods in embedding space avoid this.
Spline features from LLMs enable efficient, interpretable detection of toxicity and other prompt properties with state-of-the-art performance.
RLHF alignment can be bypassed by increasing the intrinsic dimension of prompts, highlighting the need for provable, geometry-based control methods.
These insights demonstrate that a geometric, spline-based understanding of neural networks provides not only theoretical clarity but also practical tools for improving robustness, interpretability, and safety across a wide range of deep learning applications.

Ask anything
We've read this whole study set, so questions about it get the best answers.