Fine-Tuning Nemotron 3.5 Parse with Open Datasets
A technical walkthrough on fine-tuning NVIDIA Nemotron 3.5 Parse using open synthetic datasets and GRPO reinforcement learning.

How Nemotron 3.5 Parse Transforms Document Extraction Workflows
Document ingestion pipelines often break when encountering complex tables, unlabelled charts, and multi-column layouts. Traditional OCR solutions spit out chaotic string blocks that ruin downstream retrieval-augmented generation. NVIDIA built Nemotron 3.5 Parse to solve this structural headache by turning raw page images into clean, hierarchical representations with explicit bounding boxes. But default models do not always match domain-specific layouts like financial balance sheets or medical intake forms. You need to fine-tune.
We are going to take the open-source training recipes and datasets released for Parse 3.5 and build a customized document parsing pipeline. Our architecture leverages three primary components: NaViT dynamic rectangular inputs for flexible page aspect ratios, a visual adapter that compresses image tokens into a causal prefix, and Grouped-Query Attention (GQA-8) to keep VRAM usage manageable during training. By the end of this tutorial, you will have a working Python script that prepares data, applies Supervised Fine-Tuning (SFT), and executes Group Relative Policy Optimization (GRPO) to stabilize extractions.
Setting Up Your Local Training Environment
You cannot run this setup on a standard laptop. Processing multi-modal document models requires serious hardware. Make sure your environment matches these specifications before running any installation commands.
- Operating System: Ubuntu 22.04 LTS or Debian 12
- Hardware: Minimum single NVIDIA A100 (80GB VRAM) or H100 GPU
- Python: Version 3.11.x
- CUDA: Version 12.4 with cuDNN 9.0
Start by provisioning your environment and installing the required packages. Open your terminal and create a dedicated virtual environment to avoid dependency conflicts with older PyTorch builds.
python3.11 -m venv parse-env
source parse-env/bin/activate
pip install --upgrade pip
pip install torch==2.5.1+cu124 torchvision==0.20.1+cu124 --index-url https://download.pytorch.org/whl/cu124
pip install transformers==4.49.0 datasets==3.2.0 accelerate==1.2.0 trl==0.13.0 vllm==0.6.6
Verify that your GPU is correctly exposed to PyTorch by running a quick inline Python check. You should see your hardware listed clearly without memory allocation errors.
python3 -c "import torch; print(f'CUDA Available: {torch.cuda.is_available()}, Device: {torch.cuda.get_device_name(0)}')"
Preparing Synthetic Datasets and Configuring SFT
NVIDIA open-sourced three major datasets for this workflow: Synthetic Charts V1 (9.98M examples), Synthetic Tables V1 (1M examples), and OCR Synthetic Multilingual v2 (7.9M examples). For this tutorial, we will pull a subset of the Synthetic Tables V1 dataset to adapt our model for financial grid extraction.
Create a training script named train_sft.py to load the dataset, configure the NaViT image processor, and execute the supervised fine-tuning phase.
import torch
from datasets import load_dataset
from transformers import AutoProcessor, AutoModelForVision2Seq, TrainingArguments, Trainer
# Load model processor and base architecture
model_id = "nvidia/Nemotron-3.5-Parse"
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForVision2Seq.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True
)
# Load dataset subset
dataset = load_dataset("nvidia/Synthetic-Tables-V1", split="train[:5000]")
def preprocess_function(examples):
images = examples["image"]
texts = examples["target_html"]
inputs = processor(text=texts, images=images, return_tensors="pt", padding=True)
inputs["labels"] = inputs["input_ids"].clone()
return inputs
tokenized_dataset = dataset.map(preprocess_function, batched=True, remove_columns=dataset.column_names)
training_args = TrainingArguments(
output_dir="./parse-sft-output",
per_device_train_batch_size=2,
gradient_accumulation_steps=8,
learning_rate=2e-5,
logging_steps=10,
save_steps=100,
bf16=True,
optim="adamw_torch"
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
)
trainer.train()
Applying Reinforcement Learning with GRPO
Supervised fine-tuning establishes general layout reading, but models often fall into repetitive generation loops when parsing dense documents. We apply Reinforcement Learning with Verifiable Rewards (RLVR) using Group Relative Policy Optimization (GRPO) to enforce structural consistency.
Create train_grpo.py to configure reward functions that check for closed HTML tags, correct row-column mappings, and repetition penalties.
import torch
from trl import GRPOTrainer, GRPOConfig
from transformers import AutoModelForVision2Seq, AutoProcessor
model_id = "./parse-sft-output"
model = AutoModelForVision2Seq.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
def table_structure_reward(completions, **kwargs):
rewards = []
for comp in completions:
score = 0.0
if comp.count("<table>") == comp.count("</table>"):
score += 1.0
if comp.count("<tr>") == comp.count("</tr>"):
score += 1.0
if "<td>" in comp:
score += 0.5
# Penalize endless generation loops
if len(set(comp.split())) / len(comp.split()) < 0.2:
score -= 2.0
rewards.append(score)
return rewards
training_args = GRPOConfig(
output_dir="./parse-grpo-output",
learning_rate=1e-6,
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
num_generations=4,
max_prompt_length=1024,
max_completion_length=2048,
bf16=True
)
trainer = GRPOTrainer(
model=model,
reward_funcs=table_structure_reward,
args=training_args,
train_dataset=dataset
)
trainer.train()
Executing the End-to-End Document Parsing Pipeline
Now that your fine-tuned checkpoint is saved, test it against a sample invoice or balance sheet image. We will use the vLLM integration optimized for Nemotron 3.5 Parse to accelerate inference using DFlash2 speculative decoding.
Write an execution script named run_inference.py to process local documents and export structured JSON output.
from transformers import AutoProcessor, AutoModelForVision2Seq
from PIL import Image
import torch
model_path = "./parse-grpo-output"
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForVision2Seq.from_pretrained(model_path, torch_dtype=torch.bfloat16, device_map="auto")
image_path = "sample_financial_statement.png"
image = Image.open(image_path).convert("RGB")
inputs = processor(text="<|parse_document|>", images=image, return_tensors="pt").to("cuda")
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=4096,
temperature=0.0,
do_sample=False
)
decoded_output = processor.decode(outputs[0], skip_special_tokens=True)
print(decoded_output)
with open("parsed_output.html", "w") as f:
f.write(decoded_output)
Run your inference script from the terminal to verify the pipeline:
python run_inference.py
You should see structured HTML elements streaming directly to your console, followed by a clean file written to your working directory.
Troubleshooting Common Training and Inference Errors
Even with clean datasets, multi-modal fine-tuning throws cryptic exceptions. Keep this troubleshooting reference handy when your runs crash.
-
CUDA Out of Memory (OOM) during SFT: Caused by unoptimized NaViT batch sizes or excessively large page resolutions. Fix: Reduce your
per_device_train_batch_sizeto 1, increasegradient_accumulation_stepsto 16, and enable FlashAttention-2 by passingattn_implementation="flash_attention_2"in your model loading config. - Infinite Generation Loops in GRPO: Occurs when the reward function does not adequately penalize token repetition. Fix: Implement an n-gram repetition check inside your reward script and clip rewards below -5.0 to stabilize policy updates.
-
Mismatched Tensor Dimensions on Visual Adapter: Triggered by passing raw images without going through the NaViT dynamic preprocessor. Fix: Always use
AutoProcessor.from_pretrained()withtrust_remote_code=Trueto ensure correct canvas scaling.
Optimizing Production Deployment and Performance
Deploying your fine-tuned parser to production requires balancing throughput with memory overhead. Because document parsers generate thousands of tokens per page, standard autoregressive decoding will bottleneck your backend.
Always export your weights to vLLM format and enable DFlash2 speculative decoding. This cuts latency by up to 3x compared to baseline execution. Set up your production serving container with a strict timeout limit of 60 seconds per page to prevent runaway inference jobs from consuming all available GPU threads. For secrets management, store your API authentication tokens inside environment variables and load them dynamically via os.getenv() rather than hardcoding credentials into your inference scripts.
What to Build Next After Mastering Parse
Once your fine-tuned Nemotron 3.5 Parse pipeline is running stably in local development, you can expand its capabilities across your broader engineering stack.
Integrate your parsed HTML output directly into a vector database using semantic chunking strategies tailored to table boundaries. Alternatively, pair your parser output with an agentic orchestration framework like LangGraph or CrewAI to automate end-to-end invoice auditing and data entry workflows. You can also explore multi-lingual fine-tuning using the OCR Synthetic Multilingual v2 dataset if your enterprise handles documents across multiple alphabets and regional layouts.
Bottom Line
Fine-tuning NVIDIA Nemotron 3.5 Parse requires heavy hardware and precise dataset preparation, but the accuracy gains for complex document workflows are undeniable. Skip default OCR setups and use this SFT and GRPO recipe when your enterprise pipelines demand zero structural hallucination.
Related Analyses
More in Tutorials →
How to Build a YouTube History Analysis Pipeline
Build a Python pipeline to extract, parse, and analyze your full YouTube viewing history back to 2020 using modern local language models.

Build a Custom Cyber Coach with Python and Dot AI
Step-by-step tutorial on building a secure AI cyber coach for small businesses using Python, local vector search, and dot framework integration.

How to Generate a 3D Game Engine with AI
I tested single prompt 3D game engine generation using LLMs. Here is how to build, run, and fix an AI generated rendering pipeline from scratch.