Recently, I was exploring options for building fast, local receipt-to-JSON inference.

The main constraint was privacy: receipt documents could not be sent to external paid LLM APIs. At the same time, running a large vision-language model locally on a 16GB RTX 5060 while keeping latency low is not practical. On the other end of the spectrum, sub-billion-parameter models are fast and fit easily in VRAM, but out of the box they struggle to reliably follow a strict JSON schema.

While looking for a way to close that gap, I explored fine-tuning—specifically LoRA (Low-Rank Adaptation).

What Is LoRA?

LoRA (Low-Rank Adaptation) is a Parameter-Efficient Fine-Tuning (PEFT) technique introduced by Microsoft researchers in 2021 (Hu et al., arXiv:2106.09685 | GitHub) to adapt large models on a tight GPU memory budget.

Instead of updating every parameter in the base model, LoRA:

  1. Freezes all original pretrained weights (W₀).
  2. Injects small trainable low-rank matrices (A and B) alongside target linear layers (such as attention and MLP projections).
  3. Backpropagates gradients only through the LoRA adapters, drastically reducing optimizer state memory.

LoRA relies on the hypothesis that the weight updates ΔW needed to adapt a pretrained model to a downstream task have a low intrinsic rank—meaning ΔW can be approximated by the product of two much smaller matrices B (shape d × r) and A (shape r × k), where rank r ≪ min(d, k).

During the forward pass, the effective weight becomes:

W' = W₀ + (α / r) · (B · A) 

Because B · A has the same shape as W₀, its output is simply scaled by α / r and added to the frozen layer's output.

The Experiment: Qwen3.5-0.8B on CORD-v2

For testing, I used Qwen3.5-0.8B to extract structured receipt JSON from the naver-clova-ix/cord-v2 dataset.

Note: While the original CORD collection gathered ~11,000 Indonesian receipts, the public cord-v2 release on Hugging Face contains 1,000 annotated receipts (800 train, 100 validation, 100 test) covering structured fields such as menu items, quantities, subtotals, taxes, and totals.

Out of the box, the base Qwen3.5-0.8B model produced valid JSON on 85% of the test receipts, but achieved 0.0% Field F1 and 0.0% Exact Match—it failed to follow the CORD schema's exact key names and structure, and still produced malformed JSON 15% of the time.

To fix this, I fine-tuned it using Hugging Face's peft and transformers libraries.

Step 1: Downloading the Dataset and Base Model

Load and cache the dataset with the datasets library:

from datasets import load_dataset, load_from_disk ds = load_dataset("naver-clova-ix/cord-v2", split=split) ds.save_to_disk(cache_dir) 

Download the base model locally via the Hugging Face CLI:

hf download Qwen/Qwen3.5-0.8B --local-dir ./models 

Step 2: Loading the Model and Processor

import torch from transformers import AutoModelForImageTextToText, AutoProcessor LOCAL_MODEL_PATH = "./models" processor = AutoProcessor.from_pretrained(LOCAL_MODEL_PATH, local_files_only=True) model = AutoModelForImageTextToText.from_pretrained( LOCAL_MODEL_PATH, dtype=torch.float32, local_files_only=True, ) model.config.use_cache = False 

Setting model.config.use_cache = False disables Key-Value (KV) caching during the forward pass. KV caching speeds up autoregressive generation at inference time, but during training it wastes GPU VRAM and is incompatible with activation/gradient checkpointing.

Step 3: Configuring LoRA with PEFT

from peft import LoraConfig, get_peft_model lora_config = LoraConfig( r=4, lora_alpha=16, target_modules=[ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", ], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) model = get_peft_model(model, lora_config) model.print_trainable_parameters() 

Key parameters:

  • r: The rank (inner dimension) of the low-rank adapter matrices A and B. Higher r adds more trainable capacity at the cost of extra VRAM.
  • lora_alpha: Controls the adapter scaling factor α / r. Here, 16 / 4 = 4, which amplifies the LoRA update relative to the frozen base weights.
  • target_modules: Which linear layers receive LoRA adapters—here, both the attention projections (q/k/v/o_proj) and MLP projections (gate/up/down_proj).
  • get_peft_model(...): Wraps the base torch.nn.Module, freezes its original weights, attaches the LoRA adapters, and returns a PeftModel.

Step 4: Preparing Multimodal Inputs with a Data Collator

A data collator formats each batch of raw samples (receipt image + ground-truth JSON) into the exact tensors the model expects (input_ids, attention_mask, vision tensors, and labels):

def make_collate_fn(processor, max_side: int = 640): """Build batch_size=1 multimodal tensors with -100 masking on prompt + image tokens.""" def collate(batch: list[dict]) -> dict: assert ( len(batch) == 1 ), "Use batch_size=1 with gradient accumulation on limited VRAM" sample = batch[0] img = resize_max_side(sample["image"], max_side) if "target_json" in sample: target_json = sample["target_json"] else: gt_dict = json.loads(sample["ground_truth"])["gt_parse"] target_json = json.dumps(gt_dict, ensure_ascii=False, separators=(",", ":")) prompt_msgs = [ {"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}, { "role": "user", "content": [ {"type": "image", "image": img}, {"type": "text", "text": USER_PROMPT}, ], }, ] full_msgs = prompt_msgs + [ {"role": "assistant", "content": [{"type": "text", "text": target_json}]} ] # Non-thinking mode keeps JSON output direct and concise prompt_text = processor.apply_chat_template( prompt_msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False, ) full_text = processor.apply_chat_template( full_msgs, tokenize=False, add_generation_prompt=False, enable_thinking=False, ) prompt_inputs = processor(text=[prompt_text], images=[img], return_tensors="pt") full_inputs = processor(text=[full_text], images=[img], return_tensors="pt") labels = full_inputs["input_ids"].clone() prompt_len = prompt_inputs["input_ids"].shape[1] labels[:, :prompt_len] = -100 # Ignore loss on system, vision, and user tokens full_inputs["labels"] = labels return full_inputs return collate 

One crucial detail here is labels[:, :prompt_len] = -100. PyTorch's cross-entropy loss ignores tokens labeled -100, ensuring the model is trained only to predict the assistant's target JSON—not to memorize the system prompt or user instructions.

Step 5: Training and Saving the Adapter

from transformers import Trainer, TrainingArguments ADAPTER_OUTPUT_DIR = "./qwen35_08b_cord_lora_fp32_peft" training_args = TrainingArguments( output_dir=ADAPTER_OUTPUT_DIR, num_train_epochs=3, per_device_train_batch_size=1, per_device_eval_batch_size=1, gradient_accumulation_steps=8, activation_checkpointing=True, activation_checkpointing_kwargs={"use_reentrant": False}, use_cache=False, learning_rate=2e-4, weight_decay=0.01, warmup_steps=0.05, lr_scheduler_type="cosine", fp16=False, bf16=False, tf32=False, max_grad_norm=1.0, logging_steps=10, eval_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, metric_for_best_model="eval_loss", save_total_limit=1, remove_unused_columns=False, ) trainer = Trainer( model=model, args=training_args, train_dataset=train_ds, eval_dataset=val_ds, data_collator=collate_fn, ) trainer.train() model.save_pretrained(ADAPTER_OUTPUT_DIR) processor.save_pretrained(ADAPTER_OUTPUT_DIR) 

Key Training Arguments Explained

Argument What It Does
num_train_epochs=3 Runs 3 full passes over the 800-sample training split.
per_device_train_batch_size=1 & gradient_accumulation_steps=8 Computes gradients 1 sample at a time to save VRAM, and updates the optimizer weights every 8 samples (effective batch size = 8, or 300 total optimizer updates over 3 epochs).
learning_rate=2e-4 Sets the peak learning rate to 0.0002.
warmup_steps=0.05 In this version of transformers, a float in (0, 1) is treated as a fraction of total optimizer steps—ramping the learning rate up over the first 5% of updates (15 of 300 steps).
lr_scheduler_type="cosine" After warmup, smoothly decays the learning rate from its peak toward zero along a cosine curve.
weight_decay=0.01 Applies mild L2 weight regularization scaled by the learning rate on each optimizer update (not a flat 1% shrinkage per step).
max_grad_norm=1.0 Clips the global L2 norm of gradients to 1.0 to prevent unstable, exploding updates.
activation_checkpointing=True Trades extra compute for lower VRAM by recomputing intermediate activations during backpropagation instead of storing them all.

Once training finishes, model.save_pretrained(ADAPTER_OUTPUT_DIR) saves the lightweight LoRA adapter weights (alongside processor.save_pretrained(...) for easy reloading at inference time).

Results

Evaluating both the base model and the LoRA fine-tuned model on all 100 samples of the cord-v2 test split:

Model Valid JSON Exact Match Field Precision Field Recall Field F1
base 85.0% 0.0% 0.0% 0.0% 0.0%
finetuned 100.0% 34.0% 78.3% 77.9% 78.1%

What these numbers show:

  • 100.0% Valid JSON: Every single test receipt produced syntactically valid JSON (up from 85.0%).
  • 34.0% Exact Match: Over a third of the test receipts matched the ground-truth JSON 100% identically—every key, nested structure, and character.
  • 78.3% Field Precision / 77.9% Field Recall (78.1% F1): Nearly 4 out of 5 individual (field_path, value) pairs were extracted accurately and completely, compared to 0.0% on the base model.

With just 800 training receipts and a tiny LoRA adapter, a 0.8B local model went from completely unusable on the CORD schema to reliably emitting valid, structured receipt JSON entirely offline.

Let's Discuss!

I'm still experimenting with fine-tuning on consumer GPUs—next up is QLoRA to cut VRAM usage via 4-bit quantization and see if we can fit larger models on the same GPU.

I'd love to hear from you in the comments:

  • Have you fine-tuned a sub-1B model for structured JSON or OCR/document extraction? What worked best for you?
  • What LoRA hyperparameters (r, lora_alpha, target modules, or learning rate) would you tweak to push that 34% Exact Match higher?
  • If you're running local inference for privacy-sensitive documents, what models or quantization setups are you using?

If you found this helpful, feel free to leave a ❤️ or 🦄, share it with someone exploring local fine-tuning, and drop your thoughts or questions below!