From 07d9d08817782662a5cf27b7b15ef926da6c37c5 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Thu, 24 Oct 2024 13:04:07 -0700 Subject: [PATCH 01/20] Ported arctic instruct code Signed-off-by: Daniel Huang --- .../habana/transformers/generation/utils.py | 1 + optimum/habana/transformers/modeling_utils.py | 8 + .../habana/transformers/models/__init__.py | 1 + .../transformers/models/snowflake/__init__.py | 3 + .../models/snowflake/configuration_arctic.py | 216 ++ .../models/snowflake/modeling_arctic.py | 1943 +++++++++++++++++ .../models/snowflake/tokenization_arctic.py | 57 + 7 files changed, 2229 insertions(+) create mode 100644 optimum/habana/transformers/models/snowflake/__init__.py create mode 100644 optimum/habana/transformers/models/snowflake/configuration_arctic.py create mode 100644 optimum/habana/transformers/models/snowflake/modeling_arctic.py create mode 100644 optimum/habana/transformers/models/snowflake/tokenization_arctic.py diff --git a/optimum/habana/transformers/generation/utils.py b/optimum/habana/transformers/generation/utils.py index 1f2e75414e..1ca34fab7b 100755 --- a/optimum/habana/transformers/generation/utils.py +++ b/optimum/habana/transformers/generation/utils.py @@ -117,6 +117,7 @@ "deepseek_v2", "chatglm", "qwen2_vl", + "arctic", ] # Initial generated token index is set to 1 to accomodate SOS (start of string) token. diff --git a/optimum/habana/transformers/modeling_utils.py b/optimum/habana/transformers/modeling_utils.py index 18d6edaa28..9b11b7b5da 100644 --- a/optimum/habana/transformers/modeling_utils.py +++ b/optimum/habana/transformers/modeling_utils.py @@ -35,6 +35,9 @@ ) from .models import ( GAUDI_WHISPER_ATTENTION_CLASSES, + ArcticConfig, + ArcticForCausalLM, + ArcticTokenizer, BaichuanConfig, BaichuanForCausalLM, BaichuanTokenizer, @@ -786,3 +789,8 @@ def adapt_transformers_to_gaudi(): transformers.models.detr.modeling_detr.DetrLoss.loss_cardinality = gaudi_DetrLoss_loss_cardinality transformers.models.detr.modeling_detr.DetrLoss.loss_boxes = gaudi_DetrLoss_loss_boxes transformers.models.detr.modeling_detr.DetrLoss.forward = gaudi_DetrLoss_forward + + transformers.AutoConfig.register("arctic", ArcticConfig) + transformers.AutoModelForCausalLM.register(ArcticConfig, ArcticForCausalLM) + transformers.AutoTokenizer.register(ArcticConfig, ArcticTokenizer) + diff --git a/optimum/habana/transformers/models/__init__.py b/optimum/habana/transformers/models/__init__.py index 8cf0575251..e34afb381f 100644 --- a/optimum/habana/transformers/models/__init__.py +++ b/optimum/habana/transformers/models/__init__.py @@ -277,6 +277,7 @@ gaudi_SeamlessM4TTextToUnitForConditionalGeneration_prepare_inputs_for_generation, gaudi_SeamlessM4TTextToUnitModel_forward, ) +from .snowflake import ArcticConfig, ArcticForCausalLM, ArcticTokenizer from .speecht5 import ( gaudi_generate_speech, gaudi_SpeechT5Attention_forward, diff --git a/optimum/habana/transformers/models/snowflake/__init__.py b/optimum/habana/transformers/models/snowflake/__init__.py new file mode 100644 index 0000000000..a907bf0e56 --- /dev/null +++ b/optimum/habana/transformers/models/snowflake/__init__.py @@ -0,0 +1,3 @@ +from .configuration_arctic import ArcticConfig +from .modeling_arctic import ArcticForCausalLM +from .tokenization_arctic import ArcticTokenizer diff --git a/optimum/habana/transformers/models/snowflake/configuration_arctic.py b/optimum/habana/transformers/models/snowflake/configuration_arctic.py new file mode 100644 index 0000000000..bf81f4942c --- /dev/null +++ b/optimum/habana/transformers/models/snowflake/configuration_arctic.py @@ -0,0 +1,216 @@ +# Copyright 2023 Snowflake AI 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. +"""Arctic model configuration. Copied from https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d.""" + +from dataclasses import asdict, dataclass +from typing import Any, Dict + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import logging + + +logger = logging.get_logger(__name__) + +ARCTIC_PRETRAINED_CONFIG_ARCHIVE_MAP = { + "arctic": "https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/main/config.json", +} + + +@dataclass +class ArcticLoraConfig: + lora_r: int = 64 + lora_alpha: float = 16 + shard_base_weights: bool = False + + +@dataclass +class ArcticQuantizationConfig: + q_bits: int = 8 + rounding: str = "nearest" + mantissa_bits: int = 3 + group_size: int = 512 + + +class ArcticConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`ArcticModel`]. It is used to instantiate an + Arctic model according to the specified arguments, defining the model architecture. Instantiating a configuration + with the defaults will yield a similar configuration to that of the #TODO(rsamdani): add what model has the default config.. + + + 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 32000): + Vocabulary size of the Arctic model. Defines the number of different tokens that can be represented by the + `inputs_ids` passed when calling [`ArcticModel`] + hidden_size (`int`, *optional*, defaults to 4096): + Dimension of the hidden representations. + intermediate_size (`int`, *optional*, defaults to 14336): + Dimension of the MLP representations. + num_hidden_layers (`int`, *optional*, defaults to 32): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 32): + Number of attention heads for each attention layer in the Transformer encoder. + num_key_value_heads (`int`, *optional*, defaults to 8): + 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 `8`. + 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 `4096*32`): + The maximum sequence length that this model might ever be used with. Arctic's sliding window attention + allows sequence of up to 4096*32 tokens. + 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-05): + 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*): + The id of the padding token. + bos_token_id (`int`, *optional*, defaults to 1): + The id of the "beginning-of-sequence" token. + eos_token_id (`int`, *optional*, defaults to 2): + The id of the "end-of-sequence" token. + tie_word_embeddings (`bool`, *optional*, defaults to `False`): + Whether the model's input and output word embeddings should be tied. + rope_theta (`float`, *optional*, defaults to 1000000.0): + The base period of the RoPE embeddings. + sliding_window (`int`, *optional*): + Sliding window attention window size. If not specified, will default to `4096`. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + num_experts_per_tok (`int`, *optional*, defaults to 2): + The number of experts to root per-token, can be also interpreted as the `top-p` routing + parameter + num_local_experts (`int`, *optional*, defaults to 8): + Number of experts per Sparse MLP layer. + router_aux_loss_coef (`float`, *optional*, defaults to 0.001): + The aux loss factor for the total loss. + + ```python + >>> from transformers import ArcticModel, ArcticConfig + + >>> # Initializing a Arctic 7B style configuration TODO(rsamdani): verify which model does the default configuration correspond to. + >>> configuration = ArcticConfig() + + >>> # Initializing a model from the Arctic 7B style configuration + >>> model = ArcticModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "arctic" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=32000, + hidden_size=4096, + intermediate_size=14336, + num_hidden_layers=32, + num_attention_heads=32, + num_key_value_heads=None, + hidden_act="silu", + max_position_embeddings=4096, + initializer_range=0.02, + rms_norm_eps=1e-5, + use_cache=True, + pad_token_id=None, + bos_token_id=1, + eos_token_id=2, + tie_word_embeddings=False, + rope_theta=1e6, + sliding_window=None, + attention_dropout=0.0, + num_experts_per_tok=1, + num_local_experts=8, + router_aux_loss_coef=0.001, + moe_layer_frequency=2, + parallel_attn_mlp_res=False, + moe_train_capacity_factor=1, + moe_eval_capacity_factor=1, + enable_expert_tensor_parallelism=False, + moe_min_capacity=0, + moe_token_dropping=True, + quantization=None, + **kwargs, + ): + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.sliding_window = sliding_window + + # for backward compatibility + if num_key_value_heads is None: + num_key_value_heads = num_attention_heads + + self.num_key_value_heads = num_key_value_heads + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.rms_norm_eps = rms_norm_eps + self.use_cache = use_cache + self.rope_theta = rope_theta + self.attention_dropout = attention_dropout + + self.num_experts_per_tok = num_experts_per_tok + self.num_local_experts = num_local_experts + self.router_aux_loss_coef = router_aux_loss_coef + self.moe_layer_frequency = moe_layer_frequency + self.moe_train_capacity_factor = moe_train_capacity_factor + self.moe_eval_capacity_factor = moe_eval_capacity_factor + self.enable_expert_tensor_parallelism = enable_expert_tensor_parallelism + self.moe_min_capacity = moe_min_capacity + self.moe_token_dropping = moe_token_dropping + self.parallel_attn_mlp_res = parallel_attn_mlp_res + if isinstance(quantization, dict): + self.quantization = ArcticQuantizationConfig(**quantization) + else: + self.quantization = quantization + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + @classmethod + def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "ArcticConfig": + result = super().from_dict(config_dict, **kwargs) + if isinstance(result, tuple): + config = result[0] + else: + config = result + if isinstance(config.quantization, dict): + config.quantization = ArcticQuantizationConfig(**config.quantization) + return result + + def to_dict(self) -> Dict[str, Any]: + ret = super().to_dict() + if isinstance(ret["quantization"], ArcticQuantizationConfig): + ret["quantization"] = asdict(ret["quantization"]) + return ret diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py new file mode 100644 index 0000000000..ea0c3839e4 --- /dev/null +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -0,0 +1,1943 @@ +# coding=utf-8 +# Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# 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 Arctic model. Copied from https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d.""" +import copy +import inspect +import time +import math +import warnings +import re +from typing import List, Optional, Tuple, Union + +import deepspeed +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN +from transformers.cache_utils import Cache, DynamicCache +from transformers.modeling_attn_mask_utils import ( + _prepare_4d_causal_attention_mask, + _prepare_4d_causal_attention_mask_for_sdpa, +) +from transformers.modeling_outputs import ( + MoeCausalLMOutputWithPast, + MoeModelOutputWithPast, + SequenceClassifierOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_13 +from transformers.utils import ( + add_start_docstrings, + add_start_docstrings_to_model_forward, + is_flash_attn_2_available, + is_flash_attn_greater_or_equal_2_10, + logging, + replace_return_docstrings, +) +from transformers.utils.import_utils import is_torch_fx_available +from .configuration_arctic import ArcticConfig +from transformers.integrations.deepspeed import is_deepspeed_available +from transformers.utils.versions import require_version + +if is_deepspeed_available(): + from deepspeed.moe.layer import MoE + # Note that below will crash if there is an available deepspeed that does not have ds_linear. + try: + import deepspeed.linear as ds_linear + except Exception: + pass +else: + MoE = None + +if is_flash_attn_2_available(): + from flash_attn import flash_attn_func, flash_attn_varlen_func + from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa + + _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters) + +# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph. +# It means that the function will not be traced through and simply appear as a node in the graph. +if is_torch_fx_available(): + if not is_torch_greater_or_equal_than_1_13: + import torch.fx + + _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask) + + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "ArcticConfig" +USE_DEEPSPEED_MOE_ARG = "use_deepspeed_moe_implementation" +MOE_EXPERT_PARALLEL_SIZE_ARG = "moe_expert_parallel_size" +DEEPSPEED_QUANTIZATION_CONFIG = "deepspeed_quantization" +DEEPSPEED_LORA_CONFIG = "deepspeed_lora" +QUANTIZATION_CONFIG = "ds_quantization_config" + +# REQUIRED_DEEPSPEED_VERSION = "deepspeed>0.14.5" +# def is_deepspeed_valid_and_available(raise_error=False, error_msg=""): +# available_and_valid = True +# if not is_deepspeed_available(): +# available_and_valid = False +# if raise_error: +# raise ValueError(f"DeepSpeed is required for this feature, {error_msg}") +# else: + +# return available_and_valid + +def load_balancing_loss_func( + gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=4, attention_mask: Optional[torch.Tensor] = None +) -> float: + r""" + Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch. + + See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss + function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between + experts is too unbalanced. + + Args: + gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]): + Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of + shape [batch_size X sequence_length, num_experts]. + attention_mask (`torch.Tensor`, None): + The attention_mask used in forward function + shape [batch_size X sequence_length] if not None. + num_experts (`int`, *optional*): + Number of experts + + Returns: + The auxiliary loss. + """ + if gate_logits is None or not isinstance(gate_logits, tuple): + return 0 + + if isinstance(gate_logits, tuple): + compute_device = gate_logits[0].device + concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0) + + routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1) + + _, selected_experts = torch.topk(routing_weights, top_k, dim=-1) + + expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts) + + if attention_mask is None: + # Compute the percentage of tokens routed to each experts + tokens_per_expert = torch.mean(expert_mask.float(), dim=0) + + # Compute the average probability of routing to these experts + router_prob_per_expert = torch.mean(routing_weights, dim=0) + else: + batch_size, sequence_length = attention_mask.shape + num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length) + + # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask + expert_attention_mask = ( + attention_mask[None, :, :, None, None] + .expand((num_hidden_layers, batch_size, sequence_length, 2, num_experts)) + .reshape(-1, 2, num_experts) + .to(compute_device) + ) + + # Compute the percentage of tokens routed to each experts + tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum( + expert_attention_mask, dim=0 + ) + + # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert + router_per_expert_attention_mask = ( + attention_mask[None, :, :, None] + .expand((num_hidden_layers, batch_size, sequence_length, num_experts)) + .reshape(-1, num_experts) + .to(compute_device) + ) + + # Compute the average probability of routing to these experts + router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum( + router_per_expert_attention_mask, dim=0 + ) + + overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0)) + return overall_loss * num_experts + + +# Copied from transformers.models.llama.modeling_llama._get_unpad_data +def _get_unpad_data(attention_mask): + seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) + indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)) + return ( + indices, + cu_seqlens, + max_seqlen_in_batch, + ) + + +# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Arctic +class ArcticRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + ArcticRMSNorm 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) + + +# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Arctic +class ArcticRotaryEmbedding(nn.Module): + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): + super().__init__() + + self.dim = dim + self.max_position_embeddings = max_position_embeddings + self.base = base + inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + # Build here to make `torch.jit.trace` work. + self._set_cos_sin_cache( + seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() + ) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + + freqs = torch.outer(t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + + def forward(self, x, seq_len=None): + # x: [bs, num_attention_heads, seq_len, head_size] + if seq_len > self.max_seq_len_cached: + self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) + + return ( + self.cos_cached[:seq_len].to(dtype=x.dtype), + self.sin_cached[:seq_len].to(dtype=x.dtype), + ) + + +# Copied from transformers.models.llama.modeling_llama.rotate_half +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) + + +# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb +def apply_rotary_pos_emb(q, k, cos, sin, position_ids, 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`): + The position indices of the tokens corresponding to the query and key tensors. For example, this can be + used to pass offsetted position ids when working with a KV-cache. + 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[position_ids].unsqueeze(unsqueeze_dim) + sin = sin[position_ids].unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +# Copied from transformers.models.llama.modeling_llama.repeat_kv +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) + + +# Copied from transformers.models.mistral.modeling_mistral.MistralAttention with Mistral->Arctic +class ArcticAttention(nn.Module): + """ + Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer + and "Generating Long Sequences with Sparse Transformers". + """ + + def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwargs): + super().__init__() + self.config = config + self.layer_idx = layer_idx + if layer_idx is None: + logger.warning_once( + f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " + "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " + "when creating this class." + ) + + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.hidden_size // self.num_heads + self.num_key_value_heads = config.num_key_value_heads + self.num_key_value_groups = self.num_heads // self.num_key_value_heads + self.max_position_embeddings = config.max_position_embeddings + self.rope_theta = config.rope_theta + self.is_causal = True + self.attention_dropout = config.attention_dropout + self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] + if (self.head_dim * self.num_heads) != self.hidden_size: + raise ValueError( + f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" + f" and `num_heads`: {self.num_heads})." + ) + + deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG) + deepspeed_lora_config = kwargs.get(DEEPSPEED_LORA_CONFIG) + quantization_config = kwargs.get(QUANTIZATION_CONFIG, None) + + self.q_proj = get_arctic_linear(self.hidden_size, self.num_heads * self.head_dim, bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16) + self.k_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16) + self.v_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16) + self.o_proj = get_arctic_linear(self.hidden_size, self.hidden_size, bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16) + + self.rotary_emb = ArcticRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + base=self.rope_theta, + ) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + 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: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if "padding_mask" in kwargs: + warnings.warn( + "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" + ) + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + if self.layer_idx is None: + raise ValueError( + f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " + "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " + "with a layer index." + ) + kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + if past_key_value is not None: + cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + + if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): + raise ValueError( + f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) + + attn_weights = attn_weights + attention_mask + + # upcast attention to fp32 + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +# Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Arctic +class ArcticFlashAttention2(ArcticAttention): + """ + Arctic flash attention module. This module inherits from `ArcticAttention` as the weights of the module stays + untouched. The only required change would be on the forward pass where it needs to correctly call the public API of + flash attention and deal with padding tokens in case the input contains any of them. + """ + + # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. + # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. + # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). + self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() + + 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: bool = False, + use_cache: bool = False, + **kwargs, + ): + if "padding_mask" in kwargs: + warnings.warn( + "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" + ) + + # overwrite attention_mask with padding_mask + attention_mask = kwargs.pop("padding_mask") + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + if self.layer_idx is None: + raise ValueError( + f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " + "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " + "with a layer index." + ) + kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + + # Because the input can be padded, the absolute sequence length depends on the max position id. + rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1 + cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len) + + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + use_sliding_windows = ( + _flash_supports_window_size + and getattr(self.config, "sliding_window", None) is not None + and kv_seq_len > self.config.sliding_window + ) + + if not _flash_supports_window_size: + logger.warning_once( + "The current flash attention version does not support sliding window attention, for a more memory efficient implementation" + " make sure to upgrade flash-attn library." + ) + + if past_key_value is not None: + # Activate slicing cache only if the config has a value `sliding_windows` attribute + cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0 + if ( + getattr(self.config, "sliding_window", None) is not None + and kv_seq_len > self.config.sliding_window + and cache_has_contents + ): + slicing_tokens = 1 - self.config.sliding_window + + past_key = past_key_value[self.layer_idx][0] + past_value = past_key_value[self.layer_idx][1] + + past_key = past_key[:, :, slicing_tokens:, :].contiguous() + past_value = past_value[:, :, slicing_tokens:, :].contiguous() + + if past_key.shape[-2] != self.config.sliding_window - 1: + raise ValueError( + f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got" + f" {past_key.shape}" + ) + + if attention_mask is not None: + attention_mask = attention_mask[:, slicing_tokens:] + attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1) + + cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + dropout_rate = 0.0 if not self.training else self.attention_dropout + + # In PEFT, usually we cast the layer norms in float32 for training stability reasons + # therefore the input hidden states gets silently casted in float32. Hence, we need + # cast them back in float16 just to be sure everything works as expected. + input_dtype = query_states.dtype + if input_dtype == torch.float32: + if torch.is_autocast_enabled(): + target_dtype = torch.get_autocast_gpu_dtype() + # Handle the case where the model is quantized + elif hasattr(self.config, "_pre_quantization_dtype"): + target_dtype = self.config._pre_quantization_dtype + else: + target_dtype = self.q_proj.weight.dtype + + logger.warning_once( + f"The input hidden states seems to be silently casted in float32, this might be related to" + f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" + f" {target_dtype}." + ) + + query_states = query_states.to(target_dtype) + key_states = key_states.to(target_dtype) + value_states = value_states.to(target_dtype) + + # Reashape to the expected shape for Flash Attention + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + attn_output = self._flash_attention_forward( + query_states, + key_states, + value_states, + attention_mask, + q_len, + dropout=dropout_rate, + use_sliding_windows=use_sliding_windows, + ) + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + def _flash_attention_forward( + self, + query_states, + key_states, + value_states, + attention_mask, + query_length, + dropout=0.0, + softmax_scale=None, + use_sliding_windows=False, + ): + """ + Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token + first unpad the input, then computes the attention scores and pad the final attention scores. + + Args: + query_states (`torch.Tensor`): + Input query states to be passed to Flash Attention API + key_states (`torch.Tensor`): + Input key states to be passed to Flash Attention API + value_states (`torch.Tensor`): + Input value states to be passed to Flash Attention API + attention_mask (`torch.Tensor`): + The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the + position of padding tokens and 1 for the position of non-padding tokens. + dropout (`int`, *optional*): + Attention dropout + softmax_scale (`float`, *optional*): + The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) + use_sliding_windows (`bool`, *optional*): + Whether to activate sliding window attention. + """ + if not self._flash_attn_uses_top_left_mask: + causal = self.is_causal + else: + # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__. + causal = self.is_causal and query_length != 1 + + # Contains at least one padding token in the sequence + if attention_mask is not None: + batch_size = query_states.shape[0] + query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( + query_states, key_states, value_states, attention_mask, query_length + ) + + cu_seqlens_q, cu_seqlens_k = cu_seq_lens + max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens + + if not use_sliding_windows: + attn_output_unpad = flash_attn_varlen_func( + query_states, + key_states, + value_states, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_in_batch_q, + max_seqlen_k=max_seqlen_in_batch_k, + dropout_p=dropout, + softmax_scale=softmax_scale, + causal=causal, + ) + else: + attn_output_unpad = flash_attn_varlen_func( + query_states, + key_states, + value_states, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_in_batch_q, + max_seqlen_k=max_seqlen_in_batch_k, + dropout_p=dropout, + softmax_scale=softmax_scale, + causal=causal, + window_size=(self.config.sliding_window, self.config.sliding_window), + ) + + attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) + else: + if not use_sliding_windows: + attn_output = flash_attn_func( + query_states, + key_states, + value_states, + dropout, + softmax_scale=softmax_scale, + causal=causal, + ) + else: + attn_output = flash_attn_func( + query_states, + key_states, + value_states, + dropout, + softmax_scale=softmax_scale, + causal=causal, + window_size=(self.config.sliding_window, self.config.sliding_window), + ) + + return attn_output + + def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): + batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape + + # On the first iteration we need to properly re-create the padding mask + # by slicing it on the proper place + if kv_seq_len != attention_mask.shape[-1]: + attention_mask_num_tokens = attention_mask.shape[-1] + attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :] + + indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) + + key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k) + value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k) + + if query_length == kv_seq_len: + query_layer = index_first_axis( + query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k + ) + cu_seqlens_q = cu_seqlens_k + max_seqlen_in_batch_q = max_seqlen_in_batch_k + indices_q = indices_k + elif query_length == 1: + max_seqlen_in_batch_q = 1 + cu_seqlens_q = torch.arange( + batch_size + 1, dtype=torch.int32, device=query_layer.device + ) # There is a memcpy here, that is very bad. + indices_q = cu_seqlens_q[:-1] + query_layer = query_layer.squeeze(1) + else: + # The -q_len: slice assumes left padding. + attention_mask = attention_mask[:, -query_length:] + query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) + + return ( + query_layer, + key_layer, + value_layer, + indices_q, + (cu_seqlens_q, cu_seqlens_k), + (max_seqlen_in_batch_q, max_seqlen_in_batch_k), + ) + +def get_arctic_linear(input_dim, + output_dim, + bias=False, + use_deepspeed_implementation=False, + ds_optimized_lora_config=None, + ds_optimized_quantization_config=None, + ds_optimized_base_weight_sharding=False, + dtype=torch.bfloat16): + """Can return deepspeed optimized linear if available. + Args: + input_dim, output_dim, bias, dtype: self explanatory (same as from nn.Linear) + ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer. + ds_optimized_quantization_config: config of type ds_linear.QuantizationConfig. + ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus + in a tensor parallel way. + """ + if is_deepspeed_available(): + if ds_optimized_lora_config is not None: + ds_optimized_lora_config: ds_linear.LoRAConfig = copy.deepcopy(ds_optimized_lora_config) + ds_optimized_lora_config.base_weight_sharding = torch.distributed.get_world_size() if ds_optimized_base_weight_sharding else 1 + return ds_linear.OptimizedLinear(input_dim, output_dim, bias, ds_optimized_lora_config, ds_optimized_quantization_config, dtype=dtype) + return nn.Linear(input_dim, output_dim, bias=bias, dtype=dtype) + + +# Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Arctic +class ArcticSdpaAttention(ArcticAttention): + """ + Arctic attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from + `ArcticAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to + SDPA API. + """ + + # Adapted from ArcticAttention.forward + 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: bool = False, + use_cache: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if output_attentions: + # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented. + logger.warning_once( + "ArcticModel is using ArcticSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, " + 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' + ) + return super().forward( + 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, + ) + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + if past_key_value is not None: + cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) + + # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, + # Reference: https://github.com/pytorch/pytorch/issues/112577. + if query_states.device.type == "cuda" and attention_mask is not None: + query_states = query_states.contiguous() + key_states = key_states.contiguous() + value_states = value_states.contiguous() + + attn_output = torch.nn.functional.scaled_dot_product_attention( + query_states, + key_states, + value_states, + attn_mask=attention_mask, + dropout_p=self.attention_dropout if self.training else 0.0, + # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1. + is_causal=self.is_causal and attention_mask is None and q_len > 1, + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + + attn_output = self.o_proj(attn_output) + + return attn_output, None, past_key_value + + +MIXTRAL_ATTENTION_CLASSES = { + "eager": ArcticAttention, + "flash_attention_2": ArcticFlashAttention2, + "sdpa": ArcticSdpaAttention, +} + + +class ArcticMLP(nn.Module): + def __init__(self, config: ArcticConfig, + use_deepspeed_implementation=False, + ds_optimized_lora_config=None, + ds_optimized_quantization_config=None, + shard_base_weights_if_doing_lora=False, + is_residual_mlp=False): + """MLP class for Arctic supporting vanilla linear layers as well as some deepspeed optimizations. + + ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer. + ds_optimized_quantization_config: config of type ds_linear.QuantizationConfig. + ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus + in a tensor parallel way. + is_residual_mlp: bool. If true, this is MLP inside arctic residual layer which has ffn_dim the same as full intermediate_size. + """ + super(ArcticMLP, self).__init__() + self.hidden_dim = config.hidden_size + self.ffn_dim = config.intermediate_size if not is_residual_mlp else self.hidden_dim + self.w1 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False, + use_deepspeed_implementation=use_deepspeed_implementation, + ds_optimized_lora_config=ds_optimized_lora_config, + ds_optimized_quantization_config=ds_optimized_quantization_config, + ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + dtype=torch.bfloat16) + self.w2 = get_arctic_linear(self.ffn_dim, self.hidden_dim, False, + use_deepspeed_implementation=use_deepspeed_implementation, + ds_optimized_lora_config=ds_optimized_lora_config, + ds_optimized_quantization_config=ds_optimized_quantization_config, + ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + dtype=torch.bfloat16) + self.w3 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False, + use_deepspeed_implementation=use_deepspeed_implementation, + ds_optimized_lora_config=ds_optimized_lora_config, + ds_optimized_quantization_config=ds_optimized_quantization_config, + ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + dtype=torch.bfloat16) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, hidden_states): + current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states) + current_hidden_states = self.w2(current_hidden_states) + return current_hidden_states + + +class ArcticMoE(nn.Module): + def __init__(self, config: ArcticConfig, layer_id: int, **kwargs): + super(ArcticMoE, self).__init__() + + self.hidden_dim = config.hidden_size + self.num_experts = config.num_local_experts + self.layer_id = layer_id + self.top_k = config.num_experts_per_tok + self.is_moe_layer = (layer_id+1) % config.moe_layer_frequency == 0 + + self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] + if self.use_deepspeed_implementation and MoE is None: + raise ValueError("Deepspeed is not installed") + quantization_config = kwargs.get(QUANTIZATION_CONFIG, None) + deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) + if not self.is_moe_layer: # dense, not MoE + self.mlp = ArcticMLP(config, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_quantization_config=quantization_config, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=True) + else: + if self.use_deepspeed_implementation: # DeepSpeed's MoE + moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1) + self.mlp = MoE(self.hidden_dim, + # base weight sharding false for all deepspeed moe calls because it is already sharded + ArcticMLP(config, + use_deepspeed_implementation=True, + ds_optimized_quantization_config=quantization_config, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=False), + num_experts=config.num_local_experts, + ep_size=moe_expert_parallel_size, + k=config.num_experts_per_tok, + use_residual=False, + capacity_factor=config.moe_train_capacity_factor, + eval_capacity_factor=config.moe_eval_capacity_factor, + enable_expert_tensor_parallelism=config.enable_expert_tensor_parallelism, + min_capacity=config.moe_min_capacity, + drop_tokens=config.moe_token_dropping + ) + else: + # "local" MoE implementation + self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False) + self.experts = nn.ModuleList([ArcticMLP(config, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_quantization_config=quantization_config, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=True) for i in range(self.num_experts)]) + + # if torch.distributed.get_rank() == 0: + # deepspeed.runtime.utils.see_memory_usage("", force=True) + + + # Similar in behavior to transformers.models.mixtral.modeling_mixtral.MixtralSparseMoeBlock.forward but more efficient. + def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: + batch_size, sequence_length, hidden_dim = hidden_states.shape + hidden_states = hidden_states.view(-1, hidden_dim) + # router_logits: (batch * sequence_length, n_experts) + router_logits = self.gate(hidden_states) + + routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) + routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1) + if self.top_k > 1: + routing_weights /= routing_weights.sum(dim=-1, keepdim=True) + # we cast back to the input dtype + + final_hidden_states = torch.zeros( + (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device + ) + + # Matching between experts, tokens, and their top-k rank. For every i, + # expert_idx[i] is the rank topk_idx[i] expert for token_idx[i]. + expert_idx, token_idx, topk_idx = torch.where( + selected_experts == torch.arange( + self.num_experts, + device=selected_experts.device, + ).view((self.num_experts, 1, 1)) + ) + + # Split into one chunk per expert. + bincount = torch.bincount(expert_idx, minlength=self.num_experts).tolist() + token_idx = token_idx.split(bincount) + topk_idx = topk_idx.split(bincount) + + # Loop over all available experts in the model and perform the computation on each expert + for expert_layer, top_x, idx in zip(self.experts, token_idx, topk_idx): + if top_x.shape[0] == 0: + continue + + # in torch it is faster to index using lists than torch tensors + top_x_list = top_x.tolist() + idx_list = idx.tolist() + + # Index the correct hidden states and compute the expert hidden state for + # the current expert. We need to make sure to multiply the output hidden + # states by `routing_weights` on the corresponding tokens (top-1 and top-2) + current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim) + current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None] + + # However `index_add_` only support torch tensors for indexing so we'll use + # the `top_x` tensor here. + final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype)) + # torch.distributed.barrier() + final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim) + return final_hidden_states, load_balancing_loss_func((router_logits, ), self.num_experts, self.top_k) # ZY: let's directly output the loss to align what we have in ds + + def forward(self, hidden_states: torch.Tensor): + if self.is_moe_layer: + if self.use_deepspeed_implementation: + # deepspeed returns a tuple including output, gate loss, and expert count. + hidden_states, moe_loss, _ = self.mlp(hidden_states) + return hidden_states, moe_loss + else: + return self._moe_foreward(hidden_states) + else: + return self.mlp(hidden_states), torch.tensor(0.0, device=hidden_states.device, dtype=hidden_states.dtype) + + +class ArcticDecoderLayer(nn.Module): + def __init__(self, config: ArcticConfig, layer_idx: int, **kwargs): + super().__init__() + self.layer_idx = layer_idx + self.hidden_size = config.hidden_size + self.self_attn = MIXTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx, **kwargs) + self.block_sparse_moe = ArcticMoE(config, layer_id=layer_idx, **kwargs) + self.input_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] + + self.parallel_attn_mlp_res = config.parallel_attn_mlp_res and self.block_sparse_moe.is_moe_layer # add residual only when it is moe layer + deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG) + deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) + if self.parallel_attn_mlp_res: + self.residual_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.residual_mlp = ArcticMLP(config, + use_deepspeed_implementation=self.use_deepspeed_implementation, + is_residual_mlp=True, + ds_optimized_quantization_config=deepspeed_quantization, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=True) # for the residual layer. always shard the base weight if doing deepspeed lora. + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + **kwargs, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + if "padding_mask" in kwargs: + warnings.warn( + "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" + ) + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, sequence_length)` where padding elements are indicated by 0. + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + 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`). + """ + + residual_input = hidden_states + + hidden_states = self.input_layernorm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = 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, + ) + hidden_states = residual_input + hidden_states + + residual_attn = hidden_states + + if self.parallel_attn_mlp_res: + # Note the architecture here is that the MOE layers reads the **pre-attention** input while there is a "normal" transformer residual part. + # This is to achieve better parallelization. + + # residual mlp part + + hidden_states = self.residual_layernorm(hidden_states) + hidden_states = self.residual_mlp(hidden_states) + residual_residual = residual_attn + hidden_states + # parallel mlp moe part + hidden_states = self.post_attention_layernorm(residual_input) # parallel attn mlp has the same input + hidden_states, gate_loss = self.block_sparse_moe(hidden_states) + hidden_states = residual_residual + hidden_states + else: + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states, gate_loss = self.block_sparse_moe(hidden_states) + hidden_states = residual_attn + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + outputs += (gate_loss,) + + return outputs + + +ARCTIC_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 ([`ArcticConfig`]): + 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 Arctic Model outputting raw hidden-states without any specific head on top.", + ARCTIC_START_DOCSTRING, +) +# Copied from transformers.models.mistral.modeling_mistral.MistralPreTrainedModel with Mistral->Arctic +class ArcticPreTrainedModel(PreTrainedModel): + config_class = ArcticConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["ArcticDecoderLayer"] + _skip_keys_device_placement = "past_key_values" + _supports_flash_attn_2 = True + _supports_sdpa = True + _supports_cache_class = True + + def _init_weights(self, module): + std = self.config.initializer_range + # if is_deepspeed_available(): + # # TODO(rajhans): remove this once ds has init for quantizedlinear. + # try: + # from deepspeed.linear.quantization import QuantizedLinear, QuantizedParameter + # if isinstance(module, QuantizedLinear): + # weights = module.weight.dequantized() + # weights.normal_(mean=0.0, std=std) + # if module.bias is not None: + # module.bias.data.zero_() + # module.weight = QuantizedParameter(weights) + # module.weight.to(dtype=torch.bfloat16, device=weights.device) + # el + 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_() + +MIXTRAL_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 `decoder_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 (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + 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)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_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. +""" + + +@add_start_docstrings( + "The bare Arctic Model outputting raw hidden-states without any specific head on top.", + ARCTIC_START_DOCSTRING, +) +# Copied from transformers.models.mistral.modeling_mistral.MistralModel with MISTRAL->MIXTRAL,Mistral->Arctic +class ArcticModel(ArcticPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ArcticDecoderLayer`] + + Args: + config: ArcticConfig + """ + + def __init__(self, config: ArcticConfig, **kwargs): + super().__init__(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.layers = nn.ModuleList( + [ArcticDecoderLayer(config, layer_idx, **kwargs) for layer_idx in range(config.num_hidden_layers)] + ) + self._attn_implementation = config._attn_implementation + self.norm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + self.gradient_checkpointing = True + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Ignore copy + @add_start_docstrings_to_model_forward(MIXTRAL_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[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, + ) -> Union[Tuple, MoeModelOutputWithPast]: + 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 + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + batch_size, seq_length = input_ids.shape + elif inputs_embeds is not None: + batch_size, seq_length, _ = inputs_embeds.shape + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + past_key_values_length = 0 + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + if use_cache: + use_legacy_cache = not isinstance(past_key_values, Cache) + if use_legacy_cache: + past_key_values = DynamicCache.from_legacy_cache(past_key_values) + past_key_values_length = past_key_values.get_usable_length(seq_length) + + if position_ids is None: + device = input_ids.device if input_ids is not None else inputs_embeds.device + position_ids = torch.arange( + past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device + ) + position_ids = position_ids.unsqueeze(0).view(-1, seq_length) + else: + position_ids = position_ids.view(-1, seq_length).long() + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache: + is_padding_right = attention_mask[:, -1].sum().item() != batch_size + if is_padding_right: + raise ValueError( + "You are attempting to perform batched generation with padding_side='right'" + " this may lead to unexpected behaviour for Flash Attention version of Arctic. Make sure to " + " call `tokenizer.padding_side = 'left'` before tokenizing the input. " + ) + + if self._attn_implementation == "flash_attention_2": + # 2d mask is passed through the layers + attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None + elif self._attn_implementation == "sdpa" and not output_attentions: + # output_attentions=True can not be supported when using SDPA, and we fall back on + # the manual implementation that requires a 4D causal mask in all cases. + attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( + attention_mask, + (batch_size, seq_length), + inputs_embeds, + past_key_values_length, + ) + else: + # 4d mask is passed through the layers + attention_mask = _prepare_4d_causal_attention_mask( + attention_mask, + (batch_size, seq_length), + inputs_embeds, + past_key_values_length, + sliding_window=self.config.sliding_window, + ) + + hidden_states = inputs_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + all_router_losses = () + next_decoder_cache = None + + for i, decoder_layer in enumerate(self.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, + attention_mask, + position_ids, + past_key_values, + output_attentions, + use_cache, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + if hasattr(layer_outputs[2 if output_attentions else 1], 'to_legacy_cache'): + next_decoder_cache = layer_outputs[2 if output_attentions else 1] + else: + if next_decoder_cache is None: + next_decoder_cache = [layer_outputs[2 if output_attentions else 1]] + else: + next_decoder_cache.append(layer_outputs[2 if output_attentions else 1]) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + all_router_losses += (layer_outputs[-1],) + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = None + if use_cache: + next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache and hasattr(next_decoder_cache, 'to_legacy_cache') else next_decoder_cache + torch.cuda.empty_cache() + + if not return_dict: + return tuple( + v + for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_losses] + if v is not None + ) + return MoeModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + router_logits=all_router_losses, + ) + +class ArcticForCausalLM(ArcticPreTrainedModel): + # TODO(jeffra): update _keys_to_ignore_on_load_unexpected with expert keys not relevant for this rank + _keys_to_ignore_on_load_unexpected = [r"model\.layers\.\d+\.block_sparse_moe\.experts\.\d+\.w\d+\.weight" + r"model\.layers\.\d+\.block_sparse_moe\.gate\.weight"] + _keys_to_ignore_on_load_missing = [r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight", + r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.gate\.wg\.weight"] + _tied_weights_keys = []#["lm_head.weight"] + + def __init__(self, config, **kwargs): + super().__init__(config) + self.model = ArcticModel(config, **kwargs) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.router_aux_loss_coef = config.router_aux_loss_coef + self.num_experts = config.num_local_experts + self.num_experts_per_tok = config.num_experts_per_tok + self.use_deepspeed_moe = kwargs.get(USE_DEEPSPEED_MOE_ARG, False) + self.moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1) + self.is_deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) is not None + self.gradient_checkpointing = True + # self.shard_base_weights_if_doing_lora = kwargs.get("shard_base_weights_if_doing_lora", False) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + + def _expert_number_from_param_name(self, param_name): + # example param_name: model.layers.1.block_sparse_moe.experts.10.w1.weight + pattern = r'experts\.(\d+)\.' + m = re.search(pattern, param_name) + if m: + return int(m[1]) + else: + return None + + def state_dict(self, *args, **kwargs): + state_dict = super().state_dict(*args, **kwargs) + + if not self.use_deepspeed_moe: + return state_dict + + # when trying to construct the deepspeed checkpoint we don't want to gather everything + if not getattr(self, '_gather_expert_params', False): + return state_dict + + rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0 + world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1 + + # non-lora experts + pattern = r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight" + expert_params = [s for s in state_dict.keys() if re.search(pattern, s)] + + for param_name in expert_params: + param_tensor = state_dict[param_name].to('cuda') + output = [torch.zeros_like(param_tensor) for _ in range(world_size)] + torch.distributed.gather(param_tensor, gather_list=output if rank == 0 else None, dst=0, group=None) + # rename from local rank to global rank + for gather_rank, gather_param in enumerate(output): + experts_per_rank = self.num_experts // self.moe_expert_parallel_size + new_expert_number = gather_rank * experts_per_rank + self._expert_number_from_param_name(param_name) + new_param_name = re.sub(r'(experts\.)(\d+)(\.)', rf'\g<1>{new_expert_number}\3', param_name) + state_dict[new_param_name] = gather_param + if rank == 0: + print(f"adding to state_dict and renaming: {param_name} -> {new_param_name}") + + # Handle custom LoRA implementation + # TODO(rajhans): the part below is untested and shows up when doing lora training. Should not affect inference. + if self.is_deepspeed_lora: + for param_name in list(state_dict.keys()): # Use list to avoid RuntimeError due to changing size during iteration + if param_name.endswith("base_weight"): + base_weight = state_dict[param_name].to('cuda') + + # If the base weight is sharded, gather weights from multiple ranks and concatenate + # except if the weights are from deespeed_moe which is not sharded (due to EP). + if self.shard_base_weights_if_doing_lora and 'deepspeed_moe.experts.deepspeed_experts' not in param_name: + gathered_weights = [torch.zeros_like(base_weight, + device=base_weight.device, dtype=base_weight.dtype) for _ in range(world_size)] + torch.distributed.gather(base_weight, gather_list=gathered_weights if rank == 0 else None, dst=0, group=None) + base_weight = torch.cat(gathered_weights, dim=1) + + + ## The part below is useful if we want to output HF transformer path weights, but commenting it for now + # Merge the LoRA weights into the base weights + # lora_weight_1 = state_dict.get(param_name.replace("base_weight", "lora_weight_1.weight")) + # lora_weight_2 = state_dict.get(param_name.replace("base_weight", "lora_weight_2.weight")) + # if lora_weight_1 is not None and lora_weight_2 is not None: + # lora_weights = torch.matmul(lora_weight_2, lora_weight_1) + # base_weight += lora_weights + # else: + # raise ValueError + + # # Rename the base weight to weight + # new_param_name = param_name.replace("base_weight", "weight") + # state_dict[new_param_name] = base_weight + + # Remove the base weight from the state dict + # del state_dict[param_name] + return state_dict + + + def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): + if not self.use_deepspeed_moe: + return super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1 + #TODO(jeffra): currently assumes fine-tuning only on one node, fix for world_size != ep size + if self.moe_expert_parallel_size > 1: + assert self.moe_expert_parallel_size == world_size, \ + f"currently only support expert parallel size equal to world size but {self.moe_expert_parallel_size=} and {world_size=}" + + rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0 + num_local_experts = self.num_experts // self.moe_expert_parallel_size + local_expert_range = range(num_local_experts * rank, num_local_experts * rank + num_local_experts) + + # no deepspeed + # model.layers.1.block_sparse_moe.experts.10.w1.weight + # model.layers.1.block_sparse_moe.gate.weight + # w. deepspeed + # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.gate.wg.weight + # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.experts.deepspeed_experts.10.w1.weight + + gate_pattern = r'model\.layers\.\d+\.block_sparse_moe\.gate\.weight' + + expert_params_to_keep = [] + expert_params_to_remove = [] + gate_params = [] + for param_name in state_dict.keys(): + expert_number = self._expert_number_from_param_name(param_name) + if expert_number is not None: + if expert_number in local_expert_range: + expert_params_to_keep.append(param_name) + else: + expert_params_to_remove.append(param_name) + elif re.search(gate_pattern, param_name): + gate_params.append(param_name) + + # drop all experts in the state_dict that we don't need locally + for param_name in expert_params_to_remove: + print(f'{rank=} dropping {param_name}') + del state_dict[param_name] + + # rename remaining experts to align with the local config + for param_name in expert_params_to_keep: + # adjust expert number wrt expert parallelism + new_expert_number = self._expert_number_from_param_name(param_name) % num_local_experts + new_param_name = re.sub(r'(experts\.)(\d+)(\.)', rf'\g<1>{new_expert_number}\3', param_name) + + # use deepspeed moe param path + split_param_name = new_param_name.split('.') + idx = split_param_name.index('experts') + ds_moe_path = "mlp.deepspeed_moe.experts.deepspeed_experts".split('.') + new_param_name = split_param_name[0:idx] + ds_moe_path + split_param_name[idx+1:] + new_param_name = ".".join(new_param_name) + + print(f'Deepspeed {rank=}, renaming {param_name} -> {new_param_name}') + state_dict[new_param_name] = state_dict.pop(param_name) + + # rename gate params + ds_suffix = "mlp.deepspeed_moe.gate.wg.weight".split('.') + for param_name in gate_params: + new_param_name = '.'.join(param_name.split('.')[:4] + ds_suffix) + print(f'Gating: {rank=}, renaming {param_name} -> {new_param_name}') + state_dict[new_param_name] = state_dict.pop(param_name) + + # If deepspeed lora is enabled, then we need to rename weight to base_weight. + # Furthermore, if the base_weight is sharded, we need to shard each weight and select the slice of local rank. + if self.is_deepspeed_lora: + local_state_dict = self.state_dict() + for param_name in local_state_dict: + if not param_name.endswith("base_weight"): + continue + + incoming_param_name = param_name.replace("base_weight", "weight") + if incoming_param_name not in state_dict: + continue + + incoming_param = state_dict[incoming_param_name] + + shape_local = local_state_dict[param_name].shape + shape_incoming = incoming_param.shape + if 'deepspeed_moe' in incoming_param_name: + assert shape_local == shape_incoming, "deepspeed moe weights are never sharded" + else: + assert shape_incoming[1] == shape_local[1] * world_size, "weights should be sharded equally across world size" + incoming_param = incoming_param[:, rank*shape_local[1]: (rank+1)*shape_local[1]] + print(f'Deepspeed lora: {rank=}, renaming {incoming_param_name} -> {param_name}') + state_dict[param_name] = incoming_param + del state_dict[incoming_param_name] + + return super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + # Ignore copy + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[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, MoeCausalLMOutputWithPast]: + 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]`. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, ArcticForCausalLM + + >>> model = ArcticForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) + >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) + + >>> 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 outputs 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, + ) + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + logits = logits.float() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + + # Move to same device for model parallelism. + aux_loss = sum([out.to(logits.device) for out in outputs[-1]]) + if labels is not None: + loss += self.router_aux_loss_coef * aux_loss + + if not return_dict: + output = (logits,) + outputs[1:] + # torch.distributed.barrier() + return (loss,) + output if loss is not None else output + + return MoeCausalLMOutputWithPast( + loss=loss, + aux_loss=aux_loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + # Omit tokens covered by past_key_values + if past_key_values is not None: + if isinstance(past_key_values, Cache): + cache_length = past_key_values.get_seq_length() + past_length = past_key_values.seen_tokens + max_cache_length = past_key_values.get_max_length() + else: + cache_length = past_length = past_key_values[0][0].shape[2] + max_cache_length = None + + # Keep only the unprocessed tokens: + # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where + # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as + # input) + if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: + input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] + # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard + # input_ids based on the past_length. + elif past_length < input_ids.shape[1]: + input_ids = input_ids[:, past_length:] + # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens. + + # If we are about to go beyond the maximum cache length, we need to crop the input attention mask. + if ( + max_cache_length is not None + and attention_mask is not None + and cache_length + input_ids.shape[1] > max_cache_length + ): + attention_mask = attention_mask[:, -max_cache_length:] + + position_ids = kwargs.get("position_ids", None) + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -input_ids.shape[1] :] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "position_ids": position_ids, + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += ( + tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past), + ) + return reordered_past + + +@add_start_docstrings( + """ + The Arctic Model transformer with a sequence classification head on top (linear layer). + + [`ArcticForSequenceClassification`] 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). + """, + ARCTIC_START_DOCSTRING, +) +# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Arctic, LLAMA->MIXTRAL +class ArcticForSequenceClassification(ArcticPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.model = ArcticModel(config) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + @add_start_docstrings_to_model_forward(MIXTRAL_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[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 + + transformer_outputs = self.model( + 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 = transformer_outputs[0] + logits = self.score(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: + labels = labels.to(logits.device) + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + 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=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) diff --git a/optimum/habana/transformers/models/snowflake/tokenization_arctic.py b/optimum/habana/transformers/models/snowflake/tokenization_arctic.py new file mode 100644 index 0000000000..b0b2cb24b2 --- /dev/null +++ b/optimum/habana/transformers/models/snowflake/tokenization_arctic.py @@ -0,0 +1,57 @@ +"""Tokenization classes for Arctic. Copied from https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d.""" + +from typing import Any, Dict, Optional + +from transformers.models.llama import LlamaTokenizer + + +class ArcticTokenizer(LlamaTokenizer): + + def __init__( + self, + vocab_file, + unk_token="", + bos_token="", + eos_token="", + pad_token=None, + sp_model_kwargs: Optional[Dict[str, Any]] = None, + add_bos_token=True, + add_eos_token=False, + clean_up_tokenization_spaces=False, + use_default_system_prompt=False, + spaces_between_special_tokens=False, + legacy=False, + add_prefix_space=True, + **kwargs, + ): + # Same as LlamaTokenizer except default legacy=False. + super().__init__( + vocab_file, + bos_token=bos_token, + eos_token=eos_token, + unk_token=unk_token, + pad_token=pad_token, + sp_model_kwargs=sp_model_kwargs, + add_bos_token=add_bos_token, + add_eos_token=add_eos_token, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + use_default_system_prompt=use_default_system_prompt, + spaces_between_special_tokens=spaces_between_special_tokens, + legacy=legacy, + add_prefix_space=add_prefix_space, + **kwargs, + ) + + @property + def default_chat_template(self): + """ + This template formats inputs in the standard Arctic format. + """ + return ( + "{% for message in messages %}" + "{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}" + "{% endfor %}" + "{% if add_generation_prompt %}" + "{{ '<|im_start|>assistant\n' }}" + "{% endif %}" + ) From c25b59a17e05ed945c316c19b5c0cc06c99ba3fd Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Fri, 25 Oct 2024 09:46:26 -0700 Subject: [PATCH 02/20] Make style and resolve GenerationMixin warnings Signed-off-by: Daniel Huang --- optimum/habana/transformers/modeling_utils.py | 1 - .../models/snowflake/modeling_arctic.py | 432 +++++++++++------- .../models/snowflake/tokenization_arctic.py | 1 - 3 files changed, 256 insertions(+), 178 deletions(-) diff --git a/optimum/habana/transformers/modeling_utils.py b/optimum/habana/transformers/modeling_utils.py index 9b11b7b5da..c38c57512d 100644 --- a/optimum/habana/transformers/modeling_utils.py +++ b/optimum/habana/transformers/modeling_utils.py @@ -793,4 +793,3 @@ def adapt_transformers_to_gaudi(): transformers.AutoConfig.register("arctic", ArcticConfig) transformers.AutoModelForCausalLM.register(ArcticConfig, ArcticForCausalLM) transformers.AutoTokenizer.register(ArcticConfig, ArcticTokenizer) - diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index ea0c3839e4..91f30e47ed 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -17,24 +17,24 @@ # 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 Arctic model. Copied from https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d.""" +"""PyTorch Arctic model. Copied from https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d.""" + import copy import inspect -import time import math -import warnings import re +import warnings from typing import List, Optional, Tuple, Union -import deepspeed import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss - +from transformers import GenerationMixin from transformers.activations import ACT2FN from transformers.cache_utils import Cache, DynamicCache +from transformers.integrations.deepspeed import is_deepspeed_available from transformers.modeling_attn_mask_utils import ( _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, @@ -55,12 +55,13 @@ replace_return_docstrings, ) from transformers.utils.import_utils import is_torch_fx_available + from .configuration_arctic import ArcticConfig -from transformers.integrations.deepspeed import is_deepspeed_available -from transformers.utils.versions import require_version + if is_deepspeed_available(): - from deepspeed.moe.layer import MoE + from deepspeed.moe.layer import MoE + # Note that below will crash if there is an available deepspeed that does not have ds_linear. try: import deepspeed.linear as ds_linear @@ -101,9 +102,10 @@ # if raise_error: # raise ValueError(f"DeepSpeed is required for this feature, {error_msg}") # else: - + # return available_and_valid + def load_balancing_loss_func( gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=4, attention_mask: Optional[torch.Tensor] = None ) -> float: @@ -305,7 +307,7 @@ class ArcticAttention(nn.Module): and "Generating Long Sequences with Sparse Transformers". """ - def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwargs): + def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwargs): super().__init__() self.config = config self.layer_idx = layer_idx @@ -332,35 +334,50 @@ def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwa f" and `num_heads`: {self.num_heads})." ) - deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG) deepspeed_lora_config = kwargs.get(DEEPSPEED_LORA_CONFIG) quantization_config = kwargs.get(QUANTIZATION_CONFIG, None) - self.q_proj = get_arctic_linear(self.hidden_size, self.num_heads * self.head_dim, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, - dtype=torch.bfloat16) - self.k_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, - dtype=torch.bfloat16) - self.v_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, - dtype=torch.bfloat16) - self.o_proj = get_arctic_linear(self.hidden_size, self.hidden_size, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, - dtype=torch.bfloat16) - + self.q_proj = get_arctic_linear( + self.hidden_size, + self.num_heads * self.head_dim, + bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16, + ) + self.k_proj = get_arctic_linear( + self.hidden_size, + self.num_key_value_heads * self.head_dim, + bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16, + ) + self.v_proj = get_arctic_linear( + self.hidden_size, + self.num_key_value_heads * self.head_dim, + bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16, + ) + self.o_proj = get_arctic_linear( + self.hidden_size, + self.hidden_size, + bias=False, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_lora_config=deepspeed_lora_config, + ds_optimized_quantization_config=quantization_config, + ds_optimized_base_weight_sharding=True, + dtype=torch.bfloat16, + ) + self.rotary_emb = ArcticRotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, @@ -746,14 +763,17 @@ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query (max_seqlen_in_batch_q, max_seqlen_in_batch_k), ) -def get_arctic_linear(input_dim, - output_dim, - bias=False, - use_deepspeed_implementation=False, - ds_optimized_lora_config=None, - ds_optimized_quantization_config=None, - ds_optimized_base_weight_sharding=False, - dtype=torch.bfloat16): + +def get_arctic_linear( + input_dim, + output_dim, + bias=False, + use_deepspeed_implementation=False, + ds_optimized_lora_config=None, + ds_optimized_quantization_config=None, + ds_optimized_base_weight_sharding=False, + dtype=torch.bfloat16, +): """Can return deepspeed optimized linear if available. Args: input_dim, output_dim, bias, dtype: self explanatory (same as from nn.Linear) @@ -765,8 +785,12 @@ def get_arctic_linear(input_dim, if is_deepspeed_available(): if ds_optimized_lora_config is not None: ds_optimized_lora_config: ds_linear.LoRAConfig = copy.deepcopy(ds_optimized_lora_config) - ds_optimized_lora_config.base_weight_sharding = torch.distributed.get_world_size() if ds_optimized_base_weight_sharding else 1 - return ds_linear.OptimizedLinear(input_dim, output_dim, bias, ds_optimized_lora_config, ds_optimized_quantization_config, dtype=dtype) + ds_optimized_lora_config.base_weight_sharding = ( + torch.distributed.get_world_size() if ds_optimized_base_weight_sharding else 1 + ) + return ds_linear.OptimizedLinear( + input_dim, output_dim, bias, ds_optimized_lora_config, ds_optimized_quantization_config, dtype=dtype + ) return nn.Linear(input_dim, output_dim, bias=bias, dtype=dtype) @@ -866,12 +890,15 @@ def forward( class ArcticMLP(nn.Module): - def __init__(self, config: ArcticConfig, - use_deepspeed_implementation=False, - ds_optimized_lora_config=None, - ds_optimized_quantization_config=None, - shard_base_weights_if_doing_lora=False, - is_residual_mlp=False): + def __init__( + self, + config: ArcticConfig, + use_deepspeed_implementation=False, + ds_optimized_lora_config=None, + ds_optimized_quantization_config=None, + shard_base_weights_if_doing_lora=False, + is_residual_mlp=False, + ): """MLP class for Arctic supporting vanilla linear layers as well as some deepspeed optimizations. ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer. @@ -879,28 +906,40 @@ def __init__(self, config: ArcticConfig, ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus in a tensor parallel way. is_residual_mlp: bool. If true, this is MLP inside arctic residual layer which has ffn_dim the same as full intermediate_size. - """ + """ super(ArcticMLP, self).__init__() self.hidden_dim = config.hidden_size - self.ffn_dim = config.intermediate_size if not is_residual_mlp else self.hidden_dim - self.w1 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False, - use_deepspeed_implementation=use_deepspeed_implementation, - ds_optimized_lora_config=ds_optimized_lora_config, - ds_optimized_quantization_config=ds_optimized_quantization_config, - ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, - dtype=torch.bfloat16) - self.w2 = get_arctic_linear(self.ffn_dim, self.hidden_dim, False, - use_deepspeed_implementation=use_deepspeed_implementation, - ds_optimized_lora_config=ds_optimized_lora_config, - ds_optimized_quantization_config=ds_optimized_quantization_config, - ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, - dtype=torch.bfloat16) - self.w3 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False, - use_deepspeed_implementation=use_deepspeed_implementation, - ds_optimized_lora_config=ds_optimized_lora_config, - ds_optimized_quantization_config=ds_optimized_quantization_config, - ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, - dtype=torch.bfloat16) + self.ffn_dim = config.intermediate_size if not is_residual_mlp else self.hidden_dim + self.w1 = get_arctic_linear( + self.hidden_dim, + self.ffn_dim, + False, + use_deepspeed_implementation=use_deepspeed_implementation, + ds_optimized_lora_config=ds_optimized_lora_config, + ds_optimized_quantization_config=ds_optimized_quantization_config, + ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + dtype=torch.bfloat16, + ) + self.w2 = get_arctic_linear( + self.ffn_dim, + self.hidden_dim, + False, + use_deepspeed_implementation=use_deepspeed_implementation, + ds_optimized_lora_config=ds_optimized_lora_config, + ds_optimized_quantization_config=ds_optimized_quantization_config, + ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + dtype=torch.bfloat16, + ) + self.w3 = get_arctic_linear( + self.hidden_dim, + self.ffn_dim, + False, + use_deepspeed_implementation=use_deepspeed_implementation, + ds_optimized_lora_config=ds_optimized_lora_config, + ds_optimized_quantization_config=ds_optimized_quantization_config, + ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + dtype=torch.bfloat16, + ) self.act_fn = ACT2FN[config.hidden_act] def forward(self, hidden_states): @@ -915,54 +954,65 @@ def __init__(self, config: ArcticConfig, layer_id: int, **kwargs): self.hidden_dim = config.hidden_size self.num_experts = config.num_local_experts - self.layer_id = layer_id + self.layer_id = layer_id self.top_k = config.num_experts_per_tok - self.is_moe_layer = (layer_id+1) % config.moe_layer_frequency == 0 + self.is_moe_layer = (layer_id + 1) % config.moe_layer_frequency == 0 self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] if self.use_deepspeed_implementation and MoE is None: raise ValueError("Deepspeed is not installed") quantization_config = kwargs.get(QUANTIZATION_CONFIG, None) deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) - if not self.is_moe_layer: # dense, not MoE - self.mlp = ArcticMLP(config, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_quantization_config=quantization_config, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=True) + if not self.is_moe_layer: # dense, not MoE + self.mlp = ArcticMLP( + config, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_quantization_config=quantization_config, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=True, + ) else: - if self.use_deepspeed_implementation: # DeepSpeed's MoE + if self.use_deepspeed_implementation: # DeepSpeed's MoE moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1) - self.mlp = MoE(self.hidden_dim, - # base weight sharding false for all deepspeed moe calls because it is already sharded - ArcticMLP(config, - use_deepspeed_implementation=True, - ds_optimized_quantization_config=quantization_config, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=False), - num_experts=config.num_local_experts, - ep_size=moe_expert_parallel_size, - k=config.num_experts_per_tok, - use_residual=False, - capacity_factor=config.moe_train_capacity_factor, - eval_capacity_factor=config.moe_eval_capacity_factor, - enable_expert_tensor_parallelism=config.enable_expert_tensor_parallelism, - min_capacity=config.moe_min_capacity, - drop_tokens=config.moe_token_dropping - ) + self.mlp = MoE( + self.hidden_dim, + # base weight sharding false for all deepspeed moe calls because it is already sharded + ArcticMLP( + config, + use_deepspeed_implementation=True, + ds_optimized_quantization_config=quantization_config, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=False, + ), + num_experts=config.num_local_experts, + ep_size=moe_expert_parallel_size, + k=config.num_experts_per_tok, + use_residual=False, + capacity_factor=config.moe_train_capacity_factor, + eval_capacity_factor=config.moe_eval_capacity_factor, + enable_expert_tensor_parallelism=config.enable_expert_tensor_parallelism, + min_capacity=config.moe_min_capacity, + drop_tokens=config.moe_token_dropping, + ) else: # "local" MoE implementation self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False) - self.experts = nn.ModuleList([ArcticMLP(config, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_quantization_config=quantization_config, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=True) for i in range(self.num_experts)]) + self.experts = nn.ModuleList( + [ + ArcticMLP( + config, + use_deepspeed_implementation=self.use_deepspeed_implementation, + ds_optimized_quantization_config=quantization_config, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=True, + ) + for i in range(self.num_experts) + ] + ) # if torch.distributed.get_rank() == 0: # deepspeed.runtime.utils.see_memory_usage("", force=True) - # Similar in behavior to transformers.models.mixtral.modeling_mixtral.MixtralSparseMoeBlock.forward but more efficient. def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape @@ -983,7 +1033,8 @@ def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: # Matching between experts, tokens, and their top-k rank. For every i, # expert_idx[i] is the rank topk_idx[i] expert for token_idx[i]. expert_idx, token_idx, topk_idx = torch.where( - selected_experts == torch.arange( + selected_experts + == torch.arange( self.num_experts, device=selected_experts.device, ).view((self.num_experts, 1, 1)) @@ -1014,7 +1065,9 @@ def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype)) # torch.distributed.barrier() final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim) - return final_hidden_states, load_balancing_loss_func((router_logits, ), self.num_experts, self.top_k) # ZY: let's directly output the loss to align what we have in ds + return final_hidden_states, load_balancing_loss_func( + (router_logits,), self.num_experts, self.top_k + ) # ZY: let's directly output the loss to align what we have in ds def forward(self, hidden_states: torch.Tensor): if self.is_moe_layer: @@ -1035,21 +1088,25 @@ def __init__(self, config: ArcticConfig, layer_idx: int, **kwargs): self.hidden_size = config.hidden_size self.self_attn = MIXTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx, **kwargs) self.block_sparse_moe = ArcticMoE(config, layer_id=layer_idx, **kwargs) - self.input_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.input_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] - self.parallel_attn_mlp_res = config.parallel_attn_mlp_res and self.block_sparse_moe.is_moe_layer # add residual only when it is moe layer + self.parallel_attn_mlp_res = ( + config.parallel_attn_mlp_res and self.block_sparse_moe.is_moe_layer + ) # add residual only when it is moe layer deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG) deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) if self.parallel_attn_mlp_res: - self.residual_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) - self.residual_mlp = ArcticMLP(config, - use_deepspeed_implementation=self.use_deepspeed_implementation, - is_residual_mlp=True, - ds_optimized_quantization_config=deepspeed_quantization, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=True) # for the residual layer. always shard the base weight if doing deepspeed lora. + self.residual_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.residual_mlp = ArcticMLP( + config, + use_deepspeed_implementation=self.use_deepspeed_implementation, + is_residual_mlp=True, + ds_optimized_quantization_config=deepspeed_quantization, + ds_optimized_lora_config=deepspeed_lora, + shard_base_weights_if_doing_lora=True, + ) # for the residual layer. always shard the base weight if doing deepspeed lora. def forward( self, @@ -1095,7 +1152,7 @@ def forward( hidden_states = residual_input + hidden_states residual_attn = hidden_states - + if self.parallel_attn_mlp_res: # Note the architecture here is that the MOE layers reads the **pre-attention** input while there is a "normal" transformer residual part. # This is to achieve better parallelization. @@ -1106,7 +1163,7 @@ def forward( hidden_states = self.residual_mlp(hidden_states) residual_residual = residual_attn + hidden_states # parallel mlp moe part - hidden_states = self.post_attention_layernorm(residual_input) # parallel attn mlp has the same input + hidden_states = self.post_attention_layernorm(residual_input) # parallel attn mlp has the same input hidden_states, gate_loss = self.block_sparse_moe(hidden_states) hidden_states = residual_residual + hidden_states else: @@ -1182,6 +1239,7 @@ def _init_weights(self, module): if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() + MIXTRAL_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): @@ -1406,7 +1464,7 @@ def forward( hidden_states = layer_outputs[0] if use_cache: - if hasattr(layer_outputs[2 if output_attentions else 1], 'to_legacy_cache'): + if hasattr(layer_outputs[2 if output_attentions else 1], "to_legacy_cache"): next_decoder_cache = layer_outputs[2 if output_attentions else 1] else: if next_decoder_cache is None: @@ -1426,8 +1484,12 @@ def forward( next_cache = None if use_cache: - next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache and hasattr(next_decoder_cache, 'to_legacy_cache') else next_decoder_cache - torch.cuda.empty_cache() + next_cache = ( + next_decoder_cache.to_legacy_cache() + if use_legacy_cache and hasattr(next_decoder_cache, "to_legacy_cache") + else next_decoder_cache + ) + torch.cuda.empty_cache() if not return_dict: return tuple( @@ -1443,13 +1505,18 @@ def forward( router_logits=all_router_losses, ) -class ArcticForCausalLM(ArcticPreTrainedModel): + +class ArcticForCausalLM(ArcticPreTrainedModel, GenerationMixin): # TODO(jeffra): update _keys_to_ignore_on_load_unexpected with expert keys not relevant for this rank - _keys_to_ignore_on_load_unexpected = [r"model\.layers\.\d+\.block_sparse_moe\.experts\.\d+\.w\d+\.weight" - r"model\.layers\.\d+\.block_sparse_moe\.gate\.weight"] - _keys_to_ignore_on_load_missing = [r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight", - r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.gate\.wg\.weight"] - _tied_weights_keys = []#["lm_head.weight"] + _keys_to_ignore_on_load_unexpected = [ + r"model\.layers\.\d+\.block_sparse_moe\.experts\.\d+\.w\d+\.weight" + r"model\.layers\.\d+\.block_sparse_moe\.gate\.weight" + ] + _keys_to_ignore_on_load_missing = [ + r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight", + r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.gate\.wg\.weight", + ] + _tied_weights_keys = [] # ["lm_head.weight"] def __init__(self, config, **kwargs): super().__init__(config) @@ -1485,10 +1552,9 @@ def set_decoder(self, decoder): def get_decoder(self): return self.model - def _expert_number_from_param_name(self, param_name): # example param_name: model.layers.1.block_sparse_moe.experts.10.w1.weight - pattern = r'experts\.(\d+)\.' + pattern = r"experts\.(\d+)\." m = re.search(pattern, param_name) if m: return int(m[1]) @@ -1502,75 +1568,87 @@ def state_dict(self, *args, **kwargs): return state_dict # when trying to construct the deepspeed checkpoint we don't want to gather everything - if not getattr(self, '_gather_expert_params', False): + if not getattr(self, "_gather_expert_params", False): return state_dict rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0 world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1 # non-lora experts - pattern = r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight" + pattern = ( + r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight" + ) expert_params = [s for s in state_dict.keys() if re.search(pattern, s)] for param_name in expert_params: - param_tensor = state_dict[param_name].to('cuda') + param_tensor = state_dict[param_name].to("cuda") output = [torch.zeros_like(param_tensor) for _ in range(world_size)] torch.distributed.gather(param_tensor, gather_list=output if rank == 0 else None, dst=0, group=None) # rename from local rank to global rank for gather_rank, gather_param in enumerate(output): experts_per_rank = self.num_experts // self.moe_expert_parallel_size new_expert_number = gather_rank * experts_per_rank + self._expert_number_from_param_name(param_name) - new_param_name = re.sub(r'(experts\.)(\d+)(\.)', rf'\g<1>{new_expert_number}\3', param_name) + new_param_name = re.sub(r"(experts\.)(\d+)(\.)", rf"\g<1>{new_expert_number}\3", param_name) state_dict[new_param_name] = gather_param if rank == 0: print(f"adding to state_dict and renaming: {param_name} -> {new_param_name}") - - # Handle custom LoRA implementation + + # Handle custom LoRA implementation # TODO(rajhans): the part below is untested and shows up when doing lora training. Should not affect inference. if self.is_deepspeed_lora: - for param_name in list(state_dict.keys()): # Use list to avoid RuntimeError due to changing size during iteration - if param_name.endswith("base_weight"): - base_weight = state_dict[param_name].to('cuda') - - # If the base weight is sharded, gather weights from multiple ranks and concatenate - # except if the weights are from deespeed_moe which is not sharded (due to EP). - if self.shard_base_weights_if_doing_lora and 'deepspeed_moe.experts.deepspeed_experts' not in param_name: - gathered_weights = [torch.zeros_like(base_weight, - device=base_weight.device, dtype=base_weight.dtype) for _ in range(world_size)] - torch.distributed.gather(base_weight, gather_list=gathered_weights if rank == 0 else None, dst=0, group=None) + for param_name in list( + state_dict.keys() + ): # Use list to avoid RuntimeError due to changing size during iteration + if param_name.endswith("base_weight"): + base_weight = state_dict[param_name].to("cuda") + + # If the base weight is sharded, gather weights from multiple ranks and concatenate + # except if the weights are from deespeed_moe which is not sharded (due to EP). + if ( + self.shard_base_weights_if_doing_lora + and "deepspeed_moe.experts.deepspeed_experts" not in param_name + ): + gathered_weights = [ + torch.zeros_like(base_weight, device=base_weight.device, dtype=base_weight.dtype) + for _ in range(world_size) + ] + torch.distributed.gather( + base_weight, gather_list=gathered_weights if rank == 0 else None, dst=0, group=None + ) base_weight = torch.cat(gathered_weights, dim=1) - - ## The part below is useful if we want to output HF transformer path weights, but commenting it for now - # Merge the LoRA weights into the base weights - # lora_weight_1 = state_dict.get(param_name.replace("base_weight", "lora_weight_1.weight")) - # lora_weight_2 = state_dict.get(param_name.replace("base_weight", "lora_weight_2.weight")) + ## The part below is useful if we want to output HF transformer path weights, but commenting it for now + # Merge the LoRA weights into the base weights + # lora_weight_1 = state_dict.get(param_name.replace("base_weight", "lora_weight_1.weight")) + # lora_weight_2 = state_dict.get(param_name.replace("base_weight", "lora_weight_2.weight")) # if lora_weight_1 is not None and lora_weight_2 is not None: # lora_weights = torch.matmul(lora_weight_2, lora_weight_1) # base_weight += lora_weights # else: - # raise ValueError + # raise ValueError - # # Rename the base weight to weight - # new_param_name = param_name.replace("base_weight", "weight") - # state_dict[new_param_name] = base_weight - - # Remove the base weight from the state dict - # del state_dict[param_name] - return state_dict + # # Rename the base weight to weight + # new_param_name = param_name.replace("base_weight", "weight") + # state_dict[new_param_name] = base_weight + # Remove the base weight from the state dict + # del state_dict[param_name] + return state_dict - def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): + def _load_from_state_dict( + self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ): if not self.use_deepspeed_moe: return super()._load_from_state_dict( state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs ) world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1 - #TODO(jeffra): currently assumes fine-tuning only on one node, fix for world_size != ep size + # TODO(jeffra): currently assumes fine-tuning only on one node, fix for world_size != ep size if self.moe_expert_parallel_size > 1: - assert self.moe_expert_parallel_size == world_size, \ - f"currently only support expert parallel size equal to world size but {self.moe_expert_parallel_size=} and {world_size=}" + assert ( + self.moe_expert_parallel_size == world_size + ), f"currently only support expert parallel size equal to world size but {self.moe_expert_parallel_size=} and {world_size=}" rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0 num_local_experts = self.num_experts // self.moe_expert_parallel_size @@ -1583,7 +1661,7 @@ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, miss # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.gate.wg.weight # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.experts.deepspeed_experts.10.w1.weight - gate_pattern = r'model\.layers\.\d+\.block_sparse_moe\.gate\.weight' + gate_pattern = r"model\.layers\.\d+\.block_sparse_moe\.gate\.weight" expert_params_to_keep = [] expert_params_to_remove = [] @@ -1600,30 +1678,30 @@ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, miss # drop all experts in the state_dict that we don't need locally for param_name in expert_params_to_remove: - print(f'{rank=} dropping {param_name}') + print(f"{rank=} dropping {param_name}") del state_dict[param_name] # rename remaining experts to align with the local config for param_name in expert_params_to_keep: # adjust expert number wrt expert parallelism new_expert_number = self._expert_number_from_param_name(param_name) % num_local_experts - new_param_name = re.sub(r'(experts\.)(\d+)(\.)', rf'\g<1>{new_expert_number}\3', param_name) + new_param_name = re.sub(r"(experts\.)(\d+)(\.)", rf"\g<1>{new_expert_number}\3", param_name) # use deepspeed moe param path - split_param_name = new_param_name.split('.') - idx = split_param_name.index('experts') - ds_moe_path = "mlp.deepspeed_moe.experts.deepspeed_experts".split('.') - new_param_name = split_param_name[0:idx] + ds_moe_path + split_param_name[idx+1:] + split_param_name = new_param_name.split(".") + idx = split_param_name.index("experts") + ds_moe_path = "mlp.deepspeed_moe.experts.deepspeed_experts".split(".") + new_param_name = split_param_name[0:idx] + ds_moe_path + split_param_name[idx + 1 :] new_param_name = ".".join(new_param_name) - print(f'Deepspeed {rank=}, renaming {param_name} -> {new_param_name}') + print(f"Deepspeed {rank=}, renaming {param_name} -> {new_param_name}") state_dict[new_param_name] = state_dict.pop(param_name) # rename gate params - ds_suffix = "mlp.deepspeed_moe.gate.wg.weight".split('.') + ds_suffix = "mlp.deepspeed_moe.gate.wg.weight".split(".") for param_name in gate_params: - new_param_name = '.'.join(param_name.split('.')[:4] + ds_suffix) - print(f'Gating: {rank=}, renaming {param_name} -> {new_param_name}') + new_param_name = ".".join(param_name.split(".")[:4] + ds_suffix) + print(f"Gating: {rank=}, renaming {param_name} -> {new_param_name}") state_dict[new_param_name] = state_dict.pop(param_name) # If deepspeed lora is enabled, then we need to rename weight to base_weight. @@ -1642,12 +1720,14 @@ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, miss shape_local = local_state_dict[param_name].shape shape_incoming = incoming_param.shape - if 'deepspeed_moe' in incoming_param_name: + if "deepspeed_moe" in incoming_param_name: assert shape_local == shape_incoming, "deepspeed moe weights are never sharded" else: - assert shape_incoming[1] == shape_local[1] * world_size, "weights should be sharded equally across world size" - incoming_param = incoming_param[:, rank*shape_local[1]: (rank+1)*shape_local[1]] - print(f'Deepspeed lora: {rank=}, renaming {incoming_param_name} -> {param_name}') + assert ( + shape_incoming[1] == shape_local[1] * world_size + ), "weights should be sharded equally across world size" + incoming_param = incoming_param[:, rank * shape_local[1] : (rank + 1) * shape_local[1]] + print(f"Deepspeed lora: {rank=}, renaming {incoming_param_name} -> {param_name}") state_dict[param_name] = incoming_param del state_dict[incoming_param_name] diff --git a/optimum/habana/transformers/models/snowflake/tokenization_arctic.py b/optimum/habana/transformers/models/snowflake/tokenization_arctic.py index b0b2cb24b2..776c1dc50b 100644 --- a/optimum/habana/transformers/models/snowflake/tokenization_arctic.py +++ b/optimum/habana/transformers/models/snowflake/tokenization_arctic.py @@ -6,7 +6,6 @@ class ArcticTokenizer(LlamaTokenizer): - def __init__( self, vocab_file, From 485010a1476918201a2e293696bcf21ee268ddd8 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 25 Nov 2024 16:18:31 -0800 Subject: [PATCH 03/20] Fixed tokenization imports Signed-off-by: Daniel Huang --- .../habana/transformers/models/snowflake/tokenization_arctic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/optimum/habana/transformers/models/snowflake/tokenization_arctic.py b/optimum/habana/transformers/models/snowflake/tokenization_arctic.py index 776c1dc50b..8fbe2463b6 100644 --- a/optimum/habana/transformers/models/snowflake/tokenization_arctic.py +++ b/optimum/habana/transformers/models/snowflake/tokenization_arctic.py @@ -2,7 +2,7 @@ from typing import Any, Dict, Optional -from transformers.models.llama import LlamaTokenizer +from transformers.models.llama.tokenization_llama import LlamaTokenizer class ArcticTokenizer(LlamaTokenizer): From 22013b366c08d19a97617b32f6859671aa93b172 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Fri, 27 Dec 2024 17:15:40 -0800 Subject: [PATCH 04/20] Updated requirements for Arctic Model Signed-off-by: Daniel Huang --- examples/text-generation/requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/text-generation/requirements.txt b/examples/text-generation/requirements.txt index 680dc8a2bb..c691c7b730 100644 --- a/examples/text-generation/requirements.txt +++ b/examples/text-generation/requirements.txt @@ -1,2 +1,3 @@ datasets peft +sentencepiece From 209eebef1e5295070e71a60d37505d2a4d41b61c Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Fri, 27 Dec 2024 17:16:20 -0800 Subject: [PATCH 05/20] Apply fix for ArcticRMSNorm from Llama Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 91f30e47ed..83d8aefd08 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -56,6 +56,14 @@ ) from transformers.utils.import_utils import is_torch_fx_available +try: + from habana_frameworks.torch.hpex.normalization import FusedRMSNorm as FusedRMSNorm + + has_fused_rms_norm = True +except ImportError: + has_fused_rms_norm = False + print("Not using HPU fused kernel for RMSNorm") + from .configuration_arctic import ArcticConfig @@ -206,11 +214,27 @@ def __init__(self, hidden_size, eps=1e-6): 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) + """ + Modified from original ArcticRMS implementation: + - Use Habana fused RMSNorm + + Modifications copied from ../llama/modeling_llama.py:gaudi_llama_rmsnorm_forward() + """ + if hidden_states.device.type == "hpu" and has_fused_rms_norm: + # mixed dtypes are not good for FusedRMSNorm, both inputs need to have same dtype + if hidden_states.dtype != self.weight.dtype: + orig_dtype = hidden_states.dtype + hidden_states = FusedRMSNorm.apply(hidden_states.to(self.weight.dtype), self.weight, self.variance_epsilon) + return hidden_states.to(orig_dtype) + else: + hidden_states = FusedRMSNorm.apply(hidden_states, self.weight, self.variance_epsilon) + return hidden_states + else: + 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) # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Arctic @@ -1518,7 +1542,7 @@ class ArcticForCausalLM(ArcticPreTrainedModel, GenerationMixin): ] _tied_weights_keys = [] # ["lm_head.weight"] - def __init__(self, config, **kwargs): + def __init__(self, config: ArcticConfig, **kwargs): super().__init__(config) self.model = ArcticModel(config, **kwargs) self.vocab_size = config.vocab_size From c498361d66f7073dceb17ecf60686bef28f8fc0f Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Fri, 27 Dec 2024 17:57:06 -0800 Subject: [PATCH 06/20] Use customized rope Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 83d8aefd08..8d7f76aef5 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -56,6 +56,14 @@ ) from transformers.utils.import_utils import is_torch_fx_available +try: + from habana_frameworks.torch.hpex.kernels import RotaryPosEmbeddingHelperV2 as FusedRoPE + + has_fused_rope = True +except ImportError: + has_fused_rope = False + print("Not using HPU fused kernel for apply_rotary_pos_emb") + try: from habana_frameworks.torch.hpex.normalization import FusedRMSNorm as FusedRMSNorm @@ -445,7 +453,7 @@ def forward( ) kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models @@ -551,7 +559,7 @@ def forward( rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1 cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len) - query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids) use_sliding_windows = ( _flash_supports_window_size @@ -866,7 +874,7 @@ def forward( kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models @@ -2045,3 +2053,25 @@ def forward( hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) + +# Copied from optimum.habana.transformers.models.llama.modeling_llama:apply_customized_rope() +def apply_customized_rope(q, k, cos, sin, position_ids): + if q.device.type == "hpu" and has_fused_rope: + # TODO: remove `.clone()` when it is fixed in SynapseAI + if k.dtype == torch.bfloat16: + return FusedRoPE.apply( + q, cos.unsqueeze(0).unsqueeze(0).clone(), sin.unsqueeze(0).unsqueeze(0).clone(), position_ids + ), FusedRoPE.apply( + k, + cos.unsqueeze(0).unsqueeze(0).clone().to(torch.bfloat16), + sin.unsqueeze(0).unsqueeze(0).clone().to(torch.bfloat16), + position_ids, + ) + return FusedRoPE.apply( + q, cos.unsqueeze(0).unsqueeze(0).clone(), sin.unsqueeze(0).unsqueeze(0).clone(), position_ids + ), FusedRoPE.apply( + k, cos.unsqueeze(0).unsqueeze(0).clone(), sin.unsqueeze(0).unsqueeze(0).clone(), position_ids + ) + else: + # keep the same implementation as Transformers v4.37.2 + return apply_rotary_pos_emb(q, k, cos[position_ids], sin[position_ids]) From 4826e79e145f2a4dafd6c99dbba32af05b7e6383 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 30 Dec 2024 12:42:54 -0800 Subject: [PATCH 07/20] Better try imports, unified RoPE implementation Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 60 +++++++++---------- 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 8d7f76aef5..35ae72934b 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -17,7 +17,12 @@ # 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 Arctic model. Copied from https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d.""" +"""PyTorch Arctic model. Adapted from https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d. + +Changes made: +- Use HPU FusedRoPE implementation +- Use HPU FusedRMSNorm implementation +""" import copy import inspect @@ -56,23 +61,26 @@ ) from transformers.utils.import_utils import is_torch_fx_available +from .configuration_arctic import ArcticConfig +from ..modeling_all_models import KVCache, apply_customized_rope_module + try: from habana_frameworks.torch.hpex.kernels import RotaryPosEmbeddingHelperV2 as FusedRoPE - - has_fused_rope = True except ImportError: - has_fused_rope = False print("Not using HPU fused kernel for apply_rotary_pos_emb") + FusedRoPE = None try: - from habana_frameworks.torch.hpex.normalization import FusedRMSNorm as FusedRMSNorm - - has_fused_rms_norm = True + from habana_frameworks.torch.hpex.normalization import FusedRMSNorm except ImportError: - has_fused_rms_norm = False print("Not using HPU fused kernel for RMSNorm") + FusedRMSNorm = None -from .configuration_arctic import ArcticConfig +try: + from habana_frameworks.torch.hpex.kernels import FusedSDPA +except ImportError: + print("Not using HPU fused scaled dot-product attention kernel.") + FusedSDPA = None if is_deepspeed_available(): @@ -228,11 +236,13 @@ def forward(self, hidden_states): Modifications copied from ../llama/modeling_llama.py:gaudi_llama_rmsnorm_forward() """ - if hidden_states.device.type == "hpu" and has_fused_rms_norm: + if hidden_states.device.type == "hpu" and FusedRMSNorm: # mixed dtypes are not good for FusedRMSNorm, both inputs need to have same dtype if hidden_states.dtype != self.weight.dtype: orig_dtype = hidden_states.dtype - hidden_states = FusedRMSNorm.apply(hidden_states.to(self.weight.dtype), self.weight, self.variance_epsilon) + hidden_states = FusedRMSNorm.apply( + hidden_states.to(self.weight.dtype), self.weight, self.variance_epsilon + ) return hidden_states.to(orig_dtype) else: hidden_states = FusedRMSNorm.apply(hidden_states, self.weight, self.variance_epsilon) @@ -453,7 +463,7 @@ def forward( ) kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids) + query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.training) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models @@ -559,7 +569,7 @@ def forward( rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1 cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len) - query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids) + query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.training) use_sliding_windows = ( _flash_supports_window_size @@ -874,7 +884,7 @@ def forward( kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids) + query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.trainig) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models @@ -2055,23 +2065,9 @@ def forward( ) # Copied from optimum.habana.transformers.models.llama.modeling_llama:apply_customized_rope() -def apply_customized_rope(q, k, cos, sin, position_ids): - if q.device.type == "hpu" and has_fused_rope: - # TODO: remove `.clone()` when it is fixed in SynapseAI - if k.dtype == torch.bfloat16: - return FusedRoPE.apply( - q, cos.unsqueeze(0).unsqueeze(0).clone(), sin.unsqueeze(0).unsqueeze(0).clone(), position_ids - ), FusedRoPE.apply( - k, - cos.unsqueeze(0).unsqueeze(0).clone().to(torch.bfloat16), - sin.unsqueeze(0).unsqueeze(0).clone().to(torch.bfloat16), - position_ids, - ) - return FusedRoPE.apply( - q, cos.unsqueeze(0).unsqueeze(0).clone(), sin.unsqueeze(0).unsqueeze(0).clone(), position_ids - ), FusedRoPE.apply( - k, cos.unsqueeze(0).unsqueeze(0).clone(), sin.unsqueeze(0).unsqueeze(0).clone(), position_ids - ) +def apply_customized_rope(q, k, cos, sin, position_ids, training=True): + if q.device.type == "hpu" and FusedRoPE: + return apply_customized_rope_module(q, k, cos, sin, position_ids, training) else: # keep the same implementation as Transformers v4.37.2 - return apply_rotary_pos_emb(q, k, cos[position_ids], sin[position_ids]) + return apply_rotary_pos_emb(q, k, cos[position_ids], sin[position_ids], position_ids) From 642999ba4776ede8ea6320bbe6c29e8e1bfdbd3b Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 30 Dec 2024 13:08:14 -0800 Subject: [PATCH 08/20] Fix typo Signed-off-by: Daniel Huang --- optimum/habana/transformers/models/snowflake/modeling_arctic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 35ae72934b..60151453a0 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -884,7 +884,7 @@ def forward( kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.trainig) + query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.training) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models From 053746a3d7a81dfbc6202936935dd811905247a3 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Tue, 31 Dec 2024 14:54:04 -0800 Subject: [PATCH 09/20] Added mark step after decoder layers Signed-off-by: Daniel Huang --- optimum/habana/transformers/models/snowflake/modeling_arctic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 60151453a0..9b408805df 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -1518,6 +1518,7 @@ def forward( all_self_attns += (layer_outputs[1],) all_router_losses += (layer_outputs[-1],) + htcore.mark_step() hidden_states = self.norm(hidden_states) # add hidden states from the last decoder layer From a18264c9e6e93e046f772f7b8bd3e9cb060d2926 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Thu, 2 Jan 2025 16:50:54 -0800 Subject: [PATCH 10/20] Using gaudi mixtral MOE impl Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 65 +++++++++---------- 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 9b408805df..38b130f5b2 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -1057,59 +1057,56 @@ def __init__(self, config: ArcticConfig, layer_id: int, **kwargs): # Similar in behavior to transformers.models.mixtral.modeling_mixtral.MixtralSparseMoeBlock.forward but more efficient. def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: + """ + Copied from ../mixtral/modeling_mixtral.py gaudi_mixtral_block_sparse_moe_forward + """ batch_size, sequence_length, hidden_dim = hidden_states.shape hidden_states = hidden_states.view(-1, hidden_dim) # router_logits: (batch * sequence_length, n_experts) router_logits = self.gate(hidden_states) + if is_deepspeed_available() and (not self.training): + from deepspeed import comm as dist + + if dist.is_initialized(): + output_tensors = [router_logits.clone() for _ in range(dist.get_world_size())] + dist.all_gather(output_tensors, router_logits) + router_logits = torch.cat(output_tensors, dim=1) + routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1) if self.top_k > 1: routing_weights /= routing_weights.sum(dim=-1, keepdim=True) # we cast back to the input dtype + routing_weights = routing_weights.to(hidden_states.dtype) final_hidden_states = torch.zeros( - (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device + (batch_size, sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device ) - # Matching between experts, tokens, and their top-k rank. For every i, - # expert_idx[i] is the rank topk_idx[i] expert for token_idx[i]. - expert_idx, token_idx, topk_idx = torch.where( - selected_experts - == torch.arange( - self.num_experts, - device=selected_experts.device, - ).view((self.num_experts, 1, 1)) + padded_weights = torch.zeros( + (batch_size * sequence_length, self.num_experts), dtype=hidden_states.dtype, device=hidden_states.device ) - - # Split into one chunk per expert. - bincount = torch.bincount(expert_idx, minlength=self.num_experts).tolist() - token_idx = token_idx.split(bincount) - topk_idx = topk_idx.split(bincount) + padded_weights.scatter_(-1, selected_experts, routing_weights) + padded_weights = padded_weights.reshape(-1, sequence_length, self.num_experts) + padded_weights = padded_weights.permute(2, 0, 1).unsqueeze(-1) # Loop over all available experts in the model and perform the computation on each expert - for expert_layer, top_x, idx in zip(self.experts, token_idx, topk_idx): - if top_x.shape[0] == 0: - continue - - # in torch it is faster to index using lists than torch tensors - top_x_list = top_x.tolist() - idx_list = idx.tolist() - - # Index the correct hidden states and compute the expert hidden state for - # the current expert. We need to make sure to multiply the output hidden - # states by `routing_weights` on the corresponding tokens (top-1 and top-2) - current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim) - current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None] - - # However `index_add_` only support torch tensors for indexing so we'll use - # the `top_x` tensor here. - final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype)) - # torch.distributed.barrier() - final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim) + for expert_idx in range(self.num_experts): + expert_layer = self.experts[expert_idx] + padded_weight = padded_weights[expert_idx] + current_state_static = hidden_states.reshape(-1, hidden_dim) + current_hidden_states_static = ( + expert_layer(current_state_static).reshape(-1, sequence_length, hidden_dim) * padded_weight + ) + final_hidden_states += current_hidden_states_static + # support long sequences exceeding 8192 + if not self.training and sequence_length > 8192: + htcore.mark_step() + return final_hidden_states, load_balancing_loss_func( (router_logits,), self.num_experts, self.top_k - ) # ZY: let's directly output the loss to align what we have in ds + ) def forward(self, hidden_states: torch.Tensor): if self.is_moe_layer: From 6888ee9fd7f8e6c820d4f4e61eeae6ffefa0cf46 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 6 Jan 2025 16:38:21 -0800 Subject: [PATCH 11/20] Changed to gaudi repeat_kv and rope impls Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 85 +++++++++++++++---- 1 file changed, 68 insertions(+), 17 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 38b130f5b2..7a2922cb16 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -22,6 +22,7 @@ Changes made: - Use HPU FusedRoPE implementation - Use HPU FusedRMSNorm implementation +- Added mark steps """ import copy @@ -61,9 +62,16 @@ ) from transformers.utils.import_utils import is_torch_fx_available +from ..llama.modeling_llama import ( + GaudiLlamaDynamicNTKScalingRotaryEmbedding, + GaudiLlamaLinearScalingRotaryEmbedding, + GaudiLlamaRotaryEmbedding, +) from .configuration_arctic import ArcticConfig from ..modeling_all_models import KVCache, apply_customized_rope_module +import habana_frameworks.torch.core as htcore + try: from habana_frameworks.torch.hpex.kernels import RotaryPosEmbeddingHelperV2 as FusedRoPE except ImportError: @@ -329,17 +337,33 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): return q_embed, k_embed -# Copied from transformers.models.llama.modeling_llama.repeat_kv +# Copied from ../llama/modeling_llama.py gaudi_llama_repeat_kv() 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) + Copied from repeat_kv: https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py + The only differences are: + - Append num_key_value_heads == 1 check as kv states can be broadcasted during matmuls so need to expand and reshape them. + - Add new args query_states, key_states, value_states and attention_mask and update the logic for expansion. + The query states go from (batch, num_heads, seqlen, head_dim) to (batch, num_key_value_heads, n_rep, seqlen, head_dim) + The key/value states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_key_value_heads, 1, 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) + batch, num_key_value_heads, kv_len, head_dim = key_states.shape + if n_rep == 1 or num_key_value_heads == 1: + return query_states, key_states, value_states, attention_mask + + new_kv_shape = (batch, num_key_value_heads, 1, kv_len, head_dim) + key_states = key_states.reshape(new_kv_shape) + value_states = value_states.reshape(new_kv_shape) + + batch, _, q_len, head_dim = query_states.shape + new_q_shape = (batch, num_key_value_heads, n_rep, q_len, head_dim) + query_states = query_states.reshape(new_q_shape) + + if attention_mask is not None: + # Add groups dim and set to 1 + attention_mask = attention_mask.unsqueeze(1) + + return query_states, key_states, value_states, attention_mask # Copied from transformers.models.mistral.modeling_mistral.MistralAttention with Mistral->Arctic @@ -420,11 +444,37 @@ def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwar dtype=torch.bfloat16, ) - self.rotary_emb = ArcticRotaryEmbedding( - self.head_dim, - max_position_embeddings=self.max_position_embeddings, - base=self.rope_theta, - ) + self._init_rope() + + def _init_rope(self): + """ + Copied from: https://github.com/huggingface/transformers/blob/v4.38.2/src/transformers/models/llama/modeling_llama.py#L294 + """ + if self.config.rope_scaling is None: + self.rotary_emb = GaudiLlamaRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + base=self.rope_theta, + ) + else: + scaling_type = self.config.rope_scaling["type"] + scaling_factor = self.config.rope_scaling["factor"] + if scaling_type == "linear": + self.rotary_emb = GaudiLlamaLinearScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + elif scaling_type == "dynamic": + self.rotary_emb = GaudiLlamaDynamicNTKScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + else: + raise ValueError(f"Unknown RoPE scaling type {scaling_type}") def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() @@ -470,8 +520,9 @@ def forward( key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) # repeat k/v heads if n_kv_heads < n_heads - key_states = repeat_kv(key_states, self.num_key_value_groups) - value_states = repeat_kv(value_states, self.num_key_value_groups) + query_states, key_states, value_states, attention_mask = repeat_kv( + query_states, key_states, value_states, attention_mask, self.num_key_value_groups + ) attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) @@ -505,7 +556,7 @@ def forward( attn_output = self.o_proj(attn_output) - if not output_attentions: + if not output_attentions or FusedSDPA: attn_weights = None return attn_output, attn_weights, past_key_value @@ -1125,7 +1176,7 @@ def __init__(self, config: ArcticConfig, layer_idx: int, **kwargs): super().__init__() self.layer_idx = layer_idx self.hidden_size = config.hidden_size - self.self_attn = MIXTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx, **kwargs) + self.self_attn = ArcticAttention(config, layer_idx, **kwargs) self.block_sparse_moe = ArcticMoE(config, layer_id=layer_idx, **kwargs) self.input_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) From ec975dbe1779c9ee81e024fdce4d899e92cfc5e6 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 6 Jan 2025 16:41:02 -0800 Subject: [PATCH 12/20] Add missing rope scaling to config Signed-off-by: Daniel Huang --- optimum/habana/transformers/models/snowflake/modeling_arctic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 7a2922cb16..0eeb90d166 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -375,6 +375,7 @@ class ArcticAttention(nn.Module): def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwargs): super().__init__() + config.rope_scaling = getattr(config, "rope_scaling", None) self.config = config self.layer_idx = layer_idx if layer_idx is None: From 0709774e9388d52d19fd646c3c6c4526ca16ffde Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 6 Jan 2025 16:48:57 -0800 Subject: [PATCH 13/20] Fix repeat_kv signature Signed-off-by: Daniel Huang --- .../transformers/models/snowflake/modeling_arctic.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 0eeb90d166..25818cbf94 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -338,7 +338,13 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): # Copied from ../llama/modeling_llama.py gaudi_llama_repeat_kv() -def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: +def repeat_kv( + query_states: torch.Tensor, + key_states: torch.Tensor, + value_states: torch.Tensor, + attention_mask: torch.Tensor, + n_rep: int, +): """ Copied from repeat_kv: https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py The only differences are: From 6b5069656e1ee223575af449806e80d5b2f5c2ea Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Tue, 7 Jan 2025 02:08:29 +0000 Subject: [PATCH 14/20] Revert "Using gaudi mixtral MOE impl" This reverts commit 9c390e7ab91ef20bdca258cbeca1cd47210f0d6f. --- .../models/snowflake/modeling_arctic.py | 65 ++++++++++--------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 25818cbf94..16533f250f 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -1115,56 +1115,59 @@ def __init__(self, config: ArcticConfig, layer_id: int, **kwargs): # Similar in behavior to transformers.models.mixtral.modeling_mixtral.MixtralSparseMoeBlock.forward but more efficient. def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: - """ - Copied from ../mixtral/modeling_mixtral.py gaudi_mixtral_block_sparse_moe_forward - """ batch_size, sequence_length, hidden_dim = hidden_states.shape hidden_states = hidden_states.view(-1, hidden_dim) # router_logits: (batch * sequence_length, n_experts) router_logits = self.gate(hidden_states) - if is_deepspeed_available() and (not self.training): - from deepspeed import comm as dist - - if dist.is_initialized(): - output_tensors = [router_logits.clone() for _ in range(dist.get_world_size())] - dist.all_gather(output_tensors, router_logits) - router_logits = torch.cat(output_tensors, dim=1) - routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1) if self.top_k > 1: routing_weights /= routing_weights.sum(dim=-1, keepdim=True) # we cast back to the input dtype - routing_weights = routing_weights.to(hidden_states.dtype) final_hidden_states = torch.zeros( - (batch_size, sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device + (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device ) - padded_weights = torch.zeros( - (batch_size * sequence_length, self.num_experts), dtype=hidden_states.dtype, device=hidden_states.device + # Matching between experts, tokens, and their top-k rank. For every i, + # expert_idx[i] is the rank topk_idx[i] expert for token_idx[i]. + expert_idx, token_idx, topk_idx = torch.where( + selected_experts + == torch.arange( + self.num_experts, + device=selected_experts.device, + ).view((self.num_experts, 1, 1)) ) - padded_weights.scatter_(-1, selected_experts, routing_weights) - padded_weights = padded_weights.reshape(-1, sequence_length, self.num_experts) - padded_weights = padded_weights.permute(2, 0, 1).unsqueeze(-1) - # Loop over all available experts in the model and perform the computation on each expert - for expert_idx in range(self.num_experts): - expert_layer = self.experts[expert_idx] - padded_weight = padded_weights[expert_idx] - current_state_static = hidden_states.reshape(-1, hidden_dim) - current_hidden_states_static = ( - expert_layer(current_state_static).reshape(-1, sequence_length, hidden_dim) * padded_weight - ) - final_hidden_states += current_hidden_states_static - # support long sequences exceeding 8192 - if not self.training and sequence_length > 8192: - htcore.mark_step() + # Split into one chunk per expert. + bincount = torch.bincount(expert_idx, minlength=self.num_experts).tolist() + token_idx = token_idx.split(bincount) + topk_idx = topk_idx.split(bincount) + # Loop over all available experts in the model and perform the computation on each expert + for expert_layer, top_x, idx in zip(self.experts, token_idx, topk_idx): + if top_x.shape[0] == 0: + continue + + # in torch it is faster to index using lists than torch tensors + top_x_list = top_x.tolist() + idx_list = idx.tolist() + + # Index the correct hidden states and compute the expert hidden state for + # the current expert. We need to make sure to multiply the output hidden + # states by `routing_weights` on the corresponding tokens (top-1 and top-2) + current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim) + current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None] + + # However `index_add_` only support torch tensors for indexing so we'll use + # the `top_x` tensor here. + final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype)) + # torch.distributed.barrier() + final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim) return final_hidden_states, load_balancing_loss_func( (router_logits,), self.num_experts, self.top_k - ) + ) # ZY: let's directly output the loss to align what we have in ds def forward(self, hidden_states: torch.Tensor): if self.is_moe_layer: From 0561e49f03922a80a63d7be027e8b181919b4e82 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 6 Jan 2025 21:35:35 -0800 Subject: [PATCH 15/20] Remove other attention impls Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 390 ------------------ 1 file changed, 390 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 16533f250f..1472e3952e 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -569,301 +569,6 @@ def forward( return attn_output, attn_weights, past_key_value -# Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Arctic -class ArcticFlashAttention2(ArcticAttention): - """ - Arctic flash attention module. This module inherits from `ArcticAttention` as the weights of the module stays - untouched. The only required change would be on the forward pass where it needs to correctly call the public API of - flash attention and deal with padding tokens in case the input contains any of them. - """ - - # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__ - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. - # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. - # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). - self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() - - 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: bool = False, - use_cache: bool = False, - **kwargs, - ): - if "padding_mask" in kwargs: - warnings.warn( - "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" - ) - - # overwrite attention_mask with padding_mask - attention_mask = kwargs.pop("padding_mask") - bsz, q_len, _ = hidden_states.size() - - query_states = self.q_proj(hidden_states) - key_states = self.k_proj(hidden_states) - value_states = self.v_proj(hidden_states) - - query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) - key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) - value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) - - kv_seq_len = key_states.shape[-2] - if past_key_value is not None: - if self.layer_idx is None: - raise ValueError( - f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " - "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " - "with a layer index." - ) - kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) - - # Because the input can be padded, the absolute sequence length depends on the max position id. - rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1 - cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len) - - query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.training) - - use_sliding_windows = ( - _flash_supports_window_size - and getattr(self.config, "sliding_window", None) is not None - and kv_seq_len > self.config.sliding_window - ) - - if not _flash_supports_window_size: - logger.warning_once( - "The current flash attention version does not support sliding window attention, for a more memory efficient implementation" - " make sure to upgrade flash-attn library." - ) - - if past_key_value is not None: - # Activate slicing cache only if the config has a value `sliding_windows` attribute - cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0 - if ( - getattr(self.config, "sliding_window", None) is not None - and kv_seq_len > self.config.sliding_window - and cache_has_contents - ): - slicing_tokens = 1 - self.config.sliding_window - - past_key = past_key_value[self.layer_idx][0] - past_value = past_key_value[self.layer_idx][1] - - past_key = past_key[:, :, slicing_tokens:, :].contiguous() - past_value = past_value[:, :, slicing_tokens:, :].contiguous() - - if past_key.shape[-2] != self.config.sliding_window - 1: - raise ValueError( - f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got" - f" {past_key.shape}" - ) - - if attention_mask is not None: - attention_mask = attention_mask[:, slicing_tokens:] - attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1) - - cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models - key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) - - # repeat k/v heads if n_kv_heads < n_heads - key_states = repeat_kv(key_states, self.num_key_value_groups) - value_states = repeat_kv(value_states, self.num_key_value_groups) - dropout_rate = 0.0 if not self.training else self.attention_dropout - - # In PEFT, usually we cast the layer norms in float32 for training stability reasons - # therefore the input hidden states gets silently casted in float32. Hence, we need - # cast them back in float16 just to be sure everything works as expected. - input_dtype = query_states.dtype - if input_dtype == torch.float32: - if torch.is_autocast_enabled(): - target_dtype = torch.get_autocast_gpu_dtype() - # Handle the case where the model is quantized - elif hasattr(self.config, "_pre_quantization_dtype"): - target_dtype = self.config._pre_quantization_dtype - else: - target_dtype = self.q_proj.weight.dtype - - logger.warning_once( - f"The input hidden states seems to be silently casted in float32, this might be related to" - f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" - f" {target_dtype}." - ) - - query_states = query_states.to(target_dtype) - key_states = key_states.to(target_dtype) - value_states = value_states.to(target_dtype) - - # Reashape to the expected shape for Flash Attention - query_states = query_states.transpose(1, 2) - key_states = key_states.transpose(1, 2) - value_states = value_states.transpose(1, 2) - - attn_output = self._flash_attention_forward( - query_states, - key_states, - value_states, - attention_mask, - q_len, - dropout=dropout_rate, - use_sliding_windows=use_sliding_windows, - ) - - attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() - attn_output = self.o_proj(attn_output) - - if not output_attentions: - attn_weights = None - - return attn_output, attn_weights, past_key_value - - def _flash_attention_forward( - self, - query_states, - key_states, - value_states, - attention_mask, - query_length, - dropout=0.0, - softmax_scale=None, - use_sliding_windows=False, - ): - """ - Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token - first unpad the input, then computes the attention scores and pad the final attention scores. - - Args: - query_states (`torch.Tensor`): - Input query states to be passed to Flash Attention API - key_states (`torch.Tensor`): - Input key states to be passed to Flash Attention API - value_states (`torch.Tensor`): - Input value states to be passed to Flash Attention API - attention_mask (`torch.Tensor`): - The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the - position of padding tokens and 1 for the position of non-padding tokens. - dropout (`int`, *optional*): - Attention dropout - softmax_scale (`float`, *optional*): - The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) - use_sliding_windows (`bool`, *optional*): - Whether to activate sliding window attention. - """ - if not self._flash_attn_uses_top_left_mask: - causal = self.is_causal - else: - # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__. - causal = self.is_causal and query_length != 1 - - # Contains at least one padding token in the sequence - if attention_mask is not None: - batch_size = query_states.shape[0] - query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( - query_states, key_states, value_states, attention_mask, query_length - ) - - cu_seqlens_q, cu_seqlens_k = cu_seq_lens - max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens - - if not use_sliding_windows: - attn_output_unpad = flash_attn_varlen_func( - query_states, - key_states, - value_states, - cu_seqlens_q=cu_seqlens_q, - cu_seqlens_k=cu_seqlens_k, - max_seqlen_q=max_seqlen_in_batch_q, - max_seqlen_k=max_seqlen_in_batch_k, - dropout_p=dropout, - softmax_scale=softmax_scale, - causal=causal, - ) - else: - attn_output_unpad = flash_attn_varlen_func( - query_states, - key_states, - value_states, - cu_seqlens_q=cu_seqlens_q, - cu_seqlens_k=cu_seqlens_k, - max_seqlen_q=max_seqlen_in_batch_q, - max_seqlen_k=max_seqlen_in_batch_k, - dropout_p=dropout, - softmax_scale=softmax_scale, - causal=causal, - window_size=(self.config.sliding_window, self.config.sliding_window), - ) - - attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) - else: - if not use_sliding_windows: - attn_output = flash_attn_func( - query_states, - key_states, - value_states, - dropout, - softmax_scale=softmax_scale, - causal=causal, - ) - else: - attn_output = flash_attn_func( - query_states, - key_states, - value_states, - dropout, - softmax_scale=softmax_scale, - causal=causal, - window_size=(self.config.sliding_window, self.config.sliding_window), - ) - - return attn_output - - def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): - batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape - - # On the first iteration we need to properly re-create the padding mask - # by slicing it on the proper place - if kv_seq_len != attention_mask.shape[-1]: - attention_mask_num_tokens = attention_mask.shape[-1] - attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :] - - indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) - - key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k) - value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k) - - if query_length == kv_seq_len: - query_layer = index_first_axis( - query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k - ) - cu_seqlens_q = cu_seqlens_k - max_seqlen_in_batch_q = max_seqlen_in_batch_k - indices_q = indices_k - elif query_length == 1: - max_seqlen_in_batch_q = 1 - cu_seqlens_q = torch.arange( - batch_size + 1, dtype=torch.int32, device=query_layer.device - ) # There is a memcpy here, that is very bad. - indices_q = cu_seqlens_q[:-1] - query_layer = query_layer.squeeze(1) - else: - # The -q_len: slice assumes left padding. - attention_mask = attention_mask[:, -query_length:] - query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) - - return ( - query_layer, - key_layer, - value_layer, - indices_q, - (cu_seqlens_q, cu_seqlens_k), - (max_seqlen_in_batch_q, max_seqlen_in_batch_k), - ) - - def get_arctic_linear( input_dim, output_dim, @@ -894,101 +599,6 @@ def get_arctic_linear( return nn.Linear(input_dim, output_dim, bias=bias, dtype=dtype) -# Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Arctic -class ArcticSdpaAttention(ArcticAttention): - """ - Arctic attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from - `ArcticAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to - SDPA API. - """ - - # Adapted from ArcticAttention.forward - 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: bool = False, - use_cache: bool = False, - ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: - if output_attentions: - # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented. - logger.warning_once( - "ArcticModel is using ArcticSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, " - 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' - ) - return super().forward( - 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, - ) - - bsz, q_len, _ = hidden_states.size() - - query_states = self.q_proj(hidden_states) - key_states = self.k_proj(hidden_states) - value_states = self.v_proj(hidden_states) - - query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) - key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) - value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) - - kv_seq_len = key_states.shape[-2] - if past_key_value is not None: - kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) - cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - - query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.training) - - if past_key_value is not None: - cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models - key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) - - key_states = repeat_kv(key_states, self.num_key_value_groups) - value_states = repeat_kv(value_states, self.num_key_value_groups) - - if attention_mask is not None: - if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): - raise ValueError( - f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" - ) - - # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, - # Reference: https://github.com/pytorch/pytorch/issues/112577. - if query_states.device.type == "cuda" and attention_mask is not None: - query_states = query_states.contiguous() - key_states = key_states.contiguous() - value_states = value_states.contiguous() - - attn_output = torch.nn.functional.scaled_dot_product_attention( - query_states, - key_states, - value_states, - attn_mask=attention_mask, - dropout_p=self.attention_dropout if self.training else 0.0, - # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1. - is_causal=self.is_causal and attention_mask is None and q_len > 1, - ) - - attn_output = attn_output.transpose(1, 2).contiguous() - attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) - - attn_output = self.o_proj(attn_output) - - return attn_output, None, past_key_value - - -MIXTRAL_ATTENTION_CLASSES = { - "eager": ArcticAttention, - "flash_attention_2": ArcticFlashAttention2, - "sdpa": ArcticSdpaAttention, -} - - class ArcticMLP(nn.Module): def __init__( self, From 32ab5f704fdad471c53f50b8e0e4d323ded90712 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Mon, 6 Jan 2025 21:55:35 -0800 Subject: [PATCH 16/20] Add initial KV cache support Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 1472e3952e..3cf0361ef9 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -486,6 +486,15 @@ def _init_rope(self): def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + def allocate_kv_cache(self, batch_size, max_seq_len, inp_seq_len): + """ + Allocate KV cache. Copied from ../mixtral/modeling_mixtral.py GaudiMixtralAttention.allocate_kv_cache + """ + cache_shape = (batch_size, self.num_key_value_heads, max_seq_len, self.head_dim) + device = self.k_proj.weight.device + dtype = self.config.torch_dtype + self.k_cache.allocate(inp_seq_len, dtype, device, cache_shape) + self.v_cache.allocate(inp_seq_len, dtype, device, cache_shape) def forward( self, hidden_states: torch.Tensor, @@ -494,6 +503,10 @@ def forward( past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, + token_idx: Optional[torch.Tensor] = None, + reuse_cache: Optional[bool] = False, + flash_attention_recompute: Optional[bool] = False, + cache_idx: Optional[int] = None, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: if "padding_mask" in kwargs: @@ -518,7 +531,16 @@ def forward( "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " "with a layer index." ) - kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + if token_idx is None: + if hasattr(past_key_value, "get_usable_length"): + kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + else: + kv_seq_len += past_key_value[0].shape[-2] + else: + if reuse_cache: + kv_seq_len = past_key_value[0][-2] + else: + kv_seq_len = past_key_value[0].shape[-2] cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.training) @@ -818,6 +840,9 @@ def __init__(self, config: ArcticConfig, layer_idx: int, **kwargs): shard_base_weights_if_doing_lora=True, ) # for the residual layer. always shard the base weight if doing deepspeed lora. + def allocate_kv_cache(self, batch_size, max_seq_len, inp_seq_len): + self.self_attn.allocate_kv_cache(batch_size, max_seq_len, inp_seq_len) + def forward( self, hidden_states: torch.Tensor, @@ -1043,6 +1068,10 @@ def __init__(self, config: ArcticConfig, **kwargs): # Initialize weights and apply final processing self.post_init() + def allocate_kv_cache(self, batch_size, max_seq_len, inp_seq_len): + for layer in self.layers: + layer.allocate_kv_cache(batch_size, max_seq_len, inp_seq_len) + def get_input_embeddings(self): return self.embed_tokens @@ -1200,7 +1229,6 @@ def forward( if use_legacy_cache and hasattr(next_decoder_cache, "to_legacy_cache") else next_decoder_cache ) - torch.cuda.empty_cache() if not return_dict: return tuple( @@ -1245,6 +1273,10 @@ def __init__(self, config: ArcticConfig, **kwargs): # Initialize weights and apply final processing self.post_init() + def allocate_kv_cache(self, batch_size, max_seq_len, inp_seq_len): + self.model.allocate_kv_cache(batch_size, max_seq_len, inp_seq_len) + self.kv_cache_len = max_seq_len + def get_input_embeddings(self): return self.model.embed_tokens From b9f36d68eca39fb38ea26b664c3e1c2bc22fcd52 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Tue, 21 Jan 2025 10:57:15 -0800 Subject: [PATCH 17/20] Add fixed moe from mixtral Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 53 +++++++------------ 1 file changed, 19 insertions(+), 34 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index 3cf0361ef9..feed57f60e 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -754,48 +754,33 @@ def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1) - if self.top_k > 1: - routing_weights /= routing_weights.sum(dim=-1, keepdim=True) + routing_weights /= routing_weights.sum(dim=-1, keepdim=True) # we cast back to the input dtype + routing_weights = routing_weights.to(hidden_states.dtype) final_hidden_states = torch.zeros( - (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device + (batch_size, sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device ) - # Matching between experts, tokens, and their top-k rank. For every i, - # expert_idx[i] is the rank topk_idx[i] expert for token_idx[i]. - expert_idx, token_idx, topk_idx = torch.where( - selected_experts - == torch.arange( - self.num_experts, - device=selected_experts.device, - ).view((self.num_experts, 1, 1)) + padded_weights = torch.zeros( + (batch_size * sequence_length, self.num_experts), dtype=hidden_states.dtype, device=hidden_states.device ) - - # Split into one chunk per expert. - bincount = torch.bincount(expert_idx, minlength=self.num_experts).tolist() - token_idx = token_idx.split(bincount) - topk_idx = topk_idx.split(bincount) + padded_weights.scatter_(-1, selected_experts, routing_weights) + padded_weights = padded_weights.reshape(-1, sequence_length, self.num_experts) + padded_weights = padded_weights.permute(2, 0, 1).unsqueeze(-1) # Loop over all available experts in the model and perform the computation on each expert - for expert_layer, top_x, idx in zip(self.experts, token_idx, topk_idx): - if top_x.shape[0] == 0: - continue - - # in torch it is faster to index using lists than torch tensors - top_x_list = top_x.tolist() - idx_list = idx.tolist() - - # Index the correct hidden states and compute the expert hidden state for - # the current expert. We need to make sure to multiply the output hidden - # states by `routing_weights` on the corresponding tokens (top-1 and top-2) - current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim) - current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None] - - # However `index_add_` only support torch tensors for indexing so we'll use - # the `top_x` tensor here. - final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype)) - # torch.distributed.barrier() + for expert_idx in range(self.num_experts): + expert_layer = self.experts[expert_idx] + padded_weight = padded_weights[expert_idx] + current_state_static = hidden_states.reshape(-1, hidden_dim) + current_hidden_states_static = ( + expert_layer(current_state_static).reshape(-1, sequence_length, hidden_dim) * padded_weight + ) + final_hidden_states += current_hidden_states_static + # support long sequences exceeding 8192 + if not self.training and sequence_length > 8192: + htcore.mark_step() final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim) return final_hidden_states, load_balancing_loss_func( (router_logits,), self.num_experts, self.top_k From 5d63631520ebcc9cd12b58cb349845648c47d02e Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Thu, 23 Jan 2025 17:33:48 -0800 Subject: [PATCH 18/20] Integrate KV cache Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 511 +++++++++--------- 1 file changed, 269 insertions(+), 242 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index feed57f60e..e326a039e8 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -25,21 +25,21 @@ - Added mark steps """ -import copy +import contextlib import inspect import math import re import warnings from typing import List, Optional, Tuple, Union +import habana_frameworks.torch.core as htcore import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss -from transformers import GenerationMixin from transformers.activations import ACT2FN -from transformers.cache_utils import Cache, DynamicCache +from transformers.cache_utils import Cache from transformers.integrations.deepspeed import is_deepspeed_available from transformers.modeling_attn_mask_utils import ( _prepare_4d_causal_attention_mask, @@ -56,7 +56,6 @@ add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, - is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings, ) @@ -67,10 +66,10 @@ GaudiLlamaLinearScalingRotaryEmbedding, GaudiLlamaRotaryEmbedding, ) -from .configuration_arctic import ArcticConfig +from ..mixtral.modeling_mixtral import GaudiMixtralAttentionLongSequence from ..modeling_all_models import KVCache, apply_customized_rope_module +from .configuration_arctic import ArcticConfig -import habana_frameworks.torch.core as htcore try: from habana_frameworks.torch.hpex.kernels import RotaryPosEmbeddingHelperV2 as FusedRoPE @@ -90,20 +89,26 @@ print("Not using HPU fused scaled dot-product attention kernel.") FusedSDPA = None +try: + from habana_frameworks.torch.hpu import sdp_kernel + + SDPContext = True +except ImportError: + SDPContext = False if is_deepspeed_available(): from deepspeed.moe.layer import MoE # Note that below will crash if there is an available deepspeed that does not have ds_linear. try: - import deepspeed.linear as ds_linear + pass except Exception: pass else: MoE = None if is_flash_attn_2_available(): - from flash_attn import flash_attn_func, flash_attn_varlen_func + from flash_attn import flash_attn_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters) @@ -239,10 +244,7 @@ def __init__(self, hidden_size, eps=1e-6): def forward(self, hidden_states): """ - Modified from original ArcticRMS implementation: - - Use Habana fused RMSNorm - - Modifications copied from ../llama/modeling_llama.py:gaudi_llama_rmsnorm_forward() + Copied from optimum/habana/transformers/models/llama/modeling_llama.py gaudi_llama_rmsnorm_forward """ if hidden_states.device.type == "hpu" and FusedRMSNorm: # mixed dtypes are not good for FusedRMSNorm, both inputs need to have same dtype @@ -286,8 +288,8 @@ def _set_cos_sin_cache(self, seq_len, device, dtype): freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) - self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) - self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + self.register_buffer("_cos_cached", emb.cos().to(dtype), persistent=False) + self.register_buffer("_sin_cached", emb.sin().to(dtype), persistent=False) def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] @@ -295,8 +297,8 @@ def forward(self, x, seq_len=None): self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) return ( - self.cos_cached[:seq_len].to(dtype=x.dtype), - self.sin_cached[:seq_len].to(dtype=x.dtype), + self._cos_cached[:seq_len].to(dtype=x.dtype), + self._sin_cached[:seq_len].to(dtype=x.dtype), ) @@ -337,7 +339,7 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): return q_embed, k_embed -# Copied from ../llama/modeling_llama.py gaudi_llama_repeat_kv() +# Copied from optimum/habana/transformers/models/llama/modeling_llama.py gaudi_llama_repeat_kv() def repeat_kv( query_states: torch.Tensor, key_states: torch.Tensor, @@ -391,6 +393,11 @@ def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwar "when creating this class." ) + self.k_cache = KVCache() + self.v_cache = KVCache() + self.inp_seq_len = -1 + self.block_size = 1024 + self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.hidden_size // self.num_heads @@ -400,54 +407,34 @@ def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwar self.rope_theta = config.rope_theta self.is_causal = True self.attention_dropout = config.attention_dropout - self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] if (self.head_dim * self.num_heads) != self.hidden_size: raise ValueError( f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" f" and `num_heads`: {self.num_heads})." ) - deepspeed_lora_config = kwargs.get(DEEPSPEED_LORA_CONFIG) - quantization_config = kwargs.get(QUANTIZATION_CONFIG, None) - - self.q_proj = get_arctic_linear( + self.q_proj = nn.Linear( self.hidden_size, self.num_heads * self.head_dim, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, dtype=torch.bfloat16, ) - self.k_proj = get_arctic_linear( + self.k_proj = nn.Linear( self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, dtype=torch.bfloat16, ) - self.v_proj = get_arctic_linear( + self.v_proj = nn.Linear( self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, dtype=torch.bfloat16, ) - self.o_proj = get_arctic_linear( + self.o_proj = nn.Linear( self.hidden_size, self.hidden_size, bias=False, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_lora_config=deepspeed_lora_config, - ds_optimized_quantization_config=quantization_config, - ds_optimized_base_weight_sharding=True, dtype=torch.bfloat16, ) @@ -495,6 +482,7 @@ def allocate_kv_cache(self, batch_size, max_seq_len, inp_seq_len): dtype = self.config.torch_dtype self.k_cache.allocate(inp_seq_len, dtype, device, cache_shape) self.v_cache.allocate(inp_seq_len, dtype, device, cache_shape) + def forward( self, hidden_states: torch.Tensor, @@ -503,12 +491,28 @@ def forward( past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, token_idx: Optional[torch.Tensor] = None, reuse_cache: Optional[bool] = False, flash_attention_recompute: Optional[bool] = False, cache_idx: Optional[int] = None, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + """ + Adapted from ArcticAttention.forward: https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/be318cae5aba5291208f27d30991a5150500887d + + Referenece Gaudi implementation from ../mixtral/modeling_mixtral.py GaudiMixtralAttention + + Changes made: + - Added new args + - token_idx + - attn_softmax_bf16 + - reuse_cache + - flash_attention_recompute + - cache_idx + - Optimize KV cache + - Use FusedSDPA attention + """ if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" @@ -542,43 +546,91 @@ def forward( else: kv_seq_len = past_key_value[0].shape[-2] cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_customized_rope(query_states, key_states, cos, sin, position_ids, self.training) - - if past_key_value is not None: - cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models - key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) - - # repeat k/v heads if n_kv_heads < n_heads - query_states, key_states, value_states, attention_mask = repeat_kv( - query_states, key_states, value_states, attention_mask, self.num_key_value_groups + query_states, key_states = apply_customized_rope( + query_states, key_states, cos, sin, position_ids, self.training ) - attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + if use_cache: + if reuse_cache: + key_states = self.k_cache(key_states, 2, token_idx) + value_states = self.v_cache(value_states, 2, token_idx) + past_key_value = (self.k_cache.get_shape(), self.v_cache.get_shape()) + else: + if past_key_value is None: + past_key = torch.zeros(key_states.shape, dtype=self.k_proj.weight.dtype, device=key_states.device) + past_value = torch.zeros( + key_states.shape, dtype=self.k_proj.weight.dtype, device=key_states.device + ) + past_key_value = (past_key, past_value) + key_states = self.k_cache.update(past_key_value[0], key_states, 2, token_idx, self.inp_seq_len) + value_states = self.v_cache.update(past_key_value[1], value_states, 2, token_idx, self.inp_seq_len) + if token_idx is None: + past_key_value = (key_states, value_states) + + if cache_idx is not None and q_len == 1: + key_states = key_states[:, :, :cache_idx, :] + value_states = value_states[:, :, :cache_idx, :] + if attention_mask is not None: + attention_mask = attention_mask[:, :, :, :cache_idx] + kv_seq_len = key_states.shape[-2] + else: + past_key_value = None - if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): - raise ValueError( - f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" - f" {attn_weights.size()}" + if FusedSDPA: + if query_states.dtype != key_states.dtype: + key_states = key_states.type(query_states.dtype) + value_states = value_states.type(query_states.dtype) + # support long sequences exceeding 8192 + if not self.training and q_len == key_states.size(-2) and q_len > 8192: + htcore.mark_step() + attn_output = GaudiMixtralAttentionLongSequence.forward( + query_states, + key_states, + value_states, + attention_mask, + False, + self.block_size, + ) + htcore.mark_step() + else: + with ( + sdp_kernel(enable_recompute=flash_attention_recompute) if SDPContext else contextlib.nullcontext() + ): + attn_output = FusedSDPA.apply( + query_states, key_states, value_states, attention_mask, 0.0, False, None + ) + else: + # repeat k/v heads if n_kv_heads < n_heads + query_states, key_states, value_states, attention_mask = repeat_kv( + query_states, key_states, value_states, attention_mask, self.num_key_value_groups ) - if attention_mask is not None: - if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + + if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): raise ValueError( - f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" + f" {attn_weights.size()}" ) - attn_weights = attn_weights + attention_mask + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) - # upcast attention to fp32 - attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) - attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) - attn_output = torch.matmul(attn_weights, value_states) + attn_weights = attn_weights + attention_mask - if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): - raise ValueError( - f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" - f" {attn_output.size()}" - ) + # upcast attention to fp32 + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) @@ -591,44 +643,10 @@ def forward( return attn_output, attn_weights, past_key_value -def get_arctic_linear( - input_dim, - output_dim, - bias=False, - use_deepspeed_implementation=False, - ds_optimized_lora_config=None, - ds_optimized_quantization_config=None, - ds_optimized_base_weight_sharding=False, - dtype=torch.bfloat16, -): - """Can return deepspeed optimized linear if available. - Args: - input_dim, output_dim, bias, dtype: self explanatory (same as from nn.Linear) - ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer. - ds_optimized_quantization_config: config of type ds_linear.QuantizationConfig. - ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus - in a tensor parallel way. - """ - if is_deepspeed_available(): - if ds_optimized_lora_config is not None: - ds_optimized_lora_config: ds_linear.LoRAConfig = copy.deepcopy(ds_optimized_lora_config) - ds_optimized_lora_config.base_weight_sharding = ( - torch.distributed.get_world_size() if ds_optimized_base_weight_sharding else 1 - ) - return ds_linear.OptimizedLinear( - input_dim, output_dim, bias, ds_optimized_lora_config, ds_optimized_quantization_config, dtype=dtype - ) - return nn.Linear(input_dim, output_dim, bias=bias, dtype=dtype) - - class ArcticMLP(nn.Module): def __init__( self, config: ArcticConfig, - use_deepspeed_implementation=False, - ds_optimized_lora_config=None, - ds_optimized_quantization_config=None, - shard_base_weights_if_doing_lora=False, is_residual_mlp=False, ): """MLP class for Arctic supporting vanilla linear layers as well as some deepspeed optimizations. @@ -642,34 +660,22 @@ def __init__( super(ArcticMLP, self).__init__() self.hidden_dim = config.hidden_size self.ffn_dim = config.intermediate_size if not is_residual_mlp else self.hidden_dim - self.w1 = get_arctic_linear( + self.w1 = nn.Linear( self.hidden_dim, self.ffn_dim, - False, - use_deepspeed_implementation=use_deepspeed_implementation, - ds_optimized_lora_config=ds_optimized_lora_config, - ds_optimized_quantization_config=ds_optimized_quantization_config, - ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + bias=False, dtype=torch.bfloat16, ) - self.w2 = get_arctic_linear( + self.w2 = nn.Linear( self.ffn_dim, self.hidden_dim, - False, - use_deepspeed_implementation=use_deepspeed_implementation, - ds_optimized_lora_config=ds_optimized_lora_config, - ds_optimized_quantization_config=ds_optimized_quantization_config, - ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + bias=False, dtype=torch.bfloat16, ) - self.w3 = get_arctic_linear( + self.w3 = nn.Linear( self.hidden_dim, self.ffn_dim, - False, - use_deepspeed_implementation=use_deepspeed_implementation, - ds_optimized_lora_config=ds_optimized_lora_config, - ds_optimized_quantization_config=ds_optimized_quantization_config, - ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora, + bias=False, dtype=torch.bfloat16, ) self.act_fn = ACT2FN[config.hidden_act] @@ -690,57 +696,12 @@ def __init__(self, config: ArcticConfig, layer_id: int, **kwargs): self.top_k = config.num_experts_per_tok self.is_moe_layer = (layer_id + 1) % config.moe_layer_frequency == 0 - self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] - if self.use_deepspeed_implementation and MoE is None: - raise ValueError("Deepspeed is not installed") - quantization_config = kwargs.get(QUANTIZATION_CONFIG, None) - deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) if not self.is_moe_layer: # dense, not MoE - self.mlp = ArcticMLP( - config, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_quantization_config=quantization_config, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=True, - ) + self.mlp = ArcticMLP(config) else: - if self.use_deepspeed_implementation: # DeepSpeed's MoE - moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1) - self.mlp = MoE( - self.hidden_dim, - # base weight sharding false for all deepspeed moe calls because it is already sharded - ArcticMLP( - config, - use_deepspeed_implementation=True, - ds_optimized_quantization_config=quantization_config, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=False, - ), - num_experts=config.num_local_experts, - ep_size=moe_expert_parallel_size, - k=config.num_experts_per_tok, - use_residual=False, - capacity_factor=config.moe_train_capacity_factor, - eval_capacity_factor=config.moe_eval_capacity_factor, - enable_expert_tensor_parallelism=config.enable_expert_tensor_parallelism, - min_capacity=config.moe_min_capacity, - drop_tokens=config.moe_token_dropping, - ) - else: - # "local" MoE implementation - self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False) - self.experts = nn.ModuleList( - [ - ArcticMLP( - config, - use_deepspeed_implementation=self.use_deepspeed_implementation, - ds_optimized_quantization_config=quantization_config, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=True, - ) - for i in range(self.num_experts) - ] - ) + # "local" MoE implementation + self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False) + self.experts = nn.ModuleList([ArcticMLP(config) for i in range(self.num_experts)]) # if torch.distributed.get_rank() == 0: # deepspeed.runtime.utils.see_memory_usage("", force=True) @@ -788,12 +749,7 @@ def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor: def forward(self, hidden_states: torch.Tensor): if self.is_moe_layer: - if self.use_deepspeed_implementation: - # deepspeed returns a tuple including output, gate loss, and expert count. - hidden_states, moe_loss, _ = self.mlp(hidden_states) - return hidden_states, moe_loss - else: - return self._moe_foreward(hidden_states) + return self._moe_foreward(hidden_states) else: return self.mlp(hidden_states), torch.tensor(0.0, device=hidden_states.device, dtype=hidden_states.dtype) @@ -807,22 +763,15 @@ def __init__(self, config: ArcticConfig, layer_idx: int, **kwargs): self.block_sparse_moe = ArcticMoE(config, layer_id=layer_idx, **kwargs) self.input_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) - self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG] self.parallel_attn_mlp_res = ( config.parallel_attn_mlp_res and self.block_sparse_moe.is_moe_layer ) # add residual only when it is moe layer - deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG) - deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) if self.parallel_attn_mlp_res: self.residual_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.residual_mlp = ArcticMLP( config, - use_deepspeed_implementation=self.use_deepspeed_implementation, is_residual_mlp=True, - ds_optimized_quantization_config=deepspeed_quantization, - ds_optimized_lora_config=deepspeed_lora, - shard_base_weights_if_doing_lora=True, ) # for the residual layer. always shard the base weight if doing deepspeed lora. def allocate_kv_cache(self, batch_size, max_seq_len, inp_seq_len): @@ -836,13 +785,22 @@ def forward( past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, + cache_position: Optional[torch.LongTensor] = None, + token_idx: Optional[torch.Tensor] = None, + reuse_cache: Optional[bool] = False, + flash_attention_recompute: Optional[bool] = False, + cache_idx: Optional[int] = None, **kwargs, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: - if "padding_mask" in kwargs: - warnings.warn( - "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" - ) """ + Modified from original Arctic forward + Changes: + - Add new arg cache_position + - Add new arg token_idx + - Add new arg reuse_cache + - Add new arg flash_attention_recompute + - Add new arg cache_idx + Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size @@ -856,6 +814,11 @@ def forward( (see `past_key_values`). """ + if "padding_mask" in kwargs: + warnings.warn( + "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" + ) + residual_input = hidden_states hidden_states = self.input_layernorm(hidden_states) @@ -868,6 +831,11 @@ def forward( past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, + cache_position=cache_position, + token_idx=token_idx, + reuse_cache=reuse_cache, + flash_attention_recompute=flash_attention_recompute, + cache_idx=cache_idx, ) hidden_states = residual_input + hidden_states @@ -1076,7 +1044,22 @@ def forward( output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + token_idx: Optional[torch.Tensor] = None, + reuse_cache: Optional[bool] = False, + flash_attention_recompute: Optional[bool] = False, + cache_idx: int = None, ) -> Union[Tuple, MoeModelOutputWithPast]: + """ + Modified from original Arctic forward + Changes: + - Add new arg cache_position + - Add new arg token_idx + - Add new arg reuse_cache + - Add new arg flash_attention_recompute + - Add new arg cache_idx + - Force legacy KV cache + """ 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 @@ -1104,11 +1087,12 @@ def forward( ) use_cache = False - if use_cache: - use_legacy_cache = not isinstance(past_key_values, Cache) - if use_legacy_cache: - past_key_values = DynamicCache.from_legacy_cache(past_key_values) - past_key_values_length = past_key_values.get_usable_length(seq_length) + # NOTE: Forcing legacy cache for HPU + if past_key_values is not None and use_cache: + if reuse_cache: + past_key_values_length = past_key_values[0][0][2] + else: + past_key_values_length = past_key_values[0][0].shape[2] if position_ids is None: device = input_ids.device if input_ids is not None else inputs_embeds.device @@ -1122,6 +1106,21 @@ def forward( if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) + if cache_position is None: + past_seen_tokens = 0 + if past_key_values is not None: + if isinstance(past_key_values, Cache): + past_seen_tokens = past_key_values.get_seq_length() + else: + past_seen_tokens = past_key_values[0][0].shape[2] + + 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) + if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache: is_padding_right = attention_mask[:, -1].sum().item() != batch_size if is_padding_right: @@ -1159,7 +1158,7 @@ def forward( all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None all_router_losses = () - next_decoder_cache = None + next_decoder_cache = () if use_cache else None for i, decoder_layer in enumerate(self.layers): if output_hidden_states: @@ -1174,27 +1173,27 @@ def forward( past_key_values, output_attentions, use_cache, + cache_position, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, - past_key_value=past_key_values, + past_key_value=None if past_key_values is None else past_key_values[i], output_attentions=output_attentions, use_cache=use_cache, + cache_position=cache_position, + token_idx=token_idx, + reuse_cache=reuse_cache, + flash_attention_recompute=flash_attention_recompute, + cache_idx=cache_idx, ) hidden_states = layer_outputs[0] if use_cache: - if hasattr(layer_outputs[2 if output_attentions else 1], "to_legacy_cache"): - next_decoder_cache = layer_outputs[2 if output_attentions else 1] - else: - if next_decoder_cache is None: - next_decoder_cache = [layer_outputs[2 if output_attentions else 1]] - else: - next_decoder_cache.append(layer_outputs[2 if output_attentions else 1]) + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) if output_attentions: all_self_attns += (layer_outputs[1],) @@ -1210,9 +1209,7 @@ def forward( next_cache = None if use_cache: next_cache = ( - next_decoder_cache.to_legacy_cache() - if use_legacy_cache and hasattr(next_decoder_cache, "to_legacy_cache") - else next_decoder_cache + next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache ) if not return_dict: @@ -1230,7 +1227,7 @@ def forward( ) -class ArcticForCausalLM(ArcticPreTrainedModel, GenerationMixin): +class ArcticForCausalLM(ArcticPreTrainedModel): # TODO(jeffra): update _keys_to_ignore_on_load_unexpected with expert keys not relevant for this rank _keys_to_ignore_on_load_unexpected = [ r"model\.layers\.\d+\.block_sparse_moe\.experts\.\d+\.w\d+\.weight" @@ -1374,9 +1371,9 @@ def _load_from_state_dict( world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1 # TODO(jeffra): currently assumes fine-tuning only on one node, fix for world_size != ep size if self.moe_expert_parallel_size > 1: - assert ( - self.moe_expert_parallel_size == world_size - ), f"currently only support expert parallel size equal to world size but {self.moe_expert_parallel_size=} and {world_size=}" + assert self.moe_expert_parallel_size == world_size, ( + f"currently only support expert parallel size equal to world size but {self.moe_expert_parallel_size=} and {world_size=}" + ) rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0 num_local_experts = self.num_experts // self.moe_expert_parallel_size @@ -1451,9 +1448,9 @@ def _load_from_state_dict( if "deepspeed_moe" in incoming_param_name: assert shape_local == shape_incoming, "deepspeed moe weights are never sharded" else: - assert ( - shape_incoming[1] == shape_local[1] * world_size - ), "weights should be sharded equally across world size" + assert shape_incoming[1] == shape_local[1] * world_size, ( + "weights should be sharded equally across world size" + ) incoming_param = incoming_param[:, rank * shape_local[1] : (rank + 1) * shape_local[1]] print(f"Deepspeed lora: {rank=}, renaming {incoming_param_name} -> {param_name}") state_dict[param_name] = incoming_param @@ -1478,8 +1475,20 @@ def forward( output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + token_idx: Optional[torch.Tensor] = None, + reuse_cache: Optional[bool] = None, + flash_attention_recompute: Optional[bool] = False, + cache_idx: int = None, ) -> Union[Tuple, MoeCausalLMOutputWithPast]: r""" + Modified from original. Only differences are: + - Add new arg cache_position + - Add new arg token_idx + - Add new arg reuse_cache + - Add new arg flash_attention_recompute + - Add new arg cache_idx + 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, ..., @@ -1523,6 +1532,11 @@ def forward( output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, + cache_position=cache_position, + token_idx=token_idx, + reuse_cache=reuse_cache, + flash_attention_recompute=flash_attention_recompute, + cache_idx=cache_idx, ) hidden_states = outputs[0] logits = self.lm_head(hidden_states) @@ -1561,58 +1575,70 @@ def forward( ) def prepare_inputs_for_generation( - self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + self, + input_ids, + past_key_values=None, + attention_mask=None, + inputs_embeds=None, + cache_position=None, + position_ids=None, + use_cache=True, + num_logits_to_keep=None, + **kwargs, ): + """ + Copied from GaudiMixtralForCausalLM in optimum/habana/transformers/models/mixtral/modeling_mixtral.py + """ + reuse_cache = kwargs.get("reuse_cache") + token_idx = kwargs.get("token_idx", None) + # Omit tokens covered by past_key_values if past_key_values is not None: - if isinstance(past_key_values, Cache): - cache_length = past_key_values.get_seq_length() - past_length = past_key_values.seen_tokens - max_cache_length = past_key_values.get_max_length() + if token_idx is not None: + idx = token_idx + kwargs.get("inputs_embeds_offset", 0) - 1 + input_ids = torch.index_select(input_ids, 1, idx) else: - cache_length = past_length = past_key_values[0][0].shape[2] - max_cache_length = None - - # Keep only the unprocessed tokens: - # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where - # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as - # input) - if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: - input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] - # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard - # input_ids based on the past_length. - elif past_length < input_ids.shape[1]: - input_ids = input_ids[:, past_length:] - # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens. - - # If we are about to go beyond the maximum cache length, we need to crop the input attention mask. - if ( - max_cache_length is not None - and attention_mask is not None - and cache_length + input_ids.shape[1] > max_cache_length - ): - attention_mask = attention_mask[:, -max_cache_length:] - - position_ids = kwargs.get("position_ids", None) + if inputs_embeds is not None: # Exception 1 + input_ids = input_ids[:, -cache_position.shape[0] :] + elif ( + input_ids.shape[1] != cache_position.shape[0] + ): # Default case (the "else", a no op, is Exception 2) + input_ids = input_ids[:, cache_position] + elif reuse_cache and token_idx is not None: + # With reuse_cache, KV cache is pre allocated hence for the 1st token we can slice the inputs till token idx for the fwd pass + input_ids = input_ids[:, :token_idx] + attention_mask = attention_mask[:, :token_idx] + if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: - position_ids = position_ids[:, -input_ids.shape[1] :] + if token_idx is not None: + position_ids = torch.index_select(position_ids, 1, token_idx - 1) + else: + position_ids = position_ids[:, -input_ids.shape[1] :] # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: - model_inputs = {"input_ids": input_ids} + model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases + + if num_logits_to_keep is not None: + model_inputs["num_logits_to_keep"] = num_logits_to_keep model_inputs.update( { "position_ids": position_ids, + "cache_position": cache_position, "past_key_values": past_key_values, - "use_cache": kwargs.get("use_cache"), + "use_cache": use_cache, "attention_mask": attention_mask, + "token_idx": token_idx, + "reuse_cache": reuse_cache, + "flash_attention_recompute": kwargs.get("flash_attention_recompute"), + "cache_idx": kwargs.get("cache_idx"), } ) return model_inputs @@ -1750,6 +1776,7 @@ def forward( attentions=transformer_outputs.attentions, ) + # Copied from optimum.habana.transformers.models.llama.modeling_llama:apply_customized_rope() def apply_customized_rope(q, k, cos, sin, position_ids, training=True): if q.device.type == "hpu" and FusedRoPE: From 72546335fa738d093b2b37168b5dcb2ad73b5b15 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Thu, 30 Jan 2025 16:31:27 -0800 Subject: [PATCH 19/20] Updated docs Signed-off-by: Daniel Huang --- README.md | 1 + docs/source/index.mdx | 1 + 2 files changed, 2 insertions(+) diff --git a/README.md b/README.md index 50688de162..2ed16cacdb 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,7 @@ The following model architectures, tasks and device distributions have been vali | DeepSeek-V2 | :heavy_check_mark: | :heavy_check_mark: |
  • [text generation](https://github.com/huggingface/optimum-habana/tree/main/examples/text-generation)
  • | | ChatGLM |
  • DeepSpeed
  • |
  • Single card
  • |
  • [language modeling](https://github.com/huggingface/optimum-habana/tree/main/examples/language-modeling)
  • [text generation](https://github.com/huggingface/optimum-habana/tree/main/examples/text-generation)
  • | | Qwen2-VL | |
  • Single card
  • |
  • [image to text](https://github.com/huggingface/optimum-habana/tree/main/examples/image-to-text)
  • | +| Arctic | |
  • DeepSpeed
  • |
  • [text generation](https://github.com/huggingface/optimum-habana/tree/main/examples/text-generation)
  • | diff --git a/docs/source/index.mdx b/docs/source/index.mdx index f71f69d3a6..63d5cf790c 100644 --- a/docs/source/index.mdx +++ b/docs/source/index.mdx @@ -110,6 +110,7 @@ In the tables below, ✅ means single-card, multi-card and DeepSpeed have all be | DeepSeek-V2 | ✅ | ✅ |
  • [text generation](https://github.com/huggingface/optimum-habana/tree/main/examples/text-generation)
  • | | ChatGLM |
  • DeepSpeed
  • |
  • Single card
  • |
  • [language modeling](https://github.com/huggingface/optimum-habana/tree/main/examples/language-modeling)
  • [text generation](https://github.com/huggingface/optimum-habana/tree/main/examples/text-generation)
  • | | Qwen2-VL | |
  • Single card
  • |
  • [image to text](https://github.com/huggingface/optimum-habana/tree/main/examples/image-to-text)
  • | +| Arctic | |
  • DeepSpeed
  • |
  • [text generation](https://github.com/huggingface/optimum-habana/tree/main/examples/text-generation)
  • | - Diffusers From 0a0cefb6248e5eeb2c25107fe44e48967e276327 Mon Sep 17 00:00:00 2001 From: Daniel Huang Date: Tue, 4 Feb 2025 12:09:56 -0800 Subject: [PATCH 20/20] Apply fixes from https://github.com/huggingface/optimum-habana/pull/1705 Signed-off-by: Daniel Huang --- .../models/snowflake/modeling_arctic.py | 84 ++++--------------- 1 file changed, 16 insertions(+), 68 deletions(-) diff --git a/optimum/habana/transformers/models/snowflake/modeling_arctic.py b/optimum/habana/transformers/models/snowflake/modeling_arctic.py index e326a039e8..093a3ef3e2 100644 --- a/optimum/habana/transformers/models/snowflake/modeling_arctic.py +++ b/optimum/habana/transformers/models/snowflake/modeling_arctic.py @@ -25,8 +25,6 @@ - Added mark steps """ -import contextlib -import inspect import math import re import warnings @@ -51,15 +49,12 @@ SequenceClassifierOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel -from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_13 from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, - is_flash_attn_2_available, logging, replace_return_docstrings, ) -from transformers.utils.import_utils import is_torch_fx_available from ..llama.modeling_llama import ( GaudiLlamaDynamicNTKScalingRotaryEmbedding, @@ -89,38 +84,8 @@ print("Not using HPU fused scaled dot-product attention kernel.") FusedSDPA = None -try: - from habana_frameworks.torch.hpu import sdp_kernel - - SDPContext = True -except ImportError: - SDPContext = False - -if is_deepspeed_available(): - from deepspeed.moe.layer import MoE - - # Note that below will crash if there is an available deepspeed that does not have ds_linear. - try: - pass - except Exception: - pass -else: - MoE = None - -if is_flash_attn_2_available(): - from flash_attn import flash_attn_func - from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa - - _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters) - -# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph. -# It means that the function will not be traced through and simply appear as a node in the graph. -if is_torch_fx_available(): - if not is_torch_greater_or_equal_than_1_13: - import torch.fx - - _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask) +deepspeed_available = is_deepspeed_available() logger = logging.get_logger(__name__) @@ -131,17 +96,6 @@ DEEPSPEED_LORA_CONFIG = "deepspeed_lora" QUANTIZATION_CONFIG = "ds_quantization_config" -# REQUIRED_DEEPSPEED_VERSION = "deepspeed>0.14.5" -# def is_deepspeed_valid_and_available(raise_error=False, error_msg=""): -# available_and_valid = True -# if not is_deepspeed_available(): -# available_and_valid = False -# if raise_error: -# raise ValueError(f"DeepSpeed is required for this feature, {error_msg}") -# else: - -# return available_and_valid - def load_balancing_loss_func( gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=4, attention_mask: Optional[torch.Tensor] = None @@ -246,7 +200,7 @@ def forward(self, hidden_states): """ Copied from optimum/habana/transformers/models/llama/modeling_llama.py gaudi_llama_rmsnorm_forward """ - if hidden_states.device.type == "hpu" and FusedRMSNorm: + if hidden_states.device.type == "hpu" and FusedRMSNorm is not None: # mixed dtypes are not good for FusedRMSNorm, both inputs need to have same dtype if hidden_states.dtype != self.weight.dtype: orig_dtype = hidden_states.dtype @@ -576,7 +530,7 @@ def forward( else: past_key_value = None - if FusedSDPA: + if FusedSDPA is not None: if query_states.dtype != key_states.dtype: key_states = key_states.type(query_states.dtype) value_states = value_states.type(query_states.dtype) @@ -593,12 +547,17 @@ def forward( ) htcore.mark_step() else: - with ( - sdp_kernel(enable_recompute=flash_attention_recompute) if SDPContext else contextlib.nullcontext() - ): - attn_output = FusedSDPA.apply( - query_states, key_states, value_states, attention_mask, 0.0, False, None - ) + attn_output = FusedSDPA.apply( + query_states, + key_states, + value_states, + attention_mask, + 0.0, + False, + None, + "None", + flash_attention_recompute, + ) else: # repeat k/v heads if n_kv_heads < n_heads query_states, key_states, value_states, attention_mask = repeat_kv( @@ -906,18 +865,7 @@ class ArcticPreTrainedModel(PreTrainedModel): def _init_weights(self, module): std = self.config.initializer_range - # if is_deepspeed_available(): - # # TODO(rajhans): remove this once ds has init for quantizedlinear. - # try: - # from deepspeed.linear.quantization import QuantizedLinear, QuantizedParameter - # if isinstance(module, QuantizedLinear): - # weights = module.weight.dequantized() - # weights.normal_(mean=0.0, std=std) - # if module.bias is not None: - # module.bias.data.zero_() - # module.weight = QuantizedParameter(weights) - # module.weight.to(dtype=torch.bfloat16, device=weights.device) - # el + if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: @@ -1779,7 +1727,7 @@ def forward( # Copied from optimum.habana.transformers.models.llama.modeling_llama:apply_customized_rope() def apply_customized_rope(q, k, cos, sin, position_ids, training=True): - if q.device.type == "hpu" and FusedRoPE: + if q.device.type == "hpu" and FusedRoPE is not None: return apply_customized_rope_module(q, k, cos, sin, position_ids, training) else: # keep the same implementation as Transformers v4.37.2