Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,13 +2,18 @@ import os
|
|
| 2 |
import sys
|
| 3 |
|
| 4 |
import torch
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
from tokenizers import Tokenizer
|
| 7 |
from huggingface_hub import hf_hub_download, snapshot_download
|
|
|
|
| 8 |
|
| 9 |
# ── Repo IDs ───────────────────────────────────────────────────────────────────
|
| 10 |
REPO_V1 = "IvmeLabs/Ivme-Conversate-v1-Base"
|
| 11 |
REPO_V2 = "IvmeLabs/Ivme-Conversate-v2-Base"
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
|
|
@@ -41,7 +46,7 @@ def load_v1():
|
|
| 41 |
or 1024
|
| 42 |
)
|
| 43 |
eos_id = tok.token_to_id("<|eos|>")
|
| 44 |
-
return {"tokenizer": tok, "model": model, "max_ctx": max_ctx, "eos_id": eos_id}
|
| 45 |
|
| 46 |
|
| 47 |
# ── Load v2 ────────────────────────────────────────────────────────────────────
|
|
@@ -75,17 +80,54 @@ def load_v2():
|
|
| 75 |
|
| 76 |
max_ctx = getattr(cfg, "context_len", 1024)
|
| 77 |
eos_id = tok.token_to_id("<|endoftext|>")
|
| 78 |
-
return {"tokenizer": tok, "model": model, "max_ctx": max_ctx, "eos_id": eos_id}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
print("Loading İvme-Conversate-v1-Base...")
|
| 82 |
V1 = load_v1()
|
| 83 |
print("Loading İvme-Conversate-v2-Base...")
|
| 84 |
V2 = load_v2()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
REGISTRY = {
|
| 87 |
"İvme-Conversate-v2-Base (recommended)": V2,
|
| 88 |
"İvme-Conversate-v1-Base": V1,
|
|
|
|
|
|
|
|
|
|
| 89 |
}
|
| 90 |
|
| 91 |
BENCH = {
|
|
@@ -96,9 +138,9 @@ BENCH = {
|
|
| 96 |
}
|
| 97 |
|
| 98 |
|
| 99 |
-
# ──
|
| 100 |
@torch.no_grad()
|
| 101 |
-
def
|
| 102 |
tokenizer = bundle["tokenizer"]
|
| 103 |
model = bundle["model"]
|
| 104 |
max_ctx = bundle["max_ctx"]
|
|
@@ -165,15 +207,210 @@ def _generate(bundle, prompt, max_new_tokens, temperature, top_k, repetition_pen
|
|
| 165 |
yield prompt
|
| 166 |
|
| 167 |
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
bundle = REGISTRY[model_choice]
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
|
| 173 |
def compare_generate(prompt, max_new_tokens, temperature, top_k, repetition_penalty):
|
| 174 |
"""Run v1 and v2 on the same prompt/settings, streaming both in parallel steps."""
|
| 175 |
-
gen_v1 =
|
| 176 |
-
gen_v2 =
|
| 177 |
|
| 178 |
last_v1, last_v2 = prompt, prompt
|
| 179 |
done_v1 = done_v2 = False
|
|
@@ -219,11 +456,85 @@ EXAMPLES = [
|
|
| 219 |
"Python is a programming language that",
|
| 220 |
]
|
| 221 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
with gr.Blocks(css=CSS, title="İvme-Conversate") as demo:
|
| 223 |
gr.Markdown(
|
| 224 |
-
"## İvme-Conversate — Tiny Language Models
|
| 225 |
-
"
|
| 226 |
-
"
|
| 227 |
)
|
| 228 |
|
| 229 |
with gr.Tabs():
|
|
@@ -235,6 +546,8 @@ with gr.Blocks(css=CSS, title="İvme-Conversate") as demo:
|
|
| 235 |
label="Model",
|
| 236 |
)
|
| 237 |
|
|
|
|
|
|
|
| 238 |
prompt_box = gr.Textbox(
|
| 239 |
label="Prompt",
|
| 240 |
placeholder="The theory of relativity states that…",
|
|
@@ -247,33 +560,84 @@ with gr.Blocks(css=CSS, title="İvme-Conversate") as demo:
|
|
| 247 |
clear_btn = gr.Button("Clear", scale=1)
|
| 248 |
|
| 249 |
output_box = gr.Textbox(
|
| 250 |
-
label="
|
| 251 |
lines=12,
|
| 252 |
show_copy_button=True,
|
| 253 |
elem_classes="ivme-output",
|
| 254 |
interactive=False,
|
| 255 |
)
|
| 256 |
|
| 257 |
-
gr.Examples(examples=[[e] for e in EXAMPLES], inputs=prompt_box, label="Try a prompt")
|
| 258 |
|
| 259 |
with gr.Accordion("Settings", open=False):
|
| 260 |
-
with gr.
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
clear_btn.click(lambda: ("", ""), None, [prompt_box, output_box], queue=False)
|
| 271 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
# ── Tab 2: side-by-side compare ──────────────────────────────────────
|
| 273 |
with gr.Tab("Compare v1 vs v2"):
|
| 274 |
gr.Markdown(
|
| 275 |
-
"Run the **same prompt and settings** through both models at once "
|
| 276 |
-
"to see the difference training data made, plus the benchmark deltas below."
|
|
|
|
|
|
|
| 277 |
)
|
| 278 |
|
| 279 |
cmp_prompt = gr.Textbox(
|
|
@@ -325,4 +689,53 @@ with gr.Blocks(css=CSS, title="İvme-Conversate") as demo:
|
|
| 325 |
cmp_prompt.submit(compare_generate, cmp_inputs, [cmp_out_v1, cmp_out_v2])
|
| 326 |
cmp_clear_btn.click(lambda: ("", "", ""), None, [cmp_prompt, cmp_out_v1, cmp_out_v2], queue=False)
|
| 327 |
|
| 328 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import sys
|
| 3 |
|
| 4 |
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
import gradio as gr
|
| 7 |
from tokenizers import Tokenizer
|
| 8 |
from huggingface_hub import hf_hub_download, snapshot_download
|
| 9 |
+
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
|
| 10 |
|
| 11 |
# ── Repo IDs ───────────────────────────────────────────────────────────────────
|
| 12 |
REPO_V1 = "IvmeLabs/Ivme-Conversate-v1-Base"
|
| 13 |
REPO_V2 = "IvmeLabs/Ivme-Conversate-v2-Base"
|
| 14 |
+
REPO_CODER = "IvmeLabs/Ivme-Coder-v1"
|
| 15 |
+
REPO_DIFF_BASE = "IvmeLabs/ExpIvme-DiffusionConversate-v1"
|
| 16 |
+
REPO_DIFF_INSTRUCT = "IvmeLabs/ExpIvme-DiffusionConversate-v1-Instruct"
|
| 17 |
|
| 18 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 19 |
|
|
|
|
| 46 |
or 1024
|
| 47 |
)
|
| 48 |
eos_id = tok.token_to_id("<|eos|>")
|
| 49 |
+
return {"kind": "ar-raw", "tokenizer": tok, "model": model, "max_ctx": max_ctx, "eos_id": eos_id}
|
| 50 |
|
| 51 |
|
| 52 |
# ── Load v2 ────────────────────────────────────────────────────────────────────
|
|
|
|
| 80 |
|
| 81 |
max_ctx = getattr(cfg, "context_len", 1024)
|
| 82 |
eos_id = tok.token_to_id("<|endoftext|>")
|
| 83 |
+
return {"kind": "ar-raw", "tokenizer": tok, "model": model, "max_ctx": max_ctx, "eos_id": eos_id}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ── Load Coder-v1 (standard transformers AutoModelForCausalLM) ────────────────
|
| 87 |
+
def load_coder():
|
| 88 |
+
tokenizer = AutoTokenizer.from_pretrained(REPO_CODER, trust_remote_code=True)
|
| 89 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 90 |
+
REPO_CODER, trust_remote_code=True, dtype=torch.float32,
|
| 91 |
+
).to(device).eval()
|
| 92 |
+
return {"kind": "ar-hf", "tokenizer": tokenizer, "model": model}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ── Load diffusion base + instruct (custom masked-diffusion sampler) ──────────
|
| 96 |
+
def load_diffusion(repo_id, instruct):
|
| 97 |
+
tokenizer = AutoTokenizer.from_pretrained(repo_id, trust_remote_code=True)
|
| 98 |
+
model = AutoModel.from_pretrained(
|
| 99 |
+
repo_id, trust_remote_code=True,
|
| 100 |
+
).to(device).eval()
|
| 101 |
+
bundle = {
|
| 102 |
+
"kind": "diffusion-instruct" if instruct else "diffusion-base",
|
| 103 |
+
"tokenizer": tokenizer,
|
| 104 |
+
"model": model,
|
| 105 |
+
"mask_token_id": model.config.mask_token_id,
|
| 106 |
+
}
|
| 107 |
+
if instruct:
|
| 108 |
+
bundle["user_token_id"] = model.config.user_token_id
|
| 109 |
+
bundle["assistant_token_id"] = model.config.assistant_token_id
|
| 110 |
+
bundle["endturn_token_id"] = model.config.endturn_token_id
|
| 111 |
+
return bundle
|
| 112 |
|
| 113 |
|
| 114 |
print("Loading İvme-Conversate-v1-Base...")
|
| 115 |
V1 = load_v1()
|
| 116 |
print("Loading İvme-Conversate-v2-Base...")
|
| 117 |
V2 = load_v2()
|
| 118 |
+
print("Loading İvme-Coder-v1...")
|
| 119 |
+
CODER = load_coder()
|
| 120 |
+
print("Loading ExpİvmeDiffusionConversate-v1 (base)...")
|
| 121 |
+
DIFF_BASE = load_diffusion(REPO_DIFF_BASE, instruct=False)
|
| 122 |
+
print("Loading ExpİvmeDiffusionConversate-v1-Instruct...")
|
| 123 |
+
DIFF_INSTRUCT = load_diffusion(REPO_DIFF_INSTRUCT, instruct=True)
|
| 124 |
|
| 125 |
REGISTRY = {
|
| 126 |
"İvme-Conversate-v2-Base (recommended)": V2,
|
| 127 |
"İvme-Conversate-v1-Base": V1,
|
| 128 |
+
"İvme-Coder-v1 (Python code)": CODER,
|
| 129 |
+
"Expİvme-DiffusionConversate-v1 (experimental)": DIFF_BASE,
|
| 130 |
+
"Expİvme-DiffusionConversate-v1-Instruct (experimental)": DIFF_INSTRUCT,
|
| 131 |
}
|
| 132 |
|
| 133 |
BENCH = {
|
|
|
|
| 138 |
}
|
| 139 |
|
| 140 |
|
| 141 |
+
# ── Generation core: raw checkpoint AR models (v1/v2) ─────────────────────────
|
| 142 |
@torch.no_grad()
|
| 143 |
+
def _generate_ar_raw(bundle, prompt, max_new_tokens, temperature, top_k, repetition_penalty):
|
| 144 |
tokenizer = bundle["tokenizer"]
|
| 145 |
model = bundle["model"]
|
| 146 |
max_ctx = bundle["max_ctx"]
|
|
|
|
| 207 |
yield prompt
|
| 208 |
|
| 209 |
|
| 210 |
+
# ── Generation core: HF transformers AR models (Coder-v1) ─────────────────────
|
| 211 |
+
@torch.no_grad()
|
| 212 |
+
def _generate_ar_hf(bundle, prompt, max_new_tokens, temperature, top_k, repetition_penalty):
|
| 213 |
+
tokenizer = bundle["tokenizer"]
|
| 214 |
+
model = bundle["model"]
|
| 215 |
+
|
| 216 |
+
prompt = prompt or ""
|
| 217 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
| 218 |
+
if inputs["input_ids"].shape[1] == 0:
|
| 219 |
+
yield prompt
|
| 220 |
+
return
|
| 221 |
+
|
| 222 |
+
generated = inputs["input_ids"]
|
| 223 |
+
response_tokens: list[int] = []
|
| 224 |
+
temperature = max(float(temperature), 1e-6)
|
| 225 |
+
eos_id = tokenizer.eos_token_id
|
| 226 |
+
|
| 227 |
+
for _ in range(int(max_new_tokens)):
|
| 228 |
+
out = model(generated)
|
| 229 |
+
logits = out.logits[:, -1, :].float()
|
| 230 |
+
vocab_size = logits.size(-1)
|
| 231 |
+
|
| 232 |
+
if repetition_penalty and repetition_penalty != 1.0:
|
| 233 |
+
seen = torch.unique(generated[0])
|
| 234 |
+
scores = logits[0, seen]
|
| 235 |
+
scores = torch.where(
|
| 236 |
+
scores > 0, scores / repetition_penalty, scores * repetition_penalty
|
| 237 |
+
)
|
| 238 |
+
logits[0, seen] = scores
|
| 239 |
+
|
| 240 |
+
logits = logits / temperature
|
| 241 |
+
|
| 242 |
+
k = int(top_k)
|
| 243 |
+
if k > 0:
|
| 244 |
+
k = min(k, vocab_size)
|
| 245 |
+
topk_vals, _ = torch.topk(logits, k)
|
| 246 |
+
logits[logits < topk_vals[:, -1:]] = float("-inf")
|
| 247 |
+
|
| 248 |
+
probs = torch.softmax(logits, dim=-1)
|
| 249 |
+
if not torch.isfinite(probs).all() or probs.sum() <= 0:
|
| 250 |
+
next_tok = torch.argmax(logits, dim=-1, keepdim=True)
|
| 251 |
+
else:
|
| 252 |
+
next_tok = torch.multinomial(probs, num_samples=1)
|
| 253 |
+
|
| 254 |
+
tok_id = next_tok.item()
|
| 255 |
+
if eos_id is not None and tok_id == eos_id:
|
| 256 |
+
break
|
| 257 |
+
|
| 258 |
+
response_tokens.append(tok_id)
|
| 259 |
+
generated = torch.cat([generated, next_tok], dim=1)
|
| 260 |
+
|
| 261 |
+
yield prompt + tokenizer.decode(response_tokens)
|
| 262 |
+
|
| 263 |
+
if not response_tokens:
|
| 264 |
+
yield prompt
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# ── Generation core: masked-diffusion base model (unconditional/continuation) ─
|
| 268 |
+
@torch.no_grad()
|
| 269 |
+
def _generate_diffusion_base(bundle, prompt, length, steps, temperature, gumbel_temp):
|
| 270 |
+
tokenizer = bundle["tokenizer"]
|
| 271 |
+
model = bundle["model"]
|
| 272 |
+
mask_token_id = bundle["mask_token_id"]
|
| 273 |
+
|
| 274 |
+
length = int(length)
|
| 275 |
+
steps = max(int(steps), 1)
|
| 276 |
+
|
| 277 |
+
prefix_ids = tokenizer.encode(prompt) if prompt else []
|
| 278 |
+
prefix_len = len(prefix_ids)
|
| 279 |
+
total_len = prefix_len + length
|
| 280 |
+
|
| 281 |
+
input_ids = torch.full((1, total_len), mask_token_id, dtype=torch.long, device=device)
|
| 282 |
+
if prefix_len > 0:
|
| 283 |
+
input_ids[0, :prefix_len] = torch.tensor(prefix_ids, dtype=torch.long, device=device)
|
| 284 |
+
|
| 285 |
+
response_start = prefix_len
|
| 286 |
+
|
| 287 |
+
for step in range(steps):
|
| 288 |
+
logits = model(input_ids=input_ids).logits
|
| 289 |
+
probs = F.softmax(logits / max(float(temperature), 1e-6), dim=-1)
|
| 290 |
+
sampled = torch.multinomial(probs.view(-1, probs.size(-1)), 1).view(1, total_len)
|
| 291 |
+
|
| 292 |
+
# Never allow the fixed prefix to be resampled.
|
| 293 |
+
is_masked = input_ids == mask_token_id
|
| 294 |
+
if prefix_len > 0:
|
| 295 |
+
is_masked[0, :prefix_len] = False
|
| 296 |
+
|
| 297 |
+
n_masked = is_masked.sum().item()
|
| 298 |
+
if n_masked == 0:
|
| 299 |
+
break
|
| 300 |
+
|
| 301 |
+
frac_remaining = 1.0 - (step + 1) / steps
|
| 302 |
+
denom = max(1 - step / steps, 1e-6)
|
| 303 |
+
n_to_unmask = min(max(1, int(n_masked * (1 - frac_remaining / denom))), n_masked)
|
| 304 |
+
|
| 305 |
+
conf = probs.gather(-1, sampled.unsqueeze(-1)).squeeze(-1)
|
| 306 |
+
log_conf = torch.log(conf.clamp(min=1e-9))
|
| 307 |
+
u = torch.rand_like(conf).clamp(min=1e-9, max=1 - 1e-9)
|
| 308 |
+
gumbel_noise = -torch.log(-torch.log(u))
|
| 309 |
+
score = (log_conf + gumbel_temp * gumbel_noise).masked_fill(~is_masked, float("-inf"))
|
| 310 |
+
|
| 311 |
+
topk = torch.topk(score, k=n_to_unmask, dim=-1).indices
|
| 312 |
+
update_mask = torch.zeros_like(is_masked).scatter_(1, topk, True)
|
| 313 |
+
input_ids = torch.where(update_mask, sampled, input_ids)
|
| 314 |
+
|
| 315 |
+
partial = input_ids[0, response_start:].tolist()
|
| 316 |
+
yield (prompt or "") + tokenizer.decode(partial)
|
| 317 |
+
|
| 318 |
+
final = input_ids[0, response_start:].tolist()
|
| 319 |
+
yield (prompt or "") + tokenizer.decode(final)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# ── Generation core: masked-diffusion instruct model (chat) ───────────────────
|
| 323 |
+
@torch.no_grad()
|
| 324 |
+
def _generate_diffusion_instruct(bundle, user_message, max_response_len, steps, temperature,
|
| 325 |
+
gumbel_temp, presence_penalty):
|
| 326 |
+
tokenizer = bundle["tokenizer"]
|
| 327 |
+
model = bundle["model"]
|
| 328 |
+
mask_id = bundle["mask_token_id"]
|
| 329 |
+
user_id = bundle["user_token_id"]
|
| 330 |
+
assistant_id = bundle["assistant_token_id"]
|
| 331 |
+
endturn_id = bundle["endturn_token_id"]
|
| 332 |
+
|
| 333 |
+
max_response_len = int(max_response_len)
|
| 334 |
+
steps = max(int(steps), 1)
|
| 335 |
+
|
| 336 |
+
prefix_ids = [user_id] + tokenizer.encode(user_message or "") + [endturn_id, assistant_id]
|
| 337 |
+
input_ids = torch.tensor(
|
| 338 |
+
[prefix_ids + [mask_id] * max_response_len], dtype=torch.long, device=device,
|
| 339 |
+
)
|
| 340 |
+
prefix_len = len(prefix_ids)
|
| 341 |
+
vocab_size = model.config.vocab_size
|
| 342 |
+
|
| 343 |
+
for step in range(steps):
|
| 344 |
+
logits = model(input_ids=input_ids).logits
|
| 345 |
+
|
| 346 |
+
if presence_penalty > 0:
|
| 347 |
+
response_span = input_ids[:, prefix_len:]
|
| 348 |
+
visible = response_span.masked_fill(response_span == mask_id, -1)
|
| 349 |
+
counts = torch.zeros(1, vocab_size, device=device)
|
| 350 |
+
valid = visible[0][visible[0] >= 0]
|
| 351 |
+
if len(valid) > 0:
|
| 352 |
+
counts[0].scatter_add_(0, valid, torch.ones_like(valid, dtype=torch.float))
|
| 353 |
+
logits = logits - presence_penalty * counts.unsqueeze(1)
|
| 354 |
+
|
| 355 |
+
probs = F.softmax(logits / max(float(temperature), 1e-6), dim=-1)
|
| 356 |
+
sampled = torch.multinomial(probs.view(-1, probs.size(-1)), 1).view(input_ids.shape)
|
| 357 |
+
|
| 358 |
+
is_masked = input_ids == mask_id
|
| 359 |
+
n_masked = is_masked.sum().item()
|
| 360 |
+
if n_masked == 0:
|
| 361 |
+
break
|
| 362 |
+
|
| 363 |
+
frac_remaining = 1.0 - (step + 1) / steps
|
| 364 |
+
denom = max(1 - step / steps, 1e-6)
|
| 365 |
+
n_to_unmask = min(max(1, int(n_masked * (1 - frac_remaining / denom))), n_masked)
|
| 366 |
+
|
| 367 |
+
conf = probs.gather(-1, sampled.unsqueeze(-1)).squeeze(-1)
|
| 368 |
+
log_conf = torch.log(conf.clamp(min=1e-9))
|
| 369 |
+
u = torch.rand_like(conf).clamp(min=1e-9, max=1 - 1e-9)
|
| 370 |
+
gumbel_noise = -torch.log(-torch.log(u))
|
| 371 |
+
score = (log_conf + gumbel_temp * gumbel_noise).masked_fill(~is_masked, float("-inf"))
|
| 372 |
+
|
| 373 |
+
topk = torch.topk(score.view(1, -1), k=n_to_unmask, dim=-1).indices
|
| 374 |
+
update_mask = torch.zeros_like(is_masked).view(1, -1).scatter_(1, topk, True).view(is_masked.shape)
|
| 375 |
+
input_ids = torch.where(update_mask, sampled, input_ids)
|
| 376 |
+
|
| 377 |
+
response_tokens = input_ids[0, prefix_len:].tolist()
|
| 378 |
+
if endturn_id in response_tokens:
|
| 379 |
+
response_tokens = response_tokens[:response_tokens.index(endturn_id)]
|
| 380 |
+
yield tokenizer.decode(response_tokens)
|
| 381 |
+
|
| 382 |
+
response_tokens = input_ids[0, prefix_len:].tolist()
|
| 383 |
+
if endturn_id in response_tokens:
|
| 384 |
+
response_tokens = response_tokens[:response_tokens.index(endturn_id)]
|
| 385 |
+
yield tokenizer.decode(response_tokens)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
# ── Unified dispatcher used by the Playground tab ──────────────────────────────
|
| 389 |
+
def continue_text(model_choice, prompt, max_new_tokens, temperature, top_k, repetition_penalty,
|
| 390 |
+
diff_steps, gumbel_temp, presence_penalty):
|
| 391 |
bundle = REGISTRY[model_choice]
|
| 392 |
+
kind = bundle["kind"]
|
| 393 |
+
|
| 394 |
+
if kind == "ar-raw":
|
| 395 |
+
yield from _generate_ar_raw(bundle, prompt, max_new_tokens, temperature, top_k, repetition_penalty)
|
| 396 |
+
elif kind == "ar-hf":
|
| 397 |
+
yield from _generate_ar_hf(bundle, prompt, max_new_tokens, temperature, top_k, repetition_penalty)
|
| 398 |
+
elif kind == "diffusion-base":
|
| 399 |
+
yield from _generate_diffusion_base(
|
| 400 |
+
bundle, prompt, max_new_tokens, diff_steps, temperature, gumbel_temp
|
| 401 |
+
)
|
| 402 |
+
elif kind == "diffusion-instruct":
|
| 403 |
+
yield from _generate_diffusion_instruct(
|
| 404 |
+
bundle, prompt, max_new_tokens, diff_steps, temperature, gumbel_temp, presence_penalty
|
| 405 |
+
)
|
| 406 |
+
else:
|
| 407 |
+
yield prompt
|
| 408 |
|
| 409 |
|
| 410 |
def compare_generate(prompt, max_new_tokens, temperature, top_k, repetition_penalty):
|
| 411 |
"""Run v1 and v2 on the same prompt/settings, streaming both in parallel steps."""
|
| 412 |
+
gen_v1 = _generate_ar_raw(V1, prompt, max_new_tokens, temperature, top_k, repetition_penalty)
|
| 413 |
+
gen_v2 = _generate_ar_raw(V2, prompt, max_new_tokens, temperature, top_k, repetition_penalty)
|
| 414 |
|
| 415 |
last_v1, last_v2 = prompt, prompt
|
| 416 |
done_v1 = done_v2 = False
|
|
|
|
| 456 |
"Python is a programming language that",
|
| 457 |
]
|
| 458 |
|
| 459 |
+
CODE_EXAMPLES = [
|
| 460 |
+
"def fibonacci(n):",
|
| 461 |
+
"class BinaryTree:",
|
| 462 |
+
"import numpy as np\n\ndef normalize(",
|
| 463 |
+
"# Sort a list using quicksort\ndef quicksort(arr):",
|
| 464 |
+
]
|
| 465 |
+
|
| 466 |
+
CHAT_EXAMPLES = [
|
| 467 |
+
"Hi there, how are you?",
|
| 468 |
+
"What's your favorite color?",
|
| 469 |
+
"Can you help me plan my day?",
|
| 470 |
+
"Tell me something interesting.",
|
| 471 |
+
]
|
| 472 |
+
|
| 473 |
+
DIFFUSION_KEYS = {
|
| 474 |
+
"Expİvme-DiffusionConversate-v1 (experimental)",
|
| 475 |
+
"Expİvme-DiffusionConversate-v1-Instruct (experimental)",
|
| 476 |
+
}
|
| 477 |
+
INSTRUCT_KEY = "Expİvme-DiffusionConversate-v1-Instruct (experimental)"
|
| 478 |
+
CODER_KEY = "İvme-Coder-v1 (Python code)"
|
| 479 |
+
|
| 480 |
+
MODEL_NOTES = {
|
| 481 |
+
"İvme-Conversate-v2-Base (recommended)": (
|
| 482 |
+
"Autoregressive base model, general text. Not instruction-tuned — continues text, doesn't chat."
|
| 483 |
+
),
|
| 484 |
+
"İvme-Conversate-v1-Base": (
|
| 485 |
+
"Autoregressive base model, general text (earlier version). Not instruction-tuned."
|
| 486 |
+
),
|
| 487 |
+
CODER_KEY: (
|
| 488 |
+
"Autoregressive base model trained only on Python source. Writes code-*shaped* text reliably; "
|
| 489 |
+
"does not reliably write *correct* code. Not instruction-tuned — give it a code prefix to continue."
|
| 490 |
+
),
|
| 491 |
+
"Expİvme-DiffusionConversate-v1 (experimental)": (
|
| 492 |
+
"🧪 Experimental masked-diffusion model (not autoregressive). Generates a fixed-length span via "
|
| 493 |
+
"iterative denoising instead of left-to-right decoding. Not instruction-tuned, no chat behavior. "
|
| 494 |
+
"Weak general capability (near-chance on ARC-Easy) — expect local fluency, not coherent long-form text."
|
| 495 |
+
),
|
| 496 |
+
INSTRUCT_KEY: (
|
| 497 |
+
"🧪 Experimental masked-diffusion model, SFT'd for basic chat. Enter a single user message (not a "
|
| 498 |
+
"free-form prompt). Known limitation per the model card: output is not reliably grammatical — "
|
| 499 |
+
"locally plausible words that often don't compose into coherent sentences."
|
| 500 |
+
),
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def on_model_change(model_choice):
|
| 505 |
+
"""Toggle which settings are relevant/visible and swap in the right examples + notes."""
|
| 506 |
+
is_diffusion = model_choice in DIFFUSION_KEYS
|
| 507 |
+
is_instruct = model_choice == INSTRUCT_KEY
|
| 508 |
+
is_coder = model_choice == CODER_KEY
|
| 509 |
+
|
| 510 |
+
if is_instruct:
|
| 511 |
+
examples = CHAT_EXAMPLES
|
| 512 |
+
prompt_label = "User message"
|
| 513 |
+
prompt_placeholder = "Hi there, how are you?"
|
| 514 |
+
elif is_coder:
|
| 515 |
+
examples = CODE_EXAMPLES
|
| 516 |
+
prompt_label = "Prompt (Python)"
|
| 517 |
+
prompt_placeholder = "def fibonacci(n):"
|
| 518 |
+
else:
|
| 519 |
+
examples = EXAMPLES
|
| 520 |
+
prompt_label = "Prompt"
|
| 521 |
+
prompt_placeholder = "The theory of relativity states that…"
|
| 522 |
+
|
| 523 |
+
return (
|
| 524 |
+
gr.update(visible=not is_diffusion), # AR-only settings group
|
| 525 |
+
gr.update(visible=is_diffusion), # diffusion-only settings group
|
| 526 |
+
gr.update(visible=is_instruct), # presence penalty (instruct diffusion only)
|
| 527 |
+
gr.update(label=prompt_label, placeholder=prompt_placeholder),
|
| 528 |
+
gr.Dataset(samples=[[e] for e in examples]),
|
| 529 |
+
gr.update(value=MODEL_NOTES.get(model_choice, "")),
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
with gr.Blocks(css=CSS, title="İvme-Conversate") as demo:
|
| 534 |
gr.Markdown(
|
| 535 |
+
"## İvme-Conversate — Tiny Language Models\n"
|
| 536 |
+
"A family of sub-130M-parameter language models from IvmeLabs: autoregressive base models, "
|
| 537 |
+
"a Python-only coder model, and experimental masked-diffusion models."
|
| 538 |
)
|
| 539 |
|
| 540 |
with gr.Tabs():
|
|
|
|
| 546 |
label="Model",
|
| 547 |
)
|
| 548 |
|
| 549 |
+
model_note = gr.Markdown(MODEL_NOTES["İvme-Conversate-v2-Base (recommended)"])
|
| 550 |
+
|
| 551 |
prompt_box = gr.Textbox(
|
| 552 |
label="Prompt",
|
| 553 |
placeholder="The theory of relativity states that…",
|
|
|
|
| 560 |
clear_btn = gr.Button("Clear", scale=1)
|
| 561 |
|
| 562 |
output_box = gr.Textbox(
|
| 563 |
+
label="Output",
|
| 564 |
lines=12,
|
| 565 |
show_copy_button=True,
|
| 566 |
elem_classes="ivme-output",
|
| 567 |
interactive=False,
|
| 568 |
)
|
| 569 |
|
| 570 |
+
example_set = gr.Examples(examples=[[e] for e in EXAMPLES], inputs=prompt_box, label="Try a prompt")
|
| 571 |
|
| 572 |
with gr.Accordion("Settings", open=False):
|
| 573 |
+
with gr.Group(visible=True) as ar_settings:
|
| 574 |
+
with gr.Row():
|
| 575 |
+
max_tokens = gr.Slider(16, 512, value=200, step=8, label="Max new tokens")
|
| 576 |
+
temperature = gr.Slider(0.1, 2.0, value=0.7, step=0.05, label="Temperature")
|
| 577 |
+
with gr.Row():
|
| 578 |
+
top_k = gr.Slider(0, 200, value=40, step=1, label="Top-k (0 = disabled)")
|
| 579 |
+
rep_penalty = gr.Slider(1.0, 2.0, value=1.15, step=0.05, label="Repetition penalty")
|
| 580 |
+
|
| 581 |
+
with gr.Group(visible=False) as diff_settings:
|
| 582 |
+
gr.Markdown(
|
| 583 |
+
"Masked-diffusion sampling: the model denoises a fully-masked span over a fixed "
|
| 584 |
+
"number of steps rather than decoding left-to-right."
|
| 585 |
+
)
|
| 586 |
+
with gr.Row():
|
| 587 |
+
diff_length = gr.Slider(16, 256, value=96, step=8, label="Response length (tokens)")
|
| 588 |
+
diff_steps = gr.Slider(4, 64, value=32, step=2, label="Diffusion steps")
|
| 589 |
+
with gr.Row():
|
| 590 |
+
diff_temperature = gr.Slider(0.1, 2.0, value=1.0, step=0.05, label="Temperature")
|
| 591 |
+
diff_gumbel_temp = gr.Slider(0.0, 2.0, value=1.0, step=0.1, label="Gumbel temp (unmask noise)")
|
| 592 |
+
diff_presence_penalty = gr.Slider(
|
| 593 |
+
0.0, 3.0, value=1.2, step=0.1,
|
| 594 |
+
label="Presence penalty (Instruct only — suppresses repetition)",
|
| 595 |
+
visible=False,
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
gen_inputs = [
|
| 599 |
+
model_picker, prompt_box, max_tokens, temperature, top_k, rep_penalty,
|
| 600 |
+
diff_steps, diff_gumbel_temp, diff_presence_penalty,
|
| 601 |
+
]
|
| 602 |
+
# Note: for diffusion models, `max_tokens` slider doubles as response length via diff_length
|
| 603 |
+
# binding below; wire diff_length into the same "max_new_tokens" slot dynamically:
|
| 604 |
+
|
| 605 |
+
def route_generate(model_choice, prompt, max_new_tokens, temperature, top_k, repetition_penalty,
|
| 606 |
+
length, steps, d_temperature, gumbel_temp, presence_penalty):
|
| 607 |
+
bundle = REGISTRY[model_choice]
|
| 608 |
+
kind = bundle["kind"]
|
| 609 |
+
if kind == "diffusion-base":
|
| 610 |
+
yield from _generate_diffusion_base(bundle, prompt, length, steps, d_temperature, gumbel_temp)
|
| 611 |
+
elif kind == "diffusion-instruct":
|
| 612 |
+
yield from _generate_diffusion_instruct(
|
| 613 |
+
bundle, prompt, length, steps, d_temperature, gumbel_temp, presence_penalty
|
| 614 |
+
)
|
| 615 |
+
elif kind == "ar-hf":
|
| 616 |
+
yield from _generate_ar_hf(bundle, prompt, max_new_tokens, temperature, top_k, repetition_penalty)
|
| 617 |
+
else:
|
| 618 |
+
yield from _generate_ar_raw(bundle, prompt, max_new_tokens, temperature, top_k, repetition_penalty)
|
| 619 |
+
|
| 620 |
+
full_inputs = [
|
| 621 |
+
model_picker, prompt_box, max_tokens, temperature, top_k, rep_penalty,
|
| 622 |
+
diff_length, diff_steps, diff_temperature, diff_gumbel_temp, diff_presence_penalty,
|
| 623 |
+
]
|
| 624 |
+
gen_btn.click(route_generate, full_inputs, output_box)
|
| 625 |
+
prompt_box.submit(route_generate, full_inputs, output_box)
|
| 626 |
clear_btn.click(lambda: ("", ""), None, [prompt_box, output_box], queue=False)
|
| 627 |
|
| 628 |
+
model_picker.change(
|
| 629 |
+
on_model_change,
|
| 630 |
+
inputs=model_picker,
|
| 631 |
+
outputs=[ar_settings, diff_settings, diff_presence_penalty, prompt_box, example_set.dataset, model_note],
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
# ── Tab 2: side-by-side compare ──────────────────────────────────────
|
| 635 |
with gr.Tab("Compare v1 vs v2"):
|
| 636 |
gr.Markdown(
|
| 637 |
+
"Run the **same prompt and settings** through both autoregressive base models at once "
|
| 638 |
+
"to see the difference training data made, plus the benchmark deltas below. "
|
| 639 |
+
"(Coder-v1 and the diffusion models aren't included here since they use different "
|
| 640 |
+
"generation mechanics — try them individually in the Playground tab.)"
|
| 641 |
)
|
| 642 |
|
| 643 |
cmp_prompt = gr.Textbox(
|
|
|
|
| 689 |
cmp_prompt.submit(compare_generate, cmp_inputs, [cmp_out_v1, cmp_out_v2])
|
| 690 |
cmp_clear_btn.click(lambda: ("", "", ""), None, [cmp_prompt, cmp_out_v1, cmp_out_v2], queue=False)
|
| 691 |
|
| 692 |
+
# ── Tab 3: diffusion chat (Instruct model, dedicated chat-style UI) ──
|
| 693 |
+
with gr.Tab("Diffusion Chat (experimental)"):
|
| 694 |
+
gr.Markdown(
|
| 695 |
+
"### Expİvme-DiffusionConversate-v1-Instruct\n"
|
| 696 |
+
"🧪 **Experimental.** A 130M-parameter masked-diffusion model, SFT'd for basic chat. "
|
| 697 |
+
"Per the model card: output is **not reliably grammatical** — expect locally plausible "
|
| 698 |
+
"word choice that often doesn't compose into coherent sentences. Included here in the "
|
| 699 |
+
"spirit of the model card's own honesty about its limitations, not as a working assistant."
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
chat_input = gr.Textbox(
|
| 703 |
+
label="Your message",
|
| 704 |
+
placeholder="Hi there, how are you?",
|
| 705 |
+
lines=2,
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
with gr.Row():
|
| 709 |
+
chat_btn = gr.Button("Send", variant="primary", scale=3)
|
| 710 |
+
chat_clear_btn = gr.Button("Clear", scale=1)
|
| 711 |
+
|
| 712 |
+
chat_output = gr.Textbox(
|
| 713 |
+
label="Assistant (diffusion-sampled)",
|
| 714 |
+
lines=6,
|
| 715 |
+
show_copy_button=True,
|
| 716 |
+
elem_classes="ivme-output",
|
| 717 |
+
interactive=False,
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
gr.Examples(examples=[[e] for e in CHAT_EXAMPLES], inputs=chat_input, label="Try a message")
|
| 721 |
+
|
| 722 |
+
with gr.Accordion("Settings", open=False):
|
| 723 |
+
with gr.Row():
|
| 724 |
+
chat_len = gr.Slider(16, 128, value=64, step=8, label="Max response length")
|
| 725 |
+
chat_steps = gr.Slider(4, 64, value=32, step=2, label="Diffusion steps")
|
| 726 |
+
with gr.Row():
|
| 727 |
+
chat_temperature = gr.Slider(0.1, 2.0, value=1.0, step=0.05, label="Temperature")
|
| 728 |
+
chat_gumbel = gr.Slider(0.0, 2.0, value=1.0, step=0.1, label="Gumbel temp")
|
| 729 |
+
chat_presence = gr.Slider(0.0, 3.0, value=1.2, step=0.1, label="Presence penalty")
|
| 730 |
+
|
| 731 |
+
def diffusion_chat(user_message, length, steps, temperature, gumbel_temp, presence_penalty):
|
| 732 |
+
yield from _generate_diffusion_instruct(
|
| 733 |
+
DIFF_INSTRUCT, user_message, length, steps, temperature, gumbel_temp, presence_penalty
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
chat_inputs = [chat_input, chat_len, chat_steps, chat_temperature, chat_gumbel, chat_presence]
|
| 737 |
+
chat_btn.click(diffusion_chat, chat_inputs, chat_output)
|
| 738 |
+
chat_input.submit(diffusion_chat, chat_inputs, chat_output)
|
| 739 |
+
chat_clear_btn.click(lambda: ("", ""), None, [chat_input, chat_output], queue=False)
|
| 740 |
+
|
| 741 |
+
demo.queue().launch()
|