Metadata-Version: 2.4
Name: opttx
Version: 0.1.0a4
Summary: JAX/Flax/Optax optimizer manager
Author: Tianshi Xu
License: MIT License
        
        Copyright (c) 2025 Tianshi Xu
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/Hitenze/opttx
Project-URL: Repository, https://github.com/Hitenze/opttx
Project-URL: Issues, https://github.com/Hitenze/opttx/issues
Keywords: jax,optax,flax,optimizer
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: jax>=0.4.20
Requires-Dist: jaxlib>=0.4.20
Requires-Dist: optax>=0.2.3
Requires-Dist: flax>=0.8.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Dynamic: license-file

# OptTx

> **Research Code**: Co-developed with Claude Code, Gemini CLI, Codex CLI, and Cursor. No guarantees provided. Use at your own risk.

JAX/Flax/Optax optimizer library for PINNs and second-order methods.

## Features

- **Multi-term objectives**: `Objective` with `TermSpec` for PINNs (PDE, BC, IC terms)
- **First-order optimizers**: Adam, SGD, AdamW, SOAP, MUON, Shampoo, L-BFGS
- **Second-order optimizers**: CGOptimizer and CROptimizer with exact Hessian,
  generalized Gauss-Newton (GGN), or empirical Fisher curvature
- **Acceleration methods**: TGS, NLTGCR, Anderson Acceleration (AA)
- **Graph neural networks**: GCN, GAT layers for node classification
- **Matrix-free curvature**: Hessian, GGN, and empirical Fisher matvecs
- **JIT-stable**: Works with `jax.jit` and `jax.lax.scan`

## Install

```bash
pip install opttx
```

For development:
```bash
pip install -e .[dev]
```

## Quickstart

### First-order optimizer

```python
import jax
import jax.numpy as jnp
from flax import linen as nn

from opttx import Adam, Objective, TermSpec, TrainState

# Define model
class MLP(nn.Module):
    @nn.compact
    def __call__(self, x):
        x = nn.Dense(32)(x)
        x = nn.relu(x)
        x = nn.Dense(1)(x)
        return x

# Define loss
def mse_loss(pred, batch):
    x, y = batch
    return jnp.mean((pred - y) ** 2)

# Create objective
term = TermSpec(name="mse", batch_key="data", loss_fn=mse_loss)
objective = Objective(terms=[term])

# Initialize
model = MLP()
params = model.init(jax.random.PRNGKey(0), jnp.ones((1, 3)))["params"]

state = TrainState(
    step=jnp.array(0),
    params=params,
    opt_state=None,
    apply_fn=lambda v, b: model.apply({"params": v["params"]}, b[0]),
)

# Create optimizer and train
optimizer = Adam(objective, learning_rate=1e-3)
state = optimizer.init(state)

batch = {"data": (jnp.ones((8, 3)), jnp.zeros((8, 1)))}
state, metrics = optimizer.step(state, batch)
print(f"Loss: {metrics['loss']}")
```

### Second-order optimizer (CR + Hessian)

```python
from opttx import CROptimizer

optimizer = CROptimizer(
    objective,
    learning_rate=1.0,
    damping=1e-3,
    cr_iters=10,
    curvature_type="hessian",  # or "fisher" (GGN), or "efisher"
)
state = optimizer.init(state)
state, metrics = optimizer.step(state, batch)
```

### Multi-term objective (PINNs)

```python
def pde_loss(pred, batch):
    return jnp.mean(pred ** 2)

def bc_loss(pred, batch):
    return jnp.mean(pred ** 2)

pde_term = TermSpec(name="pde", batch_key="x_pde", loss_fn=pde_loss)
bc_term = TermSpec(name="bc", batch_key="x_bc", loss_fn=bc_loss)

objective = Objective(
    terms=[pde_term, bc_term],
    loss_weights={"pde": 1.0, "bc": 0.1},
)

batch = {
    "x_pde": jnp.ones((100, 2)),
    "x_bc": jnp.ones((20, 2)),
}
```

### Dynamic hyperparameters (JIT-friendly)

Learning rate, damping, weight decay and CG/CR tolerance can change during a
`jax.jit`-compiled run **without recompilation**. Two mechanisms share one
resolution rule: `override > schedule > plain float`.

**Schedules** — pass a `Callable(step) -> scalar` (any Optax schedule works, or
the built-in `warmup_schedule`):

```python
import optax
from opttx import Adam, warmup_schedule

opt = Adam(objective, learning_rate=optax.cosine_decay_schedule(1e-3, decay_steps=10_000))
opt = Adam(objective, learning_rate=warmup_schedule(1e-3, warmup_steps=500))
```

**Runtime overrides** — pass a flat dict as the third argument to `step`; the
values are traced as jit inputs, so a sweep or a plateau controller runs on a
single compilation:

```python
jit_step = jax.jit(opt.step)
for lr in [1e-2, 1e-3, 1e-4]:          # no recompilation across values
    state, metrics = jit_step(state, batch, {"learning_rate": lr})
```

Second-order optimizers additionally accept `damping` (and `cg_tol` / `cr_tol`):

```python
opt = CGOptimizer(objective, learning_rate=1.0, damping=1e-3, curvature_type="fisher")
jit_step = jax.jit(opt.step)  # re-jit: jit_step above is bound to the Adam step
state, metrics = jit_step(state, batch, {"damping": 1e-2, "cg_tol": 1e-6})
```

Each optimizer exposes its runtime-adjustable knobs via `DYNAMIC_HPARAMS`.
Structural knobs (`cg_iters`, `memory_size`, `ns_steps`, `max_precond_dim`,
`curvature_type`, `precond`, `qn_window`, `qn_reset_tau`, ...) stay static and are rejected
fast if passed as an override or schedule. `OptaxOptimizer` supports overrides when its transform is
built with `optax.inject_hyperparams`; `LBFGSOptimizer` exposes none (its step
size is line-search controlled).

**Effective-value logging** — `metrics` carries `hparams/learning_rate`,
`hparams/damping`, etc., and the objective logs raw per-term losses
(`loss/<term>`) alongside effective per-term weights (`weight/<term>`), so raw
terms, their weighting, and the optimizer knobs can be plotted separately.

**Step-reset hazards (staged optimization)** — a schedule keyed on `state.step`
stays continuous when you hand `state` from one optimizer to another, because
the global step keeps advancing. Two optimizer-internal clocks do *not* follow
`state.step`, though: calling `optimizer.init(state)` resets the wrapped optax
count for `LBFGSOptimizer` (its L-BFGS curvature memory restarts) and any
`OptaxOptimizer` transform built with a *native* optax schedule (that schedule
advances on optax's own count, not on `state.step`). Prefer OptTx's
`Callable(step)` schedules or runtime `hparams` when you need a knob tied to the
global step across a staged hand-off.

See [`examples/dynamic_lr.py`](https://github.com/Hitenze/opttx/blob/main/examples/dynamic_lr.py)
for a full walkthrough including a cosine schedule, a no-recompile LR sweep, and
staged optimization.

## API Reference

### Optimizers

| Optimizer | Description |
|-----------|-------------|
| `Adam` | Adam optimizer |
| `SGD` | SGD with momentum |
| `AdamW` | Adam with weight decay |
| `SOAP` | Second-order approximation |
| `MUON` | Momentum with orthogonalization |
| `Shampoo` | Shampoo preconditioner |
| `LBFGSOptimizer` | L-BFGS quasi-Newton |
| `CGOptimizer` | Conjugate Gradient with Hessian, GGN, or empirical Fisher; optional recycled QN preconditioner (`precond="qn"`) |
| `CROptimizer` | Conjugate Residual with Hessian, GGN, or empirical Fisher |
| `TGSOptimizer` | TGS acceleration |
| `TGSAccelerator` | TGS wrapper for any optimizer |
| `AAAccelerator` | Anderson Acceleration wrapper |
| `NLTGCROptimizer` | Nonlinear truncated GCR |

### Curvature

| Function | Description |
|----------|-------------|
| `build_hessian_matvec` | Matrix-free Hessian-vector product |
| `build_fisher_matvec` | Matrix-free generalized Gauss-Newton-vector product |
| `build_efisher_matvec` | Matrix-free empirical-Fisher-vector product |
| `build_damped_matvec` | Add damping: (H + λI)v |

The public selector `curvature_type="fisher"` is retained for compatibility,
but it computes the generalized Gauss-Newton matrix
`sum_t w_t J_t^T H_t J_t`, not the statistical Fisher. The empirical Fisher
selector is `curvature_type="efisher"` and computes
`sum_t (w_t / N_t) sum_i g_ti g_ti^T`, with `g_ti` the gradient of a
per-sample loss. Term weights are linear (`w_t`, not `w_t**2`).

The GGN is positive semi-definite for output-convex losses and non-negative
term weights; the empirical Fisher is positive semi-definite for non-negative
term weights. Empirical Fisher terms must be sample-separable, mean-reduced
over axis 0, and use an array or flat tuple as their term batch. These
assumptions are documented rather than checked at runtime.

### Solvers

| Function | Description |
|----------|-------------|
| `cg_solve` | Conjugate Gradient solver |
| `pcg_solve` | Preconditioned CG; harvests (p, Ap) curvature pairs |
| `cr_solve` | Conjugate Residual solver |
| `tgs_solve_fori` | TGS solver (JIT-compatible) |
| `nltgcr_solve_fori` | NLTGCR solver (JIT-compatible) |

`CGOptimizer(..., precond="qn")` recycles the previous steps' CG directions
and their curvature images into an L-BFGS-style preconditioner
(Morales & Nocedal, 2000) at zero extra matvecs per step — the memory rolls
over every `qn_window` steps (default 1: fully overwritten each step), so
staleness is structurally bounded and an SPD preconditioner cannot break
CG's correctness. It pays off at small iteration budgets on ill-conditioned
objectives (typical PINN GGN spectra), is a harmless no-op on
well-conditioned problems, and requires a PSD curvature
(`fisher`/`efisher`). `qn_window=k` retains the last `k` steps' whole
`(p, Ap)` harvests as a ring of blocks (never mixed, each pair keeps its
secant identity): wider curvature coverage, and under minibatch resampling
the recycled metric is averaged over the last `k` batches — `qn_window=2`
is a good first try on hard problems, at a `k`-fold longer two-loop and
`k`-fold pair memory (matvec count unchanged).
The `qn/q0` metric reports preconditioner health
(≈ 1 when the recycled metric matches the current operator); the optional
`qn_reset_tau` gate clears the memory on order-of-magnitude `q0` excursions
(transient smoothing for known operator shocks, off by default).

### Models

| Model | Description |
|-------|-------------|
| `GCN` | Graph Convolutional Network |
| `GCNLayer` | Single GCN layer |
| `GAT` | Graph Attention Network |
| `GATLayer` | Single GAT layer |
| `normalize_adjacency` | Symmetric adjacency normalization |

## Float32 on GPU: force full-precision matmuls

On Ampere-or-newer NVIDIA GPUs, XLA silently runs float32 matmuls on TF32
tensor cores (10-bit mantissa). PINN-style nested derivatives and curvature
matvecs amplify that rounding into the training signal: on ill-conditioned
problems TF32 caps the reachable loss orders of magnitude above the true
float32 optimum — for every optimizer, Adam included. When training in
float32 on GPU, set

```python
jax.config.update("jax_default_matmul_precision", "highest")
```

(or export `JAX_DEFAULT_MATMUL_PRECISION=highest`). In our PINN benchmarks
this restores float64-level final losses at roughly 10–15% per-step overhead,
while float32 itself remains several times faster per step than float64.
OptTx never sets this globally on your behalf.

## Design Constraints

- `state.step` must be a scalar `jax.Array` (never Python int)
- Metrics have static string keys and scalar values
- Must include `"loss"` key in metrics
- Multi-term + `batch_stats` is not supported

## Citation

If you use OptTx in your research, please cite the software:

```bibtex
@software{xu2026opttx,
  author={Xu, Tianshi},
  title={OptTx: JAX/Flax/Optax optimizer library for PINNs and second-order methods},
  year={2026},
  url={https://github.com/Hitenze/opttx}
}
```

along with the papers behind the methods:

**Anderson Acceleration with Truncated Gram-Schmidt** (SIMAX 2024)
```bibtex
@article{tang2024anderson,
  title={Anderson Acceleration with Truncated Gram-Schmidt},
  author={Tang, Ziyuan and Xu, Tianshi and He, Huan and Saad, Yousef and Xi, Yuanzhe},
  journal={SIAM Journal on Matrix Analysis and Applications},
  volume={45},
  number={4},
  pages={1850--1872},
  year={2024},
  doi={10.1137/24M1648600}
}
```

**Design Criteria for SGD Preconditioners** (TMLR 2026)
```bibtex
@article{scott2026design,
  title={Design Criteria for {SGD} Preconditioners: Local Conditioning, Noise Floors, and Basin Stability},
  author={Scott, Mitchell and Xu, Tianshi and Tang, Ziyuan and Pichette-Emmons, Alexandra and Ye, Qiang and Saad, Yousef and Xi, Yuanzhe},
  journal={Transactions on Machine Learning Research},
  issn={2835-8856},
  year={2026},
  note={arXiv:2511.19716}
}
```

## License

MIT
