ChanBeDu commited on
Commit
4ef033d
·
verified ·
1 Parent(s): dc85b4e

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -163,3 +163,13 @@ arc1-GC/step_25933 filter=lfs diff=lfs merge=lfs -text
163
  arc1-GC/step_259332 filter=lfs diff=lfs merge=lfs -text
164
  arc1-GC/step_51866 filter=lfs diff=lfs merge=lfs -text
165
  arc1-GC/step_77800 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
163
  arc1-GC/step_259332 filter=lfs diff=lfs merge=lfs -text
164
  arc1-GC/step_51866 filter=lfs diff=lfs merge=lfs -text
165
  arc1-GC/step_77800 filter=lfs diff=lfs merge=lfs -text
166
+ arc1-Gym1H/step_103733 filter=lfs diff=lfs merge=lfs -text
167
+ arc1-Gym1H/step_129666 filter=lfs diff=lfs merge=lfs -text
168
+ arc1-Gym1H/step_155599 filter=lfs diff=lfs merge=lfs -text
169
+ arc1-Gym1H/step_181533 filter=lfs diff=lfs merge=lfs -text
170
+ arc1-Gym1H/step_207466 filter=lfs diff=lfs merge=lfs -text
171
+ arc1-Gym1H/step_233399 filter=lfs diff=lfs merge=lfs -text
172
+ arc1-Gym1H/step_25933 filter=lfs diff=lfs merge=lfs -text
173
+ arc1-Gym1H/step_259332 filter=lfs diff=lfs merge=lfs -text
174
+ arc1-Gym1H/step_51866 filter=lfs diff=lfs merge=lfs -text
175
+ arc1-Gym1H/step_77800 filter=lfs diff=lfs merge=lfs -text
arc1-Gym1H/all_config.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: 0
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_ACTGym
19
+ no_ACT_continue: true
20
+ num_heads: 8
21
+ pos_encodings: rope
22
+ puzzle_emb_len: 16
23
+ puzzle_emb_ndim: 512
24
+ reinit_variance: 1
25
+ replace_halt_threshold: 1
26
+ target_latent_for_reinit: H
27
+ universal_emb_len: 0
28
+ beta1: 0.9
29
+ beta2: 0.95
30
+ checkpoint_every_eval: true
31
+ checkpoint_path: ./checkpoint/arc-trm/checkpoint_full_100k_Gym1H
32
+ data_paths:
33
+ - data/arc1concept-aug-1000
34
+ data_paths_test: []
35
+ ema: true
36
+ ema_rate: 0.999
37
+ epochs: 100000
38
+ eval_interval: 10000
39
+ eval_save_outputs: []
40
+ evaluators: []
41
+ freeze_weights: false
42
+ global_batch_size: 1536
43
+ group_emb_lr: 0.001
44
+ group_emb_weight_decay: 0.1
45
+ load_checkpoint: null
46
+ lr: 0.0001
47
+ lr_min_ratio: 1.0
48
+ lr_warmup_steps: 2000
49
+ min_eval_interval: 0
50
+ project_name: Arc1concept-aug-1000-ACT-torch
51
+ puzzle_emb_lr: 0.01
52
+ puzzle_emb_weight_decay: 0.1
53
+ run_name: pretrain_Gym1H
54
+ seed: 0
55
+ weight_decay: 0.1
arc1-Gym1H/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()
arc1-Gym1H/step_103733 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e369808ca9deffba7a11082b54f8d5199185f20ac57721a5b6a33c21f243d4c1
3
+ size 1822205258
arc1-Gym1H/step_129666 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5aef47f9e37b7f8dc6096e957876e02cb8a3cc73d02af17f5bda70a9987f129c
3
+ size 1822205258
arc1-Gym1H/step_155599 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9010413824c1d9d13fddaf9967c30ea07396ed1e1f86ba2ae25e5ff1912b620
3
+ size 1822205258
arc1-Gym1H/step_181533 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd940778301b9c50d6d03abb654e386c448e04567768ed191cc8cd485522307b
3
+ size 1822205258
arc1-Gym1H/step_207466 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a739342a7f3e6318cfef440d70555046caae0c9189801070fcade0f6cceecec
3
+ size 1822205258
arc1-Gym1H/step_233399 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fa5037ad9f973951a64f02c98a162b04cba89f217f91c63fce3a17072371a73
3
+ size 1822205258
arc1-Gym1H/step_25933 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e523b81d3c9b638955940cca953b2e0fbe444eea1ad1e12f4bea30a1ce89d61f
3
+ size 1822205237
arc1-Gym1H/step_259332 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c44dba6e7377f78ede9d6a63441351c359fb7c6b900c9100b25757a071f1ea2
3
+ size 1822205258
arc1-Gym1H/step_51866 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a95ab6a4349bb0beebc1c67d51fb2274cb9670cd936d529841aa60bf60d45e3e
3
+ size 1822205237
arc1-Gym1H/step_77800 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc7e93303b6c928781dbb2b088c1ee9582ce187bb00e0170743438f5207d972e
3
+ size 1822205237
arc1-Gym1H/trm.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ reinit_variance: float = 1.0 # Variance for reinitializing the latent when halted. This is a hyperparameter that can be tuned. Setting it to 0 will reinitialize to the same value, which may cause the model to learn to rely on this specific value and not learn effectively. Setting it to a very large value will make the reinitialized latent too random, which may also harm learning. A moderate value can help the model learn to recover from halting and continue learning effectively.
75
+
76
+
77
+ class TinyRecursiveReasoningModel_ACTV1Block(nn.Module):
78
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config, puzzle_emb_len: int) -> None:
79
+ super().__init__()
80
+
81
+ self.config = config
82
+ if self.config.mlp_t:
83
+ self.puzzle_emb_len = puzzle_emb_len
84
+ self.mlp_t = SwiGLU(
85
+ hidden_size=self.config.seq_len + self.puzzle_emb_len, # L
86
+ expansion=config.expansion,
87
+ )
88
+ else:
89
+ self.self_attn = Attention(
90
+ hidden_size=config.hidden_size,
91
+ head_dim=config.hidden_size // config.num_heads,
92
+ num_heads=config.num_heads,
93
+ num_key_value_heads=config.num_heads,
94
+ causal=False
95
+ )
96
+ self.mlp = SwiGLU(
97
+ hidden_size=config.hidden_size,
98
+ expansion=config.expansion,
99
+ )
100
+ self.norm_eps = config.rms_norm_eps
101
+
102
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
103
+ # B, L, D = hidden_states.shape
104
+ # Post Norm
105
+ if self.config.mlp_t:
106
+ hidden_states = hidden_states.transpose(1,2)
107
+ out = self.mlp_t(hidden_states)
108
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
109
+ hidden_states = hidden_states.transpose(1,2)
110
+ else:
111
+ # Self Attention
112
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
113
+ # Fully Connected
114
+ out = self.mlp(hidden_states)
115
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
116
+ return hidden_states
117
+
118
+ class TinyRecursiveReasoningModel_ACTV1ReasoningModule(nn.Module):
119
+ def __init__(self, layers: List[TinyRecursiveReasoningModel_ACTV1Block]):
120
+ super().__init__()
121
+ self.layers = torch.nn.ModuleList(layers)
122
+
123
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
124
+ hidden_states = hidden_states + input_injection
125
+ for layer in self.layers:
126
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
127
+ return hidden_states
128
+
129
+
130
+ class TinyRecursiveReasoningModel_ACTV1_Inner(nn.Module):
131
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
132
+ super().__init__()
133
+ self.config = config
134
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
135
+
136
+ # I/O
137
+
138
+ self.embed_scale = math.sqrt(self.config.hidden_size)
139
+ embed_init_std = 1.0 / self.embed_scale
140
+
141
+ self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
142
+ self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
143
+ self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
144
+
145
+ if self.config.puzzle_emb_ndim > 0:
146
+ # Zero init puzzle embeddings
147
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
148
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
149
+
150
+ self.group_embedding_dim = self.config.group_emb_len * self.config.hidden_size
151
+ if self.group_embedding_dim > 0:
152
+ # Zero init group embeddings
153
+ self.group_emb = CastedSparseEmbedding(self.config.num_groups, self.group_embedding_dim,
154
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
155
+
156
+ self.universal_emb_ndim = self.config.universal_emb_len * self.config.hidden_size
157
+ if self.universal_emb_ndim > 0:
158
+ # Universal embedding, shared between tokens and puzzles, with non-zero init
159
+ self.universal_emb = CastedEmbedding(1, self.universal_emb_ndim, init_std=embed_init_std, cast_to=self.forward_dtype)
160
+
161
+ print("Puzzle embedding ndim:", self.config.puzzle_emb_ndim)
162
+ print("Group embedding ndim:", self.group_embedding_dim)
163
+ print("Universal embedding ndim:", self.universal_emb_ndim)
164
+ print("Puzzle embed length:", self.config.puzzle_emb_len)
165
+ total_puzzle_emb_dim = self.config.puzzle_emb_ndim + self.group_embedding_dim + self.universal_emb_ndim
166
+ self.puzzle_emb_len = max(-(total_puzzle_emb_dim // -self.config.hidden_size), self.config.puzzle_emb_len) # ceil div
167
+ print("Total puzzle embedding dim:", total_puzzle_emb_dim)
168
+ print("Final puzzle embedding length (in tokens):", self.puzzle_emb_len)
169
+
170
+ # LM Blocks
171
+ if self.config.pos_encodings == "rope":
172
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
173
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
174
+ base=self.config.rope_theta)
175
+ elif self.config.pos_encodings == "learned":
176
+ 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)
177
+ else:
178
+ pass
179
+
180
+ # Reasoning Layers
181
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[TinyRecursiveReasoningModel_ACTV1Block(self.config, self.puzzle_emb_len) for _i in range(self.config.L_layers)])
182
+
183
+ # Initial states
184
+ self.H_init = self.init_latent_buffer(self.config.hidden_size, self.forward_dtype)
185
+ self.L_init = self.init_latent_buffer(self.config.hidden_size, self.forward_dtype)
186
+
187
+ # Q head special init
188
+ # Init Q to (almost) zero for faster learning during bootstrapping
189
+ with torch.no_grad():
190
+ self.q_head.weight.zero_()
191
+ self.q_head.bias.fill_(-5) # type: ignore
192
+
193
+ @staticmethod
194
+ def init_latent_buffer(
195
+ hidden_size: int,
196
+ forward_dtype: torch.dtype,
197
+ persistent: bool = True,
198
+ device: Optional[torch.device] = None,
199
+ std: float = 1.0
200
+ ) -> torch.Tensor:
201
+ return nn.Buffer(
202
+ trunc_normal_init_(torch.empty(hidden_size, dtype=forward_dtype, device=device), std=std),
203
+ persistent=persistent,
204
+ )
205
+
206
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, group_indices: torch.Tensor):
207
+ # Token embedding
208
+ embedding = self.embed_tokens(input.to(torch.int32))
209
+
210
+ # Puzzle embeddings
211
+ if self.config.puzzle_emb_ndim > 0:
212
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
213
+
214
+ if self.config.group_emb_len > 0:
215
+ group_embedding = self.group_emb(group_indices)
216
+
217
+ # concat along feature dim -> (B, Dp + Dg)
218
+ puzzle_embedding = torch.cat([puzzle_embedding, group_embedding], dim=-1)
219
+
220
+ if self.config.universal_emb_len > 0:
221
+ # universal_embedding: (B, Du)
222
+ universal_embedding = self.universal_emb(torch.zeros(puzzle_embedding.size(0), device=puzzle_embedding.device, dtype=torch.long))
223
+
224
+ # concat along feature dim -> (B, Dp + (Dg) + Du)
225
+ puzzle_embedding = torch.cat([puzzle_embedding, universal_embedding], dim=-1)
226
+
227
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
228
+ if pad_count > 0:
229
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
230
+
231
+ embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
232
+
233
+ # Position embeddings
234
+ if self.config.pos_encodings == "learned":
235
+ # scale by 1/sqrt(2) to maintain forward variance
236
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
237
+
238
+ # Scale
239
+ return self.embed_scale * embedding
240
+
241
+ def empty_carry(self, batch_size: int):
242
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
243
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
244
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
245
+ )
246
+
247
+ def reset_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry):
248
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
249
+ z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
250
+ z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
251
+ )
252
+
253
+ def re_inittialize_carry(
254
+ self,
255
+ reset_flag: torch.Tensor,
256
+ carry: TinyRecursiveReasoningModel_ACTV1InnerCarry,
257
+ target_latent: Optional[str] = None,
258
+ init_std: float = 1.0
259
+ ):
260
+ target_device = carry.z_L.device
261
+ if target_latent == "LH":
262
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
263
+ z_H=torch.where(
264
+ reset_flag.view(-1, 1, 1),
265
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
266
+ carry.z_H,
267
+ ),
268
+ z_L=torch.where(
269
+ reset_flag.view(-1, 1, 1),
270
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
271
+ carry.z_L,
272
+ ),
273
+ )
274
+ elif target_latent == "H":
275
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
276
+ z_H=torch.where(
277
+ reset_flag.view(-1, 1, 1),
278
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
279
+ carry.z_H,
280
+ ),
281
+ z_L=carry.z_L
282
+ )
283
+ elif target_latent == "L":
284
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
285
+ z_H=carry.z_H,
286
+ z_L=torch.where(
287
+ reset_flag.view(-1, 1, 1),
288
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
289
+ carry.z_L,
290
+ )
291
+ )
292
+ else:
293
+ raise ValueError(f"Invalid target_latent value: {target_latent}")
294
+
295
+
296
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
297
+ seq_info = dict(
298
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
299
+ )
300
+
301
+ # Input encoding
302
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"], batch["group_indices"])
303
+
304
+ # Forward iterations
305
+ it = 0
306
+ z_H, z_L = carry.z_H, carry.z_L
307
+ # H_cycles-1 without grad
308
+ with torch.no_grad():
309
+ for _H_step in range(self.config.H_cycles-1):
310
+ for _L_step in range(self.config.L_cycles):
311
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
312
+ z_H = self.L_level(z_H, z_L, **seq_info)
313
+ # 1 with grad
314
+ for _L_step in range(self.config.L_cycles):
315
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
316
+ z_H = self.L_level(z_H, z_L, **seq_info)
317
+
318
+ # LM Outputs
319
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach()) # New carry no grad
320
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:]
321
+ q_logits = self.q_head(z_H[:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
322
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1])
323
+
324
+
325
+ class TinyRecursiveReasoningModel_ACTV1(nn.Module):
326
+ """ACT wrapper."""
327
+
328
+ def __init__(self, config_dict: dict):
329
+ super().__init__()
330
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
331
+ self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
332
+
333
+ @property
334
+ def puzzle_emb(self):
335
+ return self.inner.puzzle_emb
336
+
337
+ @property
338
+ def group_emb(self):
339
+ return self.inner.group_emb
340
+
341
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
342
+ batch_size = batch["inputs"].shape[0]
343
+
344
+ return TinyRecursiveReasoningModel_ACTV1Carry(
345
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
346
+
347
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
348
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
349
+
350
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
351
+ )
352
+
353
+ def step_inner_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
354
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
355
+ return new_inner_carry
356
+
357
+ def step_current_data(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
358
+ 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()}
359
+ return new_current_data
360
+
361
+ def step_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
362
+ # Step inner carry
363
+ new_inner_carry = self.step_inner_carry(carry, batch)
364
+
365
+ new_steps = torch.where(carry.halted, 0, carry.steps)
366
+
367
+ # Update data, carry (removing halted sequences)
368
+ new_current_data = self.step_current_data(carry, batch)
369
+
370
+ return new_inner_carry, new_steps, new_current_data
371
+
372
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
373
+
374
+ new_inner_carry, new_steps, new_current_data = self.step_carry(carry, batch)
375
+
376
+ # Forward inner model
377
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits) = self.inner(new_inner_carry, new_current_data)
378
+
379
+ outputs = {
380
+ "logits": logits,
381
+ "q_halt_logits": q_halt_logits,
382
+ "q_continue_logits": q_continue_logits
383
+ }
384
+
385
+ with torch.no_grad():
386
+ # Step
387
+ new_steps = new_steps + 1
388
+ is_last_step = new_steps >= self.config.halt_max_steps
389
+
390
+ halted = is_last_step
391
+
392
+ # if training, and ACT is enabled
393
+ if self.training and (self.config.halt_max_steps > 1) or (self.config.eval_with_ACT):
394
+
395
+ # Halt signal
396
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
397
+
398
+ if self.config.no_ACT_continue:
399
+ halted = halted | (q_halt_logits > self.config.ACT_threshold)
400
+ else:
401
+ halted = halted | (q_halt_logits > q_continue_logits)
402
+
403
+ # Exploration
404
+ 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)
405
+ halted = halted & (new_steps >= min_halt_steps)
406
+
407
+ if not self.config.no_ACT_continue:
408
+ # Compute target Q
409
+ # NOTE: No replay buffer and target networks for computing target Q-value.
410
+ # As batch_size is large, there're many parallel envs.
411
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
412
+ _, _, (next_q_halt_logits, next_q_continue_logits), _, _ = self.inner(new_inner_carry, new_current_data)
413
+ 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)))
414
+
415
+ return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs
416
+
417
+
418
+ class TinyRecursiveReasoningModel_ACTGym(TinyRecursiveReasoningModel_ACTV1):
419
+ """ACT wrapper."""
420
+
421
+ def __init__(self, config_dict: dict):
422
+ super().__init__(config_dict)
423
+ self.GymConfig = TinyRecursiveReasoningModel_ACTGymConfig(**config_dict)
424
+
425
+ def step_inner_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
426
+ # check the first step where all halted and steps is 0
427
+ new_inner_carry = self.inner.reset_carry(carry.halted & (carry.steps > self.GymConfig.replace_halt_threshold), carry.inner_carry)
428
+
429
+ 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, init_std=self.GymConfig.reinit_variance)
430
+ return new_inner_carry
431
+
432
+ def step_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
433
+ # Step inner carry
434
+ new_inner_carry = None
435
+ if (carry.halted & (carry.steps == 0)).all():
436
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
437
+ else:
438
+ new_inner_carry = self.step_inner_carry(carry, batch)
439
+ carry.halted = carry.halted & (carry.steps > self.GymConfig.replace_halt_threshold)
440
+
441
+ new_steps = torch.where(carry.halted, 0, carry.steps)
442
+
443
+ # Update data, carry (removing halted sequences)
444
+ new_current_data = self.step_current_data(carry, batch)
445
+
446
+ return new_inner_carry, new_steps, new_current_data