nemo_automodel.recipes.vlm.finetune
nemo_automodel.recipes.vlm.finetune
Module Contents
Classes
Functions
Data
API
Bases: BaseRecipe
Recipe for fine-tuning a VLM model.
Configure local model stages before the VLM dataloader is built.
Publish the CP-only group while a VLM forward may run its vision tower.
Create the distributed setup used by this recipe rank.
Run one local batch and accumulate its loss and optional gradients.
Parameters:
Microbatch index in the accumulation window.
Input mapping with token IDs, labels, and physical NEAT document IDs of shape [batch, sequence]. NEAT attention metadata is batch-major; legacy THD inputs are flattened by the sharder. VLM media and position tensors retain the model’s input layout. THD MTP requires physical boundaries in cu_seqlens_padded of shape [num_sequences + 1] or [1, num_sequences + 1], or _packed_seq_ids [batch, sequence] supplied by the native model sharder from physical seq_lens_padded [batch, num_sequences].
List receiving the detached scalar loss.
Global supervised-token count for loss normalization.
Number of microbatches in the accumulation window.
Whether to backpropagate the combined main and MTP loss.
Return base_loss + lambda * sum_k CE(drafter_logits[k], shifted_labels_k).
If out does not carry a non-empty drafter_logits attribute (i.e. the
model isn’t a joint composite), returns base_loss unchanged.
For drafter step k, labels are shifted left by k positions to match
the VLM collate’s pre-shifted convention (labels[t] == input_ids[t+1]).
log=True emits a one-line breakdown on rank 0; callers should gate this
on the appropriate step / microbatch index to avoid log spam.
Execute a single training step.
Parameters:
List of batches of training data.
Gradient clipping norm. Optional, if None will not clip gradients.
Run one pass over self.val_dataloader.
Whether this rank owns the trainable model and its components.
Log metrics to wandb.
Parameters:
Training loss.
Grad norm from the training step.
Total number of loss tokens.
Tokens per second.
Log metrics to wandb and other loggers Args: log_data: MetricsSample object, containing: step: int, the current step. epoch: int, the current epoch. metrics: Dict[str, float], containing: “val_loss”: Validation loss. “lr”: Learning rate. “num_label_tokens”: Number of label tokens. “mem”: Memory allocated.
Run the training loop over all epochs and batches.
For each batch, perform a forward pass, compute loss, backpropagate, and update model parameters when necessary. Also prints loss every gradient step.
Builds all components needed for training/validation/logging/checkpointing/etc.
This is the last place where self.cfg should be referenced.
Raises:
NotImplemented: Raises if it tries to restore a checkpoint; will be removed.
Model capability required by packed VLM context parallelism.
Whether the model’s active backend owns packed CP routing.
Model capability required by the VLM vision frame-sharding recipe policy.
Whether the model owns a verified CP vision frame-sharding integration.
Return the set of model _target_ callables this recipe accepts.
These are the wrapper-layer entrypoints that know how to absorb the
recipe’s infrastructure kwargs (device_mesh, distributed_config,
peft_config, freeze_config, pipeline_config, plus the
optional moe_config / fp8_config / compile_config). Anything
not on this list is rejected with a clear error — vanilla
transformers.AutoModelFor* does not handle these kwargs and would
otherwise fail deep inside HF code.
New infra-aware composites (e.g. Gemma4WithDrafter) opt in by adding their .from_pretrained
(and .from_config if applicable) here.
The Gemma4 joint composite is added behind a try/except because it
requires the optional transformers.models.gemma4_assistant module
that ships with transformers>=5.8.0.dev.
True if target is on this recipe’s allowlist of model entrypoints.
Shift labels left by k positions, padding the tail with -100.
Used to build drafter-step targets in joint base + drafter training.
The VLM collate pipeline already pre-shifts labels by 1 so that
labels[t] == input_ids[t + 1] (the next-token target). Drafter step k
predicts position t + 1 + k of the original sequence, which corresponds
to labels[t + k] in the pre-shifted convention. So for step k:
k = 0(one-step drafter) -> no shift; reuselabelsas-is.k = 1-> shift labels left by 1 (drafter predicts two tokens ahead).k = n-> shift labels left byn.
Parameters:
[B, S] LongTensor of label ids (-100 marks ignored
positions).
Number of positions to shift to the left. k <= 0 is a no-op.
Returns: torch.Tensor
A new [B, S] LongTensor with labels[:, k:] in the leading slice
Reject packed CP before dataloader construction when routing is unsupported.
Reject enabled vision frame sharding when the model has no production integration.
Build a DataLoader for the VLM dataset.
Parameters:
Dataset configuration.
DataLoader configuration.
Pretrained model name or path for processor loading.
Processor configuration or None.
Device mesh for distributed training.
Random seed.
Local batch size.
Deprecated compatibility argument; ignored.
Packed sequence configuration (top-level packed_sequence: section).
When provided, takes precedence over dataset.packing.
Optional model.get_rope_index callable. When provided,
VLM neat packing computes mRoPE 3D position IDs per sample so packed
mRoPE-aware models (Qwen2.5-VL, Qwen3-VL, …) preserve multimodal
position semantics across pack boundaries instead of falling back to
plain 1D positions.
When set, wrap collate so VLM media tensors are pre-chunked for this many PP microbatches before entering the train loop.
Built model supplying the structural packing contract.
Returns: tuple[DataLoader, ProcessorMixin]
The instantiated DataLoader and processor.
Build and initialize a model for VLM.
Returns: tuple[nn.Module | AutoPipeline, list['Optimizer']]
The instantiated model and optimizer.
Main entry point for the fine-tuning recipe.
Loads the configuration, sets up the trainer, and initiates the training loop.