NLP · LLM Fine-tuning · Information Extraction

Medical Paper Abstract
Structurization

Fine-tuning LLaMA with LoRA to convert free-text medical abstracts into structured JSON — a full-stack pipeline covering synthetic data generation, multi-layer quality filtering, targeted loss design, and field-level F1 evaluation.

5,000
Training Samples
95%+
JSON Validity
F1 ↑20%
vs. Base Model
5
Schema Fields

Overview

Medical literature is growing faster than clinicians can read. Key information — research objectives, methods, results, and conclusions — is buried in unstructured abstract text, hindering downstream retrieval, knowledge-base construction, and clinical decision support.

This project builds a low-annotation-cost pipeline that fine-tunes LLaMA via LoRA to extract structured JSON from free-text abstracts. Rather than treating it as a simple generation task, every stage — data quality, augmentation strategy, loss design, and evaluation metric — is carefully engineered to address the specific failure modes of generative models on structured extraction.

Input — Free-text Abstract
This study investigates the effect of drug A on systolic blood pressure in hypertensive patients. A randomized controlled trial was conducted with 200 participants over 12 weeks. Results showed a significant reduction of 14 mmHg (p<0.001). Drug A demonstrated superior efficacy compared to placebo.
Output — Structured JSON
{
  "Background":   "Hypertension is a major risk factor for cardiovascular disease, and effective treatments are needed to reduce systolic blood pressure.",
  "Objective":   "To evaluate the effect of drug A on systolic blood pressure in hypertensive patients.",
  "Methods":    "A randomized controlled trial was conducted with 200 participants over 12 weeks.",
  "Results":    "Drug A led to a significant reduction in systolic blood pressure of 14 mmHg (p<0.001) and showed superior efficacy compared to placebo.",
  "Conclusion": "Drug A is effective in reducing systolic blood pressure in hypertensive patients and performs better than placebo."
}

System Pipeline

End-to-end four-phase approach from raw data to evaluated model.

PubMed
seed abstracts
GPT-3.5
5k instructions
Quality Filter
JSON + embedding
Augmentation
paraphrase + schema
LoRA SFT
LLaMA fine-tune
Evaluation
field-level F1
Phase 1
Data Pipeline
Synthetic generation + multi-layer quality filtering system
Phase 2
Data Augmentation
Paraphrase augmentation + schema perturbation for generalization
Phase 3
Training Strategy
LoRA + weighted loss + curriculum learning for stable SFT
Phase 4
Evaluation
Field-level token F1 with normalization and failure penalties

Phase 1 — Data Pipeline

The core innovation: a multi-dimensional automated quality judgment system that transforms noisy GPT-generated content into high-standard SFT data.

Step 1
Synthetic Data Generation

Real PubMed abstracts serve as seeds. GPT-3.5 is called with carefully crafted prompts containing explicit schema definitions and few-shot examples to generate instruction-style paired data.

Data Source PubMed abstract subset (seed)
Generator GPT-3.5 API with few-shot prompting
Output ~5,000 instruction-style samples
Prompt Design
Extract structured information from the following medical abstract. Return JSON with keys: Background, Objective, Methods, Results, Conclusion.

[Schema definitions + few-shot examples]
Step 2
Format & Schema Validation
{ }
JSON Parse Check
Ensure bracket closure and valid JSON syntax via json.loads
Schema Compliance
Verify all required fields present, no missing or extra keys
≠∅
Content Validity
Filter empty strings, "N/A", and null values
Step 3
Content Quality Scoring (Lightweight Scoring System)

Four-dimensional quality judgment — not just non-empty, but defining what constitutes informative, trustworthy, and learnable data.

Dimension Method Target Problem
Length 10 < len(text) < 300 characters Reject "N/A" entries and verbatim abstract copies
Info Density Ensure keyword coverage andstopword ratio < 0.2 Filter low-information boilerplate sentences
Overlap Word overlap ratio with source < 0.9 Detect pseudo-extraction (verbatim copying)
Step 4
Embedding Semantic Consistency Filter — Anti-Hallucination Core

The most impactful filtering step. Uses SentenceTransformer (all-mpnet-base-v2) to compute cosine similarity between each extracted field and the most semantically similar sentence in the source abstract.

Model all-mpnet-base-v2 (SentenceTransformer)
Method max cosine sim over per-sentence embeddings
Effect Ensures extracted conclusions exist in source; prevents field confusion (Results ↔ Objective)
Source
Abstract
split into sentences
cosine
similarity
Extracted
Field
e.g. Results
sim ≥ θ → keep sim < θ → drop

Phase 2 — Data Augmentation

Two complementary perturbations — one on the input space, one on the output space — force the model to learn semantic-to-structure mapping rather than memorizing templates.

✏️
Paraphrase Augmentation
Input-space smoothing

GPT-3.5 rewrites each source abstract in multiple styles — academic to conversational, passive to active voice, long to short sentences — while keeping the ground-truth JSON unchanged.

Original "This study investigates the effect of drug A on blood pressure."
Paraphrase 1 "This research examines how drug A influences blood pressure."
Paraphrase 2 "We evaluate the impact of drug A on blood pressure levels."
Why it works: Without this, the model triggers extraction only on specific sentence patterns (e.g., "This study investigates…"). With paraphrase, it learns true semantic → structure mapping.
🔀
Schema Perturbation
Output-space smoothing

Training data randomly shuffles the order of JSON fields. The model must learn key-value mapping logic rather than position-based pattern matching.

Fixed order { Background, Objective, Methods, Results, Conclusion }
Shuffled v1 { Methods, Results, Objective ... }
Shuffled v2 { Conclusion, Background, Methods ...}
Why it works: Models over-relying on absolute position collapse when field order changes. Schema perturbation breaks this dependency. Combined with curriculum learning to maintain training stability.

Phase 3 — Training Strategy

Deep customization of the standard SFT pipeline to address format instability and domain specificity.

3.1 LoRA Configuration
Base Model LLaMA architecture
Injection Attention projection layers (Q, V)
Rank 8 or 16 (performance–VRAM tradeoff)

Preserves the base model's general language ability while adapting to structured extraction with minimal parameter overhead.

3.2 Targeted Loss Weighting Key Innovation

Standard cross-entropy is modified with two custom weightings:

Format Token Boost
JSON structural tokens ({, }, ") receive elevated loss weight → JSON validity rises to 95%+
Field Importance Weighting
Critical fields Results and Conclusion get higher loss weight → model prioritizes accuracy where it matters most
3.3 Curriculum Learning
Stage 1
Short abstracts + fixed simple schema
Stage 2
Long abstracts + shuffled complex schema

Progressive difficulty reduces training instability (early collapse) while making the schema perturbation strategy tractable.

3.4 Vertical vs. General Capability Balance
Problem Fine-tuned model tends to output JSON even in casual conversation
Solution Mix small amount of general instruction data (Multi-task SFT)
Domain Tiny set of human-curated samples + vocabulary alignment to fix Methods/Results confusion

SFT Failure Modes & Fixes

Problem 1
Unstable JSON Output
Missing brackets, extra fields, malformed syntax
Format token loss weighting → JSON validity 95%+
Problem 2
Hallucination
Results field contains information absent from source abstract
Embedding consistency filtering at data stage + prompt-level constraint
Problem 3
Template Overfitting
Extraction fails when abstract uses different writing style
Multi-style paraphrase augmentation
Problem 4
Medical Term Confusion
Methods and Results fields mixed up on domain terminology
Human-curated annotation samples + vocabulary alignment

Phase 4 — Evaluation

Field-level token F1, chosen over exact match for robustness to paraphrase and synonym variation in medical text.

1
Parse JSON Output
Extract each field from model output. Failed parse → all recalls = 0 (strict penalty).
2
Text Normalization
Lowercase, remove punctuation, normalize numbers (e.g., "5%" ↔ "five percent") to reduce noise.
3
Per-Field Token F1
For each field, compute token overlap between prediction and ground truth. Missing field → Recall = 0.
4
Aggregate
Macro-average across fields. Weighted analysis gives higher importance to Results and Conclusion.
Precision = overlap tokens / predicted tokens
Recall = overlap tokens / ground truth tokens
F1 = 2 × P × R / (P + R)  [per field, then macro-averaged]
Why not Exact Match? EM penalizes semantically equivalent outputs like "Patients improved significantly" vs "Patients significantly improved" as complete failures. Token F1 correctly treats these as near-perfect matches, aligning evaluation with actual extraction quality.

Key Results

Outcomes from the full pipeline compared to the LLaMA base model on medical abstract structurization.

Field-Level F1 Improvement
↑ ~20%
Medical abstract structurization task vs. base LLaMA.
Range: +15% to +25% depending on field.
JSON Format Validity
95%+
Achieved via format token loss weighting.
Baseline model: significant JSON parse failures.
🔬
Finding 1

Data Quality Outweighs Data Quantity

Multi-layer filtering (JSON validation + content scoring + embedding consistency) produces a smaller but higher-quality dataset that trains more effectively than raw GPT output.

3-layer filtering pipeline
⚖️
Finding 2

Format Token Weighting is Critical

Simply boosting loss weight on JSON structural tokens ({, }, ") dramatically stabilizes output format — the single highest-ROI training modification.

JSON validity: baseline → 95%+
🎯
Finding 3

Augmentation Breaks Template Overfitting

Paraphrase augmentation + schema perturbation together solve the generalization gap. The model correctly extracts from unseen writing styles and arbitrary field orderings.

Input + output space smoothing
🔄
Finding 4

LoRA Preserves General Capability

Pure LoRA fine-tuning with multi-task SFT mixing maintains general conversational ability while specializing for medical extraction — no catastrophic forgetting.

LoRA rank 8/16 + multi-task mix

Tech Stack

LLaMA
Base language model
LoRA / PEFT
Parameter-efficient fine-tuning
GPT-3.5 API
Synthetic data generation
SentenceTransformers
Embedding consistency filter
PyTorch
Training framework
HuggingFace
Model hub & Transformers
PubMed
Seed abstract corpus
scikit-learn
Cosine similarity computation