forked from maybleMyers/chromaforge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvlm.py
More file actions
1392 lines (1169 loc) · 51.8 KB
/
vlm.py
File metadata and controls
1392 lines (1169 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
VLM Chat Interface for Qwen Vision-Language Models
A standalone GUI for interacting with Qwen VL models using images, videos, and text.
"""
import os
import sys
# NOTE: cpu_offload_gb was removed in vLLM 0.11.0 (V0 engine deprecated)
# For large models, use: quantization (AWQ/GPTQ), tensor parallelism, or transformers backend
import gc
import argparse
import tempfile
import time
from pathlib import Path
from typing import Optional, List, Tuple, Dict, Any
import torch
import gradio as gr
from gradio import themes
from gradio.themes.utils import colors
from PIL import Image
# Try to import video processing utilities
try:
import cv2
CV2_AVAILABLE = True
except ImportError:
CV2_AVAILABLE = False
print("Warning: opencv-python not installed. Video support will be limited.")
# vLLM will be imported lazily to allow setting VLLM_USE_V1 before import
VLLM_AVAILABLE = False
LLM = None
SamplingParams = None
def _check_vllm_available():
"""Check if vLLM can be imported (without actually importing it)."""
try:
import importlib.util
spec = importlib.util.find_spec("vllm")
return spec is not None
except Exception:
return False
def _import_vllm():
"""Import vLLM (V0/V1 engine is determined by env var set at startup)."""
global VLLM_AVAILABLE, LLM, SamplingParams
try:
from vllm import LLM as _LLM, SamplingParams as _SamplingParams
LLM = _LLM
SamplingParams = _SamplingParams
VLLM_AVAILABLE = True
print("vLLM loaded successfully")
return True
except ImportError as e:
VLLM_AVAILABLE = False
print(f"Warning: vLLM not available. Install with: pip install vllm>=0.11.0")
print(f" Import error: {e}")
return False
except Exception as e:
VLLM_AVAILABLE = False
print(f"Warning: vLLM import failed: {e}")
return False
# Check if vLLM is available (but don't import yet)
_VLLM_CAN_IMPORT = _check_vllm_available()
if _VLLM_CAN_IMPORT:
print("vLLM detected, will be loaded when needed")
else:
print("Warning: vLLM not available. Install with: pip install vllm>=0.11.0")
# Try to import qwen-vl-utils for image processing
try:
from qwen_vl_utils import process_vision_info
QWEN_VL_UTILS_AVAILABLE = True
except ImportError:
QWEN_VL_UTILS_AVAILABLE = False
print("Warning: qwen-vl-utils not installed. Install with: pip install qwen-vl-utils")
# Default model paths (relative to models/LLM)
DEFAULT_MODELS = {
"Qwen3-VL-8B-Caption-V4.5": "models/LLM/Qwen3-VL-8B-Caption-V4.5",
"Qwen3-VL-4B-Instruct": "models/LLM/Qwen3-VL-4B-Instruct",
"Qwen3-VL-30B-A3B-Instruct": "models/LLM/Qwen3-VL-30B-A3B-Instruct",
}
def extract_video_frames(video_path: str, max_frames: int = 8, target_size: Tuple[int, int] = (448, 448)) -> List[Image.Image]:
"""
Extract frames from a video file for VLM processing.
Args:
video_path: Path to the video file
max_frames: Maximum number of frames to extract
target_size: Target size for frames (width, height)
Returns:
List of PIL Images
"""
if not CV2_AVAILABLE:
raise RuntimeError("opencv-python is required for video processing. Install with: pip install opencv-python")
frames = []
cap = cv2.VideoCapture(video_path)
try:
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames <= 0:
return frames
# Calculate frame indices to extract (evenly spaced)
if total_frames <= max_frames:
frame_indices = list(range(total_frames))
else:
frame_indices = [int(i * (total_frames - 1) / (max_frames - 1)) for i in range(max_frames)]
for idx in frame_indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if ret:
# Convert BGR to RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(frame_rgb)
# Resize to target size
pil_image = pil_image.resize(target_size, Image.Resampling.LANCZOS)
frames.append(pil_image)
finally:
cap.release()
return frames
class VLMManager:
"""Manages Qwen VL model loading, inference, and memory."""
def __init__(self, low_vram: bool = False, backend: str = "auto"):
"""
Initialize VLM Manager.
Args:
low_vram: Enable low VRAM mode for transformers backend
backend: "vllm", "transformers", or "auto" (vLLM if available, else transformers)
"""
self.model = None
self.processor = None
self.model_name = None
self.low_vram = low_vram
self.device = self._get_device()
# vLLM specific attributes
self.vllm_model = None
self.model_path = None
# Determine backend (use _VLLM_CAN_IMPORT since vLLM is lazily imported)
if backend == "auto":
self.backend = "vllm" if _VLLM_CAN_IMPORT else "transformers"
else:
self.backend = backend
if self.backend == "vllm" and not _VLLM_CAN_IMPORT:
print("Warning: vLLM requested but not available. Falling back to transformers.")
self.backend = "transformers"
print(f"VLM Backend: {self.backend}")
def _get_device(self) -> torch.device:
"""Get the best available device."""
if torch.cuda.is_available():
return torch.device("cuda")
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def get_available_models(self) -> List[str]:
"""Scan for available models in the models/LLM directory."""
models = []
llm_dir = Path("models/LLM")
if llm_dir.exists():
for item in llm_dir.iterdir():
if item.is_dir():
# Check if it looks like a valid model directory
if (item / "config.json").exists() or (item / "model.safetensors").exists():
models.append(item.name)
# Also check default paths
for name, path in DEFAULT_MODELS.items():
if Path(path).exists() and name not in models:
models.append(name)
return sorted(models) if models else ["No models found"]
def _detect_model_type(self, model_path: str) -> str:
"""Detect the model type from config.json."""
import json
config_path = Path(model_path) / "config.json"
if config_path.exists():
try:
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
model_type = config.get("model_type", "").lower()
# Check for MoE models first
if "moe" in model_type:
if "qwen3" in model_type:
return "qwen3_vl_moe"
# Then standard models
if "qwen3" in model_type:
return "qwen3_vl"
elif "qwen2_5" in model_type or "qwen2.5" in model_type:
return "qwen2_5_vl"
elif "qwen2" in model_type:
return "qwen2_vl"
except Exception as e:
print(f"Warning: Could not read config.json: {e}")
# Fallback to name-based detection
model_name_lower = Path(model_path).name.lower()
if "qwen3" in model_name_lower:
return "qwen3_vl"
elif "qwen2.5" in model_name_lower or "qwen2_5" in model_name_lower:
return "qwen2_5_vl"
return "qwen2_5_vl" # Default fallback
def _load_with_vllm(self, model_name: str, quantization: str = "none", cpu_offload: int = 0, progress=gr.Progress()) -> str:
"""Load model using vLLM backend for high-performance inference."""
global VLLM_AVAILABLE, LLM, SamplingParams
# NOTE: cpu_offload_gb was removed in vLLM 0.11.0 (V0 engine deprecated)
# For large models, use quantization or transformers backend
if cpu_offload > 0:
print(f"Warning: CPU offload requested ({cpu_offload}GB) but not supported in vLLM 0.11.0+")
print(" Options: 1) pip install vllm==0.9.0 2) Use quantization 3) Use transformers backend")
# Import vLLM if not already imported
if not VLLM_AVAILABLE:
if not _VLLM_CAN_IMPORT:
return "vLLM is not available. Please install with: pip install vllm>=0.11.0"
if not _import_vllm():
return "Failed to import vLLM. Check console for errors."
# Check if already loaded
if self.vllm_model is not None and self.model_name == model_name:
return f"Model '{model_name}' is already loaded (vLLM)."
# Unload existing model first
if self.vllm_model is not None:
self.unload_model()
progress(0.1, desc="Loading model with vLLM...")
# Determine model path
if model_name in DEFAULT_MODELS:
model_path = DEFAULT_MODELS[model_name]
else:
model_path = f"models/LLM/{model_name}"
if not Path(model_path).exists():
return f"Model path not found: {model_path}"
try:
# Detect model type
model_type = self._detect_model_type(model_path)
print(f"Detected model type: {model_type}")
progress(0.3, desc="Initializing vLLM engine...")
# Configure vLLM loading options
vllm_kwargs = {
"model": model_path,
"trust_remote_code": True,
"dtype": "bfloat16",
"max_model_len": 4096, # Adjust based on your VRAM
"gpu_memory_utilization": 0.9,
}
# NOTE: cpu_offload_gb removed in vLLM 0.11.0 - V0 engine deprecated
# To use CPU offload, downgrade: pip install vllm==0.9.0
# Handle quantization
if quantization == "4bit":
vllm_kwargs["quantization"] = "awq" # or "gptq" depending on model
print("Using AWQ 4-bit quantization with vLLM")
elif quantization == "8bit":
vllm_kwargs["quantization"] = "fp8"
print("Using FP8 quantization with vLLM")
# Enable multimodal for VL models
vllm_kwargs["limit_mm_per_prompt"] = {"image": 10, "video": 2}
progress(0.5, desc=f"Loading {model_type} with vLLM...")
self.vllm_model = LLM(**vllm_kwargs)
self.model_path = model_path
self.model_name = model_name
# Also load processor for chat template
from transformers import AutoProcessor
self.processor = AutoProcessor.from_pretrained(model_path)
progress(1.0, desc="Model loaded with vLLM!")
quant_info = f", {quantization}" if quantization != "none" else ""
return f"Successfully loaded '{model_name}' with vLLM ({model_type}{quant_info})"
except Exception as e:
import traceback
traceback.print_exc()
return f"Failed to load model with vLLM: {str(e)}"
def load_model(self, model_name: str, quantization: str = "none", use_flash_attn: bool = False, vram_buffer: int = 0, cpu_offload: int = 0, progress=gr.Progress()) -> str:
"""Load a Qwen VL model.
Args:
model_name: Name of the model to load
quantization: "none", "4bit", or "8bit"
use_flash_attn: Whether to use Flash Attention 2
vram_buffer: GB of VRAM to reserve (for loading large models)
cpu_offload: GB of model weights to offload to CPU (vLLM only)
progress: Gradio progress callback
"""
if model_name == "No models found":
return "No models available. Please download a model first."
# Use vLLM backend if selected
if self.backend == "vllm":
return self._load_with_vllm(model_name, quantization, cpu_offload, progress)
# Check if already loaded
if self.model is not None and self.model_name == model_name:
return f"Model '{model_name}' is already loaded."
# Unload existing model first
if self.model is not None:
self.unload_model()
progress(0.1, desc="Loading model...")
# Determine model path
if model_name in DEFAULT_MODELS:
model_path = DEFAULT_MODELS[model_name]
else:
model_path = f"models/LLM/{model_name}"
if not Path(model_path).exists():
return f"Model path not found: {model_path}"
try:
# Detect model type from config
model_type = self._detect_model_type(model_path)
print(f"Detected model type: {model_type}")
from transformers import AutoProcessor
progress(0.3, desc="Loading processor...")
self.processor = AutoProcessor.from_pretrained(model_path)
progress(0.5, desc=f"Loading model weights ({model_type})...")
# Select the correct model class based on detected type
if model_type == "qwen3_vl_moe":
from transformers import Qwen3VLMoeForConditionalGeneration as ModelClass
elif model_type == "qwen3_vl":
from transformers import Qwen3VLForConditionalGeneration as ModelClass
else:
from transformers import Qwen2_5_VLForConditionalGeneration as ModelClass
# Build loading kwargs
load_kwargs = {
"low_cpu_mem_usage": True,
}
# Configure quantization for faster inference with less VRAM
if quantization == "4bit":
try:
from transformers import BitsAndBytesConfig
load_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
)
# 4-bit models must use device_map for proper loading
load_kwargs["device_map"] = "auto"
print("Using 4-bit quantization (NF4)")
except ImportError:
print("Warning: bitsandbytes not installed, falling back to bfloat16")
load_kwargs["torch_dtype"] = torch.bfloat16
load_kwargs["device_map"] = "auto"
elif quantization == "8bit":
try:
from transformers import BitsAndBytesConfig
# Clear GPU memory before loading
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
load_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_8bit=True,
)
# Apply VRAM buffer if specified
if vram_buffer > 0 and torch.cuda.is_available():
total_mem_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
max_gpu = int(total_mem_gb - vram_buffer)
if max_gpu > 0:
load_kwargs["device_map"] = "auto"
load_kwargs["max_memory"] = {0: f"{max_gpu}GiB", "cpu": "100GiB"}
offload_dir = Path(tempfile.gettempdir()) / "vlm_offload"
offload_dir.mkdir(exist_ok=True)
load_kwargs["offload_folder"] = str(offload_dir)
print(f"Using 8-bit quantization (max GPU: {max_gpu}GB, buffer: {vram_buffer}GB)")
else:
load_kwargs["device_map"] = "auto"
print("Using 8-bit quantization...")
else:
load_kwargs["device_map"] = "auto"
print("Using 8-bit quantization...")
except ImportError as e:
print(f"Warning: bitsandbytes not installed, falling back to bfloat16")
load_kwargs["torch_dtype"] = torch.bfloat16
load_kwargs["device_map"] = "auto"
else:
load_kwargs["torch_dtype"] = torch.bfloat16
# Set device map based on low_vram setting
if self.low_vram:
load_kwargs["device_map"] = {"": self.device}
else:
load_kwargs["device_map"] = "auto"
# Use Flash Attention 2 if requested
if use_flash_attn:
load_kwargs["attn_implementation"] = "flash_attention_2"
print("Using Flash Attention 2")
self.model = ModelClass.from_pretrained(model_path, **load_kwargs)
self.model_name = model_name
progress(1.0, desc="Model loaded!")
quant_info = f", {quantization}" if quantization != "none" else ""
flash_info = ", flash_attn" if use_flash_attn else ""
return f"Successfully loaded '{model_name}' ({model_type}{quant_info}{flash_info})"
except Exception as e:
import traceback
traceback.print_exc()
return f"Failed to load model: {str(e)}"
def unload_model(self) -> str:
"""Unload the current model to free memory."""
# Check if any model is loaded (either vLLM or transformers)
if self.model is None and self.vllm_model is None:
return "No model is currently loaded."
model_name = self.model_name
backend_used = "vLLM" if self.vllm_model is not None else "transformers"
# Unload vLLM model
if self.vllm_model is not None:
del self.vllm_model
self.vllm_model = None
self.model_path = None
# Unload transformers model
if self.model is not None:
del self.model
self.model = None
# Clean up processor
if self.processor is not None:
del self.processor
self.processor = None
self.model_name = None
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return f"Unloaded '{model_name}' ({backend_used}) and freed memory."
def get_memory_info(self) -> str:
"""Get current GPU memory usage."""
if not torch.cuda.is_available():
return "CUDA not available"
allocated = torch.cuda.memory_allocated() / 1024**3
reserved = torch.cuda.memory_reserved() / 1024**3
total = torch.cuda.get_device_properties(0).total_memory / 1024**3
return f"GPU Memory: {allocated:.1f}GB allocated, {reserved:.1f}GB reserved, {total:.1f}GB total"
def _generate_with_vllm(
self,
messages: List[Dict[str, Any]],
max_new_tokens: int = 512,
temperature: float = 0.7,
top_p: float = 0.9,
top_k: int = 50,
repetition_penalty: float = 1.1,
video_max_frames: int = 8,
) -> str:
"""Generate a response using vLLM backend."""
if self.vllm_model is None:
return "Error: No vLLM model loaded."
try:
# Process messages to extract images and prepare for vLLM
images = []
processed_messages = []
for msg in messages:
if isinstance(msg.get("content"), list):
new_content = []
for item in msg["content"]:
if item.get("type") == "image" and "image" in item:
img = item["image"]
images.append(img)
# For vLLM, use placeholder in text
new_content.append({"type": "image"})
elif item.get("type") == "video" and "video" in item:
# Process video into frames
video_path = item["video"]
if isinstance(video_path, str) and os.path.exists(video_path):
try:
frames = extract_video_frames(video_path, max_frames=video_max_frames)
for frame in frames:
images.append(frame)
new_content.append({"type": "image"})
if frames:
new_content.append({"type": "text", "text": f"[The above {len(frames)} images are frames extracted from a video]"})
except Exception as e:
new_content.append({"type": "text", "text": f"[Video processing error: {str(e)}]"})
elif item.get("type") == "text":
new_content.append(item)
else:
new_content.append(item)
processed_messages.append({"role": msg["role"], "content": new_content})
else:
processed_messages.append(msg)
# Apply chat template using processor
text_input = self.processor.apply_chat_template(
processed_messages,
tokenize=False,
add_generation_prompt=True,
)
print(f"[vLLM Debug] Prompt preview: {text_input[:500]}...")
print(f"[vLLM Debug] Number of images: {len(images)}")
# Configure sampling parameters
sampling_params = SamplingParams(
max_tokens=max_new_tokens,
temperature=temperature if temperature > 0 else 0.001,
top_p=top_p,
top_k=top_k if top_k > 0 else -1,
repetition_penalty=repetition_penalty,
)
# Prepare multimodal inputs for vLLM
if images:
# Convert PIL images to format vLLM expects
mm_data = {"image": images}
inputs = {
"prompt": text_input,
"multi_modal_data": mm_data,
}
else:
inputs = {"prompt": text_input}
# Generate with timing
if torch.cuda.is_available():
torch.cuda.synchronize()
start_time = time.perf_counter()
outputs = self.vllm_model.generate([inputs], sampling_params=sampling_params)
if torch.cuda.is_available():
torch.cuda.synchronize()
end_time = time.perf_counter()
# Extract response
response = outputs[0].outputs[0].text
# Calculate throughput
num_generated_tokens = len(outputs[0].outputs[0].token_ids)
generation_time = end_time - start_time
tokens_per_sec = num_generated_tokens / generation_time if generation_time > 0 else 0
print(f"[vLLM Inference] Generated {num_generated_tokens} tokens in {generation_time:.2f}s ({tokens_per_sec:.2f} tok/s)")
# Clean up thinking tags if present
if "</think>" in response:
response = response.split("</think>")[-1].strip()
return response
except Exception as e:
import traceback
traceback.print_exc()
return f"Error during vLLM generation: {str(e)}"
@torch.inference_mode()
def generate(
self,
messages: List[Dict[str, Any]],
max_new_tokens: int = 512,
temperature: float = 0.7,
top_p: float = 0.9,
top_k: int = 50,
repetition_penalty: float = 1.1,
video_max_frames: int = 8,
) -> str:
"""Generate a response from the model."""
# Use vLLM backend if loaded
if self.vllm_model is not None:
return self._generate_with_vllm(
messages=messages,
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
top_k=top_k,
repetition_penalty=repetition_penalty,
video_max_frames=video_max_frames,
)
if self.model is None:
return "Error: No model loaded. Please load a model first."
try:
# Extract images and videos from messages, process videos into frames
images = []
processed_messages = []
for msg in messages:
if isinstance(msg.get("content"), list):
new_content = []
for item in msg["content"]:
if item.get("type") == "image" and "image" in item:
images.append(item["image"])
new_content.append({"type": "image", "image": item["image"]})
elif item.get("type") == "video" and "video" in item:
# Process video into frames
video_path = item["video"]
if isinstance(video_path, str) and os.path.exists(video_path):
try:
frames = extract_video_frames(video_path, max_frames=video_max_frames)
# Add each frame as an image
for frame in frames:
images.append(frame)
new_content.append({"type": "image", "image": frame})
# Add a note about video frames
if frames:
new_content.append({"type": "text", "text": f"[The above {len(frames)} images are frames extracted from a video]"})
except Exception as e:
new_content.append({"type": "text", "text": f"[Video processing error: {str(e)}]"})
else:
new_content.append({"type": "text", "text": "[Video file not found]"})
else:
new_content.append(item)
processed_messages.append({"role": msg["role"], "content": new_content})
else:
processed_messages.append(msg)
# Apply chat template
print(f"[Debug] Messages being sent to model: {len(processed_messages)} messages")
for i, msg in enumerate(processed_messages):
role = msg.get("role", "unknown")
content = msg.get("content", "")
if isinstance(content, str):
preview = content[:100] + "..." if len(content) > 100 else content
else:
preview = f"[{len(content)} content items]"
print(f" [{i}] {role}: {preview}")
text_input = self.processor.apply_chat_template(
processed_messages,
tokenize=False,
add_generation_prompt=True,
)
print(f"[Debug] Formatted prompt preview: {text_input[:500]}...")
# Process inputs
process_kwargs = {"text": [text_input], "padding": True, "return_tensors": "pt"}
if images:
process_kwargs["images"] = images
inputs = self.processor(**process_kwargs)
# Move to device
device = next(self.model.parameters()).device
inputs = {k: v.to(device) if hasattr(v, 'to') else v for k, v in inputs.items()}
# Generate with timing
input_len = inputs['input_ids'].shape[1]
if torch.cuda.is_available():
torch.cuda.synchronize()
start_time = time.perf_counter()
outputs = self.model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=temperature > 0,
temperature=temperature if temperature > 0 else 1.0,
top_p=top_p,
top_k=top_k,
repetition_penalty=repetition_penalty,
)
if torch.cuda.is_available():
torch.cuda.synchronize()
end_time = time.perf_counter()
# Calculate throughput
generated_ids = outputs[0][input_len:]
num_generated_tokens = len(generated_ids)
generation_time = end_time - start_time
tokens_per_sec = num_generated_tokens / generation_time if generation_time > 0 else 0
print(f"[Inference] Generated {num_generated_tokens} tokens in {generation_time:.2f}s ({tokens_per_sec:.2f} tok/s)")
response = self.processor.decode(generated_ids, skip_special_tokens=True)
# Clean up thinking tags if present
if "</think>" in response:
response = response.split("</think>")[-1].strip()
return response
except Exception as e:
import traceback
traceback.print_exc()
return f"Error during generation: {str(e)}"
# Global manager instance
vlm_manager: Optional[VLMManager] = None
def initialize_manager(low_vram: bool = False, backend: str = "auto"):
"""Initialize the global VLM manager."""
global vlm_manager
vlm_manager = VLMManager(low_vram=low_vram, backend=backend)
def switch_backend_handler(backend: str):
"""Handle backend switching from UI."""
global vlm_manager
if vlm_manager is not None:
# Unload current model first
vlm_manager.unload_model()
# Get current low_vram setting
low_vram = vlm_manager.low_vram if vlm_manager else False
# Reinitialize with new backend
vlm_manager = VLMManager(low_vram=low_vram, backend=backend)
return f"Switched to {vlm_manager.backend} backend"
def load_model_handler(model_name: str, quantization: str, use_flash_attn: bool, vram_buffer: int, cpu_offload: int, progress=gr.Progress()):
"""Handle model loading from UI."""
if vlm_manager is None:
return "Manager not initialized"
return vlm_manager.load_model(model_name, quantization, use_flash_attn, int(vram_buffer), int(cpu_offload), progress)
def unload_model_handler():
"""Handle model unloading from UI."""
if vlm_manager is None:
return "Manager not initialized"
return vlm_manager.unload_model()
def get_memory_handler():
"""Handle memory info request from UI."""
if vlm_manager is None:
return "Manager not initialized"
return vlm_manager.get_memory_info()
def chat_handler(
message: str,
history: List[Tuple[str, str]],
system_prompt: str,
image,
video,
max_tokens: int,
temperature: float,
top_p: float,
top_k: int,
repetition_penalty: float,
video_max_frames: int = 8,
auto_unload: bool = False,
):
"""Handle chat messages from UI."""
# Check if any model is loaded (either transformers or vLLM)
if vlm_manager is None or (vlm_manager.model is None and vlm_manager.vllm_model is None):
error_history = list(history)
error_history.append({"role": "user", "content": message})
error_history.append({"role": "assistant", "content": "Error: No model loaded. Please load a model first."})
return error_history, ""
# Build messages list for the model
messages = []
# Add system prompt if provided
if system_prompt.strip():
messages.append({"role": "system", "content": system_prompt})
# Add chat history (already in messages format for Gradio 5.x)
for msg in history:
if isinstance(msg, dict) and "role" in msg and "content" in msg:
# Extract text content for model
content = msg.get("content", "")
if isinstance(content, str):
messages.append({"role": msg["role"], "content": content})
elif isinstance(content, dict) and "path" in content:
# Skip file-only messages in history for model
continue
elif isinstance(content, list):
# Handle mixed content - extract text parts
text_parts = [c.get("text", "") for c in content if isinstance(c, dict) and c.get("type") == "text"]
if text_parts:
messages.append({"role": msg["role"], "content": " ".join(text_parts)})
# Build current message content for the model
model_content = []
if image is not None:
model_content.append({"type": "image", "image": image})
if video is not None:
model_content.append({"type": "video", "video": video})
model_content.append({"type": "text", "text": message})
messages.append({"role": "user", "content": model_content})
# Generate response
response = vlm_manager.generate(
messages=messages,
max_new_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
top_k=top_k,
repetition_penalty=repetition_penalty,
video_max_frames=video_max_frames,
)
# Build display content for chatbot (Gradio 5.x messages format)
# Format: [{"role": "user", "content": ...}, {"role": "assistant", "content": ...}]
new_history = list(history)
if image is not None:
# Save image to temp file for display
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, f"vlm_chat_{id(image)}.png")
image.save(temp_path)
# Add user message with image and text
if message:
new_history.append({"role": "user", "content": [{"type": "text", "text": message}, {"type": "image", "path": temp_path}]})
else:
new_history.append({"role": "user", "content": [{"type": "text", "text": "[Describe this image]"}, {"type": "image", "path": temp_path}]})
new_history.append({"role": "assistant", "content": response})
elif video is not None:
# Add user message with video and text
if message:
new_history.append({"role": "user", "content": [{"type": "text", "text": message}, {"type": "video", "path": video}]})
else:
new_history.append({"role": "user", "content": [{"type": "text", "text": "[Describe this video]"}, {"type": "video", "path": video}]})
new_history.append({"role": "assistant", "content": response})
else:
new_history.append({"role": "user", "content": message})
new_history.append({"role": "assistant", "content": response})
# Auto-unload if requested
status_msg = ""
if auto_unload and vlm_manager.model is not None:
status_msg = vlm_manager.unload_model()
return new_history, status_msg
def clear_chat_handler():
"""Clear chat history."""
return []
def batch_caption_handler(
folder_path: str,
prompt: str,
system_prompt: str,
max_tokens: int,
temperature: float,
top_p: float,
top_k: int,
repetition_penalty: float,
progress=gr.Progress(),
):
"""Process a folder of images and generate captions."""
if vlm_manager is None or vlm_manager.model is None:
return "Error: No model loaded. Please load a model first."
if not folder_path or not os.path.isdir(folder_path):
return f"Error: Invalid folder path: {folder_path}"
# Supported image extensions
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
# Find all images in folder
image_files = []
for f in os.listdir(folder_path):
ext = os.path.splitext(f)[1].lower()
if ext in image_extensions:
image_files.append(f)
if not image_files:
return f"No images found in {folder_path}"
results = []
total = len(image_files)
for i, filename in enumerate(image_files):
progress((i / total), desc=f"Processing {filename}...")
image_path = os.path.join(folder_path, filename)
try:
# Load image
img = Image.open(image_path).convert("RGB")
# Build messages
messages = []
if system_prompt.strip():
messages.append({"role": "system", "content": system_prompt})
content = [
{"type": "image", "image": img},
{"type": "text", "text": prompt},
]
messages.append({"role": "user", "content": content})
# Generate caption
caption = vlm_manager.generate(
messages=messages,
max_new_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
top_k=top_k,
repetition_penalty=repetition_penalty,
)
# Save caption to .txt file
base_name = os.path.splitext(filename)[0]
txt_path = os.path.join(folder_path, f"{base_name}.txt")
with open(txt_path, "w", encoding="utf-8") as f:
f.write(caption)
results.append(f"[OK] {filename} -> {base_name}.txt")
except Exception as e:
results.append(f"[ERROR] {filename}: {str(e)}")
progress(1.0, desc="Complete!")
return f"Processed {total} images:\n\n" + "\n".join(results)
def create_ui():
"""Create the Gradio interface."""
available_models = vlm_manager.get_available_models() if vlm_manager else ["Manager not initialized"]
# Theme for Gradio 5.x
global vlm_theme, vlm_css
vlm_theme = themes.Default(
primary_hue=colors.Color(
name="custom",
c50="#E6F0FF",
c100="#CCE0FF",
c200="#99C1FF",
c300="#66A3FF",
c400="#3384FF",
c500="#0060df",
c600="#0052C2",
c700="#003D91",
c800="#002961",
c900="#001430",
c950="#000A18"
)
)
vlm_css = """