Objective: adapt a vision-language model (VLM) with LoRA/QLoRA by targeting exclusively its language decoder. The task is deliberately bounded — describing a synthetic image containing a colored shape according to a strict output contract — so that the effect of fine-tuning is measurable: we compare the base model and the adapted model on a format-compliance metric and on field-by-field correctness, on images never seen during training.
Prerequisites: - FT-01 (fine-tuning overview, LoRA on GPT-2) - FT-02 (4-bit NF4 quantization, QLoRA) - FT-03 (SFT instruction-following, training/evaluation loop) - Familiarity with PyTorch and Transformers
Notebook outline: 1. Vision-language models and Qwen3.5-0.8B 2. The bounded image→text task: output contract and synthetic dataset 3. Baseline measurement of the base model 4. LoRA targeted at the decoder 5. QLoRA training 6. Comparative evaluation: base vs LoRA 7. Why the decoder only? 8. Cleaning up GPU memory 9. Exercises 10. Summary
Required hardware: GPU — the reference run (RTX 3070 Laptop, 8.6 GB) never exceeded 1.5 GB of allocated VRAM (832 MB when loading in 4-bit, 1452 MB after training, see sections 1 and 5): a modest card is enough, with the margin absorbing transient allocation spikes.
Estimated duration: 45–60 minutes
Path: we first load the multimodal model and its processor (section 1), build a fully deterministic synthetic image dataset — drawn with PIL, therefore reproducible to the exact pixel without any data download (section 2), measure the base model on a contract it has never seen (section 3), graft LoRA adapters onto only the decoder layers (section 4), train (section 5), then compare base versus LoRA with numbers in hand on the same held-out images (section 6). Section 7 justifies the “decoder only” choice; three exercises extend it: a new shape, an additional contract field, and targeting vision itself.
import warnings# Filtres poses AVANT les autres imports (issue #11725) : ils evitent que les# avertissements de dependances (barres de progression, cache HuggingFace)# n'encombrent — et ne fuient — dans les sorties du notebook.warnings.filterwarnings("ignore", message="IProgress not found.*")warnings.filterwarnings("ignore", message="Unable to fetch remote file.*")warnings.filterwarnings("ignore", message="Could not find a config file.*")import osimport gcimport jsonimport timeimport randomimport torchfrom PIL import Image, ImageDraw# Reproducibilite : graine fixee pour le dataset synthetique et les tirages PyTorchSEED =42random.seed(SEED)torch.manual_seed(SEED)print(f"PyTorch {torch.__version__}")print(f"CUDA : {torch.cuda.is_available()}")if torch.cuda.is_available():print(f"GPU : {torch.cuda.get_device_name(0)}") props = torch.cuda.get_device_properties(0)print(f"VRAM : {props.total_memory /1e9:.1f} Go")
PyTorch 2.13.0+cu126
CUDA : True
GPU : NVIDIA GeForce RTX 3070 Laptop GPU
VRAM : 8.6 Go
1. Vision-language models and Qwen3.5-0.8B
A vision-language model (VLM) juxtaposes two organs: a vision tower — a ViT that splits the image into patches and encodes them as vectors — and a language decoder that generates text using these vectors as context. Between the two, a merger projects the visual patches into the decoder’s embedding space: after it, an image is nothing more than a sequence of “visual tokens” among the text tokens.
Qwen3.5-0.8B illustrates, in miniature, two trends in recent architectures:
Attention hybridization: not all layers of the decoder are identical. Linear attention layers (Gated DeltaNet, linear_attn module) have a memory cost that is constant with respect to sequence length; the others retain full attention (classic softmax, q_proj/k_proj/v_proj/o_proj modules). The numerous image tokens make this trade-off valuable.
Native multimodality: the checkpoint embeds both the vision tower AND the decoder; the AutoModelForImageTextToText class loads the whole thing (Qwen3_5ForConditionalGeneration internally).
We load it as in FT-02/FT-03: 4-bit NF4 quantized body (QLoRA), computations in bfloat16, double quantization of constants. The new difference is the processor: for a VLM, it does two jobs at once — it tokenizes the text AND prepares the pixels (resizing, normalization, splitting into patches). An image never goes directly into the model: it goes through the processor, which produces the pixel_values and inserts into the sequence the exact number of visual tokens corresponding to the image.
The API point to remember: the text given to the processor must contain the image marker <|vision_start|><|image_pad|><|vision_end|>. The processor then replaces <|image_pad|> with as many image tokens as the image has patches — forgetting this marker means submitting an image that the model will never look at.
# Charger le modele vision-langage Qwen3.5-0.8B en 4-bit (QLoRA, comme FT-02/FT-03)from transformers import ( AutoModelForImageTextToText, AutoTokenizer, AutoProcessor, BitsAndBytesConfig,)MODEL_NAME ="Qwen/Qwen3.5-0.8B"bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True,)print(f"Chargement de {MODEL_NAME} en 4-bit NF4...")tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)if tokenizer.pad_token isNone: tokenizer.pad_token = tokenizer.eos_tokentokenizer.padding_side ="right"# transformers 5.15 : la validation de docstring du module qwen3_vl imprime des# [ERROR] via un print inconditionnel (pas un warning, non filtrable) qui embarque# le chemin d'installation du venv -- on redirige stdout le temps de cet import (#11725).import contextlib, iowith contextlib.redirect_stdout(io.StringIO()): processor = AutoProcessor.from_pretrained(MODEL_NAME)# le processor embarque sa propre instance du tokenizer : memes regles de paddingif processor.tokenizer.pad_token isNone: processor.tokenizer.pad_token = processor.tokenizer.eos_tokenprocessor.tokenizer.padding_side ="right"model_base = AutoModelForImageTextToText.from_pretrained( MODEL_NAME, quantization_config=bnb_config, device_map="auto",)nb_params =sum(p.numel() for p in model_base.parameters())print(f"Modele charge. Parametres : {nb_params:,}")print(f"Tour de vision presente : {hasattr(model_base, 'model') andhasattr(model_base.model, 'visual')}")if torch.cuda.is_available():print(f"VRAM utilisee : {torch.cuda.memory_allocated() /1e6:.0f} Mo")
Chargement de Qwen/Qwen3.5-0.8B en 4-bit NF4...
Modele charge. Parametres : 555,419,712
Tour de vision presente : True
VRAM utilisee : 832 Mo
Reading the loading. The output shows 555,419,712 parameters (sum(p.numel()) on the loaded model), vision tower and decoder combined, with the body stored in 4-bit for 832 MB of VRAM. Keep in mind: section 4 will count 860,260,416 “all params” parameters via PEFT on this same grafted model — the two counts coexist in this run without their discrepancy being clarified by the outputs themselves (one candidate explanation — the 4-bit layers count their weights by storage weight — remains a hypothesis to be verified, also mentioned in section 4). Two checkpoints: the line “Tour de vision presente : True” (printed by the cell in French, reproduced verbatim) confirms that AutoModelForImageTextToText did indeed instantiate the complete multimodal architecture (and not only the ForCausalLM decoder, which also exists for this checkpoint); the VRAM measured immediately after loading provides the reference against which the following sections (adapters, training, generation) will be compared. The processor itself consumes no VRAM — but it is what determines how many tokens an image will “cost” in the sequence, and therefore indirectly the length of the training batches.
2. The bounded image→text task: output contract and synthetic dataset
The pedagogical question of the notebook is narrow, and deliberately so: what needs to be changed in a VLM for it to honor an arbitrary output format on a simple visual task? The answer explored here: not the vision — the decoder.
The task: each 128×128 image contains exactly one colored shape on a white background. The model must answer according to the strict contract:
Three shapes, four colors — 12 possible combinations. We generate:
24 training images (2 per combination), with slight size and position jitter to prevent a precise image layout from appearing twice identically;
6 held-out test images — combinations drawn from among the 12, never seen during training, drawn with another random grain. It is this split that will give meaning to the evaluation: measuring the generalization of the contract, not its image-by-image memorization.
Two design choices are worth noting. First, the dataset is synthetic and deterministic: drawn by PIL with a local random generator (random.Random(graine)), it reproduces pixel-perfectly from one session to the next — no data download, no hidden variation, the seed is enough. Second, the jitter is bounded (positions in a central area, sizes within an interval): the task remains visually trivial for the vision tower. This is deliberate — we want any measurement discrepancy to be attributable to the language contract, not to perceptual difficulty.
# Dataset synthetique — une forme coloree par image 128x128, dessinee par PILFORMES = ["disque", "carre", "triangle"]COULEURS = {"rouge": (214, 40, 40),"vert": (40, 160, 60),"bleu": (40, 70, 214),"jaune": (230, 210, 40),}FOND = (250, 250, 250)TAILLE_IMAGE =128def dessiner_forme(forme, couleur_rgb, taille, cx, cy):"""Dessine une forme centree en (cx, cy) sur un canvas blanc 128x128.""" image = Image.new("RGB", (TAILLE_IMAGE, TAILLE_IMAGE), FOND) dessin = ImageDraw.Draw(image) demi = taille //2if forme =="disque": dessin.ellipse([cx - demi, cy - demi, cx + demi, cy + demi], fill=couleur_rgb)elif forme =="carre": dessin.rectangle([cx - demi, cy - demi, cx + demi, cy + demi], fill=couleur_rgb)elif forme =="triangle": sommets = [(cx, cy - demi), (cx - demi, cy + demi), (cx + demi, cy + demi)] dessin.polygon(sommets, fill=couleur_rgb)return imagedef generer_ensemble(nb_par_combinaison, graine):"""Genere les 12 combinaisons forme x couleur, avec jitter borne, de facon deterministe. Le generateur random.Random local ne touche pas l'etat aleatoire global : deux appels avec la meme graine produisent les memes images au pixel pres. """ gen = random.Random(graine) exemples = []for forme in FORMES:for couleur in COULEURS:for _ inrange(nb_par_combinaison): taille = gen.randint(28, 44) cx = gen.randint(48, 80) cy = gen.randint(48, 80) image = dessiner_forme(forme, COULEURS[couleur], taille, cx, cy) exemples.append({"image": image, "forme": forme, "couleur": couleur}) gen.shuffle(exemples)return exemplestrain_brut = generer_ensemble(nb_par_combinaison=2, graine=SEED) # 12 x 2 = 24candidats_test = generer_ensemble(nb_par_combinaison=1, graine=SEED +1000) # 12 candidatstest_exemples = candidats_test[::2] # 6 held-outprint(f"Train : {len(train_brut)} images ({len(FORMES)} formes x {len(COULEURS)} couleurs x 2)")print(f"Test held-out : {len(test_exemples)} images")print("\nCombinaisons de test :")for ex in test_exemples:print(f" {ex['forme']:<10}{ex['couleur']}")
Train : 24 images (3 formes x 4 couleurs x 2)
Test held-out : 6 images
Combinaisons de test :
disque jaune
carre jaune
disque bleu
carre rouge
disque rouge
triangle vert
Reading the dataset. The output confirms the intended structure: 24 training images uniformly covering the 12 combinations (2 each), and 6 test images listed with their label. Check in the list that the test combinations cover several shapes and several colors — 3 disks, 2 squares, 1 triangle over 4 distinct colors: this is the condition for the per-field accuracy (section 3) to be able to distinguish a model that always guesses “disk” from a model that truly looks at the image. Also note what the jitter does not do: it varies size and position within narrow bounds, so two images of the same combination differ, but remain perceptually identical — learning will focus on the shape/color association, not on memorizing exact pixels.
# Le contrat de sortie : paire (prompt multimodal, reponse attendue)PROMPT_MODELE = ("### Human: <|vision_start|><|image_pad|><|vision_end|> Decrivez l'image.\n### Assistant:")def construire_reponse(forme, couleur):"""La reponse attendue : le contrat de format que le LoRA doit installer."""returnf"[IMG] forme={forme} couleur={couleur} [FIN]"train_exemples = [ {"image": ex["image"],"texte": f"{PROMPT_MODELE}{construire_reponse(ex['forme'], ex['couleur'])}", }for ex in train_brut]print("Exemple complet (placeholder d'image non encore expande) :")print("-"*60)print(train_exemples[0]["texte"])print("-"*60)# Longueur de la part texte : le placeholder compte pour 1 jeton ici,# le processor l'expandra au moment du lottailles = [len(processor.tokenizer(t["texte"])["input_ids"]) for t in train_exemples]print(f"\n{len(train_exemples)} paires formatees")print(f"Longueur texte : min {min(tailles)}, max {max(tailles)}, moy {sum(tailles) /len(tailles):.0f} jetons")
Exemple complet (placeholder d'image non encore expande) :
------------------------------------------------------------
### Human: <|vision_start|><|image_pad|><|vision_end|> Decrivez l'image.
### Assistant: [IMG] forme=carre couleur=rouge [FIN]
------------------------------------------------------------
24 paires formatees
Longueur texte : min 29, max 31, moy 30 jetons
Reading the formatting. The example shown presents the complete skeleton of a training example: the prompt ### Human: contains the image marker enclosed by <|vision_start|>/<|vision_end|> followed by the instruction, and the target after ### Assistant: carries the contract [IMG] forme=… couleur=… [FIN]. The displayed lengths — 29 to 31 tokens, average 30 — cover only the textual part: when the processor prepares a batch, the marker <|image_pad|> will be replaced by the exact number of visual tokens from the image (the patches after merging), lengthening the actual sequence by that much. This is why a VLM “consumes” so much context for so few words: the visual part dominates the effective sequence (measured in section 5). As in FT-03, this format (### Human: / ### Assistant:) is a contract between training and inference — identical on both sides.
3. Baseline Measurement of the Base Model
Before any fine-tuning, we need an honest point of comparison. We submit the 6 held-out images to the base model with exactly the prompt that will be used for training, then we measure three indicators:
respecte_format — compliance with the contract: the response starts with [IMG] and contains [FIN]. This is the notebook’s central metric: it measures a language behavior (following a format), not knowledge.
accuracy_forme — is the forme= field extracted from the response correct?
accuracy_couleur — is the couleur= field correct?
The extraction is deliberately crude (splitting on spaces, reading the forme=/couleur= prefixes): if the model does not emit the fields, extraction returns None and the field is counted as wrong — no leniency. Since this protocol is written once and applied exactly as-is to both models (section 6), the base vs LoRA comparison does not depend on any hidden setting.
What should we predict for a base model? Nothing has ever exposed it to this arbitrary contract: it will likely continue the prompt in free-form prose, or recycle formats seen during pre-training. The measurement will say precisely how far it is from the contract — this is the distance the LoRA will need to close.
# Fonctions d'evaluation : generation multimodale + metriques de conformitedef generer_vlm(model, image, prompt, max_new_tokens=40):"""Genere la suite du prompt pour une image donnee (decodage glouton, deterministe).""" entrees = processor(text=prompt, images=image, return_tensors="pt").to(model.device)with torch.no_grad(): sortie = model.generate(**entrees, max_new_tokens=max_new_tokens, do_sample=False, pad_token_id=processor.tokenizer.pad_token_id, )return processor.tokenizer.decode( sortie[0][entrees["input_ids"].shape[1]:], skip_special_tokens=True, ).strip()def extraire_champs(texte):"""Extrait les valeurs des champs forme=... et couleur=... (None si absents).""" forme, couleur =None, Nonefor mot in texte.split():if mot.startswith("forme="): forme = mot.split("=", 1)[1]elif mot.startswith("couleur="): couleur = mot.split("=", 1)[1]return forme, couleurdef respecte_format(texte):"""Conformite au contrat : demarre par [IMG] et contient [FIN]."""return texte.startswith("[IMG]") and"[FIN]"in textedef evaluer_modele(model, exemples, nom="modele"):"""Soumet chaque image au modele, mesure conformite et justesse champ par champ.""" lignes = []for ex in exemples: sortie = generer_vlm(model, ex["image"], PROMPT_MODELE) forme_pred, couleur_pred = extraire_champs(sortie) lignes.append({"verite": f"{ex['forme']}/{ex['couleur']}","sortie": sortie,"respecte": respecte_format(sortie),"forme_ok": forme_pred == ex["forme"],"couleur_ok": couleur_pred == ex["couleur"], }) n =len(lignes) metriques = {"respecte_format": sum(l["respecte"] for l in lignes) / n,"accuracy_forme": sum(l["forme_ok"] for l in lignes) / n,"accuracy_couleur": sum(l["couleur_ok"] for l in lignes) / n, }print(f"--- Evaluation : {nom} ({n} images held-out) ---")print(f"{'Verite':<18}{'Conforme':<10}{'Forme':<7}{'Couleur':<9}Sortie (60 car.)")for l in lignes: extrait = l["sortie"][:60].replace("\n", " ")print(f"{l['verite']:<18}{str(l['respecte']):<10}{str(l['forme_ok']):<7}{str(l['couleur_ok']):<9}{extrait}")print(f"\nConformite de format : {metriques['respecte_format']:.2f}")print(f"Accuracy forme : {metriques['accuracy_forme']:.2f}")print(f"Accuracy couleur : {metriques['accuracy_couleur']:.2f}")return metriques, lignes
3a. Running the Base Model on the Held-Out Images
Each image is submitted individually (batch of 1, greedy decoding so that the measurement is reproducible). The table shows the ground truth, the three Boolean verdicts, and an excerpt from the raw output — read the excerpt before the metrics: it is what shows how the model fails (free-form prose? distorted fields? loop?), while the numbers only give the magnitude.
# Mesure de reference : modele de base (avant tout fine-tuning)metriques_base, lignes_base = evaluer_modele(model_base, test_exemples, nom="modele de base")
--- Evaluation : modele de base (6 images held-out) ---
Verite Conforme Forme Couleur Sortie (60 car.)
disque/jaune False False False <think> </think> L'image présente une simple composition g
carre/jaune False False False <think> </think> D'après l'image, il s'agit d'une image si
disque/bleu False False False <think> </think> L'image présente un cercle bleu pur sur u
carre/rouge False False False <think> </think> D'après l'image, il s'agit d'une image si
disque/rouge False False False <think> </think> La image présente un cercle rouge centré
triangle/vert False False False <think> </think> L'image montre un triangle vert simple et
Conformite de format : 0.00
Accuracy forme : 0.00
Accuracy couleur : 0.00
Reading the reference measurement. Compliance 0.00, shape accuracy 0.00, color accuracy 0.00 — the floor, as expected. But read the raw excerpts: this is the notebook’s most instructive result. The base model sees the images — on the three excerpts long enough to reach the description (output preserved verbatim, in French: “un cercle bleu pur”, “un cercle rouge centré”, “un triangle vert simple”), the prose contains the correct shape AND the correct color; the other three excerpts are truncated at 60 characters before the description, so the table alone does not allow us to decide “every time.” The failure regime is therefore not perceptual: the vision tower works, the decoder knows how to name what it sees. What is missing is only the contract — no forme=…, no [IMG], no tag. The Color column shows 0.00 even though the color is correct in prose: the metric rewards only the formatted field, not the knowledge. This is precisely what the LoRA on the decoder will install, without touching vision.
4. LoRA Targeted on the Decoder
The structuring choice of the notebook: we adapt exclusively the language decoder. The LoraConfig below targets three families of modules, all on the language side:
Family
Modules
Role
Full attention
q_proj, k_proj, v_proj, o_proj
softmax layers of the hybrid decoder
Linear attention
linear_attn.out_proj
Gated DeltaNet layers (constant cost in length)
MLP
gate_proj, up_proj, down_proj
feed-forward projections of each layer
This is the same list as FT-03, adapted to Qwen3.5’s hybrid architecture: the rank r=16 sets the capacity of the adapters, lora_alpha=32 their scale (the usual 2:1 ratio), and the 0.05 dropout regularizes a short training run. The vision tower, meanwhile, remains frozen — the reason why is covered in section 7; the extension (also targeting the visual merger) is exercise 3.
As in FT-03, prepare_model_for_kbit_training prepares the 4-bit body to receive gradients (fine-grained freezing, norms in float32, cache disabled for gradient checkpointing), then get_peft_model grafts on the adapters. The output of print_trainable_parameters() is the figure to remember: the share of parameters actually trained in the complete multimodal model.
# LoRA sur le decodeur : preparer le corps 4-bit puis greffer les adaptateursfrom peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training, TaskTypemodel_base = prepare_model_for_kbit_training(model_base)lora_config = LoraConfig( task_type=TaskType.CAUSAL_LM, r=16, # rang des matrices LoRA lora_alpha=32, # facteur d'echelle (ratio 2:1 usuel) lora_dropout=0.05, # regularisation pour un entrainement court target_modules=["q_proj", "k_proj", "v_proj", "o_proj", # attention complete"linear_attn.out_proj", # attention lineaire (Gated DeltaNet)"gate_proj", "up_proj", "down_proj", # MLP ], bias="none",)model_sft = get_peft_model(model_base, lora_config)model_sft.print_trainable_parameters()if torch.cuda.is_available():print(f"\nVRAM avant entrainement : {torch.cuda.memory_allocated() /1e6:.0f} Mo")
trainable params: 7,274,496 || all params: 860,260,416 || trainable%: 0.8456
VRAM avant entrainement : 1385 Mo
Reading the LoRA configuration.print_trainable_parameters() displays 7,274,496 trainable parameters out of 860,260,416 in total — 0.8456%. For comparison, FT-03 reports exactly the same numbers; the two outputs show no growth, and LoRA targets the modules named below (the exact scope of the composition of the total denominator — decoder + any other model components — cannot be established from this comparison alone). The LoRA target — q/k/v/o_proj, linear_attn.out_proj, gate/up/down_proj — is strictly on the language side; peft does not add any adapter matrix on model.visual.* in this configuration. The VRAM before training (1385 MB) gives the memory starting point: the adapters and their optimizer states will be added to it, but the 4-bit body will not move — that is the QLoRA efficiency. The modules actually targeted are the ones declared in the LoraConfig above — q/k/v/o_proj for full attention, linear_attn.out_proj for linear attention, gate/up/down_proj for the MLPs, the two attention families of the hybrid Qwen3.5 architecture — and print_trainable_parameters() does not list them: it only prints the three counts above.
5. QLoRA Training
The pipeline follows the mechanics of FT-03 with one major difference: the collator must go through the processor, because each example mixes an image and text. It is the processor that, batch by batch, tokenizes the texts, prepares the pixels, replaces the <|image_pad|> marker with the exact number of visual tokens, pads to the batch length — and creates the labels: padding positions are masked to −100 (excluded from the loss), as are the image tokens themselves (the model does not have to learn to emit visual tokens, only the text response).
Key hyperparameters: - per_device_train_batch_size=1 + gradient_accumulation_steps=8 — the sequences contain image tokens: the effective batch size of 8 is reconstructed by accumulation to keep a tiny micro-batch (the run’s VRAM peak stays below 1.5 GB) - num_train_epochs=5 — 24 examples × 5 epochs ≈ 15 optimization steps, a deliberately tiny budget - learning_rate=2e-4 — standard LoRA rate, ~100× that of pretraining, safe because only the adapters move - warmup_steps=3 — warmup is counted in steps (transformers 5.x removed warmup_ratio) - bf16=True + gradient_checkpointing=True — wide precision and recomputed activations: the combination that makes training a VLM fit on a consumer card
# Dataset HuggingFace + collator multimodal (le processor traite chaque lot image+texte)from datasets import Datasetfrom transformers import TrainingArguments, Trainertrain_dataset = Dataset.from_list(train_exemples)print(f"Dataset pret : {len(train_dataset)} exemples, colonnes : {train_dataset.column_names}")def collate_fn(exemples):"""Applique le processor aux (image, texte) du lot et fabrique les labels masques.""" lots = processor( text=[e["texte"] for e in exemples], images=[e["image"] for e in exemples], padding=True, return_tensors="pt", ) labels = lots["input_ids"].clone()# padding hors loss... labels[labels == processor.tokenizer.pad_token_id] =-100# ...et jetons d'image hors loss : le modele apprend la reponse, pas les tokens visuels labels[labels == processor.image_token_id] =-100 lots["labels"] = labelsreturn lots# Verifier le collator sur un mini-lot de 2 exemplesapercu = collate_fn([train_exemples[0], train_exemples[1]])print(f"Forme input_ids du lot : {apercu['input_ids'].shape}")print(f"Positions hors loss (labels == -100) : {(apercu['labels'] ==-100).sum().item()} jetons")
Dataset pret : 24 exemples, colonnes : ['image', 'texte']
Forme input_ids du lot : torch.Size([2, 94])
Positions hors loss (labels == -100) : 128 jetons
Reading the preparation. The mini-batch shows a true length of 94 tokens for 2 examples — compare this with the purely textual lengths from section 2 (29-31 tokens per example): the difference is the visual tokens inserted by the processor in place of the <|image_pad|> marker — 64 visual tokens per image (the two texts in this batch are 31 tokens: 31 − 1 marker + 64 visual tokens = 94). The 128 masked positions (labels at −100) are exactly the image tokens of the two examples (2 × 64) — since the two texts are the same length, this batch has no alignment padding: the loss will apply only to the useful text — the model learns neither to emit visual tokens nor to predict padding. Dataset.from_list stores the PIL images (Arrow encoding) and returns them as image objects when sampled — the collator is the only place where the processor is involved during training.
Debut de l'entrainement QLoRA (24 exemples, 5 epoques)...
[15/15 04:47, Epoch 5/5]
Step
Training Loss
5
4.597577
10
0.634687
15
0.070737
Entrainement termine en 308.4s (5.1 min)
Perte finale : 1.7677
VRAM apres entrainement : 1452 Mo
Reading the training. Three metrics come out of this cell. The duration: 308.4 s (5.1 min) for 24 examples × 5 epochs ≈ 15 optimization steps, each accumulating 8 micro-batches. The final loss: 1.7677 — the contract is short and repetitive, and the descent is clear from the first steps; but the lesson from FT-03 still fully applies: a low loss on a mini-dataset measures local memorization, not generalization, and says nothing about compliance on held-out images. The VRAM: 1452 MB after training (versus 1385 before) — the ~67 MB difference is on the order of what is expected for 7.3 M adapter parameters with their optimizer states and gradients. The useful verdict will be read in section 6, on never-before-seen images.
6. Comparative evaluation: base vs LoRA
The moment of truth: we repeat exactly the protocol from section 3 — the same 6 held-out images, the same prompt, the same evaluation function, the same greedy decoding — on the fine-tuned model. The table compares the three metrics measured before training (stored in metriques_base) with their values after training, and displays the signed delta; two raw outputs side by side show the change in textual regime. Nothing is reconstructed by hand: every number in the table comes from the variables measured in the previous cells.
# Evaluation comparative : modele de base vs modele LoRA (memes images, meme protocole)model_sft.eval()metriques_lora, lignes_lora = evaluer_modele(model_sft, test_exemples, nom="modele LoRA")print()print("="*66)print("COMPARATIF : MODELE DE BASE vs MODELE LORA (6 images held-out)")print("="*66)print(f"{'Metrique':<22}{'Base':>12}{'LoRA':>12}{'Delta':>12}")print("-"*66)for cle in ("respecte_format", "accuracy_forme", "accuracy_couleur"): delta = metriques_lora[cle] - metriques_base[cle]print(f"{cle:<22}{metriques_base[cle]:>12.2f}{metriques_lora[cle]:>12.2f}{delta:>+12.2f}")print("\nSorties brutes cote a cote (2 premieres images) :")for i inrange(min(2, len(lignes_lora))):print(f"\nImage {i +1} — verite : {lignes_lora[i]['verite']}")print(f" Base : {lignes_base[i]['sortie'][:110]}")print(f" LoRA : {lignes_lora[i]['sortie'][:110]}")
--- Evaluation : modele LoRA (6 images held-out) ---
Verite Conforme Forme Couleur Sortie (60 car.)
disque/jaune True True True [IMG] forme=disque couleur=jaune [FIN]
carre/jaune True True True [IMG] forme=carre couleur=jaune [FIN]
disque/bleu True True True [IMG] forme=disque couleur=bleu [FIN]
carre/rouge True True True [IMG] forme=carre couleur=rouge [FIN]
disque/rouge True True True [IMG] forme=disque couleur=rouge [FIN]
triangle/vert True True True [IMG] forme=triangle couleur=vert [FIN]
Conformite de format : 1.00
Accuracy forme : 1.00
Accuracy couleur : 1.00
==================================================================
COMPARATIF : MODELE DE BASE vs MODELE LORA (6 images held-out)
==================================================================
Metrique Base LoRA Delta
------------------------------------------------------------------
respecte_format 0.00 1.00 +1.00
accuracy_forme 0.00 1.00 +1.00
accuracy_couleur 0.00 1.00 +1.00
Sorties brutes cote a cote (2 premieres images) :
Image 1 — verite : disque/jaune
Base : <think>
</think>
L'image présente une simple composition graphique :
* **Contenu central :** Il y a un ce
LoRA : [IMG] forme=disque couleur=jaune [FIN]
Image 2 — verite : carre/jaune
Base : <think>
</think>
D'après l'image, il s'agit d'une image simplifiée et abstraite.
Voici une décomposition de
LoRA : [IMG] forme=carre couleur=jaune [FIN]
Reading the comparison. The table speaks for itself: compliance 0.00 → 1.00, shape accuracy 0.00 → 1.00, color accuracy 0.00 → 1.00 — 6/6 held-out images perfectly described, shape and color correct, contract respected from start to finish. Three things to note. (1) Compliance and correctness rise together: the feared case (maximum compliance, mediocre accuracy — the learned skeleton without reading the image) did not occur; the loss did force the contents of the fields. (2) Frozen vision was sufficient: the vision tower and the merger, untouched, were already extracting the right features (section 3 showed this in prose) — LoRA only taught the decoder to read them in the contract format. (3) Generalization is real: the 6 test images are not in the 24 training images (different position/size jitter) — the contract transfers to never-before-seen pixels, just as the tag format from FT-03 transferred to reformulations.
7. Why the decoder only?
The question deserves its own section, because it generalizes beyond this practical: where should adapters be placed when fine-tuning a VLM? Our answer here — the decoder — rests on three arguments.
1. The behavior to install is a language behavior. The contract [IMG] forme=… couleur=… [FIN] does not require anything new on the perception side: distinguishing a red disk from a blue square is a task that the frozen vision tower already largely solves. What the model lacks is the formatting: emitting the delimiters, the field names, the order, the closing [FIN]. All of that lives in the decoder — it is the component that produces the token sequence. Adapting the decoder’s attention and MLP projections gives LoRA exactly the degrees of freedom needed to reorganize the output language.
2. Freezing vision preserves an already competent feature extractor. The vision tower was pre-trained on millions of images; recalibrating it on 24 synthetic images of primary shapes would be useless at best, destructive at worst — overfitting a massive extractor on a tiny dataset is the classic recipe for degradation. Freezing is a safeguard here.
3. The budget follows the decision. Each targeted module adds its LoRA matrices (rank × dimensions). Targeting only the decoder keeps the footprint and training within a modest budget (≤ 1.5 GB of VRAM measured in this run); adding vision enlarges the adapters for a gain that, on such a perceptually simple task, must be demonstrated rather than assumed.
The boundary is not dogmatic, however: when the task requires visual discrimination that the merger encodes poorly (subtle shades, positions, spatial relations), targeting the visual projections — the merger model.visual.merger (linear_fc1, linear_fc2) — becomes the natural extension. This is precisely exercise 3: measuring what this targeting adds (or does not add) in parameters and metrics.
8. Cleaning GPU Memory
We free the model and its adapters before the exercises section — exercise 3 reloads a fresh model, and freeing before reloading avoids accumulating two copies and their allocation caches. The before/after measurement quantifies the footprint of the 4-bit body + adapters + allocation cache.
The three exercises each extend one thread from the notebook: (1) the richness of the contract — does a new form require more data for the same compliance?; (2) the broadening of the contract — a position= field tests whether the model reads the image, not just the format; (3) the scope of LoRA — also target vision and measure what that really changes. Each exercise reuses the previous cells; reload a fresh model as in section 1 if you ran the cleanup from section 8.
Exercise 1: a fourth shape — the star
Add a shape etoile to the dataset (10 vertices alternating outer radius and inner radius for ImageDraw.polygon), regenerate training and test, retrain with the same hyperparameters, measure compliance again.
Questions: with how many examples per combination was maximum compliance reached with 3 shapes — and is this number sufficient for 4 shapes? Is format compliance still acquired faster than the accuracy of the new field?
# Exercice 1 : ajouter la forme "etoile" au dataset et re-entrainer# TODO etudiant : completez dessiner_etoile, regenerez le dataset avec 4 formes,# relancez les cellules des sections 2 a 6, puis relevez la conformite obtenue.def dessiner_etoile(cx, cy, rayon_ext, rayon_int):"""Retourne les 10 sommets d'une etoile centree en (cx, cy)."""# Indice : bouclez sur 10 sommets en alternant rayon_ext et rayon_int,# angle progressant de pi/5 par sommet (depart en haut : -pi/2),# puis dessinez la liste avec draw.polygon(...) dans dessiner_forme.passFORMES_ETENDUES = ["disque", "carre", "triangle"] # TODO etudiant : ajoutez "etoile"exemples_par_combinaison =None# TODO etudiant : combien d'exemples pour la conformite ?print("Exercice a completer : etoile dessinee, dataset regenere, conformite relevee")
Exercice a completer : etoile dessinee, dataset regenere, conformite relevee
Exercise 2: Extend the contract to the position field
Generate shapes positioned in the upper or lower half of the image, extend the expected response to [IMG] forme=… couleur=… position=<haut|bas> [FIN], add accuracy_position to the evaluation (same pattern as accuracy_forme), retrain, and compare.
Question: Does compliance with the new field come as quickly as compliance with the format — and does the LoRA model’s position accuracy catch up with that of the other fields, or does spatial localization prove more resistant?
# Exercice 2 : etendre le contrat au champ position=<haut|bas># TODO etudiant : binarisez cy (cy < 64 -> "haut", sinon "bas") dans generer_ensemble,# etendez construire_reponse(), ajoutez accuracy_position a evaluer_modele()# (meme motif que accuracy_forme) ; re-entrainez et comparez avant/apres.resultats_position = {"accuracy_position_base": None, # TODO etudiant : mesure apres re-evaluation du modele de base"accuracy_position_lora": None, # TODO etudiant : mesure apres re-entrainement}# Indice : position et couleur varient independamment — verifiez que vos images# de test couvrent les deux positions, sinon l'accuracy position ne mesurera rien.print("Exercice a completer : contrat etendu, metrique ajoutee, comparaison faite")
Exercice a completer : contrat etendu, metrique ajoutee, comparaison faite
Exercise 3: also target vision — the merger in target_modules
Reload a fresh 4-bit model and build a LoraConfig identical to the one in section 4 plus the visual merger modules (visual.merger.linear_fc1, visual.merger.linear_fc2). Compare three things with the decoder-only run: the number of trainable parameters (print_trainable_parameters), training VRAM, and the final metrics on the same 6 images.
Question: on a task where vision was already competent, does the parameter overhead buy a measurable gain in compliance or accuracy — or was the decoder alone already the right scope?
# Exercice 3 : cibler aussi la vision — ajouter visual.merger aux target_modules# TODO etudiant : rechargez un modele 4-bit frais, construisez la LoraConfig avec# les modules du merger en plus, re-entrainez, comparez params / VRAM / metriques.config_vision =None# TODO etudiant : LoraConfig identique + ["visual.merger.linear_fc1", "visual.merger.linear_fc2"]# Indice : apres la section 8 le GPU est libre — rechargez comme en section 1# (meme BitsAndBytesConfig), puis prepare_model_for_kbit_training, get_peft_model,# et relevez print_trainable_parameters() et les trois metriques held-out.print("Exercice a completer : run decoder+vision livre et compare au run decoder-seul")
Exercice a completer : run decoder+vision livre et compare au run decoder-seul
10. Summary of FT-06
Concept
Detail
Vision-language model
Vision tower (ViT) + merger + decoder — loaded via AutoModelForImageTextToText (555 M params), prepared via AutoProcessor
Bounded task
12 shape × color combinations on deterministic PIL images — 24 train / 6 held-out
Output contract
[IMG] forme=… couleur=… [FIN] — a measurable language behavior
Metrics
respecte_format (compliance), accuracy_forme, accuracy_couleur — same protocol before/after
Decoder-only LoRA
7.3 M parameters (0.85%) on hybrid attention + MLP; vision tower and merger frozen
QLoRA training
4-bit NF4 body, bf16, gradient checkpointing — 308.4 s (5.1 min), loss 1.7677, VRAM ≤ 1452 MB
Result
Compliance 0.00 → 1.00, shape 0.00 → 1.00, color 0.00 → 1.00 on 6 held-out — the base model already saw (correct prose on the visible excerpts) but ignored the contract
TP takeaway: the base model described the images in correct prose — the three readable excerpts from section 3 (quoted verbatim, in French: “un cercle bleu pur”, “un cercle rouge centré”, “un triangle vert simple”) contain the exact shape and color — the failure was purely contractual, not perceptual. By freezing vision and adapting 0.85% of the decoder parameters, LoRA installed the contract and the structured reading of visual features: 6/6 never-before-seen images described exactly in the required format. The architectural lesson: when the task is a perception-conditioned language behavior, adapting the decoder is enough — the pretrained perception is already good.
Next steps: the exercises extend the contract (4th shape, position field), then test the boundary of this conclusion (also target the merger — exercise 3 measures what adapted vision adds when it already has everything it needs).