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

MiniMax-M3-MXFP8: VLM inference and projector training

This page is the Transformers contract of the MiniMax-M3-MXFP8 MIC and also a usage example. doc-builder renders the runnable blocks below as documentation. The MIC runner runs the same blocks against each slim fixture and the pinned checkpoint. Lines marked # doc-builder: hide only matter to the runner: they swap in the pinned checkpoint or variant and print the result record.

Text inference

import numpy as np
import torch
from PIL import Image
from transformers import (
    AutoTokenizer,
    MiniMaxM3SparseForConditionalGeneration,
    MiniMaxM3VLImageProcessor,
    MiniMaxM3VLProcessor,
    MiniMaxM3VLVideoProcessor,
    set_seed,
)
from transformers.utils import cached_file
import json  # doc-builder: hide
import os  # doc-builder: hide

model_id = "MiniMaxAI/MiniMax-M3-MXFP8"
model_id = os.environ.get("MIC_MODEL", model_id)  # doc-builder: hide
variant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}"))  # doc-builder: hide
set_seed(0)

# The repository's processor config points at remote code; build the native processor from its parts
with open(cached_file(model_id, "chat_template.jinja"), encoding="utf-8") as f:
    chat_template = f.read()
processor = MiniMaxM3VLProcessor(
    image_processor=MiniMaxM3VLImageProcessor.from_pretrained(model_id),
    video_processor=MiniMaxM3VLVideoProcessor.from_pretrained(model_id),
    tokenizer=AutoTokenizer.from_pretrained(model_id),
    chat_template=chat_template,
)

# The MXFP8 weights compute in bfloat16; on GPUs, device_map="auto" spreads the 428B-parameter MoE
device_map = "auto" if torch.cuda.is_available() else "cpu"
model = MiniMaxM3SparseForConditionalGeneration.from_pretrained(model_id, dtype=torch.bfloat16, device_map=device_map)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = MiniMaxM3SparseForConditionalGeneration.from_pretrained(model_id, **{"dtype": torch.bfloat16, "device_map": device_map, **variant})  # doc-builder: hide

def textured_image(height, width, colour, seed):
    # The base colour plus a gradient and seeded noise: every patch differs, so patch order, crops and resizing all change the pixels.
    rng = np.random.default_rng(seed)
    y, x = np.mgrid[0:height, 0:width]
    ramp = (48 * (x / width + y / height) - 48)[..., None]
    pixels = np.asarray(colour, dtype=np.float64) + ramp + rng.normal(0, 24, (height, width, 3))
    return Image.fromarray(np.clip(pixels, 0, 255).astype(np.uint8))

# Two textured images of one size with the same question: both rows tokenize to the same length, so no
# padding is needed. Padding would shift the sparse indexer's key blocks, which are anchored to slots.
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What colour is this image?"}]}]
prompt = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False, thinking_mode="disabled")
images = [textured_image(672, 672, (200, 30, 30), seed=0), textured_image(672, 672, (30, 30, 200), seed=1)]
inputs = processor(images=images, text=[prompt, prompt], return_tensors="pt").to(model.device, dtype=model.dtype)

model.eval()
with torch.no_grad():
    logits = model(**inputs).logits
# Compact probe: a few next-token logits for each image
probe = logits[:, -1, [0, 100, 5000, 50000]].float()
position_norms = logits[:, torch.linspace(0, logits.shape[1] - 1, min(logits.shape[1], 32)).long()].float().norm(dim=-1)
print(probe.tolist())

One training step on the multimodal projector

# Fine-tune only the vision-language projector (kept unquantized in the MXFP8 checkpoint); the
# language model and vision tower stay frozen
model.requires_grad_(False)
model.model.multi_modal_projector.requires_grad_(True)

# Next-token labels on the answer position only
labels = inputs["input_ids"].clone()
labels[:, :-1] = -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())
    checked = ("model.multi_modal_projector.linear_1.weight", "model.multi_modal_projector.linear_2.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)},
        },
        "logits_probe": probe.tolist(),
        "position_norms": position_norms.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),
            "frozen": named["model.language_model.embed_tokens.weight"].grad is None,
        },
    }
    print(json.dumps(result))