-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtransformers_api.py
1408 lines (1199 loc) · 67.6 KB
/
transformers_api.py
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
# transformers_api.py
from transformers import (
Qwen2VLForConditionalGeneration,
Qwen2VLProcessor,
Qwen2_5_VLForConditionalGeneration,
Qwen2_5_VLProcessor,
AutoConfig,
AutoModelForCausalLM,
AutoProcessor,
BitsAndBytesConfig,
GenerationConfig,
StoppingCriteria,
StoppingCriteriaList,
set_seed,
AutoTokenizer,
)
from qwen_vl_utils import process_vision_info
from typing import List, Union, Optional, Dict, Any
from PIL import Image
from io import BytesIO
import base64
import torch
import logging
import os
import re
import gc
import time
from folder_paths import models_dir
from unittest.mock import patch
from transformers.dynamic_module_utils import get_imports
import json
import importlib
import importlib.util
import comfy.model_management as mm
from torchvision.transforms import functional as TF
import numpy as np
import tempfile
import shutil
import sys
import glob
from importlib.machinery import SourceFileLoader
import traceback
# Configure basic logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("IF_LLM.transformers_api")
try:
import psutil
except ImportError:
psutil = None
try:
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
AutoProcessor,
StoppingCriteria,
StoppingCriteriaList,
TextIteratorStreamer
)
except ImportError:
logging.warning("Transformers not installed, some functionality may be limited")
try:
# Try to import qwen_vl_utils for better AWQ compatibility
import qwen_vl_utils
except ImportError:
logging.warning("qwen_vl_utils not found. Some AWQ models might not load correctly.")
class TransformersModelManager:
def __init__(self):
"""Initialize the TransformersModelManager"""
# Set up paths and model configurations
self.models_dir = models_dir
self.llm_path = os.path.join(self.models_dir, "LLM")
# Create the LLM directory if it doesn't exist
os.makedirs(self.llm_path, exist_ok=True)
# Set model load arguments
self.model_load_args = {
"device_map": "auto",
"torch_dtype": torch.float16
}
# Model tracking
self.loaded_models = {}
self.current_model_name = None
self.current_model_type = None
self.last_model_usage = 0
# Configure model paths
self.configure_model_paths()
def configure_model_paths(self):
"""Set up paths for different model types"""
# Models configuration
self.model_configs = {
"Qwen/QwQ-32B-AWQ": {
"model_type": "awq",
"processor_type": "auto",
"hf_repo": "Qwen/QwQ-32B-AWQ",
"local_dir": os.path.join(self.models_dir, "LLM", "QwQ-32B-AWQ"),
"min_vram_gb": 20, # This model really needs at least this much VRAM
"recommended_vram_gb": 24, # Ideally it would have this much
"supports_vision": False,
"context_length": 32768,
"requires_autoawq": True
},
"Qwen/Qwen2.5-VL-3B-Instruct-AWQ": {
"model_type": "qwen2_5_vl",
"processor_type": "qwen2_5_vl",
"hf_repo": "Qwen/Qwen2.5-VL-3B-Instruct-AWQ",
"local_dir": os.path.join(self.models_dir, "LLM", "Qwen2.5-VL-3B-Instruct-AWQ"),
"min_vram_gb": 4,
"recommended_vram_gb": 8,
"supports_vision": True,
"context_length": 32768,
"requires_autoawq": True
},
"Qwen/Qwen2.5-VL-7B-Instruct-AWQ": {
"model_type": "qwen2_5_vl",
"processor_type": "qwen2_5_vl",
"hf_repo": "Qwen/Qwen2.5-VL-7B-Instruct-AWQ",
"local_dir": os.path.join(self.models_dir, "LLM", "Qwen2.5-VL-7B-Instruct-AWQ"),
"min_vram_gb": 8,
"recommended_vram_gb": 12,
"supports_vision": True,
"context_length": 32768,
"requires_autoawq": True
},
"Qwen/Qwen2.5-7B-Instruct": {
"model_type": "auto",
"processor_type": "auto",
"hf_repo": "Qwen/Qwen2.5-7B-Instruct",
"local_dir": os.path.join(self.models_dir, "LLM", "Qwen2.5-7B-Instruct"),
"min_vram_gb": 14,
"recommended_vram_gb": 16,
"supports_vision": False,
"context_length": 32768,
"requires_autoawq": False
},
"Qwen/Qwen2.5-VL-7B-Instruct": {
"model_type": "qwen2_5_vl",
"processor_type": "qwen2_5_vl",
"hf_repo": "Qwen/Qwen2.5-VL-7B-Instruct",
"local_dir": os.path.join(self.models_dir, "LLM", "Qwen2.5-VL-7B-Instruct"),
"min_vram_gb": 16,
"recommended_vram_gb": 24,
"supports_vision": True,
"context_length": 32768,
"requires_autoawq": False
},
"Qwen/Qwen2.5-VL-3B-Instruct": {
"model_type": "qwen2_5_vl",
"processor_type": "qwen2_5_vl",
"hf_repo": "Qwen/Qwen2.5-VL-3B-Instruct",
"local_dir": os.path.join(self.models_dir, "LLM", "Qwen2.5-VL-3B-Instruct"),
"min_vram_gb": 6,
"recommended_vram_gb": 12,
"supports_vision": True,
"context_length": 32768,
"requires_autoawq": False
},
# Add other models as needed
}
def clean_memory(self):
"""Clean up memory to prepare for model loading or after use"""
try:
import gc
import torch
import logging
import time
start_time = time.time()
# Force garbage collection
gc.collect()
# Clear CUDA cache if available
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Log current VRAM usage for each GPU
for i in range(torch.cuda.device_count()):
allocated = torch.cuda.memory_allocated(i) / (1024 ** 3) # Convert to GB
reserved = torch.cuda.memory_reserved(i) / (1024 ** 3) # Convert to GB
logging.info(f"GPU {i}: Allocated {allocated:.2f} GB, Reserved {reserved:.2f} GB")
# Log RAM usage
try:
import psutil
ram_percent = psutil.virtual_memory().percent
logging.info(f"RAM usage: {ram_percent:.1f}%")
except ImportError:
logging.info("psutil not available, skipping RAM usage reporting")
elapsed = time.time() - start_time
logging.info(f"Memory cleaned in {elapsed:.2f} seconds")
except Exception as e:
logging.error(f"Error cleaning memory: {str(e)}")
return True
def ensure_model_downloaded(self, model_name):
"""Make sure the model is downloaded and available locally"""
try:
if model_name not in self.model_configs:
logging.error(f"Model {model_name} not found in configurations")
return False
model_config = self.model_configs[model_name]
local_dir = model_config["local_dir"]
hf_repo = model_config["hf_repo"]
logging.info(f"Checking for model {model_name} at {local_dir}")
# Check if the model exists locally
if os.path.exists(local_dir) and os.path.isdir(local_dir):
logging.info(f"Model {model_name} found locally at {local_dir}")
# Check for config.json to verify it's a valid model directory
if os.path.exists(os.path.join(local_dir, "config.json")):
logging.info(f"Model {model_name} directory contains config.json, proceeding")
return True
else:
logging.warning(f"Model directory for {model_name} exists but may be incomplete (no config.json)")
# Continue to download to be safe
# Create the destination directory if it doesn't exist
os.makedirs(local_dir, exist_ok=True)
# Download model files from Hugging Face
logging.info(f"Downloading model {model_name} from {hf_repo} to {local_dir}...")
try:
# Use snapshot_download to download the full model repository
hf_token = os.environ.get("HUGGINGFACE_TOKEN", None)
if hf_token:
logging.info("Using Hugging Face token from environment")
else:
logging.info("No Hugging Face token found in environment")
snapshot_download(
repo_id=hf_repo,
local_dir=local_dir,
local_dir_use_symlinks=False,
token=hf_token
)
logging.info(f"Model {model_name} downloaded successfully to {local_dir}")
return True
except Exception as dl_error:
logging.error(f"Error downloading model {model_name}: {str(dl_error)}")
import traceback
logging.error(traceback.format_exc())
return False
except Exception as e:
logging.error(f"Error ensuring model download for {model_name}: {str(e)}")
import traceback
logging.error(traceback.format_exc())
return False
def load_model(self, model_name):
"""Load a model and its processor by name"""
try:
import torch
from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM, AutoProcessor, BitsAndBytesConfig
import gc
import logging
logging.info(f"Attempting to load model: {model_name}")
# Clean up memory before loading new model
self.clean_memory()
# Check if model_name is in our configurations
if model_name not in self.model_configs:
logging.error(f"Model {model_name} not found in configurations. Available models: {list(self.model_configs.keys())}")
# Try fallback to direct model loading from Hugging Face
logging.info(f"Attempting fallback to direct model loading for: {model_name}")
try:
# For AWQ models
if "awq" in model_name.lower():
try:
# Instead of trying to import autoawq, use transformers directly
from transformers import AutoModelForCausalLM, AutoTokenizer
logging.info("Using transformers for AWQ model loading")
except ImportError:
logging.warning("Transformers not found. Please install with: pip install transformers")
return {"error": "Failed to load model: transformers package is required"}
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoTokenizer.from_pretrained(model_name)
else:
# Regular model
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoTokenizer.from_pretrained(model_name)
# Store model and processor
model_data = {
"model": model,
"processor": processor,
"supports_vision": True, # Force supports_vision to True for Qwen VL models
"context_length": 4096 # Default context length
}
self.loaded_models[model_name] = model_data
logging.info(f"Successfully loaded model directly: {model_name}")
return {"status": "success", "message": f"Model {model_name} loaded successfully via fallback"}
except Exception as fallback_error:
logging.error(f"Fallback loading failed: {str(fallback_error)}")
return {"error": f"Model {model_name} not found in configurations and fallback loading failed"}
model_config = self.model_configs[model_name]
logging.info(f"Found model configuration: {model_config}")
# Download or find the model locally
if not self.ensure_model_downloaded(model_name):
logging.error(f"Failed to download or locate model: {model_name}")
# Try direct loading as a fallback
try:
logging.info(f"Attempting direct loading from Hugging Face: {model_name}")
if model_config.get("requires_autoawq", False):
try:
# Instead of trying to import autoawq, use transformers directly
from transformers import AutoModelForCausalLM, AutoTokenizer
logging.info("Using transformers for AWQ model loading")
except ImportError:
logging.warning("Transformers not found. Please install with: pip install transformers")
return {"error": "Failed to load model: transformers package is required"}
if "qwen2_5_vl" in model_config.get("model_type", ""):
# Special handling for Qwen VL models - improved approach
logging.info(f"Loading Qwen VL AWQ model: {model_name}")
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
# Try to determine the best device configuration
device = "cuda:0" if torch.cuda.is_available() else "cpu"
logging.info(f"Using device: {device} for Qwen VL model")
# Set appropriate dtype
dtype = torch.float16
# Check if flash attention is available
can_use_flash_attn = False
if torch.cuda.is_available():
try:
from flash_attn import flash_attn_func
can_use_flash_attn = True
logging.info("Flash attention available, will use for better performance")
except ImportError:
pass
# Setup model loading parameters - similar to VideoPromptsNode
model_kwargs = {
"torch_dtype": dtype,
"trust_remote_code": True,
}
# Don't use device_map with AWQ models to avoid CPU offloading
# Just use the specific device
model_kwargs.pop("device_map", None)
# Add flash attention if available
if can_use_flash_attn:
model_kwargs["attn_implementation"] = "flash_attention_2"
# Load the model with better settings
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model_config.get("local_dir", model_config["hf_repo"]),
**model_kwargs
)
# Move to specific device to avoid CPU offloading with AWQ
if torch.cuda.is_available():
model = model.to(device)
# For processor, use standard settings as in VideoPromptsNode
processor = AutoProcessor.from_pretrained(
model_config.get("local_dir", model_config["hf_repo"]),
trust_remote_code=True
)
# Store model and processor
model_data = {
"model": model,
"processor": processor,
"supports_vision": True,
"context_length": model_config.get("context_length", 32768)
}
self.loaded_models[model_name] = model_data
logging.info(f"Successfully loaded Qwen VL model: {model_name}")
return model, processor
elif "qwen2-vl" in model_config.get("model_type", ""):
# Similar approach for Qwen2-VL models
logging.info(f"Loading Qwen2-VL AWQ model: {model_name}")
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
# Try to determine the best device configuration
device = "cuda:0" if torch.cuda.is_available() else "cpu"
logging.info(f"Using device: {device} for Qwen VL model")
# Set appropriate dtype
dtype = torch.float16
# Check if flash attention is available
can_use_flash_attn = False
if torch.cuda.is_available():
try:
from flash_attn import flash_attn_func
can_use_flash_attn = True
logging.info("Flash attention available, will use for better performance")
except ImportError:
pass
# Setup model loading parameters - similar to VideoPromptsNode
model_kwargs = {
"torch_dtype": dtype,
"trust_remote_code": True,
}
# Don't use device_map with AWQ models to avoid CPU offloading
# Just use the specific device
model_kwargs.pop("device_map", None)
# Add flash attention if available
if can_use_flash_attn:
model_kwargs["attn_implementation"] = "flash_attention_2"
# Load the model with better settings
model = Qwen2VLForConditionalGeneration.from_pretrained(
model_config.get("local_dir", model_config["hf_repo"]),
**model_kwargs
)
# Move to specific device to avoid CPU offloading with AWQ
if torch.cuda.is_available():
model = model.to(device)
# For processor, use standard settings as in VideoPromptsNode
processor = AutoProcessor.from_pretrained(
model_config.get("local_dir", model_config["hf_repo"]),
trust_remote_code=True
)
# Store model and processor
model_data = {
"model": model,
"processor": processor,
"supports_vision": True,
"context_length": model_config.get("context_length", 32768)
}
self.loaded_models[model_name] = model_data
logging.info(f"Successfully loaded Qwen VL model: {model_name}")
return model, processor
else:
# Default model loading if not a special case
logging.info(f"Loading model with standard transformers approach: {model_name}")
if model_config["model_type"] == "auto":
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoTokenizer.from_pretrained(model_path)
elif model_config["model_type"] == "vision":
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoProcessor.from_pretrained(model_path)
else:
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoTokenizer.from_pretrained(model_path)
# Store loaded model
model_data = {
"model": model,
"processor": processor,
"supports_vision": True, # Force supports_vision to True for Qwen VL models
"context_length": model_config.get("context_length", 4096)
}
self.loaded_models[model_name] = model_data
logging.info(f"Successfully loaded model: {model_name}")
return {"status": "success", "message": f"Model {model_name} loaded successfully"}
except Exception as e:
logging.error(f"Error loading model {model_name}: {str(e)}")
import traceback
logging.error(traceback.format_exc())
return {"error": f"Failed to load model: {str(e)}"}
# Use local path if available
model_path = model_config.get("local_dir", model_config["hf_repo"])
logging.info(f"Using model path: {model_path}")
# For AWQ models, we need to check and use autoawq
if model_config.get("requires_autoawq", False):
try:
logging.info(f"Model {model_name} requires AutoAWQ")
# Check for autoawq
try:
# Instead of trying to import autoawq, use transformers directly
from transformers import AutoModelForCausalLM, AutoTokenizer
logging.info("Using transformers for AWQ model loading")
except ImportError:
logging.warning("Transformers not found. Please install with: pip install transformers")
return {"error": "Failed to load model: transformers package is required"}
if "qwen2_5_vl" in model_config.get("model_type", ""):
# Special handling for Qwen VL models
logging.info(f"Loading Qwen VL AWQ model: {model_name}")
from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer
# For Qwen models use specific device mapping and dtype
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model_path,
device_map="cuda:0",
torch_dtype=torch.float16,
trust_remote_code=True
)
# Store model and processor
model_data = {
"model": model,
"processor": tokenizer,
"supports_vision": True, # Force supports_vision to True for Qwen VL models
"context_length": model_config.get("context_length", 4096)
}
self.loaded_models[model_name] = model_data
logging.info(f"Successfully loaded AWQ model: {model_name}")
return {"status": "success", "message": f"Model {model_name} loaded successfully"}
else:
# For other AWQ models
logging.info(f"Loading standard AWQ model: {model_name}")
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.float16
)
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Store model and processor
model_data = {
"model": model,
"processor": tokenizer,
"supports_vision": True, # Force supports_vision to True for Qwen VL models
"context_length": model_config.get("context_length", 4096)
}
self.loaded_models[model_name] = model_data
logging.info(f"Successfully loaded AWQ model: {model_name}")
return {"status": "success", "message": f"Model {model_name} loaded successfully"}
except Exception as e:
logging.error(f"Error loading AWQ model {model_name}: {str(e)}")
return {"error": f"Failed to load AWQ model: {str(e)}"}
# Default model loading if not a special case
logging.info(f"Loading model with standard transformers approach: {model_name}")
if model_config["model_type"] == "auto":
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoTokenizer.from_pretrained(model_path)
elif model_config["model_type"] == "vision":
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoProcessor.from_pretrained(model_path)
else:
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.float16
)
processor = AutoTokenizer.from_pretrained(model_path)
# Store loaded model
model_data = {
"model": model,
"processor": processor,
"supports_vision": True, # Force supports_vision to True for Qwen VL models
"context_length": model_config.get("context_length", 4096)
}
self.loaded_models[model_name] = model_data
logging.info(f"Successfully loaded model: {model_name}")
return {"status": "success", "message": f"Model {model_name} loaded successfully"}
except Exception as e:
logging.error(f"Error loading model {model_name}: {str(e)}")
import traceback
logging.error(traceback.format_exc())
return {"error": f"Failed to load model: {str(e)}"}
def process_frames(self, images_tensor, frame_sample_count=16, max_pixels=512*512):
"""
Process image frames for the model by sampling and resizing.
Similar to IF_VideoPromptsNode's implementation.
Args:
images_tensor: Input tensor in shape [B,H,W,C]
frame_sample_count: Number of frames to sample
max_pixels: Max pixels for each frame
Returns:
List of processed PIL images
"""
# Import required libraries
import math
from PIL import Image
import numpy as np
# Get the batch size (number of frames)
batch_size = images_tensor.shape[0]
# Sample the frames evenly from the batch
if batch_size <= frame_sample_count:
# Use all frames if we have fewer than requested
sampled_indices = list(range(batch_size))
else:
# Sample evenly across the frames
sampled_indices = [int(i * (batch_size - 1) / (frame_sample_count - 1)) for i in range(frame_sample_count)]
# Extract the sampled frames from the tensor
sampled_frames = [images_tensor[i] for i in sampled_indices]
# Convert to PIL images
pil_images = []
for frame in sampled_frames:
# Convert tensor to numpy
frame_np = frame.cpu().numpy()
# Scale from [0,1] to [0,255]
frame_np = (frame_np * 255).astype(np.uint8)
# Convert to PIL
pil_image = Image.fromarray(frame_np)
# Calculate resize dimensions if needed
if max_pixels > 0:
width, height = pil_image.size
if width * height > max_pixels:
scale = math.sqrt(max_pixels / (width * height))
new_width = int(width * scale)
new_height = int(height * scale)
pil_image = pil_image.resize((new_width, new_height), Image.LANCZOS)
pil_images.append(pil_image)
return pil_images
async def send_transformers_request(
self,
model_name: str,
user_prompt: str,
system_message: str = "",
messages: List[Dict[str, Any]] = None,
images: List[str] = None,
seed: int = 42,
random: bool = False,
max_tokens: int = 1024,
temperature: float = 0.7,
top_k: int = 40,
top_p: float = 0.9,
repeat_penalty: float = 1.1,
stop_string: str = "",
precision: str = "fp16",
attention: str = "sdpa",
keep_alive: bool = True,
**kwargs
) -> Dict[str, Any]:
"""
Process a request using the transformers library
"""
try:
import torch
from transformers import TextIteratorStreamer
import threading
import numpy as np
from PIL import Image # Re-import PIL.Image in this scope to avoid UnboundLocalError
# Set random seed if needed
if not random and seed != -1:
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# Load/reload model if needed
load_result = self.load_model(model_name)
if "error" in load_result:
return load_result
model_data = self.loaded_models.get(model_name)
if not model_data:
return {"error": f"Failed to access model data for {model_name}"}
model = model_data["model"]
processor = model_data["processor"]
supports_vision = model_data.get("supports_vision", False)
# Process images if available and model supports vision
pil_images = []
if images is not None and supports_vision:
# Check if images is a tensor, list, or other container with content
has_images = False
if isinstance(images, torch.Tensor):
has_images = images.nelement() > 0
elif isinstance(images, list) or isinstance(images, tuple):
has_images = len(images) > 0
else:
has_images = bool(images) # Only use direct boolean conversion for non-tensor types
if has_images:
logging.info(f"Processing images for vision model")
# Import these here to ensure they're available in this scope
from PIL import Image
import numpy as np
import io
import base64
# Handle different types of image inputs
if isinstance(images, torch.Tensor):
# If it's a tensor, convert each image to PIL
logging.info(f"Image tensor shape: {images.shape}")
# Determine tensor layout
if images.dim() == 4: # [batch, channels, height, width] or [batch, height, width, channels]
for i in range(images.shape[0]):
img_tensor = images[i]
# Check if [C, H, W] or [H, W, C] format
if images.shape[1] == 3 or images.shape[1] == 4: # [B, C, H, W]
# Convert from [C, H, W] to [H, W, C] for PIL
img_tensor = img_tensor.permute(1, 2, 0)
logging.info(f"Processing BCHW tensor, image {i}")
# else assume [B, H, W, C] format, which needs no permutation
# Ensure values are in 0-255 range and convert to uint8
img_np = img_tensor.cpu().numpy()
if img_np.max() <= 1.0:
img_np = (img_np * 255).astype(np.uint8)
else:
img_np = img_np.astype(np.uint8)
# Convert to PIL
pil_img = Image.fromarray(img_np)
pil_images.append(pil_img)
logging.info(f"Processed tensor image {i}: {pil_img.size}")
elif images.dim() == 3: # Single image [C, H, W] or [H, W, C]
img_tensor = images
# Check if [C, H, W] format and convert to [H, W, C]
if img_tensor.shape[0] == 3 or img_tensor.shape[0] == 4:
img_tensor = img_tensor.permute(1, 2, 0)
logging.info(f"Processing CHW tensor")
# else assume [H, W, C] format, which needs no permutation
# Ensure values are in 0-255 range and convert to uint8
img_np = img_tensor.cpu().numpy()
if img_np.max() <= 1.0:
img_np = (img_np * 255).astype(np.uint8)
else:
img_np = img_np.astype(np.uint8)
# Convert to PIL
pil_img = Image.fromarray(img_np)
pil_images.append(pil_img)
logging.info(f"Processed single tensor image: {pil_img.size}")
else:
# Original handling for string/base64 inputs or PIL images
for img_item in images:
try:
# Check if it's a numpy array
if isinstance(img_item, np.ndarray):
pil_image = Image.fromarray(img_item)
pil_images.append(pil_image)
logging.info(f"Processed numpy image: {pil_image.size}")
# Check if it's a base64 string
elif isinstance(img_item, str) and img_item.startswith("data:image"):
# Extract the base64 data
img_data = img_item.split(",")[1]
pil_image = Image.open(io.BytesIO(base64.b64decode(img_data)))
pil_images.append(pil_image)
logging.info(f"Processed base64 image: {pil_image.size}")
elif isinstance(img_item, Image.Image):
# Already a PIL image
pil_images.append(img_item)
logging.info(f"Processed PIL image: {img_item.size}")
# Handle torch tensor in list
elif isinstance(img_item, torch.Tensor):
if img_item.dim() == 3: # [C, H, W] or [H, W, C]
# Check if [C, H, W] format and convert to [H, W, C]
if img_item.shape[0] == 3 or img_item.shape[0] == 4:
img_tensor = img_item.permute(1, 2, 0)
else:
img_tensor = img_item
# Ensure values are in 0-255 range and convert to uint8
img_np = img_tensor.cpu().numpy()
if img_np.max() <= 1.0:
img_np = (img_np * 255).astype(np.uint8)
else:
img_np = img_np.astype(np.uint8)
# Convert to PIL
pil_img = Image.fromarray(img_np)
pil_images.append(pil_img)
logging.info(f"Processed tensor from list: {pil_img.size}")
else:
logging.warning(f"Unsupported image format: {type(img_item)}")
except Exception as e:
logging.error(f"Error processing image: {e}")
continue
# Construct conversation messages
chat_messages = self.construct_messages(model_name, system_message, user_prompt, messages, pil_images)
# Generate model inputs
if "qwen2.5-vl" in model_name.lower() and pil_images:
try:
logging.info(f"Using approach inspired by VideoPromptsNode for Qwen2.5-VL")
# Memory cleanup
import gc
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Force model to CUDA:0 for ComfyUI compatibility
device = "cuda:0" if torch.cuda.is_available() else "cpu"
# First, ensure we have the correct processor
from transformers import AutoProcessor
# Make sure we explicitly create the processor from the model path
processor = AutoProcessor.from_pretrained(
model.name_or_path,
trust_remote_code=True
)
# Prepare the prompt text
prompt_text = "Analyze this image and describe what you see in detail."
if system_message:
# Add the system message to instruct the model
system_content = system_message
else:
system_content = "You are a helpful assistant that analyzes images and provides detailed descriptions."
# If there's a user prompt, use it instead of the default
if user_prompt and user_prompt.strip():
prompt_text = user_prompt
# Handle multiple frames/images and limit to a reasonable number
# If we have more than 16 images, sample them evenly
max_frame_count = 16 # Limit to 16 frames to avoid VRAM issues
if len(pil_images) > max_frame_count:
logging.info(f"Found {len(pil_images)} images, sampling down to {max_frame_count}")
# Convert pil_images to tensor format if needed for processing
if hasattr(pil_images, 'shape') and len(pil_images.shape) == 4:
# Already a tensor
processed_images = self.process_frames(pil_images, max_frame_count)
else:
# Already list of PIL images, sample manually
if len(pil_images) <= max_frame_count:
processed_images = pil_images
else:
# Sample evenly
indices = [int(i * (len(pil_images) - 1) / (max_frame_count - 1)) for i in range(max_frame_count)]
processed_images = [pil_images[i] for i in indices]
else:
processed_images = pil_images
# Format as a chat with proper message structure - this is key
# This is how the VideoPromptsNode handles it
messages = [
{"role": "system", "content": system_content},
{"role": "user", "content": []}
]
# Add images to the user message - this approach is crucial
for img in processed_images:
messages[1]["content"].append({"type": "image", "image": img})
# Add the text part of the user message
messages[1]["content"].append({"type": "text", "text": prompt_text})
# Use apply_chat_template to format messages - just like VideoPromptsNode
chat_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
logging.info(f"Created chat template with length: {len(chat_text)}")
# Extract images for processing
image_inputs = [item["image"] for item in messages[1]["content"] if "type" in item and item["type"] == "image"]
# Process exactly like VideoPromptsNode
inputs = processor(text=[chat_text], images=image_inputs, return_tensors="pt")
# Move to the right device
inputs = inputs.to(device)
model.to(device)
# Log input shapes for debugging
logging.info(f"Input keys: {inputs.keys()}")
for key in inputs:
if isinstance(inputs[key], torch.Tensor):
logging.info(f"{key} shape: {inputs[key].shape}, device: {inputs[key].device}")
# Set seed if needed
if not random and seed is not None:
torch.manual_seed(seed)
np.random.seed(seed)
# Generate with parameters directly without all the special processing
logging.info(f"Starting model.generate()")
# Use the exact same generation approach as VideoPromptsNode
with torch.no_grad():
outputs = model.generate(
**inputs,
do_sample=random or temperature > 0.01,
temperature=max(0.01, temperature),
max_new_tokens=max_tokens,
top_k=top_k if random else 50,
top_p=top_p if random else 1.0,
repetition_penalty=repeat_penalty if repeat_penalty > 1.0 else None
)
# Decode exactly like VideoPromptsNode
generated_text = processor.batch_decode(
outputs[:, inputs.input_ids.shape[1]:],
skip_special_tokens=True
)[0]
logging.info(f"Generated response of length {len(generated_text)}")
# Clean up memory explicitly
del inputs
del outputs
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Clean up if not keeping the model alive
if not keep_alive:
self.unload_model(model_name)
return {
"status": "success",
"response": generated_text,
"model": model_name
}
except Exception as gen_error:
logging.error(f"Error during generation: {gen_error}")
import traceback
logging.error(traceback.format_exc())
# Clean up memory on error
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
return {"error": f"Failed to generate response with Qwen2.5-VL: {str(gen_error)}"}
elif "qwen2-vl" in model_name.lower() and pil_images:
try:
logging.info(f"Using approach inspired by VideoPromptsNode for Qwen2-VL")