Optax Documentation

repository·main·Indexed 25 days ago

https://github.com/google-deepmind/optax

A gradient processing and optimization library for JAX. Optax provides composable building blocks for creating custom optimizers and loss functions, featuring a wide range of optimizers (such as Adam, SGD, and Lion), gradient transformations for scaling and clipping, and various learning rate schedules. It includes specialized modules for microbatching, constrained optimization via projections, and experimental algorithms in optax.contrib.

Tokens
22.9K
Snippets
52
Records
102
Agent score
81%

What's inside Optax

  1. Explore Optax Gradient Transformations

    main

    Optax provides a wide variety of gradient transformations that can be composed to create complex optimizers. These transformations modify gradients before they are applied to parameters.

    Common categories of transformations include:

    • Scaling: Adjusting gradient magnitude using methods like scale_by_adam, scale_by_lion, scale_by_rms, or scale_by_learning_rate.
    • Clipping: Preventing exploding gradients using clip, clip_by_global_norm, or adaptive_grad_clip.
    • Noise/Regularization: Adding stochasticity via add_noise or managing weight decay with add_decayed_weights.
    • State Management: Using ema (Exponential Moving Average) or snapshot to track statistics.
    • Masking/Conditional: Using conditionally_mask or selective_transform to apply updates only to specific parameters.

    Each transformation typically returns an OptState (or a specific state like ScaleByAdamState) which must be maintained and passed back into the optimizer during training loops.

  2. Use experimental algorithms in optax.contrib

    main
    The optax.contrib module contains algorithms, wrappers, and experimental optimizers that do not yet meet the core library's inclusion criteria or are not supported by the main library. These are useful for testing cutting-edge optimization techniques, but users should be aware they may be less stable or subject to change compared to the core Optax API.
  3. Use microbatching in Optax

    main

    Optax provides utilities in optax.microbatching to handle microbatching, which is useful for managing memory constraints during training by breaking down large batches into smaller sub-batches.

    Key components available in this module include:

    • microbatch: The primary utility for microbatching operations.
    • micro_vmap: A version of jax.vmap designed for microbatching.
    • micro_grad: A version of jax.grad designed for microbatching.
    • reshape_batch_axis: A utility to manipulate batch axes for microbatching.
    • AccumulationType: An enumeration defining how gradients or states are accumulated.
    • Accumulator: An abstraction for managing the accumulation of values across microbatches.
  4. Use Optimizer Wrappers in Optax

    main

    Optax provides several wrapper functions to modify the behavior of existing optimizers. These wrappers allow you to add logic such as skipping updates when gradients are not finite, applying lookahead mechanisms, or masking certain updates.

    Commonly used wrappers include:

    • apply_if_finite: Only applies the optimizer update if the gradients are finite.
    • lookahead: Implements the lookahead optimization algorithm.
    • masked: Applies the optimizer update only to specific indices or elements.
    • skip_large_updates: Skips updates if the gradient magnitude exceeds a certain threshold.
    • skip_not_finite: Skips updates if gradients contain NaNs or Infs.
    • MultiSteps: Wraps an optimizer to perform multiple steps of the inner optimizer for every single step of the outer optimizer.

    When using these wrappers, you will typically interact with their associated State objects (e.g., ApplyIfFiniteState, LookaheadState, MaskedState, MultiStepsState) to manage the internal statistics required by the wrapper.

  5. Use perturbations in Optax

    main

    Optax provides tools in the optax.perturbations module to apply stochastic noise to functions or parameters. This is typically used in research settings to explore the landscape of a function or to implement specific types of stochastic optimization.

    Available tools include:

    • make_perturbed_fun: A utility to create a perturbed version of a function.
    • Gumbel: A perturbation based on the Gumbel distribution.
    • Normal: A perturbation based on the Normal (Gaussian) distribution.
  6. Perform constrained optimization using projections

    main

    Optax provides projection functions in optax.projections to perform constrained optimization. A projection onto a set $\mathcal{C}$ finds the closest point $v$ in that set to a given point $u$ by minimizing the squared Euclidean distance: $\text{proj}{\mathcal{C}}(u) := \text{argmin}{v} |u - v|^2_2$ subject to $v \in \mathcal{C}$.

    In a typical training loop, you apply the projection to your parameters immediately after applying the optimizer updates to ensure the parameters remain within the desired constraint set.

    import optax
    import jax
    import jax.numpy as jnp
    
    # Example: Projecting parameters to the non-negative orthant
    num_weights = 2
    xs = jnp.array([[-1.8, 2.2], [-2.0, 1.2]])
    ys = jnp.array([0.5, 0.8])
    optimizer = optax.adam(learning_rate=1e-3)
    params = {'w': jnp.zeros(num_weights)}
    opt_state = optimizer.init(params)
    
    loss = lambda params, x, y: jnp.mean((params['w'].dot(x) - y) ** 2)
    
    # Standard update step
    grads = jax.grad(loss)(params, xs, ys)
    updates, opt_state = optimizer.update(grads, opt_state)
    params = optax.apply_updates(params, updates)
    
    # Apply projection to enforce non-negativity
    params = optax.projections.projection_non_negative(params)
  7. Use optimizer schedules in Optax

    main

    Optax provides a variety of schedules in optax.schedules to control how hyperparameters (like learning rates) change over time. These schedules are typically used as arguments to optimizer functions.

    Commonly available schedules include:

    • Linear/Polynomial: linear_schedule, polynomial_schedule.
    • Decay-based: exponential_decay, cosine_decay_schedule.
    • Warmup-based: warmup_constant_schedule, warmup_cosine_decay_schedule, warmup_exponential_decay_schedule.
    • Cyclic/One-cycle: cosine_onecycle_schedule, linear_onecycle_schedule.
    • Piecewise: piecewise_constant_schedule, piecewise_interpolate_schedule.
    • Stochastic/Advanced: sgdr_schedule (Stochastic Gradient Descent with Restarts).
    • Composition: join_schedules allows combining multiple schedules.

    All schedules follow the Schedule abstraction, which typically takes a step count as input and returns the scheduled value.

  8. Quickstart: Basic Optimization Loop

    main

    Optax provides building blocks for optimizers and loss functions. A typical workflow involves:

    1. Initializing the optimizer: Use an optimizer function (e.g., optax.adam) and call .init(params) to obtain the initial opt_state.
    2. Computing gradients: Use JAX (e.g., jax.grad) to compute gradients of a loss function with respect to your parameters.
    3. Updating gradients: Use optimizer.update(grads, opt_state) to compute the updates and the new opt_state.
    4. Applying updates: Use optax.apply_updates(params, updates) to apply the computed updates to your parameters.

    Note: opt_state contains the statistics (like momentum or moving averages) required by the optimizer.

  9. Build Optax documentation locally

    main

    Optax documentation is written using Sphinx. To build the documentation on your local machine, follow these steps:

    1. Install requirements: Install the package in editable mode with the [docs] extra.
    2. Build the HTML: Use make within the docs directory.

    There are two build modes:

    • make html -C docs: Builds the complete documentation, including running all examples.
    • make html-noplot -C docs: A faster build that skips running the code examples.
  10. Apply updates to parameters using optax

    main

    Optax provides several ways to apply updates (gradients or other update directions) to model parameters. The primary functions for this purpose are:

    • apply_updates: The standard way to apply updates to parameters.
    • incremental_update: Used for applying updates in an incremental fashion.
    • periodic_update: Used for applying updates at specific intervals.
  11. Explore the Optax Example Gallery

    main

    The Optax example gallery provides a collection of practical implementations and research-oriented use cases. These examples demonstrate how to use Optax for standard deep learning tasks, integration with other libraries like Flax, and advanced optimization techniques.

    Core Examples include:

    • Standard Training: MLP classifier on MNIST, ResNet on CIFAR10 (with Flax), and Character-level Transformers.
    • Advanced Optimization: Gradient Accumulation, Meta-Learning, Optimistic Gradient Descent (OGDA), LBFGS with linesearch, and Lookahead wrappers.
    • Specialized Tasks: Adversarial training, solving linear assignment problems, and differentiable functions with perturbations.

    Contribution-based Examples (using optax.contrib):

    • Differential Privacy: Differentially private SGD for CNNs on MNIST.
    • Learning Rate Schedulers: Usage of reduce_on_plateau.
    • Advanced Algorithms: Sharpness-Aware Minimization (SAM) and AdEMAMix.
  12. Install Optax

    main

    You can install the latest released version of Optax from PyPI or install the latest development version directly from GitHub.

    To install from PyPI:

    pip install optax

    To install the development version from GitHub:

    pip install git+https://github.com/google-deepmind/optax.git