1
0

worker_base.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import importlib
  2. import os
  3. from abc import ABC, abstractmethod
  4. from typing import Dict, List, Optional, 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: Optional[ExecuteModelRequest] = None
  42. ) -> List[SamplerOutput]:
  43. """Executes at least one model step on the given sequences, unless no
  44. sequences are provided."""
  45. raise NotImplementedError
  46. @abstractmethod
  47. def get_cache_block_size_bytes(self) -> int:
  48. """Return the size of a single cache block, in bytes. Used in
  49. speculative decoding.
  50. """
  51. raise NotImplementedError
  52. @abstractmethod
  53. def add_lora(self, lora_request: LoRARequest) -> bool:
  54. raise NotImplementedError
  55. @abstractmethod
  56. def remove_lora(self, lora_id: int) -> bool:
  57. raise NotImplementedError
  58. @abstractmethod
  59. def list_loras(self) -> Set[int]:
  60. raise NotImplementedError
  61. class LoraNotSupportedWorkerBase(WorkerBase):
  62. """Partial implementation of WorkerBase that raises exceptions when LoRA
  63. methods are invoked.
  64. """
  65. def add_lora(self, lora_request: LoRARequest) -> bool:
  66. raise ValueError(f"{type(self)} does not support LoRA")
  67. def remove_lora(self, lora_id: int) -> bool:
  68. raise ValueError(f"{type(self)} does not support LoRA")
  69. def list_loras(self) -> Set[int]:
  70. raise ValueError(f"{type(self)} does not support LoRA")
  71. class WorkerWrapperBase:
  72. """
  73. The whole point of this class is to lazily initialize the worker.
  74. We first instantiate the WorkerWrapper, which remembers the worker module
  75. and class name. Then, when we call `update_environment_variables`, and the
  76. real initialization happens in `init_worker`.
  77. """
  78. def __init__(self,
  79. worker_module_name=None,
  80. worker_class_name=None,
  81. trust_remote_code: bool = False) -> None:
  82. self.worker_module_name = worker_module_name
  83. self.worker_class_name = worker_class_name
  84. self.worker = None
  85. if trust_remote_code:
  86. # note: lazy import to avoid importing torch before initializing
  87. from aphrodite.common.utils import init_cached_hf_modules
  88. init_cached_hf_modules()
  89. @staticmethod
  90. def update_environment_variables(envs: Dict[str, str]) -> None:
  91. key = 'CUDA_VISIBLE_DEVICES'
  92. if key in envs and key in os.environ:
  93. # overwriting CUDA_VISIBLE_DEVICES is desired behavior
  94. # suppress the warning in `update_environment_variables`
  95. del os.environ[key]
  96. update_environment_variables(envs)
  97. def init_worker(self, *args, **kwargs):
  98. """
  99. Actual initialization of the worker class, and set up
  100. function tracing if required.
  101. Arguments are passed to the worker class constructor.
  102. """
  103. enable_trace_function_call_for_thread()
  104. mod = importlib.import_module(self.worker_module_name)
  105. worker_class = getattr(mod, self.worker_class_name)
  106. self.worker = worker_class(*args, **kwargs)
  107. def execute_method(self, method, *args, **kwargs):
  108. try:
  109. target = self if self.worker is None else self.worker
  110. executor = getattr(target, method)
  111. return executor(*args, **kwargs)
  112. except Exception as e:
  113. # if the driver worker also execute methods,
  114. # exceptions in the rest worker may cause deadlock in rpc like ray
  115. # print the error and inform the user to solve the error
  116. msg = (f"Error executing method {method}. "
  117. "This might cause deadlock in distributed execution.")
  118. logger.exception(msg)
  119. raise e