Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,145 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
import os # For Hugging Face token
|
5 |
|
6 |
+
# Import spaces for ZeroGPU if you need to decorate specific functions
|
7 |
+
# For models loaded via transformers and run on a device managed by ZeroGPU,
|
8 |
+
# explicit @spaces.GPU might not always be needed directly on the inference function
|
9 |
+
# if the entire space is on ZeroGPU hardware. However, for clarity or complex setups:
|
10 |
+
# import spaces # Uncomment if using @spaces.GPU decorator
|
11 |
|
12 |
+
# --- Configuration ---
|
13 |
+
HF_TOKEN = os.getenv("HF_TOKEN") # Recommended to store your Hugging Face token as a Space secret
|
14 |
+
|
15 |
+
MODEL_OPTIONS = {
|
16 |
+
"Qwen1.5-1.8B-Chat": "Qwen/Qwen1.5-1.8B-Chat",
|
17 |
+
"Qwen2.5-Coder-3B": "Qwen/Qwen2.5-Coder-3B", # Example for a Qwen code model around 3B params
|
18 |
+
}
|
19 |
+
|
20 |
+
# --- Model Loading Cache ---
|
21 |
+
# This dictionary will cache loaded models and tokenizers to avoid reloading on every call
|
22 |
+
loaded_models = {}
|
23 |
+
|
24 |
+
def get_model_and_tokenizer(model_name_key):
|
25 |
+
if model_name_key not in loaded_models:
|
26 |
+
model_id = MODEL_OPTIONS[model_name_key]
|
27 |
+
print(f"Loading model: {model_id}...")
|
28 |
+
try:
|
29 |
+
# Ensure you have accepted the terms of use for these models on Hugging Face Hub
|
30 |
+
model = AutoModelForCausalLM.from_pretrained(
|
31 |
+
model_id,
|
32 |
+
torch_dtype="auto", # Let transformers decide the best dtype
|
33 |
+
device_map="auto", # Automatically maps model to available device (GPU on ZeroGPU)
|
34 |
+
token=HF_TOKEN # Use token if model is private or requires it
|
35 |
+
)
|
36 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
|
37 |
+
loaded_models[model_name_key] = (model, tokenizer)
|
38 |
+
print(f"Model {model_id} loaded successfully.")
|
39 |
+
except Exception as e:
|
40 |
+
print(f"Error loading model {model_id}: {e}")
|
41 |
+
# Fallback or error handling
|
42 |
+
if model_name_key in loaded_models: # Remove if partially loaded
|
43 |
+
del loaded_models[model_name_key]
|
44 |
+
raise gr.Error(f"Failed to load model {model_name_key}. Please check the model ID and your Hugging Face token permissions. Error: {e}")
|
45 |
+
return loaded_models[model_name_key]
|
46 |
+
|
47 |
+
# --- Inference Function ---
|
48 |
+
# If you need finer-grained control over GPU allocation for specific parts:
|
49 |
+
# @spaces.GPU(duration=120) # Example: Request GPU for 120 seconds for this function
|
50 |
+
def generate_response(prompt_text, model_choice, max_new_tokens=512, temperature=0.7, top_p=0.9):
|
51 |
+
if not prompt_text:
|
52 |
+
return "Please enter a prompt."
|
53 |
+
if not model_choice:
|
54 |
+
return "Please select a model."
|
55 |
+
|
56 |
+
try:
|
57 |
+
model, tokenizer = get_model_and_tokenizer(model_choice)
|
58 |
+
except Exception as e:
|
59 |
+
return str(e) # Display loading error to user
|
60 |
+
|
61 |
+
device = model.device # Get the device the model is on
|
62 |
+
|
63 |
+
if "Chat" in model_choice: # Apply chat template for chat models
|
64 |
+
messages = [
|
65 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
66 |
+
{"role": "user", "content": prompt_text}
|
67 |
+
]
|
68 |
+
try:
|
69 |
+
input_text = tokenizer.apply_chat_template(
|
70 |
+
messages,
|
71 |
+
tokenize=False,
|
72 |
+
add_generation_prompt=True
|
73 |
+
)
|
74 |
+
except Exception as e: # Fallback if apply_chat_template has issues or is not applicable
|
75 |
+
print(f"Warning: Could not apply chat template for {model_choice}: {e}. Using prompt as is.")
|
76 |
+
input_text = prompt_text
|
77 |
+
|
78 |
+
else: # For code or non-chat models, use the prompt directly or adjust as needed
|
79 |
+
input_text = prompt_text
|
80 |
+
|
81 |
+
model_inputs = tokenizer([input_text], return_tensors="pt").to(device)
|
82 |
+
|
83 |
+
try:
|
84 |
+
generated_ids = model.generate(
|
85 |
+
model_inputs.input_ids,
|
86 |
+
max_new_tokens=max_new_tokens,
|
87 |
+
temperature=temperature,
|
88 |
+
top_p=top_p,
|
89 |
+
do_sample=True # Necessary for temperature and top_p to have an effect
|
90 |
+
)
|
91 |
+
# For some models, the input prompt is included in the generated_ids.
|
92 |
+
# We need to decode only the newly generated tokens.
|
93 |
+
# This slicing can vary based on the model and tokenizer.
|
94 |
+
# A common approach is to slice based on the input_ids length:
|
95 |
+
response_ids = generated_ids[0][model_inputs.input_ids.shape[-1]:]
|
96 |
+
response_text = tokenizer.decode(response_ids, skip_special_tokens=True)
|
97 |
+
|
98 |
+
except Exception as e:
|
99 |
+
print(f"Error during generation with {model_choice}: {e}")
|
100 |
+
return f"Error generating response: {e}"
|
101 |
+
|
102 |
+
return response_text
|
103 |
+
|
104 |
+
# --- Gradio Interface ---
|
105 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
106 |
+
gr.Markdown("# LLM Coding & Math Experiment")
|
107 |
+
gr.Markdown("Query Qwen1.5-1.8B-Chat or Qwen Code models using ZeroGPU.")
|
108 |
+
|
109 |
+
with gr.Row():
|
110 |
+
model_dropdown = gr.Dropdown(
|
111 |
+
label="Select Model",
|
112 |
+
choices=list(MODEL_OPTIONS.keys()),
|
113 |
+
value=list(MODEL_OPTIONS.keys())[0] # Default to the first model
|
114 |
+
)
|
115 |
+
with gr.Row():
|
116 |
+
prompt_input = gr.Textbox(label="Enter your prompt:", lines=4, placeholder="e.g., Write a Python function to calculate factorial, or What is the capital of France?")
|
117 |
+
with gr.Row():
|
118 |
+
output_text = gr.Textbox(label="Model Response:", lines=8, interactive=False)
|
119 |
+
|
120 |
+
with gr.Row():
|
121 |
+
submit_button = gr.Button("Generate Response", variant="primary")
|
122 |
+
|
123 |
+
with gr.Accordion("Advanced Settings", open=False):
|
124 |
+
max_new_tokens_slider = gr.Slider(minimum=32, maximum=2048, value=512, step=32, label="Max New Tokens")
|
125 |
+
temperature_slider = gr.Slider(minimum=0.1, maximum=1.5, value=0.7, step=0.05, label="Temperature")
|
126 |
+
top_p_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-P")
|
127 |
+
|
128 |
+
|
129 |
+
# Event listener for the button
|
130 |
+
submit_button.click(
|
131 |
+
fn=generate_response,
|
132 |
+
inputs=[prompt_input, model_dropdown, max_new_tokens_slider, temperature_slider, top_p_slider],
|
133 |
+
outputs=output_text,
|
134 |
+
api_name="generate" # Exposes an API endpoint
|
135 |
+
)
|
136 |
+
|
137 |
+
gr.Markdown("## Notes:")
|
138 |
+
gr.Markdown(
|
139 |
+
"- Ensure you have accepted the terms of use for the selected Qwen models on the Hugging Face Hub.\n"
|
140 |
+
"- Model loading can take some time, especially on the first run or when switching models.\n"
|
141 |
+
"- This Space runs on ZeroGPU, which means GPU resources are allocated dynamically."
|
142 |
+
)
|
143 |
+
|
144 |
+
if __name__ == "__main__":
|
145 |
+
demo.launch()
|