Skip to content

Migrate VAE example from flax.linen to flax.nnx - #5662

Open
simethan wants to merge 1 commit into
google:mainfrom
simethan:fix/vae-example-nnx-5068
Open

simethan wants to merge 1 commit into
google:mainfrom
simethan:fix/vae-example-nnx-5068

Conversation

@simethan

Copy link
Copy Markdown

Description

Migrates the VAE example (examples/vae) from flax.linen to flax.nnx, as requested in #5068.

  • Reimplements Encoder, Decoder, and the VAE wrapper as nnx.Module with nnx.Linear, keeping the original architecture (784 → 500 → latent 20 → 500 → 784) and parameter count (815,824, identical to the linen version).
  • Replaces flax.training.train_state.TrainState with nnx.Optimizer (optax.adam), and apply()-based training/eval with direct model calls under @nnx.jit. Randomness for the reparameterization trick uses nnx.Rngs.
  • Loss (binary cross-entropy with logits + KL divergence), optimizer, hyperparameters, and the binarized-MNIST data pipeline are unchanged.
  • Adds examples/vae/train_test.py (model forward/generate, metrics, train-step loss decrease, eval output shapes) and bumps the example's flax requirement from 0.6.9 (which predates nnx) to 0.9.0.

Note: examples/nnx_toy_examples/05_vae.py is a separate minimal demo and is left untouched; this PR migrates the full training example in examples/vae as the issue asks. train_step uses @nnx.jit, following the in-repo nnx examples (examples/mnist/train.py); happy to switch to jax.jit if preferred.

Fixes #5068

Test evidence

  • New examples/vae/train_test.py: 4 tests, all passing.
  • End-to-end run of train_and_evaluate on real binarized MNIST (2 epochs, batch 128, CPU): epoch 1 loss 119.81, epoch 2 loss 112.18 — decreasing and on trajectory for the README's ~104 after 10 epochs.
  • ruff check and ruff format --check clean on the changed files.

Generated by AI tools, and reviewed by Ethan Sim.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Migrate vae example from flax.linen to flax.nnx

1 participant