Automodel icon indicating copy to clipboard operation
Automodel copied to clipboard

Same data + same hyperparams, NeMo-AutoModel LoRA on Gemma 4 31B regresses below base while Unsloth lifts +4pp (suspected VLM recipe routing for text-only data)

Open nuts-has-been-taken opened this issue 7 months ago β€’ 6 comments

Summary

Training Gemma 4 31B with identical data and identical hyperparameters on two frameworks produces an 8pp pass-rate gap on a 100-sample held-out eval:

Framework Pass rate Ξ” vs base
No FT (base google/gemma-4-31B-it) 88% β€”
NeMo-AutoModel FinetuneRecipeForVLM LoRA 84% βˆ’4pp
Unsloth LoRA (single-GPU, same data, same r/Ξ±/lr/epochs) 92% +4pp

NeMo's training loop converges cleanly (training loss 0.05–0.10, val_loss 0.0984 at LOWEST_VAL), checkpoint saves, dequantize-merge succeeds, vLLM serves the merged BF16 model with 32k ctx. The model just regresses on the downstream task. This looks like exactly the kind of "silent regression" called out in #1509 (E2E Convergence Robustness Roadmap), with a Gemma 4 + VLM recipe combination that is currently outside the convergence test plan.

Setup

  • Task: instruction-tuned text-only LoRA fine-tuning for domain-specific code generation
  • Base: google/gemma-4-31B-it
  • Data: 2,659 single-turn (system + user + assistant) text-only samples, ≀8K tokens, distilled from a stronger teacher model. Same JSONL on both frameworks (NeMo VLM conversation schema vs Unsloth messages schema, same content).
  • Held-out eval: 100 fixtures, downstream pass-rate is whether the generated script passes a strict mechanical validator. Identical eval pipeline for both runs.
  • Hyperparams (identical): LoRA r=32, Ξ±=32, all linear modules, AdamW lr 2e-4 cosine, Ξ²=(0.9, 0.95), wd=0.01, 3 epochs, global batch 8 / local batch 1, BF16 base + bnb 4-bit NF4 + bnb_4bit_quant_storage=bf16.
  • Hardware: NeMo on 4Γ— H100 80GB (FSDP2), Unsloth on 1Γ— A100 80GB (single-GPU).

NeMo config (relevant excerpts)

recipe: FinetuneRecipeForVLM

model:
  _target_: nemo_automodel.NeMoAutoModelForImageTextToText.from_pretrained
  pretrained_model_name_or_path: google/gemma-4-31B-it
  torch_dtype: torch.bfloat16
  use_liger_kernel: true
  use_sdpa_patching: false
  attn_implementation: sdpa
  text_config:
    use_cache: false
  quantization_config:
    _target_: transformers.BitsAndBytesConfig
    load_in_4bit: true
    bnb_4bit_quant_type: nf4
    bnb_4bit_compute_dtype: bfloat16
    bnb_4bit_use_double_quant: true
    bnb_4bit_quant_storage: bfloat16
    llm_int8_skip_modules: ["lm_head"]

peft:
  _target_: nemo_automodel.components._peft.lora.PeftConfig
  match_all_linear: false
  exclude_modules:
    - "*vision_tower*"
    - "*vision*"
    - "*visual*"
    - "*image_encoder*"
    - "*lm_head*"
    - "*audio*"
  dim: 32
  alpha: 32
  use_triton: true

distributed:
  strategy: fsdp2
  dp_size: none
  tp_size: 1
  cp_size: 1
  sequence_parallel: false
  activation_checkpointing: true

loss_fn:
  _target_: nemo_automodel.components.loss.masked_ce.MaskedCrossEntropy

dataloader:
  collate_fn:
    _target_: nemo_automodel.components.datasets.vlm.collate_fns.default_collate_fn

freeze_config:
  freeze_embeddings: true
  freeze_vision_tower: true
  freeze_audio_tower: true
  freeze_language_model: false

Training trace (healthy)

step 999/999  loss 0.10  lr 2.0e-6  mem 24-30 GiB/GPU  tps 3.5-4.1k
[val] step 998 | epoch 2 | loss 0.1025
LOWEST_VAL = epoch_1_step_665 (val_loss=0.0984)
total: 2h 38min on 4x H100

No NaNs, no warnings, no spikes. Gradient norm well-behaved. Checkpoints round-trip via the dequantize-then-save_pretrained flow used to convert bnb-4bit-merged weights to clean BF16 safetensors for vLLM.

What's Surprising

Training looked entirely healthy by every visible metric, yet the resulting LoRA delta produced a model that is worse than the un-fine-tuned base on the same eval that Unsloth's run lifted by +4pp.

base NeMo v1 Unsloth v1
Pass rate 88% 84% 92%
Both pass with base β€” 76 n/a
Saved by FT (base FAIL β†’ FT PASS) β€” 8 n/a
Broken by FT (base PASS β†’ FT FAIL) β€” 12 n/a

3 of the 12 base-PASS-but-NeMo-FAIL fixtures are textbook simple parsers that base solved on the first attempt. NeMo's LoRA delta breaks them β€” this isn't a "lost some hard cases" pattern, the distribution has drifted.

Hypothesis

The most plausible candidate from the closed/open issues we surveyed is VLM-recipe routing for text-only data:

  • NeMoAutoModelForImageTextToText constructs embed_vision, embed_audio, lm_head directly as nn.Linear (per the dtype probe in NVIDIA-NeMo/Automodel#2017), separate from nested text_config-controlled modules.
  • Even with freeze_vision_tower: true and PEFT exclusion patterns covering vision/audio/image_encoder/lm_head, the forward pass for a text-only sample still goes through the multimodal wrapper. Whether the activations that LoRA modules see exactly match the corresponding inner activations of Gemma4ForCausalLM (the path that vLLM uses at inference) is an open question β€” there's no convergence/parity test currently gating that (#1509).
  • The closed-but-related fix in NVIDIA-NeMo/Automodel#2017 shows that nested-config dtype routing in this exact recipe was wrong until very recently for fp32 cases. Our run uses bf16 throughout so we don't hit that exact bug, but it indicates the wrapper has had real correctness issues against text_config boundaries.

A secondary candidate is use_liger_kernel: true Γ— Gemma 4 heterogeneous head_dim (256 normal vs 512 global layers). Liger fused ops + this mixed head_dim configuration is not in any of the convergence test plans listed in #1509, and #676 (still open since 2025-08) shows liger has unresolved interactions with other parallelism modes.

Why This Issue

Per #1509, NVIDIA acknowledges "weight-loading mismatch, a broken RoPE implementation, or a parallelism config that diverges numerically can all ship without obvious symptoms until users hit them in production." Our case is exactly that β€” training metrics are clean, no errors, no warnings, but downstream task quality regresses 8pp vs an alternative framework on identical inputs. We're filing this so:

  1. It contributes a concrete reproducible data point for the convergence roadmap, specifically for FinetuneRecipeForVLM with text-only data on Gemma 4 31B (not in any current test plan).
  2. If others see "NeMo trained without errors but my eval got worse", they have a search hit.

Reproduction

The dataset is domain-specific so we can't share it directly, but the recipe is the standard one β€” anyone with a text-only instruction dataset and a stronger reference framework (Unsloth, HF Trainer, Axolotl…) can reproduce by training the same data on FinetuneRecipeForVLM vs the reference, then comparing downstream task quality.

To make this self-contained for triage, a minimal repro would be: take any small LoRA recipe from examples/llm_finetune/ that uses FinetuneRecipeForCausalLM, port it to FinetuneRecipeForVLM with NeMoAutoModelForImageTextToText + the VLM conversation schema (text-only, no images), train identical hyperparams on both, then run a token-level KL divergence vs an HF Trainer / Unsloth-trained adapter on the same data. Per #1509 this is exactly the kind of comparison that is currently un-CI-gated.

Environment

Field Value
nemo-automodel 0.4.0+f39ff585 (pip-installed from main)
transformers 5.5.0 (pinned per known-good window)
torch 2.10.0 + CUDA 12.9
pytorch_cuda_alloc_conf expandable_segments:True
Hardware 4Γ— H100 80GB, FSDP2
Image base nvcr.io/nvidia/nemo-automodel:26.02.00 (with manual upgrade per known-good install steps)
Eval serving vLLM 0.20.0, --max-model-len 32768, --gpu-memory-utilization 0.85, --tensor-parallel-size 4

Cross-references

  • #1509 β€” E2E Convergence Robustness Roadmap (Gemma 4 + VLM recipe not in convergence test plan)
  • NVIDIA-NeMo/Automodel#1679 β€” Training instability with healthy-looking loss / sinusoidal grad_norm pattern (still open, waiting-on-maintainers)
  • NVIDIA-NeMo/Automodel#2017 β€” Gemma 4 VLM nested-config dtype routing was wrong (closed, but indicative of the wrapper's bug surface)
  • NVIDIA-NeMo/Automodel#1853 β€” Gemma 4 31B FSDP2 OOM with FinetuneRecipeForVLM (closed, multiple latent issues found)
  • #676 β€” CP + liger kernel (open since 2025-08, milestone 26.02)

Happy to share more details (training log, validation log, the exact dequantize-merge script, the eval interaction logs) on request.

nuts-has-been-taken avatar May 03 '26 05:05 nuts-has-been-taken

@nuts-has-been-taken Thank you so much for the issue. Could you please share your training log(loss curve) for both unsloth and automodel on the same dataset, as well as the dequantize-merge script and eval logs?

HuiyingLi avatar May 03 '26 05:05 HuiyingLi

@HuiyingLi Thanks. Below are the artifacts you asked for. Speculation removed β€” only data we actually have.

NeMo training loss

Sampled every ~50 steps from training.jsonl (full 999-step file available on request, 296 KB):

step epoch loss grad_norm lr
0 0 0.5689 22.18 2.18e-05
1 0 0.6526 7.61 2.36e-05
50 0 0.1394 0.89 1.13e-04
100 0 0.1570 1.55 2.00e-04
150 0 0.1011 0.45 1.98e-04
200 0 0.1249 2.00 1.94e-04
250 0 0.1221 1.49 1.86e-04
300 0 0.1070 0.83 1.76e-04
332 0 0.1137 0.96 1.69e-04
400 1 0.0777 2.61 1.50e-04
500 1 0.0742 0.40 1.17e-04
600 1 0.1174 1.90 8.27e-05
665 1 0.0541 0.77 6.13e-05
700 2 0.0574 0.68 5.05e-05
800 2 0.0849 0.78 2.44e-05
900 2 0.0740 0.49 7.53e-06
950 2 0.0898 0.77 3.28e-06
998 2 0.1014 2.66 2.00e-06

Validation loss (val_every_steps: 200 + epoch boundaries):

step epoch val_loss
199 0 0.1173
332 0 0.1115
399 1 0.1090
599 1 0.1000
665 1 0.0984 ← LOWEST_VAL
799 2 0.1033
998 2 0.1025

Unsloth comparison

The per-step Unsloth loss log was on a GCP Spot A100 instance that has since been torn down β€” we did not preserve the curve. The only number we recorded is the final training loss = 0.172. Loss decreased monotonically over 3 epochs but we don't have intermediate values.

Dequantize-merge script

dequantize_to_bf16.py
"""Convert the 4-bit merged model to clean BF16 safetensors.

peft.merge_and_unload() on a bnb-4bit base preserves the 4-bit format
(LoRA delta is merged into the packed 4-bit weights). Walk the merged
model, dequantize every bnb.nn.Linear4bit to nn.Linear(bfloat16), then
save_pretrained as standard safetensors.
"""

import os, shutil
import torch
import torch.nn as nn
import bitsandbytes as bnb
from transformers import AutoModelForImageTextToText, AutoProcessor, BitsAndBytesConfig
from peft import PeftModel

BASE = "google/gemma-4-31B-it"
ADAPTER = "/data/ckpt/.../LOWEST_VAL/model"
OUT = "/data/merged/..._dequantbf16"

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_storage=torch.bfloat16,
    llm_int8_skip_modules=["lm_head"],
)
base = AutoModelForImageTextToText.from_pretrained(
    BASE, quantization_config=bnb_config, device_map="auto",
)
peft_model = PeftModel.from_pretrained(base, ADAPTER)
merged = peft_model.merge_and_unload()

def dequantize_recursive(module):
    for name, child in list(module.named_children()):
        if isinstance(child, bnb.nn.Linear4bit):
            weight_bf16 = bnb.functional.dequantize_4bit(
                child.weight.data, child.weight.quant_state,
            ).to(torch.bfloat16)
            new_linear = nn.Linear(
                child.in_features, child.out_features,
                bias=(child.bias is not None),
                dtype=torch.bfloat16, device=weight_bf16.device,
            )
            new_linear.weight.data = weight_bf16
            if child.bias is not None:
                new_linear.bias.data = child.bias.data.to(torch.bfloat16)
            setattr(module, name, new_linear)
        else:
            dequantize_recursive(child)

dequantize_recursive(merged)  # replaces 601 Linear4bit modules

# strip quantization_config so HF doesn't re-quantize on load
if hasattr(merged.config, "quantization_config"):
    delattr(merged.config, "quantization_config")
if hasattr(merged.config, "text_config") and hasattr(merged.config.text_config, "quantization_config"):
    delattr(merged.config.text_config, "quantization_config")

merged.save_pretrained(OUT, safe_serialization=True, max_shard_size="5GB")
AutoProcessor.from_pretrained(BASE).save_pretrained(OUT)
adapter_chat = os.path.join(ADAPTER, "chat_template.jinja")
if os.path.exists(adapter_chat):
    shutil.copy(adapter_chat, os.path.join(OUT, "chat_template.jinja"))

Output: 13 shards Γ— ~5 GB = 62.5 GB, 1188 tensors, safetensors index parity verified.

vLLM serve config

--max-model-len 32768 --gpu-memory-utilization 0.85 --tensor-parallel-size 4

nuts-has-been-taken avatar May 03 '26 06:05 nuts-has-been-taken

Hi @nuts-has-been-taken , I used pubmedqa dataset (pure text) and conducted the experiments you mentioned above. After forcing input parity between Automodel and Unsloth, I see the two frameworks converge in parity.

Image

The evaluation is done on 100 validation dataset at epoch0.

Run Validation Accuracy
Base Gemma4 31B, no adapter 72.0%
Automodel QLoRA, epoch 0 / step 112 83.0%
Unsloth QLoRA, epoch 0 / step 112 80.0%
Automodel LoRA, epoch 0 / step 112 79.0%

These are close enough that I don’t think the issue is Automodel training convergence; the likely problem is in the merge/load script. In this case the Automodel QLoRA adapter is not directly HF PEFT-compatible. I'm looking into it.

HuiyingLi avatar May 03 '26 21:05 HuiyingLi

Thanks @HuiyingLi β€” that's a really helpful reproduction. The training-side parity (Automodel QLoRA 83% vs Unsloth QLoRA 80%) lines up with the merge step being the likely culprit on our end.

I'll also try running the adapter directly via transformers + PeftModel.from_pretrained (without our dequantize-merge step) and report back what the pass rate looks like on the same 100-fixture eval. That should isolate whether the regression is purely from our merge flow or partially from how we load the adapter.

Standing by for any update on the proper Automodel-QLoRA β†’ HF PEFT conversion path.

nuts-has-been-taken avatar May 04 '26 02:05 nuts-has-been-taken

Hi @nuts-has-been-taken , To unblock I have a PR https://github.com/NVIDIA-NeMo/Automodel/pull/2120/ Can you try using the following snippet to load the model+adapter with the above PR. I believe previously there is mismatch in qlora adapter key name.

    processor = AutoProcessor.from_pretrained(args.model_name, local_files_only=True)
    quantization_config = None
    if args.load_in_4bit:
        quantization_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_compute_dtype=torch.bfloat16,
            bnb_4bit_use_double_quant=True,
            bnb_4bit_quant_storage=torch.bfloat16,
            llm_int8_skip_modules=["lm_head"],
        )

    base_model = AutoModelForImageTextToText.from_pretrained(
        args.model_name,
        local_files_only=True,
        torch_dtype=torch.bfloat16,
        attn_implementation="sdpa",
        device_map="auto",
        quantization_config=quantization_config,
    )
    model = PeftModel.from_pretrained(base_model, checkpoint_dir, is_trainable=False)
    model.eval()

HuiyingLi avatar May 04 '26 03:05 HuiyingLi

Hi @HuiyingLi β€” followup on the direct-PeftModel test we said we'd run, plus PR #2120 verification. Numbers below.

PR #2120 effect β€” verified. Hand-applied the equivalent fix (prepended base_model.model. to the saved safetensors keys, no other change). With the remapped adapter, PeftModel.from_pretrained(base, adapter_dir) loads cleanly: 0 missing adapter keys (vs 840 before). Re-running the same 100-fixture eval, 14 fixtures flipped verdict between the broken-merge and fixed-merge runs (7 newly pass, 7 newly fail) β€” the LoRA is actually being applied now.

Path A β€” dequantize_4bit + save_pretrained β†’ vLLM:

base 4-bit NF4 + PeftModel.from_pretrained(remapped)
  β†’ merge_and_unload()
  β†’ walk-replace bnb.nn.Linear4bit with nn.Linear(bfloat16)
    via bnb.functional.dequantize_4bit
  β†’ save_pretrained
  β†’ vLLM 0.20.0 serve --tensor-parallel-size 4 --max-model-len 32768

100/100 fixtures: 84%.

Path B β€” PeftModel.from_pretrained direct, no merge:

base_model = AutoModelForImageTextToText.from_pretrained(
    BASE, dtype=torch.bfloat16, device_map="auto",
)
model = PeftModel.from_pretrained(base_model, remapped_adapter_dir)

Hosted behind a minimal FastAPI /v1/chat/completions shim. Pod OOMKilled at fixture 43/100 (host CPU memory pressure on a fixture with very long output). On the 43-fixture prefix that completed: 41 PASS / 2 FAIL = 95.3%.

Same 43-fixture prefix on Path A: 37 PASS / 6 FAIL = 86%.

Comparison (same 100-fixture eval where applicable):

Configuration Pass rate
Base Gemma 4 31B, no adapter 88%
Path A β€” Automodel adapter via dequant-merge β†’ vLLM 84%
Path B β€” Automodel adapter via PeftModel.from_pretrained (43-fixture sample) 95.3%
Same-data Unsloth-trained adapter via merge-then-serve 92%

PR #2120 fixes the adapter-load layer. The remaining gap on this benchmark traces to the post-merge dequantize_4bit β†’ save_pretrained β†’ vLLM path, not training quality. Surfacing in case it's useful β€” "QLoRA train β†’ merge β†’ vLLM serve" is a common production path, and the dequantize step is costing ~9pp of pass rate vs. direct adapter loading on this eval.

Won't be re-running the direct path; OOM at 43/100 was a hard stop on our pod budget.

nuts-has-been-taken avatar May 05 '26 02:05 nuts-has-been-taken