ppstructurev3_multi_gpu_multiprocess_official.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 # ❌ 不要在主模块导入paddle
  19. # from cuda_utils import detect_available_gpus, monitor_gpu_memory # ❌ 不要在主进程使用
  20. from dotenv import load_dotenv
  21. load_dotenv(override=True)
  22. def worker(pipeline_name_or_config_path: str,
  23. device: str,
  24. task_queue: Queue,
  25. result_queue: Queue,
  26. batch_size: int,
  27. output_dir: str,
  28. worker_id: int):
  29. """
  30. 工作进程函数 - 基于官方parallel_inference.md实现
  31. Args:
  32. pipeline_name_or_config_path: Pipeline名称或配置路径
  33. device: 设备字符串
  34. task_queue: 任务队列
  35. result_queue: 结果队列
  36. batch_size: 批处理大小
  37. output_dir: 输出目录
  38. worker_id: 工作进程ID
  39. """
  40. try:
  41. # 在子进程中导入paddle,避免主进程CUDA冲突
  42. import paddle
  43. import os
  44. # 设置子进程的CUDA设备
  45. device_id = device.split(':')[1] if ':' in device else '0'
  46. os.environ['CUDA_VISIBLE_DEVICES'] = device_id
  47. # 直接创建pipeline,让PaddleX自动处理设备初始化
  48. pipeline = create_pipeline(pipeline_name_or_config_path, device=device)
  49. print(f"Worker {worker_id} initialized with device {device}")
  50. except Exception as e:
  51. print(f"Worker {worker_id} ({device}) initialization failed: {e}", file=sys.stderr)
  52. traceback.print_exc()
  53. # 发送错误信息到结果队列
  54. result_queue.put([{
  55. "error": f"Worker initialization failed: {str(e)}",
  56. "worker_id": worker_id,
  57. "device": device,
  58. "success": False
  59. }])
  60. return
  61. try:
  62. should_end = False
  63. batch = []
  64. processed_count = 0
  65. while not should_end:
  66. try:
  67. input_path = task_queue.get_nowait()
  68. except Empty:
  69. should_end = True
  70. except Exception as e:
  71. # 处理其他可能的异常
  72. print(f"Unexpected error while getting task: {e}", file=sys.stderr)
  73. traceback.print_exc()
  74. should_end = True
  75. else:
  76. # 检查是否为结束信号
  77. if input_path is None:
  78. should_end = True
  79. else:
  80. batch.append(input_path)
  81. if batch and (len(batch) == batch_size or should_end):
  82. try:
  83. start_time = time.time()
  84. # 使用pipeline预测
  85. results = pipeline.predict(
  86. batch,
  87. use_doc_orientation_classify=True,
  88. use_doc_unwarping=False,
  89. use_seal_recognition=True,
  90. use_chart_recognition=True,
  91. use_table_recognition=True,
  92. use_formula_recognition=True,
  93. )
  94. batch_processing_time = time.time() - start_time
  95. batch_results = []
  96. for result in results:
  97. try:
  98. input_path = Path(result["input_path"])
  99. # 保存结果
  100. if result.get("page_index") is not None:
  101. output_filename = f"{input_path.stem}_{result['page_index']}"
  102. else:
  103. output_filename = f"{input_path.stem}"
  104. # 保存JSON和Markdown
  105. json_output_path = str(Path(output_dir, f"{output_filename}.json"))
  106. md_output_path = str(Path(output_dir, f"{output_filename}.md"))
  107. result.save_to_json(json_output_path)
  108. result.save_to_markdown(md_output_path)
  109. # 记录处理结果
  110. batch_results.append({
  111. "image_path": input_path.name,
  112. "processing_time": batch_processing_time / len(batch), # 平均时间
  113. "success": True,
  114. "device": device,
  115. "worker_id": worker_id,
  116. "output_json": json_output_path,
  117. "output_md": md_output_path
  118. })
  119. processed_count += 1
  120. except Exception as e:
  121. traceback.print_exc()
  122. batch_results.append({
  123. "image_path": Path(result["input_path"]).name,
  124. "processing_time": 0,
  125. "success": False,
  126. "device": device,
  127. "worker_id": worker_id,
  128. "error": str(e)
  129. })
  130. # 将结果放入结果队列
  131. result_queue.put(batch_results)
  132. # print(f"Worker {worker_id} ({device}) processed batch of {len(batch)} files. Total: {processed_count}")
  133. except Exception as e:
  134. # 批处理失败
  135. error_results = []
  136. for img_path in batch:
  137. error_results.append({
  138. "image_path": Path(img_path).name,
  139. "processing_time": 0,
  140. "success": False,
  141. "device": device,
  142. "worker_id": worker_id,
  143. "error": str(e)
  144. })
  145. result_queue.put(error_results)
  146. print(f"Error processing batch {batch} on {device}: {e}", file=sys.stderr)
  147. traceback.print_exc()
  148. batch.clear()
  149. except Exception as e:
  150. print(f"Worker {worker_id} ({device}) initialization failed: {e}", file=sys.stderr)
  151. traceback.print_exc()
  152. finally:
  153. print(f"Worker {worker_id} ({device}) finished")
  154. def parallel_process_with_official_approach(image_paths: List[str],
  155. pipeline_name: str = "PP-StructureV3",
  156. device_str: str = "gpu:0,1",
  157. instances_per_device: int = 1,
  158. batch_size: int = 1,
  159. output_dir: str = "./output") -> List[Dict[str, Any]]:
  160. """
  161. 使用官方推荐的方法进行多GPU多进程并行处理
  162. Args:
  163. image_paths: 图像路径列表
  164. pipeline_name: Pipeline名称
  165. device_str: 设备字符串,如"gpu:0,1,2,3"
  166. instances_per_device: 每个设备的实例数
  167. batch_size: 批处理大小
  168. output_dir: 输出目录
  169. Returns:
  170. 处理结果列表
  171. """
  172. # 创建输出目录
  173. output_path = Path(output_dir)
  174. output_path.mkdir(parents=True, exist_ok=True)
  175. # 解析设备 - 不要在主进程中初始化paddle
  176. try:
  177. device_type, device_ids = parse_device(device_str)
  178. if device_ids is None or len(device_ids) < 1:
  179. print("No valid devices specified.", file=sys.stderr)
  180. return []
  181. print(f"Parsed devices: {device_type}:{device_ids}")
  182. except Exception as e:
  183. print(f"Failed to parse device string '{device_str}': {e}", file=sys.stderr)
  184. return []
  185. # 验证批处理大小
  186. if batch_size <= 0:
  187. print("Batch size must be greater than 0.", file=sys.stderr)
  188. return []
  189. total_instances = len(device_ids) * instances_per_device
  190. print(f"Configuration:")
  191. print(f" Devices: {device_ids}")
  192. print(f" Instances per device: {instances_per_device}")
  193. print(f" Total instances: {total_instances}")
  194. print(f" Batch size: {batch_size}")
  195. print(f" Total images: {len(image_paths)}")
  196. # 使用Manager创建队列
  197. with Manager() as manager:
  198. task_queue = manager.Queue()
  199. result_queue = manager.Queue()
  200. # 将任务放入队列
  201. for img_path in image_paths:
  202. task_queue.put(str(img_path))
  203. print(f"Added {len(image_paths)} tasks to queue")
  204. # 创建并启动工作进程
  205. processes = []
  206. worker_id = 0
  207. for device_id in device_ids:
  208. for _ in range(instances_per_device):
  209. device = constr_device(device_type, [device_id])
  210. p = Process(
  211. target=worker,
  212. args=(
  213. pipeline_name,
  214. device,
  215. task_queue,
  216. result_queue,
  217. batch_size,
  218. str(output_path),
  219. worker_id,
  220. ),
  221. )
  222. p.start()
  223. processes.append(p)
  224. worker_id += 1
  225. print(f"Started {len(processes)} worker processes")
  226. # 发送结束信号
  227. for _ in range(total_instances):
  228. task_queue.put(None)
  229. # 收集结果
  230. all_results = []
  231. total_images = len(image_paths)
  232. with tqdm(total=total_images, desc="Processing images", unit="img") as pbar:
  233. completed_count = 0
  234. while completed_count < total_images:
  235. try:
  236. batch_results = result_queue.get(timeout=600) # 10分钟超时
  237. all_results.extend(batch_results)
  238. # 更新进度条
  239. batch_success_count = sum(1 for r in batch_results if r.get('success', False))
  240. completed_count += len(batch_results)
  241. pbar.update(len(batch_results))
  242. # 显示当前批次状态
  243. pbar.set_postfix({
  244. 'batch_success': f"{batch_success_count}/{len(batch_results)}",
  245. 'total_success': f"{sum(1 for r in all_results if r.get('success', False))}/{completed_count}"
  246. })
  247. except Exception as e:
  248. print(f"Error collecting results: {e}")
  249. break
  250. # 等待所有进程结束
  251. for p in processes:
  252. p.join()
  253. return all_results
  254. def main():
  255. """主函数"""
  256. parser = argparse.ArgumentParser(description="PaddleX PP-StructureV3 Multi-GPU Parallel Processing")
  257. # 必需参数
  258. parser.add_argument("--input_dir", type=str, default="../../OmniDocBench/OpenDataLab___OmniDocBench/images", help="Input directory")
  259. parser.add_argument("--output_dir", type=str, default="./OmniDocBench_Results_Official", help="Output directory")
  260. parser.add_argument("--pipeline", type=str, default="PP-StructureV3", help="Pipeline name")
  261. parser.add_argument("--device", type=str, default="gpu:0", help="Device string")
  262. parser.add_argument("--instances_per_device", type=int, default=1, help="Instances per device")
  263. parser.add_argument("--batch_size", type=int, default=4, help="Batch size")
  264. parser.add_argument("--input_pattern", type=str, default="*", help="Input file pattern")
  265. parser.add_argument("--test_mode", action="store_true", help="Test mode (process only 20 images)")
  266. args = parser.parse_args()
  267. try:
  268. # 获取图像文件列表
  269. input_dir = Path(args.input_dir).resolve()
  270. output_dir = Path(args.output_dir).resolve()
  271. print(f"Input dir: {input_dir}, Output dir: {output_dir}")
  272. if not input_dir.exists():
  273. print(f"Input directory does not exist: {input_dir}")
  274. return 1
  275. # 查找图像文件
  276. image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif']
  277. image_files = []
  278. for ext in image_extensions:
  279. image_files.extend(list(input_dir.glob(f"*{ext}")))
  280. image_files.extend(list(input_dir.glob(f"*{ext.upper()}")))
  281. if not image_files:
  282. print(f"No image files found in {input_dir}")
  283. return 1
  284. image_files = [str(f) for f in image_files]
  285. print(f"Found {len(image_files)} image files")
  286. if args.test_mode:
  287. image_files = image_files[:20]
  288. print(f"Test mode: processing only {len(image_files)} images")
  289. # 开始处理
  290. start_time = time.time()
  291. results = parallel_process_with_official_approach(
  292. image_files,
  293. args.pipeline,
  294. args.device,
  295. args.instances_per_device,
  296. args.batch_size,
  297. str(output_dir)
  298. )
  299. total_time = time.time() - start_time
  300. # 统计结果
  301. success_count = sum(1 for r in results if r.get('success', False))
  302. error_count = len(results) - success_count
  303. print(f"\n" + "="*50)
  304. print(f"Processing completed!")
  305. print(f"Total files: {len(image_files)}")
  306. print(f"Successful: {success_count}")
  307. print(f"Failed: {error_count}")
  308. print(f"Success rate: {success_count / len(image_files) * 100:.2f}%")
  309. print(f"Total time: {total_time:.2f} seconds")
  310. print(f"Throughput: {len(image_files) / total_time:.2f} images/second")
  311. # 保存结果统计
  312. stats = {
  313. "total_files": len(image_files),
  314. "success_count": success_count,
  315. "error_count": error_count,
  316. "success_rate": success_count / len(image_files),
  317. "total_time": total_time,
  318. "throughput": len(image_files) / total_time,
  319. "batch_size": args.batch_size,
  320. "gpu_ids": args.device,
  321. "pipelines_per_gpu": args.instances_per_device
  322. }
  323. # 保存最终结果
  324. output_file = os.path.join(output_dir, f"OmniDocBench_MultiGPU_batch{args.batch_size}.json")
  325. final_results = {
  326. "stats": stats,
  327. "results": results
  328. }
  329. with open(output_file, 'w', encoding='utf-8') as f:
  330. json.dump(final_results, f, ensure_ascii=False, indent=2)
  331. return 0
  332. except Exception as e:
  333. print(f"Processing failed: {e}", file=sys.stderr)
  334. traceback.print_exc()
  335. return 1
  336. if __name__ == "__main__":
  337. # ❌ 移除所有主进程CUDA操作
  338. # print(f"🚀 启动OCR程序...")
  339. # print(f"CUDA 版本: {paddle.device.cuda.get_device_name()}")
  340. # print(f"CUDA_VISIBLE_DEVICES: {os.environ.get('CUDA_VISIBLE_DEVICES')}")
  341. # available_gpus = detect_available_gpus()
  342. # monitor_gpu_memory(available_gpus)
  343. # ✅ 只进行简单的环境检查
  344. print(f"🚀 启动OCR程序...")
  345. print(f"CUDA_VISIBLE_DEVICES: {os.environ.get('CUDA_VISIBLE_DEVICES')}")
  346. if len(sys.argv) == 1:
  347. # 如果没有命令行参数,使用默认配置运行
  348. print("No command line arguments provided. Running with default configuration...")
  349. # 默认配置
  350. default_config = {
  351. "input_dir": "../../OmniDocBench/OpenDataLab___OmniDocBench/images",
  352. "output_dir": "./OmniDocBench_Results_Official",
  353. "pipeline": "PP-StructureV3",
  354. "device": "gpu:0,1,2,3",
  355. "instances_per_device": 1,
  356. "batch_size": 4,
  357. # "test_mode": False
  358. }
  359. # 构造参数
  360. sys.argv = [sys.argv[0]]
  361. for key, value in default_config.items():
  362. sys.argv.extend([f"--{key}", str(value)])
  363. # 测试模式
  364. sys.argv.append("--test_mode")
  365. sys.exit(main())