ThomasHeim commited on
Commit
42d60b9
·
verified ·
1 Parent(s): 5cec7e2

Delete shrek-large

Browse files
shrek-large/all_config.yaml DELETED
@@ -1,38 +0,0 @@
1
- arch:
2
- H_cycles: 2
3
- H_layers: 4
4
- L_cycles: 2
5
- L_layers: 4
6
- enable_error_injection: true
7
- enable_stagnation_delta: true
8
- expansion: 4
9
- halt_exploration_prob: 0.1
10
- halt_max_steps: 16
11
- hidden_size: 512
12
- loss:
13
- loss_type: stablemax_cross_entropy
14
- name: losses@ACTLossHead
15
- name: hrm.hrm_act_v1@HierarchicalReasoningModel_ACTV1
16
- num_heads: 8
17
- pos_encodings: rope
18
- puzzle_emb_ndim: 512
19
- beta1: 0.9
20
- beta2: 0.95
21
- checkpoint_every_eval: true
22
- checkpoint_path: checkpoints/SHREK_Ablation_Sudoku/Ablation_Full
23
- data_path: ../../dataset/data/sudoku-extreme-1k-aug-1000
24
- ema: true
25
- ema_rate: 0.999
26
- epochs: 40000
27
- eval_interval: 1000
28
- eval_save_outputs: []
29
- global_batch_size: 768
30
- lr: 0.0001
31
- lr_min_ratio: 1.0
32
- lr_warmup_steps: 2000
33
- project_name: SHREK_Ablation_Sudoku
34
- puzzle_emb_lr: 0.0001
35
- puzzle_emb_weight_decay: 1.0
36
- run_name: Ablation_Full
37
- seed: 0
38
- weight_decay: 1.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shrek-large/hrm_act_v1.py DELETED
@@ -1,428 +0,0 @@
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shrek-large/losses.py DELETED
@@ -1,130 +0,0 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shrek-large/step_10416 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:147000bf80dda989b06d3d41d38b049147f09b2cd4337bc900bab47659ab051a
3
- size 109132277
 
 
 
 
shrek-large/step_11718 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b0f244eb43e8f8721aa83de3c67ea5c55981daf3d4d34b2dcc000cfb7f2fa049
3
- size 109132277
 
 
 
 
shrek-large/step_1302 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:fa57cacb5c0b4e2fe39b972ed023f607e58af1f65e00c27933447782a5a7e280
3
- size 109132227
 
 
 
 
shrek-large/step_13020 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:30ab6636ca239f58d2ad99309c21490e30d9e548a243e0a097238dbf68e51de8
3
- size 109132277
 
 
 
 
shrek-large/step_14322 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:d05112ce240492d04c17afb08bd18ee588f6d38857ed6077188271ed13e473d9
3
- size 109132277
 
 
 
 
shrek-large/step_15624 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f5d15df5b2726034b3f525fca574278732d9acee78e9f5cc38818093569adc03
3
- size 109132277
 
 
 
 
shrek-large/step_16926 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:5c24cf1d9e1857f6f7199fa1104275a403eb571e504650183fb81b620702e67b
3
- size 109132277
 
 
 
 
shrek-large/step_18228 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:87bcdeebc40bee22e21f50f2aa896c41132d66b033a4f2a40152bd40d868e719
3
- size 109132277
 
 
 
 
shrek-large/step_19530 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4febb10506ffece426ab81a7bcaaa845e5996ad6b8a11d5bd1d76b9af9f718fb
3
- size 109132277
 
 
 
 
shrek-large/step_20832 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:fd14e741dfa042160bf66d17dcb0ebc0f7a0e5e2e824d5a65054dd7e2a5028b7
3
- size 109132277
 
 
 
 
shrek-large/step_22134 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9b66855afa14a809ff6555f1d343d748c51ef4846d8a82505f50127d1593b1c7
3
- size 109132277
 
 
 
 
shrek-large/step_23436 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b68ed600f2959861eb78eae7e468a72373a528ce96ec831c9d8cc63a94d5e26c
3
- size 109132277
 
 
 
 
shrek-large/step_24738 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0cceebf820f4b19cd5f0a636f89249f40a727e0bc254ec11daca024436cdf5d1
3
- size 109132277
 
 
 
 
shrek-large/step_2604 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:52761938f9fa3a4a50f2ffbf8b4a6213a7f02f5c8bca7b31b554dbd7764bda32
3
- size 109132227
 
 
 
 
shrek-large/step_26040 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4f3a67aa7594d134869a42e545b7bb64fbb3c637665fd93abb58d55caadfd201
3
- size 109132277
 
 
 
 
shrek-large/step_26040_all_preds.0 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:ff09fb7394310084cee07c994447788922de75c52acfc3c01fa610050a64f9ea
3
- size 1033379377
 
 
 
 
shrek-large/step_27342 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:559dd246cc1056cf29c9e2aa9b6c2dd926a5bedffd86d8c80af9ac3619ca1078
3
- size 109132277
 
 
 
 
shrek-large/step_28644 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:d84277d654f1deb7c233b8002101cccb55e5b5ce0b4e995d6149803b5cb72e14
3
- size 109132277
 
 
 
 
shrek-large/step_29946 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:1627582b1a0b66ea6cb62acbe9ea41c10c827e653e1be69d478ab52119371b68
3
- size 109132277
 
 
 
 
shrek-large/step_31248 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:917aabe08aa8a1ea44571d0d0261eae2ad1cd347e04b07dae85b0e42680ae53d
3
- size 109132277
 
 
 
 
shrek-large/step_32550 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8859b628b841ae58b335b4369f4b4441ebd66af6c509dd52f46cf7e3d4654e3d
3
- size 109132277
 
 
 
 
shrek-large/step_33852 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7555488ada68c6e416a9bb340e62074a554faa46c594065bd5be4654051f002a
3
- size 109132277
 
 
 
 
shrek-large/step_35154 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:34727184d6848d7d3222a896504dfe7cd36cd81e8b1a7865b8c653299129682e
3
- size 109132277
 
 
 
 
shrek-large/step_36456 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7410dac24d57ee2ec3ebec2dc7689a59aaeb2317d3e6e816b78a088f465f7fc7
3
- size 109132277
 
 
 
 
shrek-large/step_37758 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:44ab97684ebd3a107f02c58089e18eae087a7074db7b9df4167afc7d64f3f151
3
- size 109132277
 
 
 
 
shrek-large/step_3906 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f6a24669cb7c1cdb0f12fc26841d3a559afbcc44199f5026d85d7b0e5225b0f7
3
- size 109132227
 
 
 
 
shrek-large/step_39060 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9698e5fd3de73f38d35192f61d48b7688a66e06cd1a65274697bc13710eee691
3
- size 109132277
 
 
 
 
shrek-large/step_40362 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3eb3fc8abdd5480b9ef557ce0cb9faddc5fc3b53c51bbfef4a5519be35827c7e
3
- size 109132277
 
 
 
 
shrek-large/step_41664 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9d6aebd37a278fca9dccbdf6c1cd934e8e5a53d82ac59b6e19816a369ec381a8
3
- size 109132277
 
 
 
 
shrek-large/step_42966 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2373f4a08d9232b8e5bbeac8671726095d2d80750faf7f6dc6967a599a79e334
3
- size 109132277
 
 
 
 
shrek-large/step_44268 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3dc162480a3fff229c99ffa0333e85deb60873bd145fccafe64cc421a6cc527a
3
- size 109132277
 
 
 
 
shrek-large/step_45570 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6700a7e31323d817a94f13a97faf0184e6f8106536ab0129c2b8b93fe85d430e
3
- size 109132277
 
 
 
 
shrek-large/step_46872 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b8ae314f28e9a80864ca910946419da685b34a766a84ac5d81f0336c18f890bd
3
- size 109132277
 
 
 
 
shrek-large/step_48174 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:08c5ac811a4926ed36ade9f7481e337622d4f6b5c9e9e0c97937d7c21145a6ae
3
- size 109132277
 
 
 
 
shrek-large/step_49476 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6c79eecd0930cd43b132bcdaf860af5d4704bf81b80d036e3310610178a2a97a
3
- size 109132277
 
 
 
 
shrek-large/step_50778 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:dcdcb634d4f486584b914f7056a19ef5cb41b7130e759ef9bab76781b700e7d0
3
- size 109132277
 
 
 
 
shrek-large/step_5208 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:451a3a8f5b5820ad4a9cbad091d21eb8a315592d0cba7322eee088a4c129697f
3
- size 109132227
 
 
 
 
shrek-large/step_52080 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:05c391c110109be437b145dade72bce5c60cb066317a8e1f985f967d0af4cfb4
3
- size 109132277
 
 
 
 
shrek-large/step_6510 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a8c847c9de28f92886cb048d164dfa2efbeef9e61ae666f37acb303a7b4836bb
3
- size 109132227
 
 
 
 
shrek-large/step_7812 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:c55be1e7863d5f91188515f4597a05b1aa10696ea9f98636ae60210fc8594722
3
- size 109132227
 
 
 
 
shrek-large/step_9114 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8fc304e2a5f543dc812ad0c27a2669ba0ca80fdd945bfe3e2c1bc2c163db8cde
3
- size 109132227