nnx_variable___nnx_variablestate

nnx_variable___nnx_variablestate is a cursor rule for Cursor from altaidevorg/rules-for-ai. It costs 28 tokens per session (4,620 once invoked), scanned A, original, MIT.

The two forms Flax NNX uses for values stored in a neural-network module. Variable is the changeable value inside the Python module, while VariableState is the immutable form used when working with JAX.

In plain words
What is it for?
Use them to store parameters, statistics, random state, or other module data, and to move that data into or out of JAX computations.
Why use it?
Neural-network code is easier to write with changeable object attributes, but JAX needs immutable data structures. These two forms bridge that difference.

Cursor rule for Cursor

Written for Cursor: a Cursor rule (.mdc).

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_variable___nnx_variablestate
Clone the repo
git clone --depth 1 https://github.com/altaidevorg/rules-for-ai

Made for: Cursor.

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_variable___nnx_variablestate

README.md
[![agentmods](https://agentmods.dev/badge/rules/altaidevorg/rules-for-ai/nnx_variable___nnx_variablestate.svg)](https://agentmods.dev/rules/altaidevorg/rules-for-ai/nnx_variable___nnx_variablestate)
Your own site
<a href="https://agentmods.dev/rules/altaidevorg/rules-for-ai/nnx_variable___nnx_variablestate"><img src="https://agentmods.dev/badge/rules/altaidevorg/rules-for-ai/nnx_variable___nnx_variablestate.svg" alt="Measured on agentmods" height="20"></a>
Per session 28 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 4,620 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.1 $0.00028 $0.04620
Opus 5 $0.00014 $0.02310
Sonnet 5 $0.00006 $0.00924
Haiku 4.5 $0.00003 $0.00462

Measured 5d ago against content hash 4eb6eeca5df0, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-06, from the pricing page.

Security

Grade A, and why

nnx_variable___nnx_variablestate 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 5d 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_variable___nnx_variablestate.mdc · 387 lines

How it starts

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

Chapter 2: nnx.Variable / nnx.VariableState

In the previous chapter, we introduced nnx.Module as the foundation for building stateful neural network components in Flax NNX. We saw that modules hold their state (like parameters) as attributes. This chapter delves into the core mechanism NNX uses to represent and manage this state: nnx.Variable and its immutable counterpart, nnx.VariableState.

Motivation: Bridging Stateful Objects and Functional JAX

JAX thrives on pure functions operating on immutable data structures (pytrees). However, defining complex models often feels more natural using stateful object-oriented programming. How can we reconcile these two paradigms?

NNX uses nnx.Variable to encapsulate state within the familiar, mutable nnx.Module object. When it's time to interact with JAX transformations (jit, grad, etc.), NNX extracts this state into an immutable pytree structure where the leaves are nnx.VariableState objects. This separation allows developers to work with intuitive stateful objects while ensuring compatibility with JAX's functional nature.

  • nnx.Variable: Lives inside the nnx.Module instance. It's a mutable container holding the actual state value (e.g., a JAX array) and associated metadata. You interact with it directly when defining or updating the module's state.
  • nnx.VariableState: Exists outside the module instance, typically as part of the State pytree returned by nnx.split or nnx.state. It's an immutable snapshot of a Variable's value and metadata, suitable for use in JAX-transformed functions.

Central Use Case: Defining and Managing Different State Types

Let's enhance our nnx.Module with different kinds of state using various nnx.Variable subclasses.

import jax
import jax.numpy as jnp
from flax import nnx
from flax.nnx.nn import initializers

# Define needed RNGs
rngs = nnx.Rngs(0)

class StatefulComponent(nnx.Module):
  def __init__(self, features: int, *, rngs: nnx.Rngs):
    # Learnable parameters
    self.weight = nnx.Param(
        initializers.lecun_normal()(rngs.params(), (features, features))
    )
    self.bias = nnx.Param(initializers.zeros_init()(rngs.params(), (features,)))
    
    # Batch statistics (e.g., for BatchNorm)
    self.running_mean = nnx.BatchStat(jnp.zeros((features,)))
    
    # RNG state (e.g., for Dropout)
    self.dropout_rng = nnx.RngState(rngs.dropout()) 
    
    # Custom state variable
    class StepCount(nnx.Variable): pass 
    self.steps = StepCount(0)

  def __call__(self, x: jax.Array):
    # Access variable values using .value
    output = jnp.dot(x, self.weight.value) + self.bias.value
    
    # Simulate using batch stats (simplified)
    # In reality, this would involve updating running_mean based on batch data
    output = output - self.running_mean.value 
    
    # Simulate using RNG state
    key = self.dropout_rng.value # Get current key
    key, subkey = jax.random.split(key)
    # In nnx.Dropout, the RngState variable is updated automatically
    # Here we simulate a manual update (not typical):
    # self.dropout_rng.value = key 
    noise = jax.random.normal(subkey, output.shape)
    output = output + noise
    
    # Update custom state
    self.steps.value += 1
    
    return output

  def update_mean(self, new_mean: jax.Array):
    # Directly mutate the Variable's value
    self.running_mean.value = new_mean

# Instantiate
component = StatefulComponent(features=4, rngs=rngs)

# Create dummy input
x = jnp.ones((1, 4))

# Call the component (modifies internal state)
y = component(x)
print(f"Initial step count: {component.steps.value}")
y = component(x)
print(f"Step count after second call: {component.steps.value}")

# Update a variable directly
component.update_mean(jnp.ones(4) * 0.1)
print(f"Updated running mean: {component.running_mean.value}")

# --- Interaction with Functional API ---

# Split the component into structure (GraphDef) and state (State)
graphdef, state = nnx.split(component)

print("\nExtracted State (containing VariableState objects):")
# Note: Output structure matches module attributes. Leaves are VariableState.
print(state) 

# The 'state' object is an immutable pytree suitable for JAX functions
# We can inspect the type and value of a specific state leaf
print(f"\nWeight state type: {type(state['weight'])}")
print(f"Weight value shape: {state['weight'].value.shape}")

# Reconstruct the component using nnx.merge
reconstructed_component = nnx.merge(graphdef, state)
print(f"\nReconstructed step count: {reconstructed_component.steps.value}")
assert component.steps.value == reconstructed_component.steps.value

Read the full file on GitHub · 387 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. 5d ago First seen · 387 lines · 28 tokens per session scan A 4eb6eeca5df0

Subscribe to this mod's changes

nnx_variable___nnx_variablestate is a cursor rule published in the GitHub repository altaidevorg/rules-for-ai (2 stars, last pushed 1y ago), licensed MIT. It adds 28 tokens to every session and 4,620 once invoked, about $0.0001 per session on Opus 5. 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.