ChanBeDu commited on
Commit
76fdcaa
·
verified ·
1 Parent(s): 98da9c2

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -293,3 +293,13 @@ arc1-Gym2oL/step_25933 filter=lfs diff=lfs merge=lfs -text
293
  arc1-Gym2oL/step_259332 filter=lfs diff=lfs merge=lfs -text
294
  arc1-Gym2oL/step_51866 filter=lfs diff=lfs merge=lfs -text
295
  arc1-Gym2oL/step_77800 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
293
  arc1-Gym2oL/step_259332 filter=lfs diff=lfs merge=lfs -text
294
  arc1-Gym2oL/step_51866 filter=lfs diff=lfs merge=lfs -text
295
  arc1-Gym2oL/step_77800 filter=lfs diff=lfs merge=lfs -text
296
+ sudoku/base_mlp_sid0/step_14646 filter=lfs diff=lfs merge=lfs -text
297
+ sudoku/base_mlp_sid0/step_19528 filter=lfs diff=lfs merge=lfs -text
298
+ sudoku/base_mlp_sid0/step_24410 filter=lfs diff=lfs merge=lfs -text
299
+ sudoku/base_mlp_sid0/step_29292 filter=lfs diff=lfs merge=lfs -text
300
+ sudoku/base_mlp_sid0/step_34174 filter=lfs diff=lfs merge=lfs -text
301
+ sudoku/base_mlp_sid0/step_39056 filter=lfs diff=lfs merge=lfs -text
302
+ sudoku/base_mlp_sid0/step_43938 filter=lfs diff=lfs merge=lfs -text
303
+ sudoku/base_mlp_sid0/step_4882 filter=lfs diff=lfs merge=lfs -text
304
+ sudoku/base_mlp_sid0/step_48820 filter=lfs diff=lfs merge=lfs -text
305
+ sudoku/base_mlp_sid0/step_9764 filter=lfs diff=lfs merge=lfs -text
sudoku/base_mlp_sid0/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: 6
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: true
18
+ name: recursive_reasoning.trm@TinyRecursiveReasoningModel_ACTV1
19
+ no_ACT_continue: true
20
+ num_heads: 8
21
+ pos_encodings: none
22
+ puzzle_emb_len: 16
23
+ puzzle_emb_ndim: 512
24
+ reinit_variance: 1
25
+ replace_halt_threshold: 1
26
+ target_latent_for_reinit: L
27
+ universal_emb_len: 0
28
+ beta1: 0.9
29
+ beta2: 0.95
30
+ checkpoint_every_eval: true
31
+ checkpoint_path: ./checkpoint/sudoku/sudoku_base_mlp_sid0
32
+ data_paths:
33
+ - TRM/data/sudoku-extreme-1k-aug-1000
34
+ data_paths_test: []
35
+ ema: true
36
+ ema_rate: 0.999
37
+ epochs: 50000
38
+ eval_interval: 5000
39
+ eval_save_outputs: []
40
+ evaluators: []
41
+ freeze_weights: false
42
+ global_batch_size: 1024
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: pretrain_
51
+ puzzle_emb_lr: 0.0001
52
+ puzzle_emb_weight_decay: 1.0
53
+ run_name: sudoku_base_mlp_sid0
54
+ seed: 0
55
+ weight_decay: 1.0
sudoku/base_mlp_sid0/losses.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def softmax_cross_entropy(logits, labels, ignore_index: int = -100):
35
+ # Cast logits to f32
36
+ # Flatten logits
37
+ 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)
38
+
39
+
40
+ def clip_ratio_loss(cur_logits, old_logits, labels, cliprange: float = 0.1, ignore_index: int = -100, valid_mask=None):
41
+ logprobs = log_stablemax(cur_logits.to(torch.float64), dim=-1)
42
+ old_logprobs = log_stablemax(old_logits.to(torch.float64), dim=-1)
43
+
44
+ if valid_mask is None:
45
+ valid_mask = (labels != ignore_index)
46
+ transformed_labels = torch.where(valid_mask, labels, 0)
47
+ prediction_logprobs = torch.gather(logprobs, index=transformed_labels.to(torch.long).unsqueeze(-1), dim=-1).squeeze(-1)
48
+ old_prediction_logprobs = torch.gather(old_logprobs, index=transformed_labels.to(torch.long).unsqueeze(-1), dim=-1).squeeze(-1)
49
+
50
+ ratio = (prediction_logprobs - old_prediction_logprobs)
51
+ min_log = ratio.new_tensor(1.0 - cliprange).log()
52
+ max_log = ratio.new_tensor(1.0 + cliprange).log()
53
+ clipped_ratio = torch.clamp(ratio, min_log, max_log)
54
+ return -torch.where(valid_mask, torch.minimum(ratio, clipped_ratio), 0)
55
+
56
+ def clip_ratio_loss2(
57
+ cur_logits,
58
+ old_logits,
59
+ labels,
60
+ advantages=None,
61
+ cliprange: float = 0.1,
62
+ ignore_index: int = -100,
63
+ valid_mask=None,
64
+ ):
65
+ if valid_mask is None:
66
+ valid_mask = labels != ignore_index
67
+
68
+ safe_labels = torch.where(valid_mask, labels, 0).long()
69
+
70
+ logprobs = torch.log_softmax(cur_logits.float(), dim=-1)
71
+
72
+ with torch.no_grad():
73
+ old_logprobs = torch.log_softmax(old_logits.float(), dim=-1)
74
+
75
+ new_logp = torch.gather(
76
+ logprobs,
77
+ dim=-1,
78
+ index=safe_labels.unsqueeze(-1),
79
+ ).squeeze(-1)
80
+
81
+ old_logp = torch.gather(
82
+ old_logprobs,
83
+ dim=-1,
84
+ index=safe_labels.unsqueeze(-1),
85
+ ).squeeze(-1)
86
+
87
+ log_ratio = new_logp - old_logp
88
+ ratio = torch.exp(log_ratio)
89
+
90
+ clipped_ratio = torch.clamp(
91
+ ratio,
92
+ 1.0 - cliprange,
93
+ 1.0 + cliprange,
94
+ )
95
+
96
+ if advantages is None:
97
+ advantages = torch.ones_like(ratio)
98
+
99
+ surrogate1 = ratio * advantages
100
+ surrogate2 = clipped_ratio * advantages
101
+
102
+ loss = -torch.minimum(surrogate1, surrogate2)
103
+
104
+ loss = torch.where(valid_mask, loss, torch.zeros_like(loss))
105
+
106
+ return loss
107
+
108
+
109
+ def clip_ratio_loss_with_reward(
110
+ cur_logits,
111
+ old_logits,
112
+ labels,
113
+ cliprange: float = 0.1,
114
+ ignore_index: int = -100,
115
+ valid_mask=None,
116
+ ):
117
+ if valid_mask is None:
118
+ valid_mask = labels != ignore_index
119
+
120
+ with torch.no_grad():
121
+ pred = torch.argmax(cur_logits, dim=-1)
122
+ is_correct = valid_mask & (pred == labels)
123
+
124
+ reward = is_correct.sum(-1, keepdim=True).float()
125
+
126
+ # normalize by sequence length
127
+ denom = valid_mask.sum(-1, keepdim=True).clamp_min(1).float()
128
+ reward = reward / denom
129
+
130
+ reward = reward.expand_as(labels)
131
+ reward = torch.where(valid_mask, reward, torch.zeros_like(reward))
132
+
133
+ loss = clip_ratio_loss2(
134
+ cur_logits=cur_logits,
135
+ old_logits=old_logits,
136
+ labels=labels,
137
+ advantages=reward,
138
+ cliprange=cliprange,
139
+ ignore_index=ignore_index,
140
+ valid_mask=valid_mask,
141
+ )
142
+
143
+ return loss
144
+
145
+
146
+ class ACTLossHead(nn.Module):
147
+ def __init__(self, model: nn.Module, loss_type: str, alpha: float = 0.5):
148
+ super().__init__()
149
+ self.model = model
150
+ self.loss_fn = globals()[loss_type]
151
+
152
+ def initial_carry(self, *args, **kwargs):
153
+ return self.model.initial_carry(*args, **kwargs) # type: ignore
154
+
155
+ @staticmethod
156
+ def comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts):
157
+ q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
158
+ return q_halt_loss
159
+
160
+ def compute_lm_loss(self, outputs, carry, labels, mask):
161
+ return self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID, valid_mask=mask)
162
+
163
+ def update_carry(self, carry, outputs):
164
+ return carry
165
+
166
+ def forward(
167
+ self,
168
+ return_keys: Sequence[str],
169
+ # Model args
170
+ **model_kwargs,
171
+ ) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
172
+ # Model logits
173
+ # B x SeqLen x D
174
+ new_carry, outputs = self.model(**model_kwargs)
175
+ labels = new_carry.current_data["labels"]
176
+
177
+ with torch.no_grad():
178
+ # Preds
179
+ outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
180
+
181
+ # Correctness
182
+ mask = (labels != IGNORE_LABEL_ID)
183
+ loss_counts = mask.sum(-1)
184
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
185
+
186
+ is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
187
+ seq_is_correct = is_correct.sum(-1) == loss_counts
188
+
189
+ # Metrics (halted)
190
+ valid_metrics = new_carry.halted & (loss_counts > 0)
191
+ metrics = {
192
+ "count": valid_metrics.sum(),
193
+
194
+ "accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
195
+ "exact_accuracy": (valid_metrics & seq_is_correct).sum(),
196
+
197
+ "q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
198
+ "steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
199
+ }
200
+
201
+ # Losses
202
+ lm_loss = (self.compute_lm_loss(outputs, new_carry, labels, mask) / loss_divisor).sum()
203
+ q_halt_loss = self.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
204
+ new_carry = self.update_carry(new_carry, outputs)
205
+ metrics.update({
206
+ "lm_loss": lm_loss.detach(),
207
+ "q_halt_loss": q_halt_loss.detach(),
208
+ })
209
+ # Q continue (bootstrapping target loss); Alexia: This fits Q-learning, but seems totally unecessary
210
+ q_continue_loss = 0
211
+ if "target_q_continue" in outputs:
212
+ q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
213
+
214
+ metrics["q_continue_loss"] = q_continue_loss.detach()
215
+ # Filter outputs for return
216
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
217
+
218
+ return new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss), metrics, detached_outputs, new_carry.halted.all()
219
+
220
+ class ACTLossHead_binorminal(ACTLossHead):
221
+ def __init__(self, model: nn.Module, loss_type: str, alpha: float = 0.5):
222
+ super().__init__(model, loss_type)
223
+
224
+ @staticmethod
225
+ def comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts):
226
+ t = (is_correct.sum(-1) / loss_counts.clamp_min(1)).to(outputs["q_halt_logits"].dtype) # [B] in [0,1]
227
+
228
+ # Force t=1 for sequences with no valid tokens
229
+ t = torch.where(loss_counts == 0, torch.ones_like(t), t)
230
+ q_halt_loss = F.binary_cross_entropy_with_logits(
231
+ outputs["q_halt_logits"], t, reduction="sum"
232
+ )
233
+ return q_halt_loss
234
+
235
+ class ACTLossHead_combine(ACTLossHead):
236
+ def __init__(self, model: nn.Module, loss_type: str, alpha: float = 0.5):
237
+ super().__init__(model, loss_type)
238
+ self.alpha = alpha
239
+
240
+ @staticmethod
241
+ def comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts):
242
+ q_halt_bce_loss = ACTLossHead.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
243
+ q_halt_binorm_loss = ACTLossHead_binorminal.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
244
+ q_halt_loss = self.alpha * q_halt_bce_loss + (1 - self.alpha) * q_halt_binorm_loss
245
+ return q_halt_loss
246
+
247
+ class ACTLossHead_binormonly(ACTLossHead_binorminal):
248
+ def __init__(self, model: nn.Module, loss_type: str):
249
+ super().__init__(model, loss_type)
250
+
251
+ def forward(
252
+ self,
253
+ return_keys: Sequence[str],
254
+ # Model args
255
+ **model_kwargs,
256
+ ) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
257
+ # Model logits
258
+ # B x SeqLen x D
259
+ new_carry, outputs = self.model(**model_kwargs)
260
+ labels = new_carry.current_data["labels"]
261
+
262
+ with torch.no_grad():
263
+ # Preds
264
+ outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
265
+
266
+ # Correctness
267
+ mask = (labels != IGNORE_LABEL_ID)
268
+ loss_counts = mask.sum(-1)
269
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
270
+
271
+ is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
272
+ seq_is_correct = is_correct.sum(-1) == loss_counts
273
+
274
+ # Metrics (halted)
275
+ valid_metrics = new_carry.halted & (loss_counts > 0)
276
+ metrics = {
277
+ "count": valid_metrics.sum(),
278
+
279
+ "accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
280
+ "exact_accuracy": (valid_metrics & seq_is_correct).sum(),
281
+
282
+ "q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
283
+ "steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
284
+ }
285
+
286
+ # Losses
287
+ lm_loss = (self.compute_lm_loss(outputs, new_carry, labels, mask) / loss_divisor).sum()
288
+ q_halt_loss = self.comput_q_halt_loss(self, outputs, is_correct, seq_is_correct, loss_counts)
289
+ metrics.update({
290
+ "lm_loss": lm_loss.detach(),
291
+ "q_halt_loss": q_halt_loss.detach(),
292
+ })
293
+ # Q continue (bootstrapping target loss); Alexia: This fits Q-learning, but seems totally unecessary
294
+ q_continue_loss = 0
295
+ if "target_q_continue" in outputs:
296
+ q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
297
+
298
+ metrics["q_continue_loss"] = q_continue_loss.detach()
299
+ # Filter outputs for return
300
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
301
+
302
+ return new_carry, (q_halt_loss + q_continue_loss), metrics, detached_outputs, new_carry.halted.all()
303
+
304
+ class TRMPPOLossHead(nn.Module):
305
+ def __init__(
306
+ self,
307
+ model: nn.Module,
308
+ cliprange: float = 0.1,
309
+ ent_coef: float = 0.01,
310
+ vf_coef: float = 0.5,
311
+ gamma: float = 0.99,
312
+ lam: float = 0.95,
313
+ ppo_noptepochs: int = 4,
314
+ reward_type: str = "sparse",
315
+ ) -> None:
316
+ super().__init__()
317
+ self.model = model
318
+ self.cliprange = cliprange
319
+ self.ent_coef = ent_coef
320
+ self.vf_coef = vf_coef
321
+ self.gamma = gamma
322
+ self.lam = lam
323
+ self.ppo_noptepochs = ppo_noptepochs
324
+ self.reward_type = reward_type
325
+
326
+ def initial_carry(self, *args, **kwargs):
327
+ return self.model.initial_carry(*args, **kwargs) # type: ignore
328
+
329
+ def _compute_ppo_signal(
330
+ self,
331
+ labels: torch.Tensor,
332
+ trajectory_logits: torch.Tensor,
333
+ trajectory_values: torch.Tensor,
334
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
335
+ trajectory_values = trajectory_values.squeeze(-1)
336
+ mask = labels != IGNORE_LABEL_ID
337
+ mask_exp = mask.unsqueeze(1).expand(-1, trajectory_logits.shape[1], -1)
338
+ valid_row_mask = mask.sum(-1) > 0 # [B] - True if row has valid tokens
339
+ valid_adv_mask = valid_row_mask.unsqueeze(-1).expand(-1, trajectory_logits.shape[1]) # [B, T]
340
+
341
+ preds = torch.argmax(trajectory_logits, dim=-1)
342
+ is_correct = mask_exp & (preds == labels.unsqueeze(1))
343
+
344
+ loss_counts = mask.sum(-1).unsqueeze(1)
345
+ seq_is_correct = is_correct.sum(-1) == loss_counts
346
+ seq_is_correct_f = seq_is_correct.to(torch.float32)
347
+
348
+ value_pred = trajectory_values
349
+
350
+ # Assign step-specific rewards and filter out padded rows
351
+ rewards = torch.zeros_like(value_pred) # [B, T]
352
+ if self.reward_type == "sparse":
353
+ rewards[:, -1] = seq_is_correct_f[:, -1] * valid_row_mask
354
+ elif self.reward_type == "dense":
355
+ rewards = seq_is_correct_f * valid_row_mask.unsqueeze(-1) # [B, T]
356
+ else:
357
+ raise ValueError(f"Unsupported reward type: {self.reward_type}")
358
+
359
+ next_values = torch.zeros_like(value_pred)
360
+ next_values[:, :-1] = value_pred[:, 1:]
361
+
362
+ deltas = rewards + self.gamma * next_values - value_pred
363
+
364
+ advs = torch.zeros_like(deltas)
365
+ last_gae = torch.zeros_like(deltas[:, 0])
366
+ for t in range(deltas.shape[1] - 1, -1, -1):
367
+ last_gae = deltas[:, t] + self.gamma * self.lam * last_gae
368
+ advs[:, t] = last_gae
369
+
370
+ # Returns based on end-of-trajectory reward
371
+ # This is likely to be appropriate with sparse rewards
372
+ returns = torch.zeros_like(value_pred)
373
+ final_reward = rewards[:, -1] # Shape: [B]
374
+
375
+ for t in range(deltas.shape[1]):
376
+ distance_to_end = deltas.shape[1] - 1 - t
377
+ returns[:, t] = final_reward * (self.gamma ** distance_to_end)
378
+
379
+ return mask, mask_exp, valid_adv_mask, rewards, advs, returns, value_pred, seq_is_correct, is_correct, loss_counts
380
+
381
+ def compute_ppo_baseline_returns(
382
+ self,
383
+ labels: torch.Tensor,
384
+ trajectory_logits: torch.Tensor,
385
+ trajectory_values: torch.Tensor,
386
+ ) -> torch.Tensor:
387
+ _, _, _, _, advs, _, value_pred, _, _, _ = self._compute_ppo_signal(
388
+ labels, trajectory_logits, trajectory_values
389
+ )
390
+ return advs + value_pred
391
+
392
+ def forward(
393
+ self,
394
+ return_keys: Sequence[str],
395
+ **model_kwargs,
396
+ ) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
397
+ new_carry, outputs = self.model(**model_kwargs)
398
+ labels = new_carry.current_data["labels"]
399
+
400
+ trajectory_logits = outputs["trajectory_logits"]
401
+ trajectory_values = outputs["trajectory_values"]
402
+
403
+ # Replace ignore labels so gather stays in-bounds; mask applied later.
404
+ safe_labels = torch.where(labels == IGNORE_LABEL_ID, torch.zeros_like(labels), labels)
405
+ labels_exp = safe_labels.unsqueeze(1).expand(-1, trajectory_logits.shape[1], -1).unsqueeze(-1)
406
+ logprobs = F.log_softmax(trajectory_logits.to(torch.float32), dim=-1)
407
+ action_logprobs = torch.gather(logprobs, dim=-1, index=labels_exp.to(torch.long)).squeeze(-1)
408
+ mask, mask_exp, valid_adv_mask, rewards, advs, returns, value_pred, seq_is_correct, is_correct, loss_counts = self._compute_ppo_signal(
409
+ labels, trajectory_logits, trajectory_values
410
+ )
411
+
412
+ action_logprobs = torch.where(mask_exp, action_logprobs, torch.zeros_like(action_logprobs))
413
+
414
+ batch = model_kwargs.get("batch")
415
+ returns = None
416
+ if isinstance(batch, dict) and batch.get("ppo_target_returns") is not None:
417
+ returns = batch["ppo_target_returns"]
418
+
419
+ assert returns is not None, "PPO target returns must be provided in the batch for the PPO loss head."
420
+
421
+ valid_advs = advs[valid_adv_mask]
422
+ if valid_advs.numel() > 0:
423
+ # Calculate mean and variance strictly over real data points
424
+ adv_mean = valid_advs.mean()
425
+ adv_std = valid_advs.std().clamp_min(1e-8)
426
+
427
+ # Normalize the entire tensor using the clean statistics
428
+ advs = (advs - adv_mean) / adv_std
429
+ else:
430
+ # Fallback to prevent NaNs if an empty batch somehow passes through
431
+ advs = torch.zeros_like(advs)
432
+
433
+ # 3. Explicitly zero-out advantages on padded rows to prevent gradient updates
434
+ advs = torch.where(valid_adv_mask, advs, torch.zeros_like(advs))
435
+
436
+ old_action_logprobs = None
437
+ old_action_logprobs = batch.get("ppo_old_action_logprobs")
438
+ if old_action_logprobs is None:
439
+ old_action_logprobs = action_logprobs.detach()
440
+ old_action_logprobs = torch.where(mask_exp, old_action_logprobs, torch.zeros_like(old_action_logprobs))
441
+
442
+ token_ratio = torch.exp(action_logprobs - old_action_logprobs)
443
+ clipped_token_ratio = torch.clamp(token_ratio, 1.0 - self.cliprange, 1.0 + self.cliprange)
444
+ advs_expanded = advs.unsqueeze(-1)
445
+ surr1 = token_ratio * advs_expanded
446
+ surr2 = clipped_token_ratio * advs_expanded
447
+ token_pg_loss = -torch.minimum(surr1, surr2)
448
+ token_pg_loss = torch.where(mask_exp, token_pg_loss, torch.zeros_like(token_pg_loss))
449
+ pg_loss = token_pg_loss.sum() / mask_exp.sum().clamp_min(1)
450
+
451
+ value_loss = 0.5 * torch.mean((value_pred - returns) ** 2)
452
+
453
+ probs = logprobs.exp()
454
+ token_entropy = -(probs * logprobs).sum(-1)
455
+ entropy = (token_entropy * mask_exp).sum() / mask_exp.sum().clamp_min(1)
456
+
457
+ loss = pg_loss + self.vf_coef * value_loss - self.ent_coef * entropy
458
+
459
+
460
+ valid_metrics = new_carry.halted & (loss_counts > 0)
461
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
462
+ metrics = {
463
+ "pg_loss": pg_loss.detach(),
464
+ "value_loss": value_loss.detach(),
465
+ "entropy": entropy.detach(),
466
+ "reward_mean": rewards.mean().detach(),
467
+ "count": valid_metrics.sum(),
468
+ "accuracy": torch.where(valid_metrics, (is_correct[:, -1].to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
469
+ "exact_accuracy": (valid_metrics & seq_is_correct[:, -1]).sum(),
470
+ "steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
471
+ }
472
+
473
+
474
+ outputs["ppo_old_logprobs"] = action_logprobs.sum(-1).detach()
475
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
476
+
477
+ return new_carry, loss, metrics, detached_outputs, new_carry.halted.all()
478
+
479
+ class ACTClipRatioLossHead(ACTLossHead):
480
+ def __init__(self, model: nn.Module, loss_type: str = "clip_ratio_loss", cliprange: float = 0.1):
481
+ super().__init__(model, loss_type)
482
+ self.cliprange = cliprange
483
+
484
+ def compute_lm_loss(self, outputs, carry, labels, mask):
485
+ lm_loss = self.loss_fn(outputs["logits"], carry.oldlogits, labels, cliprange=self.cliprange, ignore_index=IGNORE_LABEL_ID, valid_mask=mask)
486
+ return lm_loss
487
+
488
+ def update_carry(self, carry, outputs):
489
+ carry.oldlogits = outputs["logits"].detach()
490
+ return carry
sudoku/base_mlp_sid0/step_14646 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:957aba22e6fa3e7deb26937e960e4bc4edfca3d692daea8d1bb071cb7a9f0ed0
3
+ size 20126965
sudoku/base_mlp_sid0/step_19528 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6249097ca979f811e9f14bf0ffd415b10322df61aa13e654e743772ce24fe55b
3
+ size 20126965
sudoku/base_mlp_sid0/step_24410 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81eb2de329fa20f3f2a238a87d162ef426d0778e1b2e64438392c5b8b335acbb
3
+ size 20126965
sudoku/base_mlp_sid0/step_29292 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42a33432a0000233776c5cac10da4fd5f2f7ab605f0d18a7fce0cb23d4dacec1
3
+ size 20126965
sudoku/base_mlp_sid0/step_34174 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0ecba884b52e55bdc95545d17d3c6620fbd22267d4b6e62efcebec2d0d78669
3
+ size 20126965
sudoku/base_mlp_sid0/step_39056 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56c11792e23342a3379ec1bee4487f0050f55ba702a3a4c23bd02ca0a01beb67
3
+ size 20126965
sudoku/base_mlp_sid0/step_43938 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bd6e7988f2f345bfb04b113ce7a91ad7323057988bec92903f7357f33ef7052
3
+ size 20126965
sudoku/base_mlp_sid0/step_4882 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:446002a2da19befed51b939354e6a82d08fce2605715e9c8f7762c15a69286dc
3
+ size 20126944
sudoku/base_mlp_sid0/step_48820 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28431f68049f12a6b24bac552ed9a9627f16b3e1c0866ac194a5478e0157e330
3
+ size 20126965
sudoku/base_mlp_sid0/step_9764 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5217dc5470d8c1279fe147617af7a853c5b6ec718b4747333abfea7f69769b5b
3
+ size 20126944
sudoku/base_mlp_sid0/trm.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ @dataclass
22
+ class TinyRecursiveReasoningModel_ACTV1Carry:
23
+ inner_carry: TinyRecursiveReasoningModel_ACTV1InnerCarry
24
+
25
+ steps: torch.Tensor
26
+ halted: torch.Tensor
27
+
28
+ current_data: Dict[str, torch.Tensor]
29
+
30
+ @dataclass
31
+ class TinyRecursiveReasoningModel_ACTVClipCarry:
32
+ inner_carry: TinyRecursiveReasoningModel_ACTV1InnerCarry
33
+
34
+ oldlogits: torch.Tensor
35
+
36
+ steps: torch.Tensor
37
+ halted: torch.Tensor
38
+
39
+ current_data: Dict[str, torch.Tensor]
40
+
41
+
42
+ class TinyRecursiveReasoningModel_ACTV1Config(BaseModel):
43
+ batch_size: int
44
+ seq_len: int
45
+ puzzle_emb_ndim: int = 0
46
+ universal_emb_len: int = 0
47
+ group_emb_len: int = 0
48
+ num_puzzle_identifiers: int
49
+ num_groups: int
50
+ vocab_size: int
51
+
52
+ H_cycles: int
53
+ L_cycles: int
54
+
55
+ H_layers: int # ignored
56
+ L_layers: int
57
+
58
+ # Transformer config
59
+ hidden_size: int
60
+ expansion: float
61
+ num_heads: int
62
+ pos_encodings: str
63
+
64
+ rms_norm_eps: float = 1e-5
65
+ rope_theta: float = 10000.0
66
+
67
+ # Halting Q-learning config
68
+ halt_max_steps: int
69
+ halt_exploration_prob: float
70
+ puzzle_emb_len: int = 16 # if non-zero, its specified to this value
71
+ forward_dtype: str = "bfloat16"
72
+
73
+ # Alexia: added
74
+ mlp_t: bool = False # use mlp on L instead of transformer
75
+ no_ACT_continue: bool = True # No continue ACT loss, only use the sigmoid of the halt which makes much more sense
76
+
77
+ # chan edit
78
+ 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.
79
+ ACT_threshold: float = 0 # Threshold for ACT halting during evaluation, only used if eval_with_ACT is True
80
+
81
+ class TinyRecursiveReasoningModel_ACTGymConfig(BaseModel):
82
+ replace_halt_threshold: int = 1
83
+ target_latent_for_reinit: str = "L"
84
+ 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.
85
+
86
+
87
+ class TinyRecursiveReasoningModel_ACTV1Block(nn.Module):
88
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config, puzzle_emb_len: int) -> None:
89
+ super().__init__()
90
+
91
+ self.config = config
92
+ if self.config.mlp_t:
93
+ self.puzzle_emb_len = puzzle_emb_len
94
+ self.mlp_t = SwiGLU(
95
+ hidden_size=self.config.seq_len + self.puzzle_emb_len, # L
96
+ expansion=config.expansion,
97
+ )
98
+ else:
99
+ self.self_attn = Attention(
100
+ hidden_size=config.hidden_size,
101
+ head_dim=config.hidden_size // config.num_heads,
102
+ num_heads=config.num_heads,
103
+ num_key_value_heads=config.num_heads,
104
+ causal=False
105
+ )
106
+ self.mlp = SwiGLU(
107
+ hidden_size=config.hidden_size,
108
+ expansion=config.expansion,
109
+ )
110
+ self.norm_eps = config.rms_norm_eps
111
+
112
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
113
+ # B, L, D = hidden_states.shape
114
+ # Post Norm
115
+ if self.config.mlp_t:
116
+ hidden_states = hidden_states.transpose(1,2)
117
+ out = self.mlp_t(hidden_states)
118
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
119
+ hidden_states = hidden_states.transpose(1,2)
120
+ else:
121
+ # Self Attention
122
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
123
+ # Fully Connected
124
+ out = self.mlp(hidden_states)
125
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
126
+ return hidden_states
127
+
128
+ class TinyRecursiveReasoningModel_ACTV1ReasoningModule(nn.Module):
129
+ def __init__(self, layers: List[TinyRecursiveReasoningModel_ACTV1Block]):
130
+ super().__init__()
131
+ self.layers = torch.nn.ModuleList(layers)
132
+
133
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
134
+ hidden_states = hidden_states + input_injection
135
+ for layer in self.layers:
136
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
137
+ return hidden_states
138
+
139
+ class TinyRecursiveReasoningModel_ACTV1_Inner(nn.Module):
140
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
141
+ super().__init__()
142
+ self.config = config
143
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
144
+
145
+ # I/O
146
+
147
+ self.embed_scale = math.sqrt(self.config.hidden_size)
148
+ embed_init_std = 1.0 / self.embed_scale
149
+
150
+ self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
151
+ self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
152
+ self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
153
+
154
+ if self.config.puzzle_emb_ndim > 0:
155
+ # Zero init puzzle embeddings
156
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
157
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
158
+
159
+ self.group_embedding_dim = self.config.group_emb_len * self.config.hidden_size
160
+ if self.group_embedding_dim > 0:
161
+ # Zero init group embeddings
162
+ self.group_emb = CastedSparseEmbedding(self.config.num_groups, self.group_embedding_dim,
163
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
164
+
165
+ self.universal_emb_ndim = self.config.universal_emb_len * self.config.hidden_size
166
+ if self.universal_emb_ndim > 0:
167
+ # Universal embedding, shared between tokens and puzzles, with non-zero init
168
+ self.universal_emb = CastedEmbedding(1, self.universal_emb_ndim, init_std=embed_init_std, cast_to=self.forward_dtype)
169
+
170
+ print("Puzzle embedding ndim:", self.config.puzzle_emb_ndim)
171
+ print("Group embedding ndim:", self.group_embedding_dim)
172
+ print("Universal embedding ndim:", self.universal_emb_ndim)
173
+ print("Puzzle embed length:", self.config.puzzle_emb_len)
174
+ total_puzzle_emb_dim = self.config.puzzle_emb_ndim + self.group_embedding_dim + self.universal_emb_ndim
175
+ self.puzzle_emb_len = max(-(total_puzzle_emb_dim // -self.config.hidden_size), self.config.puzzle_emb_len) # ceil div
176
+ print("Total puzzle embedding dim:", total_puzzle_emb_dim)
177
+ print("Final puzzle embedding length (in tokens):", self.puzzle_emb_len)
178
+
179
+ # LM Blocks
180
+ if self.config.pos_encodings == "rope":
181
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
182
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
183
+ base=self.config.rope_theta)
184
+ elif self.config.pos_encodings == "learned":
185
+ 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)
186
+ else:
187
+ pass
188
+
189
+ # Reasoning Layers
190
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[TinyRecursiveReasoningModel_ACTV1Block(self.config, self.puzzle_emb_len) for _i in range(self.config.L_layers)])
191
+
192
+ # Initial states
193
+ self.H_init = self.init_latent_buffer(self.config.hidden_size, self.forward_dtype)
194
+ self.L_init = self.init_latent_buffer(self.config.hidden_size, self.forward_dtype)
195
+
196
+ # Q head special init
197
+ # Init Q to (almost) zero for faster learning during bootstrapping
198
+ with torch.no_grad():
199
+ self.q_head.weight.zero_()
200
+ self.q_head.bias.fill_(-5) # type: ignore
201
+
202
+ @staticmethod
203
+ def init_latent_buffer(
204
+ hidden_size: int,
205
+ forward_dtype: torch.dtype,
206
+ persistent: bool = True,
207
+ device: Optional[torch.device] = None,
208
+ std: float = 1.0
209
+ ) -> torch.Tensor:
210
+ return nn.Buffer(
211
+ trunc_normal_init_(torch.empty(hidden_size, dtype=forward_dtype, device=device), std=std),
212
+ persistent=persistent,
213
+ )
214
+
215
+
216
+ @staticmethod
217
+ def init_latent_buffer_around_state(
218
+ state: torch.Tensor,
219
+ forward_dtype: torch.dtype,
220
+ persistent: bool = True,
221
+ device: Optional[torch.device] = None,
222
+ std: float = 1.0
223
+ ) -> torch.Tensor:
224
+ return nn.Buffer(
225
+ state + trunc_normal_init_(torch.empty_like(state, dtype=forward_dtype, device=device), std=std),
226
+ persistent=persistent,
227
+ )
228
+
229
+
230
+
231
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor, group_indices: torch.Tensor):
232
+ # Token embedding
233
+ embedding = self.embed_tokens(input.to(torch.int32))
234
+
235
+ # Puzzle embeddings
236
+ if self.config.puzzle_emb_ndim > 0:
237
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
238
+
239
+ if self.config.group_emb_len > 0:
240
+ group_embedding = self.group_emb(group_indices)
241
+
242
+ # concat along feature dim -> (B, Dp + Dg)
243
+ puzzle_embedding = torch.cat([puzzle_embedding, group_embedding], dim=-1)
244
+
245
+ if self.config.universal_emb_len > 0:
246
+ # universal_embedding: (B, Du)
247
+ universal_embedding = self.universal_emb(torch.zeros(puzzle_embedding.size(0), device=puzzle_embedding.device, dtype=torch.long))
248
+
249
+ # concat along feature dim -> (B, Dp + (Dg) + Du)
250
+ puzzle_embedding = torch.cat([puzzle_embedding, universal_embedding], dim=-1)
251
+
252
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
253
+ if pad_count > 0:
254
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
255
+
256
+ embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
257
+
258
+ # Position embeddings
259
+ if self.config.pos_encodings == "learned":
260
+ # scale by 1/sqrt(2) to maintain forward variance
261
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
262
+
263
+ # Scale
264
+ return self.embed_scale * embedding
265
+
266
+ def empty_carry(self, batch_size: int):
267
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
268
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
269
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
270
+ )
271
+
272
+ def reset_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry):
273
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
274
+ z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
275
+ z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
276
+ )
277
+
278
+ def re_inittialize_carry(
279
+ self,
280
+ reset_flag: torch.Tensor,
281
+ carry: TinyRecursiveReasoningModel_ACTV1InnerCarry,
282
+ target_latent: Optional[str] = None,
283
+ init_std: float = 1.0
284
+ ):
285
+ target_device = carry.z_L.device
286
+ if target_latent == "LH":
287
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
288
+ z_H=torch.where(
289
+ reset_flag.view(-1, 1, 1),
290
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
291
+ carry.z_H,
292
+ ),
293
+ z_L=torch.where(
294
+ reset_flag.view(-1, 1, 1),
295
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
296
+ carry.z_L,
297
+ ),
298
+ )
299
+ elif target_latent == "H":
300
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
301
+ z_H=torch.where(
302
+ reset_flag.view(-1, 1, 1),
303
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
304
+ carry.z_H,
305
+ ),
306
+ z_L=carry.z_L
307
+ )
308
+ elif target_latent == "L":
309
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
310
+ z_H=carry.z_H,
311
+ z_L=torch.where(
312
+ reset_flag.view(-1, 1, 1),
313
+ self.init_latent_buffer(self.config.hidden_size, self.forward_dtype, device=target_device, std=init_std),
314
+ carry.z_L,
315
+ )
316
+ )
317
+ else:
318
+ raise ValueError(f"Invalid target_latent value: {target_latent}")
319
+
320
+
321
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, Dict[str, torch.Tensor]]:
322
+ seq_info = dict(
323
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
324
+ )
325
+
326
+ # Input encoding
327
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"], batch["group_indices"])
328
+
329
+ # Forward iterations
330
+ it = 0
331
+ z_H, z_L = carry.z_H, carry.z_L
332
+ # H_cycles-1 without grad
333
+ with torch.no_grad():
334
+ for _H_step in range(self.config.H_cycles-1):
335
+ for _L_step in range(self.config.L_cycles):
336
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
337
+ z_H = self.L_level(z_H, z_L, **seq_info)
338
+ # 1 with grad
339
+ for _L_step in range(self.config.L_cycles):
340
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
341
+ z_H = self.L_level(z_H, z_L, **seq_info)
342
+
343
+ # LM Outputs
344
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach()) # New carry no grad
345
+ logits = self.lm_head(z_H)[:, self.puzzle_emb_len:]
346
+ q_logits = self.q_head(z_H[:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
347
+ outputs = {
348
+ "logits": logits,
349
+ "q_halt_logits": q_logits[..., 0],
350
+ "q_continue_logits": q_logits[..., 1] if not self.config.no_ACT_continue else None
351
+ }
352
+
353
+ return new_carry, outputs
354
+
355
+ class TinyRecursiveReasoningModel_PPOInner(TinyRecursiveReasoningModel_ACTV1_Inner):
356
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
357
+ super().__init__(config)
358
+ self.v_head = CastedLinear(self.config.hidden_size, 1, bias=True) # Unbounded PPO value function regression
359
+
360
+ with torch.no_grad():
361
+ self.v_head.weight.normal_(std=0.02)
362
+ self.v_head.bias.zero_() # Clean zero-start for reward expectation
363
+
364
+ def forward(
365
+ self,
366
+ carry: TinyRecursiveReasoningModel_ACTV1InnerCarry,
367
+ batch: Dict[str, torch.Tensor],
368
+ ) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, Dict[str, torch.Tensor]]:
369
+ seq_info = dict(
370
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
371
+ )
372
+
373
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"], batch["group_indices"])
374
+
375
+ z_H, z_L = carry.z_H, carry.z_L
376
+ trajectory_logits = []
377
+ trajectory_values = []
378
+
379
+ with torch.no_grad():
380
+ for _H_step in range(self.config.H_cycles - 1):
381
+ for _L_step in range(self.config.L_cycles):
382
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
383
+ z_H = self.L_level(z_H, z_L, **seq_info)
384
+
385
+ logits = self.lm_head(z_H)[:, self.puzzle_emb_len:]
386
+ values = self.v_head(z_H[:, 0]).to(torch.float32)
387
+ trajectory_logits.append(logits.detach())
388
+ trajectory_values.append(values.detach())
389
+
390
+ for _L_step in range(self.config.L_cycles):
391
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
392
+ z_H = self.L_level(z_H, z_L, **seq_info)
393
+
394
+ logits = self.lm_head(z_H)[:, self.puzzle_emb_len:]
395
+ # q_logits = self.q_head(z_H[:, 0]).to(torch.float32)
396
+ values = self.v_head(z_H[:, 0]).to(torch.float32)
397
+ trajectory_logits.append(logits)
398
+ trajectory_values.append(values)
399
+
400
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach())
401
+ outputs = {
402
+ "logits": logits,
403
+ "trajectory_logits": torch.stack(trajectory_logits, dim=1),
404
+ "trajectory_values": torch.stack(trajectory_values, dim=1)
405
+ }
406
+
407
+ return new_carry, outputs
408
+
409
+
410
+ class TinyRecursiveReasoningModel_ACTV1(nn.Module):
411
+ """ACT wrapper."""
412
+
413
+ def __init__(self, config_dict: dict):
414
+ super().__init__()
415
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
416
+ self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
417
+
418
+ @property
419
+ def puzzle_emb(self):
420
+ return self.inner.puzzle_emb
421
+
422
+ @property
423
+ def group_emb(self):
424
+ return self.inner.group_emb
425
+
426
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
427
+ batch_size = batch["inputs"].shape[0]
428
+
429
+ return TinyRecursiveReasoningModel_ACTV1Carry(
430
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
431
+
432
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
433
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
434
+
435
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
436
+ )
437
+
438
+ def step_inner_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
439
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
440
+ return new_inner_carry
441
+
442
+ def step_current_data(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
443
+ 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()}
444
+ return new_current_data
445
+
446
+ def step_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
447
+ # Step inner carry
448
+ new_inner_carry = self.step_inner_carry(carry, batch)
449
+
450
+ new_steps = torch.where(carry.halted, 0, carry.steps)
451
+
452
+ # Update data, carry (removing halted sequences)
453
+ new_current_data = self.step_current_data(carry, batch)
454
+
455
+ return new_inner_carry, new_steps, new_current_data
456
+
457
+
458
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
459
+
460
+ new_inner_carry, new_steps, new_current_data = self.step_carry(carry, batch)
461
+
462
+ # Forward inner model
463
+ new_inner_carry, outputs = self.inner(new_inner_carry, new_current_data)
464
+
465
+
466
+ with torch.no_grad():
467
+ # Step
468
+ new_steps = new_steps + 1
469
+ is_last_step = new_steps >= self.config.halt_max_steps
470
+
471
+ halted = is_last_step
472
+
473
+ # if training, and ACT is enabled
474
+ if self.training and (self.config.halt_max_steps > 1) or (self.config.eval_with_ACT):
475
+
476
+ # Halt signal
477
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
478
+
479
+ if self.config.no_ACT_continue:
480
+ halted = halted | (outputs["q_halt_logits"] > self.config.ACT_threshold)
481
+ else:
482
+ halted = halted | (outputs["q_halt_logits"] > outputs["q_continue_logits"])
483
+
484
+ # Exploration
485
+ min_halt_steps = (torch.rand_like(outputs["q_halt_logits"]) < self.config.halt_exploration_prob) * torch.randint_like(new_steps, low=2, high=self.config.halt_max_steps + 1)
486
+ halted = halted & (new_steps >= min_halt_steps)
487
+
488
+ if not self.config.no_ACT_continue:
489
+ # Compute target Q
490
+ # NOTE: No replay buffer and target networks for computing target Q-value.
491
+ # As batch_size is large, there're many parallel envs.
492
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
493
+ _, _, (next_q_halt_logits, next_q_continue_logits), _, _ = self.inner(new_inner_carry, new_current_data)
494
+ 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)))
495
+
496
+ return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs
497
+
498
+
499
+ class TinyRecursiveReasoningModel_ACTVClip(nn.Module):
500
+ """ACT wrapper."""
501
+
502
+ def __init__(self, config_dict: dict):
503
+ super().__init__()
504
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
505
+ self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
506
+
507
+ @property
508
+ def puzzle_emb(self):
509
+ return self.inner.puzzle_emb
510
+
511
+ @property
512
+ def group_emb(self):
513
+ return self.inner.group_emb
514
+
515
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
516
+ batch_size = batch["inputs"].shape[0]
517
+
518
+ return TinyRecursiveReasoningModel_ACTVClipCarry(
519
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
520
+
521
+ oldlogits=torch.zeros((batch_size, self.config.seq_len, self.config.vocab_size), dtype=self.inner.forward_dtype),
522
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
523
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
524
+
525
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
526
+ )
527
+
528
+ def step_inner_carry(self, carry: TinyRecursiveReasoningModel_ACTVClipCarry, batch: Dict[str, torch.Tensor]):
529
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
530
+ return new_inner_carry
531
+
532
+ def step_current_data(self, carry: TinyRecursiveReasoningModel_ACTVClipCarry, batch: Dict[str, torch.Tensor]):
533
+ 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()}
534
+ return new_current_data
535
+
536
+ def step_carry(self, carry: TinyRecursiveReasoningModel_ACTVClipCarry, batch: Dict[str, torch.Tensor]):
537
+ # Step inner carry
538
+ new_inner_carry = self.step_inner_carry(carry, batch)
539
+
540
+ # new policy is assumed to start from equal probability
541
+ old_logits = torch.where(carry.halted.view((-1, 1, 1)), torch.zeros_like(carry.oldlogits), carry.oldlogits)
542
+
543
+ new_steps = torch.where(carry.halted, 0, carry.steps)
544
+
545
+ # Update data, carry (removing halted sequences)
546
+ new_current_data = self.step_current_data(carry, batch)
547
+
548
+ return new_inner_carry, old_logits, new_steps, new_current_data
549
+
550
+
551
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTVClipCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTVClipCarry, Dict[str, torch.Tensor]]:
552
+
553
+ new_inner_carry, old_logits, new_steps, new_current_data = self.step_carry(carry, batch)
554
+
555
+ # Forward inner model
556
+ new_inner_carry, outputs = self.inner(new_inner_carry, new_current_data)
557
+
558
+
559
+ with torch.no_grad():
560
+ # Step
561
+ new_steps = new_steps + 1
562
+ is_last_step = new_steps >= self.config.halt_max_steps
563
+
564
+ halted = is_last_step
565
+
566
+ # if training, and ACT is enabled
567
+ if self.training and (self.config.halt_max_steps > 1) or (self.config.eval_with_ACT):
568
+
569
+ # Halt signal
570
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
571
+
572
+ if self.config.no_ACT_continue:
573
+ halted = halted | (outputs["q_halt_logits"] > self.config.ACT_threshold)
574
+ else:
575
+ halted = halted | (outputs["q_halt_logits"] > outputs["q_continue_logits"])
576
+
577
+ # Exploration
578
+ min_halt_steps = (torch.rand_like(outputs["q_halt_logits"]) < self.config.halt_exploration_prob) * torch.randint_like(new_steps, low=2, high=self.config.halt_max_steps + 1)
579
+ halted = halted & (new_steps >= min_halt_steps)
580
+
581
+ if not self.config.no_ACT_continue:
582
+ # Compute target Q
583
+ # NOTE: No replay buffer and target networks for computing target Q-value.
584
+ # As batch_size is large, there're many parallel envs.
585
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
586
+ _, _, (next_q_halt_logits, next_q_continue_logits), _, _ = self.inner(new_inner_carry, new_current_data)
587
+ 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)))
588
+
589
+ return TinyRecursiveReasoningModel_ACTVClipCarry(new_inner_carry, old_logits, new_steps, halted, new_current_data), outputs
590
+
591
+ class TinyRecursiveReasoningModel_ACTGym(TinyRecursiveReasoningModel_ACTV1):
592
+ """ACT wrapper."""
593
+
594
+ def __init__(self, config_dict: dict):
595
+ super().__init__(config_dict)
596
+ self.GymConfig = TinyRecursiveReasoningModel_ACTGymConfig(**config_dict)
597
+
598
+ def step_inner_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
599
+ # check the first step where all halted and steps is 0
600
+ new_inner_carry = self.inner.reset_carry(carry.halted & (carry.steps > self.GymConfig.replace_halt_threshold), carry.inner_carry)
601
+
602
+ 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)
603
+ return new_inner_carry
604
+
605
+ def step_carry(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]):
606
+ # Step inner carry
607
+ new_inner_carry = None
608
+ if (carry.halted & (carry.steps == 0)).all():
609
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
610
+ else:
611
+ new_inner_carry = self.step_inner_carry(carry, batch)
612
+ carry.halted = carry.halted & (carry.steps > self.GymConfig.replace_halt_threshold)
613
+
614
+ new_steps = torch.where(carry.halted, 0, carry.steps)
615
+
616
+ # Update data, carry (removing halted sequences)
617
+ new_current_data = self.step_current_data(carry, batch)
618
+
619
+ return new_inner_carry, new_steps, new_current_data
620
+
621
+
622
+ class TinyRecursiveReasoningModel_TRMPPO(TinyRecursiveReasoningModel_ACTV1):
623
+ """TRM PPO-style wrapper."""
624
+
625
+ def __init__(self, config_dict: dict):
626
+ super().__init__(config_dict)
627
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
628
+ self.inner = TinyRecursiveReasoningModel_PPOInner(self.config)
629
+
630
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
631
+
632
+ new_inner_carry, new_steps, new_current_data = self.step_carry(carry, batch)
633
+
634
+ # Forward inner model
635
+ new_inner_carry, outputs = self.inner(new_inner_carry, new_current_data)
636
+
637
+
638
+ with torch.no_grad():
639
+ # Step
640
+ new_steps = new_steps + 1
641
+ is_last_step = new_steps >= self.config.halt_max_steps
642
+
643
+ halted = is_last_step
644
+
645
+ return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs