ThomasHeim commited on
Commit
137b270
·
verified ·
1 Parent(s): 58fd084

Upload 86 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +77 -0
  2. maze-hard/original-hrm/all_config.yaml +35 -0
  3. maze-hard/original-hrm/hrm_act_v1.py +283 -0
  4. maze-hard/original-hrm/losses.py +101 -0
  5. maze-hard/original-hrm/step_101556 +3 -0
  6. maze-hard/original-hrm/step_109368 +3 -0
  7. maze-hard/original-hrm/step_117180 +3 -0
  8. maze-hard/original-hrm/step_124992 +3 -0
  9. maze-hard/original-hrm/step_132804 +3 -0
  10. maze-hard/original-hrm/step_140616 +3 -0
  11. maze-hard/original-hrm/step_148428 +3 -0
  12. maze-hard/original-hrm/step_15624 +3 -0
  13. maze-hard/original-hrm/step_156240 +3 -0
  14. maze-hard/original-hrm/step_23436 +3 -0
  15. maze-hard/original-hrm/step_31248 +3 -0
  16. maze-hard/original-hrm/step_39060 +3 -0
  17. maze-hard/original-hrm/step_46872 +3 -0
  18. maze-hard/original-hrm/step_54684 +3 -0
  19. maze-hard/original-hrm/step_62496 +3 -0
  20. maze-hard/original-hrm/step_70308 +3 -0
  21. maze-hard/original-hrm/step_7812 +3 -0
  22. maze-hard/original-hrm/step_78120 +3 -0
  23. maze-hard/original-hrm/step_85932 +3 -0
  24. maze-hard/original-hrm/step_93744 +3 -0
  25. maze-hard/shrek-large/all_config.yaml +36 -0
  26. maze-hard/shrek-large/hrm_act_v1.py +428 -0
  27. maze-hard/shrek-large/losses.py +130 -0
  28. maze-hard/shrek-large/step_101556 +3 -0
  29. maze-hard/shrek-large/step_109368 +3 -0
  30. maze-hard/shrek-large/step_117180 +3 -0
  31. maze-hard/shrek-large/step_124992 +3 -0
  32. maze-hard/shrek-large/step_132804 +3 -0
  33. maze-hard/shrek-large/step_140616 +3 -0
  34. maze-hard/shrek-large/step_148428 +3 -0
  35. maze-hard/shrek-large/step_15624 +3 -0
  36. maze-hard/shrek-large/step_156240 +3 -0
  37. maze-hard/shrek-large/step_23436 +3 -0
  38. maze-hard/shrek-large/step_31248 +3 -0
  39. maze-hard/shrek-large/step_39060 +3 -0
  40. maze-hard/shrek-large/step_46872 +3 -0
  41. maze-hard/shrek-large/step_54684 +3 -0
  42. maze-hard/shrek-large/step_62496 +3 -0
  43. maze-hard/shrek-large/step_70308 +3 -0
  44. maze-hard/shrek-large/step_7812 +3 -0
  45. maze-hard/shrek-large/step_78120 +3 -0
  46. maze-hard/shrek-large/step_85932 +3 -0
  47. maze-hard/shrek-large/step_93744 +3 -0
  48. maze-hard/shrek-tiny/all_config.yaml +36 -0
  49. maze-hard/shrek-tiny/hrm_act_v1.py +428 -0
  50. maze-hard/shrek-tiny/losses.py +130 -0
.gitattributes CHANGED
@@ -253,3 +253,80 @@ sudoku-extreme/trm-attention/step_52080 filter=lfs diff=lfs merge=lfs -text
253
  sudoku-extreme/trm-attention/step_6510 filter=lfs diff=lfs merge=lfs -text
254
  sudoku-extreme/trm-attention/step_7812 filter=lfs diff=lfs merge=lfs -text
255
  sudoku-extreme/trm-attention/step_9114 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  sudoku-extreme/trm-attention/step_6510 filter=lfs diff=lfs merge=lfs -text
254
  sudoku-extreme/trm-attention/step_7812 filter=lfs diff=lfs merge=lfs -text
255
  sudoku-extreme/trm-attention/step_9114 filter=lfs diff=lfs merge=lfs -text
256
+ maze-hard/original-hrm/step_101556 filter=lfs diff=lfs merge=lfs -text
257
+ maze-hard/original-hrm/step_109368 filter=lfs diff=lfs merge=lfs -text
258
+ maze-hard/original-hrm/step_117180 filter=lfs diff=lfs merge=lfs -text
259
+ maze-hard/original-hrm/step_124992 filter=lfs diff=lfs merge=lfs -text
260
+ maze-hard/original-hrm/step_132804 filter=lfs diff=lfs merge=lfs -text
261
+ maze-hard/original-hrm/step_140616 filter=lfs diff=lfs merge=lfs -text
262
+ maze-hard/original-hrm/step_148428 filter=lfs diff=lfs merge=lfs -text
263
+ maze-hard/original-hrm/step_15624 filter=lfs diff=lfs merge=lfs -text
264
+ maze-hard/original-hrm/step_156240 filter=lfs diff=lfs merge=lfs -text
265
+ maze-hard/original-hrm/step_23436 filter=lfs diff=lfs merge=lfs -text
266
+ maze-hard/original-hrm/step_31248 filter=lfs diff=lfs merge=lfs -text
267
+ maze-hard/original-hrm/step_39060 filter=lfs diff=lfs merge=lfs -text
268
+ maze-hard/original-hrm/step_46872 filter=lfs diff=lfs merge=lfs -text
269
+ maze-hard/original-hrm/step_54684 filter=lfs diff=lfs merge=lfs -text
270
+ maze-hard/original-hrm/step_62496 filter=lfs diff=lfs merge=lfs -text
271
+ maze-hard/original-hrm/step_70308 filter=lfs diff=lfs merge=lfs -text
272
+ maze-hard/original-hrm/step_7812 filter=lfs diff=lfs merge=lfs -text
273
+ maze-hard/original-hrm/step_78120 filter=lfs diff=lfs merge=lfs -text
274
+ maze-hard/original-hrm/step_85932 filter=lfs diff=lfs merge=lfs -text
275
+ maze-hard/original-hrm/step_93744 filter=lfs diff=lfs merge=lfs -text
276
+ maze-hard/shrek-large/step_101556 filter=lfs diff=lfs merge=lfs -text
277
+ maze-hard/shrek-large/step_109368 filter=lfs diff=lfs merge=lfs -text
278
+ maze-hard/shrek-large/step_117180 filter=lfs diff=lfs merge=lfs -text
279
+ maze-hard/shrek-large/step_124992 filter=lfs diff=lfs merge=lfs -text
280
+ maze-hard/shrek-large/step_132804 filter=lfs diff=lfs merge=lfs -text
281
+ maze-hard/shrek-large/step_140616 filter=lfs diff=lfs merge=lfs -text
282
+ maze-hard/shrek-large/step_148428 filter=lfs diff=lfs merge=lfs -text
283
+ maze-hard/shrek-large/step_15624 filter=lfs diff=lfs merge=lfs -text
284
+ maze-hard/shrek-large/step_156240 filter=lfs diff=lfs merge=lfs -text
285
+ maze-hard/shrek-large/step_23436 filter=lfs diff=lfs merge=lfs -text
286
+ maze-hard/shrek-large/step_31248 filter=lfs diff=lfs merge=lfs -text
287
+ maze-hard/shrek-large/step_39060 filter=lfs diff=lfs merge=lfs -text
288
+ maze-hard/shrek-large/step_46872 filter=lfs diff=lfs merge=lfs -text
289
+ maze-hard/shrek-large/step_54684 filter=lfs diff=lfs merge=lfs -text
290
+ maze-hard/shrek-large/step_62496 filter=lfs diff=lfs merge=lfs -text
291
+ maze-hard/shrek-large/step_70308 filter=lfs diff=lfs merge=lfs -text
292
+ maze-hard/shrek-large/step_7812 filter=lfs diff=lfs merge=lfs -text
293
+ maze-hard/shrek-large/step_78120 filter=lfs diff=lfs merge=lfs -text
294
+ maze-hard/shrek-large/step_85932 filter=lfs diff=lfs merge=lfs -text
295
+ maze-hard/shrek-large/step_93744 filter=lfs diff=lfs merge=lfs -text
296
+ maze-hard/shrek-tiny/step_101556 filter=lfs diff=lfs merge=lfs -text
297
+ maze-hard/shrek-tiny/step_10416 filter=lfs diff=lfs merge=lfs -text
298
+ maze-hard/shrek-tiny/step_109368 filter=lfs diff=lfs merge=lfs -text
299
+ maze-hard/shrek-tiny/step_11718 filter=lfs diff=lfs merge=lfs -text
300
+ maze-hard/shrek-tiny/step_117180 filter=lfs diff=lfs merge=lfs -text
301
+ maze-hard/shrek-tiny/step_124992 filter=lfs diff=lfs merge=lfs -text
302
+ maze-hard/shrek-tiny/step_1302 filter=lfs diff=lfs merge=lfs -text
303
+ maze-hard/shrek-tiny/step_13020 filter=lfs diff=lfs merge=lfs -text
304
+ maze-hard/shrek-tiny/step_132804 filter=lfs diff=lfs merge=lfs -text
305
+ maze-hard/shrek-tiny/step_140616 filter=lfs diff=lfs merge=lfs -text
306
+ maze-hard/shrek-tiny/step_14322 filter=lfs diff=lfs merge=lfs -text
307
+ maze-hard/shrek-tiny/step_148428 filter=lfs diff=lfs merge=lfs -text
308
+ maze-hard/shrek-tiny/step_15624 filter=lfs diff=lfs merge=lfs -text
309
+ maze-hard/shrek-tiny/step_156240 filter=lfs diff=lfs merge=lfs -text
310
+ maze-hard/shrek-tiny/step_16926 filter=lfs diff=lfs merge=lfs -text
311
+ maze-hard/shrek-tiny/step_18228 filter=lfs diff=lfs merge=lfs -text
312
+ maze-hard/shrek-tiny/step_19530 filter=lfs diff=lfs merge=lfs -text
313
+ maze-hard/shrek-tiny/step_20832 filter=lfs diff=lfs merge=lfs -text
314
+ maze-hard/shrek-tiny/step_22134 filter=lfs diff=lfs merge=lfs -text
315
+ maze-hard/shrek-tiny/step_23436 filter=lfs diff=lfs merge=lfs -text
316
+ maze-hard/shrek-tiny/step_24738 filter=lfs diff=lfs merge=lfs -text
317
+ maze-hard/shrek-tiny/step_2604 filter=lfs diff=lfs merge=lfs -text
318
+ maze-hard/shrek-tiny/step_26040 filter=lfs diff=lfs merge=lfs -text
319
+ maze-hard/shrek-tiny/step_31248 filter=lfs diff=lfs merge=lfs -text
320
+ maze-hard/shrek-tiny/step_3906 filter=lfs diff=lfs merge=lfs -text
321
+ maze-hard/shrek-tiny/step_39060 filter=lfs diff=lfs merge=lfs -text
322
+ maze-hard/shrek-tiny/step_46872 filter=lfs diff=lfs merge=lfs -text
323
+ maze-hard/shrek-tiny/step_5208 filter=lfs diff=lfs merge=lfs -text
324
+ maze-hard/shrek-tiny/step_54684 filter=lfs diff=lfs merge=lfs -text
325
+ maze-hard/shrek-tiny/step_62496 filter=lfs diff=lfs merge=lfs -text
326
+ maze-hard/shrek-tiny/step_6510 filter=lfs diff=lfs merge=lfs -text
327
+ maze-hard/shrek-tiny/step_70308 filter=lfs diff=lfs merge=lfs -text
328
+ maze-hard/shrek-tiny/step_7812 filter=lfs diff=lfs merge=lfs -text
329
+ maze-hard/shrek-tiny/step_78120 filter=lfs diff=lfs merge=lfs -text
330
+ maze-hard/shrek-tiny/step_85932 filter=lfs diff=lfs merge=lfs -text
331
+ maze-hard/shrek-tiny/step_9114 filter=lfs diff=lfs merge=lfs -text
332
+ maze-hard/shrek-tiny/step_93744 filter=lfs diff=lfs merge=lfs -text
maze-hard/original-hrm/all_config.yaml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 2
3
+ H_layers: 4
4
+ L_cycles: 2
5
+ L_layers: 4
6
+ expansion: 4
7
+ halt_exploration_prob: 0.1
8
+ halt_max_steps: 16
9
+ hidden_size: 512
10
+ loss:
11
+ loss_type: stablemax_cross_entropy
12
+ name: losses@ACTLossHead
13
+ name: hrm.hrm_act_v1@HierarchicalReasoningModel_ACTV1
14
+ num_heads: 8
15
+ pos_encodings: rope
16
+ puzzle_emb_ndim: 512
17
+ beta1: 0.9
18
+ beta2: 0.95
19
+ checkpoint_every_eval: true
20
+ checkpoint_path: checkpoints/HRM_Maze_Comparison/HierarchicalReasoningModel_ACTV1
21
+ stalwart-oryx
22
+ data_path: ../../../dataset/data/maze-30x30-hard-1k
23
+ epochs: 20000
24
+ eval_interval: 1000
25
+ eval_save_outputs: []
26
+ global_batch_size: 128
27
+ lr: 0.0001
28
+ lr_min_ratio: 1.0
29
+ lr_warmup_steps: 2000
30
+ project_name: HRM_Maze_Comparison
31
+ puzzle_emb_lr: 0.0001
32
+ puzzle_emb_weight_decay: 1.0
33
+ run_name: HierarchicalReasoningModel_ACTV1 stalwart-oryx
34
+ seed: 0
35
+ weight_decay: 1.0
maze-hard/original-hrm/hrm_act_v1.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, List, Dict, Optional
2
+ from dataclasses import dataclass
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+ from pydantic import BaseModel
9
+
10
+ from models.common import trunc_normal_init_
11
+ from models.layers import rms_norm, SwiGLU, Attention, RotaryEmbedding, CosSin, CastedEmbedding, CastedLinear
12
+ from models.sparse_embedding import CastedSparseEmbedding
13
+
14
+
15
+ @dataclass
16
+ class HierarchicalReasoningModel_ACTV1InnerCarry:
17
+ z_H: torch.Tensor
18
+ z_L: torch.Tensor
19
+
20
+
21
+ @dataclass
22
+ class HierarchicalReasoningModel_ACTV1Carry:
23
+ inner_carry: HierarchicalReasoningModel_ACTV1InnerCarry
24
+
25
+ steps: torch.Tensor
26
+ halted: torch.Tensor
27
+
28
+ current_data: Dict[str, torch.Tensor]
29
+
30
+
31
+ class HierarchicalReasoningModel_ACTV1Config(BaseModel):
32
+ batch_size: int
33
+ seq_len: int
34
+ puzzle_emb_ndim: int = 0
35
+ num_puzzle_identifiers: int
36
+ vocab_size: int
37
+
38
+ H_cycles: int
39
+ L_cycles: int
40
+
41
+ H_layers: int
42
+ L_layers: int
43
+
44
+ # Transformer config
45
+ hidden_size: int
46
+ expansion: float
47
+ num_heads: int
48
+ pos_encodings: str
49
+
50
+ rms_norm_eps: float = 1e-5
51
+ rope_theta: float = 10000.0
52
+
53
+ # Halting Q-learning config
54
+ halt_max_steps: int
55
+ halt_exploration_prob: float
56
+
57
+ forward_dtype: str = "bfloat16"
58
+
59
+
60
+ class HierarchicalReasoningModel_ACTV1Block(nn.Module):
61
+ def __init__(self, config: HierarchicalReasoningModel_ACTV1Config) -> None:
62
+ super().__init__()
63
+
64
+ self.self_attn = Attention(
65
+ hidden_size=config.hidden_size,
66
+ head_dim=config.hidden_size // config.num_heads,
67
+ num_heads=config.num_heads,
68
+ num_key_value_heads=config.num_heads,
69
+ causal=False
70
+ )
71
+ self.mlp = SwiGLU(
72
+ hidden_size=config.hidden_size,
73
+ expansion=config.expansion,
74
+ )
75
+ self.norm_eps = config.rms_norm_eps
76
+
77
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
78
+ # Post Norm
79
+ # Self Attention
80
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
81
+ # Fully Connected
82
+ hidden_states = rms_norm(hidden_states + self.mlp(hidden_states), variance_epsilon=self.norm_eps)
83
+ return hidden_states
84
+
85
+
86
+ class HierarchicalReasoningModel_ACTV1ReasoningModule(nn.Module):
87
+ def __init__(self, layers: List[HierarchicalReasoningModel_ACTV1Block]):
88
+ super().__init__()
89
+
90
+ self.layers = torch.nn.ModuleList(layers)
91
+
92
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
93
+ # Input injection (add)
94
+ hidden_states = hidden_states + input_injection
95
+ # Layers
96
+ for layer in self.layers:
97
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
98
+
99
+ return hidden_states
100
+
101
+
102
+ class HierarchicalReasoningModel_ACTV1_Inner(nn.Module):
103
+ def __init__(self, config: HierarchicalReasoningModel_ACTV1Config) -> None:
104
+ super().__init__()
105
+ self.config = config
106
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
107
+
108
+ # I/O
109
+ self.embed_scale = math.sqrt(self.config.hidden_size)
110
+ embed_init_std = 1.0 / self.embed_scale
111
+
112
+ self.embed_tokens = CastedEmbedding(self.config.vocab_size, self.config.hidden_size, init_std=embed_init_std, cast_to=self.forward_dtype)
113
+ self.lm_head = CastedLinear(self.config.hidden_size, self.config.vocab_size, bias=False)
114
+ self.q_head = CastedLinear(self.config.hidden_size, 2, bias=True)
115
+
116
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) # ceil div
117
+ if self.config.puzzle_emb_ndim > 0:
118
+ # Zero init puzzle embeddings
119
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
120
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
121
+
122
+ # LM Blocks
123
+ if self.config.pos_encodings == "rope":
124
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
125
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
126
+ base=self.config.rope_theta)
127
+ elif self.config.pos_encodings == "learned":
128
+ 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)
129
+ else:
130
+ raise NotImplementedError()
131
+
132
+ # Reasoning Layers
133
+ self.H_level = HierarchicalReasoningModel_ACTV1ReasoningModule(layers=[HierarchicalReasoningModel_ACTV1Block(self.config) for _i in range(self.config.H_layers)])
134
+ self.L_level = HierarchicalReasoningModel_ACTV1ReasoningModule(layers=[HierarchicalReasoningModel_ACTV1Block(self.config) for _i in range(self.config.L_layers)])
135
+
136
+ # Initial states
137
+ self.H_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
138
+ self.L_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
139
+
140
+ # Q head special init
141
+ # Init Q to (almost) zero for faster learning during bootstrapping
142
+ with torch.no_grad():
143
+ self.q_head.weight.zero_()
144
+ self.q_head.bias.fill_(-5) # type: ignore
145
+
146
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
147
+ # Token embedding
148
+ embedding = self.embed_tokens(input.to(torch.int32))
149
+
150
+ # Puzzle embeddings
151
+ if self.config.puzzle_emb_ndim > 0:
152
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
153
+
154
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
155
+ if pad_count > 0:
156
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
157
+
158
+ embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
159
+
160
+ # Position embeddings
161
+ if self.config.pos_encodings == "learned":
162
+ # scale by 1/sqrt(2) to maintain forward variance
163
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
164
+
165
+ # Scale
166
+ return self.embed_scale * embedding
167
+
168
+ def empty_carry(self, batch_size: int):
169
+ return HierarchicalReasoningModel_ACTV1InnerCarry(
170
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
171
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
172
+ )
173
+
174
+ def reset_carry(self, reset_flag: torch.Tensor, carry: HierarchicalReasoningModel_ACTV1InnerCarry):
175
+ return HierarchicalReasoningModel_ACTV1InnerCarry(
176
+ z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
177
+ z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
178
+ )
179
+
180
+ def forward(self, carry: HierarchicalReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor]) -> Tuple[HierarchicalReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
181
+ seq_info = dict(
182
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
183
+ )
184
+
185
+ # Input encoding
186
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"])
187
+
188
+ # Forward iterations
189
+ with torch.no_grad():
190
+ z_H, z_L = carry.z_H, carry.z_L
191
+
192
+ for _H_step in range(self.config.H_cycles):
193
+ for _L_step in range(self.config.L_cycles):
194
+ if not ((_H_step == self.config.H_cycles - 1) and (_L_step == self.config.L_cycles - 1)):
195
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
196
+
197
+ if not (_H_step == self.config.H_cycles - 1):
198
+ z_H = self.H_level(z_H, z_L, **seq_info)
199
+
200
+ assert not z_H.requires_grad and not z_L.requires_grad
201
+
202
+ # 1-step grad
203
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
204
+ z_H = self.H_level(z_H, z_L, **seq_info)
205
+
206
+ # LM Outputs
207
+ new_carry = HierarchicalReasoningModel_ACTV1InnerCarry(z_H=z_H.detach(), z_L=z_L.detach()) # New carry no grad
208
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:]
209
+
210
+ # Q head
211
+ q_logits = self.q_head(z_H[:, 0]).to(torch.float32)
212
+
213
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1])
214
+
215
+
216
+ class HierarchicalReasoningModel_ACTV1(nn.Module):
217
+ """ACT wrapper."""
218
+
219
+ def __init__(self, config_dict: dict):
220
+ super().__init__()
221
+ self.config = HierarchicalReasoningModel_ACTV1Config(**config_dict)
222
+ self.inner = HierarchicalReasoningModel_ACTV1_Inner(self.config)
223
+
224
+ @property
225
+ def puzzle_emb(self):
226
+ return self.inner.puzzle_emb
227
+
228
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
229
+ batch_size = batch["inputs"].shape[0]
230
+
231
+ return HierarchicalReasoningModel_ACTV1Carry(
232
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
233
+
234
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
235
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
236
+
237
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
238
+ )
239
+
240
+ def forward(self, carry: HierarchicalReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor]) -> Tuple[HierarchicalReasoningModel_ACTV1Carry, Dict[str, torch.Tensor]]:
241
+ # Update data, carry (removing halted sequences)
242
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
243
+
244
+ new_steps = torch.where(carry.halted, 0, carry.steps)
245
+
246
+ 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()}
247
+
248
+ # Forward inner model
249
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits) = self.inner(new_inner_carry, new_current_data)
250
+
251
+ outputs = {
252
+ "logits": logits,
253
+ "q_halt_logits": q_halt_logits,
254
+ "q_continue_logits": q_continue_logits
255
+ }
256
+
257
+ with torch.no_grad():
258
+ # Step
259
+ new_steps = new_steps + 1
260
+ is_last_step = new_steps >= self.config.halt_max_steps
261
+
262
+ halted = is_last_step
263
+
264
+ # if training, and ACT is enabled
265
+ if self.training and (self.config.halt_max_steps > 1):
266
+ # Halt signal
267
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
268
+ halted = halted | (q_halt_logits > q_continue_logits)
269
+
270
+ # Exploration
271
+ 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)
272
+
273
+ halted = halted & (new_steps >= min_halt_steps)
274
+
275
+ # Compute target Q
276
+ # NOTE: No replay buffer and target networks for computing target Q-value.
277
+ # As batch_size is large, there're many parallel envs.
278
+ # Similar concept as PQN https://arxiv.org/abs/2407.04811
279
+ next_q_halt_logits, next_q_continue_logits = self.inner(new_inner_carry, new_current_data)[-1]
280
+
281
+ 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)))
282
+
283
+ return HierarchicalReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs
maze-hard/original-hrm/losses.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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):
25
+ logprobs = log_stablemax(logits.to(torch.float64), dim=-1)
26
+
27
+ valid_mask = labels != ignore_index
28
+ transformed_labels = torch.where(valid_mask, labels, 0)
29
+ prediction_logprobs = torch.gather(logprobs, index=transformed_labels.to(torch.long).unsqueeze(-1), dim=-1).squeeze(-1)
30
+
31
+ return -torch.where(valid_mask, prediction_logprobs, 0)
32
+
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
+ class ACTLossHead(nn.Module):
41
+ def __init__(self, model: nn.Module, loss_type: str):
42
+ super().__init__()
43
+ self.model = model
44
+ self.loss_fn = globals()[loss_type]
45
+
46
+ def initial_carry(self, *args, **kwargs):
47
+ return self.model.initial_carry(*args, **kwargs) # type: ignore
48
+
49
+ def forward(
50
+ self,
51
+ return_keys: Sequence[str],
52
+ # Model args
53
+ **model_kwargs,
54
+ ) -> Tuple[Any, torch.Tensor, Dict[str, torch.Tensor], Optional[Dict[str, torch.Tensor]], torch.Tensor]:
55
+ # Model logits
56
+ # B x SeqLen x D
57
+ new_carry, outputs = self.model(**model_kwargs)
58
+ labels = new_carry.current_data["labels"]
59
+
60
+ # Correctness
61
+ with torch.no_grad():
62
+ mask = labels != IGNORE_LABEL_ID
63
+ loss_counts = mask.sum(-1)
64
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
65
+
66
+ is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
67
+ seq_is_correct = is_correct.sum(-1) == loss_counts
68
+
69
+ # Metrics (halted)
70
+ valid_metrics = new_carry.halted & (loss_counts > 0)
71
+ metrics = {
72
+ "count": valid_metrics.sum(),
73
+
74
+ "accuracy": torch.where(valid_metrics, (is_correct.to(torch.float32) / loss_divisor).sum(-1), 0).sum(),
75
+ "exact_accuracy": (valid_metrics & seq_is_correct).sum(),
76
+
77
+ "q_halt_accuracy": (valid_metrics & ((outputs["q_halt_logits"] >= 0) == seq_is_correct)).sum(),
78
+ "steps": torch.where(valid_metrics, new_carry.steps, 0).sum(),
79
+ }
80
+
81
+ # Losses
82
+ # FIXME: Assuming the batch is always full
83
+ lm_loss = (self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID) / loss_divisor).sum()
84
+ q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
85
+
86
+ metrics.update({
87
+ "lm_loss": lm_loss.detach(),
88
+ "q_halt_loss": q_halt_loss.detach(),
89
+ })
90
+
91
+ # Q continue (bootstrapping target loss)
92
+ q_continue_loss = 0
93
+ if "target_q_continue" in outputs:
94
+ q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
95
+
96
+ metrics["q_continue_loss"] = q_continue_loss.detach()
97
+
98
+ # Filter outputs for return
99
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
100
+
101
+ return new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss), metrics, detached_outputs, new_carry.halted.all()
maze-hard/original-hrm/step_101556 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef9c68a6903d5dedd80c0784ae8312a0824ad2ee9a10521809b7b012dc00d2ae
3
+ size 109103906
maze-hard/original-hrm/step_109368 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10dd5a1e8682f17fba4f09863376bc4452040b5b1dfe7dd9f403870e58ffa6ee
3
+ size 109103906
maze-hard/original-hrm/step_117180 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:370df57b9bcd3a8430206a1441a264dc1a76403dbebdbc70e84d958b19611ee6
3
+ size 109103906
maze-hard/original-hrm/step_124992 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50258c4fd7e2343a52bfcadb221805721e7e91a71cd24373dbdb7e9ab5389dc3
3
+ size 109103906
maze-hard/original-hrm/step_132804 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3449afe9f7d8e2068d8cecb92c711f0cefa15620433d0d8ccfd82bbb4bf2b042
3
+ size 109103906
maze-hard/original-hrm/step_140616 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0db23d79c94ef4553e76f191127c8a484a07c3bb58ab2134e42dd8fb8493c511
3
+ size 109103906
maze-hard/original-hrm/step_148428 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:950498283faa9832b2fb0da91b4975cd04b75cba91320d01b4c55922c72974c7
3
+ size 109103906
maze-hard/original-hrm/step_15624 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24433ec581392dc0677b1a0b0b3f50af16edecf1b5b38e1e6a06b82a3bdcea59
3
+ size 109103861
maze-hard/original-hrm/step_156240 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:148d8bd84ed22d4db1eddef76dab227d6e5fe6955de7cb8810248ccc98ebeac3
3
+ size 109103906
maze-hard/original-hrm/step_23436 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7dbe385f6e9c11c3141391471a4b4cd79dadaff4738b8ea0f8fc47dc9dd17cb
3
+ size 109103861
maze-hard/original-hrm/step_31248 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:232903a94774281767b2bcbcd4579d8a32c822816e8646ca2e1ee67110997e5f
3
+ size 109103861
maze-hard/original-hrm/step_39060 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c1a956113527727345c0d636a9cb05c007affd0b3f6da752ec542bc74412dd79
3
+ size 109103861
maze-hard/original-hrm/step_46872 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4d7810b5fc2e97138f9b2320a81c0af3f94c0e876ea505526beb23d4f0a3c0c
3
+ size 109103861
maze-hard/original-hrm/step_54684 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e57bf7870ceb4f2e19179b29cd041761e6fb891fb80894a2ebcea88b3d9b8bb3
3
+ size 109103861
maze-hard/original-hrm/step_62496 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2bde8cbff83de2a34fe71bb99d21d1f18c857115acb9e2010026efad8a95918d
3
+ size 109103861
maze-hard/original-hrm/step_70308 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da0b19a21a631324c2e00a1297f831f1b2f58c71068704fb4419b2a78ad355c0
3
+ size 109103861
maze-hard/original-hrm/step_7812 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e21f2f1c004ea64a081fee1763fa5e09631de1365298f59df92d345c572a576
3
+ size 109103816
maze-hard/original-hrm/step_78120 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb34d5ffea78ced7f3985168ec20a4de29ef48f88d5bfe6767b77a009ad2fe76
3
+ size 109103861
maze-hard/original-hrm/step_85932 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50fa60917de1909525681da60c4403a83f6a28d45d5473a9df94579a6d449bdf
3
+ size 109103861
maze-hard/original-hrm/step_93744 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58c046141e6c7b890982e0b78dfdecf8ab788007ea93c9472c736fff61f89730
3
+ size 109103861
maze-hard/shrek-large/all_config.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 2
3
+ H_layers: 4
4
+ L_cycles: 2
5
+ L_layers: 4
6
+ expansion: 4
7
+ halt_exploration_prob: 0.1
8
+ halt_max_steps: 16
9
+ hidden_size: 512
10
+ loss:
11
+ loss_type: stablemax_cross_entropy
12
+ name: losses@ACTLossHead
13
+ name: hrm.hrm_act_v1@HierarchicalReasoningModel_ACTV1
14
+ num_heads: 8
15
+ pos_encodings: rope
16
+ puzzle_emb_ndim: 512
17
+ beta1: 0.9
18
+ beta2: 0.95
19
+ checkpoint_every_eval: true
20
+ checkpoint_path: checkpoints/HRM_Maze_Comparison/SHREK_Large_Maze
21
+ data_path: ../../dataset/data/maze-30x30-hard-1k
22
+ ema: true
23
+ ema_rate: 0.999
24
+ epochs: 20000
25
+ eval_interval: 1000
26
+ eval_save_outputs: []
27
+ global_batch_size: 128
28
+ lr: 0.0001
29
+ lr_min_ratio: 1.0
30
+ lr_warmup_steps: 2000
31
+ project_name: HRM_Maze_Comparison
32
+ puzzle_emb_lr: 0.0001
33
+ puzzle_emb_weight_decay: 1.0
34
+ run_name: SHREK_Large_Maze
35
+ seed: 0
36
+ weight_decay: 1.0
maze-hard/shrek-large/hrm_act_v1.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, List, Dict, Optional
2
+ from dataclasses import dataclass
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+ from pydantic import BaseModel
9
+
10
+ from models.common import trunc_normal_init_
11
+ from models.layers import rms_norm, SwiGLU, Attention, RotaryEmbedding, CosSin, CastedEmbedding, CastedLinear
12
+ from models.sparse_embedding import CastedSparseEmbedding
13
+ from models.hrm.error_singals import get_error_signal # SHREK: error signal module
14
+
15
+
16
+ @dataclass
17
+ class HierarchicalReasoningModel_ACTV1InnerCarry:
18
+ z_H: torch.Tensor
19
+ z_L: torch.Tensor
20
+ # SHREK: prev_pred stores last step's argmax predictions for flip rate computation.
21
+ # zeros = fresh start (first step after init or reset gives flip_rate ≈ 1.0)
22
+ prev_pred: torch.Tensor # (B, seq_len) int32
23
+ # SHREK: Q-values cached in carry — no longer used for Q-targets (see Bug 4),
24
+ # but kept because removing them causes torch.compile regression.
25
+ prev_q_halt: torch.Tensor # (B,) float32
26
+ prev_q_continue: torch.Tensor # (B,) float32
27
+
28
+
29
+ @dataclass
30
+ class HierarchicalReasoningModel_ACTV1Carry:
31
+ inner_carry: HierarchicalReasoningModel_ACTV1InnerCarry
32
+
33
+ steps: torch.Tensor
34
+ halted: torch.Tensor
35
+
36
+ current_data: Dict[str, torch.Tensor]
37
+
38
+
39
+ class HierarchicalReasoningModel_ACTV1Config(BaseModel):
40
+ batch_size: int
41
+ seq_len: int
42
+ puzzle_emb_ndim: int = 0
43
+ num_puzzle_identifiers: int
44
+ vocab_size: int
45
+
46
+ H_cycles: int
47
+ L_cycles: int
48
+
49
+ H_layers: int
50
+ L_layers: int
51
+
52
+ # Transformer config
53
+ hidden_size: int
54
+ expansion: float
55
+ num_heads: int
56
+ pos_encodings: str
57
+
58
+ rms_norm_eps: float = 1e-5
59
+ rope_theta: float = 10000.0
60
+
61
+ # Halting Q-learning config
62
+ halt_max_steps: int
63
+ halt_exploration_prob: float
64
+
65
+ # SHREK: error injection warmup — ramps alpha from 0 to alpha_max over warmup steps.
66
+ # Prevents small models from collapsing before the error estimator is accurate.
67
+ alpha_max: float = 0.01
68
+ alpha_warmup_steps: int = 5000
69
+
70
+ # SHREK ablation flags — disable components from training scripts
71
+ enable_error_injection: bool = True # Error-Conditioned Injection (flip rate + learned estimator)
72
+ enable_stagnation_delta: bool = True # Stagnation-Aware Q-head (delta fed to Q-head)
73
+
74
+ forward_dtype: str = "bfloat16"
75
+
76
+
77
+ class HierarchicalReasoningModel_ACTV1Block(nn.Module):
78
+ def __init__(self, config: HierarchicalReasoningModel_ACTV1Config) -> None:
79
+ super().__init__()
80
+
81
+ self.self_attn = Attention(
82
+ hidden_size=config.hidden_size,
83
+ head_dim=config.hidden_size // config.num_heads,
84
+ num_heads=config.num_heads,
85
+ num_key_value_heads=config.num_heads,
86
+ causal=False
87
+ )
88
+ self.mlp = SwiGLU(
89
+ hidden_size=config.hidden_size,
90
+ expansion=config.expansion,
91
+ )
92
+ self.norm_eps = config.rms_norm_eps
93
+
94
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
95
+ # Post Norm
96
+ # Self Attention
97
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
98
+ # Fully Connected
99
+ hidden_states = rms_norm(hidden_states + self.mlp(hidden_states), variance_epsilon=self.norm_eps)
100
+ return hidden_states
101
+
102
+
103
+ class HierarchicalReasoningModel_ACTV1ReasoningModule(nn.Module):
104
+ def __init__(self, layers: List[HierarchicalReasoningModel_ACTV1Block]):
105
+ super().__init__()
106
+
107
+ self.layers = torch.nn.ModuleList(layers)
108
+
109
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
110
+ # Input injection (add)
111
+ hidden_states = hidden_states + input_injection
112
+ # Layers
113
+ for layer in self.layers:
114
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
115
+
116
+ return hidden_states
117
+
118
+
119
+ class HierarchicalReasoningModel_ACTV1_Inner(nn.Module):
120
+ def __init__(self, config: HierarchicalReasoningModel_ACTV1Config) -> None:
121
+ super().__init__()
122
+ self.config = config
123
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
124
+
125
+ # I/O
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
+ # SHREK: Q-head input size depends on stagnation delta flag
132
+ q_head_input_size = self.config.hidden_size + (1 if self.config.enable_stagnation_delta else 0)
133
+ self.q_head = CastedLinear(q_head_input_size, 2, bias=True)
134
+
135
+ # SHREK: error_encoder maps the scalar error score -> hidden_size vector for injection into z_H
136
+ # alpha follows a linear warmup schedule (0 → alpha_max over warmup steps).
137
+ # This lets the error estimator train before its signal affects z_H.
138
+ self.error_encoder = nn.Linear(1, self.config.hidden_size)
139
+ # SHREK: step counter for alpha warmup (not a learned parameter)
140
+ self.register_buffer('_alpha_step', torch.tensor(0, dtype=torch.long))
141
+ # SHREK: error_estimator reads z_H and predicts how wrong the model is.
142
+ # trained via auxiliary loss in pretrain.py using the real lm_loss as target.
143
+ # catches "stuck but wrong" — a model confidently on the wrong answer.
144
+ # flip rate catches oscillation; estimator catches confident-but-wrong.
145
+ self.error_estimator = nn.Linear(self.config.hidden_size, 1)
146
+
147
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) # ceil div
148
+ if self.config.puzzle_emb_ndim > 0:
149
+ # Zero init puzzle embeddings
150
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
151
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
152
+
153
+ # LM Blocks
154
+ if self.config.pos_encodings == "rope":
155
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
156
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
157
+ base=self.config.rope_theta)
158
+ elif self.config.pos_encodings == "learned":
159
+ 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)
160
+ else:
161
+ raise NotImplementedError()
162
+
163
+ # Reasoning Layers
164
+ self.H_level = HierarchicalReasoningModel_ACTV1ReasoningModule(layers=[HierarchicalReasoningModel_ACTV1Block(self.config) for _i in range(self.config.H_layers)])
165
+ self.L_level = HierarchicalReasoningModel_ACTV1ReasoningModule(layers=[HierarchicalReasoningModel_ACTV1Block(self.config) for _i in range(self.config.L_layers)])
166
+
167
+ # Initial states
168
+ self.H_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
169
+ self.L_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
170
+
171
+ # Q head special init
172
+ # Init Q to (almost) zero for faster learning during bootstrapping
173
+ with torch.no_grad():
174
+ self.q_head.weight.zero_()
175
+ self.q_head.bias.fill_(-5) # type: ignore
176
+
177
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
178
+ # Token embedding
179
+ embedding = self.embed_tokens(input.to(torch.int32))
180
+
181
+ # Puzzle embeddings
182
+ if self.config.puzzle_emb_ndim > 0:
183
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
184
+
185
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
186
+ if pad_count > 0:
187
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
188
+
189
+ embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
190
+
191
+ # Position embeddings
192
+ if self.config.pos_encodings == "learned":
193
+ # scale by 1/sqrt(2) to maintain forward variance
194
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
195
+
196
+ # Scale
197
+ return self.embed_scale * embedding
198
+
199
+ def empty_carry(self, batch_size: int):
200
+ return HierarchicalReasoningModel_ACTV1InnerCarry(
201
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
202
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
203
+ # SHREK: zeros = no previous prediction — first step gives flip_rate ≈ 1.0
204
+ # device=H_init.device ensures prev_pred is on CUDA, matching z_H and logits
205
+ prev_pred=torch.zeros(batch_size, self.config.seq_len, dtype=torch.int32, device=self.H_init.device),
206
+ prev_q_halt=torch.full((batch_size,), -5.0, device=self.H_init.device),
207
+ prev_q_continue=torch.full((batch_size,), -5.0, device=self.H_init.device),
208
+ )
209
+
210
+ def reset_carry(self, reset_flag: torch.Tensor, carry: HierarchicalReasoningModel_ACTV1InnerCarry):
211
+ # SHREK: zero out prev_pred for reset sequences so they start fresh.
212
+ # a reset sequence is one that just halted — it will solve a new puzzle next.
213
+ # zeroing prev_pred means first step gives flip_rate ≈ 1.0 (maximum uncertainty).
214
+ new_prev_pred = torch.where(
215
+ reset_flag.view(-1, 1),
216
+ torch.zeros_like(carry.prev_pred),
217
+ carry.prev_pred
218
+ )
219
+ new_prev_q_halt = torch.where(reset_flag, torch.full_like(carry.prev_q_halt, -5.0), carry.prev_q_halt)
220
+ new_prev_q_continue = torch.where(reset_flag, torch.full_like(carry.prev_q_continue, -5.0), carry.prev_q_continue)
221
+
222
+ return HierarchicalReasoningModel_ACTV1InnerCarry(
223
+ z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
224
+ z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
225
+ prev_pred=new_prev_pred,
226
+ prev_q_halt=new_prev_q_halt,
227
+ prev_q_continue=new_prev_q_continue,
228
+ )
229
+
230
+
231
+ # SHREK: removed task_type parameter — error signal is now universal (no task rules needed)
232
+ def forward(self, carry: HierarchicalReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor], require_trace=False):
233
+ # -> Tuple[HierarchicalReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
234
+ seq_info = dict(
235
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
236
+ )
237
+
238
+ # Input encoding
239
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"])
240
+
241
+ z_H_trace = []
242
+
243
+ # Forward iterations
244
+ with torch.no_grad():
245
+ z_H, z_L = carry.z_H, carry.z_L
246
+
247
+ for _H_step in range(self.config.H_cycles):
248
+ for _L_step in range(self.config.L_cycles):
249
+ if not ((_H_step == self.config.H_cycles - 1) and (_L_step == self.config.L_cycles - 1)):
250
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
251
+
252
+ if not (_H_step == self.config.H_cycles - 1):
253
+ z_H = self.H_level(z_H, z_L, **seq_info)
254
+ if require_trace:
255
+ z_H_trace.append(z_H.detach().cpu().clone())
256
+
257
+ assert not z_H.requires_grad and not z_L.requires_grad
258
+
259
+ # 1-step grad
260
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
261
+ z_H = self.H_level(z_H, z_L, **seq_info)
262
+
263
+ if require_trace:
264
+ z_H_trace.append(z_H.detach().cpu().clone())
265
+
266
+ # LM Outputs — decode z_H into token predictions
267
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:] # (B, seq_len, vocab_size)
268
+
269
+ # SHREK Component 1: Combined Error Signal
270
+ # Signal A — flip rate: what fraction of tokens changed from last step?
271
+ # catches oscillation (model changing its mind between wrong options)
272
+ flip_err, current_pred = get_error_signal(output, carry.prev_pred) # (B,), (B, seq_len)
273
+
274
+ # Signal B — learned estimator: reads z_H and predicts how wrong the model is.
275
+ # catches stuck-but-wrong (model confidently on wrong answer without oscillating)
276
+ # average over content positions (skip puzzle embedding prefix positions)
277
+ # CRITICAL: detach z_H_mean so aux_loss only trains error_estimator weights,
278
+ # NOT the main reasoning layers. Without detach, aux_loss sends parasitic
279
+ # gradients through z_H → H_level/L_level that conflict with lm_loss.
280
+ z_H_mean = z_H[:, self.puzzle_emb_len:].mean(dim=1).detach() # (B, hidden_size)
281
+ learned_err = torch.sigmoid(self.error_estimator(z_H_mean.float())) # (B, 1)
282
+ learned_err = learned_err.squeeze(-1) # (B,)
283
+
284
+ # SHREK: combined error = 50/50 blend of both signals
285
+ # flip_err works immediately from step 1 (no learning needed)
286
+ # learned_err becomes accurate over training and takes over as the stronger signal
287
+ error = 0.5 * flip_err + 0.5 * learned_err # (B,)
288
+
289
+ # SHREK Component 2: Stagnation-Aware Q-head
290
+ # Ablation: can be disabled via config.enable_stagnation_delta=False
291
+ if self.config.enable_stagnation_delta:
292
+ # Compute how much z_H changed during this reasoning step.
293
+ # CRITICAL: detach so Q-head gradients don't flow through all positions of z_H.
294
+ # Without detach, Q-head loss would route gradients through all 82 positions,
295
+ # drowning out lm_loss. With detach, Q-head gradients only flow through position 0.
296
+ z_H_f = z_H.detach().float()
297
+ z_H_start = carry.z_H.detach().float()
298
+ delta = torch.norm(z_H_f - z_H_start, dim=(1, 2)) / (torch.norm(z_H_start, dim=(1, 2)) + 1e-6) # (B,)
299
+ # Q-head reads CLS token + stagnation delta
300
+ q_input = torch.cat([z_H[:, 0].to(torch.float32), delta.unsqueeze(-1)], dim=-1) # (B, hidden_size+1)
301
+ else:
302
+ # Fallback: same as original HRM — Q-head reads CLS token only
303
+ q_input = z_H[:, 0].to(torch.float32) # (B, hidden_size)
304
+ q_logits = self.q_head(q_input).to(torch.float32) # (B, 2)
305
+
306
+ # SHREK: inject combined error into z_H (AFTER Q-head, only affects carry for next step)
307
+ # Ablation: can be disabled via config.enable_error_injection=False
308
+ if self.config.enable_error_injection:
309
+ # error_encoder maps scalar -> hidden_size vector
310
+ # alpha follows linear warmup: 0 → alpha_max over warmup steps
311
+ # scaled by 1/sqrt(hidden_size) so injection is proportional to model size
312
+ error_emb = self.error_encoder(error.unsqueeze(-1)) # (B, hidden_size)
313
+ # SHREK: compute alpha from warmup schedule (not learned)
314
+ # During warmup, alpha ramps linearly from 0 to alpha_max.
315
+ # After warmup, alpha stays at alpha_max.
316
+ # Uses torch.clamp instead of Python min() to stay compatible with torch.compile.
317
+ with torch.no_grad():
318
+ if self.training:
319
+ self._alpha_step += 1
320
+ alpha = self.config.alpha_max * torch.clamp(self._alpha_step / self.config.alpha_warmup_steps, max=1.0)
321
+ scale = math.sqrt(self.config.hidden_size)
322
+ z_H = z_H + (alpha * error_emb.unsqueeze(1) / scale).to(z_H.dtype) # (B, seq_len, hidden_size)
323
+
324
+ # New carry: store error-injected z_H so next ACT step starts from it
325
+ new_carry = HierarchicalReasoningModel_ACTV1InnerCarry(
326
+ z_H=z_H.detach(),
327
+ z_L=z_L.detach(),
328
+ # SHREK: store current predictions — next step compares against these for flip rate
329
+ prev_pred=current_pred.detach(),
330
+ # SHREK: Q-values written to carry for torch.compile compatibility (not read for Q-targets)
331
+ prev_q_halt=q_logits[..., 0].detach(),
332
+ prev_q_continue=q_logits[..., 1].detach(),
333
+ )
334
+
335
+ # SHREK: also return learned_err so pretrain.py can compute auxiliary loss
336
+ # auxiliary loss trains the estimator: predicted error should match real lm_loss
337
+ if require_trace:
338
+ return z_H_trace, new_carry, output, (q_logits[..., 0], q_logits[..., 1]), learned_err
339
+ else:
340
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1]), learned_err
341
+
342
+
343
+ class HierarchicalReasoningModel_ACTV1(nn.Module):
344
+ """ACT wrapper."""
345
+
346
+ def __init__(self, config_dict: dict):
347
+ super().__init__()
348
+ self.config = HierarchicalReasoningModel_ACTV1Config(**config_dict)
349
+ self.inner = HierarchicalReasoningModel_ACTV1_Inner(self.config)
350
+
351
+ @property
352
+ def puzzle_emb(self):
353
+ return self.inner.puzzle_emb
354
+
355
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
356
+ batch_size = batch["inputs"].shape[0]
357
+
358
+ return HierarchicalReasoningModel_ACTV1Carry(
359
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
360
+
361
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
362
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
363
+
364
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
365
+ )
366
+
367
+ # SHREK: removed task_type parameter — error signal is universal, no task rules needed
368
+ def forward(self, carry: HierarchicalReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor], require_trace=False):
369
+ # -> Tuple[HierarchicalReasoningModel_ACTV1Carry, Dict[str, torch.Tensor], torch.Tensor]:
370
+ # Update data, carry (removing halted sequences)
371
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
372
+
373
+ new_steps = torch.where(carry.halted, 0, carry.steps)
374
+
375
+ 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()}
376
+
377
+ # SHREK: run inner forward — unpack learned_err for auxiliary loss in pretrain.py
378
+ if require_trace:
379
+ z_H_trace, new_inner_carry, logits, (q_halt_logits, q_continue_logits), learned_err = self.inner(new_inner_carry, new_current_data, require_trace=require_trace)
380
+ else:
381
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits), learned_err = self.inner(new_inner_carry, new_current_data)
382
+
383
+ outputs = {
384
+ "logits": logits,
385
+ "q_halt_logits": q_halt_logits,
386
+ "q_continue_logits": q_continue_logits,
387
+ "learned_err": learned_err, # SHREK: for auxiliary loss in pretrain.py
388
+ }
389
+
390
+ with torch.no_grad():
391
+ # Step
392
+ new_steps = new_steps + 1
393
+ is_last_step = new_steps >= self.config.halt_max_steps
394
+
395
+ halted = is_last_step
396
+
397
+ # if training, and ACT is enabled
398
+ if self.training and (self.config.halt_max_steps > 1):
399
+ # Halt signal
400
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
401
+ halted = halted | (q_halt_logits > q_continue_logits)
402
+
403
+ # Exploration
404
+ min_halt_steps = (torch.rand_like(q_halt_logits) < self.config.halt_exploration_prob) * torch.randint_like(new_steps, low=2, high=self.config.halt_max_steps + 1)
405
+
406
+ halted = halted & (new_steps >= min_halt_steps)
407
+
408
+ # SHREK: Q-target via double forward pass (same as original HRM).
409
+ # Run inner() a second time to get NEXT step's Q-values (step T+1).
410
+ # Save/restore _alpha_step so the second call doesn't double-count
411
+ # the warmup — without this, alpha reaches full strength at step ~2500
412
+ # instead of 5000, destabilizing early training.
413
+ # NOTE: prev_q fields in carry are not read here — they must stay
414
+ # in the dataclass for torch.compile compatibility.
415
+ saved_alpha_step = self.inner._alpha_step.clone()
416
+ next_q_halt_logits, next_q_continue_logits = self.inner(new_inner_carry, new_current_data)[-2]
417
+ self.inner._alpha_step.copy_(saved_alpha_step)
418
+
419
+ outputs["target_q_continue"] = torch.sigmoid(
420
+ torch.where(is_last_step,
421
+ next_q_halt_logits,
422
+ torch.maximum(next_q_halt_logits, next_q_continue_logits))
423
+ )
424
+
425
+ if require_trace:
426
+ return HierarchicalReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs, new_steps, (q_halt_logits > q_continue_logits), z_H_trace
427
+ else:
428
+ return HierarchicalReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs, new_steps, (q_halt_logits > q_continue_logits)
maze-hard/shrek-large/losses.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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):
25
+ logprobs = log_stablemax(logits.to(torch.float64), dim=-1)
26
+
27
+ valid_mask = labels != ignore_index
28
+ transformed_labels = torch.where(valid_mask, labels, 0)
29
+ prediction_logprobs = torch.gather(logprobs, index=transformed_labels.to(torch.long).unsqueeze(-1), dim=-1).squeeze(-1)
30
+
31
+ return -torch.where(valid_mask, prediction_logprobs, 0)
32
+
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
+ class ACTLossHead(nn.Module):
41
+ def __init__(self, model: nn.Module, loss_type: str):
42
+ super().__init__()
43
+ self.model = model
44
+ self.loss_fn = globals()[loss_type]
45
+
46
+ def initial_carry(self, *args, **kwargs):
47
+ return self.model.initial_carry(*args, **kwargs) # type: ignore
48
+
49
+ def forward(
50
+ self,
51
+ return_keys: Sequence[str],
52
+ require_trace=False,
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
+ if require_trace:
59
+ new_carry, outputs, steps, act_halt, z_H_trace = self.model(**model_kwargs, require_trace=require_trace)
60
+ else:
61
+ new_carry, outputs, steps, act_halt = self.model(**model_kwargs)
62
+ labels = new_carry.current_data["labels"]
63
+ alpha = 1.0
64
+ ds_mask = (alpha ** (16-steps.detach())).unsqueeze(dim=1)
65
+ # print(ds_mask.shape)
66
+
67
+ # Correctness
68
+ with torch.no_grad():
69
+ mask = labels != IGNORE_LABEL_ID
70
+ loss_counts = mask.sum(-1)
71
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
72
+
73
+ is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
74
+ seq_is_correct = is_correct.sum(-1) == loss_counts
75
+
76
+ # # Metrics (halted)
77
+ # valid_metrics = new_carry.halted & (loss_counts > 0)
78
+ valid_metrics = (loss_counts > 0)
79
+
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
+ # FIXME: Assuming the batch is always full
92
+ loss = self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID)
93
+ # print(loss.shape)
94
+ lm_loss = (ds_mask * loss / loss_divisor).sum()
95
+ q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
96
+
97
+ metrics.update({
98
+ "lm_loss": lm_loss.detach(),
99
+ "q_halt_loss": q_halt_loss.detach(),
100
+ })
101
+
102
+ # Q continue (bootstrapping target loss)
103
+ q_continue_loss = 0
104
+ if "target_q_continue" in outputs:
105
+ q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
106
+
107
+ metrics["q_continue_loss"] = q_continue_loss.detach()
108
+
109
+ # SHREK: auxiliary loss — trains error_estimator to predict per-sample lm_loss.
110
+ # Computed here (not in pretrain.py) so learned_err still has gradients.
111
+ # per_sample_lm_loss is detached so only error_estimator weights get updated by aux_loss.
112
+ aux_loss = 0
113
+ if "learned_err" in outputs:
114
+ per_sample_lm_loss = (ds_mask * loss / loss_divisor).sum(dim=1).detach() # (B,)
115
+ # SHREK: min-max normalize target to 0-1 so it matches sigmoid output range.
116
+ # When all losses are equal (early training), target = 0 (no distinguishable error).
117
+ # When losses vary, target spreads across 0-1 giving the estimator a useful signal.
118
+ lm_min = per_sample_lm_loss.min()
119
+ lm_max = per_sample_lm_loss.max()
120
+ target = (per_sample_lm_loss - lm_min) / (lm_max - lm_min + 1e-6) # (B,) in [0, 1]
121
+ aux_loss = F.mse_loss(outputs["learned_err"], target, reduction="sum")
122
+ metrics["aux_loss"] = aux_loss.detach()
123
+
124
+ # Filter outputs for return
125
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
126
+
127
+ if require_trace:
128
+ return z_H_trace, new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss) + 0.1 * aux_loss, metrics, detached_outputs, new_carry.halted.all(), new_carry.halted & act_halt
129
+ else:
130
+ return new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss) + 0.1 * aux_loss, metrics, detached_outputs, new_carry.halted.all(), new_carry.halted & act_halt
maze-hard/shrek-large/step_101556 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08ccbff96ecfe43f613e4ebe70bbe16dd92f09439edd28808ca3fc4519b3e278
3
+ size 109111847
maze-hard/shrek-large/step_109368 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3d7d6fe90c6e1fad34b7dd334c36b5342b4412541239f7cf0199954e381224a4
3
+ size 109111847
maze-hard/shrek-large/step_117180 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71b3c0f56ff3fd5afdc05dfb8bde57b43a193b182825b2c246e498b6911c2379
3
+ size 109111847
maze-hard/shrek-large/step_124992 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:326936b97c74e3c1bbd975a8bfb8a076db7c1bdfa96cc91f5181ee893625c0be
3
+ size 109111847
maze-hard/shrek-large/step_132804 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27f1f125b33ab8a44b1d1ef6d5515dc3c0bef0c88df525a231cb1d6752fe5a06
3
+ size 109111847
maze-hard/shrek-large/step_140616 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f247a5c5db6eefa268be10afdb517259d51d37419a1566985f7de34adff92b4f
3
+ size 109111847
maze-hard/shrek-large/step_148428 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b37762f33727c3860def9bb511976b18ddaa1e200bef6a06d022375b07e24303
3
+ size 109111847
maze-hard/shrek-large/step_15624 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45e4add6c2dfc906588a48837c10f37563997a8f708e72958014525f96a129d9
3
+ size 109111797
maze-hard/shrek-large/step_156240 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7cedd60dfbddddf69796dfdeb983ed41446df93c0aedc7bf1aebc9e43425c2a1
3
+ size 109111847
maze-hard/shrek-large/step_23436 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf9c10bd299cf10ba281857c92428a387975d71fc4a1d8f39b801cb88d5cafe1
3
+ size 109111797
maze-hard/shrek-large/step_31248 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0c59fa16073c0302aa19f7eff997b227f794f72d7190e40611290280792451d
3
+ size 109111797
maze-hard/shrek-large/step_39060 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d08ad4309fc6595ad92fcd74a4a5da9007d3c836e088739d4a0053423b06537
3
+ size 109111797
maze-hard/shrek-large/step_46872 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3451b89f913e209a86a75ca06e1314a8fb0fa5dd7da3809089c8f57350b07f5
3
+ size 109111797
maze-hard/shrek-large/step_54684 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a69447080712933e9195514ed7b96c9bc3e6a25d2989cda4fa1540ac1e50aaf
3
+ size 109111797
maze-hard/shrek-large/step_62496 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7043f51eae15d7c889d8f0d2cfbf1df57a448a1c78397439f7adf9a7def5d14d
3
+ size 109111797
maze-hard/shrek-large/step_70308 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c492ec94fc95b45ced1f7e3e2fefb96fb200f0d7d67046a74b6716115b476497
3
+ size 109111797
maze-hard/shrek-large/step_7812 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e51f3e00e1a30d22a377ac522120f600b5d8bd0e7c894ce1bbdabc26cae6fe37
3
+ size 109111747
maze-hard/shrek-large/step_78120 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26835cb1b232c8b52e5b2d539231bb6c13a449fafcd68fe5164854acd33319b5
3
+ size 109111797
maze-hard/shrek-large/step_85932 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2dcbf7dd090524a644c088fde7547329017554e728d6fc61d50b4029d7544ec
3
+ size 109111797
maze-hard/shrek-large/step_93744 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8382c66d053d0d376a25d8dec4b882a746ea83af9bb4319c6d0bfd4d1506f239
3
+ size 109111797
maze-hard/shrek-tiny/all_config.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arch:
2
+ H_cycles: 2
3
+ H_layers: 2
4
+ L_cycles: 2
5
+ L_layers: 2
6
+ expansion: 4
7
+ halt_exploration_prob: 0.1
8
+ halt_max_steps: 16
9
+ hidden_size: 512
10
+ loss:
11
+ loss_type: stablemax_cross_entropy
12
+ name: losses@ACTLossHead
13
+ name: hrm.hrm_act_v1@HierarchicalReasoningModel_ACTV1
14
+ num_heads: 8
15
+ pos_encodings: rope
16
+ puzzle_emb_ndim: 512
17
+ beta1: 0.9
18
+ beta2: 0.95
19
+ checkpoint_every_eval: true
20
+ checkpoint_path: checkpoints/HRM_Maze_Comparison/SHREK_Tiny_Maze
21
+ data_path: ../../dataset/data/maze-30x30-hard-1k
22
+ ema: true
23
+ ema_rate: 0.999
24
+ epochs: 20000
25
+ eval_interval: 1000
26
+ eval_save_outputs: []
27
+ global_batch_size: 128
28
+ lr: 0.0001
29
+ lr_min_ratio: 1.0
30
+ lr_warmup_steps: 2000
31
+ project_name: HRM_Maze_Comparison
32
+ puzzle_emb_lr: 0.0001
33
+ puzzle_emb_weight_decay: 1.0
34
+ run_name: SHREK_Tiny_Maze
35
+ seed: 0
36
+ weight_decay: 1.0
maze-hard/shrek-tiny/hrm_act_v1.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, List, Dict, Optional
2
+ from dataclasses import dataclass
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+ from pydantic import BaseModel
9
+
10
+ from models.common import trunc_normal_init_
11
+ from models.layers import rms_norm, SwiGLU, Attention, RotaryEmbedding, CosSin, CastedEmbedding, CastedLinear
12
+ from models.sparse_embedding import CastedSparseEmbedding
13
+ from models.hrm.error_singals import get_error_signal # SHREK: error signal module
14
+
15
+
16
+ @dataclass
17
+ class HierarchicalReasoningModel_ACTV1InnerCarry:
18
+ z_H: torch.Tensor
19
+ z_L: torch.Tensor
20
+ # SHREK: prev_pred stores last step's argmax predictions for flip rate computation.
21
+ # zeros = fresh start (first step after init or reset gives flip_rate ≈ 1.0)
22
+ prev_pred: torch.Tensor # (B, seq_len) int32
23
+ # SHREK: Q-values cached in carry — no longer used for Q-targets (see Bug 4),
24
+ # but kept because removing them causes torch.compile regression.
25
+ prev_q_halt: torch.Tensor # (B,) float32
26
+ prev_q_continue: torch.Tensor # (B,) float32
27
+
28
+
29
+ @dataclass
30
+ class HierarchicalReasoningModel_ACTV1Carry:
31
+ inner_carry: HierarchicalReasoningModel_ACTV1InnerCarry
32
+
33
+ steps: torch.Tensor
34
+ halted: torch.Tensor
35
+
36
+ current_data: Dict[str, torch.Tensor]
37
+
38
+
39
+ class HierarchicalReasoningModel_ACTV1Config(BaseModel):
40
+ batch_size: int
41
+ seq_len: int
42
+ puzzle_emb_ndim: int = 0
43
+ num_puzzle_identifiers: int
44
+ vocab_size: int
45
+
46
+ H_cycles: int
47
+ L_cycles: int
48
+
49
+ H_layers: int
50
+ L_layers: int
51
+
52
+ # Transformer config
53
+ hidden_size: int
54
+ expansion: float
55
+ num_heads: int
56
+ pos_encodings: str
57
+
58
+ rms_norm_eps: float = 1e-5
59
+ rope_theta: float = 10000.0
60
+
61
+ # Halting Q-learning config
62
+ halt_max_steps: int
63
+ halt_exploration_prob: float
64
+
65
+ # SHREK: error injection warmup — ramps alpha from 0 to alpha_max over warmup steps.
66
+ # Prevents small models from collapsing before the error estimator is accurate.
67
+ alpha_max: float = 0.01
68
+ alpha_warmup_steps: int = 5000
69
+
70
+ # SHREK ablation flags — disable components from training scripts
71
+ enable_error_injection: bool = True # Error-Conditioned Injection (flip rate + learned estimator)
72
+ enable_stagnation_delta: bool = True # Stagnation-Aware Q-head (delta fed to Q-head)
73
+
74
+ forward_dtype: str = "bfloat16"
75
+
76
+
77
+ class HierarchicalReasoningModel_ACTV1Block(nn.Module):
78
+ def __init__(self, config: HierarchicalReasoningModel_ACTV1Config) -> None:
79
+ super().__init__()
80
+
81
+ self.self_attn = Attention(
82
+ hidden_size=config.hidden_size,
83
+ head_dim=config.hidden_size // config.num_heads,
84
+ num_heads=config.num_heads,
85
+ num_key_value_heads=config.num_heads,
86
+ causal=False
87
+ )
88
+ self.mlp = SwiGLU(
89
+ hidden_size=config.hidden_size,
90
+ expansion=config.expansion,
91
+ )
92
+ self.norm_eps = config.rms_norm_eps
93
+
94
+ def forward(self, cos_sin: CosSin, hidden_states: torch.Tensor) -> torch.Tensor:
95
+ # Post Norm
96
+ # Self Attention
97
+ hidden_states = rms_norm(hidden_states + self.self_attn(cos_sin=cos_sin, hidden_states=hidden_states), variance_epsilon=self.norm_eps)
98
+ # Fully Connected
99
+ hidden_states = rms_norm(hidden_states + self.mlp(hidden_states), variance_epsilon=self.norm_eps)
100
+ return hidden_states
101
+
102
+
103
+ class HierarchicalReasoningModel_ACTV1ReasoningModule(nn.Module):
104
+ def __init__(self, layers: List[HierarchicalReasoningModel_ACTV1Block]):
105
+ super().__init__()
106
+
107
+ self.layers = torch.nn.ModuleList(layers)
108
+
109
+ def forward(self, hidden_states: torch.Tensor, input_injection: torch.Tensor, **kwargs) -> torch.Tensor:
110
+ # Input injection (add)
111
+ hidden_states = hidden_states + input_injection
112
+ # Layers
113
+ for layer in self.layers:
114
+ hidden_states = layer(hidden_states=hidden_states, **kwargs)
115
+
116
+ return hidden_states
117
+
118
+
119
+ class HierarchicalReasoningModel_ACTV1_Inner(nn.Module):
120
+ def __init__(self, config: HierarchicalReasoningModel_ACTV1Config) -> None:
121
+ super().__init__()
122
+ self.config = config
123
+ self.forward_dtype = getattr(torch, self.config.forward_dtype)
124
+
125
+ # I/O
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
+ # SHREK: Q-head input size depends on stagnation delta flag
132
+ q_head_input_size = self.config.hidden_size + (1 if self.config.enable_stagnation_delta else 0)
133
+ self.q_head = CastedLinear(q_head_input_size, 2, bias=True)
134
+
135
+ # SHREK: error_encoder maps the scalar error score -> hidden_size vector for injection into z_H
136
+ # alpha follows a linear warmup schedule (0 → alpha_max over warmup steps).
137
+ # This lets the error estimator train before its signal affects z_H.
138
+ self.error_encoder = nn.Linear(1, self.config.hidden_size)
139
+ # SHREK: step counter for alpha warmup (not a learned parameter)
140
+ self.register_buffer('_alpha_step', torch.tensor(0, dtype=torch.long))
141
+ # SHREK: error_estimator reads z_H and predicts how wrong the model is.
142
+ # trained via auxiliary loss in pretrain.py using the real lm_loss as target.
143
+ # catches "stuck but wrong" — a model confidently on the wrong answer.
144
+ # flip rate catches oscillation; estimator catches confident-but-wrong.
145
+ self.error_estimator = nn.Linear(self.config.hidden_size, 1)
146
+
147
+ self.puzzle_emb_len = -(self.config.puzzle_emb_ndim // -self.config.hidden_size) # ceil div
148
+ if self.config.puzzle_emb_ndim > 0:
149
+ # Zero init puzzle embeddings
150
+ self.puzzle_emb = CastedSparseEmbedding(self.config.num_puzzle_identifiers, self.config.puzzle_emb_ndim,
151
+ batch_size=self.config.batch_size, init_std=0, cast_to=self.forward_dtype)
152
+
153
+ # LM Blocks
154
+ if self.config.pos_encodings == "rope":
155
+ self.rotary_emb = RotaryEmbedding(dim=self.config.hidden_size // self.config.num_heads,
156
+ max_position_embeddings=self.config.seq_len + self.puzzle_emb_len,
157
+ base=self.config.rope_theta)
158
+ elif self.config.pos_encodings == "learned":
159
+ 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)
160
+ else:
161
+ raise NotImplementedError()
162
+
163
+ # Reasoning Layers
164
+ self.H_level = HierarchicalReasoningModel_ACTV1ReasoningModule(layers=[HierarchicalReasoningModel_ACTV1Block(self.config) for _i in range(self.config.H_layers)])
165
+ self.L_level = HierarchicalReasoningModel_ACTV1ReasoningModule(layers=[HierarchicalReasoningModel_ACTV1Block(self.config) for _i in range(self.config.L_layers)])
166
+
167
+ # Initial states
168
+ self.H_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
169
+ self.L_init = nn.Buffer(trunc_normal_init_(torch.empty(self.config.hidden_size, dtype=self.forward_dtype), std=1), persistent=True)
170
+
171
+ # Q head special init
172
+ # Init Q to (almost) zero for faster learning during bootstrapping
173
+ with torch.no_grad():
174
+ self.q_head.weight.zero_()
175
+ self.q_head.bias.fill_(-5) # type: ignore
176
+
177
+ def _input_embeddings(self, input: torch.Tensor, puzzle_identifiers: torch.Tensor):
178
+ # Token embedding
179
+ embedding = self.embed_tokens(input.to(torch.int32))
180
+
181
+ # Puzzle embeddings
182
+ if self.config.puzzle_emb_ndim > 0:
183
+ puzzle_embedding = self.puzzle_emb(puzzle_identifiers)
184
+
185
+ pad_count = self.puzzle_emb_len * self.config.hidden_size - puzzle_embedding.shape[-1]
186
+ if pad_count > 0:
187
+ puzzle_embedding = F.pad(puzzle_embedding, (0, pad_count))
188
+
189
+ embedding = torch.cat((puzzle_embedding.view(-1, self.puzzle_emb_len, self.config.hidden_size), embedding), dim=-2)
190
+
191
+ # Position embeddings
192
+ if self.config.pos_encodings == "learned":
193
+ # scale by 1/sqrt(2) to maintain forward variance
194
+ embedding = 0.707106781 * (embedding + self.embed_pos.embedding_weight.to(self.forward_dtype))
195
+
196
+ # Scale
197
+ return self.embed_scale * embedding
198
+
199
+ def empty_carry(self, batch_size: int):
200
+ return HierarchicalReasoningModel_ACTV1InnerCarry(
201
+ z_H=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
202
+ z_L=torch.empty(batch_size, self.config.seq_len + self.puzzle_emb_len, self.config.hidden_size, dtype=self.forward_dtype),
203
+ # SHREK: zeros = no previous prediction — first step gives flip_rate ≈ 1.0
204
+ # device=H_init.device ensures prev_pred is on CUDA, matching z_H and logits
205
+ prev_pred=torch.zeros(batch_size, self.config.seq_len, dtype=torch.int32, device=self.H_init.device),
206
+ prev_q_halt=torch.full((batch_size,), -5.0, device=self.H_init.device),
207
+ prev_q_continue=torch.full((batch_size,), -5.0, device=self.H_init.device),
208
+ )
209
+
210
+ def reset_carry(self, reset_flag: torch.Tensor, carry: HierarchicalReasoningModel_ACTV1InnerCarry):
211
+ # SHREK: zero out prev_pred for reset sequences so they start fresh.
212
+ # a reset sequence is one that just halted — it will solve a new puzzle next.
213
+ # zeroing prev_pred means first step gives flip_rate ≈ 1.0 (maximum uncertainty).
214
+ new_prev_pred = torch.where(
215
+ reset_flag.view(-1, 1),
216
+ torch.zeros_like(carry.prev_pred),
217
+ carry.prev_pred
218
+ )
219
+ new_prev_q_halt = torch.where(reset_flag, torch.full_like(carry.prev_q_halt, -5.0), carry.prev_q_halt)
220
+ new_prev_q_continue = torch.where(reset_flag, torch.full_like(carry.prev_q_continue, -5.0), carry.prev_q_continue)
221
+
222
+ return HierarchicalReasoningModel_ACTV1InnerCarry(
223
+ z_H=torch.where(reset_flag.view(-1, 1, 1), self.H_init, carry.z_H),
224
+ z_L=torch.where(reset_flag.view(-1, 1, 1), self.L_init, carry.z_L),
225
+ prev_pred=new_prev_pred,
226
+ prev_q_halt=new_prev_q_halt,
227
+ prev_q_continue=new_prev_q_continue,
228
+ )
229
+
230
+
231
+ # SHREK: removed task_type parameter — error signal is now universal (no task rules needed)
232
+ def forward(self, carry: HierarchicalReasoningModel_ACTV1InnerCarry, batch: Dict[str, torch.Tensor], require_trace=False):
233
+ # -> Tuple[HierarchicalReasoningModel_ACTV1InnerCarry, torch.Tensor, Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
234
+ seq_info = dict(
235
+ cos_sin=self.rotary_emb() if hasattr(self, "rotary_emb") else None,
236
+ )
237
+
238
+ # Input encoding
239
+ input_embeddings = self._input_embeddings(batch["inputs"], batch["puzzle_identifiers"])
240
+
241
+ z_H_trace = []
242
+
243
+ # Forward iterations
244
+ with torch.no_grad():
245
+ z_H, z_L = carry.z_H, carry.z_L
246
+
247
+ for _H_step in range(self.config.H_cycles):
248
+ for _L_step in range(self.config.L_cycles):
249
+ if not ((_H_step == self.config.H_cycles - 1) and (_L_step == self.config.L_cycles - 1)):
250
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
251
+
252
+ if not (_H_step == self.config.H_cycles - 1):
253
+ z_H = self.H_level(z_H, z_L, **seq_info)
254
+ if require_trace:
255
+ z_H_trace.append(z_H.detach().cpu().clone())
256
+
257
+ assert not z_H.requires_grad and not z_L.requires_grad
258
+
259
+ # 1-step grad
260
+ z_L = self.L_level(z_L, z_H + input_embeddings, **seq_info)
261
+ z_H = self.H_level(z_H, z_L, **seq_info)
262
+
263
+ if require_trace:
264
+ z_H_trace.append(z_H.detach().cpu().clone())
265
+
266
+ # LM Outputs — decode z_H into token predictions
267
+ output = self.lm_head(z_H)[:, self.puzzle_emb_len:] # (B, seq_len, vocab_size)
268
+
269
+ # SHREK Component 1: Combined Error Signal
270
+ # Signal A — flip rate: what fraction of tokens changed from last step?
271
+ # catches oscillation (model changing its mind between wrong options)
272
+ flip_err, current_pred = get_error_signal(output, carry.prev_pred) # (B,), (B, seq_len)
273
+
274
+ # Signal B — learned estimator: reads z_H and predicts how wrong the model is.
275
+ # catches stuck-but-wrong (model confidently on wrong answer without oscillating)
276
+ # average over content positions (skip puzzle embedding prefix positions)
277
+ # CRITICAL: detach z_H_mean so aux_loss only trains error_estimator weights,
278
+ # NOT the main reasoning layers. Without detach, aux_loss sends parasitic
279
+ # gradients through z_H → H_level/L_level that conflict with lm_loss.
280
+ z_H_mean = z_H[:, self.puzzle_emb_len:].mean(dim=1).detach() # (B, hidden_size)
281
+ learned_err = torch.sigmoid(self.error_estimator(z_H_mean.float())) # (B, 1)
282
+ learned_err = learned_err.squeeze(-1) # (B,)
283
+
284
+ # SHREK: combined error = 50/50 blend of both signals
285
+ # flip_err works immediately from step 1 (no learning needed)
286
+ # learned_err becomes accurate over training and takes over as the stronger signal
287
+ error = 0.5 * flip_err + 0.5 * learned_err # (B,)
288
+
289
+ # SHREK Component 2: Stagnation-Aware Q-head
290
+ # Ablation: can be disabled via config.enable_stagnation_delta=False
291
+ if self.config.enable_stagnation_delta:
292
+ # Compute how much z_H changed during this reasoning step.
293
+ # CRITICAL: detach so Q-head gradients don't flow through all positions of z_H.
294
+ # Without detach, Q-head loss would route gradients through all 82 positions,
295
+ # drowning out lm_loss. With detach, Q-head gradients only flow through position 0.
296
+ z_H_f = z_H.detach().float()
297
+ z_H_start = carry.z_H.detach().float()
298
+ delta = torch.norm(z_H_f - z_H_start, dim=(1, 2)) / (torch.norm(z_H_start, dim=(1, 2)) + 1e-6) # (B,)
299
+ # Q-head reads CLS token + stagnation delta
300
+ q_input = torch.cat([z_H[:, 0].to(torch.float32), delta.unsqueeze(-1)], dim=-1) # (B, hidden_size+1)
301
+ else:
302
+ # Fallback: same as original HRM — Q-head reads CLS token only
303
+ q_input = z_H[:, 0].to(torch.float32) # (B, hidden_size)
304
+ q_logits = self.q_head(q_input).to(torch.float32) # (B, 2)
305
+
306
+ # SHREK: inject combined error into z_H (AFTER Q-head, only affects carry for next step)
307
+ # Ablation: can be disabled via config.enable_error_injection=False
308
+ if self.config.enable_error_injection:
309
+ # error_encoder maps scalar -> hidden_size vector
310
+ # alpha follows linear warmup: 0 → alpha_max over warmup steps
311
+ # scaled by 1/sqrt(hidden_size) so injection is proportional to model size
312
+ error_emb = self.error_encoder(error.unsqueeze(-1)) # (B, hidden_size)
313
+ # SHREK: compute alpha from warmup schedule (not learned)
314
+ # During warmup, alpha ramps linearly from 0 to alpha_max.
315
+ # After warmup, alpha stays at alpha_max.
316
+ # Uses torch.clamp instead of Python min() to stay compatible with torch.compile.
317
+ with torch.no_grad():
318
+ if self.training:
319
+ self._alpha_step += 1
320
+ alpha = self.config.alpha_max * torch.clamp(self._alpha_step / self.config.alpha_warmup_steps, max=1.0)
321
+ scale = math.sqrt(self.config.hidden_size)
322
+ z_H = z_H + (alpha * error_emb.unsqueeze(1) / scale).to(z_H.dtype) # (B, seq_len, hidden_size)
323
+
324
+ # New carry: store error-injected z_H so next ACT step starts from it
325
+ new_carry = HierarchicalReasoningModel_ACTV1InnerCarry(
326
+ z_H=z_H.detach(),
327
+ z_L=z_L.detach(),
328
+ # SHREK: store current predictions — next step compares against these for flip rate
329
+ prev_pred=current_pred.detach(),
330
+ # SHREK: Q-values written to carry for torch.compile compatibility (not read for Q-targets)
331
+ prev_q_halt=q_logits[..., 0].detach(),
332
+ prev_q_continue=q_logits[..., 1].detach(),
333
+ )
334
+
335
+ # SHREK: also return learned_err so pretrain.py can compute auxiliary loss
336
+ # auxiliary loss trains the estimator: predicted error should match real lm_loss
337
+ if require_trace:
338
+ return z_H_trace, new_carry, output, (q_logits[..., 0], q_logits[..., 1]), learned_err
339
+ else:
340
+ return new_carry, output, (q_logits[..., 0], q_logits[..., 1]), learned_err
341
+
342
+
343
+ class HierarchicalReasoningModel_ACTV1(nn.Module):
344
+ """ACT wrapper."""
345
+
346
+ def __init__(self, config_dict: dict):
347
+ super().__init__()
348
+ self.config = HierarchicalReasoningModel_ACTV1Config(**config_dict)
349
+ self.inner = HierarchicalReasoningModel_ACTV1_Inner(self.config)
350
+
351
+ @property
352
+ def puzzle_emb(self):
353
+ return self.inner.puzzle_emb
354
+
355
+ def initial_carry(self, batch: Dict[str, torch.Tensor]):
356
+ batch_size = batch["inputs"].shape[0]
357
+
358
+ return HierarchicalReasoningModel_ACTV1Carry(
359
+ inner_carry=self.inner.empty_carry(batch_size), # Empty is expected, it will be reseted in first pass as all sequences are halted.
360
+
361
+ steps=torch.zeros((batch_size, ), dtype=torch.int32),
362
+ halted=torch.ones((batch_size, ), dtype=torch.bool), # Default to halted
363
+
364
+ current_data={k: torch.empty_like(v) for k, v in batch.items()}
365
+ )
366
+
367
+ # SHREK: removed task_type parameter — error signal is universal, no task rules needed
368
+ def forward(self, carry: HierarchicalReasoningModel_ACTV1Carry, batch: Dict[str, torch.Tensor], require_trace=False):
369
+ # -> Tuple[HierarchicalReasoningModel_ACTV1Carry, Dict[str, torch.Tensor], torch.Tensor]:
370
+ # Update data, carry (removing halted sequences)
371
+ new_inner_carry = self.inner.reset_carry(carry.halted, carry.inner_carry)
372
+
373
+ new_steps = torch.where(carry.halted, 0, carry.steps)
374
+
375
+ 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()}
376
+
377
+ # SHREK: run inner forward — unpack learned_err for auxiliary loss in pretrain.py
378
+ if require_trace:
379
+ z_H_trace, new_inner_carry, logits, (q_halt_logits, q_continue_logits), learned_err = self.inner(new_inner_carry, new_current_data, require_trace=require_trace)
380
+ else:
381
+ new_inner_carry, logits, (q_halt_logits, q_continue_logits), learned_err = self.inner(new_inner_carry, new_current_data)
382
+
383
+ outputs = {
384
+ "logits": logits,
385
+ "q_halt_logits": q_halt_logits,
386
+ "q_continue_logits": q_continue_logits,
387
+ "learned_err": learned_err, # SHREK: for auxiliary loss in pretrain.py
388
+ }
389
+
390
+ with torch.no_grad():
391
+ # Step
392
+ new_steps = new_steps + 1
393
+ is_last_step = new_steps >= self.config.halt_max_steps
394
+
395
+ halted = is_last_step
396
+
397
+ # if training, and ACT is enabled
398
+ if self.training and (self.config.halt_max_steps > 1):
399
+ # Halt signal
400
+ # NOTE: During evaluation, always use max steps, this is to guarantee the same halting steps inside a batch for batching purposes
401
+ halted = halted | (q_halt_logits > q_continue_logits)
402
+
403
+ # Exploration
404
+ min_halt_steps = (torch.rand_like(q_halt_logits) < self.config.halt_exploration_prob) * torch.randint_like(new_steps, low=2, high=self.config.halt_max_steps + 1)
405
+
406
+ halted = halted & (new_steps >= min_halt_steps)
407
+
408
+ # SHREK: Q-target via double forward pass (same as original HRM).
409
+ # Run inner() a second time to get NEXT step's Q-values (step T+1).
410
+ # Save/restore _alpha_step so the second call doesn't double-count
411
+ # the warmup — without this, alpha reaches full strength at step ~2500
412
+ # instead of 5000, destabilizing early training.
413
+ # NOTE: prev_q fields in carry are not read here — they must stay
414
+ # in the dataclass for torch.compile compatibility.
415
+ saved_alpha_step = self.inner._alpha_step.clone()
416
+ next_q_halt_logits, next_q_continue_logits = self.inner(new_inner_carry, new_current_data)[-2]
417
+ self.inner._alpha_step.copy_(saved_alpha_step)
418
+
419
+ outputs["target_q_continue"] = torch.sigmoid(
420
+ torch.where(is_last_step,
421
+ next_q_halt_logits,
422
+ torch.maximum(next_q_halt_logits, next_q_continue_logits))
423
+ )
424
+
425
+ if require_trace:
426
+ return HierarchicalReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs, new_steps, (q_halt_logits > q_continue_logits), z_H_trace
427
+ else:
428
+ return HierarchicalReasoningModel_ACTV1Carry(new_inner_carry, new_steps, halted, new_current_data), outputs, new_steps, (q_halt_logits > q_continue_logits)
maze-hard/shrek-tiny/losses.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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):
25
+ logprobs = log_stablemax(logits.to(torch.float64), dim=-1)
26
+
27
+ valid_mask = labels != ignore_index
28
+ transformed_labels = torch.where(valid_mask, labels, 0)
29
+ prediction_logprobs = torch.gather(logprobs, index=transformed_labels.to(torch.long).unsqueeze(-1), dim=-1).squeeze(-1)
30
+
31
+ return -torch.where(valid_mask, prediction_logprobs, 0)
32
+
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
+ class ACTLossHead(nn.Module):
41
+ def __init__(self, model: nn.Module, loss_type: str):
42
+ super().__init__()
43
+ self.model = model
44
+ self.loss_fn = globals()[loss_type]
45
+
46
+ def initial_carry(self, *args, **kwargs):
47
+ return self.model.initial_carry(*args, **kwargs) # type: ignore
48
+
49
+ def forward(
50
+ self,
51
+ return_keys: Sequence[str],
52
+ require_trace=False,
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
+ if require_trace:
59
+ new_carry, outputs, steps, act_halt, z_H_trace = self.model(**model_kwargs, require_trace=require_trace)
60
+ else:
61
+ new_carry, outputs, steps, act_halt = self.model(**model_kwargs)
62
+ labels = new_carry.current_data["labels"]
63
+ alpha = 1.0
64
+ ds_mask = (alpha ** (16-steps.detach())).unsqueeze(dim=1)
65
+ # print(ds_mask.shape)
66
+
67
+ # Correctness
68
+ with torch.no_grad():
69
+ mask = labels != IGNORE_LABEL_ID
70
+ loss_counts = mask.sum(-1)
71
+ loss_divisor = loss_counts.clamp_min(1).unsqueeze(-1) # Avoid NaNs in division
72
+
73
+ is_correct = mask & (torch.argmax(outputs["logits"], dim=-1) == labels)
74
+ seq_is_correct = is_correct.sum(-1) == loss_counts
75
+
76
+ # # Metrics (halted)
77
+ # valid_metrics = new_carry.halted & (loss_counts > 0)
78
+ valid_metrics = (loss_counts > 0)
79
+
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
+ # FIXME: Assuming the batch is always full
92
+ loss = self.loss_fn(outputs["logits"], labels, ignore_index=IGNORE_LABEL_ID)
93
+ # print(loss.shape)
94
+ lm_loss = (ds_mask * loss / loss_divisor).sum()
95
+ q_halt_loss = F.binary_cross_entropy_with_logits(outputs["q_halt_logits"], seq_is_correct.to(outputs["q_halt_logits"].dtype), reduction="sum")
96
+
97
+ metrics.update({
98
+ "lm_loss": lm_loss.detach(),
99
+ "q_halt_loss": q_halt_loss.detach(),
100
+ })
101
+
102
+ # Q continue (bootstrapping target loss)
103
+ q_continue_loss = 0
104
+ if "target_q_continue" in outputs:
105
+ q_continue_loss = F.binary_cross_entropy_with_logits(outputs["q_continue_logits"], outputs["target_q_continue"], reduction="sum")
106
+
107
+ metrics["q_continue_loss"] = q_continue_loss.detach()
108
+
109
+ # SHREK: auxiliary loss — trains error_estimator to predict per-sample lm_loss.
110
+ # Computed here (not in pretrain.py) so learned_err still has gradients.
111
+ # per_sample_lm_loss is detached so only error_estimator weights get updated by aux_loss.
112
+ aux_loss = 0
113
+ if "learned_err" in outputs:
114
+ per_sample_lm_loss = (ds_mask * loss / loss_divisor).sum(dim=1).detach() # (B,)
115
+ # SHREK: min-max normalize target to 0-1 so it matches sigmoid output range.
116
+ # When all losses are equal (early training), target = 0 (no distinguishable error).
117
+ # When losses vary, target spreads across 0-1 giving the estimator a useful signal.
118
+ lm_min = per_sample_lm_loss.min()
119
+ lm_max = per_sample_lm_loss.max()
120
+ target = (per_sample_lm_loss - lm_min) / (lm_max - lm_min + 1e-6) # (B,) in [0, 1]
121
+ aux_loss = F.mse_loss(outputs["learned_err"], target, reduction="sum")
122
+ metrics["aux_loss"] = aux_loss.detach()
123
+
124
+ # Filter outputs for return
125
+ detached_outputs = {k: outputs[k].detach() for k in return_keys if k in outputs}
126
+
127
+ if require_trace:
128
+ return z_H_trace, new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss) + 0.1 * aux_loss, metrics, detached_outputs, new_carry.halted.all(), new_carry.halted & act_halt
129
+ else:
130
+ return new_carry, lm_loss + 0.5 * (q_halt_loss + q_continue_loss) + 0.1 * aux_loss, metrics, detached_outputs, new_carry.halted.all(), new_carry.halted & act_halt