Skip to content

Add RoPE visualization toolkit for embedding space analysis - #935

Merged
makr-code merged 4 commits into
developfrom
copilot/add-visualization-tools-for-rope
Jan 28, 2026
Merged

makr-code merged 4 commits into
developfrom
copilot/add-visualization-tools-for-rope

Conversation

Copilot AI commented Jan 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

Visualization toolkit for analyzing Rotary Position Embeddings. Implements 2D/3D projections, rotation trails, similarity heatmaps, and theta distribution plots via Python API and CLI.

from rope_visualizer import RopeVisualizer

viz = RopeVisualizer({'hidden_dim': 128, 'base_theta': 10000.0})
viz.plot_embeddings(embeddings, positions, method='pca')
viz.plot_rotation_trail(embedding, positions)
viz.plot_similarity_matrix(embedding, positions, metric='cosine')
rope-visualize visualize --embeddings data.npy --method umap --output viz.png
rope-visualize heatmap --embeddings data.npy --positions 0,50,100,200 --output heatmap.png
rope-visualize trail --embeddings data.npy --positions 0-500 --output trail.png

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📝 Documentation update
  • ♻️ Code refactoring (no functional changes)
  • ⚡ Performance improvement
  • ✅ Test addition or update
  • 🔧 Configuration change
  • 🎨 UI/UX change

Related Issues

Feature request for RoPE visualization tools.

Changes Made

Core Module (tools/rope_visualizer/):

  • utils.py - Similarity computation (cosine/euclidean/dot), dimensionality reduction (PCA/t-SNE/UMAP), pure-Python RoPE rotation
  • visualizer.py - RopeVisualizer class with 7 visualization methods (2D/3D projections, rotation trails, similarity heatmaps, theta distribution)
  • cli.py - Command-line tool with 4 subcommands (visualize, heatmap, trail, theta)
  • Support for NPY/NPZ/JSON file formats, JSON config files

Tests (tests/rope_visualizer/):

  • 16 unit tests covering similarity computation, projections, rotation operations, mathematical properties, error handling

Examples (examples/rope_visualization/):

  • basic_visualization_example.py - Introduction to all visualization types
  • cli_usage_demo.py - CLI command demonstrations
  • advanced_analysis_example.py - Comparative analysis workflows (theta values, position separation, dimension impact)
  • rope_visualization_tutorial.ipynb - Interactive Jupyter notebook with widgets
  • rope_config.json - Configuration example

Documentation:

  • Tool README with API reference (377 lines)
  • Examples README with quick start (308 lines)
  • Implementation summary (596 lines)
  • Jupyter tutorial with step-by-step guide (473 lines)

Testing

Test Environment

  • OS: Ubuntu (GitHub Actions runner)
  • Compiler: Python 3.x
  • Build Type: N/A (Pure Python)

Test Results

  • All existing tests pass
  • New tests added for changes
  • Manual testing performed

Test Commands

# Unit tests
python3 tests/rope_visualizer/test_utils.py -v  # 16/16 passing

# Examples
python3 examples/rope_visualization/basic_visualization_example.py
python3 examples/rope_visualization/cli_usage_demo.py
python3 examples/rope_visualization/advanced_analysis_example.py

# CLI
python3 tools/rope_visualizer/cli.py visualize --embeddings /tmp/test.npy --method pca --output /tmp/out.png

Checklist

  • My code follows the coding standards
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have updated the documentation accordingly
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published

Code Quality

  • Code builds without errors
  • Code builds without warnings
  • Static analysis (cppcheck) passes
  • No memory leaks detected
  • Code follows C++17 standards

Documentation

  • README.md updated (if applicable)
  • CHANGELOG.md updated
  • API documentation updated (if applicable)
  • Code comments added/updated

Branch Strategy Compliance

  • PR targets the correct branch (develop for features, main for releases/hotfixes)
  • Branch naming follows convention (e.g., feature/, bugfix/, hotfix/, release/)
  • No direct commits to main or develop

Performance Impact

  • No significant performance impact
  • Performance improvement (describe below)
  • Performance regression (justify below)

Performance Notes:

  • PCA: ~0.1s for 100 embeddings (128-dim)
  • t-SNE: ~2-5s for 100 embeddings
  • UMAP: ~1-2s for 100 embeddings
  • Recommended limit: 1000 embeddings for interactive use

Breaking Changes

None. Purely additive feature.

Security Considerations

  • No security implications
  • Security review required
  • Dependencies updated to secure versions

Security Validation:

  • CodeQL scan: 0 alerts
  • Code review: 0 issues
  • Safe file handling (no shell injection, path traversal prevention)

Additional Notes

Dependencies (required):

  • numpy >= 1.20.0
  • matplotlib >= 3.3.0
  • seaborn >= 0.11.0
  • scikit-learn >= 0.24.0

Optional:

  • umap-learn >= 0.5.0 (UMAP projections)
  • jupyter, ipywidgets (notebook integration)

Use cases:

  • Research: Compare rotation patterns, validate implementations
  • Debugging: Diagnose position separation, find optimal theta
  • Education: Interactive tutorials, visual explanations
  • Production: Batch visualization, automated reports

Not implemented (future enhancements):

  • Web UI (React + D3.js/Plotly)
  • Flask REST API
  • GIF/MP4 animation generation
  • C++ Python bindings (pybind11)

Screenshots/Logs

Example outputs generated by the toolkit:

  • 2D PCA projection with rotation
  • Rotation trail showing embedding movement
  • Similarity heatmap across positions
  • Theta distribution (logarithmic scale)
  • 3D embedding space visualization

All visualizations successfully generated and validated in /tmp/ during testing.


For Maintainers:

Review Checklist

  • Code quality acceptable
  • Tests adequate
  • Documentation complete
  • No security concerns
  • Ready to merge

Merge Strategy

  • Squash and merge (✅ Recommended for feature/bugfix PRs - cleaner history)
  • Merge commit (Only for release/hotfix branches)
  • Rebase and merge
Original prompt

This section details on the original issue you should resolve

<issue_title>[RoPE] Visualization Tools for Embedding Space Analysis</issue_title>
<issue_description>## Feature Description

Develop visualization tools to analyze and understand how Rotary Position Embeddings (RoPE) affect embedding spaces. Provide interactive visualizations for debugging, optimization, and educational purposes.

Problem Statement

RoPE rotation is a complex mathematical operation that's difficult to understand intuitively:

  • Users can't see how rotation affects embedding distributions
  • Debugging positional encoding issues requires manual analysis
  • No way to compare different rotation configurations visually
  • Educational barriers to understanding RoPE mechanics

Proposed Solution

Core Components

1. Embedding Space Visualizer (Web UI)

Features:

  • 2D/3D projection of rotated embeddings (t-SNE, UMAP, PCA)
  • Animation showing rotation effects over positions
  • Side-by-side comparison: before vs. after rotation
  • Interactive position slider to see rotation at different positions
  • Heatmap of similarity changes due to rotation

Technology Stack:

  • Frontend: React + D3.js or Plotly.js
  • Backend: Python Flask API + scikit-learn
  • WebGL for 3D rendering

2. Rotation Analysis Dashboard

Metrics Displayed:

  • Theta value distribution across rotation pairs
  • Cosine similarity heatmap (position × position)
  • Distance preservation analysis
  • Orthogonality metrics for different positions
  • Relational rotation comparison

Interactive Controls:

  • Adjust hidden_dim, num_rotation_pairs, base_theta
  • Real-time visualization updates
  • Export plots as PNG/SVG
  • Compare multiple configurations

3. Command-Line Tools

rope-visualize CLI tool:

# Visualize embeddings with rotation
rope-visualize \
  --embeddings embeddings.npy \
  --config rope_config.json \
  --output rotation_effect.html \
  --method umap \
  --positions 0,50,100,200

# Generate similarity heatmap
rope-visualize heatmap \
  --embeddings embeddings.npy \
  --config rope_config.json \
  --output similarity_heatmap.png

# Animation of rotation effects
rope-visualize animate \
  --embeddings embeddings.npy \
  --config rope_config.json \
  --positions 0-500 \
  --output rotation_animation.gif \
  --fps 30

4. Jupyter Notebook Integration

from themisdb.rope import RopeVisualizer

# Initialize visualizer
viz = RopeVisualizer(config)

# Plot embedding space with rotation
viz.plot_embeddings(
    embeddings=embeddings,
    positions=positions,
    method='umap',
    color_by='position'
)

# Interactive widget
viz.interactive_rotation_explorer(
    embeddings=embeddings,
    slider_range=(0, 1000)
)

# Similarity analysis
viz.plot_similarity_matrix(
    embedding=base_embedding,
    positions=range(0, 100, 10)
)

Technical Implementation

Web Visualizer Architecture

+-------------------+
|   React Frontend  |
|   (D3.js/Plotly)  |
+-------------------+
         |
         | HTTP/WebSocket
         v
+-------------------+
|   Flask API       |
|   - UMAP/t-SNE    |
|   - RoPE compute  |
+-------------------+
         |
         | C++ binding
         v
+-------------------+
| RoPE C++ Library  |
| (ThemisDB core)   |
+-------------------+

Key Visualization Components

2D Projection with Rotation Trail

def plot_rotation_trail(embedding, positions, method='umap'):
    """
    Show how a single embedding moves in 2D space as position changes.
    
    Visualizes:
    - Starting point (position 0)
    - Trail of rotated positions
    - End point
    - Color gradient by position
    """
    rotated_embeddings = [
        rope.rotate(embedding, pos) for pos in positions
    ]
    
    # Dimensionality reduction
    embeddings_2d = UMAP().fit_transform(rotated_embeddings)
    
    # Plot with trail
    plt.plot(embeddings_2d[:, 0], embeddings_2d[:, 1], 
             marker='o', alpha=0.6, c=positions, cmap='viridis')
    plt.colorbar(label='Position')
    plt.title('Rotation Trail in Embedding Space')

Similarity Heatmap

def plot_similarity_heatmap(base_embedding, positions):
    """
    Heatmap showing cosine similarity between rotated versions
    at different positions.
    """
    n = len(positions)
    similarity_matrix = np.zeros((n, n))
    
    for i, pos_i in enumerate(positions):
        rot_i = rope.rotate(base_embedding, pos_i)
        for j, pos_j in enumerate(positions):
            rot_j = rope.rotate(base_embedding, pos_j)
            similarity_matrix[i, j] = cosine_similarity(rot_i, rot_j)
    
    sns.heatmap(similarity_matrix, 
                xticklabels=positions, 
                yticklabels=positions,
                cmap='coolwarm', center=0)
    plt.title('Position-wise Similarity Heatmap')

3D Interactive Visualization

// Plotly.js 3D scatter with rotation animation
function animate3DRotation(embeddings, p...

</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes makr-code/ThemisDB#920

<!-- START COPILOT CODING AGENT TIPS -->
---

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more [Copilot coding agent tips](https://gh.io/copilot-coding-agent-tips) in the docs.

Copilot AI changed the title [WIP] Add visualization tools for embedding space analysis Add RoPE visualization toolkit for embedding space analysis Jan 27, 2026
Copilot AI requested a review from makr-code January 27, 2026 17:57
@makr-code
makr-code marked this pull request as ready for review January 28, 2026 09:56
@makr-code
makr-code merged commit 393c641 into develop Jan 28, 2026
@makr-code makr-code modified the milestones: v1.4.1, v1.4.0 Mar 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RoPE] Visualization Tools for Embedding Space Analysis

2 participants