Skip to main content

EggRoll-style Evolution Strategies with low-rank noise for PyTorch

Project description

TorchEggroll

EggRoll-style Evolution Strategies with low-rank noise for PyTorch.

TorchEggroll provides a simple, efficient Evolution Strategies (ES) optimizer for PyTorch models. It uses low-rank noise for matrix parameters, reducing variance in gradient estimates while maintaining computational efficiency.

Installation

pip install torcheggroll

Or with uv:

uv add torcheggroll

Quick Start

import torch
import torch.nn as nn
from torcheggroll import TorchEggrollES

# Define your model
model = nn.Sequential(
    nn.Linear(10, 20),
    nn.ReLU(),
    nn.Linear(20, 5)
)

# Create the ES optimizer
es = TorchEggrollES(
    model=model,
    pop_size=32,      # Population size (must be even for antithetic sampling)
    sigma=0.1,        # Noise scale
    lr=0.1,           # Learning rate
    rank=4,           # Rank for low-rank noise on matrices
    antithetic=True,  # Use antithetic sampling for lower variance
)

# Define your fitness function (higher is better)
def fitness(m):
    pred = m(x_train)
    loss = ((pred - y_train) ** 2).mean()
    return -float(loss)  # Negative loss = higher fitness

# Optimize!
for step in range(100):
    mean_fitness = es.step(fitness)
    print(f"Step {step}: fitness = {mean_fitness:.4f}")

Features

  • Low-rank noise for matrices: Uses EggRoll-style A @ B.T noise for 2D parameters, reducing variance in gradient estimates
  • Antithetic sampling: Half the population uses +noise, half uses -noise, further reducing variance
  • Parameter filtering: Optimize only specific parameters using param_filter
  • Works with any nn.Module: No modifications needed to your model

API Reference

TorchEggrollES

TorchEggrollES(
    model: nn.Module,           # Model to optimize
    pop_size: int = 32,         # Population size per step
    sigma: float = 0.02,        # Noise scale
    lr: float = 0.05,           # Learning rate
    rank: int = 4,              # Rank for low-rank noise
    device: torch.device = None,# Device (inferred from model if None)
    param_filter: Callable = None,  # Filter which params to optimize
    normalize_fitness: bool = True, # Z-score normalize fitness
    antithetic: bool = True,    # Use antithetic sampling
)

Methods:

  • step(eval_fn) -> float: Run one ES step. eval_fn(model) -> float should return fitness (higher is better). Returns mean fitness across population.

Utility Functions

  • generate_lora_noise(param, rank, sigma, seed, device): Generate low-rank A @ B.T noise for a 2D tensor
  • generate_standard_noise(param, sigma, seed, device): Generate standard Gaussian noise

Examples

See the examples/ directory for complete examples:

  • nano_classifier.py: Train a factorized classifier using ES

Run the example:

python examples/nano_classifier.py --steps 50 --pop-size 64

How It Works

TorchEggroll implements Evolution Strategies with two key optimizations:

  1. Low-rank noise: For matrix parameters (2D tensors), instead of generating full Gaussian noise, we generate low-rank noise as A @ B.T where A and B are small random matrices. This reduces the effective dimensionality of the search space.

  2. Antithetic sampling: For each random perturbation, we evaluate both +noise and -noise. This creates correlated pairs that reduce variance in the gradient estimate.

The ES gradient is estimated as:

grad ≈ (1/N) * Σ fitness_i * noise_i

Where fitness_i is the normalized fitness of the i-th population member.

Related Projects

  • hyperfunc: Higher-level ES optimization framework that uses TorchEggroll internally

License

MIT

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

torcheggroll-0.1.0.tar.gz (55.7 kB view details)

Uploaded Source

Built Distribution

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

torcheggroll-0.1.0-py3-none-any.whl (7.4 kB view details)

Uploaded Python 3

File details

Details for the file torcheggroll-0.1.0.tar.gz.

File metadata

  • Download URL: torcheggroll-0.1.0.tar.gz
  • Upload date:
  • Size: 55.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for torcheggroll-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cbf046f8de5ced804c8e55325b28124395b46881eb558f7958aa92743bc9799f
MD5 865d7707663f4324d1c8bc114405bc67
BLAKE2b-256 0b615c449e865a406c3a5eacb06addddcc462eceb1de6ceba08a170e7e5e530a

See more details on using hashes here.

File details

Details for the file torcheggroll-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: torcheggroll-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for torcheggroll-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3b6f59783c00c0f2ef19c88c185505e5585fce3ae12626204794c4ef605ae632
MD5 9c0590e00d17d348a538b3711885b250
BLAKE2b-256 bcdb8f712d9a5437a7f89b0da1a2c3daa467513a821ab46cbef913409a967ed7

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