Add shareable URL state, speedup column and family-scoped metric legend
#7
by JonnaMat - opened
Files changed (7)
- app.js+52-11
- config.json+1
- embed.js+5-2
- index.html+2
- speedup.jsAdded+127
- style.css+21
- urlstate.jsAdded+213
370 unmodified lines37137237337437537637737837938038149 unmodified lines43143243343443543643743843989 unmodified lines529530531532533534535536537145 unmodified lines68368468568668768868969069151 unmodified lines74374474574674774810 unmodified lines75976076176276376440 unmodified lines805806807808809810121 unmodified lines9329339349359369371 unmodified line93994094194294394494594612 unmodified lines959960961962963964965966967370 unmodified linesreturn div;}// Metric legendconst legendGrid = document.getElementById("legend-grid");legendGrid.innerHTML = config.metrics.map(m =>`<div><strong>${m.short || m.column}</strong> ${m.description || m.label}</div>`).join("");// ─── State ────────────────────────────────────────────────────────────────────49 unmodified linesconst strVals = vals.map(String);const needsReset = resetDefaults || !strVals.includes(String(filters[f.column]));if (needsReset) {// Prefer family-specific default_device for the device/group_by filterconst defaultVal = f.column === GROUP_BY && familyCfg.default_device;if (defaultVal && strVals.includes(String(defaultVal))) {filters[f.column] = defaultVal;} else {filters[f.column] = vals[0] ?? "";89 unmodified linesheaderRight.className = "chart-header-right";// Only show metric buttons for metrics that have non-zero dataconst chartVisibleMetrics = config.metrics.filter(m =>gRows.some(r => r[m.column] !== undefined && r[m.column] !== null && r[m.column] !== 0 && r[m.column] !== "N/A"));if (chartVisibleMetrics.length > 1) {const metricEl = metricGroup.querySelector(".btn-group");renderBtnGroup(metricEl,145 unmodified lines});// Hide metric columns where every value in the filtered data is zero, null, or N/Aconst visibleMetrics = config.metrics.filter(m =>filtered.some(r => r[m.column] !== undefined && r[m.column] !== null && r[m.column] !== 0 && r[m.column] !== "N/A"));// Build column list: Model + visible display cols + metricsconst colDefs = [51 unmodified linesreturn metricHib ? va - vb : vb - va;});// Track row group for break detectionlet prevGroupVal = undefined;10 unmodified linesconst cls = i === firstMetricIdx ? ' class="first-metric metric-cell"' : (c.isMetric ? ' class="metric-cell"' : '');return `<th${tip}${cls}>${c.label}</th>`;}).join("");html += `</tr></thead><tbody>`;// Compute best metric value per sub-group (tableGroupBy) per column40 unmodified lineshtml += `<td>${val || "—"}</td>`;}});html += "</tr>";});121 unmodified linessection.appendChild(card);}// ─── Embed SVG module ────────────────────────────────────────────────────────const embed = initEmbed({1 unmodified linegetData: () => DATA, MODEL_COL, FAMILY_COL, GROUP_BY, CHART_CFG,MODEL_COLORS, MODEL_SHORT, isOOMRow, isExternalModel,sortModels, parseModelSize,});// ─── Render ───────────────────────────────────────────────────────────────────function render() {12 unmodified linesbuildChart(filtered);const chartsShown = charts.length > 0;buildTables(filtered, chartsShown);buildDemo();buildAccuracyTable();buildExperimentSetup();}// ─── Switch Base Family (load data + re-render) ───────────────────────────────370 unmodified lines37137237337437537637737837938038138238338438538638738838939039139239339439539639739839949 unmodified lines44945045145245345445545645745845946046189 unmodified lines551552553554555556557145 unmodified lines70370470570670770870951 unmodified lines76176276376476576676776876910 unmodified lines78078178278378478578640 unmodified lines827828829830831832833121 unmodified lines9559569579589599609619629639649659669679689699709711 unmodified line97397497597697797897998098198298398412 unmodified lines997998999100010011002100310041005100610071008370 unmodified linesreturn div;}// ─── Metric legend ────────────────────────────────────────────────────────────// [legend] Single source of truth for "which metrics have data in these rows".// Used by buildChart (metric buttons), buildTables (metric columns) and the// legend below, so all three agree on what is relevant to the current family.function metricsWithData(rows) {return config.metrics.filter(m =>rows.some(r => r[m.column] !== undefined && r[m.column] !== null && r[m.column] !== 0 && r[m.column] !== "N/A"));}// [legend] The legend explains only the metrics currently on screen: a CV family// (ips/lat/mem) no longer shows the LLM keys and vice versa. Re-rendered on every// render(). Set config.legend_filter = false to always list every metric.const legendGrid = document.getElementById("legend-grid");function renderLegend(metrics) {const shown = config.legend_filter === false ? config.metrics : metrics;legendGrid.innerHTML = shown.map(m =>`<div><strong>${m.short || m.column}</strong> ${m.description || m.label}</div>`).join("");legendGrid.style.display = shown.length ? "" : "none";}// ─── State ────────────────────────────────────────────────────────────────────49 unmodified linesconst strVals = vals.map(String);const needsReset = resetDefaults || !strVals.includes(String(filters[f.column]));if (needsReset) {// [urlstate] a value asked for by the URL hash wins over the family defaultconst wanted = urlstate.desiredFilterValue(f.column, strVals);// Prefer family-specific default_device for the device/group_by filterconst defaultVal = f.column === GROUP_BY && familyCfg.default_device;if (wanted !== null) {filters[f.column] = wanted;} else if (defaultVal && strVals.includes(String(defaultVal))) {filters[f.column] = defaultVal;} else {filters[f.column] = vals[0] ?? "";89 unmodified linesheaderRight.className = "chart-header-right";// Only show metric buttons for metrics that have non-zero dataconst chartVisibleMetrics = metricsWithData(gRows); // [legend] was an inline config.metrics.filter(...)if (chartVisibleMetrics.length > 1) {const metricEl = metricGroup.querySelector(".btn-group");renderBtnGroup(metricEl,145 unmodified lines});// Hide metric columns where every value in the filtered data is zero, null, or N/Aconst visibleMetrics = metricsWithData(filtered); // [legend] was an inline config.metrics.filter(...)// Build column list: Model + visible display cols + metricsconst colDefs = [51 unmodified linesreturn metricHib ? va - vb : vb - va;});// [speedup] pair optimized rows with their baseline for this tablespeedup.prepare(rows, { tableGroupCols, visibleMetrics, activeMetricCol });// Track row group for break detectionlet prevGroupVal = undefined;10 unmodified linesconst cls = i === firstMetricIdx ? ' class="first-metric metric-cell"' : (c.isMetric ? ' class="metric-cell"' : '');return `<th${tip}${cls}>${c.label}</th>`;}).join("");html += speedup.headerHtml(); // [speedup] extra right-hand columnhtml += `</tr></thead><tbody>`;// Compute best metric value per sub-group (tableGroupBy) per column40 unmodified lineshtml += `<td>${val || "—"}</td>`;}});html += speedup.cellHtml(r); // [speedup] extra right-hand columnhtml += "</tr>";});121 unmodified linessection.appendChild(card);}// ─── URL state module ────────────────────────────────────────────────────────// [urlstate] Construction applies any incoming #hash to `filters` right here,// before populateFilters()/switchBaseFamily() below, so the first render// already shows the linked view. render() then keeps the hash in sync.const urlstate = initUrlState({config, filters, BASE_FAMILIES, deriveBaseFamily, GROUP_BY,availableOptions, renderSidebar, updateDependentFilters,switchBaseFamily, render,});// ─── Embed SVG module ────────────────────────────────────────────────────────const embed = initEmbed({1 unmodified linegetData: () => DATA, MODEL_COL, FAMILY_COL, GROUP_BY, CHART_CFG,MODEL_COLORS, MODEL_SHORT, isOOMRow, isExternalModel,sortModels, parseModelSize,shareHash: urlstate.currentHash, // [urlstate] embed link points at this view});// [speedup] Speedup vs baseline column moduleconst speedup = initSpeedup({ config, MODEL_COL, FAMILY_COL, isExternalModel });// ─── Render ───────────────────────────────────────────────────────────────────function render() {12 unmodified linesbuildChart(filtered);const chartsShown = charts.length > 0;buildTables(filtered, chartsShown);renderLegend(metricsWithData(filtered)); // [legend] follows the table columnsbuildDemo();buildAccuracyTable();buildExperimentSetup();urlstate.sync(); // [urlstate] mirror the settled view into location.hash}// ─── Switch Base Family (load data + re-render) ───────────────────────────────
4 unmodified lines56789104 unmodified lines"model_family_column": "model_family","model_link_prefix": "https://huggingface.co/","optimized_org": "embedl","base_names": {"Llama-3.2-1B": "Llama-3.2-1B-Instruct","Llama-3.2-3B": "Llama-3.2-3B-Instruct",4 unmodified lines5678910114 unmodified lines"model_family_column": "model_family","model_link_prefix": "https://huggingface.co/","optimized_org": "embedl","speedup_column": true,"base_names": {"Llama-3.2-1B": "Llama-3.2-1B-Instruct","Llama-3.2-3B": "Llama-3.2-3B-Instruct",
9 unmodified lines10111213141516293 unmodified lines3103113123133143153169 unmodified linesconfig, filters, activeFamilyKey, getActiveModelSet,getData, MODEL_COL, FAMILY_COL, GROUP_BY, CHART_CFG,MODEL_COLORS, MODEL_SHORT, isOOMRow, isExternalModel,sortModels, parseModelSize,} = deps;let embedModal = null;293 unmodified linesconst fileName = embedFileName();const svgUrl = "https://huggingface.co/datasets/" + HF_DOCS_REPO + "/resolve/main/" + HF_SVG_FOLDER + "/" + fileName;const embedCode = '<a href="' + HF_SPACES_URL + '" target="_blank" rel="noopener">\n <img\n src="' + svgUrl + '"\n alt="Edge Inference Benchmarks for ' + famKey + '"\n width="100%"\n />\n</a>';embedModal.querySelector("#embed-code").value = embedCode;embedModal.classList.add("visible");9 unmodified lines10111213141516293 unmodified lines3103113123133143153163173183199 unmodified linesconfig, filters, activeFamilyKey, getActiveModelSet,getData, MODEL_COL, FAMILY_COL, GROUP_BY, CHART_CFG,MODEL_COLORS, MODEL_SHORT, isOOMRow, isExternalModel,sortModels, parseModelSize, shareHash,} = deps;let embedModal = null;293 unmodified linesconst fileName = embedFileName();const svgUrl = "https://huggingface.co/datasets/" + HF_DOCS_REPO + "/resolve/main/" + HF_SVG_FOLDER + "/" + fileName;// Deep-link the embed back to the exact view it was generated from.const spacesUrl = HF_SPACES_URL + (typeof shareHash === "function" ? shareHash() : "");const embedCode = '<a href="' + spacesUrl + '" target="_blank" rel="noopener">\n <img\n src="' + svgUrl + '"\n alt="Edge Inference Benchmarks for ' + famKey + '"\n width="100%"\n />\n</a>';embedModal.querySelector("#embed-code").value = embedCode;embedModal.classList.add("visible");
85 unmodified lines86878889909185 unmodified lines<script src="demo/demo.js"></script><script src="embed.js"></script><script src="app.js"></script></body></html>85 unmodified lines868788899091929385 unmodified lines<script src="demo/demo.js"></script><script src="embed.js"></script><script src="speedup.js"></script><script src="urlstate.js"></script><script src="app.js"></script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127// ─── Speedup vs Baseline Column ──────────────────────────────────────────────//// Extracted module. Call initSpeedup(deps) from the main app once globals are// ready. Returns { prepare, headerHtml, cellHtml }.//// The benchmark data is inherently paired: an external baseline model (e.g.// meta-llama/Llama-3.2-1B-Instruct) and the optimized embedl variants of it// (embedl/Llama-3.2-1B-Instruct-FlashHead, …) measured under identical// conditions. This module pairs them up and renders their ratio for the// active metric as an extra right-hand column in the benchmark tables.
// eslint-disable-next-line no-unused-varsfunction initSpeedup(deps) {
const { config, MODEL_COL, FAMILY_COL, isExternalModel,} = deps;
const ENABLED = config.speedup_column !== false;const LABEL = config.speedup_label || "VS BASE";
// Two rows are comparable only when everything that defines the measurement// matches: the model family, every filter column (type / batch / device) and// every configured display column (res / fps / frames / ctx). Leaving the// display columns out would happily pair a 1920x1080 run with a 854x480 one.const KEY_COLS = [ FAMILY_COL, ...config.filters.map(f => f.column), ...(config.display_columns || []).map(d => d.column),].filter(Boolean);
function pairKey(row, cols) { return cols.map(c => String(row[c] ?? "")).join("\0");}
/** Metric value as a usable positive number; undefined for OOM / not-measured / "N/A" / 0. */function usable(val) { return typeof val === "number" && isFinite(val) && val > 0 ? val : undefined;}
function formatRatio(ratio) { return ratio.toFixed(2) + "×";}
// Per-table state, rebuilt by prepare() before each table is rendered.let state = null;
// ─── Pairing ─────────────────────────────────────────────────────────────────
/** * Compute the baseline pairing for one rendered table. * @param rows the rows of this table (already filtered to one group_by value) * @param opts { tableGroupCols, visibleMetrics, activeMetricCol } */function prepare(rows, opts) { state = null; if (!ENABLED || !rows || !rows.length) return;
const visibleMetrics = opts.visibleMetrics || []; const metricCfg = visibleMetrics.find(m => m.column === opts.activeMetricCol) || visibleMetrics[0]; if (!metricCfg) return;
const metricCol = metricCfg.column; const hib = metricCfg.higher_is_better !== false; const cols = [...new Set(KEY_COLS.concat(opts.tableGroupCols || []))];
// Bucket the external (baseline) rows by comparison key. const baselines = {}; rows.forEach(r => { if (!isExternalModel(r[MODEL_COL])) return; const k = pairKey(r, cols); (baselines[k] = baselines[k] || []).push(r); });
const ratios = new Map(); // optimized row -> ratio const isBase = new Set(); // baseline rows that actually anchor a pair
rows.forEach(r => { if (isExternalModel(r[MODEL_COL])) return; const cands = baselines[pairKey(r, cols)]; if (!cands || !cands.length) return; // Ambiguous: several *different* baseline models match the same key. // Show nothing rather than an arbitrary ratio. if (new Set(cands.map(c => c[MODEL_COL])).size > 1) return; const base = cands[0]; const b = usable(base[metricCol]); const o = usable(r[metricCol]); if (b === undefined || o === undefined) return; const ratio = hib ? o / b : b / o; if (!isFinite(ratio) || ratio <= 0) return; ratios.set(r, ratio); isBase.add(base); });
if (!ratios.size) return; // no real pair in this table -> no column state = { ratios, isBase, metricCfg };}
// ─── Rendering ───────────────────────────────────────────────────────────────
function headerHtml() { if (!state) return ""; const m = state.metricCfg; const tip = `Ratio of this model's ${m.label || m.column} against the original ` + `(non-${config.optimized_org || "embedl"}) model measured under identical conditions. ` + `Always oriented so that higher is better: 1.26× means 26% better than the baseline.`; return `<th class="metric-cell speedup-cell" data-tip="${tip.replace(/"/g, """)}">${LABEL}</th>`;}
function cellHtml(row) { if (!state) return ""; if (state.isBase.has(row)) { // The baseline is the reference point, so it is 1.00x by definition. // Spelling it out keeps "—" unambiguously meaning "no comparison". return `<td class="metric-cell speedup-cell"><span class="speedup-ref">1.00×</span></td>`; } const ratio = state.ratios.get(row); if (ratio === undefined) return `<td class="metric-cell speedup-cell">—</td>`; const down = ratio < 0.995 ? " is-down" : ""; return `<td class="metric-cell speedup-cell">` + `<span class="speedup-val${down}">${formatRatio(ratio)}</span></td>`;}
return { prepare, headerHtml, cellHtml };
}797 unmodified lines798799800801802803797 unmodified linesborder-color: var(--btn-active-border);}/* ── Responsive ──────────────────────────────────────── */@media (max-width: 900px) {.page {797 unmodified lines798799800801802803804805806807808809810811812813814815816817818819820821822823824797 unmodified linesborder-color: var(--btn-active-border);}/* ── Speedup ─────────────────────────────────────────── */td.speedup-cell {position: relative;color: var(--text);font-variant-numeric: tabular-nums;}.speedup-val {position: relative;font-weight: 600;color: var(--green);}.speedup-val.is-down {color: var(--red);}.speedup-ref {color: var(--text-dim);}/* ── Responsive ──────────────────────────────────────── */@media (max-width: 900px) {.page {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213// ─── Shareable URL State ─────────────────────────────────────────────────────//// Mirrors the current view — base family, variant, metric and every// config.filters column — into location.hash so that a view can be linked://// #family=Llama-3.2&device=agx_orin&metric=tps//// Extracted module. Call initUrlState(deps) once, after `filters` exists and// BEFORE the first render: construction applies an incoming hash to `filters`// in place, so the very first render already shows the linked view (there is// no visible second render). Returns { desiredFilterValue, sync, currentHash }.//// Disable with "url_state": false in config.json.
// eslint-disable-next-line no-unused-varsfunction initUrlState(deps) {
const { config, filters, BASE_FAMILIES, deriveBaseFamily, GROUP_BY, availableOptions, renderSidebar, updateDependentFilters, switchBaseFamily, render,} = deps;
const ENABLED = config.url_state !== false;const FILTER_COLS = config.filters.map(f => f.column);const METRIC_COLS = config.metrics.map(m => m.column);
// Filter values requested by the hash but not applied yet. They are consumed// by updateDependentFilters(), which otherwise resets every filter column to a// family default whenever the newly loaded data does not contain the current// value. Cleared by sync() once the view has settled.let pending = {};
// The hash this module last wrote, so our own replaceState is not re-applied.let lastWritten = null;
// Guard against re-entrant hashchange handling during an async family switch.let applying = false;
// ─── Parse ────────────────────────────────────────────────────────────────────
function parseHash(raw) { const out = {}; const s = String(raw || "").replace(/^#/, ""); if (!s) return out; s.split("&").forEach(part => { const i = part.indexOf("="); if (i < 1) return; try { const k = decodeURIComponent(part.slice(0, i)).trim(); const v = decodeURIComponent(part.slice(i + 1)).trim(); if (k) out[k] = v; } catch { // Malformed percent-escape — drop the pair rather than throw. } }); return out;}
// Accept either a base family ("Llama-3.2") or a config family key// ("Llama-3.2-1B"), mirroring the ?family= query deep link.function resolveFamily(fam) { if (!fam) return null; if (BASE_FAMILIES[fam]) return { baseFamily: fam, variant: null }; if (config.model_families?.[fam]) { const base = deriveBaseFamily(fam); if (BASE_FAMILIES[base]) return { baseFamily: base, variant: fam }; } return null;}
// Apply parsed hash params onto `filters`. Unknown families/metrics/variants// are ignored, never applied. Returns true when the base family changed (the// caller then has to reload that family's data).function applyParams(params) { let familyChanged = false;
const fam = resolveFamily(params.family); if (fam) { familyChanged = fam.baseFamily !== filters.baseFamily; filters.baseFamily = fam.baseFamily; filters.variant = fam.variant; }
if (params.variant !== undefined) { const v = params.variant; // A variant may be a data-derived model_family key that is absent from // config, so it can only be checked against the base-family rule here; // sync() drops it later if the loaded family does not offer it. filters.variant = (v && deriveBaseFamily(v) === filters.baseFamily) ? v : null; }
if (params.metric && METRIC_COLS.includes(params.metric)) { filters.metric = params.metric; }
pending = {}; FILTER_COLS.forEach(col => { if (params[col] !== undefined && params[col] !== "") pending[col] = params[col]; });
return familyChanged;}
// ─── Serialize ────────────────────────────────────────────────────────────────
// Drop a variant the currently loaded family does not actually offer — the// sidebar only shows variants when there is more than one.function normalizeVariant() { const variants = BASE_FAMILIES[filters.baseFamily]?.variants || []; if (filters.variant && (variants.length <= 1 || !variants.includes(filters.variant))) { filters.variant = null; }}
function buildHash() { const parts = []; const push = (k, v) => parts.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
push("family", filters.baseFamily); if (filters.variant) push("variant", filters.variant);
// Always link the group_by (device) column — it is what people share. // The remaining filter columns are only linked when the loaded family // actually offers a choice; otherwise their button group is hidden and the // value is noise that would be re-derived identically anyway. const opts = availableOptions(); config.filters.forEach(f => { const v = filters[f.column]; if (v === "" || v === null || v === undefined) return; if (f.column !== GROUP_BY && (opts[f.column] || []).length <= 1) return; push(f.column, v); });
if (filters.metric) push("metric", filters.metric); return parts.join("&");}
// ─── Public: called from app.js ──────────────────────────────────────────────
// Hook in updateDependentFilters(): the value the hash asked for, when it is// available in the freshly loaded data, else null (caller falls back to its// own default). "all" is only meaningful for the group_by column.function desiredFilterValue(col, availableStrVals) { if (!ENABLED) return null; const want = pending[col]; if (want === undefined) return null; if (col === GROUP_BY && want === "all") return "all"; return availableStrVals.includes(want) ? want : null;}
// Hook at the end of render(): the view has settled, publish it. replaceState// keeps every button click out of the history stack.function sync() { if (!ENABLED) return; pending = {}; normalizeVariant(); const hash = buildHash(); if (hash === lastWritten && String(location.hash).replace(/^#/, "") === hash) return; lastWritten = hash; const url = location.pathname + location.search + "#" + hash; try { history.replaceState(history.state, "", url); } catch { // file:// and a few sandboxes reject replaceState; the assignment below // fires hashchange, which the lastWritten guard then ignores. location.hash = hash; }}
function currentHash() { return ENABLED ? "#" + buildHash() : "";}
// ─── Incoming navigation ─────────────────────────────────────────────────────
async function onHashChange() { if (!ENABLED || applying) return; const raw = String(location.hash).replace(/^#/, ""); if (raw === lastWritten) return; const params = parseHash(raw); if (!Object.keys(params).length) return; applying = true; try { const familyChanged = applyParams(params); renderSidebar(); if (familyChanged) { await switchBaseFamily(filters.baseFamily); } else { // Reset first so columns the URL omits fall back to their default, // then desiredFilterValue() re-applies the ones it does name. updateDependentFilters(true); render(); } } finally { applying = false; }}
// ─── Init ─────────────────────────────────────────────────────────────────────
// Applied here, before populateFilters()/switchBaseFamily() run, so the first// render already reflects the link. The hash therefore wins over the existing// ?family= query deep link, which is applied earlier in app.js.if (ENABLED) { const initial = parseHash(typeof location !== "undefined" ? location.hash : ""); if (Object.keys(initial).length) applyParams(initial); if (typeof window !== "undefined") window.addEventListener("hashchange", onHashChange);}
return { desiredFilterValue, sync, currentHash };
} // end initUrlStateapp.js+52-11
config.json+1
embed.js+5-2
index.html+2
speedup.jsAdded+127
style.css+21
urlstate.jsAdded+213