Visual Instruction Tuning Loss: Label Masks, Causal Shift and Freezing
Visual Instruction Tuning Loss: Label Masks, Causal Shift and Freezing
Search
Ask the AI

Visual Instruction Tuning Loss: Label Masks, Causal Shift and Freezing

This article explains the loss function for assistant-response supervision in Visual Instruction Tuning, with checks for aligned labels and frozen parameters.

The Core Concept: Multimodal Auto-Regressive Next-Token Prediction

In the autoregressive MLLMs discussed here, the model predicts the next text token from its preceding context. Models such as LLaVA and Qwen-VL supply continuous visual features through an encoder and connector. These features can occupy sequence positions without being discrete text vocabulary IDs. CLIP is one encoder source; the fusion path depends on the model.

The Math: Multi-Modal Auto-Regressive Loss

Given an image \(\mathbf{X}_v\) and instruction–response text \(\mathbf{X}_t\), let \(\mathbf{H}_v\) denote visual representations and \(\mathbf{H}_t\) text embeddings. The simplified prefix concatenation is \(\mathbf{H} = [\mathbf{H}_v, \mathbf{H}_t]\). Images can also be inserted at specified conversation positions; a single visual prefix is not universal.

Under teacher forcing, the gold response \(\mathbf{X}_{response}\) supplies targets conditioned on the image \(\mathbf{X}_v\), instruction \(\mathbf{X}_{instruct}\) and preceding gold text. The loss function \(L\) is the negative log-likelihood. The first equation sums unmasked text targets, with instruction conditioning included in the prefix. Its upper limit L denotes text sequence length, distinct from the loss function with the same name.

$$L(\theta) = -\sum_{i=1}^{L} \log p_\theta(x_i | \mathbf{X}_v, x_{\lt i})$$

Assistant-response label mask
For this objective, the boolean mask \(\mathbf{M}\) selects gold assistant targets: \(m_i = 1\) when the \(i\)-th target belongs to a response, and \(m_i = 0\) for user/system text and padding. Visual-position labels are ignored too. Continuous visual vectors are not vocabulary targets: the equation does not mean evaluating an undefined visual-token probability and then multiplying it by zero.

The next equation averages valid response targets. Count them after causal shifting, truncation and padding, and require a positive denominator. For unweighted cross-entropy over a batch, this is a mean over valid tokens, not an equally weighted mean of each sequence’s mean loss.

$$L(\theta) = -\frac{1}{\sum_{i=1}^{L} m_i} \sum_{i=1}^{L} m_i \log p_\theta(x_i | \mathbf{X}_v, x_{\lt i})$$

Data Flow: From JSON to Masked Labels

The following diagram traces data from disk to the loss function:


graph TD
    A[Multimodal JSON Dataset] -->|Extract| B(Image Path & Conversation)
    B --> C{Tokenizer & Processor}
    C -->|Image| D[Vision Encoder -> Image Tokens]
    C -->|Text| E[LLM Tokenizer -> Text Tokens]
    D --> F[Sequence Concatenation]
    E --> F
    F --> G[Generate Label Mask]
    G -->|Image & Instruction Tokens| H[Label = -100 Ignored]
    G -->|Response Tokens| I[Label = Token ID]
    H --> J[PyTorch CrossEntropyLoss]
    I --> J

PyTorch Implementation: Masking the Labels

PyTorch’s CrossEntropyLoss ignores integer targets equal to -100 by default. Here labels select assistant-response supervision. A label mask selects direct loss terms; an attention mask controls accessible context. Prompt and image positions can still influence answers through causal attention, so ignoring their labels does not remove every gradient path through those inputs.


import torch
from torch.utils.data import Dataset

IGNORE_INDEX = -100
IMAGE_TOKEN_ID = 32000 # Example ID for <image>

class MultimodalDataset(Dataset):
    def __init__(self, data, tokenizer):
        self.data = data
        self.tokenizer = tokenizer
        
    def __getitem__(self, idx):
        item = self.data[idx]
        # Example format: "<image>\nUser: What is this?\nAssistant: A cat."
        text = item['conversations'] 
        
        # 1. Tokenize the entire sequence
        input_ids = self.tokenizer(text, return_tensors="pt").input_ids[0]
        
        # 2. Clone input_ids to create labels
        labels = input_ids.clone()
        
        # 3. Mask out the image tokens
        labels[labels == IMAGE_TOKEN_ID] = IGNORE_INDEX
        
        # 4. Mask out the user instruction (simplified logic for demonstration)
        # Find the delimiter where the assistant's response begins
        assistant_token_id = self.tokenizer.convert_tokens_to_ids("Assistant:")
        try:
            assistant_idx = (input_ids == assistant_token_id).nonzero(as_tuple=True)[0][0]
            # Mask everything up to the assistant's response (including the prompt)
            labels[:assistant_idx + 1] = IGNORE_INDEX
        except IndexError:
            pass # Handle edge cases
            
        return {
            "input_ids": input_ids,
            "labels": labels,
            "image_path": item['image']
        }

Limits of the original simplified example: The retained Dataset omits length, image loading and collation. “Assistant:” need not be one token, and converting a token string to an ID is not string tokenization. Passing when the boundary is absent keeps user labels; later user turns after the first boundary also remain unmasked. The value 32000 is illustrative. The model-specific processor must produce per-turn assistant masks and align them through visual expansion, truncation, EOS and padding.

The independent correction below checks only aligned label and loss tensors after visual expansion. The model’s processor supplies these inputs; visual placeholder IDs must be excluded by visual_mask. This helper implements neither tokenization nor image encoding nor chat templates. It shifts causal targets once. Use the model’s own loss directly if its forward method already handles this shift.

import torch
import torch.nn.functional as F

IGNORE_INDEX = -100

def make_labels(token_ids, assistant_mask, attention_mask, visual_mask, vocab_size):
    # Inputs are already aligned AFTER visual expansion and padding.
    if token_ids.ndim != 2 or token_ids.dtype != torch.long:
        raise ValueError("token_ids must be a B x T LongTensor")
    for mask in (assistant_mask, attention_mask, visual_mask):
        if mask.shape != token_ids.shape or mask.dtype != torch.bool:
            raise ValueError("masks must be aligned B x T BoolTensors")
        if mask.device != token_ids.device:
            raise ValueError("masks and token_ids must share a device")
    keep = assistant_mask & attention_mask & ~visual_mask
    if vocab_size <= 0 or ((token_ids[keep] < 0) | (token_ids[keep] >= vocab_size)).any():
        raise ValueError("answer targets must be in the text vocabulary")
    labels = torch.full_like(token_ids, IGNORE_INDEX)
    labels[keep] = token_ids[keep]
    return labels

def causal_answer_loss(logits, labels):
    # Use this ONLY when the model has not already shifted/computed its loss.
    if logits.ndim != 3 or labels.shape != logits.shape[:2]:
        raise ValueError("expected B x T x V logits and B x T labels")
    if labels.dtype != torch.long or labels.device != logits.device:
        raise ValueError("labels must be LongTensor on the logits device")
    if not logits.is_floating_point() or not torch.isfinite(logits).all():
        raise ValueError("logits must be finite floating point values")
    targets = labels[:, 1:]
    count = (targets != IGNORE_INDEX).sum()
    if count.item() == 0:
        raise ValueError("no supervised targets remain after causal shift")
    loss_sum = F.cross_entropy(
        logits[:, :-1, :].reshape(-1, logits.shape[-1]),
        targets.reshape(-1), ignore_index=IGNORE_INDEX, reduction="sum")
    return loss_sum / count, count

LLaVA’s two-stage schedule and frozen parameters

Label masking selects direct loss terms; freezing selects parameter updates. The original LLaVA uses the two-stage recipe below. Other MLLMs can use different stages and trainable modules.

Stage one trains only the projector, freezing the vision encoder and LLM weights while fitting the visual interface with image–caption pairs. This fixes the downstream LLM parameters. Random projector initialization alone does not establish that joint training must degrade language ability.

Freezing LLM weights still requires an autograd path from response loss to the projector. Wrapping the entire LLM forward pass in torch.no_grad() would cut that path. Original LLaVA converts captions into single-turn image-description instructions; data sufficiency depends on the target task.

Stage two updates both the projector and LLM on visual instruction data while keeping the vision encoder frozen. The pretrained projector supplies initialization, but it continues to change during training; the input distribution is not fixed by this schedule.

The vision encoder stays frozen throughout original LLaVA training. That is a choice in this recipe. Whether to update it depends on the target domain, data, learning rate, budget and held-out results. Small instruction datasets can increase overfitting risk without making degradation inevitable.

# Stage one: only the projector is trainable
for p in vision_encoder.parameters(): p.requires_grad = False
for p in llm.parameters():            p.requires_grad = False
for p in projector.parameters():      p.requires_grad = True

# Stage two: unfreeze the LLM, vision encoder still frozen
for p in llm.parameters():            p.requires_grad = True

When freezing parameters, check existing gradients and optimizer groups. PyTorch AdamW skips parameters whose grad is None, including weight decay. Passing frozen parameters through model.parameters() does not itself update them. Setting requires_grad to False prevents new gradients from backward, but a retained gradient tensor can still be used by the optimizer; zero is different from None. Clear stale gradients when freezing. If the optimizer originally received only trainable parameters, unfreezing also requires adding those parameters or rebuilding it.

opt = torch.optim.AdamW(
    [p for p in model.parameters() if p.requires_grad],  # filter is mandatory
    lr=2e-5, weight_decay=0.0)

The original “filtering is mandatory” comment is too strong. Filtering trainable parameters simplifies group management; it is not necessary for AdamW to skip grad=None parameters. Its weight_decay=0.0 setting cannot demonstrate decay of frozen weights either. When freezing, set p.requires_grad_(False), clear p.grad=None, and check the parameter values after the next step.

Check label masks against the loss

Falling loss alone does not establish correct supervision. Some label errors still allow training; out-of-range vocabulary targets can raise an error. Inspect labels, the valid-target count after causal shift and the associated prediction positions.

Check visual-position and user-instruction labels separately:

Visual labels are not ignored. A valid vocabulary placeholder ID becomes a supervised text target; an out-of-range ID can raise an error. A continuous visual vector is not an integer class label. These errors do not imply a necessarily high starting loss or fixed plateau; inspect the actual targets.

User instructions contribute to response loss. This adds user-text prediction terms and changes the assistant-only objective used here. Whether the model then invents further questions requires inference and turn-termination tests. Other objectives may intentionally supervise more text; record that choice explicitly.

Inspect label tensors and test multiple turns, absent boundaries, visual expansion, truncation and padding. The print example below applies only when input_ids and labels still share the same position alignment:

ignored = (labels == -100).sum().item()
total   = labels.numel()
print(f"ignored {ignored}/{total}")
# decode the part that actually contributes to loss and read it
kept = input_ids[labels != -100]
print(tokenizer.decode(kept))

In the final aligned labels, check that supervised vocabulary targets contain only the specified assistant replies and their termination tokens. Ignore image, user, system and padding targets. Decode each sample separately and check the valid count after shifting. One decoded sample does not cover the entire preprocessing pipeline.

Production Pitfalls

1. Catastrophic Forgetting

A large learning rate and narrow visual instruction data can degrade existing language capabilities through catastrophic forgetting. Compare mixtures with text-only data such as Alpaca or ShareGPT, and evaluate language and visual tasks before and after tuning. Results depend on mixture and data quality; mixing alone does not guarantee retention.

2. Why We Freeze the Vision Encoder

Original LLaVA stage two freezes the Vision Encoder, such as CLIP ViT, while training the Projection Layer and LLM. Evaluate representation and resource conditions separately when choosing what to freeze:

  • Representation Stability: The original CLIP paper reports 400 million image–text pairs, not billions; check the source of other checkpoints separately. Its features provide a transfer starting point, but a Manifold description does not establish target-domain suitability. With a dataset such as 150k instruction samples, compare overfitting risk through held-out tasks and learning-rate choices.
  • Compute Efficiency: Freezing the vision encoder and omitting its backward graph can reduce that module’s gradient, optimizer-state and activation costs. For 7B or 13B LLMs, feasible batch size still depends on sequence length, precision and training method. A frozen LLM may still need activation storage to train its projector through it. Gradient Accumulation also works in unfrozen configurations.

Implementation checks: The Vision Encoder supplies continuous features; the processor aligns response labels with the final sequence; the loss averages valid shifted targets; and optimizer updates depend on parameter groups and actual gradient state. Measure visual understanding and reasoning on held-out tasks.

Leave a Reply

Scroll down