deepijatel's picture
Add gpt-oss-20b chat support to consolidate onto one endpoint
4fc3618 verified
Raw History Blame Contribute Delete
7.13 kB
import base64
import logging
import os
import queue
import threading
import types
import torch
from huggingface_hub import HfApi
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
from diarization_utils import diarize
logger = logging.getLogger(__name__)
ASR_MODEL = os.environ.get("ASR_MODEL", "openai/whisper-large-v3")
NUM_INSTANCES = int(os.environ.get("NUM_INSTANCES", "5"))
DIARIZATION_MODEL = os.environ.get("DIARIZATION_MODEL") # unset = diarization disabled
NUM_DIARIZATION_INSTANCES = int(os.environ.get("NUM_DIARIZATION_INSTANCES", "1"))
LLM_MODEL = os.environ.get("LLM_MODEL") # unset = LLM chat disabled
HF_TOKEN = os.environ.get("HF_TOKEN")
# gpt-oss's harmony response format tags the assistant's chain-of-thought and
# final answer as separate channels within one generation — only the "final"
# channel is the actual response callers expect back as `content`; the rest
# is internal reasoning that would otherwise corrupt JSON-parsing callers.
_FINAL_CHANNEL_MARKER = "<|channel|>final<|message|>"
_TURN_END_MARKERS = ("<|return|>", "<|end|>")
def _extract_final_channel(raw_text: str) -> str:
if _FINAL_CHANNEL_MARKER in raw_text:
raw_text = raw_text.rsplit(_FINAL_CHANNEL_MARKER, 1)[1]
for marker in _TURN_END_MARKERS:
raw_text = raw_text.split(marker, 1)[0]
return raw_text.strip()
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 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)
self.diarization_pipelines = []
self.diarization_pool: queue.Queue = queue.Queue()
if DIARIZATION_MODEL:
from pyannote.audio import Pipeline as DiarizationPipeline
# Raises if the token can't access the (gated) diarization model.
HfApi().whoami(HF_TOKEN)
logger.info(f"Loading {NUM_DIARIZATION_INSTANCES} copies of diarization model {DIARIZATION_MODEL}")
for i in range(NUM_DIARIZATION_INSTANCES):
dp = DiarizationPipeline.from_pretrained(checkpoint_path=DIARIZATION_MODEL, use_auth_token=HF_TOKEN)
dp.to(device)
self.diarization_pipelines.append(dp)
self.diarization_pool.put(i)
self.llm_model = None
self.llm_tokenizer = None
if LLM_MODEL:
logger.info(f"Loading LLM {LLM_MODEL} on {device}")
self.llm_tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL)
self.llm_model = AutoModelForCausalLM.from_pretrained(LLM_MODEL, torch_dtype="auto", device_map="auto")
self.llm_model.eval()
# Only one copy of a 20B model fits in memory alongside ASR/diarization,
# so concurrent chat requests are serialized rather than pooled.
self.llm_lock = threading.Lock()
def __call__(self, data: dict) -> dict:
if "messages" in data:
return self._generate_chat(data)
return self._transcribe(data)
def _generate_chat(self, data: dict) -> dict:
if self.llm_model is None:
return {"error": "LLM_MODEL is not configured on this endpoint"}
messages = data["messages"]
parameters = dict(data.get("parameters", None) or {})
max_new_tokens = int(parameters.get("max_tokens") or 1024)
temperature = parameters.get("temperature")
temperature = 0.7 if temperature is None else float(temperature)
prompt = self.llm_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = self.llm_tokenizer(prompt, return_tensors="pt").to(self.llm_model.device)
with self.llm_lock:
with torch.no_grad():
output_ids = self.llm_model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=temperature > 0,
temperature=max(temperature, 1e-5),
)
generated_ids = output_ids[0][inputs["input_ids"].shape[1]:]
raw_text = self.llm_tokenizer.decode(generated_ids, skip_special_tokens=False)
content = _extract_final_channel(raw_text)
# Shaped like an OpenAI chat-completion response so existing callers
# (response.json()["choices"][0]["message"]["content"]) need no changes
# beyond pointing at this endpoint's root URL instead of /v1/chat/completions.
return {"choices": [{"message": {"role": "assistant", "content": content}}]}
def _transcribe(self, data: dict) -> dict:
inputs = data.pop("inputs")
raw_bytes = base64.b64decode(inputs) if isinstance(inputs, str) else inputs
parameters = dict(data.pop("parameters", None) or {})
want_diarization = parameters.pop("diarize", False)
num_speakers = parameters.pop("num_speakers", None)
min_speakers = parameters.pop("min_speakers", None)
max_speakers = parameters.pop("max_speakers", None)
sampling_rate = parameters.pop("sampling_rate", 16000)
# Diarization's speaker/transcript alignment needs chunk timestamps to merge
# against, even if the caller didn't explicitly ask for them.
if want_diarization and "return_timestamps" not in parameters:
parameters["return_timestamps"] = True
index = self.pool.get() # blocks here if all instances are busy
try:
asr_outputs = self.pipelines[index](raw_bytes, **parameters)
finally:
self.pool.put(index)
if not want_diarization:
return asr_outputs
if not self.diarization_pipelines:
return {**asr_outputs, "speakers": [], "error": "DIARIZATION_MODEL is not configured on this endpoint"}
diar_params = types.SimpleNamespace(
sampling_rate=sampling_rate,
num_speakers=num_speakers,
min_speakers=min_speakers,
max_speakers=max_speakers,
)
chunks = asr_outputs.get("chunks") or [{"timestamp": [0, None], "text": asr_outputs.get("text", "")}]
diar_index = self.diarization_pool.get() # blocks here if all diarization instances are busy
try:
speakers = diarize(self.diarization_pipelines[diar_index], raw_bytes, diar_params, {"chunks": chunks})
finally:
self.diarization_pool.put(diar_index)
return {**asr_outputs, "speakers": speakers}