coder5809 commited on
Commit
2aaacbe
·
verified ·
1 Parent(s): 06c2dd2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import spaces
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+
6
+ # Load model & tokenizer outside the decorated function to keep them in RAM
7
+ model_id = "Qwen/Qwen2.5-1.5B-Instruct"
8
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ model_id,
11
+ torch_dtype=torch.bfloat16,
12
+ device_map="auto"
13
+ )
14
+
15
+ # The @spaces.GPU decorator requests temporary GPU access only when a user sends a prompt
16
+ @spaces.GPU
17
+ def generate(prompt, max_new_tokens=512, temperature=0.7):
18
+ messages = [
19
+ {"role": "system", "content": "You are a helpful assistant."},
20
+ {"role": "user", "content": prompt}
21
+ ]
22
+
23
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
24
+ model_inputs = tokenizer([text], return_tensors="pt").to("cuda")
25
+
26
+ generated_ids = model.generate(
27
+ **model_inputs,
28
+ max_new_tokens=max_new_tokens,
29
+ temperature=temperature
30
+ )
31
+
32
+ generated_ids = [
33
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
34
+ ]
35
+
36
+ return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
37
+
38
+ # Build the Gradio Web Interface
39
+ demo = gr.Interface(
40
+ fn=generate,
41
+ inputs=[
42
+ gr.Textbox(lines=4, placeholder="Enter your prompt here..."),
43
+ gr.Slider(64, 1024, value=512, label="Max New Tokens"),
44
+ gr.Slider(0.1, 1.0, value=0.7, label="Temperature")
45
+ ],
46
+ outputs="text",
47
+ title="Free ZeroGPU LLM Playground"
48
+ )
49
+
50
+ if __name__ == "__main__":
51
+ demo.launch()