Custom handler loading N Whisper-large-v3 copies on one GPU with a request pool for real concurrency
Browse filesFiles changed (2)
- handler.pyAdded+43
- requirements.txtAdded+6
12345678910111213141516171819202122232425262728293031323334353637383940414243import base64import loggingimport osimport queue
import torchfrom transformers import pipeline
logger = logging.getLogger(__name__)
ASR_MODEL = os.environ.get("ASR_MODEL", "openai/whisper-large-v3")NUM_INSTANCES = int(os.environ.get("NUM_INSTANCES", "3"))
class EndpointHandler: def __init__(self, path: str = ""): device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") torch_dtype = torch.float16 if device.type == "cuda" else torch.float32 logger.info(f"Loading {NUM_INSTANCES} copies of {ASR_MODEL} on {device}")
self.pipelines = [ pipeline("automatic-speech-recognition", model=ASR_MODEL, torch_dtype=torch_dtype, device=device) for _ in range(NUM_INSTANCES) ]
# Each pipeline instance has internal state (KV cache buffers etc.) that isn't # safe to share across concurrent calls, so requests check an instance out of # this pool and return it when done rather than all hitting self.pipelines[0]. self.pool: queue.Queue = queue.Queue() for i in range(NUM_INSTANCES): self.pool.put(i)
def __call__(self, data: dict) -> dict: inputs = data.pop("inputs") if isinstance(inputs, str): inputs = base64.b64decode(inputs) parameters = data.pop("parameters", None) or {}
index = self.pool.get() # blocks here if all instances are busy try: return self.pipelines[index](inputs, **parameters) finally: self.pool.put(index)123456accelerate==1.0.1torch==2.4.0torchvision==0.19.0torchaudio==2.4.0transformers==4.44.2numpy==1.26.4handler.pyAdded+43
requirements.txtAdded+6