multimodalart HF Staff commited on
Commit
fb0307e
·
verified ·
1 Parent(s): 3c422aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -302
app.py CHANGED
@@ -9,11 +9,9 @@ import time
9
  import re
10
  from typing import List, Dict, Tuple, Optional
11
  import torch.distributions as dists # Added import
12
- import traceback # For printing exceptions
13
 
14
  # --- START: Copied Helper functions from generation_utils.py ---
15
- # These are needed because we are reimplementing the sampling loop locally.
16
-
17
  def top_p_logits(logits, top_p=None):
18
  """ Applies top-p filtering to logits. """
19
  if top_p is None or top_p >= 1.0:
@@ -21,10 +19,8 @@ def top_p_logits(logits, top_p=None):
21
  sorted_logits, sorted_indices = torch.sort(logits, descending=True)
22
  cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
23
  sorted_indices_to_remove = cumulative_probs > top_p
24
- # Shift the indices to the right to keep the first token above the threshold
25
  sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
26
  sorted_indices_to_remove[..., 0] = 0
27
-
28
  mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
29
  mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
30
  logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
@@ -34,10 +30,7 @@ def top_k_logits(logits, top_k=None):
34
  """ Applies top-k filtering to logits. """
35
  if top_k is None or top_k <= 0:
36
  return logits
37
- top_k = min(top_k, logits.size(-1)) # Safety check
38
- if top_k == logits.size(-1): # Avoid unnecessary computation if k is full size
39
- return logits
40
- # Remove all tokens with a probability less than the last token of the top-k
41
  indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
42
  logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
43
  return logits
@@ -45,201 +38,145 @@ def top_k_logits(logits, top_k=None):
45
  def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False):
46
  """ Samples tokens based on logits and calculates confidence. """
47
  if temperature > 0:
48
- # Prevent division by zero or negative temperatures
49
  safe_temp = max(temperature, 1e-6)
50
  logits = logits / safe_temp
51
- if top_p is not None and 0.0 < top_p < 1.0: # Apply top_p if valid (and not disabled)
52
  logits = top_p_logits(logits, top_p)
53
- if top_k is not None and top_k > 0: # Apply top_k if valid
54
  logits = top_k_logits(logits, top_k)
55
-
56
- # Ensure logits are not all -inf after filtering, if so, assign uniform probability.
57
- is_all_neg_inf = torch.all(logits <= torch.finfo(logits.dtype).min, dim=-1, keepdim=True)
58
  if torch.any(is_all_neg_inf):
59
- # print("Warning: All logits became -inf after filtering. Assigning uniform probabilities.")
60
- uniform_logits = torch.zeros_like(logits) # Uniform logits (zeros before softmax)
61
  logits = torch.where(is_all_neg_inf, uniform_logits, logits)
62
-
63
  probs = torch.softmax(logits, dim=-1)
64
-
65
- # Clamp probabilities to avoid NaNs in sampling, ensure they sum to 1
66
- probs = torch.clamp(probs, min=0.0) # Ensure non-negative
67
- prob_sum_for_norm = probs.sum(dim=-1, keepdim=True)
68
- # Use a tolerance check for division
69
- safe_prob_sum_for_norm = torch.where(prob_sum_for_norm > 1e-12, prob_sum_for_norm, torch.ones_like(prob_sum_for_norm))
70
- probs = probs / safe_prob_sum_for_norm # Re-normalize with safe denominator
71
- probs = torch.nan_to_num(probs, nan=0.0) # Handle any remaining NaNs
72
-
73
  if temperature > 0:
74
  try:
75
- # Ensure probs sum to 1 before sampling
76
- probs_sum_check = probs.sum(dim=-1)
77
- if not torch.all(torch.isclose(probs_sum_check, torch.ones_like(probs_sum_check))):
78
- # print(f"Warning: Probs do not sum to 1 before sampling ({probs_sum_check}). Re-normalizing.")
79
- probs = probs / probs.sum(dim=-1, keepdim=True) # Final normalization attempt
80
-
81
  x0 = dists.Categorical(probs=probs).sample()
82
  confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
83
- except Exception as e: # Catch broader exceptions during sampling
84
  print(f"Warning: Error during Categorical sampling: {e}. Falling back to argmax.")
85
  confidence, x0 = probs.max(dim=-1)
86
- else: # Greedy decoding (temperature == 0)
87
  confidence, x0 = probs.max(dim=-1)
88
-
89
  if margin_confidence:
90
  sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
91
- # Ensure there are at least 2 probabilities to compare
92
  top1_probs = sorted_probs[..., 0]
93
- top2_probs = sorted_probs[..., 1] if sorted_probs.shape[-1] > 1 else torch.zeros_like(top1_probs) # Use 0 if only one prob
94
  confidence = top1_probs - top2_probs
95
-
96
  if neg_entropy:
97
- epsilon = torch.finfo(probs.dtype).eps # Use dtype's epsilon
98
- # Ensure probs are > 0 for log
99
- log_probs = torch.log(torch.clamp(probs, min=epsilon)) # Clamp before log
100
- confidence = torch.sum(probs * log_probs, dim=-1) # This is negative entropy
101
-
102
- # Ensure confidence is not NaN
103
  confidence = torch.nan_to_num(confidence, nan=0.0)
104
-
105
  return confidence, x0
106
  # --- END: Copied Helper functions ---
107
 
108
 
109
- # --- Model Loading and Constants ---
110
- # Load model configuration to get special token IDs
111
  config = AutoConfig.from_pretrained("Dream-org/Dream-v0-Instruct-7B", trust_remote_code=True)
112
- # Use AutoModel for the base model loading, relying on trust_remote_code=True
113
- # for the custom DreamModel class and generation mixin.
114
  model_path = "Dream-org/Dream-v0-Instruct-7B"
115
-
116
- # Determine device
117
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
118
  print(f"Using device: {device}")
119
-
120
- # Load model and tokenizer
121
  print("Loading tokenizer...")
122
  tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
123
  print("Loading model...")
124
- # Ensure torch_dtype is set appropriately for your hardware if needed
125
  model = AutoModel.from_pretrained(
126
  model_path,
127
- torch_dtype=torch.bfloat16 if device == 'cuda' else torch.float32, # Use bfloat16 only on CUDA
128
  trust_remote_code=True,
129
- attn_implementation="sdpa" # Explicitly request SDPA if available/desired
130
  )
131
  model = model.to(device).eval()
132
  print("Model loaded.")
133
-
134
- # Constants from Dream's config/tokenizer
135
  MASK_TOKEN = tokenizer.mask_token
136
- MASK_ID = tokenizer.mask_token_id # Use tokenizer's mask_token_id directly
137
- PAD_ID = tokenizer.pad_token_id # Use tokenizer's pad_token_id
138
- EOS_ID = tokenizer.eos_token_id # Use tokenizer's eos_token_id
139
-
140
- if MASK_ID is None:
141
- print("Warning: Mask token ID not found in config/tokenizer. Trying to fetch from tokenizer...")
142
- mask_token_special = tokenizer.mask_token
143
- if mask_token_special:
144
- MASK_ID = tokenizer.convert_tokens_to_ids(mask_token_special)
145
- print(f"Found MASK_ID from tokenizer: {MASK_ID}")
146
- else:
147
- raise ValueError("Cannot determine MASK_ID. Check model's tokenizer configuration.")
148
-
149
  SPECIAL_TOKEN_IDS = {PAD_ID, EOS_ID, MASK_ID}
150
  try:
151
  IM_START_ID = tokenizer.convert_tokens_to_ids("<|im_start|>")
152
  IM_END_ID = tokenizer.convert_tokens_to_ids("<|im_end|>")
153
- if IM_START_ID is not None: SPECIAL_TOKEN_IDS.add(IM_START_ID)
154
- if IM_END_ID is not None: SPECIAL_TOKEN_IDS.add(IM_END_ID)
155
- except KeyError:
156
- print("Warning: <|im_start|> or <|im_end|> not found in tokenizer vocab.")
157
- IM_START_ID = None
158
- IM_END_ID = None
159
 
160
 
161
- # --- App Helper Functions ---
162
  def parse_constraints(constraints_text: str) -> Dict[int, List[int]]:
163
- """ Parses constraints. """
164
  constraints = {}
165
- if not constraints_text:
166
- return constraints
167
-
168
- # Simple split on comma, assumes format 'pos:word, pos:word'
169
  parts = constraints_text.split(',')
170
-
171
  for part in parts:
172
  part = part.strip()
173
- if ':' not in part:
174
- continue
175
  pos_str, word = part.split(':', 1)
176
  try:
177
  pos = int(pos_str.strip())
178
  word = word.strip()
179
  token_ids = []
180
- if word: # Only encode if word is not empty
181
- # Add space prefix automatically if pos > 0 and word doesn't start with space
182
  text_to_encode = (" " + word) if (pos > 0 and not word.startswith(" ")) else word
183
  token_ids = tokenizer.encode(text_to_encode, add_special_tokens=False)
184
-
185
- if token_ids and pos >= 0:
186
- constraints[pos] = token_ids
187
- elif not token_ids and word: # Don't warn for empty words after split
188
- print(f"Warning: Could not tokenize constraint word '{word}'")
189
- except ValueError:
190
- print(f"Warning: Invalid position '{pos_str}' in constraint part '{part}'")
191
- continue # Ignore malformed constraint parts
192
- except Exception as e:
193
- print(f"Warning: Error processing constraint '{part}': {e}")
194
- continue
195
-
196
- # print(f"Parsed constraints: {constraints}") # Debugging
197
  return constraints
198
 
199
-
200
  def format_chat_history(history: List[List[Optional[str]]]) -> List[Dict[str, str]]:
201
- """ Formats chat history for the template. """
 
 
 
202
  messages = []
203
- for user_msg, assistant_msg in history:
204
- if user_msg is not None: # Check for None explicitly
205
- messages.append({"role": "user", "content": user_msg})
206
- # Add assistant message only if it exists (it won't for the last turn before generation)
 
 
 
 
 
 
 
 
 
207
  if assistant_msg is not None:
208
- messages.append({"role": "assistant", "content": assistant_msg})
 
 
209
  return messages
210
 
211
  def apply_constraints_to_state(
212
- x: torch.Tensor,
213
- prompt_length: int,
214
- total_length: int,
215
- parsed_constraints: Dict[int, List[int]],
216
- current_step: Optional[int] = None # For logging/debugging
217
  ) -> torch.Tensor:
218
- """ Applies constraints directly to the state tensor `x`. """
219
- modified_x = x.clone() # Work on a copy
220
  for rel_pos, word_token_ids in parsed_constraints.items():
221
  abs_start_pos = prompt_length + rel_pos
222
  abs_end_pos = abs_start_pos + len(word_token_ids)
223
-
224
- # Ensure the constraint fits within the generation length
225
  if abs_start_pos < total_length and abs_end_pos <= total_length:
226
  try:
227
  constraint_tensor = torch.tensor(word_token_ids, dtype=torch.long, device=modified_x.device)
228
- # Force the constraint tokens onto the sequence
229
  modified_x[0, abs_start_pos:abs_end_pos] = constraint_tensor
230
- except IndexError:
231
- print(f"Warning (Step {current_step}): Constraint at {rel_pos} ('{tokenizer.decode(word_token_ids)}') goes out of bounds.")
232
- except Exception as e:
233
- print(f"Warning (Step {current_step}): Failed to apply constraint at {rel_pos}: {e}")
234
  return modified_x
235
 
236
 
237
  # --- Core Generation Logic with Live Visualization ---
238
 
239
- @spaces.GPU # Decorator for Hugging Face Spaces GPU usage
240
- @torch.no_grad() # Ensure no gradients are computed during generation
241
  def generate_dream_response(
242
- history: List[List[Optional[str]]], # Receives the list from _chat_history_store
243
  gen_length: int,
244
  steps: int,
245
  constraints_text: str,
@@ -249,19 +186,17 @@ def generate_dream_response(
249
  alg: str,
250
  alg_temp: Optional[float],
251
  visualization_delay: float
252
- ) -> List[Tuple[str, str]]:
253
  """ Generates text step-by-step and yields visualization states live. """
254
 
255
- # No history_copy needed, work directly on the input 'history' list
256
- # which is a reference to the value in _chat_history_store
257
-
258
- if not history or not history[-1][0]:
259
- # Yield the original history back if there's no input
260
- yield history, [("No input message found.", "red")], ""
261
  return
262
 
263
  # --- 1. Preparation ---
264
- last_user_message = history[-1][0]
265
  messages_for_template = format_chat_history(history)
266
  parsed_constraints = parse_constraints(constraints_text)
267
 
@@ -270,13 +205,17 @@ def generate_dream_response(
270
  messages_for_template,
271
  return_tensors="pt",
272
  return_dict=True,
273
- add_generation_prompt=True
274
  )
275
  input_ids = inputs.input_ids.to(device)
276
  prompt_attention_mask = inputs.attention_mask.to(device) if 'attention_mask' in inputs else torch.ones_like(input_ids)
277
  prompt_length = input_ids.shape[1]
 
 
 
278
  except Exception as e:
279
  print(f"Error applying chat template: {e}")
 
280
  yield history, [("Error preparing input.", "red")], ""
281
  return
282
 
@@ -290,103 +229,89 @@ def generate_dream_response(
290
  initial_generation_part = torch.full((1, gen_length), MASK_ID, dtype=torch.long, device=device)
291
  x = torch.cat((input_ids, initial_generation_part), dim=1)
292
 
 
293
  generation_attention_mask = torch.ones((1, gen_length), dtype=torch.long, device=device)
294
  full_attention_mask_long = torch.cat((prompt_attention_mask, generation_attention_mask), dim=1)
295
-
296
  attention_mask_for_model = full_attention_mask_long.to(model.dtype)
297
  large_neg_val = torch.finfo(model.dtype).min
298
  attention_mask_for_model = (1.0 - attention_mask_for_model) * large_neg_val
299
- attention_mask_for_model = attention_mask_for_model.unsqueeze(1).unsqueeze(2)
300
 
301
  timesteps = torch.linspace(1, eps, steps + 1, device=device)
302
  x = apply_constraints_to_state(x, prompt_length, total_length, parsed_constraints, current_step=-1)
303
 
304
- # --- 3. Visualization Setup ---
305
  previous_tokens_vis = None
306
- final_response_text = ""
307
- # history_copy removed
 
 
 
308
 
309
  # --- 4. Initial Yield (Masked State) ---
310
  initial_generated_tokens = x[0, prompt_length:].cpu()
311
  vis_data_initial = []
312
  for tok_id in initial_generated_tokens.tolist():
313
- display_token = MASK_TOKEN
314
- color = "#444444"
315
- vis_data_initial.append((display_token, color))
316
-
317
  previous_tokens_vis = initial_generated_tokens
318
- # Yield the current state of the history (which has None for the bot response)
319
- yield history, vis_data_initial, ""
320
  time.sleep(visualization_delay)
321
 
322
  # --- 5. Step-by-Step Diffusion Loop ---
323
  try:
324
  start_time = time.time()
 
 
325
  for i in range(steps):
326
  mask_index = (x == MASK_ID)
327
  if not mask_index.any():
328
  print(f"No mask tokens left at step {i}. Stopping early.")
329
  break
330
 
331
- # --- Model Forward Pass ---
332
  outputs = model(
333
  input_ids=x,
334
  attention_mask=attention_mask_for_model,
335
- position_ids=None,
336
- use_cache=False,
337
- return_dict=True
338
  )
339
  logits = outputs.logits
340
- logits = torch.cat([logits[:,:1], logits[:, :-1]], dim=1) # Align logits
341
 
342
  mask_logits = logits[mask_index]
343
  if mask_logits.numel() == 0:
344
  print(f"No masked tokens found for logit selection at step {i}. Stopping.")
345
  break
346
 
347
- # --- Sampling / Remasking Logic ---
348
- t = timesteps[i]
349
- s = timesteps[i + 1]
350
  x_new_masked_part = torch.full_like(x[mask_index], MASK_ID, device=device, dtype=torch.long)
351
 
352
- # [Keep sampling logic identical to previous correct version]
353
  if alg == 'origin':
354
  p_transfer = (1.0 - s / t) if i < steps - 1 else 1.0
355
  num_masked = mask_logits.shape[0]
356
  transfer_indices_relative = torch.rand(num_masked, device=device) < p_transfer
357
  logits_to_sample = mask_logits[transfer_indices_relative]
358
-
359
  if logits_to_sample.numel() > 0:
360
  _, sampled_tokens = sample_tokens(logits_to_sample, temperature=temperature, top_p=top_p_val, top_k=top_k_val)
361
  x_new_masked_part[transfer_indices_relative] = sampled_tokens
362
-
363
- else: # Confidence-based algorithms
364
- use_margin = (alg == 'topk_margin')
365
- use_entropy = (alg == 'entropy')
366
  confidence, x0_candidates = sample_tokens(
367
- mask_logits,
368
- temperature=temperature,
369
- top_p=top_p_val,
370
- top_k=top_k_val,
371
- margin_confidence=use_margin,
372
- neg_entropy=use_entropy
373
  )
374
-
375
  num_mask_token = mask_logits.shape[0]
376
  target_num_revealed_float = num_mask_token * (1.0 - s / t)
377
  number_transfer_tokens = int(target_num_revealed_float) if i < steps - 1 else num_mask_token
378
-
379
  if number_transfer_tokens > 0:
380
  num_samples = min(number_transfer_tokens, num_mask_token)
381
  if num_samples > 0:
382
- transfer_indices_relative = torch.tensor([], dtype=torch.long, device=device) # Initialize
383
- if alg_temp_val is None or alg_temp_val <= 0: # Top-k confidence
384
  sort_metric = confidence if alg != 'entropy' else -confidence
385
  k_topk = min(num_samples, sort_metric.numel())
386
- if k_topk > 0:
387
- _, transfer_indices_relative = torch.topk(sort_metric, k=k_topk)
388
-
389
- else: # Sample based on confidence temperature
390
  if confidence.numel() > 0:
391
  conf_probs = confidence / alg_temp_val
392
  conf_probs = torch.nan_to_num(conf_probs, nan=0.0, posinf=1e9, neginf=-1e9)
@@ -394,41 +319,26 @@ def generate_dream_response(
394
  conf_probs = F.softmax(conf_probs, dim=-1)
395
  conf_probs = torch.clamp(conf_probs, min=0.0)
396
  conf_probs = torch.nan_to_num(conf_probs, nan=0.0)
397
-
398
  prob_sum = conf_probs.sum()
399
  target_sum_tensor = torch.tensor(1.0, device=device, dtype=prob_sum.dtype)
400
  if not torch.isclose(prob_sum, target_sum_tensor, atol=1e-4) and prob_sum > 0:
401
  safe_prob_sum = torch.max(prob_sum, torch.tensor(1e-12, device=device, dtype=prob_sum.dtype))
402
  conf_probs = conf_probs / safe_prob_sum
403
-
404
  final_prob_sum_check = conf_probs.sum()
405
  if conf_probs.numel() > 0 and num_samples > 0 and torch.all(conf_probs >= 0) and torch.isclose(final_prob_sum_check, target_sum_tensor, atol=1e-4):
406
- try:
407
- transfer_indices_relative = torch.multinomial(conf_probs, num_samples=num_samples, replacement=False)
408
- except RuntimeError as e:
409
- print(f"Warning step {i}: Multinomial sampling failed ('{e}'). Falling back to top-k.")
410
- sort_metric = confidence if alg != 'entropy' else -confidence
411
- k_multinomial_fallback = min(num_samples, sort_metric.numel())
412
- if k_multinomial_fallback > 0:
413
- _, transfer_indices_relative = torch.topk(sort_metric, k=k_multinomial_fallback)
414
- else:
415
- # print(f"Warning step {i}: Invalid probabilities for multinomial sampling (sum={final_prob_sum_check:.4f}). Falling back to top-k.")
416
  sort_metric = confidence if alg != 'entropy' else -confidence
417
- k_multinomial_fallback = min(num_samples, sort_metric.numel())
418
- if k_multinomial_fallback > 0:
419
- _, transfer_indices_relative = torch.topk(sort_metric, k=k_multinomial_fallback)
420
- # else: # No confidence values to sample from, transfer_indices_relative remains empty
421
-
422
- # Apply the transfer
423
  if transfer_indices_relative.numel() > 0:
424
- valid_indices = transfer_indices_relative < x0_candidates.shape[0]
425
- valid_transfer_indices = transfer_indices_relative[valid_indices]
426
- if valid_transfer_indices.numel() > 0:
427
- if valid_transfer_indices.max() < x_new_masked_part.shape[0]:
428
- x_new_masked_part[valid_transfer_indices] = x0_candidates[valid_transfer_indices].clone()
429
- else:
430
- print(f"Warning step {i}: transfer_indices out of bounds for x_new_masked_part.")
431
- # --- End Sampling Logic ---
432
 
433
  x[mask_index] = x_new_masked_part
434
  x = apply_constraints_to_state(x, prompt_length, total_length, parsed_constraints, current_step=i)
@@ -436,7 +346,7 @@ def generate_dream_response(
436
  # --- Yield Visualization ---
437
  current_generated_tokens = x[0, prompt_length:].cpu()
438
  vis_data = []
439
- # [Keep visualization formatting logic the same]
440
  for j in range(gen_length):
441
  current_tok_id = current_generated_tokens[j].item()
442
  previous_tok_id = previous_tokens_vis[j].item() if previous_tokens_vis is not None and j < len(previous_tokens_vis) else MASK_ID
@@ -448,25 +358,30 @@ def generate_dream_response(
448
  if current_tok_id == MASK_ID: color = "#444444"
449
  elif previous_tok_id == MASK_ID: color = "#66CC66"
450
  else: color = "#6699CC"
451
- should_hide = (PAD_ID is not None and current_tok_id == PAD_ID) or \
452
- (EOS_ID is not None and current_tok_id == EOS_ID)
453
  if should_hide and previous_tok_id == current_tok_id: token_to_display = ""; color = None
454
  if token_to_display: vis_data.append((token_to_display, color))
455
- # --- End Vis Formatting ---
456
 
457
  previous_tokens_vis = current_generated_tokens
458
 
 
459
  intermediate_response_tokens = x[0, prompt_length:]
460
- intermediate_response_text = tokenizer.decode(
461
  intermediate_response_tokens,
462
  skip_special_tokens=True,
463
  clean_up_tokenization_spaces=True
464
  ).strip()
465
 
466
- # Yield the current state of the history list (bot response still None)
467
- yield history, vis_data, intermediate_response_text
 
 
 
 
 
468
  time.sleep(visualization_delay)
469
- # --- End Loop ---
470
 
471
  end_time = time.time()
472
  print(f"Dream generation finished in {end_time - start_time:.2f} seconds.")
@@ -480,41 +395,43 @@ def generate_dream_response(
480
  clean_up_tokenization_spaces=True
481
  ).strip()
482
 
483
- # --- CRITICAL FIX: Update history IN PLACE before final yield ---
484
- if history: # Ensure history is not empty
485
- history[-1][1] = final_response_text
486
- # Now the list referenced by _chat_history_store is updated.
487
 
 
488
  final_generated_tokens = x[0, prompt_length:].cpu()
489
  vis_data_final = []
490
- # [Keep final visualization formatting logic the same]
491
  for j in range(gen_length):
492
- current_tok_id = final_generated_tokens[j].item()
493
- previous_tok_id = previous_tokens_vis[j].item() if previous_tokens_vis is not None and j < len(previous_tokens_vis) else MASK_ID
494
- try:
495
- decoded_token = tokenizer.decode([current_tok_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)
496
- display_token = MASK_TOKEN if current_tok_id == MASK_ID else decoded_token
497
- except Exception: display_token = f"[ID:{current_tok_id}]"
498
- color = None; token_to_display = display_token
499
- if current_tok_id == MASK_ID: color = "#444444"
500
- elif previous_tok_id == MASK_ID: color = "#66CC66"
501
- else: color = "#6699CC"
502
- should_hide = (PAD_ID is not None and current_tok_id == PAD_ID) or \
503
- (EOS_ID is not None and current_tok_id == EOS_ID)
504
- if should_hide and previous_tok_id == current_tok_id: token_to_display = ""; color = None
505
- if token_to_display: vis_data_final.append((token_to_display, color))
506
- # --- End Final Vis Formatting ---
507
-
508
- # Yield the FINAL updated history list
509
- yield history, vis_data_final, final_response_text
510
  print("Visualization streaming complete.")
511
 
512
  except Exception as e:
513
  print(f"Error during generation or processing: {e}")
514
  import traceback
515
  traceback.print_exc()
516
- # Yield the history state as it was when the error occurred
517
- yield history, [("Error during generation.", "red")], ""
 
 
 
518
  return
519
 
520
 
@@ -528,13 +445,12 @@ def create_chatbot_demo():
528
  gr.Markdown("# Dream 7B - Diffusion Language Model Demo")
529
  gr.Markdown(
530
  "[[Model Card](https://huggingface.co/Dream-org/Dream-v0-Instruct-7B)] "
531
- "[[Blog](https://hkunlp.github.io/blog/2025/dream/)]" # Note: Link might be hypothetical
532
  )
533
 
534
- # STATE MANAGEMENT: Use a hidden state variable to store the actual list
535
- _chat_history_store = gr.State([])
536
 
537
- # UI COMPONENTS
538
  with gr.Row():
539
  with gr.Column(scale=3):
540
  chatbot_ui = gr.Chatbot(
@@ -542,39 +458,31 @@ def create_chatbot_demo():
542
  height=500,
543
  show_copy_button=True,
544
  bubble_full_width=False,
 
545
  )
546
  with gr.Group():
547
  with gr.Row():
548
  user_input = gr.Textbox(
549
- label="Your Message",
550
- placeholder="Type your message here...",
551
- scale=7,
552
- autofocus=True,
553
- show_label=False,
554
- container=False
555
  )
556
  send_btn = gr.Button("Send", scale=1, variant="primary")
557
  constraints_input = gr.Textbox(
558
  label="Word Constraints (Optional)",
559
- info="Place words at specific positions (0-indexed from start of generation). Format: 'pos:word, pos:word,...'. Example: '0:Once, 5:upon, 10:time'",
560
- placeholder="0:Hello, 10:world",
561
- value=""
562
  )
563
  with gr.Column(scale=2):
564
  output_vis = gr.HighlightedText(
565
- label="Denoising Process Visualization",
566
- combine_adjacent=False,
567
- show_legend=True,
568
- interactive=False
569
  )
570
  response_text_display = gr.Textbox(
571
- label="Generated Response",
572
- interactive=False,
573
- lines=5
574
  )
575
 
576
- # Advanced generation settings
577
  with gr.Accordion("Generation Settings", open=False):
 
578
  with gr.Row():
579
  gen_length = gr.Slider(minimum=16, maximum=512, value=128, step=8, label="Max New Tokens")
580
  steps = gr.Slider(minimum=8, maximum=512, value=128, step=8, label="Diffusion Steps")
@@ -589,84 +497,89 @@ def create_chatbot_demo():
589
  with gr.Row():
590
  visualization_delay = gr.Slider(minimum=0.0, maximum=0.5, value=0.03, step=0.01, label="Visualization Delay (seconds)")
591
 
592
- # Clear button
593
  clear_btn = gr.Button("Clear Conversation")
594
 
595
- # --- Event Handlers ---
596
 
597
- def add_user_message_to_history(message: str, history_store: List[List[Optional[str]]]):
598
- """Adds user message, clears input, prepares for bot response."""
 
 
 
599
  if not message.strip():
600
  gr.Warning("Please enter a message.")
601
- # Return unchanged history store, history for UI, empty input, empty vis, empty response
602
- return history_store, history_store, "", [], ""
603
- # Append user message with placeholder for bot response
604
- history_store.append([message, None])
605
- # Return updated history store for the state, history for the UI, clear other fields
606
- return history_store, history_store, "", [], ""
607
-
608
- def clear_conversation():
609
- """Clears the chat history, visualization, and response text."""
610
- # Return empty values for all relevant outputs
611
- return [], [], "", [], "" # History store, chatbot UI, input, vis, response text
612
 
613
  # --- Connect UI elements ---
614
 
615
- # Define the inputs for the generation function once
616
  generation_inputs = [
617
- _chat_history_store, gen_length, steps, constraints_input,
618
  temperature, top_p, top_k, remasking_strategy, alg_temp,
619
  visualization_delay
620
  ]
621
- # Define the outputs for the generation function's yield values
622
- # Yields: history_list, vis_data, response_text
623
- # CRITICAL FIX: Map the first yielded value (history_list) back to _chat_history_store
624
- # as well as chatbot_ui.
625
- generation_outputs = [_chat_history_store, chatbot_ui, output_vis, response_text_display]
 
 
 
 
 
 
 
 
 
626
 
627
- # Handle Textbox Submission (Enter key)
628
  submit_listener = user_input.submit(
629
- fn=add_user_message_to_history,
630
- inputs=[user_input, _chat_history_store],
631
- # Outputs of step 1: update store, UI, clear inputs/outputs
632
- outputs=[_chat_history_store, chatbot_ui, user_input, output_vis, response_text_display]
633
- )
634
- # Chain the bot response generation after the user message is added
635
- submit_listener.then(
636
  fn=generate_dream_response,
637
- inputs=generation_inputs, # Passes the updated _chat_history_store
638
- # Outputs of step 2: **UPDATE STORE**, UI, vis, response text
639
- outputs=generation_outputs, # Maps the final yielded history back to the store
640
  show_progress="hidden"
641
  )
642
 
643
- # Handle Send Button Click
644
  click_listener = send_btn.click(
645
- fn=add_user_message_to_history,
646
- inputs=[user_input, _chat_history_store],
647
- outputs=[_chat_history_store, chatbot_ui, user_input, output_vis, response_text_display]
648
- )
649
- # Chain the bot response generation after the user message is added
650
- click_listener.then(
651
  fn=generate_dream_response,
652
  inputs=generation_inputs,
653
- # Outputs of step 2: **UPDATE STORE**, UI, vis, response text
654
- outputs=generation_outputs, # Map final history back to store here too
655
  show_progress="hidden"
656
  )
657
 
658
- # Clear Button Action
659
  clear_btn.click(
660
- clear_conversation,
661
  inputs=[],
662
- # Ensure clear updates the state variable too
663
- outputs=[_chat_history_store, chatbot_ui, user_input, output_vis, response_text_display]
 
 
664
  )
665
 
666
  return demo
667
 
 
668
  # --- Launch ---
669
  if __name__ == "__main__":
670
  demo = create_chatbot_demo()
671
- # Use queue for handling multiple users and streaming
672
- demo.queue().launch(debug=True, share=False) # Set share=True for public link
 
9
  import re
10
  from typing import List, Dict, Tuple, Optional
11
  import torch.distributions as dists # Added import
 
12
 
13
  # --- START: Copied Helper functions from generation_utils.py ---
14
+ # [Keep the copied functions: top_p_logits, top_k_logits, sample_tokens]
 
15
  def top_p_logits(logits, top_p=None):
16
  """ Applies top-p filtering to logits. """
17
  if top_p is None or top_p >= 1.0:
 
19
  sorted_logits, sorted_indices = torch.sort(logits, descending=True)
20
  cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
21
  sorted_indices_to_remove = cumulative_probs > top_p
 
22
  sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
23
  sorted_indices_to_remove[..., 0] = 0
 
24
  mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
25
  mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
26
  logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
 
30
  """ Applies top-k filtering to logits. """
31
  if top_k is None or top_k <= 0:
32
  return logits
33
+ top_k = min(top_k, logits.size(-1))
 
 
 
34
  indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
35
  logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
36
  return logits
 
38
  def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False):
39
  """ Samples tokens based on logits and calculates confidence. """
40
  if temperature > 0:
 
41
  safe_temp = max(temperature, 1e-6)
42
  logits = logits / safe_temp
43
+ if top_p is not None and 0.0 < top_p < 1.0:
44
  logits = top_p_logits(logits, top_p)
45
+ if top_k is not None and top_k > 0:
46
  logits = top_k_logits(logits, top_k)
47
+ is_all_neg_inf = torch.all(logits == torch.finfo(logits.dtype).min, dim=-1, keepdim=True)
 
 
48
  if torch.any(is_all_neg_inf):
49
+ uniform_logits = torch.zeros_like(logits)
 
50
  logits = torch.where(is_all_neg_inf, uniform_logits, logits)
 
51
  probs = torch.softmax(logits, dim=-1)
52
+ probs = torch.clamp(probs, min=0.0)
53
+ probs = probs / probs.sum(dim=-1, keepdim=True)
54
+ probs = torch.nan_to_num(probs, nan=0.0)
 
 
 
 
 
 
55
  if temperature > 0:
56
  try:
 
 
 
 
 
 
57
  x0 = dists.Categorical(probs=probs).sample()
58
  confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
59
+ except Exception as e:
60
  print(f"Warning: Error during Categorical sampling: {e}. Falling back to argmax.")
61
  confidence, x0 = probs.max(dim=-1)
62
+ else:
63
  confidence, x0 = probs.max(dim=-1)
 
64
  if margin_confidence:
65
  sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
 
66
  top1_probs = sorted_probs[..., 0]
67
+ top2_probs = sorted_probs[..., 1] if sorted_probs.shape[-1] > 1 else top1_probs
68
  confidence = top1_probs - top2_probs
 
69
  if neg_entropy:
70
+ epsilon = 1e-10
71
+ log_probs = torch.log(probs + epsilon)
72
+ confidence = torch.sum(probs * log_probs, dim=-1)
 
 
 
73
  confidence = torch.nan_to_num(confidence, nan=0.0)
 
74
  return confidence, x0
75
  # --- END: Copied Helper functions ---
76
 
77
 
78
+ # [Keep model loading, constants]
 
79
  config = AutoConfig.from_pretrained("Dream-org/Dream-v0-Instruct-7B", trust_remote_code=True)
 
 
80
  model_path = "Dream-org/Dream-v0-Instruct-7B"
 
 
81
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
82
  print(f"Using device: {device}")
 
 
83
  print("Loading tokenizer...")
84
  tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
85
  print("Loading model...")
 
86
  model = AutoModel.from_pretrained(
87
  model_path,
88
+ torch_dtype=torch.bfloat16 if device == 'cuda' else torch.float32,
89
  trust_remote_code=True,
90
+ attn_implementation="sdpa"
91
  )
92
  model = model.to(device).eval()
93
  print("Model loaded.")
 
 
94
  MASK_TOKEN = tokenizer.mask_token
95
+ MASK_ID = tokenizer.mask_token_id
96
+ PAD_ID = tokenizer.pad_token_id
97
+ EOS_ID = tokenizer.eos_token_id
98
+ if MASK_ID is None: raise ValueError("Cannot determine MASK_ID.")
 
 
 
 
 
 
 
 
 
99
  SPECIAL_TOKEN_IDS = {PAD_ID, EOS_ID, MASK_ID}
100
  try:
101
  IM_START_ID = tokenizer.convert_tokens_to_ids("<|im_start|>")
102
  IM_END_ID = tokenizer.convert_tokens_to_ids("<|im_end|>")
103
+ SPECIAL_TOKEN_IDS.add(IM_START_ID)
104
+ SPECIAL_TOKEN_IDS.add(IM_END_ID)
105
+ except KeyError: IM_START_ID, IM_END_ID = None, None
 
 
 
106
 
107
 
108
+ # --- Helper Functions ---
109
  def parse_constraints(constraints_text: str) -> Dict[int, List[int]]:
110
+ """ Parses word constraints. """
111
  constraints = {}
112
+ if not constraints_text: return constraints
 
 
 
113
  parts = constraints_text.split(',')
 
114
  for part in parts:
115
  part = part.strip()
116
+ if ':' not in part: continue
 
117
  pos_str, word = part.split(':', 1)
118
  try:
119
  pos = int(pos_str.strip())
120
  word = word.strip()
121
  token_ids = []
122
+ if word:
 
123
  text_to_encode = (" " + word) if (pos > 0 and not word.startswith(" ")) else word
124
  token_ids = tokenizer.encode(text_to_encode, add_special_tokens=False)
125
+ if token_ids and pos >= 0: constraints[pos] = token_ids
126
+ elif not token_ids and word: print(f"Warning: Could not tokenize constraint word '{word}'")
127
+ except ValueError: print(f"Warning: Invalid position '{pos_str}' in constraint part '{part}'")
128
+ except Exception as e: print(f"Warning: Error processing constraint '{part}': {e}")
 
 
 
 
 
 
 
 
 
129
  return constraints
130
 
 
131
  def format_chat_history(history: List[List[Optional[str]]]) -> List[Dict[str, str]]:
132
+ """
133
+ Formats chat history [[user, bot], [user, bot]] into [{'role': 'user', 'content': ...}, ...]
134
+ for the tokenizer's chat template.
135
+ """
136
  messages = []
137
+ # Ensure history is not empty and is properly structured
138
+ if not history:
139
+ return messages
140
+ for turn in history:
141
+ if not isinstance(turn, (list, tuple)) or len(turn) != 2:
142
+ print(f"Warning: Skipping malformed history turn: {turn}")
143
+ continue
144
+ user_msg, assistant_msg = turn
145
+ if user_msg is not None: # Check if user message exists
146
+ # Ensure content is a string
147
+ user_content = str(user_msg) if user_msg is not None else ""
148
+ messages.append({"role": "user", "content": user_content})
149
+ # Add assistant message only if it exists and is not None
150
  if assistant_msg is not None:
151
+ assistant_content = str(assistant_msg) if assistant_msg is not None else ""
152
+ messages.append({"role": "assistant", "content": assistant_content})
153
+ # print(f"Formatted messages for template: {messages}") # Debug
154
  return messages
155
 
156
  def apply_constraints_to_state(
157
+ x: torch.Tensor, prompt_length: int, total_length: int,
158
+ parsed_constraints: Dict[int, List[int]], current_step: Optional[int] = None
 
 
 
159
  ) -> torch.Tensor:
160
+ """ Applies constraints to the state tensor `x`. """
161
+ modified_x = x.clone()
162
  for rel_pos, word_token_ids in parsed_constraints.items():
163
  abs_start_pos = prompt_length + rel_pos
164
  abs_end_pos = abs_start_pos + len(word_token_ids)
 
 
165
  if abs_start_pos < total_length and abs_end_pos <= total_length:
166
  try:
167
  constraint_tensor = torch.tensor(word_token_ids, dtype=torch.long, device=modified_x.device)
 
168
  modified_x[0, abs_start_pos:abs_end_pos] = constraint_tensor
169
+ except IndexError: print(f"Warning (Step {current_step}): Constraint OOB: {rel_pos}")
170
+ except Exception as e: print(f"Warning (Step {current_step}): Constraint failed {rel_pos}: {e}")
 
 
171
  return modified_x
172
 
173
 
174
  # --- Core Generation Logic with Live Visualization ---
175
 
176
+ @spaces.GPU
177
+ @torch.no_grad()
178
  def generate_dream_response(
179
+ history: List[List[Optional[str]]], # IMPORTANT: This is the *full* history from the state
180
  gen_length: int,
181
  steps: int,
182
  constraints_text: str,
 
186
  alg: str,
187
  alg_temp: Optional[float],
188
  visualization_delay: float
189
+ ): # No return type annotation for generators in older Python? Or use -> Iterator[Tuple[...]]
190
  """ Generates text step-by-step and yields visualization states live. """
191
 
192
+ # Ensure history is valid before proceeding
193
+ if not history or not history[-1] or history[-1][0] is None:
194
+ # Yield the current (potentially empty) history back
195
+ yield history, [("No valid input message found.", "red")], ""
 
 
196
  return
197
 
198
  # --- 1. Preparation ---
199
+ # Use the *entire* history received from the state for context
200
  messages_for_template = format_chat_history(history)
201
  parsed_constraints = parse_constraints(constraints_text)
202
 
 
205
  messages_for_template,
206
  return_tensors="pt",
207
  return_dict=True,
208
+ add_generation_prompt=True # This adds the assistant prompt turn
209
  )
210
  input_ids = inputs.input_ids.to(device)
211
  prompt_attention_mask = inputs.attention_mask.to(device) if 'attention_mask' in inputs else torch.ones_like(input_ids)
212
  prompt_length = input_ids.shape[1]
213
+ # print(f"Prompt length for model: {prompt_length}") # Debug
214
+ # print(f"Input IDs to model (first 50): {input_ids[0, :50].tolist()}") # Debug
215
+
216
  except Exception as e:
217
  print(f"Error applying chat template: {e}")
218
+ # Yield the current history back with an error message
219
  yield history, [("Error preparing input.", "red")], ""
220
  return
221
 
 
229
  initial_generation_part = torch.full((1, gen_length), MASK_ID, dtype=torch.long, device=device)
230
  x = torch.cat((input_ids, initial_generation_part), dim=1)
231
 
232
+ # --- Prepare Attention Mask ---
233
  generation_attention_mask = torch.ones((1, gen_length), dtype=torch.long, device=device)
234
  full_attention_mask_long = torch.cat((prompt_attention_mask, generation_attention_mask), dim=1)
 
235
  attention_mask_for_model = full_attention_mask_long.to(model.dtype)
236
  large_neg_val = torch.finfo(model.dtype).min
237
  attention_mask_for_model = (1.0 - attention_mask_for_model) * large_neg_val
238
+ attention_mask_for_model = attention_mask_for_model.unsqueeze(1).unsqueeze(2) # Shape [B, 1, 1, N]
239
 
240
  timesteps = torch.linspace(1, eps, steps + 1, device=device)
241
  x = apply_constraints_to_state(x, prompt_length, total_length, parsed_constraints, current_step=-1)
242
 
243
+ # --- 3. Visualization & State Setup ---
244
  previous_tokens_vis = None
245
+ # Use the passed-in history directly. We will modify the *last* item's assistant response.
246
+ # No need for history_copy if we are careful. Let's try modifying `history` directly.
247
+ # IMPORTANT: Gradio state needs the component to receive the *entire object* back if it's mutated.
248
+ # So yielding the modified `history` list itself should work.
249
+ history_for_yield = history # Reference the original list
250
 
251
  # --- 4. Initial Yield (Masked State) ---
252
  initial_generated_tokens = x[0, prompt_length:].cpu()
253
  vis_data_initial = []
254
  for tok_id in initial_generated_tokens.tolist():
255
+ vis_data_initial.append((MASK_TOKEN, "#444444"))
 
 
 
256
  previous_tokens_vis = initial_generated_tokens
257
+ # Yield the *current* history (with None for last bot msg)
258
+ yield history_for_yield, vis_data_initial, ""
259
  time.sleep(visualization_delay)
260
 
261
  # --- 5. Step-by-Step Diffusion Loop ---
262
  try:
263
  start_time = time.time()
264
+ current_response_text = "" # Store intermediate text
265
+
266
  for i in range(steps):
267
  mask_index = (x == MASK_ID)
268
  if not mask_index.any():
269
  print(f"No mask tokens left at step {i}. Stopping early.")
270
  break
271
 
 
272
  outputs = model(
273
  input_ids=x,
274
  attention_mask=attention_mask_for_model,
275
+ position_ids=None, use_cache=False, return_dict=True
 
 
276
  )
277
  logits = outputs.logits
278
+ logits = torch.cat([logits[:,:1], logits[:, :-1]], dim=1)
279
 
280
  mask_logits = logits[mask_index]
281
  if mask_logits.numel() == 0:
282
  print(f"No masked tokens found for logit selection at step {i}. Stopping.")
283
  break
284
 
285
+ t = timesteps[i]; s = timesteps[i + 1]
 
 
286
  x_new_masked_part = torch.full_like(x[mask_index], MASK_ID, device=device, dtype=torch.long)
287
 
288
+ # [Sampling logic remains the same as previous working version]
289
  if alg == 'origin':
290
  p_transfer = (1.0 - s / t) if i < steps - 1 else 1.0
291
  num_masked = mask_logits.shape[0]
292
  transfer_indices_relative = torch.rand(num_masked, device=device) < p_transfer
293
  logits_to_sample = mask_logits[transfer_indices_relative]
 
294
  if logits_to_sample.numel() > 0:
295
  _, sampled_tokens = sample_tokens(logits_to_sample, temperature=temperature, top_p=top_p_val, top_k=top_k_val)
296
  x_new_masked_part[transfer_indices_relative] = sampled_tokens
297
+ else: # Confidence-based
298
+ use_margin = (alg == 'topk_margin'); use_entropy = (alg == 'entropy')
 
 
299
  confidence, x0_candidates = sample_tokens(
300
+ mask_logits, temperature=temperature, top_p=top_p_val, top_k=top_k_val,
301
+ margin_confidence=use_margin, neg_entropy=use_entropy
 
 
 
 
302
  )
 
303
  num_mask_token = mask_logits.shape[0]
304
  target_num_revealed_float = num_mask_token * (1.0 - s / t)
305
  number_transfer_tokens = int(target_num_revealed_float) if i < steps - 1 else num_mask_token
 
306
  if number_transfer_tokens > 0:
307
  num_samples = min(number_transfer_tokens, num_mask_token)
308
  if num_samples > 0:
309
+ transfer_indices_relative = torch.tensor([], dtype=torch.long, device=device) # Init empty
310
+ if alg_temp_val is None or alg_temp_val <= 0: # Top-k
311
  sort_metric = confidence if alg != 'entropy' else -confidence
312
  k_topk = min(num_samples, sort_metric.numel())
313
+ if k_topk > 0: _, transfer_indices_relative = torch.topk(sort_metric, k=k_topk)
314
+ else: # Sampled
 
 
315
  if confidence.numel() > 0:
316
  conf_probs = confidence / alg_temp_val
317
  conf_probs = torch.nan_to_num(conf_probs, nan=0.0, posinf=1e9, neginf=-1e9)
 
319
  conf_probs = F.softmax(conf_probs, dim=-1)
320
  conf_probs = torch.clamp(conf_probs, min=0.0)
321
  conf_probs = torch.nan_to_num(conf_probs, nan=0.0)
 
322
  prob_sum = conf_probs.sum()
323
  target_sum_tensor = torch.tensor(1.0, device=device, dtype=prob_sum.dtype)
324
  if not torch.isclose(prob_sum, target_sum_tensor, atol=1e-4) and prob_sum > 0:
325
  safe_prob_sum = torch.max(prob_sum, torch.tensor(1e-12, device=device, dtype=prob_sum.dtype))
326
  conf_probs = conf_probs / safe_prob_sum
 
327
  final_prob_sum_check = conf_probs.sum()
328
  if conf_probs.numel() > 0 and num_samples > 0 and torch.all(conf_probs >= 0) and torch.isclose(final_prob_sum_check, target_sum_tensor, atol=1e-4):
329
+ try: transfer_indices_relative = torch.multinomial(conf_probs, num_samples=num_samples, replacement=False)
330
+ except RuntimeError as e: print(f"W{i}: Multinomial failed ('{e}'). Fallback.") # Fallback handled below
331
+ if transfer_indices_relative.numel() == 0: # Fallback if sampling failed or wasn't possible
 
 
 
 
 
 
 
332
  sort_metric = confidence if alg != 'entropy' else -confidence
333
+ k_fallback = min(num_samples, sort_metric.numel())
334
+ if k_fallback > 0: _, transfer_indices_relative = torch.topk(sort_metric, k=k_fallback)
335
+ # Apply transfer
 
 
 
336
  if transfer_indices_relative.numel() > 0:
337
+ valid_indices = transfer_indices_relative < x0_candidates.shape[0]
338
+ valid_transfer_indices = transfer_indices_relative[valid_indices]
339
+ if valid_transfer_indices.numel() > 0 and valid_transfer_indices.max() < x_new_masked_part.shape[0]:
340
+ x_new_masked_part[valid_transfer_indices] = x0_candidates[valid_transfer_indices].clone()
341
+
 
 
 
342
 
343
  x[mask_index] = x_new_masked_part
344
  x = apply_constraints_to_state(x, prompt_length, total_length, parsed_constraints, current_step=i)
 
346
  # --- Yield Visualization ---
347
  current_generated_tokens = x[0, prompt_length:].cpu()
348
  vis_data = []
349
+ # [Visualization formatting logic remains the same]
350
  for j in range(gen_length):
351
  current_tok_id = current_generated_tokens[j].item()
352
  previous_tok_id = previous_tokens_vis[j].item() if previous_tokens_vis is not None and j < len(previous_tokens_vis) else MASK_ID
 
358
  if current_tok_id == MASK_ID: color = "#444444"
359
  elif previous_tok_id == MASK_ID: color = "#66CC66"
360
  else: color = "#6699CC"
361
+ should_hide = (PAD_ID is not None and current_tok_id == PAD_ID) or (EOS_ID is not None and current_tok_id == EOS_ID)
 
362
  if should_hide and previous_tok_id == current_tok_id: token_to_display = ""; color = None
363
  if token_to_display: vis_data.append((token_to_display, color))
364
+ # ---
365
 
366
  previous_tokens_vis = current_generated_tokens
367
 
368
+ # --- Update intermediate response text ---
369
  intermediate_response_tokens = x[0, prompt_length:]
370
+ current_response_text = tokenizer.decode(
371
  intermediate_response_tokens,
372
  skip_special_tokens=True,
373
  clean_up_tokenization_spaces=True
374
  ).strip()
375
 
376
+ # --- Update history for yield ---
377
+ # Update the placeholder in the *last turn* of the history list
378
+ if history_for_yield and history_for_yield[-1]:
379
+ history_for_yield[-1][1] = current_response_text + "..." # Indicate streaming
380
+
381
+ # --- Yield current state ---
382
+ yield history_for_yield, vis_data, current_response_text
383
  time.sleep(visualization_delay)
384
+ # --- End loop iteration ---
385
 
386
  end_time = time.time()
387
  print(f"Dream generation finished in {end_time - start_time:.2f} seconds.")
 
395
  clean_up_tokenization_spaces=True
396
  ).strip()
397
 
398
+ # Update the history definitively with the final text
399
+ if history_for_yield and history_for_yield[-1]:
400
+ history_for_yield[-1][1] = final_response_text
 
401
 
402
+ # Format final visualization
403
  final_generated_tokens = x[0, prompt_length:].cpu()
404
  vis_data_final = []
405
+ # [Final visualization formatting logic remains the same]
406
  for j in range(gen_length):
407
+ current_tok_id = final_generated_tokens[j].item()
408
+ previous_tok_id = previous_tokens_vis[j].item() if previous_tokens_vis is not None and j < len(previous_tokens_vis) else MASK_ID
409
+ try:
410
+ decoded_token = tokenizer.decode([current_tok_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)
411
+ display_token = MASK_TOKEN if current_tok_id == MASK_ID else decoded_token
412
+ except Exception: display_token = f"[ID:{current_tok_id}]"
413
+ color = None; token_to_display = display_token
414
+ if current_tok_id == MASK_ID: color = "#444444"
415
+ elif previous_tok_id == MASK_ID: color = "#66CC66"
416
+ else: color = "#6699CC"
417
+ should_hide = (PAD_ID is not None and current_tok_id == PAD_ID) or (EOS_ID is not None and current_tok_id == EOS_ID)
418
+ if should_hide and previous_tok_id == current_tok_id: token_to_display = ""; color = None
419
+ if token_to_display: vis_data_final.append((token_to_display, color))
420
+ # ---
421
+
422
+ # Yield the final state
423
+ yield history_for_yield, vis_data_final, final_response_text
 
424
  print("Visualization streaming complete.")
425
 
426
  except Exception as e:
427
  print(f"Error during generation or processing: {e}")
428
  import traceback
429
  traceback.print_exc()
430
+ # Ensure the history state reflects the error somehow? Or just yield error vis.
431
+ # Yield the history *as it was* when the error occurred.
432
+ if history_for_yield and history_for_yield[-1]:
433
+ history_for_yield[-1][1] = f"<Error: {e}>" # Put error in bot response
434
+ yield history_for_yield, [("Error during generation.", "red")], ""
435
  return
436
 
437
 
 
445
  gr.Markdown("# Dream 7B - Diffusion Language Model Demo")
446
  gr.Markdown(
447
  "[[Model Card](https://huggingface.co/Dream-org/Dream-v0-Instruct-7B)] "
448
+ "[[Blog](https://hkunlp.github.io/blog/2025/dream/)]"
449
  )
450
 
451
+ # Use a single state variable for the history list
452
+ chat_history_state = gr.State([])
453
 
 
454
  with gr.Row():
455
  with gr.Column(scale=3):
456
  chatbot_ui = gr.Chatbot(
 
458
  height=500,
459
  show_copy_button=True,
460
  bubble_full_width=False,
461
+ # value=[] # Initial value set by state binding later
462
  )
463
  with gr.Group():
464
  with gr.Row():
465
  user_input = gr.Textbox(
466
+ label="Your Message", placeholder="Type your message here...",
467
+ scale=7, autofocus=True, show_label=False, container=False
 
 
 
 
468
  )
469
  send_btn = gr.Button("Send", scale=1, variant="primary")
470
  constraints_input = gr.Textbox(
471
  label="Word Constraints (Optional)",
472
+ info="Format: 'pos:word, pos:word,...'. Example: '0:Once, 5:upon, 10:time'",
473
+ placeholder="0:Hello, 10:world", value=""
 
474
  )
475
  with gr.Column(scale=2):
476
  output_vis = gr.HighlightedText(
477
+ label="Denoising Process Visualization", combine_adjacent=True,
478
+ show_legend=False, interactive=False
 
 
479
  )
480
  response_text_display = gr.Textbox(
481
+ label="Generated Response (Live)", interactive=False, lines=5
 
 
482
  )
483
 
 
484
  with gr.Accordion("Generation Settings", open=False):
485
+ # [Settings sliders remain the same]
486
  with gr.Row():
487
  gen_length = gr.Slider(minimum=16, maximum=512, value=128, step=8, label="Max New Tokens")
488
  steps = gr.Slider(minimum=8, maximum=512, value=128, step=8, label="Diffusion Steps")
 
497
  with gr.Row():
498
  visualization_delay = gr.Slider(minimum=0.0, maximum=0.5, value=0.03, step=0.01, label="Visualization Delay (seconds)")
499
 
500
+
501
  clear_btn = gr.Button("Clear Conversation")
502
 
503
+ # --- Event Handler Functions ---
504
 
505
+ def add_user_message(message: str, history: List[List[Optional[str]]]):
506
+ """
507
+ Adds the user message to the history state and prepares the UI
508
+ for the bot's response (clearing previous outputs).
509
+ """
510
  if not message.strip():
511
  gr.Warning("Please enter a message.")
512
+ # Return unchanged history and empty outputs
513
+ return history, history, "", [], ""
514
+ # Append new turn with user message and None placeholder for bot response
515
+ history.append([message, None])
516
+ # Return updated history (for state), history (for immediate UI update),
517
+ # empty input, empty vis, empty response text.
518
+ return history, history, "", [], ""
519
+
520
+ def clear_all():
521
+ """Clears state and all relevant UI components."""
522
+ return [], [], "", [], "" # state, chatbot, input, vis, response text
523
 
524
  # --- Connect UI elements ---
525
 
526
+ # Define inputs/outputs for the generator
527
  generation_inputs = [
528
+ chat_history_state, gen_length, steps, constraints_input,
529
  temperature, top_p, top_k, remasking_strategy, alg_temp,
530
  visualization_delay
531
  ]
532
+ # Generator yields: history_list, vis_data, response_text
533
+ generation_outputs = [chatbot_ui, output_vis, response_text_display]
534
+
535
+ # Chain the actions: Submit/Click -> add_user_message -> generate_dream_response
536
+
537
+ # 1. User submits message (Enter or Button)
538
+ user_interaction = [user_input, chat_history_state]
539
+ outputs_after_user_add = [
540
+ chat_history_state, # Update the state
541
+ chatbot_ui, # Update chatbot UI immediately
542
+ user_input, # Clear user input box
543
+ output_vis, # Clear visualization
544
+ response_text_display # Clear response text box
545
+ ]
546
 
 
547
  submit_listener = user_input.submit(
548
+ fn=add_user_message,
549
+ inputs=user_interaction,
550
+ outputs=outputs_after_user_add
551
+ ).then( # 2. Trigger generation AFTER user message is added and UI cleared
 
 
 
552
  fn=generate_dream_response,
553
+ inputs=generation_inputs, # Pass the updated state and parameters
554
+ outputs=generation_outputs, # Stream updates to chatbot, vis, text
 
555
  show_progress="hidden"
556
  )
557
 
 
558
  click_listener = send_btn.click(
559
+ fn=add_user_message,
560
+ inputs=user_interaction,
561
+ outputs=outputs_after_user_add
562
+ ).then( # 2. Trigger generation AFTER user message is added and UI cleared
 
 
563
  fn=generate_dream_response,
564
  inputs=generation_inputs,
565
+ outputs=generation_outputs,
 
566
  show_progress="hidden"
567
  )
568
 
569
+ # 3. Clear Button
570
  clear_btn.click(
571
+ clear_all,
572
  inputs=[],
573
+ outputs=[
574
+ chat_history_state, chatbot_ui, user_input,
575
+ output_vis, response_text_display
576
+ ]
577
  )
578
 
579
  return demo
580
 
581
+
582
  # --- Launch ---
583
  if __name__ == "__main__":
584
  demo = create_chatbot_demo()
585
+ demo.queue().launch(debug=True, share=False)