"""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", "": "end of text", "": "start of text", "": "padding", "": "start 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'{SPECIAL_TOKENS[text]}' if text == "": return '∅' marks = {" ": "·", "\n": "↵", "\t": "⇥", "\r": "␍"} return "".join( f'{marks[ch]}' 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'

{title}

' def _note(body: str, kind: str = "info") -> str: icon = {"info": "i", "skip": "!"}[kind] return (f'
{icon}
{body}
') def _legend(items: list[tuple[str, str]]) -> str: keys = "".join( f'{label}' for cls, label in items ) return f'
{keys}
' # -------------------------------------------------------------------------- # 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'' if cur is not None: bars += f'' title = f' title="{escape(tip, quote=True)}"' if tip else "" values = "".join( f'{cell}' for i, cell in enumerate(cells) ) return ( f'
' f'{rank}' f'{token_html}' f'{bars}{values}
' ) 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 = "" * len(columns) head = ('
Candidate' + "".join(f'{name}' for name in columns) + "
") axis = ( '
' '0%' f"{pct(scale / 2, 1 if scale < 0.1 else 0)}" f"{pct(scale, 0)}{blanks}
" ) return (f'
{head}{"".join(rows)}{axis}
') def _gap_row(text: str, cls: str = "sx-gap") -> str: return f'
{text}
' # -------------------------------------------------------------------------- # 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'{SPECIAL_TOKENS[text]}' return escape(text).replace("\n", '↵\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'{_reading_text(run.token_text[run.new_ids[j]])}') 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'{escape(run.prompt)}' body += _generated_spans(run, shown, t if revealed else None, " sx-fresh" if stage == "sample" else "") if not revealed: body += '?' count = (f"Prompt of {_plural(run.prompt_len, 'token')}, " f"{shown} of {run.n_steps} generated") return ( '
' f'Text so far{count}
' f'
{body}
' ) 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'{_reading_text(run.token_text[run.new_ids[j]])}') body = "".join(spans) if focused and not revealed: body += '?' 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 = ('
Weighted Mean with this key' f"{text}
") tag = 'stepping through this one' if focused else "" columns.append( f'
' f'
{title}{tag}
' f'
{escape(run.prompt)}{body}
' f"{score}
" ) 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'
{"".join(columns)}
' # -------------------------------------------------------------------------- # 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'{piece(run.token_text[token_id])}' if with_ids: inner += f'{token_id}' tiles.append(f'{inner}') return f'
{"".join(tiles)}
' 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"

{model_setup(run, t)}

" key = run.key or (run.detection.key if run.detection is not None else None) if key is not None: body += ( f'

Key file ' f'{escape(key.source)}: {key.depth} integers, ' "one per watermark layer. Fingerprint " f'{key.short_fingerprint}

') return f'
{body}
' # 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'{pct(w, 0)}' chips.append( f'{badge}' f'{piece(run.token_text[token_id])}' ) cells = "".join(f'{i + 1}' for i in range(n_layer)) def bars(rows, best): return "".join( f'
' f'{label}' f'' f'{value}
' for i, (label, size, value) in enumerate(rows) ) looks = bars([ (f'{piece(run.token_text[ids[j]])}#{j + 1}', 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'{note}' if note else "" return (f'
' f"{label}{extra}
{body}
") last = piece(run.token_text[ids[-1]]) flow = ( '
' + beat("in", f"Context · {_plural(len(ids), 'token')}", f'
{"".join(chips)}
') + '' + beat("net", f"{n_layer} layers × {facts['n_head']} heads", f'
{cells}
') + '' + '
' + beat("att", f'Where {last} looks', f'
{looks}
', "all layers averaged · first token excluded") + beat("out", "Next-token scores (logits)", f'
{scores}
') + "
" ) 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'' for b in row) return f'{cells}' 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('empty') else: tiles.append(f'' f'{piece(run.token_text[token_id])}') 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 = ( '
' f'
Last {window} generated tokens' f'
{_context_tiles(run, mark)}
' '+' '
Candidate' '
each of the ' f"{step.kept}
" '+' '
Key file' f'
{escape(run.key.source)}' f'{run.key.short_fingerprint}
' 'gives' f'
{depth} bits per candidate' f'
{_bit_strip(np.array([1, 0, 1, 1, 0, 1]))}' '…
' ) 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'
{i + 1}' f'{piece(run.token_text[int(mark.topk_ids[i])])}' f"{_bit_strip(mark.g_values[i], dim=not mark.applied)}" f'{int(mark.g_values[i].sum())} of {depth}
' 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'
{rows}
') 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'' f' ' f'{abs(change):.1f} pts') 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]), 'drawn' 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'
' + _bars(rows, scale, ["Probability", ""]) + f'
') def _append_flow(run, step) -> str: return ( '
' '
Token ID' f'
{step.chosen_id}
' 'is' '
Text' f'
' f'{piece(run.token_text[step.chosen_id])}
' "
" ) 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'
{inner}
' # -------------------------------------------------------------------------- # 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 ('

No tournament ' "ran for this token.

") 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'' 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'' f"{cells}" f'' f'' f'' "" ) rows.append( f'
{i + 1}' f'{piece(run.token_text[int(mark.topk_ids[i])])}' f'{pct(mark.layer_probs[0, i])}{svg}' f'{pct(end)}
' ) head = ( '
Candidate' f"StartBit of each layer (1 to {depth}), then the " f"probability after itEnd
" ) 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'
{skipped}{legend}' f'
{head}{"".join(rows)}
' '
') # -------------------------------------------------------------------------- # 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'{note}' if note else "" return (f'
{label}' f'{value}{extra}
') 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"

{title}

" if title else "" if summary["weighted_mean_score"] is None: return ( f'
{heading}' + _note(f"Not enough text to score ({_plural(len(token_ids), 'token')}; " f"at least {detection.ngram_len} needed).") + "
") 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'{text}') meter = (f'') table.append(f"{j + 1}" f"{text}" f"{ones} / {depth}{meter}" f"{info.mean_g:.3f}" f"{info.weighted_g:.3f}") else: strip.append(f'{text}') 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'') table.append(f"{j + 1}*" f"{text}" f"{ones} / {depth}{meter}" f"{info.mean_g:.3f}" f"{info.weighted_g:.3f}") else: why = escape(_STATUS_TEXT[info.status], quote=True) table.append(f"{j + 1}" f"{text}–" "" "––") present = {info.status for info in detection.tokens} keys = "".join( f'ab{label}' 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 = ( '
Share of 1-bits per token' '25%' "75%" '50% = no watermark' f"{keys}
" ) 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 = ( '
Table view' '
' '' '' '' f'{"".join(table)}
#Token1-bitsShare of 1-bits (line at 50%)MeanWeighted
' + (f'

* Bits computed during generation. The scores above ' f"count from token {window + 1}.

" if extra else "") + "
" ) return (f'
{heading}
{tiles}
' f'
{"".join(strip)}
{scale}' f'{table_html}
') def render_detection_pending() -> str: return ('
' + _note("The score appears at the last step of the last token.") + "
") # -------------------------------------------------------------------------- # 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"{k}{v}" for k, v in rows) return f'
{body}
'