SeaWolf-AI commited on
Commit
e186935
·
verified ·
1 Parent(s): fef847f

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """POCKET-35B CPU chat — FastAPI + llama-cpp-python (no GPU).
3
+ Serves a 35B MoE model (Q2_K) answering on a CPU-only Hugging Face Space."""
4
+ import os, json, threading
5
+ from fastapi import FastAPI, Request
6
+ from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
7
+ from huggingface_hub import hf_hub_download
8
+
9
+ MODEL_REPO = os.environ.get("MODEL_REPO", "FINAL-Bench/POCKET-35B-GGUF")
10
+ MODEL_FILE = os.environ.get("MODEL_FILE", "POCKET-35B-Q2_K.gguf")
11
+ N_THREADS = int(os.environ.get("N_THREADS", str(os.cpu_count() or 8)))
12
+ N_CTX = int(os.environ.get("N_CTX", "4096"))
13
+
14
+ app = FastAPI(title="POCKET-35B CPU chat")
15
+ _llm = None
16
+ _lock = threading.Lock()
17
+ _status = {"state": "loading", "detail": "downloading model…"}
18
+
19
+ def get_llm():
20
+ global _llm
21
+ if _llm is None:
22
+ with _lock:
23
+ if _llm is None:
24
+ from llama_cpp import Llama
25
+ _status.update(state="loading", detail="downloading %s…" % MODEL_FILE)
26
+ path = hf_hub_download(MODEL_REPO, MODEL_FILE)
27
+ _status.update(detail="loading into RAM…")
28
+ _llm = Llama(model_path=path, n_ctx=N_CTX, n_threads=N_THREADS,
29
+ n_gpu_layers=0, verbose=False, chat_format=None)
30
+ _status.update(state="ready", detail="POCKET-35B on CPU · ready")
31
+ return _llm
32
+
33
+ @app.on_event("startup")
34
+ def _warm():
35
+ threading.Thread(target=get_llm, daemon=True).start()
36
+
37
+ @app.get("/api/status")
38
+ def status():
39
+ return JSONResponse(_status)
40
+
41
+ @app.post("/api/chat")
42
+ async def chat(req: Request):
43
+ body = await req.json()
44
+ messages = body.get("messages") or [{"role": "user", "content": body.get("prompt", "Hi")}]
45
+ temperature = float(body.get("temperature", 0.7))
46
+ max_tokens = int(body.get("max_tokens", 512))
47
+ llm = get_llm()
48
+
49
+ def gen():
50
+ try:
51
+ stream = llm.create_chat_completion(
52
+ messages=messages, temperature=temperature, top_p=0.95,
53
+ max_tokens=max_tokens, stream=True)
54
+ for chunk in stream:
55
+ delta = chunk["choices"][0]["delta"].get("content")
56
+ if delta:
57
+ yield "data: " + json.dumps({"t": delta}) + "\n\n"
58
+ yield "data: " + json.dumps({"done": True}) + "\n\n"
59
+ except Exception as e:
60
+ yield "data: " + json.dumps({"error": str(e)[:200]}) + "\n\n"
61
+
62
+ return StreamingResponse(gen(), media_type="text/event-stream")
63
+
64
+ @app.get("/", response_class=HTMLResponse)
65
+ def index():
66
+ with open(os.path.join(os.path.dirname(__file__), "index.html"), encoding="utf-8") as f:
67
+ return f.read()