File size: 11,519 Bytes
f5ab8aa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | """Offline DePlot (google/deplot) batch pipeline for ChartQA visual_fact_deplot."""
from __future__ import annotations
import json
import os
from typing import Any, Optional
from data_utils.paths import resolve_image_path
DEFAULT_MODEL_ID = "google/deplot"
DEFAULT_PROMPT = "Generate underlying data table of the figure below:"
PLACEHOLDER_SOURCE = "deplot_placeholder"
REAL_SOURCE = "google/deplot"
def _parse_vf(raw: Any) -> Optional[dict[str, Any]]:
if raw is None:
return None
if isinstance(raw, dict):
return raw
if isinstance(raw, str):
text = raw.strip()
if not text:
return None
try:
data = json.loads(text)
except json.JSONDecodeError:
return None
return data if isinstance(data, dict) else None
return None
def is_deplot_placeholder(vf: Any) -> bool:
data = _parse_vf(vf)
if data is None:
return False
return data.get("source") == PLACEHOLDER_SOURCE
def has_real_deplot(vf: Any) -> bool:
data = _parse_vf(vf)
if data is None:
return False
if data.get("source") == PLACEHOLDER_SOURCE:
return False
table = (data.get("parsed_table") or "").strip()
return bool(table) and data.get("source") in (REAL_SOURCE, "google/deplot", "deplot")
def format_deplot_for_teacher(vf: Any) -> str:
"""Teacher-facing text from visual_fact_deplot; empty if missing/placeholder."""
data = _parse_vf(vf)
if data is None:
return ""
if data.get("source") == PLACEHOLDER_SOURCE:
return ""
table = (data.get("parsed_table") or "").strip()
if table:
return table
return ""
def placeholder_deplot_table(entry: dict[str, Any], error: Optional[str] = None) -> str:
question = entry.get("question", entry.get("question_wo_prompt", ""))
payload: dict[str, Any] = {
"source": PLACEHOLDER_SOURCE,
"question": question,
"parsed_table": {"note": "DePlot unavailable or image missing"},
}
if error:
payload["error"] = error
return json.dumps(payload, ensure_ascii=False)
def build_deplot_visual_fact(
entry: dict[str, Any],
parsed_table: str,
*,
model_id: str = DEFAULT_MODEL_ID,
) -> str:
question = entry.get("question", entry.get("question_wo_prompt", ""))
payload = {
"source": REAL_SOURCE,
"model_id": model_id,
"question": question,
"parsed_table": parsed_table.strip(),
}
return json.dumps(payload, ensure_ascii=False)
def cache_key_for_entry(entry: dict[str, Any]) -> str:
image = entry.get("image", "")
return os.path.abspath(resolve_image_path(image)) if image else ""
def load_deplot_cache(path: str) -> dict[str, str]:
if not path or not os.path.isfile(path):
return {}
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
return {str(k): str(v) for k, v in data.items()}
except (json.JSONDecodeError, OSError):
pass
return {}
def save_deplot_cache(path: str, cache: dict[str, str]) -> None:
if not path:
return
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
tmp = f"{path}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(cache, f, ensure_ascii=False, indent=2)
os.replace(tmp, path)
def needs_deplot_processing(
entry: dict[str, Any],
*,
replace_placeholder: bool = True,
only_missing: bool = False,
) -> bool:
vf = entry.get("visual_fact_deplot")
if not vf:
return True
if is_deplot_placeholder(vf):
return replace_placeholder or only_missing
if has_real_deplot(vf):
return replace_placeholder and not only_missing
return only_missing or replace_placeholder
class DePlotRunner:
"""Lazy-loaded batched DePlot inference."""
def __init__(
self,
model_id: str = DEFAULT_MODEL_ID,
device: Optional[str] = None,
dtype: Optional[str] = None,
prompt: str = DEFAULT_PROMPT,
max_new_tokens: int = 384,
):
self.model_id = model_id
self.prompt = prompt
self.max_new_tokens = max_new_tokens
self._device = device
self._dtype = dtype
self._processor = None
self._model = None
def _resolve_device(self):
import torch
if self._device and self._device != "auto":
return torch.device(self._device)
if torch.cuda.is_available():
return torch.device("cuda")
return torch.device("cpu")
def _resolve_dtype(self, device):
import torch
if self._dtype == "float32":
return torch.float32
if self._dtype == "float16":
return torch.float16
if self._dtype == "bfloat16":
return torch.bfloat16
if device.type == "cuda":
return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
return torch.float32
def load(self) -> bool:
if self._model is not None:
return True
try:
import torch
from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor
device = self._resolve_device()
dtype = self._resolve_dtype(device)
self._processor = Pix2StructProcessor.from_pretrained(self.model_id)
self._model = Pix2StructForConditionalGeneration.from_pretrained(
self.model_id,
torch_dtype=dtype,
).to(device)
self._model.eval()
self._device_obj = device
return True
except Exception as exc:
print(f"[DePlot] model load failed: {exc}")
self._model = None
return False
def generate_batch(self, image_paths: list[str]) -> list[str]:
if not image_paths:
return []
if not self.load():
return [""] * len(image_paths)
import torch
from PIL import Image
images = []
valid_indices: list[int] = []
results: list[str] = [""] * len(image_paths)
for i, path in enumerate(image_paths):
if not path or not os.path.isfile(path):
continue
try:
images.append(Image.open(path).convert("RGB"))
valid_indices.append(i)
except OSError:
continue
if not images:
return results
device = self._device_obj
texts = [self.prompt] * len(images)
with torch.inference_mode():
inputs = self._processor(images=images, text=texts, return_tensors="pt")
inputs = {k: v.to(device) for k, v in inputs.items()}
outputs = self._model.generate(**inputs, max_new_tokens=self.max_new_tokens)
decoded = self._processor.batch_decode(outputs, skip_special_tokens=True)
for idx, text in zip(valid_indices, decoded):
results[idx] = (text or "").strip()
return results
def generate_batch_with_oom_retry(
self,
image_paths: list[str],
batch_size: int = 8,
max_retries: int = 3,
) -> list[str]:
if not image_paths:
return []
import torch
bs = max(1, batch_size)
out: list[str] = []
pos = 0
retries_left = max_retries
while pos < len(image_paths):
chunk_paths = image_paths[pos : pos + bs]
try:
chunk_out = self.generate_batch(chunk_paths)
out.extend(chunk_out)
pos += len(chunk_paths)
retries_left = max_retries
except RuntimeError as exc:
if "out of memory" not in str(exc).lower() or bs <= 1 or retries_left <= 0:
out.extend([""] * len(chunk_paths))
pos += len(chunk_paths)
continue
if torch.cuda.is_available():
torch.cuda.empty_cache()
bs = max(1, bs // 2)
retries_left -= 1
return out
def enrich_entries_with_deplot(
entries: list[dict[str, Any]],
*,
enabled: bool = True,
model_id: str = DEFAULT_MODEL_ID,
batch_size: int = 8,
max_new_tokens: int = 384,
cache_path: str = "",
replace_placeholder: bool = True,
only_missing: bool = False,
max_samples: int = 0,
device: Optional[str] = None,
) -> dict[str, int]:
"""
Fill visual_fact_deplot on entries in-place.
Returns stats dict: real, placeholder, skipped, failed, cached.
"""
stats = {"real": 0, "placeholder": 0, "skipped": 0, "failed": 0, "cached": 0}
work_entries = entries[:max_samples] if max_samples > 0 else entries
if not enabled:
for entry in work_entries:
if not needs_deplot_processing(
entry, replace_placeholder=replace_placeholder, only_missing=only_missing
):
stats["skipped"] += 1
continue
entry["visual_fact_deplot"] = placeholder_deplot_table(entry, error="deplot_disabled")
stats["placeholder"] += 1
return stats
cache = load_deplot_cache(cache_path)
runner = DePlotRunner(model_id=model_id, device=device, max_new_tokens=max_new_tokens)
model_ok = runner.load()
pending: list[tuple[int, str, str]] = []
for idx, entry in enumerate(work_entries):
if not needs_deplot_processing(
entry, replace_placeholder=replace_placeholder, only_missing=only_missing
):
stats["skipped"] += 1
continue
key = cache_key_for_entry(entry)
if key and key in cache and cache[key].strip():
entry["visual_fact_deplot"] = build_deplot_visual_fact(entry, cache[key], model_id=model_id)
stats["cached"] += 1
stats["real"] += 1
continue
if not key or not os.path.isfile(key):
entry["visual_fact_deplot"] = placeholder_deplot_table(entry, error="image_missing")
stats["placeholder"] += 1
continue
if not model_ok:
entry["visual_fact_deplot"] = placeholder_deplot_table(entry, error="model_load_failed")
stats["placeholder"] += 1
continue
pending.append((idx, key, key))
if pending and model_ok:
bs = max(1, batch_size)
for start in range(0, len(pending), bs):
chunk = pending[start : start + bs]
paths = [p[2] for p in chunk]
tables = runner.generate_batch_with_oom_retry(paths, batch_size=bs)
for (entry_idx, key, _), table in zip(chunk, tables):
entry = work_entries[entry_idx]
if table:
entry["visual_fact_deplot"] = build_deplot_visual_fact(
entry, table, model_id=model_id
)
if key:
cache[key] = table
stats["real"] += 1
else:
entry["visual_fact_deplot"] = placeholder_deplot_table(
entry, error="inference_failed"
)
stats["failed"] += 1
stats["placeholder"] += 1
if cache_path and cache:
save_deplot_cache(cache_path, cache)
return stats
|