# MuseGlimmer: image-conditioned text generation with Transformers This page is the Transformers contract of the MuseGlimmer 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 `optimumintel/tiny-random-muse-glimmer`. 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 pin the checkpoint or variant and print the result record. ## Describe two images ```py runnable:describe 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 = "optimum-intel-internal-testing/tiny-random-muse-glimmer" 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 # Two synthetic images that differ in colour, not only in texture. images = [ np.full((56, 56, 3), (200, 40, 40), dtype=np.uint8), np.full((56, 56, 3), (40, 40, 200), dtype=np.uint8), ] messages = [ [ {"role": "user", "content": [ {"type": "image", "image": images[0]}, {"type": "text", "text": "What colour is this image?"}, ]}, ], [ {"role": "user", "content": [ {"type": "image", "image": images[1]}, {"type": "text", "text": "What colour is this image?"}, ]}, ], ] texts = [ processor.apply_chat_template(m, add_generation_prompt=True, tokenize=False) for m in messages ] inputs = processor(text=texts, images=images, padding=True, return_tensors="pt") inputs = inputs.to(device) if "pixel_values" in inputs: inputs["pixel_values"] = inputs["pixel_values"].to(dtype=model.dtype) model.eval() with torch.no_grad(): outputs = model(**inputs) # Probe the last position of each sequence (left padding puts the real last token at -1). probe_logits = outputs.logits[:, -1, :] predicted = probe_logits.argmax(dim=-1) print(processor.batch_decode(predicted.unsqueeze(-1), skip_special_tokens=True)) ``` ## One training step ```py runnable:describe:2 # Causal-LM labels: copy input_ids and mask padded positions. labels = inputs["input_ids"].clone() 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.self_attn.q_proj.weight", # doc-builder: hide "model.vision_adapter.fc1.weight", # doc-builder: hide ) # 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 }, # doc-builder: hide "predicted_tokens": predicted.tolist(), # doc-builder: hide "predicted_text": processor.batch_decode(predicted.unsqueeze(-1), skip_special_tokens=True), # doc-builder: hide "answer_logits": probe_logits[:, predicted].float().tolist(), # doc-builder: hide "training": { # doc-builder: hide "loss": loss.item(), # doc-builder: hide "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}, # doc-builder: hide "updated": any(not torch.equal(p.detach().cpu(), before[n]) for n, p in model.named_parameters() if n in before), # doc-builder: hide }, # doc-builder: hide } # doc-builder: hide print(json.dumps(result)) # doc-builder: hide ```