Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -239,7 +239,7 @@ def apply_constraints_to_state(
|
|
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
|
243 |
gen_length: int,
|
244 |
steps: int,
|
245 |
constraints_text: str,
|
@@ -252,12 +252,16 @@ def generate_dream_response(
|
|
252 |
) -> List[Tuple[str, str]]:
|
253 |
""" Generates text step-by-step and yields visualization states live. """
|
254 |
|
255 |
-
|
256 |
-
|
|
|
|
|
|
|
|
|
257 |
return
|
258 |
|
259 |
# --- 1. Preparation ---
|
260 |
-
|
261 |
messages_for_template = format_chat_history(history)
|
262 |
parsed_constraints = parse_constraints(constraints_text)
|
263 |
|
@@ -266,15 +270,13 @@ def generate_dream_response(
|
|
266 |
messages_for_template,
|
267 |
return_tensors="pt",
|
268 |
return_dict=True,
|
269 |
-
add_generation_prompt=True
|
270 |
)
|
271 |
input_ids = inputs.input_ids.to(device)
|
272 |
-
# Ensure prompt_attention_mask is also on the correct device and handle missing mask
|
273 |
prompt_attention_mask = inputs.attention_mask.to(device) if 'attention_mask' in inputs else torch.ones_like(input_ids)
|
274 |
prompt_length = input_ids.shape[1]
|
275 |
except Exception as e:
|
276 |
print(f"Error applying chat template: {e}")
|
277 |
-
# Yield current history (with None), error message, empty text
|
278 |
yield history, [("Error preparing input.", "red")], ""
|
279 |
return
|
280 |
|
@@ -288,38 +290,33 @@ def generate_dream_response(
|
|
288 |
initial_generation_part = torch.full((1, gen_length), MASK_ID, dtype=torch.long, device=device)
|
289 |
x = torch.cat((input_ids, initial_generation_part), dim=1)
|
290 |
|
291 |
-
|
292 |
-
|
293 |
-
full_attention_mask_long = torch.cat((prompt_attention_mask, generation_attention_mask), dim=1) # Shape [B, N]
|
294 |
|
295 |
-
attention_mask_for_model = full_attention_mask_long.to(model.dtype)
|
296 |
large_neg_val = torch.finfo(model.dtype).min
|
297 |
attention_mask_for_model = (1.0 - attention_mask_for_model) * large_neg_val
|
298 |
-
attention_mask_for_model = attention_mask_for_model.unsqueeze(1).unsqueeze(2)
|
299 |
|
300 |
-
# Timesteps
|
301 |
timesteps = torch.linspace(1, eps, steps + 1, device=device)
|
302 |
-
|
303 |
-
# Apply initial constraints
|
304 |
x = apply_constraints_to_state(x, prompt_length, total_length, parsed_constraints, current_step=-1)
|
305 |
|
306 |
# --- 3. Visualization Setup ---
|
307 |
previous_tokens_vis = None
|
308 |
final_response_text = ""
|
309 |
-
#
|
310 |
-
history_copy = [list(item) for item in history]
|
311 |
|
312 |
# --- 4. Initial Yield (Masked State) ---
|
313 |
initial_generated_tokens = x[0, prompt_length:].cpu()
|
314 |
vis_data_initial = []
|
315 |
for tok_id in initial_generated_tokens.tolist():
|
316 |
display_token = MASK_TOKEN
|
317 |
-
color = "#444444"
|
318 |
vis_data_initial.append((display_token, color))
|
319 |
|
320 |
previous_tokens_vis = initial_generated_tokens
|
321 |
-
# Yield the
|
322 |
-
yield
|
323 |
time.sleep(visualization_delay)
|
324 |
|
325 |
# --- 5. Step-by-Step Diffusion Loop ---
|
@@ -334,19 +331,15 @@ def generate_dream_response(
|
|
334 |
# --- Model Forward Pass ---
|
335 |
outputs = model(
|
336 |
input_ids=x,
|
337 |
-
attention_mask=attention_mask_for_model,
|
338 |
-
position_ids=None,
|
339 |
use_cache=False,
|
340 |
return_dict=True
|
341 |
)
|
342 |
logits = outputs.logits
|
|
|
343 |
|
344 |
-
|
345 |
-
# Shift left, effectively aligning logits[t] with inputs[t]
|
346 |
-
logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1)
|
347 |
-
|
348 |
-
# Select logits for masked positions
|
349 |
-
mask_logits = logits[mask_index] # Shape [num_masked_tokens, V]
|
350 |
if mask_logits.numel() == 0:
|
351 |
print(f"No masked tokens found for logit selection at step {i}. Stopping.")
|
352 |
break
|
@@ -354,9 +347,9 @@ def generate_dream_response(
|
|
354 |
# --- Sampling / Remasking Logic ---
|
355 |
t = timesteps[i]
|
356 |
s = timesteps[i + 1]
|
357 |
-
# Initialize the update tensor for masked positions with MASK_ID
|
358 |
x_new_masked_part = torch.full_like(x[mask_index], MASK_ID, device=device, dtype=torch.long)
|
359 |
|
|
|
360 |
if alg == 'origin':
|
361 |
p_transfer = (1.0 - s / t) if i < steps - 1 else 1.0
|
362 |
num_masked = mask_logits.shape[0]
|
@@ -365,13 +358,11 @@ def generate_dream_response(
|
|
365 |
|
366 |
if logits_to_sample.numel() > 0:
|
367 |
_, sampled_tokens = sample_tokens(logits_to_sample, temperature=temperature, top_p=top_p_val, top_k=top_k_val)
|
368 |
-
# Place sampled tokens into the correct positions within the masked part update
|
369 |
x_new_masked_part[transfer_indices_relative] = sampled_tokens
|
370 |
|
371 |
-
else: # Confidence-based algorithms
|
372 |
use_margin = (alg == 'topk_margin')
|
373 |
use_entropy = (alg == 'entropy')
|
374 |
-
# Sample candidates and get confidence for all masked positions
|
375 |
confidence, x0_candidates = sample_tokens(
|
376 |
mask_logits,
|
377 |
temperature=temperature,
|
@@ -382,129 +373,89 @@ def generate_dream_response(
|
|
382 |
)
|
383 |
|
384 |
num_mask_token = mask_logits.shape[0]
|
385 |
-
# Calculate target number of tokens to reveal in this step
|
386 |
target_num_revealed_float = num_mask_token * (1.0 - s / t)
|
387 |
number_transfer_tokens = int(target_num_revealed_float) if i < steps - 1 else num_mask_token
|
388 |
|
389 |
if number_transfer_tokens > 0:
|
390 |
-
|
391 |
-
num_samples = min(number_transfer_tokens, num_mask_token) # Ensure k <= num_mask_token
|
392 |
if num_samples > 0:
|
393 |
-
transfer_indices_relative = torch.tensor([], dtype=torch.long, device=device) # Initialize
|
394 |
-
if alg_temp_val is None or alg_temp_val <= 0: #
|
395 |
-
# Sort by confidence (higher is better, except for entropy where lower is better)
|
396 |
sort_metric = confidence if alg != 'entropy' else -confidence
|
397 |
-
# Ensure k is not greater than the number of elements
|
398 |
k_topk = min(num_samples, sort_metric.numel())
|
399 |
if k_topk > 0:
|
400 |
_, transfer_indices_relative = torch.topk(sort_metric, k=k_topk)
|
401 |
|
402 |
else: # Sample based on confidence temperature
|
403 |
-
# Ensure confidence has elements before processing
|
404 |
if confidence.numel() > 0:
|
405 |
conf_probs = confidence / alg_temp_val
|
406 |
-
# Handle potential inf/-inf before softmax, ensure non-negative probabilities
|
407 |
conf_probs = torch.nan_to_num(conf_probs, nan=0.0, posinf=1e9, neginf=-1e9)
|
408 |
-
|
409 |
-
conf_probs = torch.clamp(conf_probs - conf_probs.max(), min=-30) # Softmax is invariant to shift
|
410 |
conf_probs = F.softmax(conf_probs, dim=-1)
|
411 |
-
conf_probs = torch.clamp(conf_probs, min=0.0)
|
412 |
-
conf_probs = torch.nan_to_num(conf_probs, nan=0.0)
|
413 |
|
414 |
-
# Normalize probabilities if they don't sum to 1 (within tolerance)
|
415 |
prob_sum = conf_probs.sum()
|
416 |
target_sum_tensor = torch.tensor(1.0, device=device, dtype=prob_sum.dtype)
|
417 |
if not torch.isclose(prob_sum, target_sum_tensor, atol=1e-4) and prob_sum > 0:
|
418 |
safe_prob_sum = torch.max(prob_sum, torch.tensor(1e-12, device=device, dtype=prob_sum.dtype))
|
419 |
conf_probs = conf_probs / safe_prob_sum
|
420 |
|
421 |
-
# Check if probabilities are valid for multinomial sampling
|
422 |
final_prob_sum_check = conf_probs.sum()
|
423 |
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):
|
424 |
try:
|
425 |
transfer_indices_relative = torch.multinomial(conf_probs, num_samples=num_samples, replacement=False)
|
426 |
except RuntimeError as e:
|
427 |
print(f"Warning step {i}: Multinomial sampling failed ('{e}'). Falling back to top-k.")
|
428 |
-
# Fallback to top-k if multinomial fails
|
429 |
sort_metric = confidence if alg != 'entropy' else -confidence
|
430 |
k_multinomial_fallback = min(num_samples, sort_metric.numel())
|
431 |
if k_multinomial_fallback > 0:
|
432 |
_, transfer_indices_relative = torch.topk(sort_metric, k=k_multinomial_fallback)
|
433 |
-
else:
|
434 |
# print(f"Warning step {i}: Invalid probabilities for multinomial sampling (sum={final_prob_sum_check:.4f}). Falling back to top-k.")
|
435 |
sort_metric = confidence if alg != 'entropy' else -confidence
|
436 |
k_multinomial_fallback = min(num_samples, sort_metric.numel())
|
437 |
if k_multinomial_fallback > 0:
|
438 |
_, transfer_indices_relative = torch.topk(sort_metric, k=k_multinomial_fallback)
|
|
|
439 |
|
440 |
-
# Apply the transfer
|
441 |
if transfer_indices_relative.numel() > 0:
|
442 |
-
|
443 |
-
|
444 |
-
max_mask_idx = x_new_masked_part.shape[0] - 1
|
445 |
-
valid_indices_mask = (transfer_indices_relative >= 0) & \
|
446 |
-
(transfer_indices_relative <= max_cand_idx) & \
|
447 |
-
(transfer_indices_relative <= max_mask_idx)
|
448 |
-
valid_transfer_indices = transfer_indices_relative[valid_indices_mask]
|
449 |
-
|
450 |
if valid_transfer_indices.numel() > 0:
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
|
457 |
-
# Update the global state `x` only at the masked positions
|
458 |
x[mask_index] = x_new_masked_part
|
459 |
-
|
460 |
-
# --- Apply Constraints ---
|
461 |
-
# Constraints should be applied *after* sampling/revealing tokens for the step
|
462 |
x = apply_constraints_to_state(x, prompt_length, total_length, parsed_constraints, current_step=i)
|
463 |
|
464 |
# --- Yield Visualization ---
|
465 |
-
current_generated_tokens = x[0, prompt_length:].cpu()
|
466 |
vis_data = []
|
|
|
467 |
for j in range(gen_length):
|
468 |
current_tok_id = current_generated_tokens[j].item()
|
469 |
-
# Ensure previous_tokens_vis exists and index is valid
|
470 |
previous_tok_id = previous_tokens_vis[j].item() if previous_tokens_vis is not None and j < len(previous_tokens_vis) else MASK_ID
|
471 |
-
|
472 |
try:
|
473 |
-
# Use replace='�' to handle potential bytes rendering issues in Gradio HighlightedText
|
474 |
decoded_token = tokenizer.decode([current_tok_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)
|
475 |
display_token = MASK_TOKEN if current_tok_id == MASK_ID else decoded_token
|
476 |
-
except Exception:
|
477 |
-
|
478 |
-
|
479 |
-
color =
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
color = "#6699CC" # Light Blue
|
488 |
-
|
489 |
-
# Hide special tokens (PAD/EOS) if they were already revealed (LLaDA effect)
|
490 |
-
# Ensure PAD_ID and EOS_ID are not None before checking
|
491 |
-
should_hide = False
|
492 |
-
if PAD_ID is not None and current_tok_id == PAD_ID: should_hide = True
|
493 |
-
if EOS_ID is not None and current_tok_id == EOS_ID: should_hide = True
|
494 |
-
# Special check: If PAD and EOS are the same, only hide if it's that ID
|
495 |
-
if PAD_ID == EOS_ID and PAD_ID is not None and current_tok_id == PAD_ID: should_hide = True
|
496 |
-
|
497 |
-
if should_hide and previous_tok_id == current_tok_id:
|
498 |
-
token_to_display = "" # Hide by making empty
|
499 |
-
color = None # No color for hidden
|
500 |
-
|
501 |
-
if token_to_display: # Avoid adding empty strings if hiding
|
502 |
-
vis_data.append((token_to_display, color))
|
503 |
-
|
504 |
-
# Update previous state for the next iteration's color logic
|
505 |
previous_tokens_vis = current_generated_tokens
|
506 |
|
507 |
-
# Decode intermediate response text using the *current* state x
|
508 |
intermediate_response_tokens = x[0, prompt_length:]
|
509 |
intermediate_response_text = tokenizer.decode(
|
510 |
intermediate_response_tokens,
|
@@ -512,13 +463,10 @@ def generate_dream_response(
|
|
512 |
clean_up_tokenization_spaces=True
|
513 |
).strip()
|
514 |
|
515 |
-
#
|
516 |
-
|
517 |
-
history_copy[-1][1] = intermediate_response_text # Update the None placeholder
|
518 |
-
|
519 |
-
# Yield the updated history copy, current vis, and intermediate text
|
520 |
-
yield history_copy, vis_data, intermediate_response_text
|
521 |
time.sleep(visualization_delay)
|
|
|
522 |
|
523 |
end_time = time.time()
|
524 |
print(f"Dream generation finished in {end_time - start_time:.2f} seconds.")
|
@@ -532,45 +480,41 @@ def generate_dream_response(
|
|
532 |
clean_up_tokenization_spaces=True
|
533 |
).strip()
|
534 |
|
535 |
-
# Update
|
536 |
-
if
|
537 |
-
|
|
|
538 |
|
539 |
-
# Format the final visualization state
|
540 |
final_generated_tokens = x[0, prompt_length:].cpu()
|
541 |
vis_data_final = []
|
|
|
542 |
for j in range(gen_length):
|
543 |
current_tok_id = final_generated_tokens[j].item()
|
544 |
previous_tok_id = previous_tokens_vis[j].item() if previous_tokens_vis is not None and j < len(previous_tokens_vis) else MASK_ID
|
545 |
try:
|
546 |
decoded_token = tokenizer.decode([current_tok_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)
|
547 |
display_token = MASK_TOKEN if current_tok_id == MASK_ID else decoded_token
|
548 |
-
except Exception:
|
549 |
-
|
550 |
-
color = None
|
551 |
-
token_to_display = display_token
|
552 |
if current_tok_id == MASK_ID: color = "#444444"
|
553 |
elif previous_tok_id == MASK_ID: color = "#66CC66"
|
554 |
else: color = "#6699CC"
|
555 |
-
|
556 |
-
|
557 |
-
if
|
558 |
-
if EOS_ID is not None and current_tok_id == EOS_ID: should_hide = True
|
559 |
-
if PAD_ID == EOS_ID and PAD_ID is not None and current_tok_id == PAD_ID: should_hide = True
|
560 |
-
|
561 |
-
if should_hide and previous_tok_id == current_tok_id:
|
562 |
-
token_to_display = ""; color = None
|
563 |
if token_to_display: vis_data_final.append((token_to_display, color))
|
|
|
564 |
|
565 |
-
# Yield the
|
566 |
-
yield
|
567 |
print("Visualization streaming complete.")
|
568 |
|
569 |
except Exception as e:
|
570 |
-
print(f"Error during generation or processing
|
|
|
571 |
traceback.print_exc()
|
572 |
-
# Yield the history as it was
|
573 |
-
yield
|
574 |
return
|
575 |
|
576 |
|
|
|
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,
|
|
|
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 |
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 |
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 ---
|
|
|
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
|
|
|
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]
|
|
|
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,
|
|
|
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)
|
393 |
+
conf_probs = torch.clamp(conf_probs - conf_probs.max(), min=-30)
|
|
|
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)
|
435 |
|
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
|
|
|
443 |
try:
|
|
|
444 |
decoded_token = tokenizer.decode([current_tok_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)
|
445 |
display_token = MASK_TOKEN if current_tok_id == MASK_ID else decoded_token
|
446 |
+
except Exception: display_token = f"[ID:{current_tok_id}]"
|
447 |
+
color = None; token_to_display = display_token
|
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,
|
|
|
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 |
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 |
|