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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# llada_app.py -> dream_app.py
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
import gradio as gr
|
6 |
+
import spaces
|
7 |
+
# import torch.nn.functional as F # Not needed for DREAM's basic visualization
|
8 |
+
from transformers import AutoTokenizer, AutoModel
|
9 |
+
import time
|
10 |
+
import re # Keep for parsing constraints
|
11 |
+
|
12 |
+
# Use try-except for space deployment vs local
|
13 |
+
try:
|
14 |
+
# Used for spaces deployment with GPU
|
15 |
+
gpu_check = spaces.GPU
|
16 |
+
print("Running in Gradio Spaces with GPU environment.")
|
17 |
+
except AttributeError:
|
18 |
+
# Fallback for local execution or environments without spaces.GPU
|
19 |
+
print("Running in local environment or without spaces.GPU.")
|
20 |
+
# Define a dummy decorator if spaces.GPU is not available
|
21 |
+
def gpu_check(func):
|
22 |
+
return func
|
23 |
+
|
24 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
25 |
+
print(f"Using device: {device}")
|
26 |
+
|
27 |
+
# --- Load DREAM Model and Tokenizer ---
|
28 |
+
model_path = "Dream-org/Dream-v0-Instruct-7B"
|
29 |
+
print(f"Loading model: {model_path}")
|
30 |
+
model = AutoModel.from_pretrained(model_path, torch_dtype=torch.bfloat16, trust_remote_code=True).to(device).eval()
|
31 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
32 |
+
print("Model and tokenizer loaded.")
|
33 |
+
|
34 |
+
# --- Constants for DREAM ---
|
35 |
+
# Find the mask token and ID from the DREAM tokenizer
|
36 |
+
if tokenizer.mask_token is None:
|
37 |
+
# Handle cases where a mask token might not be explicitly set
|
38 |
+
# You might need to choose a suitable placeholder or investigate further
|
39 |
+
# For now, let's try adding one if it's missing and check its id
|
40 |
+
# This is speculative and might depend on the specific tokenizer setup
|
41 |
+
print("Warning: Mask token not found in tokenizer. Attempting to add.")
|
42 |
+
tokenizer.add_special_tokens({'mask_token': '[MASK]'})
|
43 |
+
model.resize_token_embeddings(len(tokenizer)) # Important if vocab size changed
|
44 |
+
if tokenizer.mask_token is None:
|
45 |
+
raise ValueError("Could not set a mask token for the tokenizer.")
|
46 |
+
|
47 |
+
MASK_TOKEN = tokenizer.mask_token
|
48 |
+
MASK_ID = tokenizer.mask_token_id
|
49 |
+
print(f"Using MASK_TOKEN='{MASK_TOKEN}' with ID={MASK_ID}")
|
50 |
+
# --- Helper Functions (Constraint Parsing, History Formatting) ---
|
51 |
+
|
52 |
+
def parse_constraints(constraints_text):
|
53 |
+
"""Parse constraints in format: 'position:word, position:word, ...'"""
|
54 |
+
constraints = {}
|
55 |
+
if not constraints_text:
|
56 |
+
return constraints
|
57 |
+
|
58 |
+
parts = constraints_text.split(',')
|
59 |
+
for part in parts:
|
60 |
+
part = part.strip() # Trim whitespace
|
61 |
+
if ':' not in part:
|
62 |
+
continue
|
63 |
+
try:
|
64 |
+
pos_str, word = part.split(':', 1)
|
65 |
+
pos = int(pos_str.strip())
|
66 |
+
word = word.strip()
|
67 |
+
# Allow empty words if needed, but usually we want a word
|
68 |
+
if word and pos >= 0:
|
69 |
+
constraints[pos] = word
|
70 |
+
except ValueError:
|
71 |
+
print(f"Warning: Could not parse constraint part: '{part}'")
|
72 |
+
continue
|
73 |
+
|
74 |
+
return constraints
|
75 |
+
|
76 |
+
def format_chat_history(history):
|
77 |
+
"""
|
78 |
+
Format chat history for the DREAM model (standard messages format)
|
79 |
+
|
80 |
+
Args:
|
81 |
+
history: List of [user_message, assistant_message] pairs
|
82 |
+
|
83 |
+
Returns:
|
84 |
+
Formatted conversation for the model (list of dictionaries)
|
85 |
+
"""
|
86 |
+
messages = []
|
87 |
+
# Add system prompt if desired (check DREAM examples/recommendations)
|
88 |
+
# messages.append({"role": "system", "content": "You are a helpful assistant."}) # Optional
|
89 |
+
for user_msg, assistant_msg in history:
|
90 |
+
if user_msg: # Handle potential None message if clearing failed
|
91 |
+
messages.append({"role": "user", "content": user_msg})
|
92 |
+
if assistant_msg: # Skip if None (for the latest user message awaiting response)
|
93 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
94 |
+
|
95 |
+
return messages
|
96 |
+
|
97 |
+
# --- Core Generation Logic for DREAM with Visualization ---
|
98 |
+
|
99 |
+
@gpu_check # Use the potentially dummy decorator
|
100 |
+
def dream_generate_response_with_visualization(
|
101 |
+
messages,
|
102 |
+
gen_length=64,
|
103 |
+
steps=64, # Default based on DREAM examples
|
104 |
+
constraints=None,
|
105 |
+
temperature=0.6, # Default based on DREAM examples
|
106 |
+
top_p=0.95, # Default based on DREAM examples
|
107 |
+
alg="entropy", # Default based on DREAM examples
|
108 |
+
alg_temp=0.0, # Default based on DREAM examples
|
109 |
+
):
|
110 |
+
"""
|
111 |
+
Generate text with DREAM model with visualization using the generation hook.
|
112 |
+
|
113 |
+
Args:
|
114 |
+
messages: List of message dictionaries with 'role' and 'content'
|
115 |
+
gen_length: Length of text to generate (max_new_tokens)
|
116 |
+
steps: Number of diffusion steps
|
117 |
+
constraints: Dictionary mapping positions (relative to response start) to words
|
118 |
+
temperature: Sampling temperature
|
119 |
+
top_p: Nucleus sampling p
|
120 |
+
alg: Remasking algorithm ('origin', 'maskgit_plus', 'topk_margin', 'entropy')
|
121 |
+
alg_temp: Temperature for confidence-based algorithms
|
122 |
+
|
123 |
+
Returns:
|
124 |
+
Tuple: (List of visualization states, final generated text string)
|
125 |
+
"""
|
126 |
+
print("--- Starting DREAM Generation ---")
|
127 |
+
print(f"Parameters: gen_length={gen_length}, steps={steps}, temperature={temperature}, top_p={top_p}, alg='{alg}', alg_temp={alg_temp}")
|
128 |
+
print(f"Constraints: {constraints}")
|
129 |
+
|
130 |
+
# --- Input Preparation ---
|
131 |
+
if constraints is None:
|
132 |
+
constraints = {}
|
133 |
+
|
134 |
+
# Convert word constraints to token IDs (handle multi-token words)
|
135 |
+
processed_constraints = {}
|
136 |
+
print("Processing constraints:")
|
137 |
+
for pos, word in constraints.items():
|
138 |
+
# Prepend space for consistent tokenization, similar to LLaDA example
|
139 |
+
tokens = tokenizer.encode(" " + word, add_special_tokens=False)
|
140 |
+
if not tokens:
|
141 |
+
print(f" Warning: Could not tokenize constraint word '{word}' at position {pos}. Skipping.")
|
142 |
+
continue
|
143 |
+
print(f" Pos {pos}, Word '{word}' -> Tokens {tokens}")
|
144 |
+
for i, token_id in enumerate(tokens):
|
145 |
+
# Ensure we don't overwrite parts of multi-token constraints accidentally
|
146 |
+
if pos + i not in processed_constraints:
|
147 |
+
processed_constraints[pos + i] = token_id
|
148 |
+
else:
|
149 |
+
print(f" Warning: Overlapping constraint at position {pos+i}. Keeping first.")
|
150 |
+
|
151 |
+
# Prepare the prompt using chat template
|
152 |
+
# Note: DREAM examples use add_generation_prompt=True
|
153 |
+
try:
|
154 |
+
inputs = tokenizer.apply_chat_template(
|
155 |
+
messages,
|
156 |
+
return_tensors="pt",
|
157 |
+
return_dict=True,
|
158 |
+
add_generation_prompt=True # Crucial for instruction-tuned models like Dream-Instruct
|
159 |
+
)
|
160 |
+
input_ids = inputs.input_ids.to(device=device)
|
161 |
+
attention_mask = inputs.attention_mask.to(device=device) # Get attention mask
|
162 |
+
prompt_length = input_ids.shape[1]
|
163 |
+
print(f"Input prompt length: {prompt_length}")
|
164 |
+
print(f"Input IDs: {input_ids}")
|
165 |
+
except Exception as e:
|
166 |
+
print(f"Error applying chat template: {e}")
|
167 |
+
# Provide a fallback or raise the error
|
168 |
+
# Fallback: Simple concatenation (less ideal for instruction models)
|
169 |
+
# chat_input = "".join([f"{msg['role']}: {msg['content']}\n" for msg in messages]) + "assistant:"
|
170 |
+
# input_ids = tokenizer(chat_input, return_tensors="pt").input_ids.to(device)
|
171 |
+
# attention_mask = torch.ones_like(input_ids)
|
172 |
+
# prompt_length = input_ids.shape[1]
|
173 |
+
# print(f"Warning: Using basic concatenation due to template error. Prompt length: {prompt_length}")
|
174 |
+
return [([("Error applying chat template.", "red")],)], f"Error: {e}"
|
175 |
+
|
176 |
+
|
177 |
+
if prompt_length + gen_length > 2048: # Check context length (DREAM uses 2048)
|
178 |
+
print(f"Warning: Requested length ({prompt_length + gen_length}) exceeds model max length (2048). Truncating gen_length.")
|
179 |
+
gen_length = 2048 - prompt_length
|
180 |
+
if gen_length <= 0:
|
181 |
+
print("Error: Prompt is already too long.")
|
182 |
+
return [([("Prompt too long.", "red")],)], "Error: Prompt too long."
|
183 |
+
|
184 |
+
|
185 |
+
# --- State for Visualization Hook ---
|
186 |
+
visualization_states = []
|
187 |
+
last_x = None # Store the sequence from the previous step
|
188 |
+
|
189 |
+
# Initial state: Prompt + all masks
|
190 |
+
initial_x_part = torch.full((1, gen_length), MASK_ID, dtype=torch.long, device=device)
|
191 |
+
# Apply initial constraints to the masked part *before* showing the first state
|
192 |
+
for pos, token_id in processed_constraints.items():
|
193 |
+
absolute_pos = pos # Position relative to start of generation
|
194 |
+
if 0 <= absolute_pos < gen_length:
|
195 |
+
initial_x_part[0, absolute_pos] = token_id
|
196 |
+
|
197 |
+
initial_state_vis = []
|
198 |
+
for i in range(gen_length):
|
199 |
+
token_id = initial_x_part[0, i].item()
|
200 |
+
if token_id == MASK_ID:
|
201 |
+
initial_state_vis.append((MASK_TOKEN, "#444444")) # Mask color
|
202 |
+
else:
|
203 |
+
# This must be a constraint applied initially
|
204 |
+
token_str = tokenizer.decode([token_id], skip_special_tokens=True)
|
205 |
+
initial_state_vis.append((token_str if token_str else "?", "#800080")) # Constraint color (purple)
|
206 |
+
visualization_states.append(initial_state_vis)
|
207 |
+
|
208 |
+
# --- Define the Hook Function ---
|
209 |
+
def generation_tokens_hook_func(step, x, logits):
|
210 |
+
nonlocal last_x, visualization_states # Allow modification of outer scope variables
|
211 |
+
print(f"Hook called for step {step}")
|
212 |
+
|
213 |
+
current_x = x.clone() # Work on a copy for comparison
|
214 |
+
|
215 |
+
# 1. Apply Constraints *before* generating visualization
|
216 |
+
# Constraints are relative to the start of the *generated* part
|
217 |
+
constrained_x = current_x.clone()
|
218 |
+
prompt_len = current_x.shape[1] - gen_length # Recalculate just in case
|
219 |
+
if prompt_len < 0:
|
220 |
+
print("Warning: prompt_len negative in hook, skipping constraints/vis.")
|
221 |
+
return current_x # Return unmodified if something is wrong
|
222 |
+
|
223 |
+
constraints_applied_this_step = False
|
224 |
+
for pos, token_id in processed_constraints.items():
|
225 |
+
absolute_pos = prompt_len + pos
|
226 |
+
if prompt_len <= absolute_pos < current_x.shape[1]:
|
227 |
+
if constrained_x[0, absolute_pos] != token_id:
|
228 |
+
constrained_x[0, absolute_pos] = token_id
|
229 |
+
constraints_applied_this_step = True
|
230 |
+
# print(f" Constraint applied at pos {pos} ({absolute_pos}) -> token {token_id}")
|
231 |
+
|
232 |
+
|
233 |
+
# 2. Generate Visualization State for *this* step
|
234 |
+
current_state_vis = []
|
235 |
+
# Compare current_x (before explicit constraint application in *this* hook call)
|
236 |
+
# with last_x (state from *previous* hook call / initial state)
|
237 |
+
# Generate based on the state *before* reapplying constraints here,
|
238 |
+
# but *after* the model's diffusion step determined current_x.
|
239 |
+
gen_part_current = current_x[0, prompt_len:]
|
240 |
+
gen_part_last = last_x[0, prompt_len:] if last_x is not None else None
|
241 |
+
|
242 |
+
for i in range(gen_length):
|
243 |
+
current_token_id = gen_part_current[i].item()
|
244 |
+
token_str = tokenizer.decode([current_token_id], skip_special_tokens=True).strip()
|
245 |
+
# Use a placeholder if decoding results in empty string
|
246 |
+
display_token = token_str if token_str else MASK_TOKEN if current_token_id == MASK_ID else "?"
|
247 |
+
|
248 |
+
# Check if this position is constrained
|
249 |
+
is_constrained = i in processed_constraints
|
250 |
+
|
251 |
+
if current_token_id == MASK_ID:
|
252 |
+
color = "#444444" # Dark Gray for masks
|
253 |
+
elif is_constrained and processed_constraints[i] == current_token_id:
|
254 |
+
color = "#800080" # Purple for correctly constrained tokens
|
255 |
+
elif gen_part_last is None or gen_part_last[i].item() == MASK_ID:
|
256 |
+
# Newly revealed (was mask in previous step or initial state)
|
257 |
+
color = "#66CC66" # Light Green
|
258 |
+
else:
|
259 |
+
# Previously revealed and not masked
|
260 |
+
color = "#6699CC" # Light Blue
|
261 |
+
|
262 |
+
current_state_vis.append((display_token, color))
|
263 |
+
|
264 |
+
visualization_states.append(current_state_vis)
|
265 |
+
|
266 |
+
# 3. Update last_x for the *next* step's comparison
|
267 |
+
# Store the state *after* applying constraints for accurate comparison next time
|
268 |
+
last_x = constrained_x.clone()
|
269 |
+
|
270 |
+
# 4. Return the sequence with constraints applied for the model's next step
|
271 |
+
# print(f"Hook returning constrained_x: {constrained_x[:, prompt_len:]}")
|
272 |
+
return constrained_x # Return the sequence with constraints enforced
|
273 |
+
|
274 |
+
|
275 |
+
# --- Run DREAM Generation ---
|
276 |
+
try:
|
277 |
+
print("Calling model.diffusion_generate...")
|
278 |
+
# Make sure last_x is initialized correctly before the first hook call
|
279 |
+
# It should represent the state *before* the first diffusion step.
|
280 |
+
initial_full_x = torch.cat([input_ids, initial_x_part], dim=1)
|
281 |
+
last_x = initial_full_x.clone()
|
282 |
+
|
283 |
+
output = model.diffusion_generate(
|
284 |
+
input_ids,
|
285 |
+
attention_mask=attention_mask,
|
286 |
+
max_new_tokens=gen_length,
|
287 |
+
output_history=False, # We build history in the hook
|
288 |
+
return_dict_in_generate=True,
|
289 |
+
steps=steps,
|
290 |
+
temperature=temperature,
|
291 |
+
top_p=top_p,
|
292 |
+
alg=alg,
|
293 |
+
alg_temp=alg_temp if alg != "origin" else 0.0, # alg_temp only for confidence algs
|
294 |
+
generation_tokens_hook_func=generation_tokens_hook_func
|
295 |
+
)
|
296 |
+
print("model.diffusion_generate finished.")
|
297 |
+
|
298 |
+
# Extract final generated sequence (response part only)
|
299 |
+
# The hook ensures the returned sequence has constraints applied
|
300 |
+
final_sequence = output.sequences[0]
|
301 |
+
response_token_ids = final_sequence[prompt_length:]
|
302 |
+
|
303 |
+
# Decode the final response
|
304 |
+
final_text = tokenizer.decode(
|
305 |
+
response_token_ids,
|
306 |
+
skip_special_tokens=True,
|
307 |
+
clean_up_tokenization_spaces=True # Recommended for cleaner output
|
308 |
+
).strip()
|
309 |
+
print(f"Final generated text: {final_text}")
|
310 |
+
|
311 |
+
# Add the very final state to visualization if the hook didn't capture it
|
312 |
+
# (Should be captured, but as a safeguard)
|
313 |
+
if len(visualization_states) <= steps: # Hook might run 'steps' times
|
314 |
+
final_state_vis = []
|
315 |
+
final_gen_part = final_sequence[prompt_length:]
|
316 |
+
for i in range(gen_length):
|
317 |
+
token_id = final_gen_part[i].item()
|
318 |
+
token_str = tokenizer.decode([token_id], skip_special_tokens=True).strip()
|
319 |
+
display_token = token_str if token_str else MASK_TOKEN if token_id == MASK_ID else "?"
|
320 |
+
is_constrained = i in processed_constraints
|
321 |
+
|
322 |
+
if token_id == MASK_ID: color = "#444444"
|
323 |
+
elif is_constrained and processed_constraints[i] == token_id: color = "#800080"
|
324 |
+
else: color = "#6699CC" # Default to blue for final state tokens
|
325 |
+
final_state_vis.append((display_token, color))
|
326 |
+
visualization_states.append(final_state_vis)
|
327 |
+
|
328 |
+
|
329 |
+
except Exception as e:
|
330 |
+
print(f"Error during generation: {e}")
|
331 |
+
import traceback
|
332 |
+
traceback.print_exc()
|
333 |
+
# Add error message to visualization
|
334 |
+
error_msg = f"Error during generation: {str(e)}"
|
335 |
+
visualization_states.append([("Error", "red")])
|
336 |
+
final_text = f"Generation failed: {e}"
|
337 |
+
|
338 |
+
print("--- DREAM Generation Finished ---")
|
339 |
+
return visualization_states, final_text
|
340 |
+
|
341 |
+
|
342 |
+
# --- Gradio UI Setup ---
|
343 |
+
|
344 |
+
css = '''
|
345 |
+
.category-legend{display:none}
|
346 |
+
/* button{height: 60px} */ /* Optional: Adjust button height */
|
347 |
+
.small_btn {
|
348 |
+
max-width: 100px; /* Adjust as needed */
|
349 |
+
height: 40px; /* Adjust as needed */
|
350 |
+
flex-grow: 0; /* Prevent button from growing */
|
351 |
+
margin-left: 5px; /* Add some space */
|
352 |
+
}
|
353 |
+
.chat-input-row {
|
354 |
+
display: flex;
|
355 |
+
align-items: center; /* Vertically align items */
|
356 |
+
}
|
357 |
+
.chat-input-row > * {
|
358 |
+
margin-right: 5px; /* Space between textbox and button */
|
359 |
+
}
|
360 |
+
.chat-input-row > *:last-child {
|
361 |
+
margin-right: 0;
|
362 |
+
}
|
363 |
+
'''
|
364 |
+
def create_chatbot_demo():
|
365 |
+
with gr.Blocks(css=css) as demo:
|
366 |
+
gr.Markdown("# Dream 7B - Diffusion Language Model Demo")
|
367 |
+
gr.Markdown("A demonstration of the Dream 7B diffusion-based language model. Watch the text generate step-by-step.")
|
368 |
+
gr.Markdown("[Model Card](https://huggingface.co/Dream-org/Dream-v0-Instruct-7B) - [Blog Post](https://hkunlp.github.io/blog/2025/dream/)")
|
369 |
+
|
370 |
+
# STATE MANAGEMENT
|
371 |
+
chat_history = gr.State([])
|
372 |
+
|
373 |
+
# UI COMPONENTS
|
374 |
+
with gr.Row():
|
375 |
+
with gr.Column(scale=3):
|
376 |
+
chatbot_ui = gr.Chatbot(
|
377 |
+
label="Conversation",
|
378 |
+
height=500,
|
379 |
+
bubble_full_width=False # Improves layout for shorter messages
|
380 |
+
)
|
381 |
+
|
382 |
+
# Message input Row
|
383 |
+
with gr.Row(elem_classes="chat-input-row"):
|
384 |
+
user_input = gr.Textbox(
|
385 |
+
label="Your Message",
|
386 |
+
placeholder="Type your message here and press Enter...",
|
387 |
+
scale=4, # Give textbox more space
|
388 |
+
container=False, # Remove container background/padding
|
389 |
+
show_label=False
|
390 |
+
)
|
391 |
+
send_btn = gr.Button("Send", scale=1, elem_classes="small_btn")
|
392 |
+
|
393 |
+
constraints_input = gr.Textbox(
|
394 |
+
label="Word Constraints (Optional)",
|
395 |
+
info="Force specific words at positions (0-indexed from response start). Format: 'pos:word, pos:word'. Example: '0:Once, 5:upon, 10:time'",
|
396 |
+
placeholder="e.g., 0:Hello, 6:world",
|
397 |
+
value="" # Default empty
|
398 |
+
)
|
399 |
+
with gr.Column(scale=2):
|
400 |
+
output_vis = gr.HighlightedText(
|
401 |
+
label="Denoising Process Visualization",
|
402 |
+
combine_adjacent=False,
|
403 |
+
show_legend=False, # Keep legend off as requested
|
404 |
+
# Color map for legend (though hidden)
|
405 |
+
# color_map={
|
406 |
+
# "Mask": "#444444",
|
407 |
+
# "New": "#66CC66",
|
408 |
+
# "Old": "#6699CC",
|
409 |
+
# "Constraint": "#800080",
|
410 |
+
# "Error": "red"
|
411 |
+
# }
|
412 |
+
)
|
413 |
+
gr.Markdown(
|
414 |
+
"**Color Legend:** <span style='color:#444444'>■ Mask</span> | <span style='color:#66CC66'>■ Newly Generated</span> | <span style='color:#6699CC'>■ Previously Generated</span> | <span style='color:#800080'>■ Constraint</span>"
|
415 |
+
)
|
416 |
+
|
417 |
+
|
418 |
+
# Advanced generation settings
|
419 |
+
with gr.Accordion("Generation Settings", open=False):
|
420 |
+
with gr.Row():
|
421 |
+
gen_length = gr.Slider(
|
422 |
+
minimum=16, maximum=512, value=128, step=8, # Increased max length
|
423 |
+
label="Max New Tokens"
|
424 |
+
)
|
425 |
+
steps = gr.Slider(
|
426 |
+
minimum=8, maximum=512, value=128, step=8, # Increased max steps
|
427 |
+
label="Diffusion Steps"
|
428 |
+
)
|
429 |
+
with gr.Row():
|
430 |
+
temperature = gr.Slider(
|
431 |
+
minimum=0.0, maximum=1.5, value=0.6, step=0.05, # Wider range for temp
|
432 |
+
label="Temperature"
|
433 |
+
)
|
434 |
+
top_p = gr.Slider(
|
435 |
+
minimum=0.0, maximum=1.0, value=0.95, step=0.05,
|
436 |
+
label="Top-P (Nucleus Sampling)"
|
437 |
+
)
|
438 |
+
with gr.Row():
|
439 |
+
# Map UI choices to DREAM's alg parameters
|
440 |
+
remasking_strategy = gr.Radio(
|
441 |
+
choices=[
|
442 |
+
("Random", "origin"), # User friendly name -> actual param
|
443 |
+
("Entropy", "entropy"),
|
444 |
+
("MaskGit+", "maskgit_plus"),
|
445 |
+
("TopK Margin", "topk_margin"),
|
446 |
+
],
|
447 |
+
value="entropy", # Default
|
448 |
+
label="Generation Order Strategy (alg)"
|
449 |
+
)
|
450 |
+
alg_temp = gr.Slider(
|
451 |
+
minimum=0.0, maximum=1.0, value=0.1, step=0.05,
|
452 |
+
label="Order Randomness (alg_temp)" ,
|
453 |
+
info="Adds randomness to non-Random strategies. Ignored for Random."
|
454 |
+
)
|
455 |
+
|
456 |
+
with gr.Row():
|
457 |
+
visualization_delay = gr.Slider(
|
458 |
+
minimum=0.0, maximum=0.5, value=0.05, step=0.01,
|
459 |
+
label="Visualization Delay (seconds)"
|
460 |
+
)
|
461 |
+
|
462 |
+
# Clear button
|
463 |
+
clear_btn = gr.Button("Clear Conversation")
|
464 |
+
|
465 |
+
# Hidden textbox to potentially store intermediate response (might not be needed)
|
466 |
+
# current_response = gr.Textbox(visible=False)
|
467 |
+
|
468 |
+
# --- Event Handlers ---
|
469 |
+
|
470 |
+
# Helper to add message to history state
|
471 |
+
def add_message_to_history(history, message, response):
|
472 |
+
history = history.copy() # Modify copy
|
473 |
+
history.append([message, response])
|
474 |
+
return history
|
475 |
+
|
476 |
+
# Function when user submits message (Enter or Send button)
|
477 |
+
def user_message_submitted(message, history):
|
478 |
+
print(f"User submitted: '{message}'")
|
479 |
+
if not message or not message.strip():
|
480 |
+
print("Empty message submitted, doing nothing.")
|
481 |
+
# Return unchanged state if message is empty
|
482 |
+
# Need to return values for all outputs of the .submit/.click
|
483 |
+
return history, history, "", [] # history, chatbot_ui, user_input, output_vis
|
484 |
+
|
485 |
+
# Add user message to history (with None for bot response initially)
|
486 |
+
history = add_message_to_history(history, message, None)
|
487 |
+
|
488 |
+
# Prepare updated history for display in Chatbot UI
|
489 |
+
history_for_display = history.copy()
|
490 |
+
|
491 |
+
# Clear the input textbox
|
492 |
+
message_out = ""
|
493 |
+
# Clear the visualization
|
494 |
+
vis_clear = []
|
495 |
+
|
496 |
+
# Return updated history state, chatbot display, cleared input, cleared visualization
|
497 |
+
return history, history_for_display, message_out, vis_clear
|
498 |
+
|
499 |
+
# Function to generate bot response (triggered after user message is processed)
|
500 |
+
def bot_response_generator(
|
501 |
+
history, gen_length, steps, constraints_text, delay,
|
502 |
+
temperature, top_p, alg, alg_temp
|
503 |
+
):
|
504 |
+
print("--- Generating Bot Response ---")
|
505 |
+
if not history or history[-1][1] is not None:
|
506 |
+
print("History empty or last message already has response. Skipping generation.")
|
507 |
+
# Yield current state if called unnecessarily
|
508 |
+
yield history, [], "No response generated."
|
509 |
+
return
|
510 |
+
|
511 |
+
# Get the conversation history in the format the model expects
|
512 |
+
messages = format_chat_history(history) # Includes the latest user query
|
513 |
+
|
514 |
+
# Parse constraints from the textbox
|
515 |
+
parsed_constraints = parse_constraints(constraints_text)
|
516 |
+
|
517 |
+
try:
|
518 |
+
# Generate response with visualization
|
519 |
+
vis_states, response_text = dream_generate_response_with_visualization(
|
520 |
+
messages,
|
521 |
+
gen_length=gen_length,
|
522 |
+
steps=steps,
|
523 |
+
constraints=parsed_constraints,
|
524 |
+
temperature=temperature,
|
525 |
+
top_p=top_p,
|
526 |
+
alg=alg,
|
527 |
+
alg_temp=alg_temp
|
528 |
+
)
|
529 |
+
|
530 |
+
# Update the history state with the final bot response
|
531 |
+
history[-1][1] = response_text.strip()
|
532 |
+
|
533 |
+
# Yield the initial visualization state immediately
|
534 |
+
if vis_states:
|
535 |
+
yield history, vis_states[0] # Update chatbot, update visualization
|
536 |
+
else:
|
537 |
+
# Handle case where generation failed before first state
|
538 |
+
yield history, [("Generation failed.", "red")]
|
539 |
+
|
540 |
+
# Then animate through the rest of the visualization states
|
541 |
+
for state in vis_states[1:]:
|
542 |
+
time.sleep(delay)
|
543 |
+
yield history, state # Update chatbot (implicitly via history), update visualization
|
544 |
+
|
545 |
+
except Exception as e:
|
546 |
+
print(f"Error in bot_response_generator: {e}")
|
547 |
+
import traceback
|
548 |
+
traceback.print_exc()
|
549 |
+
error_msg = f"Error: {str(e)}"
|
550 |
+
# Show error in visualization
|
551 |
+
error_vis = [(error_msg, "red")]
|
552 |
+
# Update history with error message? Optional.
|
553 |
+
# history[-1][1] = error_msg
|
554 |
+
yield history, error_vis
|
555 |
+
|
556 |
+
# Function to clear everything
|
557 |
+
def clear_conversation():
|
558 |
+
print("Clearing conversation.")
|
559 |
+
return [], [], "", [] # chat_history, chatbot_ui, user_input, output_vis
|
560 |
+
|
561 |
+
# --- Wire UI elements to functions ---
|
562 |
+
|
563 |
+
# Typing in Textbox and pressing Enter
|
564 |
+
user_input.submit(
|
565 |
+
fn=user_message_submitted,
|
566 |
+
inputs=[user_input, chat_history],
|
567 |
+
outputs=[chat_history, chatbot_ui, user_input, output_vis], # Update history state, chatbot display, clear input, clear vis
|
568 |
+
queue=False # Process immediately
|
569 |
+
).then(
|
570 |
+
fn=bot_response_generator,
|
571 |
+
inputs=[
|
572 |
+
chat_history, gen_length, steps, constraints_input, visualization_delay,
|
573 |
+
temperature, top_p, remasking_strategy, alg_temp
|
574 |
+
],
|
575 |
+
outputs=[chatbot_ui, output_vis] # Update chatbot display (with new response), update visualization
|
576 |
+
# Note: history state is updated implicitly by bot_response_generator modifying its input
|
577 |
+
)
|
578 |
+
|
579 |
+
# Clicking the Send button
|
580 |
+
send_btn.click(
|
581 |
+
fn=user_message_submitted,
|
582 |
+
inputs=[user_input, chat_history],
|
583 |
+
outputs=[chat_history, chatbot_ui, user_input, output_vis],
|
584 |
+
queue=False
|
585 |
+
).then(
|
586 |
+
fn=bot_response_generator,
|
587 |
+
inputs=[
|
588 |
+
chat_history, gen_length, steps, constraints_input, visualization_delay,
|
589 |
+
temperature, top_p, remasking_strategy, alg_temp
|
590 |
+
],
|
591 |
+
outputs=[chatbot_ui, output_vis]
|
592 |
+
)
|
593 |
+
|
594 |
+
# Clicking the Clear button
|
595 |
+
clear_btn.click(
|
596 |
+
fn=clear_conversation,
|
597 |
+
inputs=[],
|
598 |
+
outputs=[chat_history, chatbot_ui, user_input, output_vis],
|
599 |
+
queue=False
|
600 |
+
)
|
601 |
+
|
602 |
+
return demo
|
603 |
+
|
604 |
+
# --- Launch the Gradio App ---
|
605 |
+
if __name__ == "__main__":
|
606 |
+
print("Creating Gradio demo...")
|
607 |
+
demo = create_chatbot_demo()
|
608 |
+
print("Launching Gradio demo...")
|
609 |
+
# Use queue for potentially long generation times
|
610 |
+
# share=True generates a public link (useful for Colab/Spaces)
|
611 |
+
demo.queue().launch(share=True, debug=True) # Add debug=True for more logs
|