Last Updated on 29/11/2026 by Eran Feit
Learning how to fine tune Qwen3 VL unlocks one of the most practical breakthroughs in modern computer vision: teaching a lightweight multimodal model to extract structured JSON coordinates directly from custom images on consumer hardware. In this step-by-step Python tutorial, we build a complete, end-to-end training and inference pipeline around Qwen3-VL-2B-Instruct using PyTorch, Hugging Face Transformers, and Low-Rank Adaptation (LoRA). Instead of relying on expensive multi-GPU cloud clusters, you will configure every piece of the workflow to run smoothly on an 8GB VRAM GPU.
Most vision-language model guides skip the messy engineering details that actually cause Out-Of-Memory (OOM) crashes or broken training loss curves on local machines. Rather than feeding raw high-resolution images directly into VRAM or relying on black-box wrappers, this hands-on pipeline gives you full control over pixel token budgets, conversation formatting, and token-level loss masking. Whether you are building document parsers, retail shelf scanners, or automated nutrition label extractors, mastering these memory-saving techniques lets you adapt state-of-the-art Vision AI to your own domain data without breaking your hardware budget.
To accomplish this, the tutorial is divided into three modular Python scripts that take you from raw Hugging Face data to visual bounding-box predictions. First, you will convert a real-world nutrition table dataset into local RGB JPEGs and Qwen-compatible JSONL chat templates with normalized [0..1000] bounding boxes. Next, you will attach lightweight PEFT LoRA adapters across the attention and MLP projection layers, build a custom collate_fn using qwen_vl_utils for on-the-fly image loading, and mask <|image_pad|> tokens so SFTTrainer computes gradients strictly on the assistant’s JSON output. Finally, you will load your saved adapter weights to run deterministic inference and render dynamic bounding boxes onto validation images with OpenCV and Supervision.
By the end of this guide, you will have a reusable, production-ready codebase to fine tune Qwen3 VL on any custom object detection or structured extraction dataset. You will understand not only which hyperparameters keep an 8GB GPU stable during bfloat16 training, but also how image resolution bounds, gradient accumulation, and prompt consistency work together to turn a general-purpose Vision-Language Model into a specialized data extraction engine.
Why Should You Fine Tune Qwen3 VL Instead of Using a Traditional Object Detector? When you fine tune Qwen3 VL , you replace rigid, fixed-class bounding box predictors with a flexible Vision-Language Model capable of following natural-language instructions and outputting structured JSON schemas. Traditional detectors like YOLO or Faster R-CNN require retraining a fixed classification head whenever your label taxonomy changes, and they struggle when a task demands contextual reasoning—such as distinguishing a small energy badge from a full nutrition panel based on surrounding text. Because Qwen3-VL-2B-Instruct combines a dynamic-resolution vision encoder with a 2-billion-parameter language backbone, it understands spatial layout, embedded text, and visual hierarchy simultaneously.
At a high level, the target of this fine-tuning process is structured visual grounding . Rather than updating all 2.1 billion parameters in the base network, LoRA freezes the pre-trained weights and injects small, trainable low-rank matrices (r=8, lora_alpha=16) into the model’s linear projection layers (q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, and down_proj). This reduces trainable parameters to roughly 0.4% of the total model size, allowing you to train in bfloat16 precision with gradient checkpointing inside an 8GB VRAM envelope while preserving the base model’s general visual knowledge.
During training, each image is dynamically resized between MIN_PIXELS (256 * 32 * 32) and MAX_PIXELS (640 * 32 * 32) and converted into visual tokens interleaved with your text prompt. A custom data collator masks both padding tokens and <|image_pad|> tokens with -100 in the target labels, forcing the cross-entropy loss function to optimize exclusively on the target JSON array containing bbox_2d coordinates and class names. Once trained, the resulting LoRA adapter weights are only a few dozen megabytes on disk and can be merged or loaded on demand for fast local inference.
Pipeline Stage Core Component / Script Primary Technical Goal 1. Data Preparation Step1-prepare_dataset.pyConvert Hugging Face records into local JPEGs and Qwen chat JSONL files with [0..1000] coordinates. 2. Model & LoRA Setup Step2-train_qwen3_vl.pyLoad Qwen3-VL-2B-Instruct and attach PEFT LoRA adapters to attention and MLP layers. 3. Multimodal Collator collate_fn + qwen_vl_utilsFormat chat templates, load images on the fly, and mask non-assistant tokens. 4. Visual Inference Step3-inference_nutrition.pyLoad saved LoRA weights, generate deterministic JSON boxes, and draw labels with supervision.
How to Train Custom Vision AI on Consumer GPUs (Qwen3-VL-2B LoRA Tutorial) 11 Building a Complete Qwen3-VL Fine-Tuning Pipeline for Structured JSON Detection How Does This Three-Script Python Architecture Turn Raw Images into Structured JSON Predictions? The codebase bridges data formatting, low-VRAM LoRA adaptation, and deterministic visual inference across three sequential Python files (Step1-prepare_dataset.py, Step2-train_qwen3_vl.py, and Step3-inference_nutrition.py). Instead of treating a Vision-Language Model as a black box, the pipeline explicitly converts standard bounding-box annotations into Qwen conversational JSONL records, restricts visual token memory with custom pixel bounds during SFTTrainer optimization, and parses the model’s generated JSON arrays back into pixel-accurate bounding boxes for OpenCV and Supervision rendering.
At the heart of this tutorial is a clear, modular workflow designed to teach Qwen/Qwen3-VL-2B-Instruct how to locate specific visual regions—such as nutrition tables, energy blocks, and nutrient text—and emit valid JSON coordinates without exhausting consumer GPU memory. In Step1-prepare_dataset.py, the code pulls the openfoodfacts/nutrition-table-detection dataset from Hugging Face, saves each image locally as an RGB JPEG to avoid holding thousands of decoded tensors in system RAM, and normalizes every bounding box from [y_min, x_min, y_max, x_max] floats into Qwen’s native [x1, y1, x2, y2] integer grid spanning 0 to 1000. Each sample is wrapped in a user-assistant chat turn so the model learns a strict prompt-to-JSON mapping from the very first epoch.
Once the train.jsonl and val.jsonl manifests are written to disk, Step2-train_qwen3_vl.py takes over to configure the vision processor and attach parameter-efficient LoRA adapters. By setting MIN_PIXELS = 256 * 32 * 32 and MAX_PIXELS = 640 * 32 * 32 inside AutoProcessor, the script keeps visual token sequences compact enough for an 8GB GPU while preserving label legibility. Rather than fine-tuning all two billion base parameters, LoraConfig injects rank-8 (r=8, lora_alpha=16) trainable matrices across both the attention projections (q_proj, k_proj, v_proj, o_proj) and MLP layers (gate_proj, up_proj, down_proj).
To prevent the training loop from wasting compute on prompt instructions or visual embeddings, a custom collate_fn pairs qwen_vl_utils.process_vision_info with explicit token masking. Every padding token and <|image_pad|> token in the labels tensor is replaced with -100, ensuring PyTorch calculates cross-entropy loss strictly against the assistant’s target JSON response. Combined with bfloat16 precision, gradient checkpointing, and a per_device_train_batch_size of 1 accumulated over 8 steps, SFTTrainer smoothly updates the adapter weights and saves a lightweight checkpoint ready for deployment.
Finally, Step3-inference_nutrition.py demonstrates how to put those saved LoRA weights to work on unseen validation images. The script loads the base Qwen3-VL-2B-Instruct model alongside the trained PeftModel adapter, feeds a random validation image with the exact same detection prompt used during preparation, and runs greedy decoding (do_sample=False) for deterministic JSON output. A regex parser extracts the bbox_2d coordinates, rescales them from the 0..1000 grid back to the original image dimensions, and uses supervision.BoxAnnotator and supervision.LabelAnnotator to draw dynamically scaled green bounding boxes onto the final output image.
Base Model vs. Fine-Tuned Qwen3-VL: Real-World Detection Results How to Train Custom Vision AI on Consumer GPUs (Qwen3-VL-2B LoRA Tutorial) 12 To see the real-world impact of fine-tuning, look at the side-by-side inference comparison on validation image above. On the left, the out-of-the-box Qwen3-VL-2B-Instruct base model produces noisy, imprecise predictions (4 detections total): it draws an oversized nutrition-table-text box across the entire packaging sleeve—including barcodes and unrelated text—and generates false positives by mistakenly flagging a plain pudding cup and a separate Snack Pack box on the lower shelf as nutrition labels. On the right, our fine-tuned LoRA model eliminates every single false positive and isolates the exact Nutrition Facts panel with a clean, tightly fitted green bounding box labeled nutrition-table (1 detection), proving how effectively targeted LoRA adaptation aligns a general Vision-Language Model to a specialized domain schema.
Link to the tutorial here
Download the code for the tutorial here or here
Link for Medium users here
Master Computer Vision
Follow my latest tutorials and AI insights on my
Personal Blog .
Beginner Complete CV Bootcamp
Foundation via PyTorch & TF.
Get Started → Interactive Deep Learning with PyTorch
Hands-on interactive practice.
Start Learning → Advanced Modern CV: GPT & OpenCV4
Vision GPT production models.
Go Advanced → How to Train Custom Vision AI on Consumer GPUs (Qwen3-VL-2B LoRA Tutorial) 13 Learning how to fine tune Qwen3 VL unlocks one of the most practical breakthroughs in modern computer vision: teaching a lightweight multimodal model to extract structured JSON coordinates directly from custom images on consumer hardware. In this step-by-step Python tutorial, we build a complete, end-to-end training and inference pipeline around Qwen3-VL-2B-Instruct using PyTorch, Hugging Face Transformers, and Low-Rank Adaptation (LoRA). Instead of relying on expensive multi-GPU cloud clusters, you will configure every piece of the workflow to run smoothly on an 8GB VRAM GPU.
Most vision-language model guides skip the messy engineering details that actually cause Out-Of-Memory (OOM) crashes or broken training loss curves on local machines. Rather than feeding raw high-resolution images directly into VRAM or relying on black-box wrappers, this hands-on pipeline gives you full control over pixel token budgets, conversation formatting, and token-level loss masking. Whether you are building document parsers, retail shelf scanners, or automated nutrition label extractors, mastering these memory-saving techniques lets you adapt state-of-the-art Vision AI to your own domain data without breaking your hardware budget.
To accomplish this, the tutorial is divided into three modular Python scripts that take you from raw Hugging Face data to visual bounding-box predictions. First, you will convert a real-world nutrition table dataset into local RGB JPEGs and Qwen-compatible JSONL chat templates with normalized [0..1000] bounding boxes. Next, you will attach lightweight PEFT LoRA adapters across the attention and MLP projection layers, build a custom collate_fn using qwen_vl_utils for on-the-fly image loading, and mask <|image_pad|> tokens so SFTTrainer computes gradients strictly on the assistant’s JSON output. Finally, you will load your saved adapter weights to run deterministic inference and render dynamic bounding boxes onto validation images with OpenCV and Supervision.
By the end of this guide, you will have a reusable, production-ready codebase to fine tune Qwen3 VL on any custom object detection or structured extraction dataset. You will understand not only which hyperparameters keep an 8GB GPU stable during bfloat16 training, but also how image resolution bounds, gradient accumulation, and prompt consistency work together to turn a general-purpose Vision-Language Model into a specialized data extraction engine.
Want the exact dataset so your results match mine? If you want to reproduce the same training flow and compare your results to mine, I can share the dataset structure and what I used in this tutorial. Send me an email and mention the name of this tutorial, so I know what you’re requesting.
🖥️ Email: feitgemel@gmail.com
Why Should You Fine Tune Qwen3 VL Instead of Using a Traditional Object Detector? When you fine tune Qwen3 VL , you replace rigid, fixed-class bounding box predictors with a flexible Vision-Language Model capable of following natural-language instructions and outputting structured JSON schemas. Traditional detectors like YOLO or Faster R-CNN require retraining a fixed classification head whenever your label taxonomy changes, and they struggle when a task demands contextual reasoning—such as distinguishing a small energy badge from a full nutrition panel based on surrounding text. Because Qwen3-VL-2B-Instruct combines a dynamic-resolution vision encoder with a 2-billion-parameter language backbone, it understands spatial layout, embedded text, and visual hierarchy simultaneously.
At a high level, the target of this fine-tuning process is structured visual grounding . Rather than updating all 2.1 billion parameters in the base network, LoRA freezes the pre-trained weights and injects small, trainable low-rank matrices (r=8, lora_alpha=16) into the model’s linear projection layers (q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, and down_proj). This reduces trainable parameters to roughly 0.4% of the total model size, allowing you to train in bfloat16 precision with gradient checkpointing inside an 8GB VRAM envelope while preserving the base model’s general visual knowledge.
During training, each image is dynamically resized between MIN_PIXELS (256 * 32 * 32) and MAX_PIXELS (640 * 32 * 32) and converted into visual tokens interleaved with your text prompt. A custom data collator masks both padding tokens and <|image_pad|> tokens with -100 in the target labels, forcing the cross-entropy loss function to optimize exclusively on the target JSON array containing bbox_2d coordinates and class names. Once trained, the resulting LoRA adapter weights are only a few dozen megabytes on disk and can be merged or loaded on demand for fast local inference.
Pipeline Stage Core Component / Script Primary Technical Goal 1. Data Preparation Step1-prepare_dataset.pyConvert Hugging Face records into local JPEGs and Qwen chat JSONL files with [0..1000] coordinates. 2. Model & LoRA Setup Step2-train_qwen3_vl.pyLoad Qwen3-VL-2B-Instruct and attach PEFT LoRA adapters to attention and MLP layers. 3. Multimodal Collator collate_fn + qwen_vl_utilsFormat chat templates, load images on the fly, and mask non-assistant tokens. 4. Visual Inference Step3-inference_nutrition.pyLoad saved LoRA weights, generate deterministic JSON boxes, and draw labels with supervision.
How Do You Build a Python Environment for Qwen3-VL Training? Which Exact Library Versions Prevent Dependency Clashes in WSL2 and CUDA 12.6? Locking transformers between 4.57.0 and 5.0.0, pairing PyTorch 2.6.0 with CUDA 12.6, and pinning numpy<2.0.0 alongside pyarrow<18.0.0 prevents the most common C++ ABI crashes and tokenizer incompatibilities when running multimodal SFTTrainer loops on Windows WSL2.
Before writing a single line of model code, you need an isolated Linux environment capable of communicating directly with your NVIDIA GPU. Running inside Windows Subsystem for Linux (WSL2) gives you native Linux file-system performance and full compatibility with bitsandbytes, trl, and PyTorch CUDA kernels without fighting Windows path limits. By creating a fresh Conda environment running Python 3.11 , you isolate your Vision-Language Model dependencies from any existing computer vision projects on your machine.
Next, verifying your local CUDA toolkit version with nvcc --version ensures your PyTorch wheel matches your system driver. Installing PyTorch 2.6.0 compiled for CUDA 12.6 provides native bfloat16 tensor core acceleration and stable scaled_dot_product_attention kernels required by Qwen3-VL’s dynamic vision encoder. Without matching CUDA wheels, training will either fall back to slow CPU execution or throw runtime library errors during backpropagation.
The second group of packages installs the core vision-language stack: transformers (>=4.57.0,<5.0.0), accelerate, and qwen-vl-utils. Because Qwen3-VL relies on recent architecture definitions introduced in late 4.57 releases—while major version 5.0 introduces breaking trainer API shifts—pinning that exact version range guarantees seamless loading of AutoModelForImageTextToText. Meanwhile, supervision, pillow, and opencv-python-headless prepare your environment for bounding-box coordinate parsing and visual rendering.
The final installation commands bring in the parameter-efficient training ecosystem: peft, bitsandbytes, trl, and datasets. Notice the explicit upper-bound pins on numpy<2.0.0, pandas<2.3.0, and pyarrow<18.0.0. NumPy 2.x frequently breaks older OpenCV and PyArrow binary wheels, so enforcing these exact bounds upfront saves hours of environment debugging before launching Visual Studio Code or Antigravity IDE.
# Open Powershell and run wsl for Linux ======================= wsl # create new anaconda env conda create - n qwen python = 3.11 conda activate qwen # Find the CUDA version installed on your system by running the following command: nvcc -- version # CUDA 12.6 pip install torch == 2.6 . 0 torchvision == 0.21 . 0 torchaudio == 2.6 . 0 -- index - url https : // download . pytorch . org / whl / cu126 # Install dependencies for qwen-vl-detection : pip install " transformers>=4.57.0,<5.0.0 " pip install " accelerate>=1.3.0 " pip install " qwen-vl-utils>=0.0.10 " pip install " supervision>=0.26.0 " pip install " pillow>=10.0.0 " pip install " opencv-python-headless<4.10 " " numpy<2.0.0 " " pandas<2.3.0 " # For the train : pip install " peft>=0.14.0 " pip install " bitsandbytes>=0.45.0 " pip install " trl>=0.14.0 " pip install " datasets>=3.2.0 " pip install " pyarrow<18.0.0 " " pandas<2.3.0 " " numpy<2.0.0 " pip install " datasets>=3.2.0,<4.0.0 " " trl>=0.14.0,<0.20.0 " " pyarrow<18.0.0 " " pandas<2.3.0 " " numpy<2.0.0 " #Run vscode or antigravity : code . antigravity - ide . With this isolated Conda environment active and all version constraints locked in, your workstation is ready to download datasets, stream multimodal batches, and fine-tune Qwen3-VL without library conflicts.
How Do You Convert Raw Hugging Face Bounding Boxes into Qwen3-VL JSONL Chat Format? Why Must Bounding Box Coordinates Be Converted from [y_min, x_min, y_max, x_max] Floats to [0..1000] Integers? Qwen3-VL is pre-trained to interpret and emit spatial coordinates on a normalized 0 to 1000 integer grid ordered horizontally first ([x1, y1, x2, y2]), whereas standard Hugging Face object detection datasets store normalized floats ordered vertically first ([y_min, x_min, y_max, x_max]).
When you fine tune Qwen3 VL for structured object detection, data formatting makes or breaks model convergence. In Step1-prepare_dataset.py, we pull the public openfoodfacts/nutrition-table-detection dataset directly from the Hugging Face Hub and transform every sample into a local file layout optimized for low-RAM training. Instead of keeping thousands of high-resolution PIL images resident in memory during training, the script writes each image out to /mnt/d/Data-Sets-Object-Detection/nutrition_qwen_dataset/images as a clean RGB JPEG.
Look closely at the PROMPT constant defined near the top of the script. It explicitly instructs the model to locate four specific classes—nutrition-table, nutrition-table-small, nutrition-table-small-energy, and nutrition-table-text—and return a JSON list containing bbox_2d and label keys. Keeping this prompt string identical across dataset preparation and inference ensures zero distribution shift when you test your trained model later.
Inside process_and_save_split, each image is converted to RGB (stripping alpha channels or grayscale modes that could confuse vision processors) and saved with quality=95. Immediately afterward, the loop unpacks each bounding box from the dataset’s [y_min, x_min, y_max, x_max] float representation, swaps the axes so x comes before y, multiplies by 1000, rounds to the nearest integer, and clamps every value safely inside [0, 1000].
Finally, each record is serialized as a single JSON line (train.jsonl and val.jsonl) containing a messages array with user and assistant turns. The user turn pairs the local JPEG path with your detection prompt, while the assistant turn wraps the ground-truth JSON list inside triple-backtick markdown fences (```json ... ```). Training the model to emit fenced JSON makes downstream parsing clean, predictable, and easy to extract with regular expressions.
# Link to the dataset : https://huggingface.co/datasets/openfoodfacts/nutrition-table-detection # ============================================================================== # STEP 1: Environment Setup & Imports # ============================================================================== ### Import OS utilities for path management, JSON for serialization, and load_dataset from Hugging Face: import os import json from datasets import load_dataset # ============================================================================== # STEP 2: Define Dataset Source, Output Directories & Detection Prompt # ============================================================================== ### Official Hugging Face Hub repository ID to download the dataset from: DATASET_NAME = " openfoodfacts/nutrition-table-detection " ### Save processed images and JSONL files to D: drive (using WSL mount path): BASE_DIR = " /mnt/d/Data-Sets-Object-Detection/nutrition_qwen_dataset " IMAGES_DIR = os . path . join ( BASE_DIR , " images " ) ### Create local subdirectories for train and validation image splits if they do not exist: os . makedirs ( os . path . join ( IMAGES_DIR , " train " ), exist_ok =True ) os . makedirs ( os . path . join ( IMAGES_DIR , " val " ), exist_ok =True ) ### Keep the prompt identical to what you will use later during inference: PROMPT = ( " Locate every nutrition-table, nutrition-table-small, " " nutrition-table-small-energy, and nutrition-table-text in the image " " and output their coordinates in JSON format with 'bbox_2d' and 'label'. " ) # ============================================================================== # STEP 3: Download Raw Dataset from Hugging Face Hub # ============================================================================== ### Print status and fetch both train and validation splits from Hugging Face Hub: print ( f "Downloading dataset: { DATASET_NAME } ..." ) raw_dataset = load_dataset ( DATASET_NAME ) # ============================================================================== # STEP 4: Convert Bounding Boxes & Save Images + JSONL Annotations # ============================================================================== ### Define helper function to convert one dataset split into local JPEGs and a JSONL manifest: def process_and_save_split ( split_name : str ): ### Select the target split and define output JSONL and image directory paths: split_data = raw_dataset [ split_name ] jsonl_path = os . path . join ( BASE_DIR , f " { split_name } .jsonl" ) split_img_dir = os . path . join ( IMAGES_DIR , split_name ) saved_count = 0 ### Open the JSONL file for writing UTF-8 encoded conversation samples: with open ( jsonl_path , " w " , encoding = " utf-8 " ) as f : for idx , example in enumerate ( split_data ): ### 1. Save PIL image locally as RGB JPEG to save RAM during training: img_filename = f " { split_name } _ { idx :05d } .jpg" img_path = os . path . join ( split_img_dir , img_filename ) ### Convert image to 3-channel RGB and save to disk at high JPEG quality: image = example [ " image " ]. convert ( " RGB " ) image . save ( img_path , format = " JPEG " , quality = 95 ) ### 2. Convert coordinates from (y_min, x_min, y_max, x_max) [0..1] ### to Qwen3-VL format [x_min, y_min, x_max, y_max] [0..1000]: bboxes = example [ " objects " ][ " bbox " ] categories = example [ " objects " ][ " category_name " ] annotations_list = [] ### Loop through all ground-truth boxes and labels in the current image: for bbox , label in zip ( bboxes , categories ): y_min , x_min , y_max , x_max = bbox ### Rescale float coordinates to [0..1000] integers and clamp within valid bounds: x1 = max ( 0 , min ( 1000 , int ( round ( x_min * 1000 )))) y1 = max ( 0 , min ( 1000 , int ( round ( y_min * 1000 )))) x2 = max ( 0 , min ( 1000 , int ( round ( x_max * 1000 )))) y2 = max ( 0 , min ( 1000 , int ( round ( y_max * 1000 )))) ### Append formatted Qwen3-VL dictionary entry for this object: annotations_list . append ({ " bbox_2d " : [ x1 , y1 , x2 , y2 ], " label " : label }) ### 3. Build Qwen conversational sample pointing to the saved image path: sample = { " image_path " : img_path , " messages " : [ { " role " : " user " , " content " : [ { " type " : " image " , " image " : img_path }, { " type " : " text " , " text " : PROMPT }, ], }, { " role " : " assistant " , " content " : [ { " type " : " text " , " text " : f "```json \n{ json . dumps ( annotations_list ) }\n ```" } ], }, ], } ### Write serialized JSON sample as a single line and increment counter: f . write ( json . dumps ( sample ) + " \n " ) saved_count += 1 ### Report total processed images and JSONL output path for the split: print ( f "[ { split_name . upper () } ] Saved { saved_count } images and annotations to { jsonl_path } " ) # ============================================================================== # STEP 5: Run Conversion for Train and Validation Splits # ============================================================================== ### Execute dataset preparation for both training and validation splits when run as main script: if __name__ == " __main__ " : process_and_save_split ( " train " ) process_and_save_split ( " val " ) print ( " Dataset preparation complete! " ) You now have clean, disk-backed train.jsonl and val.jsonl files containing normalized [0..1000] bounding boxes formatted specifically for Qwen3-VL’s multimodal chat template.
How Do You Configure Qwen3-VL-2B and LoRA Adapters to Fit Inside a Low GPU? How Do MIN_PIXELS, MAX_PIXELS, and LoraConfig Prevent Out-Of-Memory Crashes? Capping MAX_PIXELS at 640 * 32 * 32 bounds the maximum number of visual tokens fed into self-attention, while LoraConfig(r=8) freezes the 2-billion-parameter base model in bfloat16 and trains less than 1% of total weights.
The single biggest obstacle when developers try to fine tune Qwen3 VL locally is quadratic memory growth in the vision transformer’s attention layers. Unlike fixed-resolution CNNs, Qwen3-VL processes images at dynamic resolutions, meaning a single 4K smartphone photo can explode into thousands of visual tokens and instantly crash an 8GB GPU. In the first half of Step2-train_qwen3_vl.py, we solve this by loading the local JSONL manifests into lightweight Python lists and explicitly bounding the processor’s pixel budget.
Setting MIN_PIXELS = 256 * 32 * 32 and MAX_PIXELS = 640 * 32 * 32 inside AutoProcessor.from_pretrained forces every input image to scale smoothly within a predictable token window. This resolution ceiling is sharp enough for the vision encoder to read small nutrition table text clearly, yet compact enough to keep activation memory well below 8GB during backpropagation.
Next, AutoModelForImageTextToText.from_pretrained loads Qwen/Qwen3-VL-2B-Instruct in torch.bfloat16 precision with device_map="auto". Using bfloat16 cuts model weight memory in half compared to float32 while preserving the dynamic range needed for stable gradients without loss scaling.
To adapt the model without updating billions of weights, we wrap it in a LoraConfig with rank r=8, lora_alpha=16, and lora_dropout=0.05. Notice that target_modules covers both the attention projections (q_proj, k_proj, v_proj, o_proj) and the SwiGLU MLP projections (gate_proj, up_proj, down_proj). Targeting all seven linear projections gives the adapter enough expressive capacity to learn precise [x1, y1, x2, y2] coordinate formatting while keeping trainable parameters tiny.
# ============================================================================== # STEP 1: Environment Setup & Suppressing Warnings # ============================================================================== ### Import system utilities, PyTorch, Hugging Face Transformers, PEFT, TRL, and Qwen vision helpers: import os import json import warnings import torch from transformers import AutoModelForImageTextToText , AutoProcessor from peft import LoraConfig , get_peft_model from trl import SFTConfig , SFTTrainer from qwen_vl_utils import process_vision_info # ============================================================================== # STEP 2: Load Prepared Local JSONL Datasets from D: Drive # ============================================================================== ### Point to the directory containing train.jsonl and val.jsonl created in Step 1: DATASET_DIR = " /mnt/d/Data-Sets-Object-Detection/nutrition_qwen_dataset " ### Define helper function to parse JSONL files line by line into Python dictionaries: def load_jsonl_dataset ( jsonl_path : str ) -> list [ dict ]: ### Read each line from the JSONL file into a list of conversation samples: samples = [] with open ( jsonl_path , " r " , encoding = " utf-8 " ) as f : for line in f : if line . strip (): samples . append ( json . loads ( line )) return samples ### Load both training and validation conversation lists into memory: train_dataset = load_jsonl_dataset ( os . path . join ( DATASET_DIR , " train.jsonl " )) val_dataset = load_jsonl_dataset ( os . path . join ( DATASET_DIR , " val.jsonl " )) ### Print sample counts to verify datasets loaded properly: print ( f "Loaded { len ( train_dataset ) } train samples and { len ( val_dataset ) } val samples." ) # ============================================================================== # STEP 3: Load Base Model, Processor & Configure LoRA for 8GB VRAM # ============================================================================== ### Define Hugging Face base model ID and local output folder for LoRA checkpoints: MODEL_ID = " Qwen/Qwen3-VL-2B-Instruct " OUTPUT_DIR = " results/qwen3-vl-2b-nutrition-lora-model-weights " ### Use moderate image resolution during training so activations fit in 8GB VRAM: MIN_PIXELS = 256 * 32 * 32 MAX_PIXELS = 640 * 32 * 32 ### Initialize AutoProcessor with explicit shortest_edge and longest_edge pixel bounds: processor = AutoProcessor . from_pretrained ( MODEL_ID , size = { " shortest_edge " : MIN_PIXELS , " longest_edge " : MAX_PIXELS } ) ### Load base Qwen3-VL-2B-Instruct model in bfloat16 precision onto GPU: model = AutoModelForImageTextToText . from_pretrained ( MODEL_ID , dtype = torch . bfloat16 , device_map = " auto " ) ### Attach lightweight LoRA adapters to attention and MLP projection layers: lora_config = LoraConfig ( r = 8 , lora_alpha = 16 , lora_dropout = 0.05 , bias = " none " , task_type = " CAUSAL_LM " , target_modules = [ " q_proj " , " k_proj " , " v_proj " , " o_proj " , " gate_proj " , " up_proj " , " down_proj " ], ) ### Wrap base model with PEFT LoRA adapters and print trainable parameter ratio: model = get_peft_model ( model , lora_config ) model . print_trainable_parameters () With the base model loaded in bfloat16, image token resolution capped, and rank-8 LoRA adapters attached, model.print_trainable_parameters() confirms that less than 1% of the network is active for gradient updates.
Why Do You Need a Custom Multimodal Data Collator and Token Masking in SFTTrainer? What Happens If You Do Not Mask <|image_pad|> Tokens with -100 During Training? If <|image_pad|> placeholder tokens are left unmasked in the labels tensor, PyTorch attempts to compute cross-entropy language modeling loss over visual patch embeddings, corrupting gradients and wasting VRAM.
Standard text-only SFTTrainer pipelines assume every token in a batch belongs to a flat string, which breaks immediately when multimodal image placeholders enter the sequence. In the second half of Step2-train_qwen3_vl.py, we build a custom collate_fn that bridges raw conversation dictionaries and multimodal PyTorch tensors on the fly. First, processor.apply_chat_template(ex["messages"], tokenize=False) converts each user-assistant turn into Qwen’s exact special-token markup (<|im_start|>, <|vision_start|>, <|image_pad|>, and <|im_end|>).
Simultaneously, process_vision_info(ex["messages"])[0] from qwen_vl_utils reads the JPEG file from disk only when that specific batch is assembled. Lazy on-the-fly image loading keeps system RAM flat regardless of whether your dataset contains 1,000 images or 100,000 images. The processor then tokenizes the formatted strings and packs the resized image patches into a unified batch dictionary (input_ids, attention_mask, pixel_values, and image_grid_thw).
The most critical three lines in the entire script happen right before collate_fn returns batch. We clone input_ids into labels and overwrite every pad_token_id and every <|image_pad|> token ID with -100—the standard ignore index in PyTorch’s CrossEntropyLoss. Masking those tokens guarantees the model is penalized solely on its structured JSON prediction rather than trying to predict image patch tokens.
Finally, SFTConfig pairs per_device_train_batch_size=1 with gradient_accumulation_steps=8, simulating an effective batch size of 8 while holding only a single image’s activations in GPU memory at any instant. Enabling gradient_checkpointing=True with use_reentrant=False trades a tiny fraction of compute speed for dramatic VRAM savings, allowing two full epochs to complete cleanly and save both the adapter weights and processor configuration to OUTPUT_DIR.
# ============================================================================== # STEP 4: Build Multimodal Data Collator (On-the-Fly Image Loading) # ============================================================================== ### Define custom batch collator to format chat text, load JPEGs on the fly, and mask labels: def collate_fn ( examples ): ### Format chat templates for each sample in the batch: texts = [ processor . apply_chat_template ( ex [ " messages " ], tokenize =False ) for ex in examples ] ### Load and resize images from the local JPEG paths on the fly: image_inputs = [ process_vision_info ( ex [ " messages " ])[ 0 ] for ex in examples ] ### Tokenize text and process visual tensors into a padded PyTorch batch: batch = processor ( text = texts , images = image_inputs , padding =True , return_tensors = " pt " , ) ### Mask padding and image tokens so loss is computed only on assistant JSON: labels = batch [ " input_ids " ]. clone () labels [ labels == processor . tokenizer . pad_token_id ] = - 100 ### Look up Qwen's image placeholder token ID and mask it out from loss calculation: image_token_id = processor . tokenizer . convert_tokens_to_ids ( " <|image_pad|> " ) labels [ labels == image_token_id ] = - 100 ### Attach masked labels tensor to the batch dictionary and return: batch [ " labels " ] = labels return batch # ============================================================================== # STEP 5: Configure Training Hyperparameters & Start Fine-Tuning # ============================================================================== ### Configure SFTTrainer arguments optimized for 8GB VRAM stability and effective batch size 8: training_args = SFTConfig ( output_dir = OUTPUT_DIR , num_train_epochs = 2 , per_device_train_batch_size = 1 , per_device_eval_batch_size = 1 , gradient_accumulation_steps = 8 , learning_rate = 2e-4 , warmup_steps = 15 , logging_steps = 10 , eval_strategy = " epoch " , save_strategy = " epoch " , bf16 =True , gradient_checkpointing =True , gradient_checkpointing_kwargs = { " use_reentrant " : False }, remove_unused_columns =False , dataset_kwargs = { " skip_prepare_dataset " : True }, report_to = " none " , ) ### Initialize SFTTrainer with LoRA-wrapped model, datasets, and custom multimodal collator: trainer = SFTTrainer ( model = model , args = training_args , train_dataset = train_dataset , eval_dataset = val_dataset , data_collator = collate_fn , processing_class = processor . tokenizer , ) ### Run training and save the final LoRA adapter weights and processor: trainer . train () trainer . save_model ( OUTPUT_DIR ) processor . save_pretrained ( OUTPUT_DIR ) print ( f "Fine-tuning complete! LoRA adapter saved to: { OUTPUT_DIR } " ) Once trainer.train() finishes, your trained LoRA adapter weights and exact pixel-bound processor settings are saved locally in results/qwen3-vl-2b-nutrition-lora-model-weights, ready for inference.
How Do You Run Deterministic Inference and Convert Qwen3-VL JSON Back into Bounding Boxes? How Does Step3-inference_nutrition.py Map Normalized [0..1000] Coordinates onto Real Images? A regex parser extracts the JSON list from the model’s generated text, divides each [x1, y1, x2, y2] integer by 1000.0, and multiplies by the original image’s pixel width and height before passing the array into supervision.Detections.
Training a model is only half the story—you also need a reliable inference script that loads your lightweight LoRA adapter, enforces deterministic JSON generation, and renders clean bounding boxes onto unseen test images. In Step3-inference_nutrition.py, we initialize AutoProcessor.from_pretrained(LORA_DIR) directly from our saved training folder so the inference pipeline automatically inherits the exact MIN_PIXELS and MAX_PIXELS configuration used during training. Then, PeftModel.from_pretrained(base_model, LORA_DIR) attaches our trained adapter weights onto Qwen/Qwen3-VL-2B-Instruct and switches the network into model.eval() mode.
To evaluate generalization on unseen data, the script picks a random validation JPEG from VAL_IMAGES_DIR and constructs a single-turn user message containing the exact PROMPT string from Step 1. Notice how processor.apply_chat_template is called with add_generation_prompt=True so Qwen appends the assistant turn header and immediately begins generating the JSON response.
Inside torch.no_grad(), we invoke model.generate(**inputs, max_new_tokens=512, do_sample=False). Setting do_sample=False disables temperature randomness and forces greedy decoding, which is essential when generating structured JSON syntax and exact numerical coordinates. We then slice off the input prompt tokens (out_ids[len(in_ids):]) so raw_response contains strictly the model’s newly generated JSON block.
Finally, parse_qwen_detections searches raw_response for the JSON array (\[.*\]), rescales each [0..1000] coordinate back to true pixel coordinates ((x1_norm / 1000.0) * img_width), and packages them into a supervision.Detections object. To make sure bounding boxes and labels remain crisp on both small web thumbnails and high-resolution product photos, the script calculates dynamic_thickness and dynamic_text_scale proportionally to the image dimensions before saving the annotated result with OpenCV and displaying it via Matplotlib.
# ============================================================================== # STEP 1: Environment Setup & Imports # ============================================================================== ### Import file system, regex, OpenCV, PyTorch, Supervision, Matplotlib, and PEFT modules: import os import re import glob import json import random import warnings import cv2 import numpy as np import torch import supervision as sv import matplotlib . pyplot as plt from transformers import AutoModelForImageTextToText , AutoProcessor from peft import PeftModel from qwen_vl_utils import process_vision_info # ============================================================================== # STEP 2: Load Base Model & Trained LoRA Adapter Weights # ============================================================================== ### Define base model ID and path to the fine-tuned LoRA weights saved in Step 2: BASE_MODEL_ID = " Qwen/Qwen3-VL-2B-Instruct " LORA_DIR = " results/qwen3-vl-2b-nutrition-lora-model-weights " ### Load the processor saved during training (keeps the same resolution settings): processor = AutoProcessor . from_pretrained ( LORA_DIR ) ### Load the base model in bfloat16 and attach your trained LoRA weights: base_model = AutoModelForImageTextToText . from_pretrained ( BASE_MODEL_ID , dtype = torch . bfloat16 , device_map = " auto " ) model = PeftModel . from_pretrained ( base_model , LORA_DIR ) model . eval () # ============================================================================== # STEP 3: Pick a Random Validation Image & Set Exact Training Prompt # ============================================================================== ### Locate all validation JPEGs prepared in Step 1 and verify directory is not empty: VAL_IMAGES_DIR = " /mnt/d/Data-Sets-Object-Detection/nutrition_qwen_dataset/images/val " all_val_images = glob . glob ( os . path . join ( VAL_IMAGES_DIR , " *.jpg " )) if not all_val_images : raise FileNotFoundError ( f "No .jpg images found in { VAL_IMAGES_DIR } " ) ### Choose one random validation image and build the output prediction filename: IMAGE_PATH = random . choice ( all_val_images ) image_filename = os . path . basename ( IMAGE_PATH ) OUTPUT_IMAGE_PATH = os . path . join ( " results " , f "pred_ { image_filename } " ) print ( f "Selected random image: { IMAGE_PATH } " ) ### Must match the exact prompt used in Step2a-prepare_dataset.py: PROMPT = ( " Locate every nutrition-table, nutrition-table-small, " " nutrition-table-small-energy, and nutrition-table-text in the image " " and output their coordinates in JSON format with 'bbox_2d' and 'label'. " ) ### Build single-turn multimodal user message for inference: messages = [ { " role " : " user " , " content " : [ { " type " : " image " , " image " : IMAGE_PATH }, { " type " : " text " , " text " : PROMPT }, ], } ] # ============================================================================== # STEP 4: Run Inference with the Fine-Tuned Model # ============================================================================== ### Format chat prompt with generation cue and extract image inputs: text = processor . apply_chat_template ( messages , tokenize =False , add_generation_prompt =True ) image_inputs , _ = process_vision_info ( messages ) ### Tokenize prompt and image into PyTorch tensors on the active GPU device: inputs = processor ( text = [ text ], images = image_inputs , padding =True , return_tensors = " pt " , ). to ( model . device ) ### Run deterministic greedy decoding without gradient tracking: with torch . no_grad (): generated_ids = model . generate ( ** inputs , max_new_tokens = 512 , do_sample =False ) ### Trim prompt tokens and decode only the model's JSON response: generated_ids_trimmed = [ out_ids [ len ( in_ids ):] for in_ids , out_ids in zip ( inputs . input_ids , generated_ids ) ] raw_response = processor . batch_decode ( generated_ids_trimmed , skip_special_tokens =True )[ 0 ] print ( " Model Raw Output: \n " , raw_response ) # ============================================================================== # STEP 5: Parse JSON Coordinates, Annotate Dynamically & Display with Matplotlib # ============================================================================== ### Define helper function to parse JSON boxes and rescale [0..1000] coordinates to pixels: def parse_qwen_detections ( response_text : str , img_width : int , img_height : int ) -> sv . Detections : ### Extract the JSON array from markdown code fences or raw text: match = re . search ( r " \[. * \] " , response_text , re . DOTALL ) if not match : return sv . Detections . empty () ### Parse matched JSON string into Python list of detection dictionaries: items = json . loads ( match . group ( 0 )) if not items : return sv . Detections . empty () xyxy_list = [] class_names = [] ### Loop through each predicted box and convert normalized coordinates back to pixels: for item in items : x1_norm , y1_norm , x2_norm , y2_norm = item [ " bbox_2d " ] ### Convert normalized [0..1000] coordinates back to image pixel coordinates: x1 = ( x1_norm / 1000.0 ) * img_width y1 = ( y1_norm / 1000.0 ) * img_height x2 = ( x2_norm / 1000.0 ) * img_width y2 = ( y2_norm / 1000.0 ) * img_height xyxy_list . append ([ x1 , y1 , x2 , y2 ]) class_names . append ( item [ " label " ]) ### Map string class names to integer IDs and return a Supervision Detections object: unique_classes = sorted ( set ( class_names )) class_ids = np . array ([ unique_classes . index ( name ) for name in class_names ]) return sv . Detections ( xyxy = np . array ( xyxy_list , dtype = np . float32 ), class_id = class_ids , data = { " class_name " : np . array ( class_names )} ) ### Load original image and compute dynamic thickness/text scale for high-res images: image_bgr = cv2 . imread ( IMAGE_PATH ) h , w , _ = image_bgr . shape ### Parse raw model JSON output into scaled pixel bounding boxes: detections = parse_qwen_detections ( raw_response , w , h ) ### Scale box line thickness and label font size proportionally to image resolution: dynamic_thickness = max ( 4 , int ( max ( h , w ) / 250 )) dynamic_text_scale = max ( 1.0 , max ( h , w ) / 1000.0 ) dynamic_text_thickness = max ( 2 , int ( dynamic_thickness / 2 )) ### Initialize Supervision BoxAnnotator and LabelAnnotator with bright green styling: box_annotator = sv . BoxAnnotator ( color = sv . Color . from_hex ( " #00FF00 " ), thickness = dynamic_thickness ) label_annotator = sv . LabelAnnotator ( color = sv . Color . from_hex ( " #00FF00 " ), text_color = sv . Color . BLACK , text_scale = dynamic_text_scale , text_thickness = dynamic_text_thickness , text_padding = 10 ) ### Draw bounding boxes and class labels onto a copy of the original image: annotated_bgr = box_annotator . annotate ( scene = image_bgr . copy (), detections = detections ) annotated_bgr = label_annotator . annotate ( scene = annotated_bgr , detections = detections , labels = detections . data . get ( " class_name " , []) ) ### Save annotated image to disk and display it in RGB format via Matplotlib: cv2 . imwrite ( OUTPUT_IMAGE_PATH , annotated_bgr ) print ( f "Annotated image saved to: { OUTPUT_IMAGE_PATH } " ) ### Convert BGR to RGB and display the result using Matplotlib: annotated_rgb = cv2 . cvtColor ( annotated_bgr , cv2 . COLOR_BGR2RGB ) plt . figure ( figsize = ( 10 , 12 )) plt . imshow ( annotated_rgb ) plt . axis ( " off " ) plt . title ( f " { image_filename } | Detections: { len ( detections ) } " , fontsize = 14 ) plt . tight_layout () plt . show () In just under 150 lines of clean Python, you have a complete inference loop that loads your custom LoRA weights, outputs valid structured JSON, and draws scaled bounding boxes onto any validation image.
Visual Comparison: Base Qwen3-VL-2B vs. Fine-Tuned LoRA on “val_00117.jpg“ Qwen3-VL result Looking at validation sample val_00117.jpg above highlights why domain-specific fine-tuning is essential when using a Vision-Language Model for structured object detection .
Left — Base Qwen3-VL-2B-Instruct (4 Detections): Without domain adaptation, the out-of-the-box model fails to distinguish the actual nutrition panel from the surrounding product packaging. Instead of isolating the tabular breakdown, it draws an oversized orange bounding box around the entire Pocky box—swallowing the brand logo, product illustrations, ingredient paragraph, and manufacturer address under a noisy, overlapping label (nutrition-table-textll-energy). Right — Fine-Tuned LoRA Model (1 Detection): After just two epochs of LoRA training on our custom JSONL dataset, the model completely ignores the product branding, strawberry graphics, and ingredient list. It snaps a single, tightly fitted green bounding box (nutrition-table) directly onto the rotated Nutrition Facts panel, demonstrating clean spatial precision and strict adherence to our target JSON schema. Frequently Asked Questions (FAQ) Can I fine tune Qwen3 VL-2B-Instruct on an 8GB VRAM GPU without quantization? Yes. By loading the base model in bfloat16, capping MAX_PIXELS at 640 * 32 * 32, enabling gradient_checkpointing, and using per_device_train_batch_size=1 with gradient_accumulation_steps=8, the entire LoRA training loop runs comfortably inside 8GB of VRAM without needing 4-bit quantization.
Why does Step1-prepare_dataset.py convert bounding boxes to a [0..1000] integer range? Qwen3-VL’s spatial grounding pre-training uses normalized [x1, y1, x2, y2] coordinates scaled from 0 to 1000 regardless of image aspect ratio. Formatting your custom dataset to match this exact convention allows the model to converge much faster and avoids aspect-ratio distortion errors.
Why must we mask <|image_pad|> tokens with -100 inside collate_fn? In PyTorch’s cross-entropy loss function, any target label set to -100 is ignored during gradient computation. Masking both padding tokens and <|image_pad|> visual placeholders ensures the model only optimizes its predictions on the assistant’s structured JSON output.
Which layers of Qwen3-VL-2B are updated by our LoRA configuration? Our LoraConfig targets all seven linear projection layers across the attention and MLP blocks: q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, and down_proj. With r=8 and lora_alpha=16, this updates less than 1% of total parameters while adapting both visual grounding and JSON formatting.
Why do we save images locally as JPEGs instead of streaming directly from Hugging Face during training? Saving images to disk as RGB JPEGs allows qwen_vl_utils.process_vision_info to load and resize one image at a time inside collate_fn. This prevents large image datasets from consuming all available system RAM before training even begins.
What happens if I change the PROMPT text during inference? Changing the prompt wording or class names during inference can reduce detection accuracy because the LoRA adapter learned to map that specific instruction structure to your target JSON schema. Always keep the PROMPT constant identical across dataset preparation and inference.
Why is do_sample=False used in model.generate() during inference? Setting do_sample=False forces greedy decoding, which selects the highest-probability token at every step. For structured JSON extraction and bounding-box coordinates, deterministic output prevents random syntax errors or hallucinated numbers.
Can I use this exact pipeline for other datasets beyond nutrition labels? Absolutely. You can adapt Step1-prepare_dataset.py to any custom dataset—such as invoices, retail shelves, medical scans, or ID cards—simply by updating the PROMPT string and converting your ground-truth boxes into [x1, y1, x2, y2] coordinates on the 0..1000 scale.
Why do we pin transformers>=4.57.0,<5.0.0 and numpy<2.0.0 in the Conda environment? Qwen3-VL requires architecture support introduced in transformers 4.57+, while version 5.0 introduces breaking changes to trainer APIs. Pinning numpy<2.0.0 and pyarrow<18.0.0 prevents binary compatibility errors with OpenCV and Hugging Face datasets.
How large are the saved LoRA adapter weights after training completes? Because LoRA only stores the low-rank rank-8 update matrices rather than the full 2-billion-parameter base model, the saved adapter directory is typically around 35MB to 70MB, making it easy to version, share, or deploy in production.
Wrapping Up Your Local Qwen3-VL Fine-Tuning Pipeline You now have a complete, end-to-end blueprint to fine tune Qwen3 VL on consumer hardware without sacrificing precision or stability. By combining a clean WSL2 and CUDA 12.6 Conda environment with normalized [0..1000] JSONL chat templates, bounded AutoProcessor pixel budgets, <|image_pad|> token masking, and rank-8 PEFT LoRA adapters, you can train a 2-billion-parameter Vision-Language Model on an 8GB GPU and turn raw images into reliable, structured JSON predictions.
As seen in our side-by-side comparison, targeted LoRA fine-tuning transforms a noisy zero-shot vision model into a sharp domain specialist—eliminating false positives and snapping tightly onto exact visual regions of interest. From here, you can swap in your own annotated datasets, adjust MAX_PIXELS for higher-density documents, or merge the saved LoRA adapter into the base weights for fast production deployment.
Connect : ☕ Buy me a coffee — https://ko-fi.com/eranfeit
🖥️ Email : feitgemel@gmail.com
🌐 https://eranfeit.net
🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb
Enjoy,
Eran