Views
No views yet
| Unsloth supports | Free Notebooks | Performance | Memory use |
|---|---|---|---|
| Llama-3.2 (3B) | ▶️ Start on Colab | 2.4x faster | 58% less |
| Llama-3.2 (11B vision) | ▶️ Start on Colab | 2x faster | 60% less |
| Qwen2 VL (7B) | ▶️ Start on Colab | 1.8x faster | 60% less |
| Qwen2.5 (7B) | ▶️ Start on Colab | 2x faster | 60% less |
| Llama-3.1 (8B) | ▶️ Start on Colab | 2.4x faster | 58% less |
| Phi-3.5 (mini) | ▶️ Start on Colab | 2x faster | 50% less |
| Gemma 2 (9B) | ▶️ Start on Colab | 2.4x faster | 58% less |
| Mistral (7B) | ▶️ Start on Colab | 2.2x faster | 62% less |

1pip install transformers torch bitsandbytes accelerate pillow huggingface_hub
2pip install qwen-vl-utils[decord]==0.0.8 # For video support (recommended)
3# OR
4pip install qwen-vl-utils # Falls back to torchvision for video1import torch
2from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration, BitsAndBytesConfig
3from huggingface_hub import login
4import requests
5from PIL import Image
6from io import BytesIO
7
8# Login to Hugging Face with token
9# You need to use a valid token with access to the model
10token = "YOUR_HF_TOKEN" # Replace with your valid token
11login(token)
12
13# Configure quantization
14bnb_config = BitsAndBytesConfig(
15 load_in_4bit=True,
16 bnb_4bit_compute_dtype=torch.float16,
17 bnb_4bit_use_double_quant=True,
18 bnb_4bit_quant_type="nf4"
19)
20
21# Model ID
22model_id = "ABDALLALSWAITI/Qwen2.5-VL-7B-Instruct-unsloth-bnb-4bit-copy"
23
24# Load processor
25processor = AutoProcessor.from_pretrained(model_id, token=token)
26
27# Load model
28model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
29 model_id,
30 quantization_config=bnb_config,
31 device_map="auto",
32 token=token
33)
34
35# Process image from URL
36image_url = "https://i.pinimg.com/736x/69/cd/59/69cd59a5ee5e041aa00f088465befbad.jpg"
37response = requests.get(image_url)
38image = Image.open(BytesIO(response.content)).convert("RGB")
39
40# Create message according to Qwen2.5-VL format
41messages = [
42 {
43 "role": "user",
44 "content": [
45 {"type": "image", "image": image},
46 {"type": "text", "text": "Describe this image in detail."}
47 ]
48 }
49]
50
51# Process input
52text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
53inputs = processor(text=[text], images=[image], return_tensors="pt").to("cuda")
54
55# Generate response
56with torch.no_grad():
57 output_ids = model.generate(**inputs, max_new_tokens=200)
58
59 # Decode response
60 response = processor.batch_decode(
61 output_ids[:, inputs.input_ids.shape[1]:],
62 skip_special_tokens=True
63 )[0]
64
65print(response)1import torch
2import transformers
3from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration, BitsAndBytesConfig
4from huggingface_hub import login
5import requests
6from PIL import Image
7from io import BytesIO
8import gc
9import os
10
11# Login to Hugging Face with token
12token = "YOUR_HF_TOKEN" # Replace with your valid token
13login(token)
14
15# Set environment variables to optimize memory usage
16os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"
17
18def process_vision_info(messages):
19 """Process images and videos from messages"""
20 image_inputs = []
21 video_inputs = None
22
23 for message in messages:
24 if message["role"] == "user" and isinstance(message["content"], list):
25 for content in message["content"]:
26 if content["type"] == "image":
27 # Handle image from URL
28 if isinstance(content["image"], str) and content["image"].startswith("http"):
29 try:
30 response = requests.get(content["image"], timeout=10)
31 response.raise_for_status()
32 image = Image.open(BytesIO(response.content)).convert("RGB")
33 image_inputs.append(image)
34 except (requests.RequestException, IOError) as e:
35 print(f"Error loading image from URL: {e}")
36 # Handle base64 images
37 elif isinstance(content["image"], str) and content["image"].startswith("data:image"):
38 try:
39 import base64
40 # Extract base64 data after the comma
41 base64_data = content["image"].split(',')[1]
42 image_data = base64.b64decode(base64_data)
43 image = Image.open(BytesIO(image_data)).convert("RGB")
44 image_inputs.append(image)
45 except Exception as e:
46 print(f"Error loading base64 image: {e}")
47 # Handle local file paths
48 elif isinstance(content["image"], str) and content["image"].startswith("file://"):
49 try:
50 file_path = content["image"][7:] # Remove 'file://'
51 image = Image.open(file_path).convert("RGB")
52 image_inputs.append(image)
53 except Exception as e:
54 print(f"Error loading local image: {e}")
55 else:
56 print("Unsupported image format or source")
57
58 return image_inputs, video_inputs
59
60# Print versions for debugging
61print(f"Transformers version: {transformers.__version__}")
62print(f"PyTorch version: {torch.__version__}")
63print(f"CUDA available: {torch.cuda.is_available()}")
64if torch.cuda.is_available():
65 print(f"CUDA device: {torch.cuda.get_device_name(0)}")
66 print(f"CUDA memory allocated: {torch.cuda.memory_allocated(0)/1024**3:.2f} GB")
67 print(f"CUDA memory reserved: {torch.cuda.memory_reserved(0)/1024**3:.2f} GB")
68
69# Load the 4-bit quantized model from Unsloth
70model_id = "ABDALLALSWAITI/Qwen2.5-VL-7B-Instruct-unsloth-bnb-4bit-copy"
71try:
72 # Free GPU memory before loading
73 if torch.cuda.is_available():
74 torch.cuda.empty_cache()
75 gc.collect()
76
77 # Load the processor first (less memory intensive)
78 print("Loading processor...")
79 processor = AutoProcessor.from_pretrained(model_id, token=token)
80
81 # Configure quantization parameters
82 quantization_config = BitsAndBytesConfig(
83 load_in_4bit=True,
84 bnb_4bit_compute_dtype=torch.float16,
85 bnb_4bit_use_double_quant=True,
86 bnb_4bit_quant_type="nf4",
87 llm_int8_enable_fp32_cpu_offload=True
88 )
89
90 print("Loading model...")
91 # Try loading with GPU offloading enabled
92 try:
93 model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
94 model_id,
95 token=token,
96 device_map="auto",
97 quantization_config=quantization_config,
98 low_cpu_mem_usage=True,
99 )
100 print("Model loaded successfully with GPU acceleration")
101 except (ValueError, RuntimeError, torch.cuda.OutOfMemoryError) as e:
102 print(f"GPU loading failed: {e}")
103 print("Falling back to CPU-only mode")
104
105 # Clean up any partially loaded model
106 if 'model' in locals():
107 del model
108 torch.cuda.empty_cache()
109 gc.collect()
110
111 # Try again with CPU only
112 model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
113 model_id,
114 token=token,
115 device_map="cpu",
116 torch_dtype=torch.float32,
117 )
118 print("Model loaded on CPU successfully")
119
120 # Print model's device map if available
121 if hasattr(model, 'hf_device_map'):
122 print("Model device map:")
123 for module, device in model.hf_device_map.items():
124 print(f" {module}: {device}")
125
126 # Example message with an image
127 messages = [
128 {
129 "role": "user",
130 "content": [
131 {
132 "type": "image",
133 "image": "https://i.pinimg.com/736x/69/cd/59/69cd59a5ee5e041aa00f088465befbad.jpg",
134 },
135 {"type": "text", "text": "Describe this image in detail."},
136 ],
137 }
138 ]
139
140 # Process the messages
141 print("Processing input...")
142 text = processor.apply_chat_template(
143 messages, tokenize=False, add_generation_prompt=True
144 )
145 image_inputs, video_inputs = process_vision_info(messages)
146
147 # Check if we have valid image inputs
148 if not image_inputs:
149 raise ValueError("No valid images were processed")
150
151 # Prepare inputs for the model
152 inputs = processor(
153 text=[text],
154 images=image_inputs,
155 videos=video_inputs,
156 padding=True,
157 return_tensors="pt",
158 )
159
160 # Determine which device to use based on model's main device
161 if hasattr(model, 'hf_device_map'):
162 # Find the primary device (usually where the first transformer block is)
163 for key, device in model.hf_device_map.items():
164 if 'transformer.blocks.0' in key or 'model.embed_tokens' in key:
165 input_device = device
166 break
167 else:
168 # Default to first device in the map
169 input_device = next(iter(model.hf_device_map.values()))
170 else:
171 # If not distributed, use the model's device
172 input_device = next(model.parameters()).device
173
174 print(f"Using device {input_device} for inputs")
175 inputs = {k: v.to(input_device) for k, v in inputs.items()}
176
177 # Generate the response
178 print("Generating response...")
179 with torch.no_grad():
180 generation_config = {
181 "max_new_tokens": 256,
182 "do_sample": True,
183 "temperature": 0.7,
184 "top_p": 0.9,
185 }
186 generated_ids = model.generate(**inputs, **generation_config)
187
188 # Process the output
189 generated_ids_trimmed = [
190 out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids)
191 ]
192 output_text = processor.batch_decode(
193 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
194 )
195
196 # Print the response
197 print("\nModel response:")
198 print(output_text[0])
199except Exception as e:
200 import traceback
201 print(f"An error occurred: {e}")
202 print(traceback.format_exc())
203finally:
204 # Clean up
205 if torch.cuda.is_available():
206 torch.cuda.empty_cache()1processor = AutoProcessor.from_pretrained(
2 model_id,
3 token=token,
4 min_pixels=256*28*28, # Lower bound
5 max_pixels=1280*28*28 # Upper bound
6)1model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
2 model_id,
3 token=token,
4 torch_dtype=torch.bfloat16,
5 attn_implementation="flash_attention_2",
6 device_map="auto",
7 quantization_config=bnb_config
8)torch.cuda.empty_cache() and gc.collect() before and after using the modelos.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"low_cpu_mem_usage=True when loading the modelmax_new_tokens based on your needs (lower values use less memory)1generation_config = {
2 "max_new_tokens": 256,
3 "do_sample": True,
4 "temperature": 0.7,
5 "top_p": 0.9,
6}1messages = [
2 {
3 "role": "user",
4 "content": [
5 {"type": "image", "image": "url_to_image1"},
6 {"type": "image", "image": "url_to_image2"},
7 {"type": "text", "text": "Compare these two images."}
8 ]
9 }
10]