Spaces:
Sleeping
Sleeping
Log-prob heatmap demo for Delphi 1e22 (9.7B)
Browse files- README.md +35 -6
- app.py +194 -0
- requirements.txt +3 -0
README.md
CHANGED
|
@@ -1,13 +1,42 @@
|
|
| 1 |
---
|
| 2 |
-
title: Delphi 1e22
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version: '3.13'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Delphi 1e22 (9.7B) Log-Prob Heatmap
|
| 3 |
+
emoji: 🔮
|
| 4 |
+
colorFrom: indigo
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.49.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
short_description: Per-token log-prob heatmap for Delphi 1e22 (9.7B).
|
| 11 |
+
models:
|
| 12 |
+
- marin-community/delphi-1e22-9.7Bparams-160Btokens
|
| 13 |
---
|
| 14 |
|
| 15 |
+
Per-token log-probability heatmap for
|
| 16 |
+
[`marin-community/delphi-1e22-9.7Bparams-160Btokens`](https://huggingface.co/marin-community/delphi-1e22-9.7Bparams-160Btokens),
|
| 17 |
+
the 1e22-FLOP rung of the [Delphi scaling suite](https://openathena.ai/blog/delphi).
|
| 18 |
+
|
| 19 |
+
Submit any text; each token is colored by its surprisal (NLL =
|
| 20 |
+
`-log p(token | context)`), hover for the exact value, and see the cumulative
|
| 21 |
+
log-prob curve plus summary stats (total log-prob, mean NLL, perplexity). This
|
| 22 |
+
is the baseline companion to the
|
| 23 |
+
[1e23 (25B) Space](https://huggingface.co/spaces/WillHeld/delphi-1e23-demo) —
|
| 24 |
+
handy for comparing the same input across the two rungs.
|
| 25 |
+
|
| 26 |
+
## Running the Space
|
| 27 |
+
|
| 28 |
+
The Space targets [ZeroGPU](https://huggingface.co/docs/hub/spaces-zerogpu). The
|
| 29 |
+
9.7B model in bf16 (~19 GB) fits the default slot. Scoring is wrapped in
|
| 30 |
+
`@spaces.GPU(duration=120)`; the model is placed on `cuda` at module level per
|
| 31 |
+
the ZeroGPU docs.
|
| 32 |
+
|
| 33 |
+
To run locally with a GPU:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install -r requirements.txt
|
| 37 |
+
python app.py
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
`DELPHI_MODEL_ID` overrides the default checkpoint to swap in a different rung
|
| 41 |
+
of the suite; `DELPHI_MIN_PROB` sets the probability at which a token reaches
|
| 42 |
+
full color saturation (default `0.01`).
|
app.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import html
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import spaces # provided by the HF ZeroGPU runtime
|
| 14 |
+
|
| 15 |
+
HAS_SPACES = True
|
| 16 |
+
except ImportError: # running locally — no-op decorator
|
| 17 |
+
HAS_SPACES = False
|
| 18 |
+
|
| 19 |
+
class _SpacesShim:
|
| 20 |
+
def GPU(self, *args, **kwargs):
|
| 21 |
+
def decorator(fn):
|
| 22 |
+
return fn
|
| 23 |
+
|
| 24 |
+
return decorator
|
| 25 |
+
|
| 26 |
+
spaces = _SpacesShim()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# On ZeroGPU we keep the original cuda/bf16 path; locally we fall back to
|
| 30 |
+
# whatever device is actually available (Apple MPS or CPU).
|
| 31 |
+
if HAS_SPACES:
|
| 32 |
+
DEVICE, DTYPE = "cuda", torch.bfloat16
|
| 33 |
+
elif torch.cuda.is_available():
|
| 34 |
+
DEVICE, DTYPE = "cuda", torch.bfloat16
|
| 35 |
+
elif torch.backends.mps.is_available():
|
| 36 |
+
DEVICE, DTYPE = "mps", torch.float32
|
| 37 |
+
else:
|
| 38 |
+
DEVICE, DTYPE = "cpu", torch.float32
|
| 39 |
+
|
| 40 |
+
MODEL_ID = os.environ.get(
|
| 41 |
+
"DELPHI_MODEL_ID", "marin-community/delphi-1e22-9.7Bparams-160Btokens"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _model_label(model_id: str) -> str:
|
| 46 |
+
"""Friendly label like 'Delphi 1e22 (9.7B)' derived from the checkpoint id."""
|
| 47 |
+
m = re.search(r"delphi-(\d+e\d+)-([\d.]+)Bparams", model_id)
|
| 48 |
+
return f"Delphi {m.group(1)} ({m.group(2)}B)" if m else model_id
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
LABEL = _model_label(MODEL_ID)
|
| 52 |
+
|
| 53 |
+
# Tokens the model gave less than MIN_PROB are shown at full saturation;
|
| 54 |
+
# COLOR_SCALE is the surprisal (NLL, nats) at that probability.
|
| 55 |
+
MIN_PROB = float(os.environ.get("DELPHI_MIN_PROB", "0.01"))
|
| 56 |
+
COLOR_SCALE = -math.log(MIN_PROB)
|
| 57 |
+
|
| 58 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 59 |
+
if tokenizer.pad_token_id is None:
|
| 60 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 61 |
+
|
| 62 |
+
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=DTYPE).to(DEVICE)
|
| 63 |
+
model.eval()
|
| 64 |
+
|
| 65 |
+
DEFAULT_TEXT = "The capital of France is Paris."
|
| 66 |
+
|
| 67 |
+
# Injected via gr.Blocks(css=...) rather than inside the gr.HTML value, because
|
| 68 |
+
# Gradio sanitizes <style> tags out of HTML component content.
|
| 69 |
+
_CSS = """
|
| 70 |
+
.hm-wrap{white-space:pre-wrap;line-height:2.6;font-size:16px;overflow:visible;
|
| 71 |
+
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;padding:4px 2px;}
|
| 72 |
+
.hm-tok{position:relative;border-radius:3px;padding:2px 1px;cursor:default;}
|
| 73 |
+
.hm-tok:hover{outline:2px solid #2563eb;outline-offset:1px;}
|
| 74 |
+
.hm-tok:hover::after{content:attr(data-tip);position:absolute;left:50%;top:125%;
|
| 75 |
+
transform:translateX(-50%);background:#111;color:#fff;padding:5px 9px;
|
| 76 |
+
border-radius:5px;font-size:12px;font-family:ui-monospace,monospace;
|
| 77 |
+
white-space:nowrap;z-index:9999;pointer-events:none;
|
| 78 |
+
box-shadow:0 2px 8px rgba(0,0,0,.35);}
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _render_html(tokens):
|
| 83 |
+
"""Inline spans with an instant CSS tooltip (data-tip) = exact NLL on hover.
|
| 84 |
+
|
| 85 |
+
`tokens` is a list of (token_text, nll_or_None); None = unscored first token.
|
| 86 |
+
The `.hm-tok` CSS lives in gr.Blocks(css=...) since Gradio strips inline
|
| 87 |
+
<style> tags from HTML component content. `title` is a native fallback.
|
| 88 |
+
"""
|
| 89 |
+
spans = []
|
| 90 |
+
for tok, nll in tokens:
|
| 91 |
+
text = html.escape(tok)
|
| 92 |
+
if nll is None:
|
| 93 |
+
style = "background:#ececec;color:#999;"
|
| 94 |
+
tip = "unscored (no preceding context)"
|
| 95 |
+
else:
|
| 96 |
+
value = min(nll / COLOR_SCALE, 1.0) # 0..1 -> red saturation
|
| 97 |
+
text_color = "#fff" if value > 0.55 else "#111"
|
| 98 |
+
style = f"background:rgba(220,38,38,{value:.3f});color:{text_color};"
|
| 99 |
+
tip = f"NLL {nll:.3f} nats | log-prob {-nll:.3f} | p {math.exp(-nll):.4f}"
|
| 100 |
+
tip = html.escape(tip, quote=True)
|
| 101 |
+
spans.append(
|
| 102 |
+
f'<span class="hm-tok" data-tip="{tip}" title="{tip}" '
|
| 103 |
+
f'style="{style}">{text}</span>'
|
| 104 |
+
)
|
| 105 |
+
return '<div class="hm-wrap">' + "".join(spans) + "</div>"
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@spaces.GPU(duration=120)
|
| 109 |
+
@torch.no_grad()
|
| 110 |
+
def analyze(text: str):
|
| 111 |
+
"""Per-token log-probs of `text` under the model.
|
| 112 |
+
|
| 113 |
+
Returns (heatmap, summary, cumulative curve):
|
| 114 |
+
- heatmap: HTML; each token colored by surprisal (NLL), brighter = more
|
| 115 |
+
surprising, clamped at p < MIN_PROB. Hover a token for its exact NLL.
|
| 116 |
+
- summary: total log-prob, mean NLL, and perplexity.
|
| 117 |
+
- curve: cumulative log-prob vs token position.
|
| 118 |
+
"""
|
| 119 |
+
empty_curve = pd.DataFrame({"token #": [], "cumulative log-prob": []})
|
| 120 |
+
if not text:
|
| 121 |
+
return "", "", empty_curve
|
| 122 |
+
|
| 123 |
+
input_ids = tokenizer(text, return_tensors="pt").input_ids.to(DEVICE)
|
| 124 |
+
ids = input_ids[0]
|
| 125 |
+
if ids.shape[0] < 2:
|
| 126 |
+
return _render_html([(tokenizer.decode(ids), None)]), "Need at least 2 tokens.", empty_curve
|
| 127 |
+
|
| 128 |
+
logits = model(input_ids).logits[0]
|
| 129 |
+
# logits[i] predicts token i+1, so log p(token_i) lives at logits[i-1].
|
| 130 |
+
log_probs = F.log_softmax(logits[:-1].float(), dim=-1)
|
| 131 |
+
token_lp = log_probs.gather(-1, ids[1:].unsqueeze(-1)).squeeze(-1)
|
| 132 |
+
lps = token_lp.tolist()
|
| 133 |
+
|
| 134 |
+
# First token has no context, so it's unscored. NLL = -log-prob (nats >= 0).
|
| 135 |
+
tokens = [(tokenizer.decode(ids[0]), None)]
|
| 136 |
+
for tid, lp in zip(ids[1:].tolist(), lps):
|
| 137 |
+
tokens.append((tokenizer.decode(tid), -lp))
|
| 138 |
+
heatmap = _render_html(tokens)
|
| 139 |
+
|
| 140 |
+
total_lp = sum(lps)
|
| 141 |
+
mean_nll = -total_lp / len(lps)
|
| 142 |
+
perplexity = float(torch.tensor(mean_nll).exp())
|
| 143 |
+
summary = (
|
| 144 |
+
f"scored tokens: {len(lps)}\n"
|
| 145 |
+
f"total log-prob: {total_lp:.3f} nats\n"
|
| 146 |
+
f"mean NLL: {mean_nll:.3f} nats/token\n"
|
| 147 |
+
f"perplexity: {perplexity:.2f}"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
cum = []
|
| 151 |
+
running = 0.0
|
| 152 |
+
for i, lp in enumerate(lps, start=1):
|
| 153 |
+
running += lp
|
| 154 |
+
cum.append({"token #": i, "cumulative log-prob": running})
|
| 155 |
+
curve = pd.DataFrame(cum)
|
| 156 |
+
|
| 157 |
+
return heatmap, summary, curve
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
with gr.Blocks(title=f"{LABEL} — log-prob heatmap", css=_CSS) as demo:
|
| 161 |
+
gr.Markdown(
|
| 162 |
+
f"""# {LABEL} — log-prob heatmap
|
| 163 |
+
|
| 164 |
+
Submit any text and see the model's per-token surprise as a heatmap. Each token
|
| 165 |
+
is colored by its **surprisal** (NLL = `-log p(token | context)`, in nats):
|
| 166 |
+
faint = predictable, bright red = surprising. **Hover any token** for its exact
|
| 167 |
+
NLL, log-prob, and probability. The scale is fixed so colors are comparable
|
| 168 |
+
across inputs — any token the model gave **p < {MIN_PROB:g}** (NLL ≥
|
| 169 |
+
{COLOR_SCALE:.2f} nats) is shown at full saturation. The first token is unscored
|
| 170 |
+
(no preceding context).
|
| 171 |
+
|
| 172 |
+
Below the heatmap: summary stats (total log-prob, mean NLL, perplexity) and the
|
| 173 |
+
**cumulative log-prob** curve over the sequence.
|
| 174 |
+
|
| 175 |
+
Model: [`{MODEL_ID}`](https://huggingface.co/{MODEL_ID}),
|
| 176 |
+
a base pretrained model from the [Delphi scaling suite](https://openathena.ai/blog/delphi).
|
| 177 |
+
"""
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
text = gr.Textbox(value=DEFAULT_TEXT, lines=6, label="Text")
|
| 181 |
+
button = gr.Button("Visualize log-probs", variant="primary")
|
| 182 |
+
heatmap = gr.HTML(label="Per-token surprisal (hover for NLL)")
|
| 183 |
+
summary = gr.Textbox(label="Summary", lines=4)
|
| 184 |
+
curve = gr.LinePlot(
|
| 185 |
+
x="token #",
|
| 186 |
+
y="cumulative log-prob",
|
| 187 |
+
label="Cumulative log-prob",
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
button.click(analyze, inputs=[text], outputs=[heatmap, summary, curve])
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
demo.queue().launch(server_name="0.0.0.0")
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
huggingface_hub<1.0
|
| 2 |
+
transformers>=4.45
|
| 3 |
+
accelerate
|