gyung commited on
Commit
f915521
·
verified ·
1 Parent(s): 3d90852

Upload Ouro-2.6B-Thinking Terminal SFT (2 epoch)

Browse files
chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {%- if messages[0]['role'] == 'system' -%}{{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}{%- else -%}{{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{%- endif -%}{%- for message in messages -%}{%- if message.role == 'system' and loop.first -%}{# Skip #}{%- else -%}{{- '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n' }}{%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%}{{- '<|im_start|>assistant\n' }}{%- if enable_thinking is defined and enable_thinking is true -%}{{- '<think>\n' }}{%- endif -%}{%- endif -%}
config.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "OuroForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_ouro.OuroConfig",
8
+ "AutoModel": "modeling_ouro.OuroModel",
9
+ "AutoModelForCausalLM": "modeling_ouro.OuroForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "dtype": "bfloat16",
13
+ "early_exit_threshold": 1.0,
14
+ "eos_token_id": 2,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 5632,
20
+ "layer_types": [
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention",
44
+ "full_attention",
45
+ "full_attention",
46
+ "full_attention",
47
+ "full_attention",
48
+ "full_attention",
49
+ "full_attention",
50
+ "full_attention",
51
+ "full_attention",
52
+ "full_attention",
53
+ "full_attention",
54
+ "full_attention",
55
+ "full_attention",
56
+ "full_attention",
57
+ "full_attention",
58
+ "full_attention",
59
+ "full_attention",
60
+ "full_attention",
61
+ "full_attention",
62
+ "full_attention",
63
+ "full_attention",
64
+ "full_attention",
65
+ "full_attention",
66
+ "full_attention",
67
+ "full_attention",
68
+ "full_attention"
69
+ ],
70
+ "max_position_embeddings": 65536,
71
+ "max_window_layers": 48,
72
+ "model_type": "ouro",
73
+ "num_attention_heads": 16,
74
+ "num_hidden_layers": 48,
75
+ "num_key_value_heads": 16,
76
+ "pad_token_id": 2,
77
+ "rms_norm_eps": 1e-06,
78
+ "rope_parameters": {
79
+ "factor": 1.0,
80
+ "rope_theta": 1000000.0,
81
+ "rope_type": "linear"
82
+ },
83
+ "rope_theta": 1000000.0,
84
+ "sliding_window": null,
85
+ "tie_word_embeddings": false,
86
+ "total_ut_steps": 4,
87
+ "transformers_version": "5.5.4",
88
+ "use_cache": false,
89
+ "use_sliding_window": false,
90
+ "vocab_size": 49152
91
+ }
configuration_ouro.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Ouro model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class OuroConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`OuroModel`]. It is used to instantiate a
28
+ Ouro model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ Ouro-7B-beta [Qwen/Ouro-7B-beta](https://huggingface.co/Qwen/Ouro-7B-beta).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the Ouro model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`OuroModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details, check out [this
54
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
58
+ The maximum sequence length that this model might ever be used with.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether the model's input and output word embeddings should be tied.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'llama3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`list[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`list[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
108
+ Whether to use sliding window attention.
109
+ sliding_window (`int`, *optional*, defaults to 4096):
110
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
111
+ max_window_layers (`int`, *optional*, defaults to 28):
112
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
113
+ additional layer afterwards will use SWA (Sliding Window Attention).
114
+ layer_types (`list`, *optional*):
115
+ Attention pattern for each layer.
116
+ attention_dropout (`float`, *optional*, defaults to 0.0):
117
+ The dropout ratio for the attention probabilities.
118
+
119
+ ```python
120
+ >>> from transformers import OuroModel, OuroConfig
121
+
122
+ >>> # Initializing a Ouro style configuration
123
+ >>> configuration = OuroConfig()
124
+
125
+ >>> # Initializing a model from the Ouro-7B style configuration
126
+ >>> model = OuroModel(configuration)
127
+
128
+ >>> # Accessing the model configuration
129
+ >>> configuration = model.config
130
+ ```"""
131
+
132
+ model_type = "ouro"
133
+ keys_to_ignore_at_inference = ["past_key_values"]
134
+
135
+ # Default tensor parallel plan for base model `Ouro`
136
+ base_model_tp_plan = {
137
+ "layers.*.self_attn.q_proj": "colwise",
138
+ "layers.*.self_attn.k_proj": "colwise",
139
+ "layers.*.self_attn.v_proj": "colwise",
140
+ "layers.*.self_attn.o_proj": "rowwise",
141
+ "layers.*.mlp.gate_proj": "colwise",
142
+ "layers.*.mlp.up_proj": "colwise",
143
+ "layers.*.mlp.down_proj": "rowwise",
144
+ }
145
+ base_model_pp_plan = {
146
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
147
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
148
+ "norm": (["hidden_states"], ["hidden_states"]),
149
+ }
150
+
151
+ def __init__(
152
+ self,
153
+ vocab_size=151936,
154
+ hidden_size=4096,
155
+ intermediate_size=22016,
156
+ num_hidden_layers=32,
157
+ num_attention_heads=32,
158
+ num_key_value_heads=32,
159
+ hidden_act="silu",
160
+ max_position_embeddings=32768,
161
+ initializer_range=0.02,
162
+ rms_norm_eps=1e-6,
163
+ use_cache=True,
164
+ tie_word_embeddings=False,
165
+ rope_theta=10000.0,
166
+ rope_scaling=None,
167
+ use_sliding_window=False,
168
+ sliding_window=4096,
169
+ max_window_layers=28,
170
+ layer_types=None,
171
+ attention_dropout=0.0,
172
+ total_ut_steps=4,
173
+ early_exit_threshold=1.0,
174
+ **kwargs,
175
+ ):
176
+ self.pad_token_id = 2 # eom_token_id
177
+ self.vocab_size = vocab_size
178
+ self.max_position_embeddings = max_position_embeddings
179
+ self.hidden_size = hidden_size
180
+ self.intermediate_size = intermediate_size
181
+ self.num_hidden_layers = num_hidden_layers
182
+ self.num_attention_heads = num_attention_heads
183
+ self.use_sliding_window = use_sliding_window
184
+ self.sliding_window = sliding_window if self.use_sliding_window else None
185
+ self.max_window_layers = max_window_layers
186
+
187
+ # for backward compatibility
188
+ if num_key_value_heads is None:
189
+ num_key_value_heads = num_attention_heads
190
+
191
+ self.num_key_value_heads = num_key_value_heads
192
+ self.hidden_act = hidden_act
193
+ self.initializer_range = initializer_range
194
+ self.rms_norm_eps = rms_norm_eps
195
+ self.use_cache = use_cache
196
+ self.rope_theta = rope_theta
197
+ self.rope_scaling = rope_scaling
198
+ self.attention_dropout = attention_dropout
199
+ self.total_ut_steps = total_ut_steps
200
+ self.early_exit_threshold = early_exit_threshold
201
+ # Validate the correctness of rotary position embeddings parameters
202
+ # BC: if there is a 'type' field, move it to 'rope_type'.
203
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
204
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
205
+ rope_config_validation(self)
206
+
207
+ self.layer_types = layer_types
208
+ if self.layer_types is None:
209
+ self.layer_types = [
210
+ "sliding_attention"
211
+ if self.sliding_window is not None and i >= self.max_window_layers
212
+ else "full_attention"
213
+ for i in range(self.num_hidden_layers)
214
+ ]
215
+ layer_type_validation(self.layer_types)
216
+
217
+ super().__init__(
218
+ tie_word_embeddings=tie_word_embeddings,
219
+ **kwargs,
220
+ )
221
+
222
+
223
+ __all__ = ["OuroConfig"]
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 2
6
+ ],
7
+ "pad_token_id": 2,
8
+ "transformers_version": "5.5.4",
9
+ "use_cache": true
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1454303707d8bb473102cb1a17050e103ee9e39219b3d6da0289832f68e28131
3
+ size 5336011274
modeling_ouro.py ADDED
@@ -0,0 +1,891 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_mask_sizes(
199
+ self, cache_position: torch.Tensor, layer_idx: int = 0
200
+ ) -> tuple[int, int]:
201
+ """Return (kv_length, kv_offset) for attention mask creation.
202
+
203
+ The inherited ``Cache.get_mask_sizes`` falls back to
204
+ ``(cache_position.shape[0], 0)`` when ``layer_idx >= len(self.layers)``.
205
+ Because ``UniversalTransformerCache`` manages its own flat
206
+ ``key_cache`` / ``value_cache`` lists and keeps ``self.layers`` empty,
207
+ the fallback always fires. During the prefill step this happens to be
208
+ correct (``cache_position`` spans the full input), but during
209
+ autoregressive decoding ``cache_position`` has length 1, so the mask is
210
+ built for ``kv_length=1`` instead of ``cached_length + 1``. As a
211
+ result the 4D attention mask is too small and padding information is
212
+ lost, corrupting batched generation for every sequence except the
213
+ longest (unpadded) one.
214
+ """
215
+ query_length = cache_position.shape[0] if hasattr(cache_position, 'shape') else cache_position
216
+ seq_length = self.get_seq_length(layer_idx)
217
+ kv_length = seq_length + query_length
218
+ return kv_length, 0
219
+
220
+ def get_max_length(self) -> Optional[int]:
221
+ return None
222
+
223
+ def get_usable_length(
224
+ self, new_seq_length: int, layer_idx: Optional[int] = 0
225
+ ) -> int:
226
+ return self.get_seq_length(layer_idx)
227
+
228
+ def reorder_cache(self, beam_idx: torch.LongTensor) -> None:
229
+ for idx, (key_entry, value_entry) in enumerate(
230
+ zip(self.key_cache, self.value_cache)
231
+ ):
232
+ if key_entry is None:
233
+ continue
234
+ assert value_entry is not None
235
+ device = key_entry.device
236
+ self.key_cache[idx] = key_entry.index_select(0, beam_idx.to(device))
237
+ self.value_cache[idx] = value_entry.index_select(0, beam_idx.to(device))
238
+
239
+ @property
240
+ def is_compileable(self) -> bool:
241
+ return False
242
+
243
+ def clear(self) -> None:
244
+ logger.debug("Clearing UniversalTransformerCache")
245
+ self.key_cache = []
246
+ self.value_cache = []
247
+ self._seen_tokens = 0
248
+
249
+
250
+ def eager_attention_forward(
251
+ module: nn.Module,
252
+ query: torch.Tensor,
253
+ key: torch.Tensor,
254
+ value: torch.Tensor,
255
+ attention_mask: Optional[torch.Tensor],
256
+ scaling: float,
257
+ dropout: float = 0.0,
258
+ **kwargs: Unpack[TransformersKwargs],
259
+ ):
260
+ key_states = repeat_kv(key, module.num_key_value_groups)
261
+ value_states = repeat_kv(value, module.num_key_value_groups)
262
+
263
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
264
+ if attention_mask is not None:
265
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
266
+ attn_weights = attn_weights + causal_mask
267
+
268
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
269
+ query.dtype
270
+ )
271
+ attn_weights = nn.functional.dropout(
272
+ attn_weights, p=dropout, training=module.training
273
+ )
274
+ attn_output = torch.matmul(attn_weights, value_states)
275
+ attn_output = attn_output.transpose(1, 2).contiguous()
276
+
277
+ return attn_output, attn_weights
278
+
279
+
280
+ class OuroAttention(nn.Module):
281
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
282
+
283
+ def __init__(self, config: OuroConfig, layer_idx: int):
284
+ super().__init__()
285
+ self.config = config
286
+ self.layer_idx = layer_idx
287
+ self.head_dim = getattr(
288
+ config, "head_dim", config.hidden_size // config.num_attention_heads
289
+ )
290
+ self.num_key_value_groups = (
291
+ config.num_attention_heads // config.num_key_value_heads
292
+ )
293
+ self.scaling = self.head_dim**-0.5
294
+ self.attention_dropout = config.attention_dropout
295
+ self.is_causal = True
296
+ self.q_proj = nn.Linear(
297
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=False
298
+ )
299
+ self.k_proj = nn.Linear(
300
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
301
+ )
302
+ self.v_proj = nn.Linear(
303
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
304
+ )
305
+ self.o_proj = nn.Linear(
306
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=False
307
+ )
308
+ self.sliding_window = (
309
+ config.sliding_window
310
+ if config.layer_types[layer_idx] == "sliding_attention"
311
+ else None
312
+ )
313
+
314
+ def forward(
315
+ self,
316
+ hidden_states: torch.Tensor,
317
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
318
+ attention_mask: Optional[torch.Tensor],
319
+ past_key_value: Optional[Cache] = None,
320
+ cache_position: Optional[torch.LongTensor] = None,
321
+ current_ut: int = 0,
322
+ **kwargs: Unpack[FlashAttentionKwargs],
323
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
324
+ input_shape = hidden_states.shape[:-1]
325
+ hidden_shape = (*input_shape, -1, self.head_dim)
326
+
327
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
328
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
329
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
330
+
331
+ cos, sin = position_embeddings
332
+ query_states, key_states = apply_rotary_pos_emb(
333
+ query_states, key_states, cos, sin
334
+ )
335
+
336
+ if past_key_value is not None:
337
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
338
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
339
+ key_states, value_states = past_key_value.update(
340
+ key_states,
341
+ value_states,
342
+ current_ut * self.config.num_hidden_layers + self.layer_idx,
343
+ cache_kwargs,
344
+ )
345
+
346
+ attention_interface: Callable = eager_attention_forward
347
+ if self.config._attn_implementation != "eager":
348
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
349
+ self.config._attn_implementation
350
+ ]
351
+
352
+ attn_output, attn_weights = attention_interface(
353
+ self,
354
+ query_states,
355
+ key_states,
356
+ value_states,
357
+ attention_mask,
358
+ dropout=0.0 if not self.training else self.attention_dropout,
359
+ scaling=self.scaling,
360
+ sliding_window=self.sliding_window, # main diff with Llama
361
+ **kwargs,
362
+ )
363
+
364
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
365
+ attn_output = self.o_proj(attn_output)
366
+ return attn_output, attn_weights
367
+
368
+
369
+ @use_kernel_forward_from_hub("RMSNorm")
370
+ class OuroRMSNorm(nn.Module):
371
+ def __init__(self, hidden_size, eps=1e-6):
372
+ """
373
+ OuroRMSNorm is equivalent to T5LayerNorm
374
+ """
375
+ super().__init__()
376
+ self.weight = nn.Parameter(torch.ones(hidden_size))
377
+ self.variance_epsilon = eps
378
+
379
+ def forward(self, hidden_states):
380
+ input_dtype = hidden_states.dtype
381
+ hidden_states = hidden_states.to(torch.float32)
382
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
383
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
384
+ return self.weight * hidden_states.to(input_dtype)
385
+
386
+ def extra_repr(self):
387
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
388
+
389
+
390
+ class OuroDecoderLayer(GradientCheckpointingLayer):
391
+ def __init__(self, config: OuroConfig, layer_idx: int):
392
+ super().__init__()
393
+ self.hidden_size = config.hidden_size
394
+
395
+ self.self_attn = OuroAttention(config=config, layer_idx=layer_idx)
396
+
397
+ self.mlp = OuroMLP(config)
398
+ self.input_layernorm = OuroRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
399
+ self.input_layernorm_2 = OuroRMSNorm(
400
+ config.hidden_size, eps=config.rms_norm_eps
401
+ )
402
+ self.post_attention_layernorm = OuroRMSNorm(
403
+ config.hidden_size, eps=config.rms_norm_eps
404
+ )
405
+ self.post_attention_layernorm_2 = OuroRMSNorm(
406
+ config.hidden_size, eps=config.rms_norm_eps
407
+ )
408
+ self.attention_type = config.layer_types[layer_idx]
409
+
410
+ def forward(
411
+ self,
412
+ hidden_states: torch.Tensor,
413
+ attention_mask: Optional[torch.Tensor] = None,
414
+ position_ids: Optional[torch.LongTensor] = None,
415
+ past_key_value: Optional[Cache] = None,
416
+ use_cache: Optional[bool] = False,
417
+ cache_position: Optional[torch.LongTensor] = None,
418
+ position_embeddings: Optional[
419
+ tuple[torch.Tensor, torch.Tensor]
420
+ ] = None, # necessary, but kept here for BC
421
+ **kwargs: Unpack[TransformersKwargs],
422
+ ) -> tuple[torch.Tensor]:
423
+ residual = hidden_states
424
+ hidden_states = self.input_layernorm(hidden_states)
425
+ # Self Attention
426
+ hidden_states, _ = self.self_attn(
427
+ hidden_states=hidden_states,
428
+ attention_mask=attention_mask,
429
+ position_ids=position_ids,
430
+ past_key_value=past_key_value,
431
+ use_cache=use_cache,
432
+ cache_position=cache_position,
433
+ position_embeddings=position_embeddings,
434
+ **kwargs,
435
+ )
436
+ hidden_states = self.input_layernorm_2(hidden_states)
437
+ hidden_states = residual + hidden_states
438
+
439
+ # Fully Connected
440
+ residual = hidden_states
441
+ hidden_states = self.post_attention_layernorm(hidden_states)
442
+ hidden_states = self.mlp(hidden_states)
443
+ hidden_states = self.post_attention_layernorm_2(hidden_states)
444
+ hidden_states = residual + hidden_states
445
+ return hidden_states
446
+
447
+
448
+ @auto_docstring
449
+ class OuroPreTrainedModel(PreTrainedModel):
450
+ config: OuroConfig
451
+ base_model_prefix = "model"
452
+ supports_gradient_checkpointing = True
453
+ _no_split_modules = ["OuroDecoderLayer"]
454
+ _skip_keys_device_placement = ["past_key_values"]
455
+ _supports_flash_attn = True
456
+ _supports_sdpa = True
457
+ _supports_flex_attn = True
458
+
459
+ _can_compile_fullgraph = True
460
+ _supports_attention_backend = True
461
+ _can_record_outputs = {
462
+ "hidden_states": OuroDecoderLayer,
463
+ "attentions": OuroAttention,
464
+ }
465
+
466
+
467
+ class OuroRotaryEmbedding(nn.Module):
468
+ def __init__(self, config: OuroConfig, device=None):
469
+ super().__init__()
470
+ # BC: "rope_type" was originally "type"
471
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
472
+ self.rope_type = config.rope_scaling.get(
473
+ "rope_type", config.rope_scaling.get("type")
474
+ )
475
+ else:
476
+ self.rope_type = "default"
477
+ self.max_seq_len_cached = config.max_position_embeddings
478
+ self.original_max_seq_len = config.max_position_embeddings
479
+
480
+ self.config = config
481
+
482
+ rope_init_fn: Callable = self.compute_default_rope_parameters
483
+ if self.rope_type != "default":
484
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
485
+
486
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
487
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
488
+ self.original_inv_freq = self.inv_freq
489
+
490
+
491
+ @staticmethod
492
+ def compute_default_rope_parameters(
493
+ config: Optional[OuroConfig] = None,
494
+ device: Optional["torch.device"] = None,
495
+ seq_len: Optional[int] = None,
496
+ ) -> tuple["torch.Tensor", float]:
497
+ """
498
+ Computes the inverse frequencies according to the original RoPE implementation
499
+ """
500
+
501
+ base = config.rope_theta
502
+ partial_rotary_factor = getattr(config, "partial_rotary_factor", 1.0)
503
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
504
+ dim = int(head_dim * partial_rotary_factor)
505
+
506
+ attention_factor = 1.0 # Unused in this type of RoPE
507
+
508
+ # Compute the inverse frequencies
509
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim))
510
+ return inv_freq, attention_factor
511
+
512
+
513
+ @torch.no_grad()
514
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
515
+ def forward(self, x, position_ids):
516
+ inv_freq_expanded = (
517
+ self.inv_freq[None, :, None]
518
+ .float()
519
+ .expand(position_ids.shape[0], -1, 1)
520
+ .to(x.device)
521
+ )
522
+ position_ids_expanded = position_ids[:, None, :].float()
523
+
524
+ device_type = (
525
+ x.device.type
526
+ if isinstance(x.device.type, str) and x.device.type != "mps"
527
+ else "cpu"
528
+ )
529
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
530
+ freqs = (
531
+ inv_freq_expanded.float() @ position_ids_expanded.float()
532
+ ).transpose(1, 2)
533
+ emb = torch.cat((freqs, freqs), dim=-1)
534
+ cos = emb.cos() * self.attention_scaling
535
+ sin = emb.sin() * self.attention_scaling
536
+
537
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
538
+
539
+
540
+ @auto_docstring
541
+ class OuroModel(OuroPreTrainedModel):
542
+ def __init__(self, config: OuroConfig):
543
+ super().__init__(config)
544
+ self.padding_idx = config.pad_token_id
545
+ self.vocab_size = config.vocab_size
546
+
547
+ self.embed_tokens = nn.Embedding(
548
+ config.vocab_size, config.hidden_size, self.padding_idx
549
+ )
550
+ self.layers = nn.ModuleList(
551
+ [
552
+ OuroDecoderLayer(config, layer_idx)
553
+ for layer_idx in range(config.num_hidden_layers)
554
+ ]
555
+ )
556
+ self.norm = OuroRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
557
+ self.rotary_emb = OuroRotaryEmbedding(config=config)
558
+ self.gradient_checkpointing = False
559
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
560
+ self.total_ut_steps = getattr(self.config, "total_ut_steps", 4)
561
+ self.early_exit_gate = nn.Linear(config.hidden_size, 1)
562
+ # Initialize weights and apply final processing
563
+ self.post_init()
564
+
565
+ @check_model_inputs
566
+ @auto_docstring
567
+ def forward(
568
+ self,
569
+ input_ids: Optional[torch.LongTensor] = None,
570
+ attention_mask: Optional[torch.Tensor] = None,
571
+ position_ids: Optional[torch.LongTensor] = None,
572
+ past_key_values: Optional[Cache] = None,
573
+ inputs_embeds: Optional[torch.FloatTensor] = None,
574
+ use_cache: Optional[bool] = None,
575
+ cache_position: Optional[torch.LongTensor] = None,
576
+ **kwargs: Unpack[TransformersKwargs],
577
+ ) -> BaseModelOutputWithPast:
578
+ if (input_ids is None) ^ (inputs_embeds is not None):
579
+ raise ValueError(
580
+ "You must specify exactly one of input_ids or inputs_embeds"
581
+ )
582
+
583
+ if inputs_embeds is None:
584
+ inputs_embeds = self.embed_tokens(input_ids)
585
+
586
+ if use_cache is None:
587
+ use_cache = self.config.use_cache
588
+
589
+ max_cache_size: Optional[int] = None
590
+ if use_cache:
591
+ total_ut_steps = getattr(self.config, "total_ut_steps", 1) or 1
592
+ total_layers = getattr(self.config, "num_hidden_layers", None)
593
+ if total_layers is not None:
594
+ max_cache_size = total_layers * total_ut_steps
595
+
596
+ if needs_universal_cache(past_key_values, max_cache_size):
597
+ past_key_values = UniversalTransformerCache(max_cache_size)
598
+
599
+ if cache_position is None:
600
+ past_seen_tokens = (
601
+ past_key_values.get_seq_length() if past_key_values is not None else 0
602
+ )
603
+ cache_position = torch.arange(
604
+ past_seen_tokens,
605
+ past_seen_tokens + inputs_embeds.shape[1],
606
+ device=inputs_embeds.device,
607
+ )
608
+
609
+ if position_ids is None:
610
+ position_ids = cache_position.unsqueeze(0)
611
+
612
+ # It may already have been prepared by e.g. `generate`
613
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
614
+ # Prepare mask arguments
615
+ mask_kwargs = {
616
+ "config": self.config,
617
+ "input_embeds": inputs_embeds,
618
+ "attention_mask": attention_mask,
619
+ "cache_position": cache_position,
620
+ "past_key_values": past_key_values,
621
+ "position_ids": position_ids,
622
+ }
623
+ # Create the masks
624
+ causal_mask_mapping = {
625
+ "full_attention": create_causal_mask(**mask_kwargs),
626
+ }
627
+ # The sliding window alternating layers are not always activated depending on the config
628
+ if self.has_sliding_layers:
629
+ causal_mask_mapping["sliding_attention"] = (
630
+ create_sliding_window_causal_mask(**mask_kwargs)
631
+ )
632
+
633
+ hidden_states = inputs_embeds
634
+
635
+ # create position embeddings to be shared across the decoder layers
636
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
637
+ hidden_states_list = []
638
+ gate_list = []
639
+
640
+ for current_ut in range(self.total_ut_steps):
641
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
642
+ hidden_states = decoder_layer(
643
+ hidden_states,
644
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
645
+ position_ids=position_ids,
646
+ past_key_value=past_key_values,
647
+ use_cache=use_cache,
648
+ cache_position=cache_position,
649
+ position_embeddings=position_embeddings,
650
+ current_ut=current_ut,
651
+ **kwargs,
652
+ )
653
+
654
+ hidden_states = self.norm(hidden_states)
655
+ hidden_states_list.append(hidden_states)
656
+ gate_list.append(self.early_exit_gate(hidden_states))
657
+
658
+ return (
659
+ BaseModelOutputWithPast(
660
+ last_hidden_state=hidden_states,
661
+ past_key_values=past_key_values if use_cache else None,
662
+ ),
663
+ hidden_states_list,
664
+ gate_list,
665
+ )
666
+
667
+
668
+ @auto_docstring
669
+ class OuroForCausalLM(OuroPreTrainedModel, GenerationMixin):
670
+ _tied_weights_keys = ["lm_head.weight"]
671
+ _tp_plan = {"lm_head": "colwise_rep"}
672
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
673
+
674
+ def __init__(self, config):
675
+ super().__init__(config)
676
+ self.model = OuroModel(config)
677
+ self.vocab_size = config.vocab_size
678
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
679
+
680
+ # 分块大小配置
681
+ self.chunk_size = getattr(config, "chunk_size", 2) # 默认分块大小为2
682
+ self.early_exit_step = getattr(config, "early_exit_step", None)
683
+ self.early_exit_threshold = getattr(config, "early_exit_threshold", None)
684
+
685
+ # Initialize weights and apply final processing
686
+ self.post_init()
687
+
688
+ def set_decoder(self, decoder):
689
+ self.model = decoder
690
+
691
+ def get_decoder(self):
692
+ return self.model
693
+
694
+ @can_return_tuple
695
+ @auto_docstring
696
+ def forward(
697
+ self,
698
+ input_ids: Optional[torch.LongTensor] = None,
699
+ attention_mask: Optional[torch.Tensor] = None,
700
+ position_ids: Optional[torch.LongTensor] = None,
701
+ past_key_values: Optional[Cache] = None,
702
+ inputs_embeds: Optional[torch.FloatTensor] = None,
703
+ labels: Optional[torch.LongTensor] = None,
704
+ use_cache: Optional[bool] = None,
705
+ cache_position: Optional[torch.LongTensor] = None,
706
+ logits_to_keep: Union[int, torch.Tensor] = 0,
707
+ use_weighted_exit: Optional[bool] = False, # 控制是否使用加权 early exit
708
+ exit_at_step: Optional[int] = None,
709
+ exit_threshold: Optional[float] = None,
710
+ **kwargs: Unpack[TransformersKwargs],
711
+ ) -> CausalLMOutputWithPast:
712
+ r"""
713
+ Args:
714
+ use_weighted_exit (`bool`, *optional*, defaults to `False`):
715
+ Whether to use weighted early exit. If `True`, the logits from all UT steps will be
716
+ averaged according to the exit probability distribution.
717
+ exit_at_step (`int`, *optional*):
718
+ Specifies which UT step to exit at. If set, the model will directly use the hidden states
719
+ from this step to generate logits, ignoring other exit strategies.
720
+ exit_threshold (`float`, *optional*):
721
+ The cumulative probability threshold for early exit. When the cumulative exit probability
722
+ reaches this threshold, the model will exit at that step.
723
+
724
+ Example:
725
+
726
+ ```python
727
+ >>> from transformers import AutoTokenizer, OuroForCausalLM
728
+
729
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
730
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
731
+
732
+ >>> # Generate
733
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
734
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
735
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
736
+ ```"""
737
+ exit_at_step = (
738
+ exit_at_step if exit_at_step is not None else self.early_exit_step
739
+ )
740
+ exit_threshold = (
741
+ exit_threshold if exit_threshold is not None else self.early_exit_threshold
742
+ )
743
+
744
+ outputs, hidden_states_list, gate_list = self.model(
745
+ input_ids=input_ids,
746
+ attention_mask=attention_mask,
747
+ position_ids=position_ids,
748
+ past_key_values=past_key_values,
749
+ inputs_embeds=inputs_embeds,
750
+ use_cache=use_cache,
751
+ cache_position=cache_position,
752
+ **kwargs,
753
+ )
754
+ slice_indices = (
755
+ slice(-logits_to_keep, None)
756
+ if isinstance(logits_to_keep, int)
757
+ else logits_to_keep
758
+ )
759
+
760
+ def _select_token_positions(tensor: torch.Tensor) -> torch.Tensor:
761
+ if isinstance(slice_indices, slice):
762
+ return tensor[:, slice_indices, ...]
763
+ if isinstance(slice_indices, torch.Tensor):
764
+ return tensor.index_select(1, slice_indices.to(tensor.device))
765
+ raise TypeError(
766
+ f"Unsupported index type for logits_to_keep: {type(slice_indices)}"
767
+ )
768
+
769
+ stacked_exit_pdf = None
770
+ if gate_list:
771
+ pdf_list = []
772
+ remaining_prob = torch.ones_like(gate_list[0].squeeze(-1))
773
+ for idx, gate_tensor in enumerate(gate_list):
774
+ lambda_i = torch.sigmoid(gate_tensor.squeeze(-1))
775
+ if idx < len(gate_list) - 1:
776
+ p_i = lambda_i * remaining_prob
777
+ remaining_prob = remaining_prob * (1.0 - lambda_i)
778
+ else:
779
+ p_i = remaining_prob
780
+ pdf_list.append(p_i)
781
+ stacked_exit_pdf = torch.stack(pdf_list, dim=2)
782
+
783
+ expected_logits_cache: Optional[torch.Tensor] = None
784
+
785
+ def compute_expected_logits() -> Optional[torch.Tensor]:
786
+ nonlocal expected_logits_cache
787
+ if expected_logits_cache is not None:
788
+ return expected_logits_cache
789
+ if stacked_exit_pdf is None or not hidden_states_list:
790
+ return None
791
+ token_exit_pdf = _select_token_positions(stacked_exit_pdf)
792
+ expected_logits = None
793
+ for step_idx, hidden in enumerate(hidden_states_list):
794
+ step_hidden = _select_token_positions(hidden)
795
+ step_logits = self.lm_head(step_hidden)
796
+ weight = (
797
+ token_exit_pdf[..., step_idx].unsqueeze(-1).to(step_logits.dtype)
798
+ )
799
+ expected_logits = (
800
+ step_logits * weight
801
+ if expected_logits is None
802
+ else expected_logits + step_logits * weight
803
+ )
804
+ expected_logits_cache = expected_logits
805
+ return expected_logits_cache
806
+
807
+ logits: Optional[torch.Tensor] = None
808
+ loss: Optional[torch.Tensor] = None
809
+
810
+ if labels is not None:
811
+ logits = compute_expected_logits()
812
+ if logits is None:
813
+ hidden_states = outputs.last_hidden_state
814
+ logits = self.lm_head(_select_token_positions(hidden_states))
815
+ loss = self.loss_function(
816
+ logits=logits,
817
+ labels=labels,
818
+ vocab_size=self.config.vocab_size,
819
+ **kwargs,
820
+ )
821
+ else:
822
+ if stacked_exit_pdf is not None and hidden_states_list:
823
+ if exit_at_step is not None and 0 <= exit_at_step < len(
824
+ hidden_states_list
825
+ ):
826
+ selected_hidden = hidden_states_list[exit_at_step]
827
+ logits = self.lm_head(_select_token_positions(selected_hidden))
828
+ elif exit_threshold is not None:
829
+ cumulative_probs = torch.cumsum(stacked_exit_pdf, dim=2)
830
+ threshold_value = exit_threshold
831
+ if isinstance(threshold_value, torch.Tensor):
832
+ threshold_value = threshold_value.to(cumulative_probs.device)
833
+ threshold_mask = cumulative_probs >= threshold_value
834
+ exit_steps = torch.argmax(threshold_mask.float(), dim=2)
835
+ last_step_idx = stacked_exit_pdf.shape[2] - 1
836
+ if last_step_idx >= 0:
837
+ never_exceeded = ~threshold_mask.any(dim=2)
838
+ exit_steps[never_exceeded] = last_step_idx
839
+ stacked_hidden = torch.stack(hidden_states_list, dim=2)
840
+ gather_index = (
841
+ exit_steps.unsqueeze(-1)
842
+ .unsqueeze(-1)
843
+ .expand(-1, -1, 1, stacked_hidden.size(-1))
844
+ )
845
+ final_hidden_states = torch.gather(
846
+ stacked_hidden, 2, gather_index
847
+ ).squeeze(2)
848
+ logits = self.lm_head(_select_token_positions(final_hidden_states))
849
+ elif use_weighted_exit:
850
+ logits = compute_expected_logits()
851
+
852
+ if logits is None:
853
+ hidden_states = outputs.last_hidden_state
854
+ logits = self.lm_head(_select_token_positions(hidden_states))
855
+
856
+ result = CausalLMOutputWithPast(
857
+ loss=loss,
858
+ logits=logits,
859
+ past_key_values=outputs.past_key_values,
860
+ hidden_states=outputs.hidden_states,
861
+ attentions=outputs.attentions,
862
+ )
863
+
864
+ return result
865
+
866
+
867
+ class OuroForSequenceClassification(
868
+ GenericForSequenceClassification, OuroPreTrainedModel
869
+ ):
870
+ pass
871
+
872
+
873
+ class OuroForTokenClassification(GenericForTokenClassification, OuroPreTrainedModel):
874
+ pass
875
+
876
+
877
+ class OuroForQuestionAnswering(GenericForQuestionAnswering, OuroPreTrainedModel):
878
+ base_model_prefix = (
879
+ "transformer" # For BC, where `transformer` was used instead of `model`
880
+ )
881
+
882
+
883
+ __all__ = [
884
+ "OuroPreTrainedModel",
885
+ "OuroModel",
886
+ "OuroForCausalLM",
887
+ "OuroForSequenceClassification",
888
+ "OuroForTokenClassification",
889
+ "OuroForQuestionAnswering",
890
+ "UniversalTransformerCache",
891
+ ]
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|im_start|>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "is_local": false,
9
+ "model_max_length": 131072,
10
+ "pad_token": "<|im_end|>",
11
+ "tokenizer_class": "GPT2Tokenizer",
12
+ "unk_token": "<|endoftext|>",
13
+ "vocab_size": 49152
14
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b68c233cc028e45e73e88386a69c08d193238d8abb5754bffa02ae56273f1ab4
3
+ size 5265