Need a distinct JAX random key for each loop iteration without allocating all keys in advance? random.fold_in() combines an existing key with integer data and returns a statistically safe derived key. JAX keys are explicit state: reuse the same key when identical output is intended, and discard keys after consuming them. section 9.2.3 section 9.4
Derive keys inside a loop
key = random.PRNGKey(42) for i in range(5): new_key = random.fold_in(key, i) vals = random.normal(new_key, shape=(3, 5)) # use vals Each iteration produces a different key and random array. The integer may also represent stable data such as a layer identifier; convert strings to integers first, for example with a deterministic SHA-1-based hash. section 9.2.3
Listing 9.18 Using fold_in() to generate new keys
key = random.PRNGKey(42) #1 for i in range(5): new_key = random.fold_in(key, i) #2 print(new_key) vals = random.normal(new_key, shape=(3,5)) #3 # do something with values >>> [1832780943 270669613] >>> [ 64467757 2916123636] >>> [2465931498 255383827] >>> [3134548294 894150801] >>> [2954079971 3276725750]
Shows fold_in() deriving a fresh key from a loop index and using it with random.normal(). section 9.2.3
