ppstructurev3_multi_gpu_multiprocess_official.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. # zhch/ppstructurev3_multi_gpu_multiprocess_official.py
  2. import json
  3. import time
  4. import os
  5. import glob
  6. import traceback
  7. import argparse
  8. import sys
  9. from pathlib import Path
  10. from typing import List, Dict, Any, Tuple
  11. from multiprocessing import Manager, Process, Queue
  12. from queue import Empty
  13. import cv2
  14. import numpy as np
  15. from paddlex import create_pipeline
  16. from paddlex.utils.device import constr_device, parse_device
  17. from tqdm import tqdm
  18. import paddle
  19. from dotenv import load_dotenv
  20. load_dotenv(override=True)
  21. def worker(pipeline_name_or_config_path: str,
  22. device: str,
  23. task_queue: Queue,
  24. result_queue: Queue,
  25. batch_size: int,
  26. output_dir: str,
  27. worker_id: int):
  28. """
  29. 工作进程函数 - 基于官方parallel_inference.md实现
  30. Args:
  31. pipeline_name_or_config_path: Pipeline名称或配置路径
  32. device: 设备字符串
  33. task_queue: 任务队列
  34. result_queue: 结果队列
  35. batch_size: 批处理大小
  36. output_dir: 输出目录
  37. worker_id: 工作进程ID
  38. """
  39. try:
  40. # 创建pipeline实例
  41. pipeline = create_pipeline(pipeline_name_or_config_path, device=device)
  42. print(f"Worker {worker_id} initialized with device {device}")
  43. should_end = False
  44. batch = []
  45. processed_count = 0
  46. while not should_end:
  47. try:
  48. input_path = task_queue.get_nowait()
  49. except Empty:
  50. should_end = True
  51. else:
  52. batch.append(input_path)
  53. if batch and (len(batch) == batch_size or should_end):
  54. try:
  55. start_time = time.time()
  56. # 使用pipeline预测
  57. results = list(pipeline.predict(
  58. batch,
  59. use_doc_orientation_classify=True,
  60. use_doc_unwarping=False,
  61. use_seal_recognition=True,
  62. use_chart_recognition=True,
  63. use_table_recognition=True,
  64. use_formula_recognition=True,
  65. ))
  66. batch_processing_time = time.time() - start_time
  67. batch_results = []
  68. for result in results:
  69. try:
  70. input_path = Path(result.input_path)
  71. # 保存结果
  72. if result.get("page_index") is not None:
  73. output_filename = f"{input_path.stem}_{result['page_index']}"
  74. else:
  75. output_filename = f"{input_path.stem}"
  76. # 保存JSON和Markdown
  77. json_output_path = str(Path(output_dir, f"{output_filename}.json"))
  78. md_output_path = str(Path(output_dir, f"{output_filename}.md"))
  79. result.save_to_json(json_output_path)
  80. result.save_to_markdown(md_output_path)
  81. # 记录处理结果
  82. batch_results.append({
  83. "image_path": input_path.name,
  84. "processing_time": batch_processing_time / len(batch), # 平均时间
  85. "success": True,
  86. "device": device,
  87. "worker_id": worker_id,
  88. "output_json": json_output_path,
  89. "output_md": md_output_path
  90. })
  91. processed_count += 1
  92. except Exception as e:
  93. batch_results.append({
  94. "image_path": Path(result.input_path).name if hasattr(result, 'input_path') else "unknown",
  95. "processing_time": 0,
  96. "success": False,
  97. "device": device,
  98. "worker_id": worker_id,
  99. "error": str(e)
  100. })
  101. # 将结果放入结果队列
  102. result_queue.put(batch_results)
  103. print(f"Worker {worker_id} ({device}) processed batch of {len(batch)} files. Total: {processed_count}")
  104. except Exception as e:
  105. # 批处理失败
  106. error_results = []
  107. for img_path in batch:
  108. error_results.append({
  109. "image_path": Path(img_path).name,
  110. "processing_time": 0,
  111. "success": False,
  112. "device": device,
  113. "worker_id": worker_id,
  114. "error": str(e)
  115. })
  116. result_queue.put(error_results)
  117. print(f"Error processing batch {batch} on {device}: {e}", file=sys.stderr)
  118. batch.clear()
  119. except Exception as e:
  120. print(f"Worker {worker_id} ({device}) initialization failed: {e}", file=sys.stderr)
  121. traceback.print_exc()
  122. finally:
  123. print(f"Worker {worker_id} ({device}) finished")
  124. def parallel_process_with_official_approach(image_paths: List[str],
  125. pipeline_name: str = "PP-StructureV3",
  126. device_str: str = "gpu:0,1",
  127. instances_per_device: int = 1,
  128. batch_size: int = 1,
  129. output_dir: str = "./output") -> List[Dict[str, Any]]:
  130. """
  131. 使用官方推荐的方法进行多GPU多进程并行处理
  132. Args:
  133. image_paths: 图像路径列表
  134. pipeline_name: Pipeline名称
  135. device_str: 设备字符串,如"gpu:0,1,2,3"
  136. instances_per_device: 每个设备的实例数
  137. batch_size: 批处理大小
  138. output_dir: 输出目录
  139. Returns:
  140. 处理结果列表
  141. """
  142. # 创建输出目录
  143. output_path = Path(output_dir)
  144. output_path.mkdir(parents=True, exist_ok=True)
  145. # 解析设备
  146. try:
  147. device_type, device_ids = parse_device(device_str)
  148. if device_ids is None or len(device_ids) < 1:
  149. print("No valid devices specified.", file=sys.stderr)
  150. return []
  151. print(f"Parsed devices: {device_type}:{device_ids}")
  152. except Exception as e:
  153. print(f"Failed to parse device string '{device_str}': {e}", file=sys.stderr)
  154. return []
  155. # 验证批处理大小
  156. if batch_size <= 0:
  157. print("Batch size must be greater than 0.", file=sys.stderr)
  158. return []
  159. total_instances = len(device_ids) * instances_per_device
  160. print(f"Configuration:")
  161. print(f" Devices: {device_ids}")
  162. print(f" Instances per device: {instances_per_device}")
  163. print(f" Total instances: {total_instances}")
  164. print(f" Batch size: {batch_size}")
  165. print(f" Total images: {len(image_paths)}")
  166. # 使用Manager创建队列
  167. with Manager() as manager:
  168. task_queue = manager.Queue()
  169. result_queue = manager.Queue()
  170. # 将任务放入队列
  171. for img_path in image_paths:
  172. task_queue.put(str(img_path))
  173. print(f"Added {len(image_paths)} tasks to queue")
  174. # 创建并启动工作进程
  175. processes = []
  176. worker_id = 0
  177. for device_id in device_ids:
  178. for instance_idx in range(instances_per_device):
  179. device = constr_device(device_type, [device_id])
  180. p = Process(
  181. target=worker,
  182. args=(
  183. pipeline_name,
  184. device,
  185. task_queue,
  186. result_queue,
  187. batch_size,
  188. str(output_path),
  189. worker_id,
  190. ),
  191. name=f"Worker-{worker_id}-{device}"
  192. )
  193. p.start()
  194. processes.append(p)
  195. worker_id += 1
  196. print(f"Started {len(processes)} worker processes")
  197. # 收集结果
  198. all_results = []
  199. completed_images = 0
  200. total_images = len(image_paths)
  201. with tqdm(total=total_images, desc="Processing images", unit="img") as pbar:
  202. # 等待所有结果
  203. active_workers = len(processes)
  204. while completed_images < total_images and active_workers > 0:
  205. try:
  206. # 设置较短的超时时间,定期检查进程状态
  207. batch_results = result_queue.get(timeout=5.0)
  208. all_results.extend(batch_results)
  209. batch_size_actual = len(batch_results)
  210. completed_images += batch_size_actual
  211. pbar.update(batch_size_actual)
  212. # 更新进度条信息
  213. success_count = sum(1 for r in batch_results if r.get('success', False))
  214. total_success = sum(1 for r in all_results if r.get('success', False))
  215. # 按设备统计
  216. device_stats = {}
  217. for r in all_results:
  218. device = r.get('device', 'unknown')
  219. if device not in device_stats:
  220. device_stats[device] = {'success': 0, 'total': 0}
  221. device_stats[device]['total'] += 1
  222. if r.get('success', False):
  223. device_stats[device]['success'] += 1
  224. device_info = ', '.join([f"{k}:{v['success']}/{v['total']}"
  225. for k, v in device_stats.items()])
  226. pbar.set_postfix({
  227. 'batch_success': f"{success_count}/{batch_size_actual}",
  228. 'total_success': f"{total_success}/{completed_images}",
  229. 'devices': device_info
  230. })
  231. except Exception as e:
  232. # 检查是否还有活跃的进程
  233. active_workers = sum(1 for p in processes if p.is_alive())
  234. if active_workers == 0:
  235. print("All workers have finished")
  236. break
  237. # 超时或其他错误,继续等待
  238. continue
  239. # 等待所有进程结束
  240. print("Waiting for all processes to finish...")
  241. for p in processes:
  242. p.join(timeout=10.0)
  243. if p.is_alive():
  244. print(f"Force terminating process: {p.name}")
  245. p.terminate()
  246. p.join(timeout=5.0)
  247. return all_results
  248. def main():
  249. """主函数"""
  250. parser = argparse.ArgumentParser(description="PaddleX PP-StructureV3 Multi-GPU Parallel Processing")
  251. # 必需参数
  252. parser.add_argument("--input_dir", type=str, required=True,
  253. help="Input directory containing images")
  254. parser.add_argument("--output_dir", type=str, default="./output",
  255. help="Output directory")
  256. # Pipeline配置
  257. parser.add_argument("--pipeline", type=str, default="PP-StructureV3",
  258. help="Pipeline name or config path")
  259. parser.add_argument("--device", type=str, default="gpu:0,1",
  260. help="Devices for parallel inference (e.g., 'gpu:0,1,2,3')")
  261. # 并行配置
  262. parser.add_argument("--instances_per_device", type=int, default=1,
  263. help="Number of pipeline instances per device")
  264. parser.add_argument("--batch_size", type=int, default=1,
  265. help="Inference batch size for each pipeline instance")
  266. # 输入文件配置
  267. parser.add_argument("--input_glob_pattern", type=str, default="*",
  268. help="Pattern to find input files")
  269. # 测试模式
  270. parser.add_argument("--test_mode", action="store_true",
  271. help="Test mode: only process first 20 images")
  272. args = parser.parse_args()
  273. # 验证输入目录
  274. input_dir = Path(args.input_dir)
  275. if not input_dir.exists():
  276. print(f"Input directory does not exist: {input_dir}", file=sys.stderr)
  277. return 2
  278. if not input_dir.is_dir():
  279. print(f"{input_dir} is not a directory", file=sys.stderr)
  280. return 2
  281. # 验证输出目录
  282. output_dir = Path(args.output_dir)
  283. if output_dir.exists() and not output_dir.is_dir():
  284. print(f"{output_dir} is not a directory", file=sys.stderr)
  285. return 2
  286. print("="*70)
  287. print("PaddleX PP-StructureV3 Multi-GPU Parallel Processing")
  288. print("="*70)
  289. print(f"Input directory: {input_dir}")
  290. print(f"Output directory: {output_dir}")
  291. print(f"Pipeline: {args.pipeline}")
  292. print(f"Device: {args.device}")
  293. print(f"Instances per device: {args.instances_per_device}")
  294. print(f"Batch size: {args.batch_size}")
  295. print(f"Input pattern: {args.input_glob_pattern}")
  296. # 查找图像文件
  297. image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.tiff', '*.pdf']
  298. image_files = []
  299. for ext in image_extensions:
  300. pattern = args.input_glob_pattern if args.input_glob_pattern != "*" else ext
  301. image_files.extend(input_dir.glob(pattern))
  302. # 如果没有找到文件,尝试使用用户指定的模式
  303. if not image_files and args.input_glob_pattern != "*":
  304. image_files = list(input_dir.glob(args.input_glob_pattern))
  305. if not image_files:
  306. print(f"No image files found in {input_dir} with pattern {args.input_glob_pattern}")
  307. return 1
  308. # 转换为字符串路径
  309. image_paths = [str(f) for f in image_files]
  310. print(f"Found {len(image_paths)} image files")
  311. # 测试模式
  312. if args.test_mode:
  313. image_paths = image_paths[:20]
  314. print(f"Test mode: processing only {len(image_paths)} images")
  315. # 开始处理
  316. start_time = time.time()
  317. try:
  318. results = parallel_process_with_official_approach(
  319. image_paths=image_paths,
  320. pipeline_name=args.pipeline,
  321. device_str=args.device,
  322. instances_per_device=args.instances_per_device,
  323. batch_size=args.batch_size,
  324. output_dir=args.output_dir
  325. )
  326. total_time = time.time() - start_time
  327. # 统计信息
  328. success_count = sum(1 for r in results if r.get('success', False))
  329. error_count = len(results) - success_count
  330. total_processing_time = sum(r.get('processing_time', 0) for r in results if r.get('success', False))
  331. avg_processing_time = total_processing_time / success_count if success_count > 0 else 0
  332. # 按设备统计
  333. device_stats = {}
  334. worker_stats = {}
  335. for r in results:
  336. device = r.get('device', 'unknown')
  337. worker_id = r.get('worker_id', 'unknown')
  338. # 设备统计
  339. if device not in device_stats:
  340. device_stats[device] = {'success': 0, 'total': 0, 'total_time': 0}
  341. device_stats[device]['total'] += 1
  342. if r.get('success', False):
  343. device_stats[device]['success'] += 1
  344. device_stats[device]['total_time'] += r.get('processing_time', 0)
  345. # Worker统计
  346. if worker_id not in worker_stats:
  347. worker_stats[worker_id] = {'success': 0, 'total': 0, 'device': device}
  348. worker_stats[worker_id]['total'] += 1
  349. if r.get('success', False):
  350. worker_stats[worker_id]['success'] += 1
  351. # 保存详细结果
  352. detailed_results = {
  353. "configuration": {
  354. "pipeline": args.pipeline,
  355. "device": args.device,
  356. "instances_per_device": args.instances_per_device,
  357. "batch_size": args.batch_size,
  358. "input_glob_pattern": args.input_glob_pattern,
  359. "test_mode": args.test_mode
  360. },
  361. "statistics": {
  362. "total_files": len(image_paths),
  363. "success_count": success_count,
  364. "error_count": error_count,
  365. "success_rate": success_count / len(image_paths) if image_paths else 0,
  366. "total_time": total_time,
  367. "avg_processing_time": avg_processing_time,
  368. "throughput": len(image_paths) / total_time if total_time > 0 else 0,
  369. "device_stats": device_stats,
  370. "worker_stats": worker_stats
  371. },
  372. "results": results
  373. }
  374. # 保存结果文件
  375. result_file = output_dir / "processing_results.json"
  376. with open(result_file, 'w', encoding='utf-8') as f:
  377. json.dump(detailed_results, f, ensure_ascii=False, indent=2)
  378. # 打印统计信息
  379. print("\n" + "="*70)
  380. print("Processing completed!")
  381. print("="*70)
  382. print(f"Total files: {len(image_paths)}")
  383. print(f"Successfully processed: {success_count}")
  384. print(f"Failed: {error_count}")
  385. print(f"Success rate: {success_count / len(image_paths) * 100:.2f}%")
  386. print(f"Total time: {total_time:.2f} seconds")
  387. print(f"Average processing time: {avg_processing_time:.2f} seconds/image")
  388. print(f"Throughput: {len(image_paths) / total_time:.2f} images/second")
  389. # 设备统计
  390. print(f"\nDevice Statistics:")
  391. for device, stats in device_stats.items():
  392. if stats['total'] > 0:
  393. success_rate = stats['success'] / stats['total'] * 100
  394. avg_time = stats['total_time'] / stats['success'] if stats['success'] > 0 else 0
  395. print(f" {device}: {stats['success']}/{stats['total']} "
  396. f"({success_rate:.1f}%), avg {avg_time:.2f}s/image")
  397. # Worker统计
  398. print(f"\nWorker Statistics:")
  399. for worker_id, stats in worker_stats.items():
  400. if stats['total'] > 0:
  401. success_rate = stats['success'] / stats['total'] * 100
  402. print(f" Worker {worker_id} ({stats['device']}): {stats['success']}/{stats['total']} "
  403. f"({success_rate:.1f}%)")
  404. print(f"\nDetailed results saved to: {result_file}")
  405. print("All done!")
  406. return 0
  407. except Exception as e:
  408. print(f"Processing failed: {e}", file=sys.stderr)
  409. traceback.print_exc()
  410. return 1
  411. if __name__ == "__main__":
  412. if len(sys.argv) == 1:
  413. # 如果没有命令行参数,使用默认配置运行
  414. print("No command line arguments provided. Running with default configuration...")
  415. # 默认配置
  416. default_config = {
  417. "input_dir": "../../OmniDocBench/OpenDataLab___OmniDocBench/images",
  418. "output_dir": "./OmniDocBench_Results_Official",
  419. "pipeline": "PP-StructureV3",
  420. "device": "gpu:0,1",
  421. "instances_per_device": 1,
  422. "batch_size": 1,
  423. "test_mode": False
  424. }
  425. # 构造参数
  426. sys.argv = [sys.argv[0]]
  427. for key, value in default_config.items():
  428. sys.argv.extend([f"--{key}", str(value)])
  429. # 测试模式
  430. # sys.argv.append("--test_mode")
  431. sys.exit(main())