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

HyperCLOVAX-SEED-Think-32B: vision-language generation with Transformers

This page is the Transformers contract of the HyperCLOVAX-SEED-Think-32B MIC and also a usage example. doc-builder renders the runnable blocks below as documentation, and its pytest plugin runs them as written against naver-hyperclovax/HyperCLOVAX-SEED-Think-32B. The MIC runner runs the same blocks against the slim fixture and the 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.

Describe a batch of images

import torch
from transformers import AutoProcessor, HyperCLOVAXVisionV2ForConditionalGeneration, set_seed
import json  # doc-builder: hide
import os  # doc-builder: hide
import numpy as np  # doc-builder: hide
from PIL import Image  # doc-builder: hide

model_id = "naver-hyperclovax/HyperCLOVAX-SEED-Think-32B"
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 and is too large for a float32 copy on a single GPU.
model = HyperCLOVAXVisionV2ForConditionalGeneration.from_pretrained(model_id, dtype=torch.bfloat16).to(device)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = HyperCLOVAXVisionV2ForConditionalGeneration.from_pretrained(model_id, **{"dtype": torch.bfloat16, **variant}).to(device)  # doc-builder: hide

# Two small images that differ in colour, not only texture, so the vision tower can tell them apart.
def make_image(offset):  # doc-builder: hide
    h, w = 112, 112  # doc-builder: hide
    y, x = np.mgrid[:h, :w]  # doc-builder: hide
    arr = np.zeros((h, w, 3), dtype=np.uint8)  # doc-builder: hide
    arr[..., 0] = (x + 2 * y + offset) % 256  # doc-builder: hide
    arr[..., 1] = (2 * x + y + offset * 2) % 256  # doc-builder: hide
    arr[..., 2] = (x + y + offset * 3) % 256  # doc-builder: hide
    return Image.fromarray(arr)  # doc-builder: hide

images = [make_image(0), make_image(64)]  # doc-builder: hide
texts = ["Describe this image in detail.", "What colours are in this image?"]
messages = [[{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": t}]}] for t in texts]
prompts = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
inputs = processor(text=prompts, images=images, return_tensors="pt", padding=True).to(device, dtype=model.dtype)
generated = model.generate(**inputs, max_new_tokens=16, do_sample=False)
print(processor.batch_decode(generated, skip_special_tokens=True))

One training step

# Train on labels the model does not predict: the overfit fixture predicts its own outputs,
# and the near-zero loss leaves bfloat16 weights unchanged.
with torch.no_grad():
    logits = model(**inputs).logits
labels = (logits.argmax(-1) + 1) % model.config.text_config.vocab_size
# Mask image placeholder tokens so the loss only covers text.
for token_id in [model.config.image_token_id, model.config.image_start_token_id, model.config.image_end_token_id]:
    labels[labels == token_id] = -100

# Freeze everything except the language-model head and the last decoder layer:
# a full training step on a 32B model does not fit the GPU.
last_layer = model.config.text_config.num_hidden_layers - 1
for name, param in model.named_parameters():
    if not (name.startswith("model.projector") or name.startswith(f"model.language_model.layers.{last_layer}")):
        param.requires_grad_(False)

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.projector.weight",
        f"model.language_model.layers.{last_layer}.self_attn.q_proj.weight",
        f"model.language_model.layers.{last_layer}.mlp.gate_proj.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),
        "label_logprobs": logits.float().log_softmax(-1).gather(-1, labels.clamp(min=0)[..., None])[..., 0].masked_fill(labels == -100, 0.0).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),
        },
    }
    print(json.dumps(result))