Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
|
5 |
+
MODEL_NAME = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
6 |
+
|
7 |
+
# Load tokenizer and model
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
9 |
+
if tokenizer.pad_token is None:
|
10 |
+
tokenizer.pad_token = tokenizer.eos_token
|
11 |
+
|
12 |
+
model = AutoModelForCausalLM.from_pretrained(
|
13 |
+
MODEL_NAME,
|
14 |
+
torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
|
15 |
+
)
|
16 |
+
if torch.cuda.is_available():
|
17 |
+
model.to("cuda")
|
18 |
+
model.eval()
|
19 |
+
|
20 |
+
def generate_text(prompt, max_new_tokens=100, temperature=0.7, top_k=50):
|
21 |
+
if not prompt:
|
22 |
+
return "Please enter a prompt."
|
23 |
+
|
24 |
+
messages = [{"role": "user", "content": prompt}]
|
25 |
+
encoded = tokenizer.apply_chat_template(
|
26 |
+
messages,
|
27 |
+
add_generation_prompt=True,
|
28 |
+
return_tensors="pt",
|
29 |
+
padding=True,
|
30 |
+
return_attention_mask=True,
|
31 |
+
)
|
32 |
+
|
33 |
+
input_ids = encoded["input_ids"]
|
34 |
+
attention_mask = encoded["attention_mask"]
|
35 |
+
|
36 |
+
if torch.cuda.is_available():
|
37 |
+
input_ids = input_ids.to("cuda")
|
38 |
+
attention_mask = attention_mask.to("cuda")
|
39 |
+
|
40 |
+
output_ids = model.generate(
|
41 |
+
input_ids,
|
42 |
+
attention_mask=attention_mask,
|
43 |
+
max_new_tokens=max_new_tokens,
|
44 |
+
do_sample=True,
|
45 |
+
temperature=temperature,
|
46 |
+
top_k=top_k,
|
47 |
+
pad_token_id=tokenizer.eos_token_id
|
48 |
+
)
|
49 |
+
|
50 |
+
response = tokenizer.decode(output_ids[0][input_ids.shape[-1]:], skip_special_tokens=True)
|
51 |
+
return response
|
52 |
+
|
53 |
+
# Gradio interface
|
54 |
+
demo = gr.Interface(
|
55 |
+
fn=generate_text,
|
56 |
+
inputs=[
|
57 |
+
gr.Textbox(label="Prompt"),
|
58 |
+
gr.Slider(minimum=10, maximum=500, value=100, label="Max New Tokens"),
|
59 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.05, label="Temperature"),
|
60 |
+
gr.Slider(minimum=0, maximum=100, value=50, step=1, label="Top K")
|
61 |
+
],
|
62 |
+
outputs=gr.Textbox(label="Generated Text"),
|
63 |
+
title="TinyLlama Gradio API",
|
64 |
+
description="Use this via UI or API via `/run/predict`"
|
65 |
+
)
|
66 |
+
|
67 |
+
if __name__ == "__main__":
|
68 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|