Run this model with HF Jobs
Run IFM/Crystal 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/IFM/Crystal. 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/IFM/Crystal 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/IFM/Crystal. 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/IFM/Crystal. 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 IFM/Crystal with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use IFM/Crystal with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="IFM/Crystal", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("IFM/Crystal", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use IFM/Crystal with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "IFM/Crystal" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "IFM/Crystal", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/IFM/Crystal
- SGLang
How to use IFM/Crystal 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 "IFM/Crystal" \ --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": "IFM/Crystal", "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 "IFM/Crystal" \ --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": "IFM/Crystal", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use IFM/Crystal with Docker Model Runner:
docker model run hf.co/IFM/Crystal
Commit ·
e875200
1
Parent(s): ff221ca
Upload folder using huggingface_hub
Browse filesCommitting checkpoint CrystalCoder_phase3_checkpoint_027728
Files changed (13)
- config.jsonAdded+33
- configuration_crystalcoder.pyAdded+149
- generation_config.jsonAdded+6
- modeling_crystalcoder.pyAdded+1671
- pytorch_model-00001-of-00004.binAdded+3
- pytorch_model-00002-of-00004.binAdded+3
- pytorch_model-00003-of-00004.binAdded+3
- pytorch_model-00004-of-00004.binAdded+3
- pytorch_model.bin.index.jsonAdded+523
- register_crystalcoder.pyAdded+9
- tokenization_crystalcoder_fast.pyAdded+139
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+245
123456789101112131415161718192021222324252627282930313233{ "attn_pdrop": 0.0, "scale_attn_weights": true, "resid_pdrop": 0.0, "mup_embeddings_scale": 14.6, "n_inner": 10922, "n_embd": 4096, "layer_norm_epsilon": 1e-05, "n_positions": 2048, "activation_function": "swiglu", "n_head": 32, "n_layer": 32, "mup_output_alpha": 2.22, "mup_width_scale": 0.0625, "position_embedding_type": "rotary", "rotary_dim": 32, "mup_scale_qk_dot_by_d": true, "tie_word_embeddings": true, "vocab_size": 32032, "embd_pdrop": 0.0, "model_type": "crystalcoder", "use_cache": true, "bos_token_id": 1, "eos_token_id": 2, "auto_map": { "AutoConfig": "configuration_crystalcoder.CrystalCoderConfig", "AutoModel": "modeling_crystalcoder.CrystalCoderModel", "AutoModelForCausalLM": "modeling_crystalcoder.CrystalCoderLMHeadModel" }, "architectures": [ "CrystalCoderLMHeadModel" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149""" CrystalCoder configuration"""
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class CrystalCoderConfig(PretrainedConfig): """ This is the configuration class to store the configuration of a [`CrystalCoderModel`]. It is used to instantiate a CrystalCoder model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 50257): Vocabulary size of the CrystalCoder model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`CrystalCoderModel`]. n_positions (`int`, *optional*, defaults to 1024): 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). n_embd (`int`, *optional*, defaults to 768): Dimensionality of the embeddings and hidden states. n_layer (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. n_head (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. n_inner (`int`, *optional*, defaults to None): Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd activation_function (`str`, *optional*, defaults to `"gelu"`): Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new", "swiglu"]`. resid_pdrop (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. embd_pdrop (`float`, *optional*, defaults to 0.1): The dropout ratio for the embeddings. attn_pdrop (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention. layer_norm_epsilon (`float`, *optional*, defaults to 1e-5): The epsilon to use in the layer normalization layers. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. scale_attn_weights (`bool`, *optional*, defaults to `True`): Scale attention weights by dividing by sqrt(hidden_size).. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`): Whether to additionally scale attention weights by `1 / layer_idx + 1`. reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`): Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention dot-product/softmax to float() when training with mixed precision. position_embedding_type (`str`, *optional*, defaults to `"learned"`): Positional embedding can be either `"alibi"`, `"learned"`, or `"learned"`. rotary_dim (`int`, *optional*, defaults to `n_embd / n_head`): The dimension along which to apply rope. mup_width_scale (`float`, *optional*, defaults to 1.0): muP parameter to scale learning rate and initializers. Calculated as (`d_model,0 / d_model`), where `d_model` is the model's width and `d_model,0` is the proxy model's width. mup_embeddings_scale (`float`, *optional*, defaults to 1.0): muP parameter to scale token and position embeddings. mup_output_alpha (`float`, *optional*, defaults to 1.0): muP parameter to scale output logits (`output_logits_scale = mup_output_alpha * mup_width_scale`). mup_scale_qk_dot_by_d (`bool`, *optional*, defaults to `False`): Scale attention weights by dividing by hidden_size instead of sqrt(hidden_size). Need to set scale_attn_weights to `True` as well.
Example:
```python >>> from transformers import CrystalCoderConfig, CrystalCoderModel
>>> # Initializing a CrystalCoder configuration >>> configuration = CrystalCoderConfig()
>>> # Initializing a model (with random weights) from the configuration >>> model = CrystalCoderModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "crystalcoder" keys_to_ignore_at_inference = ["past_key_values"] attribute_map = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", }
def __init__( self, vocab_size=32032, n_positions=2048, n_embd=4096, n_layer=32, n_head=32, n_inner=None, activation_function="swiglu", resid_pdrop=0.1, embd_pdrop=0.1, attn_pdrop=0.1, layer_norm_epsilon=1e-5, initializer_range=0.02, scale_attn_weights=True, use_cache=True, bos_token_id=1, eos_token_id=2, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False, position_embedding_type="rotary", rotary_dim=None, mup_width_scale=1.0, mup_embeddings_scale=1.0, mup_output_alpha=1.0, mup_scale_qk_dot_by_d=False, **kwargs, ): self.vocab_size = vocab_size self.n_positions = n_positions self.n_embd = n_embd self.n_layer = n_layer self.n_head = n_head self.n_inner = n_inner self.activation_function = activation_function self.resid_pdrop = resid_pdrop self.embd_pdrop = embd_pdrop self.attn_pdrop = attn_pdrop self.layer_norm_epsilon = layer_norm_epsilon self.initializer_range = initializer_range self.scale_attn_weights = scale_attn_weights self.use_cache = use_cache self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx self.reorder_and_upcast_attn = reorder_and_upcast_attn
self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id
self.position_embedding_type = position_embedding_type self.rotary_dim = rotary_dim self.mup_width_scale = mup_width_scale self.mup_embeddings_scale = mup_embeddings_scale self.mup_output_alpha = mup_output_alpha self.mup_scale_qk_dot_by_d = mup_scale_qk_dot_by_d
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)123456{ "_from_model_config": true, "bos_token_id": 1, "eos_token_id": 2, "transformers_version": "4.33.0.dev0"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
""" PyTorch CrystalCoder model."""
import mathimport osimport warningsfrom typing import Optional, Tuple, Union
import torchfrom torch import Tensor, nnfrom torch.cuda.amp import autocastfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FNfrom transformers.modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions, QuestionAnsweringModelOutput, SequenceClassifierOutputWithPast, TokenClassifierOutput,)from transformers.modeling_utils import PreTrainedModelfrom transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layerfrom transformers.utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging,)from transformers.utils.model_parallel_utils import assert_device_map, get_device_mapfrom .configuration_crystalcoder import CrystalCoderConfig# from configuration_crystalcoder import CrystalCoderConfig
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "CrystalCoderConfig"
def _duplicate_interleave(m): """ A simple version of `torch.repeat_interleave` for duplicating a matrix while interleaving the copy. """ dim0 = m.shape[0] m = m.view(-1, 1) # flatten the matrix m = m.repeat(1, 2) # repeat all elements into the 2nd dimension m = m.view(dim0, -1) # reshape into a matrix, interleaving the copy return m
class RotaryPositionEmbeddingHelper: def __init__(self, max_position_embeddings, rotary_dim, base=10000): super(RotaryPositionEmbeddingHelper, self).__init__() self.max_position_embeddings = max_position_embeddings self.rotary_dim = rotary_dim self.base = base self.sin_cached = None self.cos_cached = None # self.offset = 0
def create_fixed_pos_emb(self, x, offset): if (self.sin_cached is not None and self.cos_cached is not None and x.device == self.sin_cached.device and x.device == self.cos_cached.device ): sin, cos = self.sin_cached, self.cos_cached else: # compute sin and cos for the fixed positional embeddings, using the maximum possible sequence length # store as cache for future use # self.offset = offset device = x.device
inv_freq = 1.0 / ( self.base ** ( torch.arange(0, self.rotary_dim, 2, device=device) / self.rotary_dim ) ) sinusoid_inp = torch.einsum( "i , j -> i j", torch.arange(self.max_position_embeddings, device=device), inv_freq, ) sin, cos = ( torch.sin(sinusoid_inp).to(x.dtype), torch.cos(sinusoid_inp).to(x.dtype), )
sin, cos = map(_duplicate_interleave, (sin, cos))
self.sin_cached = sin self.cos_cached = cos assert ( self.max_position_embeddings >= x.shape[1] + offset ), "RoPE requires max position embeddings ({}) >= sequence length ({}) + offset ({})".format( self.max_position_embeddings, x.shape[1], offset, )
def slice_at_offset(t): return t[None, offset : x.shape[1] + offset, None, :] sin, cos = map(slice_at_offset, (sin, cos))
return sin, cos
def _apply_rotary_pos_emb(self, x, offset=0): def rotate_every_two(x): x1 = x[:, :, :, ::2] x2 = x[:, :, :, 1::2] x = torch.stack((-x2, x1), dim=-1) # in einsum notation: rearrange(x, '... d j -> ... (d j)') return x.flatten(-2)
sin, cos = self.create_fixed_pos_emb(x, offset) l = x.size(1) sin = sin[:, :l] cos = cos[:, :l]
# einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2) return (x * cos) + (rotate_every_two(x) * sin)
def rotate_tensor(self, x, offset=0): assert ( len(x.shape) == 4 ), "Tensor should be of shape [batch_size, seq_length, num_heads, head_dim] !" x_rotary = x[:, :, :, : self.rotary_dim] x_pass = x[:, :, :, self.rotary_dim :] x_rotated = self._apply_rotary_pos_emb( x_rotary, offset=offset ) x = torch.cat([x_rotated, x_pass], dim=-1) return x
class SwiGLUActivation(nn.Module): def forward(self, x1: Tensor, x2: Tensor) -> Tensor: return x1 * nn.functional.silu(x2)
class AlibiPositionEmbeddingLayer(nn.Module): def __init__(self, num_heads): super(AlibiPositionEmbeddingLayer, self).__init__()
self.num_heads = num_heads slopes = torch.tensor(AlibiPositionEmbeddingLayer._get_alibi_slopes(num_heads)).unsqueeze(-1) self.slopes = nn.parameter.Parameter(slopes, requires_grad=False)
def forward( self, seq_length, key_length, cached_qk_len, ): context_position = torch.arange( cached_qk_len, cached_qk_len + seq_length, device=self.slopes.device )[:, None] memory_position = torch.arange( key_length + cached_qk_len, device=self.slopes.device )[None, :] relative_position = memory_position - context_position relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.num_heads, -1, -1) alibi = (self.slopes * -1.0).unsqueeze(1) * relative_position return alibi
@staticmethod def _get_alibi_slopes(n): def get_slopes_power_of_2(n): start = 2 ** (-(2 ** -(math.log2(n) - 3))) ratio = start return [start * ratio**i for i in range(n)]
if math.log2(n).is_integer(): return get_slopes_power_of_2( n ) # In the paper, we only train models that have 2^a heads for some a. This function has else: # some good properties that only occur when the input is a power of 2. To maintain that even closest_power_of_2 = 2 ** math.floor( math.log2(n) ) # when the number of heads is not a power of 2, we use this workaround. return ( get_slopes_power_of_2(closest_power_of_2) + AlibiPositionEmbeddingLayer._get_alibi_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2] )
def load_tf_weights_in_crystalcoder(model, config, crystalcoder_checkpoint_path): """Load tf checkpoints in a pytorch model""" try: import re
import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise tf_path = os.path.abspath(crystalcoder_checkpoint_path) logger.info(f"Converting TensorFlow checkpoint from {tf_path}") # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array.squeeze())
for name, array in zip(names, arrays): name = name[6:] # skip "model/" name = name.split("/") pointer = model for m_name in name: if re.fullmatch(r"[A-Za-z]+\d+", m_name): scope_names = re.split(r"(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] == "w" or scope_names[0] == "g": pointer = getattr(pointer, "weight") elif scope_names[0] == "b": pointer = getattr(pointer, "bias") elif scope_names[0] == "wpe" or scope_names[0] == "wte": pointer = getattr(pointer, scope_names[0]) pointer = getattr(pointer, "weight") else: pointer = getattr(pointer, scope_names[0]) if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) return model
class CrystalCoderAttention(nn.Module): def __init__(self, config, is_cross_attention=False, layer_idx=None): super().__init__()
max_positions = config.max_position_embeddings self.register_buffer( "bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view( 1, 1, max_positions, max_positions ), persistent=False, ) self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.embed_dim // self.num_heads self.split_size = self.embed_dim if self.head_dim * self.num_heads != self.embed_dim: raise ValueError( f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads})." ) if config.position_embedding_type == "rotary": rotary_dim = config.rotary_dim or self.head_dim self.rope_helper = RotaryPositionEmbeddingHelper(max_positions, rotary_dim) else: self.rope_helper = None
self.scale_attn_weights = config.scale_attn_weights self.is_cross_attention = is_cross_attention
# Layer-wise attention scaling, reordering, and upcasting self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx self.layer_idx = layer_idx self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
if self.is_cross_attention: self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim) self.q_attn = Conv1D(self.embed_dim, self.embed_dim) else: self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim) self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
self.attn_dropout = nn.Dropout(config.attn_pdrop) self.resid_dropout = nn.Dropout(config.resid_pdrop)
self.pruned_heads = set()
self.attn_scale_power = 1.0 if config.mup_scale_qk_dot_by_d else 0.5
def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads) index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
# Prune conv1d layers self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1) self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
# Update hyper params self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads)) self.num_heads = self.num_heads - len(heads) self.pruned_heads = self.pruned_heads.union(heads)
def _attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None): attn_weights = torch.matmul(query, key.transpose(-1, -2))
if self.scale_attn_weights: attn_weights = attn_weights / torch.full( [], value.size(-1) ** self.attn_scale_power, dtype=attn_weights.dtype, device=attn_weights.device )
# Layer-wise attention scaling if self.scale_attn_by_inverse_layer_idx: attn_weights = attn_weights / float(self.layer_idx + 1)
if not self.is_cross_attention: # if only "normal" attention layer implements causal mask query_length, key_length = query.size(-2), key.size(-2) causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length] mask_value = torch.finfo(attn_weights.dtype).min # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`. # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device` mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device) attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
if attention_mask is not None: # Apply the attention mask attn_weights = attn_weights + attention_mask
if position_bias is not None: attn_weights += position_bias.type_as(attn_weights).unsqueeze(0) attn_weights = nn.functional.softmax(attn_weights, dim=-1)
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise attn_weights = attn_weights.type(value.dtype) attn_weights = self.attn_dropout(attn_weights)
# Mask heads if we want to if head_mask is not None: attn_weights = attn_weights * head_mask
attn_output = torch.matmul(attn_weights, value)
return attn_output, attn_weights
def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None): # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM) bsz, num_heads, q_seq_len, dk = query.size() _, _, k_seq_len, _ = key.size()
# Preallocate attn_weights for `baddbmm` attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
# Compute Scale Factor scale_factor = 1.0 if self.scale_attn_weights: scale_factor /= float(value.size(-1)) ** self.attn_scale_power
if self.scale_attn_by_inverse_layer_idx: scale_factor /= float(self.layer_idx + 1)
# Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk)) with autocast(enabled=False): q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len) attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor) attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
if not self.is_cross_attention: # if only "normal" attention layer implements causal mask query_length, key_length = query.size(-2), key.size(-2) causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length] mask_value = torch.finfo(attn_weights.dtype).min # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`. # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device` mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device) attn_weights = torch.where(causal_mask, attn_weights, mask_value)
if attention_mask is not None: # Apply the attention mask attn_weights = attn_weights + attention_mask
if position_bias is not None: attn_weights += position_bias.type_as(attn_weights).unsqueeze(0) attn_weights = nn.functional.softmax(attn_weights, dim=-1)
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise if attn_weights.dtype != torch.float32: raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32") attn_weights = attn_weights.type(value.dtype) attn_weights = self.attn_dropout(attn_weights)
# Mask heads if we want to if head_mask is not None: attn_weights = attn_weights * head_mask
attn_output = torch.matmul(attn_weights, value)
return attn_output, attn_weights
def _split_heads(self, tensor, num_heads, attn_head_size): """ Splits hidden_size dim into attn_head_size and num_heads """ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size) tensor = tensor.view(new_shape) return tensor
def _merge_heads(self, tensor, num_heads, attn_head_size): """ Merges attn_head_size dim and num_attn_heads dim into hidden_size """ tensor = tensor.permute(0, 2, 1, 3).contiguous() new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,) return tensor.view(new_shape)
def forward( self, hidden_states: Optional[Tuple[torch.FloatTensor]], layer_past: Optional[Tuple[torch.Tensor]] = None, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = False, output_attentions: Optional[bool] = False, position_bias: Optional[torch.FloatTensor] = None, ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]: if encoder_hidden_states is not None: if not hasattr(self, "q_attn"): raise ValueError( "If class is used as cross attention, the weights `q_attn` have to be defined. " "Please make sure to instantiate class with `CrystalCoderAttention(..., is_cross_attention=True)`." )
query = self.q_attn(hidden_states) key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2) attention_mask = encoder_attention_mask else: query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
query = self._split_heads(query, self.num_heads, self.head_dim) key = self._split_heads(key, self.num_heads, self.head_dim) value = self._split_heads(value, self.num_heads, self.head_dim)
# apply rope and transpose if self.rope_helper is not None: len_past = (layer_past and layer_past[0].size(-2)) or 0 query = self.rope_helper.rotate_tensor(query, offset=len_past) key = self.rope_helper.rotate_tensor(key, offset=len_past) query = query.transpose(1, 2) key = key.transpose(1, 2) value = value.transpose(1, 2)
if layer_past is not None: past_key, past_value = layer_past key = torch.cat((past_key, key), dim=-2) value = torch.cat((past_value, value), dim=-2)
if use_cache is True: present = (key, value) else: present = None
if self.reorder_and_upcast_attn: attn_output, attn_weights = self._upcast_and_reordered_attn( query, key, value, attention_mask, head_mask, position_bias ) else: attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask, position_bias)
attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim) attn_output = self.c_proj(attn_output) attn_output = self.resid_dropout(attn_output)
outputs = (attn_output, present) if output_attentions: outputs += (attn_weights,)
return outputs # a, present, (attentions)
class CrystalCoderMLP(nn.Module): def __init__(self, intermediate_size, config): super().__init__() embed_dim = config.hidden_size self.swiglu = config.activation_function == "swiglu" self.c_fc = Conv1D(intermediate_size, embed_dim) self.c_fc2 = Conv1D(intermediate_size, embed_dim) if self.swiglu else None self.c_proj = Conv1D(embed_dim, intermediate_size) self.act = SwiGLUActivation() if self.swiglu else ACT2FN[config.activation_function] self.dropout = nn.Dropout(config.resid_pdrop)
def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor: if self.swiglu: hidden_states2 = self.c_fc2(hidden_states) hidden_states = self.c_fc(hidden_states) hidden_states = self.act(hidden_states, hidden_states2) if self.swiglu else self.act(hidden_states) hidden_states = self.c_proj(hidden_states) hidden_states = self.dropout(hidden_states) return hidden_states
class CrystalCoderBlock(nn.Module): def __init__(self, config, layer_idx=None): super().__init__() hidden_size = config.hidden_size inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon) self.attn = CrystalCoderAttention(config, layer_idx=layer_idx) self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
if config.add_cross_attention: self.crossattention = CrystalCoderAttention(config, is_cross_attention=True, layer_idx=layer_idx) self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
self.mlp = CrystalCoderMLP(inner_dim, config)
def forward( self, hidden_states: Optional[Tuple[torch.FloatTensor]], layer_past: Optional[Tuple[torch.Tensor]] = None, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = False, output_attentions: Optional[bool] = False, position_bias: Optional[torch.FloatTensor] = None, ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]: residual = hidden_states hidden_states = self.ln_1(hidden_states) attn_outputs = self.attn( hidden_states, layer_past=layer_past, attention_mask=attention_mask, head_mask=head_mask, use_cache=use_cache, output_attentions=output_attentions, position_bias=position_bias, ) attn_output = attn_outputs[0] # output_attn: a, present, (attentions) outputs = attn_outputs[1:] # residual connection hidden_states = attn_output + residual
if encoder_hidden_states is not None: # add one self-attention block for cross-attention if not hasattr(self, "crossattention"): raise ValueError( f"If `encoder_hidden_states` are passed, {self} has to be instantiated with " "cross-attention layers by setting `config.add_cross_attention=True`" ) residual = hidden_states hidden_states = self.ln_cross_attn(hidden_states) cross_attn_outputs = self.crossattention( hidden_states, attention_mask=attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions, position_bias=position_bias, ) attn_output = cross_attn_outputs[0] # residual connection hidden_states = residual + attn_output outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
residual = hidden_states hidden_states = self.ln_2(hidden_states) feed_forward_hidden_states = self.mlp(hidden_states) # residual connection hidden_states = residual + feed_forward_hidden_states
if use_cache: outputs = (hidden_states,) + outputs else: outputs = (hidden_states,) + outputs[1:]
return outputs # hidden_states, present, (attentions, cross_attentions)
class CrystalCoderPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """
config_class = CrystalCoderConfig load_tf_weights = load_tf_weights_in_crystalcoder base_model_prefix = "transformer" is_parallelizable = True supports_gradient_checkpointing = True _no_split_modules = ["CrystalCoderBlock"] _skip_keys_device_placement = "past_key_values"
def __init__(self, *inputs, **kwargs): super().__init__(*inputs, **kwargs)
def _init_weights(self, module): """Initialize the weights.""" mup_init_scale = math.sqrt(self.config.mup_width_scale) if isinstance(module, (nn.Linear, Conv1D)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=(self.config.initializer_range * mup_init_scale)) 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)
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. # > -- GPT-2 :: https://openai.com/blog/better-language-models/ # # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py for name, p in module.named_parameters(): if name == "c_proj.weight": # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block stddev = self.config.initializer_range * mup_init_scale / math.sqrt(2 * self.config.n_layer) p.data.normal_(mean=0.0, std=stddev)
def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, CrystalCoderModel): module.gradient_checkpointing = value
def get_mup_param_groups(self, lr, weight_decay=0.0, decoupled_wd=True): """ Returns list of dicts defining parameter groups for muP: group 0: most model params get scaled learning rate and weight decay. group 1: embedding layer gets non-scaled learning rate and weight decay. group 2: normalization layers and biases get non-scaled learning rate only.
The output can be passed to Adam-base optimizers e.g. param_groups = model.get_mup_param_groups(lr=1e-3, weight_decay=0.1) torch.optim.AdamW(param_groups, betas=(0.9, 0.95), eps=1e-8) """ norm_modules = ( torch.nn.LayerNorm, torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.GroupNorm, torch.nn.SyncBatchNorm, torch.nn.LocalResponseNorm, )
def get_group_index(param_name): for name, module in self.named_modules(): if name in param_name: if isinstance(module, norm_modules): return 2 elif isinstance(module, torch.nn.Embedding): return 1 return 0
width_scale = self.config.mup_width_scale new_param_groups = [] new_param_groups.append({"params": [], "lr": lr * width_scale, "weight_decay": weight_decay}) if not decoupled_wd: new_param_groups[0]["weight_decay"] /= width_scale new_param_groups.append({"params": [], "lr": lr, "weight_decay": weight_decay}) new_param_groups.append({"params": [], "lr": lr, "weight_decay": 0.0})
for name, param in self.named_parameters(): if not param.requires_grad: continue
if name.endswith("bias"): new_param_groups[2]["params"].append(param) else: new_param_groups[get_group_index(name)]["params"].append(param)
for idx, param_group in enumerate(new_param_groups): if len(param_group["params"]) == 0: del new_param_groups[idx]
return new_param_groups
CrystalCoder_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Parameters: config ([`CrystalCoderConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights."""
CrystalCoder_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as `input_ids`.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids) past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`): Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have their past given to this model should not be passed as `input_ids` as they have already been computed. attention_mask (`torch.FloatTensor` 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**.
If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for `past_key_values`. In other words, the `attention_mask` always has to have the length: `len(past_key_values) + len(input_ids)`
[What are attention masks?](../glossary#attention-mask) token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
- 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids) 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.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids) head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**, - 0 indicates the head is **masked**.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see `past_key_values`). use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""PARALLELIZE_DOCSTRING = r""" This is an experimental feature and is a subject to change at a moment's notice.
Uses a device map to distribute attention modules of the model across several devices. If no device map is given, it will evenly distribute blocks across all devices.
Args: device_map (`Dict[int, list]`, optional, defaults to None): A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always automatically mapped to the first device (for esoteric reasons). That means that the first device should have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the following number of attention modules:
- gpt2: 12 - gpt2-medium: 24 - gpt2-large: 36 - gpt2-xl: 48
Example:
```python # Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules: model = GPT2LMHeadModel.from_pretrained("gpt2-xl") device_map = { 0: [0, 1, 2, 3, 4, 5, 6, 7, 8], 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34], 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47], } model.parallelize(device_map) ```"""DEPARALLELIZE_DOCSTRING = r""" Moves the model to cpu from a model parallel state.
Example:
```python # On a 4 GPU machine with gpt2-large: model = GPT2LMHeadModel.from_pretrained("gpt2-large") device_map = { 0: [0, 1, 2, 3, 4, 5, 6, 7], 1: [8, 9, 10, 11, 12, 13, 14, 15], 2: [16, 17, 18, 19, 20, 21, 22, 23], 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35], } model.parallelize(device_map) # Splits the model across several devices model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache() ```"""
@add_start_docstrings( "The bare CrystalCoder Model transformer outputting raw hidden-states without any specific head on top.", CrystalCoder_START_DOCSTRING,)class CrystalCoderModel(CrystalCoderPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
def __init__(self, config): super().__init__(config)
self.embed_dim = config.hidden_size
self.wte = nn.Embedding(config.vocab_size, self.embed_dim) self.wpe = ( nn.Embedding(config.max_position_embeddings, self.embed_dim) if config.position_embedding_type == "learned" else None ) self.embeddings_scale = config.mup_embeddings_scale
self.drop = nn.Dropout(config.embd_pdrop) self.h = nn.ModuleList([CrystalCoderBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)]) self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
self.relative_pe = ( AlibiPositionEmbeddingLayer(config.num_attention_heads) if config.position_embedding_type == "alibi" else None )
# Model parallel self.model_parallel = False self.device_map = None self.gradient_checkpointing = False
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings(PARALLELIZE_DOCSTRING) def parallelize(self, device_map=None): # Check validity of device_map warnings.warn( "`CrystalCoderModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your" " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own" " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1," " ...}", FutureWarning, ) self.device_map = ( get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map ) assert_device_map(self.device_map, len(self.h)) self.model_parallel = True self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys())) self.last_device = "cuda:" + str(max(self.device_map.keys())) self.wte = self.wte.to(self.first_device) if self.wpe is not None: self.wpe = self.wpe.to(self.first_device) # Load onto devices for k, v in self.device_map.items(): for block in v: cuda_device = "cuda:" + str(k) self.h[block] = self.h[block].to(cuda_device) # ln_f to last self.ln_f = self.ln_f.to(self.last_device)
@add_start_docstrings(DEPARALLELIZE_DOCSTRING) def deparallelize(self): warnings.warn( "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.", FutureWarning, ) self.model_parallel = False self.device_map = None self.first_device = "cpu" self.last_device = "cpu" self.wte = self.wte.to("cpu") if self.wpe is not None: self.wpe = self.wpe.to("cpu") for index in range(len(self.h)): self.h[index] = self.h[index].to("cpu") self.ln_f = self.ln_f.to("cpu") torch.cuda.empty_cache()
def get_input_embeddings(self): return self.wte
def set_input_embeddings(self, new_embeddings): self.wte = new_embeddings
def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} """ for layer, heads in heads_to_prune.items(): self.h[layer].attn.prune_heads(heads)
@add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING) def forward( self, input_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) batch_size = input_ids.shape[0] elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] batch_size = inputs_embeds.shape[0] else: raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if token_type_ids is not None: token_type_ids = token_type_ids.view(-1, input_shape[-1]) if position_ids is not None: position_ids = position_ids.view(-1, input_shape[-1])
if past_key_values is None: past_length = 0 past_key_values = tuple([None] * len(self.h)) else: past_length = past_key_values[0][0].size(-2) if position_ids is None: position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device) position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
# CrystalCoderAttention mask. if attention_mask is not None: if batch_size <= 0: raise ValueError("batch_size has to be defined and > 0") attention_mask = attention_mask.view(batch_size, -1) # We create a 3D attention mask from a 2D tensor mask. # Sizes are [batch_size, 1, 1, to_seq_length] # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length] # this attention mask is more simple than the triangular masking of causal attention # used in OpenAI GPT, we just need to prepare the broadcast dimension here. attention_mask = attention_mask[:, None, None, :]
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and the dtype's smallest value for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
# If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.add_cross_attention and encoder_hidden_states is not None: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_attention_mask = None
# Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # head_mask has shape n_layer x batch x n_heads x N x N head_mask = self.get_head_mask(head_mask, self.config.n_layer)
if inputs_embeds is None: inputs_embeds = self.wte(input_ids) if self.wpe is not None: position_embeds = self.wpe(position_ids) hidden_states = inputs_embeds + position_embeds else: hidden_states = inputs_embeds hidden_states *= torch.tensor( float(self.embeddings_scale), dtype=hidden_states.dtype, device=hidden_states.device )
if token_type_ids is not None: token_type_embeds = self.wte(token_type_ids) hidden_states = hidden_states + token_type_embeds
hidden_states = self.drop(hidden_states)
if self.relative_pe is not None: length = input_ids.shape[1] cached_kv_length = 0 cached_kv = past_key_values[0] if cached_kv is not None: cached_kv_length = cached_kv[0].shape[-2] position_bias = self.relative_pe(length, length, cached_kv_length) else: position_bias = None
output_shape = input_shape + (hidden_states.size(-1),)
if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False
presents = () if use_cache else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None all_hidden_states = () if output_hidden_states else None for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)): # Model parallel if self.model_parallel: torch.cuda.set_device(hidden_states.device) # Ensure layer_past is on same device as hidden_states (might not be correct) if layer_past is not None: layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past) # Ensure that attention_mask is always on the same device as hidden_states if attention_mask is not None: attention_mask = attention_mask.to(hidden_states.device) if isinstance(head_mask, torch.Tensor): head_mask = head_mask.to(hidden_states.device) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,)
if self.gradient_checkpointing and self.training:
def create_custom_forward(module): def custom_forward(*inputs): # None for past_key_value return module(*inputs, use_cache, output_attentions)
return custom_forward
outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(block), hidden_states, None, attention_mask, head_mask[i], encoder_hidden_states, encoder_attention_mask, ) else: outputs = block( hidden_states, layer_past=layer_past, attention_mask=attention_mask, head_mask=head_mask[i], encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=use_cache, output_attentions=output_attentions, position_bias=position_bias, )
hidden_states = outputs[0] if use_cache is True: presents = presents + (outputs[1],)
if output_attentions: all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],) if self.config.add_cross_attention: all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
# Model Parallel: If it's the last layer for that device, put things on the next device if self.model_parallel: for k, v in self.device_map.items(): if i == v[-1] and "cuda:" + str(k) != self.last_device: hidden_states = hidden_states.to("cuda:" + str(k + 1))
hidden_states = self.ln_f(hidden_states)
hidden_states = hidden_states.view(output_shape) # Add last hidden state if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict: return tuple( v for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions] if v is not None )
return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, )
@add_start_docstrings( """ The CrystalCoder Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). """, CrystalCoder_START_DOCSTRING,)class CrystalCoderLMHeadModel(CrystalCoderPreTrainedModel): _keys_to_ignore_on_load_missing = [r"lm_head.weight"] _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
def __init__(self, config): super().__init__(config) self.transformer = CrystalCoderModel(config) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
# Model parallel self.model_parallel = False self.device_map = None
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings(PARALLELIZE_DOCSTRING) def parallelize(self, device_map=None): warnings.warn( "`CrystalCoderLMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load" " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own" " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':" " 0, 'transformer.h.1': 1, ...}", FutureWarning, ) self.device_map = ( get_device_map(len(self.transformer.h), range(torch.cuda.device_count())) if device_map is None else device_map ) assert_device_map(self.device_map, len(self.transformer.h)) self.transformer.parallelize(self.device_map) self.lm_head = self.lm_head.to(self.transformer.first_device) self.model_parallel = True
@add_start_docstrings(DEPARALLELIZE_DOCSTRING) def deparallelize(self): warnings.warn( "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.", FutureWarning, ) self.transformer.deparallelize() self.transformer = self.transformer.to("cpu") self.lm_head = self.lm_head.to("cpu") self.model_parallel = False torch.cuda.empty_cache()
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): token_type_ids = kwargs.get("token_type_ids", None) # only last token for inputs_ids if past is defined in kwargs if past_key_values: input_ids = input_ids[:, -1].unsqueeze(-1) if token_type_ids is not None: token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
attention_mask = kwargs.get("attention_mask", None) position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: position_ids = position_ids[:, -1].unsqueeze(-1) else: position_ids = None
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids}
model_inputs.update( { "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "position_ids": position_ids, "attention_mask": attention_mask, "token_type_ids": token_type_ids, } ) return model_inputs
@add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING) def forward( self, input_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: 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, CausalLMOutputWithCrossAttentions]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0]
# Set device for model parallelism if self.model_parallel: torch.cuda.set_device(self.transformer.first_device) hidden_states = hidden_states.to(self.lm_head.weight.device)
lm_logits = self.lm_head(hidden_states) lm_logits *= torch.tensor(float(self.output_logits_scale), dtype=lm_logits.dtype, device=lm_logits.device)
loss = None if labels is not None: # move labels to correct device to enable model parallelism labels = labels.to(lm_logits.device) # Shift so that tokens < n predict n shift_logits = lm_logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict: output = (lm_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithCrossAttentions( loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, cross_attentions=transformer_outputs.cross_attentions, )
@staticmethod def _reorder_cache( past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor ) -> Tuple[Tuple[torch.Tensor]]: """ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct beam_idx at every generation step. """ return tuple( tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past) for layer_past in past_key_values )
@add_start_docstrings( """ The CrystalCoder Model transformer with a sequence classification head on top (linear layer).
[`CrystalCoderForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-1) do.
Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, CrystalCoder_START_DOCSTRING,)class CrystalCoderForSequenceClassification(CrystalCoderPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = CrystalCoderModel(config) self.score = nn.Linear(config.n_embd, self.num_labels, bias=False) self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
# Model parallel self.model_parallel = False self.device_map = None
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING) @add_code_sample_docstrings( checkpoint="microsoft/DialogRPT-updown", output_type=SequenceClassifierOutputWithPast, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, SequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, 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) logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
if input_ids is not None: batch_size, sequence_length = input_ids.shape[:2] else: batch_size, sequence_length = inputs_embeds.shape[:2]
assert ( self.config.pad_token_id is not None or batch_size == 1 ), "Cannot handle batch sizes > 1 if no padding token is defined." if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device) else: sequence_lengths = -1 logger.warning( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" )
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )
@add_start_docstrings( """ CrystalCoder Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, CrystalCoder_START_DOCSTRING,)class CrystalCoderForTokenClassification(CrystalCoderPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels
self.transformer = CrystalCoderModel(config) if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None: classifier_dropout = config.classifier_dropout elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None: classifier_dropout = config.hidden_dropout else: classifier_dropout = 0.1 self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
# Model parallel self.model_parallel = False self.device_map = None
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING) # fmt: off @add_code_sample_docstrings( checkpoint="brad1141/gpt2-finetuned-comp2", output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, expected_loss=0.25, expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"], ) # fmt: on def forward( self, input_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[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, TokenClassifierOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, 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] hidden_states = self.dropout(hidden_states) logits = self.classifier(hidden_states) logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
loss = None if labels is not None: labels = labels.to(logits.device) loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict: output = (logits,) + transformer_outputs[2:] return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )
@add_start_docstrings( """ The CrystalCoder Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`). """, CrystalCoder_START_DOCSTRING,)class CrystalCoderForQuestionAnswering(CrystalCoderPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = CrystalCoderModel(config) self.qa_outputs = nn.Linear(config.hidden_size, 2) self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
# Model parallel self.model_parallel = False self.device_map = None self.gradient_checkpointing = False
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING.format("batch_size, sequence_length")) def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, QuestionAnsweringModelOutput]: r""" start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.transformer( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output) logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1).to(start_logits.device) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1).to(end_logits.device) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2
if not return_dict: output = (start_logits, end_logits) + outputs[2:] return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )123version https://git-lfs.github.com/spec/v1oid sha256:ebe6b5c1fde84d667aa5c38d505b4e9497a32cbf0bb942ade7cffb4057ac7db2size 7812180971123version https://git-lfs.github.com/spec/v1oid sha256:1837d1c91c7f82e62551ba466ccea119d85808478e71e53983a1fe45f29a36d8size 7918113181123version https://git-lfs.github.com/spec/v1oid sha256:3015eb5d2a135c4c262d666c166f0b08deaae921cdc4565eef0cdc40dea04f68size 7918085829123version https://git-lfs.github.com/spec/v1oid sha256:96a8491eb3eb6b39cb9143cd6c1c8d5f3a49603db520796a490e15fc2ccc7dfdsize 3311921344123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523{ "metadata": { "total_size": 26960145024 }, "weight_map": { "transformer.wte.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.0.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.0.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.1.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.1.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.1.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.1.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.1.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.1.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.1.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.1.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.2.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.2.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.2.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.2.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.2.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.2.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.2.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.2.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.3.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.3.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.3.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.3.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.3.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.3.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.3.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.3.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.4.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.4.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.4.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.4.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.4.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.4.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.4.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.4.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.5.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.5.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.5.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.5.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.5.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.5.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.5.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.5.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.6.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.6.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.6.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.6.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.6.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.6.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.6.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.6.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.7.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.7.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.7.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.7.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.7.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.7.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.7.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.7.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.attn.c_attn.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.8.attn.c_attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.attn.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.attn.masked_bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.attn.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.8.attn.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.ln_1.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.8.ln_1.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.ln_2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.8.ln_2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.mlp.c_fc.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.8.mlp.c_fc.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.mlp.c_fc2.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.8.mlp.c_fc2.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.8.mlp.c_proj.weight": "pytorch_model-00001-of-00004.bin", "transformer.h.8.mlp.c_proj.bias": "pytorch_model-00001-of-00004.bin", "transformer.h.9.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.9.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.9.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.9.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.9.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.9.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.9.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.9.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.9.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.10.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.10.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.10.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.10.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.10.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.10.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.10.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.10.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.11.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.11.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.11.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.11.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.11.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.11.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.11.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.11.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.12.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.12.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.12.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.12.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.12.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.12.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.12.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.12.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.13.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.13.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.13.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.13.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.13.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.13.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.13.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.13.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.14.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.14.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.14.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.14.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.14.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.14.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.14.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.14.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.15.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.15.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.15.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.15.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.15.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.15.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.15.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.15.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.16.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.16.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.16.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.16.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.16.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.16.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.16.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.16.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.17.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.17.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.17.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.17.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.17.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.17.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.17.mlp.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.17.mlp.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.attn.c_attn.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.18.attn.c_attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.attn.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.attn.masked_bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.attn.c_proj.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.18.attn.c_proj.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.ln_1.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.18.ln_1.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.ln_2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.18.ln_2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.mlp.c_fc.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.18.mlp.c_fc.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.mlp.c_fc2.weight": "pytorch_model-00002-of-00004.bin", "transformer.h.18.mlp.c_fc2.bias": "pytorch_model-00002-of-00004.bin", "transformer.h.18.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.18.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.19.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.19.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.19.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.19.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.19.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.19.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.19.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.19.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.20.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.20.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.20.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.20.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.20.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.20.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.20.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.20.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.21.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.21.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.21.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.21.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.21.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.21.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.21.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.21.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.22.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.22.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.22.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.22.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.22.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.22.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.22.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.22.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.23.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.23.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.23.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.23.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.23.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.23.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.23.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.23.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.24.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.24.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.24.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.24.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.24.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.24.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.24.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.24.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.25.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.25.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.25.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.25.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.25.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.25.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.25.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.25.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.26.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.26.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.26.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.26.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.26.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.26.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.26.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.26.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.27.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.27.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.27.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.27.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.27.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.mlp.c_fc2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.27.mlp.c_fc2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.27.mlp.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.27.mlp.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.attn.c_attn.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.28.attn.c_attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.attn.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.attn.masked_bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.attn.c_proj.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.28.attn.c_proj.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.ln_1.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.28.ln_1.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.ln_2.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.28.ln_2.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.mlp.c_fc.weight": "pytorch_model-00003-of-00004.bin", "transformer.h.28.mlp.c_fc.bias": "pytorch_model-00003-of-00004.bin", "transformer.h.28.mlp.c_fc2.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.28.mlp.c_fc2.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.28.mlp.c_proj.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.28.mlp.c_proj.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.attn.c_attn.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.29.attn.c_attn.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.attn.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.attn.masked_bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.attn.c_proj.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.29.attn.c_proj.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.ln_1.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.29.ln_1.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.ln_2.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.29.ln_2.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.mlp.c_fc.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.29.mlp.c_fc.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.mlp.c_fc2.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.29.mlp.c_fc2.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.29.mlp.c_proj.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.29.mlp.c_proj.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.attn.c_attn.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.30.attn.c_attn.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.attn.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.attn.masked_bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.attn.c_proj.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.30.attn.c_proj.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.ln_1.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.30.ln_1.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.ln_2.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.30.ln_2.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.mlp.c_fc.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.30.mlp.c_fc.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.mlp.c_fc2.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.30.mlp.c_fc2.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.30.mlp.c_proj.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.30.mlp.c_proj.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.attn.c_attn.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.31.attn.c_attn.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.attn.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.attn.masked_bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.attn.c_proj.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.31.attn.c_proj.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.ln_1.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.31.ln_1.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.ln_2.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.31.ln_2.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.mlp.c_fc.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.31.mlp.c_fc.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.mlp.c_fc2.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.31.mlp.c_fc2.bias": "pytorch_model-00004-of-00004.bin", "transformer.h.31.mlp.c_proj.weight": "pytorch_model-00004-of-00004.bin", "transformer.h.31.mlp.c_proj.bias": "pytorch_model-00004-of-00004.bin", "transformer.ln_f.weight": "pytorch_model-00004-of-00004.bin", "transformer.ln_f.bias": "pytorch_model-00004-of-00004.bin", "lm_head.weight": "pytorch_model-00004-of-00004.bin" }}123456789from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, AutoTokenizerfrom transformers.tokenization_utils_fast import PreTrainedTokenizerFastfrom configuration_crystalcoder import CrystalCoderConfigfrom modeling_crystalcoder import CrystalCoderModel, CrystalCoderLMHeadModel
AutoConfig.register("crystalcoder", CrystalCoderConfig)AutoModel.register(CrystalCoderConfig, CrystalCoderModel)AutoModelForCausalLM.register(CrystalCoderConfig, CrystalCoderLMHeadModel)AutoTokenizer.register(CrystalCoderConfig, fast_tokenizer_class=PreTrainedTokenizerFast)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
import osfrom shutil import copyfilefrom typing import Optional, Tuple
from tokenizers import processors
from transformers.tokenization_utils_fast import PreTrainedTokenizerFastfrom transformers.utils import is_sentencepiece_available, loggingfrom transformers.utils.versions import require_version
require_version("tokenizers>=0.13.3")
logger = logging.get_logger(__name__)VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
# fmt: offDEFAULT_SYSTEM_PROMPT = """You are CrystalCoder, a helpful and intelligent assistant. Follow the instructions and answer the questions as accurately as possible."""# fmt: on
class CrystalCoderTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES slow_tokenizer_class = None padding_side = "left" model_input_names = ["input_ids", "attention_mask"]
def __init__( self, vocab_file=None, tokenizer_file=None, clean_up_tokenization_spaces=False, unk_token="<|unk|>", bos_token="<|startoftext|>", eos_token="<|endoftext|>", add_bos_token=False, add_eos_token=False, use_default_system_prompt=False, **kwargs, ): super().__init__( vocab_file=vocab_file, tokenizer_file=tokenizer_file, clean_up_tokenization_spaces=clean_up_tokenization_spaces, unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, use_default_system_prompt=use_default_system_prompt, **kwargs, ) self._add_bos_token = add_bos_token self._add_eos_token = add_eos_token self.update_post_processor() self.use_default_system_prompt = use_default_system_prompt self.vocab_file = vocab_file
@property def can_save_slow_tokenizer(self) -> bool: return os.path.isfile(self.vocab_file) if self.vocab_file else False
def update_post_processor(self): """ Updates the underlying post processor with the current `bos_token` and `eos_token`. """ bos = self.bos_token bos_token_id = self.bos_token_id if bos is None and self.add_bos_token: raise ValueError("add_bos_token = True but bos_token = None")
eos = self.eos_token eos_token_id = self.eos_token_id if eos is None and self.add_eos_token: raise ValueError("add_eos_token = True but eos_token = None")
single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}" pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
special_tokens = [] if self.add_bos_token: special_tokens.append((bos, bos_token_id)) if self.add_eos_token: special_tokens.append((eos, eos_token_id)) self._tokenizer.post_processor = processors.TemplateProcessing( single=single, pair=pair, special_tokens=special_tokens )
@property def add_eos_token(self): return self._add_eos_token
@property def add_bos_token(self): return self._add_bos_token
@add_eos_token.setter def add_eos_token(self, value): self._add_eos_token = value self.update_post_processor()
@add_bos_token.setter def add_bos_token(self, value): self._add_bos_token = value self.update_post_processor()
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." )
if not os.path.isdir(save_directory): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return out_vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): copyfile(self.vocab_file, out_vocab_file)
return (out_vocab_file,)
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): bos_token_id = [self.bos_token_id] if self.add_bos_token else [] eos_token_id = [self.eos_token_id] if self.add_eos_token else []
output = bos_token_id + token_ids_0 + eos_token_id
if token_ids_1 is not None: output = output + bos_token_id + token_ids_1 + eos_token_id
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245{ "added_tokens_decoder": { "0": { "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "</s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32000": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32001": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32002": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32003": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32004": { "content": "<|filename|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32005": { "content": "<|gh_stars|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32006": { "content": "<|issue_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32007": { "content": "<|issue_comment|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32008": { "content": "<|issue_closed|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32009": { "content": "<|jupyter_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32010": { "content": "<|jupyter_text|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32011": { "content": "<|jupyter_code|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32012": { "content": "<|jupyter_output|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32013": { "content": "<|empty_output|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32014": { "content": "<|commit_before|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32015": { "content": "<|commit_msg|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32016": { "content": "<|commit_after|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32017": { "content": "<|reponame|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32018": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32019": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32020": { "content": "<|sys_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "32021": { "content": "<|sys_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<|fim_prefix|>", "<|fim_middle|>", "<|fim_suffix|>", "<|fim_pad|>", "<|filename|>", "<|gh_stars|>", "<|issue_start|>", "<|issue_comment|>", "<|issue_closed|>", "<|jupyter_start|>", "<|jupyter_text|>", "<|jupyter_code|>", "<|jupyter_output|>", "<|empty_output|>", "<|commit_before|>", "<|commit_msg|>", "<|commit_after|>", "<|reponame|>", "<|im_start|>", "<|im_end|>", "<|sys_start|>", "<|sys_end|>" ], "bos_token": "<s>", "clean_up_tokenization_spaces": false, "eos_token": "</s>", "legacy": false, "model_max_length": 1000000000000000019884624838656, "pad_token": null, "padding_side": "right", "sp_model_kwargs": {}, "auto_map": { "AutoTokenizer": [ null, "tokenization_crystalcoder_fast.CrystalCoderTokenizerFast" ] }, "tokenizer_class": "CrystalCoderTokenizer", "unk_token": "<unk>", "use_default_system_prompt": false}config.jsonAdded+33
configuration_crystalcoder.pyAdded+149
generation_config.jsonAdded+6
modeling_crystalcoder.pyAdded+1671
pytorch_model-00001-of-00004.binAdded+3
pytorch_model-00002-of-00004.binAdded+3
pytorch_model-00003-of-00004.binAdded+3
pytorch_model-00004-of-00004.binAdded+3
pytorch_model.bin.index.jsonAdded+523
register_crystalcoder.pyAdded+9
tokenization_crystalcoder_fast.pyAdded+139
tokenizer.jsonAdded
tokenizer_config.jsonAdded+245