# MiniCPM-OCR: document understanding with Transformers This page is the Transformers contract of the MiniCPM-OCR 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 `openbmb/MiniCPM-OCR-1.0`. 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. ## Read an image ```py runnable:minicpm_ocr import json # doc-builder: hide import os # doc-builder: hide import numpy as np import torch from transformers import AutoProcessor, MiniCPMOcrForConditionalGeneration, set_seed model_id = "openbmb/MiniCPM-OCR-1.0" 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 is stored in bfloat16; load it in bfloat16 so it fits on the GPU. model = MiniCPMOcrForConditionalGeneration.from_pretrained(model_id, dtype=torch.bfloat16).to(device) if variant: # doc-builder: hide del model # doc-builder: hide model = MiniCPMOcrForConditionalGeneration.from_pretrained(model_id, **{"dtype": torch.bfloat16, **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 ```py runnable:minicpm_ocr:2 # 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 # Train on labels the model does not predict: shift by one modulo the vocabulary. labels = (labels + 1) % model.config.text_config.vocab_size labels[labels == 0] = -100 # keep padding masked 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 next(n for n in named if n.endswith("linear_attn.in_proj_qkv.weight")), # doc-builder: hide next(n for n in named if n.endswith("mlp.down_proj.weight")), # doc-builder: hide next(n for n in named if n.endswith("merger.mlp.0.linear_1.weight")), # doc-builder: hide ) # doc-builder: hide probe = logits[:, -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 ```