Upload Ouro-2.6B_smoothquant_W8A8 with bundled source code
Browse files- qouro/__init__.py +1 -0
- qouro/__pycache__/configuration_ouro.cpython-311.pyc +0 -0
- qouro/__pycache__/configuration_ouro.cpython-312.pyc +0 -0
- qouro/__pycache__/modeling_ouro.cpython-311.pyc +0 -0
- qouro/__pycache__/modeling_ouro.cpython-312.pyc +0 -0
- qouro/__pycache__/modeling_qouro.cpython-311.pyc +0 -0
- qouro/__pycache__/modeling_qouro.cpython-312.pyc +0 -0
- qouro/configuration_ouro.py +222 -0
- qouro/modeling_ouro.py +701 -0
- qouro/modeling_qouro.py +110 -0
- qouro/quantization/__init__.py +4 -0
- qouro/quantization/__pycache__/__init__.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/__init__.cpython-312.pyc +0 -0
- qouro/quantization/__pycache__/awq_core.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/awq_core.cpython-312.pyc +0 -0
- qouro/quantization/__pycache__/calibration.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/calibration.cpython-312.pyc +0 -0
- qouro/quantization/__pycache__/config.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/config.cpython-312.pyc +0 -0
- qouro/quantization/__pycache__/modules.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/modules.cpython-312.pyc +0 -0
- qouro/quantization/__pycache__/observers.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/observers.cpython-312.pyc +0 -0
- qouro/quantization/__pycache__/pipeline.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/pipeline.cpython-312.pyc +0 -0
- qouro/quantization/__pycache__/smoothquant.cpython-311.pyc +0 -0
- qouro/quantization/__pycache__/smoothquant.cpython-312.pyc +0 -0
- qouro/quantization/awq_core.py +102 -0
- qouro/quantization/calibration.py +111 -0
- qouro/quantization/config.py +57 -0
- qouro/quantization/modules.py +221 -0
- qouro/quantization/observers.py +71 -0
- qouro/quantization/pipeline.py +162 -0
- qouro/quantization/smoothquant.py +95 -0
qouro/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__all__ = []
|
qouro/__pycache__/configuration_ouro.cpython-311.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
qouro/__pycache__/configuration_ouro.cpython-312.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
qouro/__pycache__/modeling_ouro.cpython-311.pyc
ADDED
|
Binary file (35.4 kB). View file
|
|
|
qouro/__pycache__/modeling_ouro.cpython-312.pyc
ADDED
|
Binary file (33.1 kB). View file
|
|
|
qouro/__pycache__/modeling_qouro.cpython-311.pyc
ADDED
|
Binary file (5.44 kB). View file
|
|
|
qouro/__pycache__/modeling_qouro.cpython-312.pyc
ADDED
|
Binary file (6.29 kB). View file
|
|
|
qouro/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"]
|
qouro/modeling_ouro.py
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Optional, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
from transformers.activations import ACT2FN
|
| 7 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 8 |
+
from transformers.generation import GenerationMixin
|
| 9 |
+
from transformers.integrations import use_kernel_forward_from_hub
|
| 10 |
+
from transformers.masking_utils import (
|
| 11 |
+
create_causal_mask,
|
| 12 |
+
create_sliding_window_causal_mask,
|
| 13 |
+
)
|
| 14 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 15 |
+
from transformers.modeling_layers import (
|
| 16 |
+
GenericForQuestionAnswering,
|
| 17 |
+
GenericForSequenceClassification,
|
| 18 |
+
GenericForTokenClassification,
|
| 19 |
+
GradientCheckpointingLayer,
|
| 20 |
+
)
|
| 21 |
+
from transformers.modeling_outputs import (
|
| 22 |
+
BaseModelOutputWithPast,
|
| 23 |
+
CausalLMOutputWithPast,
|
| 24 |
+
)
|
| 25 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 26 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 27 |
+
from transformers.processing_utils import Unpack
|
| 28 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 29 |
+
from transformers.utils.generic import check_model_inputs
|
| 30 |
+
from .configuration_ouro import OuroConfig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class OuroMLP(nn.Module):
|
| 34 |
+
def __init__(self, config):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.config = config
|
| 37 |
+
self.hidden_size = config.hidden_size
|
| 38 |
+
self.intermediate_size = config.intermediate_size
|
| 39 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 40 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 41 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 42 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 43 |
+
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 46 |
+
return down_proj
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def rotate_half(x):
|
| 50 |
+
"""Rotates half the hidden dims of the input."""
|
| 51 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 52 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 53 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 57 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
q (`torch.Tensor`): The query tensor.
|
| 61 |
+
k (`torch.Tensor`): The key tensor.
|
| 62 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 63 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 64 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 65 |
+
Deprecated and unused.
|
| 66 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 67 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 68 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 69 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 70 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 71 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 72 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 73 |
+
Returns:
|
| 74 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 75 |
+
"""
|
| 76 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 77 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 78 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 79 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 80 |
+
return q_embed, k_embed
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 84 |
+
"""
|
| 85 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 86 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 87 |
+
"""
|
| 88 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 89 |
+
if n_rep == 1:
|
| 90 |
+
return hidden_states
|
| 91 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
| 92 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
| 93 |
+
)
|
| 94 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def eager_attention_forward(
|
| 98 |
+
module: nn.Module,
|
| 99 |
+
query: torch.Tensor,
|
| 100 |
+
key: torch.Tensor,
|
| 101 |
+
value: torch.Tensor,
|
| 102 |
+
attention_mask: Optional[torch.Tensor],
|
| 103 |
+
scaling: float,
|
| 104 |
+
dropout: float = 0.0,
|
| 105 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 106 |
+
):
|
| 107 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 108 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 109 |
+
|
| 110 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 111 |
+
if attention_mask is not None:
|
| 112 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 113 |
+
attn_weights = attn_weights + causal_mask
|
| 114 |
+
|
| 115 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
|
| 116 |
+
query.dtype
|
| 117 |
+
)
|
| 118 |
+
attn_weights = nn.functional.dropout(
|
| 119 |
+
attn_weights, p=dropout, training=module.training
|
| 120 |
+
)
|
| 121 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 122 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 123 |
+
|
| 124 |
+
return attn_output, attn_weights
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class OuroAttention(nn.Module):
|
| 128 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 129 |
+
|
| 130 |
+
def __init__(self, config: OuroConfig, layer_idx: int):
|
| 131 |
+
super().__init__()
|
| 132 |
+
self.config = config
|
| 133 |
+
self.layer_idx = layer_idx
|
| 134 |
+
self.head_dim = getattr(
|
| 135 |
+
config, "head_dim", config.hidden_size // config.num_attention_heads
|
| 136 |
+
)
|
| 137 |
+
self.num_key_value_groups = (
|
| 138 |
+
config.num_attention_heads // config.num_key_value_heads
|
| 139 |
+
)
|
| 140 |
+
self.scaling = self.head_dim**-0.5
|
| 141 |
+
self.attention_dropout = config.attention_dropout
|
| 142 |
+
self.is_causal = True
|
| 143 |
+
self.q_proj = nn.Linear(
|
| 144 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=False
|
| 145 |
+
)
|
| 146 |
+
self.k_proj = nn.Linear(
|
| 147 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
|
| 148 |
+
)
|
| 149 |
+
self.v_proj = nn.Linear(
|
| 150 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
|
| 151 |
+
)
|
| 152 |
+
self.o_proj = nn.Linear(
|
| 153 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=False
|
| 154 |
+
)
|
| 155 |
+
self.sliding_window = (
|
| 156 |
+
config.sliding_window
|
| 157 |
+
if config.layer_types[layer_idx] == "sliding_attention"
|
| 158 |
+
else None
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def forward(
|
| 162 |
+
self,
|
| 163 |
+
hidden_states: torch.Tensor,
|
| 164 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 165 |
+
attention_mask: Optional[torch.Tensor],
|
| 166 |
+
past_key_value: Optional[Cache] = None,
|
| 167 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 168 |
+
current_ut: int = 0,
|
| 169 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 170 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
|
| 171 |
+
input_shape = hidden_states.shape[:-1]
|
| 172 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 173 |
+
|
| 174 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 175 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 176 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 177 |
+
|
| 178 |
+
cos, sin = position_embeddings
|
| 179 |
+
query_states, key_states = apply_rotary_pos_emb(
|
| 180 |
+
query_states, key_states, cos, sin
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
if past_key_value is not None:
|
| 184 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 185 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 186 |
+
key_states, value_states = past_key_value.update(
|
| 187 |
+
key_states,
|
| 188 |
+
value_states,
|
| 189 |
+
current_ut * self.config.num_hidden_layers + self.layer_idx,
|
| 190 |
+
cache_kwargs,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
attention_interface: Callable = eager_attention_forward
|
| 194 |
+
if self.config._attn_implementation != "eager":
|
| 195 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[
|
| 196 |
+
self.config._attn_implementation
|
| 197 |
+
]
|
| 198 |
+
|
| 199 |
+
attn_output, attn_weights = attention_interface(
|
| 200 |
+
self,
|
| 201 |
+
query_states,
|
| 202 |
+
key_states,
|
| 203 |
+
value_states,
|
| 204 |
+
attention_mask,
|
| 205 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 206 |
+
scaling=self.scaling,
|
| 207 |
+
sliding_window=self.sliding_window, # main diff with Llama
|
| 208 |
+
**kwargs,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 212 |
+
attn_output = self.o_proj(attn_output)
|
| 213 |
+
return attn_output, attn_weights
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 217 |
+
class OuroRMSNorm(nn.Module):
|
| 218 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 219 |
+
"""
|
| 220 |
+
OuroRMSNorm is equivalent to T5LayerNorm
|
| 221 |
+
"""
|
| 222 |
+
super().__init__()
|
| 223 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 224 |
+
self.variance_epsilon = eps
|
| 225 |
+
|
| 226 |
+
def forward(self, hidden_states):
|
| 227 |
+
input_dtype = hidden_states.dtype
|
| 228 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 229 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 230 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 231 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 232 |
+
|
| 233 |
+
def extra_repr(self):
|
| 234 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class OuroDecoderLayer(GradientCheckpointingLayer):
|
| 238 |
+
def __init__(self, config: OuroConfig, layer_idx: int):
|
| 239 |
+
super().__init__()
|
| 240 |
+
self.hidden_size = config.hidden_size
|
| 241 |
+
|
| 242 |
+
self.self_attn = OuroAttention(config=config, layer_idx=layer_idx)
|
| 243 |
+
|
| 244 |
+
self.mlp = OuroMLP(config)
|
| 245 |
+
self.input_layernorm = OuroRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 246 |
+
self.input_layernorm_2 = OuroRMSNorm(
|
| 247 |
+
config.hidden_size, eps=config.rms_norm_eps
|
| 248 |
+
)
|
| 249 |
+
self.post_attention_layernorm = OuroRMSNorm(
|
| 250 |
+
config.hidden_size, eps=config.rms_norm_eps
|
| 251 |
+
)
|
| 252 |
+
self.post_attention_layernorm_2 = OuroRMSNorm(
|
| 253 |
+
config.hidden_size, eps=config.rms_norm_eps
|
| 254 |
+
)
|
| 255 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 256 |
+
|
| 257 |
+
def forward(
|
| 258 |
+
self,
|
| 259 |
+
hidden_states: torch.Tensor,
|
| 260 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 261 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 262 |
+
past_key_value: Optional[Cache] = None,
|
| 263 |
+
use_cache: Optional[bool] = False,
|
| 264 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 265 |
+
position_embeddings: Optional[
|
| 266 |
+
tuple[torch.Tensor, torch.Tensor]
|
| 267 |
+
] = None, # necessary, but kept here for BC
|
| 268 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 269 |
+
) -> tuple[torch.Tensor]:
|
| 270 |
+
residual = hidden_states
|
| 271 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 272 |
+
# Self Attention
|
| 273 |
+
hidden_states, _ = self.self_attn(
|
| 274 |
+
hidden_states=hidden_states,
|
| 275 |
+
attention_mask=attention_mask,
|
| 276 |
+
position_ids=position_ids,
|
| 277 |
+
past_key_value=past_key_value,
|
| 278 |
+
use_cache=use_cache,
|
| 279 |
+
cache_position=cache_position,
|
| 280 |
+
position_embeddings=position_embeddings,
|
| 281 |
+
**kwargs,
|
| 282 |
+
)
|
| 283 |
+
hidden_states = self.input_layernorm_2(hidden_states)
|
| 284 |
+
hidden_states = residual + hidden_states
|
| 285 |
+
|
| 286 |
+
# Fully Connected
|
| 287 |
+
residual = hidden_states
|
| 288 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 289 |
+
hidden_states = self.mlp(hidden_states)
|
| 290 |
+
hidden_states = self.post_attention_layernorm_2(hidden_states)
|
| 291 |
+
hidden_states = residual + hidden_states
|
| 292 |
+
return hidden_states
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@auto_docstring
|
| 296 |
+
class OuroPreTrainedModel(PreTrainedModel):
|
| 297 |
+
config: OuroConfig
|
| 298 |
+
base_model_prefix = "model"
|
| 299 |
+
supports_gradient_checkpointing = True
|
| 300 |
+
_no_split_modules = ["OuroDecoderLayer"]
|
| 301 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 302 |
+
_supports_flash_attn = True
|
| 303 |
+
_supports_sdpa = True
|
| 304 |
+
_supports_flex_attn = True
|
| 305 |
+
|
| 306 |
+
_can_compile_fullgraph = True
|
| 307 |
+
_supports_attention_backend = True
|
| 308 |
+
_can_record_outputs = {
|
| 309 |
+
"hidden_states": OuroDecoderLayer,
|
| 310 |
+
"attentions": OuroAttention,
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class OuroRotaryEmbedding(nn.Module):
|
| 315 |
+
def __init__(self, config: OuroConfig, device=None):
|
| 316 |
+
super().__init__()
|
| 317 |
+
# BC: "rope_type" was originally "type"
|
| 318 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
| 319 |
+
self.rope_type = config.rope_scaling.get(
|
| 320 |
+
"rope_type", config.rope_scaling.get("type")
|
| 321 |
+
)
|
| 322 |
+
else:
|
| 323 |
+
self.rope_type = "default"
|
| 324 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 325 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 326 |
+
|
| 327 |
+
self.config = config
|
| 328 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 329 |
+
|
| 330 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 331 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 332 |
+
self.original_inv_freq = self.inv_freq
|
| 333 |
+
|
| 334 |
+
@torch.no_grad()
|
| 335 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 336 |
+
def forward(self, x, position_ids):
|
| 337 |
+
inv_freq_expanded = (
|
| 338 |
+
self.inv_freq[None, :, None]
|
| 339 |
+
.float()
|
| 340 |
+
.expand(position_ids.shape[0], -1, 1)
|
| 341 |
+
.to(x.device)
|
| 342 |
+
)
|
| 343 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 344 |
+
|
| 345 |
+
device_type = (
|
| 346 |
+
x.device.type
|
| 347 |
+
if isinstance(x.device.type, str) and x.device.type != "mps"
|
| 348 |
+
else "cpu"
|
| 349 |
+
)
|
| 350 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 351 |
+
freqs = (
|
| 352 |
+
inv_freq_expanded.float() @ position_ids_expanded.float()
|
| 353 |
+
).transpose(1, 2)
|
| 354 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 355 |
+
cos = emb.cos() * self.attention_scaling
|
| 356 |
+
sin = emb.sin() * self.attention_scaling
|
| 357 |
+
|
| 358 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@auto_docstring
|
| 362 |
+
class OuroModel(OuroPreTrainedModel):
|
| 363 |
+
def __init__(self, config: OuroConfig):
|
| 364 |
+
super().__init__(config)
|
| 365 |
+
self.padding_idx = config.pad_token_id
|
| 366 |
+
self.vocab_size = config.vocab_size
|
| 367 |
+
|
| 368 |
+
self.embed_tokens = nn.Embedding(
|
| 369 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
| 370 |
+
)
|
| 371 |
+
self.layers = nn.ModuleList(
|
| 372 |
+
[
|
| 373 |
+
OuroDecoderLayer(config, layer_idx)
|
| 374 |
+
for layer_idx in range(config.num_hidden_layers)
|
| 375 |
+
]
|
| 376 |
+
)
|
| 377 |
+
self.norm = OuroRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 378 |
+
self.rotary_emb = OuroRotaryEmbedding(config=config)
|
| 379 |
+
self.gradient_checkpointing = False
|
| 380 |
+
self.has_sliding_layers = "sliding_attention" in self.config.layer_types
|
| 381 |
+
self.total_ut_steps = getattr(self.config, "total_ut_steps", 4)
|
| 382 |
+
self.early_exit_gate = nn.Linear(config.hidden_size, 1)
|
| 383 |
+
# Initialize weights and apply final processing
|
| 384 |
+
self.post_init()
|
| 385 |
+
|
| 386 |
+
@check_model_inputs
|
| 387 |
+
@auto_docstring
|
| 388 |
+
def forward(
|
| 389 |
+
self,
|
| 390 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 391 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 392 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 393 |
+
past_key_values: Optional[Cache] = None,
|
| 394 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 395 |
+
use_cache: Optional[bool] = None,
|
| 396 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 397 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 398 |
+
) -> BaseModelOutputWithPast:
|
| 399 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 400 |
+
raise ValueError(
|
| 401 |
+
"You must specify exactly one of input_ids or inputs_embeds"
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
if inputs_embeds is None:
|
| 405 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 406 |
+
|
| 407 |
+
if use_cache and past_key_values is None:
|
| 408 |
+
past_key_values = DynamicCache()
|
| 409 |
+
|
| 410 |
+
if cache_position is None:
|
| 411 |
+
past_seen_tokens = (
|
| 412 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 413 |
+
)
|
| 414 |
+
cache_position = torch.arange(
|
| 415 |
+
past_seen_tokens,
|
| 416 |
+
past_seen_tokens + inputs_embeds.shape[1],
|
| 417 |
+
device=inputs_embeds.device,
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
if position_ids is None:
|
| 421 |
+
position_ids = cache_position.unsqueeze(0)
|
| 422 |
+
|
| 423 |
+
# It may already have been prepared by e.g. `generate`
|
| 424 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
| 425 |
+
# Prepare mask arguments
|
| 426 |
+
mask_kwargs = {
|
| 427 |
+
"config": self.config,
|
| 428 |
+
"input_embeds": inputs_embeds,
|
| 429 |
+
"attention_mask": attention_mask,
|
| 430 |
+
"cache_position": cache_position,
|
| 431 |
+
"past_key_values": past_key_values,
|
| 432 |
+
"position_ids": position_ids,
|
| 433 |
+
}
|
| 434 |
+
# Create the masks
|
| 435 |
+
causal_mask_mapping = {
|
| 436 |
+
"full_attention": create_causal_mask(**mask_kwargs),
|
| 437 |
+
}
|
| 438 |
+
# The sliding window alternating layers are not always activated depending on the config
|
| 439 |
+
if self.has_sliding_layers:
|
| 440 |
+
causal_mask_mapping["sliding_attention"] = (
|
| 441 |
+
create_sliding_window_causal_mask(**mask_kwargs)
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
hidden_states = inputs_embeds
|
| 445 |
+
|
| 446 |
+
# create position embeddings to be shared across the decoder layers
|
| 447 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 448 |
+
hidden_states_list = []
|
| 449 |
+
gate_list = []
|
| 450 |
+
|
| 451 |
+
for current_ut in range(self.total_ut_steps):
|
| 452 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 453 |
+
hidden_states = decoder_layer(
|
| 454 |
+
hidden_states,
|
| 455 |
+
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
| 456 |
+
position_ids=position_ids,
|
| 457 |
+
past_key_value=past_key_values,
|
| 458 |
+
use_cache=use_cache,
|
| 459 |
+
cache_position=cache_position,
|
| 460 |
+
position_embeddings=position_embeddings,
|
| 461 |
+
current_ut=current_ut,
|
| 462 |
+
**kwargs,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
hidden_states = self.norm(hidden_states)
|
| 466 |
+
hidden_states_list.append(hidden_states)
|
| 467 |
+
gate_list.append(self.early_exit_gate(hidden_states))
|
| 468 |
+
|
| 469 |
+
return (
|
| 470 |
+
BaseModelOutputWithPast(
|
| 471 |
+
last_hidden_state=hidden_states,
|
| 472 |
+
past_key_values=past_key_values if use_cache else None,
|
| 473 |
+
),
|
| 474 |
+
hidden_states_list,
|
| 475 |
+
gate_list,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@auto_docstring
|
| 480 |
+
class OuroForCausalLM(OuroPreTrainedModel, GenerationMixin):
|
| 481 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 482 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 483 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 484 |
+
|
| 485 |
+
def __init__(self, config):
|
| 486 |
+
super().__init__(config)
|
| 487 |
+
self.model = OuroModel(config)
|
| 488 |
+
self.vocab_size = config.vocab_size
|
| 489 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 490 |
+
|
| 491 |
+
# 分块大小配置
|
| 492 |
+
self.chunk_size = getattr(config, "chunk_size", 2) # 默认分块大小为2
|
| 493 |
+
self.early_exit_step = getattr(config, "early_exit_step", None)
|
| 494 |
+
self.early_exit_threshold = getattr(config, "early_exit_threshold", None)
|
| 495 |
+
|
| 496 |
+
# Initialize weights and apply final processing
|
| 497 |
+
self.post_init()
|
| 498 |
+
|
| 499 |
+
def set_decoder(self, decoder):
|
| 500 |
+
self.model = decoder
|
| 501 |
+
|
| 502 |
+
def get_decoder(self):
|
| 503 |
+
return self.model
|
| 504 |
+
|
| 505 |
+
@can_return_tuple
|
| 506 |
+
@auto_docstring
|
| 507 |
+
def forward(
|
| 508 |
+
self,
|
| 509 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 510 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 511 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 512 |
+
past_key_values: Optional[Cache] = None,
|
| 513 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 514 |
+
labels: Optional[torch.LongTensor] = None,
|
| 515 |
+
use_cache: Optional[bool] = None,
|
| 516 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 517 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 518 |
+
use_weighted_exit: Optional[bool] = False, # 控制是否使用加权 early exit
|
| 519 |
+
exit_at_step: Optional[int] = None,
|
| 520 |
+
exit_threshold: Optional[float] = None,
|
| 521 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 522 |
+
) -> CausalLMOutputWithPast:
|
| 523 |
+
r"""
|
| 524 |
+
Args:
|
| 525 |
+
use_weighted_exit (`bool`, *optional*, defaults to `False`):
|
| 526 |
+
Whether to use weighted early exit. If `True`, the logits from all UT steps will be
|
| 527 |
+
averaged according to the exit probability distribution.
|
| 528 |
+
exit_at_step (`int`, *optional*):
|
| 529 |
+
Specifies which UT step to exit at. If set, the model will directly use the hidden states
|
| 530 |
+
from this step to generate logits, ignoring other exit strategies.
|
| 531 |
+
exit_threshold (`float`, *optional*):
|
| 532 |
+
The cumulative probability threshold for early exit. When the cumulative exit probability
|
| 533 |
+
reaches this threshold, the model will exit at that step.
|
| 534 |
+
|
| 535 |
+
Example:
|
| 536 |
+
|
| 537 |
+
```python
|
| 538 |
+
>>> from transformers import AutoTokenizer, OuroForCausalLM
|
| 539 |
+
|
| 540 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 541 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 542 |
+
|
| 543 |
+
>>> # Generate
|
| 544 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 545 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 546 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 547 |
+
```"""
|
| 548 |
+
exit_at_step = (
|
| 549 |
+
exit_at_step if exit_at_step is not None else self.early_exit_step
|
| 550 |
+
)
|
| 551 |
+
exit_threshold = (
|
| 552 |
+
exit_threshold if exit_threshold is not None else self.early_exit_threshold
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
outputs, hidden_states_list, gate_list = self.model(
|
| 556 |
+
input_ids=input_ids,
|
| 557 |
+
attention_mask=attention_mask,
|
| 558 |
+
position_ids=position_ids,
|
| 559 |
+
past_key_values=past_key_values,
|
| 560 |
+
inputs_embeds=inputs_embeds,
|
| 561 |
+
use_cache=use_cache,
|
| 562 |
+
cache_position=cache_position,
|
| 563 |
+
**kwargs,
|
| 564 |
+
)
|
| 565 |
+
slice_indices = (
|
| 566 |
+
slice(-logits_to_keep, None)
|
| 567 |
+
if isinstance(logits_to_keep, int)
|
| 568 |
+
else logits_to_keep
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
def _select_token_positions(tensor: torch.Tensor) -> torch.Tensor:
|
| 572 |
+
if isinstance(slice_indices, slice):
|
| 573 |
+
return tensor[:, slice_indices, ...]
|
| 574 |
+
if isinstance(slice_indices, torch.Tensor):
|
| 575 |
+
return tensor.index_select(1, slice_indices.to(tensor.device))
|
| 576 |
+
raise TypeError(
|
| 577 |
+
f"Unsupported index type for logits_to_keep: {type(slice_indices)}"
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
stacked_exit_pdf = None
|
| 581 |
+
if gate_list:
|
| 582 |
+
pdf_list = []
|
| 583 |
+
remaining_prob = torch.ones_like(gate_list[0].squeeze(-1))
|
| 584 |
+
for idx, gate_tensor in enumerate(gate_list):
|
| 585 |
+
lambda_i = torch.sigmoid(gate_tensor.squeeze(-1))
|
| 586 |
+
if idx < len(gate_list) - 1:
|
| 587 |
+
p_i = lambda_i * remaining_prob
|
| 588 |
+
remaining_prob = remaining_prob * (1.0 - lambda_i)
|
| 589 |
+
else:
|
| 590 |
+
p_i = remaining_prob
|
| 591 |
+
pdf_list.append(p_i)
|
| 592 |
+
stacked_exit_pdf = torch.stack(pdf_list, dim=2)
|
| 593 |
+
|
| 594 |
+
expected_logits_cache: Optional[torch.Tensor] = None
|
| 595 |
+
|
| 596 |
+
def compute_expected_logits() -> Optional[torch.Tensor]:
|
| 597 |
+
nonlocal expected_logits_cache
|
| 598 |
+
if expected_logits_cache is not None:
|
| 599 |
+
return expected_logits_cache
|
| 600 |
+
if stacked_exit_pdf is None or not hidden_states_list:
|
| 601 |
+
return None
|
| 602 |
+
token_exit_pdf = _select_token_positions(stacked_exit_pdf)
|
| 603 |
+
expected_logits = None
|
| 604 |
+
for step_idx, hidden in enumerate(hidden_states_list):
|
| 605 |
+
step_hidden = _select_token_positions(hidden)
|
| 606 |
+
step_logits = self.lm_head(step_hidden)
|
| 607 |
+
weight = (
|
| 608 |
+
token_exit_pdf[..., step_idx].unsqueeze(-1).to(step_logits.dtype)
|
| 609 |
+
)
|
| 610 |
+
expected_logits = (
|
| 611 |
+
step_logits * weight
|
| 612 |
+
if expected_logits is None
|
| 613 |
+
else expected_logits + step_logits * weight
|
| 614 |
+
)
|
| 615 |
+
expected_logits_cache = expected_logits
|
| 616 |
+
return expected_logits_cache
|
| 617 |
+
|
| 618 |
+
logits: Optional[torch.Tensor] = None
|
| 619 |
+
loss: Optional[torch.Tensor] = None
|
| 620 |
+
|
| 621 |
+
if labels is not None:
|
| 622 |
+
logits = compute_expected_logits()
|
| 623 |
+
if logits is None:
|
| 624 |
+
hidden_states = outputs.last_hidden_state
|
| 625 |
+
logits = self.lm_head(_select_token_positions(hidden_states))
|
| 626 |
+
loss = self.loss_function(
|
| 627 |
+
logits=logits,
|
| 628 |
+
labels=labels,
|
| 629 |
+
vocab_size=self.config.vocab_size,
|
| 630 |
+
**kwargs,
|
| 631 |
+
)
|
| 632 |
+
else:
|
| 633 |
+
if stacked_exit_pdf is not None and hidden_states_list:
|
| 634 |
+
if exit_at_step is not None and 0 <= exit_at_step < len(
|
| 635 |
+
hidden_states_list
|
| 636 |
+
):
|
| 637 |
+
selected_hidden = hidden_states_list[exit_at_step]
|
| 638 |
+
logits = self.lm_head(_select_token_positions(selected_hidden))
|
| 639 |
+
elif exit_threshold is not None:
|
| 640 |
+
cumulative_probs = torch.cumsum(stacked_exit_pdf, dim=2)
|
| 641 |
+
threshold_value = exit_threshold
|
| 642 |
+
if isinstance(threshold_value, torch.Tensor):
|
| 643 |
+
threshold_value = threshold_value.to(cumulative_probs.device)
|
| 644 |
+
threshold_mask = cumulative_probs >= threshold_value
|
| 645 |
+
exit_steps = torch.argmax(threshold_mask.float(), dim=2)
|
| 646 |
+
last_step_idx = stacked_exit_pdf.shape[2] - 1
|
| 647 |
+
if last_step_idx >= 0:
|
| 648 |
+
never_exceeded = ~threshold_mask.any(dim=2)
|
| 649 |
+
exit_steps[never_exceeded] = last_step_idx
|
| 650 |
+
stacked_hidden = torch.stack(hidden_states_list, dim=2)
|
| 651 |
+
gather_index = (
|
| 652 |
+
exit_steps.unsqueeze(-1)
|
| 653 |
+
.unsqueeze(-1)
|
| 654 |
+
.expand(-1, -1, 1, stacked_hidden.size(-1))
|
| 655 |
+
)
|
| 656 |
+
final_hidden_states = torch.gather(
|
| 657 |
+
stacked_hidden, 2, gather_index
|
| 658 |
+
).squeeze(2)
|
| 659 |
+
logits = self.lm_head(_select_token_positions(final_hidden_states))
|
| 660 |
+
elif use_weighted_exit:
|
| 661 |
+
logits = compute_expected_logits()
|
| 662 |
+
|
| 663 |
+
if logits is None:
|
| 664 |
+
hidden_states = outputs.last_hidden_state
|
| 665 |
+
logits = self.lm_head(_select_token_positions(hidden_states))
|
| 666 |
+
|
| 667 |
+
result = CausalLMOutputWithPast(
|
| 668 |
+
loss=loss,
|
| 669 |
+
logits=logits,
|
| 670 |
+
past_key_values=outputs.past_key_values,
|
| 671 |
+
hidden_states=outputs.hidden_states,
|
| 672 |
+
attentions=outputs.attentions,
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
return result
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
class OuroForSequenceClassification(
|
| 679 |
+
GenericForSequenceClassification, OuroPreTrainedModel
|
| 680 |
+
):
|
| 681 |
+
pass
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
class OuroForTokenClassification(GenericForTokenClassification, OuroPreTrainedModel):
|
| 685 |
+
pass
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
class OuroForQuestionAnswering(GenericForQuestionAnswering, OuroPreTrainedModel):
|
| 689 |
+
base_model_prefix = (
|
| 690 |
+
"transformer" # For BC, where `transformer` was used instead of `model`
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
__all__ = [
|
| 695 |
+
"OuroPreTrainedModel",
|
| 696 |
+
"OuroModel",
|
| 697 |
+
"OuroForCausalLM",
|
| 698 |
+
"OuroForSequenceClassification",
|
| 699 |
+
"OuroForTokenClassification",
|
| 700 |
+
"OuroForQuestionAnswering",
|
| 701 |
+
]
|
qouro/modeling_qouro.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from typing import Dict, Iterable, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
import fnmatch
|
| 9 |
+
|
| 10 |
+
from .modeling_ouro import OuroForCausalLM
|
| 11 |
+
from .quantization.modules import QuantizedLinear, SmoothQuantLinear
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _resolve_parent_module(
|
| 15 |
+
root: nn.Module, qualified_name: str
|
| 16 |
+
) -> Tuple[nn.Module | None, str]:
|
| 17 |
+
if not qualified_name:
|
| 18 |
+
return None, qualified_name
|
| 19 |
+
path = qualified_name.split(".")
|
| 20 |
+
parent = root
|
| 21 |
+
for item in path[:-1]:
|
| 22 |
+
parent = getattr(parent, item)
|
| 23 |
+
return parent, path[-1]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _collect_linear_modules(model: nn.Module) -> Iterable[Tuple[str, nn.Linear]]:
|
| 27 |
+
for name, module in model.named_modules():
|
| 28 |
+
if isinstance(module, nn.Linear):
|
| 29 |
+
yield name, module
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class OuroForCausalLMQuantized(OuroForCausalLM):
|
| 33 |
+
"""
|
| 34 |
+
Quantized variant of `OuroForCausalLM` that relies on `QuantizedLinear` modules.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, config):
|
| 38 |
+
quant_config = getattr(config, "quantization", None)
|
| 39 |
+
if quant_config is None:
|
| 40 |
+
raise ValueError(
|
| 41 |
+
"The provided config does not contain 'quantization' settings required "
|
| 42 |
+
"to instantiate OuroForCausalLMQuantized."
|
| 43 |
+
)
|
| 44 |
+
self.quantization_config = deepcopy(quant_config)
|
| 45 |
+
super().__init__(config)
|
| 46 |
+
self._replace_linear_layers()
|
| 47 |
+
|
| 48 |
+
def _replace_linear_layers(self) -> None:
|
| 49 |
+
method = str(self.quantization_config.get("method", "awq")).lower()
|
| 50 |
+
weight_bits = int(self.quantization_config.get("weight_bits", 4))
|
| 51 |
+
activation_bits = int(self.quantization_config.get("activation_bits", 8))
|
| 52 |
+
group_size = int(self.quantization_config.get("group_size", 128))
|
| 53 |
+
include_patterns = list(
|
| 54 |
+
self.quantization_config.get("include_modules", []) or []
|
| 55 |
+
)
|
| 56 |
+
exclude_patterns = list(
|
| 57 |
+
self.quantization_config.get("exclude_modules", []) or []
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
replacements = list(_collect_linear_modules(self))
|
| 61 |
+
|
| 62 |
+
# apply include/exclude filters on qualified module names
|
| 63 |
+
def _is_included(name: str) -> bool:
|
| 64 |
+
if exclude_patterns:
|
| 65 |
+
if any(fnmatch.fnmatch(name, pat) for pat in exclude_patterns):
|
| 66 |
+
return False
|
| 67 |
+
if include_patterns:
|
| 68 |
+
if not any(fnmatch.fnmatch(name, pat) for pat in include_patterns):
|
| 69 |
+
return False
|
| 70 |
+
return True
|
| 71 |
+
|
| 72 |
+
replacements = [(n, m) for (n, m) in replacements if _is_included(n)]
|
| 73 |
+
for name, module in replacements:
|
| 74 |
+
parent, attribute = _resolve_parent_module(self, name)
|
| 75 |
+
if parent is None:
|
| 76 |
+
continue
|
| 77 |
+
if method == "smoothquant":
|
| 78 |
+
quantized = SmoothQuantLinear(
|
| 79 |
+
module.in_features,
|
| 80 |
+
module.out_features,
|
| 81 |
+
weight_bits=weight_bits,
|
| 82 |
+
activation_bits=activation_bits,
|
| 83 |
+
bias=module.bias is not None,
|
| 84 |
+
)
|
| 85 |
+
else:
|
| 86 |
+
quantized = QuantizedLinear(
|
| 87 |
+
module.in_features,
|
| 88 |
+
module.out_features,
|
| 89 |
+
weight_bits=weight_bits,
|
| 90 |
+
group_size=group_size,
|
| 91 |
+
bias=module.bias is not None,
|
| 92 |
+
)
|
| 93 |
+
if module.bias is not None:
|
| 94 |
+
quantized.bias.data.copy_(module.bias.detach().to(quantized.bias.dtype))
|
| 95 |
+
setattr(parent, attribute, quantized)
|
| 96 |
+
|
| 97 |
+
def apply_quantized_weights(
|
| 98 |
+
self, weights: Dict[str, Dict[str, torch.Tensor]]
|
| 99 |
+
) -> None:
|
| 100 |
+
module_map = dict(self.named_modules())
|
| 101 |
+
for name, tensors in weights.items():
|
| 102 |
+
candidate = module_map.get(name)
|
| 103 |
+
if candidate is None or not hasattr(candidate, "load_quant_state"):
|
| 104 |
+
continue
|
| 105 |
+
try:
|
| 106 |
+
candidate.load_quant_state(**tensors)
|
| 107 |
+
except TypeError as exc:
|
| 108 |
+
raise ValueError(
|
| 109 |
+
f"Failed to load quantized tensors for module '{name}': {exc}"
|
| 110 |
+
) from exc
|
qouro/quantization/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .config import CalibrationConfig, QuantizationConfig
|
| 2 |
+
from .pipeline import run_quantization_pipeline
|
| 3 |
+
|
| 4 |
+
__all__ = ["CalibrationConfig", "QuantizationConfig", "run_quantization_pipeline"]
|
qouro/quantization/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (357 Bytes). View file
|
|
|
qouro/quantization/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (337 Bytes). View file
|
|
|
qouro/quantization/__pycache__/awq_core.cpython-311.pyc
ADDED
|
Binary file (5.26 kB). View file
|
|
|
qouro/quantization/__pycache__/awq_core.cpython-312.pyc
ADDED
|
Binary file (4.96 kB). View file
|
|
|
qouro/quantization/__pycache__/calibration.cpython-311.pyc
ADDED
|
Binary file (4.5 kB). View file
|
|
|
qouro/quantization/__pycache__/calibration.cpython-312.pyc
ADDED
|
Binary file (4.15 kB). View file
|
|
|
qouro/quantization/__pycache__/config.cpython-311.pyc
ADDED
|
Binary file (3 kB). View file
|
|
|
qouro/quantization/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (3.03 kB). View file
|
|
|
qouro/quantization/__pycache__/modules.cpython-311.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
qouro/quantization/__pycache__/modules.cpython-312.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
qouro/quantization/__pycache__/observers.cpython-311.pyc
ADDED
|
Binary file (3.92 kB). View file
|
|
|
qouro/quantization/__pycache__/observers.cpython-312.pyc
ADDED
|
Binary file (3.56 kB). View file
|
|
|
qouro/quantization/__pycache__/pipeline.cpython-311.pyc
ADDED
|
Binary file (8.03 kB). View file
|
|
|
qouro/quantization/__pycache__/pipeline.cpython-312.pyc
ADDED
|
Binary file (7.07 kB). View file
|
|
|
qouro/quantization/__pycache__/smoothquant.cpython-311.pyc
ADDED
|
Binary file (5.29 kB). View file
|
|
|
qouro/quantization/__pycache__/smoothquant.cpython-312.pyc
ADDED
|
Binary file (4.88 kB). View file
|
|
|
qouro/quantization/awq_core.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Dict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
from .config import QuantizationConfig
|
| 10 |
+
from .observers import ObserverState
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class QuantizedWeights:
|
| 15 |
+
"""Holds quantized weight representations for a linear layer."""
|
| 16 |
+
|
| 17 |
+
weight: Tensor
|
| 18 |
+
weight_scales: Tensor
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _prepare_importance_vector(
|
| 22 |
+
observer_state: ObserverState,
|
| 23 |
+
in_features: int,
|
| 24 |
+
device: torch.device,
|
| 25 |
+
epsilon: float,
|
| 26 |
+
) -> Tensor:
|
| 27 |
+
stats = observer_state.max_abs_values.to(device=device, dtype=torch.float32)
|
| 28 |
+
if stats.numel() < in_features:
|
| 29 |
+
stats = torch.nn.functional.pad(stats, (0, in_features - stats.numel()), value=1.0)
|
| 30 |
+
|
| 31 |
+
stats = stats[:in_features]
|
| 32 |
+
stats = stats.clamp_min(epsilon)
|
| 33 |
+
return stats
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def quantize_linear(
|
| 37 |
+
module: nn.Linear,
|
| 38 |
+
observer_state: ObserverState,
|
| 39 |
+
config: QuantizationConfig,
|
| 40 |
+
) -> QuantizedWeights:
|
| 41 |
+
"""
|
| 42 |
+
Quantize a linear layer's weights using group-wise symmetric quantization.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
weight = module.weight.detach().to(torch.float32).clone()
|
| 46 |
+
device = weight.device
|
| 47 |
+
in_features = module.in_features
|
| 48 |
+
out_features = module.out_features
|
| 49 |
+
group_size = config.group_size
|
| 50 |
+
bits = config.weight_bits
|
| 51 |
+
qmin = -(2 ** (bits - 1))
|
| 52 |
+
qmax = (2 ** (bits - 1)) - 1
|
| 53 |
+
num_groups = (in_features + group_size - 1) // group_size
|
| 54 |
+
|
| 55 |
+
importance = _prepare_importance_vector(
|
| 56 |
+
observer_state, in_features, device, config.epsilon
|
| 57 |
+
)
|
| 58 |
+
if config.activation_clip is not None:
|
| 59 |
+
importance = importance.clamp(max=config.activation_clip)
|
| 60 |
+
|
| 61 |
+
quant_dtype = torch.int8 if config.weight_bits <= 8 else torch.int16
|
| 62 |
+
quantized = torch.zeros_like(weight, dtype=quant_dtype, device=device)
|
| 63 |
+
weight_scales = torch.zeros(
|
| 64 |
+
(out_features, num_groups), dtype=torch.float32, device=device
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
for group_idx in range(num_groups):
|
| 68 |
+
start = group_idx * group_size
|
| 69 |
+
end = min((group_idx + 1) * group_size, in_features)
|
| 70 |
+
weight_block = weight[:, start:end]
|
| 71 |
+
importance_block = importance[start:end]
|
| 72 |
+
|
| 73 |
+
weighted_block = weight_block * importance_block.unsqueeze(0)
|
| 74 |
+
max_abs = weighted_block.abs().amax(dim=1)
|
| 75 |
+
scale = (max_abs / qmax).clamp_min(config.epsilon)
|
| 76 |
+
dequant_scale = scale.unsqueeze(1)
|
| 77 |
+
|
| 78 |
+
quant_block = torch.round(weight_block / dequant_scale)
|
| 79 |
+
quant_block = quant_block.clamp(qmin, qmax)
|
| 80 |
+
|
| 81 |
+
quantized[:, start:end] = quant_block.to(quant_dtype)
|
| 82 |
+
weight_scales[:, group_idx] = scale
|
| 83 |
+
|
| 84 |
+
return QuantizedWeights(weight=quantized.cpu(), weight_scales=weight_scales.cpu())
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def summarize_quantization(
|
| 88 |
+
stats: Dict[str, QuantizedWeights]
|
| 89 |
+
) -> Dict[str, Dict[str, float]]:
|
| 90 |
+
"""
|
| 91 |
+
Generate simple per-layer statistics to debug quantization quality.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
summary: Dict[str, Dict[str, float]] = {}
|
| 95 |
+
for name, record in stats.items():
|
| 96 |
+
scale = record.weight_scales
|
| 97 |
+
summary[name] = {
|
| 98 |
+
"scale_min": float(scale.min()),
|
| 99 |
+
"scale_max": float(scale.max()),
|
| 100 |
+
"scale_mean": float(scale.mean()),
|
| 101 |
+
}
|
| 102 |
+
return summary
|
qouro/quantization/calibration.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Iterable, Iterator, List
|
| 4 |
+
|
| 5 |
+
from datasets import IterableDataset, load_dataset
|
| 6 |
+
from loguru import logger
|
| 7 |
+
from torch import device as TorchDevice
|
| 8 |
+
from transformers import PreTrainedTokenizerBase
|
| 9 |
+
|
| 10 |
+
from .config import CalibrationConfig
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def collect_calibration_texts(config: CalibrationConfig) -> List[str]:
|
| 14 |
+
"""
|
| 15 |
+
Fetch calibration samples from a Hugging Face dataset.
|
| 16 |
+
|
| 17 |
+
Returns a list of raw text prompts that will be consumed by the calibration loop.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
if config.sample_count <= 0:
|
| 21 |
+
logger.warning("Calibration requested with zero samples; skipping collection.")
|
| 22 |
+
return []
|
| 23 |
+
|
| 24 |
+
logger.info(
|
| 25 |
+
f"Loading calibration dataset '{config.dataset_name}' "
|
| 26 |
+
f"(split={config.dataset_split}, streaming={config.streaming})..."
|
| 27 |
+
)
|
| 28 |
+
try:
|
| 29 |
+
dataset = load_dataset(
|
| 30 |
+
config.dataset_name,
|
| 31 |
+
split=config.dataset_split,
|
| 32 |
+
streaming=config.streaming,
|
| 33 |
+
)
|
| 34 |
+
except Exception as exc: # noqa: BLE001 - surface dataset issues to the caller
|
| 35 |
+
logger.warning(
|
| 36 |
+
f"Unable to load dataset '{config.dataset_name}': {exc}"
|
| 37 |
+
)
|
| 38 |
+
return []
|
| 39 |
+
|
| 40 |
+
if isinstance(dataset, IterableDataset):
|
| 41 |
+
iterator: Iterable[dict] = dataset
|
| 42 |
+
samples: List[str] = []
|
| 43 |
+
for example in iterator:
|
| 44 |
+
text = example.get(config.text_column)
|
| 45 |
+
if not text:
|
| 46 |
+
continue
|
| 47 |
+
samples.append(str(text))
|
| 48 |
+
if len(samples) >= config.sample_count:
|
| 49 |
+
break
|
| 50 |
+
return samples
|
| 51 |
+
|
| 52 |
+
if len(dataset) == 0:
|
| 53 |
+
logger.warning(f"Dataset '{config.dataset_name}' returned no rows.")
|
| 54 |
+
return []
|
| 55 |
+
|
| 56 |
+
upper = min(config.sample_count, len(dataset))
|
| 57 |
+
if config.shuffle:
|
| 58 |
+
dataset = dataset.shuffle(seed=config.seed)
|
| 59 |
+
selected = dataset.select(range(upper))
|
| 60 |
+
texts = []
|
| 61 |
+
for entry in selected:
|
| 62 |
+
text = entry.get(config.text_column)
|
| 63 |
+
if not isinstance(text, str):
|
| 64 |
+
continue
|
| 65 |
+
texts.append(text)
|
| 66 |
+
if not texts:
|
| 67 |
+
logger.warning(
|
| 68 |
+
f"Failed to collect calibration texts from column '{config.text_column}'."
|
| 69 |
+
)
|
| 70 |
+
return texts
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def iter_tokenized_batches(
|
| 74 |
+
tokenizer: PreTrainedTokenizerBase,
|
| 75 |
+
texts: Iterable[str],
|
| 76 |
+
device: TorchDevice,
|
| 77 |
+
batch_size: int,
|
| 78 |
+
max_length: int,
|
| 79 |
+
) -> Iterator[dict]:
|
| 80 |
+
"""
|
| 81 |
+
Yield tokenized calibration inputs suitable for feeding into the model.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
if batch_size <= 0:
|
| 85 |
+
raise ValueError("Batch size must be at least 1 for calibration.")
|
| 86 |
+
|
| 87 |
+
buffer: List[str] = []
|
| 88 |
+
for text in texts:
|
| 89 |
+
buffer.append(text)
|
| 90 |
+
if len(buffer) < batch_size:
|
| 91 |
+
continue
|
| 92 |
+
|
| 93 |
+
batch_inputs = tokenizer(
|
| 94 |
+
buffer,
|
| 95 |
+
padding=True,
|
| 96 |
+
truncation=True,
|
| 97 |
+
max_length=max_length,
|
| 98 |
+
return_tensors="pt",
|
| 99 |
+
).to(device)
|
| 100 |
+
yield batch_inputs
|
| 101 |
+
buffer.clear()
|
| 102 |
+
|
| 103 |
+
if buffer:
|
| 104 |
+
batch_inputs = tokenizer(
|
| 105 |
+
buffer,
|
| 106 |
+
padding=True,
|
| 107 |
+
truncation=True,
|
| 108 |
+
max_length=max_length,
|
| 109 |
+
return_tensors="pt",
|
| 110 |
+
).to(device)
|
| 111 |
+
yield batch_inputs
|
qouro/quantization/config.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field, asdict
|
| 4 |
+
from typing import Dict, List
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass
|
| 8 |
+
class CalibrationConfig:
|
| 9 |
+
"""Settings that govern how calibration samples are collected."""
|
| 10 |
+
|
| 11 |
+
dataset_name: str = "mit-han-lab/pile-val-backup"
|
| 12 |
+
dataset_split: str = "validation"
|
| 13 |
+
text_column: str = "text"
|
| 14 |
+
sample_count: int = 128
|
| 15 |
+
max_sequence_length: int = 512
|
| 16 |
+
batch_size: int = 8
|
| 17 |
+
shuffle: bool = False
|
| 18 |
+
streaming: bool = False
|
| 19 |
+
seed: int = 0
|
| 20 |
+
|
| 21 |
+
def to_dict(self) -> Dict[str, int | str | bool]:
|
| 22 |
+
return asdict(self)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class QuantizationConfig:
|
| 27 |
+
"""Configuration for quantization pipelines (AWQ, SmoothQuant, etc.)."""
|
| 28 |
+
|
| 29 |
+
enabled: bool = True
|
| 30 |
+
method: str = "awq"
|
| 31 |
+
weight_bits: int = 4
|
| 32 |
+
activation_bits: int = 8
|
| 33 |
+
group_size: int = 128
|
| 34 |
+
per_channel: bool = True
|
| 35 |
+
calibration: CalibrationConfig = field(default_factory=CalibrationConfig)
|
| 36 |
+
activation_clip: float | None = None
|
| 37 |
+
epsilon: float = 1e-5
|
| 38 |
+
alpha: float = 0.5
|
| 39 |
+
# module name filters (glob patterns allowed), applied on qualified names from named_modules()
|
| 40 |
+
include_modules: List[str] = field(default_factory=list)
|
| 41 |
+
exclude_modules: List[str] = field(default_factory=list)
|
| 42 |
+
|
| 43 |
+
def to_dict(self) -> Dict[str, int | float | bool | Dict[str, int | str | bool]]:
|
| 44 |
+
return {
|
| 45 |
+
"enabled": self.enabled,
|
| 46 |
+
"method": self.method,
|
| 47 |
+
"weight_bits": self.weight_bits,
|
| 48 |
+
"activation_bits": self.activation_bits,
|
| 49 |
+
"group_size": self.group_size,
|
| 50 |
+
"per_channel": self.per_channel,
|
| 51 |
+
"calibration": self.calibration.to_dict(),
|
| 52 |
+
"activation_clip": self.activation_clip,
|
| 53 |
+
"epsilon": self.epsilon,
|
| 54 |
+
"alpha": self.alpha,
|
| 55 |
+
"include_modules": list(self.include_modules),
|
| 56 |
+
"exclude_modules": list(self.exclude_modules),
|
| 57 |
+
}
|
qouro/quantization/modules.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _select_quant_dtype(bits: int) -> torch.dtype:
|
| 11 |
+
if bits <= 0:
|
| 12 |
+
raise ValueError("Quantization bits must be positive.")
|
| 13 |
+
if bits <= 8:
|
| 14 |
+
return torch.int8
|
| 15 |
+
if bits <= 16:
|
| 16 |
+
return torch.int16
|
| 17 |
+
raise ValueError("Quantization bits above 16 are not supported.")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class QuantizedLinear(nn.Module):
|
| 21 |
+
"""Weight-only linear layer with per-group scales."""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
in_features: int,
|
| 26 |
+
out_features: int,
|
| 27 |
+
*,
|
| 28 |
+
weight_bits: int = 4,
|
| 29 |
+
group_size: int = 128,
|
| 30 |
+
bias: bool = True,
|
| 31 |
+
) -> None:
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.in_features = in_features
|
| 34 |
+
self.out_features = out_features
|
| 35 |
+
self.weight_bits = weight_bits
|
| 36 |
+
self.group_size = group_size
|
| 37 |
+
self.qmin = -(2 ** (weight_bits - 1))
|
| 38 |
+
self.qmax = (2 ** (weight_bits - 1)) - 1
|
| 39 |
+
self.num_groups = math.ceil(in_features / group_size)
|
| 40 |
+
self.quant_dtype = _select_quant_dtype(weight_bits)
|
| 41 |
+
|
| 42 |
+
weight_shape = (out_features, in_features)
|
| 43 |
+
scale_shape = (out_features, self.num_groups)
|
| 44 |
+
self.register_buffer("weight", torch.zeros(weight_shape, dtype=self.quant_dtype))
|
| 45 |
+
self.register_buffer(
|
| 46 |
+
"weight_scales", torch.ones(scale_shape, dtype=torch.float32)
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None
|
| 50 |
+
self._weight_cache: Optional[Tensor] = None
|
| 51 |
+
|
| 52 |
+
def _invalidate_cache(self) -> None:
|
| 53 |
+
self._weight_cache = None
|
| 54 |
+
|
| 55 |
+
def refresh_weight_cache(self) -> None:
|
| 56 |
+
self._weight_cache = self._dequantize_weight()
|
| 57 |
+
|
| 58 |
+
def _dequantize_weight(self) -> Tensor:
|
| 59 |
+
group_tensors = []
|
| 60 |
+
for group_idx in range(self.num_groups):
|
| 61 |
+
start = group_idx * self.group_size
|
| 62 |
+
end = min((group_idx + 1) * self.group_size, self.in_features)
|
| 63 |
+
block = self.weight[:, start:end].float()
|
| 64 |
+
scale = self.weight_scales[:, group_idx].unsqueeze(1)
|
| 65 |
+
group_tensors.append(block * scale)
|
| 66 |
+
return torch.cat(group_tensors, dim=1)
|
| 67 |
+
|
| 68 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 69 |
+
if self._weight_cache is None or self._weight_cache.device != input.device:
|
| 70 |
+
self.refresh_weight_cache()
|
| 71 |
+
self._weight_cache = self._weight_cache.to(input.device)
|
| 72 |
+
|
| 73 |
+
weight = self._weight_cache
|
| 74 |
+
if weight.dtype != input.dtype:
|
| 75 |
+
weight = weight.to(input.dtype)
|
| 76 |
+
|
| 77 |
+
bias = self.bias
|
| 78 |
+
if bias is not None and bias.device != input.device:
|
| 79 |
+
bias = bias.to(input.device)
|
| 80 |
+
if bias is not None and bias.dtype != input.dtype:
|
| 81 |
+
bias = bias.to(input.dtype)
|
| 82 |
+
|
| 83 |
+
return nn.functional.linear(input, weight, bias)
|
| 84 |
+
|
| 85 |
+
def load_quant_state(self, weight: Tensor, weight_scales: Tensor) -> None:
|
| 86 |
+
if weight.shape != self.weight.shape:
|
| 87 |
+
raise ValueError(
|
| 88 |
+
f"Quantized weight shape mismatch: expected {tuple(self.weight.shape)}, "
|
| 89 |
+
f"got {tuple(weight.shape)}"
|
| 90 |
+
)
|
| 91 |
+
if weight_scales.shape != self.weight_scales.shape:
|
| 92 |
+
raise ValueError(
|
| 93 |
+
f"Scale tensor shape mismatch: expected {tuple(self.weight_scales.shape)}, "
|
| 94 |
+
f"got {tuple(weight_scales.shape)}"
|
| 95 |
+
)
|
| 96 |
+
self.weight.copy_(weight.to(dtype=self.quant_dtype))
|
| 97 |
+
self.weight_scales.copy_(weight_scales.to(dtype=torch.float32))
|
| 98 |
+
self._invalidate_cache()
|
| 99 |
+
|
| 100 |
+
def extra_repr(self) -> str:
|
| 101 |
+
return (
|
| 102 |
+
f"in_features={self.in_features}, out_features={self.out_features}, "
|
| 103 |
+
f"group_size={self.group_size}, bits={self.weight_bits}, bias={self.bias is not None}"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class SmoothQuantLinear(nn.Module):
|
| 108 |
+
"""Linear layer with SmoothQuant W8A8 (or configurable) quantization."""
|
| 109 |
+
|
| 110 |
+
def __init__(
|
| 111 |
+
self,
|
| 112 |
+
in_features: int,
|
| 113 |
+
out_features: int,
|
| 114 |
+
*,
|
| 115 |
+
weight_bits: int = 8,
|
| 116 |
+
activation_bits: int = 8,
|
| 117 |
+
bias: bool = True,
|
| 118 |
+
) -> None:
|
| 119 |
+
super().__init__()
|
| 120 |
+
if weight_bits <= 0 or weight_bits > 16:
|
| 121 |
+
raise ValueError("Weight bits must be in range [1, 16].")
|
| 122 |
+
if activation_bits <= 0 or activation_bits > 16:
|
| 123 |
+
raise ValueError("Activation bits must be in range [1, 16].")
|
| 124 |
+
self.in_features = in_features
|
| 125 |
+
self.out_features = out_features
|
| 126 |
+
self.weight_bits = weight_bits
|
| 127 |
+
self.activation_bits = activation_bits
|
| 128 |
+
self.weight_qmin = -(2 ** (weight_bits - 1))
|
| 129 |
+
self.weight_qmax = (2 ** (weight_bits - 1)) - 1
|
| 130 |
+
self.activation_qmin = -(2 ** (activation_bits - 1))
|
| 131 |
+
self.activation_qmax = (2 ** (activation_bits - 1)) - 1
|
| 132 |
+
self.quant_dtype = _select_quant_dtype(weight_bits)
|
| 133 |
+
|
| 134 |
+
weight_shape = (out_features, in_features)
|
| 135 |
+
self.register_buffer("weight", torch.zeros(weight_shape, dtype=self.quant_dtype))
|
| 136 |
+
self.register_buffer(
|
| 137 |
+
"weight_scales", torch.ones(out_features, 1, dtype=torch.float32)
|
| 138 |
+
)
|
| 139 |
+
self.register_buffer(
|
| 140 |
+
"input_scale", torch.ones(in_features, dtype=torch.float32)
|
| 141 |
+
)
|
| 142 |
+
self.register_buffer(
|
| 143 |
+
"activation_scale", torch.ones(in_features, dtype=torch.float32)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None
|
| 147 |
+
self._weight_cache: Optional[Tensor] = None
|
| 148 |
+
|
| 149 |
+
def _invalidate_cache(self) -> None:
|
| 150 |
+
self._weight_cache = None
|
| 151 |
+
|
| 152 |
+
def refresh_weight_cache(self) -> None:
|
| 153 |
+
weight = self.weight.float() * self.weight_scales
|
| 154 |
+
self._weight_cache = weight
|
| 155 |
+
|
| 156 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 157 |
+
if self._weight_cache is None or self._weight_cache.device != input.device:
|
| 158 |
+
self.refresh_weight_cache()
|
| 159 |
+
self._weight_cache = self._weight_cache.to(input.device)
|
| 160 |
+
|
| 161 |
+
activation_scale = self.activation_scale.to(input.device)
|
| 162 |
+
input_scale = self.input_scale.to(input.device)
|
| 163 |
+
|
| 164 |
+
scaled_input = input * input_scale
|
| 165 |
+
quantized = torch.round(scaled_input / activation_scale).clamp(
|
| 166 |
+
self.activation_qmin, self.activation_qmax
|
| 167 |
+
)
|
| 168 |
+
dequant_input = quantized * activation_scale
|
| 169 |
+
|
| 170 |
+
weight = self._weight_cache
|
| 171 |
+
if weight.dtype != dequant_input.dtype:
|
| 172 |
+
weight = weight.to(dequant_input.dtype)
|
| 173 |
+
|
| 174 |
+
bias = self.bias
|
| 175 |
+
if bias is not None and bias.device != input.device:
|
| 176 |
+
bias = bias.to(input.device)
|
| 177 |
+
if bias is not None and bias.dtype != dequant_input.dtype:
|
| 178 |
+
bias = bias.to(dequant_input.dtype)
|
| 179 |
+
|
| 180 |
+
return nn.functional.linear(dequant_input, weight, bias)
|
| 181 |
+
|
| 182 |
+
def load_quant_state(
|
| 183 |
+
self,
|
| 184 |
+
weight: Tensor,
|
| 185 |
+
weight_scales: Tensor,
|
| 186 |
+
input_scale: Tensor,
|
| 187 |
+
activation_scale: Tensor,
|
| 188 |
+
) -> None:
|
| 189 |
+
if weight.shape != self.weight.shape:
|
| 190 |
+
raise ValueError(
|
| 191 |
+
f"Quantized weight shape mismatch: expected {tuple(self.weight.shape)}, "
|
| 192 |
+
f"got {tuple(weight.shape)}"
|
| 193 |
+
)
|
| 194 |
+
if weight_scales.shape != self.weight_scales.shape:
|
| 195 |
+
raise ValueError(
|
| 196 |
+
f"Weight scale shape mismatch: expected {tuple(self.weight_scales.shape)}, "
|
| 197 |
+
f"got {tuple(weight_scales.shape)}"
|
| 198 |
+
)
|
| 199 |
+
if input_scale.shape != self.input_scale.shape:
|
| 200 |
+
raise ValueError(
|
| 201 |
+
f"Input scale shape mismatch: expected {tuple(self.input_scale.shape)}, "
|
| 202 |
+
f"got {tuple(input_scale.shape)}"
|
| 203 |
+
)
|
| 204 |
+
if activation_scale.shape != self.activation_scale.shape:
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f"Activation scale shape mismatch: expected {tuple(self.activation_scale.shape)}, "
|
| 207 |
+
f"got {tuple(activation_scale.shape)}"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
self.weight.copy_(weight.to(dtype=self.quant_dtype))
|
| 211 |
+
self.weight_scales.copy_(weight_scales.to(dtype=torch.float32))
|
| 212 |
+
self.input_scale.copy_(input_scale.to(dtype=torch.float32))
|
| 213 |
+
self.activation_scale.copy_(activation_scale.to(dtype=torch.float32))
|
| 214 |
+
self._invalidate_cache()
|
| 215 |
+
|
| 216 |
+
def extra_repr(self) -> str:
|
| 217 |
+
return (
|
| 218 |
+
f"in_features={self.in_features}, out_features={self.out_features}, "
|
| 219 |
+
f"weight_bits={self.weight_bits}, activation_bits={self.activation_bits}, "
|
| 220 |
+
f"bias={self.bias is not None}"
|
| 221 |
+
)
|
qouro/quantization/observers.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class ObserverState:
|
| 12 |
+
"""Activation statistics collected for a linear layer."""
|
| 13 |
+
|
| 14 |
+
max_abs_values: Tensor
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class LinearInputObserver:
|
| 18 |
+
"""
|
| 19 |
+
Collects per-feature activation maxima for a `nn.Linear` module.
|
| 20 |
+
|
| 21 |
+
The statistics are later used to derive quantization scales that take input
|
| 22 |
+
distribution into account, mimicking the behaviour of AWQ.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, module_name: str):
|
| 26 |
+
self.module_name = module_name
|
| 27 |
+
self._max_abs: Optional[Tensor] = None
|
| 28 |
+
|
| 29 |
+
def __call__(self, module: nn.Module, inputs: tuple[Tensor, ...]) -> None:
|
| 30 |
+
if not inputs:
|
| 31 |
+
return
|
| 32 |
+
|
| 33 |
+
data = inputs[0]
|
| 34 |
+
if data is None:
|
| 35 |
+
return
|
| 36 |
+
|
| 37 |
+
if data.dim() > 2:
|
| 38 |
+
data = data.reshape(-1, data.size(-1))
|
| 39 |
+
elif data.dim() < 2:
|
| 40 |
+
data = data.unsqueeze(0)
|
| 41 |
+
|
| 42 |
+
data = data.detach()
|
| 43 |
+
if data.dtype in (torch.float16, torch.bfloat16):
|
| 44 |
+
data = data.to(torch.float32)
|
| 45 |
+
|
| 46 |
+
max_vals = data.abs().amax(dim=0)
|
| 47 |
+
if self._max_abs is None:
|
| 48 |
+
self._max_abs = max_vals
|
| 49 |
+
else:
|
| 50 |
+
# Pad in case dimensionality changes due to mixed inputs.
|
| 51 |
+
if max_vals.size(0) != self._max_abs.size(0):
|
| 52 |
+
target = max(self._max_abs.size(0), max_vals.size(0))
|
| 53 |
+
self._max_abs = torch.nn.functional.pad(
|
| 54 |
+
self._max_abs,
|
| 55 |
+
(0, target - self._max_abs.size(0)),
|
| 56 |
+
value=0.0,
|
| 57 |
+
)
|
| 58 |
+
max_vals = torch.nn.functional.pad(
|
| 59 |
+
max_vals,
|
| 60 |
+
(0, target - max_vals.size(0)),
|
| 61 |
+
value=0.0,
|
| 62 |
+
)
|
| 63 |
+
self._max_abs = torch.maximum(self._max_abs, max_vals)
|
| 64 |
+
|
| 65 |
+
def to_state(self) -> ObserverState:
|
| 66 |
+
if self._max_abs is None:
|
| 67 |
+
raise RuntimeError(
|
| 68 |
+
f"No activation statistics recorded for module '{self.module_name}'."
|
| 69 |
+
)
|
| 70 |
+
return ObserverState(max_abs_values=self._max_abs)
|
| 71 |
+
|
qouro/quantization/pipeline.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
from typing import Dict, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from loguru import logger
|
| 8 |
+
from torch import nn
|
| 9 |
+
from transformers import PreTrainedModel, PreTrainedTokenizerBase
|
| 10 |
+
|
| 11 |
+
from .awq_core import QuantizedWeights, quantize_linear, summarize_quantization
|
| 12 |
+
from .calibration import collect_calibration_texts, iter_tokenized_batches
|
| 13 |
+
from .config import QuantizationConfig
|
| 14 |
+
from .observers import LinearInputObserver
|
| 15 |
+
from .smoothquant import (
|
| 16 |
+
SmoothQuantWeights,
|
| 17 |
+
quantize_linear_smooth,
|
| 18 |
+
summarize_smoothquant,
|
| 19 |
+
)
|
| 20 |
+
from ..modeling_qouro import OuroForCausalLMQuantized
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _gather_linear_modules(model: nn.Module) -> Dict[str, nn.Linear]:
|
| 24 |
+
return {
|
| 25 |
+
name: module
|
| 26 |
+
for name, module in model.named_modules()
|
| 27 |
+
if isinstance(module, nn.Linear)
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _attach_observers(
|
| 32 |
+
modules: Dict[str, nn.Linear],
|
| 33 |
+
) -> Tuple[Dict[str, LinearInputObserver], list[torch.utils.hooks.RemovableHandle]]:
|
| 34 |
+
observers: Dict[str, LinearInputObserver] = {}
|
| 35 |
+
handles: list[torch.utils.hooks.RemovableHandle] = []
|
| 36 |
+
for name, module in modules.items():
|
| 37 |
+
observer = LinearInputObserver(name)
|
| 38 |
+
handle = module.register_forward_pre_hook(observer)
|
| 39 |
+
observers[name] = observer
|
| 40 |
+
handles.append(handle)
|
| 41 |
+
return observers, handles
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _detach_handles(handles: list[torch.utils.hooks.RemovableHandle]) -> None:
|
| 45 |
+
for handle in handles:
|
| 46 |
+
handle.remove()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def run_quantization_pipeline(
|
| 50 |
+
base_model: PreTrainedModel,
|
| 51 |
+
tokenizer: PreTrainedTokenizerBase,
|
| 52 |
+
device: torch.device,
|
| 53 |
+
config: QuantizationConfig,
|
| 54 |
+
) -> Tuple[OuroForCausalLMQuantized, Dict[str, Dict[str, float]]]:
|
| 55 |
+
|
| 56 |
+
if not config.enabled:
|
| 57 |
+
raise ValueError("Quantization pipeline requested while disabled in config.")
|
| 58 |
+
|
| 59 |
+
calibration_texts = collect_calibration_texts(config.calibration)
|
| 60 |
+
if not calibration_texts:
|
| 61 |
+
raise RuntimeError(
|
| 62 |
+
"Unable to collect calibration texts; aborting quantization."
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
linear_modules = _gather_linear_modules(base_model)
|
| 66 |
+
if not linear_modules:
|
| 67 |
+
raise RuntimeError("No linear modules found in model; cannot quantize.")
|
| 68 |
+
|
| 69 |
+
observers, handles = _attach_observers(linear_modules)
|
| 70 |
+
base_model.eval()
|
| 71 |
+
|
| 72 |
+
logger.info(f"Running calibration with {len(calibration_texts)} texts...")
|
| 73 |
+
with torch.no_grad():
|
| 74 |
+
for batch_inputs in iter_tokenized_batches(
|
| 75 |
+
tokenizer=tokenizer,
|
| 76 |
+
texts=calibration_texts,
|
| 77 |
+
device=device,
|
| 78 |
+
batch_size=config.calibration.batch_size,
|
| 79 |
+
max_length=config.calibration.max_sequence_length,
|
| 80 |
+
):
|
| 81 |
+
base_model(**batch_inputs)
|
| 82 |
+
|
| 83 |
+
_detach_handles(handles)
|
| 84 |
+
|
| 85 |
+
method = config.method.lower()
|
| 86 |
+
|
| 87 |
+
observer_states: Dict[str, LinearInputObserver] = {}
|
| 88 |
+
for name, observer in observers.items():
|
| 89 |
+
observer_states[name] = observer
|
| 90 |
+
|
| 91 |
+
quantized_payload: Dict[str, Dict[str, torch.Tensor]] = {}
|
| 92 |
+
summary: Dict[str, Dict[str, float]] = {}
|
| 93 |
+
|
| 94 |
+
if method == "awq":
|
| 95 |
+
awq_weights: Dict[str, QuantizedWeights] = {}
|
| 96 |
+
for name, module in linear_modules.items():
|
| 97 |
+
observer = observer_states.get(name)
|
| 98 |
+
if observer is None:
|
| 99 |
+
continue
|
| 100 |
+
try:
|
| 101 |
+
state = observer.to_state()
|
| 102 |
+
except RuntimeError as exc:
|
| 103 |
+
logger.warning(f"Skipping module '{name}': {exc}")
|
| 104 |
+
continue
|
| 105 |
+
awq_weights[name] = quantize_linear(module, state, config)
|
| 106 |
+
|
| 107 |
+
logger.info(f"Quantized {len(awq_weights)} linear modules with AWQ.")
|
| 108 |
+
|
| 109 |
+
for name, record in awq_weights.items():
|
| 110 |
+
quantized_payload[name] = {
|
| 111 |
+
"weight": record.weight,
|
| 112 |
+
"weight_scales": record.weight_scales,
|
| 113 |
+
}
|
| 114 |
+
summary = summarize_quantization(awq_weights)
|
| 115 |
+
elif method == "smoothquant":
|
| 116 |
+
smooth_weights: Dict[str, SmoothQuantWeights] = {}
|
| 117 |
+
for name, module in linear_modules.items():
|
| 118 |
+
observer = observer_states.get(name)
|
| 119 |
+
if observer is None:
|
| 120 |
+
continue
|
| 121 |
+
try:
|
| 122 |
+
state = observer.to_state()
|
| 123 |
+
except RuntimeError as exc:
|
| 124 |
+
logger.warning(f"Skipping module '{name}': {exc}")
|
| 125 |
+
continue
|
| 126 |
+
smooth_weights[name] = quantize_linear_smooth(module, state, config)
|
| 127 |
+
|
| 128 |
+
logger.info(f"Quantized {len(smooth_weights)} linear modules with SmoothQuant.")
|
| 129 |
+
|
| 130 |
+
for name, record in smooth_weights.items():
|
| 131 |
+
quantized_payload[name] = {
|
| 132 |
+
"weight": record.weight,
|
| 133 |
+
"weight_scales": record.weight_scales,
|
| 134 |
+
"input_scale": record.input_scale,
|
| 135 |
+
"activation_scale": record.activation_scale,
|
| 136 |
+
}
|
| 137 |
+
summary = summarize_smoothquant(smooth_weights)
|
| 138 |
+
else:
|
| 139 |
+
raise ValueError(f"Unsupported quantization method '{config.method}'.")
|
| 140 |
+
|
| 141 |
+
quant_config_dict = config.to_dict()
|
| 142 |
+
quantized_config = copy.deepcopy(base_model.config)
|
| 143 |
+
quantized_config.quantization = quant_config_dict
|
| 144 |
+
quantized_config.architectures = ["OuroForCausalLMQuantized"]
|
| 145 |
+
quantized_config.auto_map = {
|
| 146 |
+
"AutoModelForCausalLM": "qouro.modeling_qouro::OuroForCausalLMQuantized"
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
quantized_model = OuroForCausalLMQuantized(quantized_config)
|
| 150 |
+
|
| 151 |
+
float_state = base_model.state_dict()
|
| 152 |
+
missing, unexpected = quantized_model.load_state_dict(float_state, strict=False)
|
| 153 |
+
if unexpected:
|
| 154 |
+
logger.debug(f"Unexpected keys during transfer: {unexpected}")
|
| 155 |
+
if missing:
|
| 156 |
+
logger.debug(f"Missing keys during transfer: {missing}")
|
| 157 |
+
|
| 158 |
+
quantized_model.apply_quantized_weights(quantized_payload)
|
| 159 |
+
quantized_model.to(device)
|
| 160 |
+
quantized_model.eval()
|
| 161 |
+
|
| 162 |
+
return quantized_model, summary
|
qouro/quantization/smoothquant.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Dict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
from .config import QuantizationConfig
|
| 10 |
+
from .observers import ObserverState
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class SmoothQuantWeights:
|
| 15 |
+
"""Quantized representation for SmoothQuant linear layers."""
|
| 16 |
+
|
| 17 |
+
weight: Tensor
|
| 18 |
+
weight_scales: Tensor
|
| 19 |
+
input_scale: Tensor
|
| 20 |
+
activation_scale: Tensor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _prepare_stats(
|
| 24 |
+
observer_state: ObserverState,
|
| 25 |
+
weight: Tensor,
|
| 26 |
+
epsilon: float,
|
| 27 |
+
) -> tuple[Tensor, Tensor]:
|
| 28 |
+
activation_stats = observer_state.max_abs_values.to(dtype=torch.float32)
|
| 29 |
+
if activation_stats.numel() < weight.size(1):
|
| 30 |
+
activation_stats = torch.nn.functional.pad(
|
| 31 |
+
activation_stats,
|
| 32 |
+
(0, weight.size(1) - activation_stats.numel()),
|
| 33 |
+
value=1.0,
|
| 34 |
+
)
|
| 35 |
+
activation_stats = activation_stats[: weight.size(1)]
|
| 36 |
+
activation_stats = activation_stats.clamp_min(epsilon)
|
| 37 |
+
|
| 38 |
+
weight_stats = weight.abs().amax(dim=0).clamp_min(epsilon)
|
| 39 |
+
return activation_stats, weight_stats
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def quantize_linear_smooth(
|
| 43 |
+
module: nn.Linear,
|
| 44 |
+
observer_state: ObserverState,
|
| 45 |
+
config: QuantizationConfig,
|
| 46 |
+
) -> SmoothQuantWeights:
|
| 47 |
+
"""
|
| 48 |
+
Apply SmoothQuant to a linear layer, producing int quantized weights and activation scales.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
weight_bits = config.weight_bits
|
| 52 |
+
activation_bits = config.activation_bits
|
| 53 |
+
epsilon = config.epsilon
|
| 54 |
+
alpha = config.alpha
|
| 55 |
+
quant_dtype = torch.int8 if weight_bits <= 8 else torch.int16
|
| 56 |
+
|
| 57 |
+
weight = module.weight.detach().to(torch.float32).clone()
|
| 58 |
+
activation_stats, weight_stats = _prepare_stats(observer_state, weight, epsilon)
|
| 59 |
+
|
| 60 |
+
ratio = activation_stats / weight_stats
|
| 61 |
+
smoothing_factor = torch.pow(ratio, alpha).clamp_min(epsilon)
|
| 62 |
+
|
| 63 |
+
input_scale = (1.0 / smoothing_factor).to(torch.float32)
|
| 64 |
+
scaled_weight = weight * smoothing_factor.unsqueeze(0)
|
| 65 |
+
|
| 66 |
+
act_max_scaled = activation_stats * input_scale
|
| 67 |
+
act_qmax = (2 ** (activation_bits - 1)) - 1
|
| 68 |
+
activation_scale = (act_max_scaled / act_qmax).clamp_min(epsilon)
|
| 69 |
+
|
| 70 |
+
weight_qmax = (2 ** (weight_bits - 1)) - 1
|
| 71 |
+
weight_max = scaled_weight.abs().amax(dim=1).clamp_min(epsilon)
|
| 72 |
+
weight_scales = (weight_max / weight_qmax).unsqueeze(1)
|
| 73 |
+
|
| 74 |
+
quantized_weight = torch.round(scaled_weight / weight_scales).clamp(
|
| 75 |
+
-(2 ** (weight_bits - 1)), weight_qmax
|
| 76 |
+
).to(quant_dtype)
|
| 77 |
+
|
| 78 |
+
return SmoothQuantWeights(
|
| 79 |
+
weight=quantized_weight.cpu(),
|
| 80 |
+
weight_scales=weight_scales.to(torch.float32).cpu(),
|
| 81 |
+
input_scale=input_scale.cpu(),
|
| 82 |
+
activation_scale=activation_scale.cpu(),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def summarize_smoothquant(
|
| 87 |
+
stats: Dict[str, SmoothQuantWeights]
|
| 88 |
+
) -> Dict[str, Dict[str, float]]:
|
| 89 |
+
summary: Dict[str, Dict[str, float]] = {}
|
| 90 |
+
for name, record in stats.items():
|
| 91 |
+
summary[name] = {
|
| 92 |
+
"weight_scale_mean": float(record.weight_scales.mean()),
|
| 93 |
+
"activation_scale_mean": float(record.activation_scale.mean()),
|
| 94 |
+
}
|
| 95 |
+
return summary
|