nnx.EMA.update fails when the model holds RNG state (e.g. nnx.Dropout with rngs)

Aperta
#5,601 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 3 giorni

@Arthur031221 ci sta già lavorando.

Dal 28/9/2026.

  • #5603 di @Arthur031221 — aperta

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

Start in flax/nnx/training/ema.py at _update_ema and inspect tests/nnx/ema_test.py, then compare the EMA docstring and optimization cookbook examples. Reproduce the failure with the provided Model containing Dropout and RNG state, including the jitted update path. Done means EMA updates work without corrupting or averaging RNG state, while the intended handling of integer Variables is covered by tests.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

System information
  • OS Platform and Distribution: Linux x86_64
  • Flax, jax, jaxlib versions: flax 0.12.10, jax 0.11.2, jaxlib 0.11.2 (PyPI wheels)
  • Python version: 3.12.13
  • GPU/TPU model and memory: none, run with JAX_PLATFORMS=cpu
  • CUDA version (if applicable): n/a
Problem you have encountered:

nnx.EMA defaults to only=..., so it copies every Variable in the model, including the RngKey and RngCount that nnx.Dropout(..., rngs=rngs) keeps. EMA.update then runs decay * ema + (1 - decay) * update on those too. For the uint32 count JAX warns that a float32 value is being written into it, and for the key it raises:

TypeError: multiply does not accept dtypes float32, key<fry>.

A module that stores self.rngs = rngs fails the same way. So the usage in the EMA docstring and the optimization cookbook breaks on the first update once the model carries RNG state. The docstring, the cookbook and tests/nnx/ema_test.py only use nnx.Linear (or an nnx.Sequential of them), which has none.

What you expected to happen:

update works on a model with dropout, averaging the parameters (and batch stats, as the default does today) and leaving RNG state alone.

Passing only=nnx.Param or only=nnx.Not(nnx.RngState) avoids the error today, including inside a jitted step that calls nnx.grad, optimizer.update and ema.update.

Logs, error messages, etc:

Output of the script below on flax 0.12.10 (traceback trimmed):

.../jax/_src/ops/scatter.py:105: FutureWarning: scatter inputs have incompatible types: cannot safely cast value from dtype=float32 to dtype=uint32 with jax_numpy_dtype_promotion=standard. In future JAX releases this will result in an error.
  warnings.warn(
Traceback (most recent call last):
  File ".../issue_repro.py", line 10, in <module>
    ema.update(model)
  ...
  File ".../flax/nnx/training/ema.py", line 138, in _update_ema
    ema[...] = self.decay * ema + (1.0 - self.decay) * update
  ...
TypeError: multiply does not accept dtypes float32, key<fry>.
Steps to reproduce:
from flax import nnx

class Model(nnx.Module):
  def __init__(self, rngs):
    self.linear = nnx.Linear(2, 2, rngs=rngs)
    self.dropout = nnx.Dropout(0.1, rngs=rngs)

model = Model(nnx.Rngs(0))
ema = nnx.EMA(model, decay=0.9)
ema.update(model)

Two ways to fix it that I tried, on a model with Linear, BatchNorm, Dropout, an integer nnx.Variable step counter and an nnx.Param(1.0):

  1. Default only to nnx.Not(nnx.RngState). Batch stats are still tracked and apply_to uses the model's own RNG state. Integer Variables are still averaged, though: the step counter at 10 comes out as 1 in the EMA model, with the same kind of cast warning for int32.

  2. Keep only=... and also drop non-floating Variables when choosing what to track:

    def _is_inexact(path, x) -> bool:
      if not isinstance(x, variablelib.Variable):
        return True
      return jnp.issubdtype(jnp.result_type(x.get_value()), jnp.inexact)
    
    # in EMA.__init__
    self.filter = filterlib.All(only, _is_inexact)
    # ... and use self.filter instead of only in the graphlib.state call
    

    Batch stats and the Python-float Param are still tracked, and RNG state and the step counter aren't, so the EMA model shows the model's live values for them (count and step match the model after a train-mode call). Non-Variable leaves still reach the existing TypeError in _to_ema_param. This also applies on top of an explicit only: with only=nnx.PathContains('step') the release averages the counter (10 becomes 1, with the int32 cast warning), and with this change nothing is tracked.

I'm not sure which one fits the intended meaning of the default better.

Lingua principale
Jupyter Notebook
Stelle
7.4k
Fork
855
Merge medio
3g 3h
PR unite (30g)
5

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di google/flax

Tutte le issue di google/flax

Issue simili

Altre issue su Machine Learning

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.