# BLT Patching Visualization App - Design Document **Date**: 2025-10-22 **Author**: Claude **Status**: Design Phase --- ## Table of Contents 1. [Executive Summary](#executive-summary) 2. [BLT Patching Analysis](#blt-patching-analysis) 3. [Patching Strategies](#patching-strategies) 4. [Key Findings from Ablations](#key-findings-from-ablations) 5. [Application Architecture](#application-architecture) 6. [Feature Specifications](#feature-specifications) 7. [Technical Implementation Plan](#technical-implementation-plan) 8. [Data Flow](#data-flow) 9. [UI/UX Design](#uiux-design) 10. [Development Roadmap](#development-roadmap) --- ## Executive Summary This document outlines the design for a comprehensive Gradio application that allows interactive exploration of BLT (Byte Latent Transformer) patching strategies. The app will support: - **Multiple patching strategies**: Strided, Space, Entropy (global & monotonic), BPE-based - **Flexible entropy models**: Different sizes, context windows, architectures - **Multiple metrics**: Both entropy and perplexity based patching - **Advanced constraints**: Logarithmic conversions, additive/multiplicative monotonicity - **Rich visualizations**: Audio spectrograms, entropy/perplexity plots, patch boundaries - **Interactive audio**: Listen to original audio and individual patches --- ## BLT Patching Analysis ### Core Concept BLT dynamically groups bytes into **patches** (variable-length segments) to allocate compute efficiently based on data complexity. Unlike fixed-vocabulary tokenization, patches: 1. Have no fixed vocabulary 2. Are determined dynamically based on context 3. Allocate more compute where complexity is higher 4. Enable simultaneous scaling of model size and patch size ### Why Patching Matters **Performance Impact**: - Patch size directly determines inference FLOPs - Average patch size of 8 bytes → ~50% inference FLOP savings vs BPE - BLT with ps=8 matches Llama 3 performance with half the inference cost **Training Efficiency**: - Longer patches reduce sequence length → fewer transformer steps - Saves compute in the expensive global latent transformer - Enables trading patch size for model size at fixed inference budget --- ## Patching Strategies ### 1. Strided Patching (§2.1) **Description**: Fixed-size patches of k bytes **Implementation**: ```python def strided_patching(bytes, k): return [bytes[i:i+k] for i in range(0, len(bytes), k)] ``` **Characteristics**: - ✅ Simple to implement - ✅ Easy to control patch size - ✅ Consistent for training and inference - ❌ No dynamic compute allocation - ❌ Same word can be split differently in different contexts - ❌ Wastes compute on easy predictions (whitespace, etc.) **Performance** (from Figure 6): - Significantly underperforms BPE models - Gap widens at larger scales - Used as baseline (MegaByte architecture) **Parameters**: - `k`: Stride size (typically 4, 6, or 8 bytes) --- ### 2. Space Patching (§2.2) **Description**: Create patches after space-like bytes (natural linguistic boundaries) **Space-like bytes defined as**: - Any byte that is NOT: - Latin character - Digit - UTF-8 continuation byte - Each patch must contain ≥1 non-space-like byte **Implementation**: ```python def is_space_like(byte): return not (is_latin(byte) or is_digit(byte) or is_utf8_continuation(byte)) def space_patching(bytes): patches = [] current_patch = [] has_non_space = False for byte in bytes: current_patch.append(byte) if not is_space_like(byte): has_non_space = True if is_space_like(byte) and has_non_space: patches.append(current_patch) current_patch = [] has_non_space = False if current_patch: patches.append(current_patch) return patches ``` **Characteristics**: - ✅ Consistent patching across contexts - ✅ Allocates compute at word boundaries (where it's needed) - ✅ Simple, no entropy model needed - ❌ Cannot vary patch size easily - ❌ Language/domain dependent - ⚠️ Works well for space-delimited languages **Performance** (from Table 6, Figure 6): - Outperforms strided patching - Close competitor to entropy patching on scaling trends - Slightly underperforms entropy on downstream tasks - At 8B scale (Llama 2 data): 67.2 ARC-E, 37.6 ARC-C, 70.8 HellaSwag **Use Case**: SpaceByte approximation, simple baseline --- ### 3. Entropy Patching (§2.3) - PRIMARY FOCUS **Description**: Use next-byte entropy from a small LM to identify patch boundaries #### 3.1 Entropy Model **Architecture** (from §4.2): - Small transformer (1M - 100M parameters) - Standard choice: 100M params, 14 layers, 512 hidden dim - Sliding window attention (512 bytes) - Trained on same data as full BLT model **Entropy Calculation**: ```python H(x_i) = -Σ p_e(x_i = v | x_{ θ_g **Implementation**: ```python def entropy_patching_global(bytes, entropy_model, theta_g): entropies = [entropy_model.compute_entropy(bytes[:i+1]) for i in range(len(bytes))] patches = [] current_patch = [] for i, byte in enumerate(bytes): current_patch.append(byte) if entropies[i] > theta_g: patches.append(current_patch) current_patch = [] if current_patch: patches.append(current_patch) return patches, entropies ``` **Characteristics**: - Absolute threshold across all positions - Identifies high-uncertainty bytes (e.g., first letter of word) - Figure 4 example: "George R.R. Martin" - "G" exceeds threshold **Threshold Selection** (§4.3): - Estimate θ_g to achieve desired average patch size - Sweep threshold on training data - Choose value that gives target patch size (e.g., 4.5, 6, 8 bytes) #### 3.3 Approximate Monotonicity Constraint **Rule**: Start new patch when H(x_i) - H(x_{i-1}) > θ_r **Implementation**: ```python def entropy_patching_monotonic(bytes, entropy_model, theta_r): entropies = [entropy_model.compute_entropy(bytes[:i+1]) for i in range(len(bytes))] patches = [] current_patch = [bytes[0]] for i in range(1, len(bytes)): entropy_increase = entropies[i] - entropies[i-1] if entropy_increase > theta_r: patches.append(current_patch) current_patch = [bytes[i]] else: current_patch.append(bytes[i]) if current_patch: patches.append(current_patch) return patches, entropies ``` **Characteristics**: - Identifies points that break monotonically decreasing entropy - More robust to "entropy drift" in long contexts - Preferred for production models (Table 1: BLT-Entropy 8B) **Intuition**: Within a patch, entropy should generally decrease as context builds. When it increases, we've hit a new uncertain region → new patch. #### 3.4 Context Management **Challenge**: Repetitive patterns can cause very large patches (Figure 9 - MMLU example) **Solution** (§4.4): - Reset entropy context at newlines - Use approximate monotonicity instead of global threshold - Prevents "entropy drift" where model gets too confident from repeated patterns **Trade-offs**: - More resets → smaller patches → more compute - Fewer resets → larger patches → less compute, but may miss reasoning opportunities #### 3.5 Entropy vs Perplexity **Entropy**: ```python H(x_i) = -Σ p(v) log p(v) ``` **Perplexity**: ```python PPL(x_i) = 2^{H(x_i)} # or exp(H(x_i)) for nats ``` **Logarithmic Conversion**: - Perplexity is exponential transform of entropy - Higher perplexity = higher uncertainty = more choices - Can threshold on either metric **Implementation Note**: Paper uses entropy, but perplexity is more interpretable - Entropy of 3 bits → perplexity of 8 → "8 equally likely choices" --- ### 4. BPE-Based Patching (§2.4) **Description**: Use tokenizer boundaries as patch boundaries **Characteristics**: - ⚠️ **Not incremental**: Same prefix can tokenize differently based on continuation - Cannot be used directly for generation - Requires delimiter tokens to make incremental - Increases sequence length **Incremental Patching Property**: ``` f_p(x_{ Space > Strided ### Entropy Model Hyperparameters (Figure 8) **Effect of Model Size** (512-byte context): - 1M params: ~1.00 BPB - 10M params: ~0.95 BPB - 50M params: ~0.92 BPB - 100M params: ~0.90 BPB **Effect of Context Window** (10M params): - 64 bytes: ~0.98 BPB - 128 bytes: ~0.96 BPB - 512 bytes: ~0.95 BPB **Optimal**: 50M-100M params, 512-byte context (diminishing returns beyond) ### Cross-Attention Impact (Table 7) **1B model, 100B bytes**: | Decoder CA | Encoder CA | Pooling Init | Wikipedia | CC | GitHub | |------------|------------|--------------|-----------|-----|---------| | None | All Layers | False | 0.830 | 0.915 | 0.442 | | All Layers | Last Layer | True | **0.823** | **0.871** | 0.443 | | All Layers | All Layers | True | 0.828 | **0.868** | 0.443 | **Key Findings**: - Decoder cross-attention is crucial - Encoder cross-attention helps with pooling initialization - Particularly important for larger patch sizes and Common Crawl data ### N-gram Hash Embeddings (Table 8) **Effect on performance (1B model, 100B bytes)**: | N-gram Sizes | Vocab per N-gram | Total Vocab | Wikipedia BPB | CC BPB | GitHub BPB | |--------------|------------------|-------------|---------------|--------|------------| | None | - | - | 0.892 | 0.867 | 0.506 | | 3,4,5 | 100k | 300k | 0.859 | 0.855 | 0.491 | | 3,4,5 | 400k | 1M | 0.844 | 0.851 | 0.483 | | 3,4,5,6,7,8 | 400k | 2M | **0.831** | **0.846** | **0.478** | **Key Findings**: - Smaller n-grams (3,4,5) more impactful than larger (6,7,8) - Vocab size per n-gram matters most - Diminishing returns after 300-500K hashes - Complementary to cross-attention (help on different datasets) ### Patch Size Scaling (Figure 1, Table 2) **Fixed Inference FLOPs - Variable Patch Size**: At 470M-760M inference budget: - Llama 2 BPE (450M): Baseline - BLT ps=6 (610M): Crossover at 150B bytes - BLT ps=8 (760M): Crossover at 150B bytes, better at scale At 3.6B-6.6B inference budget: - Llama 2 BPE (3.6B): Baseline - BLT ps=6 (5.2B): Crossover at 1T bytes - BLT ps=8 (6.4B): Crossover at 1T bytes, steeper scaling **Key Insight**: Larger patch sizes become more advantageous at larger scales and training budgets --- ## Application Architecture ### High-Level Architecture ``` ┌─────────────────────────────────────────────────────────────┐ │ Gradio Frontend │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Audio Upload │ │ Parameters │ │ Visualization │ │ │ │ & Player │ │ Controls │ │ Panel │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ Processing Pipeline │ │ ┌────────────────────────────────────────────────────┐ │ │ │ 1. Audio Loading & WavTokenizer Encoding │ │ │ └────────────────────────────────────────────────────┘ │ │ ┌────────────────────────────────────────────────────┐ │ │ │ 2. Entropy/Perplexity Model Inference │ │ │ └────────────────────────────────────────────────────┘ │ │ ┌────────────────────────────────────────────────────┐ │ │ │ 3. Patching Strategy Application │ │ │ └────────────────────────────────────────────────────┘ │ │ ┌────────────────────────────────────────────────────┐ │ │ │ 4. Visualization Generation │ │ │ └────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ Data Storage │ │ - Cached entropy models (1M, 10M, 50M, 100M) │ │ - Precomputed entropies (optional) │ │ - Generated visualizations │ └─────────────────────────────────────────────────────────────┘ ``` ### Component Breakdown #### 1. Audio Processing Module - Load audio files (MP3, WAV, FLAC) - WavTokenizer encoding (40 tokens/sec, 4096 vocab) - Spectrogram generation (Mel-spectrogram, STFT) #### 2. Entropy/Perplexity Module - Multiple entropy model sizes (1M, 10M, 50M, 100M params) - Configurable context windows (64, 128, 256, 512 bytes) - Different architectures: - Transformer (default) - CNN byte-level (2-byte context) - LSTM (research) - Compute both entropy and perplexity - Logarithmic transformations #### 3. Patching Engine - Strided patching (k=4,6,8) - Space patching - Entropy-based patching: - Global threshold - Monotonic constraint (additive) - Multiplicative monotonicity (experimental) - BPE-based (comparison) - Configurable parameters for each strategy #### 4. Visualization Engine - Audio waveform + spectrogram - Entropy/perplexity plots over time - Patch boundaries overlaid - Interactive zoom/pan - Color-coded patches by size - Statistics dashboard #### 5. Audio Playback Module - Play original audio - Play individual patches - Play with patch boundaries (audible markers) --- ## Feature Specifications ### Feature 1: Audio Upload & Management **Inputs**: - File upload (MP3, WAV, FLAC) - Or select from voice_samples - Or paste URL (YouTube/SoundCloud with download) **Processing**: - Convert to 24kHz mono - WavTokenizer encoding - Cache encoded tokens **Outputs**: - Token sequence (4096 vocab) - Duration, sample rate, token count - Audio player widget --- ### Feature 2: Entropy Model Selection **Configurable Parameters**: 1. **Model Size**: Dropdown - 1M params (fast, less accurate) - 10M params (balanced) - 50M params (good quality) - 100M params (best quality, slower) 2. **Context Window**: Slider - 64, 128, 256, 512 bytes - Default: 512 3. **Architecture**: Dropdown - Transformer (default) - CNN byte-level - LSTM 4. **Training Status**: - Pre-trained (load from checkpoint) - Train on-the-fly (small datasets) **Metric Selection**: - Entropy (bits) - Perplexity (exponential) - Both (dual plot) --- ### Feature 3: Patching Strategy Configuration **Strategy Selector**: Radio buttons - Strided - Space - Entropy - Global Threshold - Entropy - Monotonic - BPE-based - Custom (advanced) #### Strided Parameters - Stride k: Slider (1-16 bytes) #### Space Parameters - Space-like byte definition: Text input (regex) - Min patch size: Number input #### Entropy - Global Threshold Parameters - Threshold θ_g: Slider (0-10 bits) - Auto-calculate for target patch size - Target patch size: Number input (4-12 bytes) #### Entropy - Monotonic Parameters - Threshold θ_r: Slider (0-5 bits) - Monotonicity type: - Additive: H(x_i) - H(x_{i-1}) > θ_r - Multiplicative: H(x_i) / H(x_{i-1}) > θ_m - Context reset: - Never - At newlines (audio: silence detection) - Every N tokens #### Advanced Options - Logarithmic transform: Checkbox - Log base: Number input (2, e, 10) - Min/max patch size constraints - Smoothing window for entropy --- ### Feature 4: Visualization Panel **Layout**: 4 synchronized plots #### Plot 1: Audio Waveform - X-axis: Time (seconds) - Y-axis: Amplitude - Overlays: Patch boundaries (vertical lines) - Color: Gradient by patch size - Interactive: Click to play from position #### Plot 2: Spectrogram - X-axis: Time (seconds) - Y-axis: Frequency (Hz) - Color: Magnitude (dB) - Overlays: Patch boundaries - Type: Mel-spectrogram or STFT #### Plot 3: Entropy/Perplexity Plot - X-axis: Token position - Y-axis 1: Entropy (bits) - blue line - Y-axis 2: Perplexity (exponential) - orange line - Horizontal line: Threshold value - Vertical lines: Patch boundaries - Annotations: Patch numbers #### Plot 4: Patch Statistics - Bar chart: Patch sizes histogram - Table: Per-patch statistics - Patch ID - Start/end position - Duration (ms) - Size (tokens) - Avg entropy - Max entropy - Entropy change **Interactivity**: - Hover: Show detailed info - Click patch boundary: Highlight corresponding patch in all plots - Zoom: Synchronized across plots - Export: Save as PNG/PDF/SVG --- ### Feature 5: Audio Playback **Controls**: 1. **Play Original**: Full audio file 2. **Play with Markers**: Audible click at patch boundaries 3. **Play Single Patch**: Select patch ID, play isolated 4. **Play Patch Sequence**: Select range, play concatenated **Patch Audio Extraction**: ```python def extract_patch_audio(audio, tokens, patch_tokens): # Map tokens back to audio samples token_duration = 1/40 # 40 tokens/sec start_sample = int(patch_tokens[0] * token_duration * sample_rate) end_sample = int(patch_tokens[-1] * token_duration * sample_rate) return audio[start_sample:end_sample] ``` **Visualization**: - Highlight current playing patch - Progress bar - Waveform cursor --- ### Feature 6: Comparison Mode **Purpose**: Compare multiple patching strategies side-by-side **Layout**: Split view (2-4 strategies) **Synchronized**: - Same audio file - Same time axis - Synchronized playback **Comparison Metrics**: - Total patches - Avg patch size - Compute cost (estimated FLOPs) - Patch size distribution - Boundary agreement (Jaccard index) --- ### Feature 7: Batch Processing **Inputs**: - Multiple audio files - Directory of files **Process**: - Apply same patching strategy to all - Aggregate statistics - Generate summary report **Outputs**: - CSV with per-file statistics - Combined visualizations - Distribution plots across files --- ### Feature 8: Export & Sharing **Export Options**: 1. **Visualizations**: PNG, PDF, SVG 2. **Patch Data**: JSON, CSV - Patch boundaries - Entropies/perplexities - Statistics 3. **Configuration**: YAML/JSON - Reproduce exact settings 4. **Audio Patches**: Individual WAV files per patch **Sharing**: - Generate shareable link (Gradio public) - Embed code for notebooks --- ## Technical Implementation Plan ### Technology Stack **Frontend**: - Gradio 4.x (UI framework) - Plotly (interactive plots) - HTML/CSS/JS (custom components) **Backend**: - Python 3.10+ - PyTorch 2.x (entropy models) - NumPy/SciPy (numerical operations) - Librosa (audio processing) - Torchaudio (WavTokenizer integration) **Storage**: - HDF5 (precomputed entropies, cached models) - Parquet (batch processing results) ### Key Libraries ```python import gradio as gr import torch import torchaudio import librosa import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd from pathlib import Path from typing import List, Tuple, Optional, Dict ``` ### Core Classes #### 1. EntropyModel ```python class EntropyModel: """Compute next-byte entropies for patching""" def __init__(self, model_size: str = "100M", context_window: int = 512, architecture: str = "transformer", checkpoint_path: Optional[str] = None): self.model_size = model_size self.context_window = context_window self.architecture = architecture self.load_model(checkpoint_path) def compute_entropy(self, tokens: np.ndarray, use_perplexity: bool = False) -> np.ndarray: """ Compute entropy/perplexity for each token Args: tokens: Token sequence (shape: [seq_len]) use_perplexity: Return perplexity instead of entropy Returns: Entropies/perplexities (shape: [seq_len]) """ pass def load_model(self, checkpoint_path: Optional[str]): """Load pre-trained entropy model""" pass ``` #### 2. PatchingStrategy ```python class PatchingStrategy(ABC): """Abstract base class for patching strategies""" @abstractmethod def patch(self, tokens: np.ndarray, entropies: Optional[np.ndarray] = None) -> List[List[int]]: """ Apply patching strategy Args: tokens: Token sequence entropies: Pre-computed entropies (if needed) Returns: List of patches (each patch is list of token indices) """ pass class StridedPatching(PatchingStrategy): def __init__(self, stride: int = 8): self.stride = stride def patch(self, tokens, entropies=None): return [list(range(i, min(i+self.stride, len(tokens)))) for i in range(0, len(tokens), self.stride)] class SpacePatching(PatchingStrategy): def __init__(self, space_tokens: List[int]): self.space_tokens = space_tokens def patch(self, tokens, entropies=None): # Implementation pass class EntropyGlobalPatching(PatchingStrategy): def __init__(self, threshold: float = 2.0): self.threshold = threshold def patch(self, tokens, entropies): patches = [] current_patch = [] for i, (token, entropy) in enumerate(zip(tokens, entropies)): current_patch.append(i) if entropy > self.threshold: patches.append(current_patch) current_patch = [] if current_patch: patches.append(current_patch) return patches class EntropyMonotonicPatching(PatchingStrategy): def __init__(self, threshold: float = 0.5, monotonicity: str = "additive", reset_on_silence: bool = True): self.threshold = threshold self.monotonicity = monotonicity self.reset_on_silence = reset_on_silence def patch(self, tokens, entropies): # Implementation with additive/multiplicative options pass ``` #### 3. AudioProcessor ```python class AudioProcessor: """Handle audio loading and WavTokenizer encoding""" def __init__(self, wavtokenizer_checkpoint: str): self.wavtokenizer = self.load_wavtokenizer(wavtokenizer_checkpoint) def load_audio(self, file_path: str) -> Tuple[np.ndarray, int]: """ Load and resample audio to 24kHz mono Returns: (audio_samples, sample_rate) """ audio, sr = librosa.load(file_path, sr=24000, mono=True) return audio, sr def encode(self, audio: np.ndarray) -> np.ndarray: """ Encode audio with WavTokenizer Returns: Token sequence (4096 vocab) """ pass def decode_patch(self, tokens: np.ndarray, patch_indices: List[int]) -> np.ndarray: """ Decode specific patch back to audio Args: tokens: Full token sequence patch_indices: Indices of tokens in this patch Returns: Audio samples for this patch """ patch_tokens = tokens[patch_indices] return self.wavtokenizer.decode(patch_tokens) ``` #### 4. Visualizer ```python class Visualizer: """Generate interactive visualizations""" @staticmethod def create_full_visualization( audio: np.ndarray, tokens: np.ndarray, entropies: np.ndarray, perplexities: np.ndarray, patches: List[List[int]], sample_rate: int = 24000 ) -> go.Figure: """ Create 4-panel synchronized visualization Returns: Plotly figure with subplots """ fig = make_subplots( rows=4, cols=1, subplot_titles=('Waveform', 'Spectrogram', 'Entropy/Perplexity', 'Patch Statistics'), specs=[[{"secondary_y": False}], [{"secondary_y": False}], [{"secondary_y": True}], [{"type": "table"}]], vertical_spacing=0.1 ) # Add waveform time = np.linspace(0, len(audio)/sample_rate, len(audio)) fig.add_trace( go.Scatter(x=time, y=audio, name="Waveform", line=dict(color='blue', width=0.5)), row=1, col=1 ) # Add patch boundaries token_times = np.arange(len(tokens)) / 40 # 40 tokens/sec for patch in patches: boundary_time = token_times[patch[0]] fig.add_vline(x=boundary_time, line_width=1, line_dash="dash", line_color="red", row=1, col=1) # Add spectrogram # ... implementation # Add entropy/perplexity plot # ... implementation # Add statistics table # ... implementation return fig @staticmethod def create_comparison_view(results: List[Dict]) -> go.Figure: """ Create side-by-side comparison of multiple strategies """ pass ``` --- ### File Structure ``` apps/patch_view/ ├── README.md # Quick start guide ├── DESIGN_DOCUMENT.md # This file ├── requirements.txt # Python dependencies ├── app.py # Main Gradio app ├── config.yaml # Default configuration ├── models/ │ ├── entropy_models.py # EntropyModel class │ ├── patching.py # Patching strategies │ └── audio.py # AudioProcessor class ├── visualization/ │ ├── plots.py # Visualizer class │ └── themes.py # Plotly themes ├── utils/ │ ├── metrics.py # Statistics computation │ ├── io.py # File I/O helpers │ └── cache.py # Caching logic ├── checkpoints/ # Pre-trained entropy models │ ├── entropy_1M/ │ ├── entropy_10M/ │ ├── entropy_50M/ │ └── entropy_100M/ ├── examples/ # Example audio files │ └── voice_samples/ └── tests/ ├── test_entropy.py ├── test_patching.py └── test_visualization.py ``` --- ## Data Flow ### Main Processing Pipeline ``` User Input (Audio File) ↓ [Load & Resample to 24kHz] ↓ [WavTokenizer Encoding] → Token Sequence (T tokens) ↓ [Select Entropy Model] → Entropy Model (1M-100M params) ↓ [Compute Entropies] → Entropy Array (T values) ↓ [Optional: Compute Perplexity] → Perplexity Array (T values) ↓ [Select Patching Strategy] ↓ [Apply Patching] → Patches (P patches, variable sizes) ↓ [Generate Visualizations] → Plotly Figure ↓ [Render in Gradio] → Interactive UI ↓ [User Interactions]: - Click patch → Highlight in plots - Play patch → Extract & decode audio - Export → Save data/plots ``` ### Caching Strategy **Level 1: Model Caching** - Load entropy models once on startup - Keep in GPU/CPU memory - LRU cache for switching between models **Level 2: Audio Caching** - Cache uploaded audio files (30min TTL) - Cache WavTokenizer encodings - Map: file_hash → tokens **Level 3: Entropy Caching** - Cache computed entropies per (audio, model) pair - HDF5 storage for large files - Map: (file_hash, model_id) → entropies **Level 4: Visualization Caching** - Cache generated plots (5min TTL) - Update only when parameters change - Incremental updates for threshold changes --- ## UI/UX Design ### Layout Structure ``` ┌─────────────────────────────────────────────────────────────────┐ │ Header │ │ "BLT Patching Visualization Explorer" │ │ [Quick Start] [Documentation] [Examples] [Export] │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ Input Panel │ ├──────────────────────┬──────────────────────────────────────────┤ │ Audio Upload │ Preview │ │ [Choose File] │ ┌────────────────────────────┐ │ │ Or select: │ │ Audio Player │ │ │ [voice_sample_1.mp3] │ │ [▶] ━━━━━━━━━━━ 00:00 │ │ │ │ └────────────────────────────┘ │ │ Duration: 3.2s │ Tokens: 128 │ │ Sample Rate: 24kHz │ Avg Token/sec: 40.0 │ └──────────────────────┴──────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ Configuration Panel │ ├───────────────────────────────┬─────────────────────────────────┤ │ Entropy Model │ Patching Strategy │ │ ┌───────────────────────┐ │ ┌─────────────────────────────┐│ │ │ Size: [100M ▼] │ │ │ Strategy: [Entropy Global ▼]││ │ │ Context: [512 ━━━━━] │ │ │ Threshold: [2.0 ━━━━━━━━] ││ │ │ Architecture: │ │ │ Target Patch Size: [6] ││ │ │ ● Transformer │ │ │ Min Size: [1] ││ │ │ ○ CNN │ │ │ Max Size: [32] ││ │ │ ○ LSTM │ │ │ ││ │ │ │ │ │ Advanced Options: ││ │ │ Metric: │ │ │ ☑ Show Entropy ││ │ │ ☑ Entropy │ │ │ ☑ Show Perplexity ││ │ │ ☑ Perplexity │ │ │ ☐ Log Transform ││ │ └───────────────────────┘ │ │ ☐ Reset on Silence ││ │ │ └─────────────────────────────┘│ │ [Compute Entropies] │ [Apply Patching] │ └───────────────────────────────┴─────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ Visualization Panel │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ Waveform + Patch Boundaries │ │ │ │ [Interactive Plotly Plot] │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ Spectrogram + Patch Boundaries │ │ │ │ [Interactive Plotly Plot] │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ Entropy/Perplexity Plot │ │ │ │ [Interactive Plotly Plot with dual y-axes] │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ Patch Statistics │ │ │ │ Total Patches: 21 Avg Size: 6.1 Min: 2 Max: 14 │ │ │ │ [Bar Chart: Patch Size Distribution] │ │ │ │ [Table: Per-Patch Details] │ │ │ └─────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ Playback Panel │ │ [▶ Play Original] [▶ Play with Markers] [▶ Play Patch: 5] │ │ Current Patch: 5 | Start: 0.12s | End: 0.27s | Duration: 150ms │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ Comparison Panel (Optional) │ │ ☐ Enable Comparison Mode │ │ [When enabled: Side-by-side view of 2-4 strategies] │ └─────────────────────────────────────────────────────────────────┘ ``` ### Color Scheme **Patch Size Colors** (gradient): - Small patches (1-3 tokens): Light blue (#E3F2FD) - Medium patches (4-8 tokens): Blue (#2196F3) - Large patches (9-16 tokens): Dark blue (#0D47A1) - Very large patches (>16 tokens): Purple (#9C27B0) **Entropy/Perplexity Colors**: - Entropy: Blue (#1976D2) - Perplexity: Orange (#FF9800) - Threshold line: Red (#F44336) - Patch boundaries: Gray (#757575) **UI Theme**: - Gradio default theme with custom CSS - Dark mode support - Accessible color contrasts (WCAG AA) --- ## Development Roadmap ### Phase 1: Core Infrastructure (Week 1-2) **Deliverables**: 1. ✅ Project structure setup 2. ✅ EntropyModel class (support 1M, 10M models initially) 3. ✅ AudioProcessor class (WavTokenizer integration) 4. ✅ Basic patching strategies (Strided, Space, Entropy Global) 5. ✅ Simple Gradio UI (upload + basic visualization) **Testing**: - Unit tests for each class - End-to-end test with voice_sample.mp3 --- ### Phase 2: Advanced Patching (Week 3) **Deliverables**: 1. ✅ Entropy Monotonic patching 2. ✅ Additive vs Multiplicative monotonicity 3. ✅ Context reset logic 4. ✅ Logarithmic transforms 5. ✅ BPE-based patching (comparison) **Testing**: - Reproduce Figure 4 from paper - Reproduce Table 6 results - Validate monotonicity constraints --- ### Phase 3: Visualization (Week 4) **Deliverables**: 1. ✅ 4-panel synchronized plots 2. ✅ Interactive features (click, hover, zoom) 3. ✅ Color-coded patches 4. ✅ Statistics dashboard 5. ✅ Export functionality **Testing**: - Visual regression tests - Performance testing (large audio files) - Cross-browser compatibility --- ### Phase 4: Audio Playback (Week 5) **Deliverables**: 1. ✅ Individual patch playback 2. ✅ Patch markers in audio 3. ✅ Synchronized highlighting 4. ✅ Waveform cursor 5. ✅ Export patch audio files **Testing**: - Audio quality verification - Timing accuracy - WavTokenizer decode correctness --- ### Phase 5: Entropy Model Scaling (Week 6) **Deliverables**: 1. ✅ 50M and 100M parameter models 2. ✅ Multiple context windows 3. ✅ CNN and LSTM architectures 4. ✅ Model caching and optimization 5. ✅ Perplexity computation **Testing**: - Reproduce Figure 8 ablations - Performance benchmarking - Memory profiling --- ### Phase 6: Comparison & Batch Mode (Week 7) **Deliverables**: 1. ✅ Side-by-side comparison UI 2. ✅ Batch processing pipeline 3. ✅ Aggregate statistics 4. ✅ Export reports (CSV, JSON) 5. ✅ Configuration presets **Testing**: - Multi-file processing - Memory management for batch mode - Report validation --- ### Phase 7: Polish & Documentation (Week 8) **Deliverables**: 1. ✅ Complete user documentation 2. ✅ API documentation 3. ✅ Tutorial notebooks 4. ✅ Example gallery 5. ✅ Performance optimization 6. ✅ Code cleanup and refactoring **Testing**: - User acceptance testing - Documentation review - Final integration tests --- ### Phase 8: Advanced Features (Future) **Potential Additions**: 1. Real-time patching (microphone input) 2. Custom entropy model training 3. Multi-language support (non-English audio) 4. Cloud deployment (Gradio Spaces) 5. API endpoints (REST/GraphQL) 6. Integration with BLT training pipeline 7. Perplexity-based patching variants 8. Learned boundary predictors (research) --- ## Implementation Notes ### Performance Considerations **Optimization Strategies**: 1. **GPU Acceleration**: Move entropy model inference to GPU 2. **Batch Processing**: Process multiple audio files in parallel 3. **Lazy Loading**: Load entropy models only when needed 4. **Incremental Updates**: Only recompute changed visualizations 5. **Web Workers**: Offload heavy computation from main thread 6. **Quantization**: Use INT8 models for faster inference **Expected Performance** (on H100 80GB): - Audio encoding (WavTokenizer): ~1s for 10s audio - Entropy computation (100M model): ~2s for 10s audio (400 tokens) - Patching: <0.1s - Visualization generation: ~0.5s - Total latency: ~4s for 10s audio **Scaling to Large Files**: - For >1min audio: Chunk processing - Streaming visualization updates - HDF5 storage for intermediate results --- ### Error Handling **Common Issues**: 1. **Audio file corrupt**: Validate with librosa before processing 2. **OOM on large files**: Automatic chunking, warn user 3. **Model not found**: Graceful fallback to smaller model 4. **Invalid threshold**: Auto-clamp to valid range 5. **Silence in audio**: Detect and handle gracefully **User Feedback**: - Progress bars for long operations - Clear error messages - Suggested fixes - Logging for debugging --- ### Testing Strategy **Unit Tests**: - `test_entropy.py`: Entropy computation correctness - `test_patching.py`: Patching strategy outputs - `test_audio.py`: WavTokenizer encode/decode - `test_visualization.py`: Plot generation **Integration Tests**: - End-to-end pipeline with known audio - Reproduce paper figures - Cross-strategy comparisons **Performance Tests**: - Memory profiling - Latency benchmarks - Stress testing (100+ files) **User Tests**: - Usability studies - Documentation clarity - Example gallery sufficiency --- ## Success Criteria ### Functional Requirements ✅ **Must Have**: 1. Support all 4 main patching strategies (Strided, Space, Entropy Global, Entropy Monotonic) 2. Multiple entropy model sizes (1M, 10M, 50M, 100M) 3. Interactive 4-panel visualization 4. Individual patch playback 5. Export functionality (plots, data, audio) ✅ **Should Have**: 1. Comparison mode (2+ strategies) 2. Batch processing 3. Logarithmic transforms 4. Additive/multiplicative monotonicity 5. Real-time threshold adjustment 🔄 **Nice to Have**: 1. Custom entropy model training 2. Real-time audio input 3. Cloud deployment 4. REST API 5. Mobile-friendly UI --- ### Performance Requirements **Latency**: - <5s total latency for 10s audio (with 100M entropy model) - <1s UI response time for parameter changes - <2s visualization updates **Throughput**: - Process 100+ audio files in batch mode (overnight) - Handle audio files up to 10min duration **Resource Usage**: - <10GB GPU memory (with 100M model) - <50GB disk space (including models) - <5GB RAM (excluding models) --- ### Quality Requirements **Correctness**: - Reproduce key findings from BLT paper (Figures 4, 6, 8; Tables 6, 7, 8) - Entropy values match reference implementation - Patch boundaries consistent across runs **Usability**: - Intuitive UI (no training required) - Clear documentation - Helpful error messages - Responsive design **Maintainability**: - Modular code structure - Comprehensive tests (>80% coverage) - Clear API documentation - Follows Python best practices (PEP 8) --- ## Risks & Mitigations ### Technical Risks **Risk 1**: Entropy model inference too slow for real-time interaction - **Mitigation**: Precompute entropies, cache aggressively, use smaller models **Risk 2**: WavTokenizer integration issues - **Mitigation**: Use existing `encode_librispeech_wavtokenizer.py` as reference **Risk 3**: Visualization performance with large files - **Mitigation**: Downsampling for display, lazy rendering, WebGL **Risk 4**: Audio playback sync issues - **Mitigation**: Precise timestamp calculation, buffer management ### User Experience Risks **Risk 1**: Too many parameters → overwhelming - **Mitigation**: Presets, guided tutorials, progressive disclosure **Risk 2**: Unclear interpretation of results - **Mitigation**: Tooltips, annotations, example gallery **Risk 3**: Slow on user hardware - **Mitigation**: Cloud deployment option, CPU fallback --- ## Future Enhancements ### Research Directions 1. **Perplexity-Optimized Patching**: - Current work uses entropy, but perplexity may be more interpretable - Experiment with perplexity thresholds - Compare entropy vs perplexity patching quality 2. **Adaptive Thresholds**: - Learn threshold per domain (music vs speech vs noise) - Context-dependent thresholds 3. **Multi-Modal Patching**: - Combine entropy + acoustic features (energy, pitch) - Better handling of silence, music, noise 4. **Learned Patching**: - Train boundary predictor (Nawrot et al. 2023 approach) - Compare with entropy-based patching ### Product Features 1. **Collaboration**: - Share configurations - Annotate patches - Export to notebooks 2. **Integration**: - Weights & Biases logging - TensorBoard visualization - Jupyter notebook widget 3. **Deployment**: - Docker container - Kubernetes helm chart - AWS/GCP marketplace --- ## Appendices ### Appendix A: Mathematical Formulations **Entropy**: ``` H(x_i) = -Σ_{v∈V} p(x_i=v|x_{ θ_g 0 otherwise ``` **Additive Monotonic Patching**: ``` boundary(i) = 1 if H(x_i) - H(x_{i-1}) > θ_r 0 otherwise ``` **Multiplicative Monotonic Patching**: ``` boundary(i) = 1 if H(x_i) / H(x_{i-1}) > θ_m 0 otherwise ``` **Logarithmic Transform**: ``` H_log(x_i) = log_b(H(x_i)) PPL_log(x_i) = log_b(PPL(x_i)) = H(x_i) / log₂(b) ``` --- ### Appendix B: Configuration Schema ```yaml # config.yaml app: title: "BLT Patching Visualization Explorer" description: "Interactive exploration of byte-latent transformer patching strategies" theme: "default" port: 7860 audio: sample_rate: 24000 max_duration: 600 # 10 minutes supported_formats: ["mp3", "wav", "flac", "ogg"] wavtokenizer: checkpoint: "checkpoints/wavtokenizer_large_600_24k.ckpt" vocab_size: 4096 tokens_per_second: 40 entropy_models: available: - name: "1M" checkpoint: "checkpoints/entropy_1M" params: 1000000 default_context: 64 - name: "10M" checkpoint: "checkpoints/entropy_10M" params: 10000000 default_context: 128 - name: "50M" checkpoint: "checkpoints/entropy_50M" params: 50000000 default_context: 512 - name: "100M" checkpoint: "checkpoints/entropy_100M" params: 100000000 default_context: 512 default_model: "100M" patching: strategies: strided: default_k: 8 min_k: 1 max_k: 16 space: space_tokens: [32, 9, 10, 13] # space, tab, newline, carriage return entropy_global: default_threshold: 2.0 min_threshold: 0.0 max_threshold: 10.0 auto_target_patch_size: 6 entropy_monotonic: default_threshold: 0.5 min_threshold: 0.0 max_threshold: 5.0 monotonicity_types: ["additive", "multiplicative"] default_monotonicity: "additive" reset_options: ["never", "silence", "every_n_tokens"] default_reset: "never" visualization: plots: waveform: height: 200 color: "blue" spectrogram: height: 300 n_mels: 128 fmin: 0 fmax: 8000 hop_length: 512 entropy: height: 250 entropy_color: "blue" perplexity_color: "orange" threshold_color: "red" statistics: height: 200 colors: patch_sizes: small: "#E3F2FD" # 1-3 tokens medium: "#2196F3" # 4-8 tokens large: "#0D47A1" # 9-16 tokens very_large: "#9C27B0" # >16 tokens caching: audio_ttl: 1800 # 30 minutes entropy_ttl: 3600 # 1 hour visualization_ttl: 300 # 5 minutes max_cache_size_gb: 10 performance: batch_size: 32 num_workers: 4 use_gpu: true max_gpu_memory_gb: 10 export: formats: plots: ["png", "pdf", "svg", "html"] data: ["json", "csv", "parquet"] audio: ["wav"] ``` --- ### Appendix C: API Specification **Compute Entropy**: ```python POST /api/compute_entropy Request: { "audio_file": "base64_encoded_audio", "model_size": "100M", "context_window": 512, "return_perplexity": true } Response: { "tokens": [234, 1023, ...], # WavTokenizer tokens "entropies": [2.3, 1.8, ...], "perplexities": [4.9, 3.5, ...], "duration_ms": 1234 } ``` **Apply Patching**: ```python POST /api/apply_patching Request: { "tokens": [234, 1023, ...], "entropies": [2.3, 1.8, ...], "strategy": "entropy_global", "parameters": { "threshold": 2.0 } } Response: { "patches": [[0,1,2], [3,4,5,6], ...], "statistics": { "num_patches": 21, "avg_patch_size": 6.1, "min_patch_size": 2, "max_patch_size": 14 } } ``` **Generate Visualization**: ```python POST /api/visualize Request: { "audio_file": "base64_encoded_audio", "tokens": [...], "entropies": [...], "patches": [[...], ...], "options": { "show_entropy": true, "show_perplexity": true, "show_spectrogram": true } } Response: { "plot_html": "
...
", # Plotly HTML "plot_json": {...} # Plotly JSON } ``` --- ### Appendix D: Example Usage **Python API**: ```python from patch_view import EntropyModel, EntropyGlobalPatching, AudioProcessor, Visualizer # Load audio processor = AudioProcessor("checkpoints/wavtokenizer.ckpt") audio, sr = processor.load_audio("data/voice_samples/voice_sample.mp3") tokens = processor.encode(audio) # Compute entropies entropy_model = EntropyModel(model_size="100M", context_window=512) entropies = entropy_model.compute_entropy(tokens) perplexities = 2 ** entropies # Apply patching patcher = EntropyGlobalPatching(threshold=2.0) patches = patcher.patch(tokens, entropies) # Visualize fig = Visualizer.create_full_visualization( audio, tokens, entropies, perplexities, patches, sr ) fig.show() # Play patch patch_audio = processor.decode_patch(tokens, patches[5]) import soundfile as sf sf.write("patch_5.wav", patch_audio, sr) ``` **Gradio UI**: ```python import gradio as gr from patch_view import create_app app = create_app() app.launch(server_name="0.0.0.0", server_port=7860) ``` **Command Line**: ```bash # Process single file python -m patch_view process \ --audio data/voice_samples/voice_sample.mp3 \ --model 100M \ --strategy entropy_global \ --threshold 2.0 \ --output results/ # Batch processing python -m patch_view batch \ --input_dir data/voice_samples/ \ --model 50M \ --strategy entropy_monotonic \ --output results/batch/ # Launch UI python -m patch_view ui --port 7860 ``` --- ## Conclusion This design document provides a comprehensive blueprint for the BLT Patching Visualization App. The app will enable: 1. **Deep understanding** of BLT patching mechanisms through interactive exploration 2. **Experimentation** with multiple patching strategies and parameters 3. **Visual insights** into how entropy/perplexity relates to patch boundaries 4. **Audio analysis** by listening to individual patches 5. **Research support** for developing improved patching strategies The modular architecture ensures extensibility for future research directions, including perplexity-based patching, adaptive thresholds, and multi-modal approaches. **Next Steps**: 1. Review and approve this design 2. Set up development environment 3. Begin Phase 1 implementation 4. Iterate based on user feedback --- **Document Version**: 1.0 **Last Updated**: 2025-10-22 **Approved By**: [Pending Review]