add arc1 fptrm singlez checkpoints
Browse files- .gitattributes +10 -0
- arc1/all_config.yaml +84 -0
- arc1/evaluator_ARC_step_0/submission.json +0 -0
- arc1/fp_trm_singlez.py +273 -0
- arc1/losses.py +120 -0
- arc1/step_103614 +3 -0
- arc1/step_155422 +3 -0
- arc1/step_207229 +3 -0
- arc1/step_259036 +3 -0
- arc1/step_310843 +3 -0
- arc1/step_362650 +3 -0
- arc1/step_414457 +3 -0
- arc1/step_466264 +3 -0
- arc1/step_51807 +3 -0
- arc1/step_518071 +3 -0
.gitattributes
CHANGED
|
@@ -69,3 +69,13 @@ maze/step_6510 filter=lfs diff=lfs merge=lfs -text
|
|
| 69 |
maze/step_65100 filter=lfs diff=lfs merge=lfs -text
|
| 70 |
maze/step_71610 filter=lfs diff=lfs merge=lfs -text
|
| 71 |
maze/step_78120 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
maze/step_65100 filter=lfs diff=lfs merge=lfs -text
|
| 70 |
maze/step_71610 filter=lfs diff=lfs merge=lfs -text
|
| 71 |
maze/step_78120 filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
arc1/step_103614 filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
arc1/step_155422 filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
arc1/step_207229 filter=lfs diff=lfs merge=lfs -text
|
| 75 |
+
arc1/step_259036 filter=lfs diff=lfs merge=lfs -text
|
| 76 |
+
arc1/step_310843 filter=lfs diff=lfs merge=lfs -text
|
| 77 |
+
arc1/step_362650 filter=lfs diff=lfs merge=lfs -text
|
| 78 |
+
arc1/step_414457 filter=lfs diff=lfs merge=lfs -text
|
| 79 |
+
arc1/step_466264 filter=lfs diff=lfs merge=lfs -text
|
| 80 |
+
arc1/step_51807 filter=lfs diff=lfs merge=lfs -text
|
| 81 |
+
arc1/step_518071 filter=lfs diff=lfs merge=lfs -text
|
arc1/all_config.yaml
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
arch:
|
| 2 |
+
H_cycles: 3
|
| 3 |
+
H_layers: 0
|
| 4 |
+
L_cycles: 6
|
| 5 |
+
L_layers: 2
|
| 6 |
+
alpha_1_init: 0.75
|
| 7 |
+
alpha_2_init: 0.25
|
| 8 |
+
conv_bias: false
|
| 9 |
+
conv_kernel_size: 4
|
| 10 |
+
conv_type: conv1d
|
| 11 |
+
decay_patience: 5
|
| 12 |
+
disable_conv_weight_decay: false
|
| 13 |
+
disable_q_head: false
|
| 14 |
+
eps: 1.0e-08
|
| 15 |
+
expansion: 4
|
| 16 |
+
expon_scale: 72.1347520444
|
| 17 |
+
forward_dtype: bfloat16
|
| 18 |
+
fp_thresh: 0.1
|
| 19 |
+
gamma_alpha: 4.0
|
| 20 |
+
gamma_scale: 16.6666666667
|
| 21 |
+
hidden_size: 512
|
| 22 |
+
loss:
|
| 23 |
+
deep_supervision: true
|
| 24 |
+
loss_type: stablemax_cross_entropy
|
| 25 |
+
name: losses@ACTLossHead
|
| 26 |
+
q_loss_coeff: 0.5
|
| 27 |
+
max_iter: 8
|
| 28 |
+
max_iter_dist: det
|
| 29 |
+
max_iter_eval: 1000
|
| 30 |
+
mlp_t: false
|
| 31 |
+
n_backwards_L: 6
|
| 32 |
+
n_decode_steps: 0
|
| 33 |
+
name: fixed_point_reasoning.fp_trm_singlez@FPTinyRecursiveReasoningModelSingleZ_ACTV1
|
| 34 |
+
no_ACT_continue: true
|
| 35 |
+
norm_placement: none
|
| 36 |
+
norm_type: pre-norm
|
| 37 |
+
normalize_input_injection: false
|
| 38 |
+
num_heads: 8
|
| 39 |
+
outer_only: false
|
| 40 |
+
outlier_quantile: 0.25
|
| 41 |
+
pos_encodings: rope
|
| 42 |
+
puzzle_emb_len: 16
|
| 43 |
+
puzzle_emb_ndim: 512
|
| 44 |
+
residual_scale: input-independent
|
| 45 |
+
scale_init: 2.0
|
| 46 |
+
softmax_temp: 1.0
|
| 47 |
+
stepsize: 1.0
|
| 48 |
+
stepsize_decay: 0.9
|
| 49 |
+
use_spec_norm_linear: false
|
| 50 |
+
beta1: 0.9
|
| 51 |
+
beta2: 0.95
|
| 52 |
+
checkpoint_every_eval: true
|
| 53 |
+
checkpoint_every_n_steps: null
|
| 54 |
+
checkpoint_path: /fast/vmilovanovic/reasoning-model-ablation/new_runs/arc1/fptrm_singlez_arc1_lr1e-3_wd0.01_det_a0.75_0.25_iter8
|
| 55 |
+
data_paths:
|
| 56 |
+
- /home/vmilovanovic/datasets/arc/arc1concept-aug-1000
|
| 57 |
+
data_paths_test: []
|
| 58 |
+
ema: true
|
| 59 |
+
ema_rate: 0.999
|
| 60 |
+
epochs: 100000
|
| 61 |
+
eval_interval: 10000
|
| 62 |
+
eval_save_outputs: []
|
| 63 |
+
evaluators: []
|
| 64 |
+
freeze_weights: false
|
| 65 |
+
global_batch_size: 768
|
| 66 |
+
grad_clip_norm: null
|
| 67 |
+
k_eval_max: null
|
| 68 |
+
k_eval_min: null
|
| 69 |
+
k_eval_step: 1
|
| 70 |
+
load_checkpoint: null
|
| 71 |
+
lr: 0.001
|
| 72 |
+
lr_min_ratio: 1.0
|
| 73 |
+
lr_warmup_steps: 0
|
| 74 |
+
metrics_out: null
|
| 75 |
+
min_eval_interval: 0
|
| 76 |
+
optimizer: adam_atan2
|
| 77 |
+
profile_flops: false
|
| 78 |
+
project_name: reasoning-model-ablation
|
| 79 |
+
puzzle_emb_lr: 0.01
|
| 80 |
+
puzzle_emb_weight_decay: 1.0
|
| 81 |
+
resume_from: null
|
| 82 |
+
run_name: fptrm_singlez_arc1_lr1e-3_wd0.01_det_a0.75_0.25_iter8
|
| 83 |
+
seed: 0
|
| 84 |
+
weight_decay: 0.01
|
arc1/evaluator_ARC_step_0/submission.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
arc1/fp_trm_singlez.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Tuple, Dict, Generator, Union
|
| 3 |
+
import math
|
| 4 |
+
import random
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
from scipy.stats import gamma, expon
|
| 10 |
+
|
| 11 |
+
from ..layers import (
|
| 12 |
+
RotaryEmbedding,
|
| 13 |
+
CastedEmbedding,
|
| 14 |
+
CastedLinear,
|
| 15 |
+
)
|
| 16 |
+
from ..sparse_embedding import CastedSparseEmbedding
|
| 17 |
+
from ..transformer import FixedPointTransformer
|
| 18 |
+
|
| 19 |
+
from .fp_trm_config import FPTRMConfig
|
| 20 |
+
from .model_utils import FixedPointOptimizer
|
| 21 |
+
|
| 22 |
+
IGNORE_LABEL_ID = -100
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry:
|
| 27 |
+
z_L_state: dict
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class FPTinyRecursiveReasoningModelSingleZ_ACTV1Carry:
|
| 32 |
+
inner_carry: FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry
|
| 33 |
+
|
| 34 |
+
steps: torch.Tensor
|
| 35 |
+
halted: torch.Tensor
|
| 36 |
+
|
| 37 |
+
current_data: Dict[str, torch.Tensor]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class FixedPointTinyRecursiveReasoningModel_SingleZ_Inner(nn.Module):
|
| 41 |
+
def __init__(self, config: FPTRMConfig) -> None:
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.config = config
|
| 44 |
+
self.forward_dtype = getattr(torch, self.config.forward_dtype)
|
| 45 |
+
|
| 46 |
+
# I/O
|
| 47 |
+
|
| 48 |
+
self.embed_scale = math.sqrt(self.config.hidden_size)
|
| 49 |
+
embed_init_std = 1.0 / self.embed_scale
|
| 50 |
+
|
| 51 |
+
self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
|
| 52 |
+
self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
|
| 53 |
+
if not self.config.disable_q_head:
|
| 54 |
+
self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
|
| 55 |
+
|
| 56 |
+
self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) if self.config.puzzle_emb_len == 0 else self.config.puzzle_emb_len
|
| 57 |
+
if self.config.puzzle_emb_ndim > 0:
|
| 58 |
+
# Zero init puzzle embeddings
|
| 59 |
+
self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
|
| 60 |
+
batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
|
| 61 |
+
|
| 62 |
+
# LM Blocks
|
| 63 |
+
if self.config.pos_encodings == "rope":
|
| 64 |
+
self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
|
| 65 |
+
max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
|
| 66 |
+
base=self.config.rope_theta)
|
| 67 |
+
elif self.config.pos_encodings == "learned":
|
| 68 |
+
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)
|
| 69 |
+
else:
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
# Reasoning Layers
|
| 73 |
+
self.L_level = FixedPointTransformer(self.config, self.config.L_layers)
|
| 74 |
+
|
| 75 |
+
self.L_optimizer = FixedPointOptimizer(self.config)
|
| 76 |
+
|
| 77 |
+
# Q head special init
|
| 78 |
+
# Init Q to (almost) zero for faster learning during bootstrapping
|
| 79 |
+
if not self.config.disable_q_head:
|
| 80 |
+
with torch.no_grad():
|
| 81 |
+
self.q_head.weight.zero_()
|
| 82 |
+
self.q_head.bias.fill_(-5) # type: ignore
|
| 83 |
+
|
| 84 |
+
def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
|
| 85 |
+
# Token embedding
|
| 86 |
+
embedding = self.embed_tokens(input.to(torch.int32))
|
| 87 |
+
|
| 88 |
+
# Puzzle embeddings
|
| 89 |
+
if self.config.puzzle_emb_ndim > 0:
|
| 90 |
+
puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
|
| 91 |
+
|
| 92 |
+
pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
|
| 93 |
+
if pad_count > 0:
|
| 94 |
+
puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
|
| 95 |
+
|
| 96 |
+
embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
|
| 97 |
+
|
| 98 |
+
# Position embeddings
|
| 99 |
+
if self.config.pos_encodings == "learned":
|
| 100 |
+
# scale by 1/sqrt(2) to maintain forward variance
|
| 101 |
+
embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
|
| 102 |
+
|
| 103 |
+
# Scale
|
| 104 |
+
return self.embed_scale * embedding
|
| 105 |
+
|
| 106 |
+
def empty_carry(self, batch_size: int):
|
| 107 |
+
return FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry(
|
| 108 |
+
z_L_state = None,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def reset_carry(self,
|
| 112 |
+
reset_flag: torch.Tensor,
|
| 113 |
+
batch: torch.Tensor,
|
| 114 |
+
carry: FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry):
|
| 115 |
+
shape = (batch.shape[0], batch.shape[1] + self.puzzle_emb_len, self.config.hidden_size)
|
| 116 |
+
device = batch.device
|
| 117 |
+
dtype = self.forward_dtype
|
| 118 |
+
return FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry(
|
| 119 |
+
z_L_state = self.L_optimizer.reset(reset_flag, shape, dtype, device, carry.z_L_state),
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def _z_step(self, state: Dict[str, torch.Tensor], input_embeddings: torch.Tensor, seq_info: Dict[str, any]):
|
| 123 |
+
z_new = self.L_level(state["y"], input_embeddings, **seq_info)
|
| 124 |
+
return self.L_optimizer.step(state, z_new)
|
| 125 |
+
|
| 126 |
+
def forward(self,
|
| 127 |
+
carry: FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry,
|
| 128 |
+
batch: Dict[str, torch.Tensor],
|
| 129 |
+
force_grad: bool,
|
| 130 |
+
n_steps: int) -> Tuple[
|
| 131 |
+
Tuple[FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
|
| 132 |
+
]:
|
| 133 |
+
input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"])
|
| 134 |
+
|
| 135 |
+
# Slice rotary cache to the actual input length so the same model
|
| 136 |
+
# can be evaluated at sequence lengths shorter than config.seq_len
|
| 137 |
+
# (length-generalisation for state tracking).
|
| 138 |
+
cos_sin = None
|
| 139 |
+
if hasattr(self, "rotary_emb"):
|
| 140 |
+
cos, sin = self.rotary_emb()
|
| 141 |
+
s = input_embeddings.shape[1]
|
| 142 |
+
cos_sin = (cos[:s], sin[:s])
|
| 143 |
+
seq_info = dict(cos_sin=cos_sin, puzzle_emb_len=self.puzzle_emb_len)
|
| 144 |
+
z_state = carry.z_L_state
|
| 145 |
+
|
| 146 |
+
with torch.set_grad_enabled(force_grad):
|
| 147 |
+
for _ in range(n_steps):
|
| 148 |
+
z_state = self._z_step(z_state, input_embeddings, seq_info)
|
| 149 |
+
|
| 150 |
+
output = self.lm_head(z_state['y'])[:, self.puzzle_emb_len:]
|
| 151 |
+
if self.config.disable_q_head:
|
| 152 |
+
q_logits = torch.zeros(z_state['y'].shape[0], 2, dtype=torch.float32, device=z_state['y'].device)
|
| 153 |
+
else:
|
| 154 |
+
q_logits = self.q_head(z_state['y'][:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
|
| 155 |
+
new_carry = FPTinyRecursiveReasoningModelSingleZ_ACTV1InnerCarry(z_L_state=self.L_optimizer.detach_state(z_state)) # New carry no grad
|
| 156 |
+
return new_carry, output, (q_logits[..., 0], q_logits[..., 1])
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class FPTinyRecursiveReasoningModelSingleZ_ACTV1(nn.Module):
|
| 160 |
+
"""Single-state FPTRM wrapper."""
|
| 161 |
+
|
| 162 |
+
def __init__(self, config_dict: dict):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.config = FPTRMConfig(**config_dict)
|
| 165 |
+
self.inner = FixedPointTinyRecursiveReasoningModel_SingleZ_Inner(self.config)
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def puzzle_emb(self):
|
| 169 |
+
return self.inner.puzzle_emb
|
| 170 |
+
|
| 171 |
+
def initial_carry(self, batch: Dict[str, torch.Tensor]):
|
| 172 |
+
batch_size = batch["inputs"].shape[0]
|
| 173 |
+
|
| 174 |
+
return FPTinyRecursiveReasoningModelSingleZ_ACTV1Carry(
|
| 175 |
+
inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
|
| 176 |
+
|
| 177 |
+
steps=torch.zeros((batch_size, ), dtype=torch.int32),
|
| 178 |
+
halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
|
| 179 |
+
|
| 180 |
+
current_data={k: torch.empty_like(v) for k, v in batch.items()}
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
def set_num_iters(self):
|
| 184 |
+
if self.training:
|
| 185 |
+
if self.config.max_iter_dist == 'gamma':
|
| 186 |
+
sampled_max_iter = gamma.rvs(a=self.config.gamma_alpha, scale=self.config.gamma_scale)
|
| 187 |
+
elif self.config.max_iter_dist == 'expon':
|
| 188 |
+
sampled_max_iter = expon.rvs(scale=self.config.expon_scale)
|
| 189 |
+
elif self.config.max_iter_dist == 'det':
|
| 190 |
+
sampled_max_iter = self.config.max_iter
|
| 191 |
+
|
| 192 |
+
if self.config.max_iter_dist == 'det':
|
| 193 |
+
self.max_iter = max(0, int(sampled_max_iter))
|
| 194 |
+
else:
|
| 195 |
+
self.max_iter = max(1, int(sampled_max_iter))
|
| 196 |
+
else:
|
| 197 |
+
self.max_iter = self.config.max_iter_eval if self.config.max_iter_eval is not None else self.config.max_iter
|
| 198 |
+
|
| 199 |
+
def forward(
|
| 200 |
+
self,
|
| 201 |
+
carry: FPTinyRecursiveReasoningModelSingleZ_ACTV1Carry,
|
| 202 |
+
batch: Dict[str, torch.Tensor],
|
| 203 |
+
):
|
| 204 |
+
# Update data, carry (removing halted sequences)
|
| 205 |
+
# Handled inside the optimizer
|
| 206 |
+
new_inner_carry = self.inner.reset_carry(carry.halted, batch['inputs'], carry.inner_carry)
|
| 207 |
+
|
| 208 |
+
new_steps = torch.where(carry.halted, 0, carry.steps)
|
| 209 |
+
|
| 210 |
+
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()}
|
| 211 |
+
|
| 212 |
+
# Forward-backward inner model
|
| 213 |
+
n_steps = self.config.n_backwards_L if self.training else 1
|
| 214 |
+
new_inner_carry, logits, (q_halt_logits, q_continue_logits) = self.inner(new_inner_carry, new_current_data,
|
| 215 |
+
force_grad=self.training, n_steps=n_steps)
|
| 216 |
+
|
| 217 |
+
outputs = {
|
| 218 |
+
"logits": logits,
|
| 219 |
+
"q_halt_logits": q_halt_logits,
|
| 220 |
+
"q_continue_logits": q_continue_logits
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
with torch.no_grad():
|
| 224 |
+
# Step
|
| 225 |
+
new_steps = new_steps + 1
|
| 226 |
+
|
| 227 |
+
if self.config.halting_mechanism == 'act':
|
| 228 |
+
is_last_step = new_steps >= self.config.halt_max_steps
|
| 229 |
+
else:
|
| 230 |
+
is_last_step = new_steps >= self.max_iter
|
| 231 |
+
|
| 232 |
+
halted = is_last_step
|
| 233 |
+
|
| 234 |
+
# if testing, use fixed-points
|
| 235 |
+
if not self.training:
|
| 236 |
+
# during inference we only halt for the entire sequence
|
| 237 |
+
halted = halted | (new_inner_carry.z_L_state['residues'].max() < self.config.fp_thresh) \
|
| 238 |
+
| (new_inner_carry.z_L_state['stepsize'].max() < 1e-3)
|
| 239 |
+
|
| 240 |
+
# if training, and ACT is enabled
|
| 241 |
+
cap = self.config.halt_max_steps if self.config.halting_mechanism == 'act' else self.max_iter
|
| 242 |
+
if self.training and (cap > 1):
|
| 243 |
+
|
| 244 |
+
if self.config.halting_mechanism == 'act':
|
| 245 |
+
if self.config.no_ACT_continue:
|
| 246 |
+
halted = halted | (q_halt_logits > 0)
|
| 247 |
+
else:
|
| 248 |
+
halted = halted | (q_halt_logits > q_continue_logits)
|
| 249 |
+
|
| 250 |
+
# Exploration
|
| 251 |
+
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)
|
| 252 |
+
halted = halted & (new_steps >= min_halt_steps)
|
| 253 |
+
|
| 254 |
+
elif self.config.halting_mechanism == 'fixed_point':
|
| 255 |
+
# Exploration is implemented by self.max_iter if we choose to use it
|
| 256 |
+
halted = halted | (new_inner_carry.z_L_state['residues'] < self.config.fp_thresh) \
|
| 257 |
+
| (new_inner_carry.z_L_state['stepsize'].view(-1) < 1e-3)
|
| 258 |
+
|
| 259 |
+
elif self.config.halting_mechanism == 'fixed_iterations':
|
| 260 |
+
pass
|
| 261 |
+
|
| 262 |
+
else:
|
| 263 |
+
raise ValueError("FPTRM with singleZ looping only accepts ACT, Fixed_point, and Fixed_iterations as its halting mechanism.")
|
| 264 |
+
|
| 265 |
+
if not self.config.no_ACT_continue:
|
| 266 |
+
# Compute target Q
|
| 267 |
+
# NOTE: No replay buffer and target networks for computing target Q-value.
|
| 268 |
+
# As batch_size is large, there're many parallel envs.
|
| 269 |
+
# Similar concept as PQN https://arxiv.org/abs/2407.04811
|
| 270 |
+
_, _, (next_q_halt_logits, next_q_continue_logits) = self.inner(new_inner_carry, new_current_data, force_grad=False, n_steps=1)
|
| 271 |
+
outputs["target_q_continue"] = torch.sigmoid(torch.where(is_last_step, next_q_halt_logits, torch.maximum(next_q_halt_logits, next_q_continue_logits)))
|
| 272 |
+
|
| 273 |
+
return FPTinyRecursiveReasoningModelSingleZ_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs
|
arc1/losses.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Tuple, Dict, Sequence, Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
IGNORE_LABEL_ID = -100
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def s(x, epsilon=1e-30):
|
| 12 |
+
return torch.where(
|
| 13 |
+
x<0,
|
| 14 |
+
1/(1-x+ epsilon),
|
| 15 |
+
x + 1
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def log_stablemax(x, dim=-1):
|
| 20 |
+
s_x = s(x)
|
| 21 |
+
return torch.log(s_x/torch.sum(s_x, dim=dim, keepdim=True))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def stablemax_cross_entropy(logits, labels, ignore_index: int = -100, valid_mask=None):
|
| 25 |
+
logprobs = log_stablemax(logits.to(torch.float64), dim=-1)
|
| 26 |
+
|
| 27 |
+
if valid_mask is None:
|
| 28 |
+
valid_mask = (labels != ignore_index)
|
| 29 |
+
transformed_labels = torch.where(valid_mask, labels, 0)
|
| 30 |
+
prediction_logprobs = torch.gather(logprobs, index=transformed_labels.to(torch.long).unsqueeze(-1), dim=-1).squeeze(-1)
|
| 31 |
+
|
| 32 |
+
return -torch.where(valid_mask, prediction_logprobs, 0)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def softmax_cross_entropy(logits, labels, ignore_index: int = -100):
|
| 36 |
+
# Cast logits to f32
|
| 37 |
+
# Flatten logits
|
| 38 |
+
return F.cross_entropy(logits.to(torch.float32).view(-1, logits.shape[-1]), labels.to(torch.long).view(-1), ignore_index=ignore_index, reduction="none").view(labels.shape)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ACTLossHead(nn.Module):
|
| 42 |
+
def __init__(self, model: nn.Module, loss_type: str, q_loss_coeff: float = 0.5, deep_supervision: bool = True):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.model = model
|
| 45 |
+
self.loss_fn = globals()[loss_type]
|
| 46 |
+
self.deep_supervision = deep_supervision
|
| 47 |
+
self.q_loss_coeff = q_loss_coeff
|
| 48 |
+
|
| 49 |
+
def initial_carry(self, *args, **kwargs):
|
| 50 |
+
return self.model.initial_carry(*args, **kwargs) # type: ignore
|
| 51 |
+
|
| 52 |
+
def set_num_iters(self, *args, **kwargs):
|
| 53 |
+
if hasattr(self.model, "set_num_iters"):
|
| 54 |
+
return self.model.set_num_iters(*args, **kwargs) # type: ignore
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
def forward(
|
| 58 |
+
self,
|
| 59 |
+
return_keys: Sequence[str],
|
| 60 |
+
# Model args
|
| 61 |
+
**model_kwargs,
|
| 62 |
+
) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
|
| 63 |
+
# Model logits
|
| 64 |
+
# B x SeqLen x D
|
| 65 |
+
new_carry, outputs = self.model(**model_kwargs)
|
| 66 |
+
labels = new_carry.current_data["labels"]
|
| 67 |
+
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
# Preds
|
| 70 |
+
outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
|
| 71 |
+
|
| 72 |
+
# Correctness
|
| 73 |
+
mask = (labels != IGNORE_LABEL_ID)
|
| 74 |
+
loss_counts = mask.sum(-1)
|
| 75 |
+
loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
|
| 76 |
+
|
| 77 |
+
is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
|
| 78 |
+
seq_is_correct = is_correct.sum(-1) == loss_counts
|
| 79 |
+
|
| 80 |
+
# Metrics (halted)
|
| 81 |
+
valid_metrics = new_carry.halted & (loss_counts > 0)
|
| 82 |
+
metrics = {
|
| 83 |
+
"count": valid_metrics.sum(),
|
| 84 |
+
|
| 85 |
+
"accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
|
| 86 |
+
"sequence_accuracy": (valid_metrics & seq_is_correct).sum(),
|
| 87 |
+
|
| 88 |
+
"q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
|
| 89 |
+
"steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
# Losses
|
| 93 |
+
lm_loss = (self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID, valid_mask=mask) / loss_divisor).sum()
|
| 94 |
+
|
| 95 |
+
if self.deep_supervision:
|
| 96 |
+
masked_loss = lm_loss
|
| 97 |
+
else:
|
| 98 |
+
lm_mask = mask & new_carry.halted.unsqueeze(-1)
|
| 99 |
+
lm_loss_counts = lm_mask.sum(-1)
|
| 100 |
+
lm_loss_divisor = lm_loss_counts.clamp_min(1).unsqueeze(-1)
|
| 101 |
+
masked_loss = (self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID, valid_mask=lm_mask) / lm_loss_divisor).sum()
|
| 102 |
+
|
| 103 |
+
q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
|
| 104 |
+
metrics.update({
|
| 105 |
+
"lm_loss": lm_loss.detach(),
|
| 106 |
+
"q_halt_loss": q_halt_loss.detach(),
|
| 107 |
+
})
|
| 108 |
+
# Q continue (bootstrapping target loss); Alexia: This fits Q-learning, but seems totally unecessary
|
| 109 |
+
q_continue_loss = 0
|
| 110 |
+
if "target_q_continue" in outputs:
|
| 111 |
+
q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
|
| 112 |
+
|
| 113 |
+
metrics["q_continue_loss"] = q_continue_loss.detach()
|
| 114 |
+
# Filter outputs for return
|
| 115 |
+
detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
|
| 116 |
+
|
| 117 |
+
masked_full_loss = masked_loss + self.q_loss_coeff * (q_halt_loss + q_continue_loss)
|
| 118 |
+
full_loss = lm_loss + self.q_loss_coeff * (q_halt_loss + q_continue_loss)
|
| 119 |
+
|
| 120 |
+
return new_carry, masked_full_loss, full_loss, metrics, detached_outputs, new_carry.halted.all()
|
arc1/step_103614
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9714cc4e5f33d5d0a5ef90bfe9b2a8d19b41e94e1f22e5c043cb95fd74f9370c
|
| 3 |
+
size 1822215947
|
arc1/step_155422
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:11a2e23dac433d39c6b0c3fc4685cbbc294c45175b1d345102b8ac1e4908bf94
|
| 3 |
+
size 1822215947
|
arc1/step_207229
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4b1d542a1aa4cf35e00ef838c3085cd00fb5ed743a94ab57e4560aac291006b8
|
| 3 |
+
size 1822215947
|
arc1/step_259036
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2c351369473dc35071c93ce2e03041aa1d28af5b69b68065dfe2441797953829
|
| 3 |
+
size 1822215947
|
arc1/step_310843
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e38b31fbb39c4f7bf120c6f5d9cc5ef8f1bbad78da29ecd1771f7d0b207fcb06
|
| 3 |
+
size 1822215947
|
arc1/step_362650
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:55142798c4059f988074c16bacfed2db812a782dd21a6045ef03734ad41e2abf
|
| 3 |
+
size 1822215947
|
arc1/step_414457
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a74f6af8c3048b112c2f68e73e6047ee33559c8a60163d1d6fb67033dac1bfb1
|
| 3 |
+
size 1822215947
|
arc1/step_466264
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b81ad2e9e0abf8cde62461d54a9a40569ee42b6d6581ca25d5a3f5dacbf9336f
|
| 3 |
+
size 1822215947
|
arc1/step_51807
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:223f5947240e304c27c74b57a194e9a275bf14b9cbb472080c93b73015dbcba8
|
| 3 |
+
size 1822215925
|
arc1/step_518071
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:def6b01ca20982c63b9c319ecd6c8b8afd9e79dc6ba79cf4de3162488d1d36c6
|
| 3 |
+
size 1822215947
|