From 2a3812311d6ec54bb66b661a78ffb36cc0dc9a6a Mon Sep 17 00:00:00 2001 From: LoserCheems <3314685395@qq.com> Date: Sun, 26 Jan 2025 01:31:16 +0800 Subject: [PATCH 01/20] Add Doge Model --- docs/source/en/_toctree.yml | 2 + docs/source/en/index.md | 1 + docs/source/en/model_doc/doge.md | 39 + docs/source/en/perf_infer_gpu_one.md | 1 + src/transformers/__init__.py | 16 + src/transformers/models/__init__.py | 1 + .../models/auto/configuration_auto.py | 2 + src/transformers/models/auto/modeling_auto.py | 3 + src/transformers/models/doge/__init__.py | 28 + .../models/doge/configuration_doge.py | 229 ++++ src/transformers/models/doge/modeling_doge.py | 1169 +++++++++++++++++ src/transformers/utils/dummy_pt_objects.py | 28 + tests/models/doge/__init__.py | 0 tests/models/doge/test_modeling_doge.py | 383 ++++++ tests/utils/test_cache_utils.py | 16 + 15 files changed, 1918 insertions(+) create mode 100644 docs/source/en/model_doc/doge.md create mode 100644 src/transformers/models/doge/__init__.py create mode 100644 src/transformers/models/doge/configuration_doge.py create mode 100644 src/transformers/models/doge/modeling_doge.py create mode 100644 tests/models/doge/__init__.py create mode 100644 tests/models/doge/test_modeling_doge.py diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 34aacd0796a3..d4f17b57e78b 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -388,6 +388,8 @@ title: DiffLlama - local: model_doc/distilbert title: DistilBERT + - local: model_doc/doge + title: Doge - local: model_doc/dpr title: DPR - local: model_doc/electra diff --git a/docs/source/en/index.md b/docs/source/en/index.md index 7d6a9c188d40..d3babf8cbf7e 100644 --- a/docs/source/en/index.md +++ b/docs/source/en/index.md @@ -131,6 +131,7 @@ Flax), PyTorch, and/or TensorFlow. | [DINOv2 with Registers](model_doc/dinov2_with_registers) | ✅ | ❌ | ❌ | | [DistilBERT](model_doc/distilbert) | ✅ | ✅ | ✅ | | [DiT](model_doc/dit) | ✅ | ❌ | ✅ | +| [Doge](model_doc/doge) | ✅ | ❌ | ❌ | | [DonutSwin](model_doc/donut) | ✅ | ❌ | ❌ | | [DPR](model_doc/dpr) | ✅ | ✅ | ❌ | | [DPT](model_doc/dpt) | ✅ | ❌ | ❌ | diff --git a/docs/source/en/model_doc/doge.md b/docs/source/en/model_doc/doge.md new file mode 100644 index 000000000000..aa131ae48b5d --- /dev/null +++ b/docs/source/en/model_doc/doge.md @@ -0,0 +1,39 @@ + + +# Doge + + +## Overview + +Doge is a series of small language models based on the [Doge](https://github.com/LoserCheems/WonderfulMatrices) architecture, aiming to combine the advantages of state-space and self-attention algorithms, calculate dynamic masks from cached value states using the zero-order hold method, and solve the problem of existing mainstream language models getting lost in context. It uses the `wsd_scheduler` scheduler to pre-train on the `smollm-corpus`, and can continue training on new datasets or add sparse activation feedforward networks from stable stage checkpoints. + +Checkout all Doge model checkpoints [here](https://huggingface.co/collections/JingzeShi/doge-slm-677fd879f8c4fd0f43e05458). + + +## DogeConfig + +[[autodoc]] DogeConfig + +## DogeModel + +[[autodoc]] DogeModel + - forward + +## DogeForCausalLM + +[[autodoc]] DogeForCausalLM + - forward diff --git a/docs/source/en/perf_infer_gpu_one.md b/docs/source/en/perf_infer_gpu_one.md index 0003784c585e..04ccd5da4adb 100644 --- a/docs/source/en/perf_infer_gpu_one.md +++ b/docs/source/en/perf_infer_gpu_one.md @@ -246,6 +246,7 @@ For now, Transformers supports SDPA inference and training for the following arc * [Dinov2](https://huggingface.co/docs/transformers/en/model_doc/dinov2) * [Dinov2_with_registers](https://huggingface.co/docs/transformers/en/model_doc/dinov2) * [DistilBert](https://huggingface.co/docs/transformers/model_doc/distilbert#transformers.DistilBertModel) +* [Doge](https://huggingface.co/docs/transformers/model_doc/doge#transformers.DogeModel) * [Dpr](https://huggingface.co/docs/transformers/model_doc/dpr#transformers.DprReader) * [EncoderDecoder](https://huggingface.co/docs/transformers/model_doc/encoder_decoder#transformers.EncoderDecoderModel) * [Emu3](https://huggingface.co/docs/transformers/model_doc/emu3) diff --git a/src/transformers/__init__.py b/src/transformers/__init__.py index 3493634db516..75d4bddcb4e5 100755 --- a/src/transformers/__init__.py +++ b/src/transformers/__init__.py @@ -410,6 +410,7 @@ "DistilBertTokenizer", ], "models.dit": [], + "models.doge": ["DogeConfig"], "models.donut": [ "DonutProcessor", "DonutSwinConfig", @@ -2210,6 +2211,14 @@ "DistilBertPreTrainedModel", ] ) + _import_structure["models.doge"].extend( + [ + "DogeForCausalLM", + "DogeForSequenceClassification", + "DogeModel", + "DogePreTrainedModel", + ] + ) _import_structure["models.donut"].extend( [ "DonutSwinModel", @@ -5463,6 +5472,7 @@ DistilBertConfig, DistilBertTokenizer, ) + from .models.doge import DogeConfig from .models.donut import ( DonutProcessor, DonutSwinConfig, @@ -7158,6 +7168,12 @@ DistilBertModel, DistilBertPreTrainedModel, ) + from .models.doge import ( + DogeForCausalLM, + DogeForSequenceClassification, + DogeModel, + DogePreTrainedModel, + ) from .models.donut import ( DonutSwinModel, DonutSwinPreTrainedModel, diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index f196cedd3d23..8994af9350c3 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -81,6 +81,7 @@ dinov2_with_registers, distilbert, dit, + doge, donut, dpr, dpt, diff --git a/src/transformers/models/auto/configuration_auto.py b/src/transformers/models/auto/configuration_auto.py index f4590c81c7d5..c3321fc236d4 100644 --- a/src/transformers/models/auto/configuration_auto.py +++ b/src/transformers/models/auto/configuration_auto.py @@ -97,6 +97,7 @@ ("dinov2", "Dinov2Config"), ("dinov2_with_registers", "Dinov2WithRegistersConfig"), ("distilbert", "DistilBertConfig"), + ("doge", "DogeConfig"), ("donut-swin", "DonutSwinConfig"), ("dpr", "DPRConfig"), ("dpt", "DPTConfig"), @@ -419,6 +420,7 @@ ("dinov2_with_registers", "DINOv2 with Registers"), ("distilbert", "DistilBERT"), ("dit", "DiT"), + ("doge", "Doge"), ("donut-swin", "DonutSwin"), ("dpr", "DPR"), ("dpt", "DPT"), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index a3029bf650a9..ee8edf2af194 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -95,6 +95,7 @@ ("dinov2", "Dinov2Model"), ("dinov2_with_registers", "Dinov2WithRegistersModel"), ("distilbert", "DistilBertModel"), + ("doge", "DogeModel"), ("donut-swin", "DonutSwinModel"), ("dpr", "DPRQuestionEncoder"), ("dpt", "DPTModel"), @@ -500,6 +501,7 @@ ("ctrl", "CTRLLMHeadModel"), ("data2vec-text", "Data2VecTextForCausalLM"), ("dbrx", "DbrxForCausalLM"), + ("doge", "DogeForCausalLM"), ("diffllama", "DiffLlamaForCausalLM"), ("electra", "ElectraForCausalLM"), ("emu3", "Emu3ForCausalLM"), @@ -976,6 +978,7 @@ ("data2vec-text", "Data2VecTextForSequenceClassification"), ("deberta", "DebertaForSequenceClassification"), ("deberta-v2", "DebertaV2ForSequenceClassification"), + ("doge", "DogeForSequenceClassification"), ("diffllama", "DiffLlamaForSequenceClassification"), ("distilbert", "DistilBertForSequenceClassification"), ("electra", "ElectraForSequenceClassification"), diff --git a/src/transformers/models/doge/__init__.py b/src/transformers/models/doge/__init__.py new file mode 100644 index 000000000000..27c74499bf45 --- /dev/null +++ b/src/transformers/models/doge/__init__.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_doge import * + from .modeling_doge import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py new file mode 100644 index 000000000000..b2550e6dbcf7 --- /dev/null +++ b/src/transformers/models/doge/configuration_doge.py @@ -0,0 +1,229 @@ +# coding=utf-8 +# Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on the Wonderful Matrices paper implementation. +# The Doge family of small language models is trained by Jingze Shi. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch Doge model configuration""" + +from transformers.configuration_utils import PretrainedConfig +from transformers.modeling_rope_utils import rope_config_validation + + +class DogeConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge + model according to the specified arguments, defining the model architecture like [JingzeShi/Doge-20M](https://huggingface.co/JingzeShi/Doge-20M). + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + Args: + vocab_size (`int`, *optional*, defaults to 32768): + Vocabulary size of the Doge model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`DogeModel`] + hidden_size (`int`, *optional*, defaults to 1024): + Dimension of the hidden representations. + intermediate_size (`int`, *optional*, defaults to 2048): + Dimension of the MLP representations. + num_hidden_layers (`int`, *optional*, defaults to 32): + Number of hidden layers in the Transformer decoder. + hidden_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in the hidden layers. + hidden_dropout (`float`, *optional*, defaults to 0.0): + Dropout probability for each sequence transformation and state transformation module. + hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): + The non-linear activation function (function or string) in the decoder. + max_position_embeddings (`int`, *optional*, defaults to 2048): + The maximum sequence length that this model might ever be used with. + rope_theta (`float`, *optional*, defaults to 10000.0): + The base period of the RoPE embeddings. + rope_scaling (`Dict`, *optional*): + Dictionary containing the scaling configuration for the RoPE embeddings. + NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. + Expected contents: + `rope_type` (`str`): + The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. + `factor` (`float`, *optional*): + Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. + In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. + `original_max_position_embeddings` (`int`, *optional*): + Used with 'dynamic', 'longrope' and 'llama3'. + The original max position embeddings used during pretraining. + `attention_factor` (`float`, *optional*): + Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention + computation. + If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. + `beta_fast` (`float`, *optional*): + Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear + ramp function. If unspecified, it defaults to 32. + `beta_slow` (`float`, *optional*): + Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear + ramp function. If unspecified, it defaults to 1. + `short_factor` (`List[float]`, *optional*): + Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`). + Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 + `long_factor` (`List[float]`, *optional*): + Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`). + Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 + `low_freq_factor` (`float`, *optional*): + Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE + `high_freq_factor` (`float`, *optional*): + Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + rms_norm_eps (`float`, *optional*, defaults to 1e-06): + The epsilon used by the rms normalization layers. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions (not used by all models). Only + relevant if `config.is_decoder=True`. + pad_token_id (`int`, *optional*, defaults to 0): + Padding token id. + bos_token_id (`int`, *optional*, defaults to 1): + Beginning of stream token id. + eos_token_id (`int`, *optional*, defaults to 2): + End of stream token id. + tie_word_embeddings (`bool`, *optional*, defaults to `True`): + Whether to tie weight embeddings + num_attention_heads (`int`, *optional*, defaults to 8): + Number of attention heads for each attention layer in the Transformer decoder. + num_key_value_heads (`int`, *optional*, defaults to `None`): + This is the number of key_value heads that should be used to implement Grouped Query Attention. + If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if + `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. + When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. + For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). + If it is not specified, will default to `num_attention_heads`. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + dynamic_mask_ratio (`float`, *optional*, defaults to 0.0, range [0, 1]): + The ratio to control the proportion of the dynamic mask filled with the minimum value. For more details checkout [this paper](https://arxiv.org/pdf/2412.11834). + is_moe (`bool`, *optional*, defaults to `False`): + Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize. For more details checkout [this paper](https://arxiv.org/pdf/2412.11834). + num_cdmoe_experts (`int`, *optional*, defaults to 16348): + Number of Experts for the Cross Domain Mixture of Experts. calculation formula: :math:`\text{num_cdmoe_experts} = (32 \times \text{num_cdmoe_heads})^2` + num_cdmoe_heads (`int`, *optional*, defaults to 4): + Number of retrieval heads, used to mix multi-head experts. + num_cdmoe_experts_per_head (`int`, *optional*, defaults to 8): + Number of Experts per retrieval head, used to mix multi-head experts. + expert_retrieval_size (`int`, *optional*, defaults to 64): + Dimension of the Expert retrieval states for calculating the dot product of query and key to determine the expert index. + + ```python + >>> from transformers import DogeConfig, DogeModel + + >>> # Initializing a Doge-320M style configuration + >>> configuration = DogeConfig() + + >>> # Initializing a model from the Doge-320M style configuration + >>> model = DogeModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "doge" + keys_to_ignore_at_inference = ["past_key_values"] + # Default tensor parallel plan for base model `DogeModel` + base_model_tp_plan = { + "layers.*.self_attn.q_proj": "colwise", + "layers.*.self_attn.k_proj": "colwise", + "layers.*.self_attn.v_proj": "colwise", + "layers.*.self_attn.dt_proj": "colwise", + "layers.*.self_attn.o_proj": "rowwise", + "layers.*.mlp.gate_proj": "colwise", + "layers.*.mlp.up_proj": "colwise", + "layers.*.mlp.down_proj": "rowwise", + } + + def __init__( + self, + vocab_size=32768, + hidden_size=1024, + intermediate_size=2048, + num_hidden_layers=32, + hidden_bias=False, + hidden_dropout=0.0, + hidden_act="silu", + max_position_embeddings=2048, + rope_theta=10000.0, + rope_scaling={ + "rope_type": "dynamic", + "factor": 4.0, + "original_max_position_embeddings": 2048, + }, + initializer_range=0.02, + rms_norm_eps=1e-06, + use_cache=True, + bos_token_id=0, + eos_token_id=1, + pad_token_id=2, + tie_word_embeddings=True, + num_attention_heads=8, + num_key_value_heads=None, + attention_dropout=0.0, + dynamic_mask_ratio=0.0, + is_moe=False, + num_cdmoe_experts=16348, + num_cdmoe_heads=4, + num_cdmoe_experts_per_head=8, + expert_retrieval_size=64, + **kwargs, + ): + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.hidden_bias = hidden_bias + self.hidden_dropout = hidden_dropout + self.hidden_act = hidden_act + self.max_position_embeddings = max_position_embeddings + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling + self.initializer_range = initializer_range + self.rms_norm_eps = rms_norm_eps + self.use_cache = use_cache + self.bos_token_id = bos_token_id + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.tie_word_embeddings = tie_word_embeddings + self.num_attention_heads = num_attention_heads + self.num_key_value_heads = num_key_value_heads + self.attention_dropout = attention_dropout + self.dynamic_mask_ratio = dynamic_mask_ratio + self.is_moe = is_moe + self.num_cdmoe_experts = num_cdmoe_experts + self.num_cdmoe_heads = num_cdmoe_heads + self.num_cdmoe_experts_per_head = num_cdmoe_experts_per_head + self.expert_retrieval_size = expert_retrieval_size + + # Validate the correctness of rotary position embeddings parameters + # BC: if there is a 'type' field, copy it it to 'rope_type'. + if self.rope_scaling is not None and "type" in self.rope_scaling: + self.rope_scaling["rope_type"] = self.rope_scaling["type"] + rope_config_validation(self) + + # for backward compatibility + if num_key_value_heads is None: + self.num_key_value_heads = num_attention_heads + + super().__init__( + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + pad_token_id=pad_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + +__all__ = ["DogeConfig"] diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py new file mode 100644 index 000000000000..f23bf25e365e --- /dev/null +++ b/src/transformers/models/doge/modeling_doge.py @@ -0,0 +1,1169 @@ +# coding=utf-8 +# Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on the Wonderful Matrices paper implementation. +# The Doge family of small language models is trained by Jingze Shi. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch Doge model.""" + +import math +from typing import Callable, List, Optional, Tuple, Union + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn + +from ...activations import ACT2FN +from ...cache_utils import Cache, DynamicCache, StaticCache +from ...generation import GenerationMixin +from ...modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + SequenceClassifierOutputWithPast, +) +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS +from ...modeling_utils import PreTrainedModel +from ...processing_utils import Unpack +from ...utils import ( + LossKwargs, + add_start_docstrings, + add_start_docstrings_to_model_forward, + is_torch_flex_attn_available, + logging, + replace_return_docstrings, +) +from .configuration_doge import DogeConfig + +try: + from einx import add as einx_add +except ImportError: + einx_add = None + +if is_torch_flex_attn_available(): + from torch.nn.attention.flex_attention import flex_attention + + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "DogeConfig" + + +class RMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + RMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class Residual(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + + def forward(self, residual_states, hidden_states): + return self.weight * residual_states + hidden_states + + def extra_repr(self): + return f"{tuple(self.weight.shape)}" + + +class RotaryEmbedding(nn.Module): + def __init__(self, config: Optional[DogeConfig] = None): + super().__init__() + self.rope_kwargs = {} + + if config.rope_scaling is not None: + self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) + else: + self.rope_type = "default" + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + self.base = config.rope_theta + + self.config = config + self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + + inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self.original_inv_freq = self.inv_freq + + def _dynamic_frequency_update(self, position_ids, device): + """ + dynamic RoPE layers should recompute `inv_freq` in the following situations: + 1 - growing beyond the cached sequence length (allow scaling) + 2 - the current sequence length is in the original scale (avoid losing precision with small sequences) + """ + seq_len = torch.max(position_ids) + 1 + if seq_len > self.max_seq_len_cached: # growth + inv_freq, self.attention_scaling = self.rope_init_fn( + self.config, device, seq_len=seq_len, **self.rope_kwargs + ) + self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation + self.max_seq_len_cached = seq_len + + if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset + self.register_buffer("inv_freq", self.original_inv_freq, persistent=False) + self.max_seq_len_cached = self.original_max_seq_len + + @torch.no_grad() + def forward(self, x, position_ids): + if "dynamic" in self.rope_type: + self._dynamic_frequency_update(position_ids, device=x.device) + + # core RoPE block + inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) + position_ids_expanded = position_ids[:, None, :].float() + # Force float32 (see https://github.com/huggingface/transformers/pull/29285) + device_type = x.device.type + device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" + with torch.autocast(device_type=device_type, enabled=False): + freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() + sin = emb.sin() + + # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention + cos = cos * self.attention_scaling + sin = sin * self.attention_scaling + + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + +def rotate_half(x): + """ + Rotates half the hidden dims of the input. + """ + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + position_ids (`torch.Tensor`, *optional*): + Deprecated and unused. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. + For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. + Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. + Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). + The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +class DogeDynamicMaskAttention(nn.Module): + """Dynamic Mask Attention from 'Wonderful Matrices' paper.""" + + def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.head_dim = config.hidden_size // config.num_attention_heads + self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads + self.scaling = self.head_dim ** -0.5 + self.attention_dropout = config.attention_dropout + self.dynamic_mask_ratio = config.dynamic_mask_ratio + + self.ALL_ATTENTION_FUNCTIONS = { + "eager": self.eager_attention_forward, + "flex_attention": self.flex_attention_forward, + "sdpa": self.sdpa_attention_forward, + } + + # Q K V O projections + self.q_proj = nn.Linear( + config.hidden_size, + config.num_attention_heads * self.head_dim, + bias=config.hidden_bias + ) + self.k_proj = nn.Linear( + config.hidden_size, + config.num_key_value_heads * self.head_dim, + bias=config.hidden_bias + ) + self.v_proj = nn.Linear( + config.hidden_size, + config.num_key_value_heads * self.head_dim, + bias=config.hidden_bias + ) + # dynamic mask for the QK^T attention score matrix + self.A = nn.Parameter( + torch.zeros(config.num_attention_heads) + ) + self.dt_proj = nn.Linear( + config.num_key_value_heads * self.head_dim, + config.num_attention_heads, + bias=config.hidden_bias + ) + self.o_proj = nn.Linear( + config.num_attention_heads * self.head_dim, + config.hidden_size, + bias=config.hidden_bias + ) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: Tuple[torch.Tensor, torch.Tensor], + attention_mask: Optional[torch.Tensor] = None, + past_key_value: Optional[Cache] = None, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[Cache]]: + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, self.head_dim) + + query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) + key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) + value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) + + cos, sin = position_embeddings + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; cache_position needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # calculate dynamic mask from value_states + dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)) + dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) + attn_mask = self.prepare_dynamic_mask( + hidden_states=hidden_states, + dynamic_mask=dynamic_mask, + dynamic_mask_ratio=self.dynamic_mask_ratio, + attention_mask=attention_mask, + ) + + attention_interface: Callable = self.eager_attention_forward + if self.config._attn_implementation != "eager": + attention_interface = self.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] + + attn_output = attention_interface( + query_states, + key_states, + value_states, + attention_mask=attn_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + attn_output = self.o_proj(attn_output) + return attn_output + + def prepare_dynamic_mask( + self, + hidden_states: torch.Tensor, + dynamic_mask: torch.Tensor, + dynamic_mask_ratio: float = 0.0, + attention_mask: Optional[torch.Tensor] = None, + ): + """ + Combine `dynamic_mask` with `attention_mask` to generate the final `attn_mask`. + + Args: + hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision. + dynamic_mask (`torch.Tensor`): dynamic mask of shape `(batch_size, num_heads, key_sequence_length)`. + dynamic_mask_ratio (`float`, *optional*): Ratio from 0.0 to 1.0 used to control the proportion of the dynamic mask filled with the minimum value. + attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`. + """ + attn_mask = None + if dynamic_mask is not None: + attn_mask = dynamic_mask[:, :, None, :] + if 0.0 < dynamic_mask_ratio < 1.0: + min_type = torch.finfo(hidden_states.dtype).min + num_dynamic_mask = int(attn_mask.shape[-1] * dynamic_mask_ratio) + if num_dynamic_mask > 0: + rate_value = torch.kthvalue(attn_mask, num_dynamic_mask, dim=-1, keepdim=True).values + attn_mask = attn_mask.masked_fill(attn_mask < rate_value, min_type) + if attention_mask is not None: + attn_mask = attn_mask + attention_mask[:, :, :, : attn_mask.shape[-1]] + else: + attn_mask = attention_mask + + return attn_mask + + def eager_attention_forward( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, + ) -> torch.Tensor: + key_states = repeat_kv(key, self.num_key_value_groups) + value_states = repeat_kv(value, self.num_key_value_groups) + + # compute attention scores matrix + attn_weights = torch.matmul(query, key_states.transpose(-1, -2)) * scaling + if attention_mask is not None: + causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] + attn_weights = attn_weights + causal_mask + + # upcast attention scores to fp32 + attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = F.dropout(attn_weights, p=dropout, training=self.training) + + # apply attention scores to value states + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output + + def sdpa_attention_forward( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, + ) -> torch.Tensor: + key = repeat_kv(key, self.num_key_value_groups) + value = repeat_kv(value, self.num_key_value_groups) + + causal_mask = attention_mask + if attention_mask is not None: + causal_mask = causal_mask[:, :, :, : key.shape[-2]] + + # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions + # Reference: https://github.com/pytorch/pytorch/issues/112577. + query = query.contiguous() + key = key.contiguous() + value = value.contiguous() + + # NOTE: As of pytorch 2.5.1, cuDNN's SDPA backward pass is still incorrect, so we disable cuDNN SDPA (see https://github.com/pytorch/pytorch/issues/138581) + torch.backends.cuda.enable_cudnn_sdp(False) + attn_output = F.scaled_dot_product_attention( + query, + key, + value, + attn_mask=causal_mask, + dropout_p=dropout, + scale=scaling, + ) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output + + def flex_attention_forward( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, + ) -> torch.Tensor: + key = repeat_kv(key, self.num_key_value_groups) + value = repeat_kv(value, self.num_key_value_groups) + + causal_mask = attention_mask + if attention_mask is not None: + causal_mask = causal_mask[:, :, :, : key.shape[-2]] + + # TODO: flex_attention: As of pytorch 2.5.1, captured buffers that require grad are not yet supported. + # NOTE: So we only use flex_attention in inference mode. + def causal_mod(score, batch, head, q_idx, kv_idx): + score = score + causal_mask[batch][0][q_idx][kv_idx] + return score + + def dynamic_mod(score, batch, head, q_idx, kv_idx): + score = score + causal_mask[batch][head][q_idx][kv_idx] + return score + + mask_mod = causal_mod if self.is_causal else dynamic_mod + + attn_output = flex_attention( + query, + key, + value, + score_mod=mask_mod, + scale=scaling, + ) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output + + +class DogeMLP(nn.Module): + + def __init__(self, config: DogeConfig): + super().__init__() + self.hidden_dim = config.hidden_size + self.intermediate_dim = config.intermediate_size + self.act_fn = ACT2FN[config.hidden_act] + + self.gate_proj = nn.Linear(self.hidden_dim, self.intermediate_dim, bias=config.hidden_bias) + self.up_proj = nn.Linear(self.hidden_dim, self.intermediate_dim, bias=config.hidden_bias) + self.down_proj = nn.Linear(self.intermediate_dim, self.hidden_dim, bias=config.hidden_bias) + + def forward( + self, + hidden_states: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) + return hidden_states + + +class DogeCDMoE(DogeMLP): + """Cross Domain Mixture of Experts from 'Wonderful Matrices' paper.""" + + def __init__(self, config: DogeConfig): + super().__init__(config) + self.hidden_dim = config.hidden_size + self.act_fn = ACT2FN[config.hidden_act] + + self.expert_retrieval_dim = config.expert_retrieval_size + self.num_cdmoe_experts = config.num_cdmoe_experts + self.num_cdmoe_heads = config.num_cdmoe_heads + self.num_cdmoe_experts_per_head = config.num_cdmoe_experts_per_head + self.num_keys = int(math.sqrt(self.num_cdmoe_experts)) + + # queries and keys for retrieval experts + self.queries = nn.Linear(self.hidden_dim, self.num_cdmoe_heads * self.expert_retrieval_dim, bias=False) + self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.num_keys, 2, self.expert_retrieval_dim // 2)) + + # experts + self.down_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) + self.up_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) + + def forward( + self, + hidden_states: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + bsz, seq_len, _ = hidden_states.shape + + # get similarity with queries and keys + queries = self.queries(hidden_states) + queries = queries.view(bsz, seq_len, 2, self.num_cdmoe_heads, -1).permute(2, 0, 1, 3, 4) + sim = torch.einsum("p b t h n, h k p n -> p b t h k", queries, self.keys) + + # get experts with the highest similarity + (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmoe_experts_per_head, dim=-1) + if einx_add is not None: + all_scores = einx_add("... i, ... j -> ... (i j)", scores_x, scores_y) + all_indices = einx_add("... i, ... j -> ... (i j)", indices_x * self.num_keys, indices_y) + else: + all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) + all_scores = all_scores.view(*scores_x.shape[:-1], -1) + all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) + all_indices = all_indices.view(*indices_x.shape[:-1], -1) + scores, pk_indices = all_scores.topk(self.num_cdmoe_experts_per_head, dim=-1) + indices = all_indices.gather(-1, pk_indices) + down_embed = self.down_embed(indices) + up_embed = self.up_embed(indices) + + # mix experts states with cross domain states + experts_weights = torch.einsum("b t d, b t h k d -> b t h k", hidden_states, down_embed) + experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) + experts_states = torch.einsum("b t h k, b t h k d -> b t d", experts_weights, up_embed) + hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) + hidden_states = hidden_states + experts_states + return hidden_states + + +class DogeDecoderLayer(nn.Module): + def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): + super().__init__() + self.hidden_dropout = config.hidden_dropout + + self.pre_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.self_attn = DogeDynamicMaskAttention(config=config, layer_idx=layer_idx) + self.pre_residual = Residual(config.hidden_size) + + self.post_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.feed_forward = DogeMLP(config) if config.is_moe == False else DogeCDMoE(config) + self.post_residual = Residual(config.hidden_size) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + cache_position: Optional[torch.LongTensor] = None, + position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC + **kwargs, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + + # sequence transformation + residual = hidden_states + hidden_states = self.pre_layernorm(hidden_states) + hidden_states = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + cache_position=cache_position, + position_embeddings=position_embeddings, + **kwargs, + ) + self_attn_weights = None + hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training) + hidden_states = self.pre_residual(residual, hidden_states) + + # state transformation + residual = hidden_states + hidden_states = self.post_layernorm(hidden_states) + hidden_states = self.feed_forward(hidden_states) + hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training) + hidden_states = self.post_residual(residual, hidden_states) + + outputs = (hidden_states,) + if output_attentions: + outputs += (self_attn_weights,) + + return outputs + + +DOGE_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`DogeConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" +@add_start_docstrings( + "The bare Doge Model outputting raw hidden-states without any specific head on top.", + DOGE_START_DOCSTRING, +) +class DogePreTrainedModel(PreTrainedModel): + config_class = DogeConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["DogeDecoderLayer"] + _skip_keys_device_placement = ["past_key_values"] + _supports_sdpa = True + _supports_flex_attn = True + _supports_cache_class = True + _supports_quantized_cache = True + _supports_static_cache = True + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, (nn.Linear)): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + +DOGE_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): + Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` + returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. + + Two formats are allowed: + - a [`~cache_utils.Cache`] instance, see our + [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache); + - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy + cache format. + + The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the + legacy cache format will be returned. + + If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't + have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` + of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): + Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, + this tensor is not affected by padding. It is used to update the cache in the correct position and to infer + the complete sequence length. +""" + + +@add_start_docstrings( + "The bare Doge Model outputting raw hidden-states without any specific head on top.", + DOGE_START_DOCSTRING, +) +class DogeModel(DogePreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DogeDecoderLayer`] + + Args: + config: DogeConfig + """ + + def __init__(self, config: DogeConfig): + super().__init__(config) + self.config = config + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.rotary_emb = RotaryEmbedding(config) + self.layers = nn.ModuleList( + [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.gradient_checkpointing = False + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.word_embed + + def set_input_embeddings(self, value): + self.word_embed = value + + @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You cannot specify both input_ids and inputs_embeds") + + if self.gradient_checkpointing and self.training and use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + if inputs_embeds is None: + inputs_embeds = self.word_embed(input_ids) + + if use_cache and past_key_values is None: + past_key_values = DynamicCache() + + if cache_position is None: + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + cache_position = torch.arange( + past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device + ) + + if position_ids is None: + position_ids = cache_position.unsqueeze(0) + + causal_mask = self._update_causal_mask( + attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions + ) + + hidden_states = inputs_embeds + + # create position embeddings to be shared across the decoder layers + position_embeddings = self.rotary_emb(hidden_states, position_ids) + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + + for decoder_layer in self.layers[: self.config.num_hidden_layers]: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + decoder_layer.__call__, + hidden_states, + causal_mask, + position_ids, + past_key_values, + output_attentions, + use_cache, + cache_position, + position_embeddings, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=causal_mask, + position_ids=position_ids, + past_key_value=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + cache_position=cache_position, + position_embeddings=position_embeddings, + **kwargs, + ) + + hidden_states = layer_outputs[0] + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + hidden_states = self.final_layernorm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + output = BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values if use_cache else None, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + return output if return_dict else output.to_tuple() + + def _update_causal_mask( + self, + attention_mask: torch.Tensor, + input_tensor: torch.Tensor, + cache_position: torch.Tensor, + past_key_values: Cache, + output_attentions: bool, + ): + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + using_static_cache = isinstance(past_key_values, StaticCache) + + dtype, device = input_tensor.dtype, input_tensor.device + sequence_length = input_tensor.shape[1] + if using_static_cache: + target_length = past_key_values.get_max_cache_shape() + else: + target_length = ( + attention_mask.shape[-1] + if isinstance(attention_mask, torch.Tensor) + else past_seen_tokens + sequence_length + 1 + ) + + # in case the provided `attention` mask is 2D, we generate a causal mask here (4D). + causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( + attention_mask=attention_mask, + sequence_length=sequence_length, + target_length=target_length, + dtype=dtype, + device=device, + cache_position=cache_position, + batch_size=input_tensor.shape[0], + ) + + return causal_mask + + @staticmethod + def _prepare_4d_causal_attention_mask_with_cache_position( + attention_mask: torch.Tensor = None, + sequence_length: int = None, + target_length: int = None, + dtype: torch.dtype = None, + device: torch.device = None, + cache_position: torch.Tensor = None, + batch_size: int = None, + **kwargs, + ): + """ + Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape + `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. + + Args: + attention_mask (`torch.Tensor`): + A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape + `(batch_size, 1, query_length, key_value_length)`. + sequence_length (`int`): + The sequence length being processed. + target_length (`int`): + The target length: when generating with static cache, the mask should be as long as the static cache, + to account for the 0 padding, the part of the cache that is not filled yet. + dtype (`torch.dtype`): + The dtype to use for the 4D attention mask. + device (`torch.device`): + The device to plcae the 4D attention mask on. + cache_position (`torch.Tensor`): + Indices depicting the position of the input sequence tokens in the sequence. + batch_size (`torch.Tensor`): + Batch size. + """ + if attention_mask is not None and attention_mask.dim() == 4: + # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. + causal_mask = attention_mask + else: + min_dtype = torch.finfo(dtype).min + causal_mask = torch.full( + (sequence_length, target_length), + fill_value=min_dtype, dtype=dtype, device=device, + ) + if sequence_length != 1: + causal_mask = torch.triu(causal_mask, diagonal=1) + causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) + causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) + if attention_mask is not None: + causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit + mask_length = attention_mask.shape[-1] + padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] + padding_mask = padding_mask == 0 + causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( + padding_mask, min_dtype + ) + + return causal_mask + + +class KwargsForCausalLM(LossKwargs): ... + + +class DogeForCausalLM(DogePreTrainedModel, GenerationMixin): + _tied_weights_keys = ["lm_head.weight"] + _tp_plan = {"lm_head": "colwise_rep"} + + def __init__(self, config: DogeConfig): + super().__init__(config) + self.config = config + self.model = DogeModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.word_embed + + def set_input_embeddings(self, value): + self.model.word_embed = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def get_decoder(self): + return self.model + + def set_decoder(self, decoder): + self.model = decoder + + @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + num_logits_to_keep: int = 0, + **kwargs: Unpack[KwargsForCausalLM], + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + num_logits_to_keep (`int`, *optional*): + Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, AutoModelForCausalLM + + >>> model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M-Instruct") + >>> tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct") + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder output consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + cache_position=cache_position, + **kwargs, + ) + + hidden_states = outputs[0] + + # only compute necessary logits, and do not upcast them to float if we are not computing the loss + logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) + + loss = None + if labels is not None: + loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **kwargs) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + The Doge Model transformer with a sequence classification head on top (linear layer). + + [`DogeForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. + If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. + If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. + Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). + """ +) +class DogeForSequenceClassification(DogePreTrainedModel): + def __init__(self, config: DogeConfig): + super().__init__(config) + self.config = config + self.num_labels = config.num_labels + + self.model = DogeModel(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.init_weights() + + def get_input_embeddings(self): + return self.model.word_embed + + def set_input_embeddings(self, value): + self.model.word_embed = value + + @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. + Indices should be in `[0, ..., config.num_labels - 1]`. + If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = outputs[0] + logits = self.classifier(hidden_states) + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility + sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 + sequence_lengths = sequence_lengths % input_ids.shape[-1] + sequence_lengths = sequence_lengths.to(logits.device) + else: + sequence_lengths = -1 + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + loss = self.loss_function( + logits=logits, + labels=labels, + pooled_logits=pooled_logits, + config=self.config, + ) + + if not return_dict: + output = (pooled_logits,) + outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +__all__ = [ + "DogeForCausalLM", + "DogeModel", + "DogePreTrainedModel", + "DogeForSequenceClassification", +] \ No newline at end of file diff --git a/src/transformers/utils/dummy_pt_objects.py b/src/transformers/utils/dummy_pt_objects.py index f49d65941c7b..ed6f0f26107e 100644 --- a/src/transformers/utils/dummy_pt_objects.py +++ b/src/transformers/utils/dummy_pt_objects.py @@ -2839,6 +2839,34 @@ def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) +class DogeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DogeForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DogeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DogePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + class EfficientFormerForImageClassification(metaclass=DummyObject): _backends = ["torch"] diff --git a/tests/models/doge/__init__.py b/tests/models/doge/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/models/doge/test_modeling_doge.py b/tests/models/doge/test_modeling_doge.py new file mode 100644 index 000000000000..babef58ba37f --- /dev/null +++ b/tests/models/doge/test_modeling_doge.py @@ -0,0 +1,383 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Testing suite for the PyTorch Doge model.""" + +import unittest + +from packaging import version + +from transformers import AutoTokenizer, DogeConfig, StaticCache, is_torch_available, set_seed +from transformers.generation.configuration_utils import GenerationConfig +from transformers.testing_utils import ( + cleanup, + require_read_token, + require_torch, + require_torch_accelerator, + slow, + torch_device, +) + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + DogeForCausalLM, + DogeForSequenceClassification, + DogeModel, + ) + + +class DogeModelTester: + def __init__( + self, + parent, + batch_size=8, + seq_length=16, + is_training=True, + use_input_mask=True, + use_token_type_ids=False, + use_labels=True, + vocab_size=128, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=64, + hidden_act="silu", + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + pad_token_id=0, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + self.use_labels = use_labels + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.max_position_embeddings = max_position_embeddings + self.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.pad_token_id = pad_token_id + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device)) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels + + def get_config(self): + return DogeConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + pad_token_id=self.pad_token_id, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels + ): + model = DogeModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = DogeModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = DogeForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = DogeForCausalLM(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() + + self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class DogeModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + DogeModel, + DogeForCausalLM, + DogeForSequenceClassification, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (DogeForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": DogeModel, + "text-classification": DogeForSequenceClassification, + "text-generation": DogeForCausalLM, + "zero-shot": DogeForSequenceClassification, + } + if is_torch_available() + else {} + ) + has_attentions = False + test_headmasking = False + test_pruning = False + fx_compatible = False # Broken by attention refactor cc @Cyrilvallez + + # Need to use `0.8` instead of `0.9` for `test_cpu_offload` + # This is because we are hitting edge cases with the causal_mask buffer + model_split_percents = [0.5, 0.7, 0.8] + + # used in `test_torch_compile_for_training` + _torch_compile_train_cls = DogeForCausalLM if is_torch_available() else None + + def setUp(self): + self.model_tester = DogeModelTester(self) + self.config_tester = ConfigTester(self, config_class=DogeConfig, hidden_size=32) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_doge_sequence_classification_model(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.num_labels = 3 + input_ids = input_dict["input_ids"] + attention_mask = input_ids.ne(1).to(torch_device) + sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size) + model = DogeForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels) + self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels)) + + def test_doge_sequence_classification_model_for_single_label(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.num_labels = 3 + config.problem_type = "single_label_classification" + input_ids = input_dict["input_ids"] + attention_mask = input_ids.ne(1).to(torch_device) + sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size) + model = DogeForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels) + self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels)) + + def test_doge_sequence_classification_model_for_multi_label(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.num_labels = 3 + config.problem_type = "multi_label_classification" + input_ids = input_dict["input_ids"] + attention_mask = input_ids.ne(1).to(torch_device) + sequence_labels = ids_tensor( + [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size + ).to(torch.float) + model = DogeForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels) + self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels)) + + @unittest.skip(reason="Doge buffers include complex numbers, which breaks this test") + def test_save_load_fast_init_from_base(self): + pass + + +@require_torch_accelerator +class DogeIntegrationTest(unittest.TestCase): + # This variable is used to determine which CUDA device are we using for our runners (A10 or T4) + # Depending on the hardware we get different logits / generations + cuda_compute_capability_major_version = None + + @classmethod + def setUpClass(cls): + if is_torch_available() and torch.cuda.is_available(): + # 8 is for A100 / A10 and 7 for T4 + cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0] + + @slow + @require_read_token + def test_Doge_20M_hard(self): + """ + An integration test for Doge-20M. It tests against a long output to ensure the subtle numerical differences + """ + EXPECTED_TEXT = ( + "Here's everything I know about dogs. Dogs is the best animal in the world, and it's a great way to learn about the world around us. Dogs are a great" + ) + + tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") + model = DogeForCausalLM.from_pretrained( + "JingzeShi/Doge-20M", + device_map="auto", torch_dtype=torch.bfloat16 + ) + input_text = ["Here's everything I know about dogs. Dogs is the best animal in the"] + set_seed(0) + model_inputs = tokenizer(input_text, return_tensors="pt").to(model.device) + + generated_ids = model.generate(**model_inputs, max_new_tokens=20, do_sample=False) + generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) + self.assertEqual(generated_text, EXPECTED_TEXT) diff --git a/tests/utils/test_cache_utils.py b/tests/utils/test_cache_utils.py index d67b026638e9..ed6b2d909a7b 100644 --- a/tests/utils/test_cache_utils.py +++ b/tests/utils/test_cache_utils.py @@ -43,6 +43,7 @@ LlamaConfig, SinkCache, StaticCache, + SharedCache, convert_and_export_with_cache, ) from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_3 @@ -589,6 +590,21 @@ def test_offloaded_cache_uses_less_memory_than_dynamic_cache(self): model.generate(generation_config=offloaded, **inputs) offloaded_peak_memory = torch.cuda.max_memory_allocated(device) assert offloaded_peak_memory < original_peak_memory + + def test_shared_cache_hard(self): + tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct") + model = AutoModelForCausalLM.from_pretrained( + "JingzeShi/Doge-20M-Instruct", device_map="auto", + torch_dtype=torch.float16, trust_remote_code=True + ) + inputs = tokenizer(["You are a Doge"], return_tensors="pt").to(model.device) + + # SharedCache and the legacy cache format should be equivalent + set_seed(0) + gen_out_legacy = model.generate(**inputs, do_sample=True, max_new_tokens=256) + set_seed(0) + gen_out = model.generate(**inputs, do_sample=True, max_new_tokens=256, past_key_values=SharedCache(shared_layer_groups=2)) + self.assertListEqual(gen_out_legacy.tolist(), gen_out.tolist()) @require_torch_gpu def test_cache_copy(self): From 5c96118a848e6e14ae8ae5a069b1f93c975a9c5b Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Sun, 26 Jan 2025 02:42:22 +0800 Subject: [PATCH 02/20] Fix code quality --- docs/source/en/model_doc/doge.md | 5 + src/transformers/models/auto/modeling_auto.py | 4 +- .../models/doge/configuration_doge.py | 82 ++++++++-------- src/transformers/models/doge/modeling_doge.py | 98 +++++++++---------- src/transformers/utils/dummy_pt_objects.py | 56 +++++------ tests/models/doge/test_modeling_doge.py | 31 ++---- tests/utils/test_cache_utils.py | 11 ++- 7 files changed, 138 insertions(+), 149 deletions(-) diff --git a/docs/source/en/model_doc/doge.md b/docs/source/en/model_doc/doge.md index aa131ae48b5d..7c4b2468861a 100644 --- a/docs/source/en/model_doc/doge.md +++ b/docs/source/en/model_doc/doge.md @@ -37,3 +37,8 @@ Checkout all Doge model checkpoints [here](https://huggingface.co/collections/Ji [[autodoc]] DogeForCausalLM - forward + +## DogeForSequenceClassification + +[[autodoc]] DogeForSequenceClassification + - forward \ No newline at end of file diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index ee8edf2af194..51b0c8c9bbf2 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -501,8 +501,8 @@ ("ctrl", "CTRLLMHeadModel"), ("data2vec-text", "Data2VecTextForCausalLM"), ("dbrx", "DbrxForCausalLM"), - ("doge", "DogeForCausalLM"), ("diffllama", "DiffLlamaForCausalLM"), + ("doge", "DogeForCausalLM"), ("electra", "ElectraForCausalLM"), ("emu3", "Emu3ForCausalLM"), ("ernie", "ErnieForCausalLM"), @@ -978,9 +978,9 @@ ("data2vec-text", "Data2VecTextForSequenceClassification"), ("deberta", "DebertaForSequenceClassification"), ("deberta-v2", "DebertaV2ForSequenceClassification"), - ("doge", "DogeForSequenceClassification"), ("diffllama", "DiffLlamaForSequenceClassification"), ("distilbert", "DistilBertForSequenceClassification"), + ("doge", "DogeForSequenceClassification"), ("electra", "ElectraForSequenceClassification"), ("ernie", "ErnieForSequenceClassification"), ("ernie_m", "ErnieMForSequenceClassification"), diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index b2550e6dbcf7..1aaec0307330 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -44,25 +44,40 @@ class DogeConfig(PretrainedConfig): Dropout probability for each sequence transformation and state transformation module. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + rms_norm_eps (`float`, *optional*, defaults to 1e-06): + The epsilon used by the rms normalization layers. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions (not used by all models). Only + relevant if `config.is_decoder=True`. + bos_token_id (`int`, *optional*, defaults to 0): + Beginning of stream token id. + eos_token_id (`int`, *optional*, defaults to 1): + End of stream token id. + pad_token_id (`int`, *optional*, defaults to 2): + Padding token id. + tie_word_embeddings (`bool`, *optional*, defaults to `False`): + Whether to tie weight embeddings max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. - rope_scaling (`Dict`, *optional*): - Dictionary containing the scaling configuration for the RoPE embeddings. + rope_scaling (`Dict`, *optional*, defaults to `{'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048}`): + Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): - Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. + Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): - Used with 'dynamic', 'longrope' and 'llama3'. + Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. `attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention - computation. + computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear @@ -71,42 +86,27 @@ class DogeConfig(PretrainedConfig): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`List[float]`, *optional*): - Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`). + Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`List[float]`, *optional*): - Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`). + Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE - initializer_range (`float`, *optional*, defaults to 0.02): - The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (`float`, *optional*, defaults to 1e-06): - The epsilon used by the rms normalization layers. - use_cache (`bool`, *optional*, defaults to `True`): - Whether or not the model should return the last key/values attentions (not used by all models). Only - relevant if `config.is_decoder=True`. - pad_token_id (`int`, *optional*, defaults to 0): - Padding token id. - bos_token_id (`int`, *optional*, defaults to 1): - Beginning of stream token id. - eos_token_id (`int`, *optional*, defaults to 2): - End of stream token id. - tie_word_embeddings (`bool`, *optional*, defaults to `True`): - Whether to tie weight embeddings num_attention_heads (`int`, *optional*, defaults to 8): Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (`int`, *optional*, defaults to `None`): - This is the number of key_value heads that should be used to implement Grouped Query Attention. + num_key_value_heads (`int`, *optional*): + This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if - `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. - When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. - For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). + `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. + When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. + For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `num_attention_heads`. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. - dynamic_mask_ratio (`float`, *optional*, defaults to 0.0, range [0, 1]): + dynamic_mask_ratio (`float`, *optional*, defaults to 0.0): The ratio to control the proportion of the dynamic mask filled with the minimum value. For more details checkout [this paper](https://arxiv.org/pdf/2412.11834). is_moe (`bool`, *optional*, defaults to `False`): Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize. For more details checkout [this paper](https://arxiv.org/pdf/2412.11834). @@ -155,6 +155,13 @@ def __init__( hidden_bias=False, hidden_dropout=0.0, hidden_act="silu", + initializer_range=0.02, + rms_norm_eps=1e-06, + use_cache=True, + bos_token_id=0, + eos_token_id=1, + pad_token_id=2, + tie_word_embeddings=False, max_position_embeddings=2048, rope_theta=10000.0, rope_scaling={ @@ -162,13 +169,6 @@ def __init__( "factor": 4.0, "original_max_position_embeddings": 2048, }, - initializer_range=0.02, - rms_norm_eps=1e-06, - use_cache=True, - bos_token_id=0, - eos_token_id=1, - pad_token_id=2, - tie_word_embeddings=True, num_attention_heads=8, num_key_value_heads=None, attention_dropout=0.0, @@ -184,19 +184,17 @@ def __init__( self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers + self.hidden_bias = hidden_bias self.hidden_dropout = hidden_dropout self.hidden_act = hidden_act - self.max_position_embeddings = max_position_embeddings - self.rope_theta = rope_theta - self.rope_scaling = rope_scaling self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache - self.bos_token_id = bos_token_id - self.eos_token_id = eos_token_id - self.pad_token_id = pad_token_id - self.tie_word_embeddings = tie_word_embeddings + + self.max_position_embeddings = max_position_embeddings + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.attention_dropout = attention_dropout diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index f23bf25e365e..4c9b31347533 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -46,6 +46,7 @@ ) from .configuration_doge import DogeConfig + try: from einx import add as einx_add except ImportError: @@ -175,8 +176,8 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): Deprecated and unused. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and - sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. - For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. + For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: @@ -191,7 +192,7 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ - This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape @@ -210,7 +211,7 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): self.layer_idx = layer_idx self.head_dim = config.hidden_size // config.num_attention_heads self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads - self.scaling = self.head_dim ** -0.5 + self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.dynamic_mask_ratio = config.dynamic_mask_ratio @@ -222,33 +223,21 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): # Q K V O projections self.q_proj = nn.Linear( - config.hidden_size, - config.num_attention_heads * self.head_dim, - bias=config.hidden_bias + config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.hidden_bias ) self.k_proj = nn.Linear( - config.hidden_size, - config.num_key_value_heads * self.head_dim, - bias=config.hidden_bias + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.hidden_bias ) self.v_proj = nn.Linear( - config.hidden_size, - config.num_key_value_heads * self.head_dim, - bias=config.hidden_bias + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.hidden_bias ) # dynamic mask for the QK^T attention score matrix - self.A = nn.Parameter( - torch.zeros(config.num_attention_heads) - ) + self.A = nn.Parameter(torch.zeros(config.num_attention_heads)) self.dt_proj = nn.Linear( - config.num_key_value_heads * self.head_dim, - config.num_attention_heads, - bias=config.hidden_bias + config.num_key_value_heads * self.head_dim, config.num_attention_heads, bias=config.hidden_bias ) self.o_proj = nn.Linear( - config.num_attention_heads * self.head_dim, - config.hidden_size, - bias=config.hidden_bias + config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.hidden_bias ) def forward( @@ -276,7 +265,9 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # calculate dynamic mask from value_states - dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)) + dt_states = self.dt_proj( + value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1) + ) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( hidden_states=hidden_states, @@ -288,7 +279,7 @@ def forward( attention_interface: Callable = self.eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = self.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] - + attn_output = attention_interface( query_states, key_states, @@ -334,7 +325,7 @@ def prepare_dynamic_mask( attn_mask = attention_mask return attn_mask - + def eager_attention_forward( self, query: torch.Tensor, @@ -353,7 +344,7 @@ def eager_attention_forward( if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask - + # upcast attention scores to fp32 attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = F.dropout(attn_weights, p=dropout, training=self.training) @@ -362,7 +353,7 @@ def eager_attention_forward( attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output - + def sdpa_attention_forward( self, query: torch.Tensor, @@ -375,7 +366,7 @@ def sdpa_attention_forward( ) -> torch.Tensor: key = repeat_kv(key, self.num_key_value_groups) value = repeat_kv(value, self.num_key_value_groups) - + causal_mask = attention_mask if attention_mask is not None: causal_mask = causal_mask[:, :, :, : key.shape[-2]] @@ -398,7 +389,7 @@ def sdpa_attention_forward( ) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output - + def flex_attention_forward( self, query: torch.Tensor, @@ -421,13 +412,13 @@ def flex_attention_forward( def causal_mod(score, batch, head, q_idx, kv_idx): score = score + causal_mask[batch][0][q_idx][kv_idx] return score - + def dynamic_mod(score, batch, head, q_idx, kv_idx): score = score + causal_mask[batch][head][q_idx][kv_idx] return score - + mask_mod = causal_mod if self.is_causal else dynamic_mod - + attn_output = flex_attention( query, key, @@ -440,7 +431,6 @@ def dynamic_mod(score, batch, head, q_idx, kv_idx): class DogeMLP(nn.Module): - def __init__(self, config: DogeConfig): super().__init__() self.hidden_dim = config.hidden_size @@ -479,7 +469,7 @@ def __init__(self, config: DogeConfig): self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.num_keys, 2, self.expert_retrieval_dim // 2)) # experts - self.down_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) + self.down_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) self.up_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) def forward( @@ -528,7 +518,7 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): self.pre_residual = Residual(config.hidden_size) self.post_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) - self.feed_forward = DogeMLP(config) if config.is_moe == False else DogeCDMoE(config) + self.feed_forward = DogeMLP(config) if not config.is_moe else DogeCDMoE(config) self.post_residual = Residual(config.hidden_size) def forward( @@ -543,7 +533,6 @@ def forward( position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC **kwargs, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: - # sequence transformation residual = hidden_states hidden_states = self.pre_layernorm(hidden_states) @@ -589,6 +578,8 @@ def forward( load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ + + @add_start_docstrings( "The bare Doge Model outputting raw hidden-states without any specific head on top.", DOGE_START_DOCSTRING, @@ -868,7 +859,7 @@ def _update_causal_mask( ) return causal_mask - + @staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor = None, @@ -909,7 +900,9 @@ def _prepare_4d_causal_attention_mask_with_cache_position( min_dtype = torch.finfo(dtype).min causal_mask = torch.full( (sequence_length, target_length), - fill_value=min_dtype, dtype=dtype, device=device, + fill_value=min_dtype, + dtype=dtype, + device=device, ) if sequence_length != 1: causal_mask = torch.triu(causal_mask, diagonal=1) @@ -955,7 +948,7 @@ def get_output_embeddings(self): def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings - + def get_decoder(self): return self.model @@ -999,8 +992,8 @@ def forward( ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM - >>> model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M-Instruct") - >>> tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct") + >>> model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M") + >>> tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") @@ -1057,13 +1050,16 @@ def forward( """ The Doge Model transformer with a sequence classification head on top (linear layer). - [`DogeForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do. + [`DogeForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. - Since it does classification on the last token, it requires to know the position of the last token. - If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. - If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. - Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). - """ + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + DOGE_START_DOCSTRING, ) class DogeForSequenceClassification(DogePreTrainedModel): def __init__(self, config: DogeConfig): @@ -1099,9 +1095,9 @@ def forward( ) -> Union[Tuple, SequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): - Labels for computing the sequence classification/regression loss. - Indices should be in `[0, ..., config.num_labels - 1]`. - If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict @@ -1166,4 +1162,4 @@ def forward( "DogeModel", "DogePreTrainedModel", "DogeForSequenceClassification", -] \ No newline at end of file +] diff --git a/src/transformers/utils/dummy_pt_objects.py b/src/transformers/utils/dummy_pt_objects.py index ed6f0f26107e..155324e84c86 100644 --- a/src/transformers/utils/dummy_pt_objects.py +++ b/src/transformers/utils/dummy_pt_objects.py @@ -2839,34 +2839,6 @@ def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) -class DogeForCausalLM(metaclass=DummyObject): - _backends = ["torch"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["torch"]) - - -class DogeForSequenceClassification(metaclass=DummyObject): - _backends = ["torch"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["torch"]) - - -class DogeModel(metaclass=DummyObject): - _backends = ["torch"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["torch"]) - - -class DogePreTrainedModel(metaclass=DummyObject): - _backends = ["torch"] - - def __init__(self, *args, **kwargs): - requires_backends(self, ["torch"]) - - class EfficientFormerForImageClassification(metaclass=DummyObject): _backends = ["torch"] @@ -3761,6 +3733,34 @@ def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) +class DogeForCausalLM(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DogeForSequenceClassification(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DogeModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + +class DogePreTrainedModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + class DonutSwinModel(metaclass=DummyObject): _backends = ["torch"] diff --git a/tests/models/doge/test_modeling_doge.py b/tests/models/doge/test_modeling_doge.py index babef58ba37f..3af45a4f8312 100644 --- a/tests/models/doge/test_modeling_doge.py +++ b/tests/models/doge/test_modeling_doge.py @@ -16,12 +16,8 @@ import unittest -from packaging import version - -from transformers import AutoTokenizer, DogeConfig, StaticCache, is_torch_available, set_seed -from transformers.generation.configuration_utils import GenerationConfig +from transformers import AutoTokenizer, DogeConfig, is_torch_available, set_seed from transformers.testing_utils import ( - cleanup, require_read_token, require_torch, require_torch_accelerator, @@ -126,9 +122,7 @@ def get_config(self): pad_token_id=self.pad_token_id, ) - def create_and_check_model( - self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels - ): + def create_and_check_model(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels): model = DogeModel(config=config) model.to(torch_device) model.eval() @@ -297,11 +291,11 @@ def setUp(self): def test_config(self): self.config_tester.run_common_tests() - + def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) - + def test_doge_sequence_classification_model(self): config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.num_labels = 3 @@ -313,7 +307,7 @@ def test_doge_sequence_classification_model(self): model.eval() result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels) self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels)) - + def test_doge_sequence_classification_model_for_single_label(self): config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.num_labels = 3 @@ -326,7 +320,7 @@ def test_doge_sequence_classification_model_for_single_label(self): model.eval() result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels) self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels)) - + def test_doge_sequence_classification_model_for_multi_label(self): config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.num_labels = 3 @@ -341,7 +335,7 @@ def test_doge_sequence_classification_model_for_multi_label(self): model.eval() result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels) self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels)) - + @unittest.skip(reason="Doge buffers include complex numbers, which breaks this test") def test_save_load_fast_init_from_base(self): pass @@ -358,22 +352,17 @@ def setUpClass(cls): if is_torch_available() and torch.cuda.is_available(): # 8 is for A100 / A10 and 7 for T4 cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0] - + @slow @require_read_token def test_Doge_20M_hard(self): """ An integration test for Doge-20M. It tests against a long output to ensure the subtle numerical differences """ - EXPECTED_TEXT = ( - "Here's everything I know about dogs. Dogs is the best animal in the world, and it's a great way to learn about the world around us. Dogs are a great" - ) + EXPECTED_TEXT = "Here's everything I know about dogs. Dogs is the best animal in the world, and it's a great way to learn about the world around us. Dogs are a great" tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") - model = DogeForCausalLM.from_pretrained( - "JingzeShi/Doge-20M", - device_map="auto", torch_dtype=torch.bfloat16 - ) + model = DogeForCausalLM.from_pretrained("JingzeShi/Doge-20M", device_map="auto", torch_dtype=torch.bfloat16) input_text = ["Here's everything I know about dogs. Dogs is the best animal in the"] set_seed(0) model_inputs = tokenizer(input_text, return_tensors="pt").to(model.device) diff --git a/tests/utils/test_cache_utils.py b/tests/utils/test_cache_utils.py index ed6b2d909a7b..278d38daa0dd 100644 --- a/tests/utils/test_cache_utils.py +++ b/tests/utils/test_cache_utils.py @@ -41,9 +41,9 @@ GenerationConfig, GPT2LMHeadModel, LlamaConfig, + SharedCache, SinkCache, StaticCache, - SharedCache, convert_and_export_with_cache, ) from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_3 @@ -590,12 +590,11 @@ def test_offloaded_cache_uses_less_memory_than_dynamic_cache(self): model.generate(generation_config=offloaded, **inputs) offloaded_peak_memory = torch.cuda.max_memory_allocated(device) assert offloaded_peak_memory < original_peak_memory - + def test_shared_cache_hard(self): tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct") model = AutoModelForCausalLM.from_pretrained( - "JingzeShi/Doge-20M-Instruct", device_map="auto", - torch_dtype=torch.float16, trust_remote_code=True + "JingzeShi/Doge-20M-Instruct", device_map="auto", torch_dtype=torch.float16, trust_remote_code=True ) inputs = tokenizer(["You are a Doge"], return_tensors="pt").to(model.device) @@ -603,7 +602,9 @@ def test_shared_cache_hard(self): set_seed(0) gen_out_legacy = model.generate(**inputs, do_sample=True, max_new_tokens=256) set_seed(0) - gen_out = model.generate(**inputs, do_sample=True, max_new_tokens=256, past_key_values=SharedCache(shared_layer_groups=2)) + gen_out = model.generate( + **inputs, do_sample=True, max_new_tokens=256, past_key_values=SharedCache(shared_layer_groups=2) + ) self.assertListEqual(gen_out_legacy.tolist(), gen_out.tolist()) @require_torch_gpu From 0f689d6755e0e7e7b94ac1a4a4942af8082b1938 Mon Sep 17 00:00:00 2001 From: LoserCheems <3314685395@qq.com> Date: Sun, 26 Jan 2025 03:03:31 +0800 Subject: [PATCH 03/20] Rollback an error commit --- tests/utils/test_cache_utils.py | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/tests/utils/test_cache_utils.py b/tests/utils/test_cache_utils.py index 278d38daa0dd..d67b026638e9 100644 --- a/tests/utils/test_cache_utils.py +++ b/tests/utils/test_cache_utils.py @@ -41,7 +41,6 @@ GenerationConfig, GPT2LMHeadModel, LlamaConfig, - SharedCache, SinkCache, StaticCache, convert_and_export_with_cache, @@ -591,22 +590,6 @@ def test_offloaded_cache_uses_less_memory_than_dynamic_cache(self): offloaded_peak_memory = torch.cuda.max_memory_allocated(device) assert offloaded_peak_memory < original_peak_memory - def test_shared_cache_hard(self): - tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct") - model = AutoModelForCausalLM.from_pretrained( - "JingzeShi/Doge-20M-Instruct", device_map="auto", torch_dtype=torch.float16, trust_remote_code=True - ) - inputs = tokenizer(["You are a Doge"], return_tensors="pt").to(model.device) - - # SharedCache and the legacy cache format should be equivalent - set_seed(0) - gen_out_legacy = model.generate(**inputs, do_sample=True, max_new_tokens=256) - set_seed(0) - gen_out = model.generate( - **inputs, do_sample=True, max_new_tokens=256, past_key_values=SharedCache(shared_layer_groups=2) - ) - self.assertListEqual(gen_out_legacy.tolist(), gen_out.tolist()) - @require_torch_gpu def test_cache_copy(self): model_name = "microsoft/Phi-3-mini-4k-instruct" From 229cdcac10a6a4274d1dd13b729bc14c98eb0c76 Mon Sep 17 00:00:00 2001 From: LoserCheems <3314685395@qq.com> Date: Sun, 26 Jan 2025 18:15:28 +0800 Subject: [PATCH 04/20] Fix config for open-source weights --- src/transformers/models/doge/configuration_doge.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index 1aaec0307330..03d91dad698f 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -161,7 +161,7 @@ def __init__( bos_token_id=0, eos_token_id=1, pad_token_id=2, - tie_word_embeddings=False, + tie_word_embeddings=True, max_position_embeddings=2048, rope_theta=10000.0, rope_scaling={ From 749dbcded1744179cbf65d2fdd53065257755a55 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Sun, 26 Jan 2025 22:54:15 +0800 Subject: [PATCH 05/20] Revert "Fix config for open-source weights" This reverts commit 229cdcac10a6a4274d1dd13b729bc14c98eb0c76. --- src/transformers/models/doge/configuration_doge.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index 03d91dad698f..1aaec0307330 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -161,7 +161,7 @@ def __init__( bos_token_id=0, eos_token_id=1, pad_token_id=2, - tie_word_embeddings=True, + tie_word_embeddings=False, max_position_embeddings=2048, rope_theta=10000.0, rope_scaling={ From ca7630ab38fb9e9efd3dfe8445b9a34b7f1bf571 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Tue, 28 Jan 2025 01:42:24 +0800 Subject: [PATCH 06/20] Add modular_doge --- .../models/doge/configuration_doge.py | 6 +- src/transformers/models/doge/modular_doge.py | 1368 +++++++++++++++++ 2 files changed, 1371 insertions(+), 3 deletions(-) create mode 100644 src/transformers/models/doge/modular_doge.py diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index 1aaec0307330..6dc4c431004b 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -17,8 +17,8 @@ # limitations under the License. """PyTorch Doge model configuration""" -from transformers.configuration_utils import PretrainedConfig -from transformers.modeling_rope_utils import rope_config_validation +from ...configuration_utils import PretrainedConfig +from ...modeling_rope_utils import rope_config_validation class DogeConfig(PretrainedConfig): @@ -111,7 +111,7 @@ class DogeConfig(PretrainedConfig): is_moe (`bool`, *optional*, defaults to `False`): Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize. For more details checkout [this paper](https://arxiv.org/pdf/2412.11834). num_cdmoe_experts (`int`, *optional*, defaults to 16348): - Number of Experts for the Cross Domain Mixture of Experts. calculation formula: :math:`\text{num_cdmoe_experts} = (32 \times \text{num_cdmoe_heads})^2` + Number of Experts for the Cross Domain Mixture of Experts. num_cdmoe_heads (`int`, *optional*, defaults to 4): Number of retrieval heads, used to mix multi-head experts. num_cdmoe_experts_per_head (`int`, *optional*, defaults to 8): diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py new file mode 100644 index 000000000000..885f5e122a10 --- /dev/null +++ b/src/transformers/models/doge/modular_doge.py @@ -0,0 +1,1368 @@ +# coding=utf-8 +# Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on the Wonderful Matrices paper implementation. +# The Doge family of small language models is trained by Jingze Shi. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch Doge model.""" + +import math +from typing import Callable, List, Optional, Tuple, Union + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn + +from ...activations import ACT2FN +from ...cache_utils import Cache, DynamicCache, StaticCache +from ...generation import GenerationMixin +from ...modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + SequenceClassifierOutputWithPast, +) +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, rope_config_validation +from ...modeling_utils import PretrainedConfig, PreTrainedModel +from ...processing_utils import Unpack +from ...utils import ( + LossKwargs, + add_start_docstrings, + add_start_docstrings_to_model_forward, + is_torch_flex_attn_available, + logging, + replace_return_docstrings, +) + + +try: + from einx import add as einx_add +except ImportError: + einx_add = None + +if is_torch_flex_attn_available(): + from torch.nn.attention.flex_attention import flex_attention + + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "DogeConfig" + + +class DogeConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge + model according to the specified arguments, defining the model architecture like [JingzeShi/Doge-20M](https://huggingface.co/JingzeShi/Doge-20M). + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + Args: + vocab_size (`int`, *optional*, defaults to 32768): + Vocabulary size of the Doge model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`DogeModel`] + hidden_size (`int`, *optional*, defaults to 1024): + Dimension of the hidden representations. + intermediate_size (`int`, *optional*, defaults to 2048): + Dimension of the MLP representations. + num_hidden_layers (`int`, *optional*, defaults to 32): + Number of hidden layers in the Transformer decoder. + hidden_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in the hidden layers. + hidden_dropout (`float`, *optional*, defaults to 0.0): + Dropout probability for each sequence transformation and state transformation module. + hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): + The non-linear activation function (function or string) in the decoder. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + rms_norm_eps (`float`, *optional*, defaults to 1e-06): + The epsilon used by the rms normalization layers. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions (not used by all models). Only + relevant if `config.is_decoder=True`. + bos_token_id (`int`, *optional*, defaults to 0): + Beginning of stream token id. + eos_token_id (`int`, *optional*, defaults to 1): + End of stream token id. + pad_token_id (`int`, *optional*, defaults to 2): + Padding token id. + tie_word_embeddings (`bool`, *optional*, defaults to `False`): + Whether to tie weight embeddings + max_position_embeddings (`int`, *optional*, defaults to 2048): + The maximum sequence length that this model might ever be used with. + rope_theta (`float`, *optional*, defaults to 10000.0): + The base period of the RoPE embeddings. + rope_scaling (`Dict`, *optional*, defaults to `{'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048}`): + Dictionary containing the scaling configuration for the RoPE embeddings. + NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. + Expected contents: + `rope_type` (`str`): + The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. + `factor` (`float`, *optional*): + Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. + In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. + `original_max_position_embeddings` (`int`, *optional*): + Used with 'dynamic', 'longrope' and 'llama3'. + The original max position embeddings used during pretraining. + `attention_factor` (`float`, *optional*): + Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention + computation. + If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. + `beta_fast` (`float`, *optional*): + Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear + ramp function. If unspecified, it defaults to 32. + `beta_slow` (`float`, *optional*): + Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear + ramp function. If unspecified, it defaults to 1. + `short_factor` (`List[float]`, *optional*): + Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`). + Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 + `long_factor` (`List[float]`, *optional*): + Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`). + Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 + `low_freq_factor` (`float`, *optional*): + Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE + `high_freq_factor` (`float`, *optional*): + Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE + num_attention_heads (`int`, *optional*, defaults to 8): + Number of attention heads for each attention layer in the Transformer decoder. + num_key_value_heads (`int`, *optional*): + This is the number of key_value heads that should be used to implement Grouped Query Attention. + If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if + `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. + When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. + For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). + If it is not specified, will default to `num_attention_heads`. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + dynamic_mask_ratio (`float`, *optional*, defaults to 0.0): + The ratio to control the proportion of the dynamic mask filled with the minimum value. For more details checkout [this paper](https://arxiv.org/pdf/2412.11834). + is_moe (`bool`, *optional*, defaults to `False`): + Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize. For more details checkout [this paper](https://arxiv.org/pdf/2412.11834). + num_cdmoe_experts (`int`, *optional*, defaults to 16348): + Number of Experts for the Cross Domain Mixture of Experts. + num_cdmoe_heads (`int`, *optional*, defaults to 4): + Number of retrieval heads, used to mix multi-head experts. + num_cdmoe_experts_per_head (`int`, *optional*, defaults to 8): + Number of Experts per retrieval head, used to mix multi-head experts. + expert_retrieval_size (`int`, *optional*, defaults to 64): + Dimension of the Expert retrieval states for calculating the dot product of query and key to determine the expert index. + + ```python + >>> from transformers import DogeConfig, DogeModel + + >>> # Initializing a Doge-320M style configuration + >>> configuration = DogeConfig() + + >>> # Initializing a model from the Doge-320M style configuration + >>> model = DogeModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "doge" + keys_to_ignore_at_inference = ["past_key_values"] + # Default tensor parallel plan for base model `DogeModel` + base_model_tp_plan = { + "layers.*.self_attn.q_proj": "colwise", + "layers.*.self_attn.k_proj": "colwise", + "layers.*.self_attn.v_proj": "colwise", + "layers.*.self_attn.dt_proj": "colwise", + "layers.*.self_attn.o_proj": "rowwise", + "layers.*.mlp.gate_proj": "colwise", + "layers.*.mlp.up_proj": "colwise", + "layers.*.mlp.down_proj": "rowwise", + } + + def __init__( + self, + vocab_size=32768, + hidden_size=1024, + intermediate_size=2048, + num_hidden_layers=32, + hidden_bias=False, + hidden_dropout=0.0, + hidden_act="silu", + initializer_range=0.02, + rms_norm_eps=1e-06, + use_cache=True, + bos_token_id=0, + eos_token_id=1, + pad_token_id=2, + tie_word_embeddings=False, + max_position_embeddings=2048, + rope_theta=10000.0, + rope_scaling={ + "rope_type": "dynamic", + "factor": 4.0, + "original_max_position_embeddings": 2048, + }, + num_attention_heads=8, + num_key_value_heads=None, + attention_dropout=0.0, + dynamic_mask_ratio=0.0, + is_moe=False, + num_cdmoe_experts=16348, + num_cdmoe_heads=4, + num_cdmoe_experts_per_head=8, + expert_retrieval_size=64, + **kwargs, + ): + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + + self.hidden_bias = hidden_bias + self.hidden_dropout = hidden_dropout + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.rms_norm_eps = rms_norm_eps + self.use_cache = use_cache + + self.max_position_embeddings = max_position_embeddings + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling + self.num_attention_heads = num_attention_heads + self.num_key_value_heads = num_key_value_heads + self.attention_dropout = attention_dropout + self.dynamic_mask_ratio = dynamic_mask_ratio + self.is_moe = is_moe + self.num_cdmoe_experts = num_cdmoe_experts + self.num_cdmoe_heads = num_cdmoe_heads + self.num_cdmoe_experts_per_head = num_cdmoe_experts_per_head + self.expert_retrieval_size = expert_retrieval_size + + # Validate the correctness of rotary position embeddings parameters + # BC: if there is a 'type' field, copy it it to 'rope_type'. + if self.rope_scaling is not None and "type" in self.rope_scaling: + self.rope_scaling["rope_type"] = self.rope_scaling["type"] + rope_config_validation(self) + + # for backward compatibility + if num_key_value_heads is None: + self.num_key_value_heads = num_attention_heads + + super().__init__( + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + pad_token_id=pad_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + +class RMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + RMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class Residual(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + + def forward(self, residual_states, hidden_states): + return self.weight * residual_states + hidden_states + + def extra_repr(self): + return f"{tuple(self.weight.shape)}" + + +class RotaryEmbedding(nn.Module): + def __init__(self, config: Optional[DogeConfig] = None): + super().__init__() + self.rope_kwargs = {} + + if config.rope_scaling is not None: + self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) + else: + self.rope_type = "default" + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + self.base = config.rope_theta + + self.config = config + self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + + inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self.original_inv_freq = self.inv_freq + + def _dynamic_frequency_update(self, position_ids, device): + """ + dynamic RoPE layers should recompute `inv_freq` in the following situations: + 1 - growing beyond the cached sequence length (allow scaling) + 2 - the current sequence length is in the original scale (avoid losing precision with small sequences) + """ + seq_len = torch.max(position_ids) + 1 + if seq_len > self.max_seq_len_cached: # growth + inv_freq, self.attention_scaling = self.rope_init_fn( + self.config, device, seq_len=seq_len, **self.rope_kwargs + ) + self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation + self.max_seq_len_cached = seq_len + + if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset + self.register_buffer("inv_freq", self.original_inv_freq, persistent=False) + self.max_seq_len_cached = self.original_max_seq_len + + @torch.no_grad() + def forward(self, x, position_ids): + if "dynamic" in self.rope_type: + self._dynamic_frequency_update(position_ids, device=x.device) + + # core RoPE block + inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) + position_ids_expanded = position_ids[:, None, :].float() + # Force float32 (see https://github.com/huggingface/transformers/pull/29285) + device_type = x.device.type + device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" + with torch.autocast(device_type=device_type, enabled=False): + freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() + sin = emb.sin() + + # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention + cos = cos * self.attention_scaling + sin = sin * self.attention_scaling + + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + +def rotate_half(x): + """ + Rotates half the hidden dims of the input. + """ + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + position_ids (`torch.Tensor`, *optional*): + Deprecated and unused. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. + For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. + Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. + Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). + The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +class DogeDynamicMaskAttention(nn.Module): + """Dynamic Mask Attention from 'Wonderful Matrices' paper.""" + + def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.head_dim = config.hidden_size // config.num_attention_heads + self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads + self.scaling = self.head_dim**-0.5 + self.attention_dropout = config.attention_dropout + self.dynamic_mask_ratio = config.dynamic_mask_ratio + + self.ALL_ATTENTION_FUNCTIONS = { + "eager": self.eager_attention_forward, + "flex_attention": self.flex_attention_forward, + "sdpa": self.sdpa_attention_forward, + } + + # Q K V O projections + self.q_proj = nn.Linear( + config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.hidden_bias + ) + self.k_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.hidden_bias + ) + self.v_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.hidden_bias + ) + # dynamic mask for the QK^T attention score matrix + self.A = nn.Parameter(torch.zeros(config.num_attention_heads)) + self.dt_proj = nn.Linear( + config.num_key_value_heads * self.head_dim, config.num_attention_heads, bias=config.hidden_bias + ) + self.o_proj = nn.Linear( + config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.hidden_bias + ) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: Tuple[torch.Tensor, torch.Tensor], + attention_mask: Optional[torch.Tensor] = None, + past_key_value: Optional[Cache] = None, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[Cache]]: + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, self.head_dim) + + query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) + key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) + value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) + + cos, sin = position_embeddings + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; cache_position needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # calculate dynamic mask from value_states + dt_states = self.dt_proj( + value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1) + ) + dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) + attn_mask = self.prepare_dynamic_mask( + hidden_states=hidden_states, + dynamic_mask=dynamic_mask, + dynamic_mask_ratio=self.dynamic_mask_ratio, + attention_mask=attention_mask, + ) + + attention_interface: Callable = self.eager_attention_forward + if self.config._attn_implementation != "eager": + attention_interface = self.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] + + attn_output = attention_interface( + query_states, + key_states, + value_states, + attention_mask=attn_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + attn_output = self.o_proj(attn_output) + return attn_output + + def prepare_dynamic_mask( + self, + hidden_states: torch.Tensor, + dynamic_mask: torch.Tensor, + dynamic_mask_ratio: float = 0.0, + attention_mask: Optional[torch.Tensor] = None, + ): + """ + Combine `dynamic_mask` with `attention_mask` to generate the final `attn_mask`. + + Args: + hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision. + dynamic_mask (`torch.Tensor`): dynamic mask of shape `(batch_size, num_heads, key_sequence_length)`. + dynamic_mask_ratio (`float`, *optional*): Ratio from 0.0 to 1.0 used to control the proportion of the dynamic mask filled with the minimum value. + attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`. + """ + attn_mask = None + if dynamic_mask is not None: + attn_mask = dynamic_mask[:, :, None, :] + if 0.0 < dynamic_mask_ratio < 1.0: + min_type = torch.finfo(hidden_states.dtype).min + num_dynamic_mask = int(attn_mask.shape[-1] * dynamic_mask_ratio) + if num_dynamic_mask > 0: + rate_value = torch.kthvalue(attn_mask, num_dynamic_mask, dim=-1, keepdim=True).values + attn_mask = attn_mask.masked_fill(attn_mask < rate_value, min_type) + if attention_mask is not None: + attn_mask = attn_mask + attention_mask[:, :, :, : attn_mask.shape[-1]] + else: + attn_mask = attention_mask + + return attn_mask + + def eager_attention_forward( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, + ) -> torch.Tensor: + key_states = repeat_kv(key, self.num_key_value_groups) + value_states = repeat_kv(value, self.num_key_value_groups) + + # compute attention scores matrix + attn_weights = torch.matmul(query, key_states.transpose(-1, -2)) * scaling + if attention_mask is not None: + causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] + attn_weights = attn_weights + causal_mask + + # upcast attention scores to fp32 + attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = F.dropout(attn_weights, p=dropout, training=self.training) + + # apply attention scores to value states + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output + + def sdpa_attention_forward( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, + ) -> torch.Tensor: + key = repeat_kv(key, self.num_key_value_groups) + value = repeat_kv(value, self.num_key_value_groups) + + causal_mask = attention_mask + if attention_mask is not None: + causal_mask = causal_mask[:, :, :, : key.shape[-2]] + + # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions + # Reference: https://github.com/pytorch/pytorch/issues/112577. + query = query.contiguous() + key = key.contiguous() + value = value.contiguous() + + # NOTE: As of pytorch 2.5.1, cuDNN's SDPA backward pass is still incorrect, so we disable cuDNN SDPA (see https://github.com/pytorch/pytorch/issues/138581) + torch.backends.cuda.enable_cudnn_sdp(False) + attn_output = F.scaled_dot_product_attention( + query, + key, + value, + attn_mask=causal_mask, + dropout_p=dropout, + scale=scaling, + ) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output + + def flex_attention_forward( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, + ) -> torch.Tensor: + key = repeat_kv(key, self.num_key_value_groups) + value = repeat_kv(value, self.num_key_value_groups) + + causal_mask = attention_mask + if attention_mask is not None: + causal_mask = causal_mask[:, :, :, : key.shape[-2]] + + # TODO: flex_attention: As of pytorch 2.5.1, captured buffers that require grad are not yet supported. + # NOTE: So we only use flex_attention in inference mode. + def causal_mod(score, batch, head, q_idx, kv_idx): + score = score + causal_mask[batch][0][q_idx][kv_idx] + return score + + def dynamic_mod(score, batch, head, q_idx, kv_idx): + score = score + causal_mask[batch][head][q_idx][kv_idx] + return score + + mask_mod = causal_mod if self.is_causal else dynamic_mod + + attn_output = flex_attention( + query, + key, + value, + score_mod=mask_mod, + scale=scaling, + ) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output + + +class DogeMLP(nn.Module): + def __init__(self, config: DogeConfig): + super().__init__() + self.hidden_dim = config.hidden_size + self.intermediate_dim = config.intermediate_size + self.act_fn = ACT2FN[config.hidden_act] + + self.gate_proj = nn.Linear(self.hidden_dim, self.intermediate_dim, bias=config.hidden_bias) + self.up_proj = nn.Linear(self.hidden_dim, self.intermediate_dim, bias=config.hidden_bias) + self.down_proj = nn.Linear(self.intermediate_dim, self.hidden_dim, bias=config.hidden_bias) + + def forward( + self, + hidden_states: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) + return hidden_states + + +class DogeCDMoE(DogeMLP): + """Cross Domain Mixture of Experts from 'Wonderful Matrices' paper.""" + + def __init__(self, config: DogeConfig): + super().__init__(config) + self.hidden_dim = config.hidden_size + self.act_fn = ACT2FN[config.hidden_act] + + self.expert_retrieval_dim = config.expert_retrieval_size + self.num_cdmoe_experts = config.num_cdmoe_experts + self.num_cdmoe_heads = config.num_cdmoe_heads + self.num_cdmoe_experts_per_head = config.num_cdmoe_experts_per_head + self.num_keys = int(math.sqrt(self.num_cdmoe_experts)) + + # queries and keys for retrieval experts + self.queries = nn.Linear(self.hidden_dim, self.num_cdmoe_heads * self.expert_retrieval_dim, bias=False) + self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.num_keys, 2, self.expert_retrieval_dim // 2)) + + # experts + self.down_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) + self.up_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) + + def forward( + self, + hidden_states: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + bsz, seq_len, _ = hidden_states.shape + + # get similarity with queries and keys + queries = self.queries(hidden_states) + queries = queries.view(bsz, seq_len, 2, self.num_cdmoe_heads, -1).permute(2, 0, 1, 3, 4) + sim = torch.einsum("p b t h n, h k p n -> p b t h k", queries, self.keys) + + # get experts with the highest similarity + (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmoe_experts_per_head, dim=-1) + if einx_add is not None: + all_scores = einx_add("... i, ... j -> ... (i j)", scores_x, scores_y) + all_indices = einx_add("... i, ... j -> ... (i j)", indices_x * self.num_keys, indices_y) + else: + all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) + all_scores = all_scores.view(*scores_x.shape[:-1], -1) + all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) + all_indices = all_indices.view(*indices_x.shape[:-1], -1) + scores, pk_indices = all_scores.topk(self.num_cdmoe_experts_per_head, dim=-1) + indices = all_indices.gather(-1, pk_indices) + down_embed = self.down_embed(indices) + up_embed = self.up_embed(indices) + + # mix experts states with cross domain states + experts_weights = torch.einsum("b t d, b t h k d -> b t h k", hidden_states, down_embed) + experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) + experts_states = torch.einsum("b t h k, b t h k d -> b t d", experts_weights, up_embed) + hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) + hidden_states = hidden_states + experts_states + return hidden_states + + +class DogeDecoderLayer(nn.Module): + def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): + super().__init__() + self.hidden_dropout = config.hidden_dropout + + self.pre_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.self_attn = DogeDynamicMaskAttention(config=config, layer_idx=layer_idx) + self.pre_residual = Residual(config.hidden_size) + + self.post_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.feed_forward = DogeMLP(config) if not config.is_moe else DogeCDMoE(config) + self.post_residual = Residual(config.hidden_size) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + cache_position: Optional[torch.LongTensor] = None, + position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC + **kwargs, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + # sequence transformation + residual = hidden_states + hidden_states = self.pre_layernorm(hidden_states) + hidden_states = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + cache_position=cache_position, + position_embeddings=position_embeddings, + **kwargs, + ) + self_attn_weights = None + hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training) + hidden_states = self.pre_residual(residual, hidden_states) + + # state transformation + residual = hidden_states + hidden_states = self.post_layernorm(hidden_states) + hidden_states = self.feed_forward(hidden_states) + hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training) + hidden_states = self.post_residual(residual, hidden_states) + + outputs = (hidden_states,) + if output_attentions: + outputs += (self_attn_weights,) + + return outputs + + +DOGE_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`DogeConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare Doge Model outputting raw hidden-states without any specific head on top.", + DOGE_START_DOCSTRING, +) +class DogePreTrainedModel(PreTrainedModel): + config_class = DogeConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["DogeDecoderLayer"] + _skip_keys_device_placement = ["past_key_values"] + _supports_sdpa = True + _supports_flex_attn = True + _supports_cache_class = True + _supports_quantized_cache = True + _supports_static_cache = True + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, (nn.Linear)): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + +DOGE_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): + Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` + returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. + + Two formats are allowed: + - a [`~cache_utils.Cache`] instance, see our + [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache); + - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy + cache format. + + The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the + legacy cache format will be returned. + + If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't + have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` + of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): + Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, + this tensor is not affected by padding. It is used to update the cache in the correct position and to infer + the complete sequence length. +""" + + +@add_start_docstrings( + "The bare Doge Model outputting raw hidden-states without any specific head on top.", + DOGE_START_DOCSTRING, +) +class DogeModel(DogePreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DogeDecoderLayer`] + + Args: + config: DogeConfig + """ + + def __init__(self, config: DogeConfig): + super().__init__(config) + self.config = config + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.rotary_emb = RotaryEmbedding(config) + self.layers = nn.ModuleList( + [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.gradient_checkpointing = False + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.word_embed + + def set_input_embeddings(self, value): + self.word_embed = value + + @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You cannot specify both input_ids and inputs_embeds") + + if self.gradient_checkpointing and self.training and use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + if inputs_embeds is None: + inputs_embeds = self.word_embed(input_ids) + + if use_cache and past_key_values is None: + past_key_values = DynamicCache() + + if cache_position is None: + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + cache_position = torch.arange( + past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device + ) + + if position_ids is None: + position_ids = cache_position.unsqueeze(0) + + causal_mask = self._update_causal_mask( + attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions + ) + + hidden_states = inputs_embeds + + # create position embeddings to be shared across the decoder layers + position_embeddings = self.rotary_emb(hidden_states, position_ids) + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + + for decoder_layer in self.layers[: self.config.num_hidden_layers]: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + decoder_layer.__call__, + hidden_states, + causal_mask, + position_ids, + past_key_values, + output_attentions, + use_cache, + cache_position, + position_embeddings, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=causal_mask, + position_ids=position_ids, + past_key_value=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + cache_position=cache_position, + position_embeddings=position_embeddings, + **kwargs, + ) + + hidden_states = layer_outputs[0] + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + hidden_states = self.final_layernorm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + output = BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values if use_cache else None, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + return output if return_dict else output.to_tuple() + + def _update_causal_mask( + self, + attention_mask: torch.Tensor, + input_tensor: torch.Tensor, + cache_position: torch.Tensor, + past_key_values: Cache, + output_attentions: bool, + ): + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + using_static_cache = isinstance(past_key_values, StaticCache) + + dtype, device = input_tensor.dtype, input_tensor.device + sequence_length = input_tensor.shape[1] + if using_static_cache: + target_length = past_key_values.get_max_cache_shape() + else: + target_length = ( + attention_mask.shape[-1] + if isinstance(attention_mask, torch.Tensor) + else past_seen_tokens + sequence_length + 1 + ) + + # in case the provided `attention` mask is 2D, we generate a causal mask here (4D). + causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( + attention_mask=attention_mask, + sequence_length=sequence_length, + target_length=target_length, + dtype=dtype, + device=device, + cache_position=cache_position, + batch_size=input_tensor.shape[0], + ) + + return causal_mask + + @staticmethod + def _prepare_4d_causal_attention_mask_with_cache_position( + attention_mask: torch.Tensor = None, + sequence_length: int = None, + target_length: int = None, + dtype: torch.dtype = None, + device: torch.device = None, + cache_position: torch.Tensor = None, + batch_size: int = None, + **kwargs, + ): + """ + Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape + `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. + + Args: + attention_mask (`torch.Tensor`): + A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape + `(batch_size, 1, query_length, key_value_length)`. + sequence_length (`int`): + The sequence length being processed. + target_length (`int`): + The target length: when generating with static cache, the mask should be as long as the static cache, + to account for the 0 padding, the part of the cache that is not filled yet. + dtype (`torch.dtype`): + The dtype to use for the 4D attention mask. + device (`torch.device`): + The device to plcae the 4D attention mask on. + cache_position (`torch.Tensor`): + Indices depicting the position of the input sequence tokens in the sequence. + batch_size (`torch.Tensor`): + Batch size. + """ + if attention_mask is not None and attention_mask.dim() == 4: + # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. + causal_mask = attention_mask + else: + min_dtype = torch.finfo(dtype).min + causal_mask = torch.full( + (sequence_length, target_length), + fill_value=min_dtype, + dtype=dtype, + device=device, + ) + if sequence_length != 1: + causal_mask = torch.triu(causal_mask, diagonal=1) + causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) + causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) + if attention_mask is not None: + causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit + mask_length = attention_mask.shape[-1] + padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] + padding_mask = padding_mask == 0 + causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( + padding_mask, min_dtype + ) + + return causal_mask + + +class KwargsForCausalLM(LossKwargs): ... + + +class DogeForCausalLM(DogePreTrainedModel, GenerationMixin): + _tied_weights_keys = ["lm_head.weight"] + _tp_plan = {"lm_head": "colwise_rep"} + + def __init__(self, config: DogeConfig): + super().__init__(config) + self.config = config + self.model = DogeModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.word_embed + + def set_input_embeddings(self, value): + self.model.word_embed = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def get_decoder(self): + return self.model + + def set_decoder(self, decoder): + self.model = decoder + + @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + num_logits_to_keep: int = 0, + **kwargs: Unpack[KwargsForCausalLM], + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + num_logits_to_keep (`int`, *optional*): + Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all + `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that + token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, AutoModelForCausalLM + + >>> model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M") + >>> tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder output consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + cache_position=cache_position, + **kwargs, + ) + + hidden_states = outputs[0] + + # only compute necessary logits, and do not upcast them to float if we are not computing the loss + logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) + + loss = None + if labels is not None: + loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **kwargs) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + The Doge Model transformer with a sequence classification head on top (linear layer). + + [`DogeForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + DOGE_START_DOCSTRING, +) +class DogeForSequenceClassification(DogePreTrainedModel): + def __init__(self, config: DogeConfig): + super().__init__(config) + self.config = config + self.num_labels = config.num_labels + + self.model = DogeModel(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.init_weights() + + def get_input_embeddings(self): + return self.model.word_embed + + def set_input_embeddings(self, value): + self.model.word_embed = value + + @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = outputs[0] + logits = self.classifier(hidden_states) + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility + sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 + sequence_lengths = sequence_lengths % input_ids.shape[-1] + sequence_lengths = sequence_lengths.to(logits.device) + else: + sequence_lengths = -1 + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + loss = self.loss_function( + logits=logits, + labels=labels, + pooled_logits=pooled_logits, + config=self.config, + ) + + if not return_dict: + output = (pooled_logits,) + outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +__all__ = [ + "DogeConfig", + "DogeForCausalLM", + "DogeModel", + "DogePreTrainedModel", + "DogeForSequenceClassification", +] From 79c0659357d09565475b58fda52ed1334da8675f Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Tue, 28 Jan 2025 11:47:15 +0800 Subject: [PATCH 07/20] Update Doge inherits from Llama --- .../models/doge/configuration_doge.py | 17 +- src/transformers/models/doge/modeling_doge.py | 88 ++++---- src/transformers/models/doge/modular_doge.py | 191 +++--------------- src/transformers/utils/__init__.py | 1 + src/transformers/utils/import_utils.py | 6 + 5 files changed, 89 insertions(+), 214 deletions(-) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index 6dc4c431004b..d178e59b60e9 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -1,3 +1,9 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/doge/modular_doge.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_doge.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # coding=utf-8 # Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved. # @@ -15,10 +21,15 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""PyTorch Doge model configuration""" - -from ...configuration_utils import PretrainedConfig from ...modeling_rope_utils import rope_config_validation +from ...modeling_utils import PretrainedConfig +from ...utils import is_einx_available + + +if is_einx_available(): + from einx import add as einx_add +else: + einx_add = None class DogeConfig(PretrainedConfig): diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index 4c9b31347533..0ba264ff85a5 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -1,3 +1,9 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/doge/modular_doge.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_doge.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # coding=utf-8 # Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved. # @@ -15,24 +21,18 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""PyTorch Doge model.""" import math from typing import Callable, List, Optional, Tuple, Union import torch import torch.nn.functional as F -import torch.utils.checkpoint from torch import nn from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache, StaticCache from ...generation import GenerationMixin -from ...modeling_outputs import ( - BaseModelOutputWithPast, - CausalLMOutputWithPast, - SequenceClassifierOutputWithPast, -) +from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import PreTrainedModel from ...processing_utils import Unpack @@ -40,16 +40,18 @@ LossKwargs, add_start_docstrings, add_start_docstrings_to_model_forward, + is_einx_available, is_torch_flex_attn_available, logging, replace_return_docstrings, ) +from ...utils.deprecation import deprecate_kwarg from .configuration_doge import DogeConfig -try: +if is_einx_available(): from einx import add as einx_add -except ImportError: +else: einx_add = None if is_torch_flex_attn_available(): @@ -94,22 +96,20 @@ def extra_repr(self): class RotaryEmbedding(nn.Module): - def __init__(self, config: Optional[DogeConfig] = None): + def __init__(self, config: Optional[DogeConfig] = None, device=None): super().__init__() - self.rope_kwargs = {} - - if config.rope_scaling is not None: + # BC: "rope_type" was originally "type" + if hasattr(config, "rope_scaling") and config.rope_scaling is not None: self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) else: self.rope_type = "default" self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings - self.base = config.rope_theta self.config = config self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] - inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs) + inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.original_inv_freq = self.inv_freq @@ -121,13 +121,14 @@ def _dynamic_frequency_update(self, position_ids, device): """ seq_len = torch.max(position_ids) + 1 if seq_len > self.max_seq_len_cached: # growth - inv_freq, self.attention_scaling = self.rope_init_fn( - self.config, device, seq_len=seq_len, **self.rope_kwargs - ) + inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len) self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation self.max_seq_len_cached = seq_len if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset + # This .to() is needed if the model has been moved to a device after being initialized (because + # the buffer is automatically moved, but not the original copy) + self.original_inv_freq = self.original_inv_freq.to(device) self.register_buffer("inv_freq", self.original_inv_freq, persistent=False) self.max_seq_len_cached = self.original_max_seq_len @@ -136,7 +137,7 @@ def forward(self, x, position_ids): if "dynamic" in self.rope_type: self._dynamic_frequency_update(position_ids, device=x.device) - # core RoPE block + # Core RoPE block inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) position_ids_expanded = position_ids[:, None, :].float() # Force float32 (see https://github.com/huggingface/transformers/pull/29285) @@ -955,6 +956,7 @@ def get_decoder(self): def set_decoder(self, decoder): self.model = decoder + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( @@ -970,7 +972,7 @@ def forward( output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, - num_logits_to_keep: int = 0, + logits_to_keep: int = 0, **kwargs: Unpack[KwargsForCausalLM], ) -> Union[Tuple, CausalLMOutputWithPast]: r""" @@ -980,10 +982,12 @@ def forward( config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. - num_logits_to_keep (`int`, *optional*): - Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all + logits_to_keep (`int`, *optional*): + If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. + This is useful when using packed tensor format (single dimension for batch and sequence length). Returns: @@ -1025,9 +1029,9 @@ def forward( ) hidden_states = outputs[0] - # only compute necessary logits, and do not upcast them to float if we are not computing the loss - logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) + slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep + logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: @@ -1064,14 +1068,14 @@ def forward( class DogeForSequenceClassification(DogePreTrainedModel): def __init__(self, config: DogeConfig): super().__init__(config) - self.config = config self.num_labels = config.num_labels self.model = DogeModel(config) - self.classifier = nn.Linear(config.hidden_size, self.num_labels, bias=False) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + self.config = config # Initialize weights and apply final processing - self.init_weights() + self.post_init() def get_input_embeddings(self): return self.model.word_embed @@ -1101,8 +1105,8 @@ def forward( """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict - outputs = self.model( - input_ids=input_ids, + transformer_outputs = self.model( + input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, @@ -1112,8 +1116,8 @@ def forward( output_hidden_states=output_hidden_states, return_dict=return_dict, ) - hidden_states = outputs[0] - logits = self.classifier(hidden_states) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) if input_ids is not None: batch_size = input_ids.shape[0] @@ -1137,29 +1141,19 @@ def forward( loss = None if labels is not None: - loss = self.loss_function( - logits=logits, - labels=labels, - pooled_logits=pooled_logits, - config=self.config, - ) + loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config) if not return_dict: - output = (pooled_logits,) + outputs[1:] + output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, ) -__all__ = [ - "DogeForCausalLM", - "DogeModel", - "DogePreTrainedModel", - "DogeForSequenceClassification", -] +__all__ = ["DogeForCausalLM", "DogeModel", "DogePreTrainedModel", "DogeForSequenceClassification"] diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 885f5e122a10..eb38e4fe7768 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -22,33 +22,39 @@ import torch import torch.nn.functional as F -import torch.utils.checkpoint from torch import nn +from transformers.models.llama.modeling_llama import ( + LlamaForSequenceClassification, + LlamaRMSNorm, + LlamaRotaryEmbedding, +) + from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache, StaticCache from ...generation import GenerationMixin from ...modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, - SequenceClassifierOutputWithPast, ) -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, rope_config_validation +from ...modeling_rope_utils import rope_config_validation from ...modeling_utils import PretrainedConfig, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( LossKwargs, add_start_docstrings, add_start_docstrings_to_model_forward, + is_einx_available, is_torch_flex_attn_available, logging, replace_return_docstrings, ) +from ...utils.deprecation import deprecate_kwarg -try: +if is_einx_available(): from einx import add as einx_add -except ImportError: +else: einx_add = None if is_torch_flex_attn_available(): @@ -263,24 +269,12 @@ def __init__( ) -class RMSNorm(nn.Module): +class RMSNorm(LlamaRMSNorm): def __init__(self, hidden_size, eps=1e-6): """ RMSNorm is equivalent to T5LayerNorm """ - super().__init__() - self.weight = nn.Parameter(torch.ones(hidden_size)) - self.variance_epsilon = eps - - def forward(self, hidden_states): - input_dtype = hidden_states.dtype - hidden_states = hidden_states.to(torch.float32) - variance = hidden_states.pow(2).mean(-1, keepdim=True) - hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) - return self.weight * hidden_states.to(input_dtype) - - def extra_repr(self): - return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + super().__init__(hidden_size, eps) class Residual(nn.Module): @@ -295,66 +289,9 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}" -class RotaryEmbedding(nn.Module): - def __init__(self, config: Optional[DogeConfig] = None): - super().__init__() - self.rope_kwargs = {} - - if config.rope_scaling is not None: - self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) - else: - self.rope_type = "default" - self.max_seq_len_cached = config.max_position_embeddings - self.original_max_seq_len = config.max_position_embeddings - self.base = config.rope_theta - - self.config = config - self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] - - inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs) - self.register_buffer("inv_freq", inv_freq, persistent=False) - self.original_inv_freq = self.inv_freq - - def _dynamic_frequency_update(self, position_ids, device): - """ - dynamic RoPE layers should recompute `inv_freq` in the following situations: - 1 - growing beyond the cached sequence length (allow scaling) - 2 - the current sequence length is in the original scale (avoid losing precision with small sequences) - """ - seq_len = torch.max(position_ids) + 1 - if seq_len > self.max_seq_len_cached: # growth - inv_freq, self.attention_scaling = self.rope_init_fn( - self.config, device, seq_len=seq_len, **self.rope_kwargs - ) - self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation - self.max_seq_len_cached = seq_len - - if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset - self.register_buffer("inv_freq", self.original_inv_freq, persistent=False) - self.max_seq_len_cached = self.original_max_seq_len - - @torch.no_grad() - def forward(self, x, position_ids): - if "dynamic" in self.rope_type: - self._dynamic_frequency_update(position_ids, device=x.device) - - # core RoPE block - inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) - position_ids_expanded = position_ids[:, None, :].float() - # Force float32 (see https://github.com/huggingface/transformers/pull/29285) - device_type = x.device.type - device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" - with torch.autocast(device_type=device_type, enabled=False): - freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() - sin = emb.sin() - - # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention - cos = cos * self.attention_scaling - sin = sin * self.attention_scaling - - return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) +class RotaryEmbedding(LlamaRotaryEmbedding): + def __init__(self, config: Optional[DogeConfig] = None, device=None): + super().__init__(config, device) def rotate_half(x): @@ -1157,6 +1094,7 @@ def get_decoder(self): def set_decoder(self, decoder): self.model = decoder + @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( @@ -1172,7 +1110,7 @@ def forward( output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, - num_logits_to_keep: int = 0, + logits_to_keep: int = 0, **kwargs: Unpack[KwargsForCausalLM], ) -> Union[Tuple, CausalLMOutputWithPast]: r""" @@ -1182,10 +1120,12 @@ def forward( config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. - num_logits_to_keep (`int`, *optional*): - Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all + logits_to_keep (`int`, *optional*): + If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. + If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. + This is useful when using packed tensor format (single dimension for batch and sequence length). Returns: @@ -1227,9 +1167,9 @@ def forward( ) hidden_states = outputs[0] - # only compute necessary logits, and do not upcast them to float if we are not computing the loss - logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) + slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep + logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: @@ -1263,17 +1203,17 @@ def forward( """, DOGE_START_DOCSTRING, ) -class DogeForSequenceClassification(DogePreTrainedModel): +class DogeForSequenceClassification(LlamaForSequenceClassification): def __init__(self, config: DogeConfig): super().__init__(config) self.config = config self.num_labels = config.num_labels self.model = DogeModel(config) - self.classifier = nn.Linear(config.hidden_size, self.num_labels, bias=False) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) # Initialize weights and apply final processing - self.init_weights() + self.post_init() def get_input_embeddings(self): return self.model.word_embed @@ -1281,83 +1221,6 @@ def get_input_embeddings(self): def set_input_embeddings(self, value): self.model.word_embed = value - @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) - def forward( - self, - input_ids: Optional[torch.LongTensor] = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, - inputs_embeds: Optional[torch.FloatTensor] = None, - labels: Optional[torch.LongTensor] = None, - use_cache: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, SequenceClassifierOutputWithPast]: - r""" - labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): - Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., - config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If - `config.num_labels > 1` a classification loss is computed (Cross-Entropy). - """ - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - outputs = self.model( - input_ids=input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - past_key_values=past_key_values, - inputs_embeds=inputs_embeds, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - hidden_states = outputs[0] - logits = self.classifier(hidden_states) - - if input_ids is not None: - batch_size = input_ids.shape[0] - else: - batch_size = inputs_embeds.shape[0] - - if self.config.pad_token_id is None and batch_size != 1: - raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") - if self.config.pad_token_id is None: - sequence_lengths = -1 - else: - if input_ids is not None: - # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility - sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 - sequence_lengths = sequence_lengths % input_ids.shape[-1] - sequence_lengths = sequence_lengths.to(logits.device) - else: - sequence_lengths = -1 - - pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] - - loss = None - if labels is not None: - loss = self.loss_function( - logits=logits, - labels=labels, - pooled_logits=pooled_logits, - config=self.config, - ) - - if not return_dict: - output = (pooled_logits,) + outputs[1:] - return ((loss,) + output) if loss is not None else output - - return SequenceClassifierOutputWithPast( - loss=loss, - logits=pooled_logits, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) - __all__ = [ "DogeConfig", diff --git a/src/transformers/utils/__init__.py b/src/transformers/utils/__init__.py index e5aedf5916fa..b3c99b704644 100755 --- a/src/transformers/utils/__init__.py +++ b/src/transformers/utils/__init__.py @@ -133,6 +133,7 @@ is_decord_available, is_detectron2_available, is_eetq_available, + is_einx_available, is_essentia_available, is_faiss_available, is_fbgemm_gpu_available, diff --git a/src/transformers/utils/import_utils.py b/src/transformers/utils/import_utils.py index ac07281b3d33..736094375d6a 100755 --- a/src/transformers/utils/import_utils.py +++ b/src/transformers/utils/import_utils.py @@ -475,6 +475,12 @@ def is_causal_conv1d_available(): return False +def is_einx_available(): + if is_torch_available(): + return _is_package_available("einx") + return False + + def is_mambapy_available(): if is_torch_available(): return _is_package_available("mambapy") From 941d6b5975c397b0fd1c7aa1e2784770fe9e5afc Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Tue, 28 Jan 2025 12:07:03 +0800 Subject: [PATCH 08/20] Fix import bug --- .../models/doge/configuration_doge.py | 7 ------- src/transformers/models/doge/modeling_doge.py | 18 ++++-------------- src/transformers/models/doge/modular_doge.py | 18 ++++-------------- src/transformers/utils/__init__.py | 1 - src/transformers/utils/import_utils.py | 6 ------ 5 files changed, 8 insertions(+), 42 deletions(-) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index d178e59b60e9..adee0287ac8f 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -23,13 +23,6 @@ # limitations under the License. from ...modeling_rope_utils import rope_config_validation from ...modeling_utils import PretrainedConfig -from ...utils import is_einx_available - - -if is_einx_available(): - from einx import add as einx_add -else: - einx_add = None class DogeConfig(PretrainedConfig): diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index 0ba264ff85a5..577f4ba7292d 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -40,7 +40,6 @@ LossKwargs, add_start_docstrings, add_start_docstrings_to_model_forward, - is_einx_available, is_torch_flex_attn_available, logging, replace_return_docstrings, @@ -49,11 +48,6 @@ from .configuration_doge import DogeConfig -if is_einx_available(): - from einx import add as einx_add -else: - einx_add = None - if is_torch_flex_attn_available(): from torch.nn.attention.flex_attention import flex_attention @@ -487,14 +481,10 @@ def forward( # get experts with the highest similarity (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmoe_experts_per_head, dim=-1) - if einx_add is not None: - all_scores = einx_add("... i, ... j -> ... (i j)", scores_x, scores_y) - all_indices = einx_add("... i, ... j -> ... (i j)", indices_x * self.num_keys, indices_y) - else: - all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) - all_scores = all_scores.view(*scores_x.shape[:-1], -1) - all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) - all_indices = all_indices.view(*indices_x.shape[:-1], -1) + all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) + all_scores = all_scores.view(*scores_x.shape[:-1], -1) + all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) + all_indices = all_indices.view(*indices_x.shape[:-1], -1) scores, pk_indices = all_scores.topk(self.num_cdmoe_experts_per_head, dim=-1) indices = all_indices.gather(-1, pk_indices) down_embed = self.down_embed(indices) diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index eb38e4fe7768..07d03585ce9a 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -44,7 +44,6 @@ LossKwargs, add_start_docstrings, add_start_docstrings_to_model_forward, - is_einx_available, is_torch_flex_attn_available, logging, replace_return_docstrings, @@ -52,11 +51,6 @@ from ...utils.deprecation import deprecate_kwarg -if is_einx_available(): - from einx import add as einx_add -else: - einx_add = None - if is_torch_flex_attn_available(): from torch.nn.attention.flex_attention import flex_attention @@ -625,14 +619,10 @@ def forward( # get experts with the highest similarity (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmoe_experts_per_head, dim=-1) - if einx_add is not None: - all_scores = einx_add("... i, ... j -> ... (i j)", scores_x, scores_y) - all_indices = einx_add("... i, ... j -> ... (i j)", indices_x * self.num_keys, indices_y) - else: - all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) - all_scores = all_scores.view(*scores_x.shape[:-1], -1) - all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) - all_indices = all_indices.view(*indices_x.shape[:-1], -1) + all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) + all_scores = all_scores.view(*scores_x.shape[:-1], -1) + all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) + all_indices = all_indices.view(*indices_x.shape[:-1], -1) scores, pk_indices = all_scores.topk(self.num_cdmoe_experts_per_head, dim=-1) indices = all_indices.gather(-1, pk_indices) down_embed = self.down_embed(indices) diff --git a/src/transformers/utils/__init__.py b/src/transformers/utils/__init__.py index b3c99b704644..e5aedf5916fa 100755 --- a/src/transformers/utils/__init__.py +++ b/src/transformers/utils/__init__.py @@ -133,7 +133,6 @@ is_decord_available, is_detectron2_available, is_eetq_available, - is_einx_available, is_essentia_available, is_faiss_available, is_fbgemm_gpu_available, diff --git a/src/transformers/utils/import_utils.py b/src/transformers/utils/import_utils.py index 736094375d6a..ac07281b3d33 100755 --- a/src/transformers/utils/import_utils.py +++ b/src/transformers/utils/import_utils.py @@ -475,12 +475,6 @@ def is_causal_conv1d_available(): return False -def is_einx_available(): - if is_torch_available(): - return _is_package_available("einx") - return False - - def is_mambapy_available(): if is_torch_available(): return _is_package_available("mambapy") From 14661427b52c5da7e6db7f33f6098c37a1e8e4cb Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Tue, 28 Jan 2025 21:06:02 +0800 Subject: [PATCH 09/20] [docs] Add usage of doge model --- docs/source/en/model_doc/doge.md | 59 ++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/docs/source/en/model_doc/doge.md b/docs/source/en/model_doc/doge.md index 7c4b2468861a..65c1cc8cae47 100644 --- a/docs/source/en/model_doc/doge.md +++ b/docs/source/en/model_doc/doge.md @@ -21,9 +21,68 @@ rendered properly in your Markdown viewer. Doge is a series of small language models based on the [Doge](https://github.com/LoserCheems/WonderfulMatrices) architecture, aiming to combine the advantages of state-space and self-attention algorithms, calculate dynamic masks from cached value states using the zero-order hold method, and solve the problem of existing mainstream language models getting lost in context. It uses the `wsd_scheduler` scheduler to pre-train on the `smollm-corpus`, and can continue training on new datasets or add sparse activation feedforward networks from stable stage checkpoints. +drawing + +As shown in the figure below, the sequence transformation part of the Doge architecture uses `Dynamic Mask Attention`, which can be understood as using self-attention related to value states during training, and using state-space without past state decay during inference, to solve the problem of existing Transformers or SSMs getting lost in long text. The state transformation part of Doge uses `Cross Domain Mixture of Experts`, which consists of dense linear layers and sparse embedding layers, and can additionally increase sparse parameters to continue training from dense weight checkpoints without retraining the entire model, thereby reducing the cost of continuous iteration of the model. In addition, Doge also uses `RMSNorm` and `Residual` with learnable parameters to adapt the gradient range of deep models. + Checkout all Doge model checkpoints [here](https://huggingface.co/collections/JingzeShi/doge-slm-677fd879f8c4fd0f43e05458). +## Usage + +
+Using Doge-Base for text generation + +```python +from transformers import AutoTokenizer, AutoModelForCausalLM + +tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") +>model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M", trust_remote_code=True) +inputs = tokenizer("Hey how are you doing?", return_tensors="pt") + +outputs = model.generate(**inputs, max_new_tokens=100) +print(tokenizer.batch_decode(outputs)) +``` +
+ +
+Using Doge-Instruct for question answering + +```python +from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, TextStreamer + +tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct") +model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M-Instruct") + +generation_config = GenerationConfig( + max_new_tokens=100, + use_cache=True, + do_sample=True, + temperature=0.8, + top_p=0.9, + repetition_penalty=1.0 +) +steamer = TextStreamer(tokenizer=tokenizer, skip_prompt=True) + +prompt = "Hi, how are you doing today?" +conversation = [ + {"role": "user", "content": prompt} +] +inputs = tokenizer.apply_chat_template( + conversation=conversation, + tokenize=True, + return_tensors="pt", +) + +outputs = model.generate( + inputs, + tokenizer=tokenizer, + generation_config=generation_config, + streamer=steamer +) +``` +
+ ## DogeConfig [[autodoc]] DogeConfig From aa4fcfdb727f6d505015a301dc1b935a04d84f9c Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Wed, 29 Jan 2025 00:13:08 +0800 Subject: [PATCH 10/20] Fix Doge import pretrainedconfig from modeling_utils to configuration_utils --- src/transformers/models/doge/configuration_doge.py | 2 +- src/transformers/models/doge/modular_doge.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index adee0287ac8f..2dd5dcd5a15a 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -21,8 +21,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +from ...configuration_utils import PretrainedConfig from ...modeling_rope_utils import rope_config_validation -from ...modeling_utils import PretrainedConfig class DogeConfig(PretrainedConfig): diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 07d03585ce9a..5ebaa901ed01 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -22,6 +22,7 @@ import torch import torch.nn.functional as F +import torch.utils.checkpoint from torch import nn from transformers.models.llama.modeling_llama import ( @@ -32,13 +33,14 @@ from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache, StaticCache +from ...configuration_utils import PretrainedConfig from ...generation import GenerationMixin from ...modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, ) from ...modeling_rope_utils import rope_config_validation -from ...modeling_utils import PretrainedConfig, PreTrainedModel +from ...modeling_utils import PreTrainedModel from ...processing_utils import Unpack from ...utils import ( LossKwargs, From 7cbea8945dc88ac62505d4f3501930df15b2f7f8 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Wed, 29 Jan 2025 00:30:58 +0800 Subject: [PATCH 11/20] [docs] remove trust remote code from doge --- docs/source/en/model_doc/doge.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/en/model_doc/doge.md b/docs/source/en/model_doc/doge.md index 65c1cc8cae47..11e9145ef6ac 100644 --- a/docs/source/en/model_doc/doge.md +++ b/docs/source/en/model_doc/doge.md @@ -37,7 +37,7 @@ Checkout all Doge model checkpoints [here](https://huggingface.co/collections/Ji from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") ->model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M", trust_remote_code=True) +model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M") inputs = tokenizer("Hey how are you doing?", return_tensors="pt") outputs = model.generate(**inputs, max_new_tokens=100) From c935266ecc38858e44990b5a888756ca4ce86176 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Wed, 29 Jan 2025 09:05:40 +0800 Subject: [PATCH 12/20] Fix dynamo bug in doge model --- src/transformers/models/doge/configuration_doge.py | 9 +++------ src/transformers/models/doge/modular_doge.py | 9 +++------ 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index 2dd5dcd5a15a..c873ce18d7f9 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -67,9 +67,10 @@ class DogeConfig(PretrainedConfig): The maximum sequence length that this model might ever be used with. rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. - rope_scaling (`Dict`, *optional*, defaults to `{'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048}`): + rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. + Doge family of small models use `{ 'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048 }` as the default value. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. @@ -168,11 +169,7 @@ def __init__( tie_word_embeddings=False, max_position_embeddings=2048, rope_theta=10000.0, - rope_scaling={ - "rope_type": "dynamic", - "factor": 4.0, - "original_max_position_embeddings": 2048, - }, + rope_scaling=None, num_attention_heads=8, num_key_value_heads=None, attention_dropout=0.0, diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 5ebaa901ed01..ddc0378d6344 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -104,9 +104,10 @@ class DogeConfig(PretrainedConfig): The maximum sequence length that this model might ever be used with. rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. - rope_scaling (`Dict`, *optional*, defaults to `{'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048}`): + rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. + Doge family of small models use `{ 'rope_type': 'dynamic', 'factor': 4.0, 'original_max_position_embeddings': 2048 }` as the default value. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. @@ -205,11 +206,7 @@ def __init__( tie_word_embeddings=False, max_position_embeddings=2048, rope_theta=10000.0, - rope_scaling={ - "rope_type": "dynamic", - "factor": 4.0, - "original_max_position_embeddings": 2048, - }, + rope_scaling=None, num_attention_heads=8, num_key_value_heads=None, attention_dropout=0.0, From 9612ddb1eaea9a64f36e4ae9d9107f75a6b25619 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Fri, 31 Jan 2025 22:06:21 +0800 Subject: [PATCH 13/20] Update docstrings --- docs/source/en/model_doc/doge.md | 10 +++++----- src/transformers/models/doge/configuration_doge.py | 2 +- src/transformers/models/doge/modeling_doge.py | 4 ++-- src/transformers/models/doge/modular_doge.py | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/source/en/model_doc/doge.md b/docs/source/en/model_doc/doge.md index 11e9145ef6ac..fbcbd0144fbb 100644 --- a/docs/source/en/model_doc/doge.md +++ b/docs/source/en/model_doc/doge.md @@ -25,7 +25,7 @@ Doge is a series of small language models based on the [Doge](https://github.com As shown in the figure below, the sequence transformation part of the Doge architecture uses `Dynamic Mask Attention`, which can be understood as using self-attention related to value states during training, and using state-space without past state decay during inference, to solve the problem of existing Transformers or SSMs getting lost in long text. The state transformation part of Doge uses `Cross Domain Mixture of Experts`, which consists of dense linear layers and sparse embedding layers, and can additionally increase sparse parameters to continue training from dense weight checkpoints without retraining the entire model, thereby reducing the cost of continuous iteration of the model. In addition, Doge also uses `RMSNorm` and `Residual` with learnable parameters to adapt the gradient range of deep models. -Checkout all Doge model checkpoints [here](https://huggingface.co/collections/JingzeShi/doge-slm-677fd879f8c4fd0f43e05458). +Checkout all Doge model checkpoints [here](https://huggingface.co/collections/SmallDoge/doge-slm-679cc991f027c4a3abbded4a). ## Usage @@ -36,8 +36,8 @@ Checkout all Doge model checkpoints [here](https://huggingface.co/collections/Ji ```python from transformers import AutoTokenizer, AutoModelForCausalLM -tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") -model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M") +tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-20M") +model = AutoModelForCausalLM.from_pretrained("SmallDoge/Doge-20M") inputs = tokenizer("Hey how are you doing?", return_tensors="pt") outputs = model.generate(**inputs, max_new_tokens=100) @@ -51,8 +51,8 @@ print(tokenizer.batch_decode(outputs)) ```python from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, TextStreamer -tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct") -model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M-Instruct") +tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-20M-Instruct") +model = AutoModelForCausalLM.from_pretrained("SmallDoge/Doge-20M-Instruct") generation_config = GenerationConfig( max_new_tokens=100, diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index c873ce18d7f9..a0eee44ce6eb 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -28,7 +28,7 @@ class DogeConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge - model according to the specified arguments, defining the model architecture like [JingzeShi/Doge-20M](https://huggingface.co/JingzeShi/Doge-20M). + model according to the specified arguments, defining the model architecture like [SmallDoge/Doge-20M](https://huggingface.co/SmallDoge/Doge-20M). Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index 577f4ba7292d..bf824b7fed13 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -986,8 +986,8 @@ def forward( ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM - >>> model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M") - >>> tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") + >>> model = AutoModelForCausalLM.from_pretrained("SmallDoge/Doge-20M") + >>> tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-20M") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index ddc0378d6344..c06c38ab5527 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -65,7 +65,7 @@ class DogeConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge - model according to the specified arguments, defining the model architecture like [JingzeShi/Doge-20M](https://huggingface.co/JingzeShi/Doge-20M). + model according to the specified arguments, defining the model architecture like [SmallDoge/Doge-20M](https://huggingface.co/SmallDoge/Doge-20M). Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. @@ -1123,8 +1123,8 @@ def forward( ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM - >>> model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M") - >>> tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M") + >>> model = AutoModelForCausalLM.from_pretrained("SmallDoge/Doge-20M") + >>> tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-20M") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") From 8e094752b9a31fc441ef662b9100b801131d9821 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Wed, 5 Feb 2025 02:43:10 +0800 Subject: [PATCH 14/20] Import apply_rotary_pos_emb and repeat_kv from Llama --- src/transformers/models/doge/modeling_doge.py | 22 ++++---- src/transformers/models/doge/modular_doge.py | 54 ++----------------- 2 files changed, 12 insertions(+), 64 deletions(-) diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index bf824b7fed13..5b5dece7efc5 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -151,9 +151,7 @@ def forward(self, x, position_ids): def rotate_half(x): - """ - Rotates half the hidden dims of the input. - """ + """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) @@ -171,10 +169,11 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): Deprecated and unused. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and - sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. - For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. - Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. - Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ @@ -187,8 +186,8 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ - This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). - The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: @@ -911,9 +910,6 @@ def _prepare_4d_causal_attention_mask_with_cache_position( return causal_mask -class KwargsForCausalLM(LossKwargs): ... - - class DogeForCausalLM(DogePreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} @@ -963,7 +959,7 @@ def forward( return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: int = 0, - **kwargs: Unpack[KwargsForCausalLM], + **kwargs: Unpack[LossKwargs], ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index c06c38ab5527..d318421769b1 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -29,6 +29,8 @@ LlamaForSequenceClassification, LlamaRMSNorm, LlamaRotaryEmbedding, + apply_rotary_pos_emb, + repeat_kv, ) from ...activations import ACT2FN @@ -287,53 +289,6 @@ def __init__(self, config: Optional[DogeConfig] = None, device=None): super().__init__(config, device) -def rotate_half(x): - """ - Rotates half the hidden dims of the input. - """ - x1 = x[..., : x.shape[-1] // 2] - x2 = x[..., x.shape[-1] // 2 :] - return torch.cat((-x2, x1), dim=-1) - - -def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): - """Applies Rotary Position Embedding to the query and key tensors. - - Args: - q (`torch.Tensor`): The query tensor. - k (`torch.Tensor`): The key tensor. - cos (`torch.Tensor`): The cosine part of the rotary embedding. - sin (`torch.Tensor`): The sine part of the rotary embedding. - position_ids (`torch.Tensor`, *optional*): - Deprecated and unused. - unsqueeze_dim (`int`, *optional*, defaults to 1): - The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and - sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. - For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. - Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. - Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. - Returns: - `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. - """ - cos = cos.unsqueeze(unsqueeze_dim) - sin = sin.unsqueeze(unsqueeze_dim) - q_embed = (q * cos) + (rotate_half(q) * sin) - k_embed = (k * cos) + (rotate_half(k) * sin) - return q_embed, k_embed - - -def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: - """ - This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). - The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) - """ - batch, num_key_value_heads, slen, head_dim = hidden_states.shape - if n_rep == 1: - return hidden_states - hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) - return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) - - class DogeDynamicMaskAttention(nn.Module): """Dynamic Mask Attention from 'Wonderful Matrices' paper.""" @@ -1048,9 +1003,6 @@ def _prepare_4d_causal_attention_mask_with_cache_position( return causal_mask -class KwargsForCausalLM(LossKwargs): ... - - class DogeForCausalLM(DogePreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} @@ -1100,7 +1052,7 @@ def forward( return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: int = 0, - **kwargs: Unpack[KwargsForCausalLM], + **kwargs: Unpack[LossKwargs], ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: From 49bca1f6617cec1a480f0e65dad2698cd5f3330a Mon Sep 17 00:00:00 2001 From: LoserCheems <3314685395@qq.com> Date: Thu, 6 Feb 2025 22:44:58 +0800 Subject: [PATCH 15/20] Fix all nits --- src/transformers/models/doge/modular_doge.py | 424 ++++++++----------- 1 file changed, 181 insertions(+), 243 deletions(-) diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index d318421769b1..55025c28b7ef 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -26,6 +26,7 @@ from torch import nn from transformers.models.llama.modeling_llama import ( + LlamaModel, LlamaForSequenceClassification, LlamaRMSNorm, LlamaRotaryEmbedding, @@ -43,7 +44,9 @@ ) from ...modeling_rope_utils import rope_config_validation from ...modeling_utils import PreTrainedModel +from modeling_utils import ALL_ATTENTION_FUNCTIONS from ...processing_utils import Unpack +from ...pytorch_utils import ALL_LAYERNORM_LAYERS from ...utils import ( LossKwargs, add_start_docstrings, @@ -61,6 +64,7 @@ logger = logging.get_logger(__name__) +_CHECKPOINT_FOR_DOC = "SmallDoge/Doge-20M" _CONFIG_FOR_DOC = "DogeConfig" @@ -183,7 +187,7 @@ class DogeConfig(PretrainedConfig): "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", - "layers.*.self_attn.dt_proj": "colwise", + "layers.*.self_attn.dt_proj": "rowwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", @@ -264,15 +268,14 @@ def __init__( ) -class RMSNorm(LlamaRMSNorm): - def __init__(self, hidden_size, eps=1e-6): - """ - RMSNorm is equivalent to T5LayerNorm - """ - super().__init__(hidden_size, eps) +class DogeRMSNorm(LlamaRMSNorm): + pass + + +ALL_LAYERNORM_LAYERS.append(DogeRMSNorm) -class Residual(nn.Module): +class DogeResidual(nn.Module): def __init__(self, hidden_size): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) @@ -284,9 +287,138 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}" -class RotaryEmbedding(LlamaRotaryEmbedding): - def __init__(self, config: Optional[DogeConfig] = None, device=None): - super().__init__(config, device) +class DogeRotaryEmbedding(LlamaRotaryEmbedding): + pass + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, +) -> Tuple[torch.Tensor, torch.Tensor]: + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + + attn_weights = torch.matmul(query, key_states.transpose(-1, -2)) * scaling + if attention_mask is not None: + causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] + attn_weights = attn_weights + causal_mask + + attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = F.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, attn_weights + + +def sdpa_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, +) -> Tuple[torch.Tensor, None]: + key = repeat_kv(key, module.num_key_value_groups) + value = repeat_kv(value, module.num_key_value_groups) + + causal_mask = attention_mask + if attention_mask is not None: + causal_mask = causal_mask[:, :, :, : key.shape[-2]] + + # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions + # Reference: https://github.com/pytorch/pytorch/issues/112577. + query = query.contiguous() + key = key.contiguous() + value = value.contiguous() + + # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment + # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling. + if is_causal is None: + is_causal = causal_mask is None and query.shape[2] > 1 + + # Shapes (e.g. query.shape[2]) are tensors during jit tracing, resulting in `is_causal` being a tensor. + # We convert it to a bool for the SDPA kernel that only accepts bools. + if torch.jit.is_tracing() and isinstance(is_causal, torch.Tensor): + is_causal = is_causal.item() + + # NOTE: As of pytorch 2.5.1, SDPA backward pass of cuDNN is still incorrect, so we disable cuDNN SDPA (see https://github.com/pytorch/pytorch/issues/138581) + torch.backends.cuda.enable_cudnn_sdp(False) + attn_output = F.scaled_dot_product_attention( + query=query, + key=key, + value=value, + attn_mask=causal_mask, + dropout_p=dropout, + scale=scaling, + is_causal=is_causal, + ) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, None + + +def flex_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, +) -> Tuple[torch.Tensor, torch.Tensor]: + causal_mask = attention_mask + if attention_mask is not None: + causal_mask = causal_mask[:, :, :, : key.shape[-2]] + + if is_causal is None: + is_causal = causal_mask is None and query.shape[2] > 1 + + def causal_mod(score, batch, head, q_idx, kv_idx): + score = score + causal_mask[batch][0][q_idx][kv_idx] + return score + + def dynamic_mod(score, batch, head, q_idx, kv_idx): + score = score + causal_mask[batch][head][q_idx][kv_idx] + return score + + # TODO: flex_attention: As of pytorch 2.5.1, captured buffers that require grad are not yet supported. + # NOTE: So we only use flex_attention in inference mode. + mask_mod = causal_mod if is_causal or module.training else dynamic_mod + + attn_output, attention_weights = flex_attention( + query=query, + key=key, + value=value, + score_mod=mask_mod, + enable_gqa=True, + scale=scaling, + # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless. + # For simplification, we thus always return it as no additional computations are introduced. + return_lse=True, + ) + # lse is returned in float32 + attention_weights = attention_weights.to(value.dtype) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, attention_weights + + +ALL_ATTENTION_FUNCTIONS.update( + { + "sdpa": sdpa_attention_forward, + "flex_attention": flex_attention_forward, + } +) class DogeDynamicMaskAttention(nn.Module): @@ -296,19 +428,12 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx - self.head_dim = config.hidden_size // config.num_attention_heads + self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.dynamic_mask_ratio = config.dynamic_mask_ratio - self.ALL_ATTENTION_FUNCTIONS = { - "eager": self.eager_attention_forward, - "flex_attention": self.flex_attention_forward, - "sdpa": self.sdpa_attention_forward, - } - - # Q K V O projections self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.hidden_bias ) @@ -318,7 +443,7 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.hidden_bias ) - # dynamic mask for the QK^T attention score matrix + # dynamic mask for the QK^T attention weights matrix self.A = nn.Parameter(torch.zeros(config.num_attention_heads)) self.dt_proj = nn.Linear( config.num_key_value_heads * self.head_dim, config.num_attention_heads, bias=config.hidden_bias @@ -335,7 +460,7 @@ def forward( past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, - ) -> Tuple[torch.Tensor, Optional[Cache]]: + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) @@ -353,7 +478,7 @@ def forward( # calculate dynamic mask from value_states dt_states = self.dt_proj( - value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1) + value_states.transpose(1, 2).reshape(input_shape, -1) ) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( @@ -363,11 +488,18 @@ def forward( attention_mask=attention_mask, ) - attention_interface: Callable = self.eager_attention_forward + attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": - attention_interface = self.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] + if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): + logger.warning_once( + "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to " + 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' + ) + else: + attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] - attn_output = attention_interface( + attn_output, attn_weights = attention_interface( + self, query_states, key_states, value_states, @@ -379,7 +511,7 @@ def forward( attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) - return attn_output + return attn_output, attn_weights def prepare_dynamic_mask( self, @@ -413,109 +545,6 @@ def prepare_dynamic_mask( return attn_mask - def eager_attention_forward( - self, - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - attention_mask: Optional[torch.Tensor], - scaling: float, - dropout: float = 0.0, - **kwargs, - ) -> torch.Tensor: - key_states = repeat_kv(key, self.num_key_value_groups) - value_states = repeat_kv(value, self.num_key_value_groups) - - # compute attention scores matrix - attn_weights = torch.matmul(query, key_states.transpose(-1, -2)) * scaling - if attention_mask is not None: - causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] - attn_weights = attn_weights + causal_mask - - # upcast attention scores to fp32 - attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) - attn_weights = F.dropout(attn_weights, p=dropout, training=self.training) - - # apply attention scores to value states - attn_output = torch.matmul(attn_weights, value_states) - attn_output = attn_output.transpose(1, 2).contiguous() - return attn_output - - def sdpa_attention_forward( - self, - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - attention_mask: Optional[torch.Tensor], - scaling: float, - dropout: float = 0.0, - **kwargs, - ) -> torch.Tensor: - key = repeat_kv(key, self.num_key_value_groups) - value = repeat_kv(value, self.num_key_value_groups) - - causal_mask = attention_mask - if attention_mask is not None: - causal_mask = causal_mask[:, :, :, : key.shape[-2]] - - # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions - # Reference: https://github.com/pytorch/pytorch/issues/112577. - query = query.contiguous() - key = key.contiguous() - value = value.contiguous() - - # NOTE: As of pytorch 2.5.1, cuDNN's SDPA backward pass is still incorrect, so we disable cuDNN SDPA (see https://github.com/pytorch/pytorch/issues/138581) - torch.backends.cuda.enable_cudnn_sdp(False) - attn_output = F.scaled_dot_product_attention( - query, - key, - value, - attn_mask=causal_mask, - dropout_p=dropout, - scale=scaling, - ) - attn_output = attn_output.transpose(1, 2).contiguous() - return attn_output - - def flex_attention_forward( - self, - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - attention_mask: Optional[torch.Tensor], - scaling: float, - dropout: float = 0.0, - **kwargs, - ) -> torch.Tensor: - key = repeat_kv(key, self.num_key_value_groups) - value = repeat_kv(value, self.num_key_value_groups) - - causal_mask = attention_mask - if attention_mask is not None: - causal_mask = causal_mask[:, :, :, : key.shape[-2]] - - # TODO: flex_attention: As of pytorch 2.5.1, captured buffers that require grad are not yet supported. - # NOTE: So we only use flex_attention in inference mode. - def causal_mod(score, batch, head, q_idx, kv_idx): - score = score + causal_mask[batch][0][q_idx][kv_idx] - return score - - def dynamic_mod(score, batch, head, q_idx, kv_idx): - score = score + causal_mask[batch][head][q_idx][kv_idx] - return score - - mask_mod = causal_mod if self.is_causal else dynamic_mod - - attn_output = flex_attention( - query, - key, - value, - score_mod=mask_mod, - scale=scaling, - ) - attn_output = attn_output.transpose(1, 2).contiguous() - return attn_output - class DogeMLP(nn.Module): def __init__(self, config: DogeConfig): @@ -552,8 +581,8 @@ def __init__(self, config: DogeConfig): self.num_keys = int(math.sqrt(self.num_cdmoe_experts)) # queries and keys for retrieval experts - self.queries = nn.Linear(self.hidden_dim, self.num_cdmoe_heads * self.expert_retrieval_dim, bias=False) - self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.num_keys, 2, self.expert_retrieval_dim // 2)) + self.queries_proj = nn.Linear(self.hidden_dim, self.num_cdmoe_heads * self.expert_retrieval_dim, bias=False) + self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.expert_retrieval_dim, self.num_keys)) # experts self.down_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) @@ -566,13 +595,15 @@ def forward( ) -> torch.Tensor: bsz, seq_len, _ = hidden_states.shape - # get similarity with queries and keys - queries = self.queries(hidden_states) - queries = queries.view(bsz, seq_len, 2, self.num_cdmoe_heads, -1).permute(2, 0, 1, 3, 4) - sim = torch.einsum("p b t h n, h k p n -> p b t h k", queries, self.keys) + # get routing weights with queries and keys + queries = self.queries_proj(hidden_states) + queries = queries.view(2 * self.num_cdmoe_heads, bsz * seq_len, -1) + keys = self.keys.view(2 * self.num_cdmoe_heads, -1, self.num_keys) + routing_weights = torch.matmul(queries, keys) + routing_weights = routing_weights.view(2, bsz, seq_len, self.num_cdmoe_heads, self.num_keys) - # get experts with the highest similarity - (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmoe_experts_per_head, dim=-1) + # get experts with the highest routing weights + (scores_x, scores_y), (indices_x, indices_y) = routing_weights.topk(self.num_cdmoe_experts_per_head, dim=-1) all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) all_scores = all_scores.view(*scores_x.shape[:-1], -1) all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) @@ -583,9 +614,9 @@ def forward( up_embed = self.up_embed(indices) # mix experts states with cross domain states - experts_weights = torch.einsum("b t d, b t h k d -> b t h k", hidden_states, down_embed) + experts_weights = (hidden_states[:, :, None, None, :] * down_embed).sum(dim=-1) experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) - experts_states = torch.einsum("b t h k, b t h k d -> b t d", experts_weights, up_embed) + experts_states = (experts_weights[:, :, :, None, :] * up_embed).sum(dim=-2).sum(dim=-2) hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) hidden_states = hidden_states + experts_states return hidden_states @@ -596,13 +627,13 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): super().__init__() self.hidden_dropout = config.hidden_dropout - self.pre_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.pre_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.self_attn = DogeDynamicMaskAttention(config=config, layer_idx=layer_idx) - self.pre_residual = Residual(config.hidden_size) + self.pre_residual = DogeResidual(config.hidden_size) - self.post_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.feed_forward = DogeMLP(config) if not config.is_moe else DogeCDMoE(config) - self.post_residual = Residual(config.hidden_size) + self.post_residual = DogeResidual(config.hidden_size) def forward( self, @@ -619,11 +650,13 @@ def forward( # sequence transformation residual = hidden_states hidden_states = self.pre_layernorm(hidden_states) - hidden_states = self.self_attn( + hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, @@ -770,7 +803,7 @@ def _init_weights(self, module): "The bare Doge Model outputting raw hidden-states without any specific head on top.", DOGE_START_DOCSTRING, ) -class DogeModel(DogePreTrainedModel): +class DogeModel(DogePreTrainedModel, LlamaModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DogeDecoderLayer`] @@ -785,11 +818,11 @@ def __init__(self, config: DogeConfig): self.vocab_size = config.vocab_size self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) - self.rotary_emb = RotaryEmbedding(config) + self.rotary_emb = DogeRotaryEmbedding(config) self.layers = nn.ModuleList( [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) - self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.final_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.gradient_checkpointing = False # Initialize weights and apply final processing @@ -908,100 +941,6 @@ def forward( ) return output if return_dict else output.to_tuple() - def _update_causal_mask( - self, - attention_mask: torch.Tensor, - input_tensor: torch.Tensor, - cache_position: torch.Tensor, - past_key_values: Cache, - output_attentions: bool, - ): - past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 - using_static_cache = isinstance(past_key_values, StaticCache) - - dtype, device = input_tensor.dtype, input_tensor.device - sequence_length = input_tensor.shape[1] - if using_static_cache: - target_length = past_key_values.get_max_cache_shape() - else: - target_length = ( - attention_mask.shape[-1] - if isinstance(attention_mask, torch.Tensor) - else past_seen_tokens + sequence_length + 1 - ) - - # in case the provided `attention` mask is 2D, we generate a causal mask here (4D). - causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( - attention_mask=attention_mask, - sequence_length=sequence_length, - target_length=target_length, - dtype=dtype, - device=device, - cache_position=cache_position, - batch_size=input_tensor.shape[0], - ) - - return causal_mask - - @staticmethod - def _prepare_4d_causal_attention_mask_with_cache_position( - attention_mask: torch.Tensor = None, - sequence_length: int = None, - target_length: int = None, - dtype: torch.dtype = None, - device: torch.device = None, - cache_position: torch.Tensor = None, - batch_size: int = None, - **kwargs, - ): - """ - Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape - `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. - - Args: - attention_mask (`torch.Tensor`): - A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape - `(batch_size, 1, query_length, key_value_length)`. - sequence_length (`int`): - The sequence length being processed. - target_length (`int`): - The target length: when generating with static cache, the mask should be as long as the static cache, - to account for the 0 padding, the part of the cache that is not filled yet. - dtype (`torch.dtype`): - The dtype to use for the 4D attention mask. - device (`torch.device`): - The device to plcae the 4D attention mask on. - cache_position (`torch.Tensor`): - Indices depicting the position of the input sequence tokens in the sequence. - batch_size (`torch.Tensor`): - Batch size. - """ - if attention_mask is not None and attention_mask.dim() == 4: - # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. - causal_mask = attention_mask - else: - min_dtype = torch.finfo(dtype).min - causal_mask = torch.full( - (sequence_length, target_length), - fill_value=min_dtype, - dtype=dtype, - device=device, - ) - if sequence_length != 1: - causal_mask = torch.triu(causal_mask, diagonal=1) - causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) - causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) - if attention_mask is not None: - causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit - mask_length = attention_mask.shape[-1] - padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] - padding_mask = padding_mask == 0 - causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( - padding_mask, min_dtype - ) - - return causal_mask - class DogeForCausalLM(DogePreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] @@ -1035,7 +974,6 @@ def get_decoder(self): def set_decoder(self, decoder): self.model = decoder - @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( @@ -1051,7 +989,7 @@ def forward( output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, - logits_to_keep: int = 0, + logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[LossKwargs], ) -> Union[Tuple, CausalLMOutputWithPast]: r""" From d33af946b2e9568a8e0c0832be47e3a65733300f Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Thu, 6 Feb 2025 23:03:12 +0800 Subject: [PATCH 16/20] Fix code quality --- .../models/doge/configuration_doge.py | 2 +- src/transformers/models/doge/modeling_doge.py | 302 ++++++++---------- src/transformers/models/doge/modular_doge.py | 38 ++- 3 files changed, 151 insertions(+), 191 deletions(-) diff --git a/src/transformers/models/doge/configuration_doge.py b/src/transformers/models/doge/configuration_doge.py index a0eee44ce6eb..3df866d22343 100644 --- a/src/transformers/models/doge/configuration_doge.py +++ b/src/transformers/models/doge/configuration_doge.py @@ -144,7 +144,7 @@ class DogeConfig(PretrainedConfig): "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", - "layers.*.self_attn.dt_proj": "colwise", + "layers.*.self_attn.dt_proj": "rowwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index 5b5dece7efc5..cd8d61a6f8f2 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -32,35 +32,30 @@ from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache, StaticCache from ...generation import GenerationMixin +from ...modeling_attn_mask_utils import AttentionMaskConverter from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS -from ...modeling_utils import PreTrainedModel +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( LossKwargs, add_start_docstrings, add_start_docstrings_to_model_forward, - is_torch_flex_attn_available, logging, replace_return_docstrings, ) -from ...utils.deprecation import deprecate_kwarg from .configuration_doge import DogeConfig -if is_torch_flex_attn_available(): - from torch.nn.attention.flex_attention import flex_attention - - logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "DogeConfig" -class RMSNorm(nn.Module): +class DogeRMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ - RMSNorm is equivalent to T5LayerNorm + DogeRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) @@ -77,7 +72,7 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" -class Residual(nn.Module): +class DogeResidual(nn.Module): def __init__(self, hidden_size): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) @@ -89,8 +84,8 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}" -class RotaryEmbedding(nn.Module): - def __init__(self, config: Optional[DogeConfig] = None, device=None): +class DogeRotaryEmbedding(nn.Module): + def __init__(self, config: DogeConfig, device=None): super().__init__() # BC: "rope_type" was originally "type" if hasattr(config, "rope_scaling") and config.rope_scaling is not None: @@ -196,6 +191,32 @@ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + scaling: float, + dropout: float = 0.0, + **kwargs, +) -> Tuple[torch.Tensor, torch.Tensor]: + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + + attn_weights = torch.matmul(query, key_states.transpose(-1, -2)) * scaling + if attention_mask is not None: + causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] + attn_weights = attn_weights + causal_mask + + attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = F.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, attn_weights + + class DogeDynamicMaskAttention(nn.Module): """Dynamic Mask Attention from 'Wonderful Matrices' paper.""" @@ -203,19 +224,12 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx - self.head_dim = config.hidden_size // config.num_attention_heads + self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.dynamic_mask_ratio = config.dynamic_mask_ratio - self.ALL_ATTENTION_FUNCTIONS = { - "eager": self.eager_attention_forward, - "flex_attention": self.flex_attention_forward, - "sdpa": self.sdpa_attention_forward, - } - - # Q K V O projections self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.hidden_bias ) @@ -225,7 +239,7 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.hidden_bias ) - # dynamic mask for the QK^T attention score matrix + # dynamic mask for the QK^T attention weights matrix self.A = nn.Parameter(torch.zeros(config.num_attention_heads)) self.dt_proj = nn.Linear( config.num_key_value_heads * self.head_dim, config.num_attention_heads, bias=config.hidden_bias @@ -242,7 +256,7 @@ def forward( past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, - ) -> Tuple[torch.Tensor, Optional[Cache]]: + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) @@ -259,9 +273,7 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # calculate dynamic mask from value_states - dt_states = self.dt_proj( - value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1) - ) + dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(input_shape, -1)) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( hidden_states=hidden_states, @@ -270,11 +282,18 @@ def forward( attention_mask=attention_mask, ) - attention_interface: Callable = self.eager_attention_forward + attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": - attention_interface = self.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] + if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): + logger.warning_once( + "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to " + 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' + ) + else: + attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] - attn_output = attention_interface( + attn_output, attn_weights = attention_interface( + self, query_states, key_states, value_states, @@ -286,7 +305,7 @@ def forward( attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) - return attn_output + return attn_output, attn_weights def prepare_dynamic_mask( self, @@ -320,109 +339,6 @@ def prepare_dynamic_mask( return attn_mask - def eager_attention_forward( - self, - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - attention_mask: Optional[torch.Tensor], - scaling: float, - dropout: float = 0.0, - **kwargs, - ) -> torch.Tensor: - key_states = repeat_kv(key, self.num_key_value_groups) - value_states = repeat_kv(value, self.num_key_value_groups) - - # compute attention scores matrix - attn_weights = torch.matmul(query, key_states.transpose(-1, -2)) * scaling - if attention_mask is not None: - causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] - attn_weights = attn_weights + causal_mask - - # upcast attention scores to fp32 - attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) - attn_weights = F.dropout(attn_weights, p=dropout, training=self.training) - - # apply attention scores to value states - attn_output = torch.matmul(attn_weights, value_states) - attn_output = attn_output.transpose(1, 2).contiguous() - return attn_output - - def sdpa_attention_forward( - self, - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - attention_mask: Optional[torch.Tensor], - scaling: float, - dropout: float = 0.0, - **kwargs, - ) -> torch.Tensor: - key = repeat_kv(key, self.num_key_value_groups) - value = repeat_kv(value, self.num_key_value_groups) - - causal_mask = attention_mask - if attention_mask is not None: - causal_mask = causal_mask[:, :, :, : key.shape[-2]] - - # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions - # Reference: https://github.com/pytorch/pytorch/issues/112577. - query = query.contiguous() - key = key.contiguous() - value = value.contiguous() - - # NOTE: As of pytorch 2.5.1, cuDNN's SDPA backward pass is still incorrect, so we disable cuDNN SDPA (see https://github.com/pytorch/pytorch/issues/138581) - torch.backends.cuda.enable_cudnn_sdp(False) - attn_output = F.scaled_dot_product_attention( - query, - key, - value, - attn_mask=causal_mask, - dropout_p=dropout, - scale=scaling, - ) - attn_output = attn_output.transpose(1, 2).contiguous() - return attn_output - - def flex_attention_forward( - self, - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - attention_mask: Optional[torch.Tensor], - scaling: float, - dropout: float = 0.0, - **kwargs, - ) -> torch.Tensor: - key = repeat_kv(key, self.num_key_value_groups) - value = repeat_kv(value, self.num_key_value_groups) - - causal_mask = attention_mask - if attention_mask is not None: - causal_mask = causal_mask[:, :, :, : key.shape[-2]] - - # TODO: flex_attention: As of pytorch 2.5.1, captured buffers that require grad are not yet supported. - # NOTE: So we only use flex_attention in inference mode. - def causal_mod(score, batch, head, q_idx, kv_idx): - score = score + causal_mask[batch][0][q_idx][kv_idx] - return score - - def dynamic_mod(score, batch, head, q_idx, kv_idx): - score = score + causal_mask[batch][head][q_idx][kv_idx] - return score - - mask_mod = causal_mod if self.is_causal else dynamic_mod - - attn_output = flex_attention( - query, - key, - value, - score_mod=mask_mod, - scale=scaling, - ) - attn_output = attn_output.transpose(1, 2).contiguous() - return attn_output - class DogeMLP(nn.Module): def __init__(self, config: DogeConfig): @@ -459,8 +375,8 @@ def __init__(self, config: DogeConfig): self.num_keys = int(math.sqrt(self.num_cdmoe_experts)) # queries and keys for retrieval experts - self.queries = nn.Linear(self.hidden_dim, self.num_cdmoe_heads * self.expert_retrieval_dim, bias=False) - self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.num_keys, 2, self.expert_retrieval_dim // 2)) + self.queries_proj = nn.Linear(self.hidden_dim, self.num_cdmoe_heads * self.expert_retrieval_dim, bias=False) + self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.expert_retrieval_dim, self.num_keys)) # experts self.down_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim) @@ -473,13 +389,15 @@ def forward( ) -> torch.Tensor: bsz, seq_len, _ = hidden_states.shape - # get similarity with queries and keys - queries = self.queries(hidden_states) - queries = queries.view(bsz, seq_len, 2, self.num_cdmoe_heads, -1).permute(2, 0, 1, 3, 4) - sim = torch.einsum("p b t h n, h k p n -> p b t h k", queries, self.keys) + # get routing weights with queries and keys + queries = self.queries_proj(hidden_states) + queries = queries.view(2 * self.num_cdmoe_heads, bsz * seq_len, -1) + keys = self.keys.view(2 * self.num_cdmoe_heads, -1, self.num_keys) + routing_weights = torch.matmul(queries, keys) + routing_weights = routing_weights.view(2, bsz, seq_len, self.num_cdmoe_heads, self.num_keys) - # get experts with the highest similarity - (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmoe_experts_per_head, dim=-1) + # get experts with the highest routing weights + (scores_x, scores_y), (indices_x, indices_y) = routing_weights.topk(self.num_cdmoe_experts_per_head, dim=-1) all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2) all_scores = all_scores.view(*scores_x.shape[:-1], -1) all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2) @@ -490,9 +408,9 @@ def forward( up_embed = self.up_embed(indices) # mix experts states with cross domain states - experts_weights = torch.einsum("b t d, b t h k d -> b t h k", hidden_states, down_embed) + experts_weights = (hidden_states[:, :, None, None, :] * down_embed).sum(dim=-1) experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) - experts_states = torch.einsum("b t h k, b t h k d -> b t d", experts_weights, up_embed) + experts_states = (experts_weights[:, :, :, None, :] * up_embed).sum(dim=-2).sum(dim=-2) hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) hidden_states = hidden_states + experts_states return hidden_states @@ -503,13 +421,13 @@ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None): super().__init__() self.hidden_dropout = config.hidden_dropout - self.pre_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.pre_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.self_attn = DogeDynamicMaskAttention(config=config, layer_idx=layer_idx) - self.pre_residual = Residual(config.hidden_size) + self.pre_residual = DogeResidual(config.hidden_size) - self.post_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.feed_forward = DogeMLP(config) if not config.is_moe else DogeCDMoE(config) - self.post_residual = Residual(config.hidden_size) + self.post_residual = DogeResidual(config.hidden_size) def forward( self, @@ -526,11 +444,13 @@ def forward( # sequence transformation residual = hidden_states hidden_states = self.pre_layernorm(hidden_states) - hidden_states = self.self_attn( + hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, @@ -687,17 +607,20 @@ class DogeModel(DogePreTrainedModel): def __init__(self, config: DogeConfig): super().__init__(config) - self.config = config self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size - self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) - self.rotary_emb = RotaryEmbedding(config) + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) - self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.norm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.rotary_emb = DogeRotaryEmbedding(config) self.gradient_checkpointing = False + self.config = config + + self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.final_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) # Initialize weights and apply final processing self.post_init() @@ -823,9 +746,27 @@ def _update_causal_mask( past_key_values: Cache, output_attentions: bool, ): + if self.config._attn_implementation == "flash_attention_2": + if attention_mask is not None and (attention_mask == 0.0).any(): + return attention_mask + return None + + # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in + # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail + # to infer the attention mask. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 using_static_cache = isinstance(past_key_values, StaticCache) + # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward + if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions: + if AttentionMaskConverter._ignore_causal_mask_sdpa( + attention_mask, + inputs_embeds=input_tensor, + past_key_values_length=past_seen_tokens, + is_training=self.training, + ): + return None + dtype, device = input_tensor.dtype, input_tensor.device sequence_length = input_tensor.shape[1] if using_static_cache: @@ -837,9 +778,9 @@ def _update_causal_mask( else past_seen_tokens + sequence_length + 1 ) - # in case the provided `attention` mask is 2D, we generate a causal mask here (4D). + # In case the provided `attention` mask is 2D, we generate a causal mask here (4D). causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( - attention_mask=attention_mask, + attention_mask, sequence_length=sequence_length, target_length=target_length, dtype=dtype, @@ -848,17 +789,29 @@ def _update_causal_mask( batch_size=input_tensor.shape[0], ) + if ( + self.config._attn_implementation == "sdpa" + and attention_mask is not None + and attention_mask.device.type in ["cuda", "xpu"] + and not output_attentions + ): + # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when + # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. + # Details: https://github.com/pytorch/pytorch/issues/110213 + min_dtype = torch.finfo(dtype).min + causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) + return causal_mask @staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( - attention_mask: torch.Tensor = None, - sequence_length: int = None, - target_length: int = None, - dtype: torch.dtype = None, - device: torch.device = None, - cache_position: torch.Tensor = None, - batch_size: int = None, + attention_mask: torch.Tensor, + sequence_length: int, + target_length: int, + dtype: torch.dtype, + device: torch.device, + cache_position: torch.Tensor, + batch_size: int, **kwargs, ): """ @@ -889,10 +842,7 @@ def _prepare_4d_causal_attention_mask_with_cache_position( else: min_dtype = torch.finfo(dtype).min causal_mask = torch.full( - (sequence_length, target_length), - fill_value=min_dtype, - dtype=dtype, - device=device, + (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device ) if sequence_length != 1: causal_mask = torch.triu(causal_mask, diagonal=1) @@ -942,7 +892,6 @@ def get_decoder(self): def set_decoder(self, decoder): self.model = decoder - @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep") @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( @@ -958,7 +907,7 @@ def forward( output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, - logits_to_keep: int = 0, + logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[LossKwargs], ) -> Union[Tuple, CausalLMOutputWithPast]: r""" @@ -1113,17 +1062,20 @@ def forward( if self.config.pad_token_id is None and batch_size != 1: raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") if self.config.pad_token_id is None: - sequence_lengths = -1 + last_non_pad_token = -1 + elif input_ids is not None: + # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id + non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32) + token_indices = torch.arange(input_ids.shape[-1], device=logits.device) + last_non_pad_token = (token_indices * non_pad_mask).argmax(-1) else: - if input_ids is not None: - # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility - sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 - sequence_lengths = sequence_lengths % input_ids.shape[-1] - sequence_lengths = sequence_lengths.to(logits.device) - else: - sequence_lengths = -1 + last_non_pad_token = -1 + logger.warning_once( + f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " + "unexpected if using padding tokens in conjunction with `inputs_embeds.`" + ) - pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token] loss = None if labels is not None: diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 55025c28b7ef..4ab2061295cd 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -26,8 +26,8 @@ from torch import nn from transformers.models.llama.modeling_llama import ( - LlamaModel, LlamaForSequenceClassification, + LlamaModel, LlamaRMSNorm, LlamaRotaryEmbedding, apply_rotary_pos_emb, @@ -35,7 +35,7 @@ ) from ...activations import ACT2FN -from ...cache_utils import Cache, DynamicCache, StaticCache +from ...cache_utils import Cache, DynamicCache from ...configuration_utils import PretrainedConfig from ...generation import GenerationMixin from ...modeling_outputs import ( @@ -43,8 +43,7 @@ CausalLMOutputWithPast, ) from ...modeling_rope_utils import rope_config_validation -from ...modeling_utils import PreTrainedModel -from modeling_utils import ALL_ATTENTION_FUNCTIONS +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...pytorch_utils import ALL_LAYERNORM_LAYERS from ...utils import ( @@ -55,7 +54,6 @@ logging, replace_return_docstrings, ) -from ...utils.deprecation import deprecate_kwarg if is_torch_flex_attn_available(): @@ -64,7 +62,6 @@ logger = logging.get_logger(__name__) -_CHECKPOINT_FOR_DOC = "SmallDoge/Doge-20M" _CONFIG_FOR_DOC = "DogeConfig" @@ -269,7 +266,7 @@ def __init__( class DogeRMSNorm(LlamaRMSNorm): - pass + pass ALL_LAYERNORM_LAYERS.append(DogeRMSNorm) @@ -323,8 +320,9 @@ def sdpa_attention_forward( key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], - scaling: float, dropout: float = 0.0, + scaling: Optional[float] = None, + is_causal: Optional[bool] = None, **kwargs, ) -> Tuple[torch.Tensor, None]: key = repeat_kv(key, module.num_key_value_groups) @@ -372,8 +370,10 @@ def flex_attention_forward( key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], - scaling: float, - dropout: float = 0.0, + scaling: Optional[float] = None, + is_causal: Optional[bool] = None, + softcap: Optional[float] = None, + head_mask: Optional[torch.Tensor] = None, **kwargs, ) -> Tuple[torch.Tensor, torch.Tensor]: causal_mask = attention_mask @@ -384,11 +384,21 @@ def flex_attention_forward( is_causal = causal_mask is None and query.shape[2] > 1 def causal_mod(score, batch, head, q_idx, kv_idx): - score = score + causal_mask[batch][0][q_idx][kv_idx] + if softcap is not None: + score = softcap * torch.tanh(score / softcap) + if causal_mask is not None: + score = score + causal_mask[batch][0][q_idx][kv_idx] + if head_mask is not None: + score = score + head_mask[batch][head][0][0] return score def dynamic_mod(score, batch, head, q_idx, kv_idx): - score = score + causal_mask[batch][head][q_idx][kv_idx] + if softcap is not None: + score = softcap * torch.tanh(score / softcap) + if causal_mask is not None: + score = score + causal_mask[batch][head][q_idx][kv_idx] + if head_mask is not None: + score = score + head_mask[batch][head][0][0] return score # TODO: flex_attention: As of pytorch 2.5.1, captured buffers that require grad are not yet supported. @@ -477,9 +487,7 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # calculate dynamic mask from value_states - dt_states = self.dt_proj( - value_states.transpose(1, 2).reshape(input_shape, -1) - ) + dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(input_shape, -1)) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( hidden_states=hidden_states, From e064520ca41c1530fe3d1ef20b2d829827cff064 Mon Sep 17 00:00:00 2001 From: LoserCheems <3314685395@qq.com> Date: Thu, 6 Feb 2025 23:33:57 +0800 Subject: [PATCH 17/20] Fix some bugs --- src/transformers/models/doge/modeling_doge.py | 6 +++--- src/transformers/models/doge/modular_doge.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index cd8d61a6f8f2..6f73b673c6c4 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -273,7 +273,7 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # calculate dynamic mask from value_states - dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(input_shape, -1)) + dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( hidden_states=hidden_states, @@ -408,9 +408,9 @@ def forward( up_embed = self.up_embed(indices) # mix experts states with cross domain states - experts_weights = (hidden_states[:, :, None, None, :] * down_embed).sum(dim=-1) + experts_weights = torch.sum(hidden_states[:, :, None, None, :] * down_embed, dim=-1) experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) - experts_states = (experts_weights[:, :, :, None, :] * up_embed).sum(dim=-2).sum(dim=-2) + experts_states = torch.sum(experts_weights[:, :, :, :, None] * up_embed, dim=(2, 3)) hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) hidden_states = hidden_states + experts_states return hidden_states diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 4ab2061295cd..9c5bf4fea063 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -487,7 +487,7 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # calculate dynamic mask from value_states - dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(input_shape, -1)) + dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( hidden_states=hidden_states, @@ -622,9 +622,9 @@ def forward( up_embed = self.up_embed(indices) # mix experts states with cross domain states - experts_weights = (hidden_states[:, :, None, None, :] * down_embed).sum(dim=-1) + experts_weights = torch.sum(hidden_states[:, :, None, None, :] * down_embed, dim=-1) experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) - experts_states = (experts_weights[:, :, :, None, :] * up_embed).sum(dim=-2).sum(dim=-2) + experts_states = torch.sum(experts_weights[:, :, :, :, None] * up_embed, dim=(2, 3)) hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) hidden_states = hidden_states + experts_states return hidden_states From be9afcd5b37bf80e2ed84f09f1f114db9e615d05 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Thu, 6 Feb 2025 23:38:25 +0800 Subject: [PATCH 18/20] Fix code quality --- src/transformers/models/doge/modeling_doge.py | 4 +++- src/transformers/models/doge/modular_doge.py | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index 6f73b673c6c4..beece35a7327 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -273,7 +273,9 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # calculate dynamic mask from value_states - dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)) + dt_states = self.dt_proj( + value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1) + ) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( hidden_states=hidden_states, diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 9c5bf4fea063..028a95c3cdbe 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -487,7 +487,9 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # calculate dynamic mask from value_states - dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)) + dt_states = self.dt_proj( + value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1) + ) dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2) attn_mask = self.prepare_dynamic_mask( hidden_states=hidden_states, From 1c99852d89a4a891c8d4537917978e8a99b780b6 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Fri, 7 Feb 2025 02:41:23 +0800 Subject: [PATCH 19/20] Remove inherited `_update_causal_mask` from Llama This leads to incorrect weight initialization. --- src/transformers/models/doge/modeling_doge.py | 11 +- src/transformers/models/doge/modular_doge.py | 127 +++++++++++++++++- 2 files changed, 128 insertions(+), 10 deletions(-) diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index beece35a7327..715725150948 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -609,20 +609,17 @@ class DogeModel(DogePreTrainedModel): def __init__(self, config: DogeConfig): super().__init__(config) + self.config = config self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size - self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.rotary_emb = DogeRotaryEmbedding(config) self.layers = nn.ModuleList( [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) - self.norm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) - self.rotary_emb = DogeRotaryEmbedding(config) - self.gradient_checkpointing = False - self.config = config - - self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.final_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 028a95c3cdbe..50e413c30e45 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -27,7 +27,6 @@ from transformers.models.llama.modeling_llama import ( LlamaForSequenceClassification, - LlamaModel, LlamaRMSNorm, LlamaRotaryEmbedding, apply_rotary_pos_emb, @@ -35,9 +34,10 @@ ) from ...activations import ACT2FN -from ...cache_utils import Cache, DynamicCache +from ...cache_utils import Cache, DynamicCache, StaticCache from ...configuration_utils import PretrainedConfig from ...generation import GenerationMixin +from ...modeling_attn_mask_utils import AttentionMaskConverter from ...modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, @@ -813,7 +813,7 @@ def _init_weights(self, module): "The bare Doge Model outputting raw hidden-states without any specific head on top.", DOGE_START_DOCSTRING, ) -class DogeModel(DogePreTrainedModel, LlamaModel): +class DogeModel(DogePreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DogeDecoderLayer`] @@ -951,6 +951,127 @@ def forward( ) return output if return_dict else output.to_tuple() + def _update_causal_mask( + self, + attention_mask: torch.Tensor, + input_tensor: torch.Tensor, + cache_position: torch.Tensor, + past_key_values: Cache, + output_attentions: bool, + ): + if self.config._attn_implementation == "flash_attention_2": + if attention_mask is not None and (attention_mask == 0.0).any(): + return attention_mask + return None + + # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in + # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail + # to infer the attention mask. + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + using_static_cache = isinstance(past_key_values, StaticCache) + + # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward + if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions: + if AttentionMaskConverter._ignore_causal_mask_sdpa( + attention_mask, + inputs_embeds=input_tensor, + past_key_values_length=past_seen_tokens, + is_training=self.training, + ): + return None + + dtype, device = input_tensor.dtype, input_tensor.device + sequence_length = input_tensor.shape[1] + if using_static_cache: + target_length = past_key_values.get_max_cache_shape() + else: + target_length = ( + attention_mask.shape[-1] + if isinstance(attention_mask, torch.Tensor) + else past_seen_tokens + sequence_length + 1 + ) + + # In case the provided `attention` mask is 2D, we generate a causal mask here (4D). + causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( + attention_mask, + sequence_length=sequence_length, + target_length=target_length, + dtype=dtype, + device=device, + cache_position=cache_position, + batch_size=input_tensor.shape[0], + ) + + if ( + self.config._attn_implementation == "sdpa" + and attention_mask is not None + and attention_mask.device.type in ["cuda", "xpu"] + and not output_attentions + ): + # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when + # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. + # Details: https://github.com/pytorch/pytorch/issues/110213 + min_dtype = torch.finfo(dtype).min + causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) + + return causal_mask + + @staticmethod + def _prepare_4d_causal_attention_mask_with_cache_position( + attention_mask: torch.Tensor, + sequence_length: int, + target_length: int, + dtype: torch.dtype, + device: torch.device, + cache_position: torch.Tensor, + batch_size: int, + **kwargs, + ): + """ + Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape + `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. + + Args: + attention_mask (`torch.Tensor`): + A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape + `(batch_size, 1, query_length, key_value_length)`. + sequence_length (`int`): + The sequence length being processed. + target_length (`int`): + The target length: when generating with static cache, the mask should be as long as the static cache, + to account for the 0 padding, the part of the cache that is not filled yet. + dtype (`torch.dtype`): + The dtype to use for the 4D attention mask. + device (`torch.device`): + The device to plcae the 4D attention mask on. + cache_position (`torch.Tensor`): + Indices depicting the position of the input sequence tokens in the sequence. + batch_size (`torch.Tensor`): + Batch size. + """ + if attention_mask is not None and attention_mask.dim() == 4: + # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. + causal_mask = attention_mask + else: + min_dtype = torch.finfo(dtype).min + causal_mask = torch.full( + (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device + ) + if sequence_length != 1: + causal_mask = torch.triu(causal_mask, diagonal=1) + causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) + causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) + if attention_mask is not None: + causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit + mask_length = attention_mask.shape[-1] + padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] + padding_mask = padding_mask == 0 + causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( + padding_mask, min_dtype + ) + + return causal_mask + class DogeForCausalLM(DogePreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] From 6ae4982c1ee9c0cbb9c0dab14c3be1c0d7e0e516 Mon Sep 17 00:00:00 2001 From: LoserCheems Date: Fri, 7 Feb 2025 03:36:09 +0800 Subject: [PATCH 20/20] Fix the wrong tensor orderings in DogeCDMoE --- src/transformers/models/doge/modeling_doge.py | 8 ++++---- src/transformers/models/doge/modular_doge.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/transformers/models/doge/modeling_doge.py b/src/transformers/models/doge/modeling_doge.py index 715725150948..fcedc9ed80e9 100644 --- a/src/transformers/models/doge/modeling_doge.py +++ b/src/transformers/models/doge/modeling_doge.py @@ -393,10 +393,10 @@ def forward( # get routing weights with queries and keys queries = self.queries_proj(hidden_states) - queries = queries.view(2 * self.num_cdmoe_heads, bsz * seq_len, -1) - keys = self.keys.view(2 * self.num_cdmoe_heads, -1, self.num_keys) + queries = queries.view(2, self.num_cdmoe_heads, bsz * seq_len, -1) + keys = self.keys.view(2, self.num_cdmoe_heads, -1, self.num_keys) routing_weights = torch.matmul(queries, keys) - routing_weights = routing_weights.view(2, bsz, seq_len, self.num_cdmoe_heads, self.num_keys) + routing_weights = routing_weights.transpose(-2, -3).view(2, bsz, seq_len, self.num_cdmoe_heads, self.num_keys) # get experts with the highest routing weights (scores_x, scores_y), (indices_x, indices_y) = routing_weights.topk(self.num_cdmoe_experts_per_head, dim=-1) @@ -412,7 +412,7 @@ def forward( # mix experts states with cross domain states experts_weights = torch.sum(hidden_states[:, :, None, None, :] * down_embed, dim=-1) experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) - experts_states = torch.sum(experts_weights[:, :, :, :, None] * up_embed, dim=(2, 3)) + experts_states = torch.sum(experts_weights[:, :, :, :, None] * up_embed, dim=(-2, -3)) hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) hidden_states = hidden_states + experts_states return hidden_states diff --git a/src/transformers/models/doge/modular_doge.py b/src/transformers/models/doge/modular_doge.py index 50e413c30e45..6542a24a4bc8 100644 --- a/src/transformers/models/doge/modular_doge.py +++ b/src/transformers/models/doge/modular_doge.py @@ -607,10 +607,10 @@ def forward( # get routing weights with queries and keys queries = self.queries_proj(hidden_states) - queries = queries.view(2 * self.num_cdmoe_heads, bsz * seq_len, -1) - keys = self.keys.view(2 * self.num_cdmoe_heads, -1, self.num_keys) + queries = queries.view(2, self.num_cdmoe_heads, bsz * seq_len, -1) + keys = self.keys.view(2, self.num_cdmoe_heads, -1, self.num_keys) routing_weights = torch.matmul(queries, keys) - routing_weights = routing_weights.view(2, bsz, seq_len, self.num_cdmoe_heads, self.num_keys) + routing_weights = routing_weights.transpose(-2, -3).view(2, bsz, seq_len, self.num_cdmoe_heads, self.num_keys) # get experts with the highest routing weights (scores_x, scores_y), (indices_x, indices_y) = routing_weights.topk(self.num_cdmoe_experts_per_head, dim=-1) @@ -626,7 +626,7 @@ def forward( # mix experts states with cross domain states experts_weights = torch.sum(hidden_states[:, :, None, None, :] * down_embed, dim=-1) experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1) - experts_states = torch.sum(experts_weights[:, :, :, :, None] * up_embed, dim=(2, 3)) + experts_states = torch.sum(experts_weights[:, :, :, :, None] * up_embed, dim=(-2, -3)) hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) hidden_states = hidden_states + experts_states return hidden_states