Run this model with HF Jobs
Run stabilityai/stablelm-3b-4e1t on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/stabilityai/stablelm-3b-4e1t. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/stabilityai/stablelm-3b-4e1t on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/stabilityai/stablelm-3b-4e1t. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/stabilityai/stablelm-3b-4e1t. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use stabilityai/stablelm-3b-4e1t with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use stabilityai/stablelm-3b-4e1t with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="stabilityai/stablelm-3b-4e1t")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("stabilityai/stablelm-3b-4e1t") model = AutoModelForCausalLM.from_pretrained("stabilityai/stablelm-3b-4e1t", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use stabilityai/stablelm-3b-4e1t with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "stabilityai/stablelm-3b-4e1t" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "stabilityai/stablelm-3b-4e1t", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/stabilityai/stablelm-3b-4e1t
- SGLang
How to use stabilityai/stablelm-3b-4e1t with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "stabilityai/stablelm-3b-4e1t" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "stabilityai/stablelm-3b-4e1t", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "stabilityai/stablelm-3b-4e1t" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "stabilityai/stablelm-3b-4e1t", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use stabilityai/stablelm-3b-4e1t with Docker Model Runner:
docker model run hf.co/stabilityai/stablelm-3b-4e1t
merge: upload transformers implementation (#10)
Browse files- merge: upload `transformers` implementation (ef92c21fd57a2c5e79f220acd1bcf44a7bea5f54)
- feat: use latest modeling code (26fc2dc83d3984e90a4a4b1819b31f19267cd184)
Files changed (4)
- config.json+6-11
- configuration_stablelm_epoch.py → configuration_stablelm.pyRenamed+102-33
- generation_config.json+1-1
- modeling_stablelm_epoch.py → modeling_stablelm.pyRenamed+757-334
12345678910111 unmodified line131415161718192021222324252627282930{"architectures": ["StableLMEpochForCausalLM"],"auto_map": {"AutoConfig": "configuration_stablelm_epoch.StableLMEpochConfig","AutoModelForCausalLM": "modeling_stablelm_epoch.StableLMEpochForCausalLM"},"bos_token_id": 0,"eos_token_id": 0,"hidden_act": "silu",1 unmodified line"initializer_range": 0.02,"intermediate_size": 6912,"max_position_embeddings": 4096,"model_type": "stablelm_epoch","norm_eps": 1e-05,"num_attention_heads": 32,"num_heads": 32,"num_hidden_layers": 32,"num_key_value_heads": 32,"rope_pct": 0.25,"rope_theta": 10000,"rotary_scaling_factor": 1.0,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "4.33.2","use_cache": true,"vocab_size": 50304}12345671 unmodified line910111213141516171819202122232425{"architectures": ["StableLmForCausalLM"],"bos_token_id": 0,"eos_token_id": 0,"hidden_act": "silu",1 unmodified line"initializer_range": 0.02,"intermediate_size": 6912,"max_position_embeddings": 4096,"model_type": "stablelm","layer_norm_eps": 1e-05,"num_attention_heads": 32,"num_hidden_layers": 32,"num_key_value_heads": 32,"partial_rotary_factor": 0.25,"rope_theta": 10000,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "4.38.0","use_cache": true,"use_qkv_bias": false,"vocab_size": 50304}
123456 unmodified lines12131415161718192021222324252627282930313233343536373839404142433 unmodified lines4748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# coding=utf-8# Copyright 2023 Stability 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.6 unmodified lines# 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.""" StableLM Epoch model configuration"""from transformers import PretrainedConfigfrom transformers.utils import logginglogger = logging.get_logger(__name__)class StableLMEpochConfig(PretrainedConfig):r"""Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read thedocumentation from [`PretrainedConfig`] for more information.Args:vocab_size (`int`, *optional*, defaults to 50_304):Vocabulary size of the StableLM model. Defines the number of different tokens thatcan be represented by the `inputs_ids` passed when calling [`StableLMEpochModel`].intermediate_size (`int`, *optional*, defaults to 6912):Dimension of the MLP representations.hidden_size (`int`, *optional*, defaults to 2560):Dimension of the decoder layers and the pooler layer.num_hidden_layers (`int`, *optional*, defaults to 32):Number of hidden layers in the Transformer decoder.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*):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. When3 unmodified lines`num_attention_heads`.hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):The non-linear activation function (function or string).rope_pct (`float`, *optional*, defaults to 1.0):Percentage of hidden dimensions to allocate to rotary embeddings.rope_theta (`float`, *optional*, defaults to 10000.0):The base period of the RoPE embeddings.max_position_embeddings (`int`, *optional*, defaults to 2048):The maximum sequence length that this model might ever be used with.Typically set this to something large just in case (e.g., 512 or 1024 or 2048).initializer_range (`float`, *optional*, defaults to 1e-5):The standard deviation of the truncated_normal_initializer for initializingall weight matrices.norm_eps (`float`, *optional*, defaults to 1e-8):The epsilon used by the 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`.tie_word_embeddings(`bool`, *optional*, defaults to `False`):Whether to tie weight embeddingsattention_dropout (`float`, *optional*, defaults to 0.0):The dropout ratio for the attention probabilities."""model_type = "stablelm_epoch"keys_to_ignore_at_inference = ["past_key_values"]def __init__(self,vocab_size=50_304,intermediate_size=6912,hidden_size=2560,num_hidden_layers=32,num_attention_heads=32,num_key_value_heads=32,hidden_act="silu",rope_pct=0.25,rope_theta=10_000,max_position_embeddings=4096,initializer_range=0.02,norm_eps=1.0e-5,use_cache=True,bos_token_id=0,eos_token_id=2,tie_word_embeddings=False,attention_dropout: float = 0.0,**kwargs,):self.vocab_size = vocab_sizeself.max_position_embeddings = max_position_embeddingsself.intermediate_size = intermediate_sizeself.hidden_size = hidden_sizeself.num_hidden_layers = num_hidden_layersself.num_attention_heads = num_attention_headsself.num_key_value_heads = num_key_value_headsself.hidden_act = hidden_actself.rope_pct = rope_pctself.rope_theta = rope_thetaself.initializer_range = initializer_rangeself.norm_eps = norm_epsself.use_cache = use_cacheself.tie_word_embeddings = tie_word_embeddingsself.attention_dropout = attention_dropoutsuper().__init__(bos_token_id=bos_token_id,eos_token_id=eos_token_id,tie_word_embeddings=tie_word_embeddings,**kwargs,)123456 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455563 unmodified lines60616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183# coding=utf-8# Copyright 2024 Stability 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.6 unmodified lines# 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.""" StableLM model configuration """from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logginglogger = logging.get_logger(__name__)STABLELM_PRETRAINED_CONFIG_ARCHIVE_MAP = {"stabilityai/stablelm-3b-4e1t": "https://huggingface.co/stabilityai/stablelm-3b-4e1t/resolve/main/config.json",# See all StableLM models at https://huggingface.co/models?filter=stablelm}class StableLmConfig(PretrainedConfig):r"""This is the configuration class to store the configuration of a [`~StableLmModel`].It is used to instantiate an StableLM model according to the specified arguments, defining the modelarchitecture. Instantiating a configuration with the defaults will yield a similar configuration to that ofthe StableLM [stabilityai/stablelm-3b-4e1t](https://huggingface.co/stabilityai/stablelm-3b-4e1t) architecture.Configuration objects inherit from [`PretrainedConfig`] and can be usedto control the model outputs. Read the documentation from [`PretrainedConfig`]for more information.Args:vocab_size (`int`, *optional*, defaults to 50304):Vocabulary size of the StableLM model. Defines the number of different tokens thatcan be represented by the `inputs_ids` passed when calling [`StableLmModel`].intermediate_size (`int`, *optional*, defaults to 6912):Dimension of the MLP representations.hidden_size (`int`, *optional*, defaults to 2560):Number of hidden layers in the Transformer decoder.num_hidden_layers (`int`, *optional*, defaults to 32):Number of hidden layers in the Transformer decoder.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 32):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. When3 unmodified lines`num_attention_heads`.hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):The non-linear activation function (function or string).max_position_embeddings (`int`, *optional*, defaults to 4096):The maximum sequence length that this model might ever be used with.Typically set this to something large just in case (e.g., 512 or 1024 or 2048).initializer_range (`float`, *optional*, defaults to 0.02):The standard deviation of the truncated_normal_initializer for initializingall weight matrices.layer_norm_eps (`float`, *optional*, defaults to 1e-05):The epsilon used by the 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`.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 `10000.0`):The base period of the RoPE embeddings.rope_scaling (`Dict`, *optional*):Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scalingstrategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update`max_position_embeddings` to the expected new maximum. See the following thread for more information on howthese scaling strategies behave:https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. Thisis an experimental feature, subject to breaking API changes in future versions.use_qkv_bias (`bool`, *optional*, defaults to `False`):Whether or not the model should use bias for qkv layers.hidden_dropout (`float`, *optional*, defaults to 0.0):The dropout ratio after applying the MLP to the hidden states.attention_dropout (`float`, *optional*, defaults to 0.0):The dropout ratio for the attention probabilities.partial_rotary_factor (`float`, *optional*, defaults to 0.25):Percentage of the query and keys which will have rotary embedding.bos_token_id (int, *optional*, defaults to 0):The id of the `BOS` token in the vocabulary.eos_token_id (int, *optional*, defaults to 0):The id of the `EOS` token in the vocabulary.Example:```python>>> from transformers import StableLmModel, StableLmConfig>>> # Initializing a StableLM stablelm-3b style configuration>>> configuration = StableLmConfig()```"""model_type = "stablelm"keys_to_ignore_at_inference = ["past_key_values"]def __init__(self,vocab_size=50304,intermediate_size=6912,hidden_size=2560,num_hidden_layers=32,num_attention_heads=32,num_key_value_heads=32,hidden_act="silu",max_position_embeddings=4096,initializer_range=0.02,layer_norm_eps=1.0e-5,use_cache=True,tie_word_embeddings=False,rope_theta=10_000,rope_scaling=None,use_qkv_bias=False,hidden_dropout=0.0,attention_dropout=0.0,partial_rotary_factor=0.25,bos_token_id=0,eos_token_id=0,**kwargs,):self.vocab_size = vocab_sizeself.max_position_embeddings = max_position_embeddingsself.hidden_size = hidden_sizeself.intermediate_size = intermediate_sizeself.num_hidden_layers = num_hidden_layersself.num_attention_heads = num_attention_headsself.num_key_value_heads = num_key_value_headsself.hidden_act = hidden_actself.initializer_range = initializer_rangeself.layer_norm_eps = layer_norm_epsself.use_cache = use_cacheself.rope_theta = rope_thetaself.rope_scaling = rope_scalingself.use_qkv_bias = use_qkv_biasself.hidden_dropout = hidden_dropoutself.attention_dropout = attention_dropoutself.partial_rotary_factor = partial_rotary_factorself._rope_scaling_validation()super().__init__(bos_token_id=bos_token_id,eos_token_id=eos_token_id,tie_word_embeddings=tie_word_embeddings,**kwargs,)# Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validationdef _rope_scaling_validation(self):"""Validate the `rope_scaling` configuration."""if self.rope_scaling is None:returnif not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:raise ValueError("`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "f"got {self.rope_scaling}")rope_scaling_type = self.rope_scaling.get("type", None)rope_scaling_factor = self.rope_scaling.get("factor", None)if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:raise ValueError(f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}")if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
1 unmodified line234561 unmodified line"_from_model_config": true,"bos_token_id": 0,"eos_token_id": 0,"transformers_version": "4.33.2"}1 unmodified line234561 unmodified line"_from_model_config": true,"bos_token_id": 0,"eos_token_id": 0,"transformers_version": "4.38.0"}
123456 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758591 unmodified line6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721736 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252265 unmodified lines23223323423523623723823924024124224324424524624724824925025125225325425525625725814 unmodified lines2732742752762772782792802812 unmodified lines2842852862872882892902912922932942 unmodified lines29729829930030130230330430530630712 unmodified lines32032132232332432532632732832933033133233310 unmodified lines3443453463473483493503513523533543553563573583593603613623633643653663673683693704 unmodified lines3753763773783793803813822 unmodified lines38538638738838939019 unmodified lines41041141241341441541627 unmodified lines44444544644744844934 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850951051113 unmodified lines5255265275285295305316 unmodified lines5385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815821 unmodified line5845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256261 unmodified line6286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297301 unmodified line7327337347357367377387397407417427437447457467477487497507517527537547552 unmodified lines7587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987991 unmodified line8018028038048058068078088098108118128138148158168178188198208218228235 unmodified lines82983083183283383483521 unmodified lines8578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908911 unmodified line8938948958968978988999009019023 unmodified lines906907908909910911912913914915916917918# coding=utf-8# Copyright 2023 Stability AI, EleutherAI, 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.6 unmodified lines# 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.## This code is based off the following work:# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py# https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt_neox/modeling_gpt_neox.py""" PyTorch StableLM Epoch model. """from typing import Optional, Tuple, Unionimport mathimport warningsimport torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch import nnfrom torch.nn import CrossEntropyLossfrom transformers.cache_utils import Cachefrom transformers.modeling_outputs import (BaseModelOutputWithPast,CausalLMOutputWithPast,)from transformers.modeling_utils import PreTrainedModelfrom transformers.utils import logging, is_flash_attn_greater_or_equal_2_10from .configuration_stablelm_epoch import StableLMEpochConfigtry:from flash_attn import flash_attn_func, flash_attn_varlen_funcfrom flash_attn.bert_padding import index_first_axis, pad_input, unpad_inputexcept:flash_attn_func, flash_attn_varlen_func = None, Noneindex_first_axis, pad_input, unpad_input = None, None, Nonelogger = logging.get_logger(__name__)# Copied from transformers.models.llama.modeling_llama._get_unpad_datadef _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,1 unmodified line)# Copied from transformers.models.bart.modeling_bart._make_causal_maskdef _make_causal_mask(input_ids_shape: torch.Size,dtype: torch.dtype,device: torch.device,past_key_values_length: int = 0,):"""Make causal mask used for bi-directional self-attention."""batch_size, tgt_len = input_ids_shapemask = torch.full((tgt_len, tgt_len), torch.finfo(torch.float16).min, device=device)mask_cond = torch.arange(mask.size(-1), device=device)mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)mask = mask.to(dtype)if past_key_values_length > 0:mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)return mask[None, None, :, :].expand(batch_size, 1, tgt_len, tgt_len + past_key_values_length)# Copied from transformers.models.bart.modeling_bart._expand_maskdef _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):"""Expands attention_mask from `[batch_size, seq_len]` to `[batch_size, 1, tgt_seq_len, src_seq_len]`."""batch_size, src_len = mask.size()tgt_len = tgt_len if tgt_len is not None else src_lenexpanded_mask = mask[:, None, None, :].expand(batch_size, 1, tgt_len, src_len).to(dtype)inverted_mask = 1.0 - expanded_maskreturn inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)class RotaryEmbedding(nn.Module):def __init__(self,dim: int,max_position_embeddings: int,base: int = 10_000,device: Optional[torch.device] = None,):super().__init__()self.dim = dimself.max_position_embeddings = max_position_embeddingsself.base = baseinv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / 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: int, device: torch.device, dtype: torch.dtype):self.max_seq_len_cached = seq_lent = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)# Don't do einsum, it converts fp32 to fp16 under AMP# freqs = torch.einsum("i,j->ij", t, self.inv_freq)freqs = torch.outer(t, self.inv_freq)# Different from paper, but it uses a different permutation in order to obtain the same calculationemb = torch.cat((freqs, freqs), dim=-1)self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)def forward(self, x: torch.Tensor, seq_len: Optional[int] = None):# x: [batch_size, num_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=torch.get_default_dtype())return (self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),)def rotate_half(x: torch.Tensor):"""Rotates half the hidden dims of the input."""x1, x2 = torch.chunk(x, 2, dim=-1)return torch.cat((-x2, x1), dim=-1)def apply_rotary_pos_emb(q, k, cos, sin, position_ids):# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]cos = cos[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]sin = sin[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]q_embed = (q * cos) + (rotate_half(q) * sin)k_embed = (k * cos) + (rotate_half(k) * sin)return q_embed, k_embedclass MLP(nn.Module):def __init__(self, config: StableLMEpochConfig):super().__init__()self.config = configself.hidden_size = config.hidden_sizeself.intermediate_size = config.intermediate_sizeself.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)self.act_fn = nn.SiLU()def forward(self, x: torch.Tensor) -> torch.Tensor:return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))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,6 unmodified linesreturn hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)class Attention(nn.Module):def __init__(self, config: StableLMEpochConfig):super().__init__()self.config = configself.hidden_size = config.hidden_sizeself.num_heads = config.num_attention_headsself.head_dim = self.hidden_size // self.num_headsself.num_key_value_heads = config.num_key_value_headsself.num_key_value_groups = self.num_heads // self.num_key_value_headsself.max_position_embeddings = config.max_position_embeddingsself.is_causal = Trueself.attention_dropout = config.attention_dropoutif (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}).")self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)self._init_rope()def _init_rope(self):self.rotary_ndims = int(self.head_dim * self.config.rope_pct)self.rotary_emb = RotaryEmbedding(self.rotary_ndims,max_position_embeddings=self.config.max_position_embeddings,base=self.config.rope_theta,)def forward(self,hidden_states: torch.FloatTensor,attention_mask: torch.FloatTensor,position_ids: torch.LongTensor,past_key_value: Optional[Tuple[torch.Tensor]] = None,output_attentions: Optional[bool] = False,use_cache: Optional[bool] = False,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:bsz, q_len, _ = hidden_states.size()5 unmodified lineskey_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)query_rot = query_states[..., : self.rotary_ndims]query_pass = query_states[..., self.rotary_ndims :]key_rot = key_states[..., : self.rotary_ndims]key_pass = key_states[..., self.rotary_ndims :]kv_seq_len = key_states.shape[-2]if past_key_value is not None: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_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)# [batch_size, num_heads, seq_len, head_dim]query_states = torch.cat((query_states, query_pass), dim=-1)key_states = torch.cat((key_states, key_pass), dim=-1)if past_key_value is not None:# Reuse k, v, self_attentionkey_states = torch.cat((past_key_value[0], key_states), dim=2)value_states = torch.cat((past_key_value[1], value_states), dim=2)past_key_value = (key_states, value_states) if use_cache else None# Repeat k/v heads if n_kv_heads < n_headskey_states = repeat_kv(key_states, self.num_key_value_groups)14 unmodified lines)attn_weights = attn_weights + attention_mask# Upcast attention to fp32attn_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):2 unmodified linesf" {attn_output.size()}")# Merge headsattn_output = attn_output.transpose(1, 2).contiguous()attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)# Final linear projectionattn_output = self.o_proj(attn_output)if not output_attentions:2 unmodified linesreturn attn_output, attn_weights, past_key_valueclass FlashAttention2(Attention):"""Reference: https://github.com/huggingface/transformers/blob/5d36025ca13d05151b7a0c761e90d429c4644a30/src/transformers/models/llama/modeling_llama.py#L456"""def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)12 unmodified linesuse_cache: bool = False,**kwargs,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:# FlashAttention2 attention does not support output_attentionsif "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_maskattention_mask = kwargs.pop("padding_mask")output_attentions = False10 unmodified lineskey_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)query_rot = query_states[..., : self.rotary_ndims]query_pass = query_states[..., self.rotary_ndims :]key_rot = key_states[..., : self.rotary_ndims]key_pass = key_states[..., self.rotary_ndims :]kv_seq_len = key_states.shape[-2]if past_key_value is not None: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_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)# [batch_size, num_heads, seq_len, head_dim]query_states = torch.cat((query_states, query_pass), dim=-1)key_states = torch.cat((key_states, key_pass), dim=-1)if past_key_value is not None:# Reuse k, v, self_attentionkey_states = torch.cat((past_key_value[0], key_states), dim=2)value_states = torch.cat((past_key_value[1], value_states), dim=2)past_key_value = (key_states, value_states) if use_cache else None# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache# to be able to avoid many of these transpose/reshape/view.4 unmodified linesdropout_rate = self.attention_dropout if self.training else 0.0attn_output = self._flash_attention_forward(query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate)attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()attn_output = self.o_proj(attn_output)2 unmodified linesreturn attn_output, attn_weights, past_key_valuedef _flash_attention_forward(self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None):19 unmodified linesif not self._flash_attn_uses_top_left_mask:causal = self.is_causalelse:# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in FlashAttention2 __init__.causal = self.is_causal and query_length != 1# Contains at least one padding token in the sequence27 unmodified linesreturn attn_outputdef _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape34 unmodified linesATTENTION_CLASSES = {"eager": Attention,"flash_attention_2": FlashAttention2,}class DecoderLayer(nn.Module):def __init__(self, config: StableLMEpochConfig):super().__init__()self.self_attn = ATTENTION_CLASSES[config._attn_implementation](config=config)self.mlp = MLP(config)self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)def forward(self,hidden_states: Optional[torch.FloatTensor],attention_mask: Optional[torch.FloatTensor] = 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,) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:residual = hidden_stateshidden_states = self.input_layernorm(hidden_states)13 unmodified linesresidual = hidden_stateshidden_states = self.post_attention_layernorm(hidden_states)hidden_states = self.mlp(hidden_states)hidden_states = residual + hidden_statesoutputs = (hidden_states,)6 unmodified linesreturn outputsclass StableLMEpochPreTrainedModel(PreTrainedModel):"""An abstract class to handle weights initialization and a simple interfacefor downloading and loading pretrained models."""config_class = StableLMEpochConfigbase_model_prefix = "model"supports_gradient_checkpointing = True_no_split_modules = ["DecoderLayer"]_skip_keys_device_placement = "past_key_values"_supports_flash_attn_2 = Truedef _init_weights(self, module: nn.Module):"""Initialize the weights"""if isinstance(module, nn.Linear):module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)if module.bias is not None:module.bias.data.zero_()elif isinstance(module, nn.Embedding):module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)if module.padding_idx is not None:module.weight.data[module.padding_idx].zero_()elif isinstance(module, nn.LayerNorm):module.bias.data.zero_()module.weight.data.fill_(1.0)def _set_gradient_checkpointing(self, module: nn.Module, value=False):if isinstance(module, StableLMEpochModel):module.gradient_checkpointing = valueclass StableLMEpochModel(StableLMEpochPreTrainedModel):def __init__(self, config: StableLMEpochConfig):super().__init__(config)self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"self.gradient_checkpointing = False# Initialize weights and apply final processingself.post_init()1 unmodified linedef get_input_embeddings(self):return self.embed_tokensdef set_input_embeddings(self, value: nn.Module):self.embed_tokens = value# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_maskdef _prepare_decoder_attention_mask(self,attention_mask: torch.Tensor,input_shape: torch.Size,inputs_embeds: torch.Tensor,past_key_values_length: int,):# Create causal mask# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]combined_attention_mask = Noneif input_shape[-1] > 1:combined_attention_mask = _make_causal_mask(input_shape,inputs_embeds.dtype,device=inputs_embeds.device,past_key_values_length=past_key_values_length,)if attention_mask is not None:# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_maskreturn combined_attention_maskdef forward(self,input_ids: Optional[torch.LongTensor] = None,attention_mask: Optional[torch.FloatTensor] = None,position_ids: Optional[torch.LongTensor] = None,past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,inputs_embeds: Optional[torch.FloatTensor] = None,use_cache: Optional[bool] = None,output_attentions: Optional[bool] = None,1 unmodified linereturn_dict: Optional[bool] = None,) -> Union[Tuple, BaseModelOutputWithPast]:output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_statesuse_cache = use_cache if use_cache is not None else self.config.use_cachereturn_dict = return_dict if return_dict is not None else self.config.use_return_dict# Retrieve input_ids and inputs_embedsif 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.shapeelif inputs_embeds is not None:batch_size, seq_length, _ = inputs_embeds.shapeelse:raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")seq_length_with_past = seq_lengthpast_key_values_length = 0if position_ids is None:device = input_ids.device if input_ids is not None else inputs_embeds.deviceposition_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)# Embed positionsif self._use_flash_attention_2:# 2d mask is passed through the layersattention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else Noneelse:if attention_mask is None:attention_mask = torch.ones((batch_size, seq_length_with_past),dtype=torch.bool,device=inputs_embeds.device,)attention_mask = self._prepare_decoder_attention_mask(attention_mask,(batch_size, seq_length),inputs_embeds,past_key_values_length,)hidden_states = inputs_embedsif self.gradient_checkpointing and self.training:if use_cache:logger.warning("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")use_cache = False# Decoder layersall_hidden_states = () if output_hidden_states else Noneall_self_attns = () if output_attentions else Nonenext_decoder_cache = () if use_cache else Nonefor idx, decoder_layer in enumerate(self.layers):if output_hidden_states:all_hidden_states += (hidden_states,)past_key_value = (past_key_values[idx] if past_key_values is not None else None)if self.gradient_checkpointing and self.training:def create_custom_forward(module):def custom_forward(*inputs):# None for past_key_valuereturn module(*inputs, past_key_value, output_attentions)return custom_forwardlayer_outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(decoder_layer),hidden_states,attention_mask,position_ids,)else:layer_outputs = decoder_layer(hidden_states,attention_mask=attention_mask,position_ids=position_ids,past_key_value=past_key_value,output_attentions=output_attentions,use_cache=use_cache,)1 unmodified linehidden_states = layer_outputs[0]if use_cache:next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)if output_attentions:all_self_attns += (layer_outputs[1],)hidden_states = self.norm(hidden_states)# Add hidden states from the last decoder layerif output_hidden_states:all_hidden_states += (hidden_states,)next_cache = next_decoder_cache if use_cache else Noneif not return_dict:return tuple(vfor v in [hidden_states, next_cache, all_hidden_states, all_self_attns]if v is not None)return BaseModelOutputWithPast(last_hidden_state=hidden_states,past_key_values=next_cache,2 unmodified lines)class StableLMEpochForCausalLM(StableLMEpochPreTrainedModel):_tied_weights_keys = ["lm_head.weight"]def __init__(self, config: StableLMEpochConfig):super().__init__(config)self.model = StableLMEpochModel(config)self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)# Initialize weights and apply final processingself.post_init()def get_input_embeddings(self):return self.model.embed_tokensdef set_input_embeddings(self, value):self.model.embed_tokens = valuedef get_output_embeddings(self):return self.lm_headdef set_output_embeddings(self, new_embeddings: nn.Module):self.lm_head = new_embeddingsdef get_decoder(self):return self.modeldef set_decoder(self, decoder):self.model = decoderdef forward(self,input_ids: Optional[torch.LongTensor] = None,attention_mask: Optional[torch.FloatTensor] = None,position_ids: Optional[torch.LongTensor] = None,past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,inputs_embeds: Optional[torch.FloatTensor] = None,labels: Optional[torch.LongTensor] = None,use_cache: Optional[bool] = None,1 unmodified lineoutput_hidden_states: Optional[bool] = None,return_dict: Optional[bool] = None,) -> Union[Tuple, CausalLMOutputWithPast]:output_attentions = (output_attentionsif output_attentions is not Noneelse self.config.output_attentions)output_hidden_states = (output_hidden_statesif output_hidden_states is not Noneelse 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,attention_mask=attention_mask,position_ids=position_ids,past_key_values=past_key_values,5 unmodified lines)hidden_states = outputs[0]logits = self.lm_head(hidden_states).float()loss = Noneif labels is not None:21 unmodified lines)def prepare_inputs_for_generation(self,input_ids,past_key_values: Optional[torch.Tensor] = None,attention_mask: Optional[torch.Tensor] = None,inputs_embeds: Optional[torch.Tensor] = None,**kwargs,):# Trim decoder_input_ids if past is usedif past_key_values is not None:past_length = past_key_values[0][0].shape[2]# Some generation methods already pass only the last input IDif input_ids.shape[1] > past_length:remove_prefix_length = past_lengthelse:# Default to old behavior: keep only final IDremove_prefix_length = input_ids.shape[1] - 1input_ids = input_ids[:, remove_prefix_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 generationposition_ids = attention_mask.long().cumsum(-1) - 1position_ids.masked_fill_(attention_mask == 0, 1)if past_key_values:position_ids = position_ids[:, -1].unsqueeze(-1)# If `inputs_embeds` are passed, we only want to use them in the 1st generation stepif inputs_embeds is not None and past_key_values is None:model_inputs = {"inputs_embeds": inputs_embeds}else:1 unmodified linemodel_inputs.update({"attention_mask": attention_mask,"past_key_values": past_key_values,"use_cache": kwargs.get("use_cache"),"position_ids": position_ids,})return model_inputs3 unmodified linesreordered_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_pastStableLMEpochConfig.register_for_auto_class()StableLMEpochForCausalLM.register_for_auto_class("AutoModelForCausalLM")123456789106 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263641 unmodified line666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082096 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932945 unmodified lines30030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533614 unmodified lines3513523533543553563573583593602 unmodified lines3633643653663673683693703712 unmodified lines37437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248312 unmodified lines49649749849950050150210 unmodified lines5135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465474 unmodified lines5525535545555565575585595605615625635645652 unmodified lines56856957057157257357419 unmodified lines59459559659759859960027 unmodified lines62862963063163263363434 unmodified lines66967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871913 unmodified lines7337347357367377387397407416 unmodified lines7487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898901 unmodified line8928938948958968978988999009019029039049059069071 unmodified line9099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979981 unmodified line100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110222 unmodified lines102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771 unmodified line10791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711185 unmodified lines112411251126112711281129113021 unmodified lines11521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971 unmodified line11991200120112021203120412051206120712083 unmodified lines1212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341# coding=utf-8# Copyright 2024 EleutherAI 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.6 unmodified lines# 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 StableLM model."""import mathfrom typing import List, Optional, Tuple, Unionimport torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELossfrom transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_maskfrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPastfrom transformers.modeling_utils import PreTrainedModelfrom 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 .configuration_stablelm import StableLmConfigif is_flash_attn_2_available():from flash_attn import flash_attn_func, flash_attn_varlen_funcfrom flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqalogger = logging.get_logger(__name__)_CONFIG_FOR_DOC = "StableLmConfig"# Copied from transformers.models.llama.modeling_llama._get_unpad_datadef _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.int32), (1, 0))return (indices,cu_seqlens,1 unmodified line)# Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->StableLmclass StableLmRotaryEmbedding(nn.Module):def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):super().__init__()self.dim = dimself.max_position_embeddings = max_position_embeddingsself.base = baseinv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).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_lent = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)freqs = torch.outer(t, self.inv_freq)# Different from paper, but it uses a different permutation in order to obtain the same calculationemb = 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.falcon.modeling_falcon.FalconLinearScalingRotaryEmbedding with Falcon->StableLmclass StableLmLinearScalingRotaryEmbedding(StableLmRotaryEmbedding):"""StableLmRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):self.scaling_factor = scaling_factorsuper().__init__(dim, max_position_embeddings, base, device)def _set_cos_sin_cache(self, seq_len, device, dtype):self.max_seq_len_cached = seq_lent = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)t = t / self.scaling_factorfreqs = torch.outer(t, self.inv_freq)# Different from paper, but it uses a different permutation in order to obtain the same calculationemb = 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)# Copied from transformers.models.falcon.modeling_falcon.FalconDynamicNTKScalingRotaryEmbedding with Falcon->StableLmclass StableLmDynamicNTKScalingRotaryEmbedding(StableLmRotaryEmbedding):"""StableLmRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):self.scaling_factor = scaling_factorsuper().__init__(dim, max_position_embeddings, base, device)def _set_cos_sin_cache(self, seq_len, device, dtype):self.max_seq_len_cached = seq_lenif seq_len > self.max_position_embeddings:base = self.base * ((self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)) ** (self.dim / (self.dim - 2))inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))self.register_buffer("inv_freq", inv_freq, persistent=False)t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)freqs = torch.outer(t, self.inv_freq)# Different from paper, but it uses a different permutation in order to obtain the same calculationemb = 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)# Copied from transformers.models.llama.modeling_llama.rotate_halfdef 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.mistral.modeling_mistral.apply_rotary_pos_embdef 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 beused 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] andsin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, notethat cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q andk have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makescos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k havethe 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.mistral.modeling_mistral.MistralMLP with Mistral->StableLmclass StableLmMLP(nn.Module):def __init__(self, config):super().__init__()self.config = configself.hidden_size = config.hidden_sizeself.intermediate_size = config.intermediate_sizeself.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)self.act_fn = ACT2FN[config.hidden_act]def forward(self, x):return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))# Copied from transformers.models.llama.modeling_llama.repeat_kvdef 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,6 unmodified linesreturn hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)class StableLmAttention(nn.Module):"""Multi-headed attention from 'Attention Is All You Need' paper"""def __init__(self, config: StableLmConfig, layer_idx: Optional[int] = None):super().__init__()self.config = configself.layer_idx = layer_idxif layer_idx is None:logger.warning_once(f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will ""lead 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_sizeself.num_heads = config.num_attention_headsself.head_dim = self.hidden_size // self.num_headsself.num_key_value_heads = config.num_key_value_headsself.num_key_value_groups = self.num_heads // self.num_key_value_headsself.max_position_embeddings = config.max_position_embeddingsself.rope_theta = config.rope_thetaself.partial_rotary_factor = config.partial_rotary_factorself.is_causal = Trueif (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}).")self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.use_qkv_bias)self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)self.attention_dropout = nn.Dropout(config.attention_dropout)self._init_rope()# Copied from transformers.models.persimmon.modeling_persimmon.PersimmonAttention._init_rope with Persimmon->StableLmdef _init_rope(self):if self.config.rope_scaling is None:self.rotary_emb = StableLmRotaryEmbedding(int(self.partial_rotary_factor * 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 = StableLmLinearScalingRotaryEmbedding(int(self.partial_rotary_factor * 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 = StableLmDynamicNTKScalingRotaryEmbedding(int(self.partial_rotary_factor * 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 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]]]:bsz, q_len, _ = hidden_states.size()5 unmodified lineskey_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)# Partial rotary embeddingquery_rot, query_pass = (query_states[..., : self.rotary_emb.dim],query_states[..., self.rotary_emb.dim :],)key_rot, key_pass = (key_states[..., : self.rotary_emb.dim],key_states[..., self.rotary_emb.dim :],)# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)# [batch_size, seq_length, num_heads, head_dim]query_states = torch.cat((query_rot, query_pass), dim=-1)key_states = torch.cat((key_rot, key_pass), dim=-1)if past_key_value is not None:# Specific to RoPE models with partial rotationcache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}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_headskey_states = repeat_kv(key_states, self.num_key_value_groups)14 unmodified lines)attn_weights = attn_weights + attention_mask# upcast attention to fp32attn_weights = nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query_states.dtype)attn_weights = self.attention_dropout(attn_weights)attn_output = torch.matmul(attn_weights, value_states)if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):2 unmodified linesf" {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:2 unmodified linesreturn attn_output, attn_weights, past_key_valueclass StableLmSdpaAttention(StableLmAttention):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("StableLmModel is using StableLmSdpaAttention, 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: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)# Partial rotary embeddingquery_rot, query_pass = (query_states[..., : self.rotary_emb.dim],query_states[..., self.rotary_emb.dim :],)key_rot, key_pass = (key_states[..., : self.rotary_emb.dim],key_states[..., self.rotary_emb.dim :],)# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)# [batch_size, seq_length, num_heads, head_dim]query_states = torch.cat((query_rot, query_pass), dim=-1)key_states = torch.cat((key_rot, key_pass), dim=-1)if past_key_value is not None:# Specific to RoPE models with partial rotationcache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}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_headskey_states = repeat_kv(key_states, self.num_key_value_groups)value_states = repeat_kv(value_states, self.num_key_value_groups)# 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.p 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.view(bsz, q_len, self.hidden_size)attn_output = self.o_proj(attn_output)return attn_output, None, past_key_valueclass StableLmFlashAttention2(StableLmAttention):"""StableLM flash attention module. This module inherits from `StableLmAttention` as the weights of the module staysuntouched. The only required change would be on the forward pass where it needs to correctly call the public API offlash 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)12 unmodified linesuse_cache: bool = False,**kwargs,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:# StableLmFlashAttention2 attention does not support output_attentionsoutput_attentions = False10 unmodified lineskey_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)# Partial rotary embeddingquery_rot, query_pass = (query_states[..., : self.rotary_emb.dim],query_states[..., self.rotary_emb.dim :],)key_rot, key_pass = (key_states[..., : self.rotary_emb.dim],key_states[..., self.rotary_emb.dim :],)query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)# [batch_size, seq_length, num_heads, head_dim]query_states = torch.cat((query_rot, query_pass), dim=-1)key_states = torch.cat((key_rot, key_pass), dim=-1)if past_key_value is not None:cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache# to be able to avoid many of these transpose/reshape/view.4 unmodified linesdropout_rate = self.attention_dropout if self.training else 0.0attn_output = self._flash_attention_forward(query_states,key_states,value_states,attention_mask,q_len,dropout=dropout_rate,)attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()attn_output = self.o_proj(attn_output)2 unmodified linesreturn attn_output, attn_weights, past_key_value# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forwarddef _flash_attention_forward(self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None):19 unmodified linesif not self._flash_attn_uses_top_left_mask:causal = self.is_causalelse:# 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 sequence27 unmodified linesreturn attn_output# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_inputdef _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape34 unmodified linesATTENTION_CLASSES = {"eager": StableLmAttention,"sdpa": StableLmSdpaAttention,"flash_attention_2": StableLmFlashAttention2,}class StableLmDecoderLayer(nn.Module):def __init__(self, config: StableLmConfig, layer_idx: int):super().__init__()self.hidden_size = config.hidden_sizeself.self_attn = ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)self.mlp = StableLmMLP(config)self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)self.dropout = nn.Dropout(config.hidden_dropout)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,) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:"""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, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.position_ids (`torch.LongTensor` of shape `({0})`, *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_value (`Tuple(torch.FloatTensor)`, *optional*):cached past key and value projection statesoutput_attentions (`bool`, *optional*):Whether or not to return the attentions tensors of all attention layers. See `attentions` underreturned 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 = hidden_stateshidden_states = self.input_layernorm(hidden_states)13 unmodified linesresidual = hidden_stateshidden_states = self.post_attention_layernorm(hidden_states)hidden_states = self.mlp(hidden_states)hidden_states = self.dropout(hidden_states)hidden_states = hidden_states + residualoutputs = (hidden_states,)6 unmodified linesreturn outputsSTABLELM_START_DOCSTRING = r"""This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)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 usageand behavior.Parameters:config ([`StableLmConfig`]):Model configuration class with all the parameters of the model. Initializing with a config file does notload 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 StableLm Model outputting raw hidden-states without any specific head on top.",STABLELM_START_DOCSTRING,)class StableLmPreTrainedModel(PreTrainedModel):config_class = StableLmConfigbase_model_prefix = "model"supports_gradient_checkpointing = True_no_split_modules = ["StableLmDecoderLayer"]_skip_keys_device_placement = "past_key_values"_supports_flash_attn_2 = True_supports_cache_class = True_supports_sdpa = Truedef _init_weights(self, module):std = self.config.initializer_rangeif 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_()STABLELM_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 provideit.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 moreinformation on the default strategy.- 1 indicates the head is **not masked**,- 0 indicates the head is **masked**.position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,config.n_positions - 1]`.[What are position IDs?](../glossary#position-ids)past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.Two formats are allowed:- a [`~cache_utils.Cache`] instance;- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors ofshape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacycache format.The model will output the same cache format that is fed as input. If no `past_key_values` are passed, thelegacy cache format will be returned.If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don'thave their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`of shape `(batch_size, sequence_length)`.inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. Thisis useful if you want more control over how to convert `input_ids` indices into associated vectors than themodel'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 returnedtensors 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 formore detail.return_dict (`bool`, *optional*):Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""@add_start_docstrings("The bare StableLm Model outputting raw hidden-states without any specific head on top.",STABLELM_START_DOCSTRING,)class StableLmModel(StableLmPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`StableLmDecoderLayer`]Args:config: StableLmConfig"""def __init__(self, config: StableLmConfig):super().__init__(config)self.padding_idx = config.pad_token_idself.vocab_size = config.vocab_sizeself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)self.layers = nn.ModuleList([StableLmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)self._attn_implementation = config._attn_implementationself.gradient_checkpointing = False# Initialize weights and apply final processingself.post_init()1 unmodified linedef get_input_embeddings(self):return self.embed_tokensdef set_input_embeddings(self, value):self.embed_tokens = value@add_start_docstrings_to_model_forward(STABLELM_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,1 unmodified linereturn_dict: Optional[bool] = None,) -> Union[Tuple, BaseModelOutputWithPast]:output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_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_cachereturn_dict = return_dict if return_dict is not None else self.config.use_return_dict# retrieve input_ids and inputs_embedsif 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.shapeelif inputs_embeds is not None:batch_size, seq_length, _ = inputs_embeds.shapeelse:raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")seq_length_with_past = seq_lengthpast_key_values_length = 0if 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 = Falseif 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)seq_length_with_past = seq_length_with_past + past_key_values_lengthif position_ids is None:device = input_ids.device if input_ids is not None else inputs_embeds.deviceposition_ids = torch.arange(past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device)position_ids = position_ids.unsqueeze(0)if inputs_embeds is None:inputs_embeds = self.embed_tokens(input_ids)# embed positionsif self._attn_implementation == "flash_attention_2":# 2d mask is passed through the layersattention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None# for output_attentions case used fallback to eager attention realizationelif self._attn_implementation == "sdpa" and not output_attentions: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 layersattention_mask = _prepare_4d_causal_attention_mask(attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length)hidden_states = inputs_embeds# decoder layersall_hidden_states = () if output_hidden_states else Noneall_self_attns = () if output_attentions else Nonenext_decoder_cache = Nonefor decoder_layer in 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,)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,)1 unmodified linehidden_states = layer_outputs[0]if use_cache:next_decoder_cache = layer_outputs[2 if output_attentions else 1]if output_attentions:all_self_attns += (layer_outputs[1],)hidden_states = self.norm(hidden_states)# add hidden states from the last decoder layerif output_hidden_states:all_hidden_states += (hidden_states,)next_cache = Noneif use_cache:next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cacheif not return_dict:return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)return BaseModelOutputWithPast(last_hidden_state=hidden_states,past_key_values=next_cache,2 unmodified lines)# Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM with PERSIMMON->STABLELM,Persimmon->StableLmclass StableLmForCausalLM(StableLmPreTrainedModel):_tied_weights_keys = ["lm_head.weight"]# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with LLAMA->STABLELM,Llama->StableLmdef __init__(self, config):super().__init__(config)self.model = StableLmModel(config)self.vocab_size = config.vocab_sizeself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)# Initialize weights and apply final processingself.post_init()# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddingsdef get_input_embeddings(self):return self.model.embed_tokens# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddingsdef set_input_embeddings(self, value):self.model.embed_tokens = value# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddingsdef get_output_embeddings(self):return self.lm_head# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddingsdef set_output_embeddings(self, new_embeddings):self.lm_head = new_embeddings# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoderdef set_decoder(self, decoder):self.model = decoder# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoderdef get_decoder(self):return self.model@add_start_docstrings_to_model_forward(STABLELM_INPUTS_DOCSTRING)@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)# Ignore copydef 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,1 unmodified lineoutput_hidden_states: Optional[bool] = None,return_dict: Optional[bool] = None,) -> Union[Tuple, CausalLMOutputWithPast]:r"""Args:labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.Returns:Example:```python>>> from transformers import AutoTokenizer, StableLmForCausalLM>>> model = StableLmForCausalLM.from_pretrained("stabilityai/stablelm-3b-4e1t")>>> tokenizer = AutoTokenizer.from_pretrained("stabilityai/stablelm-3b-4e1t")>>> prompt = "The weather is always wonderful in">>> 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]'The weather is always wonderful in the summer in the city of San Diego. The city is located on the coast of the Pacific Ocean and is surrounded by'```"""output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_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_dictoutputs = self.model(input_ids=input_ids,attention_mask=attention_mask,position_ids=position_ids,past_key_values=past_key_values,5 unmodified lines)hidden_states = outputs[0]logits = self.lm_head(hidden_states)loss = Noneif labels is not None:21 unmodified lines)def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs):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_tokensmax_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 Noneand attention_mask is not Noneand 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 generationposition_ids = attention_mask.long().cumsum(-1) - 1position_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 stepif inputs_embeds is not None and past_key_values is None:model_inputs = {"inputs_embeds": inputs_embeds}else:1 unmodified linemodel_inputs.update({"position_ids": position_ids,"past_key_values": past_key_values,"use_cache": kwargs.get("use_cache"),"attention_mask": attention_mask,})return model_inputs3 unmodified linesreordered_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 StableLm transformer with a sequence classification head on top (linear layer).[`StableLmForSequenceClassification`] uses the last token in order to do the classification, as other causalmodels (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. Ifno `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess thepadding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value ineach row of the batch).""",STABLELM_START_DOCSTRING,)# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->STABLELM,Llama->StableLmclass StableLmForSequenceClassification(StableLmPreTrainedModel):def __init__(self, config):super().__init__(config)self.num_labels = config.num_labelsself.model = StableLmModel(config)self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)# Initialize weights and apply final processingself.post_init()def get_input_embeddings(self):return self.model.embed_tokensdef set_input_embeddings(self, value):self.model.embed_tokens = value@add_start_docstrings_to_model_forward(STABLELM_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_dicttransformer_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 = -1else:if input_ids is not None:# if no pad token found, use modulo instead of reverse indexing for ONNX compatibilitysequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1sequence_lengths = sequence_lengths % input_ids.shape[-1]sequence_lengths = sequence_lengths.to(logits.device)else:sequence_lengths = -1pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]loss = Noneif 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 outputreturn SequenceClassifierOutputWithPast(loss=loss,logits=pooled_logits,past_key_values=transformer_outputs.past_key_values,hidden_states=transformer_outputs.hidden_states,attentions=transformer_outputs.attentions,)
config.json+6-11
configuration_stablelm_epoch.py → configuration_stablelm.pyRenamed+102-33
generation_config.json+1-1
modeling_stablelm_epoch.py → modeling_stablelm.pyRenamed+757-334