Codex commited on
Commit
1cbcf63
·
1 Parent(s): 993480a

feat: real-report labeling helper + real-data mix-in for fine-tune

Browse files

- modal_eval: label entrypoint drafts labels with the base model over the real PDFs to correct.
- modal_finetune: mix corrected real reports into training (render PDFs + oversample) via --real-labels/--real-repeat, to beat the base where synthetic-only could not.

Files changed (2) hide show
  1. train/modal_eval.py +57 -0
  2. train/modal_finetune.py +60 -4
train/modal_eval.py CHANGED
@@ -118,3 +118,60 @@ def compare(
118
  out = Path("eval/before_after.json")
119
  out.write_text(json.dumps({"base": base, "finetuned": fine}, indent=2), encoding="utf-8")
120
  print(f"\n wrote {out} -> render the chart with: python eval/make_chart.py\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  out = Path("eval/before_after.json")
119
  out.write_text(json.dumps({"base": base, "finetuned": fine}, indent=2), encoding="utf-8")
120
  print(f"\n wrote {out} -> render the chart with: python eval/make_chart.py\n")
121
+
122
+
123
+ @app.function(
124
+ image=image,
125
+ gpu="A100",
126
+ timeout=60 * 60,
127
+ volumes={"/root/.cache/huggingface": hf_cache},
128
+ secrets=[modal.Secret.from_name("huggingface-secret")],
129
+ )
130
+ def draft_labels(
131
+ pdf_dir_rel: str = "eval/data/real",
132
+ model_id: str = "openbmb/MiniCPM-V-4.6",
133
+ exclude: tuple[str, ...] = ("06_drlogy_cbc.pdf", "02_cbc_umc_johndoe.pdf"),
134
+ ) -> list[dict]:
135
+ """Run the BASE model over the real PDFs to produce DRAFT labels you then correct by hand.
136
+
137
+ Excludes the held-out eval reports so train/eval stay separate (no leakage).
138
+ """
139
+ import os
140
+ import sys
141
+ from pathlib import Path
142
+
143
+ sys.path.insert(0, "/root/app")
144
+ os.environ["ZEROGPU_QUANTIZE"] = "0"
145
+ from src.extraction.zerogpu_transformers import ZeroGPUTransformersExtractor
146
+
147
+ pdf_dir = Path("/root/app") / pdf_dir_rel
148
+ extractor = ZeroGPUTransformersExtractor(model_id=model_id)
149
+ drafts: list[dict] = []
150
+ for pdf in sorted(pdf_dir.glob("*.pdf")):
151
+ if pdf.name in exclude:
152
+ continue
153
+ try:
154
+ tests = extractor.extract(str(pdf), max_pages=3).tests
155
+ print(f"{pdf.name}: {len(tests)} draft markers")
156
+ except Exception as error:
157
+ print(f"{pdf.name}: FAILED — {error}")
158
+ tests = []
159
+ drafts.append({"image": pdf.name, "tests": tests, "notes": []})
160
+ return drafts
161
+
162
+
163
+ @app.local_entrypoint()
164
+ def label(pdf_dir: str = "eval/data/real", out: str = "eval/data/real/labels_train_draft.jsonl") -> None:
165
+ """Generate draft labels (base model) for you to correct, then mix into training."""
166
+ import json
167
+ from pathlib import Path
168
+
169
+ drafts = draft_labels.remote(pdf_dir_rel=pdf_dir)
170
+ out_path = Path(out)
171
+ with out_path.open("w", encoding="utf-8") as fh:
172
+ for row in drafts:
173
+ fh.write(json.dumps(row, ensure_ascii=False) + "\n")
174
+ print(f"\n Wrote {len(drafts)} DRAFT labels -> {out_path}")
175
+ print(" Correct each line (fix marker/value/unit/status, delete junk rows), save it as")
176
+ print(" eval/data/real/labels_train.jsonl, then retrain with the real mix-in:")
177
+ print(" modal run train/modal_finetune.py::main --real-labels eval/data/real/labels_train.jsonl\n")
train/modal_finetune.py CHANGED
@@ -45,19 +45,69 @@ image = (
45
  # Mount our generator + converter + marker reference so the box builds its own data.
46
  .add_local_dir("src", "/root/app/src")
47
  .add_local_dir("train", "/root/app/train")
 
48
  )
49
 
50
  adapters = modal.Volume.from_name("blood-test-adapters", create_if_missing=True)
51
  hf_cache = modal.Volume.from_name("blood-test-hf-cache", create_if_missing=True)
52
 
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  @app.function(
55
  image=image,
56
  gpu="A100",
57
  timeout=6 * 60 * 60,
58
  volumes={"/adapters": adapters, "/root/.cache/huggingface": hf_cache},
59
  )
60
- def train(n: int = 2000, epochs: int = 1, lr: float = 2e-5, seed: int = 13) -> str:
61
  import os
62
  import subprocess
63
  import sys
@@ -72,7 +122,13 @@ def train(n: int = 2000, epochs: int = 1, lr: float = 2e-5, seed: int = 13) -> s
72
  labels = generate(n, data_dir, seed=seed)
73
  sft_path = Path("/root/app/train/data/sft.jsonl")
74
  n_examples = convert(labels, sft_path)
75
- print(f"Generated {n_examples} SFT examples at {sft_path}")
 
 
 
 
 
 
76
 
77
  # 2) LoRA fine-tune with ms-swift
78
  out_dir = "/adapters/minicpmv-lab-lora"
@@ -109,8 +165,8 @@ def train(n: int = 2000, epochs: int = 1, lr: float = 2e-5, seed: int = 13) -> s
109
 
110
 
111
  @app.local_entrypoint()
112
- def main(n: int = 2000, epochs: int = 1, lr: float = 2e-5) -> None:
113
- path = train.remote(n=n, epochs=epochs, lr=lr)
114
  print(f"\nLoRA adapters saved to Modal volume 'blood-test-adapters' at {path}")
115
  print("Next: merge the adapter into the base model and push it to the Hub:")
116
  print(" modal run train/modal_finetune.py::merge --repo-id <owner>/<model-name>")
 
45
  # Mount our generator + converter + marker reference so the box builds its own data.
46
  .add_local_dir("src", "/root/app/src")
47
  .add_local_dir("train", "/root/app/train")
48
+ .add_local_dir("eval", "/root/app/eval") # real PDFs + corrected labels for the real mix-in
49
  )
50
 
51
  adapters = modal.Volume.from_name("blood-test-adapters", create_if_missing=True)
52
  hf_cache = modal.Volume.from_name("blood-test-hf-cache", create_if_missing=True)
53
 
54
 
55
+ def _append_real_sft(real_labels_path, sft_path, repeat: int) -> int:
56
+ """Render real report PDFs to PNG and append oversampled SFT rows to the synthetic dataset.
57
+
58
+ Runs on the Modal box (fitz/pymupdf + the app prompt are available there). Oversampling gives a
59
+ handful of real reports enough weight to anchor the model against ~2000 synthetic samples — the
60
+ lever that synthetic-only training could not clear.
61
+ """
62
+ import json
63
+ import sys
64
+ from pathlib import Path
65
+
66
+ import fitz # pymupdf
67
+
68
+ sys.path.insert(0, "/root/app")
69
+ from src.openbmb_client import EXTRACTION_PROMPT
70
+
71
+ real_labels_path = Path(real_labels_path)
72
+ if not real_labels_path.exists():
73
+ print(f"real labels not found: {real_labels_path} — skipping real mix-in")
74
+ return 0
75
+ rows = [json.loads(ln) for ln in real_labels_path.read_text(encoding="utf-8").splitlines() if ln.strip()]
76
+ labels_dir = real_labels_path.parent
77
+ png_dir = Path("/root/app/train/data/real_png")
78
+ png_dir.mkdir(parents=True, exist_ok=True)
79
+
80
+ written = 0
81
+ with sft_path.open("a", encoding="utf-8") as fh:
82
+ for row in rows:
83
+ src = labels_dir / row["image"]
84
+ if not src.exists():
85
+ continue
86
+ png = png_dir / (Path(row["image"]).stem + ".png")
87
+ doc = fitz.open(str(src))
88
+ doc[0].get_pixmap(dpi=150).save(str(png)) # page 0 — lab reports are typically 1 page
89
+ doc.close()
90
+ target = json.dumps({"tests": row.get("tests", []), "notes": row.get("notes", [])}, ensure_ascii=False)
91
+ example = json.dumps({
92
+ "messages": [
93
+ {"role": "user", "content": "<image>\n" + EXTRACTION_PROMPT},
94
+ {"role": "assistant", "content": target},
95
+ ],
96
+ "images": [str(png.resolve())],
97
+ }, ensure_ascii=False)
98
+ for _ in range(repeat):
99
+ fh.write(example + "\n")
100
+ written += 1
101
+ return written
102
+
103
+
104
  @app.function(
105
  image=image,
106
  gpu="A100",
107
  timeout=6 * 60 * 60,
108
  volumes={"/adapters": adapters, "/root/.cache/huggingface": hf_cache},
109
  )
110
+ def train(n: int = 2000, epochs: int = 1, lr: float = 2e-5, real_labels: str | None = None, real_repeat: int = 50, seed: int = 13) -> str:
111
  import os
112
  import subprocess
113
  import sys
 
122
  labels = generate(n, data_dir, seed=seed)
123
  sft_path = Path("/root/app/train/data/sft.jsonl")
124
  n_examples = convert(labels, sft_path)
125
+ print(f"Generated {n_examples} synthetic SFT examples at {sft_path}")
126
+
127
+ # 1b) Mix in REAL labeled reports (oversampled) so the model anchors to real layouts — the
128
+ # lever synthetic-only training could not clear. real_labels = a corrected labels JSONL.
129
+ if real_labels:
130
+ n_real = _append_real_sft(Path("/root/app") / real_labels, sft_path, real_repeat)
131
+ print(f"Mixed {n_real} real SFT rows ({real_repeat}x oversample of each report)")
132
 
133
  # 2) LoRA fine-tune with ms-swift
134
  out_dir = "/adapters/minicpmv-lab-lora"
 
165
 
166
 
167
  @app.local_entrypoint()
168
+ def main(n: int = 2000, epochs: int = 1, lr: float = 2e-5, real_labels: str | None = None, real_repeat: int = 50) -> None:
169
+ path = train.remote(n=n, epochs=epochs, lr=lr, real_labels=real_labels, real_repeat=real_repeat)
170
  print(f"\nLoRA adapters saved to Modal volume 'blood-test-adapters' at {path}")
171
  print("Next: merge the adapter into the base model and push it to the Hub:")
172
  print(" modal run train/modal_finetune.py::merge --repo-id <owner>/<model-name>")