Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files123420 unmodified lines25262728293031323334353637383940414243444546471 unmodified line495051525354555657585960616214 unmodified lines77787980818215 unmodified lines98991001011021035 unmodified lines109110111112113114115116117113 unmodified lines23123223323423523658 unmodified lines29529629729829930030130230330430530630730830959 unmodified lines36937037137237337437537637733 unmodified lines4114124134144154163 unmodified lines4204214224234244256 unmodified lines4324334344354364375 unmodified lines4434444454464474484494504514524534544554564574584594604614624634644654662 unmodified lines4694704714724734744755 unmodified lines48148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854914 unmodified lines5645655665675685696 unmodified lines57657757857958058113 unmodified lines59559659759859960050 unmodified lines6516526536546556566574 unmodified lines66266366466566666766898 unmodified lines76776876977077177277313 unmodified lines7877887897907917927936 unmodified lines8008018028038048054 unmodified lines810811812813814815816817818819820174 unmodified lines995996997998999100010 unmodified lines1011101210131014101510165 unmodified lines102210231024102510261027102827 unmodified lines10561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107923 unmodified lines11031104110511061107110811091110111111127 unmodified lines1120112111221123112411251126112711281129113011311132113323 unmodified lines11571158115911601161116232 unmodified lines11951196119711981199120012011 unmodified line120312041205120612071208120919 unmodified lines1229123012311232123312341235123612371238123912401241124212432 unmodified lines1246124712481249125012511252125312546 unmodified lines1261126212631264126512667 unmodified lines12741275127612771278127944 unmodified lines13241325132613271328132913301331133213331334133510 unmodified lines134613471348134913501351135213531354135513566 unmodified lines13631364136513661367136877 unmodified lines1446144714481449145014511452# scikit-plots/ai-model Β· app.py v2.0.0## PURPOSE# βββββββ20 unmodified lines# + Long-term maintainability# + Minimal hidden behavior## CRITICAL: ZEROGPU ARCHITECTURE REQUIREMENT# ββββββββββββββββββββββββββββββββββββββββββ# On HuggingFace Spaces with sdk: gradio, ZeroGPU hooks attach to the# Gradio server lifecycle. Gradio MUST be the ASGI root application.## CORRECT (v2.0.0):# Gradio (gr.Blocks) is the ASGI root.# REST routes are registered on Gradio's internal FastAPI instance# via gradio.routes.App.create_app(demo).# @spaces.GPU is active on _generate.## WRONG (v1.x.x):# FastAPI was the ASGI root; Gradio was a child via gr.mount_gradio_app.# @spaces.GPU was commented out.# ZeroGPU hooks never activated.## CRITICAL: ZERO-GPU MODEL PATTERN# ββββββββββββββββββββββββββββββββ# CORRECT:# * Tokenizer loaded on CPU at import time.1 unmodified line# * Model moved to GPU ONLY inside @spaces.GPU scope.# * Model returned to CPU in finally block after inference.# * torch.cuda.empty_cache() called after every request.## WRONG:# * pipeline(... device_map="auto") at module level.# * model.to("cuda") outside @spaces.GPU scope.# * Holding GPU between requests.# * Blocking asyncio event loop with synchronous inference.## ASSEMBLY DIAGRAM (v2.0.0)# βββββββββββββββββββββββββ## HuggingFace Spaces14 unmodified lines# MAX_BODY_BYTES# Maximum accepted request size.## SPDX-License-Identifier: BSD-3-Clause# Authors: The scikit-plots developers15 unmodified linesHuggingFace Spaces exports the ``app`` variable. It must be theGradio-rooted ASGI application returned by ``App.create_app``.User noteThe Gradio UI at ``/`` is for manual testing only.Production traffic routes through the proxy Space.5 unmodified linesimport jsonimport loggingimport osimport timeimport uuidfrom typing import Finalimport gradio as gr # type: ignore[]import spaces # type: ignore[] # ZeroGPU β must be imported before torch113 unmodified lines_MAX_NEW_TOKENS_CEIL: Final[int] = 4096_MAX_NEW_TOKENS_DEFAULT: Final[int] = 512DEFAULT_MAX_BODY_BYTES: Final[int] = 10 * 1024 * 1024MAX_BODY_BYTES: Final[int] = _safe_int(58 unmodified linesparsed = int(value)except (TypeError, ValueError) as exc:raise ValueError(f"max_tokens must be integer, got {value!r}") from excreturn max(_MAX_NEW_TOKENS_FLOOR,min(parsed,_MAX_NEW_TOKENS_CEIL,),)59 unmodified linesreturn validatedlogger.info("Validation helpers initialized successfully.")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Model loading# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ33 unmodified lines# * GPU exists only inside @spaces.GPU scope.# * Model moved CPU β GPU at entry; GPU β CPU in finally.# * VRAM fully released after every request.# * This function is called from both:# - Gradio event handlers (direct sync call via _gradio_respond)# - FastAPI route handlers (via asyncio.to_thread in _generate_async)3 unmodified linesdef _generate(messages: list[dict[str, str]],max_new_tokens: int = _MAX_NEW_TOKENS_DEFAULT,) -> str:"""Run generation using ZeroGPU.6 unmodified linesmax_new_tokens : int, default=512Maximum generated tokens.Returns-------str5 unmodified linesOn invalid inputs or missing chat template.RuntimeErrorOn inference failure.Notes-----Developer noteGPU is acquired automatically by ``@spaces.GPU``.Model is explicitly moved CPU β GPU β CPU during each requestto avoid persistent VRAM ownership between requests.``finally`` block ensures CPU return and cache clear even ifinference raises. The inner ``try`` around ``_model.cpu()``guarantees ``torch.cuda.empty_cache()`` runs regardless ofwhether the CPU move itself fails.This function is intentionally synchronous. Async routes callit via ``_generate_async`` which wraps it with``asyncio.to_thread``. Gradio event handlers call it directlybecause Gradio dispatches handlers in its own thread pool,outside the asyncio event loop.2 unmodified linesUse ``_generate_async`` from FastAPI routes."""validated_messages = _validate_messages(messages)max_new_tokens = _clamp_max_tokens(max_new_tokens)if not getattr(_tokenizer, "chat_template", None):5 unmodified lineslogger.info("GPU generation starting | ""messages=%d | ""max_new_tokens=%d",len(validated_messages),max_new_tokens,)try:logger.info("Moving model to GPU...")_model.cuda()input_ids = _tokenizer.apply_chat_template(validated_messages,add_generation_prompt=True,return_tensors="pt",)input_ids = input_ids.cuda()logger.info("Generation started.")with torch.no_grad():output_ids = _model.generate(input_ids,max_new_tokens=max_new_tokens,do_sample=True,temperature=0.7,pad_token_id=_tokenizer.eos_token_id,)new_token_ids = output_ids[0][input_ids.shape[-1]:]decoded = _tokenizer.decode(new_token_ids,skip_special_tokens=True,)logger.info("Generation completed successfully.")return decodedexcept ValueError:raiseexcept Exception as exc:logger.exception("Inference failure.")raise RuntimeError(f"Inference failed: {exc}") from excfinally:logger.info("Returning model to CPU ""and clearing CUDA cache...")try:_model.cpu()finally:if torch.cuda.is_available():torch.cuda.empty_cache()logger.info("GPU resources released.")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ14 unmodified linesasync def _generate_async(messages: list[dict[str, str]],max_new_tokens: int,) -> str:"""Async wrapper for GPU generation.6 unmodified linesmax_new_tokens : intGeneration token limit.Returns-------str13 unmodified lines_generate,messages,max_new_tokens,)50 unmodified linesdef _parse_request_body(raw: bytes,) -> dict:"""Decode and parse a UTF-8 JSON request body.4 unmodified linesReturns-------dictParsed JSON payload.Raises98 unmodified linesmodel_id: str,prompt_tokens: int,completion_tokens: int,) -> dict:"""Build an OpenAI-compatible chat completion response payload.13 unmodified linesReturns-------dictOpenAI-compatible ``chat.completion`` object.Notes6 unmodified linescurrent ``_generate`` implementation does not expose partialstop conditions. Extend this if streaming or early stoppingis added.User noteThe returned dict is compatible with OpenAI Python SDK4 unmodified lines.. [1] OpenAI API reference: Chat completions objecthttps://platform.openai.com/docs/api-reference/chat/object"""return {"id": f"chatcmpl-{uuid.uuid4().hex}","object": "chat.completion","created": int(time.time()),"model": model_id,"choices": [{"index": 0,174 unmodified linesmessage: str,history: list,max_new_tokens: int,) -> str:"""Gradio ``ChatInterface`` event handler.10 unmodified linesmax_new_tokens : intMaximum tokens to generate, sourced from the UI slider.Returns-------str5 unmodified linesIf ``message`` is empty after stripping.RuntimeErrorPropagated from ``_generate`` on inference failure.Notes-----27 unmodified lineslogger.info("Gradio inference | ""history_turns=%d | ""max_new_tokens=%d",len(messages) - 1,max_new_tokens,)return _generate(messages,max_new_tokens,)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Gradio UI# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# v2.0.0: Gradio is the ASGI ROOT β not a child sub-app mounted on FastAPI.# This is required for ZeroGPU to activate on HuggingFace Spaces.## The Gradio UI is now served at / (root) instead of /ui.# Custom REST routes are added to Gradio's internal FastAPI instance below._UI_WARNING = """\23 unmodified linesstep=1,label="max_tokens",info=(f"Range: {_MAX_NEW_TOKENS_FLOOR}-{_MAX_NEW_TOKENS_CEIL}. "f"Default: {_MAX_NEW_TOKENS_DEFAULT}."),),],additional_inputs_accordion="Generation settings",)7 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# App assembly β HuggingFace Space export# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# v2.0.0 ARCHITECTURE CHANGE:## v1.x.x (BROKEN):# _api = FastAPI() β FastAPI was ASGI root# app = gr.mount_gradio_app(_api, ui, "/ui") β Gradio was child# ZeroGPU never activated β wrong root.## v2.0.0 (CORRECT):# app = _GradioApp.create_app(_gradio_ui) β Gradio is ASGI root# @app.get/post(...) β routes on Gradio's FastAPI# ZeroGPU activates correctly.23 unmodified linesallow_headers=["Content-Type",],)logger.info(32 unmodified linesExamples-------->>> # curl http://localhost:7860/health... # {"status": "ok", "model": "...", "version": "2.0.0"}"""logger.info("GET /health")1 unmodified linecontent={"status": "ok","model": MODEL_ID,"version": "2.0.0",},status_code=200,)19 unmodified linesReturns-------JSONResponseHTTP 200 with an OpenAI-compatible completion payload.Raises------JSONResponseHTTP 413 if the body exceeds ``MAX_BODY_BYTES``.HTTP 400 if the body is not valid UTF-8 JSON.HTTP 400 if ``messages`` or ``max_tokens`` fail validation.HTTP 500 on inference failure.Notes-----2 unmodified lines1. Read and bound-check raw body bytes (413 guard).2. Decode and parse JSON (400 guard).3. Extract ``messages`` and ``max_tokens`` fields.4. Validate with ``_validate_messages`` and``_clamp_max_tokens`` (400 guard).5. Count prompt tokens on CPU (no GPU needed).6. Dispatch to ``_generate_async`` which offloads to``@spaces.GPU`` via ``asyncio.to_thread``.6 unmodified lines* ``RuntimeError`` β 500 (wrapped inference failure from ``_generate``)* ``Exception`` β 500 (unexpected catch-all, never leaks internals)User noteCompatible with the OpenAI Python SDK:7 unmodified linesresponse = client.chat.completions.create(model="any",messages=[{"role": "user", "content": "Hello"}],)"""request_id = uuid.uuid4().hex44 unmodified lines"max_tokens",_MAX_NEW_TOKENS_DEFAULT,)# ββ 4. Input validation βββββββββββββββββββββββββββββββββββββββββββββββββββtry:messages = _validate_messages(messages_raw)max_new_tokens = _clamp_max_tokens(max_tokens_raw)except ValueError as exc:logger.warning("Validation error | request_id=%s | error=%s",10 unmodified lineslogger.info("Dispatching inference | ""request_id=%s | ""messages=%d | ""max_new_tokens=%d",request_id,len(messages),max_new_tokens,)# ββ 5. Prompt token count (CPU, pre-dispatch) ββββββββββββββββββββββββββββοΏ½οΏ½οΏ½6 unmodified linescontent = await _generate_async(messages,max_new_tokens,)except ValueError as exc:77 unmodified lineslogger.info("scikit-plots ai-model Space initialized successfully.\n"" version : 2.0.0\n"" model : %s\n"" CORS : %s\n"" max_body : %s bytes\n"123420 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061621 unmodified line6465666768697071727374757677787914 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114215 unmodified lines1581591601611621631641651661675 unmodified lines173174175176177178179180181182113 unmodified lines29629729829930030130230330430558 unmodified lines36436536636736836937037137237337437559 unmodified lines43543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255333 unmodified lines5875885895905915925935943 unmodified lines5985996006016026036046056 unmodified lines6126136146156166176186196206216226236246255 unmodified lines6316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656662 unmodified lines6696706716726736745 unmodified lines68068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777814 unmodified lines7937947957967977987998006 unmodified lines80780880981081181281381481581681781813 unmodified lines83283383483583683783883950 unmodified lines8908918928938948958964 unmodified lines90190290390490590690798 unmodified lines100610071008100910101011101213 unmodified lines10261027102810291030103110326 unmodified lines1039104010411042104310441045104610474 unmodified lines105210531054105510561057105810591060106110621063106410651066106710681069107010711072174 unmodified lines1247124812491250125112521253125410 unmodified lines1265126612671268126912701271127212731274127512765 unmodified lines1282128312841285128612871288128927 unmodified lines13171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134623 unmodified lines137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413957 unmodified lines1403140414051406140714081409141023 unmodified lines143414351436143714381439144032 unmodified lines14731474147514761477147814791 unmodified line148114821483148414851486148719 unmodified lines1507150815091510151115121513151415151516151715181519152015212 unmodified lines1524152515261527152815291530153115326 unmodified lines15391540154115421543154415451546154715487 unmodified lines1556155715581559156015611562156344 unmodified lines160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163210 unmodified lines164316441645164616471648164916501651165216531654165516561657165816596 unmodified lines1666166716681669167016711672167377 unmodified lines1751175217531754175517561757# scikit-plots/ai-model Β· app.py v2.1.0## PURPOSE# βββββββ20 unmodified lines# + Long-term maintainability# + Minimal hidden behavior## CRITICAL: SINGLE-WORKER REQUIREMENT# ββββββββββββββββββββββββββββββββββββ# This Space MUST run with a single uvicorn worker.# The model (7B params, bfloat16) consumes ~14 GB of RAM on CPU.# The ZeroGPU hard RAM limit is 16 GB.## Two workers Γ 14 GB = 28 GB β OOM β the OS kills the second process# with a clean exit code (0), which HuggingFace reports as "runtime error".## HuggingFace Spaces with sdk: gradio default to a single worker, which# is the correct configuration. If you observe two initialization sequences# in the container log, verify that no external launcher is adding workers# (e.g., GRADIO_NUM_WORKERS, uvicorn --workers) and file a HuggingFace# support ticket if the double-start persists.## CRITICAL: ZEROGPU ARCHITECTURE REQUIREMENT# ββββββββββββββββββββββββββββββββββββββββββ# On HuggingFace Spaces with sdk: gradio, ZeroGPU hooks attach to the# Gradio server lifecycle. Gradio MUST be the ASGI root application.## CORRECT (v2.x):# Gradio (gr.Blocks) is the ASGI root.# REST routes are registered on Gradio's internal FastAPI instance# via gradio.routes.App.create_app(demo).# @spaces.GPU is active on _generate.## WRONG (v1.x):# FastAPI was the ASGI root; Gradio was a child via gr.mount_gradio_app.# @spaces.GPU was commented out.# ZeroGPU hooks never activated.## CRITICAL: ZEROGPU MODEL PATTERN# ββββββββββββββββββββββββββββββββ# CORRECT:# * Tokenizer loaded on CPU at import time.1 unmodified line# * Model moved to GPU ONLY inside @spaces.GPU scope.# * Model returned to CPU in finally block after inference.# * torch.cuda.empty_cache() called after every request.# * _MODEL_LOCK serialises all model device transitions.## WRONG:# * pipeline(... device_map="auto") at module level.# * model.to("cuda") outside @spaces.GPU scope.# * Holding GPU between requests.# * Blocking asyncio event loop with synchronous inference.# * Concurrent model.cuda() / model.cpu() without a lock.## ASSEMBLY DIAGRAM (v2.1.0)# βββββββββββββββββββββββββ## HuggingFace Spaces14 unmodified lines# MAX_BODY_BYTES# Maximum accepted request size.## CHANGES v2.0.0 β v2.1.0# βββββββββββββββββββββββββ# [CRITICAL] Add _MODEL_LOCK (threading.Lock) to serialise all model# device transitions (cuda/cpu) across concurrent inference# calls. Without this, concurrent @spaces.GPU activations# can corrupt model device state.## [CRITICAL] Explicit GPU tensor cleanup (del input_ids, output_ids,# new_token_ids) in the success path before _model.cpu() and# torch.cuda.empty_cache(). Ensures VRAM is fully released# before the ZeroGPU scope exits.## [HIGH] Add `except RuntimeError: raise` to _generate exception# chain so that RuntimeErrors (including the empty-response# guard below) are not accidentally double-wrapped.## [HIGH] Guard against empty model output: raise RuntimeError if# the decoded string is empty after skip_special_tokens.## [MEDIUM] temperature and top_p are now configurable from the# request body (REST) and from sliders (Gradio UI).# Defaults: temperature=0.7, top_p=1.0.# temperature=0.0 β greedy decoding (do_sample=False).## [MEDIUM] Log the requested model field from the request body for# proxy-routing diagnostics.## [MEDIUM] Fix chat_completions docstring: JSONResponse error cases# moved from the incorrect Raises section to Notes, because# they are returned values, not raised exceptions.## [LOW] _parse_request_body and _build_completion_response now# carry precise dict[str, Any] return type annotations.## [LOW] system_fingerprint field added to completion response for# improved OpenAI SDK compatibility.## [LOW] Explicit allow_credentials=False in CORS middleware.## [DOC] Prominent single-worker warning added to module header# (see above) explaining the double-startup / exit-0 OOM# failure mode observed in the container log.## SPDX-License-Identifier: BSD-3-Clause# Authors: The scikit-plots developers15 unmodified linesHuggingFace Spaces exports the ``app`` variable. It must be theGradio-rooted ASGI application returned by ``App.create_app``.``_MODEL_LOCK`` serialises all calls to ``_model.cuda()`` and``_model.cpu()``. A single ``_model`` object must not have itsdevice changed by two threads simultaneously.User noteThe Gradio UI at ``/`` is for manual testing only.Production traffic routes through the proxy Space.5 unmodified linesimport jsonimport loggingimport osimport threadingimport timeimport uuidfrom typing import Any, Finalimport gradio as gr # type: ignore[]import spaces # type: ignore[] # ZeroGPU β must be imported before torch113 unmodified lines_MAX_NEW_TOKENS_CEIL: Final[int] = 4096_MAX_NEW_TOKENS_DEFAULT: Final[int] = 512# Generation defaults β match OpenAI API defaults where applicable._DEFAULT_TEMPERATURE: Final[float] = 0.7_DEFAULT_TOP_P: Final[float] = 1.0DEFAULT_MAX_BODY_BYTES: Final[int] = 10 * 1024 * 1024MAX_BODY_BYTES: Final[int] = _safe_int(58 unmodified linesparsed = int(value)except (TypeError, ValueError) as exc:raise ValueError(f"max_tokens must be an integer, got {value!r}") from excreturn max(_MAX_NEW_TOKENS_FLOOR,min(parsed, _MAX_NEW_TOKENS_CEIL),)59 unmodified linesreturn validateddef _validate_temperature(value: object,) -> float:"""Validate and return a generation temperature value.Parameters----------value : objectCandidate temperature.Returns-------floatValidated temperature in [0.0, 2.0].Raises------ValueErrorIf conversion fails or value is out of range.Notes-----Developer note``temperature=0.0`` selects greedy decoding (``do_sample=False``).The upper bound 2.0 matches the OpenAI API specification.References----------.. [1] OpenAI API reference: temperature parameterhttps://platform.openai.com/docs/api-reference/chat/create#temperature"""try:parsed = float(value)except (TypeError, ValueError) as exc:raise ValueError(f"temperature must be a number, got {value!r}") from excif not (0.0 <= parsed <= 2.0):raise ValueError(f"temperature must be in [0.0, 2.0], got {parsed!r}")return parseddef _validate_top_p(value: object,) -> float:"""Validate and return a nucleus-sampling top_p value.Parameters----------value : objectCandidate top_p.Returns-------floatValidated top_p in (0.0, 1.0].Raises------ValueErrorIf conversion fails or value is out of range.Notes-----Developer note``top_p=1.0`` effectively disables nucleus sampling.OpenAI recommends altering temperature or top_p but not both.References----------.. [1] OpenAI API reference: top_p parameterhttps://platform.openai.com/docs/api-reference/chat/create#top_p"""try:parsed = float(value)except (TypeError, ValueError) as exc:raise ValueError(f"top_p must be a number, got {value!r}") from excif not (0.0 < parsed <= 1.0):raise ValueError(f"top_p must be in (0.0, 1.0], got {parsed!r}")return parsedlogger.info("Validation helpers initialized successfully.")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Model lock# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Serialises all _model.cuda() / _model.cpu() transitions.## A single _model object must not be moved to different devices by two# threads simultaneously. @spaces.GPU does not prevent concurrent calls# by itself (the Gradio queue or multiple in-flight async requests can# dispatch _generate from multiple threads at the same time).## Holding _MODEL_LOCK for the duration of the entire inference (cuda β# generate β cpu) is correct and safe: we are single-model, single-GPU._MODEL_LOCK: Final[threading.Lock] = threading.Lock()# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Model loading# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ33 unmodified lines# * GPU exists only inside @spaces.GPU scope.# * Model moved CPU β GPU at entry; GPU β CPU in finally.# * VRAM fully released after every request.# * _MODEL_LOCK held for the full duration of the inference to prevent# concurrent device transitions on the shared _model object.# * This function is called from both:# - Gradio event handlers (direct sync call via _gradio_respond)# - FastAPI route handlers (via asyncio.to_thread in _generate_async)3 unmodified linesdef _generate(messages: list[dict[str, str]],max_new_tokens: int = _MAX_NEW_TOKENS_DEFAULT,temperature: float = _DEFAULT_TEMPERATURE,top_p: float = _DEFAULT_TOP_P,) -> str:"""Run generation using ZeroGPU.6 unmodified linesmax_new_tokens : int, default=512Maximum generated tokens.temperature : float, default=0.7Sampling temperature in [0.0, 2.0].``0.0`` selects greedy decoding (do_sample=False).top_p : float, default=1.0Nucleus sampling cutoff in (0.0, 1.0].``1.0`` disables nucleus sampling.Returns-------str5 unmodified linesOn invalid inputs or missing chat template.RuntimeErrorOn inference failure or empty model output.Notes-----Developer noteGPU is acquired automatically by ``@spaces.GPU``.``_MODEL_LOCK`` is held for the entire inference duration(cuda β generate β cpu) to prevent concurrent threads fromissuing conflicting device transitions on the shared ``_model``object. ZeroGPU + Gradio queue can dispatch this function frommultiple threads simultaneously; the lock serialises them.GPU tensors (``input_ids``, ``output_ids``, ``new_token_ids``)are explicitly deleted in the success path before ``_model.cpu()``and ``torch.cuda.empty_cache()``. This ensures VRAM is fullyreclaimed before the ``@spaces.GPU`` scope exits. On theexception path, any tensors that were assigned before the errorremain alive until the function exits (acceptable: ZeroGPUreleases all GPU memory at ``@spaces.GPU`` scope exit).``finally`` block ensures CPU return and cache clear even ifinference raises. The inner ``try/except`` around ``_model.cpu()``logs and absorbs a potential CPU-move failure so that theoriginal inference exception is not masked; it still calls``torch.cuda.empty_cache()`` via its own nested ``finally``.This function is intentionally synchronous. Async routes callit via ``_generate_async`` which wraps it with``asyncio.to_thread``. Gradio event handlers call it directlybecause Gradio dispatches handlers in its own thread pool,outside the asyncio event loop.2 unmodified linesUse ``_generate_async`` from FastAPI routes."""validated_messages = _validate_messages(messages)max_new_tokens = _clamp_max_tokens(max_new_tokens)if not getattr(_tokenizer, "chat_template", None):5 unmodified lineslogger.info("GPU generation starting | ""messages=%d | ""max_new_tokens=%d | ""temperature=%.2f | ""top_p=%.2f",len(validated_messages),max_new_tokens,temperature,top_p,)with _MODEL_LOCK:try:logger.info("Moving model to GPU...")_model.cuda()input_ids = _tokenizer.apply_chat_template(validated_messages,add_generation_prompt=True,return_tensors="pt",)input_ids = input_ids.cuda()logger.info("Generation started.")# Build generation kwargs.# temperature=0.0 β greedy (do_sample=False, no temperature/top_p).# temperature>0.0 β sampling; top_p applied only when < 1.0.generate_kwargs: dict[str, Any] = {"max_new_tokens": max_new_tokens,"pad_token_id": _tokenizer.eos_token_id,}if temperature > 0.0:generate_kwargs["do_sample"] = Truegenerate_kwargs["temperature"] = temperatureif top_p < 1.0:generate_kwargs["top_p"] = top_pwith torch.no_grad():output_ids = _model.generate(input_ids,**generate_kwargs,)new_token_ids = output_ids[0][input_ids.shape[-1]:]decoded = _tokenizer.decode(new_token_ids,skip_special_tokens=True,)# Release GPU tensors before CPU move and cache clear.# new_token_ids is a view of output_ids; deleting both here# drops all references, freeing the underlying CUDA storage.del input_ids, output_ids, new_token_idsif not decoded.strip():raise RuntimeError("Model returned an empty response. ""Retry or reduce prompt length.")logger.info("Generation completed successfully.")return decodedexcept ValueError:raiseexcept RuntimeError:raiseexcept Exception as exc:logger.exception("Inference failure.")raise RuntimeError(f"Inference failed: {exc}") from excfinally:logger.info("Returning model to CPU ""and clearing CUDA cache...")try:_model.cpu()except Exception: # noqa: BLE001logger.exception("Failed to move model back to CPU. ""VRAM may not be fully released.")finally:if torch.cuda.is_available():torch.cuda.empty_cache()logger.info("GPU resources released.")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ14 unmodified linesasync def _generate_async(messages: list[dict[str, str]],max_new_tokens: int,temperature: float = _DEFAULT_TEMPERATURE,top_p: float = _DEFAULT_TOP_P,) -> str:"""Async wrapper for GPU generation.6 unmodified linesmax_new_tokens : intGeneration token limit.temperature : float, default=0.7Sampling temperature forwarded to ``_generate``.top_p : float, default=1.0Nucleus sampling cutoff forwarded to ``_generate``.Returns-------str13 unmodified lines_generate,messages,max_new_tokens,temperature,top_p,)50 unmodified linesdef _parse_request_body(raw: bytes,) -> dict[str, Any]:"""Decode and parse a UTF-8 JSON request body.4 unmodified linesReturns-------dict[str, Any]Parsed JSON payload.Raises98 unmodified linesmodel_id: str,prompt_tokens: int,completion_tokens: int,) -> dict[str, Any]:"""Build an OpenAI-compatible chat completion response payload.13 unmodified linesReturns-------dict[str, Any]OpenAI-compatible ``chat.completion`` object.Notes6 unmodified linescurrent ``_generate`` implementation does not expose partialstop conditions. Extend this if streaming or early stoppingis added.``system_fingerprint`` is derived from the model ID slug tosatisfy OpenAI SDK response parsing without exposing internalinfrastructure details.User noteThe returned dict is compatible with OpenAI Python SDK4 unmodified lines.. [1] OpenAI API reference: Chat completions objecthttps://platform.openai.com/docs/api-reference/chat/object"""# Derive a deterministic, URL-safe fingerprint from the model ID._model_slug = (model_id.lower().replace("/", "-").replace(".", "-").replace("_", "-"))return {"id": f"chatcmpl-{uuid.uuid4().hex}","object": "chat.completion","created": int(time.time()),"model": model_id,"system_fingerprint": f"fp-{_model_slug}","choices": [{"index": 0,174 unmodified linesmessage: str,history: list,max_new_tokens: int,temperature: float,top_p: float,) -> str:"""Gradio ``ChatInterface`` event handler.10 unmodified linesmax_new_tokens : intMaximum tokens to generate, sourced from the UI slider.temperature : floatSampling temperature sourced from the UI slider.top_p : floatNucleus sampling cutoff sourced from the UI slider.Returns-------str5 unmodified linesIf ``message`` is empty after stripping.RuntimeErrorPropagated from ``_generate`` on inference failure or emptymodel output.Notes-----27 unmodified lineslogger.info("Gradio inference | ""history_turns=%d | ""max_new_tokens=%d | ""temperature=%.2f | ""top_p=%.2f",len(messages) - 1,max_new_tokens,temperature,top_p,)return _generate(messages,max_new_tokens,temperature,top_p,)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Gradio UI# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# v2.x: Gradio is the ASGI ROOT β not a child sub-app mounted on FastAPI.# This is required for ZeroGPU to activate on HuggingFace Spaces.## The Gradio UI is served at / (root).# Custom REST routes are added to Gradio's internal FastAPI instance below._UI_WARNING = """\23 unmodified linesstep=1,label="max_tokens",info=(f"Range: {_MAX_NEW_TOKENS_FLOOR}β{_MAX_NEW_TOKENS_CEIL}. "f"Default: {_MAX_NEW_TOKENS_DEFAULT}."),),gr.Slider(minimum=0.0,maximum=2.0,value=_DEFAULT_TEMPERATURE,step=0.05,label="temperature",info="0.0 = greedy, 0.7 = default, 2.0 = very random.",),gr.Slider(minimum=0.01,maximum=1.0,value=_DEFAULT_TOP_P,step=0.01,label="top_p",info="Nucleus sampling cutoff. 1.0 = disabled.",),],additional_inputs_accordion="Generation settings",)7 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# App assembly β HuggingFace Space export# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# v2.x ARCHITECTURE:## app = _GradioApp.create_app(_gradio_ui) β Gradio is ASGI root# @app.get/post(...) β routes on Gradio's FastAPI# ZeroGPU activates correctly.23 unmodified linesallow_headers=["Content-Type",],allow_credentials=False, # This Space does not use credential-bearing requests.)logger.info(32 unmodified linesExamples-------->>> # curl http://localhost:7860/health... # {"status": "ok", "model": "...", "version": "2.1.0"}"""logger.info("GET /health")1 unmodified linecontent={"status": "ok","model": MODEL_ID,"version": "2.1.0",},status_code=200,)19 unmodified linesReturns-------JSONResponseHTTP 200 with an OpenAI-compatible completion payload on success.HTTP 413 if the body exceeds ``MAX_BODY_BYTES``.HTTP 400 if the body is not valid UTF-8 JSON, or if``messages``, ``max_tokens``, ``temperature``, or ``top_p``fail validation.HTTP 500 on inference failure or unexpected server error.Notes-----2 unmodified lines1. Read and bound-check raw body bytes (413 guard).2. Decode and parse JSON (400 guard).3. Extract ``messages``, ``max_tokens``, ``temperature``,``top_p``, and ``model`` fields.4. Validate with field-specific validators (400 guard).5. Count prompt tokens on CPU (no GPU needed).6. Dispatch to ``_generate_async`` which offloads to``@spaces.GPU`` via ``asyncio.to_thread``.6 unmodified lines* ``RuntimeError`` β 500 (wrapped inference failure from ``_generate``)* ``Exception`` β 500 (unexpected catch-all, never leaks internals)The requested ``model`` field is logged for proxy-routingdiagnostics but does not affect which model is used; this Spacealways serves ``MODEL_ID``.User noteCompatible with the OpenAI Python SDK:7 unmodified linesresponse = client.chat.completions.create(model="any",messages=[{"role": "user", "content": "Hello"}],temperature=0.7,top_p=1.0,)"""request_id = uuid.uuid4().hex44 unmodified lines"max_tokens",_MAX_NEW_TOKENS_DEFAULT,)temperature_raw: object = payload.get("temperature",_DEFAULT_TEMPERATURE,)top_p_raw: object = payload.get("top_p",_DEFAULT_TOP_P,)# Log requested model for proxy-routing diagnostics only.# This Space always serves MODEL_ID regardless of the field value.model_requested: object = payload.get("model", MODEL_ID)# ββ 4. Input validation βββββββββββββββββββββββββββββββββββββββββββββββββββtry:messages = _validate_messages(messages_raw)max_new_tokens = _clamp_max_tokens(max_tokens_raw)temperature = _validate_temperature(temperature_raw)top_p = _validate_top_p(top_p_raw)except ValueError as exc:logger.warning("Validation error | request_id=%s | error=%s",10 unmodified lineslogger.info("Dispatching inference | ""request_id=%s | ""model_requested=%s | ""messages=%d | ""max_new_tokens=%d | ""temperature=%.2f | ""top_p=%.2f",request_id,model_requested,len(messages),max_new_tokens,temperature,top_p,)# ββ 5. Prompt token count (CPU, pre-dispatch) ββββββββββββββββββββββββββββοΏ½οΏ½οΏ½6 unmodified linescontent = await _generate_async(messages,max_new_tokens,temperature,top_p,)except ValueError as exc:77 unmodified lineslogger.info("scikit-plots ai-model Space initialized successfully.\n"" version : 2.1.0\n"" model : %s\n"" CORS : %s\n"" max_body : %s bytes\n"
app.py+398-93