tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
cd55ca8 verified |
Download integrations/transformers/usage.md from huggingface-mic/blip-image-captioning-base-mic: direct link, hf CLI and curl.
- Browser
- Download file 4.74 kB
-
https://huggingface.co/huggingface-mic/blip-image-captioning-base-mic/resolve/main/integrations/transformers/usage.md
- Command line
-
hf download hf://huggingface-mic/blip-image-captioning-base-mic/integrations/transformers/usage.md
-
curl -L -o usage.md https://huggingface.co/huggingface-mic/blip-image-captioning-base-mic/resolve/main/integrations/transformers/usage.md
4.74 kB
| # BLIP: image captioning with Transformers | |
| This page is the Transformers contract of the BLIP 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 `Salesforce/blip-image-captioning-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. | |
| The images are synthetic, so the example runs offline: two distinct colour blocks. A real checkpoint captions them as noise; the slim fixture is trained to name them. | |
| ## Generate captions for a batch | |
| ```py runnable:caption | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from transformers import BlipForConditionalGeneration, BlipProcessor, set_seed | |
| import json # doc-builder: hide | |
| import os # doc-builder: hide | |
| model_id = "Salesforce/blip-image-captioning-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 = BlipProcessor.from_pretrained(model_id) | |
| model = BlipForConditionalGeneration.from_pretrained(model_id).to(device) | |
| if variant: # doc-builder: hide | |
| model = BlipForConditionalGeneration.from_pretrained(model_id, **variant).to(device) | |
| # Two distinct colour blocks: the fixture can tell them apart, and a real checkpoint sees different inputs. | |
| images = [ | |
| Image.fromarray(np.full((384, 384, 3), (220, 20, 60), dtype=np.uint8)), | |
| Image.fromarray(np.full((384, 384, 3), (30, 144, 255), dtype=np.uint8)), | |
| ] | |
| inputs = processor(images=images, return_tensors="pt").to(device, model.dtype) | |
| generated = model.generate(**inputs, max_new_tokens=8) | |
| print(processor.batch_decode(generated, skip_special_tokens=True)) | |
| ``` | |
| ## Conditional captioning | |
| BLIP accepts an optional text prefix. The processor tokenizes it as the decoder prompt. | |
| ```py runnable:caption:3 | |
| conditional_inputs = processor(images=images, text=["a picture of", "a picture of"], return_tensors="pt").to(device, model.dtype) | |
| conditional = model.generate(**conditional_inputs, max_new_tokens=8) | |
| print(processor.batch_decode(conditional, skip_special_tokens=True)) | |
| ``` | |
| ## One training step | |
| ```py runnable:caption:3 | |
| captions = ["a red block", "a blue block"] | |
| targets = processor(text=captions, return_tensors="pt", padding=True).to(device) | |
| labels = targets.input_ids.masked_fill(targets.attention_mask == 0, -100) | |
| with torch.no_grad(): # doc-builder: hide | |
| # Teacher-forced logits for the reference captions. | |
| logits = model(pixel_values=inputs.pixel_values, input_ids=targets.input_ids).logits | |
| logits_probe = logits[:, -1, :8].float() | |
| model.train() | |
| optimizer = torch.optim.SGD(model.parameters(), lr=0.01) | |
| loss = model(pixel_values=inputs.pixel_values, input_ids=targets.input_ids, labels=labels).loss | |
| loss.backward() | |
| before = {name: p.detach().clone() for name, p in model.named_parameters()} # 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 = ( | |
| "vision_model.encoder.layers.0.self_attn.qkv.weight", | |
| "text_decoder.bert.encoder.layer.0.crossattention.self.query.weight", | |
| ) | |
| result = { | |
| "runtime": { | |
| "device": model.device.type, | |
| "dtype": str(model.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)}, | |
| }, | |
| "generated_tokens": generated.tolist(), | |
| "generated_text": processor.batch_decode(generated, skip_special_tokens=True), | |
| "conditional_tokens": conditional.tolist(), | |
| "conditional_text": processor.batch_decode(conditional, skip_special_tokens=True), | |
| "logits_probe": logits_probe.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, before[n]) for n, p in named.items()), | |
| }, | |
| } | |
| print(json.dumps(result)) | |
| ``` | |