Spaces:
Running on T4
Running on T4
serving: manual load + GenerationMixin + use_cache=False + streaming
Browse files
app.py
CHANGED
|
@@ -133,24 +133,28 @@ def stream(req: GenReq):
|
|
| 133 |
media_type="text/plain; charset=utf-8", status_code=503)
|
| 134 |
if (req.prompt or "").strip() == "":
|
| 135 |
return StreamingResponse(iter(["(empty prompt)"]), media_type="text/plain")
|
| 136 |
-
if not _gen_lock.acquire(blocking=False):
|
| 137 |
-
return StreamingResponse(
|
| 138 |
-
iter(["The demo is busy generating for another visitor — please retry in a moment."]),
|
| 139 |
-
media_type="text/plain; charset=utf-8", status_code=429)
|
| 140 |
|
| 141 |
from transformers import TextIteratorStreamer
|
| 142 |
|
| 143 |
def run():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
try:
|
| 145 |
tok, model, dev, ids, gen = _prep(req)
|
| 146 |
streamer = TextIteratorStreamer(tok, skip_prompt=True, skip_special_tokens=True,
|
| 147 |
-
timeout=
|
| 148 |
-
th = threading.Thread(target=_safe_generate,
|
| 149 |
args=(model, dict(input_ids=ids, streamer=streamer, **gen)))
|
| 150 |
th.start()
|
| 151 |
for chunk in streamer:
|
| 152 |
yield chunk
|
| 153 |
th.join(timeout=5)
|
|
|
|
|
|
|
| 154 |
finally:
|
| 155 |
_gen_lock.release()
|
| 156 |
|
|
|
|
| 133 |
media_type="text/plain; charset=utf-8", status_code=503)
|
| 134 |
if (req.prompt or "").strip() == "":
|
| 135 |
return StreamingResponse(iter(["(empty prompt)"]), media_type="text/plain")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
from transformers import TextIteratorStreamer
|
| 138 |
|
| 139 |
def run():
|
| 140 |
+
# Acquire AND release inside the generator. Acquiring in the endpoint and releasing in
|
| 141 |
+
# the generator's finally leaks the lock whenever the response is never consumed (client
|
| 142 |
+
# disconnects before streaming starts) — which wedges the demo at "busy" forever.
|
| 143 |
+
if not _gen_lock.acquire(timeout=2):
|
| 144 |
+
yield "The demo is busy generating for another visitor — please retry in a moment."
|
| 145 |
+
return
|
| 146 |
try:
|
| 147 |
tok, model, dev, ids, gen = _prep(req)
|
| 148 |
streamer = TextIteratorStreamer(tok, skip_prompt=True, skip_special_tokens=True,
|
| 149 |
+
timeout=120)
|
| 150 |
+
th = threading.Thread(target=_safe_generate, daemon=True,
|
| 151 |
args=(model, dict(input_ids=ids, streamer=streamer, **gen)))
|
| 152 |
th.start()
|
| 153 |
for chunk in streamer:
|
| 154 |
yield chunk
|
| 155 |
th.join(timeout=5)
|
| 156 |
+
except Exception:
|
| 157 |
+
yield "\n[generation stopped]"
|
| 158 |
finally:
|
| 159 |
_gen_lock.release()
|
| 160 |
|