添加flash attn和sdpa支持,添加processor
Browse files- Qwenov3Config.py +110 -57
- inference.py +33 -27
Qwenov3Config.py
CHANGED
|
@@ -1,8 +1,14 @@
|
|
| 1 |
-
from
|
|
|
|
| 2 |
from modelscope import AutoConfig, AutoProcessor, AutoModel, AutoTokenizer, AutoModelForCausalLM
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
|
|
|
| 5 |
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
class Qwenov3Config(PretrainedConfig):
|
|
@@ -34,8 +40,55 @@ class Qwenov3Config(PretrainedConfig):
|
|
| 34 |
super().__init__(**kwargs)
|
| 35 |
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
class Qwenov3(GenerationMixin, PreTrainedModel):
|
| 38 |
config_class = Qwenov3Config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
def __init__(self, config):
|
| 41 |
super().__init__(config)
|
|
@@ -90,48 +143,61 @@ class Qwenov3(GenerationMixin, PreTrainedModel):
|
|
| 90 |
for param in self.llm_model.parameters():
|
| 91 |
param.requires_grad = False
|
| 92 |
|
| 93 |
-
def forward(
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
outputs = self.llm_model(
|
| 110 |
-
|
| 111 |
attention_mask=attention_mask,
|
|
|
|
| 112 |
past_key_values=past_key_values,
|
|
|
|
| 113 |
use_cache=use_cache,
|
| 114 |
-
|
|
|
|
| 115 |
)
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
| 118 |
loss = None
|
| 119 |
if labels is not None:
|
| 120 |
-
loss_fct =
|
| 121 |
-
loss = loss_fct(
|
| 122 |
-
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
return CausalLMOutputWithPast(
|
| 126 |
-
loss=loss,
|
| 127 |
logits=logits,
|
| 128 |
past_key_values=outputs.past_key_values,
|
| 129 |
hidden_states=outputs.hidden_states,
|
| 130 |
-
attentions=outputs.attentions
|
| 131 |
)
|
| 132 |
|
| 133 |
@torch.inference_mode()
|
| 134 |
-
def generate(self, input_ids=None, pixel_values=None, attention_mask=None,
|
| 135 |
max_new_tokens=512, temperature=0.7, top_p=0.8, top_k=20,
|
| 136 |
do_sample=True, num_beams=1, use_cache=True, **kwargs):
|
| 137 |
if pixel_values is not None:
|
|
@@ -143,36 +209,23 @@ class Qwenov3(GenerationMixin, PreTrainedModel):
|
|
| 143 |
image_features = self.adapter(patch_embeds)
|
| 144 |
text_embeds = text_embeds.to(image_features.dtype)
|
| 145 |
inputs_embeds = self.merge_input_ids_with_image_features(image_features, text_embeds, input_ids)
|
| 146 |
-
return self.llm_model.generate(
|
| 147 |
-
input_ids=input_ids,
|
| 148 |
-
inputs_embeds=inputs_embeds,
|
| 149 |
-
attention_mask=attention_mask,
|
| 150 |
-
max_new_tokens=max_new_tokens,
|
| 151 |
-
temperature=temperature,
|
| 152 |
-
top_p=top_p,
|
| 153 |
-
top_k=top_k,
|
| 154 |
-
do_sample=do_sample,
|
| 155 |
-
num_beams=num_beams,
|
| 156 |
-
use_cache=use_cache,
|
| 157 |
-
pad_token_id=self.tokenizer.pad_token_id,
|
| 158 |
-
eos_token_id=self.tokenizer.eos_token_id,
|
| 159 |
-
**kwargs
|
| 160 |
-
)
|
| 161 |
else:
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
| 176 |
|
| 177 |
def can_generate(self):
|
| 178 |
return True
|
|
|
|
| 1 |
+
from typing import Optional, Union
|
| 2 |
+
from transformers import PreTrainedModel, PretrainedConfig, GenerationMixin, Cache, BatchFeature
|
| 3 |
from modelscope import AutoConfig, AutoProcessor, AutoModel, AutoTokenizer, AutoModelForCausalLM
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
| 6 |
+
from transformers.image_utils import ImageInput
|
| 7 |
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 8 |
+
from liger_kernel.transformers import LigerCrossEntropyLoss
|
| 9 |
+
from transformers.processing_utils import Unpack, ProcessorMixin
|
| 10 |
+
from transformers.tokenization_utils_base import TextInput, PreTokenizedInput
|
| 11 |
+
from transformers.utils import TransformersKwargs
|
| 12 |
|
| 13 |
|
| 14 |
class Qwenov3Config(PretrainedConfig):
|
|
|
|
| 40 |
super().__init__(**kwargs)
|
| 41 |
|
| 42 |
|
| 43 |
+
class Qwenov3Processor(ProcessorMixin):
|
| 44 |
+
attributes = ["image_processor", "tokenizer"]
|
| 45 |
+
image_processor_class = "AutoImageProcessor"
|
| 46 |
+
tokenizer_class = "AutoTokenizer"
|
| 47 |
+
|
| 48 |
+
def __init__(self, image_processor=None, tokenizer=None, chat_template=None, image_pad_num=49, **kwargs):
|
| 49 |
+
self.image_token = "<|image_pad|>"
|
| 50 |
+
self.image_pad_num = image_pad_num
|
| 51 |
+
if chat_template is None and tokenizer is not None:
|
| 52 |
+
chat_template = getattr(tokenizer, "chat_template", None)
|
| 53 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 54 |
+
|
| 55 |
+
def __call__(
|
| 56 |
+
self,
|
| 57 |
+
images: Optional[ImageInput] = None,
|
| 58 |
+
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
|
| 59 |
+
return_tensors: str = "pt",
|
| 60 |
+
**kwargs,
|
| 61 |
+
) -> BatchFeature:
|
| 62 |
+
image_inputs = {}
|
| 63 |
+
if images is not None:
|
| 64 |
+
image_inputs = {'pixel_values': self.image_processor(images=images, return_tensors="pt")['pixel_values']}
|
| 65 |
+
|
| 66 |
+
if not isinstance(text, list):
|
| 67 |
+
text = [text]
|
| 68 |
+
|
| 69 |
+
processed_text = []
|
| 70 |
+
for t in text:
|
| 71 |
+
replacement = '<|vision_start|>' + '<|image_pad|>' * self.image_pad_num + '<|vision_end|>'
|
| 72 |
+
if '<image>' not in t:
|
| 73 |
+
t = t.replace('<|im_end|>', '<image><|im_end|>', 1)
|
| 74 |
+
processed_text.append(t.replace('<image>', replacement))
|
| 75 |
+
|
| 76 |
+
tokenizer_kwargs = {k: v for k, v in kwargs.items() if k not in ['images']}
|
| 77 |
+
text_inputs = self.tokenizer(processed_text, return_tensors=return_tensors, **tokenizer_kwargs)
|
| 78 |
+
|
| 79 |
+
return BatchFeature(data={**text_inputs, **image_inputs})
|
| 80 |
+
|
| 81 |
+
|
| 82 |
class Qwenov3(GenerationMixin, PreTrainedModel):
|
| 83 |
config_class = Qwenov3Config
|
| 84 |
+
base_model_prefix = "model"
|
| 85 |
+
supports_gradient_checkpointing = True
|
| 86 |
+
_no_split_modules = ["MoeDecoderLayer"]
|
| 87 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 88 |
+
_supports_sdpa = True
|
| 89 |
+
_supports_flash_attn = True
|
| 90 |
+
_can_compile_fullgraph = False
|
| 91 |
+
_supports_attention_backend = True
|
| 92 |
|
| 93 |
def __init__(self, config):
|
| 94 |
super().__init__(config)
|
|
|
|
| 143 |
for param in self.llm_model.parameters():
|
| 144 |
param.requires_grad = False
|
| 145 |
|
| 146 |
+
def forward(
|
| 147 |
+
self,
|
| 148 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 149 |
+
pixel_values: Optional[torch.LongTensor] = None,
|
| 150 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 151 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 152 |
+
past_key_values: Optional[Cache] = None,
|
| 153 |
+
labels: Optional[torch.LongTensor] = None,
|
| 154 |
+
use_cache: Optional[bool] = None,
|
| 155 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 156 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 157 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 158 |
+
):
|
| 159 |
+
text_embeds = self.llm_model.get_input_embeddings()(input_ids)
|
| 160 |
+
if pixel_values is not None:
|
| 161 |
+
image_embeds = self.vision_model(pixel_values).last_hidden_state
|
| 162 |
+
patch_embeds = image_embeds[:, 5:, :] # [batch, 196, 1024]
|
| 163 |
+
b, num_patches, hidden_dim = patch_embeds.shape
|
| 164 |
+
patch_embeds = patch_embeds.view(b, num_patches // 4, hidden_dim * 4) # [batch, 49, 4096]
|
| 165 |
+
image_features = self.adapter(patch_embeds)
|
| 166 |
+
text_embeds = text_embeds.to(image_features.dtype)
|
| 167 |
+
inputs_embeds = self.merge_input_ids_with_image_features(image_features, text_embeds, input_ids)
|
| 168 |
+
else:
|
| 169 |
+
inputs_embeds = text_embeds
|
| 170 |
|
| 171 |
outputs = self.llm_model(
|
| 172 |
+
input_ids=input_ids,
|
| 173 |
attention_mask=attention_mask,
|
| 174 |
+
position_ids=position_ids,
|
| 175 |
past_key_values=past_key_values,
|
| 176 |
+
inputs_embeds=inputs_embeds,
|
| 177 |
use_cache=use_cache,
|
| 178 |
+
cache_position=cache_position,
|
| 179 |
+
**kwargs,
|
| 180 |
)
|
| 181 |
+
|
| 182 |
+
hidden_states = outputs.last_hidden_state
|
| 183 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 184 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 185 |
+
|
| 186 |
loss = None
|
| 187 |
if labels is not None:
|
| 188 |
+
loss_fct = LigerCrossEntropyLoss(ignore_index=self.tokenizer.pad_token_id)
|
| 189 |
+
loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1).to(logits.device))
|
| 190 |
+
|
|
|
|
|
|
|
| 191 |
return CausalLMOutputWithPast(
|
| 192 |
+
loss=loss,
|
| 193 |
logits=logits,
|
| 194 |
past_key_values=outputs.past_key_values,
|
| 195 |
hidden_states=outputs.hidden_states,
|
| 196 |
+
attentions=outputs.attentions,
|
| 197 |
)
|
| 198 |
|
| 199 |
@torch.inference_mode()
|
| 200 |
+
def generate(self, input_ids=None, pixel_values=None, attention_mask=None,
|
| 201 |
max_new_tokens=512, temperature=0.7, top_p=0.8, top_k=20,
|
| 202 |
do_sample=True, num_beams=1, use_cache=True, **kwargs):
|
| 203 |
if pixel_values is not None:
|
|
|
|
| 209 |
image_features = self.adapter(patch_embeds)
|
| 210 |
text_embeds = text_embeds.to(image_features.dtype)
|
| 211 |
inputs_embeds = self.merge_input_ids_with_image_features(image_features, text_embeds, input_ids)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
else:
|
| 213 |
+
inputs_embeds = self.llm_model.get_input_embeddings()(input_ids)
|
| 214 |
+
return self.llm_model.generate(
|
| 215 |
+
input_ids=input_ids,
|
| 216 |
+
inputs_embeds=inputs_embeds,
|
| 217 |
+
attention_mask=attention_mask,
|
| 218 |
+
max_new_tokens=max_new_tokens,
|
| 219 |
+
temperature=temperature,
|
| 220 |
+
top_p=top_p,
|
| 221 |
+
top_k=top_k,
|
| 222 |
+
do_sample=do_sample,
|
| 223 |
+
num_beams=num_beams,
|
| 224 |
+
use_cache=use_cache,
|
| 225 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 226 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
| 227 |
+
**kwargs
|
| 228 |
+
)
|
| 229 |
|
| 230 |
def can_generate(self):
|
| 231 |
return True
|
inference.py
CHANGED
|
@@ -1,50 +1,56 @@
|
|
| 1 |
from transformers import AutoModelForCausalLM, AutoConfig
|
| 2 |
-
from
|
| 3 |
-
from Qwenov3Config import Qwenov3Config, Qwenov3
|
| 4 |
import torch
|
| 5 |
|
| 6 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 7 |
-
model_path = ''
|
| 8 |
AutoConfig.register("Qwenov3", Qwenov3Config)
|
| 9 |
AutoModelForCausalLM.register(Qwenov3Config, Qwenov3)
|
|
|
|
| 10 |
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, dtype=torch.bfloat16,
|
| 11 |
-
trust_remote_code=True).to(device)
|
|
|
|
| 12 |
model.eval()
|
| 13 |
-
|
| 14 |
-
tokenizer = model.tokenizer
|
| 15 |
messages = [
|
| 16 |
{"role": "system", "content": 'You are a helpful assistant.'},
|
| 17 |
-
{"role": "user", "content":
|
| 18 |
]
|
| 19 |
-
if '<image>' not in messages[1]['content']:
|
| 20 |
-
messages[1]['content'] = '<image>\n' + messages[1]['content']
|
| 21 |
-
|
| 22 |
-
print(messages)
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
add_generation_prompt=True,
|
| 27 |
-
enable_thinking=False).replace('<image>',
|
| 28 |
-
'<|vision_start|>' + '<|image_pad|>' * model.config.image_pad_num + '<|vision_end|>')
|
| 29 |
-
print(q_text)
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
output_ids = model.generate(
|
| 39 |
-
|
| 40 |
-
attention_mask=attention_mask,
|
| 41 |
-
pixel_values=pixel_values,
|
| 42 |
max_new_tokens=512,
|
| 43 |
temperature=0.7,
|
| 44 |
top_k=20,
|
| 45 |
top_p=0.8,
|
| 46 |
do_sample=True,
|
| 47 |
-
repetition_penalty=1.
|
| 48 |
)
|
| 49 |
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from transformers import AutoModelForCausalLM, AutoConfig
|
| 2 |
+
from transformers.image_utils import load_image
|
| 3 |
+
from Qwenov3Config import Qwenov3Config, Qwenov3, Qwenov3Processor
|
| 4 |
import torch
|
| 5 |
|
| 6 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 7 |
+
model_path = 'TianYeZ1214/Qwenov3'
|
| 8 |
AutoConfig.register("Qwenov3", Qwenov3Config)
|
| 9 |
AutoModelForCausalLM.register(Qwenov3Config, Qwenov3)
|
| 10 |
+
|
| 11 |
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, dtype=torch.bfloat16,
|
| 12 |
+
trust_remote_code=True, attn_implementation="flash_attention_2").to(device)
|
| 13 |
+
processor = Qwenov3Processor(image_processor=model.processor, tokenizer=model.tokenizer)
|
| 14 |
model.eval()
|
| 15 |
+
|
|
|
|
| 16 |
messages = [
|
| 17 |
{"role": "system", "content": 'You are a helpful assistant.'},
|
| 18 |
+
{"role": "user", "content": "描述图片内容"},
|
| 19 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 22 |
+
image = load_image(url)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
q_text = processor.apply_chat_template(
|
| 25 |
+
messages,
|
| 26 |
+
tokenize=False,
|
| 27 |
+
add_generation_prompt=True,
|
| 28 |
+
enable_thinking=False
|
| 29 |
+
)
|
| 30 |
|
| 31 |
+
inputs = processor(
|
| 32 |
+
text=[q_text],
|
| 33 |
+
images=image,
|
| 34 |
+
padding=True,
|
| 35 |
+
return_tensors="pt",
|
| 36 |
+
).to(device)
|
| 37 |
|
| 38 |
output_ids = model.generate(
|
| 39 |
+
**inputs,
|
|
|
|
|
|
|
| 40 |
max_new_tokens=512,
|
| 41 |
temperature=0.7,
|
| 42 |
top_k=20,
|
| 43 |
top_p=0.8,
|
| 44 |
do_sample=True,
|
| 45 |
+
repetition_penalty=1.1,
|
| 46 |
)
|
| 47 |
|
| 48 |
+
output_ids = output_ids[0].tolist()
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
index = len(output_ids) - output_ids[::-1].index(151668)
|
| 52 |
+
except ValueError:
|
| 53 |
+
index = 0
|
| 54 |
+
|
| 55 |
+
content = processor.decode(output_ids[index:], skip_special_tokens=True)
|
| 56 |
+
print("content:", content)
|