🔪 Flax - The Sharp Bits 🔪
Flax exposes the full power of JAX. And just like when using JAX, there are certain "sharp bits" you may experience when working with Flax. This evolving document is designed to assist you with them.
First, install and/or update Flax:
🔪 flax.linen.Dropout layer and randomness
TL;DR
When working on a model with dropout (subclassed from Flax Module), add the 'dropout' PRNGkey only during the forward pass.
- Start with
jax.random.split()to explicitly create PRNG keys for'params'and'dropout'. - Add the
flax.linen.Dropoutlayer(s) to your model (subclassed from FlaxModule). - When initializing the model (
flax.linen.init()), there's no need to pass in an extra'dropout'PRNG key—just the'params'key like in a "simpler" model. - During the forward pass with
flax.linen.apply(), pass inrngs={'dropout': dropout_key}.
Check out a full example below.
Why this works
- Internally,
flax.linen.Dropoutmakes use offlax.linen.Module.make_rngto create a key for dropout (check out the source code). - Every time
make_rngis called (in this case, it's done implicitly inDropout), you get a new PRNG key split from the main/root PRNG key. make_rngstill guarantees full reproducibility.
Background
The dropout stochastic regularization technique randomly removes hidden and visible units in a network. Dropout is a random operation, requiring a PRNG state, and Flax (like JAX) uses Threefry PRNG that is splittable.
Note: Recall that JAX has an explicit way of giving you PRNG keys: you can fork the main PRNG state (such as
key = jax.random.key(seed=0)) into multiple new PRNG keys withkey, subkey = jax.random.split(key). Refresh your memory in 🔪 JAX - The Sharp Bits 🔪 Randomness and PRNG keys.
Flax provides an implicit way of handling PRNG key streams via Flax Module's flax.linen.Module.make_rng helper function. It allows the code in Flax Modules (or its sub-Modules) to "pull PRNG keys". make_rng guarantees to provide a unique key each time you call it. See the RNG guide for more details.
Note: Recall that
flax.linen.Moduleis the base class for all neural network modules. All layers and models are subclassed from it.
Example
Remember that each of the Flax PRNG streams has a name. The example below uses the 'params' stream for initializing parameters, as well as the 'dropout' stream. The PRNG key provided to flax.linen.init() is the one that seeds the 'params' PRNG key stream. To draw PRNG keys during the forward pass (with dropout), provide a PRNG key to seed that stream ('dropout') when you call Module.apply().
Real-life examples:
- Applying word dropout to a batch of input IDs (in a text classification context).
- Defining a prediction token in a decoder of a sequence-to-sequence model.