scpalmetto commited on
Commit
8134578
·
verified ·
1 Parent(s): 7cdf2ff

Upload modeling_ouro.py.bak with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_ouro.py.bak +843 -0
modeling_ouro.py.bak ADDED
@@ -0,0 +1,843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Any, Callable, Optional, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ from transformers.activations import ACT2FN
8
+ from transformers.cache_utils import Cache
9
+ from transformers.generation import GenerationMixin
10
+ from transformers.integrations import use_kernel_forward_from_hub
11
+ from transformers.masking_utils import (
12
+ create_causal_mask,
13
+ create_sliding_window_causal_mask,
14
+ )
15
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
16
+ from transformers.modeling_layers import (
17
+ GenericForQuestionAnswering,
18
+ GenericForSequenceClassification,
19
+ GenericForTokenClassification,
20
+ GradientCheckpointingLayer,
21
+ )
22
+ from transformers.modeling_outputs import (
23
+ BaseModelOutputWithPast,
24
+ CausalLMOutputWithPast,
25
+ )
26
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
27
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
28
+ from transformers.processing_utils import Unpack
29
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
30
+ from transformers.utils.generic import check_model_inputs
31
+ from .configuration_ouro import OuroConfig
32
+
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ def needs_universal_cache(
38
+ cache: Optional[Cache], max_cache_size: Optional[int]
39
+ ) -> bool:
40
+ if cache is None:
41
+ return True
42
+ if isinstance(cache, UniversalTransformerCache):
43
+ return False
44
+ if not isinstance(cache, Cache):
45
+ return False
46
+ can_grow = getattr(cache, "layer_class_to_replicate", None) is not None
47
+ if can_grow:
48
+ # Dynamic caches can extend to any index, so let them be
49
+ return False
50
+ cache_layers = getattr(cache, "layers", [])
51
+ if max_cache_size is not None and len(cache_layers) < max_cache_size:
52
+ try:
53
+ cached_tokens = cache.get_seq_length()
54
+ except Exception:
55
+ cached_tokens = 0
56
+ if cached_tokens > 0:
57
+ raise ValueError(
58
+ "The provided cache cannot store all Universal Transformer iterations. Please "
59
+ "instantiate Ouro.modeling_ouro.UniversalTransformerCache and pass it as past_key_values."
60
+ )
61
+ return True
62
+ return False
63
+
64
+
65
+ class OuroMLP(nn.Module):
66
+ def __init__(self, config):
67
+ super().__init__()
68
+ self.config = config
69
+ self.hidden_size = config.hidden_size
70
+ self.intermediate_size = config.intermediate_size
71
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
72
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
73
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
74
+ self.act_fn = ACT2FN[config.hidden_act]
75
+
76
+ def forward(self, x):
77
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
78
+ return down_proj
79
+
80
+
81
+ def rotate_half(x):
82
+ """Rotates half the hidden dims of the input."""
83
+ x1 = x[..., : x.shape[-1] // 2]
84
+ x2 = x[..., x.shape[-1] // 2 :]
85
+ return torch.cat((-x2, x1), dim=-1)
86
+
87
+
88
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
89
+ """Applies Rotary Position Embedding to the query and key tensors.
90
+
91
+ Args:
92
+ q (`torch.Tensor`): The query tensor.
93
+ k (`torch.Tensor`): The key tensor.
94
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
95
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
96
+ position_ids (`torch.Tensor`, *optional*):
97
+ Deprecated and unused.
98
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
99
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
100
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
101
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
102
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
103
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
104
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
105
+ Returns:
106
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
107
+ """
108
+ cos = cos.unsqueeze(unsqueeze_dim)
109
+ sin = sin.unsqueeze(unsqueeze_dim)
110
+ q_embed = (q * cos) + (rotate_half(q) * sin)
111
+ k_embed = (k * cos) + (rotate_half(k) * sin)
112
+ return q_embed, k_embed
113
+
114
+
115
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
116
+ """
117
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
118
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
119
+ """
120
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
121
+ if n_rep == 1:
122
+ return hidden_states
123
+ hidden_states = hidden_states[:, :, None, :, :].expand(
124
+ batch, num_key_value_heads, n_rep, slen, head_dim
125
+ )
126
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
127
+
128
+
129
+ class UniversalTransformerCache(Cache):
130
+ """Cache implementation that supports Ouro's multi-step Universal Transformer loops."""
131
+
132
+ def __init__(self, max_cache_size: Optional[int] = None):
133
+ # We intentionally don't call super().__init__ because the parent assumes static cache sizes.
134
+ self.key_cache: list[Optional[torch.Tensor]] = []
135
+ self.value_cache: list[Optional[torch.Tensor]] = []
136
+ self.layers: list[Any] = [] # attribute expected by HF Cache utilities
137
+ self._seen_tokens = 0
138
+ self.max_cache_size = max_cache_size
139
+
140
+ def update(
141
+ self,
142
+ key_states: torch.Tensor,
143
+ value_states: torch.Tensor,
144
+ layer_idx: int,
145
+ cache_kwargs: Optional[dict] = None,
146
+ ) -> tuple[torch.Tensor, torch.Tensor]:
147
+ if layer_idx < 0:
148
+ raise ValueError(f"layer_idx must be non-negative, got {layer_idx}")
149
+
150
+ if self.max_cache_size is not None and layer_idx >= self.max_cache_size:
151
+ raise IndexError(
152
+ f"Cache index {layer_idx} exceeds configured max_cache_size={self.max_cache_size}. "
153
+ "Check total_ut_steps and num_hidden_layers."
154
+ )
155
+
156
+ # Expand cache storage so the requested index is available.
157
+ while len(self.key_cache) <= layer_idx:
158
+ self.key_cache.append(None)
159
+ self.value_cache.append(None)
160
+
161
+ cached_key = self.key_cache[layer_idx]
162
+ cached_value = self.value_cache[layer_idx]
163
+
164
+ if cached_key is None:
165
+ self.key_cache[layer_idx] = key_states
166
+ self.value_cache[layer_idx] = value_states
167
+ else:
168
+ if (
169
+ key_states.shape[0] != cached_key.shape[0]
170
+ or key_states.shape[1] != cached_key.shape[1]
171
+ or key_states.shape[3] != cached_key.shape[3]
172
+ ):
173
+ raise ValueError(
174
+ "Cached and incoming key/value tensors must match on batch, head, and head_dim dimensions."
175
+ )
176
+ assert cached_value is not None
177
+ self.key_cache[layer_idx] = torch.cat([cached_key, key_states], dim=2)
178
+ self.value_cache[layer_idx] = torch.cat([cached_value, value_states], dim=2)
179
+
180
+ result_key = self.key_cache[layer_idx]
181
+ result_value = self.value_cache[layer_idx]
182
+ assert result_key is not None and result_value is not None
183
+
184
+ # Track sequence length using the first populated cache entry.
185
+ self._seen_tokens = result_key.shape[2]
186
+ return result_key, result_value
187
+
188
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
189
+ if layer_idx is None:
190
+ layer_idx = 0
191
+ if layer_idx < 0 or len(self.key_cache) <= layer_idx:
192
+ return 0
193
+ cached = self.key_cache[layer_idx]
194
+ if cached is None:
195
+ return 0
196
+ return cached.shape[2]
197
+
198
+ def get_max_length(self) -> Optional[int]:
199
+ return None
200
+
201
+ def get_usable_length(
202
+ self, new_seq_length: int, layer_idx: Optional[int] = 0
203
+ ) -> int:
204
+ return self.get_seq_length(layer_idx)
205
+
206
+ def reorder_cache(self, beam_idx: torch.LongTensor) -> None:
207
+ for idx, (key_entry, value_entry) in enumerate(
208
+ zip(self.key_cache, self.value_cache)
209
+ ):
210
+ if key_entry is None:
211
+ continue
212
+ assert value_entry is not None
213
+ device = key_entry.device
214
+ self.key_cache[idx] = key_entry.index_select(0, beam_idx.to(device))
215
+ self.value_cache[idx] = value_entry.index_select(0, beam_idx.to(device))
216
+
217
+ @property
218
+ def is_compileable(self) -> bool:
219
+ return False
220
+
221
+ def clear(self) -> None:
222
+ logger.debug("Clearing UniversalTransformerCache")
223
+ self.key_cache = []
224
+ self.value_cache = []
225
+ self._seen_tokens = 0
226
+
227
+
228
+ def eager_attention_forward(
229
+ module: nn.Module,
230
+ query: torch.Tensor,
231
+ key: torch.Tensor,
232
+ value: torch.Tensor,
233
+ attention_mask: Optional[torch.Tensor],
234
+ scaling: float,
235
+ dropout: float = 0.0,
236
+ **kwargs: Unpack[TransformersKwargs],
237
+ ):
238
+ key_states = repeat_kv(key, module.num_key_value_groups)
239
+ value_states = repeat_kv(value, module.num_key_value_groups)
240
+
241
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
242
+ if attention_mask is not None:
243
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
244
+ attn_weights = attn_weights + causal_mask
245
+
246
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
247
+ query.dtype
248
+ )
249
+ attn_weights = nn.functional.dropout(
250
+ attn_weights, p=dropout, training=module.training
251
+ )
252
+ attn_output = torch.matmul(attn_weights, value_states)
253
+ attn_output = attn_output.transpose(1, 2).contiguous()
254
+
255
+ return attn_output, attn_weights
256
+
257
+
258
+ class OuroAttention(nn.Module):
259
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
260
+
261
+ def __init__(self, config: OuroConfig, layer_idx: int):
262
+ super().__init__()
263
+ self.config = config
264
+ self.layer_idx = layer_idx
265
+ self.head_dim = getattr(
266
+ config, "head_dim", config.hidden_size // config.num_attention_heads
267
+ )
268
+ self.num_key_value_groups = (
269
+ config.num_attention_heads // config.num_key_value_heads
270
+ )
271
+ self.scaling = self.head_dim**-0.5
272
+ self.attention_dropout = config.attention_dropout
273
+ self.is_causal = True
274
+ self.q_proj = nn.Linear(
275
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=False
276
+ )
277
+ self.k_proj = nn.Linear(
278
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
279
+ )
280
+ self.v_proj = nn.Linear(
281
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
282
+ )
283
+ self.o_proj = nn.Linear(
284
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=False
285
+ )
286
+ self.sliding_window = (
287
+ config.sliding_window
288
+ if config.layer_types[layer_idx] == "sliding_attention"
289
+ else None
290
+ )
291
+
292
+ def forward(
293
+ self,
294
+ hidden_states: torch.Tensor,
295
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
296
+ attention_mask: Optional[torch.Tensor],
297
+ past_key_value: Optional[Cache] = None,
298
+ cache_position: Optional[torch.LongTensor] = None,
299
+ current_ut: int = 0,
300
+ **kwargs: Unpack[FlashAttentionKwargs],
301
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
302
+ input_shape = hidden_states.shape[:-1]
303
+ hidden_shape = (*input_shape, -1, self.head_dim)
304
+
305
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
306
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
307
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
308
+
309
+ cos, sin = position_embeddings
310
+ query_states, key_states = apply_rotary_pos_emb(
311
+ query_states, key_states, cos, sin
312
+ )
313
+
314
+ if past_key_value is not None:
315
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
316
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
317
+ key_states, value_states = past_key_value.update(
318
+ key_states,
319
+ value_states,
320
+ current_ut * self.config.num_hidden_layers + self.layer_idx,
321
+ cache_kwargs,
322
+ )
323
+
324
+ attention_interface: Callable = eager_attention_forward
325
+ if self.config._attn_implementation != "eager":
326
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
327
+ self.config._attn_implementation
328
+ ]
329
+
330
+ attn_output, attn_weights = attention_interface(
331
+ self,
332
+ query_states,
333
+ key_states,
334
+ value_states,
335
+ attention_mask,
336
+ dropout=0.0 if not self.training else self.attention_dropout,
337
+ scaling=self.scaling,
338
+ sliding_window=self.sliding_window, # main diff with Llama
339
+ **kwargs,
340
+ )
341
+
342
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
343
+ attn_output = self.o_proj(attn_output)
344
+ return attn_output, attn_weights
345
+
346
+
347
+ @use_kernel_forward_from_hub("RMSNorm")
348
+ class OuroRMSNorm(nn.Module):
349
+ def __init__(self, hidden_size, eps=1e-6):
350
+ """
351
+ OuroRMSNorm is equivalent to T5LayerNorm
352
+ """
353
+ super().__init__()
354
+ self.weight = nn.Parameter(torch.ones(hidden_size))
355
+ self.variance_epsilon = eps
356
+
357
+ def forward(self, hidden_states):
358
+ input_dtype = hidden_states.dtype
359
+ hidden_states = hidden_states.to(torch.float32)
360
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
361
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
362
+ return self.weight * hidden_states.to(input_dtype)
363
+
364
+ def extra_repr(self):
365
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
366
+
367
+
368
+ class OuroDecoderLayer(GradientCheckpointingLayer):
369
+ def __init__(self, config: OuroConfig, layer_idx: int):
370
+ super().__init__()
371
+ self.hidden_size = config.hidden_size
372
+
373
+ self.self_attn = OuroAttention(config=config, layer_idx=layer_idx)
374
+
375
+ self.mlp = OuroMLP(config)
376
+ self.input_layernorm = OuroRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
377
+ self.input_layernorm_2 = OuroRMSNorm(
378
+ config.hidden_size, eps=config.rms_norm_eps
379
+ )
380
+ self.post_attention_layernorm = OuroRMSNorm(
381
+ config.hidden_size, eps=config.rms_norm_eps
382
+ )
383
+ self.post_attention_layernorm_2 = OuroRMSNorm(
384
+ config.hidden_size, eps=config.rms_norm_eps
385
+ )
386
+ self.attention_type = config.layer_types[layer_idx]
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: Optional[torch.Tensor] = None,
392
+ position_ids: Optional[torch.LongTensor] = None,
393
+ past_key_value: Optional[Cache] = None,
394
+ use_cache: Optional[bool] = False,
395
+ cache_position: Optional[torch.LongTensor] = None,
396
+ position_embeddings: Optional[
397
+ tuple[torch.Tensor, torch.Tensor]
398
+ ] = None, # necessary, but kept here for BC
399
+ **kwargs: Unpack[TransformersKwargs],
400
+ ) -> tuple[torch.Tensor]:
401
+ residual = hidden_states
402
+ hidden_states = self.input_layernorm(hidden_states)
403
+ # Self Attention
404
+ hidden_states, _ = self.self_attn(
405
+ hidden_states=hidden_states,
406
+ attention_mask=attention_mask,
407
+ position_ids=position_ids,
408
+ past_key_value=past_key_value,
409
+ use_cache=use_cache,
410
+ cache_position=cache_position,
411
+ position_embeddings=position_embeddings,
412
+ **kwargs,
413
+ )
414
+ hidden_states = self.input_layernorm_2(hidden_states)
415
+ hidden_states = residual + hidden_states
416
+
417
+ # Fully Connected
418
+ residual = hidden_states
419
+ hidden_states = self.post_attention_layernorm(hidden_states)
420
+ hidden_states = self.mlp(hidden_states)
421
+ hidden_states = self.post_attention_layernorm_2(hidden_states)
422
+ hidden_states = residual + hidden_states
423
+ return hidden_states
424
+
425
+
426
+ @auto_docstring
427
+ class OuroPreTrainedModel(PreTrainedModel):
428
+ config: OuroConfig
429
+ base_model_prefix = "model"
430
+ supports_gradient_checkpointing = True
431
+ _no_split_modules = ["OuroDecoderLayer"]
432
+ _skip_keys_device_placement = ["past_key_values"]
433
+ _supports_flash_attn = True
434
+ _supports_sdpa = True
435
+ _supports_flex_attn = True
436
+
437
+ _can_compile_fullgraph = True
438
+ _supports_attention_backend = True
439
+ _can_record_outputs = {
440
+ "hidden_states": OuroDecoderLayer,
441
+ "attentions": OuroAttention,
442
+ }
443
+
444
+
445
+ class OuroRotaryEmbedding(nn.Module):
446
+ def __init__(self, config: OuroConfig, device=None):
447
+ super().__init__()
448
+ # BC: "rope_type" was originally "type"
449
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
450
+ self.rope_type = config.rope_scaling.get(
451
+ "rope_type", config.rope_scaling.get("type")
452
+ )
453
+ else:
454
+ self.rope_type = "default"
455
+ self.max_seq_len_cached = config.max_position_embeddings
456
+ self.original_max_seq_len = config.max_position_embeddings
457
+
458
+ self.config = config
459
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
460
+
461
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
462
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
463
+ self.original_inv_freq = self.inv_freq
464
+
465
+ @torch.no_grad()
466
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
467
+ def forward(self, x, position_ids):
468
+ inv_freq_expanded = (
469
+ self.inv_freq[None, :, None]
470
+ .float()
471
+ .expand(position_ids.shape[0], -1, 1)
472
+ .to(x.device)
473
+ )
474
+ position_ids_expanded = position_ids[:, None, :].float()
475
+
476
+ device_type = (
477
+ x.device.type
478
+ if isinstance(x.device.type, str) and x.device.type != "mps"
479
+ else "cpu"
480
+ )
481
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
482
+ freqs = (
483
+ inv_freq_expanded.float() @ position_ids_expanded.float()
484
+ ).transpose(1, 2)
485
+ emb = torch.cat((freqs, freqs), dim=-1)
486
+ cos = emb.cos() * self.attention_scaling
487
+ sin = emb.sin() * self.attention_scaling
488
+
489
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
490
+
491
+
492
+ @auto_docstring
493
+ class OuroModel(OuroPreTrainedModel):
494
+ def __init__(self, config: OuroConfig):
495
+ super().__init__(config)
496
+ self.padding_idx = config.pad_token_id
497
+ self.vocab_size = config.vocab_size
498
+
499
+ self.embed_tokens = nn.Embedding(
500
+ config.vocab_size, config.hidden_size, self.padding_idx
501
+ )
502
+ self.layers = nn.ModuleList(
503
+ [
504
+ OuroDecoderLayer(config, layer_idx)
505
+ for layer_idx in range(config.num_hidden_layers)
506
+ ]
507
+ )
508
+ self.norm = OuroRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
509
+ self.rotary_emb = OuroRotaryEmbedding(config=config)
510
+ self.gradient_checkpointing = False
511
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
512
+ self.total_ut_steps = getattr(self.config, "total_ut_steps", 4)
513
+ self.early_exit_gate = nn.Linear(config.hidden_size, 1)
514
+ # Initialize weights and apply final processing
515
+ self.post_init()
516
+
517
+ @check_model_inputs
518
+ @auto_docstring
519
+ def forward(
520
+ self,
521
+ input_ids: Optional[torch.LongTensor] = None,
522
+ attention_mask: Optional[torch.Tensor] = None,
523
+ position_ids: Optional[torch.LongTensor] = None,
524
+ past_key_values: Optional[Cache] = None,
525
+ inputs_embeds: Optional[torch.FloatTensor] = None,
526
+ use_cache: Optional[bool] = None,
527
+ cache_position: Optional[torch.LongTensor] = None,
528
+ **kwargs: Unpack[TransformersKwargs],
529
+ ) -> BaseModelOutputWithPast:
530
+ if (input_ids is None) ^ (inputs_embeds is not None):
531
+ raise ValueError(
532
+ "You must specify exactly one of input_ids or inputs_embeds"
533
+ )
534
+
535
+ if inputs_embeds is None:
536
+ inputs_embeds = self.embed_tokens(input_ids)
537
+
538
+ if use_cache is None:
539
+ use_cache = self.config.use_cache
540
+
541
+ max_cache_size: Optional[int] = None
542
+ if use_cache:
543
+ total_ut_steps = getattr(self.config, "total_ut_steps", 1) or 1
544
+ total_layers = getattr(self.config, "num_hidden_layers", None)
545
+ if total_layers is not None:
546
+ max_cache_size = total_layers * total_ut_steps
547
+
548
+ if needs_universal_cache(past_key_values, max_cache_size):
549
+ past_key_values = UniversalTransformerCache(max_cache_size)
550
+
551
+ if cache_position is None:
552
+ past_seen_tokens = (
553
+ past_key_values.get_seq_length() if past_key_values is not None else 0
554
+ )
555
+ cache_position = torch.arange(
556
+ past_seen_tokens,
557
+ past_seen_tokens + inputs_embeds.shape[1],
558
+ device=inputs_embeds.device,
559
+ )
560
+
561
+ if position_ids is None:
562
+ position_ids = cache_position.unsqueeze(0)
563
+
564
+ # It may already have been prepared by e.g. `generate`
565
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
566
+ # Prepare mask arguments
567
+ mask_kwargs = {
568
+ "config": self.config,
569
+ "input_embeds": inputs_embeds,
570
+ "attention_mask": attention_mask,
571
+ "cache_position": cache_position,
572
+ "past_key_values": past_key_values,
573
+ "position_ids": position_ids,
574
+ }
575
+ # Create the masks
576
+ causal_mask_mapping = {
577
+ "full_attention": create_causal_mask(**mask_kwargs),
578
+ }
579
+ # The sliding window alternating layers are not always activated depending on the config
580
+ if self.has_sliding_layers:
581
+ causal_mask_mapping["sliding_attention"] = (
582
+ create_sliding_window_causal_mask(**mask_kwargs)
583
+ )
584
+
585
+ hidden_states = inputs_embeds
586
+
587
+ # create position embeddings to be shared across the decoder layers
588
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
589
+ hidden_states_list = []
590
+ gate_list = []
591
+
592
+ for current_ut in range(self.total_ut_steps):
593
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
594
+ hidden_states = decoder_layer(
595
+ hidden_states,
596
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
597
+ position_ids=position_ids,
598
+ past_key_value=past_key_values,
599
+ use_cache=use_cache,
600
+ cache_position=cache_position,
601
+ position_embeddings=position_embeddings,
602
+ current_ut=current_ut,
603
+ **kwargs,
604
+ )
605
+
606
+ hidden_states = self.norm(hidden_states)
607
+ hidden_states_list.append(hidden_states)
608
+ gate_list.append(self.early_exit_gate(hidden_states))
609
+
610
+ return (
611
+ BaseModelOutputWithPast(
612
+ last_hidden_state=hidden_states,
613
+ past_key_values=past_key_values if use_cache else None,
614
+ ),
615
+ hidden_states_list,
616
+ gate_list,
617
+ )
618
+
619
+
620
+ @auto_docstring
621
+ class OuroForCausalLM(OuroPreTrainedModel, GenerationMixin):
622
+ _tied_weights_keys = ["lm_head.weight"]
623
+ _tp_plan = {"lm_head": "colwise_rep"}
624
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
625
+
626
+ def __init__(self, config):
627
+ super().__init__(config)
628
+ self.model = OuroModel(config)
629
+ self.vocab_size = config.vocab_size
630
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
631
+
632
+ # 分块大小配置
633
+ self.chunk_size = getattr(config, "chunk_size", 2) # 默认分块大小为2
634
+ self.early_exit_step = getattr(config, "early_exit_step", None)
635
+ self.early_exit_threshold = getattr(config, "early_exit_threshold", None)
636
+
637
+ # Initialize weights and apply final processing
638
+ self.post_init()
639
+
640
+ def set_decoder(self, decoder):
641
+ self.model = decoder
642
+
643
+ def get_decoder(self):
644
+ return self.model
645
+
646
+ @can_return_tuple
647
+ @auto_docstring
648
+ def forward(
649
+ self,
650
+ input_ids: Optional[torch.LongTensor] = None,
651
+ attention_mask: Optional[torch.Tensor] = None,
652
+ position_ids: Optional[torch.LongTensor] = None,
653
+ past_key_values: Optional[Cache] = None,
654
+ inputs_embeds: Optional[torch.FloatTensor] = None,
655
+ labels: Optional[torch.LongTensor] = None,
656
+ use_cache: Optional[bool] = None,
657
+ cache_position: Optional[torch.LongTensor] = None,
658
+ logits_to_keep: Union[int, torch.Tensor] = 0,
659
+ use_weighted_exit: Optional[bool] = False, # 控制是否使用加权 early exit
660
+ exit_at_step: Optional[int] = None,
661
+ exit_threshold: Optional[float] = None,
662
+ **kwargs: Unpack[TransformersKwargs],
663
+ ) -> CausalLMOutputWithPast:
664
+ r"""
665
+ Args:
666
+ use_weighted_exit (`bool`, *optional*, defaults to `False`):
667
+ Whether to use weighted early exit. If `True`, the logits from all UT steps will be
668
+ averaged according to the exit probability distribution.
669
+ exit_at_step (`int`, *optional*):
670
+ Specifies which UT step to exit at. If set, the model will directly use the hidden states
671
+ from this step to generate logits, ignoring other exit strategies.
672
+ exit_threshold (`float`, *optional*):
673
+ The cumulative probability threshold for early exit. When the cumulative exit probability
674
+ reaches this threshold, the model will exit at that step.
675
+
676
+ Example:
677
+
678
+ ```python
679
+ >>> from transformers import AutoTokenizer, OuroForCausalLM
680
+
681
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
682
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
683
+
684
+ >>> # Generate
685
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
686
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
687
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
688
+ ```"""
689
+ exit_at_step = (
690
+ exit_at_step if exit_at_step is not None else self.early_exit_step
691
+ )
692
+ exit_threshold = (
693
+ exit_threshold if exit_threshold is not None else self.early_exit_threshold
694
+ )
695
+
696
+ outputs, hidden_states_list, gate_list = self.model(
697
+ input_ids=input_ids,
698
+ attention_mask=attention_mask,
699
+ position_ids=position_ids,
700
+ past_key_values=past_key_values,
701
+ inputs_embeds=inputs_embeds,
702
+ use_cache=use_cache,
703
+ cache_position=cache_position,
704
+ **kwargs,
705
+ )
706
+ slice_indices = (
707
+ slice(-logits_to_keep, None)
708
+ if isinstance(logits_to_keep, int)
709
+ else logits_to_keep
710
+ )
711
+
712
+ def _select_token_positions(tensor: torch.Tensor) -> torch.Tensor:
713
+ if isinstance(slice_indices, slice):
714
+ return tensor[:, slice_indices, ...]
715
+ if isinstance(slice_indices, torch.Tensor):
716
+ return tensor.index_select(1, slice_indices.to(tensor.device))
717
+ raise TypeError(
718
+ f"Unsupported index type for logits_to_keep: {type(slice_indices)}"
719
+ )
720
+
721
+ stacked_exit_pdf = None
722
+ if gate_list:
723
+ pdf_list = []
724
+ remaining_prob = torch.ones_like(gate_list[0].squeeze(-1))
725
+ for idx, gate_tensor in enumerate(gate_list):
726
+ lambda_i = torch.sigmoid(gate_tensor.squeeze(-1))
727
+ if idx < len(gate_list) - 1:
728
+ p_i = lambda_i * remaining_prob
729
+ remaining_prob = remaining_prob * (1.0 - lambda_i)
730
+ else:
731
+ p_i = remaining_prob
732
+ pdf_list.append(p_i)
733
+ stacked_exit_pdf = torch.stack(pdf_list, dim=2)
734
+
735
+ expected_logits_cache: Optional[torch.Tensor] = None
736
+
737
+ def compute_expected_logits() -> Optional[torch.Tensor]:
738
+ nonlocal expected_logits_cache
739
+ if expected_logits_cache is not None:
740
+ return expected_logits_cache
741
+ if stacked_exit_pdf is None or not hidden_states_list:
742
+ return None
743
+ token_exit_pdf = _select_token_positions(stacked_exit_pdf)
744
+ expected_logits = None
745
+ for step_idx, hidden in enumerate(hidden_states_list):
746
+ step_hidden = _select_token_positions(hidden)
747
+ step_logits = self.lm_head(step_hidden)
748
+ weight = (
749
+ token_exit_pdf[..., step_idx].unsqueeze(-1).to(step_logits.dtype)
750
+ )
751
+ expected_logits = (
752
+ step_logits * weight
753
+ if expected_logits is None
754
+ else expected_logits + step_logits * weight
755
+ )
756
+ expected_logits_cache = expected_logits
757
+ return expected_logits_cache
758
+
759
+ logits: Optional[torch.Tensor] = None
760
+ loss: Optional[torch.Tensor] = None
761
+
762
+ if labels is not None:
763
+ logits = compute_expected_logits()
764
+ if logits is None:
765
+ hidden_states = outputs.last_hidden_state
766
+ logits = self.lm_head(_select_token_positions(hidden_states))
767
+ loss = self.loss_function(
768
+ logits=logits,
769
+ labels=labels,
770
+ vocab_size=self.config.vocab_size,
771
+ **kwargs,
772
+ )
773
+ else:
774
+ if stacked_exit_pdf is not None and hidden_states_list:
775
+ if exit_at_step is not None and 0 <= exit_at_step < len(
776
+ hidden_states_list
777
+ ):
778
+ selected_hidden = hidden_states_list[exit_at_step]
779
+ logits = self.lm_head(_select_token_positions(selected_hidden))
780
+ elif exit_threshold is not None:
781
+ cumulative_probs = torch.cumsum(stacked_exit_pdf, dim=2)
782
+ threshold_value = exit_threshold
783
+ if isinstance(threshold_value, torch.Tensor):
784
+ threshold_value = threshold_value.to(cumulative_probs.device)
785
+ threshold_mask = cumulative_probs >= threshold_value
786
+ exit_steps = torch.argmax(threshold_mask.float(), dim=2)
787
+ last_step_idx = stacked_exit_pdf.shape[2] - 1
788
+ if last_step_idx >= 0:
789
+ never_exceeded = ~threshold_mask.any(dim=2)
790
+ exit_steps[never_exceeded] = last_step_idx
791
+ stacked_hidden = torch.stack(hidden_states_list, dim=2)
792
+ gather_index = (
793
+ exit_steps.unsqueeze(-1)
794
+ .unsqueeze(-1)
795
+ .expand(-1, -1, 1, stacked_hidden.size(-1))
796
+ )
797
+ final_hidden_states = torch.gather(
798
+ stacked_hidden, 2, gather_index
799
+ ).squeeze(2)
800
+ logits = self.lm_head(_select_token_positions(final_hidden_states))
801
+ elif use_weighted_exit:
802
+ logits = compute_expected_logits()
803
+
804
+ if logits is None:
805
+ hidden_states = outputs.last_hidden_state
806
+ logits = self.lm_head(_select_token_positions(hidden_states))
807
+
808
+ result = CausalLMOutputWithPast(
809
+ loss=loss,
810
+ logits=logits,
811
+ past_key_values=outputs.past_key_values,
812
+ hidden_states=outputs.hidden_states,
813
+ attentions=outputs.attentions,
814
+ )
815
+
816
+ return result
817
+
818
+
819
+ class OuroForSequenceClassification(
820
+ GenericForSequenceClassification, OuroPreTrainedModel
821
+ ):
822
+ pass
823
+
824
+
825
+ class OuroForTokenClassification(GenericForTokenClassification, OuroPreTrainedModel):
826
+ pass
827
+
828
+
829
+ class OuroForQuestionAnswering(GenericForQuestionAnswering, OuroPreTrainedModel):
830
+ base_model_prefix = (
831
+ "transformer" # For BC, where `transformer` was used instead of `model`
832
+ )
833
+
834
+
835
+ __all__ = [
836
+ "OuroPreTrainedModel",
837
+ "OuroModel",
838
+ "OuroForCausalLM",
839
+ "OuroForSequenceClassification",
840
+ "OuroForTokenClassification",
841
+ "OuroForQuestionAnswering",
842
+ "UniversalTransformerCache",
843
+ ]