PaliGemma2 JSON 信息抽取微调实战从货盘清单图片到结构化数据这篇教程是我根据 PaliGemma2 视觉文档理解和 JSON 信息抽取任务复现过程整理出来的。重点演示如何使用 JSONL 数据集微调 PaliGemma2让模型从货盘清单图片中生成结构化 JSON。和目标检测不同JSON 抽取任务关注完整结构化文本生成。这里使用 LoRA/QLoRA 微调整个模型并用 BLEU、TER 等文本指标评估生成结果和标注 JSON 的接近程度。本文会重点跑通以下流程下载 JSONL 视觉文档数据集用固定 prompt 训练 JSON 结构化输出使用 QLoRA 降低 PaliGemma2 微调显存占用在测试集上生成 JSON 并和标注对比使用 BLEU 和 TER 评估文本生成质量如果你正在系统学习多模态微调、目标检测、OCR 或图像分割建议收藏本文配套 notebook、示例图片和运行环境说明后续会继续整理。如果环境配置卡住可以在评论区说明具体报错。 文章目录PaliGemma2 JSON 信息抽取微调实战从货盘清单图片到结构化数据⚙️ 环境准备 下载 JSONL 数据集 加载并预览数据 加载 PaliGemma2 与 QLoRA️ 微调 JSON 抽取模型 运行微调模型推理 评估 JSON 生成质量 小结 同系列教程汇总⚙️ 环境准备检查 GPU安装训练依赖并准备从数据集后台导出的 JSONL 格式数据集。!nvidia-smi 下载 JSONL 数据集下载 pallet load manifest JSON 数据集并查看标注文件前几行。!pip install-q supervision peft bitsandbytes transformers4.47.0fromtypesimportSimpleNamespace# 从数据集后台下载并解压数据集后修改 DATASET_DIR 指向数据集目录。DATASET_DIR/content/dataset# 修改为数据集后台导出的数据集目录datasetSimpleNamespace(locationDATASET_DIR)!head-n5{dataset.location}/train/annotations.jsonl 加载并预览数据定义 JSONL 数据集类读取图片和对应 JSON suffix并预览部分训练图片。importosimportjsonimportrandomfromPILimportImagefromtorch.utils.dataimportDatasetclassJSONLDataset(Dataset):def__init__(self,jsonl_file_path:str,image_directory_path:str):self.jsonl_file_pathjsonl_file_path self.image_directory_pathimage_directory_path self.entriesself._load_entries()def_load_entries(self):entries[]withopen(self.jsonl_file_path,r)asfile:forlineinfile:datajson.loads(line)entries.append(data)returnentriesdef__len__(self):returnlen(self.entries)def__getitem__(self,idx:int):ifidx0oridxlen(self.entries):raiseIndexError(Index out of range)entryself.entries[idx]image_pathos.path.join(self.image_directory_path,entry[image])imageImage.open(image_path)returnimage,entrytrain_datasetJSONLDataset(jsonl_file_pathf{dataset.location}/train/annotations.jsonl,image_directory_pathf{dataset.location}/train,)valid_datasetJSONLDataset(jsonl_file_pathf{dataset.location}/valid/annotations.jsonl,image_directory_pathf{dataset.location}/valid,)test_datasetJSONLDataset(jsonl_file_pathf{dataset.location}/test/annotations.jsonl,image_directory_pathf{dataset.location}/test,)fromtqdmimporttqdmimportsupervisionassv images[]foriinrange(25):image,labeltrain_dataset[i]images.append(image)sv.plot_images_grid(images,(5,5)) 加载 PaliGemma2 与 QLoRA加载 processor并启用 LoRA/QLoRA 进行显存友好的微调。importtorchfromtransformersimportPaliGemmaProcessor,PaliGemmaForConditionalGeneration MODEL_IDgoogle/paligemma2-3b-pt-448DEVICEtorch.device(cudaiftorch.cuda.is_available()elsecpu)fromhuggingface_hubimportnotebook_login notebook_login()processorPaliGemmaProcessor.from_pretrained(MODEL_ID)# title Freeze the image encoder# TORCH_DTYPE torch.bfloat16# model PaliGemmaForConditionalGeneration.from_pretrained(MODEL_ID, torch_dtypeTORCH_DTYPE).to(DEVICE)# for param in model.vision_tower.parameters():# param.requires_grad False# for param in model.multi_modal_projector.parameters():# param.requires_grad False# title Fine-tune the entire model with LoRA and QLoRAfromtransformersimportBitsAndBytesConfigfrompeftimportget_peft_model,LoraConfig bnb_configBitsAndBytesConfig(load_in_4bitTrue,bnb_4bit_compute_dtypetorch.bfloat16)lora_configLoraConfig(r8,target_modules[q_proj,o_proj,k_proj,v_proj,gate_proj,up_proj,down_proj],task_typeCAUSAL_LM,)modelPaliGemmaForConditionalGeneration.from_pretrained(MODEL_ID,device_mapauto)modelget_peft_model(model,lora_config)model.print_trainable_parameters()TORCH_DTYPEmodel.dtype️ 微调 JSON 抽取模型固定 prompt 为extract data in JSON format让模型学习输出目标 JSON。fromtransformersimportTrainer,TrainingArgumentsdefcollate_fn(batch):images,labelszip(*batch)paths[label[image]forlabelinlabels]prefixes[imageextract data in JSON formatforlabelinlabels]suffixes[label[suffix]forlabelinlabels]inputsprocessor(textprefixes,imagesimages,return_tensorspt,suffixsuffixes,paddinglongest).to(TORCH_DTYPE).to(DEVICE)returninputs argsTrainingArguments(num_train_epochs20,remove_unused_columnsFalse,per_device_train_batch_size1,gradient_accumulation_steps8,warmup_steps2,learning_rate2e-5,weight_decay1e-6,adam_beta20.999,logging_steps50,optimadamw_hf,save_strategysteps,save_steps1000,save_total_limit1,output_dirpaligemma2_object_detection,bf16True,report_to[tensorboard],dataloader_pin_memoryFalse)trainerTrainer(modelmodel,train_datasettrain_dataset,eval_datasetvalid_dataset,data_collatorcollate_fn,argsargs)trainer.train() 运行微调模型推理在测试集样本上生成 JSON并显示对应图片。image,labeltest_dataset[1]prefiximageextract data in JSON formatsuffixlabel[suffix]inputsprocessor(textprefix,imagesimage,return_tensorspt).to(TORCH_DTYPE).to(DEVICE)prefix_lengthinputs[input_ids].shape[-1]withtorch.inference_mode():generationmodel.generate(**inputs,max_new_tokens512,do_sampleFalse)generationgeneration[0][prefix_length:]decodedprocessor.decode(generation,skip_special_tokensTrue)print(json.dumps(json.loads(decoded),indent4))image 评估 JSON 生成质量遍历测试集收集预测和标注使用 BLEU 和 TER 衡量文本生成质量。importnumpyasnp targets[]predictions[]withtorch.inference_mode():foriinrange(len(test_dataset)):image,labeltest_dataset[i]prefiximageextract data in JSON formatsuffixlabel[suffix]inputsprocessor(textprefix,imagesimage,return_tensorspt).to(TORCH_DTYPE).to(DEVICE)prefix_lengthinputs[input_ids].shape[-1]generationmodel.generate(**inputs,max_new_tokens512,do_sampleFalse)generationgeneration[0][prefix_length:]generated_textprocessor.decode(generation,skip_special_tokensTrue)targets.append(suffix)predictions.append(generated_text)!pip install-q evaluate# title Calculate BLEUfromevaluateimportload bleuload(bleu)resultsbleu.compute(predictionspredictions,referencestargets)print(results)!pip install-q sacrebleu# title Calculate TERfromevaluateimportload terload(ter)resultster.compute(predictionspredictions,referencestargets,case_sensitiveTrue)print(results) 小结这篇教程完整整理了Fine-Tune PaliGemma2 for JSON Data Extraction的核心复现流程。实际操作时建议先确认 GPU、依赖版本、数据集路径和模型权限再逐段运行 notebook。下载 JSONL 视觉文档数据集用固定 prompt 训练 JSON 结构化输出使用 QLoRA 降低 PaliGemma2 微调显存占用在测试集上生成 JSON 并和标注对比使用 BLEU 和 TER 评估文本生成质量后续我会继续按源项目顺序整理 项目教程 中的目标检测、实例分割、OCR、多目标跟踪和视觉大模型教程。 同系列教程汇总Google Gemini 3.5 Flash 零样本目标检测教程从提示词到可视化结果GLM-OCR 文档识别实战教程从验证码、公式到车牌 OCRRF-DETR ByteTrack 多目标跟踪实战教程从命令行到 Python 视频轨迹可视化SAM 3 图像分割实战教程文本、框和点提示的多种分割方式PaliGemma2 JSON 信息抽取微调实战从货盘清单图片到结构化数据-本文