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

Gemma: causal language modeling with Transformers

This page is the Transformers contract of the Gemma MIC and also a usage example. doc-builder renders the runnable blocks below as documentation, and its pytest plugin runs them as written against google/gemma-2b. The MIC runner runs the same blocks against each slim fixture and each 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.

Predict the next token

import os
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed

model_id = "google/gemma-2b"
model_id = os.environ.get("MIC_MODEL", model_id)  # doc-builder: hide
variant = __import__("json").loads(os.environ.get("MIC_MODEL_KWARGS", "{}"))  # doc-builder: hide
device = "cuda" if torch.cuda.is_available() else "cpu"
set_seed(0)

tokenizer = AutoTokenizer.from_pretrained(model_id)
# The checkpoint is stored in bfloat16; load in float32 so the seeded SGD step is stable.
model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.float32).to(device)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = AutoModelForCausalLM.from_pretrained(model_id, **{"dtype": torch.float32, **variant}).to(device)  # doc-builder: hide
model.eval()

prompts = [
    "The capital of France is",
    "Machine learning is a field of",
]
inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(device)

with torch.no_grad():
    outputs = model(**inputs)

# Probe the last non-padded position of each sequence.
last = inputs["attention_mask"].sum(dim=-1) - 1
logits = outputs.logits[torch.arange(len(prompts)), last]
next_ids = logits.argmax(dim=-1)
next_text = tokenizer.batch_decode(next_ids.unsqueeze(-1))
probe_logits = logits[:, next_ids].float().tolist()
print(next_text)

# One seeded training step on the same batch.
labels = inputs["input_ids"].clone()
labels[inputs["attention_mask"] == 0] = -100
model.train()
optimizer = torch.optim.SGD(model.parameters(), 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
    import json  # doc-builder: hide
    named = dict(model.named_parameters())  # doc-builder: hide
    checks = ["model.layers.0.self_attn.q_proj.weight", "model.layers.0.mlp.gate_proj.weight"]  # doc-builder: hide
    result = {  # doc-builder: hide
        "runtime": {"device": model.device.type, "dtype": str(model.dtype).replace("torch.", ""), "attn_implementation": model.config._attn_implementation},  # doc-builder: hide
        "next_ids": [int(i) for i in next_ids],  # doc-builder: hide
        "next_text": next_text,  # doc-builder: hide
        "probe_logits": probe_logits,  # doc-builder: hide
        "training": {  # doc-builder: hide
            "loss": float(loss.item()),  # doc-builder: hide
            "gradients": {n: bool(named[n].grad is not None and torch.isfinite(named[n].grad).all() and torch.count_nonzero(named[n].grad) > 0) for n in checks},  # 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