Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,44 @@
|
|
| 1 |
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import spaces
|
| 4 |
-
import torch
|
| 5 |
-
import json
|
| 6 |
import time
|
| 7 |
import uuid
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
from
|
| 10 |
-
from fastapi import FastAPI, HTTPException
|
| 11 |
from pydantic import BaseModel
|
| 12 |
from typing import Optional
|
|
|
|
|
|
|
| 13 |
|
| 14 |
MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
|
| 15 |
|
|
|
|
| 16 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 17 |
|
|
|
|
| 18 |
model = AutoModelForCausalLM.from_pretrained(
|
| 19 |
MODEL_ID,
|
| 20 |
dtype=torch.bfloat16,
|
| 21 |
device_map="auto"
|
| 22 |
)
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
prompt = tokenizer.apply_chat_template(
|
| 27 |
messages,
|
| 28 |
tokenize=False,
|
|
@@ -43,63 +59,30 @@ def inference(messages, max_tokens=512, temperature=0.7):
|
|
| 43 |
pad_token_id=tokenizer.eos_token_id
|
| 44 |
)
|
| 45 |
|
| 46 |
-
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
skip_special_tokens=True
|
| 51 |
)
|
| 52 |
|
| 53 |
-
|
| 54 |
-
# Gradio GPU endpoint
|
| 55 |
-
with gr.Blocks() as demo:
|
| 56 |
-
|
| 57 |
-
gr.api(
|
| 58 |
-
inference,
|
| 59 |
-
inputs=[
|
| 60 |
-
gr.JSON(label="Messages"),
|
| 61 |
-
gr.Slider(1, 4096, value=512),
|
| 62 |
-
gr.Slider(0, 2, value=0.7)
|
| 63 |
-
],
|
| 64 |
-
outputs=gr.Textbox(),
|
| 65 |
-
api_name="inference"
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
# FastAPI application
|
| 70 |
-
app = FastAPI(title="Qwen OpenAI API")
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
class ChatRequest(BaseModel):
|
| 74 |
-
model: Optional[str] = MODEL_ID
|
| 75 |
-
messages: list[dict]
|
| 76 |
-
temperature: Optional[float] = 0.7
|
| 77 |
-
max_tokens: Optional[int] = 512
|
| 78 |
-
stream: Optional[bool] = False
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
@app.get("/")
|
| 82 |
-
def home():
|
| 83 |
return {
|
| 84 |
-
"
|
| 85 |
-
"
|
|
|
|
| 86 |
}
|
| 87 |
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
"id": MODEL_ID,
|
| 95 |
-
"object": "model",
|
| 96 |
-
"owned_by": "local"
|
| 97 |
-
}]
|
| 98 |
-
}
|
| 99 |
|
| 100 |
|
|
|
|
| 101 |
@app.post("/v1/chat/completions")
|
| 102 |
-
|
| 103 |
|
| 104 |
if request.stream:
|
| 105 |
raise HTTPException(
|
|
@@ -108,59 +91,66 @@ async def chat(request: ChatRequest):
|
|
| 108 |
)
|
| 109 |
|
| 110 |
if not request.messages:
|
| 111 |
-
raise HTTPException(
|
| 112 |
-
status_code=400,
|
| 113 |
-
detail="Messages cannot be empty."
|
| 114 |
-
)
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
"content": m["content"]
|
| 120 |
-
}
|
| 121 |
-
for m in request.messages
|
| 122 |
-
]
|
| 123 |
|
| 124 |
try:
|
| 125 |
-
result =
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
min(max(request.max_tokens or 512, 1), 4096),
|
| 130 |
-
min(max(request.temperature or 0.7, 0), 2)
|
| 131 |
-
]
|
| 132 |
)
|
| 133 |
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
except Exception as e:
|
| 137 |
-
raise HTTPException(
|
|
|
|
| 138 |
|
|
|
|
|
|
|
| 139 |
return {
|
| 140 |
-
"
|
| 141 |
-
"object": "chat.completion",
|
| 142 |
-
"created": int(time.time()),
|
| 143 |
"model": MODEL_ID,
|
| 144 |
-
"
|
| 145 |
-
"index": 0,
|
| 146 |
-
"message": {
|
| 147 |
-
"role": "assistant",
|
| 148 |
-
"content": content
|
| 149 |
-
},
|
| 150 |
-
"finish_reason": "stop"
|
| 151 |
-
}],
|
| 152 |
-
"usage": {
|
| 153 |
-
"prompt_tokens": 0,
|
| 154 |
-
"completion_tokens": 0,
|
| 155 |
-
"total_tokens": 0
|
| 156 |
-
}
|
| 157 |
}
|
| 158 |
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
|
| 164 |
if __name__ == "__main__":
|
| 165 |
-
|
| 166 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import time
|
| 3 |
import uuid
|
| 4 |
+
import torch
|
| 5 |
+
import spaces
|
| 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 |
|
| 15 |
+
print("Loading tokenizer...")
|
| 16 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 17 |
|
| 18 |
+
print("Loading model...")
|
| 19 |
model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
MODEL_ID,
|
| 21 |
dtype=torch.bfloat16,
|
| 22 |
device_map="auto"
|
| 23 |
)
|
| 24 |
|
| 25 |
+
print("Model loaded!")
|
| 26 |
+
|
| 27 |
+
app = Server(title="Qwen OpenAI API")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ChatRequest(BaseModel):
|
| 31 |
+
model: Optional[str] = MODEL_ID
|
| 32 |
+
messages: list[dict]
|
| 33 |
+
temperature: Optional[float] = 0.7
|
| 34 |
+
max_tokens: Optional[int] = 512
|
| 35 |
+
stream: Optional[bool] = False
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Actual GPU inference
|
| 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,
|
|
|
|
| 59 |
pad_token_id=tokenizer.eos_token_id
|
| 60 |
)
|
| 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": response,
|
| 71 |
+
"prompt_tokens": inputs.input_ids.shape[-1],
|
| 72 |
+
"completion_tokens": generated.shape[-1]
|
| 73 |
}
|
| 74 |
|
| 75 |
|
| 76 |
+
# Gradio API registration
|
| 77 |
+
@app.api(name="generate")
|
| 78 |
+
def generate(messages: list[dict], temperature: float = 0.7,
|
| 79 |
+
max_tokens: int = 512):
|
| 80 |
+
return run_inference(messages, temperature, max_tokens)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
|
| 83 |
+
# OpenAI-compatible API
|
| 84 |
@app.post("/v1/chat/completions")
|
| 85 |
+
def chat_completions(request: ChatRequest):
|
| 86 |
|
| 87 |
if request.stream:
|
| 88 |
raise HTTPException(
|
|
|
|
| 91 |
)
|
| 92 |
|
| 93 |
if not request.messages:
|
| 94 |
+
raise HTTPException(400, "Messages cannot be empty")
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
if any(m.get("role") not in ("system", "user", "assistant")
|
| 97 |
+
for m in request.messages):
|
| 98 |
+
raise HTTPException(400, "Invalid message role")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
try:
|
| 101 |
+
result = run_inference(
|
| 102 |
+
request.messages,
|
| 103 |
+
min(max(request.temperature if request.temperature is not None else 0.7, 0), 2),
|
| 104 |
+
min(max(request.max_tokens if request.max_tokens is not None else 512, 1), 4096)
|
|
|
|
|
|
|
|
|
|
| 105 |
)
|
| 106 |
|
| 107 |
+
prompt_tokens = result["prompt_tokens"]
|
| 108 |
+
completion_tokens = result["completion_tokens"]
|
| 109 |
+
|
| 110 |
+
return {
|
| 111 |
+
"id": "chatcmpl-" + uuid.uuid4().hex,
|
| 112 |
+
"object": "chat.completion",
|
| 113 |
+
"created": int(time.time()),
|
| 114 |
+
"model": MODEL_ID,
|
| 115 |
+
"choices": [{
|
| 116 |
+
"index": 0,
|
| 117 |
+
"message": {
|
| 118 |
+
"role": "assistant",
|
| 119 |
+
"content": result["content"]
|
| 120 |
+
},
|
| 121 |
+
"finish_reason": "stop"
|
| 122 |
+
}],
|
| 123 |
+
"usage": {
|
| 124 |
+
"prompt_tokens": prompt_tokens,
|
| 125 |
+
"completion_tokens": completion_tokens,
|
| 126 |
+
"total_tokens": prompt_tokens + completion_tokens
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
+
raise HTTPException(500, str(e))
|
| 132 |
+
|
| 133 |
|
| 134 |
+
@app.get("/")
|
| 135 |
+
def home():
|
| 136 |
return {
|
| 137 |
+
"status": "online",
|
|
|
|
|
|
|
| 138 |
"model": MODEL_ID,
|
| 139 |
+
"api": "/v1/chat/completions"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
}
|
| 141 |
|
| 142 |
|
| 143 |
+
@app.get("/v1/models")
|
| 144 |
+
def models():
|
| 145 |
+
return {
|
| 146 |
+
"object": "list",
|
| 147 |
+
"data": [{
|
| 148 |
+
"id": MODEL_ID,
|
| 149 |
+
"object": "model",
|
| 150 |
+
"owned_by": "local"
|
| 151 |
+
}]
|
| 152 |
+
}
|
| 153 |
|
| 154 |
|
| 155 |
if __name__ == "__main__":
|
| 156 |
+
app.launch()
|
|
|