worker_base.py 5.3 KB

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