R-Kentaren commited on
Commit
65287ee
Β·
verified Β·
1 Parent(s): 66415d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -12
app.py CHANGED
@@ -3,19 +3,28 @@ import re
3
  import time
4
  import traceback
5
  from pathlib import Path
6
- from typing import Any, Dict, List
7
 
8
- import spaces
9
  from fastapi import Request
10
  from fastapi.responses import HTMLResponse, JSONResponse
11
  from fastapi.staticfiles import StaticFiles
12
  from gradio import Server
13
-
14
- import torch
15
- from transformers import (
16
- AutoModelForCausalLM,
17
- AutoTokenizer,
18
- )
 
 
 
 
 
 
 
 
 
19
 
20
  # ── Configuration ───────────────────────────────────────────────────────
21
  DEFAULT_SYSTEM_PROMPT = (
@@ -26,8 +35,9 @@ DEFAULT_SYSTEM_PROMPT = (
26
  STATIC_DIR = Path(__file__).parent / "static"
27
  os.makedirs(STATIC_DIR, exist_ok=True)
28
 
29
- # ── Model Registry ──────────────────────────────────────────────────────
30
  MODEL_REGISTRY: Dict[str, Dict[str, Any]] = {
 
31
  "HuggingFaceTB/SmolLM2-360M-Instruct": {
32
  "label": "SmolLM2 360M Β· ultra-fast",
33
  "family": "causal-lm",
@@ -58,6 +68,31 @@ MODEL_REGISTRY: Dict[str, Dict[str, Any]] = {
58
  "tasks": ["chat", "code", "summarize", "translate", "agent"],
59
  "context": 128000,
60
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
 
63
  DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct"
@@ -107,6 +142,8 @@ TASK_REGISTRY: Dict[str, Dict[str, Any]] = {
107
  _MODEL_CACHE: Dict[str, Dict[str, Any]] = {}
108
 
109
  def _device() -> str:
 
 
110
  if torch.cuda.is_available():
111
  return "cuda"
112
  if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
@@ -114,12 +151,13 @@ def _device() -> str:
114
  return "cpu"
115
 
116
  def _dtype():
117
- return torch.float16 if torch.cuda.is_available() else torch.float32
 
 
118
 
119
  def get_model(model_id: str) -> Dict[str, Any]:
120
  if model_id in _MODEL_CACHE:
121
  return _MODEL_CACHE[model_id]
122
-
123
  if model_id not in MODEL_REGISTRY:
124
  raise ValueError(f"Unknown model: {model_id}")
125
 
@@ -182,7 +220,7 @@ def _build_prompt(model_id: str, messages: List[Dict[str, Any]],
182
  @spaces.GPU
183
  def generate(model_id: str, messages: List[Dict[str, Any]],
184
  system_prompt: str, max_tokens: int, temperature: float,
185
- top_p: float = 0.95) -> tuple:
186
  bundle = get_model(model_id)
187
  tokenizer = bundle["tokenizer"]
188
  model = bundle["model"]
@@ -446,6 +484,7 @@ async def homepage():
446
  async def healthz():
447
  return JSONResponse({
448
  "status": "ok",
 
449
  "device": _device(),
450
  "models_cached": list(_MODEL_CACHE.keys()),
451
  "models_registered": list(MODEL_REGISTRY.keys()),
 
3
  import time
4
  import traceback
5
  from pathlib import Path
6
+ from typing import Any, Dict, List, Tuple
7
 
8
+ import torch
9
  from fastapi import Request
10
  from fastapi.responses import HTMLResponse, JSONResponse
11
  from fastapi.staticfiles import StaticFiles
12
  from gradio import Server
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer
14
+
15
+ # ── ZeroGPU Detection ───────────────────────────────────────────────────
16
+ IS_ZEROGPU = False
17
+ try:
18
+ import spaces
19
+ from spaces.config import Config as _ZeroGPUConfig
20
+ IS_ZEROGPU = bool(_ZeroGPUConfig.zero_gpu)
21
+ except ImportError:
22
+ # Local / non-ZeroGPU runtime β€” make @spaces.GPU harmless
23
+ class _DummySpaces:
24
+ @staticmethod
25
+ def GPU(fn):
26
+ return fn
27
+ spaces = _DummySpaces()
28
 
29
  # ── Configuration ───────────────────────────────────────────────────────
30
  DEFAULT_SYSTEM_PROMPT = (
 
35
  STATIC_DIR = Path(__file__).parent / "static"
36
  os.makedirs(STATIC_DIR, exist_ok=True)
37
 
38
+ # ── Model Registry (T4-compatible additions marked with *new*) ──────────
39
  MODEL_REGISTRY: Dict[str, Dict[str, Any]] = {
40
+ # Existing
41
  "HuggingFaceTB/SmolLM2-360M-Instruct": {
42
  "label": "SmolLM2 360M Β· ultra-fast",
43
  "family": "causal-lm",
 
68
  "tasks": ["chat", "code", "summarize", "translate", "agent"],
69
  "context": 128000,
70
  },
71
+ # *new* T4-friendly additions
72
+ "microsoft/Phi-3-mini-4k-instruct": {
73
+ "label": "Phi-3 mini 4K Β· T4 sweet spot",
74
+ "family": "causal-lm",
75
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
76
+ "context": 4096,
77
+ },
78
+ "Qwen/Qwen2.5-3B-Instruct": {
79
+ "label": "Qwen2.5 3B Β· T4 capable",
80
+ "family": "causal-lm",
81
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
82
+ "context": 32768,
83
+ },
84
+ "openbmb/MiniCPM5-2B": {
85
+ "label": "MiniCPM5 2B Β· T4 verified 100+ tok/s",
86
+ "family": "causal-lm",
87
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
88
+ "context": 131072,
89
+ },
90
+ "constructai/Qwenite3.5-2B": {
91
+ "label": "Qwenite 3.5 2B Β· T4 trained reasoning",
92
+ "family": "causal-lm",
93
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
94
+ "context": 32768,
95
+ },
96
  }
97
 
98
  DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct"
 
142
  _MODEL_CACHE: Dict[str, Dict[str, Any]] = {}
143
 
144
  def _device() -> str:
145
+ if IS_ZEROGPU:
146
+ return "cuda"
147
  if torch.cuda.is_available():
148
  return "cuda"
149
  if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
 
151
  return "cpu"
152
 
153
  def _dtype():
154
+ if IS_ZEROGPU or torch.cuda.is_available():
155
+ return torch.float16
156
+ return torch.float32
157
 
158
  def get_model(model_id: str) -> Dict[str, Any]:
159
  if model_id in _MODEL_CACHE:
160
  return _MODEL_CACHE[model_id]
 
161
  if model_id not in MODEL_REGISTRY:
162
  raise ValueError(f"Unknown model: {model_id}")
163
 
 
220
  @spaces.GPU
221
  def generate(model_id: str, messages: List[Dict[str, Any]],
222
  system_prompt: str, max_tokens: int, temperature: float,
223
+ top_p: float = 0.95) -> Tuple[str, str]:
224
  bundle = get_model(model_id)
225
  tokenizer = bundle["tokenizer"]
226
  model = bundle["model"]
 
484
  async def healthz():
485
  return JSONResponse({
486
  "status": "ok",
487
+ "zerogpu": IS_ZEROGPU,
488
  "device": _device(),
489
  "models_cached": list(_MODEL_CACHE.keys()),
490
  "models_registered": list(MODEL_REGISTRY.keys()),