Spaces:
Runtime error
Runtime error
File size: 6,817 Bytes
a7e85e8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
import os
import time
import uuid
from typing import List, Optional, Dict, Any
import torch
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse
from pydantic import BaseModel, Field
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_ID = os.getenv("MODEL_ID", "LiquidAI/LFM2-1.2B")
DEFAULT_MAX_TOKENS = int(os.getenv("MAX_TOKENS", "256"))
app = FastAPI(title="OpenAI-compatible API for LiquidAI/LFM2-1.2B")
tokenizer = None
model = None
def get_dtype() -> torch.dtype:
if torch.cuda.is_available():
# Prefer bfloat16 if supported; else float16
if torch.cuda.is_bf16_supported():
return torch.bfloat16
return torch.float16
# CPU
return torch.float32
@app.on_event("startup")
def load_model():
global tokenizer, model
dtype = get_dtype()
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=True, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=dtype,
device_map="auto",
trust_remote_code=True,
)
# Ensure eos/bos tokens exist
if tokenizer.eos_token is None:
tokenizer.eos_token = tokenizer.sep_token or tokenizer.pad_token or "</s>"
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
class ChatMessage(BaseModel):
role: str
content: str
class ChatCompletionRequest(BaseModel):
model: Optional[str] = Field(default=MODEL_ID)
messages: List[ChatMessage]
temperature: Optional[float] = 0.7
top_p: Optional[float] = 0.95
max_tokens: Optional[int] = None
stop: Optional[List[str] | str] = None
n: Optional[int] = 1
class CompletionRequest(BaseModel):
model: Optional[str] = Field(default=MODEL_ID)
prompt: str | List[str]
temperature: Optional[float] = 0.7
top_p: Optional[float] = 0.95
max_tokens: Optional[int] = None
stop: Optional[List[str] | str] = None
n: Optional[int] = 1
class Usage(BaseModel):
prompt_tokens: int
completion_tokens: int
total_tokens: int
# Simple chat prompt formatter
def build_chat_prompt(messages: List[ChatMessage]) -> str:
system_prefix = "You are a helpful assistant."
system_msgs = [m.content for m in messages if m.role == "system"]
if system_msgs:
system_prefix = system_msgs[-1]
conv: List[str] = [f"System: {system_prefix}"]
for m in messages:
if m.role == "system":
continue
role = "User" if m.role == "user" else ("Assistant" if m.role == "assistant" else m.role.capitalize())
conv.append(f"{role}: {m.content}")
conv.append("Assistant:")
return "\n".join(conv)
def apply_stop_sequences(text: str, stop: Optional[List[str] | str]) -> str:
if stop is None:
return text
stops = stop if isinstance(stop, list) else [stop]
cut = len(text)
for s in stops:
if not s:
continue
idx = text.find(s)
if idx != -1:
cut = min(cut, idx)
return text[:cut]
def generate_once(prompt: str, temperature: float, top_p: float, max_new_tokens: int) -> Dict[str, Any]:
assert tokenizer is not None and model is not None, "Model not loaded"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
gen_ids = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=True if temperature and temperature > 0 else False,
temperature=max(0.0, float(temperature or 0.0)),
top_p=max(0.0, float(top_p or 1.0)),
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
)
out = tokenizer.decode(gen_ids[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
return {
"text": out,
"prompt_tokens": inputs["input_ids"].numel(),
"completion_tokens": gen_ids[0].shape[0] - inputs["input_ids"].shape[-1],
}
@app.get("/")
def root():
return RedirectResponse(url="/docs")
@app.get("/health")
def health():
return {"status": "ok", "model": MODEL_ID}
@app.post("/v1/chat/completions")
def chat_completions(req: ChatCompletionRequest):
if req.n and req.n > 1:
raise HTTPException(status_code=400, detail="Only n=1 is supported in this simple server.")
max_new = req.max_tokens or DEFAULT_MAX_TOKENS
prompt = build_chat_prompt(req.messages)
g = generate_once(prompt, req.temperature or 0.7, req.top_p or 0.95, max_new)
text = apply_stop_sequences(g["text"], req.stop)
created = int(time.time())
comp_id = f"chatcmpl-{uuid.uuid4().hex[:24]}"
usage = Usage(
prompt_tokens=g["prompt_tokens"],
completion_tokens=g["completion_tokens"],
total_tokens=g["prompt_tokens"] + g["completion_tokens"],
)
return {
"id": comp_id,
"object": "chat.completion",
"created": created,
"model": req.model or MODEL_ID,
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": text},
"finish_reason": "stop",
}
],
"usage": usage.dict(),
}
@app.post("/v1/completions")
def completions(req: CompletionRequest):
if req.n and req.n > 1:
raise HTTPException(status_code=400, detail="Only n=1 is supported in this simple server.")
prompts = req.prompt if isinstance(req.prompt, list) else [req.prompt]
if len(prompts) != 1:
raise HTTPException(status_code=400, detail="Only a single prompt is supported in this simple server.")
max_new = req.max_tokens or DEFAULT_MAX_TOKENS
g = generate_once(prompts[0], req.temperature or 0.7, req.top_p or 0.95, max_new)
text = apply_stop_sequences(g["text"], req.stop)
created = int(time.time())
comp_id = f"cmpl-{uuid.uuid4().hex[:24]}"
usage = Usage(
prompt_tokens=g["prompt_tokens"],
completion_tokens=g["completion_tokens"],
total_tokens=g["prompt_tokens"] + g["completion_tokens"],
)
return {
"id": comp_id,
"object": "text_completion",
"created": created,
"model": req.model or MODEL_ID,
"choices": [
{
"index": 0,
"text": text,
"finish_reason": "stop",
"logprobs": None,
}
],
"usage": usage.dict(),
}
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", "7860"))
uvicorn.run("app:app", host="0.0.0.0", port=port, reload=False)
|