Spaces:
Sleeping
Download DESIGN_DOCUMENT.md from benhong/blt-patch-view: direct link, hf CLI and curl.
- Browser
- Download file 54.7 kB
-
https://huggingface.co/spaces/benhong/blt-patch-view/resolve/main/DESIGN_DOCUMENT.md
- Command line
-
hf download hf://spaces/benhong/blt-patch-view/DESIGN_DOCUMENT.md
-
curl -L -o DESIGN_DOCUMENT.md https://huggingface.co/spaces/benhong/blt-patch-view/resolve/main/DESIGN_DOCUMENT.md
A newer version of the Gradio SDK is available: 6.32.0
BLT Patching Visualization App - Design Document
Date: 2025-10-22 Author: Claude Status: Design Phase
Table of Contents
- Executive Summary
- BLT Patching Analysis
- Patching Strategies
- Key Findings from Ablations
- Application Architecture
- Feature Specifications
- Technical Implementation Plan
- Data Flow
- UI/UX Design
- 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:
- Have no fixed vocabulary
- Are determined dynamically based on context
- Allocate more compute where complexity is higher
- 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:
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:
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:
H(x_i) = -Ξ£ p_e(x_i = v | x_{<i}) * log(p_e(x_i = v | x_{<i}))
vβV
Where:
p_e: Entropy model distributionV: Byte vocabulary (256 bytes)x_i: Byte at position i
Entropy Model Variations (from Figure 8 ablations):
| Model Size | Context Window | Performance (BPB) | Notes |
|---|---|---|---|
| 1M | 64 | ~1.05 | Minimal |
| 1M | 512 | ~1.00 | Better context helps |
| 10M | 128 | ~0.98 | Size matters more than context |
| 10M | 512 | ~0.95 | Good balance |
| 50M | 512 | ~0.92 | Strong performance |
| 100M | 512 | ~0.90 | Diminishing returns beyond this |
Key Finding: 50M-100M params with 512-byte context is optimal
3.2 Global Threshold Constraint
Rule: Start new patch when H(x_i) > ΞΈ_g
Implementation:
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:
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:
H(x_i) = -Ξ£ p(v) log p(v)
Perplexity:
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_{<i}) = f_p(x)_{<i}
BPE violates this - "running" might tokenize as ["run", "ning"] but "runner" as ["runner"]
Use Case: Primarily for comparison/baseline in paper
5. Learned Boundary Patching (Related Work Β§8)
Description: Train classifier to predict patch boundaries (Nawrot et al. 2023)
Not used in BLT: Preprocessing approach preferred
- BLT computes entropy during dataloading
- No learned boundary predictor needed
- Simpler and more flexible
Key Findings from Ablations
Patching Strategy Comparison (Table 6)
8B models trained on Llama 2 data (compute optimal):
| Strategy | ARC-E | ARC-C | HellaSwag | PIQA | Avg |
|---|---|---|---|---|---|
| Llama 3 BPE | 67.4 | 40.5 | 71.3 | 77.0 | 64.1 |
| Space Patching | 67.2 | 37.6 | 70.8 | 76.5 | 63.0 |
| Entropy Patching | 68.9 | 38.3 | 72.7 | 77.6 | 64.4 |
Conclusion: Entropy patching β₯ BPE > 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:
Model Size: Dropdown
- 1M params (fast, less accurate)
- 10M params (balanced)
- 50M params (good quality)
- 100M params (best quality, slower)
Context Window: Slider
- 64, 128, 256, 512 bytes
- Default: 512
Architecture: Dropdown
- Transformer (default)
- CNN byte-level
- LSTM
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:
- Play Original: Full audio file
- Play with Markers: Audible click at patch boundaries
- Play Single Patch: Select patch ID, play isolated
- Play Patch Sequence: Select range, play concatenated
Patch Audio Extraction:
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:
- Visualizations: PNG, PDF, SVG
- Patch Data: JSON, CSV
- Patch boundaries
- Entropies/perplexities
- Statistics
- Configuration: YAML/JSON
- Reproduce exact settings
- 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
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
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
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
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
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:
- β Project structure setup
- β EntropyModel class (support 1M, 10M models initially)
- β AudioProcessor class (WavTokenizer integration)
- β Basic patching strategies (Strided, Space, Entropy Global)
- β 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:
- β Entropy Monotonic patching
- β Additive vs Multiplicative monotonicity
- β Context reset logic
- β Logarithmic transforms
- β BPE-based patching (comparison)
Testing:
- Reproduce Figure 4 from paper
- Reproduce Table 6 results
- Validate monotonicity constraints
Phase 3: Visualization (Week 4)
Deliverables:
- β 4-panel synchronized plots
- β Interactive features (click, hover, zoom)
- β Color-coded patches
- β Statistics dashboard
- β Export functionality
Testing:
- Visual regression tests
- Performance testing (large audio files)
- Cross-browser compatibility
Phase 4: Audio Playback (Week 5)
Deliverables:
- β Individual patch playback
- β Patch markers in audio
- β Synchronized highlighting
- β Waveform cursor
- β Export patch audio files
Testing:
- Audio quality verification
- Timing accuracy
- WavTokenizer decode correctness
Phase 5: Entropy Model Scaling (Week 6)
Deliverables:
- β 50M and 100M parameter models
- β Multiple context windows
- β CNN and LSTM architectures
- β Model caching and optimization
- β Perplexity computation
Testing:
- Reproduce Figure 8 ablations
- Performance benchmarking
- Memory profiling
Phase 6: Comparison & Batch Mode (Week 7)
Deliverables:
- β Side-by-side comparison UI
- β Batch processing pipeline
- β Aggregate statistics
- β Export reports (CSV, JSON)
- β Configuration presets
Testing:
- Multi-file processing
- Memory management for batch mode
- Report validation
Phase 7: Polish & Documentation (Week 8)
Deliverables:
- β Complete user documentation
- β API documentation
- β Tutorial notebooks
- β Example gallery
- β Performance optimization
- β Code cleanup and refactoring
Testing:
- User acceptance testing
- Documentation review
- Final integration tests
Phase 8: Advanced Features (Future)
Potential Additions:
- Real-time patching (microphone input)
- Custom entropy model training
- Multi-language support (non-English audio)
- Cloud deployment (Gradio Spaces)
- API endpoints (REST/GraphQL)
- Integration with BLT training pipeline
- Perplexity-based patching variants
- Learned boundary predictors (research)
Implementation Notes
Performance Considerations
Optimization Strategies:
- GPU Acceleration: Move entropy model inference to GPU
- Batch Processing: Process multiple audio files in parallel
- Lazy Loading: Load entropy models only when needed
- Incremental Updates: Only recompute changed visualizations
- Web Workers: Offload heavy computation from main thread
- 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:
- Audio file corrupt: Validate with librosa before processing
- OOM on large files: Automatic chunking, warn user
- Model not found: Graceful fallback to smaller model
- Invalid threshold: Auto-clamp to valid range
- 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 correctnesstest_patching.py: Patching strategy outputstest_audio.py: WavTokenizer encode/decodetest_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:
- Support all 4 main patching strategies (Strided, Space, Entropy Global, Entropy Monotonic)
- Multiple entropy model sizes (1M, 10M, 50M, 100M)
- Interactive 4-panel visualization
- Individual patch playback
- Export functionality (plots, data, audio)
β Should Have:
- Comparison mode (2+ strategies)
- Batch processing
- Logarithmic transforms
- Additive/multiplicative monotonicity
- Real-time threshold adjustment
π Nice to Have:
- Custom entropy model training
- Real-time audio input
- Cloud deployment
- REST API
- 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.pyas 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
Perplexity-Optimized Patching:
- Current work uses entropy, but perplexity may be more interpretable
- Experiment with perplexity thresholds
- Compare entropy vs perplexity patching quality
Adaptive Thresholds:
- Learn threshold per domain (music vs speech vs noise)
- Context-dependent thresholds
Multi-Modal Patching:
- Combine entropy + acoustic features (energy, pitch)
- Better handling of silence, music, noise
Learned Patching:
- Train boundary predictor (Nawrot et al. 2023 approach)
- Compare with entropy-based patching
Product Features
Collaboration:
- Share configurations
- Annotate patches
- Export to notebooks
Integration:
- Weights & Biases logging
- TensorBoard visualization
- Jupyter notebook widget
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_{<i}) logβ p(x_i=v|x_{<i})
Perplexity:
PPL(x_i) = 2^{H(x_i)}
Global Threshold Patching:
boundary(i) = 1 if H(x_i) > ΞΈ_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
# 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:
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:
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:
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": "<div>...</div>", # Plotly HTML
"plot_json": {...} # Plotly JSON
}
Appendix D: Example Usage
Python API:
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:
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:
# 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:
- Deep understanding of BLT patching mechanisms through interactive exploration
- Experimentation with multiple patching strategies and parameters
- Visual insights into how entropy/perplexity relates to patch boundaries
- Audio analysis by listening to individual patches
- 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:
- Review and approve this design
- Set up development environment
- Begin Phase 1 implementation
- Iterate based on user feedback
Document Version: 1.0 Last Updated: 2025-10-22 Approved By: [Pending Review]