vlm_analyze.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import os
  3. import time
  4. from loguru import logger
  5. from .utils import enable_custom_logits_processors, set_default_gpu_memory_utilization, set_default_batch_size
  6. from .model_output_to_middle_json import result_to_middle_json
  7. from ...data.data_reader_writer import DataWriter
  8. from mineru.utils.pdf_image_tools import load_images_from_pdf
  9. from ...utils.check_sys_env import is_mac_os_version_supported
  10. from ...utils.config_reader import get_device
  11. from ...utils.enum_class import ImageType
  12. from ...utils.models_download_utils import auto_download_and_get_model_root_path
  13. from mineru_vl_utils import MinerUClient
  14. from packaging import version
  15. class ModelSingleton:
  16. _instance = None
  17. _models = {}
  18. def __new__(cls, *args, **kwargs):
  19. if cls._instance is None:
  20. cls._instance = super().__new__(cls)
  21. return cls._instance
  22. def get_model(
  23. self,
  24. backend: str,
  25. model_path: str | None,
  26. server_url: str | None,
  27. **kwargs,
  28. ) -> MinerUClient:
  29. key = (backend, model_path, server_url)
  30. if key not in self._models:
  31. start_time = time.time()
  32. model = None
  33. processor = None
  34. vllm_llm = None
  35. lmdeploy_engine = None
  36. vllm_async_llm = None
  37. batch_size = kwargs.get("batch_size", 0) # for transformers backend only
  38. max_concurrency = kwargs.get("max_concurrency", 100) # for http-client backend only
  39. http_timeout = kwargs.get("http_timeout", 600) # for http-client backend only
  40. # 从kwargs中移除这些参数,避免传递给不相关的初始化函数
  41. for param in ["batch_size", "max_concurrency", "http_timeout"]:
  42. if param in kwargs:
  43. del kwargs[param]
  44. if backend in ['transformers', 'vllm-engine', "vllm-async-engine", "mlx-engine", "lmdeploy-engine"] and not model_path:
  45. model_path = auto_download_and_get_model_root_path("/","vlm")
  46. if backend == "transformers":
  47. try:
  48. from transformers import (
  49. AutoProcessor,
  50. Qwen2VLForConditionalGeneration,
  51. )
  52. from transformers import __version__ as transformers_version
  53. except ImportError:
  54. raise ImportError("Please install transformers to use the transformers backend.")
  55. if version.parse(transformers_version) >= version.parse("4.56.0"):
  56. dtype_key = "dtype"
  57. else:
  58. dtype_key = "torch_dtype"
  59. device = get_device()
  60. model = Qwen2VLForConditionalGeneration.from_pretrained(
  61. model_path,
  62. device_map={"": device},
  63. **{dtype_key: "auto"}, # type: ignore
  64. )
  65. processor = AutoProcessor.from_pretrained(
  66. model_path,
  67. use_fast=True,
  68. )
  69. if batch_size == 0:
  70. batch_size = set_default_batch_size()
  71. elif backend == "mlx-engine":
  72. mlx_supported = is_mac_os_version_supported()
  73. if not mlx_supported:
  74. raise EnvironmentError("mlx-engine backend is only supported on macOS 13.5+ with Apple Silicon.")
  75. try:
  76. from mlx_vlm import load as mlx_load
  77. except ImportError:
  78. raise ImportError("Please install mlx-vlm to use the mlx-engine backend.")
  79. model, processor = mlx_load(model_path)
  80. else:
  81. if os.getenv('OMP_NUM_THREADS') is None:
  82. os.environ["OMP_NUM_THREADS"] = "1"
  83. if backend == "vllm-engine":
  84. try:
  85. import vllm
  86. from mineru_vl_utils import MinerULogitsProcessor
  87. except ImportError:
  88. raise ImportError("Please install vllm to use the vllm-engine backend.")
  89. if "gpu_memory_utilization" not in kwargs:
  90. kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()
  91. if "model" not in kwargs:
  92. kwargs["model"] = model_path
  93. if enable_custom_logits_processors() and ("logits_processors" not in kwargs):
  94. kwargs["logits_processors"] = [MinerULogitsProcessor]
  95. # 使用kwargs为 vllm初始化参数
  96. vllm_llm = vllm.LLM(**kwargs)
  97. elif backend == "vllm-async-engine":
  98. try:
  99. from vllm.engine.arg_utils import AsyncEngineArgs
  100. from vllm.v1.engine.async_llm import AsyncLLM
  101. from mineru_vl_utils import MinerULogitsProcessor
  102. except ImportError:
  103. raise ImportError("Please install vllm to use the vllm-async-engine backend.")
  104. if "gpu_memory_utilization" not in kwargs:
  105. kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()
  106. if "model" not in kwargs:
  107. kwargs["model"] = model_path
  108. if enable_custom_logits_processors() and ("logits_processors" not in kwargs):
  109. kwargs["logits_processors"] = [MinerULogitsProcessor]
  110. # 使用kwargs为 vllm初始化参数
  111. vllm_async_llm = AsyncLLM.from_engine_args(AsyncEngineArgs(**kwargs))
  112. elif backend == "lmdeploy-engine":
  113. try:
  114. from lmdeploy import PytorchEngineConfig, TurbomindEngineConfig
  115. from lmdeploy.serve.vl_async_engine import VLAsyncEngine
  116. except ImportError:
  117. raise ImportError("Please install lmdeploy to use the lmdeploy-engine backend.")
  118. if "cache_max_entry_count" not in kwargs:
  119. kwargs["cache_max_entry_count"] = 0.5
  120. # 默认使用 turbomind
  121. lm_backend = "turbomind"
  122. device = kwargs.get("device", "cuda").lower()
  123. # 特定设备强制使用 pytorch backend
  124. if device in ["ascend", "maca", "camb"]:
  125. lm_backend = "pytorch"
  126. backend_config = PytorchEngineConfig(**kwargs)
  127. else:
  128. backend_config = TurbomindEngineConfig(**kwargs)
  129. log_level = 'ERROR'
  130. from lmdeploy.utils import get_logger
  131. lm_logger = get_logger('lmdeploy')
  132. lm_logger.setLevel(log_level)
  133. if os.getenv('TM_LOG_LEVEL') is None:
  134. os.environ['TM_LOG_LEVEL'] = log_level
  135. lmdeploy_engine = VLAsyncEngine(
  136. model_path,
  137. backend=lm_backend,
  138. backend_config=backend_config,
  139. )
  140. self._models[key] = MinerUClient(
  141. backend=backend,
  142. model=model,
  143. processor=processor,
  144. lmdeploy_engine=lmdeploy_engine,
  145. vllm_llm=vllm_llm,
  146. vllm_async_llm=vllm_async_llm,
  147. server_url=server_url,
  148. batch_size=batch_size,
  149. max_concurrency=max_concurrency,
  150. http_timeout=http_timeout,
  151. )
  152. elapsed = round(time.time() - start_time, 2)
  153. logger.info(f"get {backend} predictor cost: {elapsed}s")
  154. return self._models[key]
  155. def doc_analyze(
  156. pdf_bytes,
  157. image_writer: DataWriter | None,
  158. predictor: MinerUClient | None = None,
  159. backend="transformers",
  160. model_path: str | None = None,
  161. server_url: str | None = None,
  162. **kwargs,
  163. ):
  164. if predictor is None:
  165. predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)
  166. # load_images_start = time.time()
  167. images_list, pdf_doc = load_images_from_pdf(pdf_bytes, image_type=ImageType.PIL)
  168. images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
  169. # load_images_time = round(time.time() - load_images_start, 2)
  170. # logger.info(f"load images cost: {load_images_time}, speed: {round(len(images_base64_list)/load_images_time, 3)} images/s")
  171. # infer_start = time.time()
  172. results = predictor.batch_two_step_extract(images=images_pil_list)
  173. # infer_time = round(time.time() - infer_start, 2)
  174. # logger.info(f"infer finished, cost: {infer_time}, speed: {round(len(results)/infer_time, 3)} page/s")
  175. middle_json = result_to_middle_json(results, images_list, pdf_doc, image_writer)
  176. return middle_json, results
  177. async def aio_doc_analyze(
  178. pdf_bytes,
  179. image_writer: DataWriter | None,
  180. predictor: MinerUClient | None = None,
  181. backend="transformers",
  182. model_path: str | None = None,
  183. server_url: str | None = None,
  184. **kwargs,
  185. ):
  186. if predictor is None:
  187. predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)
  188. # load_images_start = time.time()
  189. images_list, pdf_doc = load_images_from_pdf(pdf_bytes, image_type=ImageType.PIL)
  190. images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
  191. # load_images_time = round(time.time() - load_images_start, 2)
  192. # logger.debug(f"load images cost: {load_images_time}, speed: {round(len(images_pil_list)/load_images_time, 3)} images/s")
  193. # infer_start = time.time()
  194. results = await predictor.aio_batch_two_step_extract(images=images_pil_list)
  195. # infer_time = round(time.time() - infer_start, 2)
  196. # logger.info(f"infer finished, cost: {infer_time}, speed: {round(len(results)/infer_time, 3)} page/s")
  197. middle_json = result_to_middle_json(results, images_list, pdf_doc, image_writer)
  198. return middle_json, results