Upload server_runtime.py
Browse files98 unmodified lines9910010110210310410516 unmodified lines122123124125126127128129 unmodified lines25825926026126226326426526693 unmodified lines36036136236336436536636736836937037198 unmodified linesdef _format_sse_event(payload: Dict[str, Any]) -> str:return f"data: {json.dumps(payload)}\n\n"def _detect_concurrency(device: str) -> int:16 unmodified linesreturn 3cpu_count = os.cpu_count() or 1return max(1, min(4, max(1, cpu_count // 2)))def create_hf_space_app(config: RuntimeConfig) -> FastAPI:129 unmodified linesbreaktry:new_text = await asyncio.to_thread(next, stream_iter)except StopIteration:breakexcept QueueEmpty:if generation_done.is_set():break93 unmodified linesif config.tokenizer_use_fast is not None:tokenizer_kwargs["use_fast"] = config.tokenizer_use_fasttokenizer = AutoTokenizer.from_pretrained(config.model_name, **tokenizer_kwargs)model = AutoModelForCausalLM.from_pretrained(config.model_name,trust_remote_code=True,torch_dtype="auto" if device == "cuda" else torch.float32,device_map="auto" if device == "cuda" else None,)if device != "cuda":model = model.to("cpu")98 unmodified lines9910010110210310410510610710810911011111211311416 unmodified lines131132133134135136137138129 unmodified lines26826927027127227327427527693 unmodified lines37037137237337437537637737837938038138238338438538638738838939039139239339439539639798 unmodified linesdef _format_sse_event(payload: Dict[str, Any]) -> str:event_type = str(payload.get("type", "token"))return f"event: {event_type}\ndata: {json.dumps(payload)}\n\n"def _read_stream_item(stream_iter) -> tuple[bool, Optional[str]]:"""Read one item from streamer iterator without leaking StopIteration across threads."""try:return False, next(stream_iter)except StopIteration:return True, Nonedef _detect_concurrency(device: str) -> int:16 unmodified linesreturn 3cpu_count = os.cpu_count() or 1# Conservative CPU default for large models; still within 1..4 range.return max(1, min(4, max(1, cpu_count // 6)))def create_hf_space_app(config: RuntimeConfig) -> FastAPI:129 unmodified linesbreaktry:stream_finished, new_text = await asyncio.to_thread(_read_stream_item, stream_iter)if stream_finished:breakexcept QueueEmpty:if generation_done.is_set():break93 unmodified linesif config.tokenizer_use_fast is not None:tokenizer_kwargs["use_fast"] = config.tokenizer_use_fasttokenizer = AutoTokenizer.from_pretrained(config.model_name, **tokenizer_kwargs)model_load_kwargs: Dict[str, Any] = {"trust_remote_code": True,"device_map": "auto" if device == "cuda" else None,}if device == "cuda":model_load_kwargs["dtype"] = "auto"else:model_load_kwargs["torch_dtype"] = torch.float32try:model = AutoModelForCausalLM.from_pretrained(config.model_name,**model_load_kwargs,)except TypeError:# Backward compatibility for older transformers that do not accept `dtype`.if "dtype" in model_load_kwargs:model_load_kwargs["torch_dtype"] = model_load_kwargs.pop("dtype")model = AutoModelForCausalLM.from_pretrained(config.model_name,**model_load_kwargs,)if device != "cuda":model = model.to("cpu")
server_runtime.py+37-11