ChanBeDu commited on
Commit
dc85b4e
·
verified ·
1 Parent(s): 472e543

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -153,3 +153,13 @@ arc1-G_24/step_25933 filter=lfs diff=lfs merge=lfs -text
153
  arc1-G_24/step_259332 filter=lfs diff=lfs merge=lfs -text
154
  arc1-G_24/step_51866 filter=lfs diff=lfs merge=lfs -text
155
  arc1-G_24/step_77800 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
153
  arc1-G_24/step_259332 filter=lfs diff=lfs merge=lfs -text
154
  arc1-G_24/step_51866 filter=lfs diff=lfs merge=lfs -text
155
  arc1-G_24/step_77800 filter=lfs diff=lfs merge=lfs -text
156
+ arc1-GC/step_103733 filter=lfs diff=lfs merge=lfs -text
157
+ arc1-GC/step_129666 filter=lfs diff=lfs merge=lfs -text
158
+ arc1-GC/step_155599 filter=lfs diff=lfs merge=lfs -text
159
+ arc1-GC/step_181533 filter=lfs diff=lfs merge=lfs -text
160
+ arc1-GC/step_207466 filter=lfs diff=lfs merge=lfs -text
161
+ arc1-GC/step_233399 filter=lfs diff=lfs merge=lfs -text
162
+ 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
arc1-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/arc-trm/checkpoint_full_100k_group_uni_emb1
29
+ data_paths:
30
+ - data/arc1concept-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: 1536
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: Arc1concept-aug-1000-ACT-torch
48
+ puzzle_emb_lr: 0.01
49
+ puzzle_emb_weight_decay: 0.1
50
+ run_name: pretrain_group_uni_emb1
51
+ seed: 0
52
+ weight_decay: 0.1
arc1-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()
arc1-GC/step_103733 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d34b748517f6bb3dea3a94785df3ef81b0e88ab4cafe28b42c5ae6ea95b2fbe0
3
+ size 1824174156
arc1-GC/step_129666 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92bed31f6f2da8485d34e84a634972219533b1d5983839fb63666aa4837f93f1
3
+ size 1824174156
arc1-GC/step_155599 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfbf2a903282fc599df60a229a0c143b139f82981895e50bc2875318b7a8c687
3
+ size 1824174156
arc1-GC/step_181533 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7c641a0283f1b03915ac559d40a4f79607eaa7598a854612be3306db0c8229f
3
+ size 1824174156
arc1-GC/step_207466 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a7ae578fd2b897c1c3db97cb9944c58a800d77dff46e9387fe7d1587a80f5a3
3
+ size 1824174156
arc1-GC/step_233399 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb93af62bd3cc063520cc46f380a32b8af8f397d8af42950fd89949e095d787e
3
+ size 1824174156
arc1-GC/step_25933 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0963c63f0f4b3104b24bbaef30e80a68cbd0546c809a2775125d00b764dd54b1
3
+ size 1824174133
arc1-GC/step_259332 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8652e3c3d61dd39a32058b005b73ad1f55e350ff9574c31eb1248a1b4d1bd84
3
+ size 1824174156
arc1-GC/step_51866 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93687f98240219e570b17f8a976a1a7fb14f003a4b367efaf77dc924c7880957
3
+ size 1824174133
arc1-GC/step_77800 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fdd385d07bf53b4b5eb84d0fc95fe29bfbccb4c651585d15fdb58ad1ed43bf73
3
+ size 1824174133
arc1-GC/trm.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_ACTV1Block(nn.Module):
72
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config, puzzle_emb_len: int) -> None:
73
+ super().__init__()
74
+
75
+ self.config = config
76
+ if self.config.mlp_t:
77
+ self.puzzle_emb_len = puzzle_emb_len
78
+ self.mlp_t = SwiGLU(
79
+ hidden_size=self.config.seq_len + self.puzzle_emb_len, # L
80
+ expansion=config.expansion,
81
+ )
82
+ else:
83
+ self.self_attn = Attention(
84
+ hidden_size=config.hidden_size,
85
+ head_dim=config.hidden_size // config.num_heads,
86
+ num_heads=config.num_heads,
87
+ num_key_value_heads=config.num_heads,
88
+ causal=False
89
+ )
90
+ self.mlp = SwiGLU(
91
+ hidden_size=config.hidden_size,
92
+ expansion=config.expansion,
93
+ )
94
+ self.norm_eps = config.rms_norm_eps
95
+
96
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
97
+ # B, L, D = hidden_states.shape
98
+ # Post Norm
99
+ if self.config.mlp_t:
100
+ hidden_states = hidden_states.transpose(1,2)
101
+ out = self.mlp_t(hidden_states)
102
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
103
+ hidden_states = hidden_states.transpose(1,2)
104
+ else:
105
+ # Self Attention
106
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
107
+ # Fully Connected
108
+ out = self.mlp(hidden_states)
109
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
110
+ return hidden_states
111
+
112
+ class TinyRecursiveReasoningModel_ACTV1ReasoningModule(nn.Module):
113
+ def __init__(self, layers: List[TinyRecursiveReasoningModel_ACTV1Block]):
114
+ super().__init__()
115
+ self.layers = torch.nn.ModuleList(layers)
116
+
117
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
118
+ hidden_states = hidden_states + input_injection
119
+ for layer in self.layers:
120
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
121
+ return hidden_states
122
+
123
+
124
+ class TinyRecursiveReasoningModel_ACTV1_Inner(nn.Module):
125
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
126
+ super().__init__()
127
+ self.config = config
128
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
129
+
130
+ # I/O
131
+
132
+ self.embed_scale = math.sqrt(self.config.hidden_size)
133
+ embed_init_std = 1.0 / self.embed_scale
134
+
135
+ self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
136
+ self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
137
+ self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
138
+
139
+ if self.config.puzzle_emb_ndim > 0:
140
+ # Zero init puzzle embeddings
141
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
142
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
143
+
144
+ self.group_embedding_dim = self.config.group_emb_len * self.config.hidden_size
145
+ if self.group_embedding_dim > 0:
146
+ # Zero init group embeddings
147
+ self.group_emb = CastedSparseEmbedding(self.config.num_groups, self.group_embedding_dim,
148
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
149
+
150
+ self.universal_emb_ndim = self.config.universal_emb_len * self.config.hidden_size
151
+ if self.universal_emb_ndim > 0:
152
+ # Universal embedding, shared between tokens and puzzles, with non-zero init
153
+ self.universal_emb = CastedEmbedding(1, self.universal_emb_ndim, init_std=embed_init_std, cast_to=self.forward_dtype)
154
+
155
+ print("Puzzle embedding ndim:", self.config.puzzle_emb_ndim)
156
+ print("Group embedding ndim:", self.group_embedding_dim)
157
+ print("Universal embedding ndim:", self.universal_emb_ndim)
158
+ print("Puzzle embed length:", self.config.puzzle_emb_len)
159
+ total_puzzle_emb_dim = self.config.puzzle_emb_ndim + self.group_embedding_dim + self.universal_emb_ndim
160
+ self.puzzle_emb_len = max(-(total_puzzle_emb_dim // -self.config.hidden_size), self.config.puzzle_emb_len) # ceil div
161
+ print("Total puzzle embedding dim:", total_puzzle_emb_dim)
162
+ print("Final puzzle embedding length (in tokens):", self.puzzle_emb_len)
163
+
164
+ # LM Blocks
165
+ if self.config.pos_encodings == "rope":
166
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
167
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
168
+ base=self.config.rope_theta)
169
+ elif self.config.pos_encodings == "learned":
170
+ 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)
171
+ else:
172
+ pass
173
+
174
+ # Reasoning Layers
175
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[TinyRecursiveReasoningModel_ACTV1Block(self.config, self.puzzle_emb_len) for _i in range(self.config.L_layers)])
176
+
177
+ # Initial states
178
+ self.H_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
179
+ self.L_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
180
+
181
+ # Q head special init
182
+ # Init Q to (almost) zero for faster learning during bootstrapping
183
+ with torch.no_grad():
184
+ self.q_head.weight.zero_()
185
+ self.q_head.bias.fill_(-5) # type: ignore
186
+
187
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, group_indices: torch.Tensor):
188
+ # Token embedding
189
+ embedding = self.embed_tokens(input.to(torch.int32))
190
+
191
+ # Puzzle embeddings
192
+ if self.config.puzzle_emb_ndim > 0:
193
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
194
+
195
+ if self.config.group_emb_len > 0:
196
+ group_embedding = self.group_emb(group_indices)
197
+
198
+ # concat along feature dim -> (B, Dp + Dg)
199
+ puzzle_embedding = torch.cat([puzzle_embedding, group_embedding], dim=-1)
200
+
201
+ if self.config.universal_emb_len > 0:
202
+ # universal_embedding: (B, Du)
203
+ universal_embedding = self.universal_emb(torch.zeros(puzzle_embedding.size(0), device=puzzle_embedding.device, dtype=torch.long))
204
+
205
+ # concat along feature dim -> (B, Dp + (Dg) + Du)
206
+ puzzle_embedding = torch.cat([puzzle_embedding, universal_embedding], dim=-1)
207
+
208
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
209
+ if pad_count > 0:
210
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
211
+
212
+ embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
213
+
214
+ # Position embeddings
215
+ if self.config.pos_encodings == "learned":
216
+ # scale by 1/sqrt(2) to maintain forward variance
217
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
218
+
219
+ # Scale
220
+ return self.embed_scale * embedding
221
+
222
+ def empty_carry(self, batch_size: int):
223
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
224
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
225
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
226
+ )
227
+
228
+ def reset_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry):
229
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
230
+ z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
231
+ z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
232
+ )
233
+
234
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
235
+ seq_info = dict(
236
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
237
+ )
238
+
239
+ # Input encoding
240
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"], batch["group_indices"])
241
+
242
+ # Forward iterations
243
+ it = 0
244
+ z_H, z_L = carry.z_H, carry.z_L
245
+ # H_cycles-1 without grad
246
+ with torch.no_grad():
247
+ for _H_step in range(self.config.H_cycles-1):
248
+ for _L_step in range(self.config.L_cycles):
249
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
250
+ z_H = self.L_level(z_H, z_L, **seq_info)
251
+ # 1 with grad
252
+ for _L_step in range(self.config.L_cycles):
253
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
254
+ z_H = self.L_level(z_H, z_L, **seq_info)
255
+
256
+ # LM Outputs
257
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach()) # New carry no grad
258
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:]
259
+ q_logits = self.q_head(z_H[:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
260
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1])
261
+
262
+
263
+ class TinyRecursiveReasoningModel_ACTV1(nn.Module):
264
+ """ACT wrapper."""
265
+
266
+ def __init__(self, config_dict: dict):
267
+ super().__init__()
268
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
269
+ self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
270
+
271
+ @property
272
+ def puzzle_emb(self):
273
+ return self.inner.puzzle_emb
274
+
275
+ @property
276
+ def group_emb(self):
277
+ return self.inner.group_emb
278
+
279
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
280
+ batch_size = batch["inputs"].shape[0]
281
+
282
+ return TinyRecursiveReasoningModel_ACTV1Carry(
283
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
284
+
285
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
286
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
287
+
288
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
289
+ )
290
+
291
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
292
+
293
+ # Update data, carry (removing halted sequences)
294
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
295
+
296
+ new_steps = torch.where(carry.halted, 0, carry.steps)
297
+
298
+ 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()}
299
+
300
+ # Forward inner model
301
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits) = self.inner(new_inner_carry, new_current_data)
302
+
303
+ outputs = {
304
+ "logits": logits,
305
+ "q_halt_logits": q_halt_logits,
306
+ "q_continue_logits": q_continue_logits
307
+ }
308
+
309
+ with torch.no_grad():
310
+ # Step
311
+ new_steps = new_steps + 1
312
+ is_last_step = new_steps >= self.config.halt_max_steps
313
+
314
+ halted = is_last_step
315
+
316
+ # if training, and ACT is enabled
317
+ if self.training and (self.config.halt_max_steps > 1) or (self.config.eval_with_ACT):
318
+
319
+ # Halt signal
320
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
321
+
322
+ if self.config.no_ACT_continue:
323
+ halted = halted | (q_halt_logits > self.config.ACT_threshold)
324
+ else:
325
+ halted = halted | (q_halt_logits > q_continue_logits)
326
+
327
+ # Exploration
328
+ 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)
329
+ halted = halted & (new_steps >= min_halt_steps)
330
+
331
+ if not self.config.no_ACT_continue:
332
+ # Compute target Q
333
+ # NOTE: No replay buffer and target networks for computing target Q-value.
334
+ # As batch_size is large, there're many parallel envs.
335
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
336
+ _, _, (next_q_halt_logits, next_q_continue_logits), _, _ = self.inner(new_inner_carry, new_current_data)
337
+ 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)))
338
+
339
+ return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs