SeaWolf-AI commited on
Commit
2893ee9
Β·
verified Β·
1 Parent(s): 2fc471e

v1: FastAPI OpenAI-compatible Darwin-35B-A3B-Opus API (INT4, Docker)

Browse files
Files changed (4) hide show
  1. Dockerfile +26 -0
  2. README.md +55 -5
  3. app.py +426 -0
  4. requirements.txt +11 -0
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.5.1-cuda12.1-cudnn9-runtime
2
+
3
+ # System deps
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ build-essential git curl ca-certificates \
6
+ && rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+
10
+ # HF cache β€” writable directory inside container
11
+ ENV HF_HOME=/app/.cache/huggingface \
12
+ TRANSFORMERS_CACHE=/app/.cache/huggingface \
13
+ HF_HUB_ENABLE_HF_TRANSFER=1 \
14
+ PYTHONUNBUFFERED=1
15
+
16
+ COPY requirements.txt .
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # Pre-create HF cache dir (HF Spaces are read-only by default; this is writable)
20
+ RUN mkdir -p /app/.cache/huggingface && chmod -R 777 /app/.cache
21
+
22
+ COPY app.py .
23
+
24
+ EXPOSE 7860
25
+
26
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,60 @@
1
  ---
2
- title: Darwin 35B A3B Opus API
3
- emoji: πŸ“š
4
- colorFrom: gray
5
- colorTo: red
6
  sdk: docker
 
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Darwin-35B-A3B-Opus API
3
+ emoji: 🧬
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
+ license: apache-2.0
10
+ short_description: OpenAI-compatible FastAPI for Darwin-35B-A3B-Opus (INT4)
11
  ---
12
 
13
+ # Darwin-35B-A3B-Opus API
14
+
15
+ Self-hosted OpenAI-compatible FastAPI server for [FINAL-Bench/Darwin-35B-A3B-Opus](https://huggingface.co/FINAL-Bench/Darwin-35B-A3B-Opus).
16
+
17
+ - **35B MoE / 3B active** β€” Qwen3.5-MoE based
18
+ - **INT4 quantized** (~18 GB) β€” fits on L4/A10G/L40S
19
+ - **OpenAI-compatible** endpoints + SSE streaming
20
+ - **Bearer auth** (configurable via `API_KEYS` secret)
21
+
22
+ ## Endpoints
23
+
24
+ - `GET /` β€” Landing page with examples
25
+ - `GET /health` β€” Health + load status
26
+ - `GET /v1/models` β€” List models
27
+ - `POST /v1/chat/completions` β€” Chat (OpenAI compat)
28
+
29
+ ## Configuration (HF Space secrets)
30
+
31
+ | Secret | Required | Description |
32
+ |--------|----------|-------------|
33
+ | `HF_TOKEN` | optional | HF token for private/gated models |
34
+ | `API_KEYS` | optional | Comma-separated bearer keys (empty = public) |
35
+ | `QUANT_MODE` | optional | `int4` (default), `int8`, `bf16` |
36
+ | `MODEL_ID` | optional | HF model id (default: `FINAL-Bench/Darwin-35B-A3B-Opus`) |
37
+
38
+ ## Hardware
39
+
40
+ Recommended:
41
+ - **L4 (24GB)** β€” INT4 βœ…
42
+ - **A10G-small (24GB)** β€” INT4 βœ…
43
+ - **L40S (48GB)** β€” INT4 βœ… or INT8 βœ…
44
+ - **A100 (80GB)** β€” any mode including BF16
45
+
46
+ ## Example
47
+
48
+ ```python
49
+ from openai import OpenAI
50
+ client = OpenAI(
51
+ api_key="YOUR_KEY",
52
+ base_url="https://final-bench-darwin-35b-a3b-opus-api.hf.space/v1",
53
+ )
54
+ resp = client.chat.completions.create(
55
+ model="Darwin-35B-A3B-Opus",
56
+ messages=[{"role":"user","content":"Explain GPQA"}],
57
+ max_tokens=300,
58
+ )
59
+ print(resp.choices[0].message.content)
60
+ ```
app.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Darwin-35B-A3B-Opus FastAPI Server β€” HF Space (Docker SDK)
3
+
4
+ OpenAI-compatible chat completions endpoint with optional bearer auth.
5
+ INT4 quantization (default) fits 35B MoE into ~18GB β†’ runs on L4/A10G/L40S.
6
+
7
+ Environment variables:
8
+ MODEL_ID β€” HuggingFace model id (default: FINAL-Bench/Darwin-35B-A3B-Opus)
9
+ HF_TOKEN β€” HuggingFace token (for private/gated models)
10
+ API_KEYS β€” Comma-separated bearer keys (empty = public, no auth)
11
+ QUANT_MODE β€” int4 (default) | int8 | bf16
12
+ """
13
+ import os
14
+ import re
15
+ import time
16
+ import json
17
+ import threading
18
+ import traceback
19
+ from typing import List, Optional, Union, Any, Dict
20
+
21
+ import torch
22
+ from transformers import (
23
+ AutoTokenizer,
24
+ AutoModelForCausalLM,
25
+ BitsAndBytesConfig,
26
+ TextIteratorStreamer,
27
+ )
28
+
29
+ from fastapi import FastAPI, HTTPException, Header, Depends
30
+ from fastapi.middleware.cors import CORSMiddleware
31
+ from fastapi.responses import StreamingResponse, HTMLResponse
32
+ from pydantic import BaseModel, Field
33
+
34
+
35
+ # === Configuration ===
36
+ MODEL_ID = os.environ.get('MODEL_ID', 'FINAL-Bench/Darwin-35B-A3B-Opus')
37
+ MODEL_NAME = MODEL_ID.split('/')[-1]
38
+ HF_TOKEN = os.environ.get('HF_TOKEN', '').strip() or None
39
+ API_KEYS = set(k.strip() for k in os.environ.get('API_KEYS', '').split(',') if k.strip())
40
+ QUANT_MODE = os.environ.get('QUANT_MODE', 'int4').lower()
41
+
42
+ SPECIAL_TOKEN_RE = re.compile(
43
+ r'<\|im_(?:start|end)\|>|<\|endoftext\|>|<\|startoftext\|>'
44
+ )
45
+
46
+
47
+ def log(msg: str) -> None:
48
+ print(f'[{time.strftime("%H:%M:%S")}] {msg}', flush=True)
49
+
50
+
51
+ def strip_special(text: str) -> str:
52
+ return SPECIAL_TOKEN_RE.sub('', text)
53
+
54
+
55
+ # === Globals ===
56
+ model = None
57
+ tok = None
58
+ inference_lock = threading.Lock()
59
+
60
+
61
+ # === Pydantic schemas (OpenAI-compatible) ===
62
+ class ChatMessage(BaseModel):
63
+ role: str
64
+ content: Union[str, List[Dict[str, Any]]]
65
+
66
+
67
+ class ChatCompletionRequest(BaseModel):
68
+ model: str = MODEL_NAME
69
+ messages: List[ChatMessage]
70
+ max_tokens: int = Field(default=1024, ge=1, le=8192)
71
+ temperature: float = Field(default=0.7, ge=0.0, le=2.0)
72
+ top_p: float = Field(default=0.95, ge=0.0, le=1.0)
73
+ n: int = Field(default=1, ge=1, le=4)
74
+ stream: bool = False
75
+ stop: Optional[Union[str, List[str]]] = None
76
+ seed: Optional[int] = None
77
+ repetition_penalty: Optional[float] = Field(default=None, ge=1.0, le=2.0)
78
+
79
+
80
+ def verify_api_key(authorization: Optional[str] = Header(None)) -> None:
81
+ if not API_KEYS:
82
+ return # public
83
+ if not authorization:
84
+ raise HTTPException(401, 'Missing Authorization header. Use: Authorization: Bearer YOUR_API_KEY')
85
+ if not authorization.lower().startswith('bearer '):
86
+ raise HTTPException(401, 'Invalid Authorization format. Use: Bearer YOUR_API_KEY')
87
+ token = authorization[7:].strip()
88
+ if token not in API_KEYS:
89
+ raise HTTPException(401, 'Invalid API key')
90
+
91
+
92
+ # === FastAPI ===
93
+ app = FastAPI(title=f'{MODEL_NAME} API', version='1.0')
94
+ app.add_middleware(
95
+ CORSMiddleware,
96
+ allow_origins=['*'],
97
+ allow_credentials=True,
98
+ allow_methods=['*'],
99
+ allow_headers=['*'],
100
+ )
101
+
102
+
103
+ @app.get('/health')
104
+ def health():
105
+ return {
106
+ 'status': 'ok',
107
+ 'model': MODEL_NAME,
108
+ 'loaded': model is not None,
109
+ 'quant_mode': QUANT_MODE,
110
+ 'auth_required': len(API_KEYS) > 0,
111
+ 'cuda': torch.cuda.is_available(),
112
+ 'cuda_device_count': torch.cuda.device_count() if torch.cuda.is_available() else 0,
113
+ }
114
+
115
+
116
+ @app.get('/v1/models')
117
+ def list_models():
118
+ return {
119
+ 'object': 'list',
120
+ 'data': [{
121
+ 'id': MODEL_NAME,
122
+ 'object': 'model',
123
+ 'created': int(time.time()),
124
+ 'owned_by': 'FINAL-Bench',
125
+ }],
126
+ }
127
+
128
+
129
+ def _stream_generate(inputs, gen_kwargs):
130
+ """Background thread + SSE generator for streaming responses."""
131
+ streamer = TextIteratorStreamer(
132
+ tok, skip_prompt=True, skip_special_tokens=False, timeout=600.0
133
+ )
134
+ gk = {**gen_kwargs, 'streamer': streamer}
135
+
136
+ def _run():
137
+ with inference_lock:
138
+ try:
139
+ with torch.no_grad():
140
+ model.generate(**inputs, **gk)
141
+ except Exception as e:
142
+ log(f'stream gen FAIL: {e}')
143
+ traceback.print_exc()
144
+
145
+ t = threading.Thread(target=_run, daemon=True)
146
+ t.start()
147
+
148
+ def event_stream():
149
+ cid = f'chatcmpl-{int(time.time()*1000)}'
150
+ first = {
151
+ 'id': cid, 'object': 'chat.completion.chunk',
152
+ 'created': int(time.time()), 'model': MODEL_NAME,
153
+ 'choices': [{'index': 0, 'delta': {'role': 'assistant'}, 'finish_reason': None}],
154
+ }
155
+ yield f'data: {json.dumps(first)}\n\n'
156
+
157
+ for chunk_text in streamer:
158
+ if not chunk_text:
159
+ continue
160
+ cleaned = strip_special(chunk_text)
161
+ if not cleaned:
162
+ continue
163
+ delta = {
164
+ 'id': cid, 'object': 'chat.completion.chunk',
165
+ 'created': int(time.time()), 'model': MODEL_NAME,
166
+ 'choices': [{'index': 0, 'delta': {'content': cleaned}, 'finish_reason': None}],
167
+ }
168
+ yield f'data: {json.dumps(delta)}\n\n'
169
+
170
+ last = {
171
+ 'id': cid, 'object': 'chat.completion.chunk',
172
+ 'created': int(time.time()), 'model': MODEL_NAME,
173
+ 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}],
174
+ }
175
+ yield f'data: {json.dumps(last)}\n\n'
176
+ yield 'data: [DONE]\n\n'
177
+
178
+ return event_stream()
179
+
180
+
181
+ @app.post('/v1/chat/completions', dependencies=[Depends(verify_api_key)])
182
+ def chat_completions(req: ChatCompletionRequest):
183
+ if model is None:
184
+ raise HTTPException(503, 'Model still loading')
185
+
186
+ # Convert messages β€” flatten content if it's a list
187
+ msgs = []
188
+ for m in req.messages:
189
+ content = m.content
190
+ if isinstance(content, list):
191
+ # Take text-typed items only (no multimodal in v1)
192
+ parts = [it.get('text', '') for it in content if isinstance(it, dict) and it.get('type') == 'text']
193
+ content = '\n'.join(parts)
194
+ msgs.append({'role': m.role, 'content': content})
195
+
196
+ try:
197
+ prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
198
+ except Exception as e:
199
+ raise HTTPException(400, f'chat_template error: {e}')
200
+
201
+ inputs = tok(prompt, return_tensors='pt')
202
+ input_device = next(model.parameters()).device
203
+ inputs = {k: v.to(input_device) for k, v in inputs.items()}
204
+ input_len = inputs['input_ids'].shape[1]
205
+
206
+ if req.seed is not None:
207
+ torch.manual_seed(req.seed)
208
+
209
+ do_sample = req.temperature > 0
210
+ gen_kwargs = dict(
211
+ max_new_tokens=req.max_tokens,
212
+ do_sample=do_sample,
213
+ temperature=req.temperature if do_sample else 1.0,
214
+ top_p=req.top_p,
215
+ pad_token_id=tok.eos_token_id,
216
+ )
217
+ if req.repetition_penalty and req.repetition_penalty > 1.0:
218
+ gen_kwargs['repetition_penalty'] = req.repetition_penalty
219
+
220
+ # Streaming branch
221
+ if req.stream:
222
+ log(f'STREAM start: in={input_len} max={req.max_tokens}')
223
+ return StreamingResponse(
224
+ _stream_generate(inputs, gen_kwargs),
225
+ media_type='text/event-stream',
226
+ headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'},
227
+ )
228
+
229
+ # Non-streaming
230
+ if req.n > 1:
231
+ gen_kwargs['num_return_sequences'] = req.n
232
+
233
+ with inference_lock:
234
+ t0 = time.time()
235
+ with torch.no_grad():
236
+ try:
237
+ outputs = model.generate(**inputs, **gen_kwargs)
238
+ except Exception as e:
239
+ log(f'generate FAIL: {e}')
240
+ traceback.print_exc()
241
+ raise HTTPException(500, f'generate error: {e}')
242
+ elapsed = time.time() - t0
243
+
244
+ choices = []
245
+ total_completion = 0
246
+ for i in range(req.n):
247
+ gen = outputs[i][input_len:]
248
+ text = tok.decode(gen, skip_special_tokens=True)
249
+ text = strip_special(text).strip()
250
+ if req.stop:
251
+ stops = [req.stop] if isinstance(req.stop, str) else req.stop
252
+ for s in stops:
253
+ idx = text.find(s)
254
+ if idx >= 0:
255
+ text = text[:idx]
256
+ ct = int(len(gen))
257
+ total_completion += ct
258
+ choices.append({
259
+ 'index': i,
260
+ 'message': {'role': 'assistant', 'content': text},
261
+ 'finish_reason': 'stop' if ct < req.max_tokens else 'length',
262
+ })
263
+
264
+ log(f'chat_completions: in={input_len} gen={total_completion} n={req.n} {elapsed:.1f}s')
265
+ return {
266
+ 'id': f'chatcmpl-{int(time.time()*1000)}',
267
+ 'object': 'chat.completion',
268
+ 'created': int(time.time()),
269
+ 'model': MODEL_NAME,
270
+ 'choices': choices,
271
+ 'usage': {
272
+ 'prompt_tokens': input_len,
273
+ 'completion_tokens': total_completion,
274
+ 'total_tokens': input_len + total_completion,
275
+ },
276
+ }
277
+
278
+
279
+ # === Landing page (HTML) ===
280
+ @app.get('/', response_class=HTMLResponse)
281
+ def root():
282
+ state = 'loaded' if model is not None else 'loading...'
283
+ auth_note = 'Bearer API key required' if API_KEYS else 'No auth (public)'
284
+ return f"""<!DOCTYPE html>
285
+ <html lang="en">
286
+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
287
+ <title>{MODEL_NAME} API</title>
288
+ <style>
289
+ *{{margin:0;padding:0;box-sizing:border-box}}
290
+ body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;max-width:900px;margin:40px auto;padding:0 24px;line-height:1.65;color:#1f2937;background:#f9fafb}}
291
+ h1{{color:#4338ca;font-size:32px;margin-bottom:8px}}
292
+ h2{{margin:32px 0 12px;color:#1e293b;border-bottom:2px solid #e5e7eb;padding-bottom:6px;font-size:20px}}
293
+ pre{{background:#1e293b;color:#e2e8f0;padding:16px 18px;border-radius:8px;overflow-x:auto;font-size:13px;line-height:1.55}}
294
+ code{{background:#eef2ff;color:#4338ca;padding:2px 7px;border-radius:4px;font-family:'JetBrains Mono',Consolas,monospace;font-size:0.93em}}
295
+ pre code{{background:transparent;color:inherit;padding:0}}
296
+ .badge{{display:inline-block;padding:4px 12px;background:#dbeafe;color:#1e40af;border-radius:12px;font-size:12px;margin-right:6px;font-weight:500}}
297
+ .status{{display:inline-block;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600}}
298
+ .status.ok{{background:#dcfce7;color:#166534}}.status.warn{{background:#fef3c7;color:#92400e}}
299
+ ul{{padding-left:24px;margin:10px 0}}li{{margin:6px 0}}
300
+ a{{color:#4338ca;text-decoration:none}}a:hover{{text-decoration:underline}}
301
+ .card{{background:white;border:1px solid #e5e7eb;border-radius:10px;padding:20px;margin:16px 0}}
302
+ .footer{{margin-top:50px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b7280;font-size:13px;text-align:center}}
303
+ </style></head>
304
+ <body>
305
+ <h1>🧬 {MODEL_NAME} API</h1>
306
+ <p>
307
+ <span class="badge">35B MoE</span>
308
+ <span class="badge">3B active</span>
309
+ <span class="badge">{QUANT_MODE.upper()}</span>
310
+ <span class="badge">OpenAI-compatible</span>
311
+ <span class="status {'ok' if model is not None else 'warn'}">{state}</span>
312
+ </p>
313
+ <p>Self-hosted FastAPI inference server for FINAL-Bench/Darwin-35B-A3B-Opus.<br/>
314
+ Auth: <strong>{auth_note}</strong></p>
315
+
316
+ <h2>πŸ”Œ Endpoints</h2>
317
+ <ul>
318
+ <li><code>GET /health</code> β€” health + load status</li>
319
+ <li><code>GET /v1/models</code> β€” list available models</li>
320
+ <li><code>POST /v1/chat/completions</code> β€” chat (OpenAI compat, supports streaming)</li>
321
+ </ul>
322
+
323
+ <h2>πŸ’» Example (curl)</h2>
324
+ <pre><code>curl https://final-bench-darwin-35b-a3b-opus-api.hf.space/v1/chat/completions \\
325
+ -H "Authorization: Bearer YOUR_API_KEY" \\
326
+ -H "Content-Type: application/json" \\
327
+ -d '{{"model":"{MODEL_NAME}","messages":[{{"role":"user","content":"Explain SN2 reaction"}}],"max_tokens":500}}'</code></pre>
328
+
329
+ <h2>🐍 Example (Python OpenAI SDK)</h2>
330
+ <pre><code>from openai import OpenAI
331
+ client = OpenAI(
332
+ api_key="YOUR_API_KEY",
333
+ base_url="https://final-bench-darwin-35b-a3b-opus-api.hf.space/v1",
334
+ )
335
+ resp = client.chat.completions.create(
336
+ model="{MODEL_NAME}",
337
+ messages=[{{"role": "user", "content": "What is GPQA?"}}],
338
+ max_tokens=300,
339
+ )
340
+ print(resp.choices[0].message.content)</code></pre>
341
+
342
+ <h2>🌊 Streaming</h2>
343
+ <pre><code>stream = client.chat.completions.create(
344
+ model="{MODEL_NAME}",
345
+ messages=[{{"role":"user","content":"Write a Python function"}}],
346
+ max_tokens=500,
347
+ stream=True,
348
+ )
349
+ for chunk in stream:
350
+ if chunk.choices[0].delta.content:
351
+ print(chunk.choices[0].delta.content, end="", flush=True)</code></pre>
352
+
353
+ <div class="card">
354
+ <h2 style="border:none;margin-top:0">πŸ“Š Health check</h2>
355
+ <pre><code>curl https://final-bench-darwin-35b-a3b-opus-api.hf.space/health</code></pre>
356
+ </div>
357
+
358
+ <div class="footer">
359
+ Powered by <strong>FINAL-Bench</strong> Β· Model: <a href="https://huggingface.co/{MODEL_ID}">{MODEL_ID}</a>
360
+ </div>
361
+ </body></html>"""
362
+
363
+
364
+ # === Model loading ===
365
+ def load_model():
366
+ global model, tok
367
+ log(f'Loading tokenizer from {MODEL_ID}...')
368
+ tok = AutoTokenizer.from_pretrained(
369
+ MODEL_ID, trust_remote_code=True, token=HF_TOKEN
370
+ )
371
+ log(f' vocab={tok.vocab_size}, type={type(tok).__name__}')
372
+
373
+ log(f'Loading model in {QUANT_MODE} mode...')
374
+ t0 = time.time()
375
+ kwargs: Dict[str, Any] = {
376
+ 'trust_remote_code': True,
377
+ 'token': HF_TOKEN,
378
+ 'device_map': 'auto',
379
+ 'low_cpu_mem_usage': True,
380
+ }
381
+
382
+ if QUANT_MODE == 'int8':
383
+ kwargs['quantization_config'] = BitsAndBytesConfig(load_in_8bit=True)
384
+ elif QUANT_MODE == 'int4':
385
+ kwargs['quantization_config'] = BitsAndBytesConfig(
386
+ load_in_4bit=True,
387
+ bnb_4bit_compute_dtype=torch.bfloat16,
388
+ bnb_4bit_quant_type='nf4',
389
+ bnb_4bit_use_double_quant=True,
390
+ )
391
+ else:
392
+ # bf16 full precision (requires ~72GB GPU)
393
+ pass
394
+
395
+ # Try new "dtype" arg first (transformers >=4.46), fall back to "torch_dtype"
396
+ try:
397
+ if QUANT_MODE not in ('int8', 'int4'):
398
+ kwargs['dtype'] = torch.bfloat16
399
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
400
+ except TypeError:
401
+ kwargs.pop('dtype', None)
402
+ if QUANT_MODE not in ('int8', 'int4'):
403
+ kwargs['torch_dtype'] = torch.bfloat16
404
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
405
+
406
+ model.eval()
407
+ log(f'Loaded in {(time.time()-t0)/60:.1f} min')
408
+ log(f' class: {type(model).__name__}')
409
+ log(f' total params: {sum(p.numel() for p in model.parameters())/1e9:.2f}B')
410
+
411
+ if torch.cuda.is_available():
412
+ for i in range(torch.cuda.device_count()):
413
+ free, total = torch.cuda.mem_get_info(i)
414
+ log(f' GPU{i}: {(total-free)/1e9:.1f}/{total/1e9:.0f} GB used')
415
+
416
+ log('=== Ready ===')
417
+
418
+
419
+ log(f'=== {MODEL_NAME} API Server starting ===')
420
+ log(f' MODEL_ID: {MODEL_ID}')
421
+ log(f' QUANT_MODE: {QUANT_MODE}')
422
+ log(f' API_KEYS: {len(API_KEYS)} configured (auth {"required" if API_KEYS else "DISABLED β€” public"})')
423
+ log(f' HF_TOKEN: {"set" if HF_TOKEN else "(none)"}')
424
+
425
+ # Launch model load in background thread (uvicorn starts immediately, /health works)
426
+ threading.Thread(target=load_model, daemon=True).start()
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.115.0
2
+ uvicorn[standard]==0.32.0
3
+ pydantic==2.9.2
4
+ transformers>=4.46.0
5
+ accelerate>=1.0.0
6
+ bitsandbytes>=0.44.0
7
+ sentencepiece
8
+ protobuf
9
+ Pillow
10
+ hf_transfer
11
+ huggingface_hub>=0.26.0