Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK : develop code below Mirror Descent in great details using torch module only from stratch
2.2 Mirror Descent
Mirror descent (MD) is a general framework for the construction and analysis of optimization
algorithms [Nemirovski and Yudin, 1983]. Its key machinery is a pair of conjugate mirror maps that
map the iterates of an optimization algorithm back-and-forth between a primal space and a dual space.
We follow the common practice of defining the mirror maps with the gradient mapping of a convex
function of Legendre-type [Rockafellar, 1970, Section 26].
Let’s first define Bregman divergence and Bregman projection. Suppose that Ψ is a convex function
of Legendre type. It induces a Bregman divergence between any x ∈ dom Φ and y ∈ int (dom Φ):
DΦ(x, y) = Φ(x) − Φ(y) − ⟨∇Φ(y), x − y⟩. (5)
Let C ∈ dom Φ be a closed convex set. The Bregman projection of any y ∈ int (dom Φ) onto C is
projΦ
C
(y) = arg min
x∈C
DΦ(x, y). (6)
Properties of Bregman projection can be found in, e.g., Bauschke and Borwein [1997].
2
Now consider the problem of minimizing a convex function f : X → R ∪ {∞} over a closed convex
set C ⊂ dom Φ. We use the presentation of MD given by Bubeck [2015]: at each iteration k,
Given x
(k)
, find y
(k+1) such that
∇Φ(y
(k+1)) = ∇Φ(x
(k)
) − ηkg
(k)
. (7)
where ηk is the step size and g
(k)
is the gradient ∇f(x
(k)
) or a sub-gradient of f at x
(k)
.
Compute x
(k+1) = projΦ
C
(y
(k+1)).
Define the conjugate function of Φ as Φ
∗
(x
∗
) = supx∈dom Φ {⟨x, x∗
⟩ − Φ(x)}. Then, using the
definition in (6) and the identity ∇Φ
∗
(∇Φ(x)) = x, we can express it more compactly as
x
(k+1)= arg min
x∈C
DΦ
x, ∇Φ
∗
∇Φ(x
(k)
)−ηkg
(k)
, (8)
which can be further simplified to [Beck and Teboulle, 2003, Bubeck et al., 2012]
x
(k+1) = arg min
x∈C
n
ηk
g
(k)
, x
DΦ(x, x(k)
)
o
. (9)
Next we discuss three examples of the MD algorithm for solving minx∈∆ f(x), where ∆ is the
simplex. Each leads to a variant of the DAPO method we will present in Section 3.
Example 2.1 (Squared L2-norm). Let Φ(x) = 1
2
∥x∥
2
2
, which is Legendre type with int (dom Φ) =
dom Φ = R
n. We have Φ
∗
(x
∗
) = 1
2
∥x
∗∥
2
2
, ∇Φ(x) = x, ∇Φ
∗
(x
∗
) = x
∗
, and DΦ(x, y) =
1
2
∥x − y∥
2
2
. In this case, the MD algorithm (8) becomes the classical projected gradient method
x
(k+1) = arg min
x∈∆
Assistant
x −
x
(k) − ηk∇f(x
(k)
)
2
2
.
Example 2.2 (Negative entropy on R
n
+). Consider the negative entropy Φ(x) = P
i
(xi
log(xi) − xi)
with dom Φ = R
n
(and the convention 0 log 0 = 0). It is of Legendre type, with Φ
∗
(x
∗ P
) =
i
exp(x
∗
i
), ∇Φ(x) = log(x) and ∇Φ
∗
(x
∗
) = exp(x
∗
), where log and exp apply component-wise
to vectors. For any x ∈ R
n
and y ∈ R
n
++, their Bregman divergence is the KL-divergence:
DΦ(x, y) = P
i
(xi
log(xi/yi) − xi + yi). (10)
In this case, the Bregman projection of y ∈ R
n
++ onto ∆ is projΦ
∆(y) = y/∥y∥1 and (8) becomes
x
(k+1) = x
(k)
exp(−ηkg
(k)
)/∥x
(k)
exp(−ηkg
(k)
)∥1. (11)
Example 2.3 (Negative entropy on ∆). Let ϕ(x) = P
i
(xi
log(xi) − xi) and define Φ(x) =
ϕ(x) + δ(x|∆), where δ(·|∆) is the indicator function of ∆, i.e., δ(x|∆) = 0 if x ∈ ∆ and +∞
otherwise. Apparently dom Φ = ∆, which has an empty interior. As a result, Φ is not of Legendre
type and in fact is not differentiable (see Appendix B). However, the MD algorithm is still welldefined. Specifically, in (7) we interpret ∇Φ(x
(k)
) as any subgradient in the subdifferential ∂Φ(x
(k)
),
and find y
(k+1) such that there exists some ∇Φ(y
(k+1)) ∈ ∂Φ(y
(k+1)) to make the equality hold.
Despite ∇Φ(y) being multi-valued as a subgradient, the Bregman divergence (5) is still well defined
(Corollary B.3). As a result, DΦ is the same as (10). Using the fact x, y ∈ ∆, it can be simplified as
DΦ(x, y) = P
i
xi
log(xi/yi). (12)
In addition, we have Φ
∗
(x
∗
) = log (P
i
exp(x
∗
i
)) with dom Φ∗ = R
n [Rockafellar, 1970, Section 16]. Clearly, Φ
∗
is a differentiable function throughout R
n and
∇Φ
∗
(x
∗
) = exp(x
∗
)/∥ exp(x
∗
)∥1.
In this case, the MD algorithm (8) yields the same update as (11). However, the projection step is no
longer needed because the range of ∇Φ
∗
is the interior of ∆ and we can simply express MD as
x
(k+1) = ∇Φ
∗
∇Φ(x
(k)
) − ηkg
(k)
.
Remark 2.4. Although Examples 2.2 and 2.3 give the same update (11), there are subtle differences
in the theory. In particular, we have ∇Φ
∗ = (∇Φ)−1
in Example 2.2 and the equivalence between (8)
and 9 is easily established. However, this is not the case for Example 2.3 because Φ is not Legendre
and nondifferentiable. Consequently, we can no longer leverage the convex optimization machinery
as in the tabular case [e.g., Xiao, 2022, Lan, 2023] for convergence analysis with general function
approximation. Instead, we extend the classical MD theory to work with mirror maps whose gradient
mapping and conjugate mapping are not inverses of each other; see Appendix B, Lemma B.2.
Algorithm 1 Dual Approximation Policy Optimization (DAPO)
1: Input: Initialize policy π
(0) with parameters θ
(0); mirror map Φ
2: for k = 0, . . . , K − 1 do
3: Find Qb(k)
that approximates Q(k)
(Critic Update)
4: Find θ
(k+1) that (approximately) solves the problem
min
θ∈Θ
Es∼d
(k)
ρ
h
DΦ∗
∇Φ(π
(k)
s
) − ηkQb(k)
s
, f θ
s
i
5: Assign π
(k+1)
s = projΦ
∆(A)
∇Φ
∗
(f
θ
(k+1)
s
)
, s ∈ S
6: end fo
Certainly! Below is a comprehensive implementation of the Mirror Descent (MD) algorithm using the PyTorch library, adhering strictly to PEP-8 standards and incorporating best practices for readability, maintainability, and efficiency.
The implementation is modular, allowing flexibility in choosing different mirror maps such as the squared L2-norm and negative entropy. Comprehensive error handling ensures robustness, and type hints enhance code clarity.
Overview
Mirror Maps: Defined as classes inheriting from an abstract base class MirrorMap. Each mirror map must implement methods to compute the convex function Φ, its conjugate Φ∗, gradients, and Bregman divergence.
MirrorDescent Optimizer: A class that encapsulates the Mirror Descent optimization process. It interacts with the chosen mirror map to perform iterative updates.
Utility Functions: Helper functions for projection and other repeated operations.
Example Usage: Demonstrates how to use the implemented classes with a sample convex optimization problem.
Implementation
python
import torch
from torch import Tensor
from typing import Callable, Optional, Tuple, Union
import abc
import logging
# Configure logging for debug purposes
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MirrorMap(abc.ABC):
"""
Abstract base class for defining mirror maps.
"""
@abc.abstractmethod
def phi(self, x: Tensor) -> Tensor:
"""
Compute the convex function Φ(x).
Args:
x (Tensor): Input tensor.
Returns:
Tensor: Φ(x).
"""
pass
@abc.abstractmethod
def phi_star(self, x_star: Tensor) -> Tensor:
"""
Compute the conjugate function Φ∗(x∗).
Args:
x_star (Tensor): Input tensor in the dual space.
Returns:
Tensor: Φ∗(x∗).
"""
pass
@abc.abstractmethod
def grad_phi(self, x: Tensor) -> Tensor:
"""
Compute the gradient of Φ at x, ∇Φ(x).
Args:
x (Tensor): Input tensor.
Returns:
Tensor: Gradient tensor.
"""
pass
@abc.abstractmethod
def grad_phi_star(self, x_star: Tensor) -> Tensor:
"""
Compute the gradient of Φ∗ at x∗, ∇Φ∗(x∗).
Args:
x_star (Tensor): Input tensor in the dual space.
Returns:
Tensor: Gradient tensor.
"""
pass
@abc.abstractmethod
def bregman_divergence(self, x: Tensor, y: Tensor) -> Tensor:
"""
Compute the Bregman divergence DΦ(x, y).
Args:
x (Tensor): Primal space tensor.
y (Tensor): Primal space tensor.
Returns:
Tensor: Bregman divergence.
"""
pass
@abc.abstractmethod
def projection(self, y: Tensor, constraints: Optional[Callable[[Tensor], bool]] = None) -> Tensor:
"""
Compute the Bregman projection of y onto the convex set C.
Args:
y (Tensor): Input tensor in the primal space.
constraints (Optional[Callable[[Tensor], bool]]): Constraints defining the convex set C.
Returns:
Tensor: Projected tensor x ∈ C.
"""
pass
class SquaredL2NormMirrorMap(MirrorMap):
"""
Mirror map using the squared L2-norm: Φ(x) = 0.5 * ||x||^2.
"""
def phi(self, x: Tensor) -> Tensor:
return 0.5 * torch.sum(x ** 2)
def phi_star(self, x_star: Tensor) -> Tensor:
return 0.5 * torch.sum(x_star ** 2)
def grad_phi(self, x: Tensor) -> Tensor:
return x
def grad_phi_star(self, x_star: Tensor) -> Tensor:
return x_star
def bregman_divergence(self, x: Tensor, y: Tensor) -> Tensor:
return 0.5 * torch.sum((x - y) ** 2)
def projection(self, y: Tensor, constraints: Optional[Callable[[Tensor], bool]] = None) -> Tensor:
# For Euclidean projection, PyTorch does not have a built-in projection onto generic convex sets.
# Therefore, the user must provide the projection logic via constraints.
if constraints is None:
raise NotImplementedError("Projection method requires constraints.")
# Assuming constraints define a projection function
return constraints(y)
class NegativeEntropyMirrorMap(MirrorMap):
"""
Mirror map using the negative entropy: Φ(x) = Σ x_i log(x_i) - x_i.
Applicable for x ∈ R^n_+.
"""
def phi(self, x: Tensor) -> Tensor:
# To ensure numerical stability, add a small epsilon inside the log.
epsilon = 1e-12
return torch.sum(x * torch.log(x + epsilon) - x)
def phi_star(self, x_star: Tensor) -> Tensor:
# Φ∗(x∗) = log(Σ exp(x∗_i))
return torch.log(torch.sum(torch.exp(x_star)))
def grad_phi(self, x: Tensor) -> Tensor:
# ∇Φ(x) = log(x)
epsilon = 1e-12
return torch.log(x + epsilon)
def grad_phi_star(self, x_star: Tensor) -> Tensor:
# ∇Φ∗(x∗) = exp(x∗) / ||exp(x∗)||_1
exp_x_star = torch.exp(x_star)
sum_exp = torch.sum(exp_x_star)
return exp_x_star / sum_exp
def bregman_divergence(self, x: Tensor, y: Tensor) -> Tensor:
# KL divergence: DΦ(x, y) = Σ x_i log(x_i / y_i) - x_i + y_i
epsilon = 1e-12
return torch.sum(x * torch.log((x + epsilon) / (y + epsilon)) - x + y)
def projection(self, y: Tensor, constraints: Optional[Callable[[Tensor], bool]] = None) -> Tensor:
# Project onto the simplex: x = y / ||y||_1
sum_y = torch.sum(y)
if sum_y == 0:
raise ValueError("Sum of y is zero, cannot project onto simplex.")
return y / sum_y
class MirrorDescent:
"""
Mirror Descent optimization algorithm.
"""
def __init__(
self,
mirror_map: MirrorMap,
step_size: Union[float, Callable[[int], float]],
constraints: Optional[Callable[[Tensor], bool]] = None,
) -> None:
"""
Initialize the Mirror Descent optimizer.
Args:
mirror_map (MirrorMap): The mirror map to use.
step_size (Union[float, Callable[[int], float]]): Step size (constant or function of iteration).
constraints (Optional[Callable[[Tensor], bool]]): Constraints defining the convex set C.
"""
self.mirror_map = mirror_map
if isinstance(step_size, float):
self.step_size = lambda k: step_size
elif callable(step_size):
self.step_size = step_size
else:
raise TypeError("step_size must be a float or a callable function of iteration.")
self.constraints = constraints
def project(
self, y: Tensor, constraints: Optional[Callable[[Tensor], bool]] = None
) -> Tensor:
"""
Project tensor y onto the convex set C using the mirror map's projection.
Args:
y (Tensor): Tensor to project.
constraints (Optional[Callable[[Tensor], bool]]): Constraints defining C.
Returns:
Tensor: Projected tensor.
"""
logger.debug("Projecting y onto C using the mirror map's projection.")
return self.mirror_map.projection(y, constraints)
def step(
self,
x_current: Tensor,
gradient: Tensor,
iteration: int
) -> Tensor:
"""
Perform a single Mirror Descent update step.
Args:
x_current (Tensor): Current iterate x^(k).
gradient (Tensor): Gradient or sub-gradient g^(k) of f at x^(k).
iteration (int): Current iteration number k.
Returns:
Tensor: Next iterate x^(k+1).
"""
eta_k = self.step_size(iteration)
logger.debug(f"Iteration {iteration}: Step size eta_k = {eta_k}")
# Compute gradient of Phi at current x
grad_phi_x = self.mirror_map.grad_phi(x_current)
logger.debug(f"Gradient of Phi at x_current: {grad_phi_x}")
# Compute y^{k+1} in the dual space
grad_phi_y = grad_phi_x - eta_k * gradient
logger.debug(f"Gradient in dual space (grad_phi_y): {grad_phi_y}")
# Compute y^{k+1} in the primal space using the conjugate gradient
y_next = self.mirror_map.grad_phi_star(grad_phi_y)
logger.debug(f"Primal space y_next before projection: {y_next}")
# Project y_next onto the convex set C
x_next = self.project(y_next, self.constraints)
logger.debug(f"Primal space x_next after projection: {x_next}")
return x_next
def optimize(
self,
x_init: Tensor,
objective: Callable[[Tensor], Tensor],
num_iterations: int,
verbose: bool = False
) -> Tensor:
"""
Run the Mirror Descent optimization algorithm.
Args:
x_init (Tensor): Initial point x^(0) ∈ C.
objective (Callable[[Tensor], Tensor]): The objective function to minimize.
num_iterations (int): Number of iterations to perform.
verbose (bool): If True, print progress.
Returns:
Tensor: Optimized point x^(K).
"""
x = x_init.clone().detach().requires_grad_(False)
logger.info("Starting Mirror Descent optimization.")
for k in range(num_iterations):
# Compute gradient of the objective at current x
obj = objective(x)
obj.backward()
try:
gradient = x.grad.clone()
except AttributeError:
raise RuntimeError("Objective function must be differentiable.")
x.grad.zero_()
if verbose and k % max(1, num_iterations // 10) == 0:
logger.info(f"Iteration {k}: Objective = {obj.item()}")
# Perform Mirror Descent step
x = self.step(x, gradient, k)
logger.info("Mirror Descent optimization completed.")
return x
def euclidean_projection_simplex(y: Tensor) -> Tensor:
"""
Project a tensor onto the simplex using the method by Duchi et al. (2008).
Args:
y (Tensor): Input tensor.
Returns:
Tensor: Projected tensor onto the simplex.
"""
logger.debug("Projecting onto the simplex.")
sorted_y, _ = torch.sort(y, descending=True)
cssv = torch.cumsum(sorted_y, dim=0) - 1
ind = torch.arange(1, len(y) + 1, device=y.device)
cond = sorted_y - cssv / ind.float() > 0
rho = ind[cond][-1]
theta = cssv[rho - 1] / rho.float()
return torch.clamp(y - theta, min=0)
class SimplexProjectionConstraint:
"""
Constraint class for projecting onto the simplex.
"""
def __call__(self, y: Tensor) -> Tensor:
"""
Project tensor y onto the simplex.
Args:
y (Tensor): Tensor to project.
Returns:
Tensor: Projected tensor.
"""
return euclidean_projection_simplex(y)
def example_squared_l2_norm():
"""
Example usage of Mirror Descent with Squared L2-norm mirror map.
Minimizes f(x) = (1/2) * ||x - a||^2, subject to ||x||_2 <= R.
"""
logger.info("Running example with Squared L2-norm mirror map.")
# Define parameters
a = torch.tensor([1.0, 2.0, 3.0])
R = 5.0
# Define the objective function f(x) = 0.5 * ||x - a||^2
def objective(x: Tensor) -> Tensor:
return 0.5 * torch.sum((x - a) ** 2)
# Define constraints: ||x||_2 <= R
def constraint_project(y: Tensor) -> Tensor:
norm_y = torch.norm(y, p=2)
if norm_y <= R:
return y
else:
return y * (R / norm_y)
# Initialize mirror map and optimizer
mirror_map = SquaredL2NormMirrorMap()
optimizer = MirrorDescent(
mirror_map=mirror_map,
step_size=0.1,
constraints=constraint_project
)
# Initialize x
x_init = torch.zeros_like(a)
# Run optimization
num_iterations = 100
x_opt = optimizer.optimize(x_init, objective, num_iterations, verbose=True)
logger.info(f"Optimized x: {x_opt}")
logger.info(f"Objective value at optimized x: {objective(x_opt).item()}")
def example_negative_entropy():
"""
Example usage of Mirror Descent with Negative Entropy mirror map.
Minimizes f(x) = -c^T x, subject to x ∈ simplex.
"""
logger.info("Running example with Negative Entropy mirror map.")
# Define parameters
c = torch.tensor([1.0, 2.0, 3.0])
# Define the objective function f(x) = -c^T x
def objective(x: Tensor) -> Tensor:
return -torch.dot(c, x)
# Define constraints: x ∈ simplex
simplex_constraint = SimplexProjectionConstraint()
# Initialize mirror map and optimizer
mirror_map = NegativeEntropyMirrorMap()
optimizer = MirrorDescent(
mirror_map=mirror_map,
step_size=0.1,
constraints=simplex_constraint
)
# Initialize x (must be in the simplex)
x_init = torch.ones_like(c) / len(c)
# Run optimization
num_iterations = 100
x_opt = optimizer.optimize(x_init, objective, num_iterations, verbose=True)
logger.info(f"Optimized x: {x_opt}")
logger.info(f"Objective value at optimized x: {objective(x_opt).item()}")
def main():
"""
Main function to run examples.
"""
example_squared_l2_norm()
example_negative_entropy()
if __name__ == "__main__":
main()
Explanation
Abstract Base Class MirrorMap:
Defines the interface for mirror maps.
Requires implementing methods for Φ, Φ∗, their gradients, Bregman divergence, and projection.
SquaredL2NormMirrorMap:
Implements the mirror map using the squared L2-norm.
Suitable for Euclidean spaces.
The projection method requires the user to provide the projection logic based on constraints.
NegativeEntropyMirrorMap:
Implements the mirror map using negative entropy, making it suitable for probability distributions (simplex).
Bregman divergence corresponds to the Kullback-Leibler (KL) divergence.
The projection method projects onto the simplex by normalizing the exponentiated gradient step.
MirrorDescent Class:
Encapsulates the Mirror Descent optimization process.
Initializes with a specified mirror map, step size, and optional constraints.
Provides methods to perform projection and iterative optimization steps.
The optimize method runs the algorithm for a specified number of iterations, updating the solution at each step.
Projection Functions:
euclidean_projection_simplex: Projects a tensor onto the simplex using an efficient algorithm.
SimplexProjectionConstraint: A callable class that utilizes the projection function for constraints.
Example Functions:
example_squared_l2_norm: Demonstrates minimizing a quadratic function subject to an L2-norm constraint using the squared L2-norm mirror map.
example_negative_entropy: Demonstrates minimizing a linear function over the simplex using the negative entropy mirror map.
main Function:
Executes the example functions when the script is run directly.
Running the Code
Ensure you have PyTorch installed. If not, install it using:
bash
pip install torch
Run the script using:
bash
python mirror_descent.py
You should observe logs indicating the progress of the optimization, along with the optimized variables and objective values.
Customization
Mirror Maps: To implement a new mirror map, inherit from MirrorMap and define the required methods.
Step Size: The MirrorDescent class accepts either a constant step size or a function that defines the step size as a function of the iteration number.
Constraints: Define custom projection logic by passing a callable that projects tensors onto your desired convex set.
Error Handling
The code includes checks to ensure that projections are feasible and that gradients are computable.
Raises informative errors if constraints are not provided where necessary or if input tensors are invalid.
Optimization
Utilizes PyTorch tensors for efficient computation.
Avoids unnecessary computations by leveraging in-place operations and cloning tensors when necessary.
Conclusion
This implementation provides a flexible and efficient framework for performing Mirror Descent optimization using PyTorch. By adhering to best practices and ensuring modularity, it can be easily extended and integrated into larger machine learning pipelines or optimization tasks.