tarekziade's picture
tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
5cec567 verified
|
Raw History Blame Contribute Delete
5.57 kB

MiniCPM-V-4.6: image chat with Transformers

This page is the Transformers contract of the MiniCPM-V-4.6 MIC and also a usage example. doc-builder renders the runnable blocks below as documentation, and its pytest plugin runs them as written against openbmb/MiniCPM-V-4.6. The MIC runner runs the same blocks against each slim fixture and each checkpoint in integration.json. Lines marked # doc-builder: hide only matter there: they swap in the pinned checkpoint or variant and print the result record.

Ask about an image

import json  # doc-builder: hide
import os  # doc-builder: hide

import numpy as np
import torch
from transformers import AutoModelForImageTextToText, AutoProcessor, set_seed

model_id = "openbmb/MiniCPM-V-4.6"
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)
model = AutoModelForImageTextToText.from_pretrained(model_id).to(device)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = AutoModelForImageTextToText.from_pretrained(model_id, **variant).to(device)  # doc-builder: hide
model.eval()

# Two synthetic images that differ in colour so the vision tower sees distinct inputs.
red_image = np.zeros((64, 64, 3), dtype=np.uint8)
red_image[..., 0] = 220
blue_image = np.zeros((64, 64), dtype=np.uint8)
blue_image[...] = 200
blue_image = np.stack([blue_image, blue_image, np.full_like(blue_image, 30)], axis=-1)
images = [red_image, blue_image]

prompts = [
    "What is the dominant colour of this image?",
    "Describe the colour of this picture.",
]
messages = [
    [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt}]}]
    for prompt in prompts
]
texts = [
    processor.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
    for msgs in messages
]
inputs = processor(text=texts, images=images, return_tensors="pt", padding=True)
inputs = inputs.to(device, dtype=model.dtype)

with torch.no_grad():
    generated = model.generate(**inputs, max_new_tokens=8, do_sample=False)
trimmed = [out[len(inp):] for inp, out in zip(inputs["input_ids"], generated)]
generated_text = processor.batch_decode(trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
print(generated_text)

One training step

# Keep the inference outputs from the previous block for the result record.
logits = None  # doc-builder: hide
with torch.no_grad():  # doc-builder: hide
    out = model(**inputs)  # doc-builder: hide
    logits = out.logits  # doc-builder: hide

labels = inputs["input_ids"].clone()
if "attention_mask" in inputs:
    labels[inputs["attention_mask"] == 0] = -100

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())  # doc-builder: hide
    checked = (  # doc-builder: hide
        "model.language_model.layers.0.linear_attn.in_proj_qkv.weight",  # doc-builder: hide
        "model.language_model.layers.0.mlp.down_proj.weight",  # doc-builder: hide
        "model.merger.mlp.0.linear_1.weight",  # doc-builder: hide
    )  # doc-builder: hide
    probe = logits[0, -1, :8].float().tolist()  # doc-builder: hide
    result = {  # doc-builder: hide
        "runtime": {  # doc-builder: hide
            "device": model.device.type,  # doc-builder: hide
            "dtype": str(model.dtype).removeprefix("torch."),  # doc-builder: hide
            "attn_implementation": model.config._attn_implementation,  # doc-builder: hide
            "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)},  # doc-builder: hide
        },  # doc-builder: hide
        "generated_text": generated_text,  # doc-builder: hide
        "logits": {"probe": probe},  # doc-builder: hide
        "training": {  # doc-builder: hide
            "loss": loss.item(),  # doc-builder: hide
            "gradients": {  # doc-builder: hide
                n: bool(  # doc-builder: hide
                    named[n].grad is not None  # doc-builder: hide
                    and torch.count_nonzero(named[n].grad) > 0  # doc-builder: hide
                    and torch.isfinite(named[n].grad).all()  # doc-builder: hide
                )  # doc-builder: hide
                for n in checked  # doc-builder: hide
            },  # doc-builder: hide
            "updated": any(  # doc-builder: hide
                not torch.equal(p.detach().cpu(), before[n])  # doc-builder: hide
                for n, p in model.named_parameters()  # doc-builder: hide
                if n in before  # doc-builder: hide
            ),  # doc-builder: hide
        },  # doc-builder: hide
    }  # doc-builder: hide
    print(json.dumps(result))  # doc-builder: hide