Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,154 +1,176 @@
|
|
1 |
import gradio as gr
|
2 |
-
import numpy as np
|
3 |
-
import random
|
4 |
-
|
5 |
-
# import spaces #[uncomment to use ZeroGPU]
|
6 |
-
from diffusers import DiffusionPipeline
|
7 |
import torch
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
):
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
"An astronaut riding a green horse",
|
57 |
-
"A delicious ceviche cheesecake slice",
|
58 |
-
]
|
59 |
-
|
60 |
-
css = """
|
61 |
-
#col-container {
|
62 |
-
margin: 0 auto;
|
63 |
-
max-width: 640px;
|
64 |
-
}
|
65 |
-
"""
|
66 |
-
|
67 |
-
with gr.Blocks(css=css) as demo:
|
68 |
-
with gr.Column(elem_id="col-container"):
|
69 |
-
gr.Markdown(" # Text-to-Image Gradio Template")
|
70 |
-
|
71 |
-
with gr.Row():
|
72 |
-
prompt = gr.Text(
|
73 |
-
label="Prompt",
|
74 |
-
show_label=False,
|
75 |
-
max_lines=1,
|
76 |
-
placeholder="Enter your prompt",
|
77 |
-
container=False,
|
78 |
)
|
79 |
|
80 |
-
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
90 |
)
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
minimum=0,
|
95 |
-
maximum=MAX_SEED,
|
96 |
-
step=1,
|
97 |
-
value=0,
|
98 |
)
|
|
|
|
|
99 |
|
100 |
-
|
101 |
-
|
|
|
102 |
with gr.Row():
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
value=1024, # Replace with defaults that work for your model
|
117 |
-
)
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
value=0.0, # Replace with defaults that work for your model
|
126 |
-
)
|
127 |
-
|
128 |
-
num_inference_steps = gr.Slider(
|
129 |
-
label="Number of inference steps",
|
130 |
-
minimum=1,
|
131 |
-
maximum=50,
|
132 |
-
step=1,
|
133 |
-
value=2, # Replace with defaults that work for your model
|
134 |
-
)
|
135 |
-
|
136 |
-
gr.Examples(examples=examples, inputs=[prompt])
|
137 |
-
gr.on(
|
138 |
-
triggers=[run_button.click, prompt.submit],
|
139 |
-
fn=infer,
|
140 |
-
inputs=[
|
141 |
-
prompt,
|
142 |
-
negative_prompt,
|
143 |
-
seed,
|
144 |
-
randomize_seed,
|
145 |
-
width,
|
146 |
-
height,
|
147 |
-
guidance_scale,
|
148 |
-
num_inference_steps,
|
149 |
-
],
|
150 |
-
outputs=[result, seed],
|
151 |
)
|
152 |
|
|
|
|
|
153 |
if __name__ == "__main__":
|
154 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
2 |
import torch
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig # Example for LLM
|
4 |
+
# from diffusers import StableDiffusionPipeline # Example for Diffusion
|
5 |
+
from peft import PeftModel
|
6 |
+
import accelerate # Often needed for device_map='auto'
|
7 |
+
import os
|
8 |
+
import time # For basic timing/feedback
|
9 |
+
|
10 |
+
# --- Global Placeholder (Alternative: Use gr.State for cleaner state management) ---
|
11 |
+
# We will use gr.State in the Blocks interface, which is generally preferred.
|
12 |
+
# loaded_model = None
|
13 |
+
# loaded_tokenizer = None
|
14 |
+
|
15 |
+
# --- Model Loading Function ---
|
16 |
+
def load_models(base_model_id, lora_model_id, progress=gr.Progress(track_tqdm=True)):
|
17 |
+
"""Loads the base model and applies the LoRA adapter."""
|
18 |
+
global loaded_model, loaded_tokenizer # If not using gr.State
|
19 |
+
model = None
|
20 |
+
tokenizer = None
|
21 |
+
status = "Starting model loading..."
|
22 |
+
progress(0, desc=status)
|
23 |
+
print(status)
|
24 |
+
|
25 |
+
if not base_model_id or not lora_model_id:
|
26 |
+
return None, None, "Error: Base Model ID and LoRA Model ID cannot be empty."
|
27 |
+
|
28 |
+
try:
|
29 |
+
# --- Load Base Model Tokenizer (for LLMs) ---
|
30 |
+
status = f"Loading tokenizer for {base_model_id}..."
|
31 |
+
progress(0.1, desc=status)
|
32 |
+
print(status)
|
33 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
|
34 |
+
if tokenizer.pad_token is None:
|
35 |
+
print("Setting pad_token to eos_token")
|
36 |
+
tokenizer.pad_token = tokenizer.eos_token
|
37 |
+
|
38 |
+
# --- Load Base Model ---
|
39 |
+
# Add quantization or other configs if needed
|
40 |
+
status = f"Loading base model: {base_model_id}..."
|
41 |
+
progress(0.3, desc=status)
|
42 |
+
print(status)
|
43 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
44 |
+
base_model_id,
|
45 |
+
torch_dtype=torch.bfloat16, # Or float16
|
46 |
+
device_map="auto",
|
47 |
+
trust_remote_code=True
|
48 |
+
)
|
49 |
+
progress(0.7, desc="Base model loaded.")
|
50 |
+
print("Base model loaded.")
|
51 |
+
|
52 |
+
# --- Load LoRA Adapter ---
|
53 |
+
status = f"Loading LoRA adapter: {lora_model_id}..."
|
54 |
+
progress(0.8, desc=status)
|
55 |
+
print(status)
|
56 |
+
model = PeftModel.from_pretrained(
|
57 |
+
base_model,
|
58 |
+
lora_model_id,
|
59 |
+
)
|
60 |
+
progress(0.95, desc="LoRA adapter applied.")
|
61 |
+
print("PEFT LoRA model loaded.")
|
62 |
+
|
63 |
+
model.eval() # Set model to evaluation mode
|
64 |
+
status = "Models loaded successfully!"
|
65 |
+
progress(1.0, desc=status)
|
66 |
+
print(status)
|
67 |
+
# Return the loaded model and tokenizer to be stored in gr.State
|
68 |
+
return model, tokenizer, status
|
69 |
+
|
70 |
+
except Exception as e:
|
71 |
+
error_msg = f"Error loading models: {str(e)}"
|
72 |
+
print(error_msg)
|
73 |
+
# Ensure we return None for model/tokenizer on error
|
74 |
+
return None, None, error_msg
|
75 |
+
|
76 |
+
# --- Inference Function ---
|
77 |
+
def generate_text(
|
78 |
+
state_model, state_tokenizer, # Receive model/tokenizer from gr.State
|
79 |
+
prompt, max_new_tokens, temperature,
|
80 |
+
progress=gr.Progress(track_tqdm=True)
|
81 |
):
|
82 |
+
"""Generates text using the loaded model."""
|
83 |
+
if state_model is None or state_tokenizer is None:
|
84 |
+
return "Error: Models not loaded. Please load models first."
|
85 |
+
|
86 |
+
status = "Tokenizing prompt..."
|
87 |
+
progress(0.1, desc=status)
|
88 |
+
print(status)
|
89 |
+
try:
|
90 |
+
inputs = state_tokenizer(prompt, return_tensors="pt").to(state_model.device)
|
91 |
+
|
92 |
+
status = "Generating text..."
|
93 |
+
progress(0.3, desc=status)
|
94 |
+
print(status)
|
95 |
+
with torch.no_grad():
|
96 |
+
outputs = state_model.generate(
|
97 |
+
**inputs,
|
98 |
+
max_new_tokens=int(max_new_tokens), # Ensure it's int
|
99 |
+
temperature=float(temperature), # Ensure it's float
|
100 |
+
pad_token_id=state_tokenizer.pad_token_id
|
101 |
+
# Add other parameters like top_k, top_p if desired
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
)
|
103 |
|
104 |
+
status = "Decoding output..."
|
105 |
+
progress(0.9, desc=status)
|
106 |
+
print(status)
|
107 |
+
result = state_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
108 |
+
progress(1.0, desc="Generation complete.")
|
109 |
+
print("Generation complete.")
|
110 |
+
return result
|
111 |
+
|
112 |
+
except Exception as e:
|
113 |
+
error_msg = f"Error during generation: {str(e)}"
|
114 |
+
print(error_msg)
|
115 |
+
return error_msg
|
116 |
+
|
117 |
+
|
118 |
+
# --- Gradio Interface Definition ---
|
119 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
120 |
+
# Using gr.State to hold the loaded model and tokenizer objects
|
121 |
+
# This state persists within the user's session
|
122 |
+
model_state = gr.State(None)
|
123 |
+
tokenizer_state = gr.State(None)
|
124 |
+
|
125 |
+
gr.Markdown("# 🎛️ Dynamic LoRA Model Loader & Generator (Gradio)")
|
126 |
+
gr.Markdown(
|
127 |
+
"Enter the Hugging Face IDs for the base model and your LoRA adapter repository. "
|
128 |
+
"Then, load the models and generate text."
|
129 |
+
"\n**Note:** Ensure your LoRA file is named appropriately (e.g., `adapter_model.safetensors` or specify filename if loader supports it) and your Space has adequate hardware (GPU recommended)."
|
130 |
+
)
|
131 |
|
132 |
+
with gr.Row():
|
133 |
+
with gr.Column(scale=1):
|
134 |
+
gr.Markdown("## Configuration")
|
135 |
+
base_model_input = gr.Textbox(
|
136 |
+
label="Base Model ID (Hugging Face)",
|
137 |
+
placeholder="e.g., meta-llama/Meta-Llama-3-8B",
|
138 |
+
value="meta-llama/Meta-Llama-3-8B" # Example default
|
139 |
)
|
140 |
+
lora_model_input = gr.Textbox(
|
141 |
+
label="LoRA Model ID (Hugging Face - where lora.safetensors is)",
|
142 |
+
placeholder="e.g., YourUsername/YourLoraRepo"
|
|
|
|
|
|
|
|
|
143 |
)
|
144 |
+
load_button = gr.Button("Load Models", variant="primary")
|
145 |
+
status_output = gr.Textbox(label="Loading Status", interactive=False)
|
146 |
|
147 |
+
with gr.Column(scale=2):
|
148 |
+
gr.Markdown("## Inference")
|
149 |
+
prompt_input = gr.Textbox(label="Enter Prompt:", lines=5, placeholder="Once upon a time...")
|
150 |
with gr.Row():
|
151 |
+
max_tokens_slider = gr.Slider(label="Max New Tokens", minimum=10, maximum=1024, value=200, step=10)
|
152 |
+
temp_slider = gr.Slider(label="Temperature", minimum=0.1, maximum=1.5, value=0.7, step=0.05)
|
153 |
+
generate_button = gr.Button("Generate Text", variant="primary")
|
154 |
+
generated_output = gr.Textbox(label="Generated Output", lines=10, interactive=False)
|
155 |
+
|
156 |
+
# --- Connect Actions ---
|
157 |
+
load_button.click(
|
158 |
+
fn=load_models,
|
159 |
+
inputs=[base_model_input, lora_model_input],
|
160 |
+
# Outputs: model state, tokenizer state, status message textbox
|
161 |
+
outputs=[model_state, tokenizer_state, status_output],
|
162 |
+
show_progress="full" # Show progress bar
|
163 |
+
)
|
|
|
|
|
164 |
|
165 |
+
generate_button.click(
|
166 |
+
fn=generate_text,
|
167 |
+
# Inputs: model state, tokenizer state, prompt, sliders
|
168 |
+
inputs=[model_state, tokenizer_state, prompt_input, max_tokens_slider, temp_slider],
|
169 |
+
outputs=[generated_output], # Output: generated text textbox
|
170 |
+
show_progress="full" # Show progress bar
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
)
|
172 |
|
173 |
+
# --- Launch the Gradio App ---
|
174 |
+
# HF Spaces automatically runs this when deploying app.py
|
175 |
if __name__ == "__main__":
|
176 |
+
demo.launch() # Use share=True for a public link if running locally
|