Spaces:
Sleeping
Sleeping
Download views.py from JoaoK90/token_Explorer: direct link, hf CLI and curl.
- Browser
- Download file 41.6 kB
-
https://huggingface.co/spaces/JoaoK90/token_Explorer/resolve/main/views.py
- Command line
-
hf download hf://spaces/JoaoK90/token_Explorer/views.py
-
curl -L -o views.py https://huggingface.co/spaces/JoaoK90/token_Explorer/resolve/main/views.py
41.6 kB
| """HTML renderers for the explorer: a recorded trace in, markup out. | |
| Nothing here computes model outputs. Every number comes from a ``RunTrace`` | |
| recorded by ``engine.generate``. | |
| """ | |
| from __future__ import annotations | |
| from html import escape | |
| import numpy as np | |
| STAGE_TITLES = { | |
| "tokens": "Tokenize", | |
| "model": "Transformer", | |
| "probs": "Probabilities", | |
| "topk": "Top-k filter", | |
| "bits": "Keyed bits", | |
| "tournament": "Tournament", | |
| "sample": "Sample", | |
| "append": "Append", | |
| } | |
| RAIL_LABELS = {"topk": "Top-k"} | |
| PLAIN_STAGES = ("tokens", "model", "probs", "topk", "sample", "append") | |
| MARKED_STAGES = ("tokens", "model", "probs", "topk", "bits", "tournament", | |
| "sample", "append") | |
| WATERMARK_STAGES = ("bits", "tournament") | |
| SPECIAL_TOKENS = {"<|endoftext|>": "end of text", "<eos>": "end of text", | |
| "<bos>": "start of text", "<pad>": "padding", | |
| "<start_of_turn>": "start of turn", "<end_of_turn>": "end of turn"} | |
| _NICE_MAXIMA = (1, 2, 5, 10, 15, 20, 25, 30, 40, 50, 60, 80, 100) | |
| def stages_for(run) -> tuple[str, ...]: | |
| return MARKED_STAGES if run.watermarked else PLAIN_STAGES | |
| def stage_choices(run) -> list[tuple[str, str]]: | |
| """(label, key) pairs for the stage selector.""" | |
| return [(f"{i + 1} {RAIL_LABELS.get(key, STAGE_TITLES[key])}", key) | |
| for i, key in enumerate(stages_for(run))] | |
| # -------------------------------------------------------------------------- | |
| # Small formatters | |
| # -------------------------------------------------------------------------- | |
| def piece(text: str) -> str: | |
| """A token's text with its whitespace made visible.""" | |
| if text in SPECIAL_TOKENS: | |
| return f'<span class="sx-special">{SPECIAL_TOKENS[text]}</span>' | |
| if text == "": | |
| return '<span class="sx-ws">∅</span>' | |
| marks = {" ": "·", "\n": "↵", "\t": "⇥", "\r": "␍"} | |
| return "".join( | |
| f'<span class="sx-ws">{marks[ch]}</span>' if ch in marks else escape(ch) | |
| for ch in text | |
| ) | |
| def pct(p: float, digits: int = 1) -> str: | |
| value = 100.0 * float(p) | |
| if value == 0: | |
| return "0%" | |
| if value < 10 ** -digits / 2: | |
| return f"<{10 ** -digits:.{digits}f}%" | |
| return f"{value:.{digits}f}%" | |
| def bits(x: float) -> str: | |
| return f"{x:.2f} bits" | |
| def _plural(n: int, word: str) -> str: | |
| return f"{n:,} {word}" + ("" if n == 1 else "s") | |
| def _nice_max(p: float) -> float: | |
| value = 100.0 * p | |
| return next((m for m in _NICE_MAXIMA if m >= value - 1e-9), 100) / 100.0 | |
| def _head(title: str, body: str = "") -> str: | |
| """Stage title. The explanatory body is no longer shown (minimal layout).""" | |
| return f'<header class="sx-head"><h3>{title}</h3></header>' | |
| def _note(body: str, kind: str = "info") -> str: | |
| icon = {"info": "i", "skip": "!"}[kind] | |
| return (f'<div class="sx-note sx-note-{kind}"><span class="sx-note-icon" ' | |
| f'aria-hidden="true">{icon}</span><div>{body}</div></div>') | |
| def _legend(items: list[tuple[str, str]]) -> str: | |
| keys = "".join( | |
| f'<span class="sx-key"><span class="sx-swatch {cls}"></span>{label}</span>' | |
| for cls, label in items | |
| ) | |
| return f'<div class="sx-legend">{keys}</div>' | |
| # -------------------------------------------------------------------------- | |
| # Derived distributions | |
| # -------------------------------------------------------------------------- | |
| def _distributions(run, step) -> dict[str, np.ndarray]: | |
| """Candidate probabilities at each stage, aligned with ``step.cand_ids``.""" | |
| logits = step.cand_logits.astype(np.float64) | |
| raw = np.exp(logits - step.logz_raw) | |
| temp = np.exp(logits / run.temperature - step.logz_temp) | |
| topk = np.zeros_like(temp) | |
| topk[: step.kept] = temp[: step.kept] / temp[: step.kept].sum() | |
| final = topk.copy() | |
| if step.watermark is not None: | |
| final[: step.kept] = step.watermark.p_after | |
| return {"raw": raw, "temp": temp, "topk": topk, "final": final} | |
| # -------------------------------------------------------------------------- | |
| # Ranked bars (the one chart form used for every distribution) | |
| # -------------------------------------------------------------------------- | |
| def _bar_row(rank, token_html, ref, cur, scale, cells, *, cls="", tip=""): | |
| """One candidate: reference bar (grey), current bar (blue), value cells.""" | |
| def width(v): | |
| return f"{max(0.0, min(1.0, v / scale)) * 100:.2f}%" | |
| bars = "" | |
| if ref is not None: | |
| bars += f'<span class="sx-bar sx-bar-ref" style="width:{width(ref)}"></span>' | |
| if cur is not None: | |
| bars += f'<span class="sx-bar sx-bar-cur" style="width:{width(cur)}"></span>' | |
| title = f' title="{escape(tip, quote=True)}"' if tip else "" | |
| values = "".join( | |
| f'<span class="sx-val{" sx-val-ref" if i else ""}">{cell}</span>' | |
| for i, cell in enumerate(cells) | |
| ) | |
| return ( | |
| f'<div class="sx-row {cls}"{title}>' | |
| f'<span class="sx-rank">{rank}</span>' | |
| f'<span class="sx-tok">{token_html}</span>' | |
| f'<span class="sx-track">{bars}</span>{values}</div>' | |
| ) | |
| def _bars(rows: list[str], scale: float, columns: list[str]) -> str: | |
| """Ranked bars with a header naming the value columns and a shared axis.""" | |
| blanks = "<span></span>" * len(columns) | |
| head = ('<div class="sx-row sx-row-head"><span></span><span>Candidate</span><span></span>' | |
| + "".join(f'<span class="sx-val">{name}</span>' for name in columns) + "</div>") | |
| axis = ( | |
| '<div class="sx-row sx-axis"><span></span><span></span>' | |
| '<span class="sx-axis-track"><span>0%</span>' | |
| f"<span>{pct(scale / 2, 1 if scale < 0.1 else 0)}</span>" | |
| f"<span>{pct(scale, 0)}</span></span>{blanks}</div>" | |
| ) | |
| return (f'<div class="sx-bars sx-cols-{len(columns)}">{head}{"".join(rows)}{axis}</div>') | |
| def _gap_row(text: str, cls: str = "sx-gap") -> str: | |
| return f'<div class="sx-row {cls}"><span></span><span class="sx-gap-text">{text}</span></div>' | |
| # -------------------------------------------------------------------------- | |
| # Text so far | |
| # -------------------------------------------------------------------------- | |
| def _reading_text(text: str) -> str: | |
| """Token text for the running paragraph (newlines kept, marked).""" | |
| if text in SPECIAL_TOKENS: | |
| return f'<span class="sx-special">{SPECIAL_TOKENS[text]}</span>' | |
| return escape(text).replace("\n", '<span class="sx-ws">↵</span>\n') | |
| def _generated_spans(run, shown: int, current: int | None, fresh: str = "") -> str: | |
| spans = [] | |
| for j in range(shown): | |
| cls = f"sx-gen sx-now{fresh}" if j == current else f"sx-gen sx-alt{j % 2}" | |
| spans.append(f'<span class="{cls}">{_reading_text(run.token_text[run.new_ids[j]])}</span>') | |
| return "".join(spans) | |
| def render_tape(run, t: int, stage: str) -> str: | |
| """The prompt and the tokens generated up to the current position.""" | |
| stages = stages_for(run) | |
| revealed = stages.index(stage) >= stages.index("sample") | |
| shown = t + 1 if revealed else t | |
| body = f'<span class="sx-prompt">{escape(run.prompt)}</span>' | |
| body += _generated_spans(run, shown, t if revealed else None, | |
| " sx-fresh" if stage == "sample" else "") | |
| if not revealed: | |
| body += '<span class="sx-slot" title="The next token is being chosen">?</span>' | |
| count = (f"Prompt of {_plural(run.prompt_len, 'token')}, " | |
| f"{shown} of {run.n_steps} generated") | |
| return ( | |
| '<section class="sx sx-tape"><div class="sx-tape-head">' | |
| f'<span class="sx-tape-title">Text so far</span><span>{count}</span></div>' | |
| f'<div class="sx-tape-body">{body}</div></section>' | |
| ) | |
| def render_compare(plain, marked, t: int, stage: str, focus: str, show_scores: bool) -> str: | |
| """Both runs side by side, revealed up to the current position.""" | |
| focus_run = marked if focus == "marked" else plain | |
| stages = stages_for(focus_run) | |
| revealed = stages.index(stage) >= stages.index("sample") | |
| limit = min(plain.n_steps, marked.n_steps) | |
| split = next((i for i in range(limit) if plain.new_ids[i] != marked.new_ids[i]), None) | |
| columns = [] | |
| for name, run, title in (("plain", plain, "Without watermark"), | |
| ("marked", marked, "With SynthID watermark")): | |
| focused = name == focus | |
| shown = min(run.n_steps, t + 1 if revealed else t) | |
| spans = [] | |
| for j in range(shown): | |
| cls = f"sx-gen sx-alt{j % 2}" | |
| if focused and revealed and j == t: | |
| cls = "sx-gen sx-now" + (" sx-fresh" if stage == "sample" else "") | |
| if split is not None and j == split: | |
| cls += " sx-split" | |
| spans.append(f'<span class="{cls}">{_reading_text(run.token_text[run.new_ids[j]])}</span>') | |
| body = "".join(spans) | |
| if focused and not revealed: | |
| body += '<span class="sx-slot" title="The next token is being chosen">?</span>' | |
| score = "" | |
| if show_scores and run.detection is not None: | |
| value = run.detection.summary["weighted_mean_score"] | |
| text = "not enough text" if value is None else f"{value:.4f}" | |
| score = ('<div class="sx-cmp-score"><span>Weighted Mean with this key</span>' | |
| f"<strong>{text}</strong></div>") | |
| tag = '<span class="sx-cmp-tag">stepping through this one</span>' if focused else "" | |
| columns.append( | |
| f'<div class="sx-cmp-col{" sx-cmp-focus" if focused else ""}">' | |
| f'<div class="sx-cmp-title">{title}{tag}</div>' | |
| f'<div class="sx-tape-body"><span class="sx-prompt">{escape(run.prompt)}</span>{body}</div>' | |
| f"{score}</div>" | |
| ) | |
| if split is None: | |
| where = "The two generated texts are identical." | |
| else: | |
| where = (f"The two texts part ways at generated token {split + 1}, " | |
| "outlined once it is on screen.") | |
| caption = ( | |
| f"{where} Both runs use the same prompt, settings and seed. The plain " | |
| "run draws from the model's own probabilities; the watermarked run " | |
| "draws from the tournament's, which the key and the last four tokens " | |
| "largely decide. After the first different token the two contexts " | |
| "differ, so the texts keep drifting apart." | |
| ) | |
| return f'<section class="sx sx-cmp"><div class="sx-cmp-grid">{"".join(columns)}</div></section>' | |
| # -------------------------------------------------------------------------- | |
| # Stages | |
| # -------------------------------------------------------------------------- | |
| def _tiles(run, upto: int, with_ids: bool) -> str: | |
| ids = run.prompt_ids + run.new_ids[:upto] | |
| tiles = [] | |
| for j, token_id in enumerate(ids): | |
| cls = "sx-tile" | |
| if j >= run.prompt_len: | |
| cls += " sx-tile-gen" | |
| if upto > 0 and j == len(ids) - 1: | |
| cls += " sx-tile-new" | |
| inner = f'<span class="sx-tile-text">{piece(run.token_text[token_id])}</span>' | |
| if with_ids: | |
| inner += f'<span class="sx-tile-id">{token_id}</span>' | |
| tiles.append(f'<span class="{cls}" style="--i:{min(j, 60)}">{inner}</span>') | |
| return f'<div class="sx-tiles{" sx-tiles-ids" if with_ids else ""}">{"".join(tiles)}</div>' | |
| def _stage_tokens(run, t, _opts): | |
| """Tokens, then their vocabulary IDs appearing underneath.""" | |
| return _head("Tokenize") + _tiles(run, t, with_ids=True) | |
| def attention_weights(run, t: int) -> np.ndarray: | |
| """Share of attention from the predicting position to each context token. | |
| Averaged over every layer and head. GPT-2 parks most of its attention on | |
| the first token whatever the text says, so that token is left out and the | |
| rest is rescaled to 100%. | |
| """ | |
| n_context = run.prompt_len + t | |
| weights = run.attention[:, :, t, :n_context].astype(np.float32).mean(axis=(0, 1)) | |
| if n_context > 1: | |
| weights[0] = 0.0 | |
| total = float(weights.sum()) | |
| return weights / total if total > 0 else weights | |
| def model_setup(run, t: int) -> str: | |
| """One sentence on the network, for the "Model setup" menu.""" | |
| facts, n = run.model_facts, run.prompt_len + t | |
| return ( | |
| f"{escape(run.model)} passes the {_plural(n, 'token ID')} through " | |
| f"{facts['n_layer']} layers of {facts['n_head']} attention heads " | |
| f"({facts['n_params'] / 1e6:.0f} million parameters). In every layer, each " | |
| "position looks at the positions before it. The last position ends " | |
| f"with one score, called a logit, for each of the {facts['vocab_size']:,} " | |
| "vocabulary entries." | |
| ) | |
| def render_model_setup(run, t: int) -> str: | |
| body = f"<p>{model_setup(run, t)}</p>" | |
| key = run.key or (run.detection.key if run.detection is not None else None) | |
| if key is not None: | |
| body += ( | |
| f'<p class="sx-setup-key"><strong>Key file</strong> ' | |
| f'<span class="sx-mono">{escape(key.source)}</span>: {key.depth} integers, ' | |
| "one per watermark layer. Fingerprint " | |
| f'<span class="sx-mono">{key.short_fingerprint}</span></p>') | |
| return f'<section class="sx sx-run">{body}</section>' | |
| # The Transformer stage plays once, in four beats, moving the spotlight: | |
| # 1 context in -> 2 layers run -> 3 attention chart -> 4 scores out. | |
| _TF_TOP_SCORES = 6 | |
| _TF_TOP_ATTENTION = 6 | |
| _TF_BADGES = 3 | |
| def _stage_model(run, t, _opts): | |
| facts, step = run.model_facts, run.steps[t] | |
| n_layer = facts["n_layer"] | |
| weights = attention_weights(run, t) | |
| top = float(weights.max()) or 1.0 | |
| ids = run.prompt_ids + run.new_ids[:t] | |
| order = [int(i) for i in np.argsort(-weights)[:_TF_TOP_ATTENTION] if weights[i] > 0] | |
| badges = {j: r for r, j in enumerate(order[:_TF_BADGES])} | |
| chips = [] | |
| for j, (token_id, w) in enumerate(zip(ids, weights)): | |
| share = float(w) / top | |
| cls = ["sx-tf-chip"] | |
| if share > 0.55: | |
| cls.append("sx-tf-strong") | |
| if j == len(ids) - 1: | |
| cls.append("sx-tf-query") | |
| badge = "" | |
| if j in badges: | |
| badge = f'<b class="sx-tf-badge" style="--r:{badges[j]}">{pct(w, 0)}</b>' | |
| chips.append( | |
| f'<span class="{" ".join(cls)}" style="--a:{share:.3f};--i:{min(j, 40)}" ' | |
| f'title="{pct(w)} of the attention">{badge}' | |
| f'<span class="sx-tf-text">{piece(run.token_text[token_id])}</span></span>' | |
| ) | |
| cells = "".join(f'<span class="sx-tf-cell" style="--i:{i}">{i + 1}</span>' | |
| for i in range(n_layer)) | |
| def bars(rows, best): | |
| return "".join( | |
| f'<div class="sx-tf-score{" sx-tf-best" if i < best else ""}" style="--i:{i}">' | |
| f'<span class="sx-tok">{label}</span>' | |
| f'<span class="sx-tf-track"><span class="sx-tf-bar" ' | |
| f'style="--s:{max(0.03, size):.3f}"></span></span>' | |
| f'<span class="sx-num">{value}</span></div>' | |
| for i, (label, size, value) in enumerate(rows) | |
| ) | |
| looks = bars([ | |
| (f'{piece(run.token_text[ids[j]])}<i class="sx-tf-pos">#{j + 1}</i>', | |
| float(weights[j]) / top, pct(weights[j], 0)) | |
| for j in order], best=len(order)) | |
| shown = min(_TF_TOP_SCORES, len(step.cand_ids)) | |
| logits = step.cand_logits[:shown].astype(np.float64) | |
| floor = float(step.cand_logits[min(len(step.cand_ids), 3 * shown) - 1]) | |
| span = float(logits[0] - floor) or 1.0 | |
| scores = bars([ | |
| (piece(run.token_text[int(step.cand_ids[i])]), (logits[i] - floor) / span, | |
| f"{logits[i]:.1f}") | |
| for i in range(shown)], best=1) | |
| def beat(name, label, body, note=""): | |
| extra = f'<span class="sx-tf-note">{note}</span>' if note else "" | |
| return (f'<div class="sx-tf-beat sx-tf-{name}"><div class="sx-tf-label">' | |
| f"<span>{label}</span>{extra}</div>{body}</div>") | |
| last = piece(run.token_text[ids[-1]]) | |
| flow = ( | |
| '<div class="sx-tf" aria-label="Context, layers, attention and scores">' | |
| + beat("in", f"Context · {_plural(len(ids), 'token')}", | |
| f'<div class="sx-tf-chips">{"".join(chips)}</div>') | |
| + '<span class="sx-tf-link" aria-hidden="true"></span>' | |
| + beat("net", f"{n_layer} layers × {facts['n_head']} heads", | |
| f'<div class="sx-tf-cells">{cells}</div>') | |
| + '<span class="sx-tf-link" aria-hidden="true"></span>' | |
| + '<div class="sx-tf-row">' | |
| + beat("att", f'Where <span class="sx-tf-q">{last}</span> looks', | |
| f'<div class="sx-tf-scores">{looks}</div>', | |
| "all layers averaged · first token excluded") | |
| + beat("out", "Next-token scores (logits)", | |
| f'<div class="sx-tf-scores">{scores}</div>') | |
| + "</div></div>" | |
| ) | |
| return _head("Transformer") + flow | |
| def _stage_probs(run, t, opts): | |
| step, dist = run.steps[t], _distributions(run, run.steps[t]) | |
| n = min(opts["n_show"], step.kept) | |
| temp = run.temperature | |
| same = abs(temp - 1.0) < 1e-9 | |
| body = ( | |
| "Softmax turns the scores into probabilities that sum to 100% over the " | |
| "whole vocabulary. " | |
| + ("The temperature is 1, so the scores are used as they are." | |
| if same else | |
| f"The scores are first divided by the temperature, {temp:g}. Below 1 " | |
| "this moves probability toward the candidates that were already ahead.") | |
| ) | |
| scale = _nice_max(max(dist["temp"][:n].max(), dist["raw"][:n].max())) | |
| rows = [ | |
| _bar_row(i + 1, piece(run.token_text[int(step.cand_ids[i])]), | |
| None if same else dist["raw"][i], dist["temp"][i], scale, | |
| [pct(dist["temp"][i])] if same | |
| else [pct(dist["temp"][i]), pct(dist["raw"][i])]) | |
| for i in range(n) | |
| ] | |
| columns = ["Probability"] if same else [f"Temp. {temp:g}", "Temp. 1"] | |
| legend = "" if same else _legend([ | |
| ("sx-bar-ref", "At temperature 1"), ("sx-bar-cur", f"At temperature {temp:g}")]) | |
| rest = run.model_facts["vocab_size"] - n | |
| caption = ( | |
| f"These {n} candidates hold {pct(dist['temp'][:n].sum())} of the " | |
| f"probability; the other {rest:,} tokens share the rest. Uncertainty " | |
| f"about the next token: {bits(step.entropy_raw)} at temperature 1" | |
| + ("." if same else f", {bits(step.entropy_temp)} at temperature {temp:g}.") | |
| ) | |
| return _head("Probabilities", body) + legend + _bars(rows, scale, columns) | |
| def _stage_topk(run, t, opts): | |
| step, dist = run.steps[t], _distributions(run, run.steps[t]) | |
| n = min(opts["n_show"], step.kept) | |
| body = ( | |
| f"Only the {step.kept} most likely tokens stay in the draw (top-k = " | |
| f"{run.top_k}). Everything else is set to zero and the survivors are " | |
| "rescaled so that they sum to 100% again." | |
| ) | |
| scale = _nice_max(max(dist["topk"][:n].max(), dist["temp"][:n].max())) | |
| rows = [ | |
| _bar_row(i + 1, piece(run.token_text[int(step.cand_ids[i])]), | |
| dist["temp"][i], dist["topk"][i], scale, | |
| [pct(dist["topk"][i]), pct(dist["temp"][i])]) | |
| for i in range(n) | |
| ] | |
| if step.kept > n: | |
| rows.append(_gap_row(f"{_plural(step.kept - n, 'more candidate')} kept")) | |
| rows.append(_gap_row(f"Cut after rank {step.kept}", "sx-gap sx-cut")) | |
| for i in range(step.kept, min(step.kept + 3, len(step.cand_ids))): | |
| rows.append(_bar_row( | |
| i + 1, piece(run.token_text[int(step.cand_ids[i])]), dist["temp"][i], | |
| None, scale, ["removed", pct(dist["temp"][i], 2)], cls="sx-row-out")) | |
| removed = max(0.0, 1.0 - float(dist["temp"][: step.kept].sum())) | |
| caption = ( | |
| f"The cut removes {pct(removed)} of the probability. Uncertainty about " | |
| f"the next token: {bits(step.entropy_temp)} before, " | |
| f"{bits(step.entropy_topk)} after." | |
| ) | |
| legend = _legend([("sx-bar-ref", "Before the cut"), ("sx-bar-cur", "After the cut")]) | |
| return _head("Top-k filter", body) + legend + _bars(rows, scale, ["After", "Before"]) | |
| def _bit_strip(row: np.ndarray, dim: bool = False) -> str: | |
| cells = "".join(f'<i class="sx-bit{int(b)}"></i>' for b in row) | |
| return f'<span class="sx-bits{" sx-bits-dim" if dim else ""}">{cells}</span>' | |
| def _context_tiles(run, mark) -> str: | |
| empty = len(mark.context_ids) - mark.context_real | |
| tiles = [] | |
| for j, token_id in enumerate(mark.context_ids): | |
| if j < empty: | |
| tiles.append('<span class="sx-tile sx-tile-empty" title="No generated ' | |
| 'token here yet">empty</span>') | |
| else: | |
| tiles.append(f'<span class="sx-tile sx-tile-gen"><span class="sx-tile-text">' | |
| f'{piece(run.token_text[token_id])}</span></span>') | |
| return "".join(tiles) | |
| def _skip_note(mark) -> str: | |
| if mark.reason == "repeated_context": | |
| return _note("Repeated context: this token is not watermarked or scored.", "skip") | |
| if mark.reason == "skipped_start": | |
| return _note("Start of the text: this token is not watermarked.", "skip") | |
| return "" | |
| def _stage_bits(run, t, opts): | |
| step, mark = run.steps[t], run.steps[t].watermark | |
| depth = run.key.depth | |
| window = len(mark.context_ids) | |
| body = ( | |
| "SynthID never edits text after the fact. Before the draw, it hashes " | |
| f"three things together: the {window} tokens generated just before, one " | |
| f"candidate token, and one of the {depth} integers of the key file. " | |
| "Each hash gives one pseudorandom bit, called a g-value: " | |
| f"{depth} bits for every candidate. Another key gives other bits." | |
| ) | |
| flow = ( | |
| '<div class="sx-flow">' | |
| f'<div class="sx-flow-part"><span class="sx-flow-label">Last {window} generated tokens</span>' | |
| f'<div class="sx-tiles">{_context_tiles(run, mark)}</div></div>' | |
| '<span class="sx-flow-op">+</span>' | |
| '<div class="sx-flow-part"><span class="sx-flow-label">Candidate</span>' | |
| '<div class="sx-tiles"><span class="sx-tile sx-tile-any">each of the ' | |
| f"{step.kept}</span></div></div>" | |
| '<span class="sx-flow-op">+</span>' | |
| '<div class="sx-flow-part"><span class="sx-flow-label">Key file</span>' | |
| f'<div class="sx-tiles"><span class="sx-tile sx-tile-key">{escape(run.key.source)}' | |
| f'<span class="sx-tile-id">{run.key.short_fingerprint}</span></span></div></div>' | |
| '<span class="sx-flow-op">gives</span>' | |
| f'<div class="sx-flow-part"><span class="sx-flow-label">{depth} bits per candidate</span>' | |
| f'<div class="sx-tiles">{_bit_strip(np.array([1, 0, 1, 1, 0, 1]))}' | |
| '<span class="sx-ws">…</span></div></div></div>' | |
| ) | |
| if mark.g_values is None: | |
| return _head("Keyed bits", body) + flow + _skip_note(mark) | |
| n = min(opts["n_show"], step.kept) | |
| rows = "".join( | |
| f'<div class="sx-bitrow"><span class="sx-rank">{i + 1}</span>' | |
| f'<span class="sx-tok">{piece(run.token_text[int(mark.topk_ids[i])])}</span>' | |
| f"{_bit_strip(mark.g_values[i], dim=not mark.applied)}" | |
| f'<span class="sx-val">{int(mark.g_values[i].sum())} of {depth}</span></div>' | |
| for i in range(n) | |
| ) | |
| legend = _legend([("sx-bit1", "Bit 1"), ("sx-bit0", "Bit 0")]) | |
| return (_head("Keyed bits", body) + flow + _skip_note(mark) + legend | |
| + f'<div class="sx-bittable">{rows}</div>') | |
| def _expected_ones(mark, probs: np.ndarray) -> float: | |
| return float((probs * mark.g_values.mean(axis=1)).sum()) | |
| def _stage_tournament(run, t, opts): | |
| step, mark = run.steps[t], run.steps[t].watermark | |
| depth = run.key.depth | |
| body = ( | |
| f"The {depth} bit layers are applied one after another. In each layer, " | |
| "candidates whose bit is 1 gain probability and candidates whose bit " | |
| "is 0 lose some: p becomes p × (1 + g − share of probability with g = 1). " | |
| "After the last layer, most of the probability usually sits on very few " | |
| "candidates: the keyed bits have largely decided the draw. The bits " | |
| "behave like fair coin flips, so averaged over keys and contexts each " | |
| "candidate still wins as often as the model wanted." | |
| ) | |
| if mark.g_values is None: | |
| return _head("Tournament", body) + _skip_note(mark) | |
| n = min(opts["n_show"], step.kept) | |
| scale = _nice_max(max(mark.p_before[:n].max(), mark.p_after[:n].max())) | |
| rows = [] | |
| changes = 100.0 * (mark.p_after[:n] - mark.p_before[:n]).astype(np.float64) | |
| largest = float(np.abs(changes).max()) or 1.0 | |
| for i in range(n): | |
| change = float(changes[i]) | |
| arrow = "▲" if change > 0.05 else "▼" if change < -0.05 else "■" | |
| word = "up" if change > 0.05 else "down" if change < -0.05 else "same" | |
| # Green for gains, red for losses, stronger for larger moves; grey for none. | |
| strength = 0.0 if word == "same" else 0.14 + 0.86 * abs(change) / largest | |
| strong = " sx-delta-strong" if strength > 0.45 else "" | |
| # ui.HEAD counts the number (and the colour strength) up from zero. | |
| delta = (f'<span class="sx-delta sx-delta-{word}{strong}" style="--m:{strength:.3f}" ' | |
| f'data-to="{abs(change):.1f}" data-m="{strength:.3f}">' | |
| f'<span aria-hidden="true">{arrow}</span> ' | |
| f'<span class="sx-count">{abs(change):.1f}</span> pts</span>') | |
| rows.append(_bar_row( | |
| i + 1, piece(run.token_text[int(mark.topk_ids[i])]), mark.p_before[i], | |
| mark.p_after[i], scale, | |
| [pct(mark.p_after[i]), pct(mark.p_before[i]), delta], | |
| tip=f"{int(mark.g_values[i].sum())} of {depth} bits are 1")) | |
| if step.kept > n: | |
| rows.append(_gap_row(f"{_plural(step.kept - n, 'more candidate')} adjusted")) | |
| legend = _legend([("sx-bar-ref", "Model alone"), ("sx-bar-cur", "With the watermark")]) | |
| if mark.applied: | |
| before, after = _expected_ones(mark, mark.p_before), _expected_ones(mark, mark.p_after) | |
| caption = ( | |
| f"Expected share of 1-bits in the token about to be drawn: " | |
| f"{pct(before)} with the model alone, {pct(after)} with the " | |
| "watermark. The detector looks for an excess over 50%. It builds " | |
| "up on average over many tokens, not on every one: where the model " | |
| "is nearly certain, the bits have little to choose between. Early " | |
| "layers act while many candidates are still alive, which is why " | |
| "the Weighted Mean score counts them more. The layer-by-layer view " | |
| "is in the panel below." | |
| ) | |
| else: | |
| caption = "The probabilities are unchanged for this token." | |
| return (_head("Tournament", body) + _skip_note(mark) + legend | |
| + _bars(rows, scale, ["Watermark", "Model", "Change"])) | |
| def _stage_sample(run, t, opts): | |
| step, dist = run.steps[t], _distributions(run, run.steps[t]) | |
| probs = dist["final"] | |
| n = min(opts["n_show"], step.kept) | |
| body = ( | |
| "One token is drawn at random with these probabilities, so the most " | |
| f"likely one does not always win. The seed, {run.seed}, fixes the " | |
| "random numbers: the same settings give the same text again, another " | |
| "seed can give another." | |
| ) | |
| if step.watermark is not None and step.watermark.applied: | |
| body += (" With the watermark, the tournament has often left little " | |
| "for this draw to decide.") | |
| scale = _nice_max(probs[:n].max()) | |
| shown = list(range(n)) | |
| if step.chosen_pos >= n: | |
| shown.append(step.chosen_pos) | |
| rows = [] | |
| for i in shown: | |
| chosen = i == step.chosen_pos | |
| if i > n: | |
| rows.append(_gap_row(f"{_plural(i - n, 'candidate')} in between")) | |
| rows.append(_bar_row( | |
| i + 1, piece(run.token_text[int(step.cand_ids[i])]), None, probs[i], | |
| scale, [pct(probs[i]), '<span class="sx-drawn">drawn</span>' if chosen else ""], | |
| cls="sx-row-chosen" if chosen else "sx-row-rest")) | |
| # The drawn token is lifted out of the list and lands where the Append | |
| # step shows it, so the two steps join without a jump. | |
| row = shown.index(step.chosen_pos) + (1 if step.chosen_pos > n else 0) | |
| return (_head("Sample", body) | |
| + f'<div class="sx-pickwrap" style="--row:{row}">' | |
| + _bars(rows, scale, ["Probability", ""]) | |
| + f'<div class="sx-pick" aria-hidden="true">{_append_flow(run, step)}</div></div>') | |
| def _append_flow(run, step) -> str: | |
| return ( | |
| '<div class="sx-flow sx-flow-big">' | |
| '<div class="sx-flow-part"><span class="sx-flow-label">Token ID</span>' | |
| f'<div class="sx-tiles"><span class="sx-tile sx-tile-idonly">{step.chosen_id}</span></div></div>' | |
| '<span class="sx-flow-op">is</span>' | |
| '<div class="sx-flow-part"><span class="sx-flow-label">Text</span>' | |
| f'<div class="sx-tiles"><span class="sx-tile sx-tile-gen sx-tile-new">' | |
| f'<span class="sx-tile-text">{piece(run.token_text[step.chosen_id])}</span></span></div></div>' | |
| "</div>" | |
| ) | |
| def _stage_append(run, t, _opts): | |
| step = run.steps[t] | |
| last = t == run.n_steps - 1 | |
| body = ( | |
| "The ID is turned back into text and added to the end. " | |
| + ("" if last else | |
| "The longer text goes back to the first step to produce the next token.") | |
| ) | |
| flow = _append_flow(run, step) | |
| if not last: | |
| end = "" | |
| elif run.stop_reason == "eos": | |
| end = _note(f"Stopped: end-of-text token, after {_plural(run.n_steps, 'token')}.") | |
| else: | |
| end = _note(f"Stopped: limit of {_plural(run.max_new_tokens, 'new token')}.") | |
| return _head("Append", body) + flow + end | |
| _STAGES = { | |
| "tokens": _stage_tokens, "model": _stage_model, | |
| "probs": _stage_probs, "topk": _stage_topk, "bits": _stage_bits, | |
| "tournament": _stage_tournament, "sample": _stage_sample, "append": _stage_append, | |
| } | |
| def render_stage(run, t: int, stage: str, *, n_show: int = 10) -> str: | |
| """The panel for one stage of one generated token.""" | |
| opts = {"n_show": int(n_show)} | |
| inner = _STAGES[stage](run, t, opts) | |
| keyed = " data-keyed" if run.detection is not None else "" | |
| return f'<section class="sx sx-stage sx-stage-{stage}"{keyed}>{inner}</section>' | |
| # -------------------------------------------------------------------------- | |
| # Tournament, layer by layer | |
| # -------------------------------------------------------------------------- | |
| def render_tournament_detail(run, t: int, n_show: int = 10) -> str: | |
| """Probability of each candidate after every tournament layer.""" | |
| step, mark = run.steps[t], run.steps[t].watermark | |
| if mark is None or mark.layer_probs is None: | |
| return ('<section class="sx sx-detail"><p class="sx-caption">No tournament ' | |
| "ran for this token.</p></section>") | |
| depth = mark.g_values.shape[1] | |
| n = min(int(n_show), step.kept) | |
| pitch, pad, top, height = 12, 8, 16, 40 | |
| width = depth * pitch + 2 * pad | |
| peak = float(mark.layer_probs[:, :n].max()) or 1.0 | |
| def y(p): | |
| return top + height - height * float(p) / peak | |
| rows = [] | |
| for i in range(n): | |
| cells = "".join( | |
| f'<rect class="sx-bit{int(mark.g_values[i, layer])}" x="{pad + layer * pitch + 1}" ' | |
| f'y="0" width="{pitch - 2}" height="10" rx="2"></rect>' | |
| for layer in range(depth) | |
| ) | |
| points = " ".join( | |
| f"{pad + layer * pitch},{y(mark.layer_probs[layer, i]):.1f}" | |
| for layer in range(depth + 1) | |
| ) | |
| end = mark.layer_probs[depth, i] | |
| svg = ( | |
| f'<svg viewBox="0 0 {width} {top + height + 6}" width="{width}" ' | |
| f'height="{top + height + 6}" role="img" aria-label="Probability after each layer">' | |
| f"{cells}" | |
| f'<line class="sx-base" x1="{pad}" x2="{width - pad}" y1="{top + height}" y2="{top + height}"></line>' | |
| f'<polyline class="sx-line" points="{points}"></polyline>' | |
| f'<circle class="sx-dot" cx="{pad + depth * pitch}" cy="{y(end):.1f}" r="4"></circle>' | |
| "</svg>" | |
| ) | |
| rows.append( | |
| f'<div class="sx-layer-row"><span class="sx-rank">{i + 1}</span>' | |
| f'<span class="sx-tok">{piece(run.token_text[int(mark.topk_ids[i])])}</span>' | |
| f'<span class="sx-val">{pct(mark.layer_probs[0, i])}</span>{svg}' | |
| f'<span class="sx-val">{pct(end)}</span></div>' | |
| ) | |
| head = ( | |
| '<div class="sx-layer-row sx-layer-head"><span></span><span>Candidate</span>' | |
| f"<span>Start</span><span>Bit of each layer (1 to {depth}), then the " | |
| f"probability after it</span><span>End</span></div>" | |
| ) | |
| skipped = "" if mark.applied else _note( | |
| "Not watermarked: the model's own probabilities were used.", "skip") | |
| caption = ( | |
| f"All lines share one vertical scale, from 0% to {pct(peak)}. A line " | |
| "rises under a blue cell (bit 1) and falls under a grey one (bit 0). " | |
| "The size of each move depends on how much probability the 1-bit " | |
| "candidates hold together in that layer." | |
| ) | |
| legend = _legend([("sx-bit1", "Bit 1"), ("sx-bit0", "Bit 0"), | |
| ("sx-key-line", "Probability")]) | |
| return (f'<section class="sx sx-detail">{skipped}{legend}' | |
| f'<div class="sx-layers">{head}{"".join(rows)}</div>' | |
| '</section>') | |
| # -------------------------------------------------------------------------- | |
| # Detection | |
| # -------------------------------------------------------------------------- | |
| _STATUS_TEXT = { | |
| "valid": "scored", | |
| "start": "one of the first 4 generated tokens: the detector has no full 4-token window before it", | |
| "repeated": "not scored: repeated context", | |
| "eos": "not scored: at or after the end of text", | |
| } | |
| def _score_tile(label: str, value: str, note: str = "") -> str: | |
| extra = f'<span class="sx-stat-note">{note}</span>' if note else "" | |
| return (f'<div class="sx-stat"><span class="sx-stat-label">{label}</span>' | |
| f'<span class="sx-stat-value">{value}</span>{extra}</div>') | |
| def render_detection(detection, token_ids, token_text, title: str = "") -> str: | |
| """Scores of a token sequence and the per-token evidence behind them.""" | |
| summary, depth = detection.summary, detection.depth | |
| window = detection.ngram_len - 1 | |
| heading = f"<h4>{title}</h4>" if title else "" | |
| if summary["weighted_mean_score"] is None: | |
| return ( | |
| f'<section class="sx sx-detect">{heading}' | |
| + _note(f"Not enough text to score ({_plural(len(token_ids), 'token')}; " | |
| f"at least {detection.ngram_len} needed).") | |
| + "</section>") | |
| tiles = "".join([ | |
| _score_tile("Weighted Mean", f'{summary["weighted_mean_score"]:.4f}'), | |
| _score_tile("Mean", f'{summary["mean_score"]:.4f}'), | |
| _score_tile("Tokens scored", f'{summary["valid_ngram_count"]} of {len(token_ids)}'), | |
| _score_tile("Key", escape(detection.key.source)), | |
| ]) | |
| strip, table, extra = [], [], False | |
| for j, (token_id, info) in enumerate(zip(token_ids, detection.tokens)): | |
| text = piece(token_text[token_id]) | |
| if info.status == "valid": | |
| side = "hi" if info.mean_g >= 0.5 else "lo" | |
| amount = min(1.0, abs(info.mean_g - 0.5) / 0.25) * 100 | |
| ones = int(info.g_values.sum()) | |
| strong = " sx-g-strong" if amount > 55 else "" | |
| strip.append( | |
| f'<span class="sx-g{strong}" style="background:color-mix(in oklab, ' | |
| f'var(--sx-div-mid), var(--sx-div-{side}) {amount:.0f}%)" ' | |
| f'title="{ones} of {depth} bits are 1 (mean {info.mean_g:.3f})">{text}</span>') | |
| meter = (f'<span class="sx-meter sx-meter-{side}"><i style="width:' | |
| f'{100 * info.mean_g:.0f}%"></i></span>') | |
| table.append(f"<tr><td class='sx-num sx-idx'>{j + 1}</td>" | |
| f"<td class='sx-tok'>{text}</td>" | |
| f"<td class='sx-num'>{ones} / {depth}</td><td>{meter}</td>" | |
| f"<td class='sx-num'>{info.mean_g:.3f}</td>" | |
| f"<td class='sx-num'>{info.weighted_g:.3f}</td></tr>") | |
| else: | |
| strip.append(f'<span class="sx-g sx-g-{info.status}" ' | |
| f'title="{_STATUS_TEXT[info.status]}">{text}</span>') | |
| if info.g_values is not None and info.mean_g is not None: | |
| # First tokens: bits from generation, shown but not in the scores. | |
| extra = True | |
| ones = int(info.g_values.sum()) | |
| side = "hi" if info.mean_g >= 0.5 else "lo" | |
| meter = (f'<span class="sx-meter sx-meter-{side}"><i style="width:' | |
| f'{100 * info.mean_g:.0f}%"></i></span>') | |
| table.append(f"<tr><td class='sx-num sx-idx'>{j + 1}*</td>" | |
| f"<td class='sx-tok'>{text}</td>" | |
| f"<td class='sx-num'>{ones} / {depth}</td><td>{meter}</td>" | |
| f"<td class='sx-num'>{info.mean_g:.3f}</td>" | |
| f"<td class='sx-num'>{info.weighted_g:.3f}</td></tr>") | |
| else: | |
| why = escape(_STATUS_TEXT[info.status], quote=True) | |
| table.append(f"<tr title='{why}'><td class='sx-num sx-idx'>{j + 1}</td>" | |
| f"<td class='sx-tok'>{text}</td><td class='sx-num'>–</td>" | |
| "<td><span class='sx-meter sx-meter-none'></span></td>" | |
| "<td class='sx-num'>–</td><td class='sx-num'>–</td></tr>") | |
| present = {info.status for info in detection.tokens} | |
| keys = "".join( | |
| f'<span class="sx-key"><span class="sx-g sx-g-{status} sx-g-key">ab</span>{label}</span>' | |
| for status, label in (("start", f"First {window} tokens: no full window yet"), | |
| ("repeated", "Repeated context"), | |
| ("eos", "End of text and after")) | |
| if status in present | |
| ) | |
| scale = ( | |
| '<div class="sx-legend"><span class="sx-key">Share of 1-bits per token</span>' | |
| '<span class="sx-divscale"><span>25%</span><span class="sx-divbar"></span>' | |
| "<span>75%</span></span>" | |
| '<span class="sx-key">50% = no watermark</span>' | |
| f"{keys}</div>" | |
| ) | |
| note = ( | |
| "The detector recomputes each token's bits from the text and the key " | |
| "alone, without the model. Text that does not carry this watermark " | |
| "gives 1-bits about half the time, so its scores sit near 0.5. A score " | |
| "is not a probability, and no decision threshold has been calibrated " | |
| "for this demo." | |
| ) | |
| table_html = ( | |
| '<details class="sx-details"><summary>Table view</summary>' | |
| '<div class="sx-dwrap"><table class="sx-table sx-dtable"><thead><tr>' | |
| '<th class="sx-num">#</th><th>Token</th><th class="sx-num">1-bits</th>' | |
| '<th>Share of 1-bits (line at 50%)</th><th class="sx-num">Mean</th>' | |
| '<th class="sx-num">Weighted</th></tr></thead>' | |
| f'<tbody>{"".join(table)}</tbody></table></div>' | |
| + (f'<p class="sx-foot">* Bits computed during generation. The scores above ' | |
| f"count from token {window + 1}.</p>" if extra else "") | |
| + "</details>" | |
| ) | |
| return (f'<section class="sx sx-detect">{heading}<div class="sx-stats">{tiles}</div>' | |
| f'<div class="sx-gstrip">{"".join(strip)}</div>{scale}' | |
| f'{table_html}</section>') | |
| def render_detection_pending() -> str: | |
| return ('<section class="sx sx-detect">' | |
| + _note("The score appears at the last step of the last token.") | |
| + "</section>") | |
| # -------------------------------------------------------------------------- | |
| # Run details | |
| # -------------------------------------------------------------------------- | |
| def render_run_details(run) -> str: | |
| checks = run.checks | |
| rows = [ | |
| ("Model", f"{escape(run.model)}" + (f" (revision {run.revision[:12]})" if run.revision else "")), | |
| ("Device", escape(run.device)), | |
| ("Sampling", f"temperature {run.temperature:g}, top-k {run.top_k}, top-p 1.0, " | |
| f"seed {run.seed}, up to {_plural(run.max_new_tokens, 'new token')}"), | |
| ("Generated", f"{_plural(run.n_steps, 'token')}, stopped by " | |
| + ("the end-of-text token" if run.stop_reason == "eos" else "the length limit")), | |
| ] | |
| if run.watermarked: | |
| rows.append(("Key file", f"{escape(run.key.source)}, {run.key.depth} layers, " | |
| f"fingerprint {run.key.short_fingerprint}")) | |
| rows.append(("Tournament check", | |
| "largest difference between the displayed layer-by-layer result " | |
| "and the probabilities the library sampled from: " | |
| f"{checks['watermark_recompute_max_abs_diff']:.1e}")) | |
| else: | |
| rows.append(("Filter check", | |
| "largest difference between the displayed top-k probabilities " | |
| f"and the ones Transformers sampled from: {checks['plain_filter_max_abs_diff']:.1e}")) | |
| rows.append(("Attention pass", | |
| "attention weights come from one extra forward pass over the finished " | |
| "text; its scores differ from the generation's by at most " | |
| f"{checks['attention_replay_max_logit_diff']:.1e}")) | |
| body = "".join(f"<tr><th>{k}</th><td>{v}</td></tr>" for k, v in rows) | |
| return f'<section class="sx sx-run"><table class="sx-table sx-kv">{body}</table></section>' | |