# Idefics2: image-text-to-text with Transformers This page is the Transformers contract of the Idefics2 MIC and also a usage example. [doc-builder](https://github.com/huggingface/doc-builder/blob/main/docs/runnable-code-blocks.md) renders the `runnable` blocks below as documentation, and its pytest plugin runs them as written against `HuggingFaceM4/idefics2-8b-base`. The MIC runner runs the same blocks against each slim fixture and each checkpoint in [`integration.json`](../../integration.json). Lines marked `# doc-builder: hide` only matter there: they swap in the pinned checkpoint or variant and print the result record. ## Inference: image-text batch ```py runnable:idefics2_image_text import torch from transformers import AutoProcessor, AutoModelForImageTextToText, set_seed import json # doc-builder: hide import os # doc-builder: hide import numpy as np # doc-builder: hide from PIL import Image # doc-builder: hide model_id = "HuggingFaceM4/idefics2-8b-base" model_id = os.environ.get("MIC_MODEL", model_id) # doc-builder: hide variant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}")) # doc-builder: hide device = "cuda" if torch.cuda.is_available() else "cpu" set_seed(0) # seeds torch, NumPy, and Python: loading, dropout, and data augmentation draw random numbers processor = AutoProcessor.from_pretrained(model_id) # The checkpoint has 8.4B parameters: a float32 copy does not fit the GPU, so load in bfloat16. model = AutoModelForImageTextToText.from_pretrained(model_id, dtype=torch.bfloat16).to(device) if variant: # doc-builder: hide del model # doc-builder: hide model = AutoModelForImageTextToText.from_pretrained(model_id, **{"dtype": torch.bfloat16, **variant}).to(device) # doc-builder: hide # Build two small synthetic images that differ in colour, not only texture. def make_image(offset): # doc-builder: hide h, w = 64, 64 # doc-builder: hide y, x = np.mgrid[:h, :w] # doc-builder: hide arr = np.zeros((h, w, 3), dtype=np.uint8) # doc-builder: hide arr[..., 0] = (x + offset) % 256 # doc-builder: hide arr[..., 1] = (y + 2 * offset) % 256 # doc-builder: hide arr[..., 2] = (x + y + 3 * offset) % 256 # doc-builder: hide return Image.fromarray(arr) # doc-builder: hide image1 = make_image(0) # doc-builder: hide image2 = make_image(80) # doc-builder: hide prompts = [ "In this image, we can see", "In this image, we can see", ] images = [[image1], [image2]] inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(device) model.eval() with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits last_positions = inputs["attention_mask"].sum(dim=-1) - 1 batch_idx = torch.arange(len(prompts), device=device) selected_logits = logits[batch_idx, last_positions, :10].float() predicted_ids = logits[batch_idx, last_positions].argmax(dim=-1) predicted_tokens = [processor.tokenizer.decode([pid], skip_special_tokens=True) for pid in predicted_ids.tolist()] print(f"predicted: {predicted_tokens}") print(f"selected_logits: {selected_logits.tolist()}") ``` ## One training step ```py runnable:idefics2_image_text:2 labels = inputs["input_ids"].clone() labels[inputs["attention_mask"] == 0] = -100 labels[labels == model.config.image_token_id] = -100 # A full bfloat16 training step on 8.4B parameters (weights plus gradients) does not fit the GPU. # Freeze the model and train only the language-model head, which the loss reaches directly. model.requires_grad_(False) model.lm_head.weight.requires_grad_(True) model.train() optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01) loss = model(**inputs, labels=labels).loss loss.backward() before = {n: p.detach().cpu().clone() for n, p in model.named_parameters() if p.requires_grad} # doc-builder: hide optimizer.step() print(f"loss: {loss.item():.4f}") if os.environ.get("MIC_RUNNER"): # doc-builder: hide named = dict(model.named_parameters()) checked = tuple(n for n, p in named.items() if p.requires_grad and p.grad is not None and p.ndim >= 2 and torch.count_nonzero(p.grad) > 0)[:2] frozen_checked = next(n for n, p in named.items() if not p.requires_grad and p.ndim >= 2) result = { "runtime": { "device": model.device.type, "dtype": str(next(model.parameters()).dtype).removeprefix("torch."), "attn_implementation": model.config._attn_implementation, "attn_implementations": {n: getattr(model.config, n)._attn_implementation for n in sorted(model.config.sub_configs) if getattr(getattr(model.config, n, None), '_attn_implementation', None)}, }, "predicted_tokens": predicted_tokens, "answer_logits": selected_logits.tolist(), "training": { "loss": loss.item(), "gradients": {n: bool(named[n].grad is not None and torch.count_nonzero(named[n].grad) > 0 and torch.isfinite(named[n].grad).all()) for n in checked}, "updated": any(not torch.equal(p.detach().cpu(), before[n]) for n, p in model.named_parameters() if n in before), }, } print(json.dumps(result)) ```