Add gpt-oss-20b chat support to consolidate onto one endpoint
Browse filesFiles changed (2)
- handler.py+65-1
- requirements.txt+7-5
1 unmodified line234567899101112133 unmodified lines17181920212223242526272829303132333435363738394027 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211 unmodified lineimport loggingimport osimport queueimport threadingimport types
import torchfrom huggingface_hub import HfApifrom transformers import pipelinefrom transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
from diarization_utils import diarize
3 unmodified linesNUM_INSTANCES = int(os.environ.get("NUM_INSTANCES", "5"))DIARIZATION_MODEL = os.environ.get("DIARIZATION_MODEL") # unset = diarization disabledNUM_DIARIZATION_INSTANCES = int(os.environ.get("NUM_DIARIZATION_INSTANCES", "1"))LLM_MODEL = os.environ.get("LLM_MODEL") # unset = LLM chat disabledHF_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 = ""):27 unmodified lines 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 {})12345123456789accelerate==1.0.1torch==2.4.0torchvision==0.19.0torchaudio==2.4.0transformers==4.44.2accelerate>=1.2.0torch>=2.4.0,<2.7.0torchvision>=0.19.0,<0.22.0torchaudio>=2.4.0,<2.7.0transformers>=4.56.0,<5.0.0numpy==1.26.4pyannote-audio==3.1.1kernels>=0.4.0triton>=3.2.0handler.py+65-1
requirements.txt+7-5