Text Generation
MLX
Safetensors
English
CoDA
quantized
text-diffusion
conversational
4-bit precision
Instructions to use TiGa-RCE/CoDA-v0-Instruct-MLX-4bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use TiGa-RCE/CoDA-v0-Instruct-MLX-4bit with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("TiGa-RCE/CoDA-v0-Instruct-MLX-4bit") prompt = "Write a story about Einstein" messages = [{"role": "user", "content": prompt}] prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True ) text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use TiGa-RCE/CoDA-v0-Instruct-MLX-4bit with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit"
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit" } ] } } }Run Pi
# Start Pi in your project directory: pi
- MLX LM
How to use TiGa-RCE/CoDA-v0-Instruct-MLX-4bit with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Interactive chat REPL mlx_lm.chat --model "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit"
Run an OpenAI-compatible server
# Install MLX LM uv tool install mlx-lm # Start the server mlx_lm.server --model "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit" # Calling the OpenAI-compatible server with curl curl -X POST "http://localhost:8080/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit", "messages": [ {"role": "user", "content": "Hello"} ] }' - Hermes Agent
How to use TiGa-RCE/CoDA-v0-Instruct-MLX-4bit with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default TiGa-RCE/CoDA-v0-Instruct-MLX-4bit
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use TiGa-RCE/CoDA-v0-Instruct-MLX-4bit with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "TiGa-RCE/CoDA-v0-Instruct-MLX-4bit" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Add files using upload-large-folder tool
Browse filesFiles changed (13)
- .gitattributes+1
- attention.pyAdded+90
- chat_template.jinjaAdded+89
- config.jsonAdded+65
- generation_config.jsonAdded+12
- generation_utils.pyAdded+552
- model.safetensorsAdded+3
- model.safetensors.index.jsonAdded+715
- model_config.pyAdded+91
- modeling_coda.pyAdded+558
- modeling_utils.pyAdded+224
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+19
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import mathfrom typing import Any
import torchfrom torch import nnfrom torch.nn.functional import scaled_dot_product_attentionfrom torch.nn.attention import SDPBackend, sdpa_kernelfrom .model_config import CoDAConfig
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand( batch, num_key_value_heads, n_rep, slen, head_dim ) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
class AttentionModule(nn.Module): def __init__(self, config: CoDAConfig, kernel_config: dict[str, Any] | None = None): super().__init__() self.config = config self.kernel_config = kernel_config self.partition_spec = None
def forward( self, query_states: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, attention_mask: torch.Tensor | None = None, ): """GPU-optimized PyTorch implementation"""
if self.config.attention_kernel != "splash_attention": num_key_value_groups = ( self.config.num_attention_heads // self.config.num_key_value_heads ) key_states = repeat_kv(key_states, num_key_value_groups) value_states = repeat_kv(value_states, num_key_value_groups)
bsz, num_heads, q_len, head_dim = query_states.size() head_dim = value_states.shape[-1] kv_seq_len = key_states.shape[-2]
# Use SDPA with appropriate backend match self.config.attention_kernel: case "splash_attention": raise NotImplementedError( "Splash Attention is not supported in GPU environment" )
case "flash_attention": # Try to use flash attention backend, fallback to default if not available with sdpa_kernel(SDPBackend.FLASH_ATTENTION): attn_output = scaled_dot_product_attention( query_states, key_states, value_states, dropout_p=( self.config.attention_dropout if self.training else 0.0 ), is_causal=False, # weiran: causal=False for bi-directional attention ) case _: # Default implementation - use math backend for compatibility with sdpa_kernel(SDPBackend.MATH): attn_output = scaled_dot_product_attention( query_states, key_states, value_states, dropout_p=( self.config.attention_dropout if self.training else 0.0 ), is_causal=False, # weiran: causal=False for bi-directional attention )
if attn_output.size() != (bsz, num_heads, q_len, head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, num_heads, q_len, head_dim)}, but is" f" {attn_output.size()}" ) return attn_output1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0].role == 'system' %} {{- messages[0].content + '\n\n' }} {%- endif %} {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}{%- else %} {%- if messages[0].role == 'system' %} {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %}{%- endfor %}{%- for message in messages %} {%- if message.content is string %} {%- set content = message.content %} {%- else %} {%- set content = '' %} {%- endif %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if loop.index0 > ns.last_query_index %} {%- if loop.last or (not loop.last and reasoning_content) %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- if message.tool_calls %} {%- for tool_call in message.tool_calls %} {%- if (loop.first and content) or (not loop.first) %} {{- '\n' }} {%- endif %} {%- if tool_call.function %} {%- set tool_call = tool_call.function %} {%- endif %} {{- '<tool_call>\n{"name": "' }} {{- tool_call.name }} {{- '", "arguments": ' }} {%- if tool_call.arguments is string %} {{- tool_call.arguments }} {%- else %} {{- tool_call.arguments | tojson }} {%- endif %} {{- '}\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} {{- '<|im_end|>\n' }} {%- endif %} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- endif %}{%- endif %}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465{ "architectures": [ "CoDALanguageModel" ], "attention_bias": false, "attention_dropout": 0.0, "attention_kernel": "flash_attention", "block_masking_probability": [ 0.25, 0.5, 0.5, 0.75, 0.25 ], "head_dim": 128, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 6144, "mask_block_sizes": [ 4, 8, 16, 32 ], "mask_token_id": 151669, "max_position_embeddings": 40960, "max_window_layers": 28, "mlx_runtime_architecture": "qwen3-layout-bidirectional-diffusion", "model_type": "CoDA", "num_attention_heads": 16, "num_hidden_layers": 28, "num_key_value_heads": 8, "pad_token_id": 151643, "prefix_probability": 0, "quantization": { "group_size": 64, "bits": 4, "mode": "affine" }, "quantization_config": { "group_size": 64, "bits": 4, "mode": "affine" }, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sampling_eps": [ 0.001, 0.25, 0.5, 0.25, 0.001 ], "sliding_window": null, "source_revision": "f2d40ce1282766e2c9fbf5ca62c611817164a246", "tie_word_embeddings": false, "torch_dtype": "float32", "transformers_version": "4.47.1", "truncate_probability": 0, "use_cache": true, "use_sliding_window": false, "vocab_size": 151936}123456789101112{ "alg": "origin", "alg_temp": null, "eps": 0.001, "mask_token_id": 151669, "output_history": false, "steps": 512, "temperature": 0.0, "top_k": null, "top_p": null, "transformers_version": "4.47.1"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552"""Adapted from https://huggingface.co/Dream-org/Dream-v0-Instruct-7B"""
# coding=utf-8# Copyright 2024 The Dream team, HKUNLP Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import warningsimport copyfrom dataclasses import dataclassfrom typing import Any, Dict, Optional, Tuple, Union
import torchimport torch.distributions as distsfrom torch.nn import functional as Ffrom transformers import __version__from transformers.generation.configuration_utils import GenerationConfigfrom transformers.utils import ( ModelOutput, is_torchdynamo_compiling, logging,)
logger = logging.get_logger(__name__)
def top_p_logits(logits, top_p=None): sorted_logits, sorted_indices = torch.sort(logits, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) sorted_indices_to_remove = cumulative_probs > top_p # Shift the indices to the right to keep the first token above the threshold sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0
mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device) mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove) logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min) return logits
def top_k_logits(logits, top_k=None): top_k = min(top_k, logits.size(-1)) # Safety check # Remove all tokens with a probability less than the last token of the top-k indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min) return logits
def sample_tokens( logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False,):
if temperature > 0: logits = logits / temperature if top_p is not None and top_p < 1: logits = top_p_logits(logits, top_p) if top_k is not None: logits = top_k_logits(logits, top_k) probs = torch.softmax(logits, dim=-1)
if temperature > 0: try: x0 = dists.Categorical(probs=probs).sample() confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1) except: confidence, x0 = probs.max(dim=-1) else: confidence, x0 = probs.max(dim=-1)
if margin_confidence: sorted_probs, _ = torch.sort(probs, dim=-1, descending=True) # Extract top1 and top2 probabilities top1_probs = sorted_probs[:, 0] top2_probs = sorted_probs[:, 1] # Calculate confidence as top1 - top2 confidence = top1_probs - top2_probs
if neg_entropy: epsilon = 1e-10 log_probs = torch.log(probs + epsilon) confidence = torch.sum(probs * log_probs, dim=-1)
return confidence, x0
@dataclassclass DLMModelOutput(ModelOutput): sequences: torch.LongTensor = None history: Optional[Tuple[torch.FloatTensor]] = None
class DLMGenerationConfig(GenerationConfig): def __init__(self, **kwargs): self.temperature: float = kwargs.pop("temperature", 0.0) self.top_p: Optional[float] = kwargs.pop("top_p", None) self.top_k: Optional[int] = kwargs.pop("top_k", None) self.max_length = kwargs.pop("max_length", 20) self.max_new_tokens = kwargs.pop("max_new_tokens", None) # diffusion specific params self.eps: float = kwargs.pop("eps", 1e-3) self.steps: int = kwargs.pop("steps", 512) self.alg: str = kwargs.pop("alg", "origin") self.alg_temp: Optional[float] = kwargs.pop("alg_temp", None)
# Parameters that define the output variables of `generate` self.num_return_sequences: int = kwargs.pop("num_return_sequences", 1) self.return_dict_in_generate: bool = kwargs.pop( "return_dict_in_generate", False ) self.output_history: bool = kwargs.pop("output_history", False)
# Special tokens that can be used at generation time self.mask_token_id = kwargs.pop("mask_token_id", None) self.pad_token_id = kwargs.pop("pad_token_id", None) self.bos_token_id = kwargs.pop("bos_token_id", None) self.eos_token_id = kwargs.pop("eos_token_id", None)
# Wild card self.generation_kwargs = kwargs.pop("generation_kwargs", {})
# The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub # interface. self._from_model_config = kwargs.pop("_from_model_config", False) self._commit_hash = kwargs.pop("_commit_hash", None) self.transformers_version = kwargs.pop("transformers_version", __version__)
# Additional attributes without default values if not self._from_model_config: # we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a # model's default configuration file for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err
# Validate the values of the attributes self.validate(is_init=True)
def validate(self, is_init=False): pass
class DLMGenerationMixin: @staticmethod def _expand_inputs_for_generation( expand_size: int = 1, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, ) -> Tuple[torch.LongTensor, Dict[str, Any]]: """Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]""" # Do not call torch.repeat_interleave if expand_size is 1 because it clones # the input tensor and thus requires more memory although no change is applied if expand_size == 1: return input_ids, attention_mask if input_ids is not None: input_ids = input_ids.repeat_interleave(expand_size, dim=0) if attention_mask is not None: attention_mask = attention_mask.repeat_interleave(expand_size, dim=0) return input_ids, attention_mask
def _validate_generated_length( self, generation_config, input_ids_length, has_default_max_length ): """Performs validation related to the resulting generated length"""
# Can't throw warnings/exceptions during compilation if is_torchdynamo_compiling(): return
# 1. Max length warnings related to poor parameterization if ( has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20 ): # 20 is the default max_length of the generation config warnings.warn( f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the " "generation length. We recommend setting `max_new_tokens` to control the maximum length of the " "generation.", UserWarning, ) if input_ids_length >= generation_config.max_length: input_ids_string = "input_ids" raise ValueError( f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to" f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider" " increasing `max_length` or, better yet, setting `max_new_tokens`." )
def _prepare_generated_length( self, generation_config, has_default_max_length, input_ids_length, ): """Prepared max and min length in generation configs to avoid clashes between similar attributes"""
if generation_config.max_new_tokens is not None: if not has_default_max_length and generation_config.max_length is not None: logger.warning( f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(=" f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. " "Please refer to the documentation for more information. " "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)" ) generation_config.max_length = ( generation_config.max_new_tokens + input_ids_length )
elif has_default_max_length: if generation_config.max_length == DLMGenerationConfig().max_length: generation_config.max_length = ( generation_config.max_length + input_ids_length ) max_position_embeddings = getattr( self.config, "max_position_embeddings", None ) if max_position_embeddings is not None: generation_config.max_length = min( generation_config.max_length, max_position_embeddings )
return generation_config
def _prepare_generation_config( self, generation_config: Optional[DLMGenerationConfig], **kwargs: Dict ) -> DLMGenerationConfig: """ Prepares the base generation config, then applies any generation configuration options from kwargs. This function handles retrocompatibility with respect to configuration files. """ # priority: `generation_config` argument > `model.generation_config` (the default generation config) using_model_generation_config = False if generation_config is None: generation_config = DLMGenerationConfig.from_model_config(self.config) using_model_generation_config = True
# `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config` # will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an # exception will be raised in `_validate_model_kwargs` if not is_torchdynamo_compiling(): generation_config = copy.deepcopy(generation_config) _kwargs = generation_config.update(**kwargs) # If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model if not using_model_generation_config: if generation_config.bos_token_id is None: generation_config.bos_token_id = self.generation_config.bos_token_id if generation_config.eos_token_id is None: generation_config.eos_token_id = self.generation_config.eos_token_id if generation_config.pad_token_id is None: generation_config.pad_token_id = self.generation_config.pad_token_id if generation_config.mask_token_id is None: generation_config.mask_token_id = ( self.generation_config.mask_token_id )
return generation_config
def _prepare_special_tokens( self, generation_config: DLMGenerationConfig, device: Optional[Union[torch.device, str]] = None, ): """ Prepares the special tokens for generation, overwriting the generation config with their processed versions converted to tensor.
Note that `generation_config` is changed in place and stops being serializable after this method is called. That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the function). However, if called outside `generate`, consider creating a copy of `generation_config` first. """
# Convert special tokens to tensors def _tensor_or_none(token, device=None): if token is None: return token
device = device if device is not None else self.device if isinstance(token, torch.Tensor): return token.to(device) return torch.tensor(token, device=device, dtype=torch.long)
bos_token_tensor = _tensor_or_none( generation_config.bos_token_id, device=device ) eos_token_tensor = _tensor_or_none( generation_config.eos_token_id, device=device ) pad_token_tensor = _tensor_or_none( generation_config.pad_token_id, device=device ) mask_token_tensor = _tensor_or_none( generation_config.mask_token_id, device=device )
# We can have more than one eos token. Always treat it as a 1D tensor (when it exists). if eos_token_tensor is not None and eos_token_tensor.ndim == 0: eos_token_tensor = eos_token_tensor.unsqueeze(0)
# Set pad token if unset (and there are conditions to do so) if pad_token_tensor is None and eos_token_tensor is not None: pad_token_tensor = eos_token_tensor[0] logger.warning( f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation." )
# Update generation config with the updated special tokens tensors # NOTE: this must be written into a different attribute name than the one holding the original special tokens # (in their non-tensor form), in order to enable end-to-end compilation. See # https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations generation_config._bos_token_tensor = bos_token_tensor generation_config._eos_token_tensor = eos_token_tensor generation_config._pad_token_tensor = pad_token_tensor generation_config._mask_token_tensor = mask_token_tensor
@torch.no_grad() def diffusion_generate( self, inputs: Optional[torch.Tensor] = None, generation_config: Optional[DLMGenerationConfig] = None, **kwargs, ) -> Union[DLMModelOutput, torch.LongTensor]: # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call generation_config = self._prepare_generation_config(generation_config, **kwargs) generation_tokens_hook_func = kwargs.pop( "generation_tokens_hook_func", lambda step, x, logits: x ) generation_logits_hook_func = kwargs.pop( "generation_logits_hook_func", lambda step, x, logits: logits )
# 2. Define model inputs assert inputs is not None input_ids = inputs device = input_ids.device attention_mask = kwargs.pop("attention_mask", None) self._prepare_special_tokens(generation_config, device=device)
# 3. Prepare `max_length`. input_ids_length = input_ids.shape[-1] has_default_max_length = ( kwargs.get("max_length") is None and generation_config.max_length is not None ) generation_config = self._prepare_generated_length( generation_config=generation_config, has_default_max_length=has_default_max_length, input_ids_length=input_ids_length, )
self._validate_generated_length( generation_config, input_ids_length, has_default_max_length )
# 4. Check input_ids if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type: warnings.warn( "You are calling .generate() with the `input_ids` being on a device type different" f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model" f" is on {self.device.type}. You may experience unexpected behaviors or slower generation." " Please make sure that you have put `input_ids` to the" f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before" " running `.generate()`.", UserWarning, ) if ( hasattr(generation_config, "pad_token_id") and torch.any(input_ids == generation_config.pad_token_id) and attention_mask is None ): warnings.warn( "Padding was detected but no attention mask is passed here. For correct " "generation results, please set `attention_mask` when batch-padding inputs.", UserWarning, )
input_ids, attention_mask = self._expand_inputs_for_generation( expand_size=generation_config.num_return_sequences, input_ids=input_ids, attention_mask=attention_mask, )
result = self._sample( input_ids, attention_mask=attention_mask, generation_config=generation_config, generation_tokens_hook_func=generation_tokens_hook_func, generation_logits_hook_func=generation_logits_hook_func, ) return result
def _sample( self, input_ids: torch.LongTensor, attention_mask: Optional[torch.LongTensor], generation_config: DLMGenerationConfig, generation_tokens_hook_func, generation_logits_hook_func, ) -> Union[DLMModelOutput, torch.LongTensor]: # init values output_history = generation_config.output_history return_dict_in_generate = generation_config.return_dict_in_generate max_length = generation_config.max_length mask_token_id = generation_config.mask_token_id steps = generation_config.steps eps = generation_config.eps alg = generation_config.alg alg_temp = generation_config.alg_temp temperature = generation_config.temperature top_p = generation_config.top_p top_k = generation_config.top_k
histories = [] if (return_dict_in_generate and output_history) else None
# pad input_ids to max_length x = F.pad(input_ids, (0, max_length - input_ids.shape[1]), value=mask_token_id)
if attention_mask is not None and torch.any(attention_mask == 0.0): # we do not mask the [MASK] tokens so value = 1.0 attention_mask = F.pad( attention_mask, (0, max_length - attention_mask.shape[1]), value=1.0 ) # attention_mask is of shape [B, N] # broadcast to [B, 1, N, N] attention_mask = torch.logical_and( attention_mask.unsqueeze(1).unsqueeze(-2), attention_mask.unsqueeze(1).unsqueeze(-1), )
timesteps = torch.linspace(1, eps, steps + 1, device=x.device)
# this allows user-defined token control of the intermediate steps x = generation_tokens_hook_func(None, x, None) for i in range(steps): mask_index = x == mask_token_id logits, _ = self(x, attention_mask=attention_mask) logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1)
# this allows user-defined logits control of the intermediate steps logits = generation_logits_hook_func(i, x, logits)
mask_logits = logits[mask_index] t = timesteps[i] s = timesteps[i + 1]
if alg == "origin": p_transfer = 1 - s / t if i < steps - 1 else 1 x0 = ( torch.zeros_like( x[mask_index], device=self.device, dtype=torch.long ) + mask_token_id ) transfer_index_t_s = ( torch.rand(*x0.shape, device=self.device) < p_transfer ) _, x0[transfer_index_t_s] = sample_tokens( mask_logits[transfer_index_t_s], temperature=temperature, top_p=top_p, top_k=top_k, ) x[mask_index] = x0.clone() else: if alg == "maskgit_plus": confidence, x0 = sample_tokens( mask_logits, temperature=temperature, top_p=top_p, top_k=top_k ) elif alg == "topk_margin": confidence, x0 = sample_tokens( mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, margin_confidence=True, ) elif alg == "entropy": confidence, x0 = sample_tokens( mask_logits, temperature, top_p=top_p, top_k=top_k, neg_entropy=True, ) else: raise RuntimeError(f"Unknown alg: {alg}") num_mask_token = mask_index.sum() / mask_index.shape[0] number_transfer_tokens = ( int(num_mask_token * (1 - s / t)) if i < steps - 1 else int(num_mask_token) ) full_confidence = torch.full_like( x, -torch.inf, device=self.device, dtype=logits.dtype ) full_confidence[mask_index] = confidence if number_transfer_tokens > 0: if alg_temp is None or alg_temp == 0: _, transfer_index = torch.topk( full_confidence, number_transfer_tokens ) else: full_confidence = full_confidence / alg_temp full_confidence = F.softmax(full_confidence, dim=-1) transfer_index = torch.multinomial( full_confidence, num_samples=number_transfer_tokens ) x_ = ( torch.zeros_like(x, device=self.device, dtype=torch.long) + mask_token_id ) x_[mask_index] = x0.clone() row_indices = ( torch.arange(x.size(0), device=self.device) .unsqueeze(1) .expand_as(transfer_index) ) x[row_indices, transfer_index] = x_[row_indices, transfer_index]
# this allows user-defined token control of the intermediate steps x = generation_tokens_hook_func(i, x, logits)
if histories is not None: histories.append(x.clone())
if return_dict_in_generate: return DLMModelOutput( sequences=x, history=histories, ) else: return x123version https://git-lfs.github.com/spec/v1oid sha256:ffc779cfe6a466803a61a11130a73be221c0af527d1bfce679c954f9ad15ddbasize 1270334341123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715{ "metadata": { "total_size": 1270255616, "total_parameters": 2031739904 }, "weight_map": { "lm_head.biases": "model.safetensors", "lm_head.scales": "model.safetensors", "lm_head.weight": "model.safetensors", "model.embed_tokens.biases": "model.safetensors", "model.embed_tokens.scales": "model.safetensors", "model.embed_tokens.weight": "model.safetensors", "model.layers.0.input_layernorm.weight": "model.safetensors", "model.layers.0.mlp.down_proj.biases": "model.safetensors", "model.layers.0.mlp.down_proj.scales": "model.safetensors", "model.layers.0.mlp.down_proj.weight": "model.safetensors", "model.layers.0.mlp.gate_proj.biases": "model.safetensors", "model.layers.0.mlp.gate_proj.scales": "model.safetensors", "model.layers.0.mlp.gate_proj.weight": "model.safetensors", "model.layers.0.mlp.up_proj.biases": "model.safetensors", "model.layers.0.mlp.up_proj.scales": "model.safetensors", "model.layers.0.mlp.up_proj.weight": "model.safetensors", "model.layers.0.post_attention_layernorm.weight": "model.safetensors", "model.layers.0.self_attn.k_norm.weight": "model.safetensors", "model.layers.0.self_attn.k_proj.biases": "model.safetensors", "model.layers.0.self_attn.k_proj.scales": "model.safetensors", "model.layers.0.self_attn.k_proj.weight": "model.safetensors", "model.layers.0.self_attn.o_proj.biases": "model.safetensors", "model.layers.0.self_attn.o_proj.scales": "model.safetensors", "model.layers.0.self_attn.o_proj.weight": "model.safetensors", "model.layers.0.self_attn.q_norm.weight": "model.safetensors", "model.layers.0.self_attn.q_proj.biases": "model.safetensors", "model.layers.0.self_attn.q_proj.scales": "model.safetensors", "model.layers.0.self_attn.q_proj.weight": "model.safetensors", "model.layers.0.self_attn.v_proj.biases": "model.safetensors", "model.layers.0.self_attn.v_proj.scales": "model.safetensors", "model.layers.0.self_attn.v_proj.weight": "model.safetensors", "model.layers.1.input_layernorm.weight": "model.safetensors", "model.layers.1.mlp.down_proj.biases": "model.safetensors", "model.layers.1.mlp.down_proj.scales": "model.safetensors", "model.layers.1.mlp.down_proj.weight": "model.safetensors", "model.layers.1.mlp.gate_proj.biases": "model.safetensors", "model.layers.1.mlp.gate_proj.scales": "model.safetensors", "model.layers.1.mlp.gate_proj.weight": "model.safetensors", "model.layers.1.mlp.up_proj.biases": "model.safetensors", "model.layers.1.mlp.up_proj.scales": "model.safetensors", "model.layers.1.mlp.up_proj.weight": "model.safetensors", "model.layers.1.post_attention_layernorm.weight": "model.safetensors", "model.layers.1.self_attn.k_norm.weight": "model.safetensors", "model.layers.1.self_attn.k_proj.biases": "model.safetensors", "model.layers.1.self_attn.k_proj.scales": "model.safetensors", "model.layers.1.self_attn.k_proj.weight": "model.safetensors", "model.layers.1.self_attn.o_proj.biases": "model.safetensors", "model.layers.1.self_attn.o_proj.scales": "model.safetensors", "model.layers.1.self_attn.o_proj.weight": "model.safetensors", "model.layers.1.self_attn.q_norm.weight": "model.safetensors", "model.layers.1.self_attn.q_proj.biases": "model.safetensors", "model.layers.1.self_attn.q_proj.scales": "model.safetensors", "model.layers.1.self_attn.q_proj.weight": "model.safetensors", "model.layers.1.self_attn.v_proj.biases": "model.safetensors", "model.layers.1.self_attn.v_proj.scales": "model.safetensors", "model.layers.1.self_attn.v_proj.weight": "model.safetensors", "model.layers.10.input_layernorm.weight": "model.safetensors", "model.layers.10.mlp.down_proj.biases": "model.safetensors", "model.layers.10.mlp.down_proj.scales": "model.safetensors", "model.layers.10.mlp.down_proj.weight": "model.safetensors", "model.layers.10.mlp.gate_proj.biases": "model.safetensors", "model.layers.10.mlp.gate_proj.scales": "model.safetensors", "model.layers.10.mlp.gate_proj.weight": "model.safetensors", "model.layers.10.mlp.up_proj.biases": "model.safetensors", "model.layers.10.mlp.up_proj.scales": "model.safetensors", "model.layers.10.mlp.up_proj.weight": "model.safetensors", "model.layers.10.post_attention_layernorm.weight": "model.safetensors", "model.layers.10.self_attn.k_norm.weight": "model.safetensors", "model.layers.10.self_attn.k_proj.biases": "model.safetensors", "model.layers.10.self_attn.k_proj.scales": "model.safetensors", "model.layers.10.self_attn.k_proj.weight": "model.safetensors", "model.layers.10.self_attn.o_proj.biases": "model.safetensors", "model.layers.10.self_attn.o_proj.scales": "model.safetensors", "model.layers.10.self_attn.o_proj.weight": "model.safetensors", "model.layers.10.self_attn.q_norm.weight": "model.safetensors", "model.layers.10.self_attn.q_proj.biases": "model.safetensors", "model.layers.10.self_attn.q_proj.scales": "model.safetensors", "model.layers.10.self_attn.q_proj.weight": "model.safetensors", "model.layers.10.self_attn.v_proj.biases": "model.safetensors", "model.layers.10.self_attn.v_proj.scales": "model.safetensors", "model.layers.10.self_attn.v_proj.weight": "model.safetensors", "model.layers.11.input_layernorm.weight": "model.safetensors", "model.layers.11.mlp.down_proj.biases": "model.safetensors", "model.layers.11.mlp.down_proj.scales": "model.safetensors", "model.layers.11.mlp.down_proj.weight": "model.safetensors", "model.layers.11.mlp.gate_proj.biases": "model.safetensors", "model.layers.11.mlp.gate_proj.scales": "model.safetensors", "model.layers.11.mlp.gate_proj.weight": "model.safetensors", "model.layers.11.mlp.up_proj.biases": "model.safetensors", "model.layers.11.mlp.up_proj.scales": "model.safetensors", "model.layers.11.mlp.up_proj.weight": "model.safetensors", "model.layers.11.post_attention_layernorm.weight": "model.safetensors", "model.layers.11.self_attn.k_norm.weight": "model.safetensors", "model.layers.11.self_attn.k_proj.biases": "model.safetensors", "model.layers.11.self_attn.k_proj.scales": "model.safetensors", "model.layers.11.self_attn.k_proj.weight": "model.safetensors", "model.layers.11.self_attn.o_proj.biases": "model.safetensors", "model.layers.11.self_attn.o_proj.scales": "model.safetensors", "model.layers.11.self_attn.o_proj.weight": "model.safetensors", "model.layers.11.self_attn.q_norm.weight": "model.safetensors", "model.layers.11.self_attn.q_proj.biases": "model.safetensors", "model.layers.11.self_attn.q_proj.scales": "model.safetensors", "model.layers.11.self_attn.q_proj.weight": "model.safetensors", "model.layers.11.self_attn.v_proj.biases": "model.safetensors", "model.layers.11.self_attn.v_proj.scales": "model.safetensors", "model.layers.11.self_attn.v_proj.weight": "model.safetensors", "model.layers.12.input_layernorm.weight": "model.safetensors", "model.layers.12.mlp.down_proj.biases": "model.safetensors", "model.layers.12.mlp.down_proj.scales": "model.safetensors", "model.layers.12.mlp.down_proj.weight": "model.safetensors", "model.layers.12.mlp.gate_proj.biases": "model.safetensors", "model.layers.12.mlp.gate_proj.scales": "model.safetensors", "model.layers.12.mlp.gate_proj.weight": "model.safetensors", "model.layers.12.mlp.up_proj.biases": "model.safetensors", "model.layers.12.mlp.up_proj.scales": "model.safetensors", "model.layers.12.mlp.up_proj.weight": "model.safetensors", "model.layers.12.post_attention_layernorm.weight": "model.safetensors", "model.layers.12.self_attn.k_norm.weight": "model.safetensors", "model.layers.12.self_attn.k_proj.biases": "model.safetensors", "model.layers.12.self_attn.k_proj.scales": "model.safetensors", "model.layers.12.self_attn.k_proj.weight": "model.safetensors", "model.layers.12.self_attn.o_proj.biases": "model.safetensors", "model.layers.12.self_attn.o_proj.scales": "model.safetensors", "model.layers.12.self_attn.o_proj.weight": "model.safetensors", "model.layers.12.self_attn.q_norm.weight": "model.safetensors", "model.layers.12.self_attn.q_proj.biases": "model.safetensors", "model.layers.12.self_attn.q_proj.scales": "model.safetensors", "model.layers.12.self_attn.q_proj.weight": "model.safetensors", "model.layers.12.self_attn.v_proj.biases": "model.safetensors", "model.layers.12.self_attn.v_proj.scales": "model.safetensors", "model.layers.12.self_attn.v_proj.weight": "model.safetensors", "model.layers.13.input_layernorm.weight": "model.safetensors", "model.layers.13.mlp.down_proj.biases": "model.safetensors", "model.layers.13.mlp.down_proj.scales": "model.safetensors", "model.layers.13.mlp.down_proj.weight": "model.safetensors", "model.layers.13.mlp.gate_proj.biases": "model.safetensors", "model.layers.13.mlp.gate_proj.scales": "model.safetensors", "model.layers.13.mlp.gate_proj.weight": "model.safetensors", "model.layers.13.mlp.up_proj.biases": "model.safetensors", "model.layers.13.mlp.up_proj.scales": "model.safetensors", "model.layers.13.mlp.up_proj.weight": "model.safetensors", "model.layers.13.post_attention_layernorm.weight": "model.safetensors", "model.layers.13.self_attn.k_norm.weight": "model.safetensors", "model.layers.13.self_attn.k_proj.biases": "model.safetensors", "model.layers.13.self_attn.k_proj.scales": "model.safetensors", "model.layers.13.self_attn.k_proj.weight": "model.safetensors", "model.layers.13.self_attn.o_proj.biases": "model.safetensors", "model.layers.13.self_attn.o_proj.scales": "model.safetensors", "model.layers.13.self_attn.o_proj.weight": "model.safetensors", "model.layers.13.self_attn.q_norm.weight": "model.safetensors", "model.layers.13.self_attn.q_proj.biases": "model.safetensors", "model.layers.13.self_attn.q_proj.scales": "model.safetensors", "model.layers.13.self_attn.q_proj.weight": "model.safetensors", "model.layers.13.self_attn.v_proj.biases": "model.safetensors", "model.layers.13.self_attn.v_proj.scales": "model.safetensors", "model.layers.13.self_attn.v_proj.weight": "model.safetensors", "model.layers.14.input_layernorm.weight": "model.safetensors", "model.layers.14.mlp.down_proj.biases": "model.safetensors", "model.layers.14.mlp.down_proj.scales": "model.safetensors", "model.layers.14.mlp.down_proj.weight": "model.safetensors", "model.layers.14.mlp.gate_proj.biases": "model.safetensors", "model.layers.14.mlp.gate_proj.scales": "model.safetensors", "model.layers.14.mlp.gate_proj.weight": "model.safetensors", "model.layers.14.mlp.up_proj.biases": "model.safetensors", "model.layers.14.mlp.up_proj.scales": "model.safetensors", "model.layers.14.mlp.up_proj.weight": "model.safetensors", "model.layers.14.post_attention_layernorm.weight": "model.safetensors", "model.layers.14.self_attn.k_norm.weight": "model.safetensors", "model.layers.14.self_attn.k_proj.biases": "model.safetensors", "model.layers.14.self_attn.k_proj.scales": "model.safetensors", "model.layers.14.self_attn.k_proj.weight": "model.safetensors", "model.layers.14.self_attn.o_proj.biases": "model.safetensors", "model.layers.14.self_attn.o_proj.scales": "model.safetensors", "model.layers.14.self_attn.o_proj.weight": "model.safetensors", "model.layers.14.self_attn.q_norm.weight": "model.safetensors", "model.layers.14.self_attn.q_proj.biases": "model.safetensors", "model.layers.14.self_attn.q_proj.scales": "model.safetensors", "model.layers.14.self_attn.q_proj.weight": "model.safetensors", "model.layers.14.self_attn.v_proj.biases": "model.safetensors", "model.layers.14.self_attn.v_proj.scales": "model.safetensors", "model.layers.14.self_attn.v_proj.weight": "model.safetensors", "model.layers.15.input_layernorm.weight": "model.safetensors", "model.layers.15.mlp.down_proj.biases": "model.safetensors", "model.layers.15.mlp.down_proj.scales": "model.safetensors", "model.layers.15.mlp.down_proj.weight": "model.safetensors", "model.layers.15.mlp.gate_proj.biases": "model.safetensors", "model.layers.15.mlp.gate_proj.scales": "model.safetensors", "model.layers.15.mlp.gate_proj.weight": "model.safetensors", "model.layers.15.mlp.up_proj.biases": "model.safetensors", "model.layers.15.mlp.up_proj.scales": "model.safetensors", "model.layers.15.mlp.up_proj.weight": "model.safetensors", "model.layers.15.post_attention_layernorm.weight": "model.safetensors", "model.layers.15.self_attn.k_norm.weight": "model.safetensors", "model.layers.15.self_attn.k_proj.biases": "model.safetensors", "model.layers.15.self_attn.k_proj.scales": "model.safetensors", "model.layers.15.self_attn.k_proj.weight": "model.safetensors", "model.layers.15.self_attn.o_proj.biases": "model.safetensors", "model.layers.15.self_attn.o_proj.scales": "model.safetensors", "model.layers.15.self_attn.o_proj.weight": "model.safetensors", "model.layers.15.self_attn.q_norm.weight": "model.safetensors", "model.layers.15.self_attn.q_proj.biases": "model.safetensors", "model.layers.15.self_attn.q_proj.scales": "model.safetensors", "model.layers.15.self_attn.q_proj.weight": "model.safetensors", "model.layers.15.self_attn.v_proj.biases": "model.safetensors", "model.layers.15.self_attn.v_proj.scales": "model.safetensors", "model.layers.15.self_attn.v_proj.weight": "model.safetensors", "model.layers.16.input_layernorm.weight": "model.safetensors", "model.layers.16.mlp.down_proj.biases": "model.safetensors", "model.layers.16.mlp.down_proj.scales": "model.safetensors", "model.layers.16.mlp.down_proj.weight": "model.safetensors", "model.layers.16.mlp.gate_proj.biases": "model.safetensors", "model.layers.16.mlp.gate_proj.scales": "model.safetensors", "model.layers.16.mlp.gate_proj.weight": "model.safetensors", "model.layers.16.mlp.up_proj.biases": "model.safetensors", "model.layers.16.mlp.up_proj.scales": "model.safetensors", "model.layers.16.mlp.up_proj.weight": "model.safetensors", "model.layers.16.post_attention_layernorm.weight": "model.safetensors", "model.layers.16.self_attn.k_norm.weight": "model.safetensors", "model.layers.16.self_attn.k_proj.biases": "model.safetensors", "model.layers.16.self_attn.k_proj.scales": "model.safetensors", "model.layers.16.self_attn.k_proj.weight": "model.safetensors", "model.layers.16.self_attn.o_proj.biases": "model.safetensors", "model.layers.16.self_attn.o_proj.scales": "model.safetensors", "model.layers.16.self_attn.o_proj.weight": "model.safetensors", "model.layers.16.self_attn.q_norm.weight": "model.safetensors", "model.layers.16.self_attn.q_proj.biases": "model.safetensors", "model.layers.16.self_attn.q_proj.scales": "model.safetensors", "model.layers.16.self_attn.q_proj.weight": "model.safetensors", "model.layers.16.self_attn.v_proj.biases": "model.safetensors", "model.layers.16.self_attn.v_proj.scales": "model.safetensors", "model.layers.16.self_attn.v_proj.weight": "model.safetensors", "model.layers.17.input_layernorm.weight": "model.safetensors", "model.layers.17.mlp.down_proj.biases": "model.safetensors", "model.layers.17.mlp.down_proj.scales": "model.safetensors", "model.layers.17.mlp.down_proj.weight": "model.safetensors", "model.layers.17.mlp.gate_proj.biases": "model.safetensors", "model.layers.17.mlp.gate_proj.scales": "model.safetensors", "model.layers.17.mlp.gate_proj.weight": "model.safetensors", "model.layers.17.mlp.up_proj.biases": "model.safetensors", "model.layers.17.mlp.up_proj.scales": "model.safetensors", "model.layers.17.mlp.up_proj.weight": "model.safetensors", "model.layers.17.post_attention_layernorm.weight": "model.safetensors", "model.layers.17.self_attn.k_norm.weight": "model.safetensors", "model.layers.17.self_attn.k_proj.biases": "model.safetensors", "model.layers.17.self_attn.k_proj.scales": "model.safetensors", "model.layers.17.self_attn.k_proj.weight": "model.safetensors", "model.layers.17.self_attn.o_proj.biases": "model.safetensors", "model.layers.17.self_attn.o_proj.scales": "model.safetensors", "model.layers.17.self_attn.o_proj.weight": "model.safetensors", "model.layers.17.self_attn.q_norm.weight": "model.safetensors", "model.layers.17.self_attn.q_proj.biases": "model.safetensors", "model.layers.17.self_attn.q_proj.scales": "model.safetensors", "model.layers.17.self_attn.q_proj.weight": "model.safetensors", "model.layers.17.self_attn.v_proj.biases": "model.safetensors", "model.layers.17.self_attn.v_proj.scales": "model.safetensors", "model.layers.17.self_attn.v_proj.weight": "model.safetensors", "model.layers.18.input_layernorm.weight": "model.safetensors", "model.layers.18.mlp.down_proj.biases": "model.safetensors", "model.layers.18.mlp.down_proj.scales": "model.safetensors", "model.layers.18.mlp.down_proj.weight": "model.safetensors", "model.layers.18.mlp.gate_proj.biases": "model.safetensors", "model.layers.18.mlp.gate_proj.scales": "model.safetensors", "model.layers.18.mlp.gate_proj.weight": "model.safetensors", "model.layers.18.mlp.up_proj.biases": "model.safetensors", "model.layers.18.mlp.up_proj.scales": "model.safetensors", "model.layers.18.mlp.up_proj.weight": "model.safetensors", "model.layers.18.post_attention_layernorm.weight": "model.safetensors", "model.layers.18.self_attn.k_norm.weight": "model.safetensors", "model.layers.18.self_attn.k_proj.biases": "model.safetensors", "model.layers.18.self_attn.k_proj.scales": "model.safetensors", "model.layers.18.self_attn.k_proj.weight": "model.safetensors", "model.layers.18.self_attn.o_proj.biases": "model.safetensors", "model.layers.18.self_attn.o_proj.scales": "model.safetensors", "model.layers.18.self_attn.o_proj.weight": "model.safetensors", "model.layers.18.self_attn.q_norm.weight": "model.safetensors", "model.layers.18.self_attn.q_proj.biases": "model.safetensors", "model.layers.18.self_attn.q_proj.scales": "model.safetensors", "model.layers.18.self_attn.q_proj.weight": "model.safetensors", "model.layers.18.self_attn.v_proj.biases": "model.safetensors", "model.layers.18.self_attn.v_proj.scales": "model.safetensors", "model.layers.18.self_attn.v_proj.weight": "model.safetensors", "model.layers.19.input_layernorm.weight": "model.safetensors", "model.layers.19.mlp.down_proj.biases": "model.safetensors", "model.layers.19.mlp.down_proj.scales": "model.safetensors", "model.layers.19.mlp.down_proj.weight": "model.safetensors", "model.layers.19.mlp.gate_proj.biases": "model.safetensors", "model.layers.19.mlp.gate_proj.scales": "model.safetensors", "model.layers.19.mlp.gate_proj.weight": "model.safetensors", "model.layers.19.mlp.up_proj.biases": "model.safetensors", "model.layers.19.mlp.up_proj.scales": "model.safetensors", "model.layers.19.mlp.up_proj.weight": "model.safetensors", "model.layers.19.post_attention_layernorm.weight": "model.safetensors", "model.layers.19.self_attn.k_norm.weight": "model.safetensors", "model.layers.19.self_attn.k_proj.biases": "model.safetensors", "model.layers.19.self_attn.k_proj.scales": "model.safetensors", "model.layers.19.self_attn.k_proj.weight": "model.safetensors", "model.layers.19.self_attn.o_proj.biases": "model.safetensors", "model.layers.19.self_attn.o_proj.scales": "model.safetensors", "model.layers.19.self_attn.o_proj.weight": "model.safetensors", "model.layers.19.self_attn.q_norm.weight": "model.safetensors", "model.layers.19.self_attn.q_proj.biases": "model.safetensors", "model.layers.19.self_attn.q_proj.scales": "model.safetensors", "model.layers.19.self_attn.q_proj.weight": "model.safetensors", "model.layers.19.self_attn.v_proj.biases": "model.safetensors", "model.layers.19.self_attn.v_proj.scales": "model.safetensors", "model.layers.19.self_attn.v_proj.weight": "model.safetensors", "model.layers.2.input_layernorm.weight": "model.safetensors", "model.layers.2.mlp.down_proj.biases": "model.safetensors", "model.layers.2.mlp.down_proj.scales": "model.safetensors", "model.layers.2.mlp.down_proj.weight": "model.safetensors", "model.layers.2.mlp.gate_proj.biases": "model.safetensors", "model.layers.2.mlp.gate_proj.scales": "model.safetensors", "model.layers.2.mlp.gate_proj.weight": "model.safetensors", "model.layers.2.mlp.up_proj.biases": "model.safetensors", "model.layers.2.mlp.up_proj.scales": "model.safetensors", "model.layers.2.mlp.up_proj.weight": "model.safetensors", "model.layers.2.post_attention_layernorm.weight": "model.safetensors", "model.layers.2.self_attn.k_norm.weight": "model.safetensors", "model.layers.2.self_attn.k_proj.biases": "model.safetensors", "model.layers.2.self_attn.k_proj.scales": "model.safetensors", "model.layers.2.self_attn.k_proj.weight": "model.safetensors", "model.layers.2.self_attn.o_proj.biases": "model.safetensors", "model.layers.2.self_attn.o_proj.scales": "model.safetensors", "model.layers.2.self_attn.o_proj.weight": "model.safetensors", "model.layers.2.self_attn.q_norm.weight": "model.safetensors", "model.layers.2.self_attn.q_proj.biases": "model.safetensors", "model.layers.2.self_attn.q_proj.scales": "model.safetensors", "model.layers.2.self_attn.q_proj.weight": "model.safetensors", "model.layers.2.self_attn.v_proj.biases": "model.safetensors", "model.layers.2.self_attn.v_proj.scales": "model.safetensors", "model.layers.2.self_attn.v_proj.weight": "model.safetensors", "model.layers.20.input_layernorm.weight": "model.safetensors", "model.layers.20.mlp.down_proj.biases": "model.safetensors", "model.layers.20.mlp.down_proj.scales": "model.safetensors", "model.layers.20.mlp.down_proj.weight": "model.safetensors", "model.layers.20.mlp.gate_proj.biases": "model.safetensors", "model.layers.20.mlp.gate_proj.scales": "model.safetensors", "model.layers.20.mlp.gate_proj.weight": "model.safetensors", "model.layers.20.mlp.up_proj.biases": "model.safetensors", "model.layers.20.mlp.up_proj.scales": "model.safetensors", "model.layers.20.mlp.up_proj.weight": "model.safetensors", "model.layers.20.post_attention_layernorm.weight": "model.safetensors", "model.layers.20.self_attn.k_norm.weight": "model.safetensors", "model.layers.20.self_attn.k_proj.biases": "model.safetensors", "model.layers.20.self_attn.k_proj.scales": "model.safetensors", "model.layers.20.self_attn.k_proj.weight": "model.safetensors", "model.layers.20.self_attn.o_proj.biases": "model.safetensors", "model.layers.20.self_attn.o_proj.scales": "model.safetensors", "model.layers.20.self_attn.o_proj.weight": "model.safetensors", "model.layers.20.self_attn.q_norm.weight": "model.safetensors", "model.layers.20.self_attn.q_proj.biases": "model.safetensors", "model.layers.20.self_attn.q_proj.scales": "model.safetensors", "model.layers.20.self_attn.q_proj.weight": "model.safetensors", "model.layers.20.self_attn.v_proj.biases": "model.safetensors", "model.layers.20.self_attn.v_proj.scales": "model.safetensors", "model.layers.20.self_attn.v_proj.weight": "model.safetensors", "model.layers.21.input_layernorm.weight": "model.safetensors", "model.layers.21.mlp.down_proj.biases": "model.safetensors", "model.layers.21.mlp.down_proj.scales": "model.safetensors", "model.layers.21.mlp.down_proj.weight": "model.safetensors", "model.layers.21.mlp.gate_proj.biases": "model.safetensors", "model.layers.21.mlp.gate_proj.scales": "model.safetensors", "model.layers.21.mlp.gate_proj.weight": "model.safetensors", "model.layers.21.mlp.up_proj.biases": "model.safetensors", "model.layers.21.mlp.up_proj.scales": "model.safetensors", "model.layers.21.mlp.up_proj.weight": "model.safetensors", "model.layers.21.post_attention_layernorm.weight": "model.safetensors", "model.layers.21.self_attn.k_norm.weight": "model.safetensors", "model.layers.21.self_attn.k_proj.biases": "model.safetensors", "model.layers.21.self_attn.k_proj.scales": "model.safetensors", "model.layers.21.self_attn.k_proj.weight": "model.safetensors", "model.layers.21.self_attn.o_proj.biases": "model.safetensors", "model.layers.21.self_attn.o_proj.scales": "model.safetensors", "model.layers.21.self_attn.o_proj.weight": "model.safetensors", "model.layers.21.self_attn.q_norm.weight": "model.safetensors", "model.layers.21.self_attn.q_proj.biases": "model.safetensors", "model.layers.21.self_attn.q_proj.scales": "model.safetensors", "model.layers.21.self_attn.q_proj.weight": "model.safetensors", "model.layers.21.self_attn.v_proj.biases": "model.safetensors", "model.layers.21.self_attn.v_proj.scales": "model.safetensors", "model.layers.21.self_attn.v_proj.weight": "model.safetensors", "model.layers.22.input_layernorm.weight": "model.safetensors", "model.layers.22.mlp.down_proj.biases": "model.safetensors", "model.layers.22.mlp.down_proj.scales": "model.safetensors", "model.layers.22.mlp.down_proj.weight": "model.safetensors", "model.layers.22.mlp.gate_proj.biases": "model.safetensors", "model.layers.22.mlp.gate_proj.scales": "model.safetensors", "model.layers.22.mlp.gate_proj.weight": "model.safetensors", "model.layers.22.mlp.up_proj.biases": "model.safetensors", "model.layers.22.mlp.up_proj.scales": "model.safetensors", "model.layers.22.mlp.up_proj.weight": "model.safetensors", "model.layers.22.post_attention_layernorm.weight": "model.safetensors", "model.layers.22.self_attn.k_norm.weight": "model.safetensors", "model.layers.22.self_attn.k_proj.biases": "model.safetensors", "model.layers.22.self_attn.k_proj.scales": "model.safetensors", "model.layers.22.self_attn.k_proj.weight": "model.safetensors", "model.layers.22.self_attn.o_proj.biases": "model.safetensors", "model.layers.22.self_attn.o_proj.scales": "model.safetensors", "model.layers.22.self_attn.o_proj.weight": "model.safetensors", "model.layers.22.self_attn.q_norm.weight": "model.safetensors", "model.layers.22.self_attn.q_proj.biases": "model.safetensors", "model.layers.22.self_attn.q_proj.scales": "model.safetensors", "model.layers.22.self_attn.q_proj.weight": "model.safetensors", "model.layers.22.self_attn.v_proj.biases": "model.safetensors", "model.layers.22.self_attn.v_proj.scales": "model.safetensors", "model.layers.22.self_attn.v_proj.weight": "model.safetensors", "model.layers.23.input_layernorm.weight": "model.safetensors", "model.layers.23.mlp.down_proj.biases": "model.safetensors", "model.layers.23.mlp.down_proj.scales": "model.safetensors", "model.layers.23.mlp.down_proj.weight": "model.safetensors", "model.layers.23.mlp.gate_proj.biases": "model.safetensors", "model.layers.23.mlp.gate_proj.scales": "model.safetensors", "model.layers.23.mlp.gate_proj.weight": "model.safetensors", "model.layers.23.mlp.up_proj.biases": "model.safetensors", "model.layers.23.mlp.up_proj.scales": "model.safetensors", "model.layers.23.mlp.up_proj.weight": "model.safetensors", "model.layers.23.post_attention_layernorm.weight": "model.safetensors", "model.layers.23.self_attn.k_norm.weight": "model.safetensors", "model.layers.23.self_attn.k_proj.biases": "model.safetensors", "model.layers.23.self_attn.k_proj.scales": "model.safetensors", "model.layers.23.self_attn.k_proj.weight": "model.safetensors", "model.layers.23.self_attn.o_proj.biases": "model.safetensors", "model.layers.23.self_attn.o_proj.scales": "model.safetensors", "model.layers.23.self_attn.o_proj.weight": "model.safetensors", "model.layers.23.self_attn.q_norm.weight": "model.safetensors", "model.layers.23.self_attn.q_proj.biases": "model.safetensors", "model.layers.23.self_attn.q_proj.scales": "model.safetensors", "model.layers.23.self_attn.q_proj.weight": "model.safetensors", "model.layers.23.self_attn.v_proj.biases": "model.safetensors", "model.layers.23.self_attn.v_proj.scales": "model.safetensors", "model.layers.23.self_attn.v_proj.weight": "model.safetensors", "model.layers.24.input_layernorm.weight": "model.safetensors", "model.layers.24.mlp.down_proj.biases": "model.safetensors", "model.layers.24.mlp.down_proj.scales": "model.safetensors", "model.layers.24.mlp.down_proj.weight": "model.safetensors", "model.layers.24.mlp.gate_proj.biases": "model.safetensors", "model.layers.24.mlp.gate_proj.scales": "model.safetensors", "model.layers.24.mlp.gate_proj.weight": "model.safetensors", "model.layers.24.mlp.up_proj.biases": "model.safetensors", "model.layers.24.mlp.up_proj.scales": "model.safetensors", "model.layers.24.mlp.up_proj.weight": "model.safetensors", "model.layers.24.post_attention_layernorm.weight": "model.safetensors", "model.layers.24.self_attn.k_norm.weight": "model.safetensors", "model.layers.24.self_attn.k_proj.biases": "model.safetensors", "model.layers.24.self_attn.k_proj.scales": "model.safetensors", "model.layers.24.self_attn.k_proj.weight": "model.safetensors", "model.layers.24.self_attn.o_proj.biases": "model.safetensors", "model.layers.24.self_attn.o_proj.scales": "model.safetensors", "model.layers.24.self_attn.o_proj.weight": "model.safetensors", "model.layers.24.self_attn.q_norm.weight": "model.safetensors", "model.layers.24.self_attn.q_proj.biases": "model.safetensors", "model.layers.24.self_attn.q_proj.scales": "model.safetensors", "model.layers.24.self_attn.q_proj.weight": "model.safetensors", "model.layers.24.self_attn.v_proj.biases": "model.safetensors", "model.layers.24.self_attn.v_proj.scales": "model.safetensors", "model.layers.24.self_attn.v_proj.weight": "model.safetensors", "model.layers.25.input_layernorm.weight": "model.safetensors", "model.layers.25.mlp.down_proj.biases": "model.safetensors", "model.layers.25.mlp.down_proj.scales": "model.safetensors", "model.layers.25.mlp.down_proj.weight": "model.safetensors", "model.layers.25.mlp.gate_proj.biases": "model.safetensors", "model.layers.25.mlp.gate_proj.scales": "model.safetensors", "model.layers.25.mlp.gate_proj.weight": "model.safetensors", "model.layers.25.mlp.up_proj.biases": "model.safetensors", "model.layers.25.mlp.up_proj.scales": "model.safetensors", "model.layers.25.mlp.up_proj.weight": "model.safetensors", "model.layers.25.post_attention_layernorm.weight": "model.safetensors", "model.layers.25.self_attn.k_norm.weight": "model.safetensors", "model.layers.25.self_attn.k_proj.biases": "model.safetensors", "model.layers.25.self_attn.k_proj.scales": "model.safetensors", "model.layers.25.self_attn.k_proj.weight": "model.safetensors", "model.layers.25.self_attn.o_proj.biases": "model.safetensors", "model.layers.25.self_attn.o_proj.scales": "model.safetensors", "model.layers.25.self_attn.o_proj.weight": "model.safetensors", "model.layers.25.self_attn.q_norm.weight": "model.safetensors", "model.layers.25.self_attn.q_proj.biases": "model.safetensors", "model.layers.25.self_attn.q_proj.scales": "model.safetensors", "model.layers.25.self_attn.q_proj.weight": "model.safetensors", "model.layers.25.self_attn.v_proj.biases": "model.safetensors", "model.layers.25.self_attn.v_proj.scales": "model.safetensors", "model.layers.25.self_attn.v_proj.weight": "model.safetensors", "model.layers.26.input_layernorm.weight": "model.safetensors", "model.layers.26.mlp.down_proj.biases": "model.safetensors", "model.layers.26.mlp.down_proj.scales": "model.safetensors", "model.layers.26.mlp.down_proj.weight": "model.safetensors", "model.layers.26.mlp.gate_proj.biases": "model.safetensors", "model.layers.26.mlp.gate_proj.scales": "model.safetensors", "model.layers.26.mlp.gate_proj.weight": "model.safetensors", "model.layers.26.mlp.up_proj.biases": "model.safetensors", "model.layers.26.mlp.up_proj.scales": "model.safetensors", "model.layers.26.mlp.up_proj.weight": "model.safetensors", "model.layers.26.post_attention_layernorm.weight": "model.safetensors", "model.layers.26.self_attn.k_norm.weight": "model.safetensors", "model.layers.26.self_attn.k_proj.biases": "model.safetensors", "model.layers.26.self_attn.k_proj.scales": "model.safetensors", "model.layers.26.self_attn.k_proj.weight": "model.safetensors", "model.layers.26.self_attn.o_proj.biases": "model.safetensors", "model.layers.26.self_attn.o_proj.scales": "model.safetensors", "model.layers.26.self_attn.o_proj.weight": "model.safetensors", "model.layers.26.self_attn.q_norm.weight": "model.safetensors", "model.layers.26.self_attn.q_proj.biases": "model.safetensors", "model.layers.26.self_attn.q_proj.scales": "model.safetensors", "model.layers.26.self_attn.q_proj.weight": "model.safetensors", "model.layers.26.self_attn.v_proj.biases": "model.safetensors", "model.layers.26.self_attn.v_proj.scales": "model.safetensors", "model.layers.26.self_attn.v_proj.weight": "model.safetensors", "model.layers.27.input_layernorm.weight": "model.safetensors", "model.layers.27.mlp.down_proj.biases": "model.safetensors", "model.layers.27.mlp.down_proj.scales": "model.safetensors", "model.layers.27.mlp.down_proj.weight": "model.safetensors", "model.layers.27.mlp.gate_proj.biases": "model.safetensors", "model.layers.27.mlp.gate_proj.scales": "model.safetensors", "model.layers.27.mlp.gate_proj.weight": "model.safetensors", "model.layers.27.mlp.up_proj.biases": "model.safetensors", "model.layers.27.mlp.up_proj.scales": "model.safetensors", "model.layers.27.mlp.up_proj.weight": "model.safetensors", "model.layers.27.post_attention_layernorm.weight": "model.safetensors", "model.layers.27.self_attn.k_norm.weight": "model.safetensors", "model.layers.27.self_attn.k_proj.biases": "model.safetensors", "model.layers.27.self_attn.k_proj.scales": "model.safetensors", "model.layers.27.self_attn.k_proj.weight": "model.safetensors", "model.layers.27.self_attn.o_proj.biases": "model.safetensors", "model.layers.27.self_attn.o_proj.scales": "model.safetensors", "model.layers.27.self_attn.o_proj.weight": "model.safetensors", "model.layers.27.self_attn.q_norm.weight": "model.safetensors", "model.layers.27.self_attn.q_proj.biases": "model.safetensors", "model.layers.27.self_attn.q_proj.scales": "model.safetensors", "model.layers.27.self_attn.q_proj.weight": "model.safetensors", "model.layers.27.self_attn.v_proj.biases": "model.safetensors", "model.layers.27.self_attn.v_proj.scales": "model.safetensors", "model.layers.27.self_attn.v_proj.weight": "model.safetensors", "model.layers.3.input_layernorm.weight": "model.safetensors", "model.layers.3.mlp.down_proj.biases": "model.safetensors", "model.layers.3.mlp.down_proj.scales": "model.safetensors", "model.layers.3.mlp.down_proj.weight": "model.safetensors", "model.layers.3.mlp.gate_proj.biases": "model.safetensors", "model.layers.3.mlp.gate_proj.scales": "model.safetensors", "model.layers.3.mlp.gate_proj.weight": "model.safetensors", "model.layers.3.mlp.up_proj.biases": "model.safetensors", "model.layers.3.mlp.up_proj.scales": "model.safetensors", "model.layers.3.mlp.up_proj.weight": "model.safetensors", "model.layers.3.post_attention_layernorm.weight": "model.safetensors", "model.layers.3.self_attn.k_norm.weight": "model.safetensors", "model.layers.3.self_attn.k_proj.biases": "model.safetensors", "model.layers.3.self_attn.k_proj.scales": "model.safetensors", "model.layers.3.self_attn.k_proj.weight": "model.safetensors", "model.layers.3.self_attn.o_proj.biases": "model.safetensors", "model.layers.3.self_attn.o_proj.scales": "model.safetensors", "model.layers.3.self_attn.o_proj.weight": "model.safetensors", "model.layers.3.self_attn.q_norm.weight": "model.safetensors", "model.layers.3.self_attn.q_proj.biases": "model.safetensors", "model.layers.3.self_attn.q_proj.scales": "model.safetensors", "model.layers.3.self_attn.q_proj.weight": "model.safetensors", "model.layers.3.self_attn.v_proj.biases": "model.safetensors", "model.layers.3.self_attn.v_proj.scales": "model.safetensors", "model.layers.3.self_attn.v_proj.weight": "model.safetensors", "model.layers.4.input_layernorm.weight": "model.safetensors", "model.layers.4.mlp.down_proj.biases": "model.safetensors", "model.layers.4.mlp.down_proj.scales": "model.safetensors", "model.layers.4.mlp.down_proj.weight": "model.safetensors", "model.layers.4.mlp.gate_proj.biases": "model.safetensors", "model.layers.4.mlp.gate_proj.scales": "model.safetensors", "model.layers.4.mlp.gate_proj.weight": "model.safetensors", "model.layers.4.mlp.up_proj.biases": "model.safetensors", "model.layers.4.mlp.up_proj.scales": "model.safetensors", "model.layers.4.mlp.up_proj.weight": "model.safetensors", "model.layers.4.post_attention_layernorm.weight": "model.safetensors", "model.layers.4.self_attn.k_norm.weight": "model.safetensors", "model.layers.4.self_attn.k_proj.biases": "model.safetensors", "model.layers.4.self_attn.k_proj.scales": "model.safetensors", "model.layers.4.self_attn.k_proj.weight": "model.safetensors", "model.layers.4.self_attn.o_proj.biases": "model.safetensors", "model.layers.4.self_attn.o_proj.scales": "model.safetensors", "model.layers.4.self_attn.o_proj.weight": "model.safetensors", "model.layers.4.self_attn.q_norm.weight": "model.safetensors", "model.layers.4.self_attn.q_proj.biases": "model.safetensors", "model.layers.4.self_attn.q_proj.scales": "model.safetensors", "model.layers.4.self_attn.q_proj.weight": "model.safetensors", "model.layers.4.self_attn.v_proj.biases": "model.safetensors", "model.layers.4.self_attn.v_proj.scales": "model.safetensors", "model.layers.4.self_attn.v_proj.weight": "model.safetensors", "model.layers.5.input_layernorm.weight": "model.safetensors", "model.layers.5.mlp.down_proj.biases": "model.safetensors", "model.layers.5.mlp.down_proj.scales": "model.safetensors", "model.layers.5.mlp.down_proj.weight": "model.safetensors", "model.layers.5.mlp.gate_proj.biases": "model.safetensors", "model.layers.5.mlp.gate_proj.scales": "model.safetensors", "model.layers.5.mlp.gate_proj.weight": "model.safetensors", "model.layers.5.mlp.up_proj.biases": "model.safetensors", "model.layers.5.mlp.up_proj.scales": "model.safetensors", "model.layers.5.mlp.up_proj.weight": "model.safetensors", "model.layers.5.post_attention_layernorm.weight": "model.safetensors", "model.layers.5.self_attn.k_norm.weight": "model.safetensors", "model.layers.5.self_attn.k_proj.biases": "model.safetensors", "model.layers.5.self_attn.k_proj.scales": "model.safetensors", "model.layers.5.self_attn.k_proj.weight": "model.safetensors", "model.layers.5.self_attn.o_proj.biases": "model.safetensors", "model.layers.5.self_attn.o_proj.scales": "model.safetensors", "model.layers.5.self_attn.o_proj.weight": "model.safetensors", "model.layers.5.self_attn.q_norm.weight": "model.safetensors", "model.layers.5.self_attn.q_proj.biases": "model.safetensors", "model.layers.5.self_attn.q_proj.scales": "model.safetensors", "model.layers.5.self_attn.q_proj.weight": "model.safetensors", "model.layers.5.self_attn.v_proj.biases": "model.safetensors", "model.layers.5.self_attn.v_proj.scales": "model.safetensors", "model.layers.5.self_attn.v_proj.weight": "model.safetensors", "model.layers.6.input_layernorm.weight": "model.safetensors", "model.layers.6.mlp.down_proj.biases": "model.safetensors", "model.layers.6.mlp.down_proj.scales": "model.safetensors", "model.layers.6.mlp.down_proj.weight": "model.safetensors", "model.layers.6.mlp.gate_proj.biases": "model.safetensors", "model.layers.6.mlp.gate_proj.scales": "model.safetensors", "model.layers.6.mlp.gate_proj.weight": "model.safetensors", "model.layers.6.mlp.up_proj.biases": "model.safetensors", "model.layers.6.mlp.up_proj.scales": "model.safetensors", "model.layers.6.mlp.up_proj.weight": "model.safetensors", "model.layers.6.post_attention_layernorm.weight": "model.safetensors", "model.layers.6.self_attn.k_norm.weight": "model.safetensors", "model.layers.6.self_attn.k_proj.biases": "model.safetensors", "model.layers.6.self_attn.k_proj.scales": "model.safetensors", "model.layers.6.self_attn.k_proj.weight": "model.safetensors", "model.layers.6.self_attn.o_proj.biases": "model.safetensors", "model.layers.6.self_attn.o_proj.scales": "model.safetensors", "model.layers.6.self_attn.o_proj.weight": "model.safetensors", "model.layers.6.self_attn.q_norm.weight": "model.safetensors", "model.layers.6.self_attn.q_proj.biases": "model.safetensors", "model.layers.6.self_attn.q_proj.scales": "model.safetensors", "model.layers.6.self_attn.q_proj.weight": "model.safetensors", "model.layers.6.self_attn.v_proj.biases": "model.safetensors", "model.layers.6.self_attn.v_proj.scales": "model.safetensors", "model.layers.6.self_attn.v_proj.weight": "model.safetensors", "model.layers.7.input_layernorm.weight": "model.safetensors", "model.layers.7.mlp.down_proj.biases": "model.safetensors", "model.layers.7.mlp.down_proj.scales": "model.safetensors", "model.layers.7.mlp.down_proj.weight": "model.safetensors", "model.layers.7.mlp.gate_proj.biases": "model.safetensors", "model.layers.7.mlp.gate_proj.scales": "model.safetensors", "model.layers.7.mlp.gate_proj.weight": "model.safetensors", "model.layers.7.mlp.up_proj.biases": "model.safetensors", "model.layers.7.mlp.up_proj.scales": "model.safetensors", "model.layers.7.mlp.up_proj.weight": "model.safetensors", "model.layers.7.post_attention_layernorm.weight": "model.safetensors", "model.layers.7.self_attn.k_norm.weight": "model.safetensors", "model.layers.7.self_attn.k_proj.biases": "model.safetensors", "model.layers.7.self_attn.k_proj.scales": "model.safetensors", "model.layers.7.self_attn.k_proj.weight": "model.safetensors", "model.layers.7.self_attn.o_proj.biases": "model.safetensors", "model.layers.7.self_attn.o_proj.scales": "model.safetensors", "model.layers.7.self_attn.o_proj.weight": "model.safetensors", "model.layers.7.self_attn.q_norm.weight": "model.safetensors", "model.layers.7.self_attn.q_proj.biases": "model.safetensors", "model.layers.7.self_attn.q_proj.scales": "model.safetensors", "model.layers.7.self_attn.q_proj.weight": "model.safetensors", "model.layers.7.self_attn.v_proj.biases": "model.safetensors", "model.layers.7.self_attn.v_proj.scales": "model.safetensors", "model.layers.7.self_attn.v_proj.weight": "model.safetensors", "model.layers.8.input_layernorm.weight": "model.safetensors", "model.layers.8.mlp.down_proj.biases": "model.safetensors", "model.layers.8.mlp.down_proj.scales": "model.safetensors", "model.layers.8.mlp.down_proj.weight": "model.safetensors", "model.layers.8.mlp.gate_proj.biases": "model.safetensors", "model.layers.8.mlp.gate_proj.scales": "model.safetensors", "model.layers.8.mlp.gate_proj.weight": "model.safetensors", "model.layers.8.mlp.up_proj.biases": "model.safetensors", "model.layers.8.mlp.up_proj.scales": "model.safetensors", "model.layers.8.mlp.up_proj.weight": "model.safetensors", "model.layers.8.post_attention_layernorm.weight": "model.safetensors", "model.layers.8.self_attn.k_norm.weight": "model.safetensors", "model.layers.8.self_attn.k_proj.biases": "model.safetensors", "model.layers.8.self_attn.k_proj.scales": "model.safetensors", "model.layers.8.self_attn.k_proj.weight": "model.safetensors", "model.layers.8.self_attn.o_proj.biases": "model.safetensors", "model.layers.8.self_attn.o_proj.scales": "model.safetensors", "model.layers.8.self_attn.o_proj.weight": "model.safetensors", "model.layers.8.self_attn.q_norm.weight": "model.safetensors", "model.layers.8.self_attn.q_proj.biases": "model.safetensors", "model.layers.8.self_attn.q_proj.scales": "model.safetensors", "model.layers.8.self_attn.q_proj.weight": "model.safetensors", "model.layers.8.self_attn.v_proj.biases": "model.safetensors", "model.layers.8.self_attn.v_proj.scales": "model.safetensors", "model.layers.8.self_attn.v_proj.weight": "model.safetensors", "model.layers.9.input_layernorm.weight": "model.safetensors", "model.layers.9.mlp.down_proj.biases": "model.safetensors", "model.layers.9.mlp.down_proj.scales": "model.safetensors", "model.layers.9.mlp.down_proj.weight": "model.safetensors", "model.layers.9.mlp.gate_proj.biases": "model.safetensors", "model.layers.9.mlp.gate_proj.scales": "model.safetensors", "model.layers.9.mlp.gate_proj.weight": "model.safetensors", "model.layers.9.mlp.up_proj.biases": "model.safetensors", "model.layers.9.mlp.up_proj.scales": "model.safetensors", "model.layers.9.mlp.up_proj.weight": "model.safetensors", "model.layers.9.post_attention_layernorm.weight": "model.safetensors", "model.layers.9.self_attn.k_norm.weight": "model.safetensors", "model.layers.9.self_attn.k_proj.biases": "model.safetensors", "model.layers.9.self_attn.k_proj.scales": "model.safetensors", "model.layers.9.self_attn.k_proj.weight": "model.safetensors", "model.layers.9.self_attn.o_proj.biases": "model.safetensors", "model.layers.9.self_attn.o_proj.scales": "model.safetensors", "model.layers.9.self_attn.o_proj.weight": "model.safetensors", "model.layers.9.self_attn.q_norm.weight": "model.safetensors", "model.layers.9.self_attn.q_proj.biases": "model.safetensors", "model.layers.9.self_attn.q_proj.scales": "model.safetensors", "model.layers.9.self_attn.q_proj.weight": "model.safetensors", "model.layers.9.self_attn.v_proj.biases": "model.safetensors", "model.layers.9.self_attn.v_proj.scales": "model.safetensors", "model.layers.9.self_attn.v_proj.weight": "model.safetensors", "model.norm.weight": "model.safetensors" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091from transformers.configuration_utils import PretrainedConfigfrom transformers.modeling_rope_utils import rope_config_validationfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class CoDAConfig(PretrainedConfig): model_type = "CoDA" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, vocab_size=151936, head_dim=128, hidden_act="silu", hidden_size=2048, intermediate_size=6144, num_attention_heads=16, num_hidden_layers=28, num_key_value_heads=8, max_position_embeddings=40960, initializer_range=0.02, use_cache=True, use_sliding_window=False, tie_word_embeddings=True, rms_norm_eps=1e-6, rope_scaling=None, rope_theta=1000000, sliding_window=None, max_window_layers=28, attention_bias=False, attention_dropout=0.0, bos_token_id=151643, eos_token_id=151645, pad_token_id=151643, mask_token_id=151669, attention_kernel="flash_attention", prefix_probability=0, truncate_probability=0, block_masking_probability=[0.25, 0.5, 0.5, 0.75, 0.25], mask_block_sizes=[4, 8, 16, 32], sampling_eps=[0.001, 0.25, 0.5, 0.25, 0.001], # minimum noise level **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window if use_sliding_window else None self.max_window_layers = max_window_layers
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_dropout = attention_dropout # Validate the correctness of rotary position embeddings parameters # BC: if there is a 'type' field, move it to 'rope_type'. if self.rope_scaling is not None and "type" in self.rope_scaling: self.rope_scaling["rope_type"] = self.rope_scaling["type"] rope_config_validation(self)
self.head_dim = head_dim self.attention_bias = attention_bias self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id self.attention_kernel = attention_kernel self.prefix_probability = prefix_probability self.truncate_probability = truncate_probability self.block_masking_probability = block_masking_probability self.mask_block_sizes = mask_block_sizes self.sampling_eps = sampling_eps
super().__init__( tie_word_embeddings=tie_word_embeddings, **kwargs, ) self.mask_token_id = mask_token_id self.pad_token_id = pad_token_id123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558"""Adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3/modeling_qwen3.py"""
from typing import Callable, Optional, Tuple, Union
import torchfrom torch import nnfrom transformers import PreTrainedModelfrom transformers.activations import ACT2FNfrom transformers.utils import loggingfrom .model_config import CoDAConfigfrom .attention import AttentionModulefrom .modeling_utils import ( HomogeneousSequential, RopeScaling, default_rope_frequencies, apply_rotary_pos_emb, transition, prefix_input_ids, truncate_input_ids,)from .generation_utils import DLMGenerationMixin, DLMGenerationConfig
logger = logging.get_logger(__name__)
class CoDARMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype)
def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
class CoDAMLP(nn.Module): def __init__(self, config: CoDAConfig): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj
class CoDAAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: CoDAConfig, layer_idx: int | None = None): super().__init__() self.config = config self.attention_block = AttentionModule(config) self.layer_idx = layer_idx if layer_idx is None: logger.warning_once( f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will " "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads) self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = getattr(config, "attention_dropout", 0.0) # weiran: diffullama self.is_causal = False
self.q_proj = nn.Linear( self.hidden_size, self.num_heads * self.head_dim, bias=getattr(config, "attention_bias", False), ) self.k_proj = nn.Linear( self.hidden_size, self.num_key_value_heads * self.head_dim, bias=getattr(config, "attention_bias", False), ) self.v_proj = nn.Linear( self.hidden_size, self.num_key_value_heads * self.head_dim, bias=getattr(config, "attention_bias", False), ) self.o_proj = nn.Linear( self.num_heads * self.head_dim, self.hidden_size, bias=getattr(config, "attention_bias", False), ) self.q_norm = CoDARMSNorm( self.head_dim, eps=getattr(config, "rms_norm_eps", 1e-6) ) self.k_norm = CoDARMSNorm( self.head_dim, eps=getattr(config, "rms_norm_eps", 1e-6) )
def forward( self, hidden_states: torch.Tensor, position_embeddings: Tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, ) -> torch.FloatTensor: bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
# Apply q_norm and k_norm to the head dimension query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim) key_states = key_states.view( bsz, q_len, self.num_key_value_heads, self.head_dim ) value_states = value_states.view( bsz, q_len, self.num_key_value_heads, self.head_dim )
# Apply normalization query_states = self.q_norm(query_states) key_states = self.k_norm(key_states)
# Transpose to get the right shape for attention query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2)
cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb( query_states, key_states, cos, sin )
attn_output = self.attention_block( query_states, key_states, value_states, attention_mask ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) attn_output = self.o_proj(attn_output) return attn_output
class CoDARotaryEmbedding(nn.Module): inv_freq: nn.Buffer
def __init__( self, head_dim, rope_theta, scaling: RopeScaling | None = None, ): super().__init__() if scaling is None: inv_freq = default_rope_frequencies(head_dim, theta=rope_theta) else: raise NotImplementedError("Scaling is not implemented") self.register_buffer("inv_freq", inv_freq, persistent=False)
@torch.no_grad() def forward(self, x, position_ids): # x: [bs, num_attention_heads, seq_len, head_size] inv_freq_expanded = ( self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) ) position_ids_expanded = position_ids[:, None, :].float() # Force float32 since bfloat16 loses precision on long contexts # See https://github.com/huggingface/transformers/pull/29285 device_type = x.device.type device_type = ( device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" ) with torch.autocast(device_type=device_type, enabled=False): freqs = ( inv_freq_expanded.float() @ position_ids_expanded.float() ).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() sin = emb.sin() return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
class CoDADecoderLayer(nn.Module): def __init__(self, config: CoDAConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.layer_idx = layer_idx
self.self_attn = CoDAAttention(config=config, layer_idx=layer_idx)
self.mlp = CoDAMLP(config) self.input_layernorm = CoDARMSNorm( config.hidden_size, eps=getattr(config, "rms_norm_eps", 1e-6) ) self.post_attention_layernorm = CoDARMSNorm( config.hidden_size, eps=getattr(config, "rms_norm_eps", 1e-6) )
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.Tensor | None = None, position_embeddings: ( tuple[torch.Tensor, torch.Tensor] | None ) = None, # necessary, but kept here for BC ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. """ # This gives the `hidden_states` tensor a name so that we can layer specify # to offload this tensor to host RAM to save memory. This is not a standard # torch API because there is no such feature in PyTorch. Instead, the name # becomes node metadata during FX graph capture.
residual = hidden_states hidden_states = self.input_layernorm(hidden_states)
# Self Attention hidden_states = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, position_embeddings=position_embeddings, ) hidden_states = residual + hidden_states
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states
return hidden_states
class CoDAModel(PreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers.
Args: config: FlexConfig """ config_class = CoDAConfig
def __init__(self, config: CoDAConfig): super().__init__(config=config) self.vocab_size = config.vocab_size if "pad_token_id" not in config: self.padding_idx = None else: self.padding_idx = config.pad_token_id self.embed_tokens = nn.Embedding( config.vocab_size, config.hidden_size, padding_idx=self.padding_idx ) # `HomogeneousSequential` is similar to `nn.Sequential` but can be compiled with # `scan` described in https://pytorch.org/xla/release/r2.6/features/scan.html. self.layers = HomogeneousSequential( *[ CoDADecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers) ] ) self.norm = CoDARMSNorm( config.hidden_size, eps=getattr(config, "rms_norm_eps", 1e-6) )
rope_scaling = getattr(config, "rope_scaling", None) head_dim = getattr( config, "head_dim", config.hidden_size // config.num_attention_heads ) self.rope_theta = getattr(config, "rope_theta", 10000.0) if rope_scaling is not None: rope_scaling = RopeScaling(**rope_scaling) self.rotary_emb = CoDARotaryEmbedding( head_dim=head_dim, rope_theta=self.rope_theta, scaling=rope_scaling ) self.post_init()
def _init_weights(self, module): std = getattr(self.config, "initializer_range", 0.02) if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.FloatTensor | None = None, ) -> torch.Tensor: # convert input ids to embeddings inputs_embeds = self.embed_tokens(input_ids)
seq_length = inputs_embeds.size(1)
position_ids = ( torch.arange(seq_length, device=inputs_embeds.device).unsqueeze(0).float() )
# Create a causal attention mask causal_mask = torch.triu( torch.full( (seq_length, seq_length), float("-inf"), device=inputs_embeds.device ), diagonal=1, ) causal_mask = causal_mask.unsqueeze(0).unsqueeze( 0 ) # Add batch and head dimension
if attention_mask is not None: causal_mask = causal_mask * attention_mask[:, None, None, :]
hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids)
# decoder layers hidden_states = self.layers( hidden_states, attention_mask=causal_mask, position_ids=position_ids, position_embeddings=position_embeddings, )
hidden_states = self.norm(hidden_states)
return hidden_states
class CoDALanguageModel(DLMGenerationMixin, PreTrainedModel): config_class = CoDAConfig base_model_prefix = "model" is_parallelizable = True supports_gradient_checkpointing = False _no_split_modules = ["FlexDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn_2 = True _supports_sdpa = True _supports_cache_class = True
def __init__(self, config: CoDAConfig): super().__init__(config) self.config = config self.model = CoDAModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.mask_token_id = config.mask_token_id self.generation_config = DLMGenerationConfig(mask_token_id=config.mask_token_id) self.apply(self._init_weights)
def _init_weights(self, module): std = getattr(self.config, "initializer_range", 0.02) if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
def get_embeds(self, input_ids): """ Get input embeddings from the model. This method is used by the diffusion trainer to access embeddings. """ return self.model.embed_tokens(input_ids)
def forward( self, input_ids: torch.LongTensor, labels: torch.LongTensor | None = None, attention_mask: torch.FloatTensor | None = None, src_mask: torch.BoolTensor | None = None, training_mode: str = "pretrain", **kwargs, ) -> tuple[torch.FloatTensor, torch.FloatTensor | None]: if not self.training: model_output = self.model( input_ids=input_ids, attention_mask=None ) hidden_states = model_output logits = self.lm_head(hidden_states) # NOTE: we shift logits at inference time return logits, None
if training_mode == "sft" and src_mask is None: raise ValueError("SFT mode requires a non-null src_mask")
epoch = kwargs.get("epoch", None) sampling_eps = getattr( self.config, "sampling_eps", 1e-3 ) # NOTE: use sampling_eps to control the noise level # If sampling_eps is a list, choose based on epoch if isinstance(sampling_eps, list): if epoch is None: # If epoch is not provided, use the first value sampling_eps = sampling_eps[0] else: # Use modulo to cycle through the list if epoch exceeds list length sampling_eps = sampling_eps[epoch % len(sampling_eps)]
mask_token_id = self.mask_token_id loss_func = nn.CrossEntropyLoss(reduction="none") batch_size, seq_len = input_ids.shape # input_ids: [batch_size, seq_len] masking_schedule = kwargs.get("masking_schedule", None)
# Create maskable_mask based on training mode and src_mask # For SFT: src_mask is provided, maskable_mask = ~src_mask # For pretrain: src_mask is None, maskable_mask = all True
if src_mask is not None: maskable_mask = ~src_mask else: # pretrain or midtrain maskable_mask = torch.ones_like( input_ids, dtype=torch.bool, device=input_ids.device ) if masking_schedule is not None: prefix_probability = masking_schedule.get("prefix_probability", 0) truncate_probability = masking_schedule.get("truncate_probability", 0) else: prefix_probability = getattr(self.config, "prefix_probability", 0) truncate_probability = getattr(self.config, "truncate_probability", 0) if training_mode == "sft": prefix_probability = 0 truncate_probability = 0 # Generate random decisions for all batch items apply_prefix = ( torch.rand(batch_size, device=input_ids.device) < prefix_probability ) # Only apply truncation to rows that are NOT prefixed apply_truncate = ( torch.rand(batch_size, device=input_ids.device) < truncate_probability ) apply_truncate = apply_truncate & ~apply_prefix
if prefix_probability > 0: maskable_mask = prefix_input_ids(input_ids, maskable_mask, apply_prefix) if truncate_probability > 0: input_ids = truncate_input_ids( input_ids, apply_truncate, self.config.pad_token_id ) maskable_mask = maskable_mask & (input_ids != self.config.pad_token_id)
# add noise to input_ids sigma = (1 - sampling_eps) * torch.rand( input_ids.shape[0], device=input_ids.device ) + sampling_eps dsigma = torch.reciprocal(sigma)
# Sample mask block size # Use mask_block_sizes from masking_probs if provided, otherwise fall back to config if masking_schedule is not None and "mask_block_sizes" in masking_schedule: mask_block_sizes = masking_schedule["mask_block_sizes"] else: mask_block_sizes = getattr(self.config, "mask_block_sizes", None) # Use masking_config if provided, otherwise fall back to config values if masking_schedule is not None: block_masking_probability = masking_schedule.get( "block_masking_probability", 0 ) else: block_masking_probability = getattr( self.config, "block_masking_probability", 0 ) if isinstance(block_masking_probability, list): if epoch is None: block_masking_probability = block_masking_probability[0] else: block_masking_probability = block_masking_probability[ epoch % len(block_masking_probability) ]
if block_masking_probability > 0 and mask_block_sizes is not None and len(mask_block_sizes) > 0: mask_block_size = mask_block_sizes[ torch.randint(0, len(mask_block_sizes), (1,)).item() ] else: mask_block_size = 1
noisy_input_ids = transition( input_ids, sigma[:, None], maskable_mask=maskable_mask, mask_token_id=mask_token_id, mask_block_size=mask_block_size, ) loss_mask = noisy_input_ids == mask_token_id
# Use gradient checkpointing if enabled if ( hasattr(self, "gradient_checkpointing") and self.gradient_checkpointing and self.training ): # Define a function for gradient checkpointing def custom_forward(*inputs): return self.model(*inputs)
# Apply gradient checkpointing to the model forward pass hidden_states = self._gradient_checkpointing_func( custom_forward, noisy_input_ids, attention_mask ) else: hidden_states = self.model( input_ids=noisy_input_ids, attention_mask=attention_mask )
logits = self.lm_head(hidden_states) logits = logits.float() # logits: [bs, seq_len, vocab_size] # Shifted logits and labels # logits: [bs, seq_len-1, vocab_size] logits = logits[..., :-1, :].contiguous() # weiran: if the shifted token is not masked in the original input, the loss is 0 # loss_mask: [bs, seq_len-1] loss_mask = loss_mask[..., 1:].contiguous() target_ids = input_ids[..., 1:].contiguous() # loss: [bs, seq_len-1] loss = loss_func( logits.reshape(-1, logits.shape[-1]), target_ids.reshape(-1) ).reshape(target_ids.shape[0], -1) loss = loss.masked_fill(~loss_mask, 0) # weiran: divide by the number of tokens in the sequence instead of the number of masked tokens # justification is dsigma already accounts for the number of masked tokens # this is a hack to get something like per token loss # https://github.com/ML-GSAI/SMDM/blob/main/pretrain/train_mdm_rl.py#L281-L283 loss = (dsigma[:, None] * loss).sum() / ( input_ids.shape[0] * input_ids.shape[1] ) return logits, loss123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224from typing import Callable, Optional, Tuple, Unionfrom dataclasses import dataclass
import torchfrom torch import nn
class HomogeneousSequential(nn.Sequential): """ HomogenousSequential is a sequential container that requires all child modules to be of the same type and have matching input/output shapes. In turn, it may be compiled with the `scan` higher order operator to save compile time. """
repeated_layer: type """The type of the layer being looped over."""
def __init__(self, *args: nn.Module) -> None: super().__init__(*args) types = set(type(module) for module in args) assert len(types) == 1, f"All modules must be of the same type. Got {types}" self.repeated_layer = types.pop()
def forward(self, *input, **broadcasted_inputs): """ Much like `torch.nn.Sequential`, this takes `input` and forwards it to the first module it contains. It then "chains" outputs to inputs sequentially for each subsequent module, finally returning the output of the last module. Different from `torch.nn.Sequential`, you may specify `broadcasted_inputs` via keyword arguments. The same keyword arguments will be passed to every layer without changes (i.e. "broadcasted"). """ for module in self: input = module(*splat(input), **broadcasted_inputs) return input
def splat(input): if not isinstance(input, list | tuple): input = (input,) return input
@dataclass(kw_only=True)class RopeScaling: """ RoPE scaling parameters. The defaults are what was selected in Llama 3.1. """ factor: float = 8.0 low_freq_factor: float = 1.0 high_freq_factor: float = 4.0 original_context_len: int = 8192
def default_rope_frequencies( head_dim: int, theta: float = 10000.0,) -> torch.Tensor: """ Computes the original RoPE frequencies in e.g. Llama 2. Args: head_dim: the size of a single attention head. theta: a hyperparameter controlling how fast the embeddings rotate. Returns: The frequencies for the RoPE embeddings. """ return 1.0 / ( theta ** (torch.arange(0, head_dim, 2, dtype=torch.int64).float() / head_dim) )
def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors.
Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`, *optional*): Deprecated and unused. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
def transition(x_0, sigma, maskable_mask, mask_token_id, mask_block_size: int = 1): """Apply masking to input tokens. If mask_block_size > 1, use block masking for all rows."""
if mask_block_size == 1: # Original behavior # weiran: diffullama move_indices = ( torch.rand(*x_0.shape, device=x_0.device) < sigma ) & maskable_mask x_t = torch.where(move_indices, mask_token_id, x_0) return x_t
# Block masking for entire batch return block_masking(x_0, sigma, maskable_mask, mask_token_id, mask_block_size)
def block_masking(x_0, sigma, maskable_mask, mask_token_id, mask_block_size): """ XLA-compatible block masking applied uniformly to all rows in the batch. Uses efficient tensor operations to avoid dynamic loops. """ batch_size, seq_len = x_0.shape
if seq_len < mask_block_size: return x_0
# Calculate number of possible block positions num_windows = seq_len - mask_block_size + 1
# Create all possible block positions: [num_windows, mask_block_size] window_starts = torch.arange(num_windows, device=x_0.device) block_offsets = torch.arange(mask_block_size, device=x_0.device) all_positions = window_starts.unsqueeze(1) + block_offsets.unsqueeze(0)
# Check which blocks are fully maskable: [batch_size, num_windows] maskable_blocks = ( maskable_mask.unsqueeze(1) .expand(-1, num_windows, -1) .gather(2, all_positions.unsqueeze(0).expand(batch_size, -1, -1)) ) fully_maskable = maskable_blocks.all(dim=2)
# Determine which blocks should be masked: (batch_size, num_windows) effective_sigma = 1 - (1 - sigma) ** ( 1 / mask_block_size ) # NOTE: since we mask with blocks, we need to scale sigma by block size should_mask = ( torch.rand(batch_size, num_windows, device=x_0.device) < effective_sigma ) & fully_maskable
# Create final mask using simple broadcasting (fully XLA-compatible) # For each position in the sequence, check if it's part of any masked block position_indices = torch.arange(seq_len, device=x_0.device) # [seq_len]
# Check for each position if it falls within any masked block # position_indices: [seq_len] -> [1, 1, seq_len] # all_positions: [num_windows, mask_block_size] -> [1, num_windows, mask_block_size] # should_mask: [batch_size, num_windows] -> [batch_size, num_windows, 1]
position_indices = position_indices.unsqueeze(0).unsqueeze(0) # [1, 1, seq_len] all_positions = all_positions.unsqueeze(0) # [1, num_windows, mask_block_size] should_mask = should_mask.unsqueeze(2) # [batch_size, num_windows, 1]
# Check if each position matches any of the positions in masked blocks # [1, 1, seq_len] == [1, num_windows, mask_block_size] -> [1, num_windows, seq_len] position_matches = (position_indices == all_positions.unsqueeze(3)).any( dim=2 ) # [1, num_windows, seq_len]
# Apply should_mask to get final positions to mask # [batch_size, num_windows, 1] & [1, num_windows, seq_len] -> [batch_size, num_windows, seq_len] should_mask_positions = should_mask & position_matches
# Reduce over windows: if any window masks this position, mask it final_mask = should_mask_positions.any(dim=1) # [batch_size, seq_len]
# Apply the mask result = torch.where(final_mask, mask_token_id, x_0)
return result
def prefix_input_ids(input_ids, maskable_mask, apply_prefix): """Apply prefix to input_ids based on configured probability. Return a masksable mask such that the prefix is not masked.""" batch_size, seq_len = input_ids.shape # Generate random prefix lengths for all batch items prefix_lengths = torch.randint(1, seq_len, (batch_size,), device=input_ids.device) # Create position indices: [1, seq_len] position_indices = torch.arange(seq_len, device=input_ids.device).unsqueeze( 0 ) # [1, seq_len] # Create prefix mask: True where position < prefix_length prefix_mask = position_indices < prefix_lengths.unsqueeze( 1 ) # [batch_size, seq_len] # Apply prefix masking: set to False where we should apply prefix masking maskable_mask = maskable_mask & ~(apply_prefix.unsqueeze(1) & prefix_mask) return maskable_mask
def truncate_input_ids(input_ids, apply_truncate, pad_token_id): """Truncate input_ids at random position and fill with pad token. Return the input_ids with suffix truncated and filled with pad token.""" batch_size, seq_len = input_ids.shape # Generate random truncation positions for all batch items truncate_positions = torch.randint( 1, seq_len, (batch_size,), device=input_ids.device ) # Create position indices: [1, seq_len] position_indices = torch.arange(seq_len, device=input_ids.device).unsqueeze( 0 ) # [1, seq_len] # Create truncate mask: True where position >= truncate_position truncate_mask = position_indices >= truncate_positions.unsqueeze( 1 ) # [batch_size, seq_len] # Apply truncation: fill with pad token where we should truncate input_ids = torch.where( apply_truncate.unsqueeze(1) & truncate_mask, pad_token_id, input_ids ) return input_ids123version https://git-lfs.github.com/spec/v1oid sha256:69a5551c482eff25ed3d9c5ffe719762c0fc60371f9288827f464e3fa43e713csize 1142283412345678910111213141516171819{ "add_prefix_space": false, "backend": "tokenizers", "bos_token": "<|im_end|>", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "is_local": true, "local_files_only": false, "mask_token": "<|mask|>", "model_max_length": 131072, "pad_token": "<|endoftext|>", "padding_side": "right", "sep_token": "<|file_sep|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "tool_parser_type": "json_tools", "unk_token": null}.gitattributes+1
attention.pyAdded+90
chat_template.jinjaAdded+89
config.jsonAdded+65
generation_config.jsonAdded+12
generation_utils.pyAdded+552
model.safetensorsAdded+3
model.safetensors.index.jsonAdded+715
model_config.pyAdded+91
modeling_coda.pyAdded+558
modeling_utils.pyAdded+224
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+19