Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces # nur importieren wenn ZeroGPU verfügbar
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
|
| 7 |
+
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL)
|
| 9 |
+
|
| 10 |
+
# Fallback: versuche CUDA, sonst CPU
|
| 11 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
+
model = AutoModelForCausalLM.from_pretrained(MODEL).to(device)
|
| 13 |
+
|
| 14 |
+
@spaces.GPU(duration=30) # ZeroGPU decorator — wird ignoriert wenn kein GPU da
|
| 15 |
+
def generate(prompt, max_new_tokens=200):
|
| 16 |
+
messages = [{"role": "user", "content": prompt}]
|
| 17 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False)
|
| 18 |
+
inputs = tokenizer.encode(text, return_tensors="pt").to(device)
|
| 19 |
+
|
| 20 |
+
with torch.no_grad():
|
| 21 |
+
outputs = model.generate(
|
| 22 |
+
inputs,
|
| 23 |
+
max_new_tokens=max_new_tokens,
|
| 24 |
+
temperature=0.2,
|
| 25 |
+
top_p=0.9,
|
| 26 |
+
do_sample=True,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# nur neue tokens zurückgeben
|
| 30 |
+
new_tokens = outputs[0][inputs.shape[-1]:]
|
| 31 |
+
return tokenizer.decode(new_tokens, skip_special_tokens=True)
|
| 32 |
+
|
| 33 |
+
demo = gr.Interface(fn=generate, inputs="text", outputs="text")
|
| 34 |
+
demo.launch()
|