# MT5: seq2seq generation with Transformers This page is the Transformers contract of the MT5 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 `google/mt5-small`. 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. ## Translate a batch ```py runnable:mt5 import torch from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, set_seed import json # doc-builder: hide import os # doc-builder: hide model_id = "google/mt5-small" 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 generation draw random numbers tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForSeq2SeqLM.from_pretrained(model_id).to(device) if variant: # doc-builder: hide del model # doc-builder: hide model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **variant).to(device) # doc-builder: hide # MT5 is multilingual; the "translate English to German:" prefix selects the task. prompts = [ "translate English to German: The house is wonderful.", "translate English to German: I like to read books.", ] inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(device) model.eval() with torch.no_grad(): generated = model.generate(**inputs, max_new_tokens=8) logits = model(**inputs, decoder_input_ids=generated).logits decoded = tokenizer.batch_decode(generated, skip_special_tokens=True) print(decoded) # Probe a few logits at the first generated position of each sequence. probe = logits[:, 0, :5].float().tolist() ``` ## One training step ```py runnable:mt5:2 # Teacher forcing: the labels are the tokenized German references. references = ["Das Haus ist wunderbar.", "Ich lese gerne Bücher."] labels = tokenizer(references, return_tensors="pt", padding=True).to(device)["input_ids"] labels[labels == tokenizer.pad_token_id] = -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 = ( "encoder.block.0.layer.0.SelfAttention.q.weight", "decoder.block.0.layer.0.SelfAttention.q.weight", "decoder.block.0.layer.1.EncDecAttention.q.weight", ) result = { "runtime": { "device": model.device.type, "dtype": str(model.dtype).removeprefix("torch."), "attn_implementation": model.config._attn_implementation, }, "decoded_text": decoded, "probe_logits": probe, "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)) ```