JonasGeiping commited on
Commit
6e44bc9
·
verified ·
1 Parent(s): 6b33256

Upload RavenForCausalLM

Browse files
Files changed (3) hide show
  1. config.json +0 -3
  2. generation_config.json +0 -4
  3. raven_modeling_minimal.py +489 -36
config.json CHANGED
@@ -11,9 +11,7 @@
11
  "bias": false,
12
  "block_class_name": "SandwichBlock",
13
  "block_size": 4096,
14
- "bos_token_id": 65504,
15
  "effective_expected_depth": 132,
16
- "eos_token_id": 65505,
17
  "head_dim": 96,
18
  "init_orthogonal": false,
19
  "init_strategy": "takase",
@@ -39,7 +37,6 @@
39
  "norm_class_name": "RMSNorm_llama",
40
  "norm_eps": 1e-06,
41
  "num_key_value_heads": 55,
42
- "pad_token_id": 65509,
43
  "padded_vocab_size": 65536,
44
  "padding_multiple": 4096,
45
  "qk_bias": true,
 
11
  "bias": false,
12
  "block_class_name": "SandwichBlock",
13
  "block_size": 4096,
 
14
  "effective_expected_depth": 132,
 
15
  "head_dim": 96,
16
  "init_orthogonal": false,
17
  "init_strategy": "takase",
 
37
  "norm_class_name": "RMSNorm_llama",
38
  "norm_eps": 1e-06,
39
  "num_key_value_heads": 55,
 
40
  "padded_vocab_size": 65536,
41
  "padding_multiple": 4096,
42
  "qk_bias": true,
generation_config.json CHANGED
@@ -1,8 +1,4 @@
1
  {
2
  "_from_model_config": true,
3
- "bos_token_id": 65504,
4
- "eos_token_id": 65505,
5
- "pad_token_id": 65509,
6
- "use_cache": true,
7
  "transformers_version": "4.44.2"
8
  }
 
1
  {
2
  "_from_model_config": true,
 
 
 
 
3
  "transformers_version": "4.44.2"
4
  }
raven_modeling_minimal.py CHANGED
@@ -1,11 +1,11 @@
1
- """Minimal modeling.py file for HF compatibility and funny zero-shot experiments. Usability for finetuning not guaranteed"""
2
 
3
  import torch
4
  import math
5
 
6
  from torch import Tensor
7
  from dataclasses import dataclass
8
- from typing import Optional, Union
9
 
10
  from .raven_config_minimal import RavenConfig
11
  from transformers.cache_utils import Cache, DynamicCache
@@ -13,6 +13,10 @@ from transformers.cache_utils import Cache, DynamicCache
13
  ###################### Huggingface Glue code I ##################################################################
14
  from transformers import PreTrainedModel
15
  from transformers.utils import ModelOutput
 
 
 
 
16
 
17
 
18
  class RavenPreTrainedModel(PreTrainedModel):
@@ -39,7 +43,7 @@ class CausalLMOutputRecurrentLatents(ModelOutput):
39
  past_key_values: Optional[Cache] = None
40
  latent_states: Optional[torch.Tensor] = None
41
  hidden_states: Optional[torch.Tensor] = None
42
- attention_maps: Optional[tuple[torch.Tensor, ...]] = None
43
  stats: Optional[dict] = None
44
 
45
 
@@ -66,7 +70,7 @@ class RMSNorm(torch.nn.Module):
66
 
67
 
68
  class HuginnDynamicCache(DynamicCache):
69
- def __init__(self) -> None:
70
  super().__init__()
71
  self._seen_tokens = 0
72
  self.key_cache: dict[int, dict[int, torch.Tensor]] = {}
@@ -75,14 +79,24 @@ class HuginnDynamicCache(DynamicCache):
75
  # the cache is held uncoalesced because certain recurrent steps may be missing for some sequence ids if using
76
  # per-token adaptive compute. In those cases, the "lookup_strategy" determines how to proceed
77
  # Also, It is critical that the head indices do not overlap with the recurrent iteration indices
 
78
 
79
  def update(
80
  self,
81
  key_states: torch.Tensor,
82
  value_states: torch.Tensor,
83
  step_idx: int,
84
- lookup_strategy: str = "latest",
85
  ) -> tuple[torch.Tensor, torch.Tensor]:
 
 
 
 
 
 
 
 
 
86
  # Init
87
  if step_idx not in self.key_cache:
88
  self.key_cache[step_idx] = {}
@@ -92,31 +106,49 @@ class HuginnDynamicCache(DynamicCache):
92
  self._seen_tokens += key_states.shape[-2]
93
  # Add entries to cache
94
  for idx, entry in enumerate(key_states.unbind(dim=-2)):
95
- assert self._seen_tokens - key_states.shape[-2] + idx not in self.key_cache[step_idx]
 
 
96
  self.key_cache[step_idx][self._seen_tokens - key_states.shape[-2] + idx] = entry
97
  for idx, entry in enumerate(value_states.unbind(dim=-2)):
98
  self.value_cache[step_idx][self._seen_tokens - value_states.shape[-2] + idx] = entry
99
 
100
  # Materialize past state based on lookup strategy:
101
- if len(self.key_cache[step_idx]) == self._seen_tokens:
102
  # All entries are present, materialize cache as normal
103
  return (
104
  torch.stack(list(self.key_cache[step_idx].values()), dim=-2),
105
  torch.stack(list(self.value_cache[step_idx].values()), dim=-2),
106
  )
107
  else: # some entries where not previously computed
108
- if lookup_strategy == "latest":
 
 
 
 
 
 
 
 
 
 
 
109
  latest_keys = []
110
  latest_values = []
111
  for token_pos in range(self._seen_tokens):
112
- # Find the latest step that has this token position
113
- max_step = max((s for s in range(step_idx + 1) if token_pos in self.key_cache[s]), default=None)
 
 
 
 
 
114
  if max_step is None:
115
  raise ValueError(f"No cache entry found for token position {token_pos}")
116
  latest_keys.append(self.key_cache[max_step][token_pos])
117
  latest_values.append(self.value_cache[max_step][token_pos])
118
  return torch.stack(latest_keys, dim=-2), torch.stack(latest_values, dim=-2)
119
- elif lookup_strategy == "skip":
120
  existing_keys = []
121
  existing_values = []
122
  for token_pos in range(self._seen_tokens):
@@ -124,15 +156,22 @@ class HuginnDynamicCache(DynamicCache):
124
  existing_keys.append(self.key_cache[step_idx][token_pos])
125
  existing_values.append(self.value_cache[step_idx][token_pos])
126
  return torch.stack(existing_keys, dim=-2), torch.stack(existing_values, dim=-2)
127
- elif lookup_strategy == "randomized": # sanity check
128
  rand_keys = []
129
  rand_values = []
130
  for token_pos in range(self._seen_tokens):
131
- # Find steps that have this token position
132
- steps = [s for s in range(step_idx + 1) if token_pos in self.key_cache[s]]
133
- rand_step = steps[torch.randint(len(steps), (1,))]
134
- rand_keys.append(self.key_cache[rand_step][token_pos])
135
- rand_values.append(self.value_cache[rand_step][token_pos])
 
 
 
 
 
 
 
136
  return torch.stack(rand_keys, dim=-2), torch.stack(rand_values, dim=-2)
137
  else:
138
  raise ValueError(f"Unknown lookup strategy: {lookup_strategy}")
@@ -146,6 +185,18 @@ class HuginnDynamicCache(DynamicCache):
146
  def get_seq_length(self, step_idx: int = 0) -> int:
147
  return self._seen_tokens
148
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
  class CausalSelfAttention(torch.nn.Module):
151
  def __init__(self, config: RavenConfig) -> None:
@@ -169,7 +220,8 @@ class CausalSelfAttention(torch.nn.Module):
169
  step_idx: int,
170
  mask: Optional[Tensor] = None,
171
  past_key_values: Optional[Cache] = None,
172
- ) -> Tensor:
 
173
  B, S, E = x.shape # batch size, sequence length, embedding dimensionality (n_embd)
174
  q, k, v = self.Wqkv(x).split(self.chunks, dim=2)
175
  q = q.view(B, S, self.n_head, self.head_dim)
@@ -189,11 +241,28 @@ class CausalSelfAttention(torch.nn.Module):
189
  if past_key_values is not None:
190
  k, v = past_key_values.update(k, v, step_idx)
191
 
192
- y = torch.nn.functional.scaled_dot_product_attention(
193
- q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=q.shape[2] > 1
194
- )
 
 
 
195
  y = y.transpose(1, 2).reshape(B, S, E).contiguous() # reshape is a view if possible (it mostly is)
196
- return self.proj(y)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
 
199
  class GatedMLP(torch.nn.Module):
@@ -232,10 +301,12 @@ class SandwichBlock(torch.nn.Module):
232
  step_idx: int,
233
  mask: Optional[Tensor] = None,
234
  past_key_values: Optional[Cache] = None,
235
- ) -> Tensor:
236
- x = self.norm_2(self.attn(self.norm_1(x), freqs_cis, step_idx, mask, past_key_values) + x)
 
 
237
  x = self.norm_4(self.mlp(self.norm_3(x)) + x)
238
- return x
239
 
240
 
241
  class RavenForCausalLM(RavenPreTrainedModel):
@@ -318,13 +389,18 @@ class RavenForCausalLM(RavenPreTrainedModel):
318
 
319
  if use_cache and past_key_values is None:
320
  past_key_values = HuginnDynamicCache()
 
 
321
 
322
  # Non-recurrent prelude
323
  for block_idx, block in enumerate(self.transformer.prelude):
324
- input_embeds = block(input_embeds, freqs_cis, block_idx, attention_mask, past_key_values)
 
 
 
325
 
326
  # Main recurrence
327
- x, num_steps_no_grad, num_steps_with_grad, xk = self.iterate_forward(
328
  input_embeds, # type: ignore
329
  input_states,
330
  freqs_cis,
@@ -332,12 +408,14 @@ class RavenForCausalLM(RavenPreTrainedModel):
332
  attention_mask,
333
  past_key_values,
334
  num_steps,
 
335
  )
336
  latent_states = x.clone().detach()
337
 
338
  # Coda layers
339
  for block_idx, block in enumerate(self.transformer.coda, start=1):
340
- x = block(x, freqs_cis, -block_idx, attention_mask, past_key_values)
 
341
  x = self.transformer.ln_f(x)
342
 
343
  # Prediction head, assuming labels really are labels and not equal to input_ids
@@ -356,7 +434,7 @@ class RavenForCausalLM(RavenPreTrainedModel):
356
  past_key_values=past_key_values,
357
  hidden_states=x if output_details["return_head"] else None,
358
  latent_states=latent_states if output_details["return_latents"] else None,
359
- attention_maps=ValueError() if output_details["return_attention"] else None, # type: ignore
360
  stats=self.get_stats(logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad)
361
  if output_details["return_stats"]
362
  else None,
@@ -372,9 +450,9 @@ class RavenForCausalLM(RavenPreTrainedModel):
372
  mask,
373
  past_key_values: Optional[Cache] = None,
374
  num_steps: Optional[torch.Tensor] = None,
 
375
  ):
376
  x = xk = self.initialize_state(input_embeds) if input_states is None else input_states.clone()
377
-
378
  if num_steps is None:
379
  num_steps_no_grad, num_steps_with_grad = self.randomized_iteration_sampler() # type: ignore
380
  elif hasattr(num_steps, "__len__") and len(num_steps) > 1:
@@ -389,20 +467,123 @@ class RavenForCausalLM(RavenPreTrainedModel):
389
  # and all parameters are always used
390
  for step in range(num_steps_no_grad):
391
  xk = x
392
- x, block_idx = self.core_block_forward(xk, input_embeds, freqs_cis, mask, past_key_values, block_idx)
 
 
393
 
394
  for step in range(num_steps_with_grad):
395
  xk = x
396
- x, block_idx = self.core_block_forward(xk, input_embeds, freqs_cis, mask, past_key_values, block_idx)
397
- return self.transformer.ln_f(x), num_steps_no_grad, num_steps_with_grad, xk.detach()
 
 
398
 
399
  def core_block_forward(
400
- self, x, input_embeds, freqs_cis, mask, past_key_values, block_idx: Union[torch.Tensor, int]
 
 
 
 
 
 
 
401
  ):
402
  x = self.transformer.adapter(torch.cat([x, input_embeds], dim=-1))
403
  for idx, block in enumerate(self.transformer.core_block, start=1):
404
- x = block(x, freqs_cis, block_idx + idx, mask, past_key_values)
405
- return x, block_idx + idx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
 
407
  @torch._dynamo.disable(recursive=False) # type: ignore
408
  def randomized_iteration_sampler(self) -> tuple[torch.Tensor, torch.Tensor]:
@@ -462,6 +643,278 @@ class RavenForCausalLM(RavenPreTrainedModel):
462
  model_inputs[key] = value
463
  return model_inputs
464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  def get_stats(self, logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad):
466
  probs = torch.softmax(logits.float(), dim=-1)
467
  prob_entropy = torch.where(probs > 0, -probs * probs.log(), 0).sum(dim=-1)
 
1
+ """Minimal modeling.py file for HF compatibility and funny zero-shot experiments. Use only for inference."""
2
 
3
  import torch
4
  import math
5
 
6
  from torch import Tensor
7
  from dataclasses import dataclass
8
+ from typing import Optional, Union, Any
9
 
10
  from .raven_config_minimal import RavenConfig
11
  from transformers.cache_utils import Cache, DynamicCache
 
13
  ###################### Huggingface Glue code I ##################################################################
14
  from transformers import PreTrainedModel
15
  from transformers.utils import ModelOutput
16
+ from transformers.generation.utils import GenerateDecoderOnlyOutput
17
+
18
+ import torch.nn.functional as F
19
+ from transformers import GenerationConfig
20
 
21
 
22
  class RavenPreTrainedModel(PreTrainedModel):
 
43
  past_key_values: Optional[Cache] = None
44
  latent_states: Optional[torch.Tensor] = None
45
  hidden_states: Optional[torch.Tensor] = None
46
+ attention_maps: Optional[dict[int, torch.Tensor]] = None
47
  stats: Optional[dict] = None
48
 
49
 
 
70
 
71
 
72
  class HuginnDynamicCache(DynamicCache):
73
+ def __init__(self, lookup_strategy: str = "full") -> None:
74
  super().__init__()
75
  self._seen_tokens = 0
76
  self.key_cache: dict[int, dict[int, torch.Tensor]] = {}
 
79
  # the cache is held uncoalesced because certain recurrent steps may be missing for some sequence ids if using
80
  # per-token adaptive compute. In those cases, the "lookup_strategy" determines how to proceed
81
  # Also, It is critical that the head indices do not overlap with the recurrent iteration indices
82
+ self.lookup_strategy = lookup_strategy
83
 
84
  def update(
85
  self,
86
  key_states: torch.Tensor,
87
  value_states: torch.Tensor,
88
  step_idx: int,
89
+ lookup_strategy: Optional[str] = None,
90
  ) -> tuple[torch.Tensor, torch.Tensor]:
91
+ lookup_strategy = self.lookup_strategy if lookup_strategy is None else lookup_strategy
92
+ if "compress-" in self.lookup_strategy and step_idx > 1: # hardcode for current model!
93
+ compression_stage = int(self.lookup_strategy.split("compress-")[1][1:])
94
+ if "compress-s" in self.lookup_strategy:
95
+ new_step_idx = (step_idx - 2) % compression_stage + 2
96
+ else:
97
+ new_step_idx = (step_idx - 2) // compression_stage + 2
98
+ # @ print(step_idx, new_step_idx, compression_stage)
99
+ step_idx = new_step_idx
100
  # Init
101
  if step_idx not in self.key_cache:
102
  self.key_cache[step_idx] = {}
 
106
  self._seen_tokens += key_states.shape[-2]
107
  # Add entries to cache
108
  for idx, entry in enumerate(key_states.unbind(dim=-2)):
109
+ if "compress-" not in self.lookup_strategy:
110
+ assert step_idx < 0 or self._seen_tokens - key_states.shape[-2] + idx not in self.key_cache[step_idx]
111
+ # print(f"Overwrote cache entry for step_idx {step_idx}") # likely the head
112
  self.key_cache[step_idx][self._seen_tokens - key_states.shape[-2] + idx] = entry
113
  for idx, entry in enumerate(value_states.unbind(dim=-2)):
114
  self.value_cache[step_idx][self._seen_tokens - value_states.shape[-2] + idx] = entry
115
 
116
  # Materialize past state based on lookup strategy:
117
+ if len(self.key_cache[step_idx]) == self._seen_tokens or self.lookup_strategy == "full":
118
  # All entries are present, materialize cache as normal
119
  return (
120
  torch.stack(list(self.key_cache[step_idx].values()), dim=-2),
121
  torch.stack(list(self.value_cache[step_idx].values()), dim=-2),
122
  )
123
  else: # some entries where not previously computed
124
+ # if lookup_strategy.startswith("latest"):
125
+ # latest_keys = []
126
+ # latest_values = []
127
+ # for token_pos in range(self._seen_tokens):
128
+ # # Find the latest step that has this token position
129
+ # max_step = max((s for s in range(step_idx + 1) if token_pos in self.key_cache[s]), default=None)
130
+ # if max_step is None:
131
+ # raise ValueError(f"No cache entry found for token position {token_pos}")
132
+ # latest_keys.append(self.key_cache[max_step][token_pos])
133
+ # latest_values.append(self.value_cache[max_step][token_pos])
134
+ # return torch.stack(latest_keys, dim=-2), torch.stack(latest_values, dim=-2)
135
+ if lookup_strategy.startswith("latest-m4"):
136
  latest_keys = []
137
  latest_values = []
138
  for token_pos in range(self._seen_tokens):
139
+ # For steps >= 2, use modulo 4
140
+ if step_idx >= 2:
141
+ # Find valid steps for this token position
142
+ valid_steps = [s for s in range(step_idx + 1) if token_pos in self.key_cache[s]]
143
+ max_step = max([s for s in valid_steps if s >= 2 and s % 4 == step_idx % 4])
144
+ else:
145
+ max_step = step_idx if token_pos in self.key_cache[step_idx] else 0
146
  if max_step is None:
147
  raise ValueError(f"No cache entry found for token position {token_pos}")
148
  latest_keys.append(self.key_cache[max_step][token_pos])
149
  latest_values.append(self.value_cache[max_step][token_pos])
150
  return torch.stack(latest_keys, dim=-2), torch.stack(latest_values, dim=-2)
151
+ elif lookup_strategy.startswith("skip"):
152
  existing_keys = []
153
  existing_values = []
154
  for token_pos in range(self._seen_tokens):
 
156
  existing_keys.append(self.key_cache[step_idx][token_pos])
157
  existing_values.append(self.value_cache[step_idx][token_pos])
158
  return torch.stack(existing_keys, dim=-2), torch.stack(existing_values, dim=-2)
159
+ elif lookup_strategy.startswith("randomized"): # sanity check
160
  rand_keys = []
161
  rand_values = []
162
  for token_pos in range(self._seen_tokens):
163
+ if step_idx < 2: # For prelude steps
164
+ max_step = step_idx if token_pos in self.key_cache[step_idx] else 0
165
+ else: # Get all steps from same block position
166
+ curr_modulo = (step_idx - 2) % 4 + 2
167
+ valid_steps = [
168
+ s
169
+ for s in range(2, step_idx + 1)
170
+ if (s - 2) % 4 + 2 == curr_modulo and token_pos in self.key_cache[s]
171
+ ]
172
+ max_step = valid_steps[torch.randint(len(valid_steps), (1,))]
173
+ rand_keys.append(self.key_cache[max_step][token_pos])
174
+ rand_values.append(self.value_cache[max_step][token_pos])
175
  return torch.stack(rand_keys, dim=-2), torch.stack(rand_values, dim=-2)
176
  else:
177
  raise ValueError(f"Unknown lookup strategy: {lookup_strategy}")
 
185
  def get_seq_length(self, step_idx: int = 0) -> int:
186
  return self._seen_tokens
187
 
188
+ def get_memory_usage(self) -> float:
189
+ total_bytes = 0
190
+ # For each recurrent step/layer index
191
+ for step_idx in self.key_cache:
192
+ # Get the sequence cache for this step
193
+ key_seq_cache = self.key_cache[step_idx]
194
+ for seq_idx in key_seq_cache:
195
+ key_tensor = key_seq_cache[seq_idx]
196
+ # Add memory for of key tensors, assuming value is the same
197
+ total_bytes += key_tensor.nelement() * key_tensor.element_size()
198
+ return total_bytes * 2 / (1024 * 1024)
199
+
200
 
201
  class CausalSelfAttention(torch.nn.Module):
202
  def __init__(self, config: RavenConfig) -> None:
 
220
  step_idx: int,
221
  mask: Optional[Tensor] = None,
222
  past_key_values: Optional[Cache] = None,
223
+ return_attn: bool = False,
224
+ ) -> tuple[Tensor, Optional[Tensor]]:
225
  B, S, E = x.shape # batch size, sequence length, embedding dimensionality (n_embd)
226
  q, k, v = self.Wqkv(x).split(self.chunks, dim=2)
227
  q = q.view(B, S, self.n_head, self.head_dim)
 
241
  if past_key_values is not None:
242
  k, v = past_key_values.update(k, v, step_idx)
243
 
244
+ if return_attn:
245
+ y, attention_map = self.compute_eager_sdpa(q, k, v, attn_mask=mask)
246
+ else:
247
+ y = torch.nn.functional.scaled_dot_product_attention(
248
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=q.shape[2] > 1
249
+ )
250
  y = y.transpose(1, 2).reshape(B, S, E).contiguous() # reshape is a view if possible (it mostly is)
251
+ return self.proj(y), attention_map if return_attn else None
252
+
253
+ def compute_eager_sdpa(self, q, k, v, attn_mask):
254
+ scale = 1.0 / math.sqrt(self.head_dim)
255
+ scores = torch.matmul(q, k.transpose(-2, -1)) * scale
256
+
257
+ if attn_mask is not None:
258
+ scores = scores + attn_mask
259
+ if q.shape[2] > 1:
260
+ causal_mask = torch.triu(torch.ones(q.shape[2], q.shape[2]), diagonal=1).bool()
261
+ scores.masked_fill_(causal_mask.to(scores.device), float("-inf"))
262
+
263
+ attention_weights = torch.nn.functional.softmax(scores, dim=-1)
264
+ y = torch.matmul(attention_weights, v)
265
+ return y, attention_weights.max(dim=1)[0]
266
 
267
 
268
  class GatedMLP(torch.nn.Module):
 
301
  step_idx: int,
302
  mask: Optional[Tensor] = None,
303
  past_key_values: Optional[Cache] = None,
304
+ return_attn: bool = False,
305
+ ) -> tuple[Tensor, Optional[Tensor]]:
306
+ attn_out, attn_map = self.attn(self.norm_1(x), freqs_cis, step_idx, mask, past_key_values, return_attn)
307
+ x = self.norm_2(attn_out + x)
308
  x = self.norm_4(self.mlp(self.norm_3(x)) + x)
309
+ return x, attn_map
310
 
311
 
312
  class RavenForCausalLM(RavenPreTrainedModel):
 
389
 
390
  if use_cache and past_key_values is None:
391
  past_key_values = HuginnDynamicCache()
392
+ attn_maps = {}
393
+ return_attn = output_details["return_attention"]
394
 
395
  # Non-recurrent prelude
396
  for block_idx, block in enumerate(self.transformer.prelude):
397
+ input_embeds, attn_map = block(
398
+ input_embeds, freqs_cis, block_idx, attention_mask, past_key_values, return_attn
399
+ )
400
+ attn_maps[block_idx] = attn_map
401
 
402
  # Main recurrence
403
+ x, num_steps_no_grad, num_steps_with_grad, xk, block_idx, attn_maps = self.iterate_forward(
404
  input_embeds, # type: ignore
405
  input_states,
406
  freqs_cis,
 
408
  attention_mask,
409
  past_key_values,
410
  num_steps,
411
+ attn_maps,
412
  )
413
  latent_states = x.clone().detach()
414
 
415
  # Coda layers
416
  for block_idx, block in enumerate(self.transformer.coda, start=1):
417
+ x, attn_map = block(x, freqs_cis, -block_idx, attention_mask, past_key_values, return_attn)
418
+ attn_maps[-block_idx] = attn_map
419
  x = self.transformer.ln_f(x)
420
 
421
  # Prediction head, assuming labels really are labels and not equal to input_ids
 
434
  past_key_values=past_key_values,
435
  hidden_states=x if output_details["return_head"] else None,
436
  latent_states=latent_states if output_details["return_latents"] else None,
437
+ attention_maps=attn_maps if output_details["return_attention"] else None, # type: ignore
438
  stats=self.get_stats(logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad)
439
  if output_details["return_stats"]
440
  else None,
 
450
  mask,
451
  past_key_values: Optional[Cache] = None,
452
  num_steps: Optional[torch.Tensor] = None,
453
+ attn_maps: dict = {},
454
  ):
455
  x = xk = self.initialize_state(input_embeds) if input_states is None else input_states.clone()
 
456
  if num_steps is None:
457
  num_steps_no_grad, num_steps_with_grad = self.randomized_iteration_sampler() # type: ignore
458
  elif hasattr(num_steps, "__len__") and len(num_steps) > 1:
 
467
  # and all parameters are always used
468
  for step in range(num_steps_no_grad):
469
  xk = x
470
+ x, block_idx, attn_maps = self.core_block_forward(
471
+ xk, input_embeds, freqs_cis, mask, past_key_values, block_idx, attn_maps
472
+ )
473
 
474
  for step in range(num_steps_with_grad):
475
  xk = x
476
+ x, block_idx, attn_maps = self.core_block_forward(
477
+ xk, input_embeds, freqs_cis, mask, past_key_values, block_idx, attn_maps
478
+ )
479
+ return self.transformer.ln_f(x), num_steps_no_grad, num_steps_with_grad, xk.detach(), block_idx, attn_maps
480
 
481
  def core_block_forward(
482
+ self,
483
+ x,
484
+ input_embeds,
485
+ freqs_cis,
486
+ mask,
487
+ past_key_values,
488
+ block_idx: Union[torch.Tensor, int],
489
+ attn_maps: dict = {},
490
  ):
491
  x = self.transformer.adapter(torch.cat([x, input_embeds], dim=-1))
492
  for idx, block in enumerate(self.transformer.core_block, start=1):
493
+ x, attn_map = block(x, freqs_cis, block_idx + idx, mask, past_key_values, return_attn=len(attn_maps) > 0)
494
+ attn_maps[block_idx + idx] = attn_map
495
+ return x, block_idx + idx, attn_maps
496
+
497
+ @torch.no_grad()
498
+ def iterate_one_step(
499
+ self,
500
+ input_embeds,
501
+ input_states,
502
+ position_ids: Optional[torch.Tensor] = None,
503
+ cache_position: Optional[torch.Tensor] = None,
504
+ block_idx: Union[torch.Tensor, int] = 0,
505
+ attention_mask: Optional[Tensor] = None,
506
+ past_key_values: Optional[Cache] = None,
507
+ attn_maps: dict = {},
508
+ ):
509
+ if position_ids is None and cache_position is None:
510
+ freqs_cis = self.freqs_cis[:, : input_embeds.shape[1]]
511
+ elif position_ids is not None:
512
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
513
+ elif cache_position is not None:
514
+ freqs_cis = self.freqs_cis[:, cache_position]
515
+ x, block_idx, attn_maps = self.core_block_forward(
516
+ input_states, input_embeds, freqs_cis, attention_mask, past_key_values, block_idx, attn_maps
517
+ )
518
+ return x, block_idx, attn_maps
519
+
520
+ def predict_from_latents(
521
+ self,
522
+ latents,
523
+ attention_mask: Optional[torch.Tensor] = None,
524
+ position_ids: Optional[torch.Tensor] = None,
525
+ cache_position: Optional[torch.Tensor] = None,
526
+ past_key_values: Optional[Cache] = None,
527
+ return_attn: bool = False,
528
+ attn_maps: dict = {},
529
+ ):
530
+ if position_ids is None and cache_position is None:
531
+ freqs_cis = self.freqs_cis[:, : latents.shape[1]]
532
+ elif position_ids is not None:
533
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
534
+ elif cache_position is not None:
535
+ freqs_cis = self.freqs_cis[:, cache_position]
536
+ x = self.transformer.ln_f(latents)
537
+ # Coda layers
538
+ for block_idx, block in enumerate(self.transformer.coda, start=1):
539
+ x, attn_map = block(x, freqs_cis, -block_idx, attention_mask, past_key_values)
540
+ attn_maps[block_idx] = attn_map
541
+ x = self.transformer.ln_f(x)
542
+
543
+ logits = self.lm_head(x).float()
544
+
545
+ return CausalLMOutputRecurrentLatents(
546
+ loss=torch.as_tensor(0.0),
547
+ log_ppl=torch.as_tensor(0.0),
548
+ logits=logits,
549
+ past_key_values=past_key_values,
550
+ attention_maps=attn_maps if len(attn_maps) > 0 else None,
551
+ )
552
+
553
+ def embed_inputs(
554
+ self,
555
+ input_ids: torch.Tensor,
556
+ attention_mask: Optional[torch.Tensor] = None,
557
+ position_ids: Optional[torch.Tensor] = None,
558
+ past_key_values: Optional[Cache] = None,
559
+ use_cache: bool = False,
560
+ cache_position: Optional[torch.Tensor] = None,
561
+ return_attn: bool = False,
562
+ **kwargs,
563
+ ) -> tuple[torch.Tensor, int, dict[int, Tensor]]:
564
+ # Support multiple position formats:
565
+ if position_ids is None and cache_position is None:
566
+ freqs_cis = self.freqs_cis[:, : input_ids.shape[1]]
567
+ elif position_ids is not None:
568
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
569
+ elif cache_position is not None:
570
+ freqs_cis = self.freqs_cis[:, cache_position]
571
+
572
+ input_embeds = self.transformer.wte(input_ids)
573
+
574
+ if self.emb_scale != 1:
575
+ input_embeds = input_embeds * self.emb_scale # type: ignore
576
+
577
+ if use_cache and past_key_values is None:
578
+ past_key_values = HuginnDynamicCache()
579
+
580
+ # Non-recurrent prelude
581
+ attn_maps = {}
582
+ for block_idx, block in enumerate(self.transformer.prelude):
583
+ input_embeds, attn_maps = block(
584
+ input_embeds, freqs_cis, block_idx, attention_mask, past_key_values, return_attn
585
+ )
586
+ return input_embeds, block_idx, attn_maps
587
 
588
  @torch._dynamo.disable(recursive=False) # type: ignore
589
  def randomized_iteration_sampler(self) -> tuple[torch.Tensor, torch.Tensor]:
 
643
  model_inputs[key] = value
644
  return model_inputs
645
 
646
+ @torch.no_grad()
647
+ def generate_minimal(
648
+ self,
649
+ input_ids: torch.LongTensor,
650
+ generation_config: Optional[GenerationConfig] = None, # type: ignore
651
+ tokenizer=None,
652
+ streamer=None,
653
+ continuous_compute=False, # warm-start state / continuous CoT
654
+ cache_kwargs: dict = {},
655
+ **model_kwargs,
656
+ ) -> Union[torch.Tensor, dict[str, Any]]:
657
+ """Minimal single-sequence generation. Template for more complicated generate tasks"""
658
+ # Setup
659
+ if generation_config is None:
660
+ generation_config: GenerationConfig = self.generation_config # type: ignore
661
+ model_kwargs["past_key_values"] = HuginnDynamicCache(**cache_kwargs)
662
+ model_kwargs["use_cache"] = True
663
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
664
+ stop_tokens = self._get_stops(generation_config, tokenizer).to(input_ids.device)
665
+ if continuous_compute:
666
+ embedded_inputs, _, _ = self.embed_inputs(input_ids)
667
+ model_kwargs["input_states"] = self.initialize_state(embedded_inputs)
668
+ # Generate tokens
669
+ for _ in range(generation_config.max_length - input_ids.shape[1]):
670
+ # Forward pass
671
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
672
+ outputs = self(**model_inputs)
673
+ next_token_logits = outputs.logits[0, -1, :]
674
+ if continuous_compute:
675
+ current_last_latent = outputs.latent_states[:, -1:, :]
676
+
677
+ # Sample or select next token
678
+ if generation_config.do_sample:
679
+ if generation_config.temperature:
680
+ next_token_logits = next_token_logits / generation_config.temperature
681
+
682
+ probs = F.softmax(next_token_logits, dim=-1)
683
+
684
+ # Apply top_k
685
+ if generation_config.top_k:
686
+ top_k_probs, _ = torch.topk(probs, generation_config.top_k)
687
+ probs[probs < top_k_probs[-1]] = 0
688
+ # Apply top_p
689
+ if generation_config.top_p:
690
+ sorted_probs = torch.sort(probs, descending=True)[0]
691
+ cumsum = torch.cumsum(sorted_probs, dim=-1)
692
+ probs[cumsum > generation_config.top_p] = 0
693
+ # Apply min_p
694
+ if generation_config.min_p:
695
+ probs[probs < generation_config.min_p * probs.max()] = 0
696
+
697
+ probs = probs / probs.sum()
698
+ next_token = torch.multinomial(probs, num_samples=1)
699
+ else:
700
+ next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
701
+
702
+ input_ids = torch.cat([input_ids, next_token[None, :]], dim=-1) # type: ignore
703
+
704
+ if streamer:
705
+ streamer.put(next_token.cpu())
706
+
707
+ # Update model kwargs
708
+ model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
709
+ if continuous_compute:
710
+ model_kwargs["input_states"] = current_last_latent
711
+
712
+ # Check if we hit a stop token
713
+ if stop_tokens is not None and next_token in stop_tokens:
714
+ break
715
+
716
+ if streamer:
717
+ streamer.end()
718
+
719
+ if generation_config.return_dict_in_generate:
720
+ return GenerateDecoderOnlyOutput(
721
+ sequences=input_ids,
722
+ scores=None,
723
+ logits=None,
724
+ attentions=None,
725
+ hidden_states=None,
726
+ past_key_values=model_kwargs.get("past_key_values"),
727
+ )
728
+ return input_ids
729
+
730
+ @torch.no_grad()
731
+ def generate_with_adaptive_compute(
732
+ self,
733
+ input_ids: torch.LongTensor,
734
+ generation_config: Optional[GenerationConfig] = None, # type: ignore
735
+ tokenizer=None,
736
+ streamer=None,
737
+ continuous_compute=False, # warm-start state / continuous CoT
738
+ latent_dampening=False,
739
+ criterion="entropy-diff",
740
+ exit_threshold: Union[str, float, int] = "auto",
741
+ cache_kwargs: dict = {},
742
+ **model_kwargs,
743
+ ) -> Union[torch.Tensor, GenerateDecoderOnlyOutput]:
744
+ """Minimal single-sequence generation. Template for more complicated generate tasks"""
745
+ # Setup
746
+ if generation_config is None:
747
+ generation_config: GenerationConfig = self.generation_config # type: ignore
748
+ model_kwargs["past_key_values"] = HuginnDynamicCache(**cache_kwargs)
749
+ model_kwargs["use_cache"] = True
750
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
751
+ stop_tokens = self._get_stops(generation_config, tokenizer).to(input_ids.device)
752
+ if continuous_compute:
753
+ embedded_inputs, _, _ = self.embed_inputs(input_ids)
754
+ current_last_latent = self.initialize_state(embedded_inputs)
755
+ compute_steps = []
756
+
757
+ # Generate tokens
758
+ for step in range(generation_config.max_length - input_ids.shape[1]):
759
+ # Adaptive compute forward
760
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
761
+ aux_inputs = {
762
+ k: model_inputs[k] for k in ["cache_position", "past_key_values", "attention_mask"] if k in model_inputs
763
+ }
764
+ embedded_inputs, block_idx, _ = self.embed_inputs(model_inputs["input_ids"], **aux_inputs)
765
+ if not continuous_compute:
766
+ current_latents = self.initialize_state(embedded_inputs, deterministic=False)
767
+ else:
768
+ current_latents = current_last_latent
769
+
770
+ # Prep criterions:
771
+ if criterion == "entropy-diff":
772
+ entropy = torch.tensor(100.0, device=input_ids.device)
773
+ exit_threshold = 1e-3 if exit_threshold == "auto" else float(exit_threshold)
774
+ elif criterion in ["latent-diff", "none"]:
775
+ exit_threshold = 0.03 if exit_threshold == "auto" else float(exit_threshold)
776
+ elif "kl" in criterion:
777
+ V = self.config.padded_vocab_size
778
+ log_probs = (1 / V * torch.ones(V, device=input_ids.device)).log()
779
+ if criterion == "minp-kl":
780
+ exit_threshold = 1e-6 if exit_threshold == "auto" else float(exit_threshold)
781
+ else:
782
+ exit_threshold = 5e-4 if exit_threshold == "auto" else float(exit_threshold)
783
+ elif criterion == "argmax-stability":
784
+ stable_for_n_steps = 0
785
+ current_argmax = torch.tensor(-1, dtype=torch.long, device=input_ids.device)
786
+ exit_threshold = 5 if exit_threshold == "auto" else int(exit_threshold)
787
+ else:
788
+ raise ValueError("Invalid adaptive compute strategy.")
789
+
790
+ all_latents = []
791
+ exit_values = []
792
+ for compute_step in range(model_inputs["num_steps"]):
793
+ prev_latents = current_latents.clone()
794
+ current_latents, block_idx, _ = self.iterate_one_step(
795
+ embedded_inputs, current_latents, block_idx=block_idx, **aux_inputs
796
+ )
797
+ all_latents.append(current_latents if latent_dampening else None)
798
+ if step > 0: # do not exit in prefill:
799
+ if criterion == "entropy-diff":
800
+ prev_entropy = entropy.clone()
801
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
802
+ probs = F.softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
803
+ entropy = -torch.sum(probs * torch.log(probs + 1e-10), dim=-1).mean()
804
+ entropy_diff = (entropy - prev_entropy).abs()
805
+ exit_values.append(entropy_diff.item())
806
+ if entropy_diff < exit_threshold:
807
+ break
808
+ elif criterion == "latent-diff":
809
+ norm_diff = (prev_latents - current_latents).norm() / current_latents.norm()
810
+ exit_values.append(norm_diff.item())
811
+ if norm_diff < exit_threshold:
812
+ break
813
+ elif criterion == "kl":
814
+ prev_log_probs = log_probs.clone()
815
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
816
+ log_probs = F.log_softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
817
+ kl = F.kl_div(log_probs, prev_log_probs, reduction="none", log_target=True).sum(dim=-1)
818
+ exit_values.append(kl.item())
819
+ if kl < exit_threshold:
820
+ break
821
+ elif criterion == "minp-kl":
822
+ prev_log_probs = log_probs.clone()
823
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
824
+ probs = F.softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
825
+ probs[probs < 0.1 * probs.max()] = 1 / V
826
+ probs = probs / probs.sum()
827
+ log_probs = probs.log()
828
+ kl = F.kl_div(log_probs, prev_log_probs, reduction="none", log_target=True).sum(dim=-1)
829
+ exit_values.append(kl.item())
830
+ if kl < exit_threshold:
831
+ break
832
+ elif criterion == "argmax-stability":
833
+ prev_argmax = current_argmax.clone()
834
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
835
+ current_argmax = outputs.logits[0, -1, :].argmax(dim=-1) # type: ignore
836
+ if current_argmax == prev_argmax:
837
+ stable_for_n_steps += 1
838
+ else:
839
+ stable_for_n_steps = 0
840
+ exit_values.append(stable_for_n_steps)
841
+ if stable_for_n_steps >= exit_threshold:
842
+ break
843
+ elif criterion == "none":
844
+ pass
845
+
846
+ else:
847
+ if not latent_dampening:
848
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
849
+ else:
850
+ dampened_latents = torch.sum(torch.cat(all_latents, dim=0), dim=0, keepdim=True)
851
+ outputs = self.predict_from_latents(dampened_latents, **aux_inputs)
852
+ compute_steps.append([compute_step + 1, exit_values])
853
+
854
+ next_token_logits = outputs.logits[0, -1, :] # type: ignore
855
+ if continuous_compute: # Save last latent
856
+ current_last_latent = current_latents[:, -1:, :]
857
+
858
+ # Sample or select next token
859
+ if generation_config.do_sample:
860
+ if generation_config.temperature:
861
+ next_token_logits = next_token_logits / generation_config.temperature
862
+
863
+ probs = F.softmax(next_token_logits, dim=-1)
864
+ # Apply top_k
865
+ if generation_config.top_k:
866
+ top_k_probs, _ = torch.topk(probs, generation_config.top_k)
867
+ probs[probs < top_k_probs[-1]] = 0
868
+ # Apply top_p
869
+ if generation_config.top_p:
870
+ sorted_probs = torch.sort(probs, descending=True)[0]
871
+ cumsum = torch.cumsum(sorted_probs, dim=-1)
872
+ probs[cumsum > generation_config.top_p] = 0
873
+ # Apply min_p
874
+ if generation_config.min_p:
875
+ probs[probs < generation_config.min_p * probs.max()] = 0
876
+
877
+ probs = probs / probs.sum()
878
+ next_token = torch.multinomial(probs, num_samples=1)
879
+ else:
880
+ next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
881
+
882
+ input_ids = torch.cat([input_ids, next_token[None, :]], dim=-1) # type: ignore
883
+
884
+ if streamer:
885
+ streamer.put(next_token.cpu())
886
+
887
+ # Update model kwargs
888
+ model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
889
+
890
+ # Check if we hit a stop token
891
+ if stop_tokens is not None and next_token in stop_tokens:
892
+ break
893
+
894
+ if streamer:
895
+ streamer.end()
896
+
897
+ if generation_config.return_dict_in_generate:
898
+ return GenerateDecoderOnlyOutput(
899
+ sequences=input_ids,
900
+ scores=compute_steps, # type: ignore
901
+ logits=None,
902
+ attentions=None,
903
+ hidden_states=None,
904
+ past_key_values=model_kwargs.get("past_key_values"),
905
+ )
906
+ return input_ids
907
+
908
+ def _get_stops(self, generation_config, tokenizer):
909
+ stop_tokens = set()
910
+ if generation_config.eos_token_id is not None:
911
+ stop_tokens.add(generation_config.eos_token_id)
912
+ if hasattr(generation_config, "stop_strings") and tokenizer and generation_config.stop_strings:
913
+ for s in generation_config.stop_strings:
914
+ token_id = tokenizer(s, add_special_tokens=False)["input_ids"][0]
915
+ stop_tokens.add(token_id)
916
+ return torch.tensor(list(stop_tokens))
917
+
918
  def get_stats(self, logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad):
919
  probs = torch.softmax(logits.float(), dim=-1)
920
  prob_entropy = torch.where(probs > 0, -probs * probs.log(), 0).sum(dim=-1)