File size: 3,924 Bytes
e51984f
 
94273af
 
 
 
e51984f
 
 
 
 
 
 
94273af
e51984f
94273af
e51984f
 
94273af
e51984f
94273af
 
 
e51984f
94273af
 
 
e51984f
 
 
94273af
e51984f
 
94273af
e51984f
94273af
 
 
e51984f
94273af
e51984f
 
94273af
 
 
e51984f
94273af
e51984f
94273af
 
 
 
e51984f
94273af
e51984f
94273af
e51984f
 
 
94273af
e51984f
 
94273af
 
 
 
e51984f
 
 
94273af
 
 
e51984f
94273af
e51984f
94273af
e51984f
94273af
e51984f
94273af
e51984f
94273af
e51984f
 
 
 
 
 
 
 
94273af
e51984f
94273af
 
 
e51984f
 
 
 
 
 
 
94273af
e51984f
 
94273af
 
 
 
e51984f
94273af
e51984f
94273af
 
 
 
 
 
e51984f
94273af
e51984f
94273af
 
 
 
 
 
 
e51984f
 
94273af
e51984f
94273af
e51984f
94273af
 
 
 
e51984f
94273af
 
 
e51984f
 
94273af
 
 
e51984f
94273af
 
e51984f
94273af
 
 
 
 
 
 
 
 
e51984f
 
 
94273af
e51984f
 
 
 
94273af
e51984f
 
 
 
 
 
94273af
e51984f
 
94273af
e51984f
 
94273af
e51984f
 
 
 
94273af
 
e51984f
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
import os
import torch
import uvicorn

from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForCausalLM


# ============================================================
# CONFIG
# ============================================================

MODEL_PATH = "./gemma3-270m-merged"

CPU_THREADS = int(os.environ.get("CPU_THREADS", "8"))

torch.set_num_threads(CPU_THREADS)
torch.set_num_interop_threads(2)

print("=" * 70)
print("        GEMMA 3 270M CPU API SERVER")
print("=" * 70)

print(f"Model: {MODEL_PATH}")
print("Device: cpu")
print(f"CPU threads: {CPU_THREADS}")


# ============================================================
# LOAD TOKENIZER
# ============================================================

print("\nLoading tokenizer...")

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_PATH
)

print("Tokenizer loaded.")


# ============================================================
# LOAD MODEL
# ============================================================

print("\nLoading model...")

model = AutoModelForCausalLM.from_pretrained(
    MODEL_PATH,
    dtype=torch.float32
)

model.eval()

print("Model loaded successfully.")


# ============================================================
# FASTAPI
# ============================================================

app = FastAPI(
    title="Gemma 3 270M API",
    version="1.0.0",
    description="CPU inference API for Gemma 3 270M"
)


# ============================================================
# REQUEST FORMAT
# ============================================================

class ChatRequest(BaseModel):

    message: str

    max_new_tokens: int = 128

    temperature: float = 0.7

    top_p: float = 0.9


# ============================================================
# HEALTH
# ============================================================

@app.get("/health")
def health():

    return {
        "status": "ok",
        "model": "Gemma 3 270M",
        "device": "cpu"
    }


# ============================================================
# CHAT
# ============================================================

@app.post("/v1/chat")
def chat(request: ChatRequest):

    messages = [
        {
            "role": "user",
            "content": request.message
        }
    ]

    inputs = tokenizer.apply_chat_template(
        messages,
        tokenize=True,
        add_generation_prompt=True,
        return_tensors="pt"
    )

    with torch.inference_mode():

        outputs = model.generate(
            input_ids=inputs,
            max_new_tokens=request.max_new_tokens,
            temperature=request.temperature,
            top_p=request.top_p,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id
        )

    input_length = inputs.shape[-1]

    generated_tokens = outputs[0][input_length:]

    response = tokenizer.decode(
        generated_tokens,
        skip_special_tokens=True
    )

    return {
        "response": response
    }


# ============================================================
# ROOT
# ============================================================

@app.get("/")
def root():

    return {
        "name": "Gemma 3 270M API",
        "status": "online",
        "endpoints": {
            "chat": "POST /v1/chat",
            "health": "GET /health",
            "docs": "GET /docs"
        }
    }


# ============================================================
# START
# ============================================================

if __name__ == "__main__":

    print("\n" + "=" * 70)
    print("SERVER READY")
    print("=" * 70)

    print("API:")
    print("POST /v1/chat")

    print("\nHealth:")
    print("GET /health")

    print("\nSwagger:")
    print("GET /docs")

    print("\nStarting server...")

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=7860,
        log_level="info"
    )