Attention-based Neural Cellular Automata
¶
Installation¶
You will need Python 3.12 or later, and a working JAX installation. For example, you can install JAX with:
In [1]:
Copied!
%pip install -U "jax[cuda]"
%pip install -U "jax[cuda]"
/home/faldor_google_com/dev/cax/.venv/bin/python3: No module named pip
Note: you may need to restart the kernel to use updated packages.
Then, install CAX from PyPi:
In [2]:
Copied!
%pip install -U "cax[examples]"
%pip install -U "cax[examples]"
/home/faldor_google_com/dev/cax/.venv/bin/python3: No module named pip
Note: you may need to restart the kernel to use updated packages.
Import¶
In [3]:
Copied!
import time
import jax
import jax.numpy as jnp
import mediapy
import optax
import torchvision
from flax import nnx
from jax import Array
from cax.core import ComplexSystem
from cax.core.perceive import Perceive
from cax.core.update import ResidualUpdate
from cax.nn.pool import Pool
from cax.utils import clip_and_uint8
import time
import jax
import jax.numpy as jnp
import mediapy
import optax
import torchvision
from flax import nnx
from jax import Array
from cax.core import ComplexSystem
from cax.core.perceive import Perceive
from cax.core.update import ResidualUpdate
from cax.nn.pool import Pool
from cax.utils import clip_and_uint8
Configuration¶
In [4]:
Copied!
seed = 0
spatial_dims = (28, 28)
channel_size = 32
perception_size = 64
num_heads = 4
hidden_size = 128
proj_size = 32
cell_dropout_rate = 0.5
num_steps = 32
pool_size = 1_024
batch_size = 4
learning_rate = 1e-3
mask_ratio = 0.5
key = jax.random.key(seed)
rngs = nnx.Rngs(seed)
seed = 0
spatial_dims = (28, 28)
channel_size = 32
perception_size = 64
num_heads = 4
hidden_size = 128
proj_size = 32
cell_dropout_rate = 0.5
num_steps = 32
pool_size = 1_024
batch_size = 4
learning_rate = 1e-3
mask_ratio = 0.5
key = jax.random.key(seed)
rngs = nnx.Rngs(seed)
Dataset¶
In [5]:
Copied!
# Load MNIST dataset
ds_train = torchvision.datasets.MNIST(root="./data", train=True, download=True)
ds_test = torchvision.datasets.MNIST(root="./data", train=False, download=True)
# Convert to jax.Array
y_train = jnp.array([y.resize(spatial_dims) for y, _ in ds_train])[..., None] / 255
y_test = jnp.array([y.resize(spatial_dims) for y, _ in ds_test])[..., None] / 255
# Visualize
mediapy.show_images(y_train[:8].repeat(4, axis=-3).repeat(4, axis=-2))
# Load MNIST dataset
ds_train = torchvision.datasets.MNIST(root="./data", train=True, download=True)
ds_test = torchvision.datasets.MNIST(root="./data", train=False, download=True)
# Convert to jax.Array
y_train = jnp.array([y.resize(spatial_dims) for y, _ in ds_train])[..., None] / 255
y_test = jnp.array([y.resize(spatial_dims) for y, _ in ds_test])[..., None] / 255
# Visualize
mediapy.show_images(y_train[:8].repeat(4, axis=-3).repeat(4, axis=-2))
Instantiate system¶
In [6]:
Copied!
class ViTPerceive(Perceive[Array, Array]):
"""Vision Transformer Perceive class."""
def __init__(
self,
channel_size: int,
perception_size: int,
*,
num_heads: int,
hidden_size: int,
proj_size: int,
max_position_size: int,
position_embed_features: int = 4,
rngs: nnx.Rngs,
):
"""Initialize ViT Perceive."""
self.linear = nnx.Linear(
in_features=channel_size, out_features=proj_size, rngs=rngs
)
self.position_embed_features = position_embed_features
self.position_embed = nnx.Embed(
num_embeddings=max_position_size,
features=position_embed_features,
rngs=rngs,
)
self.attention = nnx.MultiHeadAttention(
num_heads=num_heads,
in_features=proj_size + 2 * position_embed_features,
qkv_features=hidden_size,
out_features=perception_size,
decode=False,
rngs=rngs,
)
def __call__(self, state: Array) -> Array:
"""Apply perception to the input state.
Args:
state: State of the cellular automaton.
Returns:
The perceived state after applying convolutional layers.
"""
# Linear projection of state into tokens
state = self.linear(state)
# Concatenate position embed
position_embed_h = self.position_embed(jnp.arange(state.shape[-3]))
position_embed_w = self.position_embed(jnp.arange(state.shape[-2]))
position_embed = jnp.concatenate(
[
jnp.repeat(position_embed_h[:, None, :], state.shape[-2], axis=1),
jnp.repeat(position_embed_w[None, :, :], state.shape[-3], axis=0),
],
axis=-1,
)
tokens = jnp.concatenate([state, position_embed], axis=-1)
# Get mask for localized attention
mask = self.get_mask(tokens)
# Flatten grid into a sequence of tokens
tokens = jnp.reshape(tokens, tokens.shape[:-3] + (-1, tokens.shape[-1]))
# Apply localized attention
perception = self.attention(tokens, mask=mask)
perception = jnp.reshape(
perception,
perception.shape[:-2]
+ (state.shape[-3], state.shape[-2], perception.shape[-1]),
)
return perception
def get_mask(self, tokens: jax.Array) -> jax.Array:
"""Get mask for localized attention using Moore neighborhood.
Args:
tokens: Input tokens with shape [..., H, W, C]
Returns:
Boolean mask with shape [..., H*W, H*W] where True values indicate
allowed attention connections between tokens.
"""
h, w = tokens.shape[-3], tokens.shape[-2]
# Create position indices
row_idx = jnp.arange(h)[:, None, None, None] # [H, 1, 1, 1]
col_idx = jnp.arange(w)[None, :, None, None] # [1, W, 1, 1]
# Broadcast to full grid
row1 = jnp.broadcast_to(row_idx, (h, w, h, w)) # Source positions
col1 = jnp.broadcast_to(col_idx, (h, w, h, w))
row2 = jnp.broadcast_to(
row_idx.transpose((2, 3, 0, 1)), (h, w, h, w)
) # Target positions
col2 = jnp.broadcast_to(col_idx.transpose((2, 3, 0, 1)), (h, w, h, w))
# Calculate Manhattan distance between all positions
row_dist = jnp.abs(row1 - row2)
col_dist = jnp.abs(col1 - col2)
# Create mask where True allows attention (distance <= 1 in both dimensions)
mask = (row_dist <= 1) & (col_dist <= 1)
# Reshape to attention matrix shape
mask = jnp.reshape(mask, (h * w, h * w))
return mask
class ViTPerceive(Perceive[Array, Array]):
"""Vision Transformer Perceive class."""
def __init__(
self,
channel_size: int,
perception_size: int,
*,
num_heads: int,
hidden_size: int,
proj_size: int,
max_position_size: int,
position_embed_features: int = 4,
rngs: nnx.Rngs,
):
"""Initialize ViT Perceive."""
self.linear = nnx.Linear(
in_features=channel_size, out_features=proj_size, rngs=rngs
)
self.position_embed_features = position_embed_features
self.position_embed = nnx.Embed(
num_embeddings=max_position_size,
features=position_embed_features,
rngs=rngs,
)
self.attention = nnx.MultiHeadAttention(
num_heads=num_heads,
in_features=proj_size + 2 * position_embed_features,
qkv_features=hidden_size,
out_features=perception_size,
decode=False,
rngs=rngs,
)
def __call__(self, state: Array) -> Array:
"""Apply perception to the input state.
Args:
state: State of the cellular automaton.
Returns:
The perceived state after applying convolutional layers.
"""
# Linear projection of state into tokens
state = self.linear(state)
# Concatenate position embed
position_embed_h = self.position_embed(jnp.arange(state.shape[-3]))
position_embed_w = self.position_embed(jnp.arange(state.shape[-2]))
position_embed = jnp.concatenate(
[
jnp.repeat(position_embed_h[:, None, :], state.shape[-2], axis=1),
jnp.repeat(position_embed_w[None, :, :], state.shape[-3], axis=0),
],
axis=-1,
)
tokens = jnp.concatenate([state, position_embed], axis=-1)
# Get mask for localized attention
mask = self.get_mask(tokens)
# Flatten grid into a sequence of tokens
tokens = jnp.reshape(tokens, tokens.shape[:-3] + (-1, tokens.shape[-1]))
# Apply localized attention
perception = self.attention(tokens, mask=mask)
perception = jnp.reshape(
perception,
perception.shape[:-2]
+ (state.shape[-3], state.shape[-2], perception.shape[-1]),
)
return perception
def get_mask(self, tokens: jax.Array) -> jax.Array:
"""Get mask for localized attention using Moore neighborhood.
Args:
tokens: Input tokens with shape [..., H, W, C]
Returns:
Boolean mask with shape [..., H*W, H*W] where True values indicate
allowed attention connections between tokens.
"""
h, w = tokens.shape[-3], tokens.shape[-2]
# Create position indices
row_idx = jnp.arange(h)[:, None, None, None] # [H, 1, 1, 1]
col_idx = jnp.arange(w)[None, :, None, None] # [1, W, 1, 1]
# Broadcast to full grid
row1 = jnp.broadcast_to(row_idx, (h, w, h, w)) # Source positions
col1 = jnp.broadcast_to(col_idx, (h, w, h, w))
row2 = jnp.broadcast_to(
row_idx.transpose((2, 3, 0, 1)), (h, w, h, w)
) # Target positions
col2 = jnp.broadcast_to(col_idx.transpose((2, 3, 0, 1)), (h, w, h, w))
# Calculate Manhattan distance between all positions
row_dist = jnp.abs(row1 - row2)
col_dist = jnp.abs(col1 - col2)
# Create mask where True allows attention (distance <= 1 in both dimensions)
mask = (row_dist <= 1) & (col_dist <= 1)
# Reshape to attention matrix shape
mask = jnp.reshape(mask, (h * w, h * w))
return mask
In [7]:
Copied!
class ViTNCA(ComplexSystem):
"""ViT Neural Cellular Automata class."""
def __init__(self, *, rngs: nnx.Rngs):
"""Initialize ViT NCA.
Args:
rngs: rng key.
"""
self.perceive = ViTPerceive(
channel_size=channel_size,
perception_size=perception_size,
num_heads=num_heads,
hidden_size=hidden_size,
proj_size=proj_size,
max_position_size=max(spatial_dims),
rngs=rngs,
)
self.update = ResidualUpdate(
num_spatial_dims=2,
channel_size=channel_size,
perception_size=perception_size,
hidden_layer_sizes=(hidden_size,),
cell_dropout_rate=cell_dropout_rate,
zeros_init=True,
rngs=rngs,
)
def _step(self, state: Array, input: Array | None = None) -> Array:
perception = self.perceive(state)
next_state = self.update(state, perception, input)
return next_state
@nnx.jit
def render(self, state):
"""Render state to RGB."""
gray = state[..., -1:]
rgb = jnp.repeat(gray, 3, axis=-1)
# Clip values to valid range and convert to uint8
return clip_and_uint8(rgb)
class ViTNCA(ComplexSystem):
"""ViT Neural Cellular Automata class."""
def __init__(self, *, rngs: nnx.Rngs):
"""Initialize ViT NCA.
Args:
rngs: rng key.
"""
self.perceive = ViTPerceive(
channel_size=channel_size,
perception_size=perception_size,
num_heads=num_heads,
hidden_size=hidden_size,
proj_size=proj_size,
max_position_size=max(spatial_dims),
rngs=rngs,
)
self.update = ResidualUpdate(
num_spatial_dims=2,
channel_size=channel_size,
perception_size=perception_size,
hidden_layer_sizes=(hidden_size,),
cell_dropout_rate=cell_dropout_rate,
zeros_init=True,
rngs=rngs,
)
def _step(self, state: Array, input: Array | None = None) -> Array:
perception = self.perceive(state)
next_state = self.update(state, perception, input)
return next_state
@nnx.jit
def render(self, state):
"""Render state to RGB."""
gray = state[..., -1:]
rgb = jnp.repeat(gray, 3, axis=-1)
# Clip values to valid range and convert to uint8
return clip_and_uint8(rgb)
In [8]:
Copied!
cs = ViTNCA(rngs=rngs)
cs = ViTNCA(rngs=rngs)
In [9]:
Copied!
params = nnx.state(cs, nnx.Param)
print("Number of params:", sum(x.size for x in jax.tree.leaves(params)))
params = nnx.state(cs, nnx.Param)
print("Number of params:", sum(x.size for x in jax.tree.leaves(params)))
Number of params: 37616
Sample initial state¶
In [10]:
Copied!
def sample_state(key):
"""Sample a state with a randomly masked image."""
# Sample image from dataset
y_idx = jax.random.choice(key, y_train.shape[0])
y = y_train[y_idx]
y_channel_size = y.shape[-1]
# Init state with zeros
state = jnp.zeros(spatial_dims + (channel_size,))
# Mask pixels randomly
mask = jax.random.bernoulli(key, 1 - mask_ratio, shape=spatial_dims)
mask = jnp.expand_dims(mask, axis=-1)
y *= mask
# Set state
state = state.at[..., -y_channel_size:].set(y)
return state, y_idx
def sample_state_test(key):
"""Sample a state with a randomly masked image."""
# Sample image from dataset
y_idx = jax.random.choice(key, y_test.shape[0])
y = y_test[y_idx]
y_channel_size = y.shape[-1]
# Init state with zeros
state = jnp.zeros(spatial_dims + (channel_size,))
# Mask pixels randomly
mask = jax.random.bernoulli(key, 1 - mask_ratio, shape=spatial_dims)
mask = jnp.expand_dims(mask, axis=-1)
y *= mask
# Set state
state = state.at[..., -y_channel_size:].set(y)
return state, y_idx
def sample_state(key):
"""Sample a state with a randomly masked image."""
# Sample image from dataset
y_idx = jax.random.choice(key, y_train.shape[0])
y = y_train[y_idx]
y_channel_size = y.shape[-1]
# Init state with zeros
state = jnp.zeros(spatial_dims + (channel_size,))
# Mask pixels randomly
mask = jax.random.bernoulli(key, 1 - mask_ratio, shape=spatial_dims)
mask = jnp.expand_dims(mask, axis=-1)
y *= mask
# Set state
state = state.at[..., -y_channel_size:].set(y)
return state, y_idx
def sample_state_test(key):
"""Sample a state with a randomly masked image."""
# Sample image from dataset
y_idx = jax.random.choice(key, y_test.shape[0])
y = y_test[y_idx]
y_channel_size = y.shape[-1]
# Init state with zeros
state = jnp.zeros(spatial_dims + (channel_size,))
# Mask pixels randomly
mask = jax.random.bernoulli(key, 1 - mask_ratio, shape=spatial_dims)
mask = jnp.expand_dims(mask, axis=-1)
y *= mask
# Set state
state = state.at[..., -y_channel_size:].set(y)
return state, y_idx
Train¶
Pool¶
In [11]:
Copied!
key, subkey = jax.random.split(key)
keys = jax.random.split(subkey, pool_size)
state, y_idx = jax.vmap(sample_state)(keys)
pool = Pool.create({"state": state, "y_idx": y_idx})
key, subkey = jax.random.split(key)
keys = jax.random.split(subkey, pool_size)
state, y_idx = jax.vmap(sample_state)(keys)
pool = Pool.create({"state": state, "y_idx": y_idx})
Optimizer¶
In [12]:
Copied!
lr_sched = optax.linear_schedule(
init_value=learning_rate, end_value=0.1 * learning_rate, transition_steps=4_096
)
optimizer = optax.chain(
optax.clip_by_global_norm(1.0),
optax.adam(learning_rate=lr_sched),
)
optimizer = nnx.Optimizer(cs, optimizer, wrt=nnx.Param)
lr_sched = optax.linear_schedule(
init_value=learning_rate, end_value=0.1 * learning_rate, transition_steps=4_096
)
optimizer = optax.chain(
optax.clip_by_global_norm(1.0),
optax.adam(learning_rate=lr_sched),
)
optimizer = nnx.Optimizer(cs, optimizer, wrt=nnx.Param)
Loss¶
In [13]:
Copied!
def mse(state, y):
"""Mean Squared Error."""
return jnp.mean(jnp.square(state[..., -1:] - y))
def mse(state, y):
"""Mean Squared Error."""
return jnp.mean(jnp.square(state[..., -1:] - y))
In [14]:
Copied!
@nnx.jit
def loss_fn(cs, state, y):
"""Loss function."""
state_axes = nnx.StateAxes({nnx.RngState: 0, ...: None})
state = nnx.split_rngs(splits=batch_size)(
nnx.vmap(
lambda cs, state: cs(state, num_steps=num_steps),
in_axes=(state_axes, 0),
)
)(cs, state)
loss = mse(state, y)
return loss, state
@nnx.jit
def loss_fn(cs, state, y):
"""Loss function."""
state_axes = nnx.StateAxes({nnx.RngState: 0, ...: None})
state = nnx.split_rngs(splits=batch_size)(
nnx.vmap(
lambda cs, state: cs(state, num_steps=num_steps),
in_axes=(state_axes, 0),
)
)(cs, state)
loss = mse(state, y)
return loss, state
Train step¶
In [15]:
Copied!
@nnx.jit
def train_step(cs, optimizer, pool, key):
"""Train step."""
sample_key, sample_state_key = jax.random.split(key)
# Sample from pool
pool_idx, batch = pool.sample(sample_key, batch_size=batch_size, replace=False)
current_state = batch["state"]
current_y_idx = batch["y_idx"]
current_y = y_train[current_y_idx]
# Sort by descending loss
sort_idx = jnp.argsort(jax.vmap(mse)(current_state, current_y), descending=True)
pool_idx = pool_idx[sort_idx]
current_state = current_state[sort_idx]
current_y_idx = current_y_idx[sort_idx]
# Sample a new image to replace the worst
new_state, new_y_idx = sample_state(sample_state_key)
current_state = current_state.at[0].set(new_state)
current_y_idx = current_y_idx.at[0].set(new_y_idx)
current_y = y_train[current_y_idx]
(loss, current_state), grad = nnx.value_and_grad(loss_fn, has_aux=True)(
cs, current_state, current_y
)
optimizer.update(cs, grad)
pool = pool.update(pool_idx, {"state": current_state, "y_idx": current_y_idx})
return loss, pool
@nnx.jit
def train_step(cs, optimizer, pool, key):
"""Train step."""
sample_key, sample_state_key = jax.random.split(key)
# Sample from pool
pool_idx, batch = pool.sample(sample_key, batch_size=batch_size, replace=False)
current_state = batch["state"]
current_y_idx = batch["y_idx"]
current_y = y_train[current_y_idx]
# Sort by descending loss
sort_idx = jnp.argsort(jax.vmap(mse)(current_state, current_y), descending=True)
pool_idx = pool_idx[sort_idx]
current_state = current_state[sort_idx]
current_y_idx = current_y_idx[sort_idx]
# Sample a new image to replace the worst
new_state, new_y_idx = sample_state(sample_state_key)
current_state = current_state.at[0].set(new_state)
current_y_idx = current_y_idx.at[0].set(new_y_idx)
current_y = y_train[current_y_idx]
(loss, current_state), grad = nnx.value_and_grad(loss_fn, has_aux=True)(
cs, current_state, current_y
)
optimizer.update(cs, grad)
pool = pool.update(pool_idx, {"state": current_state, "y_idx": current_y_idx})
return loss, pool
Main loop¶
In [16]:
Copied!
num_train_steps = 8_196
print_interval = 128
losses = []
start = time.perf_counter()
for i in range(num_train_steps):
key, subkey = jax.random.split(key)
loss, pool = train_step(cs, optimizer, pool, subkey)
losses.append(loss)
if i % print_interval == 0 or i == num_train_steps - 1:
avg_loss = sum(losses[-print_interval:]) / len(losses[-print_interval:])
elapsed = time.perf_counter() - start
print(f"Step {i:>4}/{num_train_steps} | {elapsed:6.1f}s | Loss {avg_loss:.3e}")
print(f"✨ Trained for {num_train_steps} steps in {time.perf_counter() - start:.0f}s")
num_train_steps = 8_196
print_interval = 128
losses = []
start = time.perf_counter()
for i in range(num_train_steps):
key, subkey = jax.random.split(key)
loss, pool = train_step(cs, optimizer, pool, subkey)
losses.append(loss)
if i % print_interval == 0 or i == num_train_steps - 1:
avg_loss = sum(losses[-print_interval:]) / len(losses[-print_interval:])
elapsed = time.perf_counter() - start
print(f"Step {i:>4}/{num_train_steps} | {elapsed:6.1f}s | Loss {avg_loss:.3e}")
print(f"✨ Trained for {num_train_steps} steps in {time.perf_counter() - start:.0f}s")
W0904 22:05:07.193775 507976 cuda_timer.cc:88] Delay kernel timed out: measured time has sub-optimal accuracy. There may be a missing warmup execution, please investigate in Nsight Systems.
Step 0/8196 | 7.3s | Loss 6.006e-02
Step 128/8196 | 10.2s | Loss 3.176e-02
Step 256/8196 | 13.1s | Loss 1.465e-02
Step 384/8196 | 15.9s | Loss 1.243e-02
Step 512/8196 | 18.8s | Loss 1.024e-02
Step 640/8196 | 21.7s | Loss 9.842e-03
Step 768/8196 | 24.5s | Loss 9.025e-03
Step 896/8196 | 27.4s | Loss 8.473e-03
Step 1024/8196 | 30.3s | Loss 7.806e-03
Step 1152/8196 | 33.2s | Loss 7.484e-03
Step 1280/8196 | 36.0s | Loss 6.830e-03
Step 1408/8196 | 38.9s | Loss 6.434e-03
Step 1536/8196 | 41.8s | Loss 6.083e-03
Step 1664/8196 | 44.6s | Loss 5.919e-03
Step 1792/8196 | 47.5s | Loss 5.783e-03
Step 1920/8196 | 50.4s | Loss 5.406e-03
Step 2048/8196 | 53.3s | Loss 5.374e-03
Step 2176/8196 | 56.1s | Loss 4.986e-03
Step 2304/8196 | 59.0s | Loss 4.991e-03
Step 2432/8196 | 61.9s | Loss 4.845e-03
Step 2560/8196 | 64.7s | Loss 4.705e-03
Step 2688/8196 | 67.6s | Loss 4.577e-03
Step 2816/8196 | 70.5s | Loss 4.994e-03
Step 2944/8196 | 73.4s | Loss 4.548e-03
Step 3072/8196 | 76.2s | Loss 4.542e-03
Step 3200/8196 | 79.1s | Loss 4.246e-03
Step 3328/8196 | 82.0s | Loss 4.357e-03
Step 3456/8196 | 84.8s | Loss 4.182e-03
Step 3584/8196 | 87.7s | Loss 3.900e-03
Step 3712/8196 | 90.6s | Loss 3.951e-03
Step 3840/8196 | 93.5s | Loss 4.297e-03
Step 3968/8196 | 96.3s | Loss 3.917e-03
Step 4096/8196 | 99.2s | Loss 3.934e-03
Step 4224/8196 | 102.1s | Loss 3.761e-03
Step 4352/8196 | 105.0s | Loss 3.827e-03
Step 4480/8196 | 107.8s | Loss 3.840e-03
Step 4608/8196 | 110.7s | Loss 3.795e-03
Step 4736/8196 | 113.6s | Loss 3.544e-03
Step 4864/8196 | 116.4s | Loss 3.687e-03
Step 4992/8196 | 119.3s | Loss 3.688e-03
Step 5120/8196 | 122.2s | Loss 3.476e-03
Step 5248/8196 | 125.1s | Loss 3.937e-03
Step 5376/8196 | 127.9s | Loss 3.734e-03
Step 5504/8196 | 130.8s | Loss 4.153e-03
Step 5632/8196 | 133.7s | Loss 3.546e-03
Step 5760/8196 | 136.5s | Loss 3.729e-03
Step 5888/8196 | 139.4s | Loss 4.201e-03
Step 6016/8196 | 142.3s | Loss 3.540e-03
Step 6144/8196 | 145.2s | Loss 3.718e-03
Step 6272/8196 | 148.0s | Loss 3.679e-03
Step 6400/8196 | 150.9s | Loss 3.488e-03
Step 6528/8196 | 153.8s | Loss 3.592e-03
Step 6656/8196 | 156.7s | Loss 2.273e-02
Step 6784/8196 | 159.5s | Loss 3.108e+00
Step 6912/8196 | 162.4s | Loss 7.175e-01
Step 7040/8196 | 165.3s | Loss 7.905e+01
Step 7168/8196 | 168.1s | Loss 1.214e+00
Step 7296/8196 | 171.0s | Loss 4.162e+00
Step 7424/8196 | 173.9s | Loss 9.840e+00
Step 7552/8196 | 176.8s | Loss 1.772e+00
Step 7680/8196 | 179.6s | Loss 4.528e+01
Step 7808/8196 | 182.5s | Loss 6.665e-01
Step 7936/8196 | 185.4s | Loss 1.092e+01
Step 8064/8196 | 188.3s | Loss 2.211e-01
Step 8192/8196 | 191.1s | Loss 7.826e-02 Step 8195/8196 | 191.2s | Loss 7.824e-02 ✨ Trained for 8196 steps in 191s
Run¶
In [17]:
Copied!
num_examples = 8
key, subkey = jax.random.split(key)
keys = jax.random.split(subkey, num_examples)
state_init, y_idx = jax.vmap(sample_state_test)(keys)
state_axes = nnx.StateAxes({nnx.RngState: 0, ...: None})
state_final, states = nnx.split_rngs(splits=num_examples)(
nnx.vmap(
lambda cs, state: cs(state, num_steps=2 * num_steps, return_states=True),
in_axes=(state_axes, 0),
)
)(cs, state_init)
num_examples = 8
key, subkey = jax.random.split(key)
keys = jax.random.split(subkey, num_examples)
state_init, y_idx = jax.vmap(sample_state_test)(keys)
state_axes = nnx.StateAxes({nnx.RngState: 0, ...: None})
state_final, states = nnx.split_rngs(splits=num_examples)(
nnx.vmap(
lambda cs, state: cs(state, num_steps=2 * num_steps, return_states=True),
in_axes=(state_axes, 0),
)
)(cs, state_init)
Visualize¶
In [18]:
Copied!
states = jnp.concatenate([state_init[:, None], states], axis=1)
frame_init = nnx.vmap(
lambda cs, state: cs.render(state),
in_axes=(None, 0),
)(cs, state_init)
frames = nnx.vmap(
lambda cs, state: cs.render(state),
in_axes=(None, 0),
)(cs, states)
mediapy.show_images(y_test[y_idx].repeat(4, axis=-3).repeat(4, axis=-2))
mediapy.show_images(frame_init.repeat(4, axis=-3).repeat(4, axis=-2))
mediapy.show_videos(frames.repeat(4, axis=-3).repeat(4, axis=-2))
states = jnp.concatenate([state_init[:, None], states], axis=1)
frame_init = nnx.vmap(
lambda cs, state: cs.render(state),
in_axes=(None, 0),
)(cs, state_init)
frames = nnx.vmap(
lambda cs, state: cs.render(state),
in_axes=(None, 0),
)(cs, states)
mediapy.show_images(y_test[y_idx].repeat(4, axis=-3).repeat(4, axis=-2))
mediapy.show_images(frame_init.repeat(4, axis=-3).repeat(4, axis=-2))
mediapy.show_videos(frames.repeat(4, axis=-3).repeat(4, axis=-2))