openT2L hypernetwork for MiniCPM-V-4.7-1B (document extraction)

Give it 4 example pages of a document type that MiniCPM-V-4.7-1B has never seen, each with the JSON you want extracted. In one forward pass it writes a rank-8 LoRA adapter for that document type. Nothing is fine-tuned at use time. The adapter comes out in standard PEFT format.

  • Library: openT2L (pip install "opent2l[hf] @ git+https://github.com/ASH1998/openT2L", import name t2l)
  • Training code, data pipeline, protocols and all results: openBMB-spark-t2l
  • Built for the MiniCPM Spark Program (S2, On-Device Agent Challenge)

Results (Gate 1, held-out tasks)

The test set is 78 tasks the hypernetwork never saw in training, held out as whole tasks:

  • 64 synthetic Chinese and English forms from 4 domains absent from training (payslip, purchase order, restaurant bill, shipping label);
  • 14 public tasks: ChartQA tables, FinTabNet tables and invoices.

Each adapter was emitted from 4 example pages. The metric is field-level F1 on JSON output, with greedy decoding. Both rows use the same pages, the same decoding and the same hardware (A10G).

Held-out tasks Base model + emitted adapter Gain [95% CI, task bootstrap] Tasks better / worse
All (78) 0.728 0.881 +0.154 [+0.116, +0.195] 71 / 2
Synthetic forms (64) 0.813 0.957 +0.145 [+0.104, +0.191] 58 / 1
Public (14) 0.339 0.533 +0.194 [+0.097, +0.305] 13 / 1

Examples:

  • Chinese purchase order: 0.24 β†’ 0.98
  • FinTabNet first column: 0.21 β†’ 0.79
  • FinTabNet full table: 0.31 β†’ 0.86

Limits:

  • On the held-out set, the adapters were compared only with the base model. We did not compare them with putting the same 4 pages in the prompt, with one multi-task LoRA, or with a LoRA trained on each test task.
  • Gains on charts are small (+0.01 to +0.27).
  • On English synthetic forms the base model was already near 0.95.

Full protocol and per-task scores: studies/gate1.

Use

import json, torch
from huggingface_hub import snapshot_download
from transformers import AutoModelForImageTextToText, AutoProcessor
from peft import PeftModel
from t2l import load_hypernet, example_embedding, emit_adapter

MODEL = "openbmb/MiniCPM-V-4.7-1B"
PROC = dict(downsample_mode="16x", max_slice_nums=9, enable_thinking=False)  # must match training
proc = AutoProcessor.from_pretrained(MODEL)
model = AutoModelForImageTextToText.from_pretrained(MODEL, torch_dtype=torch.bfloat16, device_map="cuda").eval()
gen, cfg = load_hypernet(snapshot_download("ASHu2/openT2L-MiniCPM-V-4.7-1B-docs"), device="cuda")

def embed(image_path: str, prompt: str, answer: dict) -> torch.Tensor:
    """One example: page image + prompt, with the correct JSON as the assistant turn."""
    user = {"role": "user", "content": [{"type": "image", "path": image_path}, {"type": "text", "text": prompt}]}
    asst = {"role": "assistant", "content": [{"type": "text", "text": json.dumps(answer, ensure_ascii=False)}]}
    p = proc.apply_chat_template([user], tokenize=True, add_generation_prompt=True,
                                 return_dict=True, return_tensors="pt", **PROC)
    f = proc.apply_chat_template([user, asst], tokenize=True, add_generation_prompt=False,
                                 return_dict=True, return_tensors="pt", **PROC).to(model.device)
    answer_mask = torch.zeros_like(f["attention_mask"])
    answer_mask[:, p["input_ids"].shape[1]:] = 1
    with torch.no_grad():
        h = model(**f, downsample_mode=PROC["downsample_mode"], output_hidden_states=True).hidden_states[-1]
    return example_embedding(h, f["attention_mask"], answer_mask, pooling="answer")

prompt = ("Extract the listed fields from this document.\n"
          "Return only JSON with this shape: {\"invoice_no\": str, \"date\": str, \"total\": str}\n"
          "Copy text exactly as printed. Use an empty string or empty list when a field is absent.")
examples = [("page1.png", {"invoice_no": "...", "date": "...", "total": "..."}), ...]  # 4 labelled pages
support = torch.stack([embed(img, prompt, ans) for img, ans in examples])
emit_adapter(gen, support, "my_adapter/", base_model=MODEL)

model = PeftModel.from_pretrained(model, "my_adapter/")   # then generate as usual with the same prompt

Verified (2026-11-21). This code block was run as published on an A10G: openT2L installed from GitHub, the weights downloaded from this repo. It was run on 3 held-out tasks Γ— 10 pages, using the same 4 example pages as the Gate 1 evaluation.

Task Base model This code Gate 1 adapter Outputs identical to Gate 1
Chinese purchase order 0.260 0.987 0.987 10 / 10
FinTabNet full table 0.375 0.913 0.913 10 / 10
Invoice line items 0.407 0.721 0.699 8 / 10

The small invoice difference comes from PEFT applying the LoRA with slightly different numerics than the forward hooks used in Gate 1. Script and outputs: verify_hf_card.py, hf_card_check.json.

The emitted adapter is an ordinary PEFT LoRA directory, so you can merge it, serve it, or convert it for llama.cpp like any other LoRA. Use the same prompt format and processor settings as in training; the embedding recipe is recorded in hypernet_config.json under embedding.

Model details

Base model openbmb/MiniCPM-V-4.7-1B (frozen, bf16)
Adapted modules 48 in the language model: self_attn.q_proj and self_attn.v_proj in the 6 full-attention layers; linear_attn.in_proj_qkv and linear_attn.out_proj in the 18 linear-attention layers. Vision tower untouched.
LoRA rank 8, alpha 16
Hypernetwork Text-to-LoRA "M"-style shared MLP (3 Γ— 512, SiLU), with layer-position and module-type embeddings and one A/B head per weight shape. Each adapter = learned shared part + task part; both B terms start at zero.
Parameters 72.2M
Task embedding Last LM hidden state, mean over answer tokens (1024-d), averaged over k examples
Training 333 tasks; 6,000 steps Γ— 8 tasks (48,000 query examples); k sampled from {1, 2, 4, 8} support pages; AdamW, lr 1e-4, weight decay 0.01, cosine schedule with 300 warmup steps; loss 0.171 β†’ 0.033 (first/last 100-step means). About 5 h on one A10G.
Labels Real dataset labels, or exact labels from the synthetic form generator. No teacher-model labels.

Files

  • hypernet.safetensors: weights (fp32)
  • hypernet_config.json: architecture, the 48 target modules with shapes, the embedding recipe and training settings. Loaded by t2l.load_hypernet. No pickle.

Licence

CC-BY-NC-4.0 (non-commercial). The training tasks include XFUND and DVQA (non-commercial licences) and SROIE, WildReceipt and HME100K (licences unclear), so these weights and any adapter they emit are for non-commercial use. The base model, MiniCPM-V-4.7-1B, is under its own licence (Apache-2.0) and is not included here. The openT2L code is Apache-2.0. Per-dataset licences are listed in the task pool results.

Acknowledgements

The architecture follows Text-to-LoRA (Charakorn et al., Sakana AI, 2025), adapted here to condition on embedded examples rather than a text description. Base model by OpenBMB.

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Model tree for ASHu2/openT2L-MiniCPM-V-4.7-1B-docs

Adapter
(7)
this model