File size: 10,335 Bytes
fd627ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Spectral Nearest Neighbours Playground</title>
<style>
:root {
--bg: #070a12;
--card: #0f172a;
--card-border: #1e293b;
--ink: #f8fafc;
--mute: #94a3b8;
--accent: #38bdf8;
--spec: #f59e0b;
--ok: #22c55e;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--ink);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 24px;
}
.container { max-width: 1100px; margin: 0 auto; }
header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.badge { background: #0369a1; color: #fff; padding: 4px 10px; border-radius: 99px; font-size: 12px; font-weight: 600; }
.card { background: var(--card); border: 1px solid var(--card-border); border-radius: 12px; padding: 20px; margin-bottom: 18px; }
h2 { margin: 0 0 12px; font-size: 16px; font-weight: 700; color: #e2e8f0; }
input, textarea { width: 100%; background: #020617; border: 1px solid var(--card-border); color: #fff; border-radius: 8px; padding: 10px; outline: none; margin-bottom: 10px; }
.btn { background: var(--accent); color: #020617; border: 0; padding: 9px 18px; border-radius: 8px; font-weight: 700; cursor: pointer; }
.btn-secondary { background: #334155; color: #f8fafc; margin-left: 8px; }
.btn:hover { filter: brightness(1.1); }
.chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 12px; }
.chip { background: #1e293b; color: var(--mute); border: 1px solid #334155; padding: 5px 12px; border-radius: 99px; font-size: 12px; cursor: pointer; }
.chip:hover { color: #fff; border-color: var(--accent); }
.results-list { list-style: none; padding: 0; margin: 0; }
.item { display: flex; justify-content: space-between; align-items: center; background: #020617; border: 1px solid var(--card-border); padding: 10px 14px; border-radius: 8px; margin-bottom: 8px; }
.item-rank { font-weight: 700; color: var(--spec); width: 24px; }
.item-text { flex: 1; padding: 0 12px; font-size: 14px; }
.item-sim { font-family: monospace; color: var(--ok); font-weight: 600; }
</style>
</head>
<body>
<div class="container">
<header>
<div>
<h1 style="margin:0;font-size:22px;">⚡ Spectral Embeddings Playground</h1>
<div style="color:var(--mute);font-size:13px;margin-top:4px;">Direct evaluation of <code>JMullings/Spectral_Embeddings</code></div>
</div>
<span class="badge">Model: 3.93 MB · 0.45 ms</span>
</header>
<!-- Random Test Suite Card -->
<div class="card" style="border-color: #0284c7; background: #082f4922;">
<h2>🎲 Automated NN Probe & Random Generator</h2>
<p style="font-size:13px;color:var(--mute);margin:0 0 12px;">Instantly populate diverse domains to benchmark semantic discrimination.</p>
<div class="chips">
<button class="chip" onclick="loadProbe(0)">🔑 Auth & Security</button>
<button class="chip" onclick="loadProbe(1)">🤖 Machine Learning</button>
<button class="chip" onclick="loadProbe(2)">🧬 Biology & Medicine</button>
<button class="chip" onclick="loadProbe(3)">⚡ Algorithms</button>
<button class="chip" onclick="generateRandomList()">🔀 Shuffle Random 6-Domain Mix</button>
</div>
</div>
<!-- Playground Form -->
<div class="card">
<h2>Target Sentence (Anchor)</h2>
<input id="targetInput" value="How do I reset my account password?">
<h2>Neighbor Sentences (Candidates to Rank)</h2>
<textarea id="neighborsInput" rows="6">Steps to change login credentials and regain account access.
I forgot my password and need to restore my profile.
Enable two-factor authentication for higher security.
The capital of France is Paris with many historic landmarks.
Database indexes improve query retrieval speed at write expense.
Quicksort has an average runtime complexity of O(n log n).</textarea>
<div style="margin-top:6px;">
<button class="btn" id="runBtn" onclick="computeRankings()">Compute Nearest Neighbors</button>
<span id="latencySpan" style="font-size:12px;color:var(--mute);margin-left:12px;"></span>
</div>
</div>
<!-- Output Ranking -->
<div class="card" id="resultsCard" style="display:none;">
<h2>Nearest Neighbor Ranking (Spectral Manifold)</h2>
<ul class="results-list" id="resultsUl"></ul>
</div>
</div>
<script>
const PROBES = [
{
target: "How do I reset my account password?",
list: [
"Steps to change login credentials and regain account access.",
"I forgot my password and need to restore my profile.",
"Enable two-factor authentication for higher security.",
"The capital of France is Paris with many historic landmarks.",
"Mitochondria produce cellular ATP through oxidative phosphorylation."
]
},
{
target: "Transformers utilize self-attention mechanisms to process sequential text.",
list: [
"Self-attention layers in transformer models model contextual token dependencies.",
"Deep neural networks learn hierarchical feature representations from data.",
"The optimizer updates model weights step by step down the loss gradient.",
"To make espresso, force pressurized hot water through finely ground coffee.",
"The local hockey team won their championship game on Sunday evening."
]
},
{
target: "Antibiotics target bacterial cell walls without damaging human cells.",
list: [
"Antimicrobial drugs kill bacteria by disrupting bacterial peptidoglycan synthesis.",
"Supernovae scatter heavy elements into the surrounding interstellar medium.",
"Monetary tightening through rate hikes aims to cool overheated consumer prices.",
"Central banks raise interest rates to suppress rising inflation."
]
},
{
target: "Quicksort has an average runtime complexity of O(n log n).",
list: [
"Partitioning around pivot elements yields n log n expected sorting performance.",
"B-tree indices speed up SELECT lookups but increase INSERT latency.",
"Database indexes improve query retrieval speed at write expense.",
"The ancient Roman colosseum hosted gladiatorial games and spectacles."
]
}
];
const RANDOM_POOL = [
"Deadlocks occur when concurrent threads hold locks while waiting on each other.",
"Quantum entanglement links particle quantum states across space.",
"Central banks raise interest rates to suppress rising inflation.",
"Monet painted water lilies using impressionist brushstroke techniques.",
"Bake the bread dough at 200 degrees Celsius for 30 minutes.",
"Supernovae scatter heavy elements into the surrounding interstellar medium.",
"The stock index gained two percent following quarterly corporate earnings."
];
function loadProbe(idx) {
const p = PROBES[idx];
if (!p) return;
document.getElementById("targetInput").value = p.target;
document.getElementById("neighborsInput").value = p.list.join("\n");
computeRankings();
}
function generateRandomList() {
const shuffled = [...RANDOM_POOL].sort(() => 0.5 - Math.random()).slice(0, 5);
const randomProbe = PROBES[Math.floor(Math.random() * PROBES.length)];
document.getElementById("targetInput").value = randomProbe.target;
shuffled.unshift(randomProbe.list[0]);
document.getElementById("neighborsInput").value = shuffled.join("\n");
computeRankings();
}
function meanCenter(embeddings) {
const dim = embeddings[0].length;
const mean = new Float32Array(dim);
for (let i = 0; i < embeddings.length; i++) {
for (let d = 0; d < dim; d++) mean[d] += embeddings[i][d];
}
for (let d = 0; d < dim; d++) mean[d] /= embeddings.length;
return embeddings.map(emb => {
const centered = new Float32Array(dim);
let norm = 0;
for (let d = 0; d < dim; d++) {
centered[d] = emb[d] - mean[d];
norm += centered[d] * centered[d];
}
norm = Math.sqrt(norm) || 1e-12;
return Array.from(centered, x => x / norm);
});
}
async function computeRankings() {
const target = document.getElementById("targetInput").value.trim();
const cands = document.getElementById("neighborsInput").value.split("\n").map(s => s.trim()).filter(Boolean);
if (!target || !cands.length) return;
const t0 = performance.now();
const resp = await fetch("/api/embed", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ input: [target, ...cands] })
});
const data = await resp.json();
const elapsed = (performance.now() - t0).toFixed(2);
document.getElementById("latencySpan").textContent =
`Processed in ${elapsed} ms (${(elapsed / (cands.length + 1)).toFixed(3)} ms/sent)`;
const normalizedEmbs = meanCenter(data.embeddings);
const tEmb = normalizedEmbs[0];
const scored = cands.map((c, i) => {
const emb = normalizedEmbs[i + 1];
let dot = 0;
for (let j = 0; j < tEmb.length; j++) dot += tEmb[j] * emb[j];
return { text: c, score: dot };
});
scored.sort((a, b) => b.score - a.score);
const ul = document.getElementById("resultsUl");
ul.innerHTML = "";
scored.forEach((item, idx) => {
const li = document.createElement("li");
li.className = "item";
li.innerHTML = `
<span class="item-rank">#${idx + 1}</span>
<span class="item-text">${item.text}</span>
<span class="item-sim">cos: ${item.score.toFixed(6)}</span>
`;
ul.appendChild(li);
});
document.getElementById("resultsCard").style.display = "block";
}
window.addEventListener("DOMContentLoaded", computeRankings);
</script>
</body>
</html> |