Spaces:
Configuration error
Configuration error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,27 +1,46 @@
|
|
| 1 |
-
|
| 2 |
import gradio as gr
|
| 3 |
-
from
|
| 4 |
-
import
|
|
|
|
| 5 |
|
| 6 |
-
MODEL = "google/gemma-4-E4B"
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
device_map={"": "cpu"},
|
| 13 |
-
torch_dtype=torch.float32,
|
| 14 |
-
low_cpu_mem_usage=True,
|
| 15 |
-
trust_remote_code=True
|
| 16 |
-
)
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
def generate(prompt):
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
| 22 |
return out[0]["generated_text"]
|
| 23 |
|
| 24 |
-
demo = gr.Interface(fn=generate, inputs=gr.Textbox(lines=4, label="Prompt"), outputs="text", title="Gemma
|
| 25 |
|
| 26 |
app = FastAPI()
|
| 27 |
app = gr.mount_gradio_app(app, demo, path="/")
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
from fastapi import FastAPI
|
| 4 |
+
from transformers import AutoTokenizer, pipeline
|
| 5 |
+
import threading
|
| 6 |
|
| 7 |
+
MODEL = os.environ.get("MODEL_NAME", "google/gemma-4-E4B")
|
| 8 |
+
# Para Space gr谩tis, defina MODEL_NAME=google/gemma-4-E2B no settings se E4B falhar.
|
| 9 |
|
| 10 |
+
tokenizer = None
|
| 11 |
+
generator = None
|
| 12 |
+
_model_lock = threading.Lock()
|
| 13 |
+
_loading = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
def load_model():
|
| 16 |
+
global tokenizer, generator, _loading
|
| 17 |
+
with _model_lock:
|
| 18 |
+
if tokenizer is not None and generator is not None:
|
| 19 |
+
return
|
| 20 |
+
_loading = True
|
| 21 |
+
try:
|
| 22 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True)
|
| 23 |
+
# carregamento em CPU
|
| 24 |
+
from transformers import AutoModelForCausalLM
|
| 25 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 26 |
+
MODEL,
|
| 27 |
+
device_map={"": "cpu"},
|
| 28 |
+
torch_dtype="float32",
|
| 29 |
+
low_cpu_mem_usage=True,
|
| 30 |
+
trust_remote_code=True
|
| 31 |
+
)
|
| 32 |
+
generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=-1)
|
| 33 |
+
finally:
|
| 34 |
+
_loading = False
|
| 35 |
|
| 36 |
def generate(prompt):
|
| 37 |
+
if generator is None:
|
| 38 |
+
load_model()
|
| 39 |
+
# limite de tokens para reduzir uso de mem贸ria
|
| 40 |
+
out = generator(prompt, max_new_tokens=64, do_sample=False)
|
| 41 |
return out[0]["generated_text"]
|
| 42 |
|
| 43 |
+
demo = gr.Interface(fn=generate, inputs=gr.Textbox(lines=4, label="Prompt"), outputs="text", title="Gemma (Space CPU)")
|
| 44 |
|
| 45 |
app = FastAPI()
|
| 46 |
app = gr.mount_gradio_app(app, demo, path="/")
|