import gradio as gr
import torch
import numpy as np
import json
import time
from html import escape as html_escape
from transformers import AutoTokenizer
import os
import importlib
import os
from huggingface_hub import hf_hub_download
import spaces
from dotenv import load_dotenv
from infer import (
load_trained_model,
find_answer_start,
get_noising_schedule,
noisify_answer,
filter_logits,
confidence_guided_noising,
noisify_answer_without_remasking
)
from models import CustomTransformerModel
from model_config import CustomTransformerConfig
# Load .env only when running locally
if os.getenv("HF_TOKEN") is None:
load_dotenv()
hf_token = os.getenv("HF_TOKEN")
if hf_token is None:
raise ValueError("HF_TOKEN is not set")
rng = np.random.default_rng()
def _generate_step(input_ids, top_p, top_k, eos_bias=0.0):
"""Single diffusion inference step. Must be called inside a @spaces.GPU context."""
with torch.no_grad():
input_tensor = torch.tensor([input_ids], dtype=torch.long).to(model.device)
with torch.autocast(device_type=model.device.type, dtype=torch.float16):
logits = model(input_ids=input_tensor)["logits"]
# Apply eos_bias
if eos_bias != 0.0:
logits[0, :, eos_token_id] += eos_bias
logits = filter_logits(logits, top_k=top_k, top_p=top_p)
logits = logits.clamp(min=-1e8, max=1e4)
probs = torch.nn.functional.softmax(logits, dim=-1)[0]
probs = torch.clamp(probs, min=1e-8, max=1.0)
assert torch.all(torch.isfinite(probs)), "Non-finite values in probs!"
assert (probs >= 0).all(), "Negative probs!"
sampled = torch.multinomial(probs, num_samples=1).squeeze(-1).tolist()
# Extract confidence of selected tokens
conf = probs[range(len(sampled)), sampled].cpu().numpy()
return sampled, conf
@spaces.GPU
def run_diffusion_loop(input_ids, answer_start, max_it, pause_length, eos_bias,
sharpness, noise_start, use_confidence_noising,
use_permanent_unmasking, noise_clipping, top_p, top_k, added_tokens, context_window):
"""Full diffusion loop held inside a single GPU context to avoid repeated re-acquisition."""
ori_input_tokens = input_ids[:]
current_tokens, just_noised_indices = noisify_answer(
input_ids, answer_start, tokenizer, threshold=1.0, noise_start=1.0
)
yield render_html("Iteration 0 (initial noise)",
highlight_tokens(current_tokens[answer_start:], answer_start, just_noised_indices, color="red")), None
if pause_length > 0:
time.sleep(pause_length)
last_tokens = []
prev_decoded = []
unmasked_mask = [False] * len(current_tokens)
current_tokens = current_tokens[:answer_start]
for i in range(max_it):
current_tokens = current_tokens + [mask_token_id] * added_tokens
current_tokens = current_tokens[:context_window]
generated_tokens, confidences = _generate_step(current_tokens, top_p, top_k, eos_bias=eos_bias)
current_tokens = ori_input_tokens[:answer_start] + generated_tokens[answer_start:]
new_decoded = tokenizer.convert_ids_to_tokens(current_tokens[answer_start:])
diff_indices = {
answer_start + j for j, tok in enumerate(new_decoded)
if j >= len(prev_decoded) or tok != prev_decoded[j]
}
prev_decoded = new_decoded
yield render_html(f"Iteration {i+1}/{max_it} (after generation)",
highlight_tokens(current_tokens[answer_start:], answer_start, diff_indices, color="green")), None
if pause_length > 0:
time.sleep(pause_length)
last_tokens.append(current_tokens)
if len(last_tokens) > 3:
last_tokens.pop(0)
if len(last_tokens) == 3 and last_tokens[0] == last_tokens[1] == last_tokens[2]:
yield render_html("Stopped early", f"After {i+1} iterations."), None
break
if i < max_it - 1:
threshold = get_noising_schedule(i, max_it, sharpness=sharpness)
if use_confidence_noising:
noised_answer, just_noised_indices = confidence_guided_noising(
current_tokens, answer_start, tokenizer, confidences, noise_clipping,
threshold=threshold, noise_start=noise_start, unmasked_mask=unmasked_mask if use_permanent_unmasking else None
)
elif use_permanent_unmasking:
noised_answer, just_noised_indices = noisify_answer_without_remasking(
current_tokens, answer_start, tokenizer, threshold=threshold,
noise_start=noise_start, unmasked_mask=unmasked_mask
)
else:
noised_answer, just_noised_indices = noisify_answer(
current_tokens, answer_start, tokenizer,
threshold=threshold, noise_start=noise_start
)
for idx in range(answer_start, len(current_tokens)):
if noised_answer[idx] != mask_token_id:
unmasked_mask[idx] = True
if use_permanent_unmasking:
permanently_unmasked = {idx for idx in range(answer_start, len(current_tokens)) if unmasked_mask[idx]}
yield render_html(f"Iteration {i+1}/{max_it} (after noising)",
highlight_tokens(noised_answer[answer_start:], answer_start, permanently_unmasked, color="green")), None
else:
yield render_html(f"Iteration {i+1}/{max_it} (after noising)",
highlight_tokens(noised_answer[answer_start:], answer_start, just_noised_indices, color="red")), None
if pause_length > 0:
time.sleep(pause_length)
current_tokens = ori_input_tokens[:answer_start] + noised_answer[answer_start:]
answer_ids = current_tokens[answer_start:]
# Strip trailing EOS and MASK tokens before decoding
while answer_ids and answer_ids[-1] in (eos_token_id, mask_token_id):
answer_ids = answer_ids[:-1]
try:
final_ids = answer_ids[:answer_ids.index(eos_token_id)]
except ValueError:
final_ids = answer_ids
final_output = tokenizer.decode(final_ids, skip_special_tokens=True).lstrip()
yield render_html(f"Final Output ({len(final_ids)} tokens after {i+1} iterations)", final_output), final_output # type: ignore
def format_chat_prompt(question):
return (
"<|begin_of_text|>\n"
"<|start_header_id|>system<|end_header_id|>\n"
"You are a helpful assistant.\n"
"<|start_header_id|>user<|end_header_id|>\n"
f"{question}\n"
"<|start_header_id|>assistant<|end_header_id|>\n"
)
def format_multiturn_prompt(history, question):
parts = [
"<|begin_of_text|>\n"
"<|start_header_id|>system<|end_header_id|>\n"
"You are a helpful assistant.\n"
]
for q, a in history:
parts.append(f"<|start_header_id|>user<|end_header_id|>\n{q}\n")
parts.append(f"<|start_header_id|>assistant<|end_header_id|>\n{a}\n")
parts.append(f"<|start_header_id|>user<|end_header_id|>\n{question}\n")
parts.append("<|start_header_id|>assistant<|end_header_id|>\n")
return "".join(parts)
def render_html(label, text):
return f"{label}