Upload folder using huggingface_hub
Browse files- added_tokens.json +0 -0
- config.json +38 -0
- configuration_dream.py +86 -0
- generate_from_llada.py +294 -0
- generation_config.json +16 -0
- generation_utils.py +706 -0
- merges.txt +0 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_dream.py +1781 -0
- special_tokens_map.json +55 -0
- tokenization_dream.py +340 -0
- tokenizer_config.json +0 -0
- vocab.json +0 -0
added_tokens.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
config.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"DreamModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"audio_model_name_or_path": "/data/lijiang/code/Dream/22_local//cognitron_vl_magvit//cognitron_mm/models/dream",
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_dream.DreamConfig",
|
| 9 |
+
"AutoModel": "modeling_dream.DreamModel",
|
| 10 |
+
"AutoModelForCausalLM": "modeling_dream.DreamModel"
|
| 11 |
+
},
|
| 12 |
+
"bos_token_id": 151643,
|
| 13 |
+
"chunk_size": -1,
|
| 14 |
+
"eos_token_id": 151643,
|
| 15 |
+
"hidden_act": "silu",
|
| 16 |
+
"hidden_size": 3584,
|
| 17 |
+
"initializer_range": 0.02,
|
| 18 |
+
"intermediate_size": 18944,
|
| 19 |
+
"mask_token_id": 151666,
|
| 20 |
+
"max_position_embeddings": 131072,
|
| 21 |
+
"max_window_layers": 28,
|
| 22 |
+
"model_type": "Dream",
|
| 23 |
+
"num_attention_heads": 28,
|
| 24 |
+
"num_hidden_layers": 28,
|
| 25 |
+
"num_key_value_heads": 4,
|
| 26 |
+
"pad_token_id": 151643,
|
| 27 |
+
"rms_norm_eps": 1e-06,
|
| 28 |
+
"rope_scaling": null,
|
| 29 |
+
"rope_theta": 1000000.0,
|
| 30 |
+
"sliding_window": null,
|
| 31 |
+
"tie_word_embeddings": false,
|
| 32 |
+
"torch_dtype": "bfloat16",
|
| 33 |
+
"transformers_version": "4.51.3",
|
| 34 |
+
"use_cache": false,
|
| 35 |
+
"use_mrope": false,
|
| 36 |
+
"use_sliding_window": false,
|
| 37 |
+
"vocab_size": 176264
|
| 38 |
+
}
|
configuration_dream.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Dream team, HKUNLP Group and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Dream model configuration"""
|
| 16 |
+
|
| 17 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 18 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
| 19 |
+
from transformers.utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class DreamConfig(PretrainedConfig):
|
| 26 |
+
model_type = "Dream"
|
| 27 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
vocab_size=151936,
|
| 32 |
+
hidden_size=4096,
|
| 33 |
+
intermediate_size=22016,
|
| 34 |
+
num_hidden_layers=32,
|
| 35 |
+
num_attention_heads=32,
|
| 36 |
+
num_key_value_heads=32,
|
| 37 |
+
hidden_act="silu",
|
| 38 |
+
max_position_embeddings=32768,
|
| 39 |
+
initializer_range=0.02,
|
| 40 |
+
rms_norm_eps=1e-6,
|
| 41 |
+
use_cache=False, # cache not used in diffusion
|
| 42 |
+
tie_word_embeddings=False,
|
| 43 |
+
rope_theta=10000.0,
|
| 44 |
+
rope_scaling=None,
|
| 45 |
+
use_sliding_window=False,
|
| 46 |
+
sliding_window=4096,
|
| 47 |
+
max_window_layers=28,
|
| 48 |
+
attention_dropout=0.0,
|
| 49 |
+
mask_token_id=151666,
|
| 50 |
+
pad_token_id=151643,
|
| 51 |
+
**kwargs,
|
| 52 |
+
):
|
| 53 |
+
self.vocab_size = vocab_size
|
| 54 |
+
self.max_position_embeddings = max_position_embeddings
|
| 55 |
+
self.hidden_size = hidden_size
|
| 56 |
+
self.intermediate_size = intermediate_size
|
| 57 |
+
self.num_hidden_layers = num_hidden_layers
|
| 58 |
+
self.num_attention_heads = num_attention_heads
|
| 59 |
+
self.use_sliding_window = use_sliding_window
|
| 60 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
| 61 |
+
self.max_window_layers = max_window_layers
|
| 62 |
+
|
| 63 |
+
# for backward compatibility
|
| 64 |
+
if num_key_value_heads is None:
|
| 65 |
+
num_key_value_heads = num_attention_heads
|
| 66 |
+
|
| 67 |
+
self.num_key_value_heads = num_key_value_heads
|
| 68 |
+
self.hidden_act = hidden_act
|
| 69 |
+
self.initializer_range = initializer_range
|
| 70 |
+
self.rms_norm_eps = rms_norm_eps
|
| 71 |
+
self.use_cache = use_cache
|
| 72 |
+
self.rope_theta = rope_theta
|
| 73 |
+
self.rope_scaling = rope_scaling
|
| 74 |
+
self.attention_dropout = attention_dropout
|
| 75 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 76 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 77 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 78 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 79 |
+
rope_config_validation(self)
|
| 80 |
+
|
| 81 |
+
super().__init__(
|
| 82 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 83 |
+
**kwargs,
|
| 84 |
+
)
|
| 85 |
+
self.mask_token_id = mask_token_id
|
| 86 |
+
self.pad_token_id = pad_token_id
|
generate_from_llada.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
from transformers import AutoTokenizer, AutoModel
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def add_gumbel_noise(logits, temperature):
|
| 9 |
+
'''
|
| 10 |
+
The Gumbel max is a method for sampling categorical distributions.
|
| 11 |
+
According to arXiv:2409.02908, for MDM, low-precision Gumbel Max improves perplexity score but reduces generation quality.
|
| 12 |
+
Thus, we use float64.
|
| 13 |
+
'''
|
| 14 |
+
if temperature == 0:
|
| 15 |
+
return logits
|
| 16 |
+
logits = logits.to(torch.float64)
|
| 17 |
+
noise = torch.rand_like(logits, dtype=torch.float64)
|
| 18 |
+
gumbel_noise = (- torch.log(noise)) ** temperature
|
| 19 |
+
return logits.exp() / gumbel_noise
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_num_transfer_tokens(mask_index, steps):
|
| 23 |
+
'''
|
| 24 |
+
In the reverse process, the interval [0, 1] is uniformly discretized into steps intervals.
|
| 25 |
+
Furthermore, because LLaDA employs a linear noise schedule (as defined in Eq. (8)),
|
| 26 |
+
the expected number of tokens transitioned at each step should be consistent.
|
| 27 |
+
|
| 28 |
+
This function is designed to precompute the number of tokens that need to be transitioned at each step.
|
| 29 |
+
'''
|
| 30 |
+
mask_num = mask_index.sum(dim=1, keepdim=True)
|
| 31 |
+
|
| 32 |
+
base = mask_num // steps
|
| 33 |
+
remainder = mask_num % steps
|
| 34 |
+
|
| 35 |
+
num_transfer_tokens = torch.zeros(mask_num.size(0), steps, device=mask_index.device, dtype=torch.int64) + base
|
| 36 |
+
|
| 37 |
+
for i in range(mask_num.size(0)):
|
| 38 |
+
num_transfer_tokens[i, :remainder[i]] += 1
|
| 39 |
+
|
| 40 |
+
return num_transfer_tokens
|
| 41 |
+
|
| 42 |
+
def get_num_transfer_tokens_sch(mask_index, steps,schedule=None,schedule_kwargs=None):
|
| 43 |
+
'''
|
| 44 |
+
In the reverse process, the interval [0, 1] is uniformly discretized into steps intervals.
|
| 45 |
+
Furthermore, because LLaDA employs a linear noise schedule (as defined in Eq. (8)),
|
| 46 |
+
the expected number of tokens transitioned at each step should be consistent.
|
| 47 |
+
|
| 48 |
+
This function is designed to precompute the number of tokens that need to be transitioned at each step.
|
| 49 |
+
'''
|
| 50 |
+
if schedule is None:
|
| 51 |
+
return get_num_transfer_tokens(mask_index,steps)
|
| 52 |
+
if schedule_kwargs is None:
|
| 53 |
+
schedule_kwargs = {}
|
| 54 |
+
|
| 55 |
+
mask_num = mask_index.sum(dim=1, keepdim=True)
|
| 56 |
+
steps = int(min(steps,mask_num[0]))
|
| 57 |
+
t = torch.linspace(0, 1, steps+1)
|
| 58 |
+
# at least one sample per step
|
| 59 |
+
if schedule =='logit_normal':
|
| 60 |
+
sigmas = sigmoid_normal_cdf(t)
|
| 61 |
+
elif schedule =='shift':
|
| 62 |
+
sigmas = logit_normal_schedule(schedule_kwargs.get('shift',3),t)
|
| 63 |
+
elif schedule == 'cosine':
|
| 64 |
+
sigmas = cosine_schedule(t)
|
| 65 |
+
else:
|
| 66 |
+
sigmas = t
|
| 67 |
+
sigmas = sigmas.to(mask_num.device)
|
| 68 |
+
num_transfer_tokens = torch.zeros(mask_num.size(0), steps, device=mask_index.device, dtype=torch.int64)
|
| 69 |
+
|
| 70 |
+
for i in range(mask_num.size(0)):
|
| 71 |
+
# print(sigmas.shape)
|
| 72 |
+
sigmas_sample = (sigmas*mask_num[i]).to(torch.int64)
|
| 73 |
+
# print(sigmas_sample)
|
| 74 |
+
sigmas_sample = sigmas_sample[1:]-sigmas_sample[:-1]
|
| 75 |
+
# print(sigmas_sample)
|
| 76 |
+
# fix detal
|
| 77 |
+
sigmas_sample = torch.clamp(sigmas_sample,1,None) # should only increase
|
| 78 |
+
delta = sigmas_sample.sum() - mask_num[i]
|
| 79 |
+
# breakpoint()
|
| 80 |
+
assert delta>=0
|
| 81 |
+
j = 0
|
| 82 |
+
|
| 83 |
+
while delta > 0:
|
| 84 |
+
j = j % len(sigmas_sample)
|
| 85 |
+
if sigmas_sample[j] == 1:
|
| 86 |
+
j += 1
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
delta -= 1
|
| 90 |
+
sigmas_sample[j] -= 1
|
| 91 |
+
j += 1
|
| 92 |
+
# breakpoint()
|
| 93 |
+
assert sigmas_sample.sum()==mask_num[i]
|
| 94 |
+
num_transfer_tokens[i] = sigmas_sample#.to(torch.int64)
|
| 95 |
+
return num_transfer_tokens.flip(-1)
|
| 96 |
+
|
| 97 |
+
def linear(y):
|
| 98 |
+
return y
|
| 99 |
+
|
| 100 |
+
def cosine_schedule(x):
|
| 101 |
+
"""
|
| 102 |
+
Cosine schedule mapping [0, 1] -> [1, 0]
|
| 103 |
+
"""
|
| 104 |
+
x = np.clip(x, 0, 1)
|
| 105 |
+
return 1-0.5 * (1 + np.cos(np.pi * x))
|
| 106 |
+
|
| 107 |
+
def sigmoid_normal_cdf(y):
|
| 108 |
+
# y must be in (0, 1)
|
| 109 |
+
logit_y = torch.log(y / (1 - y))
|
| 110 |
+
return 0.5 * (1 + torch.erf(logit_y / torch.sqrt(torch.tensor(2.0))))
|
| 111 |
+
def logit_normal_schedule(shift,sigmas):
|
| 112 |
+
# shift = 1 / shift
|
| 113 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
|
| 114 |
+
return sigmas
|
| 115 |
+
import os
|
| 116 |
+
DEBUG_PRINT_OUTPUT = os.environ.get('DEBUG_PRINT_OUTPUT',False)
|
| 117 |
+
@ torch.no_grad()
|
| 118 |
+
def generate(model, prompt=None, steps=None, max_new_tokens=128, block_length=128, temperature=0.,
|
| 119 |
+
cfg_scale=0., remasking='low_confidence', mask_id=126336,inputs_embeds=None, position_ids=None,attention_mask=None,
|
| 120 |
+
tokenizer=None,
|
| 121 |
+
verbose=False,
|
| 122 |
+
step_per_block=None,
|
| 123 |
+
prefix_lm=False,
|
| 124 |
+
schedule=None,
|
| 125 |
+
schedule_kwargs=None,
|
| 126 |
+
draft_tokens=None,
|
| 127 |
+
step_ratio=None,
|
| 128 |
+
**kwargs):
|
| 129 |
+
'''
|
| 130 |
+
Args:
|
| 131 |
+
model: Mask predictor.
|
| 132 |
+
prompt: A tensor of shape (1, L).
|
| 133 |
+
steps: Sampling steps, less than or equal to gen_length.
|
| 134 |
+
gen_length: Generated answer length.
|
| 135 |
+
block_length: Block length, less than or equal to gen_length. If less than gen_length, it means using semi_autoregressive remasking.
|
| 136 |
+
temperature: Categorical distribution sampling temperature.
|
| 137 |
+
cfg_scale: Unsupervised classifier-free guidance scale.
|
| 138 |
+
remasking: Remasking strategy. 'low_confidence' or 'random'.
|
| 139 |
+
mask_id: The toke id of [MASK] is 126336.
|
| 140 |
+
'''
|
| 141 |
+
# breakpoint()
|
| 142 |
+
# remasking =
|
| 143 |
+
# step_ratio = 0.5
|
| 144 |
+
# block_length = 1024
|
| 145 |
+
# steps = 1024
|
| 146 |
+
steps = max_new_tokens # min(steps,max_new_tokens)
|
| 147 |
+
# if step_ratio:
|
| 148 |
+
# steps = int(max_new_tokens*step_ratio)
|
| 149 |
+
gen_length = max_new_tokens
|
| 150 |
+
assert position_ids is None
|
| 151 |
+
if prompt is None:
|
| 152 |
+
assert inputs_embeds is not None
|
| 153 |
+
bsz, seq_len = inputs_embeds.shape[:2]
|
| 154 |
+
prompt = torch.full((bsz, seq_len), 0, dtype=torch.long).to(model.device)
|
| 155 |
+
past_key_values = None
|
| 156 |
+
if prefix_lm:
|
| 157 |
+
past_key_values = model(None,input_embeddings=inputs_embeds,use_cache=True).attn_key_values
|
| 158 |
+
# breakpoint()
|
| 159 |
+
x = torch.full((1, gen_length), mask_id, dtype=torch.long).to(model.device)
|
| 160 |
+
prompt = torch.full((bsz, 0), 0, dtype=torch.long).to(model.device)
|
| 161 |
+
# x[:, :prompt.shape[1]] = prompt.clone()
|
| 162 |
+
else:
|
| 163 |
+
x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
|
| 164 |
+
x[:, :prompt.shape[1]] = prompt.clone()
|
| 165 |
+
|
| 166 |
+
prompt_index = (x != mask_id)
|
| 167 |
+
assert prompt.shape[0] == 1
|
| 168 |
+
if draft_tokens is not None:
|
| 169 |
+
assert draft_tokens.shape[1] <= gen_length
|
| 170 |
+
x[:, prompt.shape[1]:prompt.shape[1]+draft_tokens.shape[1]] = draft_tokens.clone()
|
| 171 |
+
|
| 172 |
+
# if block_length < gen_length:
|
| 173 |
+
# block_length = gen_length
|
| 174 |
+
assert gen_length % block_length == 0
|
| 175 |
+
num_blocks = gen_length // block_length
|
| 176 |
+
|
| 177 |
+
assert ( steps % num_blocks == 0) or step_per_block is not None
|
| 178 |
+
steps = steps // num_blocks
|
| 179 |
+
if step_per_block:
|
| 180 |
+
steps = min(step_per_block,block_length)
|
| 181 |
+
assert step_ratio is None, 'Please do not pass both step_ratio and step_per_block'
|
| 182 |
+
# step_ratio = 0.5
|
| 183 |
+
# schedule = 'shift'
|
| 184 |
+
# schedule_kwargs = dict(shift=3)
|
| 185 |
+
# breakpoint()
|
| 186 |
+
if step_ratio:
|
| 187 |
+
steps = int(steps*step_ratio)
|
| 188 |
+
|
| 189 |
+
# print(steps,step_per_block,block_length,draft_tokens.shape[-1])
|
| 190 |
+
# NFE = 0
|
| 191 |
+
if verbose:
|
| 192 |
+
history = []
|
| 193 |
+
for num_block in range(num_blocks):
|
| 194 |
+
|
| 195 |
+
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length:] == mask_id)
|
| 196 |
+
num_transfer_tokens = get_num_transfer_tokens_sch(block_mask_index, steps,schedule=schedule,schedule_kwargs=schedule_kwargs)
|
| 197 |
+
if DEBUG_PRINT_OUTPUT:
|
| 198 |
+
print(f"Block: {num_block + 1}/{num_blocks}, Steps per Block: {steps}, Block Length: {block_length}")
|
| 199 |
+
print(f"Tokens generated per step {num_transfer_tokens[0]}")
|
| 200 |
+
for i in range(steps):
|
| 201 |
+
# print(i)
|
| 202 |
+
mask_index = (x == mask_id)
|
| 203 |
+
# print(mask_index.sum())
|
| 204 |
+
if mask_index.sum() == 0:
|
| 205 |
+
continue
|
| 206 |
+
# NFE += 2
|
| 207 |
+
if cfg_scale > 0.:
|
| 208 |
+
assert NotImplementedError('cfg_scale > 0. is not supported.')
|
| 209 |
+
un_x = x.clone()
|
| 210 |
+
un_x[prompt_index] = mask_id
|
| 211 |
+
x_ = torch.cat([x, un_x], dim=0)
|
| 212 |
+
#
|
| 213 |
+
logits = model(x_,input_embeds_inference=[inputs_embeds,None]).logits
|
| 214 |
+
logits, un_logits = torch.chunk(logits, 2, dim=0)
|
| 215 |
+
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
|
| 216 |
+
else:
|
| 217 |
+
inputs_embeds_curr = model.transformer.wte(x)
|
| 218 |
+
#print(tokenizer.batch_decode(x)[0].replace('<|endoftext|>',''))
|
| 219 |
+
# print((x==mask_id).sum())
|
| 220 |
+
# breakpoint()
|
| 221 |
+
if prefix_lm:
|
| 222 |
+
# breakpoint()
|
| 223 |
+
logits = model(None,input_embeddings=inputs_embeds_curr,past_key_values=past_key_values).logits
|
| 224 |
+
else:
|
| 225 |
+
if inputs_embeds is not None:
|
| 226 |
+
inputs_embeds_curr[:,:inputs_embeds.shape[1]] = inputs_embeds
|
| 227 |
+
logits = model(None,input_embeddings=inputs_embeds_curr).logits
|
| 228 |
+
# logits = logits.cpu()
|
| 229 |
+
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
|
| 230 |
+
x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
|
| 231 |
+
# torch.cuda.empty_cache()
|
| 232 |
+
# torch.cuda.synchronize()
|
| 233 |
+
if remasking == 'low_confidence':
|
| 234 |
+
p = F.softmax(logits.to(torch.float64), dim=-1)
|
| 235 |
+
x0_p = torch.squeeze(
|
| 236 |
+
torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
|
| 237 |
+
elif remasking == 'random':
|
| 238 |
+
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
|
| 239 |
+
elif remasking == 'entrophy':
|
| 240 |
+
epsilon = 1e-10
|
| 241 |
+
probs = F.softmax(logits.to(torch.float64), dim=-1)
|
| 242 |
+
log_probs = torch.log(probs + epsilon)
|
| 243 |
+
x0_p = torch.sum(probs * log_probs, dim=-1)
|
| 244 |
+
elif remasking == 'margin':
|
| 245 |
+
## similar to margin algo in Dream
|
| 246 |
+
p = F.softmax(logits.to(torch.float64), dim=-1)
|
| 247 |
+
sorted_probs, _ = torch.sort(p, dim=-1, descending=True)
|
| 248 |
+
top1_probs = sorted_probs[:, :, 0]
|
| 249 |
+
top2_probs = sorted_probs[:, :, 1]
|
| 250 |
+
x0_p = top1_probs - top2_probs
|
| 251 |
+
else:
|
| 252 |
+
raise NotImplementedError(remasking)
|
| 253 |
+
|
| 254 |
+
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
|
| 255 |
+
|
| 256 |
+
x0 = torch.where(mask_index, x0, x)
|
| 257 |
+
confidence = torch.where(mask_index, x0_p, -np.inf)
|
| 258 |
+
|
| 259 |
+
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
|
| 260 |
+
for j in range(confidence.shape[0]):
|
| 261 |
+
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
|
| 262 |
+
transfer_index[j, select_index] = True
|
| 263 |
+
x[transfer_index] = x0[transfer_index]
|
| 264 |
+
if verbose:
|
| 265 |
+
history.append(x.clone().cpu())
|
| 266 |
+
# breakpoint()
|
| 267 |
+
# print(f"NFE: {NFE} Num Blocks: {num_blocks}")
|
| 268 |
+
if verbose:
|
| 269 |
+
return x,history
|
| 270 |
+
return x
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def main():
|
| 274 |
+
device = 'cuda'
|
| 275 |
+
|
| 276 |
+
model = AutoModel.from_pretrained('GSAI-ML/LLaDA-8B-Instruct', trust_remote_code=True, torch_dtype=torch.bfloat16).to(device).eval()
|
| 277 |
+
tokenizer = AutoTokenizer.from_pretrained('GSAI-ML/LLaDA-8B-Instruct', trust_remote_code=True)
|
| 278 |
+
|
| 279 |
+
prompt = "Lily can run 12 kilometers per hour for 4 hours. After that, she runs 6 kilometers per hour. How many kilometers can she run in 8 hours?"
|
| 280 |
+
|
| 281 |
+
# Add special tokens for the Instruct model. The Base model does not require the following two lines.
|
| 282 |
+
m = [{"role": "user", "content": prompt}, ]
|
| 283 |
+
prompt = tokenizer.apply_chat_template(m, add_generation_prompt=True, tokenize=False)
|
| 284 |
+
|
| 285 |
+
input_ids = tokenizer(prompt)['input_ids']
|
| 286 |
+
input_ids = torch.tensor(input_ids).to(device).unsqueeze(0)
|
| 287 |
+
|
| 288 |
+
out = generate(model, input_ids, steps=128, gen_length=128, block_length=32, temperature=0., cfg_scale=0., remasking='low_confidence')
|
| 289 |
+
print(tokenizer.batch_decode(out[:, input_ids.shape[1]:], skip_special_tokens=True)[0])
|
| 290 |
+
generate(model, input_ids, steps=128, gen_length=128, block_length=32, temperature=0., cfg_scale=0., remasking='low_confidence')
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
if __name__ == '__main__':
|
| 294 |
+
main()
|
generation_config.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"alg": "origin",
|
| 4 |
+
"alg_temp": null,
|
| 5 |
+
"bos_token_id": 151643,
|
| 6 |
+
"eos_token_id": 151643,
|
| 7 |
+
"eps": 0.001,
|
| 8 |
+
"mask_token_id": null,
|
| 9 |
+
"output_history": false,
|
| 10 |
+
"pad_token_id": 151643,
|
| 11 |
+
"steps": 512,
|
| 12 |
+
"temperature": 0.0,
|
| 13 |
+
"top_k": null,
|
| 14 |
+
"top_p": null,
|
| 15 |
+
"transformers_version": "4.51.3"
|
| 16 |
+
}
|
generation_utils.py
ADDED
|
@@ -0,0 +1,706 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import warnings
|
| 17 |
+
import copy
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributions as dists
|
| 23 |
+
from torch.nn import functional as F
|
| 24 |
+
from transformers import __version__
|
| 25 |
+
from transformers.generation.configuration_utils import (
|
| 26 |
+
GenerationConfig
|
| 27 |
+
)
|
| 28 |
+
from transformers.utils import (
|
| 29 |
+
ModelOutput,
|
| 30 |
+
is_torchdynamo_compiling,
|
| 31 |
+
logging,
|
| 32 |
+
)
|
| 33 |
+
from .generate_from_llada import get_num_transfer_tokens_sch
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
import sys
|
| 37 |
+
import pdb
|
| 38 |
+
class ForkedPdb(pdb.Pdb):
|
| 39 |
+
"""
|
| 40 |
+
PDB Subclass for debugging multi-processed code
|
| 41 |
+
Suggested in: https://stackoverflow.com/questions/4716533/how-to-attach-debugger-to-a-python-subproccess
|
| 42 |
+
"""
|
| 43 |
+
def interaction(self, *args, **kwargs):
|
| 44 |
+
_stdin = sys.stdin
|
| 45 |
+
try:
|
| 46 |
+
sys.stdin = open('/dev/stdin')
|
| 47 |
+
pdb.Pdb.interaction(self, *args, **kwargs)
|
| 48 |
+
finally:
|
| 49 |
+
sys.stdin = _stdin
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def top_p_logits(logits, top_p=None):
|
| 53 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 54 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 55 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 56 |
+
# Shift the indices to the right to keep the first token above the threshold
|
| 57 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 58 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 59 |
+
|
| 60 |
+
mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
|
| 61 |
+
mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
|
| 62 |
+
logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
|
| 63 |
+
return logits
|
| 64 |
+
|
| 65 |
+
def top_k_logits(logits, top_k=None):
|
| 66 |
+
top_k = min(top_k, logits.size(-1)) # Safety check
|
| 67 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
| 68 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 69 |
+
logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
|
| 70 |
+
return logits
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False):
|
| 74 |
+
|
| 75 |
+
# if temperature > 0:
|
| 76 |
+
# logits = logits / temperature
|
| 77 |
+
# if top_p is not None and top_p < 1:
|
| 78 |
+
# logits = top_p_logits(logits, top_p)
|
| 79 |
+
# if top_k is not None:
|
| 80 |
+
# logits = top_k_logits(logits, top_k)
|
| 81 |
+
# probs = torch.softmax(logits, dim=-1)
|
| 82 |
+
|
| 83 |
+
# if temperature > 0:
|
| 84 |
+
# try:
|
| 85 |
+
# x0 = dists.Categorical(probs=probs).sample()
|
| 86 |
+
# confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
|
| 87 |
+
# except:
|
| 88 |
+
# confidence, x0 = probs.max(dim=-1)
|
| 89 |
+
# else:
|
| 90 |
+
# confidence, x0 = probs.max(dim=-1)
|
| 91 |
+
|
| 92 |
+
# if margin_confidence:
|
| 93 |
+
# sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
|
| 94 |
+
# # Extract top1 and top2 probabilities
|
| 95 |
+
# top1_probs = sorted_probs[:, 0]
|
| 96 |
+
# top2_probs = sorted_probs[:, 1]
|
| 97 |
+
# # Calculate confidence as top1 - top2
|
| 98 |
+
# confidence = top1_probs - top2_probs
|
| 99 |
+
|
| 100 |
+
# if neg_entropy:
|
| 101 |
+
# epsilon = 1e-10
|
| 102 |
+
# log_probs = torch.log(probs + epsilon)
|
| 103 |
+
# confidence = torch.sum(probs * log_probs, dim=-1)
|
| 104 |
+
|
| 105 |
+
# return confidence, x0
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False):
|
| 109 |
+
"""
|
| 110 |
+
从给定的 logits 中采样或贪心选取 token,并返回置信度和 token ID。
|
| 111 |
+
|
| 112 |
+
参数:
|
| 113 |
+
logits (Tensor):形状 [batch_size, vocab_size],模型对各候选 token 的打分(未经 softmax)。
|
| 114 |
+
temperature (float):温度系数,默认 0.0。>0 时按概率采样,=0 时贪心选取。
|
| 115 |
+
top_p (float 或 None):核采样参数(nucleus sampling),若指定且 <1,只保留累计概率前 top_p 的 token。
|
| 116 |
+
top_k (int 或 None):前 k 采样参数(top-k sampling),若指定,只从概率最高的 k 个 token 中选取。
|
| 117 |
+
margin_confidence (bool):是否使用 top1−top2 之差作为置信度,默认 False。
|
| 118 |
+
neg_entropy (bool):是否使用负熵(−∑p·logp)作为置信度,默认 False。
|
| 119 |
+
|
| 120 |
+
返回:
|
| 121 |
+
confidence (Tensor):形状 [batch_size] 的置信度值(可用概率、margin 差值或负熵)。
|
| 122 |
+
x0 (Tensor):形状 [batch_size] 的 int64 张量,表示采样或贪心得到的 token ID。
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
# ======================================================
|
| 126 |
+
# 1. 温度缩放 (Temperature Scaling)
|
| 127 |
+
# ======================================================
|
| 128 |
+
if temperature > 0:
|
| 129 |
+
# 当 temperature>0 时,将 logits 除以 temperature,使得 softmax 分布更平滑或更尖锐
|
| 130 |
+
logits = logits / temperature
|
| 131 |
+
|
| 132 |
+
# ======================================================
|
| 133 |
+
# 2. Top-p (Nucleus) 与 Top-k 过滤
|
| 134 |
+
# ======================================================
|
| 135 |
+
if top_p is not None and top_p < 1:
|
| 136 |
+
# 调用 top_p_logits,保留累计概率达到 top_p 的 token,其它 logits 置为很小的负值
|
| 137 |
+
logits = top_p_logits(logits, top_p)
|
| 138 |
+
if top_k is not None:
|
| 139 |
+
# 调用 top_k_logits,仅保留概率最高的 top_k 个 token,其它 logits 置为很小的负值
|
| 140 |
+
logits = top_k_logits(logits, top_k)
|
| 141 |
+
|
| 142 |
+
# ======================================================
|
| 143 |
+
# 3. 计算概率分布 (Softmax)
|
| 144 |
+
# ======================================================
|
| 145 |
+
probs = torch.softmax(logits, dim=-1)
|
| 146 |
+
# 此时 probs 形状为 [batch_size, vocab_size],每行和为 1
|
| 147 |
+
|
| 148 |
+
# ======================================================
|
| 149 |
+
# 4. 根据 temperature 决定采样或贪心选取
|
| 150 |
+
# ======================================================
|
| 151 |
+
if temperature > 0:
|
| 152 |
+
# 随机采样分支:从 Categorical 分布中采样 token
|
| 153 |
+
try:
|
| 154 |
+
# 从多项分布中采样得到 token ID,形状 [batch_size]
|
| 155 |
+
x0 = dists.Categorical(probs=probs).sample()
|
| 156 |
+
# 用 gather 取出对应位置的概率值作为置信度,形状 [batch_size]
|
| 157 |
+
confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
|
| 158 |
+
except:
|
| 159 |
+
# 若采样出错(如概率分布不合法),退化为贪心选取
|
| 160 |
+
confidence, x0 = probs.max(dim=-1)
|
| 161 |
+
else:
|
| 162 |
+
# 当 temperature=0 时,直接贪心选取概率最大的 token
|
| 163 |
+
confidence, x0 = probs.max(dim=-1)
|
| 164 |
+
|
| 165 |
+
# ======================================================
|
| 166 |
+
# 5. margin_confidence: 使用 top1−top2 差值作为置信度
|
| 167 |
+
# ======================================================
|
| 168 |
+
if margin_confidence:
|
| 169 |
+
# 将每行概率按降序排序,sorted_probs[:,0] 为 top1,sorted_probs[:,1] 为 top2
|
| 170 |
+
sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
|
| 171 |
+
top1_probs = sorted_probs[:, 0]
|
| 172 |
+
top2_probs = sorted_probs[:, 1]
|
| 173 |
+
# 置信度设为 top1_probs − top2_probs
|
| 174 |
+
confidence = top1_probs - top2_probs
|
| 175 |
+
|
| 176 |
+
# ======================================================
|
| 177 |
+
# 6. neg_entropy: 使用负熵(−∑ p·log p)作为置信度
|
| 178 |
+
# ======================================================
|
| 179 |
+
if neg_entropy:
|
| 180 |
+
epsilon = 1e-10
|
| 181 |
+
# 为避免 log(0) 产生 −inf,加上一个小常数 epsilon
|
| 182 |
+
log_probs = torch.log(probs + epsilon)
|
| 183 |
+
# 计算 ∑ p_i * log p_i,结果是负熵值(值越接近 0,表示分布更“尖锐”)
|
| 184 |
+
confidence = torch.sum(probs * log_probs, dim=-1)
|
| 185 |
+
|
| 186 |
+
return confidence, x0
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@dataclass
|
| 191 |
+
class DreamModelOutput(ModelOutput):
|
| 192 |
+
sequences: torch.LongTensor = None
|
| 193 |
+
history: Optional[Tuple[torch.FloatTensor]] = None
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class DreamGenerationConfig(GenerationConfig):
|
| 197 |
+
def __init__(self, **kwargs):
|
| 198 |
+
self.temperature: float = kwargs.pop("temperature", 0.0)
|
| 199 |
+
self.top_p: Optional[float] = kwargs.pop("top_p", None)
|
| 200 |
+
self.top_k: Optional[int] = kwargs.pop("top_k", None)
|
| 201 |
+
self.max_length = kwargs.pop("max_length", 20)
|
| 202 |
+
self.max_new_tokens = kwargs.pop("max_new_tokens", None)
|
| 203 |
+
# diffusion specific params
|
| 204 |
+
self.eps: float = kwargs.pop("eps", 1e-3)
|
| 205 |
+
self.steps: int = kwargs.pop("steps", 512)
|
| 206 |
+
self.alg: str = kwargs.pop("alg", 'origin')
|
| 207 |
+
self.alg_temp: Optional[float] = kwargs.pop("alg_temp", None)
|
| 208 |
+
|
| 209 |
+
# Parameters that define the output variables of `generate`
|
| 210 |
+
self.num_return_sequences: int = kwargs.pop("num_return_sequences", 1)
|
| 211 |
+
self.return_dict_in_generate: bool = kwargs.pop("return_dict_in_generate", False)
|
| 212 |
+
self.output_history: bool = kwargs.pop("output_history", False)
|
| 213 |
+
|
| 214 |
+
# Special tokens that can be used at generation time
|
| 215 |
+
self.mask_token_id = kwargs.pop("mask_token_id", None)
|
| 216 |
+
self.pad_token_id = kwargs.pop("pad_token_id", None)
|
| 217 |
+
self.bos_token_id = kwargs.pop("bos_token_id", None)
|
| 218 |
+
self.eos_token_id = kwargs.pop("eos_token_id", None)
|
| 219 |
+
|
| 220 |
+
# Wild card
|
| 221 |
+
self.generation_kwargs = kwargs.pop("generation_kwargs", {})
|
| 222 |
+
|
| 223 |
+
# The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub
|
| 224 |
+
# interface.
|
| 225 |
+
self._from_model_config = kwargs.pop("_from_model_config", False)
|
| 226 |
+
self._commit_hash = kwargs.pop("_commit_hash", None)
|
| 227 |
+
self.transformers_version = kwargs.pop("transformers_version", __version__)
|
| 228 |
+
|
| 229 |
+
# Additional attributes without default values
|
| 230 |
+
if not self._from_model_config:
|
| 231 |
+
# we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
|
| 232 |
+
# model's default configuration file
|
| 233 |
+
for key, value in kwargs.items():
|
| 234 |
+
try:
|
| 235 |
+
setattr(self, key, value)
|
| 236 |
+
except AttributeError as err:
|
| 237 |
+
logger.error(f"Can't set {key} with value {value} for {self}")
|
| 238 |
+
raise err
|
| 239 |
+
|
| 240 |
+
# Validate the values of the attributes
|
| 241 |
+
self.validate(is_init=True)
|
| 242 |
+
|
| 243 |
+
def validate(self, is_init=False):
|
| 244 |
+
pass
|
| 245 |
+
|
| 246 |
+
class DreamGenerationMixin:
|
| 247 |
+
@staticmethod
|
| 248 |
+
def _expand_inputs_for_generation(
|
| 249 |
+
expand_size: int = 1,
|
| 250 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 251 |
+
attention_mask: Optional[torch.LongTensor] = None
|
| 252 |
+
) -> Tuple[torch.LongTensor, Dict[str, Any]]:
|
| 253 |
+
"""Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
|
| 254 |
+
# Do not call torch.repeat_interleave if expand_size is 1 because it clones
|
| 255 |
+
# the input tensor and thus requires more memory although no change is applied
|
| 256 |
+
if expand_size == 1:
|
| 257 |
+
return input_ids, attention_mask
|
| 258 |
+
if input_ids is not None:
|
| 259 |
+
input_ids = input_ids.repeat_interleave(expand_size, dim=0)
|
| 260 |
+
if attention_mask is not None:
|
| 261 |
+
attention_mask = attention_mask.repeat_interleave(expand_size, dim=0)
|
| 262 |
+
return input_ids, attention_mask
|
| 263 |
+
|
| 264 |
+
def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
|
| 265 |
+
"""Performs validation related to the resulting generated length"""
|
| 266 |
+
|
| 267 |
+
# Can't throw warnings/exceptions during compilation
|
| 268 |
+
if is_torchdynamo_compiling():
|
| 269 |
+
return
|
| 270 |
+
|
| 271 |
+
# 1. Max length warnings related to poor parameterization
|
| 272 |
+
if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
|
| 273 |
+
# 20 is the default max_length of the generation config
|
| 274 |
+
warnings.warn(
|
| 275 |
+
f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
|
| 276 |
+
"generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
|
| 277 |
+
"generation.",
|
| 278 |
+
UserWarning,
|
| 279 |
+
)
|
| 280 |
+
if input_ids_length >= generation_config.max_length:
|
| 281 |
+
input_ids_string = "input_ids"
|
| 282 |
+
raise ValueError(
|
| 283 |
+
f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
|
| 284 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
| 285 |
+
" increasing `max_length` or, better yet, setting `max_new_tokens`."
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
def _prepare_generated_length(
|
| 289 |
+
self,
|
| 290 |
+
generation_config,
|
| 291 |
+
has_default_max_length,
|
| 292 |
+
input_ids_length,
|
| 293 |
+
):
|
| 294 |
+
"""Prepared max and min length in generation configs to avoid clashes between similar attributes"""
|
| 295 |
+
|
| 296 |
+
if generation_config.max_new_tokens is not None:
|
| 297 |
+
if not has_default_max_length and generation_config.max_length is not None:
|
| 298 |
+
logger.warning(
|
| 299 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
| 300 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
| 301 |
+
"Please refer to the documentation for more information. "
|
| 302 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
|
| 303 |
+
)
|
| 304 |
+
generation_config.max_length = generation_config.max_new_tokens + input_ids_length
|
| 305 |
+
|
| 306 |
+
elif has_default_max_length:
|
| 307 |
+
if generation_config.max_length == DreamGenerationConfig().max_length:
|
| 308 |
+
generation_config.max_length = generation_config.max_length + input_ids_length
|
| 309 |
+
max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
|
| 310 |
+
if max_position_embeddings is not None:
|
| 311 |
+
generation_config.max_length = min(generation_config.max_length, max_position_embeddings)
|
| 312 |
+
|
| 313 |
+
return generation_config
|
| 314 |
+
|
| 315 |
+
def _prepare_generation_config(
|
| 316 |
+
self, generation_config: Optional[DreamGenerationConfig], **kwargs: Dict
|
| 317 |
+
) -> DreamGenerationConfig:
|
| 318 |
+
"""
|
| 319 |
+
Prepares the base generation config, then applies any generation configuration options from kwargs. This
|
| 320 |
+
function handles retrocompatibility with respect to configuration files.
|
| 321 |
+
"""
|
| 322 |
+
# priority: `generation_config` argument > `model.generation_config` (the default generation config)
|
| 323 |
+
using_model_generation_config = False
|
| 324 |
+
if generation_config is None:
|
| 325 |
+
generation_config = DreamGenerationConfig.from_model_config(self.config)
|
| 326 |
+
using_model_generation_config = True
|
| 327 |
+
|
| 328 |
+
# `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
|
| 329 |
+
# will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an
|
| 330 |
+
# exception will be raised in `_validate_model_kwargs`
|
| 331 |
+
if not is_torchdynamo_compiling():
|
| 332 |
+
generation_config = copy.deepcopy(generation_config)
|
| 333 |
+
_kwargs = generation_config.update(**kwargs)
|
| 334 |
+
# If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model
|
| 335 |
+
if not using_model_generation_config:
|
| 336 |
+
if generation_config.bos_token_id is None:
|
| 337 |
+
generation_config.bos_token_id = self.generation_config.bos_token_id
|
| 338 |
+
if generation_config.eos_token_id is None:
|
| 339 |
+
generation_config.eos_token_id = self.generation_config.eos_token_id
|
| 340 |
+
if generation_config.pad_token_id is None:
|
| 341 |
+
generation_config.pad_token_id = self.generation_config.pad_token_id
|
| 342 |
+
if generation_config.mask_token_id is None:
|
| 343 |
+
generation_config.mask_token_id = self.generation_config.mask_token_id
|
| 344 |
+
|
| 345 |
+
return generation_config
|
| 346 |
+
|
| 347 |
+
def _prepare_special_tokens(
|
| 348 |
+
self,
|
| 349 |
+
generation_config: DreamGenerationConfig,
|
| 350 |
+
device: Optional[Union[torch.device, str]] = None,
|
| 351 |
+
):
|
| 352 |
+
"""
|
| 353 |
+
Prepares the special tokens for generation, overwriting the generation config with their processed versions
|
| 354 |
+
converted to tensor.
|
| 355 |
+
|
| 356 |
+
Note that `generation_config` is changed in place and stops being serializable after this method is called.
|
| 357 |
+
That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
|
| 358 |
+
function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
|
| 359 |
+
"""
|
| 360 |
+
|
| 361 |
+
# Convert special tokens to tensors
|
| 362 |
+
def _tensor_or_none(token, device=None):
|
| 363 |
+
if token is None:
|
| 364 |
+
return token
|
| 365 |
+
|
| 366 |
+
device = device if device is not None else self.device
|
| 367 |
+
if isinstance(token, torch.Tensor):
|
| 368 |
+
return token.to(device)
|
| 369 |
+
return torch.tensor(token, device=device, dtype=torch.long)
|
| 370 |
+
|
| 371 |
+
bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)
|
| 372 |
+
eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)
|
| 373 |
+
pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)
|
| 374 |
+
mask_token_tensor = _tensor_or_none(generation_config.mask_token_id, device=device)
|
| 375 |
+
|
| 376 |
+
# We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
|
| 377 |
+
if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
|
| 378 |
+
eos_token_tensor = eos_token_tensor.unsqueeze(0)
|
| 379 |
+
|
| 380 |
+
# Set pad token if unset (and there are conditions to do so)
|
| 381 |
+
if pad_token_tensor is None and eos_token_tensor is not None:
|
| 382 |
+
pad_token_tensor = eos_token_tensor[0]
|
| 383 |
+
logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")
|
| 384 |
+
|
| 385 |
+
# Update generation config with the updated special tokens tensors
|
| 386 |
+
# NOTE: this must be written into a different attribute name than the one holding the original special tokens
|
| 387 |
+
# (in their non-tensor form), in order to enable end-to-end compilation. See
|
| 388 |
+
# https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
|
| 389 |
+
generation_config._bos_token_tensor = bos_token_tensor
|
| 390 |
+
generation_config._eos_token_tensor = eos_token_tensor
|
| 391 |
+
generation_config._pad_token_tensor = pad_token_tensor
|
| 392 |
+
generation_config._mask_token_tensor = mask_token_tensor
|
| 393 |
+
|
| 394 |
+
@torch.no_grad()
|
| 395 |
+
def diffusion_generate(
|
| 396 |
+
self,
|
| 397 |
+
inputs: Optional[torch.Tensor] = None,
|
| 398 |
+
generation_config: Optional[DreamGenerationConfig] = None,
|
| 399 |
+
inputs_embeds=None,
|
| 400 |
+
prefix_lm=False,
|
| 401 |
+
**kwargs,
|
| 402 |
+
) -> Union[DreamModelOutput, torch.LongTensor]:
|
| 403 |
+
# 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
|
| 404 |
+
generation_config = self._prepare_generation_config(generation_config, **kwargs)
|
| 405 |
+
generation_tokens_hook_func = kwargs.pop("generation_tokens_hook_func", lambda step, x, logits: x)
|
| 406 |
+
generation_logits_hook_func = kwargs.pop("generation_logits_hook_func", lambda step, x, logits: logits)
|
| 407 |
+
# breakpoint()
|
| 408 |
+
# 2. Define model inputs
|
| 409 |
+
# import pdb;pdb.set_trace()
|
| 410 |
+
if inputs is not None:
|
| 411 |
+
input_ids = inputs
|
| 412 |
+
device = input_ids.device
|
| 413 |
+
input_ids_length = input_ids.shape[-1]
|
| 414 |
+
else:
|
| 415 |
+
input_ids = None
|
| 416 |
+
device = inputs_embeds.device
|
| 417 |
+
input_ids_length = inputs_embeds.shape[1]
|
| 418 |
+
attention_mask = kwargs.pop("attention_mask", None)
|
| 419 |
+
self._prepare_special_tokens(generation_config, device=device)
|
| 420 |
+
|
| 421 |
+
# 3. Prepare `max_length`.
|
| 422 |
+
|
| 423 |
+
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
|
| 424 |
+
generation_config = self._prepare_generated_length(
|
| 425 |
+
generation_config=generation_config,
|
| 426 |
+
has_default_max_length=has_default_max_length,
|
| 427 |
+
input_ids_length=input_ids_length,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
|
| 431 |
+
# import pdb;pdb.set_trace()
|
| 432 |
+
# 4. Check input_ids
|
| 433 |
+
#if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type:
|
| 434 |
+
if not is_torchdynamo_compiling() and self.device.type != device.type:
|
| 435 |
+
warnings.warn(
|
| 436 |
+
"You are calling .generate() with the `input_ids` being on a device type different"
|
| 437 |
+
f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
|
| 438 |
+
f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
|
| 439 |
+
" Please make sure that you have put `input_ids` to the"
|
| 440 |
+
f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
|
| 441 |
+
" running `.generate()`.",
|
| 442 |
+
UserWarning,
|
| 443 |
+
|
| 444 |
+
)
|
| 445 |
+
# breakpoint()
|
| 446 |
+
if (
|
| 447 |
+
hasattr(generation_config, "pad_token_id") and
|
| 448 |
+
input_ids is not None and
|
| 449 |
+
torch.any(input_ids == generation_config.pad_token_id) and
|
| 450 |
+
attention_mask is None
|
| 451 |
+
):
|
| 452 |
+
warnings.warn(
|
| 453 |
+
"Padding was detected but no attention mask is passed here. For correct "
|
| 454 |
+
"generation results, please set `attention_mask` when batch-padding inputs.",
|
| 455 |
+
UserWarning,
|
| 456 |
+
)
|
| 457 |
+
assert generation_config.num_return_sequences == 1, "Currently, we only support num_return_sequences = 1 for diffusion generation."
|
| 458 |
+
# import pdb;pdb.set_trace()
|
| 459 |
+
input_ids, attention_mask = self._expand_inputs_for_generation(
|
| 460 |
+
expand_size=generation_config.num_return_sequences,
|
| 461 |
+
input_ids=input_ids,
|
| 462 |
+
attention_mask=attention_mask
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
result = self._sample(
|
| 466 |
+
input_ids,
|
| 467 |
+
attention_mask=attention_mask,
|
| 468 |
+
generation_config=generation_config,
|
| 469 |
+
generation_tokens_hook_func=generation_tokens_hook_func,
|
| 470 |
+
generation_logits_hook_func=generation_logits_hook_func,
|
| 471 |
+
inputs_embeds=inputs_embeds,
|
| 472 |
+
device=device,
|
| 473 |
+
prefix_lm=prefix_lm,
|
| 474 |
+
**kwargs,
|
| 475 |
+
)
|
| 476 |
+
return result
|
| 477 |
+
def _sample(
|
| 478 |
+
self,
|
| 479 |
+
input_ids: torch.LongTensor,
|
| 480 |
+
attention_mask: Optional[torch.LongTensor],
|
| 481 |
+
generation_config: DreamGenerationConfig,
|
| 482 |
+
generation_tokens_hook_func,
|
| 483 |
+
generation_logits_hook_func,
|
| 484 |
+
inputs_embeds=None,
|
| 485 |
+
prefix_lm=False,
|
| 486 |
+
device=None,
|
| 487 |
+
schedule_kwargs=None,
|
| 488 |
+
schedule=None,
|
| 489 |
+
step_ratio=None,
|
| 490 |
+
**kwargs,
|
| 491 |
+
) -> Union[DreamModelOutput, torch.LongTensor]:
|
| 492 |
+
# 1. 从 generation_config 中提取常用参数
|
| 493 |
+
output_history = generation_config.output_history # 是否保存每一步的中间结果
|
| 494 |
+
# output_history = True
|
| 495 |
+
return_dict_in_generate = generation_config.return_dict_in_generate # 生成时是否返回字典形式
|
| 496 |
+
max_length = generation_config.max_length # 生成后序列的最大长度(包括前缀)
|
| 497 |
+
mask_token_id = generation_config.mask_token_id # [MASK] 的 token ID
|
| 498 |
+
max_new_tokens = generation_config.max_new_tokens # 最多新增的 token 数量
|
| 499 |
+
steps = min(generation_config.steps, max_new_tokens) # 实际去噪步数,不能超过最大新增 token 数
|
| 500 |
+
eps = generation_config.eps # 噪声下限,用于时刻表
|
| 501 |
+
alg = generation_config.alg # 选择的去噪算法('origin'/ 'maskgit_plus'/ 'topk_margin'/ 'entropy')
|
| 502 |
+
alg_temp = generation_config.alg_temp # 针对某些算法(margin/entropy)调整置信度的温度参数
|
| 503 |
+
temperature = generation_config.temperature # 采样时的温度
|
| 504 |
+
top_p = generation_config.top_p # top-p 截断采样参数
|
| 505 |
+
top_k = generation_config.top_k # top-k 截断采样参数
|
| 506 |
+
|
| 507 |
+
# histories 用于保存每一步的 x,如果需要返回历史则初始化为列表,否则为 None
|
| 508 |
+
histories = [] if (return_dict_in_generate and output_history) else None
|
| 509 |
+
|
| 510 |
+
# 2. 如果没有传入 input_ids,而是直接传了 inputs_embeds,就根据 inputs_embeds 构造一个 placeholder 的 input_ids
|
| 511 |
+
if input_ids is None:
|
| 512 |
+
assert device is not None
|
| 513 |
+
assert inputs_embeds is not None
|
| 514 |
+
bsz, seq_len = inputs_embeds.shape[:2] # batch size 和前缀长度
|
| 515 |
+
max_length = seq_len + max_new_tokens # 重新计算 max_length
|
| 516 |
+
# 创建一个全 0 的张量作为占位,后续会把 embedding 覆盖回去
|
| 517 |
+
input_ids = torch.full((bsz, seq_len), 0, dtype=torch.long).to(device)
|
| 518 |
+
|
| 519 |
+
# tok_idx 和 past_key_values 暂时留空,后面 prefix_lm 分支会用到
|
| 520 |
+
tok_idx = None
|
| 521 |
+
past_key_values = None
|
| 522 |
+
|
| 523 |
+
# 3. 把 input_ids pad 到 max_length,后面补 [MASK]
|
| 524 |
+
# F.pad 的 (0, L) 表示在右侧 pad 长度为 (max_length - seq_len),值为 mask_token_id
|
| 525 |
+
# import pdb;pdb.set_trace()
|
| 526 |
+
x = F.pad(input_ids, (0, max_length - input_ids.shape[1]), value=mask_token_id) # 生成初始的 […, MASK, MASK, …]
|
| 527 |
+
|
| 528 |
+
# 4. 如果启用 prefix_lm 模式,先用 inputs_embeds 做一次常规模型前缀推理,得到 past_key_values 和首个 token
|
| 529 |
+
if prefix_lm:
|
| 530 |
+
dtype = inputs_embeds.dtype
|
| 531 |
+
# 先做一次前缀推理,use_cache=True 以获取 past_key_values
|
| 532 |
+
prefill = self.forward_dream(
|
| 533 |
+
None, attention_mask, tok_idx,
|
| 534 |
+
inputs_embeds=inputs_embeds.to(dtype),
|
| 535 |
+
use_cache=True
|
| 536 |
+
)
|
| 537 |
+
past_key_values = prefill.past_key_values
|
| 538 |
+
# 把前缀阶段模型最后一步的预测 token 取出,作为去噪的第一个位置
|
| 539 |
+
first_token = prefill.logits[:, -1:].argmax(dim=-1) # 形状为 [B, 1]
|
| 540 |
+
# 只保留 mask 区域(原 x 的 right half)
|
| 541 |
+
x = x[:, input_ids.shape[1]:] # 形状 [B, max_new_tokens]
|
| 542 |
+
# 把 mask 区域第一位填为 first_token
|
| 543 |
+
x[:, :1] = first_token
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
#. prefill['logits'].shape. torch.Size([1, 1063, 151667]) 即输入是这个
|
| 547 |
+
|
| 548 |
+
# 5. 当前不支持带 attention_mask 的情形,断言确保 attention_mask 一定为 None
|
| 549 |
+
assert attention_mask is None
|
| 550 |
+
|
| 551 |
+
# 6. 构造去噪时刻表 timesteps,线性从 1 -> eps,共 (steps + 1) 个值
|
| 552 |
+
# timesteps[i] 对应上一步噪声权重,timesteps[i+1] 对应本步噪声权重
|
| 553 |
+
timesteps = torch.linspace(1, eps, steps + 1, device=x.device)
|
| 554 |
+
# import pdb;pdb.set_trace()
|
| 555 |
+
# 7. 给用户一个机会在第 0 步“初始 x”阶段插入自定义逻辑
|
| 556 |
+
x = generation_tokens_hook_func(None, x, None)
|
| 557 |
+
|
| 558 |
+
# 8. 如果用户指定 step_ratio,就根据比例重计算步数
|
| 559 |
+
if step_ratio is not None:
|
| 560 |
+
steps = int(max_new_tokens * step_ratio)
|
| 561 |
+
|
| 562 |
+
# 9. 计算每一步要去噪多少个 mask(如果传了 schedule,就用自定义调度)
|
| 563 |
+
if schedule is None:
|
| 564 |
+
sch = None
|
| 565 |
+
else:
|
| 566 |
+
# get_num_transfer_tokens_sch 返回形状 [B, steps] 的矩阵
|
| 567 |
+
sch = get_num_transfer_tokens_sch((x == mask_token_id), steps, schedule, schedule_kwargs)
|
| 568 |
+
|
| 569 |
+
# 10. 进入去噪主循环
|
| 570 |
+
for i in range(steps):
|
| 571 |
+
# 10.1 找出当前仍是 [MASK] 的位置,mask_index 为布尔矩阵 [B, current_length]
|
| 572 |
+
mask_index = (x == mask_token_id)
|
| 573 |
+
|
| 574 |
+
# 10.2 先把 x 转成 embedding,得到形状 [B, current_length, D]
|
| 575 |
+
inputs_embeds_curr = self.model.embed_tokens(x)
|
| 576 |
+
|
| 577 |
+
# 10.3 如果非 prefix_lm,且外部传入了 inputs_embeds,则把前缀部分覆盖回去
|
| 578 |
+
if not prefix_lm:
|
| 579 |
+
if inputs_embeds is not None:
|
| 580 |
+
inputs_embeds_curr[:, :inputs_embeds.shape[1]] = inputs_embeds
|
| 581 |
+
|
| 582 |
+
# 用当前 embedding 做一次前向,得到 logits,形状 [B, current_length, V]
|
| 583 |
+
logits = self.forward_dream(None, attention_mask, tok_idx, inputs_embeds=inputs_embeds_curr).logits
|
| 584 |
+
# 把 logits 拼接成对齐当前预测:logits[:,1:] 对齐到 x[:, :-1]
|
| 585 |
+
logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1)
|
| 586 |
+
else:
|
| 587 |
+
# prefix_lm 模式,用 past_key_values 加速推理
|
| 588 |
+
logits = self.forward_dream(
|
| 589 |
+
None, attention_mask, tok_idx,
|
| 590 |
+
inputs_embeds=inputs_embeds_curr,
|
| 591 |
+
past_key_values=past_key_values
|
| 592 |
+
).logits
|
| 593 |
+
logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1)
|
| 594 |
+
|
| 595 |
+
# 10.4 用户自定义 logits 钩子,可以修改 logits 分布
|
| 596 |
+
# import pdb;pdb.set_trace()
|
| 597 |
+
logits = generation_logits_hook_func(i, x, logits)
|
| 598 |
+
|
| 599 |
+
# 10.5 取出当前所有 [MASK] 位置对应的 logits,形状 [num_mask, V]
|
| 600 |
+
mask_logits = logits[mask_index]
|
| 601 |
+
|
| 602 |
+
# 10.6 从 timesteps 中取出噪声权重 t, s
|
| 603 |
+
t = timesteps[i]
|
| 604 |
+
s = timesteps[i + 1]
|
| 605 |
+
|
| 606 |
+
# 10.7 根据不同算法决定本轮去噪逻辑
|
| 607 |
+
if alg == 'origin':
|
| 608 |
+
# 基础扩散算法:按概率 p_transfer 随机把一部分 mask 位置替换成 token
|
| 609 |
+
p_transfer = 1 - s / t if i < steps - 1 else 1 # 最后一轮保证把所有剩余 mask 都去掉
|
| 610 |
+
# x0 临时占位,全填 mask
|
| 611 |
+
x0 = torch.zeros_like(x[mask_index], device=self.device, dtype=torch.long) + mask_token_id
|
| 612 |
+
# 随机采样哪些位置在本轮去噪:如果 torch.rand < p_transfer 就先去噪
|
| 613 |
+
transfer_index_t_s = torch.rand(*x0.shape, device=self.device) < p_transfer
|
| 614 |
+
# 对这些选中的位置,从 mask_logits 中采样真实 token
|
| 615 |
+
_, x0[transfer_index_t_s] = sample_tokens(
|
| 616 |
+
mask_logits[transfer_index_t_s],
|
| 617 |
+
temperature=temperature,
|
| 618 |
+
top_p=top_p,
|
| 619 |
+
top_k=top_k
|
| 620 |
+
)
|
| 621 |
+
# 更新 x:只替换 mask_index 位置
|
| 622 |
+
x[mask_index] = x0.clone()
|
| 623 |
+
else:
|
| 624 |
+
# MaskGIT+ / Top-K Margin / Entropy 算法
|
| 625 |
+
if alg == 'maskgit_plus':
|
| 626 |
+
# 返回 confidence(置信度)和 x0(最可能的 token ID)
|
| 627 |
+
confidence, x0 = sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k)
|
| 628 |
+
elif alg == 'topk_margin':
|
| 629 |
+
confidence, x0 = sample_tokens(
|
| 630 |
+
mask_logits,
|
| 631 |
+
temperature=temperature,
|
| 632 |
+
top_p=top_p,
|
| 633 |
+
top_k=top_k,
|
| 634 |
+
margin_confidence=True
|
| 635 |
+
)
|
| 636 |
+
elif alg == 'entropy':
|
| 637 |
+
confidence, x0 = sample_tokens(
|
| 638 |
+
mask_logits,
|
| 639 |
+
temperature,
|
| 640 |
+
top_p=top_p,
|
| 641 |
+
top_k=top_k,
|
| 642 |
+
neg_entropy=True
|
| 643 |
+
)
|
| 644 |
+
else:
|
| 645 |
+
raise RuntimeError(f"Unknown alg: {alg}")
|
| 646 |
+
|
| 647 |
+
# 当前还有多少 mask 位置
|
| 648 |
+
num_mask_token = mask_index.sum()
|
| 649 |
+
# 根据 schedule(或默认比例)决定本轮要去噪多少个
|
| 650 |
+
|
| 651 |
+
if sch is not None:
|
| 652 |
+
number_transfer_tokens = sch[0, i]
|
| 653 |
+
else:
|
| 654 |
+
number_transfer_tokens = int(num_mask_token * (1 - s / t)) if i < steps - 1 else num_mask_token
|
| 655 |
+
|
| 656 |
+
if number_transfer_tokens > 0:
|
| 657 |
+
if alg_temp is None or alg_temp == 0:
|
| 658 |
+
# 直接选置信度最高的 number_transfer_tokens 个位置
|
| 659 |
+
_, transfer_index = torch.topk(confidence, number_transfer_tokens)
|
| 660 |
+
else:
|
| 661 |
+
# 用温度调节 confidence,再按多项式采样 number_transfer_tokens 个
|
| 662 |
+
confidence = confidence / alg_temp
|
| 663 |
+
confidence = F.softmax(confidence, dim=-1)
|
| 664 |
+
transfer_index = torch.multinomial(confidence, num_samples=number_transfer_tokens)
|
| 665 |
+
|
| 666 |
+
# x0_ 临时占位,全填 mask
|
| 667 |
+
x0_ = torch.zeros_like(x0, device=self.device, dtype=torch.long) + mask_token_id
|
| 668 |
+
# 在选中的位置填入从 x0 (argmax token) 中取得的 token
|
| 669 |
+
x0_[transfer_index] = x0[transfer_index].clone()
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
# 更新 x:只替换 mask_index 位置
|
| 674 |
+
x[mask_index] = x0_
|
| 675 |
+
|
| 676 |
+
#如果出现的token有 151643(eos) ,那么他后面的所有都换成 151643,不需要再次mask
|
| 677 |
+
SPECIAL_TOKEN_ID = 151643
|
| 678 |
+
if (x == SPECIAL_TOKEN_ID).any():
|
| 679 |
+
# 对每个 batch 处理
|
| 680 |
+
for b in range(x.shape[0]):
|
| 681 |
+
row = x[b]
|
| 682 |
+
# 找到第一个出现 SPECIAL_TOKEN_ID 的位置
|
| 683 |
+
idx = (row == SPECIAL_TOKEN_ID).nonzero(as_tuple=True)[0]
|
| 684 |
+
if len(idx) > 0:
|
| 685 |
+
first_idx = idx[0].item()
|
| 686 |
+
# 该位置及其后面全部赋值为 SPECIAL_TOKEN_ID
|
| 687 |
+
row[first_idx:] = SPECIAL_TOKEN_ID
|
| 688 |
+
x[b] = row
|
| 689 |
+
|
| 690 |
+
# 10.8 用户自定义 token 钩子:对本轮更新后的 x 做额外处理
|
| 691 |
+
x = generation_tokens_hook_func(i, x, logits)
|
| 692 |
+
|
| 693 |
+
# 10.9 如果需要保存历史,就把当前 x clone 一份放进去
|
| 694 |
+
if histories is not None:
|
| 695 |
+
histories.append(x.clone())
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
# ForkedPdb().set_trace()
|
| 699 |
+
# 11. 循环结束后,根据 return_dict_in_generate 决定返回形式
|
| 700 |
+
if return_dict_in_generate:
|
| 701 |
+
return DreamModelOutput(
|
| 702 |
+
sequences=x, # 最终生成的完整 token 序列 [B, max_length]
|
| 703 |
+
history=histories, # 如果启用,会包含每一���的 x
|
| 704 |
+
)
|
| 705 |
+
else:
|
| 706 |
+
return x # 只返回最终序列 [B, max_length]
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model-00001-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8b35dfdb5e496fd487d09b57b993bfd42726f8883d8b248c72a9c3e4aa623089
|
| 3 |
+
size 4992396112
|
model-00002-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:87ad192520ebda1eb404f566dea689c95d2e3aa52ea7d1bef508419f2a829e18
|
| 3 |
+
size 4991481280
|
model-00003-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cf26b729c709cfe7d4937b9f8361c079708e8a1bfe8ffa71e85e34e814382b49
|
| 3 |
+
size 4828352366
|
model-00004-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c1110575f31d68d39ddd890f3935971a2c76d8add5e112b2aad9098d34090d43
|
| 3 |
+
size 1263460480
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_dream.py
ADDED
|
@@ -0,0 +1,1781 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Dream team, HKUNLP Group and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT and Qwen implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT and Qwen used by the Meta AI and Qwen team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""PyTorch Dream model."""
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
from .modeling_sensevoice import AudioEncoder
|
| 25 |
+
from .resampler_projector import ResamplerProjector
|
| 26 |
+
import random
|
| 27 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# import torch._dynamo
|
| 31 |
+
# torch._dynamo.config.suppress_errors = True
|
| 32 |
+
import sys
|
| 33 |
+
import pdb
|
| 34 |
+
class ForkedPdb(pdb.Pdb):
|
| 35 |
+
"""
|
| 36 |
+
PDB Subclass for debugging multi-processed code
|
| 37 |
+
Suggested in: https://stackoverflow.com/questions/4716533/how-to-attach-debugger-to-a-python-subproccess
|
| 38 |
+
"""
|
| 39 |
+
def interaction(self, *args, **kwargs):
|
| 40 |
+
_stdin = sys.stdin
|
| 41 |
+
try:
|
| 42 |
+
sys.stdin = open('/dev/stdin')
|
| 43 |
+
pdb.Pdb.interaction(self, *args, **kwargs)
|
| 44 |
+
finally:
|
| 45 |
+
sys.stdin = _stdin
|
| 46 |
+
|
| 47 |
+
import math
|
| 48 |
+
from typing import List, Optional, Tuple, Union
|
| 49 |
+
import os
|
| 50 |
+
import torch
|
| 51 |
+
import torch.utils.checkpoint
|
| 52 |
+
from torch import nn
|
| 53 |
+
|
| 54 |
+
from transformers.activations import ACT2FN
|
| 55 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 56 |
+
from transformers.modeling_outputs import (
|
| 57 |
+
# BaseModelOutput,
|
| 58 |
+
MaskedLMOutput,
|
| 59 |
+
ModelOutput
|
| 60 |
+
)
|
| 61 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 62 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 63 |
+
from transformers.utils import (
|
| 64 |
+
add_start_docstrings,
|
| 65 |
+
add_start_docstrings_to_model_forward,
|
| 66 |
+
is_flash_attn_2_available,
|
| 67 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 68 |
+
logging,
|
| 69 |
+
)
|
| 70 |
+
from transformers import PretrainedConfig
|
| 71 |
+
from .configuration_dream import DreamConfig
|
| 72 |
+
from .generation_utils import DreamGenerationMixin, DreamGenerationConfig
|
| 73 |
+
from dataclasses import dataclass
|
| 74 |
+
from typing import Any
|
| 75 |
+
if is_flash_attn_2_available():
|
| 76 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
| 77 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 78 |
+
|
| 79 |
+
from .modeling_sensevoice import AudioEncoder
|
| 80 |
+
from .resampler_projector import ResamplerProjector
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
logger = logging.get_logger(__name__)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# def forward_process(bsz, seq_len, device, first_non_neg_idx_list, last_non_neg_idx_list, eps=1e-3):
|
| 89 |
+
# b, l = bsz, seq_len # b → batch_size,l → 序列长度
|
| 90 |
+
|
| 91 |
+
# # 初始化掩码输出
|
| 92 |
+
# masked_indices = torch.zeros((b, l), device=device, dtype=torch.bool)
|
| 93 |
+
# p_mask = torch.rand(b, device=device) # shape: [b],生成一个随机数作为掩码比例
|
| 94 |
+
|
| 95 |
+
# # 映射到 (eps, 1) 区间,保证最小值不低于 eps
|
| 96 |
+
# p_mask = (1 - eps) * p_mask + eps # shape: [b]
|
| 97 |
+
# p_mask = p_mask[:, None] # shape: [b, 1],方便广播
|
| 98 |
+
|
| 99 |
+
# # 针对每个样本的有效部分生成掩码
|
| 100 |
+
# for i in range(b):
|
| 101 |
+
# first_non_neg_idx = first_non_neg_idx_list[i]
|
| 102 |
+
# last_non_neg_idx = last_non_neg_idx_list[i]
|
| 103 |
+
|
| 104 |
+
# # 如果无有效区间,跳过
|
| 105 |
+
# if first_non_neg_idx is None or last_non_neg_idx is None:
|
| 106 |
+
# continue
|
| 107 |
+
|
| 108 |
+
# valid_length = last_non_neg_idx - first_non_neg_idx + 1
|
| 109 |
+
# if valid_length <= 0:
|
| 110 |
+
# continue
|
| 111 |
+
|
| 112 |
+
# # 生成当前样本的掩码概率阈值
|
| 113 |
+
# t = torch.rand(valid_length, device=device) # shape: [valid_length]
|
| 114 |
+
# mask_threshold = (1 - eps) * t + eps # 计算该样本的掩码概率
|
| 115 |
+
|
| 116 |
+
# # 计算该样本掩码的上限
|
| 117 |
+
# mask_cutoff = torch.max(mask_threshold, torch.min(torch.rand(valid_length, device=device))) # shape: [valid_length]
|
| 118 |
+
|
| 119 |
+
# # 在有效部分生成掩码
|
| 120 |
+
# masked_indices[i, first_non_neg_idx:last_non_neg_idx+1] = torch.rand(valid_length, device=device) <= mask_cutoff
|
| 121 |
+
|
| 122 |
+
# return masked_indices, p_mask
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def forward_process(
|
| 126 |
+
bsz: int,
|
| 127 |
+
seq_len: int,
|
| 128 |
+
device: torch.device,
|
| 129 |
+
labels: torch.Tensor, # [b, l] 的标签 tensor
|
| 130 |
+
eps: float = 1e-3,
|
| 131 |
+
special_token_id: int = 151643, # 要“优待”的 token id
|
| 132 |
+
special_mask_ratio: float = 0.1 # special token 只按原阈值的 10% 掩
|
| 133 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 134 |
+
"""
|
| 135 |
+
生成掩码,并打印统计:
|
| 136 |
+
- 总共被掩的 token 数
|
| 137 |
+
- special_token_id 被掩的数量
|
| 138 |
+
|
| 139 |
+
参数:
|
| 140 |
+
- bsz: batch size
|
| 141 |
+
- seq_len: 序列长度
|
| 142 |
+
- device: torch 设备
|
| 143 |
+
- labels: [b, l] 的标签 tensor(-100 表示无效位置)
|
| 144 |
+
- eps: 阈值下限
|
| 145 |
+
- special_token_id: 要降低掩码率的特殊 token id
|
| 146 |
+
- special_mask_ratio: special token 的掩码率缩放因子
|
| 147 |
+
返回:
|
| 148 |
+
- masked_indices: [b, l] 的 bool 掩码矩阵
|
| 149 |
+
- p_mask: [b, 1] 每个样本的整体掩码比例
|
| 150 |
+
"""
|
| 151 |
+
b, l = bsz, seq_len
|
| 152 |
+
# 初始化掩码矩阵 & 每个样本的整体掩码比例
|
| 153 |
+
masked_indices = torch.zeros((b, l), device=device, dtype=torch.bool)
|
| 154 |
+
p_mask = torch.rand(b, device=device)
|
| 155 |
+
p_mask = (1 - eps) * p_mask + eps
|
| 156 |
+
p_mask = p_mask.unsqueeze(1) # [b,1]
|
| 157 |
+
|
| 158 |
+
# 先为每条序列计算第一个和最后一个非 -100 的位置
|
| 159 |
+
first_idxs = []
|
| 160 |
+
last_idxs = []
|
| 161 |
+
for i in range(b):
|
| 162 |
+
nonneg = (labels[i] != -100).nonzero(as_tuple=True)[0]
|
| 163 |
+
if nonneg.numel() == 0:
|
| 164 |
+
first_idxs.append(None)
|
| 165 |
+
last_idxs.append(None)
|
| 166 |
+
else:
|
| 167 |
+
first_idxs.append(int(nonneg[0]))
|
| 168 |
+
last_idxs.append(int(nonneg[-1]))
|
| 169 |
+
|
| 170 |
+
# 针对每条序列的有效区间生成掩码
|
| 171 |
+
for i in range(b):
|
| 172 |
+
start = first_idxs[i]
|
| 173 |
+
end = last_idxs[i]
|
| 174 |
+
if start is None or end is None or end < start:
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
valid_len = end - start + 1
|
| 178 |
+
# 为每个位置生成基础阈值
|
| 179 |
+
t = torch.rand(valid_len, device=device)
|
| 180 |
+
mask_threshold = (1 - eps) * t + eps # [valid_len]
|
| 181 |
+
|
| 182 |
+
# 生成随机判定值
|
| 183 |
+
rand_vals = torch.rand(valid_len, device=device)
|
| 184 |
+
# 普通 token 的掩码决定
|
| 185 |
+
normal_mask = rand_vals <= mask_threshold
|
| 186 |
+
# special token 的掩码阈值更低
|
| 187 |
+
special_thresh = mask_threshold * special_mask_ratio
|
| 188 |
+
special_mask = rand_vals <= special_thresh
|
| 189 |
+
|
| 190 |
+
labels_slice = labels[i, start : end + 1]
|
| 191 |
+
# 最终掩码:特殊 token 用 special_mask,其他用 normal_mask
|
| 192 |
+
final_mask = torch.where(
|
| 193 |
+
labels_slice == special_token_id,
|
| 194 |
+
special_mask,
|
| 195 |
+
normal_mask
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
masked_indices[i, start : end + 1] = final_mask
|
| 199 |
+
|
| 200 |
+
# 打印统计信息
|
| 201 |
+
total_masked = int(masked_indices.sum().item())
|
| 202 |
+
special_masked = int((masked_indices & (labels == special_token_id)).sum().item())
|
| 203 |
+
# print(f"Total masked tokens: {total_masked}")
|
| 204 |
+
# print(f"Special token_id={special_token_id} masked count: {special_masked}")
|
| 205 |
+
|
| 206 |
+
return masked_indices, p_mask
|
| 207 |
+
|
| 208 |
+
# def forward_process(bsz, seq_len, device, eps=1e-3):
|
| 209 |
+
# b, l = bsz, seq_len # b → batch_size,l → 序列长度
|
| 210 |
+
|
| 211 |
+
# # 1) 为 batch 中的每个样本生成一个 0~1 的随机数 t
|
| 212 |
+
# t = torch.rand(b, device=device)
|
| 213 |
+
|
| 214 |
+
# # 2) 把 t 映射到 (eps, 1) 区间,保证最小值不低于 eps
|
| 215 |
+
# # p_mask 相当于给每个样本定一个「掩码概率阈值」
|
| 216 |
+
# p_mask = (1 - eps) * t + eps # shape: [b]
|
| 217 |
+
|
| 218 |
+
# # 3) 扩展出维度 [b, 1],方便后续广播
|
| 219 |
+
# p_mask = p_mask[:, None] # shape: [b, 1]
|
| 220 |
+
|
| 221 |
+
# # 4) 针对 batch 中的每个 token 再生成一次随机数
|
| 222 |
+
# masked_indices = torch.rand((b, l), device=device) # shape: [b, l]
|
| 223 |
+
|
| 224 |
+
# # 5) 计算当前样本要用的“掩码上限”:
|
| 225 |
+
# # - masked_indices.min(-1).values → 每个样本里随机矩阵的最小值(保证至少有一个 token 会被掩掉)
|
| 226 |
+
# # - torch.max(p_mask, 该最小值) → 二者取大,得到最终 cutoff
|
| 227 |
+
# mask_cutoff = torch.max(p_mask,
|
| 228 |
+
# masked_indices.min(-1, keepdim=True).values) # shape: [b, 1]
|
| 229 |
+
|
| 230 |
+
# # 6) 生成最终布尔掩码:随机值 ≤ cutoff 的 token 被置 True
|
| 231 |
+
# masked_indices = masked_indices <= mask_cutoff # shape: [b, l],dtype=bool
|
| 232 |
+
|
| 233 |
+
# # 7) (可选)把 True 位置替换成 [MASK] token(示例注释里用 126336 表示)
|
| 234 |
+
# # noisy_batch = torch.where(masked_indices, 126336, input_ids)
|
| 235 |
+
|
| 236 |
+
# # 返回:
|
| 237 |
+
# # masked_indices → [b, l] 的布尔矩阵,告诉你哪些 token 需要被掩码
|
| 238 |
+
# # p_mask → [b, 1] 的阈值,记录每条样本的“目标掩码比例”
|
| 239 |
+
# return masked_indices, p_mask
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def generate_attention_mask(labels):
|
| 245 |
+
batch_size, seq_len = labels.shape
|
| 246 |
+
attention_mask = torch.zeros(batch_size, seq_len, seq_len, device=labels.device)
|
| 247 |
+
|
| 248 |
+
# 用于存储每个 batch 的 first_non_neg_idx 和 last_non_neg_idx
|
| 249 |
+
first_non_neg_idx_list = []
|
| 250 |
+
last_non_neg_idx_list = []
|
| 251 |
+
|
| 252 |
+
for i in range(batch_size):
|
| 253 |
+
label = labels[i]
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
# assert label.dtype in [torch.int64, torch.int32], f"label dtype is {label.dtype}"
|
| 258 |
+
# assert not torch.isnan(label.float()).any(), "label has NaN"
|
| 259 |
+
# assert not torch.isinf(label.float()).any(), "label has inf"
|
| 260 |
+
|
| 261 |
+
try:
|
| 262 |
+
non_neg_idx = (label != -100).nonzero(as_tuple=True)[0]
|
| 263 |
+
except Exception as e:
|
| 264 |
+
label_cpu = label.detach().cpu() # 先搬到 CPU
|
| 265 |
+
print("label (unique) =", label_cpu.unique(), "shape =", label_cpu.shape)
|
| 266 |
+
print('label.device:', label.device)
|
| 267 |
+
print('label.shape:', label.shape)
|
| 268 |
+
# 先拷到 CPU 再打印
|
| 269 |
+
try:
|
| 270 |
+
print('label (cpu):', label.cpu())
|
| 271 |
+
except Exception as e2:
|
| 272 |
+
print('label.cpu() 也出错:', e2)
|
| 273 |
+
print('Exception:', e)
|
| 274 |
+
# continue
|
| 275 |
+
# continue # 跳过这个样本
|
| 276 |
+
|
| 277 |
+
# assert label.dtype in [torch.int64, torch.int32], f"label dtype is {label.dtype}"
|
| 278 |
+
# assert not torch.isnan(label).any(), "label has NaN"
|
| 279 |
+
# assert not torch.isinf(label).any(), "label has inf"
|
| 280 |
+
# try:
|
| 281 |
+
# non_neg_idx = (label != -100).nonzero(as_tuple=True)[0]
|
| 282 |
+
# except:
|
| 283 |
+
# print('label is :',label)
|
| 284 |
+
if non_neg_idx.numel() == 0:
|
| 285 |
+
# 全是-100,无法分区,给默认值或raise
|
| 286 |
+
first_non_neg_idx = None
|
| 287 |
+
last_non_neg_idx = None
|
| 288 |
+
# 你可以选择跳过或全0/全1
|
| 289 |
+
# attention_mask[i] = 0 # 或者1
|
| 290 |
+
else:
|
| 291 |
+
first_non_neg_idx = non_neg_idx[0].item()
|
| 292 |
+
last_non_neg_idx = non_neg_idx[-1].item()
|
| 293 |
+
|
| 294 |
+
# 第一部分只能看到自己
|
| 295 |
+
attention_mask[i, :first_non_neg_idx, :first_non_neg_idx] = 1
|
| 296 |
+
|
| 297 |
+
# 第二部分能看到第一部分和自己
|
| 298 |
+
attention_mask[i, first_non_neg_idx:last_non_neg_idx + 1, :first_non_neg_idx] = 1
|
| 299 |
+
attention_mask[i, first_non_neg_idx:last_non_neg_idx + 1, first_non_neg_idx:last_non_neg_idx + 1] = 1
|
| 300 |
+
|
| 301 |
+
# 第三部分能看到所有部分
|
| 302 |
+
attention_mask[i, last_non_neg_idx + 1:, :] = 1
|
| 303 |
+
|
| 304 |
+
first_non_neg_idx_list.append(first_non_neg_idx)
|
| 305 |
+
last_non_neg_idx_list.append(last_non_neg_idx)
|
| 306 |
+
|
| 307 |
+
return attention_mask, first_non_neg_idx_list, last_non_neg_idx_list
|
| 308 |
+
|
| 309 |
+
def update_labels(input_ids, labels, eos_id, max_n=20):
|
| 310 |
+
batch_size, seq_len = input_ids.shape
|
| 311 |
+
first_occurrence_indices = []
|
| 312 |
+
|
| 313 |
+
# 记录每个 batch 中 eos_id 首次出现的位置
|
| 314 |
+
for idx in range(batch_size):
|
| 315 |
+
eos_positions = (input_ids[idx] == eos_id).nonzero(as_tuple=True)[0]
|
| 316 |
+
if len(eos_positions) > 0:
|
| 317 |
+
first_occurrence_indices.append(eos_positions[0].item())
|
| 318 |
+
else:
|
| 319 |
+
first_occurrence_indices.append(-1) # 如果没有 eos_id,则记录为 -1
|
| 320 |
+
|
| 321 |
+
# 从 first_idx 开始,按顺序选择 n 个位置来更新
|
| 322 |
+
for i in range(batch_size):
|
| 323 |
+
first_idx = first_occurrence_indices[i]
|
| 324 |
+
if first_idx == -1:
|
| 325 |
+
continue # 跳过没有 eos 的样本
|
| 326 |
+
# 确保不会超过序列长度
|
| 327 |
+
max_possible = seq_len - first_idx
|
| 328 |
+
# 如果 max_possible==0,说明 eos 刚好在最后一个位置,也跳过
|
| 329 |
+
if max_possible <= 0:
|
| 330 |
+
continue
|
| 331 |
+
num_to_select = random.randint(1, min(max_n, max_possible))
|
| 332 |
+
|
| 333 |
+
selected_indices = torch.arange(first_idx, first_idx + num_to_select)
|
| 334 |
+
|
| 335 |
+
# 将这些位置的 labels 更新为 eos_id
|
| 336 |
+
labels[i, selected_indices] = eos_id
|
| 337 |
+
|
| 338 |
+
return labels
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
import torch
|
| 342 |
+
import random
|
| 343 |
+
|
| 344 |
+
def update_labels_and_inputs(input_ids, labels, eos_id, max_n=20, pad_token_id=0, pad_label_id=-100):
|
| 345 |
+
batch_size, seq_len = input_ids.shape
|
| 346 |
+
input_ids = input_ids.clone()
|
| 347 |
+
labels = labels.clone()
|
| 348 |
+
new_input_ids = []
|
| 349 |
+
new_labels = []
|
| 350 |
+
|
| 351 |
+
for idx in range(batch_size):
|
| 352 |
+
eos_positions = (input_ids[idx] == eos_id).nonzero(as_tuple=True)[0]
|
| 353 |
+
if len(eos_positions) > 0:
|
| 354 |
+
first_idx = eos_positions[0].item()
|
| 355 |
+
cur_input_ids = input_ids[idx]
|
| 356 |
+
cur_labels = labels[idx]
|
| 357 |
+
else:
|
| 358 |
+
# 扩展 max_n 个 eos_id
|
| 359 |
+
random_max_n = random.randint(1, max_n)
|
| 360 |
+
eos_ids = torch.full((random_max_n,), eos_id, device=input_ids.device, dtype=input_ids.dtype)
|
| 361 |
+
cur_input_ids = torch.cat([input_ids[idx], eos_ids])
|
| 362 |
+
# labels 扩展 max_n 个 pad_label_id
|
| 363 |
+
pad_labels = torch.full((random_max_n,), eos_id, device=labels.device, dtype=labels.dtype)
|
| 364 |
+
cur_labels = torch.cat([labels[idx], pad_labels])
|
| 365 |
+
# first_idx = len(cur_input_ids) - random_max_n
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
new_input_ids.append(cur_input_ids)
|
| 369 |
+
new_labels.append(cur_labels)
|
| 370 |
+
|
| 371 |
+
# pad到同一长度
|
| 372 |
+
max_len = max(len(x) for x in new_input_ids)
|
| 373 |
+
padded_input_ids = torch.stack([
|
| 374 |
+
torch.cat([x, torch.full((max_len - len(x),), pad_token_id, device=x.device, dtype=x.dtype)])
|
| 375 |
+
for x in new_input_ids
|
| 376 |
+
])
|
| 377 |
+
padded_labels = torch.stack([
|
| 378 |
+
torch.cat([x, torch.full((max_len - len(x),), pad_label_id, device=x.device, dtype=x.dtype)])
|
| 379 |
+
for x in new_labels
|
| 380 |
+
])
|
| 381 |
+
|
| 382 |
+
return padded_input_ids, padded_labels
|
| 383 |
+
|
| 384 |
+
@dataclass
|
| 385 |
+
class MaskedLMOutput(ModelOutput):
|
| 386 |
+
"""
|
| 387 |
+
Base class for masked language models outputs.
|
| 388 |
+
|
| 389 |
+
Args:
|
| 390 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 391 |
+
Masked language modeling (MLM) loss.
|
| 392 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 393 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 394 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 395 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 396 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 397 |
+
|
| 398 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 399 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 400 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 401 |
+
sequence_length)`.
|
| 402 |
+
|
| 403 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 404 |
+
heads.
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
loss: Optional[torch.FloatTensor] = None
|
| 408 |
+
# loss_tqa: Optional[torch.FloatTensor] = None
|
| 409 |
+
# loss_sqa: Optional[torch.FloatTensor] = None
|
| 410 |
+
# loss_asr: Optional[torch.FloatTensor] = None
|
| 411 |
+
# loss_tts: Optional[torch.FloatTensor] = None
|
| 412 |
+
# loss_vqa: Optional[torch.FloatTensor] = None
|
| 413 |
+
# loss_svqa: Optional[torch.FloatTensor] = None
|
| 414 |
+
# loss_t2i: Optional[torch.FloatTensor] = None
|
| 415 |
+
# loss_s2i: Optional[torch.FloatTensor] = None
|
| 416 |
+
logits: torch.FloatTensor = None
|
| 417 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 418 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 419 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
|
| 420 |
+
|
| 421 |
+
_CHECKPOINT_FOR_DOC = "Dream-7B"
|
| 422 |
+
_CONFIG_FOR_DOC = "DreamConfig"
|
| 423 |
+
import os
|
| 424 |
+
ENFORCE_NUM_ITEMIN_BATCH = os.environ.get("ENFORCE_NUM_ITEMIN_BATCH", False)
|
| 425 |
+
|
| 426 |
+
@dataclass
|
| 427 |
+
class BaseModelOutput(ModelOutput):
|
| 428 |
+
"""
|
| 429 |
+
Base class for model's outputs, with potential hidden states and attentions.
|
| 430 |
+
|
| 431 |
+
Args:
|
| 432 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 433 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 434 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 435 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 436 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 437 |
+
|
| 438 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 439 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 440 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 441 |
+
sequence_length)`.
|
| 442 |
+
|
| 443 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 444 |
+
heads.
|
| 445 |
+
"""
|
| 446 |
+
|
| 447 |
+
last_hidden_state: torch.FloatTensor = None
|
| 448 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 449 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 450 |
+
past_key_values: Optional[Cache] = None
|
| 451 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Dream
|
| 452 |
+
class DreamRMSNorm(nn.Module):
|
| 453 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 454 |
+
"""
|
| 455 |
+
DreamRMSNorm is equivalent to T5LayerNorm
|
| 456 |
+
"""
|
| 457 |
+
super().__init__()
|
| 458 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 459 |
+
self.variance_epsilon = eps
|
| 460 |
+
|
| 461 |
+
def forward(self, hidden_states):
|
| 462 |
+
input_dtype = hidden_states.dtype
|
| 463 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 464 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 465 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 466 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 467 |
+
|
| 468 |
+
def extra_repr(self):
|
| 469 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Dream
|
| 473 |
+
class DreamRotaryEmbedding(nn.Module):
|
| 474 |
+
def __init__(
|
| 475 |
+
self,
|
| 476 |
+
dim=None,
|
| 477 |
+
max_position_embeddings=2048,
|
| 478 |
+
base=10000,
|
| 479 |
+
device=None,
|
| 480 |
+
scaling_factor=1.0,
|
| 481 |
+
rope_type="default",
|
| 482 |
+
config: Optional[DreamConfig] = None,
|
| 483 |
+
):
|
| 484 |
+
super().__init__()
|
| 485 |
+
# TODO (joao): remove the `if` below, only used for BC
|
| 486 |
+
self.rope_kwargs = {}
|
| 487 |
+
if config is None:
|
| 488 |
+
logger.warning_once(
|
| 489 |
+
"`DreamRotaryEmbedding` can now be fully parameterized by passing the model config through the "
|
| 490 |
+
"`config` argument. All other arguments will be removed in v4.46"
|
| 491 |
+
)
|
| 492 |
+
self.rope_kwargs = {
|
| 493 |
+
"rope_type": rope_type,
|
| 494 |
+
"factor": scaling_factor,
|
| 495 |
+
"dim": dim,
|
| 496 |
+
"base": base,
|
| 497 |
+
"max_position_embeddings": max_position_embeddings,
|
| 498 |
+
}
|
| 499 |
+
self.rope_type = rope_type
|
| 500 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 501 |
+
self.original_max_seq_len = max_position_embeddings
|
| 502 |
+
else:
|
| 503 |
+
# BC: "rope_type" was originally "type"
|
| 504 |
+
if config.rope_scaling is not None:
|
| 505 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 506 |
+
else:
|
| 507 |
+
self.rope_type = "default"
|
| 508 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 509 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 510 |
+
|
| 511 |
+
self.config = config
|
| 512 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 513 |
+
|
| 514 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
|
| 515 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 516 |
+
self.original_inv_freq = self.inv_freq
|
| 517 |
+
|
| 518 |
+
def reset_parameters(self):
|
| 519 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, self.inv_freq.device, **self.rope_kwargs)
|
| 520 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 521 |
+
self.original_inv_freq = self.inv_freq
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
| 525 |
+
"""
|
| 526 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
| 527 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
| 528 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
| 529 |
+
"""
|
| 530 |
+
seq_len = torch.max(position_ids) + 1
|
| 531 |
+
if seq_len > self.max_seq_len_cached: # growth
|
| 532 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(
|
| 533 |
+
self.config, device, seq_len=seq_len, **self.rope_kwargs
|
| 534 |
+
)
|
| 535 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
| 536 |
+
self.max_seq_len_cached = seq_len
|
| 537 |
+
|
| 538 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
| 539 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 540 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
| 541 |
+
|
| 542 |
+
@torch.no_grad()
|
| 543 |
+
def forward(self, x, position_ids):
|
| 544 |
+
if "dynamic" in self.rope_type:
|
| 545 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 546 |
+
|
| 547 |
+
# Core RoPE block
|
| 548 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 549 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 550 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
| 551 |
+
device_type = x.device.type
|
| 552 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 553 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 554 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 555 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 556 |
+
cos = emb.cos()
|
| 557 |
+
sin = emb.sin()
|
| 558 |
+
|
| 559 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
| 560 |
+
cos = cos * self.attention_scaling
|
| 561 |
+
sin = sin * self.attention_scaling
|
| 562 |
+
|
| 563 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
| 567 |
+
def rotate_half(x):
|
| 568 |
+
"""Rotates half the hidden dims of the input."""
|
| 569 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 570 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 571 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
| 575 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 576 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 577 |
+
|
| 578 |
+
Args:
|
| 579 |
+
q (`torch.Tensor`): The query tensor.
|
| 580 |
+
k (`torch.Tensor`): The key tensor.
|
| 581 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 582 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 583 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 584 |
+
Deprecated and unused.
|
| 585 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 586 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 587 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 588 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 589 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 590 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 591 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 592 |
+
Returns:
|
| 593 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 594 |
+
"""
|
| 595 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 596 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 597 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 598 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 599 |
+
return q_embed, k_embed
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Dream
|
| 603 |
+
class DreamMLP(nn.Module):
|
| 604 |
+
def __init__(self, config):
|
| 605 |
+
super().__init__()
|
| 606 |
+
self.hidden_size = config.hidden_size
|
| 607 |
+
self.intermediate_size = config.intermediate_size
|
| 608 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 609 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 610 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 611 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 612 |
+
|
| 613 |
+
def forward(self, hidden_state):
|
| 614 |
+
return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
| 618 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 619 |
+
"""
|
| 620 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 621 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 622 |
+
"""
|
| 623 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 624 |
+
if n_rep == 1:
|
| 625 |
+
return hidden_states
|
| 626 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 627 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class DreamAttention(nn.Module):
|
| 631 |
+
"""
|
| 632 |
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
| 633 |
+
and "Generating Long Sequences with Sparse Transformers".
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
def __init__(self, config: DreamConfig, layer_idx: Optional[int] = None):
|
| 637 |
+
super().__init__()
|
| 638 |
+
self.config = config
|
| 639 |
+
self.layer_idx = layer_idx
|
| 640 |
+
if layer_idx is None:
|
| 641 |
+
logger.warning_once(
|
| 642 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
| 643 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 644 |
+
"when creating this class."
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
self.hidden_size = config.hidden_size
|
| 648 |
+
self.num_heads = config.num_attention_heads
|
| 649 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 650 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 651 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 652 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 653 |
+
self.rope_theta = config.rope_theta
|
| 654 |
+
self.is_causal = False
|
| 655 |
+
self.attention_dropout = config.attention_dropout
|
| 656 |
+
|
| 657 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 658 |
+
raise ValueError(
|
| 659 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 660 |
+
f" and `num_heads`: {self.num_heads})."
|
| 661 |
+
)
|
| 662 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
| 663 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
| 664 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
| 665 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 666 |
+
|
| 667 |
+
self.rotary_emb = DreamRotaryEmbedding(config=self.config)
|
| 668 |
+
|
| 669 |
+
def forward(
|
| 670 |
+
self,
|
| 671 |
+
hidden_states: torch.Tensor,
|
| 672 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 673 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 674 |
+
past_key_value: Optional[Cache] = None,
|
| 675 |
+
output_attentions: bool = False,
|
| 676 |
+
use_cache: bool = False,
|
| 677 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 678 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 679 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 680 |
+
bsz, q_len, _ = hidden_states.size()
|
| 681 |
+
|
| 682 |
+
query_states = self.q_proj(hidden_states)
|
| 683 |
+
key_states = self.k_proj(hidden_states)
|
| 684 |
+
value_states = self.v_proj(hidden_states)
|
| 685 |
+
|
| 686 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 687 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 688 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 689 |
+
|
| 690 |
+
if position_embeddings is None:
|
| 691 |
+
logger.warning_once(
|
| 692 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 693 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 694 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 695 |
+
"removed and `position_embeddings` will be mandatory."
|
| 696 |
+
)
|
| 697 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 698 |
+
else:
|
| 699 |
+
cos, sin = position_embeddings
|
| 700 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 701 |
+
|
| 702 |
+
if past_key_value is not None:
|
| 703 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
| 704 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 705 |
+
|
| 706 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
| 707 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 708 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 709 |
+
|
| 710 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 711 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 712 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 713 |
+
attn_weights = attn_weights + causal_mask
|
| 714 |
+
|
| 715 |
+
# upcast attention to fp32
|
| 716 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 717 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 718 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 719 |
+
|
| 720 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 721 |
+
raise ValueError(
|
| 722 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 723 |
+
f" {attn_output.size()}"
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 727 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 728 |
+
|
| 729 |
+
attn_output = self.o_proj(attn_output)
|
| 730 |
+
|
| 731 |
+
if not output_attentions:
|
| 732 |
+
attn_weights = None
|
| 733 |
+
|
| 734 |
+
return attn_output, attn_weights, past_key_value
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
class DreamSdpaAttention(DreamAttention):
|
| 738 |
+
"""
|
| 739 |
+
Dream attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 740 |
+
`DreamAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 741 |
+
SDPA API.
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
# Adapted from DreamAttention.forward
|
| 745 |
+
def forward(
|
| 746 |
+
self,
|
| 747 |
+
hidden_states: torch.Tensor,
|
| 748 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 749 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 750 |
+
past_key_value: Optional[Cache] = None,
|
| 751 |
+
output_attentions: bool = False,
|
| 752 |
+
use_cache: bool = False,
|
| 753 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 754 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 755 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 756 |
+
if output_attentions:
|
| 757 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 758 |
+
logger.warning_once(
|
| 759 |
+
"DreamModel is using DreamSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 760 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 761 |
+
)
|
| 762 |
+
return super().forward(
|
| 763 |
+
hidden_states=hidden_states,
|
| 764 |
+
attention_mask=attention_mask,
|
| 765 |
+
position_ids=position_ids,
|
| 766 |
+
past_key_value=past_key_value,
|
| 767 |
+
output_attentions=output_attentions,
|
| 768 |
+
use_cache=use_cache,
|
| 769 |
+
)
|
| 770 |
+
# breakpoint()
|
| 771 |
+
# ForkedPdb().set_trace()
|
| 772 |
+
bsz, q_len, _ = hidden_states.size()
|
| 773 |
+
|
| 774 |
+
query_states = self.q_proj(hidden_states)
|
| 775 |
+
key_states = self.k_proj(hidden_states)
|
| 776 |
+
value_states = self.v_proj(hidden_states)
|
| 777 |
+
|
| 778 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 779 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 780 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 781 |
+
|
| 782 |
+
if position_embeddings is None:
|
| 783 |
+
logger.warning_once(
|
| 784 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 785 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 786 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 787 |
+
"removed and `position_embeddings` will be mandatory."
|
| 788 |
+
)
|
| 789 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 790 |
+
else:
|
| 791 |
+
cos, sin = position_embeddings
|
| 792 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 793 |
+
|
| 794 |
+
if past_key_value is not None:
|
| 795 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
| 796 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 797 |
+
|
| 798 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 799 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 800 |
+
|
| 801 |
+
# causal_mask = attention_mask
|
| 802 |
+
# if attention_mask is not None: # no matter the length, we just slice it
|
| 803 |
+
# causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 804 |
+
|
| 805 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 806 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 807 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
| 808 |
+
query_states = query_states.contiguous()
|
| 809 |
+
key_states = key_states.contiguous()
|
| 810 |
+
value_states = value_states.contiguous()
|
| 811 |
+
|
| 812 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 813 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 814 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
| 815 |
+
# is_causal = True if causal_mask is None and q_len > 1 else False
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
bool_mask = attention_mask.to(torch.bool)
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
#原始的
|
| 822 |
+
# ForkedPdb().set_trace()
|
| 823 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 824 |
+
query_states,
|
| 825 |
+
key_states,
|
| 826 |
+
value_states,
|
| 827 |
+
attn_mask=bool_mask ,
|
| 828 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 829 |
+
is_causal=False, # hard coded
|
| 830 |
+
)
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 837 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
| 838 |
+
|
| 839 |
+
attn_output = self.o_proj(attn_output)
|
| 840 |
+
|
| 841 |
+
return attn_output, None, past_key_value
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
#换成flash attn
|
| 845 |
+
# attention_interface = ALL_ATTENTION_FUNCTIONS["flash_attention_2"]
|
| 846 |
+
# # ForkedPdb().set_trace()
|
| 847 |
+
# attn_output, attn_weights = attention_interface(
|
| 848 |
+
# self,
|
| 849 |
+
# query_states,
|
| 850 |
+
# key_states,
|
| 851 |
+
# value_states,
|
| 852 |
+
# attention_mask,
|
| 853 |
+
# dropout=0.0 if not self.training else self.attention_dropout,
|
| 854 |
+
# scaling=self.head_dim**-0.5,
|
| 855 |
+
# sliding_window=None,
|
| 856 |
+
# position_ids=position_ids,
|
| 857 |
+
# output_attentions= output_attentions,
|
| 858 |
+
# use_cache = use_cache
|
| 859 |
+
# # 其他参数
|
| 860 |
+
# )
|
| 861 |
+
|
| 862 |
+
# # attn_output = attn_output.transpose(1, 2).contiguous()
|
| 863 |
+
# attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
| 864 |
+
# attn_output = self.o_proj(attn_output)
|
| 865 |
+
|
| 866 |
+
# return attn_output, attn_weights, past_key_value
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
class DreamDecoderLayer(nn.Module):
|
| 874 |
+
def __init__(self, config: DreamConfig, layer_idx: int):
|
| 875 |
+
super().__init__()
|
| 876 |
+
self.hidden_size = config.hidden_size
|
| 877 |
+
|
| 878 |
+
if config.sliding_window and config._attn_implementation != "flash_attention_2":
|
| 879 |
+
logger.warning_once(
|
| 880 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
| 881 |
+
"unexpected results may be encountered."
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
# self.self_attn = Dream_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
| 885 |
+
self.self_attn = DreamSdpaAttention(config, layer_idx)
|
| 886 |
+
|
| 887 |
+
self.mlp = DreamMLP(config)
|
| 888 |
+
self.input_layernorm = DreamRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 889 |
+
self.post_attention_layernorm = DreamRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 890 |
+
|
| 891 |
+
# @torch.compile
|
| 892 |
+
def forward(
|
| 893 |
+
self,
|
| 894 |
+
hidden_states: torch.Tensor,
|
| 895 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 896 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 897 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 898 |
+
output_attentions: Optional[bool] = False,
|
| 899 |
+
use_cache: Optional[bool] = False,
|
| 900 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 901 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 902 |
+
**kwargs,
|
| 903 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 904 |
+
"""
|
| 905 |
+
Args:
|
| 906 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 907 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 908 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
| 909 |
+
output_attentions (`bool`, *optional*):
|
| 910 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 911 |
+
returned tensors for more detail.
|
| 912 |
+
use_cache (`bool`, *optional*):
|
| 913 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 914 |
+
(see `past_key_values`).
|
| 915 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 916 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 917 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 918 |
+
position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
| 919 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
| 920 |
+
with `head_dim` being the embedding dimension of each attention head.
|
| 921 |
+
kwargs (`dict`, *optional*):
|
| 922 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 923 |
+
into the model
|
| 924 |
+
"""
|
| 925 |
+
residual = hidden_states
|
| 926 |
+
|
| 927 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 928 |
+
|
| 929 |
+
# Self Attention
|
| 930 |
+
# ForkedPdb().set_trace()
|
| 931 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 932 |
+
hidden_states=hidden_states,
|
| 933 |
+
attention_mask=attention_mask,
|
| 934 |
+
position_ids=position_ids,
|
| 935 |
+
past_key_value=past_key_value,
|
| 936 |
+
output_attentions=output_attentions,
|
| 937 |
+
use_cache=use_cache,
|
| 938 |
+
cache_position=cache_position,
|
| 939 |
+
position_embeddings=position_embeddings,
|
| 940 |
+
)
|
| 941 |
+
hidden_states = residual + hidden_states
|
| 942 |
+
|
| 943 |
+
# Fully Connected
|
| 944 |
+
residual = hidden_states
|
| 945 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 946 |
+
hidden_states = self.mlp(hidden_states)
|
| 947 |
+
hidden_states = residual + hidden_states
|
| 948 |
+
|
| 949 |
+
outputs = (hidden_states,)
|
| 950 |
+
|
| 951 |
+
if output_attentions:
|
| 952 |
+
outputs += (self_attn_weights,)
|
| 953 |
+
|
| 954 |
+
if use_cache:
|
| 955 |
+
outputs += (present_key_value,)
|
| 956 |
+
|
| 957 |
+
return outputs
|
| 958 |
+
|
| 959 |
+
class DreamPreTrainedModel(PreTrainedModel):
|
| 960 |
+
config_class = DreamConfig
|
| 961 |
+
base_model_prefix = "model"
|
| 962 |
+
supports_gradient_checkpointing = True
|
| 963 |
+
_no_split_modules = ["DreamDecoderLayer"]
|
| 964 |
+
_skip_keys_device_placement = "past_key_values"
|
| 965 |
+
_supports_flash_attn_2 = True
|
| 966 |
+
_supports_sdpa = True
|
| 967 |
+
_supports_cache_class = True
|
| 968 |
+
_supports_quantized_cache = True
|
| 969 |
+
_supports_static_cache = True
|
| 970 |
+
|
| 971 |
+
def _init_weights(self, module):
|
| 972 |
+
std = self.config.initializer_range
|
| 973 |
+
if isinstance(module, nn.Linear):
|
| 974 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 975 |
+
if module.bias is not None:
|
| 976 |
+
module.bias.data.zero_()
|
| 977 |
+
elif isinstance(module, nn.Embedding):
|
| 978 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 979 |
+
if module.padding_idx is not None:
|
| 980 |
+
module.weight.data[module.padding_idx].zero_()
|
| 981 |
+
|
| 982 |
+
@classmethod
|
| 983 |
+
def from_pretrained(
|
| 984 |
+
cls,
|
| 985 |
+
pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
|
| 986 |
+
*model_args,
|
| 987 |
+
config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
|
| 988 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 989 |
+
ignore_mismatched_sizes: bool = False,
|
| 990 |
+
force_download: bool = False,
|
| 991 |
+
local_files_only: bool = False,
|
| 992 |
+
token: Optional[Union[str, bool]] = None,
|
| 993 |
+
revision: str = "main",
|
| 994 |
+
use_safetensors: Optional[bool] = None,
|
| 995 |
+
weights_only: bool = True,
|
| 996 |
+
**kwargs,
|
| 997 |
+
):
|
| 998 |
+
_model,_ = super().from_pretrained(
|
| 999 |
+
pretrained_model_name_or_path,
|
| 1000 |
+
*model_args,
|
| 1001 |
+
config=config,
|
| 1002 |
+
cache_dir=cache_dir,
|
| 1003 |
+
ignore_mismatched_sizes=ignore_mismatched_sizes,
|
| 1004 |
+
force_download=force_download,
|
| 1005 |
+
local_files_only=local_files_only,
|
| 1006 |
+
token=token,
|
| 1007 |
+
revision=revision,
|
| 1008 |
+
use_safetensors=use_safetensors,
|
| 1009 |
+
weights_only=weights_only,
|
| 1010 |
+
**kwargs,
|
| 1011 |
+
)
|
| 1012 |
+
# _model[0].generation_config
|
| 1013 |
+
# ForkedPdb().set_trace()
|
| 1014 |
+
# NOTE(Lin): we need to override the generation config
|
| 1015 |
+
# because the generation config loaded in `from_pretrained`
|
| 1016 |
+
# does not include all the attributes of DreamGenerationConfig
|
| 1017 |
+
resume_download = kwargs.get("resume_download", None)
|
| 1018 |
+
proxies = kwargs.get("proxies", None)
|
| 1019 |
+
subfolder = kwargs.get("subfolder", "")
|
| 1020 |
+
from_auto_class = kwargs.get("_from_auto", False)
|
| 1021 |
+
from_pipeline = kwargs.get("_from_pipeline", None)
|
| 1022 |
+
_model.generation_config= DreamGenerationConfig.from_pretrained(
|
| 1023 |
+
pretrained_model_name_or_path,
|
| 1024 |
+
cache_dir=cache_dir,
|
| 1025 |
+
force_download=force_download,
|
| 1026 |
+
resume_download=resume_download,
|
| 1027 |
+
proxies=proxies,
|
| 1028 |
+
local_files_only=local_files_only,
|
| 1029 |
+
token=token,
|
| 1030 |
+
revision=revision,
|
| 1031 |
+
subfolder=subfolder,
|
| 1032 |
+
_from_auto=from_auto_class,
|
| 1033 |
+
_from_pipeline=from_pipeline,
|
| 1034 |
+
)
|
| 1035 |
+
return _model,_
|
| 1036 |
+
|
| 1037 |
+
class DreamPrefixLMCache(Cache):
|
| 1038 |
+
|
| 1039 |
+
def __init__(self):
|
| 1040 |
+
super().__init__()
|
| 1041 |
+
self.past_key_values = {}
|
| 1042 |
+
# this will not be updated beyond the prefilling phase
|
| 1043 |
+
|
| 1044 |
+
def update(
|
| 1045 |
+
self,
|
| 1046 |
+
key_states: torch.Tensor,
|
| 1047 |
+
value_states: torch.Tensor,
|
| 1048 |
+
layer_idx: int,
|
| 1049 |
+
cache_kwargs = None,
|
| 1050 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 1051 |
+
if layer_idx in self.past_key_values:
|
| 1052 |
+
past_key, past_value = self.past_key_values[layer_idx]
|
| 1053 |
+
key_states = torch.cat((past_key, key_states), dim=-2)
|
| 1054 |
+
value_states = torch.cat((past_value, value_states), dim=-2)
|
| 1055 |
+
return key_states,value_states
|
| 1056 |
+
else:
|
| 1057 |
+
self.past_key_values[layer_idx] = (key_states, value_states)
|
| 1058 |
+
return key_states, value_states
|
| 1059 |
+
|
| 1060 |
+
def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
|
| 1061 |
+
"""Returns the sequence length of the cached states. A layer index can be optionally passed."""
|
| 1062 |
+
# TODO: deprecate this function in favor of `cache_position`
|
| 1063 |
+
if len(self.past_key_values) == 0:
|
| 1064 |
+
return 0
|
| 1065 |
+
else:
|
| 1066 |
+
return self.past_key_values[0][0].shape[-2]
|
| 1067 |
+
|
| 1068 |
+
def get_max_cache_shape(self) -> Optional[int]:
|
| 1069 |
+
return None
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
import deepspeed
|
| 1076 |
+
class DreamBaseModel(DreamPreTrainedModel):#
|
| 1077 |
+
"""
|
| 1078 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DreamDecoderLayer`]
|
| 1079 |
+
|
| 1080 |
+
Args:
|
| 1081 |
+
config: DreamConfig
|
| 1082 |
+
"""
|
| 1083 |
+
|
| 1084 |
+
def __init__(self, config: DreamConfig):
|
| 1085 |
+
super().__init__(config)
|
| 1086 |
+
self.padding_idx = config.pad_token_id
|
| 1087 |
+
self.vocab_size = config.vocab_size
|
| 1088 |
+
|
| 1089 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 1090 |
+
self.layers = nn.ModuleList(
|
| 1091 |
+
[DreamDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 1092 |
+
)
|
| 1093 |
+
self._attn_implementation = config._attn_implementation
|
| 1094 |
+
self.norm = DreamRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 1095 |
+
self.rotary_emb = DreamRotaryEmbedding(config=config)
|
| 1096 |
+
|
| 1097 |
+
self.gradient_checkpointing = False
|
| 1098 |
+
# Initialize weights and apply final processing
|
| 1099 |
+
|
| 1100 |
+
self.audio_model = AudioEncoder()
|
| 1101 |
+
self.audio_projection = ResamplerProjector(512, config.hidden_size)
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
self.post_init()
|
| 1106 |
+
|
| 1107 |
+
def get_input_embeddings(self):
|
| 1108 |
+
return self.embed_tokens
|
| 1109 |
+
|
| 1110 |
+
def set_input_embeddings(self, value):
|
| 1111 |
+
self.embed_tokens = value
|
| 1112 |
+
|
| 1113 |
+
def forward(
|
| 1114 |
+
self,
|
| 1115 |
+
input_ids: torch.LongTensor = None,
|
| 1116 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1117 |
+
audios: Optional[torch.FloatTensor] = None,
|
| 1118 |
+
audio_indices: Optional[torch.LongTensor] = None,
|
| 1119 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1120 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1121 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1122 |
+
use_cache: Optional[bool] = None,
|
| 1123 |
+
output_attentions: Optional[bool] = None,
|
| 1124 |
+
output_hidden_states: Optional[bool] = None,
|
| 1125 |
+
return_dict: Optional[bool] = None,
|
| 1126 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1127 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 1128 |
+
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
# ForkedPdb().set_trace()
|
| 1132 |
+
if (past_key_values is None or len(past_key_values) == 0) and audios is not None:
|
| 1133 |
+
audio_embeds, audio_lengths = self.audio_model(audios)
|
| 1134 |
+
# if torch.distributed.get_rank() == 0:
|
| 1135 |
+
# print(f"audio_embeds {audio_embeds.size()}")
|
| 1136 |
+
assert audio_embeds.shape[0] == len(audios)
|
| 1137 |
+
fake_audios = None
|
| 1138 |
+
|
| 1139 |
+
audio_embeds = self.audio_projection(audio_embeds)
|
| 1140 |
+
|
| 1141 |
+
# torch.set_printoptions(threshold=100_000)
|
| 1142 |
+
# if torch.distributed.get_rank() == 0:
|
| 1143 |
+
# print(f"audio_embeds {audio_embeds.size()}")
|
| 1144 |
+
# print(f"audio_embeds {audio_embeds.sum()}")
|
| 1145 |
+
# print(f"audios {[x.size() for x in audios]}")
|
| 1146 |
+
# print(f"audios {[x.sum() for x in audios]}")
|
| 1147 |
+
# print(f"input_ids {input_ids.size()}")
|
| 1148 |
+
# print(f"input_ids {input_ids.sum()}")
|
| 1149 |
+
# # print(f"input_ids {input_ids}")
|
| 1150 |
+
# print(f"audio_indices {[x.size() for x in audio_indices]}")
|
| 1151 |
+
# print(f"audio_indices {[x.sum() for x in audio_indices]}")
|
| 1152 |
+
# # print(f"audio_indices {audio_indices}")
|
| 1153 |
+
|
| 1154 |
+
elif self.training:
|
| 1155 |
+
device = self.get_input_embeddings().weight.data.device
|
| 1156 |
+
dtype = self.get_input_embeddings().weight.data.dtype
|
| 1157 |
+
fake_audios = torch.ones((1, 1, 560), dtype=dtype, device=device)
|
| 1158 |
+
audio_embeds, audio_lengths = self.audio_model(fake_audios)
|
| 1159 |
+
audio_embeds = self.audio_projection(audio_embeds)
|
| 1160 |
+
|
| 1161 |
+
else:
|
| 1162 |
+
fake_audios = None
|
| 1163 |
+
audio_embeds = None
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
|
| 1171 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1172 |
+
output_hidden_states = (
|
| 1173 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1174 |
+
)
|
| 1175 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1176 |
+
|
| 1177 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1178 |
+
|
| 1179 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 1180 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 1181 |
+
|
| 1182 |
+
if self.gradient_checkpointing and self.training:
|
| 1183 |
+
if use_cache:
|
| 1184 |
+
logger.warning_once(
|
| 1185 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 1186 |
+
)
|
| 1187 |
+
use_cache = False
|
| 1188 |
+
|
| 1189 |
+
if inputs_embeds is None:
|
| 1190 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
if fake_audios is not None:
|
| 1195 |
+
inputs_embeds = inputs_embeds + audio_embeds.mean() * 0.0
|
| 1196 |
+
elif audio_embeds is not None:
|
| 1197 |
+
inputs_embeds = inputs_embeds.clone()
|
| 1198 |
+
for audio_embeds_, audio_lengths_, audio_indices_ in zip(audio_embeds, audio_lengths, audio_indices,):
|
| 1199 |
+
# print(f"{audio_embeds_.size()=} {audio_lengths_=} {audio_indices_.size()=}")
|
| 1200 |
+
audio_embeds_ = audio_embeds_[:audio_lengths_, ...]
|
| 1201 |
+
audio_embeds_ = audio_embeds_.to(inputs_embeds.device)
|
| 1202 |
+
indices_b, indices_s = audio_indices_.to(inputs_embeds.device).unbind(dim=0)
|
| 1203 |
+
inputs_embeds[indices_b.view(-1), indices_s.view(-1)] = audio_embeds_.view(-1, audio_embeds_.shape[-1])
|
| 1204 |
+
# inputs_embeds = inputs_embeds + audio_embeds.mean() * 0.0
|
| 1205 |
+
|
| 1206 |
+
|
| 1207 |
+
if use_cache and past_key_values is None:
|
| 1208 |
+
past_key_values = DreamPrefixLMCache()
|
| 1209 |
+
|
| 1210 |
+
if cache_position is None:
|
| 1211 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 1212 |
+
cache_position = torch.arange(
|
| 1213 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 1214 |
+
)
|
| 1215 |
+
|
| 1216 |
+
if position_ids is None:
|
| 1217 |
+
position_ids = cache_position.unsqueeze(0)
|
| 1218 |
+
|
| 1219 |
+
hidden_states = inputs_embeds
|
| 1220 |
+
|
| 1221 |
+
# create position embeddings to be shared across the decoder layers
|
| 1222 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 1223 |
+
|
| 1224 |
+
# decoder layers
|
| 1225 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1226 |
+
all_self_attns = () if output_attentions else None
|
| 1227 |
+
|
| 1228 |
+
for decoder_layer in self.layers:
|
| 1229 |
+
if output_hidden_states:
|
| 1230 |
+
all_hidden_states += (hidden_states,)
|
| 1231 |
+
|
| 1232 |
+
if self.gradient_checkpointing and self.training:
|
| 1233 |
+
layer_outputs = deepspeed.checkpointing.checkpoint(
|
| 1234 |
+
decoder_layer,
|
| 1235 |
+
hidden_states,
|
| 1236 |
+
attention_mask,
|
| 1237 |
+
position_ids,
|
| 1238 |
+
past_key_values,
|
| 1239 |
+
output_attentions,
|
| 1240 |
+
use_cache,
|
| 1241 |
+
cache_position,
|
| 1242 |
+
position_embeddings,
|
| 1243 |
+
)
|
| 1244 |
+
else:
|
| 1245 |
+
layer_outputs = decoder_layer(
|
| 1246 |
+
hidden_states,
|
| 1247 |
+
attention_mask=attention_mask,
|
| 1248 |
+
position_ids=position_ids,
|
| 1249 |
+
past_key_value=past_key_values,
|
| 1250 |
+
output_attentions=output_attentions,
|
| 1251 |
+
use_cache=use_cache,
|
| 1252 |
+
cache_position=cache_position,
|
| 1253 |
+
position_embeddings=position_embeddings,
|
| 1254 |
+
)
|
| 1255 |
+
|
| 1256 |
+
# breakpoint()
|
| 1257 |
+
if isinstance(layer_outputs,torch.Tensor):
|
| 1258 |
+
layer_outputs = (layer_outputs,None)
|
| 1259 |
+
hidden_states = layer_outputs[0]
|
| 1260 |
+
|
| 1261 |
+
if output_attentions:
|
| 1262 |
+
all_self_attns += (layer_outputs[1],)
|
| 1263 |
+
|
| 1264 |
+
hidden_states = self.norm(hidden_states)
|
| 1265 |
+
|
| 1266 |
+
# add hidden states from the last decoder layer
|
| 1267 |
+
if output_hidden_states:
|
| 1268 |
+
all_hidden_states += (hidden_states,)
|
| 1269 |
+
|
| 1270 |
+
if not return_dict:
|
| 1271 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attns] if v is not None)
|
| 1272 |
+
return BaseModelOutput(
|
| 1273 |
+
last_hidden_state=hidden_states,
|
| 1274 |
+
hidden_states=all_hidden_states,
|
| 1275 |
+
attentions=all_self_attns,
|
| 1276 |
+
past_key_values=past_key_values,
|
| 1277 |
+
)
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
class DreamModel(DreamGenerationMixin, DreamPreTrainedModel):
|
| 1281 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1282 |
+
|
| 1283 |
+
def __init__(self, config):
|
| 1284 |
+
super().__init__(config)
|
| 1285 |
+
self.model = DreamBaseModel(config)
|
| 1286 |
+
self.vocab_size = config.vocab_size
|
| 1287 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1288 |
+
|
| 1289 |
+
# Initialize weights and apply final processing
|
| 1290 |
+
self.tokenizer = None
|
| 1291 |
+
self.post_init()
|
| 1292 |
+
|
| 1293 |
+
def reset_rope_parameters(self):
|
| 1294 |
+
self.model.rotary_emb.reset_parameters()
|
| 1295 |
+
for layer in self.model.layers:
|
| 1296 |
+
layer.self_attn.rotary_emb.reset_parameters()
|
| 1297 |
+
|
| 1298 |
+
def get_input_embeddings(self):
|
| 1299 |
+
return self.model.embed_tokens
|
| 1300 |
+
|
| 1301 |
+
def set_input_embeddings(self, value):
|
| 1302 |
+
self.model.embed_tokens = value
|
| 1303 |
+
|
| 1304 |
+
def get_output_embeddings(self):
|
| 1305 |
+
return self.lm_head
|
| 1306 |
+
|
| 1307 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1308 |
+
self.lm_head = new_embeddings
|
| 1309 |
+
|
| 1310 |
+
def set_decoder(self, decoder):
|
| 1311 |
+
self.model = decoder
|
| 1312 |
+
|
| 1313 |
+
def get_decoder(self):
|
| 1314 |
+
return self.model
|
| 1315 |
+
|
| 1316 |
+
def forward(
|
| 1317 |
+
self,
|
| 1318 |
+
input_ids: torch.LongTensor = None,
|
| 1319 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1320 |
+
audios: Optional[torch.FloatTensor] = None,
|
| 1321 |
+
audio_indices: Optional[torch.LongTensor] = None,
|
| 1322 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1323 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1324 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1325 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1326 |
+
use_cache: Optional[bool] = None,
|
| 1327 |
+
output_attentions: Optional[bool] = None,
|
| 1328 |
+
output_hidden_states: Optional[bool] = None,
|
| 1329 |
+
return_dict: Optional[bool] = None,
|
| 1330 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1331 |
+
num_logits_to_keep: int = 0,
|
| 1332 |
+
num_items_in_batch: int = None,
|
| 1333 |
+
**loss_kwargs,
|
| 1334 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
|
| 1338 |
+
# eos_id = 151643 # 自定义 <eos>
|
| 1339 |
+
# mask_id = 151666 # 自定义 <mask>
|
| 1340 |
+
|
| 1341 |
+
# import pdb; pdb.set_trace() # ⚠ 调试断点,如无需要可删
|
| 1342 |
+
|
| 1343 |
+
# raw_inputs_ids = input_ids # 保留原始 ID,后续需要对齐 labels
|
| 1344 |
+
|
| 1345 |
+
|
| 1346 |
+
# ---------------------------------------------------------
|
| 1347 |
+
# 1. 将 <eos> 位置从注意力 & labels 中临时移除(参见 Sec B.1)
|
| 1348 |
+
# ---------------------------------------------------------
|
| 1349 |
+
|
| 1350 |
+
#最终的输出也需要 eos,或者说输入的最后就应该全是eos
|
| 1351 |
+
|
| 1352 |
+
# non_padding = ~(raw_inputs_ids == eos_id)
|
| 1353 |
+
# 强制让 <eos> 位在 attention_mask 中视为 *可被注意*(True)
|
| 1354 |
+
# attention_mask[raw_inputs_ids == eos_id] = True
|
| 1355 |
+
# labels 位置恢复成 eos_id,避免被 -100 忽略
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
|
| 1359 |
+
# 更新labels,让模型能学到eos,但是又不想弄太多eos来影响训练
|
| 1360 |
+
# input_ids, labels = update_labels_and_inputs(input_ids,labels,eos_id,300)
|
| 1361 |
+
|
| 1362 |
+
|
| 1363 |
+
# new_attention_mask, first_non_neg_idx_list, last_non_neg_idx_list = generate_attention_mask(new_lables)
|
| 1364 |
+
# first_non_neg_idx_list里面可能有None
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
|
| 1368 |
+
# ---------------------------------------------------------
|
| 1369 |
+
# 3. 若存在 labels(训练模式),进行 Forward‑Process:
|
| 1370 |
+
# • 采样需要 Mask 的 token 下标 (masked_indices)
|
| 1371 |
+
# • 为每个样本构造互补分支 (masked / inverse masked)
|
| 1372 |
+
# • 拼接两条分支,得到 2×batch 的输入 / labels
|
| 1373 |
+
# ---------------------------------------------------------
|
| 1374 |
+
|
| 1375 |
+
# if labels is not None:
|
| 1376 |
+
# # audio 这一块应该没有这个必要? 不过训练也行吧
|
| 1377 |
+
# labels_mask = ~(labels == -100) # label != -100,assitant 部分
|
| 1378 |
+
# # noise_embeddings = self.get_input_embeddings()(torch.tensor([mask_id]).to(raw_inputs_ids)) # (1, D)
|
| 1379 |
+
# bsz, seq_len = labels_mask.shape
|
| 1380 |
+
# # noise_embeddings = noise_embeddings.view(1, 1, -1) # mask token 的embedding
|
| 1381 |
+
|
| 1382 |
+
|
| 1383 |
+
|
| 1384 |
+
# # 生成masked_indices, p_mask
|
| 1385 |
+
# masked_indices, p_mask = forward_process(
|
| 1386 |
+
# bsz, seq_len, raw_inputs_ids.device, labels
|
| 1387 |
+
# )
|
| 1388 |
+
# # ForkedPdb().set_trace()
|
| 1389 |
+
# # 只mask有效token
|
| 1390 |
+
# final_masked_indices = masked_indices & labels_mask
|
| 1391 |
+
# final_masked_indices_inv = (~masked_indices) & labels_mask
|
| 1392 |
+
|
| 1393 |
+
# # mask_id要和input_ids类型、设备一致
|
| 1394 |
+
# mask_id_tensor = torch.full_like(input_ids, mask_id)
|
| 1395 |
+
# input_ids = torch.where(final_masked_indices, mask_id_tensor, input_ids)
|
| 1396 |
+
|
| 1397 |
+
# # new_labels是labels的clone
|
| 1398 |
+
# new_labels = labels.clone()
|
| 1399 |
+
# new_labels[final_masked_indices_inv] = -100
|
| 1400 |
+
|
| 1401 |
+
|
| 1402 |
+
# final_masked_indices_inv = (~masked_indices) & labels_mask #assistant并且没有被mask部分
|
| 1403 |
+
|
| 1404 |
+
# 使用 torch.where 将目标 token 替换为噪声向量
|
| 1405 |
+
#
|
| 1406 |
+
|
| 1407 |
+
#这里改成把输入换成mask tokne的id就行
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
# inputs_embeds_inv = torch.where(final_masked_indices_inv.view(bsz, seq_len, 1),
|
| 1411 |
+
# noise_embeddings, inputs_embeds) #没被mask部分
|
| 1412 |
+
|
| 1413 |
+
# inputs_embeds = torch.where(final_masked_indices.view(bsz, seq_len, 1),
|
| 1414 |
+
# noise_embeddings, inputs_embeds) #mask部分
|
| 1415 |
+
|
| 1416 |
+
|
| 1417 |
+
# ForkedPdb().set_trace()
|
| 1418 |
+
|
| 1419 |
+
# 构造两份 labels:各自只在对应分支需要预测的位置保留真值,其余填 -100
|
| 1420 |
+
# labels_inv = labels.clone()
|
| 1421 |
+
# labels_inv[~final_masked_indices_inv] = -100
|
| 1422 |
+
# labels[~final_masked_indices] = -100
|
| 1423 |
+
|
| 1424 |
+
# 将两条分支沿 batch 维度拼接:
|
| 1425 |
+
# 文章里面说的是,视觉元素可能出现在没被mask的地方,导致训了没啥用
|
| 1426 |
+
|
| 1427 |
+
# inputs_embeds = torch.cat([inputs_embeds, inputs_embeds_inv])
|
| 1428 |
+
# labels = torch.cat([labels, labels_inv])
|
| 1429 |
+
# final_masked_indices = torch.cat([final_masked_indices, final_masked_indices_inv])
|
| 1430 |
+
|
| 1431 |
+
# Debug: 打印序列长度
|
| 1432 |
+
# seq_len = labels.shape[-1]
|
| 1433 |
+
# print(f"[forward] seq_len={seq_len}")
|
| 1434 |
+
|
| 1435 |
+
# ---------------------------------------------------------
|
| 1436 |
+
# 4. (可选) DPO ‑style 正/反样本前向;此处暂未实现
|
| 1437 |
+
# ---------------------------------------------------------
|
| 1438 |
+
# if dpo_forward:
|
| 1439 |
+
# raise NotImplementedError("DPO forward 尚未实现,请按需补充")
|
| 1440 |
+
# ForkedPdb().set_trace()
|
| 1441 |
+
# ---------------------------------------------------------
|
| 1442 |
+
# 5. 常规前向 — 调用基类实现
|
| 1443 |
+
# ---------------------------------------------------------
|
| 1444 |
+
# attention_mask = None # ⚠ 此处把 mask 置空,让基类自己处理(或依赖 ALiBi)
|
| 1445 |
+
|
| 1446 |
+
#import pdb; pdb.set_trace()
|
| 1447 |
+
#import time
|
| 1448 |
+
#print(f"begin forward - {time.time()} - {input_ids.device}")
|
| 1449 |
+
num_items_in_batch = None
|
| 1450 |
+
if ENFORCE_NUM_ITEMIN_BATCH:
|
| 1451 |
+
num_items_in_batch = labels.ne(-100).sum()
|
| 1452 |
+
num_items_in_batch = torch.distributed.reduce(num_items_in_batch)
|
| 1453 |
+
|
| 1454 |
+
# ForkedPdb().set_trace()
|
| 1455 |
+
|
| 1456 |
+
# lables = new_labels
|
| 1457 |
+
# new_attention_mask = None
|
| 1458 |
+
# attention_mask = new_attention_mask
|
| 1459 |
+
|
| 1460 |
+
is_new = position_ids == 0
|
| 1461 |
+
# is_new[0] = True
|
| 1462 |
+
segment_id = torch.cumsum(is_new.long(), dim=1) - 1
|
| 1463 |
+
new_attention_mask = (segment_id.unsqueeze(1) == segment_id.unsqueeze(2)).long()
|
| 1464 |
+
# ForkedPdb().set_trace()
|
| 1465 |
+
mask = attention_mask.unsqueeze(-1) # [bs, len, 1]
|
| 1466 |
+
new_attention_mask = new_attention_mask * mask # [bs, len, len] * [bs, len, 1],自动broadcast
|
| 1467 |
+
|
| 1468 |
+
if self.config.chunk_size > 0:
|
| 1469 |
+
item_start_id = torch.where(position_ids[0] == 0)[0]
|
| 1470 |
+
im_start_id = torch.where(input_ids[0] == self.tokenizer.encode("<|im_start|>")[0])[0].tolist()
|
| 1471 |
+
chunk_mask = torch.zeros_like(new_attention_mask)
|
| 1472 |
+
|
| 1473 |
+
for item_i in range(len(item_start_id)):
|
| 1474 |
+
im_start = item_start_id[item_i]
|
| 1475 |
+
im_end = item_start_id[item_i + 1] if item_i != len(item_start_id) - 1 else input_ids.shape[-1]
|
| 1476 |
+
|
| 1477 |
+
im_index = im_start_id.index(im_start)
|
| 1478 |
+
chunk_begin = im_start
|
| 1479 |
+
|
| 1480 |
+
while im_index < len(im_start_id) and im_start_id[im_index] < im_end:
|
| 1481 |
+
if self.tokenizer.decode(input_ids[0, im_start_id[im_index]+1]) == "assistant":
|
| 1482 |
+
chunk_id = 1
|
| 1483 |
+
ans_begin = im_start_id[im_index]
|
| 1484 |
+
ans_end = im_start_id[im_index + 1] if im_index != len(im_start_id) - 1 else input_ids.shape[-1]
|
| 1485 |
+
|
| 1486 |
+
while 1:
|
| 1487 |
+
chunk_end = min(ans_begin + chunk_id * self.config.chunk_size, ans_end)
|
| 1488 |
+
chunk_mask[:, chunk_begin: chunk_end, im_start: chunk_end] = 1
|
| 1489 |
+
if chunk_end == ans_end: break
|
| 1490 |
+
chunk_id += 1
|
| 1491 |
+
chunk_begin = chunk_end
|
| 1492 |
+
|
| 1493 |
+
chunk_begin = chunk_end
|
| 1494 |
+
im_index += 1
|
| 1495 |
+
else:
|
| 1496 |
+
im_index += 1; continue
|
| 1497 |
+
|
| 1498 |
+
new_attention_mask = new_attention_mask * chunk_mask
|
| 1499 |
+
# visualization
|
| 1500 |
+
# import matplotlib.pyplot as plt
|
| 1501 |
+
# mask_np = new_attention_mask[0].detach().cpu().numpy()
|
| 1502 |
+
# plt.figure(figsize=(10, 8)); plt.imshow(mask_np); plt.savefig("tmp.png"); plt.close()
|
| 1503 |
+
# if chunk_num != (position_ids == 0).sum(): import pdb; pdb.set_trace()
|
| 1504 |
+
|
| 1505 |
+
|
| 1506 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1507 |
+
output_hidden_states = (
|
| 1508 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1509 |
+
)
|
| 1510 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1511 |
+
# import pdb;pdb.set_trace()
|
| 1512 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1513 |
+
# position_ids = torch.arange(input_ids.size(1), dtype=torch.long).unsqueeze(0)
|
| 1514 |
+
# position_ids = torch.arange(
|
| 1515 |
+
# input_ids.size(1),
|
| 1516 |
+
# dtype=torch.long,
|
| 1517 |
+
# device=input_ids.device
|
| 1518 |
+
# ).unsqueeze(0).expand(input_ids.size(0), -1)
|
| 1519 |
+
|
| 1520 |
+
|
| 1521 |
+
# print(input_ids.shape,labels.shape)
|
| 1522 |
+
#import time
|
| 1523 |
+
#print(f"self.model forward - {time.time()} - {input_ids.device}")
|
| 1524 |
+
outputs = self.model(
|
| 1525 |
+
input_ids=input_ids,
|
| 1526 |
+
attention_mask=new_attention_mask,
|
| 1527 |
+
audios=audios,
|
| 1528 |
+
audio_indices=audio_indices,
|
| 1529 |
+
position_ids=position_ids,
|
| 1530 |
+
past_key_values=past_key_values,
|
| 1531 |
+
inputs_embeds=inputs_embeds,
|
| 1532 |
+
use_cache=use_cache,
|
| 1533 |
+
output_attentions=output_attentions,
|
| 1534 |
+
output_hidden_states=output_hidden_states,
|
| 1535 |
+
return_dict=return_dict,
|
| 1536 |
+
cache_position=cache_position,
|
| 1537 |
+
)
|
| 1538 |
+
hidden_states = outputs[0]
|
| 1539 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1540 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
| 1541 |
+
# import pdb;pdb.set_trace()
|
| 1542 |
+
loss = None
|
| 1543 |
+
if labels is not None:
|
| 1544 |
+
if ENFORCE_NUM_ITEMIN_BATCH:
|
| 1545 |
+
assert num_items_in_batch is not None, "num_items_in_batch must be provided if ENFORCE_NUM_ITEMIN_BATCH is True"
|
| 1546 |
+
# ForkedPdb().set_trace()
|
| 1547 |
+
loss = self.loss_function(logits, labels, self.vocab_size,num_items_in_batch=num_items_in_batch, **loss_kwargs)
|
| 1548 |
+
|
| 1549 |
+
if not return_dict:
|
| 1550 |
+
output = (logits,) + outputs[1:]
|
| 1551 |
+
return (loss,) + output if loss is not None else output
|
| 1552 |
+
# ForkedPdb().set_trace()
|
| 1553 |
+
#import time
|
| 1554 |
+
#print(f"forward finish - {time.time()} - {input_ids.device}")
|
| 1555 |
+
|
| 1556 |
+
# loss_t2i = None
|
| 1557 |
+
# loss_s2i = None
|
| 1558 |
+
# loss_vqa = None
|
| 1559 |
+
# loss_svqa = None
|
| 1560 |
+
# loss_asr = None
|
| 1561 |
+
# loss_tts = None
|
| 1562 |
+
# loss_tqa = None
|
| 1563 |
+
# loss_sqa = None
|
| 1564 |
+
|
| 1565 |
+
# input_text = self.tokenizer.decode(input_ids[0])
|
| 1566 |
+
# t2i_prompt = get_t2i_prompt()
|
| 1567 |
+
# for p in t2i_prompt:
|
| 1568 |
+
# if p in input_text: loss_t2i = loss.detach().copy(); break
|
| 1569 |
+
|
| 1570 |
+
# if "Convert the speech to text." in input_text: loss_asr = loss.detach().copy()
|
| 1571 |
+
# elif "Convert the text to speech." in input_text: loss_tts = loss.detach().copy()
|
| 1572 |
+
# elif "<|image" not in input_text and "<|audio" not in input_text and loss_t2i is None: loss_tqa = loss.detach().copy()
|
| 1573 |
+
# elif "<|image|>" in input_text and loss_t2i is None: in input_text: loss_vqa = loss.detach().copy()
|
| 1574 |
+
# elif "Please response the input audio." in input_text: loss_sqa = loss.detach().copy()
|
| 1575 |
+
# elif "Please generate an image based on the input audio." in input_text: loss_s2i = loss.detach().copy()
|
| 1576 |
+
# elif "Please response the input audio based on the given image." in input_text: loss_svqa = loss.detach().copy()
|
| 1577 |
+
|
| 1578 |
+
return MaskedLMOutput(
|
| 1579 |
+
loss=loss,
|
| 1580 |
+
# loss_asr=loss_asr,
|
| 1581 |
+
# loss_tts=loss_tts,
|
| 1582 |
+
# loss_tqa=loss_tqa,
|
| 1583 |
+
# loss_sqa=loss_sqa,
|
| 1584 |
+
# loss_t2i=loss_t2i,
|
| 1585 |
+
# loss_s2i=loss_s2i,
|
| 1586 |
+
# loss_vqa=loss_vqa,
|
| 1587 |
+
# loss_svqa=loss_svqa,
|
| 1588 |
+
logits=logits,
|
| 1589 |
+
hidden_states=outputs.hidden_states,
|
| 1590 |
+
attentions=outputs.attentions,
|
| 1591 |
+
past_key_values=outputs.past_key_values
|
| 1592 |
+
)
|
| 1593 |
+
|
| 1594 |
+
def forward_dream(
|
| 1595 |
+
self,
|
| 1596 |
+
input_ids: torch.LongTensor = None,
|
| 1597 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1598 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1599 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1600 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1601 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1602 |
+
use_cache: Optional[bool] = None,
|
| 1603 |
+
output_attentions: Optional[bool] = None,
|
| 1604 |
+
output_hidden_states: Optional[bool] = None,
|
| 1605 |
+
return_dict: Optional[bool] = None,
|
| 1606 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1607 |
+
num_logits_to_keep: int = 0,
|
| 1608 |
+
**loss_kwargs,
|
| 1609 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
| 1610 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1611 |
+
output_hidden_states = (
|
| 1612 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1613 |
+
)
|
| 1614 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1615 |
+
attention_mask = None
|
| 1616 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1617 |
+
# import pdb;pdb.set_trace()
|
| 1618 |
+
outputs = self.model(
|
| 1619 |
+
input_ids=input_ids,
|
| 1620 |
+
attention_mask=attention_mask,
|
| 1621 |
+
position_ids=position_ids,
|
| 1622 |
+
past_key_values=past_key_values,
|
| 1623 |
+
inputs_embeds=inputs_embeds,
|
| 1624 |
+
use_cache=use_cache,
|
| 1625 |
+
output_attentions=output_attentions,
|
| 1626 |
+
output_hidden_states=output_hidden_states,
|
| 1627 |
+
return_dict=return_dict,
|
| 1628 |
+
cache_position=cache_position,
|
| 1629 |
+
)
|
| 1630 |
+
|
| 1631 |
+
hidden_states = outputs[0]
|
| 1632 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1633 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
| 1634 |
+
|
| 1635 |
+
loss = None
|
| 1636 |
+
if labels is not None:
|
| 1637 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
|
| 1638 |
+
|
| 1639 |
+
if not return_dict:
|
| 1640 |
+
output = (logits,) + outputs[1:]
|
| 1641 |
+
return (loss,) + output if loss is not None else output
|
| 1642 |
+
|
| 1643 |
+
return MaskedLMOutput(
|
| 1644 |
+
loss=loss,
|
| 1645 |
+
logits=logits,
|
| 1646 |
+
hidden_states=outputs.hidden_states,
|
| 1647 |
+
attentions=outputs.attentions,
|
| 1648 |
+
past_key_values=outputs.past_key_values,
|
| 1649 |
+
)
|
| 1650 |
+
|
| 1651 |
+
@torch.no_grad()
|
| 1652 |
+
def generate(
|
| 1653 |
+
self,
|
| 1654 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1655 |
+
audios: Optional[torch.FloatTensor] = None,
|
| 1656 |
+
audio_indices: Optional[torch.LongTensor] = None,
|
| 1657 |
+
max_new_tokens=512,
|
| 1658 |
+
steps=512,
|
| 1659 |
+
temperature=0.2,
|
| 1660 |
+
top_p=0.95,
|
| 1661 |
+
alg_temp=0.,
|
| 1662 |
+
alg="entropy",
|
| 1663 |
+
output_history=False,
|
| 1664 |
+
**kwargs,
|
| 1665 |
+
):
|
| 1666 |
+
# modalities = kwargs.pop("modalities", None) if "modalities" in kwargs and modalities is None else modalities
|
| 1667 |
+
position_ids = kwargs.pop("position_ids", None)
|
| 1668 |
+
attention_mask = kwargs.pop("attention_mask", None)
|
| 1669 |
+
if "inputs_embeds" in kwargs:
|
| 1670 |
+
raise NotImplementedError("`inputs_embeds` is not supported")
|
| 1671 |
+
# import pdb;pdb.set_trace()
|
| 1672 |
+
|
| 1673 |
+
# if images is not None:
|
| 1674 |
+
# (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
|
| 1675 |
+
# else:
|
| 1676 |
+
# # breakpoint()
|
| 1677 |
+
# inputs_embeds = self.get_model().embed_tokens(inputs)
|
| 1678 |
+
|
| 1679 |
+
#return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
|
| 1680 |
+
#return llada_generate(self.get_model(),inputs_embeds=inputs_embeds,position_ids=position_ids,attention_mask=attention_mask,**kwargs)
|
| 1681 |
+
# breakpoint()
|
| 1682 |
+
|
| 1683 |
+
|
| 1684 |
+
# ForkedPdb().set_trace()
|
| 1685 |
+
if audios is not None:
|
| 1686 |
+
audio_embeds, audio_lengths = self.model.audio_model(audios)
|
| 1687 |
+
# if torch.distributed.get_rank() == 0:
|
| 1688 |
+
# print(f"audio_embeds {audio_embeds.size()}")
|
| 1689 |
+
assert audio_embeds.shape[0] == len(audios)
|
| 1690 |
+
fake_audios = None
|
| 1691 |
+
|
| 1692 |
+
audio_embeds = self.model.audio_projection(audio_embeds)
|
| 1693 |
+
|
| 1694 |
+
# torch.set_printoptions(threshold=100_000)
|
| 1695 |
+
# if torch.distributed.get_rank() == 0:
|
| 1696 |
+
# print(f"audio_embeds {audio_embeds.size()}")
|
| 1697 |
+
# print(f"audio_embeds {audio_embeds.sum()}")
|
| 1698 |
+
# print(f"audios {[x.size() for x in audios]}")
|
| 1699 |
+
# print(f"audios {[x.sum() for x in audios]}")
|
| 1700 |
+
# print(f"input_ids {input_ids.size()}")
|
| 1701 |
+
# print(f"input_ids {input_ids.sum()}")
|
| 1702 |
+
# # print(f"input_ids {input_ids}")
|
| 1703 |
+
# print(f"audio_indices {[x.size() for x in audio_indices]}")
|
| 1704 |
+
# print(f"audio_indices {[x.sum() for x in audio_indices]}")
|
| 1705 |
+
# # print(f"audio_indices {audio_indices}")
|
| 1706 |
+
|
| 1707 |
+
elif self.training:
|
| 1708 |
+
device = self.model.get_input_embeddings().weight.data.device
|
| 1709 |
+
dtype = self.model.get_input_embeddings().weight.data.dtype
|
| 1710 |
+
fake_audios = torch.ones((1, 1, 560), dtype=dtype, device=device)
|
| 1711 |
+
audio_embeds, audio_lengths = self.model.audio_model(fake_audios)
|
| 1712 |
+
audio_embeds = self.model.audio_projection(audio_embeds)
|
| 1713 |
+
|
| 1714 |
+
else:
|
| 1715 |
+
fake_audios = None
|
| 1716 |
+
audio_embeds = None
|
| 1717 |
+
|
| 1718 |
+
|
| 1719 |
+
|
| 1720 |
+
# if inputs_embeds is None:
|
| 1721 |
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
| 1722 |
+
|
| 1723 |
+
|
| 1724 |
+
|
| 1725 |
+
if fake_audios is not None:
|
| 1726 |
+
inputs_embeds = inputs_embeds + audio_embeds.mean() * 0.0
|
| 1727 |
+
elif audio_embeds is not None:
|
| 1728 |
+
inputs_embeds = inputs_embeds.clone()
|
| 1729 |
+
for audio_embeds_, audio_lengths_, audio_indices_ in zip(audio_embeds, audio_lengths, audio_indices,):
|
| 1730 |
+
# print(f"{audio_embeds_.size()=} {audio_lengths_=} {audio_indices_.size()=}")
|
| 1731 |
+
audio_embeds_ = audio_embeds_[:audio_lengths_, ...]
|
| 1732 |
+
audio_embeds_ = audio_embeds_.to(inputs_embeds.device)
|
| 1733 |
+
indices_b, indices_s = audio_indices_.to(inputs_embeds.device).unbind(dim=0)
|
| 1734 |
+
inputs_embeds[indices_b.view(-1), indices_s.view(-1)] = audio_embeds_.view(-1, audio_embeds_.shape[-1])
|
| 1735 |
+
# inputs_embeds = inputs_embeds + audio_embeds.mean() * 0.0
|
| 1736 |
+
|
| 1737 |
+
|
| 1738 |
+
|
| 1739 |
+
|
| 1740 |
+
|
| 1741 |
+
|
| 1742 |
+
|
| 1743 |
+
|
| 1744 |
+
return self.diffusion_generate(
|
| 1745 |
+
None,
|
| 1746 |
+
inputs_embeds=inputs_embeds,
|
| 1747 |
+
max_new_tokens=max_new_tokens,
|
| 1748 |
+
output_history=output_history,
|
| 1749 |
+
return_dict_in_generate=True,
|
| 1750 |
+
steps=steps,
|
| 1751 |
+
temperature=temperature,
|
| 1752 |
+
top_p=top_p,
|
| 1753 |
+
alg=alg,
|
| 1754 |
+
alg_temp=alg_temp,
|
| 1755 |
+
**kwargs
|
| 1756 |
+
)
|
| 1757 |
+
|
| 1758 |
+
|
| 1759 |
+
# class LlavaDreamForMaskedDiffusion(DreamModel,DreamPreTrainedModel):
|
| 1760 |
+
|
| 1761 |
+
# # config_class = LlavaDreamConfig
|
| 1762 |
+
# supports_gradient_checkpointing = True
|
| 1763 |
+
|
| 1764 |
+
# def __init__(self, config: DreamConfig, model: Optional[DreamModel] = None, init_params: bool = False,vision_kwargs=None,**kwargs):
|
| 1765 |
+
# DreamModel.__init__(self, config)
|
| 1766 |
+
|
| 1767 |
+
# # configure default generation settings
|
| 1768 |
+
# config.model_type = "llava_dream"
|
| 1769 |
+
# # config.rope_scaling = None
|
| 1770 |
+
|
| 1771 |
+
# # if not model:
|
| 1772 |
+
# self.model = DreamModel(config)
|
| 1773 |
+
# # else:
|
| 1774 |
+
# # self.model = model
|
| 1775 |
+
# #self.model.set_activation_checkpointing('whole_layer')
|
| 1776 |
+
|
| 1777 |
+
# self.post_init() # TODO
|
| 1778 |
+
|
| 1779 |
+
# def get_model(self):
|
| 1780 |
+
# return self.model
|
| 1781 |
+
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|beginoftext|>",
|
| 4 |
+
"<|mask|>",
|
| 5 |
+
"<|begin_of_image|>",
|
| 6 |
+
"<|end_of_image|>",
|
| 7 |
+
"<|context_of_image|>",
|
| 8 |
+
"<|begin_of_video|>",
|
| 9 |
+
"<|end_of_video|>",
|
| 10 |
+
"<|context_of_video|>",
|
| 11 |
+
"<|begin_of_patch|>",
|
| 12 |
+
"<|end_of_patch|>",
|
| 13 |
+
"<|context_of_patch|>",
|
| 14 |
+
"<|begin_of_quad|>",
|
| 15 |
+
"<|end_of_quad|>",
|
| 16 |
+
"<|begin_of_ref|>",
|
| 17 |
+
"<|end_of_ref|>",
|
| 18 |
+
"<|begin_of_box|>",
|
| 19 |
+
"<|end_of_box|>",
|
| 20 |
+
"<|image|>",
|
| 21 |
+
"<|video|>",
|
| 22 |
+
"<|begin_of_audio|>",
|
| 23 |
+
"<|end_of_audio|>",
|
| 24 |
+
"<|context_of_audio|>",
|
| 25 |
+
"<|audio|>"
|
| 26 |
+
],
|
| 27 |
+
"bos_token": {
|
| 28 |
+
"content": "<|beginoftext|>",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false
|
| 33 |
+
},
|
| 34 |
+
"eos_token": {
|
| 35 |
+
"content": "<|endoftext|>",
|
| 36 |
+
"lstrip": false,
|
| 37 |
+
"normalized": false,
|
| 38 |
+
"rstrip": false,
|
| 39 |
+
"single_word": false
|
| 40 |
+
},
|
| 41 |
+
"mask_token": {
|
| 42 |
+
"content": "<|mask|>",
|
| 43 |
+
"lstrip": false,
|
| 44 |
+
"normalized": false,
|
| 45 |
+
"rstrip": false,
|
| 46 |
+
"single_word": false
|
| 47 |
+
},
|
| 48 |
+
"pad_token": {
|
| 49 |
+
"content": "<|endoftext|>",
|
| 50 |
+
"lstrip": false,
|
| 51 |
+
"normalized": false,
|
| 52 |
+
"rstrip": false,
|
| 53 |
+
"single_word": false
|
| 54 |
+
}
|
| 55 |
+
}
|
tokenization_dream.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Dream team, HKUNLP Group and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on Qwen's implementations in this library.
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""Tokenization classes for Dream."""
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import unicodedata
|
| 21 |
+
from functools import lru_cache
|
| 22 |
+
from typing import Optional, Tuple
|
| 23 |
+
|
| 24 |
+
import regex as re
|
| 25 |
+
|
| 26 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
VOCAB_FILES_NAMES = {
|
| 33 |
+
"vocab_file": "vocab.json",
|
| 34 |
+
"merges_file": "merges.txt",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
MAX_MODEL_INPUT_SIZES = {"dream/dream-tokenizer": 32768}
|
| 39 |
+
|
| 40 |
+
PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@lru_cache()
|
| 44 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
|
| 45 |
+
def bytes_to_unicode():
|
| 46 |
+
"""
|
| 47 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
| 48 |
+
characters the bpe code barfs on.
|
| 49 |
+
|
| 50 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
| 51 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
| 52 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
| 53 |
+
tables between utf-8 bytes and unicode strings.
|
| 54 |
+
"""
|
| 55 |
+
bs = (
|
| 56 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
| 57 |
+
)
|
| 58 |
+
cs = bs[:]
|
| 59 |
+
n = 0
|
| 60 |
+
for b in range(2**8):
|
| 61 |
+
if b not in bs:
|
| 62 |
+
bs.append(b)
|
| 63 |
+
cs.append(2**8 + n)
|
| 64 |
+
n += 1
|
| 65 |
+
cs = [chr(n) for n in cs]
|
| 66 |
+
return dict(zip(bs, cs))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
|
| 70 |
+
def get_pairs(word):
|
| 71 |
+
"""
|
| 72 |
+
Return set of symbol pairs in a word.
|
| 73 |
+
|
| 74 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 75 |
+
"""
|
| 76 |
+
pairs = set()
|
| 77 |
+
prev_char = word[0]
|
| 78 |
+
for char in word[1:]:
|
| 79 |
+
pairs.add((prev_char, char))
|
| 80 |
+
prev_char = char
|
| 81 |
+
return pairs
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class DreamTokenizer(PreTrainedTokenizer):
|
| 85 |
+
"""
|
| 86 |
+
Construct a Dream tokenizer. Based on byte-level Byte-Pair-Encoding.
|
| 87 |
+
|
| 88 |
+
Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
|
| 89 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
| 90 |
+
|
| 91 |
+
```python
|
| 92 |
+
>>> from transformers import AutoTokenizer
|
| 93 |
+
|
| 94 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Dream-org/Dream-v0-Base-7B", trust_remote_code=True)
|
| 95 |
+
>>> tokenizer("Hello world")["input_ids"]
|
| 96 |
+
[9707, 1879]
|
| 97 |
+
|
| 98 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
| 99 |
+
[21927, 1879]
|
| 100 |
+
```
|
| 101 |
+
This is expected.
|
| 102 |
+
|
| 103 |
+
You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
|
| 104 |
+
|
| 105 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 106 |
+
this superclass for more information regarding those methods.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
vocab_file (`str`):
|
| 110 |
+
Path to the vocabulary file.
|
| 111 |
+
merges_file (`str`):
|
| 112 |
+
Path to the merges file.
|
| 113 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 114 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 115 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 116 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
| 117 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 118 |
+
token instead.
|
| 119 |
+
bos_token (`str`, *optional*):
|
| 120 |
+
The beginning of sequence token. Not applicable for this tokenizer.
|
| 121 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
| 122 |
+
The end of sequence token.
|
| 123 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
| 124 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 125 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
| 126 |
+
Whether or not the model should cleanup the spaces that were added when splitting the input text during the
|
| 127 |
+
tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
|
| 128 |
+
split_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 129 |
+
Whether or not the special tokens should be split during the tokenization process. The default behavior is
|
| 130 |
+
to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
|
| 131 |
+
['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
|
| 132 |
+
'|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 136 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
vocab_file,
|
| 141 |
+
merges_file,
|
| 142 |
+
errors="replace",
|
| 143 |
+
unk_token="<|endoftext|>",
|
| 144 |
+
bos_token=None,
|
| 145 |
+
eos_token="<|endoftext|>",
|
| 146 |
+
pad_token="<|endoftext|>",
|
| 147 |
+
clean_up_tokenization_spaces=False,
|
| 148 |
+
split_special_tokens=False,
|
| 149 |
+
**kwargs,
|
| 150 |
+
):
|
| 151 |
+
# Dream vocab does not contain control tokens; added tokens need to be special
|
| 152 |
+
bos_token = (
|
| 153 |
+
AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 154 |
+
if isinstance(bos_token, str)
|
| 155 |
+
else bos_token
|
| 156 |
+
)
|
| 157 |
+
eos_token = (
|
| 158 |
+
AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 159 |
+
if isinstance(eos_token, str)
|
| 160 |
+
else eos_token
|
| 161 |
+
)
|
| 162 |
+
unk_token = (
|
| 163 |
+
AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 164 |
+
if isinstance(unk_token, str)
|
| 165 |
+
else unk_token
|
| 166 |
+
)
|
| 167 |
+
pad_token = (
|
| 168 |
+
AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 169 |
+
if isinstance(pad_token, str)
|
| 170 |
+
else pad_token
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 174 |
+
self.encoder = json.load(vocab_handle)
|
| 175 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 176 |
+
self.errors = errors # how to handle errors in decoding
|
| 177 |
+
self.byte_encoder = bytes_to_unicode()
|
| 178 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 179 |
+
bpe_merges = []
|
| 180 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 181 |
+
for i, line in enumerate(merges_handle):
|
| 182 |
+
line = line.strip()
|
| 183 |
+
if (i == 0 and line.startswith("#version:")) or not line:
|
| 184 |
+
continue
|
| 185 |
+
bpe_merges.append(tuple(line.split()))
|
| 186 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
| 187 |
+
# NOTE: the cache can grow without bound and will get really large for long running processes
|
| 188 |
+
# (esp. for texts of language that do not use space between word, e.g. Chinese); technically
|
| 189 |
+
# not a memory leak but appears as one.
|
| 190 |
+
# GPT2Tokenizer has the same problem, so let's be consistent.
|
| 191 |
+
self.cache = {}
|
| 192 |
+
|
| 193 |
+
self.pat = re.compile(PRETOKENIZE_REGEX)
|
| 194 |
+
|
| 195 |
+
if kwargs.get("add_prefix_space", False):
|
| 196 |
+
logger.warning_once(
|
| 197 |
+
f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
super().__init__(
|
| 201 |
+
errors=errors,
|
| 202 |
+
bos_token=bos_token,
|
| 203 |
+
eos_token=eos_token,
|
| 204 |
+
pad_token=pad_token,
|
| 205 |
+
unk_token=unk_token,
|
| 206 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 207 |
+
split_special_tokens=split_special_tokens,
|
| 208 |
+
**kwargs,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def vocab_size(self) -> int:
|
| 213 |
+
return len(self.encoder)
|
| 214 |
+
|
| 215 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
|
| 216 |
+
def get_vocab(self):
|
| 217 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 218 |
+
|
| 219 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
|
| 220 |
+
def bpe(self, token):
|
| 221 |
+
if token in self.cache:
|
| 222 |
+
return self.cache[token]
|
| 223 |
+
word = tuple(token)
|
| 224 |
+
pairs = get_pairs(word)
|
| 225 |
+
|
| 226 |
+
if not pairs:
|
| 227 |
+
return token
|
| 228 |
+
|
| 229 |
+
while True:
|
| 230 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 231 |
+
if bigram not in self.bpe_ranks:
|
| 232 |
+
break
|
| 233 |
+
first, second = bigram
|
| 234 |
+
new_word = []
|
| 235 |
+
i = 0
|
| 236 |
+
while i < len(word):
|
| 237 |
+
try:
|
| 238 |
+
j = word.index(first, i)
|
| 239 |
+
except ValueError:
|
| 240 |
+
new_word.extend(word[i:])
|
| 241 |
+
break
|
| 242 |
+
else:
|
| 243 |
+
new_word.extend(word[i:j])
|
| 244 |
+
i = j
|
| 245 |
+
|
| 246 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 247 |
+
new_word.append(first + second)
|
| 248 |
+
i += 2
|
| 249 |
+
else:
|
| 250 |
+
new_word.append(word[i])
|
| 251 |
+
i += 1
|
| 252 |
+
new_word = tuple(new_word)
|
| 253 |
+
word = new_word
|
| 254 |
+
if len(word) == 1:
|
| 255 |
+
break
|
| 256 |
+
else:
|
| 257 |
+
pairs = get_pairs(word)
|
| 258 |
+
word = " ".join(word)
|
| 259 |
+
self.cache[token] = word
|
| 260 |
+
return word
|
| 261 |
+
|
| 262 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
|
| 263 |
+
def _tokenize(self, text):
|
| 264 |
+
"""Tokenize a string."""
|
| 265 |
+
bpe_tokens = []
|
| 266 |
+
for token in re.findall(self.pat, text):
|
| 267 |
+
token = "".join(
|
| 268 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
| 269 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
| 270 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
| 271 |
+
return bpe_tokens
|
| 272 |
+
|
| 273 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
|
| 274 |
+
def _convert_token_to_id(self, token):
|
| 275 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 276 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 277 |
+
|
| 278 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
|
| 279 |
+
def _convert_id_to_token(self, index):
|
| 280 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 281 |
+
return self.decoder.get(index)
|
| 282 |
+
|
| 283 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
|
| 284 |
+
def convert_tokens_to_string(self, tokens):
|
| 285 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 286 |
+
text = "".join(tokens)
|
| 287 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
| 288 |
+
return text
|
| 289 |
+
|
| 290 |
+
def decode(
|
| 291 |
+
self,
|
| 292 |
+
token_ids,
|
| 293 |
+
skip_special_tokens: bool = False,
|
| 294 |
+
clean_up_tokenization_spaces: Optional[bool] = False,
|
| 295 |
+
spaces_between_special_tokens: bool = False,
|
| 296 |
+
**kwargs,
|
| 297 |
+
) -> str:
|
| 298 |
+
# `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
|
| 299 |
+
# and cannot be configured elsewhere, but it should default to False for DreamTokenizer
|
| 300 |
+
return super().decode(
|
| 301 |
+
token_ids,
|
| 302 |
+
skip_special_tokens=skip_special_tokens,
|
| 303 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 304 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
| 305 |
+
**kwargs,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
|
| 309 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 310 |
+
if not os.path.isdir(save_directory):
|
| 311 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 312 |
+
return
|
| 313 |
+
vocab_file = os.path.join(
|
| 314 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 315 |
+
)
|
| 316 |
+
merge_file = os.path.join(
|
| 317 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 321 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 322 |
+
|
| 323 |
+
index = 0
|
| 324 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 325 |
+
writer.write("#version: 0.2\n")
|
| 326 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 327 |
+
if index != token_index:
|
| 328 |
+
logger.warning(
|
| 329 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 330 |
+
" Please check that the tokenizer is not corrupted!"
|
| 331 |
+
)
|
| 332 |
+
index = token_index
|
| 333 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 334 |
+
index += 1
|
| 335 |
+
|
| 336 |
+
return vocab_file, merge_file
|
| 337 |
+
|
| 338 |
+
def prepare_for_tokenization(self, text, **kwargs):
|
| 339 |
+
text = unicodedata.normalize("NFC", text)
|
| 340 |
+
return (text, kwargs)
|
tokenizer_config.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|