ThomasHeim commited on
Commit
c20fbd0
·
verified ·
1 Parent(s): 3ae0e77

Upload 23 files

Browse files
.gitattributes CHANGED
@@ -374,3 +374,23 @@ shrek-large/step_9114 filter=lfs diff=lfs merge=lfs -text
374
  shrek-tiny/step_37758_all_preds.0 filter=lfs diff=lfs merge=lfs -text
375
  sudoku-extreme/shrek-tiny/step_37758_all_preds.0 filter=lfs diff=lfs merge=lfs -text
376
  sudoku-extreme/shrek-large/step_26040_all_preds.0 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  shrek-tiny/step_37758_all_preds.0 filter=lfs diff=lfs merge=lfs -text
375
  sudoku-extreme/shrek-tiny/step_37758_all_preds.0 filter=lfs diff=lfs merge=lfs -text
376
  sudoku-extreme/shrek-large/step_26040_all_preds.0 filter=lfs diff=lfs merge=lfs -text
377
+ maze-hard/trm-attention/step_101556 filter=lfs diff=lfs merge=lfs -text
378
+ maze-hard/trm-attention/step_109368 filter=lfs diff=lfs merge=lfs -text
379
+ maze-hard/trm-attention/step_117180 filter=lfs diff=lfs merge=lfs -text
380
+ maze-hard/trm-attention/step_124992 filter=lfs diff=lfs merge=lfs -text
381
+ maze-hard/trm-attention/step_132804 filter=lfs diff=lfs merge=lfs -text
382
+ maze-hard/trm-attention/step_140616 filter=lfs diff=lfs merge=lfs -text
383
+ maze-hard/trm-attention/step_148428 filter=lfs diff=lfs merge=lfs -text
384
+ maze-hard/trm-attention/step_15624 filter=lfs diff=lfs merge=lfs -text
385
+ maze-hard/trm-attention/step_156240 filter=lfs diff=lfs merge=lfs -text
386
+ maze-hard/trm-attention/step_23436 filter=lfs diff=lfs merge=lfs -text
387
+ maze-hard/trm-attention/step_31248 filter=lfs diff=lfs merge=lfs -text
388
+ maze-hard/trm-attention/step_39060 filter=lfs diff=lfs merge=lfs -text
389
+ maze-hard/trm-attention/step_46872 filter=lfs diff=lfs merge=lfs -text
390
+ maze-hard/trm-attention/step_54684 filter=lfs diff=lfs merge=lfs -text
391
+ maze-hard/trm-attention/step_62496 filter=lfs diff=lfs merge=lfs -text
392
+ maze-hard/trm-attention/step_70308 filter=lfs diff=lfs merge=lfs -text
393
+ maze-hard/trm-attention/step_7812 filter=lfs diff=lfs merge=lfs -text
394
+ maze-hard/trm-attention/step_78120 filter=lfs diff=lfs merge=lfs -text
395
+ maze-hard/trm-attention/step_85932 filter=lfs diff=lfs merge=lfs -text
396
+ maze-hard/trm-attention/step_93744 filter=lfs diff=lfs merge=lfs -text
maze-hard/trm-attention/all_config.yaml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 3
3
+ H_layers: 0
4
+ L_cycles: 4
5
+ L_layers: 2
6
+ expansion: 4
7
+ forward_dtype: bfloat16
8
+ halt_exploration_prob: 0.1
9
+ halt_max_steps: 16
10
+ hidden_size: 512
11
+ loss:
12
+ loss_type: stablemax_cross_entropy
13
+ name: losses@ACTLossHead
14
+ mlp_t: false
15
+ name: recursive_reasoning.trm@TinyRecursiveReasoningModel_ACTV1
16
+ no_ACT_continue: true
17
+ num_heads: 8
18
+ pos_encodings: rope
19
+ puzzle_emb_len: 16
20
+ puzzle_emb_ndim: 512
21
+ beta1: 0.9
22
+ beta2: 0.95
23
+ checkpoint_every_eval: true
24
+ checkpoint_path: checkpoints/HRM_Maze_Comparison/TRM_ATT_Maze
25
+ data_paths:
26
+ - ../../dataset/data/maze-30x30-hard-1k
27
+ data_paths_test: []
28
+ ema: true
29
+ ema_rate: 0.999
30
+ epochs: 20000
31
+ eval_interval: 1000
32
+ eval_save_outputs: []
33
+ evaluators: []
34
+ freeze_weights: false
35
+ global_batch_size: 128
36
+ load_checkpoint: null
37
+ lr: 0.0001
38
+ lr_min_ratio: 1.0
39
+ lr_warmup_steps: 2000
40
+ min_eval_interval: 0
41
+ project_name: HRM_Maze_Comparison
42
+ puzzle_emb_lr: 0.0001
43
+ puzzle_emb_weight_decay: 1.0
44
+ run_name: TRM_ATT_Maze
45
+ seed: 0
46
+ weight_decay: 1.0
maze-hard/trm-attention/losses.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
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
+ def forward(
51
+ self,
52
+ return_keys: Sequence[str],
53
+ # Model args
54
+ **model_kwargs,
55
+ ) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
56
+ # Model logits
57
+ # B x SeqLen x D
58
+ new_carry, outputs = self.model(**model_kwargs)
59
+ labels = new_carry.current_data["labels"]
60
+
61
+ with torch.no_grad():
62
+ # Preds
63
+ outputs["preds"] = torch.argmax(outputs["logits"], dim=-1)
64
+
65
+ # Correctness
66
+ mask = (labels != IGNORE_LABEL_ID)
67
+ loss_counts = mask.sum(-1)
68
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
69
+
70
+ is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
71
+ seq_is_correct = is_correct.sum(-1) == loss_counts
72
+
73
+ # Metrics (halted)
74
+ valid_metrics = new_carry.halted & (loss_counts > 0)
75
+ metrics = {
76
+ "count": valid_metrics.sum(),
77
+
78
+ "accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
79
+ "exact_accuracy": (valid_metrics & seq_is_correct).sum(),
80
+
81
+ "q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
82
+ "steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
83
+ }
84
+
85
+ # Losses
86
+
87
+ lm_loss = (self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID, valid_mask=mask) / loss_divisor).sum()
88
+ q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
89
+ metrics.update({
90
+ "lm_loss": lm_loss.detach(),
91
+ "q_halt_loss": q_halt_loss.detach(),
92
+ })
93
+ # Q continue (bootstrapping target loss); Alexia: This fits Q-learning, but seems totally unecessary
94
+ q_continue_loss = 0
95
+ if "target_q_continue" in outputs:
96
+ q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
97
+
98
+ metrics["q_continue_loss"] = q_continue_loss.detach()
99
+ # Filter outputs for return
100
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
101
+
102
+ return new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss), metrics, detached_outputs, new_carry.halted.all()
103
+
maze-hard/trm-attention/step_101556 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56c68b3152909bfc53763774d45cf432a5053f25822685805d75f0caeeb71ae2
3
+ size 27303242
maze-hard/trm-attention/step_109368 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9953c7398c26f6fd75b8182353a2c7d02d23af76d8c6153fda8cbc5ce3aa84bb
3
+ size 27303242
maze-hard/trm-attention/step_117180 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f94b59e4c73f4b0f5c5301052790a500a6b717b4c6482824cf5788599736ac75
3
+ size 27303242
maze-hard/trm-attention/step_124992 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92cae3597a35c5d53676cd63e905917a28c0ea212d2982bdf81846f68251f159
3
+ size 27303242
maze-hard/trm-attention/step_132804 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f5f1481305ea03f029b3b2053fffa28c059dc68dfc70de67303f48fed702996
3
+ size 27303242
maze-hard/trm-attention/step_140616 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e80202b54f66a327d8df0aa405cb015e6644cb8ba082cb628762c7abc16c362
3
+ size 27303242
maze-hard/trm-attention/step_148428 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4292e12a5887b0de438a394a90107f45963262dcfc8cdfc94bb3d506d51cb1c4
3
+ size 27303242
maze-hard/trm-attention/step_15624 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f06412b770de2eada07c834a9b9ec84c9ded98b0be796fe2948f87f840cd9b84
3
+ size 27303221
maze-hard/trm-attention/step_156240 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:daa858b3fdcb5f310b80fc303cdb5b3c61a620df598e4c3c2e5727eb5fe49a01
3
+ size 27303242
maze-hard/trm-attention/step_23436 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2e5884830d77c7c24a740dd5897138a7b004087df6d94a38131cd6426af8899
3
+ size 27303221
maze-hard/trm-attention/step_31248 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64a0e36349e0226735ae6041c3662906279670bca714b5b59df45e2422bdfc83
3
+ size 27303221
maze-hard/trm-attention/step_39060 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7b1b5ddb500cf3dab912b189b8a9cc93b6e619c1bedb8d936fb979df6a9212a
3
+ size 27303221
maze-hard/trm-attention/step_46872 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b8053dda4d440867de48945cee9aa715b7974ace887c845c842efa8c46f8e1a
3
+ size 27303221
maze-hard/trm-attention/step_54684 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcf72632e9e2094667a9e93d34e9b357925836874102939ed8929d4296075d9c
3
+ size 27303221
maze-hard/trm-attention/step_62496 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4eee9ee5e7e9304d9799bf3647078505fc4c43e31c2ebed624c03210d73459a9
3
+ size 27303221
maze-hard/trm-attention/step_70308 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61dc0b74da5177a662d608bad770711446bd9b2db3d5cec22ba21aa587ea5c53
3
+ size 27303221
maze-hard/trm-attention/step_7812 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4efcb33e2031961dbd96a6e3fd36985f0979f8b7149afe45bdcfa8f8b04d98ef
3
+ size 27303200
maze-hard/trm-attention/step_78120 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5576d907b854096a1433ceee71c54c2738daf44bbd71d87cc5dcc06ca6cc2a6c
3
+ size 27303221
maze-hard/trm-attention/step_85932 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0aa32e3e1c30e96ef9719a342ca5611689053e274ab33ef766b22a513df42b0
3
+ size 27303221
maze-hard/trm-attention/step_93744 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:576c6bb4c577f7b70286dd59760791244b4d08e6199a2a54b1b6a686cd75c5aa
3
+ size 27303221
maze-hard/trm-attention/trm.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ num_puzzle_identifiers: int
37
+ vocab_size: int
38
+
39
+ H_cycles: int
40
+ L_cycles: int
41
+
42
+ H_layers: int # ignored
43
+ L_layers: int
44
+
45
+ # Transformer config
46
+ hidden_size: int
47
+ expansion: float
48
+ num_heads: int
49
+ pos_encodings: str
50
+
51
+ rms_norm_eps: float = 1e-5
52
+ rope_theta: float = 10000.0
53
+
54
+ # Halting Q-learning config
55
+ halt_max_steps: int
56
+ halt_exploration_prob: float
57
+
58
+ forward_dtype: str = "bfloat16"
59
+
60
+ # Alexia: added
61
+ mlp_t: bool = False # use mlp on L instead of transformer
62
+ puzzle_emb_len: int = 16 # if non-zero, its specified to this value
63
+ no_ACT_continue: bool = True # No continue ACT loss, only use the sigmoid of the halt which makes much more sense
64
+
65
+ class TinyRecursiveReasoningModel_ACTV1Block(nn.Module):
66
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
67
+ super().__init__()
68
+
69
+ self.config = config
70
+ if self.config.mlp_t:
71
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) if self.config.puzzle_emb_len == 0 else self.config.puzzle_emb_len
72
+ self.mlp_t = SwiGLU(
73
+ hidden_size=self.config.seq_len + self.puzzle_emb_len, # L
74
+ expansion=config.expansion,
75
+ )
76
+ else:
77
+ self.self_attn = Attention(
78
+ hidden_size=config.hidden_size,
79
+ head_dim=config.hidden_size // config.num_heads,
80
+ num_heads=config.num_heads,
81
+ num_key_value_heads=config.num_heads,
82
+ causal=False
83
+ )
84
+ self.mlp = SwiGLU(
85
+ hidden_size=config.hidden_size,
86
+ expansion=config.expansion,
87
+ )
88
+ self.norm_eps = config.rms_norm_eps
89
+
90
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
91
+ # B, L, D = hidden_states.shape
92
+ # Post Norm
93
+ if self.config.mlp_t:
94
+ hidden_states = hidden_states.transpose(1,2)
95
+ out = self.mlp_t(hidden_states)
96
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
97
+ hidden_states = hidden_states.transpose(1,2)
98
+ else:
99
+ # Self Attention
100
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
101
+ # Fully Connected
102
+ out = self.mlp(hidden_states)
103
+ hidden_states = rms_norm(hidden_states + out, variance_epsilon=self.norm_eps)
104
+ return hidden_states
105
+
106
+ class TinyRecursiveReasoningModel_ACTV1ReasoningModule(nn.Module):
107
+ def __init__(self, layers: List[TinyRecursiveReasoningModel_ACTV1Block]):
108
+ super().__init__()
109
+ self.layers = torch.nn.ModuleList(layers)
110
+
111
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
112
+ hidden_states = hidden_states + input_injection
113
+ for layer in self.layers:
114
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
115
+ return hidden_states
116
+
117
+
118
+ class TinyRecursiveReasoningModel_ACTV1_Inner(nn.Module):
119
+ def __init__(self, config: TinyRecursiveReasoningModel_ACTV1Config) -> None:
120
+ super().__init__()
121
+ self.config = config
122
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
123
+
124
+ # I/O
125
+
126
+ self.embed_scale = math.sqrt(self.config.hidden_size)
127
+ embed_init_std = 1.0 / self.embed_scale
128
+
129
+ self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
130
+ self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
131
+ self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
132
+
133
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) if self.config.puzzle_emb_len == 0 else self.config.puzzle_emb_len # ceil div
134
+ if self.config.puzzle_emb_ndim > 0:
135
+ # Zero init puzzle embeddings
136
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
137
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
138
+
139
+ # LM Blocks
140
+ if self.config.pos_encodings == "rope":
141
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
142
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
143
+ base=self.config.rope_theta)
144
+ elif self.config.pos_encodings == "learned":
145
+ 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)
146
+ else:
147
+ pass
148
+
149
+ # Reasoning Layers
150
+ self.L_level = TinyRecursiveReasoningModel_ACTV1ReasoningModule(layers=[TinyRecursiveReasoningModel_ACTV1Block(self.config) for _i in range(self.config.L_layers)])
151
+
152
+ # Initial states
153
+ self.H_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
154
+ self.L_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
155
+
156
+ # Q head special init
157
+ # Init Q to (almost) zero for faster learning during bootstrapping
158
+ with torch.no_grad():
159
+ self.q_head.weight.zero_()
160
+ self.q_head.bias.fill_(-5) # type: ignore
161
+
162
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
163
+ # Token embedding
164
+ embedding = self.embed_tokens(input.to(torch.int32))
165
+
166
+ # Puzzle embeddings
167
+ if self.config.puzzle_emb_ndim > 0:
168
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
169
+
170
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
171
+ if pad_count > 0:
172
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
173
+
174
+ embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
175
+
176
+ # Position embeddings
177
+ if self.config.pos_encodings == "learned":
178
+ # scale by 1/sqrt(2) to maintain forward variance
179
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
180
+
181
+ # Scale
182
+ return self.embed_scale * embedding
183
+
184
+ def empty_carry(self, batch_size: int):
185
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
186
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
187
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
188
+ )
189
+
190
+ def reset_carry(self, reset_flag: torch.Tensor, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry):
191
+ return TinyRecursiveReasoningModel_ACTV1InnerCarry(
192
+ z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
193
+ z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
194
+ )
195
+
196
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
197
+ seq_info = dict(
198
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
199
+ )
200
+
201
+ # Input encoding
202
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"])
203
+
204
+ # Forward iterations
205
+ it = 0
206
+ z_H, z_L = carry.z_H, carry.z_L
207
+ # H_cycles-1 without grad
208
+ with torch.no_grad():
209
+ for _H_step in range(self.config.H_cycles-1):
210
+ for _L_step in range(self.config.L_cycles):
211
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
212
+ z_H = self.L_level(z_H, z_L, **seq_info)
213
+ # 1 with grad
214
+ for _L_step in range(self.config.L_cycles):
215
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
216
+ z_H = self.L_level(z_H, z_L, **seq_info)
217
+
218
+ # LM Outputs
219
+ new_carry = TinyRecursiveReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach()) # New carry no grad
220
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:]
221
+ q_logits = self.q_head(z_H[:, 0]).to(torch.float32) # Q-head; uses the first puzzle_emb position
222
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1])
223
+
224
+
225
+ class TinyRecursiveReasoningModel_ACTV1(nn.Module):
226
+ """ACT wrapper."""
227
+
228
+ def __init__(self, config_dict: dict):
229
+ super().__init__()
230
+ self.config = TinyRecursiveReasoningModel_ACTV1Config(**config_dict)
231
+ self.inner = TinyRecursiveReasoningModel_ACTV1_Inner(self.config)
232
+
233
+ @property
234
+ def puzzle_emb(self):
235
+ return self.inner.puzzle_emb
236
+
237
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
238
+ batch_size = batch["inputs"].shape[0]
239
+
240
+ return TinyRecursiveReasoningModel_ACTV1Carry(
241
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
242
+
243
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
244
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
245
+
246
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
247
+ )
248
+
249
+ def forward(self, carry: TinyRecursiveReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[TinyRecursiveReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
250
+
251
+ # Update data, carry (removing halted sequences)
252
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
253
+
254
+ new_steps = torch.where(carry.halted, 0, carry.steps)
255
+
256
+ 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()}
257
+
258
+ # Forward inner model
259
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits) = self.inner(new_inner_carry, new_current_data)
260
+
261
+ outputs = {
262
+ "logits": logits,
263
+ "q_halt_logits": q_halt_logits,
264
+ "q_continue_logits": q_continue_logits
265
+ }
266
+
267
+ with torch.no_grad():
268
+ # Step
269
+ new_steps = new_steps + 1
270
+ is_last_step = new_steps >= self.config.halt_max_steps
271
+
272
+ halted = is_last_step
273
+
274
+ # if training, and ACT is enabled
275
+ if self.training and (self.config.halt_max_steps > 1):
276
+
277
+ # Halt signal
278
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
279
+
280
+ if self.config.no_ACT_continue:
281
+ halted = halted | (q_halt_logits > 0)
282
+ else:
283
+ halted = halted | (q_halt_logits > q_continue_logits)
284
+
285
+ # Exploration
286
+ 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)
287
+ halted = halted & (new_steps >= min_halt_steps)
288
+
289
+ if not self.config.no_ACT_continue:
290
+ # Compute target Q
291
+ # NOTE: No replay buffer and target networks for computing target Q-value.
292
+ # As batch_size is large, there're many parallel envs.
293
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
294
+ _, _, (next_q_halt_logits, next_q_continue_logits), _, _ = self.inner(new_inner_carry, new_current_data)
295
+ 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)))
296
+
297
+ return TinyRecursiveReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs