vlm_analyze.py 11 KB

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