Commit ·
ecff8f2
1
Parent(s): c31eed7
corrected gradio output
Browse files
app.py
CHANGED
|
@@ -1,104 +1,113 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
import torch.nn.functional as F
|
|
|
|
| 4 |
from tokenizers import Tokenizer
|
| 5 |
from train import MaskedDiffusionModel
|
| 6 |
|
| 7 |
-
|
| 8 |
def load_model_and_tokenizer():
|
| 9 |
device = torch.device("cpu")
|
|
|
|
| 10 |
tokenizer = Tokenizer.from_file("subword_tokenizer.json")
|
| 11 |
vocab = tokenizer.get_vocab()
|
| 12 |
id2word = {int(v): k for k, v in vocab.items()}
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
model.load_state_dict(torch.load("diffusion_model.pth", map_location=device))
|
| 17 |
model.eval()
|
|
|
|
| 18 |
return model, tokenizer, id2word, device
|
| 19 |
|
|
|
|
| 20 |
model, tokenizer, id2word, device = load_model_and_tokenizer()
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
words = []
|
| 26 |
for token_id in tensor.tolist():
|
| 27 |
word = id2word.get(token_id, "[UNK]")
|
| 28 |
-
|
| 29 |
-
words.append(word)
|
| 30 |
-
|
| 31 |
return " ".join(words).replace(" ##", "").replace("##", "")
|
| 32 |
|
| 33 |
-
|
| 34 |
def generate_step_by_step(prompt):
|
| 35 |
max_len = 15
|
| 36 |
steps = 15
|
| 37 |
-
temp = 0.
|
| 38 |
-
|
| 39 |
bos_id = tokenizer.token_to_id("[BOS]")
|
| 40 |
eos_id = tokenizer.token_to_id("[EOS]")
|
| 41 |
mask_id = tokenizer.token_to_id("[MASK]")
|
| 42 |
-
|
| 43 |
formatted_prompt = f"user: {prompt} bot:"
|
| 44 |
input_ids = tokenizer.encode(formatted_prompt).ids
|
| 45 |
-
|
| 46 |
sequence = [bos_id] + input_ids + [mask_id] * max_len + [eos_id]
|
| 47 |
seq_tensor = torch.tensor([sequence], dtype=torch.long, device=device)
|
| 48 |
-
|
| 49 |
mask_indices = (seq_tensor == mask_id).squeeze(0).nonzero(as_tuple=True)[0]
|
| 50 |
-
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
|
|
|
| 55 |
for step in range(1, steps + 1):
|
| 56 |
with torch.no_grad():
|
| 57 |
logits = model(seq_tensor)
|
| 58 |
-
|
| 59 |
probs = F.softmax(logits / max(temp, 1e-6), dim=-1)
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
| 62 |
true_probs = F.softmax(logits, dim=-1).squeeze(0)
|
| 63 |
-
confidences = torch.gather(
|
| 64 |
-
|
|
|
|
|
|
|
| 65 |
target_unmasked = int(len(mask_indices) * (step / steps))
|
| 66 |
current_seq = seq_tensor.squeeze(0).clone()
|
| 67 |
-
|
| 68 |
for idx in mask_indices:
|
| 69 |
current_seq[idx] = predicted_ids[idx]
|
| 70 |
-
|
| 71 |
if step < steps:
|
| 72 |
gen_conf = confidences[mask_indices]
|
| 73 |
num_remask = len(mask_indices) - target_unmasked
|
|
|
|
| 74 |
if num_remask > 0:
|
| 75 |
_, low_conf_idx = torch.topk(gen_conf, k=num_remask, largest=False)
|
| 76 |
for idx in mask_indices[low_conf_idx]:
|
| 77 |
current_seq[idx] = mask_id
|
| 78 |
-
|
| 79 |
-
seq_tensor = current_seq.unsqueeze(0)
|
| 80 |
-
output_log += f"`Step {step:02d}: {decode_tensor(seq_tensor[0], id2word)}`\n"
|
| 81 |
-
yield output_log
|
| 82 |
|
| 83 |
-
|
| 84 |
-
final_text = decode_tensor(response_ids, id2word)
|
| 85 |
-
output_log += f"\n**Final Output:** {final_text}"
|
| 86 |
-
yield output_log
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
### Experimental Discrete Diffusion Language Model (Proof of Concept)
|
| 91 |
-
**Note to Reviewers:** This is an early-stage checkpoint of a 90M parameter Transformer trained from scratch using a Masked Discrete Diffusion objective. Due to compute access ending before convergence (Loss ~ 5.0), the final English generation is fragmented.
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
|
| 96 |
demo = gr.Interface(
|
| 97 |
fn=generate_step_by_step,
|
| 98 |
-
inputs=gr.Textbox(label="Enter
|
| 99 |
-
outputs=gr.
|
| 100 |
-
title="
|
| 101 |
-
description=
|
| 102 |
)
|
| 103 |
|
| 104 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
import torch.nn.functional as F
|
| 4 |
+
import time
|
| 5 |
from tokenizers import Tokenizer
|
| 6 |
from train import MaskedDiffusionModel
|
| 7 |
|
| 8 |
+
|
| 9 |
def load_model_and_tokenizer():
|
| 10 |
device = torch.device("cpu")
|
| 11 |
+
|
| 12 |
tokenizer = Tokenizer.from_file("subword_tokenizer.json")
|
| 13 |
vocab = tokenizer.get_vocab()
|
| 14 |
id2word = {int(v): k for k, v in vocab.items()}
|
| 15 |
+
|
| 16 |
+
model = MaskedDiffusionModel(
|
| 17 |
+
vocab_size=len(vocab),
|
| 18 |
+
d_model=768,
|
| 19 |
+
nhead=12,
|
| 20 |
+
num_layers=12,
|
| 21 |
+
max_seq_len=128
|
| 22 |
+
).to(device)
|
| 23 |
+
|
| 24 |
model.load_state_dict(torch.load("diffusion_model.pth", map_location=device))
|
| 25 |
model.eval()
|
| 26 |
+
|
| 27 |
return model, tokenizer, id2word, device
|
| 28 |
|
| 29 |
+
|
| 30 |
model, tokenizer, id2word, device = load_model_and_tokenizer()
|
| 31 |
|
| 32 |
+
|
| 33 |
+
def decode_with_masks(tensor):
|
|
|
|
| 34 |
words = []
|
| 35 |
for token_id in tensor.tolist():
|
| 36 |
word = id2word.get(token_id, "[UNK]")
|
| 37 |
+
words.append(word)
|
|
|
|
|
|
|
| 38 |
return " ".join(words).replace(" ##", "").replace("##", "")
|
| 39 |
|
| 40 |
+
|
| 41 |
def generate_step_by_step(prompt):
|
| 42 |
max_len = 15
|
| 43 |
steps = 15
|
| 44 |
+
temp = 0.7
|
| 45 |
+
|
| 46 |
bos_id = tokenizer.token_to_id("[BOS]")
|
| 47 |
eos_id = tokenizer.token_to_id("[EOS]")
|
| 48 |
mask_id = tokenizer.token_to_id("[MASK]")
|
| 49 |
+
|
| 50 |
formatted_prompt = f"user: {prompt} bot:"
|
| 51 |
input_ids = tokenizer.encode(formatted_prompt).ids
|
| 52 |
+
|
| 53 |
sequence = [bos_id] + input_ids + [mask_id] * max_len + [eos_id]
|
| 54 |
seq_tensor = torch.tensor([sequence], dtype=torch.long, device=device)
|
| 55 |
+
|
| 56 |
mask_indices = (seq_tensor == mask_id).squeeze(0).nonzero(as_tuple=True)[0]
|
|
|
|
| 57 |
|
| 58 |
+
def get_output(seq_tensor):
|
| 59 |
+
response_ids = seq_tensor[0][1 + len(input_ids):-1]
|
| 60 |
+
return decode_with_masks(response_ids)
|
| 61 |
+
|
| 62 |
+
# initial state
|
| 63 |
+
current_output = get_output(seq_tensor)
|
| 64 |
+
yield current_output
|
| 65 |
|
| 66 |
+
# diffusion loop
|
| 67 |
for step in range(1, steps + 1):
|
| 68 |
with torch.no_grad():
|
| 69 |
logits = model(seq_tensor)
|
| 70 |
+
|
| 71 |
probs = F.softmax(logits / max(temp, 1e-6), dim=-1)
|
| 72 |
+
|
| 73 |
+
predicted_ids = torch.multinomial(
|
| 74 |
+
probs.view(-1, probs.size(-1)), 1
|
| 75 |
+
).view(probs.shape[:-1]).squeeze(0)
|
| 76 |
+
|
| 77 |
true_probs = F.softmax(logits, dim=-1).squeeze(0)
|
| 78 |
+
confidences = torch.gather(
|
| 79 |
+
true_probs, 1, predicted_ids.unsqueeze(1)
|
| 80 |
+
).squeeze(1)
|
| 81 |
+
|
| 82 |
target_unmasked = int(len(mask_indices) * (step / steps))
|
| 83 |
current_seq = seq_tensor.squeeze(0).clone()
|
| 84 |
+
|
| 85 |
for idx in mask_indices:
|
| 86 |
current_seq[idx] = predicted_ids[idx]
|
| 87 |
+
|
| 88 |
if step < steps:
|
| 89 |
gen_conf = confidences[mask_indices]
|
| 90 |
num_remask = len(mask_indices) - target_unmasked
|
| 91 |
+
|
| 92 |
if num_remask > 0:
|
| 93 |
_, low_conf_idx = torch.topk(gen_conf, k=num_remask, largest=False)
|
| 94 |
for idx in mask_indices[low_conf_idx]:
|
| 95 |
current_seq[idx] = mask_id
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
seq_tensor = current_seq.unsqueeze(0)
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
current_output = get_output(seq_tensor)
|
| 100 |
+
yield current_output
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
time.sleep(0.2)
|
| 103 |
+
|
| 104 |
|
| 105 |
demo = gr.Interface(
|
| 106 |
fn=generate_step_by_step,
|
| 107 |
+
inputs=gr.Textbox(label="Enter prompt"),
|
| 108 |
+
outputs=gr.Textbox(label="Generated Text (Converging)"),
|
| 109 |
+
title="Diffusion Model - Single Line Convergence",
|
| 110 |
+
description="Watch one sentence evolve from [MASK] tokens into final output."
|
| 111 |
)
|
| 112 |
|
| 113 |
if __name__ == "__main__":
|