nnx_optimizer

nnx_optimizer is a cursor rule for coding agents from altaidevorg/rules-for-ai. It costs 0 tokens per session (4,207 once invoked), scanned A, original, MIT.

A Flax NNX object that keeps a neural-network module together with Optax, a library for updating model parameters during training. It also stores the optimizer’s internal state and update rules.

In plain words
What is it for?
Use it to manage model parameters, gradients, optimizer updates, and optimizer state during neural-network training.
Why use it?
It gathers the model and training information that would otherwise need to be passed around separately in every training step. This reduces repetitive training-loop code.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/altaidevorg/rules-for-ai/nnx_optimizer
Clone the repo
git clone --depth 1 https://github.com/altaidevorg/rules-for-ai

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for nnx_optimizer

README.md
[![agentmods](https://agentmods.dev/badge/rules/altaidevorg/rules-for-ai/nnx_optimizer.svg)](https://agentmods.dev/rules/altaidevorg/rules-for-ai/nnx_optimizer)
Your own site
<a href="https://agentmods.dev/rules/altaidevorg/rules-for-ai/nnx_optimizer"><img src="https://agentmods.dev/badge/rules/altaidevorg/rules-for-ai/nnx_optimizer.svg" alt="Measured on agentmods" height="20"></a>
Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 4,207 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.04207
Opus 5 $0.00000 $0.02103
Sonnet 5 $0.00000 $0.00841
Haiku 4.5 $0.00000 $0.00421

Measured 3d ago against content hash f50c8f079e9b, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

nnx_optimizer scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 3d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

examples/flax/nnx_optimizer.mdc · 321 lines

How it starts

The opening of the file, as written. The whole thing — 321 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Chapter 8: nnx.Optimizer

In the previous chapter, we examined the internal GraphDef and GraphState representations used by the NNX Functional API (split/merge/state/update/graphdef). Now, we'll look at a practical helper class built upon these concepts that significantly simplifies the standard training loop structure in NNX: nnx.Optimizer.

Motivation: Simplifying Stateful Training Loops

A typical JAX training loop involves managing several pieces of state: the model's parameters, the optimizer's internal state (e.g., momentum vectors), and potentially a step counter. While you can manage these separately using the functional API or standard Python variables, it often leads to boilerplate code for passing state around and applying updates.

Flax Linen introduced flax.training.TrainState to bundle these components. nnx.Optimizer serves a similar purpose in the NNX ecosystem. It's a stateful container, inheriting from nnx.Object, designed to hold an nnx.Module instance, the corresponding Optax optimizer state (opt_state), and the Optax gradient transformation (tx). This colocation simplifies the training process by providing a single object that manages both the model's learnable parameters and the optimizer's evolving state. Its primary update() method streamlines the application of gradients.

Central Use Case: A Standard Training Step

Let's illustrate how nnx.Optimizer simplifies a basic training step involving gradient computation and parameter updates.

import jax
import jax.numpy as jnp
from flax import nnx
import optax # Standard JAX optimizer library

class SimpleModel(nnx.Module):
  def __init__(self, din: int, dout: int, *, rngs: nnx.Rngs):
    self.linear = nnx.Linear(din, dout, rngs=rngs)

  def __call__(self, x: jax.Array) -> jax.Array:
    return self.linear(x)

# --- Setup ---
key = jax.random.key(0)
model_key, data_key = jax.random.split(key)
model = SimpleModel(din=10, dout=5, rngs=nnx.Rngs(model_key))

# Define Optax optimizer
tx = optax.adam(learning_rate=1e-3)

# 1. Instantiate nnx.Optimizer
#    It holds the model, the optimizer transformation (tx), 
#    and initializes the optimizer state internally.
optimizer = nnx.Optimizer(model, tx) 

x_batch = jax.random.normal(data_key, (32, 10))
y_batch = jnp.ones((32, 5)) # Dummy targets

# --- Loss Function ---
# Takes the *model* part of the optimizer as input
def loss_fn(model: SimpleModel, x: jax.Array, y: jax.Array):
  y_pred = model(x)
  loss = jnp.mean((y_pred - y) ** 2)
  return loss

# --- JITted Training Step ---
@nnx.jit # Use nnx.jit with nnx.Optimizer
def train_step(optimizer: nnx.Optimizer, x: jax.Array, y: jax.Array):
  # 2. Calculate gradients w.r.t. model's Params (default)
  #    Pass optimizer.model to the loss function
  grad_fn = nnx.value_and_grad(loss_fn)
  loss, grads = grad_fn(optimizer.model, x, y) 
  
  # 3. Apply gradients using optimizer.update()
  #    This updates optimizer.model parameters and optimizer.opt_state in-place.
  optimizer.update(grads)
  
  # optimizer object with updated state is returned by nnx.jit
  return loss, optimizer 

# --- Execute ---
print(f"Initial loss: {loss_fn(optimizer.model, x_batch, y_batch)}")

# Run one training step
# Note: nnx.jit returns a *new* optimizer instance with updated state
loss, updated_optimizer = train_step(optimizer, x_batch, y_batch) 

print(f"Loss after step: {loss}")
# Access the updated model via the returned optimizer
print(f"Loss after update (recomputed): {loss_fn(updated_optimizer.model, x_batch, y_batch)}") 

Read the full file on GitHub · 321 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 3d ago First seen · 321 lines · 0 tokens per session scan A f50c8f079e9b

Subscribe to this mod's changes

nnx_optimizer is a cursor rule published in the GitHub repository altaidevorg/rules-for-ai (2 stars, last pushed 1y ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 4,207 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.