Universal Reasoning Model (URM) - Comprehensive Technical Guide
Table of Contents
Overview
The Universal Reasoning Model (URM) is a recurrent Transformer architecture designed for complex reasoning tasks, achieving state-of-the-art results on ARC-AGI (Abstraction and Reasoning Corpus) and Sudoku puzzles.
Key Results:
- ARC-AGI 1: 53.8% pass@1 (SOTA for small models trained from scratch)
- ARC-AGI 2: 16.0% pass@1 (SOTA)
- Sudoku: 77.6% pass@1
Paper: arXiv:2512.14693
Core Insight: Performance improvements in Universal Transformer-based models stem primarily from:
- Recurrent inductive bias - weight sharing across depth enables iterative refinement
- Strong nonlinear components - especially the ConvSwiGLU module
- NOT from elaborate architectural designs in prior work (HRM, TRM)
Proposed Methods
A. Universal Transformer Foundation
The URM builds on the Universal Transformer (UT), which differs from standard Transformers:
Standard Transformer:
A standard Transformer of depth with distinct parameters :
where is the token embedding and is the unembedding (LM head).
Universal Transformer:
The UT applies a single transition block repeatedly to refine token representations:
Parameter Sharing (Weight Tying):
The attention and transition parameters are reused for all :
This enables:
- Iterative representation refinement with flexible number of steps
- Higher theoretical expressivity than fixed-depth Transformers
- Dramatically better parameter efficiency
B. Adaptive Computation Time (ACT)
With ACT, different tokens may halt at different recurrent steps. At step , each position predicts a halting probability:
accumulated until reaching threshold . The final token representation is a weighted mixture:
where is the truncated allocation. ACT allocates more computation to complex tokens and less to simpler ones.
Key Ingredients: ConvSwiGLU and Truncated Backpropagation
The ablation studies reveal that two components are crucial for URM’s performance:
| Ablation | pass@1 | pass@10 | pass@100 | pass@1000 |
|---|---|---|---|---|
| Full URM | 53.8% | 71.3% | 80.4% | 85.1% |
| w/o Short Conv | 45.3% | 62.6% | 72.0% | 78.3% |
| w/o Trunc. Backprop | 40.0% | 54.4% | 64.5% | 70.5% |
A. ConvSwiGLU Module
Mathematical Formulation
Given an input sequence , the ConvSwiGLU module is defined as:
Step 1: Expand to intermediate representation
where projects from hidden dimension to intermediate dimension .
Step 2: SwiGLU activation (gating)
where is element-wise multiplication and .
Step 3: Depthwise 1D convolution (short-range mixing)
where is a depthwise convolution kernel of size .
Step 4: Project back to hidden dimension
where .
Why Depthwise Convolution?
- Depthwise means each channel has its own kernel:
- This provides local contextual interactions without cross-channel mixing in the spatial dimension
- Maintains parameter efficiency (only additional parameters)
Position Matters: Ablation on Insertion Point
The paper tested 6 insertion points for the short convolution:
| Position | Description | Effect |
|---|---|---|
| (a) After SDPA output | After softmax attention | Degrades performance |
| (b) After value projection | Inside attention | Degrades performance |
| (c) After key projection | Inside attention | Degrades performance |
| (d) After query projection | Inside attention | Degrades performance |
| (e) After multi-head concat | Before output projection | Mild gain |
| (f) After MLP expansion | Inside FFN | Best (dominant effect) |
Insight: Short-range mixing is most beneficial when applied within an already nonlinear subspace. The MLP—not attention—is the primary source of expressive nonlinearity.
Kernel Size Ablation
| Kernel Size | pass@1 |
|---|---|
| k=1 (no conv) | ~45% |
| k=2 | ~54% (optimal) |
| k=3 | ~52% |
| k=4 | ~50% |
Small kernel (k=2) provides just enough local context without oversmoothing.
Code Implementation
# models/layers.py:153-188
class ConvSwiGLU(nn.Module):
def __init__(self, hidden_size: int, expansion: float, conv_kernel: int = 2):
super().__init__()
inter = _find_multiple(round(expansion * hidden_size * 2 / 3), 256)
# Step 1: Expand
self.gate_up_proj = CastedLinear(hidden_size, inter * 2, bias=False)
# Step 3: Depthwise conv
self.dwconv = nn.Conv1d(
in_channels=inter,
out_channels=inter,
kernel_size=conv_kernel,
padding=conv_kernel // 2,
groups=inter, # Depthwise: groups=channels
bias=True,
)
# Step 4: Project down
self.down_proj = CastedLinear(inter, hidden_size, bias=False)
def forward(self, x: torch.Tensor):
# Step 1: Expand and split
gate, up = self.gate_up_proj(x).chunk(2, dim=-1)
# Step 2: SwiGLU
x_ffn = F.silu(gate) * up
# Step 3: Depthwise conv (needs channel-first format)
x_conv = self.dwconv(x_ffn.transpose(1, 2))
x_conv = x_conv[..., :up.size(1)] # Handle padding
x_conv = F.silu(x_conv)
x_conv = x_conv.transpose(1, 2).contiguous()
# Step 4: Project down
return self.down_proj(x_conv)B. Truncated Backpropagation Through Loops (TBPTL)
Mathematical Formulation
Consider a -layer Universal Reasoning Model unrolled for iterative loops. Let denote the hidden representation of layer at iteration .
Recurrent transition:
where is the parameterized transformation at layer .
Partitioning the rollout:
Instead of backpropagating through all loops, partition into forward-only and trainable segments:
Loss function:
Gradients:
Why Truncation Helps
Analogous to Truncated Backpropagation Through Time (TBPTT) in RNNs:
- Gradient instability: Full backprop through all loops causes vanishing/exploding gradients
- Early loops warm up: Initial iterations bring hidden states from initialization to task-relevant subspace
- Later loops are stable: Gradients from later iterations are more meaningful for learning
Optimal Truncation: Ablation Study
| Loops w/ grad | Loops w/o grad | pass@1 | pass@10 | pass@100 | pass@1000 |
|---|---|---|---|---|---|
| 8 | 0 | 36.25% | 50.75% | 61.25% | 66.88% |
| 7 | 1 | 37.75% | 49.13% | 59.50% | 65.88% |
| 6 | 2 | 39.13% | 53.50% | 61.88% | 66.88% |
| 5 | 3 | 39.50% | 51.63% | 60.88% | 65.25% |
| 4 | 4 | 38.75% | 50.50% | 61.50% | 65.88% |
| 3 | 5 | 36.88% | 49.00% | 57.75% | 63.88% |
| 2 | 6 | 34.25% | 46.25% | 55.75% | 61.75% |
| 1 | 7 | 22.50% | 37.00% | 45.38% | 52.38% |
Optimal: N=2 forward-only loops (6 loops with gradients)
Example configuration: For layers and inner loops with :
- Loops 1-2: Forward-only (no gradients)
- Loops 3-8: Forward + backward
Code Implementation
# models/urm/urm.py:151-162
def forward(self, carry, batch):
input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"])
hidden_states = carry.current_hidden
# H_cycles-1 iterations WITHOUT gradients (truncated)
if self.config.H_cycles > 1:
with torch.no_grad(): # <-- Key: no gradient tracking
for _ in range(self.config.H_cycles - 1):
for _ in range(self.config.L_cycles):
hidden_states = hidden_states + input_embeddings
for layer in self.layers:
hidden_states = layer(hidden_states=hidden_states, **seq_info)
# Final iteration WITH gradients
for _ in range(self.config.L_cycles):
hidden_states = hidden_states + input_embeddings
for layer in self.layers:
hidden_states = layer(hidden_states=hidden_states, **seq_info)
# Detach for next iteration (prevents gradient through carry)
new_carry = replace(carry, current_hidden=hidden_states.detach())C. Nonlinearity Ablations
The paper shows that strong nonlinearity is essential:
| Model Variant | pass@1 | pass@10 | pass@100 | pass@1000 |
|---|---|---|---|---|
| Full URM | 53.75% | 71.25% | 80.38% | 85.13% |
| w/o Short Conv | 45.25% | 62.63% | 72.00% | 78.25% |
| SwiGLU → SiLU | 29.75% | 42.13% | 50.00% | 54.50% |
| SiLU → ReLU | 28.63% | 43.38% | 50.63% | 54.88% |
| w/o Attention Softmax | 2.00% | 6.75% | 10.25% | 15.00% |
Key insight: Performance degrades monotonically as nonlinear components are removed. The softmax in attention is critical (removing it causes catastrophic collapse to 2% pass@1).
D. Why Universal Transformer Over Vanilla?
| Model | Layers | Loop | Hidden | Params | FLOPs | pass@1 |
|---|---|---|---|---|---|---|
| Vanilla | 32 | 1 | 512 | 32× | 32× | 23.75% |
| Vanilla | 64 | 1 | 256 | 32× | 32× | 18.25% |
| UT | 4 | 8 | 512 | 4× | 32× | 40.00% |
With only 4× parameters, a UT achieves 40.0% pass@1, dramatically outperforming vanilla Transformers with 32× parameters (23.75% pass@1).
Key insight: Recurrent computation converts computational budget into increased effective depth, better aligning with the structure of algorithmic reasoning.
Data Processing Pipeline
A. Data Structure Overview
ARC puzzles are represented as 2D grids with colors (0-9). The pipeline converts these to sequences:
Grid Representation:
- Maximum size: 30×30 pixels
- Vocabulary: PAD=0, EOS=1, digits=2-11 (colors 0-9 mapped to 2-11)
- Sequence length: 900 tokens (30×30)
B. Grid to Sequence Conversion
With translation augmentation:
def np_grid_to_seq_translational_augment(inp, out, do_translation):
if do_translation:
pad_r = np.random.randint(0, 30 - max(inp.shape[0], out.shape[0]) + 1)
pad_c = np.random.randint(0, 30 - max(inp.shape[1], out.shape[1]) + 1)
# Pad to 30×30, shift colors by 2 for vocab
grid = np.pad(grid + 2, ((pad_r, 30-pad_r-nrow), (pad_c, 30-pad_c-ncol)))
# Add EOS markers at boundaries
grid[pad_r + nrow, pad_c:eos_col] = 1 # Horizontal EOS
grid[pad_r:eos_row, pad_c + ncol] = 1 # Vertical EOS
return grid.flatten() # Shape: (900,)C. Data Augmentation
8 Dihedral Symmetries:
where:
- = rotation by degrees
- = horizontal/vertical flip
- = diagonal/anti-diagonal reflection
Color Permutation:
where (black fixed) and is a random permutation.
Total augmentations per puzzle: 1000 (configurable via --num-aug)
D. Output Data Format
Output files per split (train/test):
- {set}__inputs.npy # Shape: (N, 900) - int32
- {set}__labels.npy # Shape: (N, 900) - int32
- {set}__puzzle_identifiers.npy # Shape: (N,) - int32
- {set}__puzzle_indices.npy # Cumulative puzzle boundaries
- {set}__group_indices.npy # Cumulative augmentation groups
- dataset.json # Metadata
Neural Network Architecture
A. Model Hierarchy
URM (ACT Wrapper)
└── URM_Inner (Core Model)
├── CastedEmbedding (Token embeddings)
├── CastedSparseEmbedding (Puzzle embeddings)
├── RotaryEmbedding (RoPE)
├── [URMBlock × num_layers]
│ ├── Attention (FlashAttention)
│ ├── RMSNorm
│ ├── ConvSwiGLU
│ └── RMSNorm
├── CastedLinear (LM head)
└── CastedLinear (Q head for ACT)
B. Tensor Shapes
Input Processing:
Transformer Block:
Output Heads:
C. RoPE (Rotary Position Embedding)
where .
D. Configuration
URMConfig:
batch_size: 768
seq_len: 900
vocab_size: 12
# Architecture
num_layers: 8
hidden_size: 512
num_heads: 8
expansion: 4
# Recurrence
loops: 16 # Max outer loops (ACT)
H_cycles: 4 # Inner cycles (first H_cycles-1 w/o grad)
L_cycles: 3 # Layer applications per cycle
# Precision
forward_dtype: "bfloat16"Training
A. Loss Functions
Stablemax Cross-Entropy:
where is the set of valid (non-padding) positions.
Q-Learning Loss (ACT):
Total Loss:
B. Optimizer
AdamAtan2:
Settings: , , weight decay
Muon (Alternative - 2× faster convergence):
Uses Newton-Schulz iteration for orthogonal updates:
C. Learning Rate Schedule
Settings: , ,
D. Distributed Training
torchrun --nproc_per_node 8 pretrain.py arch=urm data_path=data/arc-aug-1000- NCCL backend for GPU communication
- Parameter broadcasting from rank 0
- All-reduce for gradients
- EMA for training stability ()
Inference and Evaluation
A. Inference Loop
with torch.inference_mode():
carry = model.initial_carry(batch)
while True:
carry, loss, metrics, preds, all_finish = model(carry, batch)
if all_finish:
breakKey: Non-autoregressive - all 900 tokens predicted simultaneously per iteration.
B. ARC Evaluator with Voting
For each test puzzle:
- Collect predictions from all augmented versions
- Inverse the augmentation (undo rotation/flip/color permutation)
- Hash predictions and count votes
- Rank by Q-value (higher = more confident)
- Check if any of top-K matches ground truth
Metrics:
- pass@1, pass@10, pass@100, pass@1000
- Majority voting: Sample N predictions, pick best by Q-value
Extension Ideas for SOTA on ARC
A. 2D-Aware Positional Embeddings
Current RoPE treats the 30×30 grid as a flat sequence. Better alternatives:
2D RoPE:
Learnable 2D Position:
B. Vision-like Attention Patterns
Local Window Attention:
Axial Attention:
C. Expert Iteration
def expert_iteration(model, puzzles):
for puzzle in puzzles:
# Generate K candidates
candidates = [model.generate(puzzle) for _ in range(K)]
# Filter correct ones (ground truth available for training)
correct = [c for c in candidates if verify(c, puzzle.answer)]
# Fine-tune on correct solutions
loss = model.compute_loss(correct)
loss.backward()D. Verifier-Based RL
Train a verifier:
Use as reward in PPO:
Code Structure Reference
URM/
├── models/
│ ├── urm/urm.py # Main model (lines 42-237)
│ ├── layers.py # ConvSwiGLU (153-188), Attention (98-137)
│ ├── losses.py # ACTLossHead (144-240)
│ └── common.py # trunc_normal_init_ (7-32)
├── data/
│ ├── build_arc_dataset.py # Data preprocessing
│ └── common.py # Dihedral transforms
├── config/arch/urm.yaml # Architecture config
├── pretrain.py # Training loop (520-989)
├── evaluate_trained_model.py # Inference
└── evaluators/arc.py # Evaluation with voting
Key Entry Points:
# Training
python pretrain.py arch=urm data_path=data/arc-aug-1000
# Evaluation
python evaluate_trained_model.py --checkpoint-path checkpoints/step_500000.ptDetailed Code Deep-Dive
A. Complete URM Model Implementation
URM Configuration (models/urm/urm.py:16-46)
class URMConfig(BaseModel):
"""Full configuration for the Universal Reasoning Model."""
batch_size: int
seq_len: int # 900 for ARC (30x30)
puzzle_emb_ndim: int = 0 # Puzzle embedding dimension
num_puzzle_identifiers: int # Total unique puzzles
vocab_size: int # 12 (PAD + EOS + 10 colors)
# Recurrence configuration
loops: int # 16 - max outer ACT loops
H_cycles: int # 4 - inner cycles (first H_cycles-1 w/o grad)
L_cycles: int # 3 - layer applications per cycle
loop_deltas: List[int] = [0, 8] # For evaluation with different loop counts
# Transformer architecture
num_layers: int # 8 layers
hidden_size: int # 512
expansion: float # 4.0
num_heads: int # 8
pos_encodings: str # "rope"
# Numerical stability
rms_norm_eps: float = 1e-5
rope_theta: float = 10000.0
# ACT halting configuration
halt_max_steps: int # 16
halt_exploration_prob: float # 0.1 (10% random exploration)
act_enabled: bool = True
act_inference: bool = False # Use max steps at inference for batching
forward_dtype: str = "bfloat16"URMBlock - Single Transformer Block (models/urm/urm.py:49-75)
class URMBlock(nn.Module):
"""Single transformer block with ConvSwiGLU."""
def __init__(self, config: URMConfig) -> None:
super().__init__()
# Self-attention (non-causal for ARC - needs full context)
self.self_attn = Attention(
hidden_size=config.hidden_size,
head_dim=config.hidden_size // config.num_heads, # 64
num_heads=config.num_heads, # 8
num_key_value_heads=config.num_heads, # No GQA
causal=False # Bidirectional!
)
# ConvSwiGLU MLP (the key innovation)
self.mlp = ConvSwiGLU(
hidden_size=config.hidden_size,
expansion=config.expansion,
)
self.norm_eps = config.rms_norm_eps
def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
# Post-norm architecture (norm after residual add)
# Self Attention + Residual + Norm
attn_output = self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states)
hidden_states = rms_norm(
hidden_states + attn_output,
variance_epsilon=self.norm_eps
)
# MLP + Residual + Norm
mlp_output = self.mlp(hidden_states)
hidden_states = rms_norm(
hidden_states + mlp_output,
variance_epsilon=self.norm_eps
)
return hidden_statesURM_Inner - Core Model (models/urm/urm.py:78-180)
class URM_Inner(nn.Module):
"""Core URM model without ACT wrapper."""
def __init__(self, config: URMConfig) -> None:
super().__init__()
self.config = config
self.forward_dtype = getattr(torch, self.config.forward_dtype)
# Embedding scale for initialization stability
self.embed_scale = math.sqrt(self.config.hidden_size) # sqrt(512) ≈ 22.6
embed_init_std = 1.0 / self.embed_scale
# Token embeddings: vocab_size -> hidden_size
self.embed_tokens = CastedEmbedding(
self.config.vocab_size, # 12
self.config.hidden_size, # 512
init_std=embed_init_std,
cast_to=self.forward_dtype # bfloat16
)
# Language model head: hidden_size -> vocab_size
self.lm_head = CastedLinear(
self.config.hidden_size, # 512
self.config.vocab_size, # 12
bias=False
)
# Q-head for ACT halting decision: hidden_size -> 2 (halt, continue)
self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
# Puzzle embeddings (sparse, learnable per-puzzle)
self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size)
if self.config.puzzle_emb_ndim > 0:
self.puzzle_emb = CastedSparseEmbedding(
self.config.num_puzzle_identifiers,
self.config.puzzle_emb_ndim,
batch_size=self.config.batch_size,
init_std=0, # Zero init for puzzle embeddings
cast_to=self.forward_dtype
)
# Positional encoding (RoPE)
if self.config.pos_encodings == "rope":
self.rotary_emb = RotaryEmbedding(
dim=self.config.hidden_size // self.config.num_heads, # 64
max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
base=self.config.rope_theta # 10000
)
elif self.config.pos_encodings == "learned":
self.embed_pos = CastedEmbedding(
self.config.seq_len + self.puzzle_emb_len,
self.config.hidden_size,
init_std=embed_init_std,
cast_to=self.forward_dtype
)
# Transformer layers (shared across recurrent steps)
self.layers = nn.ModuleList([
URMBlock(self.config) for _ in range(self.config.num_layers)
])
# Initial hidden state (learnable)
self.H_init = nn.Buffer(
trunc_normal_init_(
torch.empty(self.config.hidden_size, dtype=self.forward_dtype),
std=1
),
persistent=True
)
# Q-head initialization for faster learning
with torch.no_grad():
self.q_head.weight.zero_()
self.q_head.bias.fill_(-5) # Start with low halt probability
def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
"""Create input embeddings with puzzle prefix."""
# Token embedding: [B, 900] -> [B, 900, 512]
embedding = self.embed_tokens(input.to(torch.int32))
# Prepend puzzle embedding: [B, 1, 512]
if self.config.puzzle_emb_ndim > 0:
puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
if pad_count > 0:
puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
embedding = torch.cat(
(puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding),
dim=-2
) # [B, 901, 512]
# Add learned position embeddings (if not using RoPE)
if self.config.pos_encodings == "learned":
embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight)
return self.embed_scale * embedding
def forward(self, carry: URMInnerCarry, batch: Dict[str, torch.Tensor]):
"""Single forward pass through the model."""
seq_info = dict(
cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
)
# Get input embeddings
input_embeddings = self._input_embeddings(
batch["inputs"],
batch["puzzle_identifiers"]
)
# Start from carry hidden state
hidden_states = carry.z_H
# ===== TRUNCATED BACKPROPAGATION =====
# H_cycles-1 iterations WITHOUT gradients
if self.config.H_cycles > 1:
with torch.no_grad():
for _ in range(self.config.H_cycles - 1):
for _ in range(self.config.L_cycles):
# Input injection at each step
hidden_states = hidden_states + input_embeddings
# Pass through all layers
for layer in self.layers:
hidden_states = layer(
hidden_states=hidden_states,
**seq_info
)
# Final iteration WITH gradients
for _ in range(self.config.L_cycles):
hidden_states = hidden_states + input_embeddings
for layer in self.layers:
hidden_states = layer(hidden_states=hidden_states, **seq_info)
# Create new carry (detached to prevent gradient flow)
new_carry = URMInnerCarry(z_H=hidden_states.detach())
# LM output (remove puzzle embedding position)
output = self.lm_head(hidden_states)[:, self.puzzle_emb_len:] # [B, 900, 12]
# Q-values from first position (puzzle embedding)
q_logits = self.q_head(hidden_states[:, 0]).to(torch.float32) # [B, 2]
return new_carry, output, (q_logits[..., 0], q_logits[..., 1])URM - ACT Wrapper (models/urm/urm.py:183-270)
class URM(nn.Module):
"""URM with Adaptive Computation Time wrapper."""
def __init__(self, config_dict: dict):
super().__init__()
self.config = URMConfig(**config_dict)
self.inner = URM_Inner(self.config)
@property
def puzzle_emb(self):
return self.inner.puzzle_emb
def initial_carry(self, batch: Dict[str, torch.Tensor]):
"""Initialize carry state for a new batch."""
batch_size = batch["inputs"].shape[0]
return URMCarry(
inner_carry=self.inner.empty_carry(batch_size),
steps=torch.zeros((batch_size,), dtype=torch.int32),
halted=torch.ones((batch_size,), dtype=torch.bool), # Start halted
current_data={k: torch.empty_like(v) for k, v in batch.items()}
)
def forward(
self,
carry: URMCarry,
batch: Dict[str, torch.Tensor],
compute_target_q: bool = False
):
"""Forward pass with ACT halting logic."""
# Reset carry for halted sequences (start fresh)
new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
# Reset step counter for halted sequences
new_steps = torch.where(carry.halted, 0, carry.steps)
# Update current data for halted sequences
new_current_data = {
k: torch.where(
carry.halted.view((-1,) + (1,) * (batch[k].ndim - 1)),
batch[k],
v
)
for k, v in carry.current_data.items()
}
# Forward through inner model
new_inner_carry, logits, (q_halt_logits, q_continue_logits) = \
self.inner(new_inner_carry, new_current_data)
outputs = {
"logits": logits,
"q_halt_logits": q_halt_logits,
"q_continue_logits": q_continue_logits
}
# ===== HALTING LOGIC (no gradients) =====
with torch.no_grad():
new_steps = new_steps + 1
is_last_step = new_steps >= self.config.halt_max_steps
halted = is_last_step # Always halt at max steps
# Adaptive halting (if enabled)
use_adaptive = (self.config.halt_max_steps > 1) and (
(self.training and self.config.act_enabled) or
(not self.training and self.config.act_inference)
)
if use_adaptive:
# Halt if q_halt > q_continue
q_halt_signal = q_halt_logits > q_continue_logits
halted = halted | q_halt_signal
# Exploration during training (10% random)
if self.training:
min_halt_steps = (
(torch.rand_like(q_halt_logits) < self.config.halt_exploration_prob) *
torch.randint_like(new_steps, low=2, high=self.config.halt_max_steps + 1)
)
halted = halted & (new_steps >= min_halt_steps)
# Compute target Q for bootstrapping
if self.training and compute_target_q:
next_q_halt, next_q_continue = self.inner(
new_inner_carry, new_current_data
)[-1]
outputs["target_q_continue"] = torch.sigmoid(
torch.where(
is_last_step,
next_q_halt,
torch.maximum(next_q_halt, next_q_continue)
)
)
return URMCarry(
new_inner_carry, new_steps, halted, new_current_data
), outputsB. Attention Implementation (models/layers.py:98-152)
class Attention(nn.Module):
"""Multi-head attention with RoPE and FlashAttention."""
def __init__(
self,
hidden_size: int,
head_dim: int,
num_heads: int,
num_key_value_heads: int,
causal: bool
):
super().__init__()
self.num_heads = num_heads
self.num_key_value_heads = num_key_value_heads
self.head_dim = head_dim
self.causal = causal
# QKV projection (fused for efficiency)
# Output: [B, L, (num_heads + 2*num_kv_heads) * head_dim]
self.qkv_proj = CastedLinear(
hidden_size,
(num_heads + 2 * num_key_value_heads) * head_dim,
bias=False
)
# Output projection
self.o_proj = CastedLinear(num_heads * head_dim, hidden_size, bias=False)
def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor):
B, L, _ = hidden_states.shape
# Project to Q, K, V
qkv = self.qkv_proj(hidden_states)
# Split heads: [B, L, D] -> [B, L, num_heads, head_dim]
q_size = self.num_heads * self.head_dim
k_size = self.num_key_value_heads * self.head_dim
q = qkv[:, :, :q_size].view(B, L, self.num_heads, self.head_dim)
k = qkv[:, :, q_size:q_size+k_size].view(B, L, self.num_key_value_heads, self.head_dim)
v = qkv[:, :, q_size+k_size:].view(B, L, self.num_key_value_heads, self.head_dim)
# Apply RoPE
if cos_sin is not None:
cos, sin = cos_sin
q = apply_rotary_pos_emb(q, cos[:L], sin[:L])
k = apply_rotary_pos_emb(k, cos[:L], sin[:L])
# FlashAttention (efficient O(N) memory)
# causal=False for ARC (bidirectional attention)
attn_output = flash_attn_func(
q, k, v,
causal=self.causal
) # [B, L, num_heads, head_dim]
# Reshape and project output
attn_output = attn_output.view(B, L, -1) # [B, L, num_heads * head_dim]
return self.o_proj(attn_output)C. RMS Normalization (models/layers.py:8-15)
def rms_norm(x: torch.Tensor, variance_epsilon: float = 1e-5) -> torch.Tensor:
"""Root Mean Square Layer Normalization.
$$\text{RMSNorm}(x) = \frac{x}{\sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2 + \epsilon}}$$
"""
dtype = x.dtype
x = x.to(torch.float32)
variance = x.pow(2).mean(-1, keepdim=True)
x = x * torch.rsqrt(variance + variance_epsilon)
return x.to(dtype)D. Rotary Position Embedding (models/layers.py:18-60)
class RotaryEmbedding(nn.Module):
"""Rotary Position Embedding (RoPE).
Encodes position via rotation in 2D subspaces:
$$\text{RoPE}(x, m) = R_m x$$
where $R_m$ is a block-diagonal rotation matrix.
"""
def __init__(self, dim: int, max_position_embeddings: int, base: float = 10000.0):
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.base = base
# Compute frequency bands: theta_i = base^(-2i/d)
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)
)
self.register_buffer("inv_freq", inv_freq)
# Precompute cos/sin tables
self._set_cos_sin_cache(max_position_embeddings)
def _set_cos_sin_cache(self, seq_len: int):
t = torch.arange(seq_len, dtype=self.inv_freq.dtype)
freqs = torch.outer(t, self.inv_freq) # [seq_len, dim/2]
emb = torch.cat((freqs, freqs), dim=-1) # [seq_len, dim]
self.register_buffer("cos_cached", emb.cos())
self.register_buffer("sin_cached", emb.sin())
def forward(self) -> CosSin:
return CosSin(self.cos_cached, self.sin_cached)
def apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
"""Apply RoPE to query or key tensor.
$$x' = x \odot \cos(m\theta) + \text{rotate\_half}(x) \odot \sin(m\theta)$$
"""
# Rotate half: [x1, x2, x3, x4] -> [-x2, x1, -x4, x3]
x_rotated = torch.stack([-x[..., 1::2], x[..., ::2]], dim=-1).flatten(-2)
return x * cos.unsqueeze(-2) + x_rotated * sin.unsqueeze(-2)E. Loss Functions (models/losses.py:104-240)
IGNORE_LABEL_ID = -100
def s(x, epsilon=1e-30):
"""Stablemax transformation function.
$$s(x) = \begin{cases} \frac{1}{1-x+\epsilon} & x < 0 \\ x + 1 & x \geq 0 \end{cases}$$
"""
return torch.where(x < 0, 1/(1-x+epsilon), x + 1)
def log_stablemax(x, dim=-1):
"""Log-stablemax (more numerically stable than log-softmax)."""
s_x = s(x)
return torch.log(s_x / torch.sum(s_x, dim=dim, keepdim=True))
def stablemax_cross_entropy(logits, labels, ignore_index: int = -100):
"""Stablemax cross-entropy loss.
More numerically stable than softmax for extreme logit values.
"""
logprobs = log_stablemax(logits.to(torch.float64), dim=-1)
valid_mask = labels != ignore_index
transformed_labels = torch.where(valid_mask, labels, 0)
prediction_logprobs = torch.gather(
logprobs,
index=transformed_labels.to(torch.long).unsqueeze(-1),
dim=-1
).squeeze(-1)
return -torch.where(valid_mask, prediction_logprobs, 0)
class ACTLossHead(nn.Module):
"""Loss computation wrapper for ACT models."""
def __init__(self, model: nn.Module, loss_type: str):
super().__init__()
self.model = model
self.loss_fn = globals()[loss_type] # stablemax_cross_entropy
def initial_carry(self, *args, **kwargs):
return self.model.initial_carry(*args, **kwargs)
def forward(
self,
return_keys: Set[str],
return_raw_outputs: bool = False,
**model_kwargs
):
# Forward pass
new_carry, outputs = self.model(**model_kwargs)
labels = new_carry.current_data["labels"]
# Compute predictions and correctness
with torch.no_grad():
outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
mask = labels != IGNORE_LABEL_ID
loss_counts = mask.sum(-1)
loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1)
is_correct = mask & (outputs["preds"] == labels)
seq_is_correct = is_correct.sum(-1) == loss_counts
# Metrics for halted sequences
valid_metrics = new_carry.halted & (loss_counts > 0)
metrics = {
"count": valid_metrics.sum(),
"accuracy": torch.where(
valid_metrics,
(is_correct.to(torch.float32) / loss_divisor).sum(-1),
0
).sum(),
"exact_accuracy": (valid_metrics & seq_is_correct).sum(),
"q_halt_accuracy": (
valid_metrics &
((outputs["q_halt_logits"] >= 0) == seq_is_correct)
).sum(),
"steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
}
# ===== LOSS COMPUTATION =====
# 1. Language modeling loss
lm_loss = (
self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID)
/ loss_divisor
).sum()
# 2. Q-halt loss (binary cross-entropy)
q_halt_loss = F.binary_cross_entropy_with_logits(
outputs["q_halt_logits"],
seq_is_correct.to(outputs["q_halt_logits"].dtype),
reduction="sum"
)
metrics.update({
"lm_loss": lm_loss.detach(),
"q_halt_loss": q_halt_loss.detach(),
})
# 3. Q-continue loss (optional bootstrapping)
q_continue_loss = 0
if "target_q_continue" in outputs:
q_continue_loss = F.binary_cross_entropy_with_logits(
outputs["q_continue_logits"],
outputs["target_q_continue"],
reduction="sum"
)
metrics["q_continue_loss"] = q_continue_loss.detach()
# Total loss
total_loss = lm_loss + 0.5 * (q_halt_loss + q_continue_loss)
return (
new_carry,
total_loss,
metrics,
{k: outputs[k].detach() for k in return_keys if k in outputs},
new_carry.halted.all() # All done flag
)F. Data Preprocessing (data/build_arc_dataset.py)
def arc_grid_to_np(grid: List[List[int]]) -> np.ndarray:
"""Convert JSON grid to numpy array."""
return np.array(grid, dtype=np.uint8)
def grid_hash(grid: np.ndarray) -> int:
"""Hash a grid for deduplication and comparison."""
return hash(grid.tobytes())
def np_grid_to_seq_translational_augment(
inp: np.ndarray,
out: np.ndarray,
do_translation: bool
) -> Tuple[np.ndarray, np.ndarray]:
"""Convert grids to sequences with optional translation augmentation.
Args:
inp: Input grid (H, W)
out: Output grid (H, W)
do_translation: Whether to apply random translation
Returns:
input_seq: Flattened input sequence (900,)
output_seq: Flattened output sequence (900,)
"""
# Random translation within 30x30 canvas
if do_translation:
max_h = max(inp.shape[0], out.shape[0])
max_w = max(inp.shape[1], out.shape[1])
pad_r = np.random.randint(0, 30 - max_h + 1)
pad_c = np.random.randint(0, 30 - max_w + 1)
else:
pad_r, pad_c = 0, 0
def process_grid(grid):
nrow, ncol = grid.shape
# Create 30x30 canvas with padding token (0)
canvas = np.zeros((30, 30), dtype=np.uint8)
# Place grid (shifted by 2 for vocabulary: 0=PAD, 1=EOS, 2-11=colors)
canvas[pad_r:pad_r+nrow, pad_c:pad_c+ncol] = grid + 2
# Add EOS markers at grid boundaries
canvas[pad_r + nrow, pad_c:pad_c+ncol+1] = 1 # Horizontal EOS
canvas[pad_r:pad_r+nrow+1, pad_c + ncol] = 1 # Vertical EOS
return canvas.flatten()
return process_grid(inp), process_grid(out)
def build_dataset(
input_file_prefix: str,
output_dir: str,
subsets: List[str],
test_set_name: str,
num_aug: int = 1000
):
"""Build preprocessed dataset from raw ARC JSON files."""
all_puzzles = {}
for subset in subsets:
with open(f"{input_file_prefix}_{subset}.json") as f:
data = json.load(f)
for name, puzzle in data.items():
all_puzzles[name] = puzzle
# Process each puzzle
inputs_list = []
labels_list = []
puzzle_ids_list = []
puzzle_indices = [0]
group_indices = [0]
for puzzle_idx, (name, puzzle) in enumerate(all_puzzles.items()):
examples = puzzle["train"]
test_pairs = puzzle.get("test", [])
# Generate augmentations
for aug_idx in range(num_aug):
# Random dihedral transformation (0-7)
dihedral_id = np.random.randint(0, 8)
# Random color permutation (keep black=0 fixed)
color_perm = np.concatenate([
[0],
np.random.permutation(np.arange(1, 10))
])
for pair in examples + test_pairs:
inp = arc_grid_to_np(pair["input"])
out = arc_grid_to_np(pair["output"])
# Apply augmentations
inp = dihedral_transform(inp, dihedral_id)
out = dihedral_transform(out, dihedral_id)
inp = color_perm[inp]
out = color_perm[out]
# Convert to sequences
inp_seq, out_seq = np_grid_to_seq_translational_augment(
inp, out, do_translation=True
)
inputs_list.append(inp_seq)
labels_list.append(out_seq)
puzzle_ids_list.append(puzzle_idx)
group_indices.append(len(inputs_list))
puzzle_indices.append(len(inputs_list))
# Save as memory-mapped numpy arrays
np.save(f"{output_dir}/train__inputs.npy", np.array(inputs_list, dtype=np.int32))
np.save(f"{output_dir}/train__labels.npy", np.array(labels_list, dtype=np.int32))
np.save(f"{output_dir}/train__puzzle_identifiers.npy", np.array(puzzle_ids_list, dtype=np.int32))
np.save(f"{output_dir}/train__puzzle_indices.npy", np.array(puzzle_indices, dtype=np.int32))
np.save(f"{output_dir}/train__group_indices.npy", np.array(group_indices, dtype=np.int32))G. Training Loop (pretrain.py:520-700)
def train_batch(
config: PretrainConfig,
train_state: TrainState,
batch: Dict[str, torch.Tensor],
rank: int,
world_size: int
) -> Dict[str, float]:
"""Single training step."""
model = train_state.model
model.train()
# Move batch to GPU
batch = {k: v.cuda() for k, v in batch.items()}
# Initialize or use existing carry
if train_state.carry is None:
train_state.carry = model.initial_carry(batch)
# ===== FORWARD PASS =====
all_metrics = defaultdict(float)
total_loss = 0
# ACT loop: continue until all samples halt
step = 0
while True:
carry, loss, metrics, outputs, all_finish = model(
carry=train_state.carry,
batch=batch,
return_keys=set(),
compute_target_q=(step % config.target_q_update_every == 0)
)
train_state.carry = carry
total_loss = total_loss + loss
# Accumulate metrics
for k, v in metrics.items():
all_metrics[k] += v.item() if torch.is_tensor(v) else v
step += 1
if all_finish:
break
# ===== BACKWARD PASS =====
total_loss.backward()
# ===== GRADIENT SYNC (distributed) =====
if world_size > 1:
for param in model.parameters():
if param.requires_grad and param.grad is not None:
dist.all_reduce(param.grad)
# ===== OPTIMIZER STEP =====
for optimizer in train_state.optimizers:
optimizer.step()
optimizer.zero_grad()
# Update learning rates
for lr_lambda, optimizer in zip(train_state.optimizer_lrs, train_state.optimizers):
for param_group in optimizer.param_groups:
param_group["lr"] = lr_lambda(train_state.step)
# EMA update
if config.ema and hasattr(train_state, "ema_helper"):
train_state.ema_helper.update()
train_state.step += 1
return dict(all_metrics)
def main_training_loop(config: PretrainConfig, rank: int, world_size: int):
"""Main training loop."""
# Create dataloaders
train_loader, train_metadata = create_dataloader(
config, "train", test_set_mode=False,
epochs_per_iter=config.epochs_per_iter,
global_batch_size=config.global_batch_size,
rank=rank, world_size=world_size
)
# Create model
model, _, _ = create_model(config, train_metadata, rank, world_size)
# Initialize training state
train_state = init_train_state(config, model, train_metadata)
# Training loop
for epoch in range(config.epochs):
for batch_idx, (set_name, batch, _) in enumerate(train_loader):
metrics = train_batch(config, train_state, batch, rank, world_size)
# Logging
if rank == 0 and train_state.step % config.log_interval == 0:
wandb.log(metrics, step=train_state.step)
# Evaluation
if train_state.step % config.eval_interval == 0:
eval_metrics = evaluate(config, train_state, ...)
if rank == 0:
wandb.log(eval_metrics, step=train_state.step)
# Checkpointing
if train_state.step % config.checkpoint_interval == 0:
save_train_state(config, train_state, rank)H. ARC Evaluator (evaluators/arc.py:41-205)
class ARC:
"""ARC-AGI evaluator with majority voting."""
required_outputs = {"inputs", "puzzle_identifiers", "q_halt_logits", "preds"}
def __init__(
self,
data_path: str,
eval_metadata: PuzzleDatasetMetadata,
submission_K: int = 2,
pass_Ks: Sequence[int] = (1, 2, 5, 10, 100, 1000),
aggregated_voting: bool = True
):
self.pass_Ks = pass_Ks
self.submission_K = submission_K
self.aggregated_voting = aggregated_voting
self.blank_identifier_id = eval_metadata.blank_identifier_id
# Load test puzzles and identifier mapping
with open(os.path.join(data_path, "identifiers.json")) as f:
self.identifier_map = json.load(f)
with open(os.path.join(data_path, "test_puzzles.json")) as f:
self.test_puzzles = json.load(f)
self._local_hmap = {} # hash -> grid
self._local_preds = {} # puzzle -> input_hash -> [(pred_hash, q, log_prob)]
def update_batch(self, batch: Dict[str, torch.Tensor], preds: Dict[str, torch.Tensor]):
"""Process a batch of predictions."""
outputs = {}
q_values = preds["q_halt_logits"].to(torch.float64).sigmoid().cpu()
q_log_probs = F.logsigmoid(preds["q_halt_logits"].to(torch.float64)).cpu()
for k in self.required_outputs:
if k in batch:
outputs[k] = batch[k].cpu()
elif k in preds:
outputs[k] = preds[k].cpu()
# Remove padding
mask = outputs["puzzle_identifiers"] != self.blank_identifier_id
outputs = {k: v[mask] for k, v in outputs.items()}
# Process each prediction
for identifier, input_seq, pred_seq, q, q_lp in zip(
outputs["puzzle_identifiers"].numpy(),
outputs["inputs"].numpy(),
outputs["preds"].numpy(),
q_values.numpy(),
q_log_probs.numpy()
):
name = self.identifier_map[identifier]
orig_name, inverse_fn = inverse_aug(name) # Undo augmentation
# Crop and inverse-transform
input_grid = inverse_fn(_crop(input_seq))
pred_grid = inverse_fn(_crop(pred_seq))
input_hash = grid_hash(input_grid)
pred_hash = grid_hash(pred_grid)
# Store for voting
self._local_hmap[pred_hash] = pred_grid
self._local_preds.setdefault(orig_name, {})
self._local_preds[orig_name].setdefault(input_hash, [])
self._local_preds[orig_name][input_hash].append(
(pred_hash, float(q), float(q_lp))
)
def result(self, save_path, rank, world_size, group):
"""Compute final metrics with voting."""
# Gather predictions from all ranks
global_hmap_preds = [None] * world_size if rank == 0 else None
dist.gather_object(
(self._local_hmap, self._local_preds),
global_hmap_preds,
dst=0,
group=group
)
if rank != 0:
return None
# Aggregate and vote
correct = [0.0] * len(self.pass_Ks)
for name, puzzle in self.test_puzzles.items():
for pair in puzzle["test"]:
input_hash = grid_hash(arc_grid_to_np(pair["input"]))
label_hash = grid_hash(arc_grid_to_np(pair["output"]))
# Collect all predictions for this input
p_map = {} # pred_hash -> [count, sum_q, max_log_prob]
for hmap, preds in global_hmap_preds:
for h, q, q_lp in preds.get(name, {}).get(input_hash, []):
p_map.setdefault(h, [0, 0.0, -np.inf])
p_map[h][0] += 1
p_map[h][1] += q
p_map[h][2] = max(p_map[h][2], q_lp)
# Average Q-values
for h, stats in p_map.items():
stats[1] /= stats[0]
# Sort by average Q-value (descending)
p_map = sorted(p_map.items(), key=lambda kv: kv[1][1], reverse=True)
# Check pass@K
for i, k in enumerate(self.pass_Ks):
if any(h == label_hash for h, _ in p_map[:k]):
correct[i] += 1 / len(puzzle["test"])
return {
f"ARC/pass@{k}": correct[i] / len(self.test_puzzles)
for i, k in enumerate(self.pass_Ks)
}I. Sparse Embedding with Distributed Optimizer (models/sparse_embedding.py)
class CastedSparseEmbedding(nn.Module):
"""Sparse embedding with efficient gradient handling."""
def __init__(
self,
num_embeddings: int,
embedding_dim: int,
batch_size: int,
init_std: float = 0.02,
cast_to: torch.dtype = torch.float32
):
super().__init__()
self.num_embeddings = num_embeddings
self.embedding_dim = embedding_dim
self.cast_to = cast_to
# Use buffer instead of parameter for sparse updates
self.embedding_weight = nn.Buffer(
trunc_normal_init_(
torch.empty(num_embeddings, embedding_dim),
std=init_std
),
persistent=True
)
# Gradient accumulator
self.grad_buffer = nn.Buffer(
torch.zeros(batch_size, embedding_dim),
persistent=False
)
self.index_buffer = nn.Buffer(
torch.zeros(batch_size, dtype=torch.long),
persistent=False
)
def forward(self, indices: torch.Tensor) -> torch.Tensor:
# Store indices for sparse gradient
self.index_buffer.copy_(indices)
# Lookup and cast
return self.embedding_weight[indices].to(self.cast_to)
class CastedSparseEmbeddingSignSGD_Distributed:
"""Distributed Sign-SGD optimizer for sparse embeddings.
Uses sign of gradient for more stable updates on sparse data.
"""
def __init__(
self,
buffers: Iterator,
lr: float,
weight_decay: float = 0.0
):
self.buffers = list(buffers)
self.lr = lr
self.weight_decay = weight_decay
def step(self):
for buf in self.buffers:
if hasattr(buf, 'grad_buffer') and hasattr(buf, 'index_buffer'):
indices = buf.index_buffer
grads = buf.grad_buffer
# All-reduce gradients across GPUs
if dist.is_initialized():
dist.all_reduce(grads)
# Sign-SGD update
update = self.lr * torch.sign(grads)
# Weight decay
if self.weight_decay > 0:
update = update + self.weight_decay * buf.embedding_weight[indices]
# Sparse update
buf.embedding_weight[indices] -= update
def zero_grad(self):
for buf in self.buffers:
if hasattr(buf, 'grad_buffer'):
buf.grad_buffer.zero_()Summary
URM achieves SOTA through:
-
ConvSwiGLU:
- Short convolution (k=2) after MLP expansion
- +8.5% pass@1 improvement
-
TBPTL:
- 2 forward-only loops, 6 with gradients
- +13.8% pass@1 improvement
-
Recurrent inductive bias: Weight sharing enables iterative refinement with 4× fewer parameters than vanilla Transformers achieving the same performance.
-
Key Implementation Details:
- FlashAttention with non-causal (bidirectional) attention
- RoPE positional encoding treating 30×30 grid as 900-length sequence
- Stablemax cross-entropy for numerical stability
- Q-learning based ACT with exploration (10% random halting)
- Sparse puzzle embeddings with Sign-SGD optimizer
- EMA for training stability