Upload folder using huggingface_hub
Browse files- .gitattributes +10 -0
- mini-GC/all_config.yaml +52 -0
- mini-GC/losses.py +192 -0
- mini-GC/step_10304 +3 -0
- mini-GC/step_11592 +3 -0
- mini-GC/step_1288 +3 -0
- mini-GC/step_12880 +3 -0
- mini-GC/step_2576 +3 -0
- mini-GC/step_3864 +3 -0
- mini-GC/step_5152 +3 -0
- mini-GC/step_6440 +3 -0
- mini-GC/step_7728 +3 -0
- mini-GC/step_9016 +3 -0
- mini-GC/trm.py +445 -0
.gitattributes
CHANGED
|
@@ -243,3 +243,13 @@ arc1-Gym-G_24/step_25933 filter=lfs diff=lfs merge=lfs -text
|
|
| 243 |
arc1-Gym-G_24/step_259332 filter=lfs diff=lfs merge=lfs -text
|
| 244 |
arc1-Gym-G_24/step_51866 filter=lfs diff=lfs merge=lfs -text
|
| 245 |
arc1-Gym-G_24/step_77800 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
arc1-Gym-G_24/step_259332 filter=lfs diff=lfs merge=lfs -text
|
| 244 |
arc1-Gym-G_24/step_51866 filter=lfs diff=lfs merge=lfs -text
|
| 245 |
arc1-Gym-G_24/step_77800 filter=lfs diff=lfs merge=lfs -text
|
| 246 |
+
mini-GC/step_10304 filter=lfs diff=lfs merge=lfs -text
|
| 247 |
+
mini-GC/step_11592 filter=lfs diff=lfs merge=lfs -text
|
| 248 |
+
mini-GC/step_1288 filter=lfs diff=lfs merge=lfs -text
|
| 249 |
+
mini-GC/step_12880 filter=lfs diff=lfs merge=lfs -text
|
| 250 |
+
mini-GC/step_2576 filter=lfs diff=lfs merge=lfs -text
|
| 251 |
+
mini-GC/step_3864 filter=lfs diff=lfs merge=lfs -text
|
| 252 |
+
mini-GC/step_5152 filter=lfs diff=lfs merge=lfs -text
|
| 253 |
+
mini-GC/step_6440 filter=lfs diff=lfs merge=lfs -text
|
| 254 |
+
mini-GC/step_7728 filter=lfs diff=lfs merge=lfs -text
|
| 255 |
+
mini-GC/step_9016 filter=lfs diff=lfs merge=lfs -text
|
mini-GC/all_config.yaml
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
arch:
|
| 2 |
+
ACT_threshold: 0
|
| 3 |
+
H_cycles: 3
|
| 4 |
+
H_layers: 0
|
| 5 |
+
L_cycles: 4
|
| 6 |
+
L_layers: 2
|
| 7 |
+
expansion: 4
|
| 8 |
+
forward_dtype: bfloat16
|
| 9 |
+
group_emb_len: 1
|
| 10 |
+
halt_exploration_prob: 0.1
|
| 11 |
+
halt_max_steps: 16
|
| 12 |
+
hidden_size: 512
|
| 13 |
+
loss:
|
| 14 |
+
alpha: 0.5
|
| 15 |
+
loss_type: stablemax_cross_entropy
|
| 16 |
+
name: losses@ACTLossHead
|
| 17 |
+
mlp_t: false
|
| 18 |
+
name: recursive_reasoning.trm@TinyRecursiveReasoningModel_ACTV1
|
| 19 |
+
no_ACT_continue: true
|
| 20 |
+
num_heads: 8
|
| 21 |
+
pos_encodings: rope
|
| 22 |
+
puzzle_emb_len: 16
|
| 23 |
+
puzzle_emb_ndim: 512
|
| 24 |
+
universal_emb_len: 1
|
| 25 |
+
beta1: 0.9
|
| 26 |
+
beta2: 0.95
|
| 27 |
+
checkpoint_every_eval: true
|
| 28 |
+
checkpoint_path: ./checkpoint/miniarc/mini_GC_losses@ACTLossHead
|
| 29 |
+
data_paths:
|
| 30 |
+
- data/miniARC-aug-1000
|
| 31 |
+
data_paths_test: []
|
| 32 |
+
ema: true
|
| 33 |
+
ema_rate: 0.999
|
| 34 |
+
epochs: 100000
|
| 35 |
+
eval_interval: 10000
|
| 36 |
+
eval_save_outputs: []
|
| 37 |
+
evaluators: []
|
| 38 |
+
freeze_weights: false
|
| 39 |
+
global_batch_size: 4096
|
| 40 |
+
group_emb_lr: 0.001
|
| 41 |
+
group_emb_weight_decay: 0.1
|
| 42 |
+
load_checkpoint: null
|
| 43 |
+
lr: 0.0001
|
| 44 |
+
lr_min_ratio: 1.0
|
| 45 |
+
lr_warmup_steps: 2000
|
| 46 |
+
min_eval_interval: 0
|
| 47 |
+
project_name: Miniarc-aug-1000-ACT-torch
|
| 48 |
+
puzzle_emb_lr: 0.01
|
| 49 |
+
puzzle_emb_weight_decay: 0.1
|
| 50 |
+
run_name: mini_GC_losses@ACTLossHead
|
| 51 |
+
seed: 0
|
| 52 |
+
weight_decay: 0.1
|
mini-GC/losses.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, alpha: float = 0.5):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.model = model
|
| 45 |
+
self.loss_fn = globals()[loss_type]
|
| 46 |
+
|
| 47 |
+
def initial_carry(self, *args, **kwargs):
|
| 48 |
+
return self.model.initial_carry(*args, **kwargs) # type: ignore
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts):
|
| 52 |
+
q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
|
| 53 |
+
return q_halt_loss
|
| 54 |
+
|
| 55 |
+
def forward(
|
| 56 |
+
self,
|
| 57 |
+
return_keys: Sequence[str],
|
| 58 |
+
# Model args
|
| 59 |
+
**model_kwargs,
|
| 60 |
+
) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
|
| 61 |
+
# Model logits
|
| 62 |
+
# B x SeqLen x D
|
| 63 |
+
new_carry, outputs = self.model(**model_kwargs)
|
| 64 |
+
labels = new_carry.current_data["labels"]
|
| 65 |
+
|
| 66 |
+
with torch.no_grad():
|
| 67 |
+
# Preds
|
| 68 |
+
outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
|
| 69 |
+
|
| 70 |
+
# Correctness
|
| 71 |
+
mask = (labels != IGNORE_LABEL_ID)
|
| 72 |
+
loss_counts = mask.sum(-1)
|
| 73 |
+
loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
|
| 74 |
+
|
| 75 |
+
is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
|
| 76 |
+
seq_is_correct = is_correct.sum(-1) == loss_counts
|
| 77 |
+
|
| 78 |
+
# Metrics (halted)
|
| 79 |
+
valid_metrics = new_carry.halted & (loss_counts > 0)
|
| 80 |
+
metrics = {
|
| 81 |
+
"count": valid_metrics.sum(),
|
| 82 |
+
|
| 83 |
+
"accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
|
| 84 |
+
"exact_accuracy": (valid_metrics & seq_is_correct).sum(),
|
| 85 |
+
|
| 86 |
+
"q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
|
| 87 |
+
"steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
# Losses
|
| 91 |
+
lm_loss = (self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID, valid_mask=mask) / loss_divisor).sum()
|
| 92 |
+
q_halt_loss = self.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
|
| 93 |
+
metrics.update({
|
| 94 |
+
"lm_loss": lm_loss.detach(),
|
| 95 |
+
"q_halt_loss": q_halt_loss.detach(),
|
| 96 |
+
})
|
| 97 |
+
# Q continue (bootstrapping target loss); Alexia: This fits Q-learning, but seems totally unecessary
|
| 98 |
+
q_continue_loss = 0
|
| 99 |
+
if "target_q_continue" in outputs:
|
| 100 |
+
q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
|
| 101 |
+
|
| 102 |
+
metrics["q_continue_loss"] = q_continue_loss.detach()
|
| 103 |
+
# Filter outputs for return
|
| 104 |
+
detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
|
| 105 |
+
|
| 106 |
+
return new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss), metrics, detached_outputs, new_carry.halted.all()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class ACTLossHead_binorminal(ACTLossHead):
|
| 110 |
+
def __init__(self, model: nn.Module, loss_type: str, alpha: float = 0.5):
|
| 111 |
+
super().__init__(model, loss_type)
|
| 112 |
+
|
| 113 |
+
@staticmethod
|
| 114 |
+
def comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts):
|
| 115 |
+
t = (is_correct.sum(-1) / loss_counts.clamp_min(1)).to(outputs["q_halt_logits"].dtype) # [B] in [0,1]
|
| 116 |
+
|
| 117 |
+
# Force t=1 for sequences with no valid tokens
|
| 118 |
+
t = torch.where(loss_counts == 0, torch.ones_like(t), t)
|
| 119 |
+
q_halt_loss = F.binary_cross_entropy_with_logits(
|
| 120 |
+
outputs["q_halt_logits"], t, reduction="sum"
|
| 121 |
+
)
|
| 122 |
+
return q_halt_loss
|
| 123 |
+
|
| 124 |
+
class ACTLossHead_combine(ACTLossHead):
|
| 125 |
+
def __init__(self, model: nn.Module, loss_type: str, alpha: float = 0.5):
|
| 126 |
+
super().__init__(model, loss_type)
|
| 127 |
+
self.alpha = alpha
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts):
|
| 131 |
+
q_halt_bce_loss = ACTLossHead.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
|
| 132 |
+
q_halt_binorm_loss = ACTLossHead_binorminal.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
|
| 133 |
+
q_halt_loss = self.alpha * q_halt_bce_loss + (1 - self.alpha) * q_halt_binorm_loss
|
| 134 |
+
return q_halt_loss
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class ACTLossHead_binormonly(ACTLossHead_binorminal):
|
| 138 |
+
def __init__(self, model: nn.Module, loss_type: str):
|
| 139 |
+
super().__init__(model, loss_type)
|
| 140 |
+
|
| 141 |
+
def forward(
|
| 142 |
+
self,
|
| 143 |
+
return_keys: Sequence[str],
|
| 144 |
+
# Model args
|
| 145 |
+
**model_kwargs,
|
| 146 |
+
) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
|
| 147 |
+
# Model logits
|
| 148 |
+
# B x SeqLen x D
|
| 149 |
+
new_carry, outputs = self.model(**model_kwargs)
|
| 150 |
+
labels = new_carry.current_data["labels"]
|
| 151 |
+
|
| 152 |
+
with torch.no_grad():
|
| 153 |
+
# Preds
|
| 154 |
+
outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
|
| 155 |
+
|
| 156 |
+
# Correctness
|
| 157 |
+
mask = (labels != IGNORE_LABEL_ID)
|
| 158 |
+
loss_counts = mask.sum(-1)
|
| 159 |
+
loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
|
| 160 |
+
|
| 161 |
+
is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
|
| 162 |
+
seq_is_correct = is_correct.sum(-1) == loss_counts
|
| 163 |
+
|
| 164 |
+
# Metrics (halted)
|
| 165 |
+
valid_metrics = new_carry.halted & (loss_counts > 0)
|
| 166 |
+
metrics = {
|
| 167 |
+
"count": valid_metrics.sum(),
|
| 168 |
+
|
| 169 |
+
"accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
|
| 170 |
+
"exact_accuracy": (valid_metrics & seq_is_correct).sum(),
|
| 171 |
+
|
| 172 |
+
"q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
|
| 173 |
+
"steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
# Losses
|
| 177 |
+
lm_loss = (self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID, valid_mask=mask) / loss_divisor).sum()
|
| 178 |
+
q_halt_loss = self.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
|
| 179 |
+
metrics.update({
|
| 180 |
+
"lm_loss": lm_loss.detach(),
|
| 181 |
+
"q_halt_loss": q_halt_loss.detach(),
|
| 182 |
+
})
|
| 183 |
+
# Q continue (bootstrapping target loss); Alexia: This fits Q-learning, but seems totally unecessary
|
| 184 |
+
q_continue_loss = 0
|
| 185 |
+
if "target_q_continue" in outputs:
|
| 186 |
+
q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
|
| 187 |
+
|
| 188 |
+
metrics["q_continue_loss"] = q_continue_loss.detach()
|
| 189 |
+
# Filter outputs for return
|
| 190 |
+
detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
|
| 191 |
+
|
| 192 |
+
return new_carry, (q_halt_loss + q_continue_loss), metrics, detached_outputs, new_carry.halted.all()
|
mini-GC/step_10304
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d17091f5de2135661325fe3fbb972c340e4aa0ddf28bb75045402e9ff9aceb63
|
| 3 |
+
size 270927925
|
mini-GC/step_11592
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5ed5cb340c8ae0137b5e40545123d21b8b282fc18cf0ea98530fa479aeacc49b
|
| 3 |
+
size 270927925
|
mini-GC/step_1288
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4922745deb401c0a2447223ae9fde8ece3fbf5bbe2681ebc93aa182dbcaab244
|
| 3 |
+
size 270927902
|
mini-GC/step_12880
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5e366e61f3bd49e95e0f41a57fa922e56fff129b1bec0ac9fd00328acd49500f
|
| 3 |
+
size 270927925
|
mini-GC/step_2576
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c398e2ad28b143db9a0f21ff085c3f748dd0bf2b084f5ab933310108bc8bc47b
|
| 3 |
+
size 270927902
|
mini-GC/step_3864
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:667a203fcd93a03fc3154a5f59e4b2c4ab23ff7340306cb03461d0d17f87ff33
|
| 3 |
+
size 270927902
|
mini-GC/step_5152
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0bd545e486f722cb4c359ca78f127b27123cb21b840cf9ddf9d3183cdd8f5892
|
| 3 |
+
size 270927902
|
mini-GC/step_6440
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ca4b025dd6b276bc191d53b4ed0ebb9da40f2a7edd28d1cff3a7725df46bf5d6
|
| 3 |
+
size 270927902
|
mini-GC/step_7728
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d40aac6ab02626026b4703b18ae42a66ebfbcfd87a45411a77f3334a2749d93f
|
| 3 |
+
size 270927902
|
mini-GC/step_9016
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b0521aeb7f5778e7f1d4879b35de69a3e045071b5b0077551005344ca7f8e2c8
|
| 3 |
+
size 270927902
|
mini-GC/trm.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple, List, Dict, Optional
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
import math
|
| 4 |
+
import torch
|
| 5 |
+
import copy
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import nn
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
import random
|
| 10 |
+
from models.common import trunc_normal_init_
|
| 11 |
+
from models.layers import rms_norm, LinearSwish, SwiGLU, Attention, RotaryEmbedding, CosSin, CastedEmbedding, CastedLinear
|
| 12 |
+
from models.sparse_embedding import CastedSparseEmbedding
|
| 13 |
+
|
| 14 |
+
IGNORE_LABEL_ID = -100
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class TinyRecursiveReasoningModel_ACTV1InnerCarry:
|
| 18 |
+
z_H: torch.Tensor
|
| 19 |
+
z_L: torch.Tensor
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class TinyRecursiveReasoningModel_ACTV1Carry:
|
| 24 |
+
inner_carry: TinyRecursiveReasoningModel_ACTV1InnerCarry
|
| 25 |
+
|
| 26 |
+
steps: torch.Tensor
|
| 27 |
+
halted: torch.Tensor
|
| 28 |
+
|
| 29 |
+
current_data: Dict[str, torch.Tensor]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TinyRecursiveReasoningModel_ACTV1Config(BaseModel):
|
| 33 |
+
batch_size: int
|
| 34 |
+
seq_len: int
|
| 35 |
+
puzzle_emb_ndim: int = 0
|
| 36 |
+
universal_emb_len: int = 0
|
| 37 |
+
group_emb_len: int = 0
|
| 38 |
+
num_puzzle_identifiers: int
|
| 39 |
+
num_groups: int
|
| 40 |
+
vocab_size: int
|
| 41 |
+
|
| 42 |
+
H_cycles: int
|
| 43 |
+
L_cycles: int
|
| 44 |
+
|
| 45 |
+
H_layers: int # ignored
|
| 46 |
+
L_layers: int
|
| 47 |
+
|
| 48 |
+
# Transformer config
|
| 49 |
+
hidden_size: int
|
| 50 |
+
expansion: float
|
| 51 |
+
num_heads: int
|
| 52 |
+
pos_encodings: str
|
| 53 |
+
|
| 54 |
+
rms_norm_eps: float = 1e-5
|
| 55 |
+
rope_theta: float = 10000.0
|
| 56 |
+
|
| 57 |
+
# Halting Q-learning config
|
| 58 |
+
halt_max_steps: int
|
| 59 |
+
halt_exploration_prob: float
|
| 60 |
+
puzzle_emb_len: int = 16 # if non-zero, its specified to this value
|
| 61 |
+
forward_dtype: str = "bfloat16"
|
| 62 |
+
|
| 63 |
+
# Alexia: added
|
| 64 |
+
mlp_t: bool = False # use mlp on L instead of transformer
|
| 65 |
+
no_ACT_continue: bool = True # No continue ACT loss, only use the sigmoid of the halt which makes much more sense
|
| 66 |
+
|
| 67 |
+
# chan edit
|
| 68 |
+
eval_with_ACT: bool = False # During evaluation, whether to use ACT halting or just run max steps. Using ACT halting will cause more variance in evaluation results, but is a more realistic evaluation of the model performance when deployed.
|
| 69 |
+
ACT_threshold: float = 0 # Threshold for ACT halting during evaluation, only used if eval_with_ACT is True
|
| 70 |
+
|
| 71 |
+
class TinyRecursiveReasoningModel_ACTGymConfig(BaseModel):
|
| 72 |
+
replace_halt_threshold: int = 1
|
| 73 |
+
target_latent_for_reinit: str = "L"
|
| 74 |
+
|
| 75 |
+
class TinyRecursiveReasoningModel_ACTGym(BaseModel):
|
| 76 |
+
"""ACT wrapper."""
|
| 77 |
+
|
| 78 |
+
def __init__(self, config_dict: dict):
|
| 79 |
+
super().__init__(config_dict)
|
| 80 |
+
self.replace_halt_threshold: int = 1
|
| 81 |
+
self.target_latent_for_reinit: str = "L"
|
| 82 |
+
|
| 83 |
+
class TinyRecursiveReasoningModel_ACTV1Block(nn.Module):
|
| 84 |
+
def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config, puzzle_emb_len: int) -> None:
|
| 85 |
+
super().__init__()
|
| 86 |
+
|
| 87 |
+
self.config = config
|
| 88 |
+
if self.config.mlp_t:
|
| 89 |
+
self.puzzle_emb_len = puzzle_emb_len
|
| 90 |
+
self.mlp_t = SwiGLU(
|
| 91 |
+
hidden_size=self.config.seq_len + self.puzzle_emb_len, # L
|
| 92 |
+
expansion=config.expansion,
|
| 93 |
+
)
|
| 94 |
+
else:
|
| 95 |
+
self.self_attn = Attention(
|
| 96 |
+
hidden_size=config.hidden_size,
|
| 97 |
+
head_dim=config.hidden_size // config.num_heads,
|
| 98 |
+
num_heads=config.num_heads,
|
| 99 |
+
num_key_value_heads=config.num_heads,
|
| 100 |
+
causal=False
|
| 101 |
+
)
|
| 102 |
+
self.mlp = SwiGLU(
|
| 103 |
+
hidden_size=config.hidden_size,
|
| 104 |
+
expansion=config.expansion,
|
| 105 |
+
)
|
| 106 |
+
self.norm_eps = config.rms_norm_eps
|
| 107 |
+
|
| 108 |
+
def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
# B, L, D = hidden_states.shape
|
| 110 |
+
# Post Norm
|
| 111 |
+
if self.config.mlp_t:
|
| 112 |
+
hidden_states = hidden_states.transpose(1,2)
|
| 113 |
+
out = self.mlp_t(hidden_states)
|
| 114 |
+
hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
|
| 115 |
+
hidden_states = hidden_states.transpose(1,2)
|
| 116 |
+
else:
|
| 117 |
+
# Self Attention
|
| 118 |
+
hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
|
| 119 |
+
# Fully Connected
|
| 120 |
+
out = self.mlp(hidden_states)
|
| 121 |
+
hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
|
| 122 |
+
return hidden_states
|
| 123 |
+
|
| 124 |
+
class TinyRecursiveReasoningModel_ACTV1ReasoningModule(nn.Module):
|
| 125 |
+
def __init__(self, layers: List[TinyRecursiveReasoningModel_ACTV1Block]):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.layers = torch.nn.ModuleList(layers)
|
| 128 |
+
|
| 129 |
+
def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
|
| 130 |
+
hidden_states = hidden_states + input_injection
|
| 131 |
+
for layer in self.layers:
|
| 132 |
+
hidden_states = layer(hidden_states=hidden_states, **kwargs)
|
| 133 |
+
return hidden_states
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TinyRecursiveReasoningModel_ACTV1_Inner(nn.Module):
|
| 137 |
+
def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
|
| 138 |
+
super().__init__()
|
| 139 |
+
self.config = config
|
| 140 |
+
self.forward_dtype = getattr(torch, self.config.forward_dtype)
|
| 141 |
+
|
| 142 |
+
# I/O
|
| 143 |
+
|
| 144 |
+
self.embed_scale = math.sqrt(self.config.hidden_size)
|
| 145 |
+
embed_init_std = 1.0 / self.embed_scale
|
| 146 |
+
|
| 147 |
+
self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
|
| 148 |
+
self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
|
| 149 |
+
self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
|
| 150 |
+
|
| 151 |
+
if self.config.puzzle_emb_ndim > 0:
|
| 152 |
+
# Zero init puzzle embeddings
|
| 153 |
+
self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
|
| 154 |
+
batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
|
| 155 |
+
|
| 156 |
+
self.group_embedding_dim = self.config.group_emb_len * self.config.hidden_size
|
| 157 |
+
if self.group_embedding_dim > 0:
|
| 158 |
+
# Zero init group embeddings
|
| 159 |
+
self.group_emb = CastedSparseEmbedding(self.config.num_groups, self.group_embedding_dim,
|
| 160 |
+
batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
|
| 161 |
+
|
| 162 |
+
self.universal_emb_ndim = self.config.universal_emb_len * self.config.hidden_size
|
| 163 |
+
if self.universal_emb_ndim > 0:
|
| 164 |
+
# Universal embedding, shared between tokens and puzzles, with non-zero init
|
| 165 |
+
self.universal_emb = CastedEmbedding(1, self.universal_emb_ndim, init_std=embed_init_std, cast_to=self.forward_dtype)
|
| 166 |
+
|
| 167 |
+
print("Puzzle embedding ndim:", self.config.puzzle_emb_ndim)
|
| 168 |
+
print("Group embedding ndim:", self.group_embedding_dim)
|
| 169 |
+
print("Universal embedding ndim:", self.universal_emb_ndim)
|
| 170 |
+
print("Puzzle embed length:", self.config.puzzle_emb_len)
|
| 171 |
+
total_puzzle_emb_dim = self.config.puzzle_emb_ndim + self.group_embedding_dim + self.universal_emb_ndim
|
| 172 |
+
self.puzzle_emb_len = max(-(total_puzzle_emb_dim // -self.config.hidden_size), self.config.puzzle_emb_len) # ceil div
|
| 173 |
+
print("Total puzzle embedding dim:", total_puzzle_emb_dim)
|
| 174 |
+
print("Final puzzle embedding length (in tokens):", self.puzzle_emb_len)
|
| 175 |
+
|
| 176 |
+
# LM Blocks
|
| 177 |
+
if self.config.pos_encodings == "rope":
|
| 178 |
+
self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
|
| 179 |
+
max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
|
| 180 |
+
base=self.config.rope_theta)
|
| 181 |
+
elif self.config.pos_encodings == "learned":
|
| 182 |
+
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)
|
| 183 |
+
else:
|
| 184 |
+
pass
|
| 185 |
+
|
| 186 |
+
# Reasoning Layers
|
| 187 |
+
self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[TinyRecursiveReasoningModel_ACTV1Block(self.config, self.puzzle_emb_len) for _i in range(self.config.L_layers)])
|
| 188 |
+
|
| 189 |
+
# Initial states
|
| 190 |
+
self.H_init = self.init_latent_buffer(self.config.hidden_size, self.forward_dtype)
|
| 191 |
+
self.L_init = self.init_latent_buffer(self.config.hidden_size, self.forward_dtype)
|
| 192 |
+
|
| 193 |
+
# Q head special init
|
| 194 |
+
# Init Q to (almost) zero for faster learning during bootstrapping
|
| 195 |
+
with torch.no_grad():
|
| 196 |
+
self.q_head.weight.zero_()
|
| 197 |
+
self.q_head.bias.fill_(-5) # type: ignore
|
| 198 |
+
|
| 199 |
+
@staticmethod
|
| 200 |
+
def init_latent_buffer(
|
| 201 |
+
hidden_size: int,
|
| 202 |
+
forward_dtype: torch.dtype,
|
| 203 |
+
persistent: bool = True,
|
| 204 |
+
device: Optional[torch.device] = None,
|
| 205 |
+
) -> torch.Tensor:
|
| 206 |
+
return nn.Buffer(
|
| 207 |
+
trunc_normal_init_(torch.empty(hidden_size, dtype=forward_dtype, device=device), std=1),
|
| 208 |
+
persistent=persistent,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, group_indices: torch.Tensor):
|
| 212 |
+
# Token embedding
|
| 213 |
+
embedding = self.embed_tokens(input.to(torch.int32))
|
| 214 |
+
|
| 215 |
+
# Puzzle embeddings
|
| 216 |
+
if self.config.puzzle_emb_ndim > 0:
|
| 217 |
+
puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
|
| 218 |
+
|
| 219 |
+
if self.config.group_emb_len > 0:
|
| 220 |
+
group_embedding = self.group_emb(group_indices)
|
| 221 |
+
|
| 222 |
+
# concat along feature dim -> (B, Dp + Dg)
|
| 223 |
+
puzzle_embedding = torch.cat([puzzle_embedding, group_embedding], dim=-1)
|
| 224 |
+
|
| 225 |
+
if self.config.universal_emb_len > 0:
|
| 226 |
+
# universal_embedding: (B, Du)
|
| 227 |
+
universal_embedding = self.universal_emb(torch.zeros(puzzle_embedding.size(0), device=puzzle_embedding.device, dtype=torch.long))
|
| 228 |
+
|
| 229 |
+
# concat along feature dim -> (B, Dp + (Dg) + Du)
|
| 230 |
+
puzzle_embedding = torch.cat([puzzle_embedding, universal_embedding], dim=-1)
|
| 231 |
+
|
| 232 |
+
pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
|
| 233 |
+
if pad_count > 0:
|
| 234 |
+
puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
|
| 235 |
+
|
| 236 |
+
embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
|
| 237 |
+
|
| 238 |
+
# Position embeddings
|
| 239 |
+
if self.config.pos_encodings == "learned":
|
| 240 |
+
# scale by 1/sqrt(2) to maintain forward variance
|
| 241 |
+
embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
|
| 242 |
+
|
| 243 |
+
# Scale
|
| 244 |
+
return self.embed_scale * embedding
|
| 245 |
+
|
| 246 |
+
def empty_carry(self, batch_size: int):
|
| 247 |
+
return TinyRecursiveReasoningModel_ACTV1InnerCarry(
|
| 248 |
+
z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
|
| 249 |
+
z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
def reset_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry):
|
| 253 |
+
return TinyRecursiveReasoningModel_ACTV1InnerCarry(
|
| 254 |
+
z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
|
| 255 |
+
z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
def re_inittialize_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, target_latent: Optional[str] = None):
|
| 259 |
+
target_device = carry.z_L.device
|
| 260 |
+
if target_latent == "LH":
|
| 261 |
+
return TinyRecursiveReasoningModel_ACTV1InnerCarry(
|
| 262 |
+
z_H=torch.where(
|
| 263 |
+
reset_flag.view(-1, 1, 1),
|
| 264 |
+
self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device),
|
| 265 |
+
carry.z_H,
|
| 266 |
+
),
|
| 267 |
+
z_L=torch.where(
|
| 268 |
+
reset_flag.view(-1, 1, 1),
|
| 269 |
+
self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device),
|
| 270 |
+
carry.z_L,
|
| 271 |
+
),
|
| 272 |
+
)
|
| 273 |
+
elif target_latent == "H":
|
| 274 |
+
return TinyRecursiveReasoningModel_ACTV1InnerCarry(
|
| 275 |
+
z_H=torch.where(
|
| 276 |
+
reset_flag.view(-1, 1, 1),
|
| 277 |
+
self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device),
|
| 278 |
+
carry.z_H,
|
| 279 |
+
),
|
| 280 |
+
z_L=carry.z_L
|
| 281 |
+
)
|
| 282 |
+
elif target_latent == "L":
|
| 283 |
+
return TinyRecursiveReasoningModel_ACTV1InnerCarry(
|
| 284 |
+
z_H=carry.z_H,
|
| 285 |
+
z_L=torch.where(
|
| 286 |
+
reset_flag.view(-1, 1, 1),
|
| 287 |
+
self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device),
|
| 288 |
+
carry.z_L,
|
| 289 |
+
)
|
| 290 |
+
)
|
| 291 |
+
else:
|
| 292 |
+
raise ValueError(f"Invalid target_latent value: {target_latent}")
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
| 296 |
+
seq_info = dict(
|
| 297 |
+
cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
# Input encoding
|
| 301 |
+
input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"], batch["group_indices"])
|
| 302 |
+
|
| 303 |
+
# Forward iterations
|
| 304 |
+
it = 0
|
| 305 |
+
z_H, z_L = carry.z_H, carry.z_L
|
| 306 |
+
# H_cycles-1 without grad
|
| 307 |
+
with torch.no_grad():
|
| 308 |
+
for _H_step in range(self.config.H_cycles-1):
|
| 309 |
+
for _L_step in range(self.config.L_cycles):
|
| 310 |
+
z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
|
| 311 |
+
z_H = self.L_level(z_H, z_L, **seq_info)
|
| 312 |
+
# 1 with grad
|
| 313 |
+
for _L_step in range(self.config.L_cycles):
|
| 314 |
+
z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
|
| 315 |
+
z_H = self.L_level(z_H, z_L, **seq_info)
|
| 316 |
+
|
| 317 |
+
# LM Outputs
|
| 318 |
+
new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach()) # New carry no grad
|
| 319 |
+
output = self.lm_head(z_H)[:, self.puzzle_emb_len:]
|
| 320 |
+
q_logits = self.q_head(z_H[:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
|
| 321 |
+
return new_carry, output, (q_logits[..., 0], q_logits[..., 1])
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class TinyRecursiveReasoningModel_ACTV1(nn.Module):
|
| 325 |
+
"""ACT wrapper."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, config_dict: dict):
|
| 328 |
+
super().__init__()
|
| 329 |
+
self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
|
| 330 |
+
self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def puzzle_emb(self):
|
| 334 |
+
return self.inner.puzzle_emb
|
| 335 |
+
|
| 336 |
+
@property
|
| 337 |
+
def group_emb(self):
|
| 338 |
+
return self.inner.group_emb
|
| 339 |
+
|
| 340 |
+
def initial_carry(self, batch: Dict[str, torch.Tensor]):
|
| 341 |
+
batch_size = batch["inputs"].shape[0]
|
| 342 |
+
|
| 343 |
+
return TinyRecursiveReasoningModel_ACTV1Carry(
|
| 344 |
+
inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
|
| 345 |
+
|
| 346 |
+
steps=torch.zeros((batch_size, ), dtype=torch.int32),
|
| 347 |
+
halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
|
| 348 |
+
|
| 349 |
+
current_data={k: torch.empty_like(v) for k, v in batch.items()}
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
def step_inner_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
|
| 353 |
+
new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
|
| 354 |
+
return new_inner_carry
|
| 355 |
+
|
| 356 |
+
def step_current_data(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
|
| 357 |
+
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()}
|
| 358 |
+
return new_current_data
|
| 359 |
+
|
| 360 |
+
def step_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
|
| 361 |
+
# Step inner carry
|
| 362 |
+
new_inner_carry = self.step_inner_carry(carry, batch)
|
| 363 |
+
|
| 364 |
+
new_steps = torch.where(carry.halted, 0, carry.steps)
|
| 365 |
+
|
| 366 |
+
# Update data, carry (removing halted sequences)
|
| 367 |
+
new_current_data = self.step_current_data(carry, batch)
|
| 368 |
+
|
| 369 |
+
return new_inner_carry, new_steps, new_current_data
|
| 370 |
+
|
| 371 |
+
def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
|
| 372 |
+
|
| 373 |
+
new_inner_carry, new_steps, new_current_data = self.step_carry(carry, batch)
|
| 374 |
+
|
| 375 |
+
# Forward inner model
|
| 376 |
+
new_inner_carry, logits, (q_halt_logits, q_continue_logits) = self.inner(new_inner_carry, new_current_data)
|
| 377 |
+
|
| 378 |
+
outputs = {
|
| 379 |
+
"logits": logits,
|
| 380 |
+
"q_halt_logits": q_halt_logits,
|
| 381 |
+
"q_continue_logits": q_continue_logits
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
with torch.no_grad():
|
| 385 |
+
# Step
|
| 386 |
+
new_steps = new_steps + 1
|
| 387 |
+
is_last_step = new_steps >= self.config.halt_max_steps
|
| 388 |
+
|
| 389 |
+
halted = is_last_step
|
| 390 |
+
|
| 391 |
+
# if training, and ACT is enabled
|
| 392 |
+
if self.training and (self.config.halt_max_steps > 1) or (self.config.eval_with_ACT):
|
| 393 |
+
|
| 394 |
+
# Halt signal
|
| 395 |
+
# NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
|
| 396 |
+
|
| 397 |
+
if self.config.no_ACT_continue:
|
| 398 |
+
halted = halted | (q_halt_logits > self.config.ACT_threshold)
|
| 399 |
+
else:
|
| 400 |
+
halted = halted | (q_halt_logits > q_continue_logits)
|
| 401 |
+
|
| 402 |
+
# Exploration
|
| 403 |
+
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)
|
| 404 |
+
halted = halted & (new_steps >= min_halt_steps)
|
| 405 |
+
|
| 406 |
+
if not self.config.no_ACT_continue:
|
| 407 |
+
# Compute target Q
|
| 408 |
+
# NOTE: No replay buffer and target networks for computing target Q-value.
|
| 409 |
+
# As batch_size is large, there're many parallel envs.
|
| 410 |
+
# Similar concept as PQN https://arxiv.org/abs/2407.04811
|
| 411 |
+
_, _, (next_q_halt_logits, next_q_continue_logits), _, _ = self.inner(new_inner_carry, new_current_data)
|
| 412 |
+
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)))
|
| 413 |
+
|
| 414 |
+
return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class TinyRecursiveReasoningModel_ACTGym(TinyRecursiveReasoningModel_ACTV1):
|
| 418 |
+
"""ACT wrapper."""
|
| 419 |
+
|
| 420 |
+
def __init__(self, config_dict: dict):
|
| 421 |
+
super().__init__(config_dict)
|
| 422 |
+
self.GymConfig = TinyRecursiveReasoningModel_ACTGymConfig(**config_dict)
|
| 423 |
+
|
| 424 |
+
def step_inner_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
|
| 425 |
+
# check the first step where all halted and steps is 0
|
| 426 |
+
new_inner_carry = self.inner.reset_carry(carry.halted & (carry.steps > self.GymConfig.replace_halt_threshold), carry.inner_carry)
|
| 427 |
+
|
| 428 |
+
new_inner_carry = self.inner.re_inittialize_carry(carry.halted & (carry.steps <= self.GymConfig.replace_halt_threshold), new_inner_carry, target_latent=self.GymConfig.target_latent_for_reinit)
|
| 429 |
+
return new_inner_carry
|
| 430 |
+
|
| 431 |
+
def step_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
|
| 432 |
+
# Step inner carry
|
| 433 |
+
new_inner_carry = None
|
| 434 |
+
if (carry.halted & (carry.steps == 0)).all():
|
| 435 |
+
new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
|
| 436 |
+
else:
|
| 437 |
+
new_inner_carry = self.step_inner_carry(carry, batch)
|
| 438 |
+
carry.halted = carry.halted & (carry.steps > self.GymConfig.replace_halt_threshold)
|
| 439 |
+
|
| 440 |
+
new_steps = torch.where(carry.halted, 0, carry.steps)
|
| 441 |
+
|
| 442 |
+
# Update data, carry (removing halted sequences)
|
| 443 |
+
new_current_data = self.step_current_data(carry, batch)
|
| 444 |
+
|
| 445 |
+
return new_inner_carry, new_steps, new_current_data
|