Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files8 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474826 unmodified lines7576777879808114 unmodified lines969798991001011027 unmodified lines1101111121131141151161171181191201211222 unmodified lines12512612712812913013113213313413513613713813914014114214314411 unmodified lines15615715815916016116216316416516616716816917017117217317417517611 unmodified lines1881891901911921931944 unmodified lines1992002012022032042058 unmodified linesfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom typing import List, Optional, Dictfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadimport gradio as grMODEL_ID = "Qwen/Qwen2.5-Coder-32B-Instruct-AWQ"# Cargar Tokenizertokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)# Cargar Modelo en AWQ (18-20 GB VRAM)model = AutoModelForCausalLM.from_pretrained(MODEL_ID,dtype=torch.float16,device_map="auto",trust_remote_code=True)# Inicializar FastAPIapp = FastAPI(title="Qwen2.5-Coder-32B OpenAI Compatible API")# --- Esquemas Pydantic ---class ChatMessage(BaseModel):role: strcontent: strclass ChatCompletionRequest(BaseModel):model: Optional[str] = "Qwen/Qwen2.5-Coder-32B-Instruct-AWQ"messages: List[ChatMessage]temperature: Optional[float] = 0.2top_p: Optional[float] = 0.9max_tokens: Optional[int] = 2048stream: Optional[bool] = False# Función central de generación protegida por ZeroGPU@spaces.GPU(duration=120)def generate_stream_tokens(messages_dict: List[Dict[str, str]], temperature: float, top_p: float, max_tokens: int):text = tokenizer.apply_chat_template(26 unmodified linesfor new_token in streamer:yield new_token# --- Endpoints OpenAI (/v1) ---@app.get("/v1/models")async def list_models():return {14 unmodified linescreated_time = int(time.time())messages_dict = [{"role": m.role, "content": m.content} for m in req.messages]# Manejo de streaming (SSE)if req.stream:async def event_generator():for token in generate_stream_tokens(7 unmodified lines"object": "chat.completion.chunk","created": created_time,"model": req.model,"choices": [{"index": 0,"delta": {"content": token},"finish_reason": None}]}yield f"data: {json.dumps(chunk)}\n\n"2 unmodified lines"object": "chat.completion.chunk","created": created_time,"model": req.model,"choices": [{"index": 0,"delta": {},"finish_reason": "stop"}]}yield f"data: {json.dumps(final_chunk)}\n\n"yield "data: [DONE]\n\n"return StreamingResponse(event_generator(), media_type="text/event-stream")# Respuesta estándar (sin streaming)full_content = ""for token in generate_stream_tokens(messages_dict,11 unmodified lines"choices": [{"index": 0,"message": {"role": "assistant","content": full_content},"finish_reason": "stop"}],"usage": {"prompt_tokens": -1,"completion_tokens": -1,"total_tokens": -1}}# --- Interfaz Gradio ---def gradio_generate(message, history, system_prompt, temperature, top_p, max_tokens):messages = []if system_prompt:11 unmodified lineswith gr.Blocks(title="Qwen2.5-Coder-32B API & UI", theme=gr.themes.Soft()) as gradio_app:gr.Markdown("# 🚀 Qwen2.5-Coder-32B-Instruct (AWQ en ZeroGPU)")gr.Markdown("Servicio con interfaz web y endpoints OpenAI (`/v1/chat/completions`).")gr.ChatInterface(fn=gradio_generate,additional_inputs=[4 unmodified lines])# Montar Gradio en la raízapp = gr.mount_gradio_app(app, gradio_app, path="/")if __name__ == "__main__":8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575826 unmodified lines85868788899014 unmodified lines1051061071081091107 unmodified lines1181191201211221231242 unmodified lines12712812913013113213313413513613713813911 unmodified lines15115215315415515615715815916016116216311 unmodified lines1751761771781791801814 unmodified lines1861871881891901918 unmodified linesfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom typing import List, Optional, Dictfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, AwqConfigfrom threading import Threadimport gradio as gr# Desactivar kernels Marlin incompatibles con el init en CPU de ZeroGPUos.environ["GPTQMODEL_DISABLE_MARLIN"] = "1"os.environ["AUTOAWQ_USE_MARLIN"] = "0"MODEL_ID = "Qwen/Qwen2.5-Coder-32B-Instruct-AWQ"# Cargar Tokenizertokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)# Forzar backend GEMM estándar de AWQ para evitar fallos de repacking en CPUquant_config = AwqConfig(bits=4,version="gemm",fuse_max_seq_len=4096,do_fuse=False)# Cargar modelo en modo device_map="auto" compatible con ZeroGPUmodel = AutoModelForCausalLM.from_pretrained(MODEL_ID,dtype=torch.float16,quantization_config=quant_config,device_map="auto",trust_remote_code=True)app = FastAPI(title="Qwen2.5-Coder-32B OpenAI API")class ChatMessage(BaseModel):role: strcontent: strclass ChatCompletionRequest(BaseModel):model: Optional[str] = MODEL_IDmessages: List[ChatMessage]temperature: Optional[float] = 0.2top_p: Optional[float] = 0.9max_tokens: Optional[int] = 2048stream: Optional[bool] = False@spaces.GPU(duration=120)def generate_stream_tokens(messages_dict: List[Dict[str, str]], temperature: float, top_p: float, max_tokens: int):text = tokenizer.apply_chat_template(26 unmodified linesfor new_token in streamer:yield new_token@app.get("/v1/models")async def list_models():return {14 unmodified linescreated_time = int(time.time())messages_dict = [{"role": m.role, "content": m.content} for m in req.messages]if req.stream:async def event_generator():for token in generate_stream_tokens(7 unmodified lines"object": "chat.completion.chunk","created": created_time,"model": req.model,"choices": [{"index": 0, "delta": {"content": token}, "finish_reason": None}]}yield f"data: {json.dumps(chunk)}\n\n"2 unmodified lines"object": "chat.completion.chunk","created": created_time,"model": req.model,"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}yield f"data: {json.dumps(final_chunk)}\n\n"yield "data: [DONE]\n\n"return StreamingResponse(event_generator(), media_type="text/event-stream")full_content = ""for token in generate_stream_tokens(messages_dict,11 unmodified lines"choices": [{"index": 0,"message": {"role": "assistant", "content": full_content},"finish_reason": "stop"}],"usage": {"prompt_tokens": -1, "completion_tokens": -1, "total_tokens": -1}}def gradio_generate(message, history, system_prompt, temperature, top_p, max_tokens):messages = []if system_prompt:11 unmodified lineswith gr.Blocks(title="Qwen2.5-Coder-32B API & UI", theme=gr.themes.Soft()) as gradio_app:gr.Markdown("# 🚀 Qwen2.5-Coder-32B-Instruct (AWQ en ZeroGPU)")gr.Markdown("Endpoint OpenAI: `/v1/chat/completions` | Modelo: `Qwen/Qwen2.5-Coder-32B-Instruct-AWQ`")gr.ChatInterface(fn=gradio_generate,additional_inputs=[4 unmodified lines])app = gr.mount_gradio_app(app, gradio_app, path="/")if __name__ == "__main__":
app.py+22-36