Certainly! Below is a comprehensive implementation of the Mirror Descent (MD) algorithm using PyTorch. This implementation adheres strictly to PEP-8 standards, utilizes type hints for clarity, and incorporates robust error handling to ensure reliability and maintainability. The code is modular, allowing easy extension or modification for different mirror maps and optimization problems.
Overview
The Mirror Descent algorithm is a versatile optimization framework suitable for various convex optimization problems. It operates by mapping iterates between primal and dual spaces using conjugate mirror maps derived from a convex function of Legendre type. This implementation includes:
- Bregman Divergence Calculation: Computes the Bregman divergence based on a given mirror map.
- Mirror Maps: Supports different mirror maps, such as squared L2-norm and negative entropy.
- Mirror Descent Optimizer: Implements the core MD algorithm, allowing customization of the mirror map and projection set.
- Examples: Demonstrates usage with squared L2-norm and negative entropy mirror maps.
Code Implementation
import torch
from torch import Tensor
from torch.optim import Optimizer
from typing import Callable, Optional, Tuple, List, Any
import warnings
class MirrorMap:
"""
Abstract base class for mirror maps.
A mirror map defines the convex function Φ and its conjugate Φ*,
along with their gradients.
"""
def __init__(self) -> None:
pass
def phi(self, x: Tensor) -> Tensor:
"""
Compute Φ(x).
"""
raise NotImplementedError("phi method not implemented.")
def phi_star(self, x_star: Tensor) -> Tensor:
"""
Compute Φ*(x_star).
"""
raise NotImplementedError("phi_star method not implemented.")
def grad_phi(self, x: Tensor) -> Tensor:
"""
Compute ∇Φ(x).
"""
raise NotImplementedError("grad_phi method not implemented.")
def grad_phi_star(self, x_star: Tensor) -> Tensor:
"""
Compute ∇Φ*(x_star).
"""
raise NotImplementedError("grad_phi_star method not implemented.")
def bregman_divergence(self, x: Tensor, y: Tensor) -> Tensor:
"""
Compute the Bregman divergence DΦ(x, y).
"""
return self.phi(x) - self.phi(y) - torch.sum(self.grad_phi(y) * (x - y), dim=-1)
class SquaredL2NormMirror(MirrorMap):
"""
Mirror map based on the squared L2 norm: Φ(x) = 1/2 * ||x||^2
"""
def phi(self, x: Tensor) -> Tensor:
return 0.5 * torch.sum(x ** 2, dim=-1)
def phi_star(self, x_star: Tensor) -> Tensor:
return 0.5 * torch.sum(x_star ** 2, dim=-1)
def grad_phi(self, x: Tensor) -> Tensor:
return x
def grad_phi_star(self, x_star: Tensor) -> Tensor:
return x_star
class NegativeEntropyMirror(MirrorMap):
"""
Mirror map based on negative entropy: Φ(x) = sum(xi * log(xi) - xi)
Defined on the probability simplex.
"""
def phi(self, x: Tensor) -> Tensor:
return torch.sum(x * torch.log(x) - x, dim=-1)
def phi_star(self, x_star: Tensor) -> Tensor:
return torch.logsumexp(x_star, dim=-1)
def grad_phi(self, x: Tensor) -> Tensor:
return torch.log(x)
def grad_phi_star(self, x_star: Tensor) -> Tensor:
exp_x_star = torch.exp(x_star)
return exp_x_star / torch.sum(exp_x_star, dim=-1, keepdim=True)
class MirrorDescent:
"""
Mirror Descent optimizer implementation using PyTorch.
"""
def __init__(
self,
mirror_map: MirrorMap,
step_size: Callable[[int], float],
projection: Optional[Callable[[Tensor], Tensor]] = None,
device: Optional[torch.device] = None,
) -> None:
"""
Initialize the Mirror Descent optimizer.
Args:
mirror_map (MirrorMap): The mirror map to use.
step_size (Callable[[int], float]): Function to compute step size ηk given iteration k.
projection (Optional[Callable[[Tensor], Tensor]]): Projection onto the constraint set.
If None, no projection is performed.
device (Optional[torch.device]): Device to perform computations on.
"""
if not isinstance(mirror_map, MirrorMap):
raise TypeError("mirror_map must be an instance of MirrorMap.")
self.mirror_map = mirror_map
self.step_size = step_size
self.projection = projection
self.device = device if device is not None else torch.device("cpu")
self.iteration = 0
def update(
self,
x_k: Tensor,
gradient: Tensor,
) -> Tensor:
"""
Perform one iteration of Mirror Descent.
Args:
x_k (Tensor): Current iterate x^(k).
gradient (Tensor): Gradient g^(k) = ∇f(x^(k)).
Returns:
Tensor: Next iterate x^(k+1).
"""
x_k = x_k.to(self.device)
gradient = gradient.to(self.device)
eta_k = self.step_size(self.iteration)
self.iteration += 1
# Compute ∇Φ(x^(k))
grad_phi_xk = self.mirror_map.grad_phi(x_k)
# Compute ∇Φ*(∇Φ(x^(k)) - η_k g^(k))
dual = grad_phi_xk - eta_k * gradient
y_k_plus_1 = self.mirror_map.grad_phi_star(dual)
# Apply projection if provided
if self.projection is not None:
x_k_plus_1 = self.projection(y_k_plus_1)
else:
x_k_plus_1 = y_k_plus_1
return x_k_plus_1
def minimize(
self,
initial_x: Tensor,
gradients: List[Tensor],
iterations: Optional[int] = None,
) -> Tensor:
"""
Run Mirror Descent for a given number of iterations or until gradients are exhausted.
Args:
initial_x (Tensor): Starting point x^(0).
gradients (List[Tensor]): List of gradients g^(k) for each iteration.
iterations (Optional[int]): Number of iterations to perform.
If None, runs for the length of gradients.
Returns:
Tensor: The final iterate x^(K).
"""
x_k = initial_x.to(self.device)
num_iterations = iterations if iterations is not None else len(gradients)
for k in range(num_iterations):
if k >= len(gradients):
raise ValueError(
f"Not enough gradients provided for {num_iterations} iterations."
)
grad = gradients[k]
x_k = self.update(x_k, grad)
return x_k
def project_simplex(y: Tensor) -> Tensor:
"""
Project a tensor y onto the probability simplex.
Args:
y (Tensor): Input tensor to be projected. Assumes last dimension is the feature dimension.
Returns:
Tensor: Projected tensor on the simplex.
"""
# Sorting in descending order
sorted_y, _ = torch.sort(y, dim=-1, descending=True)
cumulative_sum = torch.cumsum(sorted_y, dim=-1)
rho = (
torch.sum(
sorted_y * torch.arange(1, y.size(-1) + 1, device=y.device).float(),
dim=-1,
)
> 1
).float() # Indicator for rho
# This is a simplified projection and may require more robust implementation
return y / torch.sum(y, dim=-1, keepdim=True)
# Example usage
def main() -> None:
"""
Demonstrates the usage of the MirrorDescent optimizer with different mirror maps.
"""
# Define device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Define step size schedule
def step_size(k: int) -> float:
return 1.0 / (k + 1)
# Example 1: Squared L2 Norm Mirror Descent
print("Squared L2 Norm Mirror Descent Example:")
l2_mirror = SquaredL2NormMirror()
md_l2 = MirrorDescent(
mirror_map=l2_mirror,
step_size=step_size,
projection=None, # No projection needed for unconstrained optimization
device=device,
)
# Initialize x^(0)
x0 = torch.zeros(5, device=device)
# Define a simple quadratic function f(x) = 0.5 * ||x - b||^2
b = torch.ones(5, device=device)
# Compute gradients: g^(k) = x^(k) - b
gradients_l2 = [x0 - b]
for _ in range(10):
gradients_l2.append(None) # Placeholder
# Initialize x0
x = x0.clone()
# Run Mirror Descent
for k in range(10):
g = x - b # Gradient of f at x
x = md_l2.update(x, g)
print(f"Iteration {k+1}: x = {x}")
# Example 2: Negative Entropy Mirror Descent on the Simplex
print("\nNegative Entropy Mirror Descent Example:")
entropy_mirror = NegativeEntropyMirror()
md_entropy = MirrorDescent(
mirror_map=entropy_mirror,
step_size=step_size,
projection=lambda y: project_simplex(y),
device=device,
)
# Initialize x^(0) on the simplex
x0_entropy = torch.ones(5, device=device) / 5.0
# Define a linear function f(x) = c^T x
c = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0], device=device)
# Compute gradients: g^(k) = c
gradients_entropy = [c.clone() for _ in range(10)]
# Initialize x0
x = x0_entropy.clone()
# Run Mirror Descent
for k in range(10):
g = c # Gradient of f at x
x = md_entropy.update(x, g)
print(f"Iteration {k+1}: x = {x}")
if __name__ == "__main__":
main()
Explanation
1. Mirror Maps
-
MirrorMap Abstract Base Class: Defines the interface for mirror maps, including methods for computing the convex function Φ, its conjugate Φ*, and their gradients. It also provides a method to compute the Bregman divergence.
-
SquaredL2NormMirror: Implements the mirror map based on the squared L2 norm. It's suitable for unconstrained optimization problems.
-
NegativeEntropyMirror: Implements the mirror map based on negative entropy, suitable for optimization over the probability simplex. It includes a projection method to ensure iterates remain within the simplex.
2. Mirror Descent Optimizer
-
Initialization:
mirror_map: An instance of a subclass of MirrorMap.
step_size: A callable that determines the step size ηₖ based on the iteration number k.
projection: An optional callable for projecting iterates onto a constraint set. For the simplex, a projection function is provided.
device: Specifies the computation device (CPU or GPU).
-
Update Method:
- Computes the dual variable using the gradient of Φ and the current gradient.
- Applies the conjugate gradient mapping to obtain the new iterate.
- Applies projection if a projection function is provided.
-
Minimize Method:
- Facilitates running the optimizer over multiple iterations, given an initial point and a list of gradients.
3. Projection onto the Simplex
project_simplex Function: Projects a tensor onto the probability simplex. This ensures that the iterates remain valid probability distributions. The implementation provided is a simplified version and can be enhanced for numerical stability and efficiency.
4. Examples
5. Error Handling and Validation
- The code includes type checks and error messages to ensure that incorrect mirror map instances or insufficient gradients are handled gracefully.
- Warnings can be added as needed to inform users of potential issues during execution.
6. Type Hints and Documentation
- Comprehensive type hints are provided for all functions and methods to enhance code clarity and maintainability.
- Docstrings explain the purpose and usage of classes, methods, and functions.
7. PEP-8 Compliance
- The code adheres to PEP-8 standards, including naming conventions, indentation, and line length.
- Clear separation of classes and functions enhances readability.
Running the Code
The main function demonstrates how to use the MirrorDescent optimizer with both the squared L2 norm and negative entropy mirror maps. When executed, it will print the iterates for each iteration, showing how the algorithm progresses towards the optimum.
Ensure that PyTorch is installed in your environment. You can install it using:
pip install torch
Then, run the script:
python mirror_descent.py
Replace mirror_descent.py with the filename you save the script as.
This implementation provides a flexible and robust foundation for applying the Mirror Descent algorithm to various convex optimization problems using PyTorch. It can be extended with additional mirror maps or integrated into larger optimization frameworks as needed.