Recurrent Residual Convolutional Neural Network
¶
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 ConvPerceive
from cax.core.update import ResidualUpdate
from cax.utils.render 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 ConvPerceive
from cax.core.update import ResidualUpdate
from cax.utils.render import clip_and_uint8
Configuration¶
In [4]:
Copied!
seed = 0
spatial_dims = (28, 28)
channel_size = 64
perception_size = 64
update_hidden_layer_sizes = (128, 128)
cell_dropout_rate = 0.5
num_steps = 64
batch_size = 8
learning_rate = 1e-3
key = jax.random.key(seed)
rngs = nnx.Rngs(seed)
seed = 0
spatial_dims = (28, 28)
channel_size = 64
perception_size = 64
update_hidden_layer_sizes = (128, 128)
cell_dropout_rate = 0.5
num_steps = 64
batch_size = 8
learning_rate = 1e-3
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 RRCNN(ComplexSystem):
"""Recurrent Residual Convolutional Neural Network class."""
def __init__(self, *, rngs: nnx.Rngs):
"""Initialize RRCNN.
Args:
rngs: rng key.
"""
self.perceive = ConvPerceive(
channel_size=channel_size,
perception_size=perception_size,
rngs=rngs,
)
self.update = ResidualUpdate(
num_spatial_dims=len(spatial_dims),
channel_size=channel_size,
perception_size=perception_size,
hidden_layer_sizes=update_hidden_layer_sizes,
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 RRCNN(ComplexSystem):
"""Recurrent Residual Convolutional Neural Network class."""
def __init__(self, *, rngs: nnx.Rngs):
"""Initialize RRCNN.
Args:
rngs: rng key.
"""
self.perceive = ConvPerceive(
channel_size=channel_size,
perception_size=perception_size,
rngs=rngs,
)
self.update = ResidualUpdate(
num_spatial_dims=len(spatial_dims),
channel_size=channel_size,
perception_size=perception_size,
hidden_layer_sizes=update_hidden_layer_sizes,
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 [7]:
Copied!
cs = RRCNN(rngs=rngs)
cs = RRCNN(rngs=rngs)
In [8]:
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: 69952
Sample initial state¶
In [9]:
Copied!
def add_noise(image, alpha, key):
"""Add noise to the image with a given alpha value."""
noise = jax.random.normal(key, image.shape)
noisy_image = (1 - alpha) * image + alpha * noise
return jnp.clip(noisy_image, 0.0, 1.0)
def sample_state(key):
"""Sample a state with a randomly sampled image and added noise."""
state = jnp.zeros(y_train.shape[1:3] + (channel_size,))
sample_key, alpha_key, noise_key = jax.random.split(key, 3)
# Sample a target image
y_idx = jax.random.choice(sample_key, y_train.shape[0])
y = y_train[y_idx]
# Add noise
alpha = jax.random.uniform(alpha_key)
noisy_y = add_noise(y, alpha, noise_key)
return state.at[..., -1:].set(noisy_y), y_idx
def add_noise(image, alpha, key):
"""Add noise to the image with a given alpha value."""
noise = jax.random.normal(key, image.shape)
noisy_image = (1 - alpha) * image + alpha * noise
return jnp.clip(noisy_image, 0.0, 1.0)
def sample_state(key):
"""Sample a state with a randomly sampled image and added noise."""
state = jnp.zeros(y_train.shape[1:3] + (channel_size,))
sample_key, alpha_key, noise_key = jax.random.split(key, 3)
# Sample a target image
y_idx = jax.random.choice(sample_key, y_train.shape[0])
y = y_train[y_idx]
# Add noise
alpha = jax.random.uniform(alpha_key)
noisy_y = add_noise(y, alpha, noise_key)
return state.at[..., -1:].set(noisy_y), y_idx
Train¶
Optimizer¶
In [10]:
Copied!
lr_sched = optax.linear_schedule(
init_value=learning_rate, end_value=0.1 * learning_rate, transition_steps=2_000
)
optimizer = optax.chain(
optax.clip_by_global_norm(1.0),
optax.adam(learning_rate=lr_sched),
)
update_params = nnx.All(nnx.Param, nnx.PathContains("update"))
optimizer = nnx.Optimizer(cs, optimizer, wrt=update_params)
lr_sched = optax.linear_schedule(
init_value=learning_rate, end_value=0.1 * learning_rate, transition_steps=2_000
)
optimizer = optax.chain(
optax.clip_by_global_norm(1.0),
optax.adam(learning_rate=lr_sched),
)
update_params = nnx.All(nnx.Param, nnx.PathContains("update"))
optimizer = nnx.Optimizer(cs, optimizer, wrt=update_params)
Loss¶
In [11]:
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 [12]:
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
@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
Train step¶
In [13]:
Copied!
@nnx.jit
def train_step(cs, optimizer, key):
"""Train step."""
keys = jax.random.split(key, batch_size)
current_state, y_idx = jax.vmap(sample_state)(keys)
y = y_train[y_idx]
loss, grad = nnx.value_and_grad(loss_fn, argnums=nnx.DiffState(0, update_params))(
cs, current_state, y
)
optimizer.update(cs, grad)
return loss
@nnx.jit
def train_step(cs, optimizer, key):
"""Train step."""
keys = jax.random.split(key, batch_size)
current_state, y_idx = jax.vmap(sample_state)(keys)
y = y_train[y_idx]
loss, grad = nnx.value_and_grad(loss_fn, argnums=nnx.DiffState(0, update_params))(
cs, current_state, y
)
optimizer.update(cs, grad)
return loss
Main loop¶
In [14]:
Copied!
num_train_steps = 8_192
print_interval = 128
losses = []
start = time.perf_counter()
for i in range(num_train_steps):
key, subkey = jax.random.split(key)
loss = train_step(cs, optimizer, 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_192
print_interval = 128
losses = []
start = time.perf_counter()
for i in range(num_train_steps):
key, subkey = jax.random.split(key)
loss = train_step(cs, optimizer, 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")
Step 0/8192 | 6.1s | Loss 1.742e-01
Step 128/8192 | 7.9s | Loss 6.702e-02
Step 256/8192 | 9.5s | Loss 5.388e-02
Step 384/8192 | 11.1s | Loss 5.062e-02
Step 512/8192 | 12.8s | Loss 4.548e-02
Step 640/8192 | 14.4s | Loss 4.144e-02
Step 768/8192 | 16.1s | Loss 4.261e-02
Step 896/8192 | 17.8s | Loss 4.335e-02
Step 1024/8192 | 19.4s | Loss 3.948e-02
Step 1152/8192 | 21.1s | Loss 3.982e-02
Step 1280/8192 | 22.7s | Loss 4.190e-02
Step 1408/8192 | 24.4s | Loss 3.994e-02
Step 1536/8192 | 26.0s | Loss 3.917e-02
Step 1664/8192 | 27.7s | Loss 3.595e-02
Step 1792/8192 | 29.3s | Loss 3.742e-02
Step 1920/8192 | 31.0s | Loss 3.579e-02
Step 2048/8192 | 32.6s | Loss 3.524e-02
Step 2176/8192 | 34.3s | Loss 3.755e-02
Step 2304/8192 | 35.9s | Loss 3.589e-02
Step 2432/8192 | 37.6s | Loss 3.647e-02
Step 2560/8192 | 39.3s | Loss 3.518e-02
Step 2688/8192 | 40.9s | Loss 3.576e-02
Step 2816/8192 | 42.6s | Loss 3.539e-02
Step 2944/8192 | 44.2s | Loss 3.634e-02
Step 3072/8192 | 45.9s | Loss 3.675e-02
Step 3200/8192 | 47.5s | Loss 3.578e-02
Step 3328/8192 | 49.2s | Loss 3.435e-02
Step 3456/8192 | 50.8s | Loss 3.677e-02
Step 3584/8192 | 52.5s | Loss 3.607e-02
Step 3712/8192 | 54.1s | Loss 3.520e-02
Step 3840/8192 | 55.8s | Loss 3.654e-02
Step 3968/8192 | 57.5s | Loss 3.514e-02
Step 4096/8192 | 59.1s | Loss 3.494e-02
Step 4224/8192 | 60.8s | Loss 3.450e-02
Step 4352/8192 | 62.5s | Loss 3.723e-02
Step 4480/8192 | 64.1s | Loss 3.623e-02
Step 4608/8192 | 65.8s | Loss 3.521e-02
Step 4736/8192 | 67.4s | Loss 3.559e-02
Step 4864/8192 | 69.1s | Loss 3.565e-02
Step 4992/8192 | 70.7s | Loss 3.531e-02
Step 5120/8192 | 72.3s | Loss 3.579e-02
Step 5248/8192 | 74.0s | Loss 3.571e-02
Step 5376/8192 | 75.6s | Loss 3.496e-02
Step 5504/8192 | 77.3s | Loss 3.447e-02
Step 5632/8192 | 78.9s | Loss 3.455e-02
Step 5760/8192 | 80.6s | Loss 3.495e-02
Step 5888/8192 | 82.3s | Loss 3.391e-02
Step 6016/8192 | 83.9s | Loss 3.437e-02
Step 6144/8192 | 85.6s | Loss 3.549e-02
Step 6272/8192 | 87.3s | Loss 3.641e-02
Step 6400/8192 | 88.9s | Loss 3.472e-02
Step 6528/8192 | 90.5s | Loss 3.475e-02
Step 6656/8192 | 92.2s | Loss 3.383e-02
Step 6784/8192 | 93.8s | Loss 3.360e-02
Step 6912/8192 | 95.5s | Loss 3.488e-02
Step 7040/8192 | 97.1s | Loss 3.717e-02
Step 7168/8192 | 98.8s | Loss 3.469e-02
Step 7296/8192 | 100.5s | Loss 3.575e-02
Step 7424/8192 | 102.1s | Loss 3.539e-02
Step 7552/8192 | 103.7s | Loss 3.494e-02
Step 7680/8192 | 105.4s | Loss 3.557e-02
Step 7808/8192 | 107.0s | Loss 3.538e-02
Step 7936/8192 | 108.7s | Loss 3.390e-02
Step 8064/8192 | 110.3s | Loss 3.423e-02
Step 8191/8192 | 112.0s | Loss 3.493e-02 ✨ Trained for 8192 steps in 112s
Run¶
In [15]:
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)(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)(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 [16]:
Copied!
states = jnp.concatenate([state_init[:, None], states], axis=1)
frames = nnx.vmap(
lambda cs, state: cs.render(state),
in_axes=(None, 0),
)(cs, states)
mediapy.show_images(y_train[y_idx].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)
frames = nnx.vmap(
lambda cs, state: cs.render(state),
in_axes=(None, 0),
)(cs, states)
mediapy.show_images(y_train[y_idx].repeat(4, axis=-3).repeat(4, axis=-2))
mediapy.show_videos(frames.repeat(4, axis=-3).repeat(4, axis=-2))