|
| 1 | +# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, |
| 10 | +# software distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +from concurrent.futures import Future |
| 17 | +from threading import Lock |
| 18 | +from typing import List |
| 19 | + |
| 20 | +from deepsparse.v2.operators import EngineOperator, Operator |
| 21 | +from deepsparse.v2.schedulers.scheduler import OperatorScheduler |
| 22 | +from deepsparse.v2.schedulers.utils import ( |
| 23 | + ContinuousBatchingExecutorThread, |
| 24 | + ContinuousBatchingQueues, |
| 25 | +) |
| 26 | + |
| 27 | + |
| 28 | +__all__ = ["ContinuousBatchingScheduler"] |
| 29 | + |
| 30 | + |
| 31 | +_GLOBAL_SCHEDULER = None |
| 32 | + |
| 33 | + |
| 34 | +class ContinuousBatchingScheduler(OperatorScheduler): |
| 35 | + """ |
| 36 | + Manages EngineOperator jobs that should be run with continuous batching. |
| 37 | + Groups requests for the same engine into larger batches and returns |
| 38 | + the result to the respective request threads after scheduled completion |
| 39 | +
|
| 40 | + Example code for getting or creating a shared instance for scheduling |
| 41 | + between pipelines and adding an engine operator to the scheduler |
| 42 | + within a pipeline |
| 43 | +
|
| 44 | + ```python |
| 45 | +
|
| 46 | + class MyPipeline(Pipeline): |
| 47 | +
|
| 48 | + def __init__(self): |
| 49 | + ... |
| 50 | + engine_operator = EngineOperator(...) |
| 51 | + ... |
| 52 | + continuous_batching_scheduler = ContinuousBatchingScheduler.get_instance() |
| 53 | + continuous_batching_scheduler.add_engine_operator(engine_operator) |
| 54 | +
|
| 55 | + super.__init__(...) |
| 56 | + ``` |
| 57 | +
|
| 58 | + :param max_workers: maximum number of threads to execute at once, default 1 |
| 59 | + """ |
| 60 | + |
| 61 | + def __init__(self, max_workers: int = 1): |
| 62 | + self._max_workers = max_workers |
| 63 | + |
| 64 | + self._mutex = Lock() |
| 65 | + |
| 66 | + # Dict[EngineOperator, Dict[batch_size, Engine]] |
| 67 | + self._operators_to_engines = {} # EngineOperator -> Dict[batch_size, Engine] |
| 68 | + self._queues = ContinuousBatchingQueues() |
| 69 | + |
| 70 | + # create and start max number of worker threads |
| 71 | + self._threads = [ |
| 72 | + ContinuousBatchingExecutorThread(self._queues, self._operators_to_engines) |
| 73 | + for _ in range(self.max_workers) |
| 74 | + ] |
| 75 | + for worker_thread in self._threads: |
| 76 | + worker_thread.start() |
| 77 | + |
| 78 | + @classmethod |
| 79 | + def get_instance(cls) -> "ContinuousBatchingScheduler": |
| 80 | + """ |
| 81 | + :return: global instance of the continuous batching scheduler. If one |
| 82 | + does not exist yet, a scheduler with a single worker thread to |
| 83 | + schedule all jobs is created and started |
| 84 | + """ |
| 85 | + if _GLOBAL_SCHEDULER is not None: |
| 86 | + return _GLOBAL_SCHEDULER # noqa: F823 |
| 87 | + |
| 88 | + _GLOBAL_SCHEDULER = cls(max_workers=1) |
| 89 | + return _GLOBAL_SCHEDULER |
| 90 | + |
| 91 | + @property |
| 92 | + def max_workers(self) -> int: |
| 93 | + """ |
| 94 | + :return: maximum number of threads to execute at once |
| 95 | + """ |
| 96 | + return self._max_workers |
| 97 | + |
| 98 | + def submit(self, *args, operator: Operator, **kwargs) -> Future: |
| 99 | + """ |
| 100 | + :param operator: operator to run |
| 101 | + :param operator_input: input schema to the operator |
| 102 | + :return: future referencing the asynchronously run output of the operator |
| 103 | + """ |
| 104 | + inputs = args[0] |
| 105 | + if not isinstance(inputs, operator.input_schema): |
| 106 | + raise ValueError( |
| 107 | + "Inputs to ContinuousBatchingScheduler must be the specific " |
| 108 | + f"input schema to the given operator. Expected {operator.input_schema}" |
| 109 | + f"found {type(inputs)}" |
| 110 | + ) |
| 111 | + |
| 112 | + future = Future() |
| 113 | + self._queues.add_queue_item(key=operator, item=inputs, future=future) |
| 114 | + |
| 115 | + return future |
| 116 | + |
| 117 | + def can_process(self, *args, operator: Operator, **kwargs) -> bool: |
| 118 | + """ |
| 119 | + :param operator: operator to check |
| 120 | + :param operator_input: operator_input to check |
| 121 | + :return: True if this Operator can process the given operator and input. |
| 122 | + SchedulerGroup always returns True |
| 123 | + """ |
| 124 | + return operator in self._operators_to_engines and operator in self._queues |
| 125 | + |
| 126 | + def add_engine_operator( |
| 127 | + self, engine_operator: EngineOperator, batch_sizes: List[int] |
| 128 | + ): |
| 129 | + """ |
| 130 | + Adds tracking for an engine operator to this scheduler |
| 131 | + with continuous batching for the given sizes |
| 132 | +
|
| 133 | + :param engine_operator: an EngineOperator, must be compiled with |
| 134 | + batch_size=1 |
| 135 | + :param batch_sizes: batch sizes to use for continuous batching |
| 136 | + """ |
| 137 | + # lock updates to _operators_to_engines while updating |
| 138 | + self._mutex.acquire() |
| 139 | + |
| 140 | + # validation |
| 141 | + if engine_operator in self._operators_to_engines: |
| 142 | + # operator already added |
| 143 | + return |
| 144 | + |
| 145 | + if not isinstance(engine_operator, EngineOperator): |
| 146 | + raise ValueError( |
| 147 | + f"Expected an EngineOperator instance, found {type(engine_operator)}" |
| 148 | + ) |
| 149 | + if engine_operator.batch_size != 1: |
| 150 | + raise ValueError( |
| 151 | + "For continuous batching, EngineOperator must have batch_size=1. " |
| 152 | + f"found batch_size={engine_operator.batch_size}" |
| 153 | + ) |
| 154 | + |
| 155 | + # build EngineOperator -> List[batch_size] dict |
| 156 | + operator_engines = {} |
| 157 | + # base engine, expected batch size is 1 |
| 158 | + operator_engines[engine_operator.batch_size] = engine_operator.engine |
| 159 | + |
| 160 | + # compile auxillary engines for continuous batching |
| 161 | + for batch_size in batch_sizes: |
| 162 | + if batch_size == 1: |
| 163 | + continue # already added |
| 164 | + operator_engines[batch_size] = operator_engines.create_engine( |
| 165 | + batch_size=batch_size |
| 166 | + ) |
| 167 | + |
| 168 | + self._operators_to_engines[engine_operator] = operator_engines |
| 169 | + self._queues.add_queue( |
| 170 | + key=engine_operator, |
| 171 | + batch_sizes=list(operator_engines.keys()), |
| 172 | + ) |
| 173 | + |
| 174 | + # release lock |
| 175 | + self._mutex.release() |
0 commit comments