Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,17 @@
|
|
| 1 |
|
|
|
|
|
|
|
| 2 |
import time
|
| 3 |
import uuid
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
|
| 7 |
from gradio import Server
|
|
|
|
|
|
|
|
|
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from typing import Optional
|
| 10 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 11 |
-
from fastapi import HTTPException
|
| 12 |
|
| 13 |
MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
|
| 14 |
|
|
@@ -24,7 +27,7 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 24 |
|
| 25 |
print("Model loaded!")
|
| 26 |
|
| 27 |
-
app = Server(title="
|
| 28 |
|
| 29 |
|
| 30 |
class ChatRequest(BaseModel):
|
|
@@ -35,21 +38,26 @@ class ChatRequest(BaseModel):
|
|
| 35 |
stream: Optional[bool] = False
|
| 36 |
|
| 37 |
|
| 38 |
-
|
| 39 |
-
@spaces.GPU(duration=120)
|
| 40 |
-
def run_inference(messages, temperature, max_tokens):
|
| 41 |
-
|
| 42 |
prompt = tokenizer.apply_chat_template(
|
| 43 |
messages,
|
| 44 |
tokenize=False,
|
| 45 |
add_generation_prompt=True
|
| 46 |
)
|
| 47 |
|
| 48 |
-
|
| 49 |
prompt,
|
| 50 |
return_tensors="pt"
|
| 51 |
).to(model.device)
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
with torch.inference_mode():
|
| 54 |
output = model.generate(
|
| 55 |
**inputs,
|
|
@@ -61,74 +69,180 @@ def run_inference(messages, temperature, max_tokens):
|
|
| 61 |
|
| 62 |
generated = output[0][inputs.input_ids.shape[-1]:]
|
| 63 |
|
| 64 |
-
response = tokenizer.decode(
|
| 65 |
-
generated,
|
| 66 |
-
skip_special_tokens=True
|
| 67 |
-
)
|
| 68 |
-
|
| 69 |
return {
|
| 70 |
-
"content":
|
|
|
|
|
|
|
|
|
|
| 71 |
"prompt_tokens": inputs.input_ids.shape[-1],
|
| 72 |
"completion_tokens": generated.shape[-1]
|
| 73 |
}
|
| 74 |
|
| 75 |
|
| 76 |
-
#
|
| 77 |
-
@app.api(name="
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
return run_inference(messages, temperature, max_tokens)
|
| 81 |
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
if not request.messages:
|
| 94 |
raise HTTPException(400, "Messages cannot be empty")
|
| 95 |
|
| 96 |
-
if any(
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
min(max(request.max_tokens if request.max_tokens is not None else 512, 1), 4096)
|
| 105 |
-
)
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
"
|
| 125 |
-
"
|
| 126 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
}
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
|
| 134 |
@app.get("/")
|
|
@@ -136,7 +250,8 @@ def home():
|
|
| 136 |
return {
|
| 137 |
"status": "online",
|
| 138 |
"model": MODEL_ID,
|
| 139 |
-
"api": "/v1/chat/completions"
|
|
|
|
| 140 |
}
|
| 141 |
|
| 142 |
|
|
|
|
| 1 |
|
| 2 |
+
import spaces
|
| 3 |
+
import torch
|
| 4 |
import time
|
| 5 |
import uuid
|
| 6 |
+
import json
|
| 7 |
+
import threading
|
| 8 |
|
| 9 |
from gradio import Server
|
| 10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 11 |
+
from fastapi import HTTPException
|
| 12 |
+
from fastapi.responses import StreamingResponse
|
| 13 |
from pydantic import BaseModel
|
| 14 |
from typing import Optional
|
|
|
|
|
|
|
| 15 |
|
| 16 |
MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
|
| 17 |
|
|
|
|
| 27 |
|
| 28 |
print("Model loaded!")
|
| 29 |
|
| 30 |
+
app = Server(title="MyAPI")
|
| 31 |
|
| 32 |
|
| 33 |
class ChatRequest(BaseModel):
|
|
|
|
| 38 |
stream: Optional[bool] = False
|
| 39 |
|
| 40 |
|
| 41 |
+
def prepare_inputs(messages):
|
|
|
|
|
|
|
|
|
|
| 42 |
prompt = tokenizer.apply_chat_template(
|
| 43 |
messages,
|
| 44 |
tokenize=False,
|
| 45 |
add_generation_prompt=True
|
| 46 |
)
|
| 47 |
|
| 48 |
+
return tokenizer(
|
| 49 |
prompt,
|
| 50 |
return_tensors="pt"
|
| 51 |
).to(model.device)
|
| 52 |
|
| 53 |
+
|
| 54 |
+
# Normal, non-streaming inference
|
| 55 |
+
@app.api(name="generate")
|
| 56 |
+
@spaces.GPU(duration=120)
|
| 57 |
+
def run_inference(messages, temperature=0.7, max_tokens=512):
|
| 58 |
+
|
| 59 |
+
inputs = prepare_inputs(messages)
|
| 60 |
+
|
| 61 |
with torch.inference_mode():
|
| 62 |
output = model.generate(
|
| 63 |
**inputs,
|
|
|
|
| 69 |
|
| 70 |
generated = output[0][inputs.input_ids.shape[-1]:]
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
return {
|
| 73 |
+
"content": tokenizer.decode(
|
| 74 |
+
generated,
|
| 75 |
+
skip_special_tokens=True
|
| 76 |
+
),
|
| 77 |
"prompt_tokens": inputs.input_ids.shape[-1],
|
| 78 |
"completion_tokens": generated.shape[-1]
|
| 79 |
}
|
| 80 |
|
| 81 |
|
| 82 |
+
# Streaming GPU inference
|
| 83 |
+
@app.api(name="generate_stream", stream_every=0.05)
|
| 84 |
+
@spaces.GPU(duration=120)
|
| 85 |
+
def run_streaming(messages, temperature=0.7, max_tokens=512):
|
|
|
|
| 86 |
|
| 87 |
+
inputs = prepare_inputs(messages)
|
| 88 |
|
| 89 |
+
streamer = TextIteratorStreamer(
|
| 90 |
+
tokenizer,
|
| 91 |
+
skip_prompt=True,
|
| 92 |
+
skip_special_tokens=True,
|
| 93 |
+
timeout=120
|
| 94 |
+
)
|
| 95 |
|
| 96 |
+
errors = []
|
| 97 |
+
|
| 98 |
+
def generate_in_thread():
|
| 99 |
+
try:
|
| 100 |
+
with torch.inference_mode():
|
| 101 |
+
model.generate(
|
| 102 |
+
**inputs,
|
| 103 |
+
max_new_tokens=max_tokens,
|
| 104 |
+
do_sample=temperature > 0,
|
| 105 |
+
temperature=max(temperature, 0.01),
|
| 106 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 107 |
+
streamer=streamer
|
| 108 |
+
)
|
| 109 |
+
except Exception as error:
|
| 110 |
+
errors.append(error)
|
| 111 |
+
streamer.end()
|
| 112 |
+
|
| 113 |
+
worker = threading.Thread(
|
| 114 |
+
target=generate_in_thread,
|
| 115 |
+
daemon=True
|
| 116 |
+
)
|
| 117 |
+
worker.start()
|
| 118 |
+
|
| 119 |
+
for text in streamer:
|
| 120 |
+
if text:
|
| 121 |
+
yield text
|
| 122 |
+
|
| 123 |
+
worker.join()
|
| 124 |
+
|
| 125 |
+
if errors:
|
| 126 |
+
raise errors[0]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# OpenAI-compatible chat endpoint
|
| 130 |
+
@app.post("/v1/chat/completions")
|
| 131 |
+
async def chat_completions(request: ChatRequest):
|
| 132 |
|
| 133 |
if not request.messages:
|
| 134 |
raise HTTPException(400, "Messages cannot be empty")
|
| 135 |
|
| 136 |
+
if any(
|
| 137 |
+
m.get("role") not in ("system", "user", "assistant")
|
| 138 |
+
or not isinstance(m.get("content"), str)
|
| 139 |
+
for m in request.messages
|
| 140 |
+
):
|
| 141 |
+
raise HTTPException(400, "Invalid message format")
|
| 142 |
|
| 143 |
+
temperature = min(
|
| 144 |
+
max(request.temperature if request.temperature is not None else 0.7, 0),
|
| 145 |
+
2
|
| 146 |
+
)
|
|
|
|
|
|
|
| 147 |
|
| 148 |
+
max_tokens = min(
|
| 149 |
+
max(request.max_tokens if request.max_tokens is not None else 512, 1),
|
| 150 |
+
4096
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# SSE streaming
|
| 154 |
+
if request.stream:
|
| 155 |
+
|
| 156 |
+
completion_id = "chatcmpl-" + uuid.uuid4().hex
|
| 157 |
+
created = int(time.time())
|
| 158 |
+
|
| 159 |
+
def event(data):
|
| 160 |
+
return "data: " + json.dumps(data, ensure_ascii=False) + "\n\n"
|
| 161 |
+
|
| 162 |
+
def stream_response():
|
| 163 |
+
|
| 164 |
+
yield event({
|
| 165 |
+
"id": completion_id,
|
| 166 |
+
"object": "chat.completion.chunk",
|
| 167 |
+
"created": created,
|
| 168 |
+
"model": MODEL_ID,
|
| 169 |
+
"choices": [{
|
| 170 |
+
"index": 0,
|
| 171 |
+
"delta": {"role": "assistant"},
|
| 172 |
+
"finish_reason": None
|
| 173 |
+
}]
|
| 174 |
+
})
|
| 175 |
+
|
| 176 |
+
for token in run_streaming(
|
| 177 |
+
request.messages,
|
| 178 |
+
temperature,
|
| 179 |
+
max_tokens
|
| 180 |
+
):
|
| 181 |
+
yield event({
|
| 182 |
+
"id": completion_id,
|
| 183 |
+
"object": "chat.completion.chunk",
|
| 184 |
+
"created": created,
|
| 185 |
+
"model": MODEL_ID,
|
| 186 |
+
"choices": [{
|
| 187 |
+
"index": 0,
|
| 188 |
+
"delta": {"content": token},
|
| 189 |
+
"finish_reason": None
|
| 190 |
+
}]
|
| 191 |
+
})
|
| 192 |
+
|
| 193 |
+
yield event({
|
| 194 |
+
"id": completion_id,
|
| 195 |
+
"object": "chat.completion.chunk",
|
| 196 |
+
"created": created,
|
| 197 |
+
"model": MODEL_ID,
|
| 198 |
+
"choices": [{
|
| 199 |
+
"index": 0,
|
| 200 |
+
"delta": {},
|
| 201 |
+
"finish_reason": "stop"
|
| 202 |
+
}]
|
| 203 |
+
})
|
| 204 |
+
|
| 205 |
+
yield "data: [DONE]\n\n"
|
| 206 |
+
|
| 207 |
+
return StreamingResponse(
|
| 208 |
+
stream_response(),
|
| 209 |
+
media_type="text/event-stream",
|
| 210 |
+
headers={
|
| 211 |
+
"Cache-Control": "no-cache",
|
| 212 |
+
"Connection": "keep-alive",
|
| 213 |
+
"X-Accel-Buffering": "no"
|
| 214 |
}
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Normal response (unchanged behavior)
|
| 218 |
+
result = run_inference(
|
| 219 |
+
request.messages,
|
| 220 |
+
temperature,
|
| 221 |
+
max_tokens
|
| 222 |
+
)
|
| 223 |
|
| 224 |
+
prompt_tokens = result["prompt_tokens"]
|
| 225 |
+
completion_tokens = result["completion_tokens"]
|
| 226 |
+
|
| 227 |
+
return {
|
| 228 |
+
"id": "chatcmpl-" + uuid.uuid4().hex,
|
| 229 |
+
"object": "chat.completion",
|
| 230 |
+
"created": int(time.time()),
|
| 231 |
+
"model": MODEL_ID,
|
| 232 |
+
"choices": [{
|
| 233 |
+
"index": 0,
|
| 234 |
+
"message": {
|
| 235 |
+
"role": "assistant",
|
| 236 |
+
"content": result["content"]
|
| 237 |
+
},
|
| 238 |
+
"finish_reason": "stop"
|
| 239 |
+
}],
|
| 240 |
+
"usage": {
|
| 241 |
+
"prompt_tokens": prompt_tokens,
|
| 242 |
+
"completion_tokens": completion_tokens,
|
| 243 |
+
"total_tokens": prompt_tokens + completion_tokens
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
|
| 247 |
|
| 248 |
@app.get("/")
|
|
|
|
| 250 |
return {
|
| 251 |
"status": "online",
|
| 252 |
"model": MODEL_ID,
|
| 253 |
+
"api": "/v1/chat/completions",
|
| 254 |
+
"streaming": True
|
| 255 |
}
|
| 256 |
|
| 257 |
|