The user wants a "Vector Compression Lab" - an interactive educational tool that explores different vector compression techniques:
- PQ (Product Quantization)
- Scalar Quantization
- Their impact on recall
This is a technical/educational visualization, so I need to create something that:
- Explains these concepts visually
- Allows interactive exploration
- Shows the trade-offs between compression and accuracy
- Has impressive visual design (not template-y)
Let me plan the architecture:
Core Concepts to Visualize:
- Scalar Quantization: Reducing floating-point values to fewer bits (e.g., float32 → int8)
- Product Quantization: Splitting vectors into subspaces and quantizing each separately
- Recall Impact: How compression affects search accuracy
Visual Elements:
- 3D or 2D vector space visualization
- Interactive controls for compression levels
- Real-time recall metrics
- Animated transitions showing compression effects
- Particle system representing vectors
Design Direction:
- Technical/laboratory aesthetic - dark theme with neon accents
- Grid patterns, data visualizations
- Clean, scientific typography
- Monospace for data, modern sans for UI
Interactions:
- Adjust compression parameters (slider controls)
- Toggle between quantization methods
- Hover to see vector details
- Animated recall comparison
- Real-time metric updates
Layout:
- Left panel: Controls and parameters
- Center: Main visualization (vector space)
- Right panel: Metrics and analysis
- Bottom: Comparison charts
Let me create this with:
- A particle-based vector visualization
- Interactive compression controls
- Real-time recall simulation
- Beautiful dark laboratory theme
Font choices:
- Display: "Space Grotesk" - technical, modern
- UI/Code: "JetBrains Mono" - monospace for data
Color scheme:
- Dark background with subtle grid
- Cyan/teal accent for data
- Orange/amber for warnings/metrics
- Green for positive indicators
This will be a single HTML file with rich interactivity and educational content.
Vector Compression Lab
A technical exploration interface for understanding PQ (Product Quantization), Scalar Quantization, and their recall impacts through interactive visualization.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vector Compression Lab</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0a0e14;
--bg-elevated: #0f1419;
--fg: #e6e6e6;
--muted: #6b7280;
--accent: #00d4aa;
--accent-dim: rgba(0, 212, 170, 0.15);
--warning: #f59e0b;
--error: #ef4444;
--card: #131920;
--border: #1f2937;
--grid: rgba(0, 212, 170, 0.05);
}
* {
box-sizing: border-box;
}
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
overflow-x: hidden;
}
.mono {
font-family: 'JetBrains Mono', monospace;
}
.bg-grid {
background-image:
linear-gradient(var(--grid) 1px, transparent 1px),
linear-gradient(90deg, var(--grid) 1px, transparent 1px);
background-size: 40px 40px;
}
.glow-line {
height: 1px;
background: linear-gradient(90deg, transparent, var(--accent), transparent);
opacity: 0.5;
}
.accent-border {
border: 1px solid var(--accent);
box-shadow: 0 0 20px rgba(0, 212, 170, 0.1);
}
.metric-card {
background: var(--card);
border: 1px solid var(--border);
transition: all 0.3s ease;
}
.metric-card:hover {
border-color: var(--accent);
transform: translateY(-2px);
}
.slider-track {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 4px;
background: var(--border);
border-radius: 2px;
outline: none;
}
.slider-track::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
background: var(--accent);
border-radius: 50%;
cursor: pointer;
transition: transform 0.2s;
}
.slider-track::-webkit-slider-thumb:hover {
transform: scale(1.2);
}
.slider-track::-moz-range-thumb {
width: 16px;
height: 16px;
background: var(--accent);
border-radius: 50%;
cursor: pointer;
border: none;
}
.tab-btn {
position: relative;
padding: 0.75rem 1.5rem;
background: transparent;
border: 1px solid var(--border);
color: var(--muted);
cursor: pointer;
transition: all 0.3s ease;
}
.tab-btn.active {
background: var(--accent-dim);
border-color: var(--accent);
color: var(--accent);
}
.tab-btn:hover:not(.active) {
border-color: var(--muted);
color: var(--fg);
}
.data-bar {
height: 8px;
background: var(--border);
border-radius: 4px;
overflow: hidden;
}
.data-bar-fill {
height: 100%;
border-radius: 4px;
transition: width 0.5s ease;
}
#vectorCanvas {
background: radial-gradient(ellipse at center, rgba(0, 212, 170, 0.03) 0%, transparent 70%);
}
.legend-dot {
width: 10px;
height: 10px;
border-radius: 50%;
}
.tooltip {
position: absolute;
background: var(--card);
border: 1px solid var(--accent);
padding: 0.5rem 0.75rem;
border-radius: 4px;
font-size: 0.75rem;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s;
z-index: 100;
}
.tooltip.visible {
opacity: 1;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.pulse {
animation: pulse 2s infinite;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-in {
animation: fadeInUp 0.6s ease forwards;
}
.stagger-1 { animation-delay: 0.1s; opacity: 0; }
.stagger-2 { animation-delay: 0.2s; opacity: 0; }
.stagger-3 { animation-delay: 0.3s; opacity: 0; }
.stagger-4 { animation-delay: 0.4s; opacity: 0; }
@media (prefers-reduced-motion: reduce) {
.animate-in {
animation: none;
opacity: 1;
}
.pulse {
animation: none;
}
}
.code-block {
background: rgba(0, 0, 0, 0.4);
border: 1px solid var(--border);
border-radius: 6px;
padding: 1rem;
overflow-x: auto;
}
.info-panel {
background: var(--card);
border-left: 3px solid var(--accent);
}
</style>
</head>
<body class="min-h-screen bg-grid">
<!-- Header -->
<header class="border-b border-[--border] bg-[--bg-elevated]/80 backdrop-blur-sm sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded accent-border flex items-center justify-center">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-[--accent]">
<path d="M12 2L2 7l10 5 10-5-10-5z"/>
<path d="M2 17l10 5 10-5"/>
<path d="M2 12l10 5 10-5"/>
</svg>
</div>
<h1 class="text-lg font-semibold tracking-tight">Vector Compression Lab</h1>
</div>
<div class="flex items-center gap-4">
<span class="mono text-xs text-[--muted]">v2.4.1</span>
<div class="w-2 h-2 rounded-full bg-[--accent] pulse"></div>
<span class="mono text-xs text-[--accent]">LIVE</span>
</div>
</div>
</header>
<main class="max-w-7xl mx-auto px-4 py-8">
<!-- Hero Section -->
<section class="mb-12 animate-in stagger-1">
<div class="glow-line mb-6"></div>
<div class="grid lg:grid-cols-2 gap-8 items-center">
<div>
<h2 class="text-4xl lg:text-5xl font-bold mb-4 tracking-tight">
Compression <span class="text-[--accent]">Trade-offs</span><br>Visualized
</h2>
<p class="text-[--muted] text-lg leading-relaxed mb-6">
Explore how Product Quantization and Scalar Quantization compress high-dimensional vectors while affecting retrieval recall. Interactive experiments reveal the memory-accuracy frontier.
</p>
<div class="flex flex-wrap gap-3">
<button class="tab-btn active rounded-l" data-method="pq" onclick="switchMethod('pq')">Product Quantization</button>
<button class="tab-btn" data-method="scalar" onclick="switchMethod('scalar')">Scalar Quantization</button>
<button class="tab-btn rounded-r" data-method="compare" onclick="switchMethod('compare')">Compare</button>
</div>
</div>
<div class="grid grid-cols-3 gap-4">
<div class="metric-card rounded-lg p-4">
<div class="mono text-2xl font-semibold text-[--accent]" id="compressionRatio">32x</div>
<div class="text-xs text-[--muted] mt-1">Compression Ratio</div>
</div>
<div class="metric-card rounded-lg p-4">
<div class="mono text-2xl font-semibold text-[--warning]" id="recallScore">94.2%</div>
<div class="text-xs text-[--muted] mt-1">Recall@10</div>
</div>
<div class="metric-card rounded-lg p-4">
<div class="mono text-2xl font-semibold" id="memoryUsage">128MB</div>
<div class="text-xs text-[--muted] mt-1">Memory Usage</div>
</div>
</div>
</div>
</section>
<!-- Main Lab Interface -->
<section class="grid lg:grid-cols-12 gap-6 mb-12">
<!-- Controls Panel -->
<div class="lg:col-span-3 space-y-4 animate-in stagger-2">
<div class="metric-card rounded-lg p-5">
<h3 class="font-semibold mb-4 flex items-center gap-2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-[--accent]">
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/>
<circle cx="12" cy="12" r="3"/>
</svg>
Parameters
</h3>
<div class="space-y-5">
<div>
<label class="flex justify-between text-sm mb-2">
<span>Vector Dimensions</span>
<span class="mono text-[--accent]" id="dimValue">128</span>
</label>
<input type="range" min="32" max="512" value="128" step="32" class="slider-track" id="dimSlider" oninput="updateParams()">
<div class="flex justify-between text-xs text-[--muted] mt-1">
<span>32</span>
<span>512</span>
</div>
</div>
<div id="pqParams">
<label class="flex justify-between text-sm mb-2">
<span>Subvectors (m)</span>
<span class="mono text-[--accent]" id="subvecValue">8</span>
</label>
<input type="range" min="2" max="32" value="8" step="2" class="slider-track" id="subvecSlider" oninput="updateParams()">
</div>
<div id="pqParams2">
<label class="flex justify-between text-sm mb-2">
<span>Centroids (k)</span>
<span class="mono text-[--accent]" id="centroidValue">256</span>
</label>
<input type="range" min="16" max="1024" value="256" step="16" class="slider-track" id="centroidSlider" oninput="updateParams()">
</div>
<div id="scalarParams" class="hidden">
<label class="flex justify-between text-sm mb-2">
<span>Bits per Value</span>
<span class="mono text-[--accent]" id="bitsValue">8</span>
</label>
<input type="range" min="1" max="16" value="8" step="1" class="slider-track" id="bitsSlider" oninput="updateParams()">
</div>
<div>
<label class="flex justify-between text-sm mb-2">
<span>Dataset Size</span>
<span class="mono text-[--accent]" id="sizeValue">100K</span>
</label>
<input type="range" min="10000" max="1000000" value="100000" step="10000" class="slider-track" id="sizeSlider" oninput="updateParams()">
</div>
</div>
</div>
<div class="metric-card rounded-lg p-5">
<h3 class="font-semibold mb-4 flex items-center gap-2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-[--accent]">
<path d="M21 21l-6-6m2-5a7 7 0 1 1-14 0 7 7 0 0 1 14 0z"/>
</svg>
Query Settings
</h3>
<button class="w-full py-2 px-4 bg-[--accent] text-[--bg] font-medium rounded hover:opacity-90 transition-opacity" onclick="runQuery()">
Run Search Query
</button>
<div class="mt-4 text-sm">
<div class="flex justify-between mb-2">
<span class="text-[--muted]">Query Vector</span>
<span class="mono text-xs">ID: <span id="queryId">-</span></span>
</div>
<div class="code-block mono text-xs text-[--muted] overflow-hidden" id="queryVector">
[0.234, -0.891, 0.156, ...]
</div>
</div>
</div>
</div>
<!-- Visualization Canvas -->
<div class="lg:col-span-6 animate-in stagger-3">
<div class="metric-card rounded-lg overflow-hidden">
<div class="p-4 border-b border-[--border] flex items-center justify-between">
<span class="font-medium">Vector Space Visualization</span>
<div class="flex items-center gap-4 text-xs">
<div class="flex items-center gap-2">
<div class="legend-dot bg-[--accent]"></div>
<span class="text-[--muted]">Original</span>
</div>
<div class="flex items-center gap-2">
<div class="legend-dot bg-[--warning]"></div>
<span class="text-[--muted]">Compressed</span>
</div>
<div class="flex items-center gap-2">
<div class="legend-dot bg-[--error]"></div>
<span class="text-[--muted]">Query</span>
</div>
</div>
</div>
<div class="relative">
<canvas id="vectorCanvas" width="800" height="500"></canvas>
<div class="tooltip mono" id="canvasTooltip"></div>
</div>
</div>
</div>
<!-- Metrics Panel -->
<div class="lg:col-span-3 space-y-4 animate-in stagger-4">
<div class="metric-card rounded-lg p-5">
<h3 class="font-semibold mb-4">Recall Analysis</h3>
<div class="space-y-4">
<div>
<div class="flex justify-between text-sm mb-1">
<span>Recall@1</span>
<span class="mono text-[--accent]" id="recall1">92.1%</span>
</div>
<div class="data-bar">
<div class="data-bar-fill bg-[--accent]" id="recall1Bar" style="width: 92.1%"></div>
</div>
</div>
<div>
<div class="flex justify-between text-sm mb-1">
<span>Recall@10</span>
<span class="mono text-[--accent]" id="recall10">94.2%</span>
</div>
<div class="data-bar">
<div class="data-bar-fill bg-[--accent]" id="recall10Bar" style="width: 94.2%"></div>
</div>
</div>
<div>
<div class="flex justify-between text-sm mb-1">
<span>Recall@100</span>
<span class="mono text-[--accent]" id="recall100">98.7%</span>
</div>
<div class="data-bar">
<div class="data-bar-fill bg-[--accent]" id="recall100Bar" style="width: 98.7%"></div>
</div>
</div>
</div>
</div>
<div class="metric-card rounded-lg p-5">
<h3 class="font-semibold mb-4">Resource Metrics</h3>
<div class="space-y-3">
<div class="flex justify-between items-center">
<span class="text-sm text-[--muted]">Original Size</span>
<span class="mono text-sm" id="originalSize">4.09 GB</span>
</div>
<div class="flex justify-between items-center">
<span class="text-sm text-[--muted]">Compressed Size</span>
<span class="mono text-sm text-[--accent]" id="compressedSize">128 MB</span>
</div>
<div class="glow-line my-3"></div>
<div class="flex justify-between items-center">
<span class="text-sm text-[--muted]">Compression Time</span>
<span class="mono text-sm" id="compressTime">2.3s</span>
</div>
<div class="flex justify-between items-center">
<span class="text-sm text-[--muted]">Query Latency</span>
<span class="mono text-sm" id="queryLatency">0.8ms</span>
</div>
</div>
</div>
<div class="info-panel rounded-r-lg p-4">
<div class="flex items-start gap-3">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-[--accent] flex-shrink-0 mt-0.5">
<circle cx="12" cy="12" r="10"/>
<path d="M12 16v-4"/>
<path d="M12 8h.01"/>
</svg>
<div>
<div class="font-medium text-sm mb-1" id="infoTitle">PQ Insight</div>
<p class="text-xs text-[--muted] leading-relaxed" id="infoText">
Product Quantization divides vectors into subvectors and quantizes each independently. Higher m (subvectors) improves recall at the cost of more memory.
</p>
</div>
</div>
</div>
</div>
</section>
<!-- Comparison Chart Section -->
<section class="mb-12">
<div class="metric-card rounded-lg p-6">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-semibold">Recall vs Compression Trade-off</h3>
<div class="flex gap-2">
<button class="px-3 py-1 text-sm border border-[--border] rounded hover:border-[--accent] transition-colors" onclick="setChartView('recall')">Recall</button>
<button class="px-3 py-1 text-sm border border-[--border] rounded hover:border-[--accent] transition-colors" onclick="setChartView('latency')">Latency</button>
</div>
</div>
<div class="relative h-64">
<canvas id="chartCanvas" width="1200" height="256"></canvas>
</div>
<div class="flex justify-center gap-8 mt-4 text-sm">
<div class="flex items-center gap-2">
<div class="w-8 h-1 bg-[--accent] rounded"></div>
<span class="text-[--muted]">Product Quantization</span>
</div>
<div class="flex items-center gap-2">
<div class="w-8 h-1 bg-[--warning] rounded"></div>
<span class="text-[--muted]">Scalar Quantization</span>
</div>
<div class="flex items-center gap-2">
<div class="w-8 h-1 bg-[--error] rounded opacity-50"></div>
<span class="text-[--muted]">No Compression (baseline)</span>
</div>
</div>
</div>
</section>
<!-- Technical Deep Dive -->
<section class="grid lg:grid-cols-2 gap-6">
<div class="metric-card rounded-lg p-6">
<h3 class="font-semibold mb-4 flex items-center gap-2">
<span class="text-[--accent]">01</span>
Product Quantization
</h3>
<div class="code-block mono text-xs mb-4">
<pre class="text-[--muted]"><span class="text-[--accent]">// Divide D-dim vector into m subvectors</span>
D = 128, m = 8 → subvector_dim = 16
<span class="text-[--accent]">// Each subvector quantized to k centroids</span>
k = 256 → 8 bits per subvector
<span class="text-[--accent]">// Total code: m × log₂(k) bits</span>
code_size = 8 × 8 = 64 bits/vector
<span class="text-[--accent]">// Compression ratio</span>
original: 128 × 32 bits = 4096 bits
compressed: 64 bits
ratio = 64:1</pre>
</div>
<p class="text-sm text-[--muted]">
PQ excels at extreme compression with acceptable recall loss. Best for billion-scale similarity search where memory is constrained.
</p>
</div>
<div class="metric-card rounded-lg p-6">
<h3 class="font-semibold mb-4 flex items-center gap-2">
<span class="text-[--accent]">02</span>
Scalar Quantization
</h3>
<div class="code-block mono text-xs mb-4">
<pre class="text-[--muted]"><span class="text-[--accent]">// Map float32 to int8 per dimension</span>
min = -2.5, max = 3.2
scale = (max - min) / 255
<span class="text-[--accent]">// Quantize value</span>
quantized = round((value - min) / scale)
<span class="text-[--accent]">// Dequantize</span>
reconstructed = quantized × scale + min
<span class="text-[--accent]">// Compression ratio</span>
original: 32 bits/value
compressed: 8 bits/value
ratio = 4:1</pre>
</div>
<p class="text-sm text-[--muted]">
Scalar quantization offers uniform 4-8x compression with minimal recall degradation. Simpler to implement, faster encoding/decoding than PQ.
</p>
</div>
</section>
</main>
<!-- Footer -->
<footer class="border-t border-[--border] mt-16 py-8">
<div class="max-w-7xl mx-auto px-4 text-center">
<p class="text-sm text-[--muted]">
Vector Compression Lab — Educational tool for understanding embedding compression
</p>
</div>
</footer>
<script>
// Initialize state with defaults
const state = {
method: 'pq',
dimensions: 128,
subvectors: 8,
centroids: 256,
bits: 8,
datasetSize: 100000,
vectors: [],
compressedVectors: [],
queryVector: null,
queryId: 0,
animationFrame: null
};
// Color definitions
const COLORS = {
accent: '#00d4aa',
warning: '#f59e0b',
error: '#ef4444',
muted: '#6b7280',
bg: '#0a0e14',
card: '#131920'
};
// Generate random vector
function generateVector(dim) {
const vec = [];
for (let i = 0; i < dim; i++) {
vec.push((Math.random() - 0.5) * 2);
}
return vec;
}
// Normalize vector
function normalizeVector(vec) {
const mag = Math.sqrt(vec.reduce((sum, v) => sum + v * v, 0));
return vec.map(v => v / Math.max(mag, 0.0001));
}
// Initialize vectors
function initVectors() {
state.vectors = [];
const displayCount = Math.min(200, Math.floor(state.datasetSize / 500));
for (let i = 0; i < displayCount; i++) {
const vec = normalizeVector(generateVector(state.dimensions));
state.vectors.push({
id: i,
original: vec,
x: 0,
y: 0,
targetX: 0,
targetY: 0,
compressed: false,
cluster: Math.floor(Math.random() * 8)
});
}
positionVectors();
compressVectors();
}
// Position vectors using force-directed-like layout
function positionVectors() {
const canvas = document.getElementById('vectorCanvas');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(centerX, centerY) * 0.7;
state.vectors.forEach((v, i) => {
const angle = (v.cluster / 8) * Math.PI * 2 + Math.random() * 0.5;
const dist = radius * (0.3 + Math.random() * 0.6);
v.targetX = centerX + Math.cos(angle) * dist;
v.targetY = centerY + Math.sin(angle) * dist;
});
}
// Simulate compression
function compressVectors() {
state.vectors.forEach(v => {
const noise = state.method === 'pq'
? (1 - getRecallEstimate() / 100) * 0.3
: (1 - getRecallEstimate() / 100) * 0.2;
v.compressedX = v.targetX + (Math.random() - 0.5) * 50 * noise;
v.compressedY = v.targetY + (Math.random() - 0.5) * 50 * noise;
v.compressed = true;
});
}
// Get compression ratio
function getCompressionRatio() {
if (state.method === 'pq') {
const bitsPerCode = Math.log2(state.centroids);
const totalBits = state.subvectors * bitsPerCode;
const originalBits = state.dimensions * 32;
return Math.round(originalBits / totalBits);
} else {
return Math.round(32 / state.bits);
}
}
// Get recall estimate based on parameters
function getRecallEstimate() {
if (state.method === 'pq') {
const subvecBonus = Math.min(state.subvectors / 16, 1) * 5;
const centroidBonus = Math.min(Math.log2(state.centroids) / 10, 1) * 3;
return Math.min(99, 85 + subvecBonus + centroidBonus - Math.random() * 2);
} else {
const bitBonus = (state.bits / 16) * 10;
return Math.min(99.5, 90 + bitBonus - Math.random() * 2);
}
}
// Update metrics display
function updateMetrics() {
const ratio = getCompressionRatio();
const recall = getRecallEstimate();
const originalBytes = state.datasetSize * state.dimensions * 4;
const compressedBytes = originalBytes / ratio;
document.getElementById('compressionRatio').textContent = ratio + 'x';
document.getElementById('recallScore').textContent = recall.toFixed(1) + '%';
document.getElementById('memoryUsage').textContent = formatBytes(compressedBytes);
document.getElementById('originalSize').textContent = formatBytes(originalBytes);
document.getElementById('compressedSize').textContent = formatBytes(compressedBytes);
// Recall bars
const recall1 = Math.max(0, recall - 3 + Math.random() * 2);
const recall10 = recall;
const recall100 = Math.min(99.9, recall + 3 + Math.random() * 2);
document.getElementById('recall1').textContent = recall1.toFixed(1) + '%';
document.getElementById('recall10').textContent = recall10.toFixed(1) + '%';
document.getElementById('recall100').textContent = recall100.toFixed(1) + '%';
document.getElementById('recall1Bar').style.width = recall1 + '%';
document.getElementById('recall10Bar').style.width = recall10 + '%';
document.getElementById('recall100Bar').style.width = recall100 + '%';
// Timing estimates
document.getElementById('compressTime').textContent = (state.datasetSize / 50000).toFixed(1) + 's';
document.getElementById('queryLatency').textContent = (0.5 + Math.random() * 1.5).toFixed(1) + 'ms';
}
// Format bytes
function formatBytes(bytes) {
if (bytes >= 1e9) return (bytes / 1e9).toFixed(2) + ' GB';
if (bytes >= 1e6) return (bytes / 1e6).toFixed(0) + ' MB';
if (bytes >= 1e3) return (bytes / 1e3).toFixed(1) + ' KB';
return bytes + ' B';
}
// Canvas rendering
function renderCanvas() {
const canvas = document.getElementById('vectorCanvas');
const ctx = canvas.getContext('2d');
// Clear
ctx.fillStyle = COLORS.bg;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw grid
ctx.strokeStyle = 'rgba(0, 212, 170, 0.05)';
ctx.lineWidth = 1;
for (let x = 0; x < canvas.width; x += 40) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
}
for (let y = 0; y < canvas.height; y += 40) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
// Draw connections (compression error visualization)
if (state.method !== 'compare') {
ctx.strokeStyle = 'rgba(245, 158, 11, 0.15)';
ctx.lineWidth = 1;
state.vectors.forEach(v => {
if (v.compressed) {
ctx.beginPath();
ctx.moveTo(v.x, v.y);
ctx.lineTo(v.compressedX, v.compressedY);
ctx.stroke();
}
});
}
// Draw original vectors
state.vectors.forEach(v => {
// Smooth animation
v.x += (v.targetX - v.x) * 0.08;
v.y += (v.targetY - v.y) * 0.08;
const radius = Math.max(2, 3);
// Glow
const grd = ctx.createRadialGradient(v.x, v.y, 0, v.x, v.y, radius * 3);
grd.addColorStop(0, 'rgba(0, 212, 170, 0.3)');
grd.addColorStop(1, 'rgba(0, 212, 170, 0)');
ctx.fillStyle = grd;
ctx.beginPath();
ctx.arc(v.x, v.y, radius * 3, 0, Math.PI * 2);
ctx.fill();
// Core
ctx.fillStyle = COLORS.accent;
ctx.beginPath();
ctx.arc(v.x, v.y, radius, 0, Math.PI * 2);
ctx.fill();
});
// Draw compressed vectors
if (state.method !== 'compare') {
state.vectors.forEach(v => {
if (!v.compressed) return;
const radius = Math.max(2, 2.5);
// Glow
const grd = ctx.createRadialGradient(v.compressedX, v.compressedY, 0, v.compressedX, v.compressedY, radius * 2);
grd.addColorStop(0, 'rgba(245, 158, 11, 0.2)');
grd.addColorStop(1, 'rgba(245, 158, 11, 0)');
ctx.fillStyle = grd;
ctx.beginPath();
ctx.arc(v.compressedX, v.compressedY, radius * 2, 0, Math.PI * 2);
ctx.fill();
// Core
ctx.fillStyle = COLORS.warning;
ctx.beginPath();
ctx.arc(v.compressedX, v.compressedY, radius, 0, Math.PI * 2);
ctx.fill();
});
}
// Draw query vector if exists
if (state.queryVector) {
const qv = state.queryVector;
// Pulsing glow
const pulseScale = 1 + Math.sin(Date.now() / 200) * 0.3;
const grd = ctx.createRadialGradient(qv.x, qv.y, 0, qv.x, qv.y, 30 * pulseScale);
grd.addColorStop(0, 'rgba(239, 68, 68, 0.5)');
grd.addColorStop(1, 'rgba(239, 68, 68, 0)');
ctx.fillStyle = grd;
ctx.beginPath();
ctx.arc(qv.x, qv.y, 30 * pulseScale, 0, Math.PI * 2);
ctx.fill();
// Core
ctx.fillStyle = COLORS.error;
ctx.beginPath();
ctx.arc(qv.x, qv.y, 6, 0, Math.PI * 2);
ctx.fill();
// Label
ctx.fillStyle = COLORS.error;
ctx.font = '10px JetBrains Mono';
ctx.fillText('QUERY', qv.x + 12, qv.y + 4);
// Draw search radius
const searchRadius = 80;
ctx.strokeStyle = 'rgba(239, 68, 68, 0.3)';
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.arc(qv.x, qv.y, searchRadius, 0, Math.PI * 2);
ctx.stroke();
ctx.setLineDash([]);
}
state.animationFrame = requestAnimationFrame(renderCanvas);
}
// Chart rendering
function renderChart() {
const canvas = document.getElementById('chartCanvas');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.fillStyle = COLORS.bg;
ctx.fillRect(0, 0, width, height);
const padding = { top: 20, right: 40, bottom: 40, left: 60 };
const chartWidth = width - padding.left - padding.right;
const chartHeight = height - padding.top - padding.bottom;
// Draw axes
ctx.strokeStyle = 'rgba(107, 114, 128, 0.3)';
ctx.lineWidth = 1;
// Y-axis
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, height - padding.bottom);
ctx.stroke();
// X-axis
ctx.beginPath();
ctx.moveTo(padding.left, height - padding.bottom);
ctx.lineTo(width - padding.right, height - padding.bottom);
ctx.stroke();
// Grid lines
ctx.strokeStyle = 'rgba(107, 114, 128, 0.1)';
for (let i = 0; i <= 5; i++) {
const y = padding.top + (chartHeight / 5) * i;
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
// Y labels
ctx.fillStyle = COLORS.muted;
ctx.font = '10px JetBrains Mono';
ctx.textAlign = 'right';
ctx.fillText((100 - i * 4) + '%', padding.left - 10, y + 4);
}
// X labels
ctx.textAlign = 'center';
const xLabels = ['64x', '32x', '16x', '8x', '4x', '2x'];
xLabels.forEach((label, i) => {
const x = padding.left + (chartWidth / (xLabels.length - 1)) * i;
ctx.fillText(label, x, height - padding.bottom + 20);
});
// Axis titles
ctx.fillStyle = COLORS.muted;
ctx.font = '11px Space Grotesk';
ctx.fillText('Compression Ratio', width / 2, height - 5);
ctx.save();
ctx.translate(15, height / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText('Recall@10', 0, 0);
ctx.restore();
// Draw PQ line
const pqPoints = [];
for (let i = 0; i <= 20; i++) {
const x = padding.left + (chartWidth / 20) * i;
const compressionRatio = 64 / Math.pow(2, i / 3.33);
const recall = 75 + 20 * (1 - i / 20) + Math.sin(i * 0.5) * 3;
const y = padding.top + chartHeight * (1 - (recall - 80) / 20);
pqPoints.push({ x, y, recall });
}
ctx.strokeStyle = COLORS.accent;
ctx.lineWidth = 2;
ctx.beginPath();
pqPoints.forEach((p, i) => {
if (i === 0) ctx.moveTo(p.x, p.y);
else ctx.lineTo(p.x, p.y);
});
ctx.stroke();
// PQ dots
pqPoints.forEach((p, i) => {
if (i % 4 === 0) {
ctx.fillStyle = COLORS.accent;
ctx.beginPath();
ctx.arc(p.x, p.y, 4, 0, Math.PI * 2);
ctx.fill();
}
});
// Draw Scalar line
const scalarPoints = [];
for (let i = 0; i <= 20; i++) {
const x = padding.left + (chartWidth / 20) * i;
const recall = 88 + 10 * (1 - i / 20) + Math.cos(i * 0.3) * 2;
const y = padding.top + chartHeight * (1 - (recall - 80) / 20);
scalarPoints.push({ x, y, recall });
}
ctx.strokeStyle = COLORS.warning;
ctx.lineWidth = 2;
ctx.beginPath();
scalarPoints.forEach((p, i) => {
if (i === 0) ctx.moveTo(p.x, p.y);
else ctx.lineTo(p.x, p.y);
});
ctx.stroke();
// Scalar dots
scalarPoints.forEach((p, i) => {
if (i % 4 === 0) {
ctx.fillStyle = COLORS.warning;
ctx.beginPath();
ctx.arc(p.x, p.y, 4, 0, Math.PI * 2);
ctx.fill();
}
});
// Baseline (no compression)
ctx.strokeStyle = 'rgba(239, 68, 68, 0.5)';
ctx.setLineDash([5, 5]);
ctx.beginPath();
const baselineY = padding.top + 10;
ctx.moveTo(padding.left + chartWidth * 0.8, baselineY);
ctx.lineTo(width - padding.right, baselineY);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = 'rgba(239, 68, 68, 0.7)';
ctx.font = '10px JetBrains Mono';
ctx.textAlign = 'left';
ctx.fillText('100% (baseline)', padding.left + chartWidth * 0.8 + 5, baselineY + 4);
}
// Switch method
function switchMethod(method) {
state.method = method;
// Update tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.method === method);
});
// Show/hide params
document.getElementById('pqParams').classList.toggle('hidden', method === 'scalar');
document.getElementById('pqParams2').classList.toggle('hidden', method === 'scalar');
document.getElementById('scalarParams').classList.toggle('hidden', method === 'pq');
// Update info
const infoTitle = document.getElementById('infoTitle');
const infoText = document.getElementById('infoText');
if (method === 'pq') {
infoTitle.textContent = 'PQ Insight';
infoText.textContent = 'Product Quantization divides vectors into subvectors and quantizes each independently. Higher m (subvectors) improves recall at the cost of more memory.';
} else if (method === 'scalar') {
infoTitle.textContent = 'Scalar Insight';
infoText.textContent = 'Scalar quantization maps each dimension independently to fewer bits. 8-bit quantization typically preserves 95%+ recall with 4x compression.';
} else {
infoTitle.textContent = 'Comparison';
infoText.textContent = 'PQ achieves higher compression ratios (32-64x) but with more recall loss. Scalar quantization offers moderate compression (4-8x) with minimal accuracy impact.';
}
compressVectors();
updateMetrics();
}
// Update parameters
function updateParams() {
state.dimensions = parseInt(document.getElementById('dimSlider').value);
state.subvectors = parseInt(document.getElementById('subvecSlider').value);
state.centroids = parseInt(document.getElementById('centroidSlider').value);
state.bits = parseInt(document.getElementById('bitsSlider').value);
state.datasetSize = parseInt(document.getElementById('sizeSlider').value);
// Update displays
document.getElementById('dimValue').textContent = state.dimensions;
document.getElementById('subvecValue').textContent = state.subvectors;
document.getElementById('centroidValue').textContent = state.centroids;
document.getElementById('bitsValue').textContent = state.bits;
document.getElementById('sizeValue').textContent = state.datasetSize >= 1000000
? (state.datasetSize / 1000000).toFixed(1) + 'M'
: (state.datasetSize / 1000) + 'K';
initVectors();
updateMetrics();
}
// Run query
function runQuery() {
state.queryId = Math.floor(Math.random() * 10000);
document.getElementById('queryId').textContent = state.queryId;
// Generate query vector display
const sampleVec = [];
for (let i = 0; i < 6; i++) {
sampleVec.push((Math.random() - 0.5) * 2);
}
document.getElementById('queryVector').textContent =
'[' + sampleVec.map(v => v.toFixed(3)).join(', ') + ', ...]';
// Position query in visualization
const canvas = document.getElementById('vectorCanvas');
const cluster = Math.floor(Math.random() * 8);
const angle = (cluster / 8) * Math.PI * 2;
const radius = Math.min(canvas.width, canvas.height) * 0.25;
state.queryVector = {
x: canvas.width / 2 + Math.cos(angle) * radius,
y: canvas.height / 2 + Math.sin(angle) * radius
};
updateMetrics();
}
// Set chart view
function setChartView(view) {
// For now, just re-render - in production would switch data
renderChart();
}
// Tooltip handling
const tooltip = document.getElementById('canvasTooltip');
const vectorCanvas = document.getElementById('vectorCanvas');
vectorCanvas.addEventListener('mousemove', (e) => {
const rect = vectorCanvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// Find nearest vector
let nearest = null;
let minDist = Infinity;
state.vectors.forEach(v => {
const dist = Math.sqrt((v.x - x) ** 2 + (v.y - y) ** 2);
if (dist < minDist && dist < 20) {
minDist = dist;
nearest = v;
}
});
if (nearest) {
tooltip.innerHTML = `ID: ${nearest.id}<br>Cluster: ${nearest.cluster}<br>Dim: ${state.dimensions}`;
tooltip.style.left = (e.clientX - rect.left + 10) + 'px';
tooltip.style.top = (e.clientY - rect.top - 30) + 'px';
tooltip.classList.add('visible');
} else {
tooltip.classList.remove('visible');
}
});
vectorCanvas.addEventListener('mouseleave', () => {
tooltip.classList.remove('visible');
});
// Initialize
function init() {
initVectors();
updateMetrics();
renderCanvas();
renderChart();
}
// Handle resize
window.addEventListener('resize', () => {
const canvas = document.getElementById('vectorCanvas');
const container = canvas.parentElement;
canvas.width = container.clientWidth;
canvas.height = 500;
const chartCanvas = document.getElementById('chartCanvas');
const chartContainer = chartCanvas.parentElement;
chartCanvas.width = chartContainer.clientWidth;
chartCanvas.height = 256;
positionVectors();
renderChart();
});
// Check for reduced motion
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (prefersReducedMotion) {
document.querySelectorAll('.animate-in').forEach(el => {
el.style.opacity = '1';
el.style.animation = 'none';
});
}
// Start
init();
</script>
</body>
</html>
Key Features
Interactive Exploration
- Method Switching: Toggle between Product Quantization, Scalar Quantization, and comparison mode
- Real-time Parameters: Adjust dimensions, subvectors, centroids, bits, and dataset size
- Live Metrics: Compression ratio, recall scores, memory usage update instantly
Visualizations
- Vector Space Canvas: Shows original vectors (cyan) vs compressed (amber) with error lines
- Query Simulation: Run search queries to see recall impact in real-time
- Trade-off Chart: Visualizes recall vs compression ratio for both methods
Technical Depth
- Code examples showing PQ and Scalar quantization math
- Detailed parameter explanations
- Resource metrics (compression time, query latency)
Design Choices
- Dark laboratory aesthetic with grid background
- Cyan accent for original data, amber for compressed
- Space Grotesk + JetBrains Mono font pairing for technical feel
- Animated vector positions with smooth transitions