worker_base.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import importlib
  2. import os
  3. from abc import ABC, abstractmethod
  4. from typing import Dict, List, Set, Tuple
  5. from loguru import logger
  6. from aphrodite.common.sequence import ExecuteModelRequest, SamplerOutput
  7. from aphrodite.common.utils import (enable_trace_function_call_for_thread,
  8. update_environment_variables)
  9. from aphrodite.lora.request import LoRARequest
  10. class WorkerBase(ABC):
  11. """Worker interface that allows Aphrodite to cleanly separate
  12. implementations for different hardware.
  13. """
  14. @abstractmethod
  15. def init_device(self) -> None:
  16. """Initialize device state, such as loading the model or other on-device
  17. memory allocations.
  18. """
  19. raise NotImplementedError
  20. @abstractmethod
  21. def determine_num_available_blocks(self) -> Tuple[int, int]:
  22. """Determine the number of available blocks for the GPU KV cache and
  23. swappable CPU KV cache.
  24. The implementation may run profiling or other heuristics to determine
  25. the size of caches.
  26. Returns a Tuple[num_gpu_blocks, num_cpu_blocks], where num_gpu_blocks
  27. are blocks that are "active" on the device and can be appended to.
  28. num_cpu_blocks refers to "swapped" blocks in CPU memory and cannot be
  29. appended to.
  30. """
  31. raise NotImplementedError
  32. @abstractmethod
  33. def initialize_cache(self, num_gpu_blocks: int,
  34. num_cpu_blocks: int) -> None:
  35. """Initialize the KV cache with the given size in blocks.
  36. """
  37. raise NotImplementedError
  38. @abstractmethod
  39. def execute_model(
  40. self,
  41. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  42. """Executes at least one model step on the given sequences, unless no
  43. sequences are provided."""
  44. raise NotImplementedError
  45. @abstractmethod
  46. def get_cache_block_size_bytes(self) -> int:
  47. """Return the size of a single cache block, in bytes. Used in
  48. speculative decoding.
  49. """
  50. raise NotImplementedError
  51. @abstractmethod
  52. def add_lora(self, lora_request: LoRARequest) -> bool:
  53. raise NotImplementedError
  54. @abstractmethod
  55. def remove_lora(self, lora_id: int) -> bool:
  56. raise NotImplementedError
  57. @abstractmethod
  58. def list_loras(self) -> Set[int]:
  59. raise NotImplementedError
  60. class LoraNotSupportedWorkerBase(WorkerBase):
  61. """Partial implementation of WorkerBase that raises exceptions when LoRA
  62. methods are invoked.
  63. """
  64. def add_lora(self, lora_request: LoRARequest) -> bool:
  65. raise ValueError(f"{type(self)} does not support LoRA")
  66. def remove_lora(self, lora_id: int) -> bool:
  67. raise ValueError(f"{type(self)} does not support LoRA")
  68. def list_loras(self) -> Set[int]:
  69. raise ValueError(f"{type(self)} does not support LoRA")
  70. class WorkerWrapperBase:
  71. """
  72. The whole point of this class is to lazily initialize the worker.
  73. We first instantiate the WorkerWrapper, which remembers the worker module
  74. and class name. Then, when we call `update_environment_variables`, and the
  75. real initialization happens in `init_worker`.
  76. """
  77. def __init__(self,
  78. worker_module_name=None,
  79. worker_class_name=None,
  80. trust_remote_code: bool = False) -> None:
  81. self.worker_module_name = worker_module_name
  82. self.worker_class_name = worker_class_name
  83. self.worker = None
  84. if trust_remote_code:
  85. # note: lazy import to avoid importing torch before initializing
  86. from aphrodite.common.utils import init_cached_hf_modules
  87. init_cached_hf_modules()
  88. @staticmethod
  89. def update_environment_variables(envs: Dict[str, str]) -> None:
  90. key = 'CUDA_VISIBLE_DEVICES'
  91. if key in envs and key in os.environ:
  92. # overwriting CUDA_VISIBLE_DEVICES is desired behavior
  93. # suppress the warning in `update_environment_variables`
  94. del os.environ[key]
  95. update_environment_variables(envs)
  96. def init_worker(self, *args, **kwargs):
  97. """
  98. Actual initialization of the worker class, and set up
  99. function tracing if required.
  100. Arguments are passed to the worker class constructor.
  101. """
  102. enable_trace_function_call_for_thread()
  103. mod = importlib.import_module(self.worker_module_name)
  104. worker_class = getattr(mod, self.worker_class_name)
  105. self.worker = worker_class(*args, **kwargs)
  106. def execute_method(self, method, *args, **kwargs):
  107. try:
  108. target = self if self.worker is None else self.worker
  109. executor = getattr(target, method)
  110. return executor(*args, **kwargs)
  111. except Exception as e:
  112. # if the driver worker also execute methods,
  113. # exceptions in the rest worker may cause deadlock in rpc like ray
  114. # print the error and inform the user to solve the error
  115. msg = (f"Error executing method {method}. "
  116. "This might cause deadlock in distributed execution.")
  117. logger.exception(msg)
  118. raise e