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.
npx agentmods add rules/altaidevorg/rules-for-ai/nnx_variable___nnx_variablestategit clone --depth 1 https://github.com/altaidevorg/rules-for-aiWrote 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.
[](https://agentmods.dev/rules/altaidevorg/rules-for-ai/nnx_variable___nnx_variablestate)<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>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.
| Model | Per session | Once 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 |
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.
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 thennx.Moduleinstance. 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 theStatepytree returned bynnx.splitornnx.state. It's an immutable snapshot of aVariable'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
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.
- 5d ago First seen · 387 lines · 28 tokens per session scan A 4eb6eeca5df0
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.
Other cursor rules, from other repositories
llm-layer
LLM provider implementation patterns.
tensorflow
TensorFlow: Keras, model training, production deployment.
cursorrules
Cursor rule "cursorrules" from Clarity-Digital-Twin/brain-go-brrr, covering .cursorrules - brain-go-brrr project (fixed architecture), rule #1: no parallel implementations ever, experiments/trainanything.py - must be thin, rule #2: check before building and rule #3: normalization is critical.
006_Program_of_Thought_Tutorial
DSPY 3 Program of Thought Tutorial - Production code reasoning system from official DSPy 3.0.1 tutorial.
standards-data-eng
Mandatory standards for Python and SQL data pipelines.
ponytail
Ponytail, lazy senior dev mode. Always pick the simplest solution that works.