update model
Browse files- .gitattributes +1 -0
- added_tokens.json +29 -0
- attention.py +90 -0
- config.json +56 -0
- generation_config.json +12 -0
- generation_utils.py +552 -0
- merges.txt +0 -0
- model-00001-of-00002.safetensors +3 -0
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +318 -0
- model_config.py +91 -0
- modeling_coda.py +558 -0
- modeling_utils.py +224 -0
- special_tokens_map.json +52 -0
- tokenizer.json +3 -0
- tokenizer_config.json +251 -0
- vocab.json +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
added_tokens.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</think>": 151668,
|
| 3 |
+
"</tool_call>": 151658,
|
| 4 |
+
"</tool_response>": 151666,
|
| 5 |
+
"<think>": 151667,
|
| 6 |
+
"<tool_call>": 151657,
|
| 7 |
+
"<tool_response>": 151665,
|
| 8 |
+
"<|box_end|>": 151649,
|
| 9 |
+
"<|box_start|>": 151648,
|
| 10 |
+
"<|endoftext|>": 151643,
|
| 11 |
+
"<|file_sep|>": 151664,
|
| 12 |
+
"<|fim_middle|>": 151660,
|
| 13 |
+
"<|fim_pad|>": 151662,
|
| 14 |
+
"<|fim_prefix|>": 151659,
|
| 15 |
+
"<|fim_suffix|>": 151661,
|
| 16 |
+
"<|im_end|>": 151645,
|
| 17 |
+
"<|im_start|>": 151644,
|
| 18 |
+
"<|image_pad|>": 151655,
|
| 19 |
+
"<|mask|>": 151669,
|
| 20 |
+
"<|object_ref_end|>": 151647,
|
| 21 |
+
"<|object_ref_start|>": 151646,
|
| 22 |
+
"<|quad_end|>": 151651,
|
| 23 |
+
"<|quad_start|>": 151650,
|
| 24 |
+
"<|repo_name|>": 151663,
|
| 25 |
+
"<|video_pad|>": 151656,
|
| 26 |
+
"<|vision_end|>": 151653,
|
| 27 |
+
"<|vision_pad|>": 151654,
|
| 28 |
+
"<|vision_start|>": 151652
|
| 29 |
+
}
|
attention.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn.functional import scaled_dot_product_attention
|
| 7 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
| 8 |
+
from .model_config import CoDAConfig
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 13 |
+
"""
|
| 14 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 15 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 16 |
+
"""
|
| 17 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 18 |
+
if n_rep == 1:
|
| 19 |
+
return hidden_states
|
| 20 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
| 21 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
| 22 |
+
)
|
| 23 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class AttentionModule(nn.Module):
|
| 27 |
+
def __init__(self, config: CoDAConfig, kernel_config: dict[str, Any] | None = None):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.config = config
|
| 30 |
+
self.kernel_config = kernel_config
|
| 31 |
+
self.partition_spec = None
|
| 32 |
+
|
| 33 |
+
def forward(
|
| 34 |
+
self,
|
| 35 |
+
query_states: torch.Tensor,
|
| 36 |
+
key_states: torch.Tensor,
|
| 37 |
+
value_states: torch.Tensor,
|
| 38 |
+
attention_mask: torch.Tensor | None = None,
|
| 39 |
+
):
|
| 40 |
+
"""GPU-optimized PyTorch implementation"""
|
| 41 |
+
|
| 42 |
+
if self.config.attention_kernel != "splash_attention":
|
| 43 |
+
num_key_value_groups = (
|
| 44 |
+
self.config.num_attention_heads // self.config.num_key_value_heads
|
| 45 |
+
)
|
| 46 |
+
key_states = repeat_kv(key_states, num_key_value_groups)
|
| 47 |
+
value_states = repeat_kv(value_states, num_key_value_groups)
|
| 48 |
+
|
| 49 |
+
bsz, num_heads, q_len, head_dim = query_states.size()
|
| 50 |
+
head_dim = value_states.shape[-1]
|
| 51 |
+
kv_seq_len = key_states.shape[-2]
|
| 52 |
+
|
| 53 |
+
# Use SDPA with appropriate backend
|
| 54 |
+
match self.config.attention_kernel:
|
| 55 |
+
case "splash_attention":
|
| 56 |
+
raise NotImplementedError(
|
| 57 |
+
"Splash Attention is not supported in GPU environment"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
case "flash_attention":
|
| 61 |
+
# Try to use flash attention backend, fallback to default if not available
|
| 62 |
+
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
|
| 63 |
+
attn_output = scaled_dot_product_attention(
|
| 64 |
+
query_states,
|
| 65 |
+
key_states,
|
| 66 |
+
value_states,
|
| 67 |
+
dropout_p=(
|
| 68 |
+
self.config.attention_dropout if self.training else 0.0
|
| 69 |
+
),
|
| 70 |
+
is_causal=False, # weiran: causal=False for bi-directional attention
|
| 71 |
+
)
|
| 72 |
+
case _:
|
| 73 |
+
# Default implementation - use math backend for compatibility
|
| 74 |
+
with sdpa_kernel(SDPBackend.MATH):
|
| 75 |
+
attn_output = scaled_dot_product_attention(
|
| 76 |
+
query_states,
|
| 77 |
+
key_states,
|
| 78 |
+
value_states,
|
| 79 |
+
dropout_p=(
|
| 80 |
+
self.config.attention_dropout if self.training else 0.0
|
| 81 |
+
),
|
| 82 |
+
is_causal=False, # weiran: causal=False for bi-directional attention
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
if attn_output.size() != (bsz, num_heads, q_len, head_dim):
|
| 86 |
+
raise ValueError(
|
| 87 |
+
f"`attn_output` should be of size {(bsz, num_heads, q_len, head_dim)}, but is"
|
| 88 |
+
f" {attn_output.size()}"
|
| 89 |
+
)
|
| 90 |
+
return attn_output
|
config.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"CoDALanguageModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"attention_kernel": "flash_attention",
|
| 8 |
+
"auto_map": {
|
| 9 |
+
"AutoConfig": "model_config.CoDAConfig",
|
| 10 |
+
"AutoModel": "modeling_coda.CoDALanguageModel"
|
| 11 |
+
},
|
| 12 |
+
"block_masking_probability": [
|
| 13 |
+
0.25,
|
| 14 |
+
0.5,
|
| 15 |
+
0.5,
|
| 16 |
+
0.75,
|
| 17 |
+
0.25
|
| 18 |
+
],
|
| 19 |
+
"head_dim": 128,
|
| 20 |
+
"hidden_act": "silu",
|
| 21 |
+
"hidden_size": 2048,
|
| 22 |
+
"initializer_range": 0.02,
|
| 23 |
+
"intermediate_size": 6144,
|
| 24 |
+
"mask_block_sizes": [
|
| 25 |
+
4,
|
| 26 |
+
8,
|
| 27 |
+
16,
|
| 28 |
+
32
|
| 29 |
+
],
|
| 30 |
+
"mask_token_id": 151669,
|
| 31 |
+
"max_position_embeddings": 40960,
|
| 32 |
+
"max_window_layers": 28,
|
| 33 |
+
"model_type": "CoDA",
|
| 34 |
+
"num_attention_heads": 16,
|
| 35 |
+
"num_hidden_layers": 28,
|
| 36 |
+
"num_key_value_heads": 8,
|
| 37 |
+
"pad_token_id": 151643,
|
| 38 |
+
"prefix_probability": 0,
|
| 39 |
+
"rms_norm_eps": 1e-06,
|
| 40 |
+
"rope_scaling": null,
|
| 41 |
+
"rope_theta": 1000000,
|
| 42 |
+
"sampling_eps": [
|
| 43 |
+
0.001,
|
| 44 |
+
0.25,
|
| 45 |
+
0.5,
|
| 46 |
+
0.25,
|
| 47 |
+
0.001
|
| 48 |
+
],
|
| 49 |
+
"sliding_window": null,
|
| 50 |
+
"torch_dtype": "float32",
|
| 51 |
+
"transformers_version": "4.47.1",
|
| 52 |
+
"truncate_probability": 0,
|
| 53 |
+
"use_cache": true,
|
| 54 |
+
"use_sliding_window": false,
|
| 55 |
+
"vocab_size": 151936
|
| 56 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"alg": "origin",
|
| 3 |
+
"alg_temp": null,
|
| 4 |
+
"eps": 0.001,
|
| 5 |
+
"mask_token_id": 151669,
|
| 6 |
+
"output_history": false,
|
| 7 |
+
"steps": 512,
|
| 8 |
+
"temperature": 0.0,
|
| 9 |
+
"top_k": null,
|
| 10 |
+
"top_p": null,
|
| 11 |
+
"transformers_version": "4.47.1"
|
| 12 |
+
}
|
generation_utils.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adapted from https://huggingface.co/Dream-org/Dream-v0-Instruct-7B
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# coding=utf-8
|
| 6 |
+
# Copyright 2024 The Dream team, HKUNLP Group and the HuggingFace Inc. team. All rights reserved.
|
| 7 |
+
#
|
| 8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 9 |
+
# you may not use this file except in compliance with the License.
|
| 10 |
+
# You may obtain a copy of the License at
|
| 11 |
+
#
|
| 12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 13 |
+
#
|
| 14 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 17 |
+
# See the License for the specific language governing permissions and
|
| 18 |
+
# limitations under the License.
|
| 19 |
+
|
| 20 |
+
import warnings
|
| 21 |
+
import copy
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.distributions as dists
|
| 27 |
+
from torch.nn import functional as F
|
| 28 |
+
from transformers import __version__
|
| 29 |
+
from transformers.generation.configuration_utils import GenerationConfig
|
| 30 |
+
from transformers.utils import (
|
| 31 |
+
ModelOutput,
|
| 32 |
+
is_torchdynamo_compiling,
|
| 33 |
+
logging,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def top_p_logits(logits, top_p=None):
|
| 40 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 41 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 42 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 43 |
+
# Shift the indices to the right to keep the first token above the threshold
|
| 44 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 45 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 46 |
+
|
| 47 |
+
mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
|
| 48 |
+
mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
|
| 49 |
+
logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
|
| 50 |
+
return logits
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def top_k_logits(logits, top_k=None):
|
| 54 |
+
top_k = min(top_k, logits.size(-1)) # Safety check
|
| 55 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
| 56 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 57 |
+
logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
|
| 58 |
+
return logits
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def sample_tokens(
|
| 62 |
+
logits,
|
| 63 |
+
temperature=0.0,
|
| 64 |
+
top_p=None,
|
| 65 |
+
top_k=None,
|
| 66 |
+
margin_confidence=False,
|
| 67 |
+
neg_entropy=False,
|
| 68 |
+
):
|
| 69 |
+
|
| 70 |
+
if temperature > 0:
|
| 71 |
+
logits = logits / temperature
|
| 72 |
+
if top_p is not None and top_p < 1:
|
| 73 |
+
logits = top_p_logits(logits, top_p)
|
| 74 |
+
if top_k is not None:
|
| 75 |
+
logits = top_k_logits(logits, top_k)
|
| 76 |
+
probs = torch.softmax(logits, dim=-1)
|
| 77 |
+
|
| 78 |
+
if temperature > 0:
|
| 79 |
+
try:
|
| 80 |
+
x0 = dists.Categorical(probs=probs).sample()
|
| 81 |
+
confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
|
| 82 |
+
except:
|
| 83 |
+
confidence, x0 = probs.max(dim=-1)
|
| 84 |
+
else:
|
| 85 |
+
confidence, x0 = probs.max(dim=-1)
|
| 86 |
+
|
| 87 |
+
if margin_confidence:
|
| 88 |
+
sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
|
| 89 |
+
# Extract top1 and top2 probabilities
|
| 90 |
+
top1_probs = sorted_probs[:, 0]
|
| 91 |
+
top2_probs = sorted_probs[:, 1]
|
| 92 |
+
# Calculate confidence as top1 - top2
|
| 93 |
+
confidence = top1_probs - top2_probs
|
| 94 |
+
|
| 95 |
+
if neg_entropy:
|
| 96 |
+
epsilon = 1e-10
|
| 97 |
+
log_probs = torch.log(probs + epsilon)
|
| 98 |
+
confidence = torch.sum(probs * log_probs, dim=-1)
|
| 99 |
+
|
| 100 |
+
return confidence, x0
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class DLMModelOutput(ModelOutput):
|
| 105 |
+
sequences: torch.LongTensor = None
|
| 106 |
+
history: Optional[Tuple[torch.FloatTensor]] = None
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class DLMGenerationConfig(GenerationConfig):
|
| 110 |
+
def __init__(self, **kwargs):
|
| 111 |
+
self.temperature: float = kwargs.pop("temperature", 0.0)
|
| 112 |
+
self.top_p: Optional[float] = kwargs.pop("top_p", None)
|
| 113 |
+
self.top_k: Optional[int] = kwargs.pop("top_k", None)
|
| 114 |
+
self.max_length = kwargs.pop("max_length", 20)
|
| 115 |
+
self.max_new_tokens = kwargs.pop("max_new_tokens", None)
|
| 116 |
+
# diffusion specific params
|
| 117 |
+
self.eps: float = kwargs.pop("eps", 1e-3)
|
| 118 |
+
self.steps: int = kwargs.pop("steps", 512)
|
| 119 |
+
self.alg: str = kwargs.pop("alg", "origin")
|
| 120 |
+
self.alg_temp: Optional[float] = kwargs.pop("alg_temp", None)
|
| 121 |
+
|
| 122 |
+
# Parameters that define the output variables of `generate`
|
| 123 |
+
self.num_return_sequences: int = kwargs.pop("num_return_sequences", 1)
|
| 124 |
+
self.return_dict_in_generate: bool = kwargs.pop(
|
| 125 |
+
"return_dict_in_generate", False
|
| 126 |
+
)
|
| 127 |
+
self.output_history: bool = kwargs.pop("output_history", False)
|
| 128 |
+
|
| 129 |
+
# Special tokens that can be used at generation time
|
| 130 |
+
self.mask_token_id = kwargs.pop("mask_token_id", None)
|
| 131 |
+
self.pad_token_id = kwargs.pop("pad_token_id", None)
|
| 132 |
+
self.bos_token_id = kwargs.pop("bos_token_id", None)
|
| 133 |
+
self.eos_token_id = kwargs.pop("eos_token_id", None)
|
| 134 |
+
|
| 135 |
+
# Wild card
|
| 136 |
+
self.generation_kwargs = kwargs.pop("generation_kwargs", {})
|
| 137 |
+
|
| 138 |
+
# The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub
|
| 139 |
+
# interface.
|
| 140 |
+
self._from_model_config = kwargs.pop("_from_model_config", False)
|
| 141 |
+
self._commit_hash = kwargs.pop("_commit_hash", None)
|
| 142 |
+
self.transformers_version = kwargs.pop("transformers_version", __version__)
|
| 143 |
+
|
| 144 |
+
# Additional attributes without default values
|
| 145 |
+
if not self._from_model_config:
|
| 146 |
+
# we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
|
| 147 |
+
# model's default configuration file
|
| 148 |
+
for key, value in kwargs.items():
|
| 149 |
+
try:
|
| 150 |
+
setattr(self, key, value)
|
| 151 |
+
except AttributeError as err:
|
| 152 |
+
logger.error(f"Can't set {key} with value {value} for {self}")
|
| 153 |
+
raise err
|
| 154 |
+
|
| 155 |
+
# Validate the values of the attributes
|
| 156 |
+
self.validate(is_init=True)
|
| 157 |
+
|
| 158 |
+
def validate(self, is_init=False):
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class DLMGenerationMixin:
|
| 163 |
+
@staticmethod
|
| 164 |
+
def _expand_inputs_for_generation(
|
| 165 |
+
expand_size: int = 1,
|
| 166 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 167 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 168 |
+
) -> Tuple[torch.LongTensor, Dict[str, Any]]:
|
| 169 |
+
"""Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
|
| 170 |
+
# Do not call torch.repeat_interleave if expand_size is 1 because it clones
|
| 171 |
+
# the input tensor and thus requires more memory although no change is applied
|
| 172 |
+
if expand_size == 1:
|
| 173 |
+
return input_ids, attention_mask
|
| 174 |
+
if input_ids is not None:
|
| 175 |
+
input_ids = input_ids.repeat_interleave(expand_size, dim=0)
|
| 176 |
+
if attention_mask is not None:
|
| 177 |
+
attention_mask = attention_mask.repeat_interleave(expand_size, dim=0)
|
| 178 |
+
return input_ids, attention_mask
|
| 179 |
+
|
| 180 |
+
def _validate_generated_length(
|
| 181 |
+
self, generation_config, input_ids_length, has_default_max_length
|
| 182 |
+
):
|
| 183 |
+
"""Performs validation related to the resulting generated length"""
|
| 184 |
+
|
| 185 |
+
# Can't throw warnings/exceptions during compilation
|
| 186 |
+
if is_torchdynamo_compiling():
|
| 187 |
+
return
|
| 188 |
+
|
| 189 |
+
# 1. Max length warnings related to poor parameterization
|
| 190 |
+
if (
|
| 191 |
+
has_default_max_length
|
| 192 |
+
and generation_config.max_new_tokens is None
|
| 193 |
+
and generation_config.max_length == 20
|
| 194 |
+
):
|
| 195 |
+
# 20 is the default max_length of the generation config
|
| 196 |
+
warnings.warn(
|
| 197 |
+
f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
|
| 198 |
+
"generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
|
| 199 |
+
"generation.",
|
| 200 |
+
UserWarning,
|
| 201 |
+
)
|
| 202 |
+
if input_ids_length >= generation_config.max_length:
|
| 203 |
+
input_ids_string = "input_ids"
|
| 204 |
+
raise ValueError(
|
| 205 |
+
f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
|
| 206 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
| 207 |
+
" increasing `max_length` or, better yet, setting `max_new_tokens`."
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def _prepare_generated_length(
|
| 211 |
+
self,
|
| 212 |
+
generation_config,
|
| 213 |
+
has_default_max_length,
|
| 214 |
+
input_ids_length,
|
| 215 |
+
):
|
| 216 |
+
"""Prepared max and min length in generation configs to avoid clashes between similar attributes"""
|
| 217 |
+
|
| 218 |
+
if generation_config.max_new_tokens is not None:
|
| 219 |
+
if not has_default_max_length and generation_config.max_length is not None:
|
| 220 |
+
logger.warning(
|
| 221 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
| 222 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
| 223 |
+
"Please refer to the documentation for more information. "
|
| 224 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
|
| 225 |
+
)
|
| 226 |
+
generation_config.max_length = (
|
| 227 |
+
generation_config.max_new_tokens + input_ids_length
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
elif has_default_max_length:
|
| 231 |
+
if generation_config.max_length == DLMGenerationConfig().max_length:
|
| 232 |
+
generation_config.max_length = (
|
| 233 |
+
generation_config.max_length + input_ids_length
|
| 234 |
+
)
|
| 235 |
+
max_position_embeddings = getattr(
|
| 236 |
+
self.config, "max_position_embeddings", None
|
| 237 |
+
)
|
| 238 |
+
if max_position_embeddings is not None:
|
| 239 |
+
generation_config.max_length = min(
|
| 240 |
+
generation_config.max_length, max_position_embeddings
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
return generation_config
|
| 244 |
+
|
| 245 |
+
def _prepare_generation_config(
|
| 246 |
+
self, generation_config: Optional[DLMGenerationConfig], **kwargs: Dict
|
| 247 |
+
) -> DLMGenerationConfig:
|
| 248 |
+
"""
|
| 249 |
+
Prepares the base generation config, then applies any generation configuration options from kwargs. This
|
| 250 |
+
function handles retrocompatibility with respect to configuration files.
|
| 251 |
+
"""
|
| 252 |
+
# priority: `generation_config` argument > `model.generation_config` (the default generation config)
|
| 253 |
+
using_model_generation_config = False
|
| 254 |
+
if generation_config is None:
|
| 255 |
+
generation_config = DLMGenerationConfig.from_model_config(self.config)
|
| 256 |
+
using_model_generation_config = True
|
| 257 |
+
|
| 258 |
+
# `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
|
| 259 |
+
# will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an
|
| 260 |
+
# exception will be raised in `_validate_model_kwargs`
|
| 261 |
+
if not is_torchdynamo_compiling():
|
| 262 |
+
generation_config = copy.deepcopy(generation_config)
|
| 263 |
+
_kwargs = generation_config.update(**kwargs)
|
| 264 |
+
# If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model
|
| 265 |
+
if not using_model_generation_config:
|
| 266 |
+
if generation_config.bos_token_id is None:
|
| 267 |
+
generation_config.bos_token_id = self.generation_config.bos_token_id
|
| 268 |
+
if generation_config.eos_token_id is None:
|
| 269 |
+
generation_config.eos_token_id = self.generation_config.eos_token_id
|
| 270 |
+
if generation_config.pad_token_id is None:
|
| 271 |
+
generation_config.pad_token_id = self.generation_config.pad_token_id
|
| 272 |
+
if generation_config.mask_token_id is None:
|
| 273 |
+
generation_config.mask_token_id = (
|
| 274 |
+
self.generation_config.mask_token_id
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
return generation_config
|
| 278 |
+
|
| 279 |
+
def _prepare_special_tokens(
|
| 280 |
+
self,
|
| 281 |
+
generation_config: DLMGenerationConfig,
|
| 282 |
+
device: Optional[Union[torch.device, str]] = None,
|
| 283 |
+
):
|
| 284 |
+
"""
|
| 285 |
+
Prepares the special tokens for generation, overwriting the generation config with their processed versions
|
| 286 |
+
converted to tensor.
|
| 287 |
+
|
| 288 |
+
Note that `generation_config` is changed in place and stops being serializable after this method is called.
|
| 289 |
+
That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
|
| 290 |
+
function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
# Convert special tokens to tensors
|
| 294 |
+
def _tensor_or_none(token, device=None):
|
| 295 |
+
if token is None:
|
| 296 |
+
return token
|
| 297 |
+
|
| 298 |
+
device = device if device is not None else self.device
|
| 299 |
+
if isinstance(token, torch.Tensor):
|
| 300 |
+
return token.to(device)
|
| 301 |
+
return torch.tensor(token, device=device, dtype=torch.long)
|
| 302 |
+
|
| 303 |
+
bos_token_tensor = _tensor_or_none(
|
| 304 |
+
generation_config.bos_token_id, device=device
|
| 305 |
+
)
|
| 306 |
+
eos_token_tensor = _tensor_or_none(
|
| 307 |
+
generation_config.eos_token_id, device=device
|
| 308 |
+
)
|
| 309 |
+
pad_token_tensor = _tensor_or_none(
|
| 310 |
+
generation_config.pad_token_id, device=device
|
| 311 |
+
)
|
| 312 |
+
mask_token_tensor = _tensor_or_none(
|
| 313 |
+
generation_config.mask_token_id, device=device
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
|
| 317 |
+
if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
|
| 318 |
+
eos_token_tensor = eos_token_tensor.unsqueeze(0)
|
| 319 |
+
|
| 320 |
+
# Set pad token if unset (and there are conditions to do so)
|
| 321 |
+
if pad_token_tensor is None and eos_token_tensor is not None:
|
| 322 |
+
pad_token_tensor = eos_token_tensor[0]
|
| 323 |
+
logger.warning(
|
| 324 |
+
f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation."
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Update generation config with the updated special tokens tensors
|
| 328 |
+
# NOTE: this must be written into a different attribute name than the one holding the original special tokens
|
| 329 |
+
# (in their non-tensor form), in order to enable end-to-end compilation. See
|
| 330 |
+
# https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
|
| 331 |
+
generation_config._bos_token_tensor = bos_token_tensor
|
| 332 |
+
generation_config._eos_token_tensor = eos_token_tensor
|
| 333 |
+
generation_config._pad_token_tensor = pad_token_tensor
|
| 334 |
+
generation_config._mask_token_tensor = mask_token_tensor
|
| 335 |
+
|
| 336 |
+
@torch.no_grad()
|
| 337 |
+
def diffusion_generate(
|
| 338 |
+
self,
|
| 339 |
+
inputs: Optional[torch.Tensor] = None,
|
| 340 |
+
generation_config: Optional[DLMGenerationConfig] = None,
|
| 341 |
+
**kwargs,
|
| 342 |
+
) -> Union[DLMModelOutput, torch.LongTensor]:
|
| 343 |
+
# 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
|
| 344 |
+
generation_config = self._prepare_generation_config(generation_config, **kwargs)
|
| 345 |
+
generation_tokens_hook_func = kwargs.pop(
|
| 346 |
+
"generation_tokens_hook_func", lambda step, x, logits: x
|
| 347 |
+
)
|
| 348 |
+
generation_logits_hook_func = kwargs.pop(
|
| 349 |
+
"generation_logits_hook_func", lambda step, x, logits: logits
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
# 2. Define model inputs
|
| 353 |
+
assert inputs is not None
|
| 354 |
+
input_ids = inputs
|
| 355 |
+
device = input_ids.device
|
| 356 |
+
attention_mask = kwargs.pop("attention_mask", None)
|
| 357 |
+
self._prepare_special_tokens(generation_config, device=device)
|
| 358 |
+
|
| 359 |
+
# 3. Prepare `max_length`.
|
| 360 |
+
input_ids_length = input_ids.shape[-1]
|
| 361 |
+
has_default_max_length = (
|
| 362 |
+
kwargs.get("max_length") is None
|
| 363 |
+
and generation_config.max_length is not None
|
| 364 |
+
)
|
| 365 |
+
generation_config = self._prepare_generated_length(
|
| 366 |
+
generation_config=generation_config,
|
| 367 |
+
has_default_max_length=has_default_max_length,
|
| 368 |
+
input_ids_length=input_ids_length,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
self._validate_generated_length(
|
| 372 |
+
generation_config, input_ids_length, has_default_max_length
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# 4. Check input_ids
|
| 376 |
+
if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type:
|
| 377 |
+
warnings.warn(
|
| 378 |
+
"You are calling .generate() with the `input_ids` being on a device type different"
|
| 379 |
+
f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
|
| 380 |
+
f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
|
| 381 |
+
" Please make sure that you have put `input_ids` to the"
|
| 382 |
+
f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
|
| 383 |
+
" running `.generate()`.",
|
| 384 |
+
UserWarning,
|
| 385 |
+
)
|
| 386 |
+
if (
|
| 387 |
+
hasattr(generation_config, "pad_token_id")
|
| 388 |
+
and torch.any(input_ids == generation_config.pad_token_id)
|
| 389 |
+
and attention_mask is None
|
| 390 |
+
):
|
| 391 |
+
warnings.warn(
|
| 392 |
+
"Padding was detected but no attention mask is passed here. For correct "
|
| 393 |
+
"generation results, please set `attention_mask` when batch-padding inputs.",
|
| 394 |
+
UserWarning,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
input_ids, attention_mask = self._expand_inputs_for_generation(
|
| 398 |
+
expand_size=generation_config.num_return_sequences,
|
| 399 |
+
input_ids=input_ids,
|
| 400 |
+
attention_mask=attention_mask,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
result = self._sample(
|
| 404 |
+
input_ids,
|
| 405 |
+
attention_mask=attention_mask,
|
| 406 |
+
generation_config=generation_config,
|
| 407 |
+
generation_tokens_hook_func=generation_tokens_hook_func,
|
| 408 |
+
generation_logits_hook_func=generation_logits_hook_func,
|
| 409 |
+
)
|
| 410 |
+
return result
|
| 411 |
+
|
| 412 |
+
def _sample(
|
| 413 |
+
self,
|
| 414 |
+
input_ids: torch.LongTensor,
|
| 415 |
+
attention_mask: Optional[torch.LongTensor],
|
| 416 |
+
generation_config: DLMGenerationConfig,
|
| 417 |
+
generation_tokens_hook_func,
|
| 418 |
+
generation_logits_hook_func,
|
| 419 |
+
) -> Union[DLMModelOutput, torch.LongTensor]:
|
| 420 |
+
# init values
|
| 421 |
+
output_history = generation_config.output_history
|
| 422 |
+
return_dict_in_generate = generation_config.return_dict_in_generate
|
| 423 |
+
max_length = generation_config.max_length
|
| 424 |
+
mask_token_id = generation_config.mask_token_id
|
| 425 |
+
steps = generation_config.steps
|
| 426 |
+
eps = generation_config.eps
|
| 427 |
+
alg = generation_config.alg
|
| 428 |
+
alg_temp = generation_config.alg_temp
|
| 429 |
+
temperature = generation_config.temperature
|
| 430 |
+
top_p = generation_config.top_p
|
| 431 |
+
top_k = generation_config.top_k
|
| 432 |
+
|
| 433 |
+
histories = [] if (return_dict_in_generate and output_history) else None
|
| 434 |
+
|
| 435 |
+
# pad input_ids to max_length
|
| 436 |
+
x = F.pad(input_ids, (0, max_length - input_ids.shape[1]), value=mask_token_id)
|
| 437 |
+
|
| 438 |
+
if attention_mask is not None and torch.any(attention_mask == 0.0):
|
| 439 |
+
# we do not mask the [MASK] tokens so value = 1.0
|
| 440 |
+
attention_mask = F.pad(
|
| 441 |
+
attention_mask, (0, max_length - attention_mask.shape[1]), value=1.0
|
| 442 |
+
)
|
| 443 |
+
# attention_mask is of shape [B, N]
|
| 444 |
+
# broadcast to [B, 1, N, N]
|
| 445 |
+
attention_mask = torch.logical_and(
|
| 446 |
+
attention_mask.unsqueeze(1).unsqueeze(-2),
|
| 447 |
+
attention_mask.unsqueeze(1).unsqueeze(-1),
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
timesteps = torch.linspace(1, eps, steps + 1, device=x.device)
|
| 451 |
+
|
| 452 |
+
# this allows user-defined token control of the intermediate steps
|
| 453 |
+
x = generation_tokens_hook_func(None, x, None)
|
| 454 |
+
for i in range(steps):
|
| 455 |
+
mask_index = x == mask_token_id
|
| 456 |
+
logits, _ = self(x, attention_mask=attention_mask)
|
| 457 |
+
logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1)
|
| 458 |
+
|
| 459 |
+
# this allows user-defined logits control of the intermediate steps
|
| 460 |
+
logits = generation_logits_hook_func(i, x, logits)
|
| 461 |
+
|
| 462 |
+
mask_logits = logits[mask_index]
|
| 463 |
+
t = timesteps[i]
|
| 464 |
+
s = timesteps[i + 1]
|
| 465 |
+
|
| 466 |
+
if alg == "origin":
|
| 467 |
+
p_transfer = 1 - s / t if i < steps - 1 else 1
|
| 468 |
+
x0 = (
|
| 469 |
+
torch.zeros_like(
|
| 470 |
+
x[mask_index], device=self.device, dtype=torch.long
|
| 471 |
+
)
|
| 472 |
+
+ mask_token_id
|
| 473 |
+
)
|
| 474 |
+
transfer_index_t_s = (
|
| 475 |
+
torch.rand(*x0.shape, device=self.device) < p_transfer
|
| 476 |
+
)
|
| 477 |
+
_, x0[transfer_index_t_s] = sample_tokens(
|
| 478 |
+
mask_logits[transfer_index_t_s],
|
| 479 |
+
temperature=temperature,
|
| 480 |
+
top_p=top_p,
|
| 481 |
+
top_k=top_k,
|
| 482 |
+
)
|
| 483 |
+
x[mask_index] = x0.clone()
|
| 484 |
+
else:
|
| 485 |
+
if alg == "maskgit_plus":
|
| 486 |
+
confidence, x0 = sample_tokens(
|
| 487 |
+
mask_logits, temperature=temperature, top_p=top_p, top_k=top_k
|
| 488 |
+
)
|
| 489 |
+
elif alg == "topk_margin":
|
| 490 |
+
confidence, x0 = sample_tokens(
|
| 491 |
+
mask_logits,
|
| 492 |
+
temperature=temperature,
|
| 493 |
+
top_p=top_p,
|
| 494 |
+
top_k=top_k,
|
| 495 |
+
margin_confidence=True,
|
| 496 |
+
)
|
| 497 |
+
elif alg == "entropy":
|
| 498 |
+
confidence, x0 = sample_tokens(
|
| 499 |
+
mask_logits,
|
| 500 |
+
temperature,
|
| 501 |
+
top_p=top_p,
|
| 502 |
+
top_k=top_k,
|
| 503 |
+
neg_entropy=True,
|
| 504 |
+
)
|
| 505 |
+
else:
|
| 506 |
+
raise RuntimeError(f"Unknown alg: {alg}")
|
| 507 |
+
num_mask_token = mask_index.sum() / mask_index.shape[0]
|
| 508 |
+
number_transfer_tokens = (
|
| 509 |
+
int(num_mask_token * (1 - s / t))
|
| 510 |
+
if i < steps - 1
|
| 511 |
+
else int(num_mask_token)
|
| 512 |
+
)
|
| 513 |
+
full_confidence = torch.full_like(
|
| 514 |
+
x, -torch.inf, device=self.device, dtype=logits.dtype
|
| 515 |
+
)
|
| 516 |
+
full_confidence[mask_index] = confidence
|
| 517 |
+
if number_transfer_tokens > 0:
|
| 518 |
+
if alg_temp is None or alg_temp == 0:
|
| 519 |
+
_, transfer_index = torch.topk(
|
| 520 |
+
full_confidence, number_transfer_tokens
|
| 521 |
+
)
|
| 522 |
+
else:
|
| 523 |
+
full_confidence = full_confidence / alg_temp
|
| 524 |
+
full_confidence = F.softmax(full_confidence, dim=-1)
|
| 525 |
+
transfer_index = torch.multinomial(
|
| 526 |
+
full_confidence, num_samples=number_transfer_tokens
|
| 527 |
+
)
|
| 528 |
+
x_ = (
|
| 529 |
+
torch.zeros_like(x, device=self.device, dtype=torch.long)
|
| 530 |
+
+ mask_token_id
|
| 531 |
+
)
|
| 532 |
+
x_[mask_index] = x0.clone()
|
| 533 |
+
row_indices = (
|
| 534 |
+
torch.arange(x.size(0), device=self.device)
|
| 535 |
+
.unsqueeze(1)
|
| 536 |
+
.expand_as(transfer_index)
|
| 537 |
+
)
|
| 538 |
+
x[row_indices, transfer_index] = x_[row_indices, transfer_index]
|
| 539 |
+
|
| 540 |
+
# this allows user-defined token control of the intermediate steps
|
| 541 |
+
x = generation_tokens_hook_func(i, x, logits)
|
| 542 |
+
|
| 543 |
+
if histories is not None:
|
| 544 |
+
histories.append(x.clone())
|
| 545 |
+
|
| 546 |
+
if return_dict_in_generate:
|
| 547 |
+
return DLMModelOutput(
|
| 548 |
+
sequences=x,
|
| 549 |
+
history=histories,
|
| 550 |
+
)
|
| 551 |
+
else:
|
| 552 |
+
return x
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model-00001-of-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a11ce25c06ac04092cd407fcb9e91439955ad1b73fcfe7b6939b29803da065c1
|
| 3 |
+
size 4969539560
|
model-00002-of-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:269abd61cf84da205b0d36ce6d6d73659d01a28fab65f0c5d0425aa0fda4b719
|
| 3 |
+
size 3157455608
|
model.safetensors.index.json
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"metadata": {
|
| 3 |
+
"total_size": 8126959616
|
| 4 |
+
},
|
| 5 |
+
"weight_map": {
|
| 6 |
+
"lm_head.weight": "model-00002-of-00002.safetensors",
|
| 7 |
+
"model.embed_tokens.weight": "model-00001-of-00002.safetensors",
|
| 8 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 9 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 10 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 11 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 12 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 13 |
+
"model.layers.0.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 14 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 15 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 16 |
+
"model.layers.0.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 17 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 18 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 19 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 20 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 21 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 22 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 23 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 24 |
+
"model.layers.1.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 25 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 26 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 27 |
+
"model.layers.1.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 28 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 29 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 30 |
+
"model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 31 |
+
"model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 32 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 33 |
+
"model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 34 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 35 |
+
"model.layers.10.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 36 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 37 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 38 |
+
"model.layers.10.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 39 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 40 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 41 |
+
"model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 42 |
+
"model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 43 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 44 |
+
"model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 45 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 46 |
+
"model.layers.11.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 47 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 48 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 49 |
+
"model.layers.11.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 50 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 51 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 52 |
+
"model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 53 |
+
"model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 54 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 55 |
+
"model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 56 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 57 |
+
"model.layers.12.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 58 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 59 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 60 |
+
"model.layers.12.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 61 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 62 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 63 |
+
"model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 64 |
+
"model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 65 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 66 |
+
"model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 67 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 68 |
+
"model.layers.13.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 69 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 70 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 71 |
+
"model.layers.13.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 72 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 73 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 74 |
+
"model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 75 |
+
"model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 76 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 77 |
+
"model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 78 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 79 |
+
"model.layers.14.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 80 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 81 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 82 |
+
"model.layers.14.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 83 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 84 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 85 |
+
"model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 86 |
+
"model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 87 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 88 |
+
"model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 89 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 90 |
+
"model.layers.15.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 91 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 92 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 93 |
+
"model.layers.15.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 94 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 95 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 96 |
+
"model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 97 |
+
"model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 98 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 99 |
+
"model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 100 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 101 |
+
"model.layers.16.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 102 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 103 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 104 |
+
"model.layers.16.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 105 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 106 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 107 |
+
"model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 108 |
+
"model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 109 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 110 |
+
"model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 111 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 112 |
+
"model.layers.17.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 113 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 114 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 115 |
+
"model.layers.17.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 116 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 117 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 118 |
+
"model.layers.18.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 119 |
+
"model.layers.18.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 120 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 121 |
+
"model.layers.18.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 122 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 123 |
+
"model.layers.18.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 124 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 125 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 126 |
+
"model.layers.18.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 127 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 128 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 129 |
+
"model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 130 |
+
"model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 131 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 132 |
+
"model.layers.19.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 133 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 134 |
+
"model.layers.19.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 135 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 136 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 137 |
+
"model.layers.19.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 138 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 139 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 140 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 141 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 142 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 143 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 144 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 145 |
+
"model.layers.2.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 146 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 147 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 148 |
+
"model.layers.2.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 149 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 150 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 151 |
+
"model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 152 |
+
"model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 153 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 154 |
+
"model.layers.20.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 155 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 156 |
+
"model.layers.20.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 157 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 158 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 159 |
+
"model.layers.20.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 160 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 161 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 162 |
+
"model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 163 |
+
"model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 164 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 165 |
+
"model.layers.21.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 166 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 167 |
+
"model.layers.21.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 168 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 169 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 170 |
+
"model.layers.21.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 171 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 172 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 173 |
+
"model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 174 |
+
"model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 175 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 176 |
+
"model.layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 177 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 178 |
+
"model.layers.22.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 179 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 180 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 181 |
+
"model.layers.22.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 182 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 183 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 184 |
+
"model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 185 |
+
"model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 186 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 187 |
+
"model.layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 188 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 189 |
+
"model.layers.23.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 190 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 191 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 192 |
+
"model.layers.23.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 193 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 194 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 195 |
+
"model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 196 |
+
"model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 197 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 198 |
+
"model.layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 199 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 200 |
+
"model.layers.24.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 201 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 202 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 203 |
+
"model.layers.24.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 204 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 205 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 206 |
+
"model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 207 |
+
"model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 208 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 209 |
+
"model.layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 210 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 211 |
+
"model.layers.25.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 212 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 213 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 214 |
+
"model.layers.25.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 215 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 216 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 217 |
+
"model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 218 |
+
"model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 219 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 220 |
+
"model.layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 221 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 222 |
+
"model.layers.26.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 223 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 224 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 225 |
+
"model.layers.26.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 226 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 227 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 228 |
+
"model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 229 |
+
"model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
| 230 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
| 231 |
+
"model.layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
| 232 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
| 233 |
+
"model.layers.27.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
|
| 234 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
| 235 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
| 236 |
+
"model.layers.27.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
|
| 237 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
| 238 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
| 239 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 240 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 241 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 242 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 243 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 244 |
+
"model.layers.3.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 245 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 246 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 247 |
+
"model.layers.3.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 248 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 249 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 250 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 251 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 252 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 253 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 254 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 255 |
+
"model.layers.4.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 256 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 257 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 258 |
+
"model.layers.4.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 259 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 260 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 261 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 262 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 263 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 264 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 265 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 266 |
+
"model.layers.5.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 267 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 268 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 269 |
+
"model.layers.5.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 270 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 271 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 272 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 273 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 274 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 275 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 276 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 277 |
+
"model.layers.6.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 278 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 279 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 280 |
+
"model.layers.6.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 281 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 282 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 283 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 284 |
+
"model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 285 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 286 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 287 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 288 |
+
"model.layers.7.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 289 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 290 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 291 |
+
"model.layers.7.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 292 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 293 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 294 |
+
"model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 295 |
+
"model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 296 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 297 |
+
"model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 298 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 299 |
+
"model.layers.8.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 300 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 301 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 302 |
+
"model.layers.8.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 303 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 304 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 305 |
+
"model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 306 |
+
"model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
| 307 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
| 308 |
+
"model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
| 309 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
| 310 |
+
"model.layers.9.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
|
| 311 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
| 312 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
| 313 |
+
"model.layers.9.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
|
| 314 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
| 315 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
| 316 |
+
"model.norm.weight": "model-00002-of-00002.safetensors"
|
| 317 |
+
}
|
| 318 |
+
}
|
model_config.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 2 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
| 3 |
+
from transformers.utils import logging
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
logger = logging.get_logger(__name__)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CoDAConfig(PretrainedConfig):
|
| 10 |
+
model_type = "CoDA"
|
| 11 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
vocab_size=151936,
|
| 16 |
+
head_dim=128,
|
| 17 |
+
hidden_act="silu",
|
| 18 |
+
hidden_size=2048,
|
| 19 |
+
intermediate_size=6144,
|
| 20 |
+
num_attention_heads=16,
|
| 21 |
+
num_hidden_layers=28,
|
| 22 |
+
num_key_value_heads=8,
|
| 23 |
+
max_position_embeddings=40960,
|
| 24 |
+
initializer_range=0.02,
|
| 25 |
+
use_cache=True,
|
| 26 |
+
use_sliding_window=False,
|
| 27 |
+
tie_word_embeddings=True,
|
| 28 |
+
rms_norm_eps=1e-6,
|
| 29 |
+
rope_scaling=None,
|
| 30 |
+
rope_theta=1000000,
|
| 31 |
+
sliding_window=None,
|
| 32 |
+
max_window_layers=28,
|
| 33 |
+
attention_bias=False,
|
| 34 |
+
attention_dropout=0.0,
|
| 35 |
+
bos_token_id=151643,
|
| 36 |
+
eos_token_id=151645,
|
| 37 |
+
pad_token_id=151643,
|
| 38 |
+
mask_token_id=151669,
|
| 39 |
+
attention_kernel="flash_attention",
|
| 40 |
+
prefix_probability=0,
|
| 41 |
+
truncate_probability=0,
|
| 42 |
+
block_masking_probability=[0.25, 0.5, 0.5, 0.75, 0.25],
|
| 43 |
+
mask_block_sizes=[4, 8, 16, 32],
|
| 44 |
+
sampling_eps=[0.001, 0.25, 0.5, 0.25, 0.001], # minimum noise level
|
| 45 |
+
**kwargs,
|
| 46 |
+
):
|
| 47 |
+
self.vocab_size = vocab_size
|
| 48 |
+
self.max_position_embeddings = max_position_embeddings
|
| 49 |
+
self.hidden_size = hidden_size
|
| 50 |
+
self.intermediate_size = intermediate_size
|
| 51 |
+
self.num_hidden_layers = num_hidden_layers
|
| 52 |
+
self.num_attention_heads = num_attention_heads
|
| 53 |
+
self.use_sliding_window = use_sliding_window
|
| 54 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
| 55 |
+
self.max_window_layers = max_window_layers
|
| 56 |
+
|
| 57 |
+
# for backward compatibility
|
| 58 |
+
if num_key_value_heads is None:
|
| 59 |
+
num_key_value_heads = num_attention_heads
|
| 60 |
+
|
| 61 |
+
self.num_key_value_heads = num_key_value_heads
|
| 62 |
+
self.hidden_act = hidden_act
|
| 63 |
+
self.initializer_range = initializer_range
|
| 64 |
+
self.rms_norm_eps = rms_norm_eps
|
| 65 |
+
self.use_cache = use_cache
|
| 66 |
+
self.rope_theta = rope_theta
|
| 67 |
+
self.rope_scaling = rope_scaling
|
| 68 |
+
self.attention_dropout = attention_dropout
|
| 69 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 70 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 71 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 72 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 73 |
+
rope_config_validation(self)
|
| 74 |
+
|
| 75 |
+
self.head_dim = head_dim
|
| 76 |
+
self.attention_bias = attention_bias
|
| 77 |
+
self.bos_token_id = bos_token_id
|
| 78 |
+
self.eos_token_id = eos_token_id
|
| 79 |
+
self.attention_kernel = attention_kernel
|
| 80 |
+
self.prefix_probability = prefix_probability
|
| 81 |
+
self.truncate_probability = truncate_probability
|
| 82 |
+
self.block_masking_probability = block_masking_probability
|
| 83 |
+
self.mask_block_sizes = mask_block_sizes
|
| 84 |
+
self.sampling_eps = sampling_eps
|
| 85 |
+
|
| 86 |
+
super().__init__(
|
| 87 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 88 |
+
**kwargs,
|
| 89 |
+
)
|
| 90 |
+
self.mask_token_id = mask_token_id
|
| 91 |
+
self.pad_token_id = pad_token_id
|
modeling_coda.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3/modeling_qwen3.py
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Callable, Optional, Tuple, Union
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import nn
|
| 9 |
+
from transformers import PreTrainedModel
|
| 10 |
+
from transformers.activations import ACT2FN
|
| 11 |
+
from transformers.utils import logging
|
| 12 |
+
from .model_config import CoDAConfig
|
| 13 |
+
from .attention import AttentionModule
|
| 14 |
+
from .modeling_utils import (
|
| 15 |
+
HomogeneousSequential,
|
| 16 |
+
RopeScaling,
|
| 17 |
+
default_rope_frequencies,
|
| 18 |
+
apply_rotary_pos_emb,
|
| 19 |
+
transition,
|
| 20 |
+
prefix_input_ids,
|
| 21 |
+
truncate_input_ids,
|
| 22 |
+
)
|
| 23 |
+
from .generation_utils import DLMGenerationMixin, DLMGenerationConfig
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CoDARMSNorm(nn.Module):
|
| 31 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 34 |
+
self.variance_epsilon = eps
|
| 35 |
+
|
| 36 |
+
def forward(self, hidden_states):
|
| 37 |
+
input_dtype = hidden_states.dtype
|
| 38 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 39 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 40 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 41 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 42 |
+
|
| 43 |
+
def extra_repr(self):
|
| 44 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class CoDAMLP(nn.Module):
|
| 48 |
+
def __init__(self, config: CoDAConfig):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.config = config
|
| 51 |
+
self.hidden_size = config.hidden_size
|
| 52 |
+
self.intermediate_size = config.intermediate_size
|
| 53 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 54 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 55 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 56 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 57 |
+
|
| 58 |
+
def forward(self, x):
|
| 59 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 60 |
+
return down_proj
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class CoDAAttention(nn.Module):
|
| 64 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 65 |
+
|
| 66 |
+
def __init__(self, config: CoDAConfig, layer_idx: int | None = None):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.config = config
|
| 69 |
+
self.attention_block = AttentionModule(config)
|
| 70 |
+
self.layer_idx = layer_idx
|
| 71 |
+
if layer_idx is None:
|
| 72 |
+
logger.warning_once(
|
| 73 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 74 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 75 |
+
"when creating this class."
|
| 76 |
+
)
|
| 77 |
+
self.hidden_size = config.hidden_size
|
| 78 |
+
self.num_heads = config.num_attention_heads
|
| 79 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 80 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 81 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 82 |
+
self.scaling = self.head_dim**-0.5
|
| 83 |
+
self.attention_dropout = getattr(config, "attention_dropout", 0.0)
|
| 84 |
+
# weiran: diffullama
|
| 85 |
+
self.is_causal = False
|
| 86 |
+
|
| 87 |
+
self.q_proj = nn.Linear(
|
| 88 |
+
self.hidden_size,
|
| 89 |
+
self.num_heads * self.head_dim,
|
| 90 |
+
bias=getattr(config, "attention_bias", False),
|
| 91 |
+
)
|
| 92 |
+
self.k_proj = nn.Linear(
|
| 93 |
+
self.hidden_size,
|
| 94 |
+
self.num_key_value_heads * self.head_dim,
|
| 95 |
+
bias=getattr(config, "attention_bias", False),
|
| 96 |
+
)
|
| 97 |
+
self.v_proj = nn.Linear(
|
| 98 |
+
self.hidden_size,
|
| 99 |
+
self.num_key_value_heads * self.head_dim,
|
| 100 |
+
bias=getattr(config, "attention_bias", False),
|
| 101 |
+
)
|
| 102 |
+
self.o_proj = nn.Linear(
|
| 103 |
+
self.num_heads * self.head_dim,
|
| 104 |
+
self.hidden_size,
|
| 105 |
+
bias=getattr(config, "attention_bias", False),
|
| 106 |
+
)
|
| 107 |
+
self.q_norm = CoDARMSNorm(
|
| 108 |
+
self.head_dim, eps=getattr(config, "rms_norm_eps", 1e-6)
|
| 109 |
+
)
|
| 110 |
+
self.k_norm = CoDARMSNorm(
|
| 111 |
+
self.head_dim, eps=getattr(config, "rms_norm_eps", 1e-6)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def forward(
|
| 115 |
+
self,
|
| 116 |
+
hidden_states: torch.Tensor,
|
| 117 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 118 |
+
attention_mask: torch.Tensor | None = None,
|
| 119 |
+
position_ids: torch.LongTensor | None = None,
|
| 120 |
+
) -> torch.FloatTensor:
|
| 121 |
+
bsz, q_len, _ = hidden_states.size()
|
| 122 |
+
|
| 123 |
+
query_states = self.q_proj(hidden_states)
|
| 124 |
+
key_states = self.k_proj(hidden_states)
|
| 125 |
+
value_states = self.v_proj(hidden_states)
|
| 126 |
+
|
| 127 |
+
# Apply q_norm and k_norm to the head dimension
|
| 128 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
|
| 129 |
+
key_states = key_states.view(
|
| 130 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
| 131 |
+
)
|
| 132 |
+
value_states = value_states.view(
|
| 133 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# Apply normalization
|
| 137 |
+
query_states = self.q_norm(query_states)
|
| 138 |
+
key_states = self.k_norm(key_states)
|
| 139 |
+
|
| 140 |
+
# Transpose to get the right shape for attention
|
| 141 |
+
query_states = query_states.transpose(1, 2)
|
| 142 |
+
key_states = key_states.transpose(1, 2)
|
| 143 |
+
value_states = value_states.transpose(1, 2)
|
| 144 |
+
|
| 145 |
+
cos, sin = position_embeddings
|
| 146 |
+
query_states, key_states = apply_rotary_pos_emb(
|
| 147 |
+
query_states, key_states, cos, sin
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
attn_output = self.attention_block(
|
| 151 |
+
query_states, key_states, value_states, attention_mask
|
| 152 |
+
)
|
| 153 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 154 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 155 |
+
attn_output = self.o_proj(attn_output)
|
| 156 |
+
return attn_output
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class CoDARotaryEmbedding(nn.Module):
|
| 160 |
+
inv_freq: nn.Buffer
|
| 161 |
+
|
| 162 |
+
def __init__(
|
| 163 |
+
self,
|
| 164 |
+
head_dim,
|
| 165 |
+
rope_theta,
|
| 166 |
+
scaling: RopeScaling | None = None,
|
| 167 |
+
):
|
| 168 |
+
super().__init__()
|
| 169 |
+
if scaling is None:
|
| 170 |
+
inv_freq = default_rope_frequencies(head_dim, theta=rope_theta)
|
| 171 |
+
else:
|
| 172 |
+
raise NotImplementedError("Scaling is not implemented")
|
| 173 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 174 |
+
|
| 175 |
+
@torch.no_grad()
|
| 176 |
+
def forward(self, x, position_ids):
|
| 177 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 178 |
+
inv_freq_expanded = (
|
| 179 |
+
self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 180 |
+
)
|
| 181 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 182 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
| 183 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
| 184 |
+
device_type = x.device.type
|
| 185 |
+
device_type = (
|
| 186 |
+
device_type
|
| 187 |
+
if isinstance(device_type, str) and device_type != "mps"
|
| 188 |
+
else "cpu"
|
| 189 |
+
)
|
| 190 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 191 |
+
freqs = (
|
| 192 |
+
inv_freq_expanded.float() @ position_ids_expanded.float()
|
| 193 |
+
).transpose(1, 2)
|
| 194 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 195 |
+
cos = emb.cos()
|
| 196 |
+
sin = emb.sin()
|
| 197 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class CoDADecoderLayer(nn.Module):
|
| 201 |
+
def __init__(self, config: CoDAConfig, layer_idx: int):
|
| 202 |
+
super().__init__()
|
| 203 |
+
self.hidden_size = config.hidden_size
|
| 204 |
+
self.layer_idx = layer_idx
|
| 205 |
+
|
| 206 |
+
self.self_attn = CoDAAttention(config=config, layer_idx=layer_idx)
|
| 207 |
+
|
| 208 |
+
self.mlp = CoDAMLP(config)
|
| 209 |
+
self.input_layernorm = CoDARMSNorm(
|
| 210 |
+
config.hidden_size, eps=getattr(config, "rms_norm_eps", 1e-6)
|
| 211 |
+
)
|
| 212 |
+
self.post_attention_layernorm = CoDARMSNorm(
|
| 213 |
+
config.hidden_size, eps=getattr(config, "rms_norm_eps", 1e-6)
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def forward(
|
| 217 |
+
self,
|
| 218 |
+
hidden_states: torch.Tensor,
|
| 219 |
+
attention_mask: torch.Tensor | None = None,
|
| 220 |
+
position_ids: torch.Tensor | None = None,
|
| 221 |
+
position_embeddings: (
|
| 222 |
+
tuple[torch.Tensor, torch.Tensor] | None
|
| 223 |
+
) = None, # necessary, but kept here for BC
|
| 224 |
+
) -> torch.Tensor:
|
| 225 |
+
"""
|
| 226 |
+
Args:
|
| 227 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 228 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 229 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
| 230 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
| 231 |
+
"""
|
| 232 |
+
# This gives the `hidden_states` tensor a name so that we can layer specify
|
| 233 |
+
# to offload this tensor to host RAM to save memory. This is not a standard
|
| 234 |
+
# torch API because there is no such feature in PyTorch. Instead, the name
|
| 235 |
+
# becomes node metadata during FX graph capture.
|
| 236 |
+
|
| 237 |
+
residual = hidden_states
|
| 238 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 239 |
+
|
| 240 |
+
# Self Attention
|
| 241 |
+
hidden_states = self.self_attn(
|
| 242 |
+
hidden_states=hidden_states,
|
| 243 |
+
attention_mask=attention_mask,
|
| 244 |
+
position_ids=position_ids,
|
| 245 |
+
position_embeddings=position_embeddings,
|
| 246 |
+
)
|
| 247 |
+
hidden_states = residual + hidden_states
|
| 248 |
+
|
| 249 |
+
# Fully Connected
|
| 250 |
+
residual = hidden_states
|
| 251 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 252 |
+
hidden_states = self.mlp(hidden_states)
|
| 253 |
+
hidden_states = residual + hidden_states
|
| 254 |
+
|
| 255 |
+
return hidden_states
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class CoDAModel(PreTrainedModel):
|
| 259 |
+
"""
|
| 260 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers.
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
config: FlexConfig
|
| 264 |
+
"""
|
| 265 |
+
config_class = CoDAConfig
|
| 266 |
+
|
| 267 |
+
def __init__(self, config: CoDAConfig):
|
| 268 |
+
super().__init__(config=config)
|
| 269 |
+
self.vocab_size = config.vocab_size
|
| 270 |
+
if "pad_token_id" not in config:
|
| 271 |
+
self.padding_idx = None
|
| 272 |
+
else:
|
| 273 |
+
self.padding_idx = config.pad_token_id
|
| 274 |
+
self.embed_tokens = nn.Embedding(
|
| 275 |
+
config.vocab_size, config.hidden_size, padding_idx=self.padding_idx
|
| 276 |
+
)
|
| 277 |
+
# `HomogeneousSequential` is similar to `nn.Sequential` but can be compiled with
|
| 278 |
+
# `scan` described in https://pytorch.org/xla/release/r2.6/features/scan.html.
|
| 279 |
+
self.layers = HomogeneousSequential(
|
| 280 |
+
*[
|
| 281 |
+
CoDADecoderLayer(config, layer_idx)
|
| 282 |
+
for layer_idx in range(config.num_hidden_layers)
|
| 283 |
+
]
|
| 284 |
+
)
|
| 285 |
+
self.norm = CoDARMSNorm(
|
| 286 |
+
config.hidden_size, eps=getattr(config, "rms_norm_eps", 1e-6)
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
rope_scaling = getattr(config, "rope_scaling", None)
|
| 290 |
+
head_dim = getattr(
|
| 291 |
+
config, "head_dim", config.hidden_size // config.num_attention_heads
|
| 292 |
+
)
|
| 293 |
+
self.rope_theta = getattr(config, "rope_theta", 10000.0)
|
| 294 |
+
if rope_scaling is not None:
|
| 295 |
+
rope_scaling = RopeScaling(**rope_scaling)
|
| 296 |
+
self.rotary_emb = CoDARotaryEmbedding(
|
| 297 |
+
head_dim=head_dim, rope_theta=self.rope_theta, scaling=rope_scaling
|
| 298 |
+
)
|
| 299 |
+
self.post_init()
|
| 300 |
+
|
| 301 |
+
def _init_weights(self, module):
|
| 302 |
+
std = getattr(self.config, "initializer_range", 0.02)
|
| 303 |
+
if isinstance(module, nn.Linear):
|
| 304 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 305 |
+
if module.bias is not None:
|
| 306 |
+
module.bias.data.zero_()
|
| 307 |
+
elif isinstance(module, nn.Embedding):
|
| 308 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 309 |
+
if module.padding_idx is not None:
|
| 310 |
+
module.weight.data[module.padding_idx].zero_()
|
| 311 |
+
|
| 312 |
+
def forward(
|
| 313 |
+
self,
|
| 314 |
+
input_ids: torch.LongTensor,
|
| 315 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 316 |
+
) -> torch.Tensor:
|
| 317 |
+
# convert input ids to embeddings
|
| 318 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 319 |
+
|
| 320 |
+
seq_length = inputs_embeds.size(1)
|
| 321 |
+
|
| 322 |
+
position_ids = (
|
| 323 |
+
torch.arange(seq_length, device=inputs_embeds.device).unsqueeze(0).float()
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
# Create a causal attention mask
|
| 327 |
+
causal_mask = torch.triu(
|
| 328 |
+
torch.full(
|
| 329 |
+
(seq_length, seq_length), float("-inf"), device=inputs_embeds.device
|
| 330 |
+
),
|
| 331 |
+
diagonal=1,
|
| 332 |
+
)
|
| 333 |
+
causal_mask = causal_mask.unsqueeze(0).unsqueeze(
|
| 334 |
+
0
|
| 335 |
+
) # Add batch and head dimension
|
| 336 |
+
|
| 337 |
+
if attention_mask is not None:
|
| 338 |
+
causal_mask = causal_mask * attention_mask[:, None, None, :]
|
| 339 |
+
|
| 340 |
+
hidden_states = inputs_embeds
|
| 341 |
+
|
| 342 |
+
# create position embeddings to be shared across the decoder layers
|
| 343 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 344 |
+
|
| 345 |
+
# decoder layers
|
| 346 |
+
hidden_states = self.layers(
|
| 347 |
+
hidden_states,
|
| 348 |
+
attention_mask=causal_mask,
|
| 349 |
+
position_ids=position_ids,
|
| 350 |
+
position_embeddings=position_embeddings,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
hidden_states = self.norm(hidden_states)
|
| 354 |
+
|
| 355 |
+
return hidden_states
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class CoDALanguageModel(DLMGenerationMixin, PreTrainedModel):
|
| 359 |
+
config_class = CoDAConfig
|
| 360 |
+
base_model_prefix = "model"
|
| 361 |
+
is_parallelizable = True
|
| 362 |
+
supports_gradient_checkpointing = False
|
| 363 |
+
_no_split_modules = ["FlexDecoderLayer"]
|
| 364 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 365 |
+
_supports_flash_attn_2 = True
|
| 366 |
+
_supports_sdpa = True
|
| 367 |
+
_supports_cache_class = True
|
| 368 |
+
|
| 369 |
+
def __init__(self, config: CoDAConfig):
|
| 370 |
+
super().__init__(config)
|
| 371 |
+
self.config = config
|
| 372 |
+
self.model = CoDAModel(config)
|
| 373 |
+
self.vocab_size = config.vocab_size
|
| 374 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 375 |
+
self.mask_token_id = config.mask_token_id
|
| 376 |
+
self.generation_config = DLMGenerationConfig(mask_token_id=config.mask_token_id)
|
| 377 |
+
self.apply(self._init_weights)
|
| 378 |
+
|
| 379 |
+
def _init_weights(self, module):
|
| 380 |
+
std = getattr(self.config, "initializer_range", 0.02)
|
| 381 |
+
if isinstance(module, nn.Linear):
|
| 382 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 383 |
+
if module.bias is not None:
|
| 384 |
+
module.bias.data.zero_()
|
| 385 |
+
elif isinstance(module, nn.Embedding):
|
| 386 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 387 |
+
if module.padding_idx is not None:
|
| 388 |
+
module.weight.data[module.padding_idx].zero_()
|
| 389 |
+
|
| 390 |
+
def get_embeds(self, input_ids):
|
| 391 |
+
"""
|
| 392 |
+
Get input embeddings from the model.
|
| 393 |
+
This method is used by the diffusion trainer to access embeddings.
|
| 394 |
+
"""
|
| 395 |
+
return self.model.embed_tokens(input_ids)
|
| 396 |
+
|
| 397 |
+
def forward(
|
| 398 |
+
self,
|
| 399 |
+
input_ids: torch.LongTensor,
|
| 400 |
+
labels: torch.LongTensor | None = None,
|
| 401 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 402 |
+
src_mask: torch.BoolTensor | None = None,
|
| 403 |
+
training_mode: str = "pretrain",
|
| 404 |
+
**kwargs,
|
| 405 |
+
) -> tuple[torch.FloatTensor, torch.FloatTensor | None]:
|
| 406 |
+
if not self.training:
|
| 407 |
+
model_output = self.model(
|
| 408 |
+
input_ids=input_ids, attention_mask=None
|
| 409 |
+
)
|
| 410 |
+
hidden_states = model_output
|
| 411 |
+
logits = self.lm_head(hidden_states) # NOTE: we shift logits at inference time
|
| 412 |
+
return logits, None
|
| 413 |
+
|
| 414 |
+
if training_mode == "sft" and src_mask is None:
|
| 415 |
+
raise ValueError("SFT mode requires a non-null src_mask")
|
| 416 |
+
|
| 417 |
+
epoch = kwargs.get("epoch", None)
|
| 418 |
+
sampling_eps = getattr(
|
| 419 |
+
self.config, "sampling_eps", 1e-3
|
| 420 |
+
) # NOTE: use sampling_eps to control the noise level
|
| 421 |
+
# If sampling_eps is a list, choose based on epoch
|
| 422 |
+
if isinstance(sampling_eps, list):
|
| 423 |
+
if epoch is None:
|
| 424 |
+
# If epoch is not provided, use the first value
|
| 425 |
+
sampling_eps = sampling_eps[0]
|
| 426 |
+
else:
|
| 427 |
+
# Use modulo to cycle through the list if epoch exceeds list length
|
| 428 |
+
sampling_eps = sampling_eps[epoch % len(sampling_eps)]
|
| 429 |
+
|
| 430 |
+
mask_token_id = self.mask_token_id
|
| 431 |
+
loss_func = nn.CrossEntropyLoss(reduction="none")
|
| 432 |
+
batch_size, seq_len = input_ids.shape # input_ids: [batch_size, seq_len]
|
| 433 |
+
masking_schedule = kwargs.get("masking_schedule", None)
|
| 434 |
+
|
| 435 |
+
# Create maskable_mask based on training mode and src_mask
|
| 436 |
+
# For SFT: src_mask is provided, maskable_mask = ~src_mask
|
| 437 |
+
# For pretrain: src_mask is None, maskable_mask = all True
|
| 438 |
+
|
| 439 |
+
if src_mask is not None:
|
| 440 |
+
maskable_mask = ~src_mask
|
| 441 |
+
else: # pretrain or midtrain
|
| 442 |
+
maskable_mask = torch.ones_like(
|
| 443 |
+
input_ids, dtype=torch.bool, device=input_ids.device
|
| 444 |
+
)
|
| 445 |
+
if masking_schedule is not None:
|
| 446 |
+
prefix_probability = masking_schedule.get("prefix_probability", 0)
|
| 447 |
+
truncate_probability = masking_schedule.get("truncate_probability", 0)
|
| 448 |
+
else:
|
| 449 |
+
prefix_probability = getattr(self.config, "prefix_probability", 0)
|
| 450 |
+
truncate_probability = getattr(self.config, "truncate_probability", 0)
|
| 451 |
+
if training_mode == "sft":
|
| 452 |
+
prefix_probability = 0
|
| 453 |
+
truncate_probability = 0
|
| 454 |
+
# Generate random decisions for all batch items
|
| 455 |
+
apply_prefix = (
|
| 456 |
+
torch.rand(batch_size, device=input_ids.device) < prefix_probability
|
| 457 |
+
)
|
| 458 |
+
# Only apply truncation to rows that are NOT prefixed
|
| 459 |
+
apply_truncate = (
|
| 460 |
+
torch.rand(batch_size, device=input_ids.device) < truncate_probability
|
| 461 |
+
)
|
| 462 |
+
apply_truncate = apply_truncate & ~apply_prefix
|
| 463 |
+
|
| 464 |
+
if prefix_probability > 0:
|
| 465 |
+
maskable_mask = prefix_input_ids(input_ids, maskable_mask, apply_prefix)
|
| 466 |
+
if truncate_probability > 0:
|
| 467 |
+
input_ids = truncate_input_ids(
|
| 468 |
+
input_ids, apply_truncate, self.config.pad_token_id
|
| 469 |
+
)
|
| 470 |
+
maskable_mask = maskable_mask & (input_ids != self.config.pad_token_id)
|
| 471 |
+
|
| 472 |
+
# add noise to input_ids
|
| 473 |
+
sigma = (1 - sampling_eps) * torch.rand(
|
| 474 |
+
input_ids.shape[0], device=input_ids.device
|
| 475 |
+
) + sampling_eps
|
| 476 |
+
dsigma = torch.reciprocal(sigma)
|
| 477 |
+
|
| 478 |
+
# Sample mask block size
|
| 479 |
+
# Use mask_block_sizes from masking_probs if provided, otherwise fall back to config
|
| 480 |
+
if masking_schedule is not None and "mask_block_sizes" in masking_schedule:
|
| 481 |
+
mask_block_sizes = masking_schedule["mask_block_sizes"]
|
| 482 |
+
else:
|
| 483 |
+
mask_block_sizes = getattr(self.config, "mask_block_sizes", None)
|
| 484 |
+
# Use masking_config if provided, otherwise fall back to config values
|
| 485 |
+
if masking_schedule is not None:
|
| 486 |
+
block_masking_probability = masking_schedule.get(
|
| 487 |
+
"block_masking_probability", 0
|
| 488 |
+
)
|
| 489 |
+
else:
|
| 490 |
+
block_masking_probability = getattr(
|
| 491 |
+
self.config, "block_masking_probability", 0
|
| 492 |
+
)
|
| 493 |
+
if isinstance(block_masking_probability, list):
|
| 494 |
+
if epoch is None:
|
| 495 |
+
block_masking_probability = block_masking_probability[0]
|
| 496 |
+
else:
|
| 497 |
+
block_masking_probability = block_masking_probability[
|
| 498 |
+
epoch % len(block_masking_probability)
|
| 499 |
+
]
|
| 500 |
+
|
| 501 |
+
if block_masking_probability > 0 and mask_block_sizes is not None and len(mask_block_sizes) > 0:
|
| 502 |
+
mask_block_size = mask_block_sizes[
|
| 503 |
+
torch.randint(0, len(mask_block_sizes), (1,)).item()
|
| 504 |
+
]
|
| 505 |
+
else:
|
| 506 |
+
mask_block_size = 1
|
| 507 |
+
|
| 508 |
+
noisy_input_ids = transition(
|
| 509 |
+
input_ids,
|
| 510 |
+
sigma[:, None],
|
| 511 |
+
maskable_mask=maskable_mask,
|
| 512 |
+
mask_token_id=mask_token_id,
|
| 513 |
+
mask_block_size=mask_block_size,
|
| 514 |
+
)
|
| 515 |
+
loss_mask = noisy_input_ids == mask_token_id
|
| 516 |
+
|
| 517 |
+
# Use gradient checkpointing if enabled
|
| 518 |
+
if (
|
| 519 |
+
hasattr(self, "gradient_checkpointing")
|
| 520 |
+
and self.gradient_checkpointing
|
| 521 |
+
and self.training
|
| 522 |
+
):
|
| 523 |
+
# Define a function for gradient checkpointing
|
| 524 |
+
def custom_forward(*inputs):
|
| 525 |
+
return self.model(*inputs)
|
| 526 |
+
|
| 527 |
+
# Apply gradient checkpointing to the model forward pass
|
| 528 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 529 |
+
custom_forward, noisy_input_ids, attention_mask
|
| 530 |
+
)
|
| 531 |
+
else:
|
| 532 |
+
hidden_states = self.model(
|
| 533 |
+
input_ids=noisy_input_ids, attention_mask=attention_mask
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
logits = self.lm_head(hidden_states)
|
| 537 |
+
logits = logits.float()
|
| 538 |
+
# logits: [bs, seq_len, vocab_size]
|
| 539 |
+
# Shifted logits and labels
|
| 540 |
+
# logits: [bs, seq_len-1, vocab_size]
|
| 541 |
+
logits = logits[..., :-1, :].contiguous()
|
| 542 |
+
# weiran: if the shifted token is not masked in the original input, the loss is 0
|
| 543 |
+
# loss_mask: [bs, seq_len-1]
|
| 544 |
+
loss_mask = loss_mask[..., 1:].contiguous()
|
| 545 |
+
target_ids = input_ids[..., 1:].contiguous()
|
| 546 |
+
# loss: [bs, seq_len-1]
|
| 547 |
+
loss = loss_func(
|
| 548 |
+
logits.reshape(-1, logits.shape[-1]), target_ids.reshape(-1)
|
| 549 |
+
).reshape(target_ids.shape[0], -1)
|
| 550 |
+
loss = loss.masked_fill(~loss_mask, 0)
|
| 551 |
+
# weiran: divide by the number of tokens in the sequence instead of the number of masked tokens
|
| 552 |
+
# justification is dsigma already accounts for the number of masked tokens
|
| 553 |
+
# this is a hack to get something like per token loss
|
| 554 |
+
# https://github.com/ML-GSAI/SMDM/blob/main/pretrain/train_mdm_rl.py#L281-L283
|
| 555 |
+
loss = (dsigma[:, None] * loss).sum() / (
|
| 556 |
+
input_ids.shape[0] * input_ids.shape[1]
|
| 557 |
+
)
|
| 558 |
+
return logits, loss
|
modeling_utils.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Optional, Tuple, Union
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
class HomogeneousSequential(nn.Sequential):
|
| 8 |
+
"""
|
| 9 |
+
HomogenousSequential is a sequential container that requires all child modules
|
| 10 |
+
to be of the same type and have matching input/output shapes. In turn, it may be
|
| 11 |
+
compiled with the `scan` higher order operator to save compile time.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
repeated_layer: type
|
| 15 |
+
"""The type of the layer being looped over."""
|
| 16 |
+
|
| 17 |
+
def __init__(self, *args: nn.Module) -> None:
|
| 18 |
+
super().__init__(*args)
|
| 19 |
+
types = set(type(module) for module in args)
|
| 20 |
+
assert len(types) == 1, f"All modules must be of the same type. Got {types}"
|
| 21 |
+
self.repeated_layer = types.pop()
|
| 22 |
+
|
| 23 |
+
def forward(self, *input, **broadcasted_inputs):
|
| 24 |
+
"""
|
| 25 |
+
Much like `torch.nn.Sequential`, this takes `input` and forwards it to the
|
| 26 |
+
first module it contains. It then "chains" outputs to inputs sequentially for
|
| 27 |
+
each subsequent module, finally returning the output of the last module.
|
| 28 |
+
Different from `torch.nn.Sequential`, you may specify `broadcasted_inputs` via
|
| 29 |
+
keyword arguments. The same keyword arguments will be passed to every layer
|
| 30 |
+
without changes (i.e. "broadcasted").
|
| 31 |
+
"""
|
| 32 |
+
for module in self:
|
| 33 |
+
input = module(*splat(input), **broadcasted_inputs)
|
| 34 |
+
return input
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def splat(input):
|
| 38 |
+
if not isinstance(input, list | tuple):
|
| 39 |
+
input = (input,)
|
| 40 |
+
return input
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass(kw_only=True)
|
| 44 |
+
class RopeScaling:
|
| 45 |
+
"""
|
| 46 |
+
RoPE scaling parameters. The defaults are what was selected in Llama 3.1.
|
| 47 |
+
"""
|
| 48 |
+
factor: float = 8.0
|
| 49 |
+
low_freq_factor: float = 1.0
|
| 50 |
+
high_freq_factor: float = 4.0
|
| 51 |
+
original_context_len: int = 8192
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def default_rope_frequencies(
|
| 55 |
+
head_dim: int,
|
| 56 |
+
theta: float = 10000.0,
|
| 57 |
+
) -> torch.Tensor:
|
| 58 |
+
"""
|
| 59 |
+
Computes the original RoPE frequencies in e.g. Llama 2.
|
| 60 |
+
Args:
|
| 61 |
+
head_dim: the size of a single attention head.
|
| 62 |
+
theta: a hyperparameter controlling how fast the embeddings rotate.
|
| 63 |
+
Returns:
|
| 64 |
+
The frequencies for the RoPE embeddings.
|
| 65 |
+
"""
|
| 66 |
+
return 1.0 / (
|
| 67 |
+
theta ** (torch.arange(0, head_dim, 2, dtype=torch.int64).float() / head_dim)
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def rotate_half(x):
|
| 71 |
+
"""Rotates half the hidden dims of the input."""
|
| 72 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 73 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 74 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 78 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
q (`torch.Tensor`): The query tensor.
|
| 82 |
+
k (`torch.Tensor`): The key tensor.
|
| 83 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 84 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 85 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 86 |
+
Deprecated and unused.
|
| 87 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 88 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 89 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 90 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 91 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 92 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 93 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 94 |
+
Returns:
|
| 95 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 96 |
+
"""
|
| 97 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 98 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 99 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 100 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 101 |
+
return q_embed, k_embed
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def transition(x_0, sigma, maskable_mask, mask_token_id, mask_block_size: int = 1):
|
| 106 |
+
"""Apply masking to input tokens. If mask_block_size > 1, use block masking for all rows."""
|
| 107 |
+
|
| 108 |
+
if mask_block_size == 1:
|
| 109 |
+
# Original behavior
|
| 110 |
+
# weiran: diffullama
|
| 111 |
+
move_indices = (
|
| 112 |
+
torch.rand(*x_0.shape, device=x_0.device) < sigma
|
| 113 |
+
) & maskable_mask
|
| 114 |
+
x_t = torch.where(move_indices, mask_token_id, x_0)
|
| 115 |
+
return x_t
|
| 116 |
+
|
| 117 |
+
# Block masking for entire batch
|
| 118 |
+
return block_masking(x_0, sigma, maskable_mask, mask_token_id, mask_block_size)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def block_masking(x_0, sigma, maskable_mask, mask_token_id, mask_block_size):
|
| 122 |
+
"""
|
| 123 |
+
XLA-compatible block masking applied uniformly to all rows in the batch.
|
| 124 |
+
Uses efficient tensor operations to avoid dynamic loops.
|
| 125 |
+
"""
|
| 126 |
+
batch_size, seq_len = x_0.shape
|
| 127 |
+
|
| 128 |
+
if seq_len < mask_block_size:
|
| 129 |
+
return x_0
|
| 130 |
+
|
| 131 |
+
# Calculate number of possible block positions
|
| 132 |
+
num_windows = seq_len - mask_block_size + 1
|
| 133 |
+
|
| 134 |
+
# Create all possible block positions: [num_windows, mask_block_size]
|
| 135 |
+
window_starts = torch.arange(num_windows, device=x_0.device)
|
| 136 |
+
block_offsets = torch.arange(mask_block_size, device=x_0.device)
|
| 137 |
+
all_positions = window_starts.unsqueeze(1) + block_offsets.unsqueeze(0)
|
| 138 |
+
|
| 139 |
+
# Check which blocks are fully maskable: [batch_size, num_windows]
|
| 140 |
+
maskable_blocks = (
|
| 141 |
+
maskable_mask.unsqueeze(1)
|
| 142 |
+
.expand(-1, num_windows, -1)
|
| 143 |
+
.gather(2, all_positions.unsqueeze(0).expand(batch_size, -1, -1))
|
| 144 |
+
)
|
| 145 |
+
fully_maskable = maskable_blocks.all(dim=2)
|
| 146 |
+
|
| 147 |
+
# Determine which blocks should be masked: (batch_size, num_windows)
|
| 148 |
+
effective_sigma = 1 - (1 - sigma) ** (
|
| 149 |
+
1 / mask_block_size
|
| 150 |
+
) # NOTE: since we mask with blocks, we need to scale sigma by block size
|
| 151 |
+
should_mask = (
|
| 152 |
+
torch.rand(batch_size, num_windows, device=x_0.device) < effective_sigma
|
| 153 |
+
) & fully_maskable
|
| 154 |
+
|
| 155 |
+
# Create final mask using simple broadcasting (fully XLA-compatible)
|
| 156 |
+
# For each position in the sequence, check if it's part of any masked block
|
| 157 |
+
position_indices = torch.arange(seq_len, device=x_0.device) # [seq_len]
|
| 158 |
+
|
| 159 |
+
# Check for each position if it falls within any masked block
|
| 160 |
+
# position_indices: [seq_len] -> [1, 1, seq_len]
|
| 161 |
+
# all_positions: [num_windows, mask_block_size] -> [1, num_windows, mask_block_size]
|
| 162 |
+
# should_mask: [batch_size, num_windows] -> [batch_size, num_windows, 1]
|
| 163 |
+
|
| 164 |
+
position_indices = position_indices.unsqueeze(0).unsqueeze(0) # [1, 1, seq_len]
|
| 165 |
+
all_positions = all_positions.unsqueeze(0) # [1, num_windows, mask_block_size]
|
| 166 |
+
should_mask = should_mask.unsqueeze(2) # [batch_size, num_windows, 1]
|
| 167 |
+
|
| 168 |
+
# Check if each position matches any of the positions in masked blocks
|
| 169 |
+
# [1, 1, seq_len] == [1, num_windows, mask_block_size] -> [1, num_windows, seq_len]
|
| 170 |
+
position_matches = (position_indices == all_positions.unsqueeze(3)).any(
|
| 171 |
+
dim=2
|
| 172 |
+
) # [1, num_windows, seq_len]
|
| 173 |
+
|
| 174 |
+
# Apply should_mask to get final positions to mask
|
| 175 |
+
# [batch_size, num_windows, 1] & [1, num_windows, seq_len] -> [batch_size, num_windows, seq_len]
|
| 176 |
+
should_mask_positions = should_mask & position_matches
|
| 177 |
+
|
| 178 |
+
# Reduce over windows: if any window masks this position, mask it
|
| 179 |
+
final_mask = should_mask_positions.any(dim=1) # [batch_size, seq_len]
|
| 180 |
+
|
| 181 |
+
# Apply the mask
|
| 182 |
+
result = torch.where(final_mask, mask_token_id, x_0)
|
| 183 |
+
|
| 184 |
+
return result
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def prefix_input_ids(input_ids, maskable_mask, apply_prefix):
|
| 188 |
+
"""Apply prefix to input_ids based on configured probability. Return a masksable mask such that the prefix is not masked."""
|
| 189 |
+
batch_size, seq_len = input_ids.shape
|
| 190 |
+
# Generate random prefix lengths for all batch items
|
| 191 |
+
prefix_lengths = torch.randint(1, seq_len, (batch_size,), device=input_ids.device)
|
| 192 |
+
# Create position indices: [1, seq_len]
|
| 193 |
+
position_indices = torch.arange(seq_len, device=input_ids.device).unsqueeze(
|
| 194 |
+
0
|
| 195 |
+
) # [1, seq_len]
|
| 196 |
+
# Create prefix mask: True where position < prefix_length
|
| 197 |
+
prefix_mask = position_indices < prefix_lengths.unsqueeze(
|
| 198 |
+
1
|
| 199 |
+
) # [batch_size, seq_len]
|
| 200 |
+
# Apply prefix masking: set to False where we should apply prefix masking
|
| 201 |
+
maskable_mask = maskable_mask & ~(apply_prefix.unsqueeze(1) & prefix_mask)
|
| 202 |
+
return maskable_mask
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def truncate_input_ids(input_ids, apply_truncate, pad_token_id):
|
| 206 |
+
"""Truncate input_ids at random position and fill with pad token. Return the input_ids with suffix truncated and filled with pad token."""
|
| 207 |
+
batch_size, seq_len = input_ids.shape
|
| 208 |
+
# Generate random truncation positions for all batch items
|
| 209 |
+
truncate_positions = torch.randint(
|
| 210 |
+
1, seq_len, (batch_size,), device=input_ids.device
|
| 211 |
+
)
|
| 212 |
+
# Create position indices: [1, seq_len]
|
| 213 |
+
position_indices = torch.arange(seq_len, device=input_ids.device).unsqueeze(
|
| 214 |
+
0
|
| 215 |
+
) # [1, seq_len]
|
| 216 |
+
# Create truncate mask: True where position >= truncate_position
|
| 217 |
+
truncate_mask = position_indices >= truncate_positions.unsqueeze(
|
| 218 |
+
1
|
| 219 |
+
) # [batch_size, seq_len]
|
| 220 |
+
# Apply truncation: fill with pad token where we should truncate
|
| 221 |
+
input_ids = torch.where(
|
| 222 |
+
apply_truncate.unsqueeze(1) & truncate_mask, pad_token_id, input_ids
|
| 223 |
+
)
|
| 224 |
+
return input_ids
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|im_start|>",
|
| 4 |
+
"<|im_end|>",
|
| 5 |
+
"<|object_ref_start|>",
|
| 6 |
+
"<|object_ref_end|>",
|
| 7 |
+
"<|box_start|>",
|
| 8 |
+
"<|box_end|>",
|
| 9 |
+
"<|quad_start|>",
|
| 10 |
+
"<|quad_end|>",
|
| 11 |
+
"<|vision_start|>",
|
| 12 |
+
"<|vision_end|>",
|
| 13 |
+
"<|vision_pad|>",
|
| 14 |
+
"<|image_pad|>",
|
| 15 |
+
"<|video_pad|>"
|
| 16 |
+
],
|
| 17 |
+
"bos_token": {
|
| 18 |
+
"content": "<|im_end|>",
|
| 19 |
+
"lstrip": false,
|
| 20 |
+
"normalized": false,
|
| 21 |
+
"rstrip": false,
|
| 22 |
+
"single_word": false
|
| 23 |
+
},
|
| 24 |
+
"eos_token": {
|
| 25 |
+
"content": "<|im_end|>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
},
|
| 31 |
+
"mask_token": {
|
| 32 |
+
"content": "<|mask|>",
|
| 33 |
+
"lstrip": false,
|
| 34 |
+
"normalized": false,
|
| 35 |
+
"rstrip": false,
|
| 36 |
+
"single_word": false
|
| 37 |
+
},
|
| 38 |
+
"pad_token": {
|
| 39 |
+
"content": "<|endoftext|>",
|
| 40 |
+
"lstrip": false,
|
| 41 |
+
"normalized": false,
|
| 42 |
+
"rstrip": false,
|
| 43 |
+
"single_word": false
|
| 44 |
+
},
|
| 45 |
+
"sep_token": {
|
| 46 |
+
"content": "<|file_sep|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false
|
| 51 |
+
}
|
| 52 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f463f6eb56afd0ad73bc96eb82f670bedad28b9fcdf170d5167d11eb82ca74ea
|
| 3 |
+
size 11422838
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": true
|
| 180 |
+
},
|
| 181 |
+
"151665": {
|
| 182 |
+
"content": "<tool_response>",
|
| 183 |
+
"lstrip": false,
|
| 184 |
+
"normalized": false,
|
| 185 |
+
"rstrip": false,
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"special": false
|
| 188 |
+
},
|
| 189 |
+
"151666": {
|
| 190 |
+
"content": "</tool_response>",
|
| 191 |
+
"lstrip": false,
|
| 192 |
+
"normalized": false,
|
| 193 |
+
"rstrip": false,
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"special": false
|
| 196 |
+
},
|
| 197 |
+
"151667": {
|
| 198 |
+
"content": "<think>",
|
| 199 |
+
"lstrip": false,
|
| 200 |
+
"normalized": false,
|
| 201 |
+
"rstrip": false,
|
| 202 |
+
"single_word": false,
|
| 203 |
+
"special": false
|
| 204 |
+
},
|
| 205 |
+
"151668": {
|
| 206 |
+
"content": "</think>",
|
| 207 |
+
"lstrip": false,
|
| 208 |
+
"normalized": false,
|
| 209 |
+
"rstrip": false,
|
| 210 |
+
"single_word": false,
|
| 211 |
+
"special": false
|
| 212 |
+
},
|
| 213 |
+
"151669": {
|
| 214 |
+
"content": "<|mask|>",
|
| 215 |
+
"lstrip": false,
|
| 216 |
+
"normalized": false,
|
| 217 |
+
"rstrip": false,
|
| 218 |
+
"single_word": false,
|
| 219 |
+
"special": true
|
| 220 |
+
}
|
| 221 |
+
},
|
| 222 |
+
"additional_special_tokens": [
|
| 223 |
+
"<|im_start|>",
|
| 224 |
+
"<|im_end|>",
|
| 225 |
+
"<|object_ref_start|>",
|
| 226 |
+
"<|object_ref_end|>",
|
| 227 |
+
"<|box_start|>",
|
| 228 |
+
"<|box_end|>",
|
| 229 |
+
"<|quad_start|>",
|
| 230 |
+
"<|quad_end|>",
|
| 231 |
+
"<|vision_start|>",
|
| 232 |
+
"<|vision_end|>",
|
| 233 |
+
"<|vision_pad|>",
|
| 234 |
+
"<|image_pad|>",
|
| 235 |
+
"<|video_pad|>"
|
| 236 |
+
],
|
| 237 |
+
"bos_token": "<|im_end|>",
|
| 238 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# 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>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\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\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- 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>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
|
| 239 |
+
"clean_up_tokenization_spaces": false,
|
| 240 |
+
"eos_token": "<|im_end|>",
|
| 241 |
+
"errors": "replace",
|
| 242 |
+
"extra_special_tokens": {},
|
| 243 |
+
"mask_token": "<|mask|>",
|
| 244 |
+
"model_max_length": 131072,
|
| 245 |
+
"pad_token": "<|endoftext|>",
|
| 246 |
+
"padding_side": "right",
|
| 247 |
+
"sep_token": "<|file_sep|>",
|
| 248 |
+
"split_special_tokens": false,
|
| 249 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 250 |
+
"unk_token": null
|
| 251 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|