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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# --------------------------------------------------------
|
2 |
+
# InternVL
|
3 |
+
# Copyright (c) 2024 OpenGVLab
|
4 |
+
# Licensed under The MIT License [see LICENSE for details]
|
5 |
+
# --------------------------------------------------------
|
6 |
+
|
7 |
+
import warnings
|
8 |
+
from typing import List, Optional, Tuple, Union
|
9 |
+
|
10 |
+
import torch.utils.checkpoint
|
11 |
+
import transformers
|
12 |
+
from torch import nn
|
13 |
+
from torch.nn import CrossEntropyLoss
|
14 |
+
from transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,
|
15 |
+
Qwen2ForCausalLM)
|
16 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
17 |
+
from transformers.modeling_utils import PreTrainedModel
|
18 |
+
from transformers.utils import ModelOutput, logging
|
19 |
+
from transformers import WhisperConfig, WhisperModel, WhisperProcessor
|
20 |
+
from .configuration_internvl_chat import InternVLChatConfig
|
21 |
+
from .conversation import get_conv_template
|
22 |
+
from .modeling_intern_vit import InternVisionModel, has_flash_attn
|
23 |
+
|
24 |
+
logger = logging.get_logger(__name__)
|
25 |
+
|
26 |
+
|
27 |
+
def version_cmp(v1, v2, op='eq'):
|
28 |
+
import operator
|
29 |
+
|
30 |
+
from packaging import version
|
31 |
+
op_func = getattr(operator, op)
|
32 |
+
return op_func(version.parse(v1), version.parse(v2))
|
33 |
+
|
34 |
+
|
35 |
+
class InternVLChatModel(PreTrainedModel):
|
36 |
+
config_class = InternVLChatConfig
|
37 |
+
main_input_name = 'pixel_values'
|
38 |
+
base_model_prefix = 'language_model'
|
39 |
+
_supports_flash_attn_2 = True
|
40 |
+
_no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'Qwen2DecoderLayer']
|
41 |
+
|
42 |
+
def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
|
43 |
+
super().__init__(config)
|
44 |
+
|
45 |
+
assert version_cmp(transformers.__version__, '4.37.0', 'ge')
|
46 |
+
image_size = config.force_image_size or config.vision_config.image_size
|
47 |
+
patch_size = config.vision_config.patch_size
|
48 |
+
self.patch_size = patch_size
|
49 |
+
self.select_layer = config.select_layer
|
50 |
+
self.template = config.template
|
51 |
+
self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
|
52 |
+
self.downsample_ratio = config.downsample_ratio
|
53 |
+
self.ps_version = config.ps_version
|
54 |
+
use_flash_attn = use_flash_attn if has_flash_attn else False
|
55 |
+
config.vision_config.use_flash_attn = True if use_flash_attn else False
|
56 |
+
config.llm_config._attn_implementation = 'flash_attention_2' if use_flash_attn else 'eager'
|
57 |
+
|
58 |
+
logger.info(f'num_image_token: {self.num_image_token}')
|
59 |
+
logger.info(f'ps_version: {self.ps_version}')
|
60 |
+
if vision_model is not None:
|
61 |
+
self.vision_model = vision_model
|
62 |
+
else:
|
63 |
+
self.vision_model = InternVisionModel(config.vision_config)
|
64 |
+
if language_model is not None:
|
65 |
+
self.language_model = language_model
|
66 |
+
else:
|
67 |
+
if config.llm_config.architectures[0] == 'LlamaForCausalLM':
|
68 |
+
self.language_model = LlamaForCausalLM(config.llm_config)
|
69 |
+
elif config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
|
70 |
+
self.language_model = Qwen2ForCausalLM(config.llm_config)
|
71 |
+
else:
|
72 |
+
raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
|
73 |
+
|
74 |
+
|
75 |
+
# whisper model
|
76 |
+
whisper_config = WhisperConfig(**self.config.audio_config)
|
77 |
+
self.audio_model = WhisperModel.from_pretrained(
|
78 |
+
"/data/nvme5n1p1/vladimir_workspace/audio_internvl/models/whisper-large-v3-turbo",
|
79 |
+
config=whisper_config,
|
80 |
+
torch_dtype=torch.float16,
|
81 |
+
low_cpu_mem_usage=True,
|
82 |
+
)
|
83 |
+
# Remove decoder since we only need the encoder
|
84 |
+
del self.audio_model.decoder
|
85 |
+
|
86 |
+
# Initialize audio processor
|
87 |
+
self.audio_processor = WhisperProcessor.from_pretrained("/data/nvme5n1p1/vladimir_workspace/audio_internvl/models/whisper-large-v3-turbo")
|
88 |
+
|
89 |
+
# Get hidden sizes
|
90 |
+
vit_hidden_size = config.vision_config.hidden_size
|
91 |
+
llm_hidden_size = config.llm_config.hidden_size
|
92 |
+
whisper_hidden_size = self.audio_model.config.d_model
|
93 |
+
|
94 |
+
self.mlp1 = nn.Sequential(
|
95 |
+
nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
|
96 |
+
nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
|
97 |
+
nn.GELU(),
|
98 |
+
nn.Linear(llm_hidden_size, llm_hidden_size)
|
99 |
+
)
|
100 |
+
|
101 |
+
# Audio projection
|
102 |
+
self.mlp2 = nn.Sequential(
|
103 |
+
nn.LayerNorm(whisper_hidden_size),
|
104 |
+
nn.Linear(whisper_hidden_size, llm_hidden_size),
|
105 |
+
nn.GELU(),
|
106 |
+
nn.Linear(llm_hidden_size, llm_hidden_size)
|
107 |
+
)
|
108 |
+
|
109 |
+
self.audio_context_token_id = None
|
110 |
+
|
111 |
+
self.img_context_token_id = None
|
112 |
+
self.conv_template = get_conv_template(self.template)
|
113 |
+
self.system_message = self.conv_template.system_message
|
114 |
+
|
115 |
+
def process_audio_feature(self, audio_values, audio_flags):
|
116 |
+
print("\n=== Processing Audio Features ===")
|
117 |
+
print(f"Input audio shape: {audio_values.shape}")
|
118 |
+
print(f"Audio flags shape: {audio_flags.shape}")
|
119 |
+
|
120 |
+
# Ensure float32 for audio input
|
121 |
+
audio_values = audio_values.to(torch.float32)
|
122 |
+
print(f"Audio values min/max: {audio_values.min():.3f}/{audio_values.max():.3f}")
|
123 |
+
|
124 |
+
# Convert audio to features
|
125 |
+
if len(audio_values.shape) == 2:
|
126 |
+
audio_list = [arr.cpu().numpy() for arr in audio_values]
|
127 |
+
else:
|
128 |
+
audio_list = [audio_values.cpu().numpy()]
|
129 |
+
|
130 |
+
processed_audio = self.audio_processor(
|
131 |
+
audio_list,
|
132 |
+
sampling_rate=16000,
|
133 |
+
return_tensors="pt"
|
134 |
+
)
|
135 |
+
audio_features = processed_audio["input_features"].to(self.device)
|
136 |
+
print(f"Processed audio features shape: {audio_features.shape}")
|
137 |
+
|
138 |
+
# Convert to float32 before encoder
|
139 |
+
audio_features = audio_features.to(torch.float32)
|
140 |
+
|
141 |
+
# Get encoder outputs
|
142 |
+
with torch.cuda.amp.autocast(enabled=False): # Disable mixed precision
|
143 |
+
audio_outputs = self.audio_model.encoder(audio_features)
|
144 |
+
audio_embeds = audio_outputs.last_hidden_state
|
145 |
+
|
146 |
+
print(f"Whisper encoder output shape: {audio_embeds.shape}")
|
147 |
+
audio_embeds = audio_embeds.to(torch.float32) # Ensure float32
|
148 |
+
print(f"Encoder output min/max: {audio_embeds.min():.3f}/{audio_embeds.max():.3f}")
|
149 |
+
|
150 |
+
# Reshape to match the expected number of tokens (300)
|
151 |
+
B, T, C = audio_embeds.shape
|
152 |
+
target_length = 300
|
153 |
+
|
154 |
+
# Use adaptive pooling to get the desired length
|
155 |
+
adaptive_pool = torch.nn.AdaptiveAvgPool1d(target_length)
|
156 |
+
audio_embeds = audio_embeds.transpose(1, 2) # [B, C, T]
|
157 |
+
audio_embeds = adaptive_pool(audio_embeds) # [B, C, 300]
|
158 |
+
audio_embeds = audio_embeds.transpose(1, 2) # [B, 300, C]
|
159 |
+
print(f"After pooling shape: {audio_embeds.shape}")
|
160 |
+
|
161 |
+
# More robust normalization before MLP2
|
162 |
+
audio_embeds = audio_embeds.float()
|
163 |
+
|
164 |
+
# First normalize per-token with more stable computation
|
165 |
+
mean = audio_embeds.mean(dim=-1, keepdim=True)
|
166 |
+
std = audio_embeds.std(dim=-1, keepdim=True)
|
167 |
+
# Add larger epsilon and clip std to avoid division by zero
|
168 |
+
std = torch.clamp(std, min=1e-6)
|
169 |
+
audio_embeds = (audio_embeds - mean) / std
|
170 |
+
|
171 |
+
# Clip extreme values more conservatively
|
172 |
+
audio_embeds = torch.clamp(audio_embeds, -2.0, 2.0)
|
173 |
+
|
174 |
+
# Apply LayerNorm with larger eps
|
175 |
+
layer_norm = nn.LayerNorm(audio_embeds.shape[-1], eps=1e-4).to(audio_embeds.device)
|
176 |
+
audio_embeds = layer_norm(audio_embeds)
|
177 |
+
|
178 |
+
print(f"Pre-MLP2 stats - min: {audio_embeds.min():.3f}, max: {audio_embeds.max():.3f}")
|
179 |
+
|
180 |
+
# Project to LLM dimension with gradient scaling and additional checks
|
181 |
+
with torch.cuda.amp.autocast(enabled=False):
|
182 |
+
# Pre-normalize and scale more carefully
|
183 |
+
mean = audio_embeds.mean(dim=-1, keepdim=True)
|
184 |
+
std = audio_embeds.std(dim=-1, keepdim=True)
|
185 |
+
std = torch.clamp(std, min=1e-6)
|
186 |
+
audio_embeds = (audio_embeds - mean) / std
|
187 |
+
|
188 |
+
# Scale down more conservatively before MLP2
|
189 |
+
audio_embeds = audio_embeds * 0.05 # Reduced from 0.1
|
190 |
+
|
191 |
+
# Apply MLP2 with gradient scaling
|
192 |
+
audio_embeds = self.mlp2(audio_embeds)
|
193 |
+
|
194 |
+
if torch.isnan(audio_embeds).any() or torch.isinf(audio_embeds).any():
|
195 |
+
print("WARNING: NaN/Inf detected after MLP2! Using robust recovery...")
|
196 |
+
audio_embeds = torch.nan_to_num(audio_embeds, nan=0.0, posinf=1.0, neginf=-1.0)
|
197 |
+
|
198 |
+
# Normalize with small noise
|
199 |
+
mean = audio_embeds.mean(dim=-1, keepdim=True)
|
200 |
+
std = audio_embeds.std(dim=-1, keepdim=True)
|
201 |
+
std = torch.clamp(std, min=1e-6)
|
202 |
+
audio_embeds = (audio_embeds - mean) / std
|
203 |
+
audio_embeds = audio_embeds + torch.randn_like(audio_embeds) * 0.0001
|
204 |
+
|
205 |
+
# Final scaling to match LLM exactly
|
206 |
+
llm_std = 0.009
|
207 |
+
audio_embeds = audio_embeds * llm_std
|
208 |
+
|
209 |
+
return audio_embeds
|
210 |
+
|
211 |
+
def forward(
|
212 |
+
self,
|
213 |
+
pixel_values: torch.FloatTensor = None,
|
214 |
+
audio_values: torch.FloatTensor = None,
|
215 |
+
input_ids: torch.LongTensor = None,
|
216 |
+
attention_mask: Optional[torch.Tensor] = None,
|
217 |
+
position_ids: Optional[torch.LongTensor] = None,
|
218 |
+
image_flags: Optional[torch.LongTensor] = None,
|
219 |
+
audio_flags: Optional[torch.LongTensor] = None,
|
220 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
221 |
+
labels: Optional[torch.LongTensor] = None,
|
222 |
+
use_cache: Optional[bool] = None,
|
223 |
+
output_attentions: Optional[bool] = None,
|
224 |
+
output_hidden_states: Optional[bool] = None,
|
225 |
+
return_dict: Optional[bool] = None,
|
226 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
227 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
228 |
+
|
229 |
+
input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
|
230 |
+
B, N, C = input_embeds.shape
|
231 |
+
input_embeds = input_embeds.reshape(B * N, C)
|
232 |
+
input_ids = input_ids.reshape(B * N)
|
233 |
+
|
234 |
+
# Process images if present
|
235 |
+
if pixel_values is not None:
|
236 |
+
image_flags = image_flags.squeeze(-1)
|
237 |
+
vit_embeds = self.extract_feature(pixel_values)
|
238 |
+
vit_embeds = vit_embeds[image_flags == 1]
|
239 |
+
vit_batch_size = pixel_values.shape[0]
|
240 |
+
|
241 |
+
if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
|
242 |
+
print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
|
243 |
+
|
244 |
+
image_selected = (input_ids == self.img_context_token_id)
|
245 |
+
try:
|
246 |
+
input_embeds[image_selected] = input_embeds[image_selected] * 0.0 + vit_embeds.reshape(-1, C)
|
247 |
+
except Exception as e:
|
248 |
+
vit_embeds = vit_embeds.reshape(-1, C)
|
249 |
+
n_token = image_selected.sum()
|
250 |
+
input_embeds[image_selected] = input_embeds[image_selected] * 0.0 + vit_embeds[:n_token]
|
251 |
+
|
252 |
+
# Process audio if present
|
253 |
+
if audio_values is not None and audio_flags is not None:
|
254 |
+
audio_flags = audio_flags.squeeze(-1)
|
255 |
+
audio_embeds = self.process_audio_feature(audio_values, audio_flags)
|
256 |
+
audio_batch_size = audio_values.shape[0] if len(audio_values.shape) > 1 else 1
|
257 |
+
|
258 |
+
if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
|
259 |
+
print(f'dynamic Audio batch size: {audio_batch_size}, audio per sample: {audio_batch_size / B}, dynamic token length: {N}')
|
260 |
+
|
261 |
+
audio_selected = (input_ids == self.audio_context_token_id)
|
262 |
+
try:
|
263 |
+
input_embeds[audio_selected] = input_embeds[audio_selected] * 0.0 + audio_embeds.reshape(-1, C)
|
264 |
+
except Exception as e:
|
265 |
+
audio_embeds = audio_embeds.reshape(-1, C)
|
266 |
+
n_token = audio_selected.sum()
|
267 |
+
input_embeds[audio_selected] = input_embeds[audio_selected] * 0.0 + audio_embeds[:n_token]
|
268 |
+
|
269 |
+
input_embeds = input_embeds.reshape(B, N, C)
|
270 |
+
|
271 |
+
outputs = self.language_model(
|
272 |
+
inputs_embeds=input_embeds,
|
273 |
+
attention_mask=attention_mask,
|
274 |
+
position_ids=position_ids,
|
275 |
+
past_key_values=past_key_values,
|
276 |
+
use_cache=use_cache,
|
277 |
+
output_attentions=output_attentions,
|
278 |
+
output_hidden_states=output_hidden_states,
|
279 |
+
return_dict=return_dict,
|
280 |
+
)
|
281 |
+
logits = outputs.logits
|
282 |
+
|
283 |
+
loss = None
|
284 |
+
if labels is not None:
|
285 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
286 |
+
shift_labels = labels[..., 1:].contiguous()
|
287 |
+
loss_fct = CrossEntropyLoss()
|
288 |
+
shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
|
289 |
+
shift_labels = shift_labels.view(-1)
|
290 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
291 |
+
loss = loss_fct(shift_logits, shift_labels)
|
292 |
+
|
293 |
+
if not return_dict:
|
294 |
+
output = (logits,) + outputs[1:]
|
295 |
+
return (loss,) + output if loss is not None else output
|
296 |
+
|
297 |
+
return CausalLMOutputWithPast(
|
298 |
+
loss=loss,
|
299 |
+
logits=logits,
|
300 |
+
past_key_values=outputs.past_key_values,
|
301 |
+
hidden_states=outputs.hidden_states,
|
302 |
+
attentions=outputs.attentions,
|
303 |
+
)
|
304 |
+
|
305 |
+
def pixel_shuffle(self, x, scale_factor=0.5):
|
306 |
+
n, w, h, c = x.size()
|
307 |
+
# N, W, H, C --> N, W, H * scale, C // scale
|
308 |
+
x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
|
309 |
+
# N, W, H * scale, C // scale --> N, H * scale, W, C // scale
|
310 |
+
x = x.permute(0, 2, 1, 3).contiguous()
|
311 |
+
# N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
|
312 |
+
x = x.view(n, int(h * scale_factor), int(w * scale_factor),
|
313 |
+
int(c / (scale_factor * scale_factor)))
|
314 |
+
if self.ps_version == 'v1':
|
315 |
+
warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
|
316 |
+
'which results in a transposed image.')
|
317 |
+
else:
|
318 |
+
x = x.permute(0, 2, 1, 3).contiguous()
|
319 |
+
return x
|
320 |
+
|
321 |
+
def extract_feature(self, pixel_values):
|
322 |
+
if self.select_layer == -1:
|
323 |
+
vit_embeds = self.vision_model(
|
324 |
+
pixel_values=pixel_values,
|
325 |
+
output_hidden_states=False,
|
326 |
+
return_dict=True).last_hidden_state
|
327 |
+
else:
|
328 |
+
vit_embeds = self.vision_model(
|
329 |
+
pixel_values=pixel_values,
|
330 |
+
output_hidden_states=True,
|
331 |
+
return_dict=True).hidden_states[self.select_layer]
|
332 |
+
vit_embeds = vit_embeds[:, 1:, :]
|
333 |
+
|
334 |
+
h = w = int(vit_embeds.shape[1] ** 0.5)
|
335 |
+
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
|
336 |
+
vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
|
337 |
+
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
|
338 |
+
vit_embeds = self.mlp1(vit_embeds)
|
339 |
+
return vit_embeds
|
340 |
+
|
341 |
+
def batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,
|
342 |
+
history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',
|
343 |
+
IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):
|
344 |
+
if history is not None or return_history:
|
345 |
+
print('Now multi-turn chat is not supported in batch_chat.')
|
346 |
+
raise NotImplementedError
|
347 |
+
|
348 |
+
if image_counts is not None:
|
349 |
+
num_patches_list = image_counts
|
350 |
+
print('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')
|
351 |
+
|
352 |
+
img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
|
353 |
+
self.img_context_token_id = img_context_token_id
|
354 |
+
|
355 |
+
if verbose and pixel_values is not None:
|
356 |
+
image_bs = pixel_values.shape[0]
|
357 |
+
print(f'dynamic ViT batch size: {image_bs}')
|
358 |
+
|
359 |
+
queries = []
|
360 |
+
for idx, num_patches in enumerate(num_patches_list):
|
361 |
+
question = questions[idx]
|
362 |
+
if pixel_values is not None and '<image>' not in question:
|
363 |
+
question = '<image>\n' + question
|
364 |
+
template = get_conv_template(self.template)
|
365 |
+
template.system_message = self.system_message
|
366 |
+
template.append_message(template.roles[0], question)
|
367 |
+
template.append_message(template.roles[1], None)
|
368 |
+
query = template.get_prompt()
|
369 |
+
|
370 |
+
image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
|
371 |
+
query = query.replace('<image>', image_tokens, 1)
|
372 |
+
queries.append(query)
|
373 |
+
|
374 |
+
tokenizer.padding_side = 'left'
|
375 |
+
model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
|
376 |
+
input_ids = model_inputs['input_ids'].to(self.device)
|
377 |
+
attention_mask = model_inputs['attention_mask'].to(self.device)
|
378 |
+
eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
|
379 |
+
generation_config['eos_token_id'] = eos_token_id
|
380 |
+
generation_output = self.generate(
|
381 |
+
pixel_values=pixel_values,
|
382 |
+
input_ids=input_ids,
|
383 |
+
attention_mask=attention_mask,
|
384 |
+
**generation_config
|
385 |
+
)
|
386 |
+
responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
|
387 |
+
responses = [response.split(template.sep.strip())[0].strip() for response in responses]
|
388 |
+
return responses
|
389 |
+
|
390 |
+
def chat(self, tokenizer, pixel_values=None, question=None, generation_config=None,
|
391 |
+
history=None, return_history=False, num_patches_list=None,
|
392 |
+
IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
|
393 |
+
AUDIO_START_TOKEN='<audio>', AUDIO_END_TOKEN='</audio>', AUDIO_CONTEXT_TOKEN='<AUDIO_CONTEXT>',
|
394 |
+
verbose=False, **kwargs): # Add **kwargs to catch extra arguments
|
395 |
+
"""Chat function that handles both text-only and multimodal inputs"""
|
396 |
+
print("=== Starting Chat Process ===")
|
397 |
+
print(f"Question: {question}")
|
398 |
+
print(f"Input types - Pixel values: {type(pixel_values)}, Audio values: {type(kwargs.get('audio_values'))}")
|
399 |
+
|
400 |
+
# Basic input validation
|
401 |
+
if question is None:
|
402 |
+
raise ValueError("Question cannot be None")
|
403 |
+
if not isinstance(question, str):
|
404 |
+
raise ValueError(f"Question must be string, got {type(question)}")
|
405 |
+
|
406 |
+
audio_values = kwargs.get('audio_values', None)
|
407 |
+
|
408 |
+
# Handle image prompt
|
409 |
+
if history is None and pixel_values is not None and '<image>' not in question:
|
410 |
+
question = '<image>\n' + question
|
411 |
+
print("Added image token to question")
|
412 |
+
|
413 |
+
# Handle audio prompt
|
414 |
+
if history is None and audio_values is not None and '<audio>' not in question:
|
415 |
+
question = '<audio>\n' + question
|
416 |
+
print("Added audio token to question")
|
417 |
+
|
418 |
+
# Process image patches
|
419 |
+
if num_patches_list is None:
|
420 |
+
num_patches_list = [pixel_values.shape[0]] if pixel_values is not None else []
|
421 |
+
if pixel_values is not None:
|
422 |
+
assert len(pixel_values) == sum(num_patches_list)
|
423 |
+
print(f"Image patches: {num_patches_list}")
|
424 |
+
|
425 |
+
# Set context token IDs
|
426 |
+
img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
|
427 |
+
audio_context_token_id = tokenizer.convert_tokens_to_ids(AUDIO_CONTEXT_TOKEN)
|
428 |
+
self.img_context_token_id = img_context_token_id
|
429 |
+
self.audio_context_token_id = audio_context_token_id
|
430 |
+
print(f"Token IDs - Image: {img_context_token_id}, Audio: {audio_context_token_id}")
|
431 |
+
|
432 |
+
# Process template and history
|
433 |
+
# Prepare conversation template
|
434 |
+
template = get_conv_template(self.template)
|
435 |
+
template.system_message = self.system_message
|
436 |
+
eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
|
437 |
+
|
438 |
+
history = [] if history is None else history
|
439 |
+
for old_question, old_answer in history:
|
440 |
+
template.append_message(template.roles[0], old_question)
|
441 |
+
template.append_message(template.roles[1], old_answer)
|
442 |
+
template.append_message(template.roles[0], question)
|
443 |
+
template.append_message(template.roles[1], None)
|
444 |
+
query = template.get_prompt()
|
445 |
+
print(f"Processed query: {query[:100]}...") # Print first 100 chars
|
446 |
+
|
447 |
+
if verbose:
|
448 |
+
if pixel_values is not None:
|
449 |
+
print(f'dynamic ViT batch size: {pixel_values.shape[0]}')
|
450 |
+
if audio_values is not None:
|
451 |
+
print(f'dynamic Audio batch size: {audio_values.shape[0]}')
|
452 |
+
|
453 |
+
# Insert image tokens
|
454 |
+
for num_patches in num_patches_list:
|
455 |
+
image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKEN
|
456 |
+
query = query.replace('<image>', image_tokens, 1)
|
457 |
+
|
458 |
+
# Insert audio tokens (assuming one audio per query)
|
459 |
+
if audio_values is not None:
|
460 |
+
audio_tokens = AUDIO_START_TOKEN + AUDIO_CONTEXT_TOKEN * 300 + AUDIO_END_TOKEN
|
461 |
+
query = query.replace('<audio>', audio_tokens, 1)
|
462 |
+
|
463 |
+
# Add debug prints
|
464 |
+
print("\n=== Audio Token Debug ===")
|
465 |
+
print(f"AUDIO_START_TOKEN: {AUDIO_START_TOKEN} (id: {tokenizer.convert_tokens_to_ids(AUDIO_START_TOKEN)})")
|
466 |
+
print(f"AUDIO_CONTEXT_TOKEN: {AUDIO_CONTEXT_TOKEN} (id: {tokenizer.convert_tokens_to_ids(AUDIO_CONTEXT_TOKEN)})")
|
467 |
+
print(f"AUDIO_END_TOKEN: {AUDIO_END_TOKEN} (id: {tokenizer.convert_tokens_to_ids(AUDIO_END_TOKEN)})")
|
468 |
+
|
469 |
+
# Verify token presence
|
470 |
+
test_tokens = tokenizer(query, return_tensors='pt')['input_ids'][0]
|
471 |
+
context_token_count = (test_tokens == self.audio_context_token_id).sum()
|
472 |
+
print(f"Number of AUDIO_CONTEXT tokens found: {context_token_count} (should be 300)")
|
473 |
+
|
474 |
+
# Print full tokenization of a small segment
|
475 |
+
audio_segment = query[query.find(AUDIO_START_TOKEN):query.find(AUDIO_END_TOKEN)+len(AUDIO_END_TOKEN)]
|
476 |
+
print("\nTokenization of audio segment:")
|
477 |
+
tokens = tokenizer.tokenize(audio_segment)
|
478 |
+
print(f"First 10 tokens: {tokens[:10]}...")
|
479 |
+
print(f"Last 10 tokens: {tokens[-10:]}")
|
480 |
+
|
481 |
+
# Prepare model inputs
|
482 |
+
model_inputs = tokenizer(query, return_tensors='pt')
|
483 |
+
print("Model inputs:")
|
484 |
+
print(f"input_ids shape: {model_inputs['input_ids'].shape}")
|
485 |
+
print(f"First few tokens: {tokenizer.convert_ids_to_tokens(model_inputs['input_ids'][0][:20])}")
|
486 |
+
input_ids = model_inputs['input_ids'].to(self.device)
|
487 |
+
attention_mask = model_inputs['attention_mask'].to(self.device)
|
488 |
+
generation_config['eos_token_id'] = eos_token_id
|
489 |
+
|
490 |
+
# Ensure generation_config is a proper dictionary
|
491 |
+
if generation_config is None or not isinstance(generation_config, dict):
|
492 |
+
generation_config = {}
|
493 |
+
|
494 |
+
# Set default generation parameters
|
495 |
+
default_config = {
|
496 |
+
"do_sample": True,
|
497 |
+
"temperature": 0.7,
|
498 |
+
"top_p": 0.9,
|
499 |
+
"max_new_tokens": 256,
|
500 |
+
"repetition_penalty": 1.2,
|
501 |
+
"no_repeat_ngram_size": 3,
|
502 |
+
"pad_token_id": tokenizer.pad_token_id,
|
503 |
+
"eos_token_id": eos_token_id
|
504 |
+
}
|
505 |
+
|
506 |
+
# Update with user provided config
|
507 |
+
for k, v in default_config.items():
|
508 |
+
if k not in generation_config:
|
509 |
+
generation_config[k] = v
|
510 |
+
|
511 |
+
# Create GenerationConfig object
|
512 |
+
generation_config = GenerationConfig(**generation_config)
|
513 |
+
|
514 |
+
# Generate response
|
515 |
+
generation_output = self.generate(
|
516 |
+
pixel_values=pixel_values,
|
517 |
+
audio_values=audio_values,
|
518 |
+
input_ids=input_ids,
|
519 |
+
attention_mask=attention_mask,
|
520 |
+
generation_config=generation_config,
|
521 |
+
)
|
522 |
+
|
523 |
+
# Process response
|
524 |
+
response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
|
525 |
+
response = response.split(template.sep.strip())[0].strip()
|
526 |
+
history.append((question, response))
|
527 |
+
|
528 |
+
if return_history:
|
529 |
+
return response, history
|
530 |
+
else:
|
531 |
+
# Clean up query for printing
|
532 |
+
query_to_print = query.replace(IMG_CONTEXT_TOKEN, '').replace(AUDIO_CONTEXT_TOKEN, '')
|
533 |
+
query_to_print = query_to_print.replace(f'{IMG_START_TOKEN}{IMG_END_TOKEN}', '<image>')
|
534 |
+
query_to_print = query_to_print.replace(f'{AUDIO_START_TOKEN}{AUDIO_END_TOKEN}', '<audio>')
|
535 |
+
if verbose:
|
536 |
+
print(query_to_print, response)
|
537 |
+
return response
|
538 |
+
|
539 |
+
@torch.no_grad()
|
540 |
+
def generate(self, pixel_values=None, audio_values=None, input_ids=None,
|
541 |
+
attention_mask=None, visual_features=None, generation_config=None,
|
542 |
+
output_hidden_states=None, **generate_kwargs):
|
543 |
+
|
544 |
+
print("\n=== Generate Method Debug ===")
|
545 |
+
|
546 |
+
# Get initial embeddings and check statistics
|
547 |
+
input_embeds = self.language_model.get_input_embeddings()(input_ids)
|
548 |
+
initial_std = input_embeds.std().item()
|
549 |
+
print(f"LLM embedding stats - mean: {input_embeds.mean():.3f}, std: {initial_std:.3f}")
|
550 |
+
|
551 |
+
B, N, C = input_embeds.shape
|
552 |
+
print(f"Initial embeddings shape: {input_embeds.shape}")
|
553 |
+
|
554 |
+
input_embeds = input_embeds.reshape(B * N, C)
|
555 |
+
input_ids = input_ids.reshape(B * N)
|
556 |
+
|
557 |
+
if audio_values is not None:
|
558 |
+
assert self.audio_context_token_id is not None
|
559 |
+
print("\nAudio Processing:")
|
560 |
+
print(f"Audio context token ID: {self.audio_context_token_id}")
|
561 |
+
|
562 |
+
audio_embeds = self.process_audio_feature(
|
563 |
+
audio_values,
|
564 |
+
torch.ones(audio_values.shape[0]).to(audio_values.device)
|
565 |
+
)
|
566 |
+
|
567 |
+
# Scale audio embeddings to match LLM embeddings
|
568 |
+
audio_embeds = audio_embeds * (initial_std / audio_embeds.std().item())
|
569 |
+
|
570 |
+
print(f"Processed audio embeds shape: {audio_embeds.shape}")
|
571 |
+
print(f"Audio embedding stats after scaling - mean: {audio_embeds.mean():.3f}, std: {audio_embeds.std():.3f}")
|
572 |
+
|
573 |
+
audio_selected = (input_ids == self.audio_context_token_id)
|
574 |
+
num_audio_tokens = audio_selected.sum()
|
575 |
+
print(f"Number of audio context tokens found: {num_audio_tokens}")
|
576 |
+
|
577 |
+
try:
|
578 |
+
input_embeds[audio_selected] = audio_embeds.reshape(-1, C).to(input_embeds.device)
|
579 |
+
print("Successfully inserted audio embeddings")
|
580 |
+
except Exception as e:
|
581 |
+
print(f"Error inserting audio embeddings: {e}")
|
582 |
+
raise
|
583 |
+
|
584 |
+
# Reshape back
|
585 |
+
input_embeds = input_embeds.reshape(B, N, C)
|
586 |
+
|
587 |
+
# Final normalization of combined embeddings
|
588 |
+
input_embeds = torch.nn.functional.layer_norm(
|
589 |
+
input_embeds,
|
590 |
+
input_embeds.shape[-1:],
|
591 |
+
eps=1e-5
|
592 |
+
) * initial_std # Scale back to original magnitude
|
593 |
+
|
594 |
+
print("\nFinal combined embedding stats:")
|
595 |
+
print(f"Mean: {input_embeds.mean():.3f}, Std: {input_embeds.std():.3f}")
|
596 |
+
print(f"Min: {input_embeds.min():.3f}, Max: {input_embeds.max():.3f}")
|
597 |
+
|
598 |
+
# Final safety check before generation
|
599 |
+
if torch.isnan(input_embeds).any() or torch.isinf(input_embeds).any():
|
600 |
+
raise ValueError("Critical: Found NaN/Inf values in embeddings before generation!")
|
601 |
+
|
602 |
+
# Generate output with additional error handling
|
603 |
+
try:
|
604 |
+
outputs = self.language_model.generate(
|
605 |
+
inputs_embeds=input_embeds,
|
606 |
+
attention_mask=attention_mask,
|
607 |
+
generation_config=generation_config,
|
608 |
+
output_hidden_states=output_hidden_states,
|
609 |
+
use_cache=True,
|
610 |
+
**generate_kwargs,
|
611 |
+
)
|
612 |
+
except RuntimeError as e:
|
613 |
+
if "probability tensor contains either `inf`" in str(e):
|
614 |
+
print("ERROR: Invalid probability distribution. Attempting recovery...")
|
615 |
+
# Try with more conservative generation settings
|
616 |
+
generate_kwargs["temperature"] = 1.0 # Reset temperature
|
617 |
+
generate_kwargs["top_p"] = 1.0 # Disable top_p
|
618 |
+
generate_kwargs["do_sample"] = False # Fall back to greedy
|
619 |
+
outputs = self.language_model.generate(
|
620 |
+
inputs_embeds=input_embeds,
|
621 |
+
attention_mask=attention_mask,
|
622 |
+
generation_config=generation_config,
|
623 |
+
output_hidden_states=output_hidden_states,
|
624 |
+
use_cache=True,
|
625 |
+
**generate_kwargs,
|
626 |
+
)
|
627 |
+
else:
|
628 |
+
raise
|
629 |
+
|
630 |
+
return outputs
|