Download integrations/transformers/usage.md from huggingface-mic/recurrentgemma-2b-mic: direct link, hf CLI and curl.
- Browser
- Download file 5.03 kB
-
https://huggingface.co/huggingface-mic/recurrentgemma-2b-mic/resolve/main/integrations/transformers/usage.md
- Command line
-
hf download hf://huggingface-mic/recurrentgemma-2b-mic/integrations/transformers/usage.md
-
curl -L -o usage.md https://huggingface.co/huggingface-mic/recurrentgemma-2b-mic/resolve/main/integrations/transformers/usage.md
RecurrentGemma: causal language modeling with Transformers
This page is the Transformers contract of the RecurrentGemma 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/recurrentgemma-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.
RecurrentGemma mixes recurrent (RG-LRU + conv1d) blocks with sliding-window attention blocks, so it is a decoder-only causal LM with the usual input_ids / attention_mask / labels interface. The checkpoint is a base (pretraining) model: it has a tokenizer and a causal-LM head, but no chat template.
Next-token logits for a padded batch
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
import json # doc-builder: hide
import os # doc-builder: hide
model_id = "google/recurrentgemma-2b"
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 and any dropout draw random numbers
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).to(device)
if variant: # doc-builder: hide
del model # doc-builder: hide
model = AutoModelForCausalLM.from_pretrained(model_id, **variant).to(device) # doc-builder: hide
model.eval()
# Two prompts of different lengths so padding and the attention mask are exercised.
prompts = [
"The capital of France is",
"Two plus two equals",
]
# Left padding keeps the last position a real token for every row.
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "left"
inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(device)
# The recurrent blocks reset their state where position_ids == 0 and do not read the mask,
# so derive positions from it (as generate does): the first real token of each row is 0.
inputs["position_ids"] = (inputs["attention_mask"].cumsum(-1) - 1).clamp(min=0)
with torch.no_grad():
logits = model(**inputs).logits
# Probe a few logits: the last position of each row, and the first real token of row 0.
last = logits[:, -1, :]
first_real = logits[0, inputs["attention_mask"][0].bool().nonzero()[0].item(), :]
probe_ids = torch.tensor([tokenizer.convert_tokens_to_ids("Paris"), tokenizer.convert_tokens_to_ids("4")], device=device)
print("last-position logits for 'Paris' and '4':", last[:, probe_ids].float().tolist())
One training step
# Causal-LM labels: copy the input ids and mask padded positions out of the loss.
labels = inputs["input_ids"].clone()
labels[inputs["attention_mask"] == 0] = -100
model.train()
# Full fine-tuning of 2.7B float32 parameters does not fit a 24 GB GPU: train the
# (tied) token embeddings and the first recurrent block, and freeze the rest.
for name, param in model.named_parameters():
param.requires_grad = name.startswith(("model.embed_tokens.", "model.layers.0."))
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.embed_tokens.weight",
"model.layers.0.temporal_block.rg_lru.recurrent_param",
"model.layers.0.mlp_block.gate_proj.weight",
"model.layers.0.temporal_block.linear_x.weight",
)
result = {
"runtime": {
"device": model.device.type,
"dtype": str(model.dtype).removeprefix("torch."),
"attn_implementation": model.config._attn_implementation,
},
"logits": {
"last": last[:, probe_ids].float().tolist(),
"first_real": first_real[probe_ids].float().tolist(),
},
"training": {
"loss": loss.item(),
"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 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))