Skip to main content

Independent building blocks for Information Bottleneck research: VIB compression, Riemannian optimization, and architectural improvements

Project description

ib-components

Modular building blocks for Information Bottleneck research in PyTorch

CI Python 3.9+ PyTorch 2.0+ License: MIT Coverage


Overview

ib-components is a modular library of Information Bottleneck building blocks for PyTorch. Unlike existing implementations (VIB-pytorch, information-bottleneck) that bundle end-to-end training scripts tied to specific experiments, ib-components provides the components themselves as a library — compose them into your own architectures without forking.

The Information Bottleneck Principle

The IB principle (Tishby et al., 1999) formalizes the trade-off between compression and predictive power:

$$\min; I(X; Z) - \beta \cdot I(Z; Y)$$

The Variational Information Bottleneck (Alemi et al., 2017) makes this tractable for deep networks:

$$\mathcal{L}{IB} = \underbrace{\mathbb{E}{q(z|x)}[\log p(y|z)]}{\text{reconstruction}} - \beta \cdot \underbrace{D{KL}(q(z|x) | p(z))}_{\text{compression}}$$


Installation

# Core library
pip install ib-components

# With Neural ODE support (AttractorDynamics)
pip install "ib-components[ode]"

# With HuggingFace Transformers integration
pip install "ib-components[transformers]"

# All optional dependencies
pip install "ib-components[all]"

# Development install
git clone https://github.com/Fengrru/ib-components.git
cd ib-components
pip install -e ".[dev]"

Requirements: Python ≥ 3.9, PyTorch ≥ 2.0


Quick Start

VIB Compression (4 lines)

import torch
from ib_components.compressor import LayerwiseVIBCompressor

compressor = LayerwiseVIBCompressor(hidden_size=768, latent_size=192, beta=0.001)

x = torch.randn(32, 128, 768)           # (batch, seq_len, hidden)
x_recon, info = compressor(x)            # reconstruct + latent info
losses = compressor.compute_ib_loss(info)  # IB loss

print(f"Total: {losses['loss']:.4f} | Recon: {losses['recon_loss']:.4f} | KL: {losses['kl_loss']:.4f}")

Hierarchical Multi-Layer Compression

from ib_components.compressor import HierarchicalVIBCompressor

compressor = HierarchicalVIBCompressor(num_layers=12, hidden_size=768, latent_ratio=0.25)

hidden_states = [torch.randn(32, 128, 768) for _ in range(12)]
reconstructed, infos = compressor(hidden_states)
total_loss = compressor.compute_total_loss(infos)

Riemannian Optimization on Sphere Manifold

from ib_components.compressor import project_to_tangent, sphere_exponential_map

point = torch.randn(1, 64)
point = point / torch.norm(point)  # normalize to unit sphere
grad = torch.randn(1, 64)

# Riemannian step — stays exactly on the sphere
riem_grad = project_to_tangent(grad, point)
riem_next = sphere_exponential_map(point, -0.1 * riem_grad)

# Euclidean step — drifts off the manifold
euc_next = point - 0.1 * grad

print(f"Riemannian norm: {torch.norm(riem_next):.6f}")  # 1.000000
print(f"Euclidean norm:  {torch.norm(euc_next):.6f}")    # ~1.07 (drifted)

Adaptive Beta Scheduling

from ib_components.improvements import AdaptiveBetaScheduler

scheduler = AdaptiveBetaScheduler(beta_min=0.0001, beta_max=0.01, schedule="sigmoid")

# High surprise → low beta (preserve information)
# Low surprise → high beta (aggressive compression)
for surprise in [0.0, 0.25, 0.5, 0.75, 1.0]:
    print(f"Surprise={surprise:.2f} → β={scheduler(surprise):.6f}")

Features

Components

Module Component Description
compressor LayerwiseVIBCompressor Single-layer VAE-style compressor with reparameterization
compressor HierarchicalVIBCompressor Multi-layer cascaded compressors with per-layer beta
compressor RiemannianOptimizer Sphere manifold optimization (tangent + exp map)
compressor SphereManifold Geodesic distance, parallel transport, normalization
improvements AdaptiveBetaScheduler Surprise-driven β adjustment (sigmoid/linear/exponential)
improvements KLAnnealingScheduler Linear/cosine/exponential KL warmup
improvements InformationGainDrive MINE-based mutual information estimation
improvements CrossLayerConsistency Frobenius norm alignment between adjacent layers
improvements AttractorDynamics Neural ODE with learnable attractor centers

Configuration

Type-safe dataclass configs with validation and YAML support:

from ib_components.config import VIBConfig, ExperimentConfig

# Direct instantiation
config = VIBConfig(hidden_size=768, latent_size=192, beta=0.001)

# From YAML file
experiment = ExperimentConfig.from_yaml("config.yaml")

# To YAML
experiment.to_yaml("experiment_config.yaml")

Benchmarks

Synthetic data, hidden_size=256. Run with python benchmarks/benchmark_compare.py.

Metric Value Notes
Compression ratio (256→64) 75% memory saved: 12 MB → 3 MB
Riemannian norm drift 0.000001 Euclidean step drifts to 1.258 (430,000× worse)
VIB KL loss 139.9 Compression vs reconstruction trade-off
Compressor parameters 445K Lightweight, ~0.13% of a 340M-param model

Riemannian vs Euclidean norm drift
100 gradient steps on S255. Riemannian stays on the manifold; Euclidean drifts ~25% per step.

Compression ratio
4× compression: 256-dim input → 64-dim latent, saving 75% memory.


Architecture

ib_components/
├── src/ib_components/
│   ├── compressor/              VIB encoder-decoder + Riemannian manifold
│   │   ├── vib_compressor.py    LayerwiseVIBCompressor, HierarchicalVIBCompressor
│   │   └── riemannian.py        RiemannianOptimizer, SphereManifold, tangent/expmap
│   ├── improvements/            Plug-and-play enhancements
│   │   ├── adaptive_beta.py     AdaptiveBetaScheduler, KLAnnealingScheduler
│   │   ├── info_gain.py         InformationGainDrive (MINE mutual information)
│   │   ├── cross_layer_consistency.py  CrossLayerConsistency (Frobenius alignment)
│   │   └── attractor_dynamics.py      AttractorDynamics (Neural ODE vector field)
│   ├── config.py                Type-safe dataclass configurations
│   ├── exceptions.py            Custom exception hierarchy
│   ├── logging.py               Structured logging (ComponentLogger)
│   └── utils/
│       ├── helpers.py           YAML config, logging, device, JSON, env, seeding
│       └── checkpointing.py     CheckpointManager, IncrementalCheckpointer
├── tests/                       Comprehensive test suite
├── benchmarks/                  Performance comparisons
├── examples/                    Runnable tutorials
└── docs/                        Sphinx documentation

Each component follows the same contract:

  1. Subclass torch.nn.Module — drop-in PyTorch integration
  2. Accept enabled: bool — set False for identity pass-through
  3. Return consistent outputs — dict of loss terms or raw tensors

Development

# Setup
git clone https://github.com/Fengrru/ib-components.git
cd ib-components
make dev

# Commands
make test       # Run tests (with coverage, ≥80% threshold)
make lint       # Run linting (black + isort + flake8)
make format     # Auto-format code
make typecheck  # Run mypy type checking
make check      # Run all checks (lint + typecheck + test)
make docs       # Build Sphinx documentation
make bench      # Run performance benchmarks

References

Paper Year Relevance
The Information Bottleneck Principle 1999 Foundational IB theory
Deep Variational Information Bottleneck 2017 VIB loss formulation
MINE: Mutual Information Neural Estimation 2018 Information gain estimation
Neural Ordinary Differential Equations 2018 Attractor dynamics
Optimization on Matrix Manifolds 2008 Riemannian optimization theory
KL Annealing for VAEs 2016 KL warmup strategy

Citation

@software{ib_components2025,
  author       = {IB Components Team},
  title        = {ib\_components: Modular building blocks for Information Bottleneck research},
  year         = {2025},
  url          = {https://github.com/Fengrru/ib-components},
  version      = {0.1.3},
}

Contributing

Contributions welcome! See CONTRIBUTING.md for development setup, coding standards, and the PR checklist.

License

MIT — see LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ib_components-0.1.3.tar.gz (53.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ib_components-0.1.3-py3-none-any.whl (38.0 kB view details)

Uploaded Python 3

File details

Details for the file ib_components-0.1.3.tar.gz.

File metadata

  • Download URL: ib_components-0.1.3.tar.gz
  • Upload date:
  • Size: 53.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for ib_components-0.1.3.tar.gz
Algorithm Hash digest
SHA256 05feeccdc08858165dbc1845fbbd94a21de7b3b490eb0f59fb870cab2a08597f
MD5 a8eb56d40a7a8dbfec50c738ed3b7e74
BLAKE2b-256 a0d44dbb95872fe948fc77cf17f4f2473191ce687bc8565d4f6bf9ddff6bf717

See more details on using hashes here.

File details

Details for the file ib_components-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: ib_components-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 38.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for ib_components-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 60de1a30b1a17830f951254daa73d778a62de707c276038c66f90fd423b5e1ee
MD5 45a2dd5812f615ea54af6cb75c45f37b
BLAKE2b-256 53a3fd63e31f3fff2f58daecd34572717339264a15eecaeb9716e97d96626188

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page