gyung commited on
Commit
39f09b3
·
verified ·
1 Parent(s): d9ff5c1

Upload folder using huggingface_hub

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' }}{%- endif -%}
config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 0,
12
+ "dtype": "bfloat16",
13
+ "early_exit_threshold": 1.0,
14
+ "eos_token_id": 0,
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
+ ],
46
+ "max_position_embeddings": 65536,
47
+ "max_window_layers": 24,
48
+ "model_type": "ouro",
49
+ "num_attention_heads": 16,
50
+ "num_hidden_layers": 24,
51
+ "num_key_value_heads": 16,
52
+ "pad_token_id": 0,
53
+ "rms_norm_eps": 1e-06,
54
+ "rope_parameters": {
55
+ "factor": 1.0,
56
+ "rope_theta": 1000000.0,
57
+ "rope_type": "linear"
58
+ },
59
+ "rope_theta": 1000000.0,
60
+ "sliding_window": null,
61
+ "tie_word_embeddings": false,
62
+ "total_ut_steps": 4,
63
+ "transformers_version": "5.5.0",
64
+ "use_cache": false,
65
+ "use_sliding_window": false,
66
+ "vocab_size": 49152
67
+ }
configuration_ouro.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.vocab_size = vocab_size
177
+ self.max_position_embeddings = max_position_embeddings
178
+ self.hidden_size = hidden_size
179
+ self.intermediate_size = intermediate_size
180
+ self.num_hidden_layers = num_hidden_layers
181
+ self.num_attention_heads = num_attention_heads
182
+ self.use_sliding_window = use_sliding_window
183
+ self.sliding_window = sliding_window if self.use_sliding_window else None
184
+ self.max_window_layers = max_window_layers
185
+
186
+ # for backward compatibility
187
+ if num_key_value_heads is None:
188
+ num_key_value_heads = num_attention_heads
189
+
190
+ self.num_key_value_heads = num_key_value_heads
191
+ self.hidden_act = hidden_act
192
+ self.initializer_range = initializer_range
193
+ self.rms_norm_eps = rms_norm_eps
194
+ self.use_cache = use_cache
195
+ self.rope_theta = rope_theta
196
+ self.rope_scaling = rope_scaling
197
+ self.attention_dropout = attention_dropout
198
+ self.total_ut_steps = total_ut_steps
199
+ self.early_exit_threshold = early_exit_threshold
200
+ # Validate the correctness of rotary position embeddings parameters
201
+ # BC: if there is a 'type' field, move it to 'rope_type'.
202
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
203
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
204
+ rope_config_validation(self)
205
+
206
+ self.layer_types = layer_types
207
+ if self.layer_types is None:
208
+ self.layer_types = [
209
+ "sliding_attention"
210
+ if self.sliding_window is not None and i >= self.max_window_layers
211
+ else "full_attention"
212
+ for i in range(self.num_hidden_layers)
213
+ ]
214
+ layer_type_validation(self.layer_types)
215
+
216
+ super().__init__(
217
+ tie_word_embeddings=tie_word_embeddings,
218
+ **kwargs,
219
+ )
220
+
221
+
222
+ __all__ = ["OuroConfig"]
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": [
5
+ 0
6
+ ],
7
+ "pad_token_id": 0,
8
+ "transformers_version": "5.5.0",
9
+ "use_cache": true
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7c31f2e43135f0ecbadb87b0acc20b9e8552942c7c743300f225373d3ea9b45
3
+ size 2869336466
modeling_ouro.py ADDED
@@ -0,0 +1,844 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "linear"
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
+ rope_type = self.rope_type if self.rope_type in ROPE_INIT_FUNCTIONS else "linear"
460
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
461
+
462
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
463
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
464
+ self.original_inv_freq = self.inv_freq
465
+
466
+ @torch.no_grad()
467
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
468
+ def forward(self, x, position_ids):
469
+ inv_freq_expanded = (
470
+ self.inv_freq[None, :, None]
471
+ .float()
472
+ .expand(position_ids.shape[0], -1, 1)
473
+ .to(x.device)
474
+ )
475
+ position_ids_expanded = position_ids[:, None, :].float()
476
+
477
+ device_type = (
478
+ x.device.type
479
+ if isinstance(x.device.type, str) and x.device.type != "mps"
480
+ else "cpu"
481
+ )
482
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
483
+ freqs = (
484
+ inv_freq_expanded.float() @ position_ids_expanded.float()
485
+ ).transpose(1, 2)
486
+ emb = torch.cat((freqs, freqs), dim=-1)
487
+ cos = emb.cos() * self.attention_scaling
488
+ sin = emb.sin() * self.attention_scaling
489
+
490
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
491
+
492
+
493
+ @auto_docstring
494
+ class OuroModel(OuroPreTrainedModel):
495
+ def __init__(self, config: OuroConfig):
496
+ super().__init__(config)
497
+ self.padding_idx = config.pad_token_id
498
+ self.vocab_size = config.vocab_size
499
+
500
+ self.embed_tokens = nn.Embedding(
501
+ config.vocab_size, config.hidden_size, self.padding_idx
502
+ )
503
+ self.layers = nn.ModuleList(
504
+ [
505
+ OuroDecoderLayer(config, layer_idx)
506
+ for layer_idx in range(config.num_hidden_layers)
507
+ ]
508
+ )
509
+ self.norm = OuroRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
510
+ self.rotary_emb = OuroRotaryEmbedding(config=config)
511
+ self.gradient_checkpointing = False
512
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
513
+ self.total_ut_steps = getattr(self.config, "total_ut_steps", 4)
514
+ self.early_exit_gate = nn.Linear(config.hidden_size, 1)
515
+ # Initialize weights and apply final processing
516
+ self.post_init()
517
+
518
+ @check_model_inputs
519
+ @auto_docstring
520
+ def forward(
521
+ self,
522
+ input_ids: Optional[torch.LongTensor] = None,
523
+ attention_mask: Optional[torch.Tensor] = None,
524
+ position_ids: Optional[torch.LongTensor] = None,
525
+ past_key_values: Optional[Cache] = None,
526
+ inputs_embeds: Optional[torch.FloatTensor] = None,
527
+ use_cache: Optional[bool] = None,
528
+ cache_position: Optional[torch.LongTensor] = None,
529
+ **kwargs: Unpack[TransformersKwargs],
530
+ ) -> BaseModelOutputWithPast:
531
+ if (input_ids is None) ^ (inputs_embeds is not None):
532
+ raise ValueError(
533
+ "You must specify exactly one of input_ids or inputs_embeds"
534
+ )
535
+
536
+ if inputs_embeds is None:
537
+ inputs_embeds = self.embed_tokens(input_ids)
538
+
539
+ if use_cache is None:
540
+ use_cache = self.config.use_cache
541
+
542
+ max_cache_size: Optional[int] = None
543
+ if use_cache:
544
+ total_ut_steps = getattr(self.config, "total_ut_steps", 1) or 1
545
+ total_layers = getattr(self.config, "num_hidden_layers", None)
546
+ if total_layers is not None:
547
+ max_cache_size = total_layers * total_ut_steps
548
+
549
+ if needs_universal_cache(past_key_values, max_cache_size):
550
+ past_key_values = UniversalTransformerCache(max_cache_size)
551
+
552
+ if cache_position is None:
553
+ past_seen_tokens = (
554
+ past_key_values.get_seq_length() if past_key_values is not None else 0
555
+ )
556
+ cache_position = torch.arange(
557
+ past_seen_tokens,
558
+ past_seen_tokens + inputs_embeds.shape[1],
559
+ device=inputs_embeds.device,
560
+ )
561
+
562
+ if position_ids is None:
563
+ position_ids = cache_position.unsqueeze(0)
564
+
565
+ # It may already have been prepared by e.g. `generate`
566
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
567
+ # Prepare mask arguments
568
+ mask_kwargs = {
569
+ "config": self.config,
570
+ "input_embeds": inputs_embeds,
571
+ "attention_mask": attention_mask,
572
+ "cache_position": cache_position,
573
+ "past_key_values": past_key_values,
574
+ "position_ids": position_ids,
575
+ }
576
+ # Create the masks
577
+ causal_mask_mapping = {
578
+ "full_attention": create_causal_mask(**mask_kwargs),
579
+ }
580
+ # The sliding window alternating layers are not always activated depending on the config
581
+ if self.has_sliding_layers:
582
+ causal_mask_mapping["sliding_attention"] = (
583
+ create_sliding_window_causal_mask(**mask_kwargs)
584
+ )
585
+
586
+ hidden_states = inputs_embeds
587
+
588
+ # create position embeddings to be shared across the decoder layers
589
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
590
+ hidden_states_list = []
591
+ gate_list = []
592
+
593
+ for current_ut in range(self.total_ut_steps):
594
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
595
+ hidden_states = decoder_layer(
596
+ hidden_states,
597
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
598
+ position_ids=position_ids,
599
+ past_key_value=past_key_values,
600
+ use_cache=use_cache,
601
+ cache_position=cache_position,
602
+ position_embeddings=position_embeddings,
603
+ current_ut=current_ut,
604
+ **kwargs,
605
+ )
606
+
607
+ hidden_states = self.norm(hidden_states)
608
+ hidden_states_list.append(hidden_states)
609
+ gate_list.append(self.early_exit_gate(hidden_states))
610
+
611
+ return (
612
+ BaseModelOutputWithPast(
613
+ last_hidden_state=hidden_states,
614
+ past_key_values=past_key_values if use_cache else None,
615
+ ),
616
+ hidden_states_list,
617
+ gate_list,
618
+ )
619
+
620
+
621
+ @auto_docstring
622
+ class OuroForCausalLM(OuroPreTrainedModel, GenerationMixin):
623
+ _tied_weights_keys = ["lm_head.weight"]
624
+ _tp_plan = {"lm_head": "colwise_rep"}
625
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
626
+
627
+ def __init__(self, config):
628
+ super().__init__(config)
629
+ self.model = OuroModel(config)
630
+ self.vocab_size = config.vocab_size
631
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
632
+
633
+ # 分块大小配置
634
+ self.chunk_size = getattr(config, "chunk_size", 2) # 默认分块大小为2
635
+ self.early_exit_step = getattr(config, "early_exit_step", None)
636
+ self.early_exit_threshold = getattr(config, "early_exit_threshold", None)
637
+
638
+ # Initialize weights and apply final processing
639
+ self.post_init()
640
+
641
+ def set_decoder(self, decoder):
642
+ self.model = decoder
643
+
644
+ def get_decoder(self):
645
+ return self.model
646
+
647
+ @can_return_tuple
648
+ @auto_docstring
649
+ def forward(
650
+ self,
651
+ input_ids: Optional[torch.LongTensor] = None,
652
+ attention_mask: Optional[torch.Tensor] = None,
653
+ position_ids: Optional[torch.LongTensor] = None,
654
+ past_key_values: Optional[Cache] = None,
655
+ inputs_embeds: Optional[torch.FloatTensor] = None,
656
+ labels: Optional[torch.LongTensor] = None,
657
+ use_cache: Optional[bool] = None,
658
+ cache_position: Optional[torch.LongTensor] = None,
659
+ logits_to_keep: Union[int, torch.Tensor] = 0,
660
+ use_weighted_exit: Optional[bool] = False, # 控制是否使用加权 early exit
661
+ exit_at_step: Optional[int] = None,
662
+ exit_threshold: Optional[float] = None,
663
+ **kwargs: Unpack[TransformersKwargs],
664
+ ) -> CausalLMOutputWithPast:
665
+ r"""
666
+ Args:
667
+ use_weighted_exit (`bool`, *optional*, defaults to `False`):
668
+ Whether to use weighted early exit. If `True`, the logits from all UT steps will be
669
+ averaged according to the exit probability distribution.
670
+ exit_at_step (`int`, *optional*):
671
+ Specifies which UT step to exit at. If set, the model will directly use the hidden states
672
+ from this step to generate logits, ignoring other exit strategies.
673
+ exit_threshold (`float`, *optional*):
674
+ The cumulative probability threshold for early exit. When the cumulative exit probability
675
+ reaches this threshold, the model will exit at that step.
676
+
677
+ Example:
678
+
679
+ ```python
680
+ >>> from transformers import AutoTokenizer, OuroForCausalLM
681
+
682
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
683
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
684
+
685
+ >>> # Generate
686
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
687
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
688
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
689
+ ```"""
690
+ exit_at_step = (
691
+ exit_at_step if exit_at_step is not None else self.early_exit_step
692
+ )
693
+ exit_threshold = (
694
+ exit_threshold if exit_threshold is not None else self.early_exit_threshold
695
+ )
696
+
697
+ outputs, hidden_states_list, gate_list = self.model(
698
+ input_ids=input_ids,
699
+ attention_mask=attention_mask,
700
+ position_ids=position_ids,
701
+ past_key_values=past_key_values,
702
+ inputs_embeds=inputs_embeds,
703
+ use_cache=use_cache,
704
+ cache_position=cache_position,
705
+ **kwargs,
706
+ )
707
+ slice_indices = (
708
+ slice(-logits_to_keep, None)
709
+ if isinstance(logits_to_keep, int)
710
+ else logits_to_keep
711
+ )
712
+
713
+ def _select_token_positions(tensor: torch.Tensor) -> torch.Tensor:
714
+ if isinstance(slice_indices, slice):
715
+ return tensor[:, slice_indices, ...]
716
+ if isinstance(slice_indices, torch.Tensor):
717
+ return tensor.index_select(1, slice_indices.to(tensor.device))
718
+ raise TypeError(
719
+ f"Unsupported index type for logits_to_keep: {type(slice_indices)}"
720
+ )
721
+
722
+ stacked_exit_pdf = None
723
+ if gate_list:
724
+ pdf_list = []
725
+ remaining_prob = torch.ones_like(gate_list[0].squeeze(-1))
726
+ for idx, gate_tensor in enumerate(gate_list):
727
+ lambda_i = torch.sigmoid(gate_tensor.squeeze(-1))
728
+ if idx < len(gate_list) - 1:
729
+ p_i = lambda_i * remaining_prob
730
+ remaining_prob = remaining_prob * (1.0 - lambda_i)
731
+ else:
732
+ p_i = remaining_prob
733
+ pdf_list.append(p_i)
734
+ stacked_exit_pdf = torch.stack(pdf_list, dim=2)
735
+
736
+ expected_logits_cache: Optional[torch.Tensor] = None
737
+
738
+ def compute_expected_logits() -> Optional[torch.Tensor]:
739
+ nonlocal expected_logits_cache
740
+ if expected_logits_cache is not None:
741
+ return expected_logits_cache
742
+ if stacked_exit_pdf is None or not hidden_states_list:
743
+ return None
744
+ token_exit_pdf = _select_token_positions(stacked_exit_pdf)
745
+ expected_logits = None
746
+ for step_idx, hidden in enumerate(hidden_states_list):
747
+ step_hidden = _select_token_positions(hidden)
748
+ step_logits = self.lm_head(step_hidden)
749
+ weight = (
750
+ token_exit_pdf[..., step_idx].unsqueeze(-1).to(step_logits.dtype)
751
+ )
752
+ expected_logits = (
753
+ step_logits * weight
754
+ if expected_logits is None
755
+ else expected_logits + step_logits * weight
756
+ )
757
+ expected_logits_cache = expected_logits
758
+ return expected_logits_cache
759
+
760
+ logits: Optional[torch.Tensor] = None
761
+ loss: Optional[torch.Tensor] = None
762
+
763
+ if labels is not None:
764
+ logits = compute_expected_logits()
765
+ if logits is None:
766
+ hidden_states = outputs.last_hidden_state
767
+ logits = self.lm_head(_select_token_positions(hidden_states))
768
+ loss = self.loss_function(
769
+ logits=logits,
770
+ labels=labels,
771
+ vocab_size=self.config.vocab_size,
772
+ **kwargs,
773
+ )
774
+ else:
775
+ if stacked_exit_pdf is not None and hidden_states_list:
776
+ if exit_at_step is not None and 0 <= exit_at_step < len(
777
+ hidden_states_list
778
+ ):
779
+ selected_hidden = hidden_states_list[exit_at_step]
780
+ logits = self.lm_head(_select_token_positions(selected_hidden))
781
+ elif exit_threshold is not None:
782
+ cumulative_probs = torch.cumsum(stacked_exit_pdf, dim=2)
783
+ threshold_value = exit_threshold
784
+ if isinstance(threshold_value, torch.Tensor):
785
+ threshold_value = threshold_value.to(cumulative_probs.device)
786
+ threshold_mask = cumulative_probs >= threshold_value
787
+ exit_steps = torch.argmax(threshold_mask.float(), dim=2)
788
+ last_step_idx = stacked_exit_pdf.shape[2] - 1
789
+ if last_step_idx >= 0:
790
+ never_exceeded = ~threshold_mask.any(dim=2)
791
+ exit_steps[never_exceeded] = last_step_idx
792
+ stacked_hidden = torch.stack(hidden_states_list, dim=2)
793
+ gather_index = (
794
+ exit_steps.unsqueeze(-1)
795
+ .unsqueeze(-1)
796
+ .expand(-1, -1, 1, stacked_hidden.size(-1))
797
+ )
798
+ final_hidden_states = torch.gather(
799
+ stacked_hidden, 2, gather_index
800
+ ).squeeze(2)
801
+ logits = self.lm_head(_select_token_positions(final_hidden_states))
802
+ elif use_weighted_exit:
803
+ logits = compute_expected_logits()
804
+
805
+ if logits is None:
806
+ hidden_states = outputs.last_hidden_state
807
+ logits = self.lm_head(_select_token_positions(hidden_states))
808
+
809
+ result = CausalLMOutputWithPast(
810
+ loss=loss,
811
+ logits=logits,
812
+ past_key_values=outputs.past_key_values,
813
+ hidden_states=outputs.hidden_states,
814
+ attentions=outputs.attentions,
815
+ )
816
+
817
+ return result
818
+
819
+
820
+ class OuroForSequenceClassification(
821
+ GenericForSequenceClassification, OuroPreTrainedModel
822
+ ):
823
+ pass
824
+
825
+
826
+ class OuroForTokenClassification(GenericForTokenClassification, OuroPreTrainedModel):
827
+ pass
828
+
829
+
830
+ class OuroForQuestionAnswering(GenericForQuestionAnswering, OuroPreTrainedModel):
831
+ base_model_prefix = (
832
+ "transformer" # For BC, where `transformer` was used instead of `model`
833
+ )
834
+
835
+
836
+ __all__ = [
837
+ "OuroPreTrainedModel",
838
+ "OuroModel",
839
+ "OuroForCausalLM",
840
+ "OuroForSequenceClassification",
841
+ "OuroForTokenClassification",
842
+ "OuroForQuestionAnswering",
843
+ "UniversalTransformerCache",
844
+ ]
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": "<|endoftext|>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|endoftext|>",
7
+ "errors": "replace",
8
+ "is_local": false,
9
+ "model_max_length": 131072,
10
+ "pad_token": "<|endoftext|>",
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:a55f81112b6e4e6189e1eff115a85aaed8b4e7fd4eaf49e0ad6556811291b295
3
+ size 5265