Okay, here is a small, self-contained JAX training script demonstrating common best practices like using jax.jit, jax.grad, managing PRNG keys, and using Flax and Optax for model and optimization.
This script trains a small Multi-Layer Perceptron (MLP) on a synthetic binary classification dataset.
import jax
import jax.numpy as jnp
import flax.linen as nn
import optax
from flax.training import train_state # Helper class for training state
from tqdm import tqdm # For progress bar (optional)
# --- 1. Configuration / Hyperparameters ---
class HParams:
seed = 42
num_epochs = 100
learning_rate = 0.01
batch_size = 32 # Note: Using full batch for simplicity in this example
input_dim = 2
hidden_dim = 64
output_dim = 1 # For binary classification (logits)
dataset_size = 1000
hparams = HParams()
# --- 2. Data Generation ---
def generate_synthetic_data(key, num_samples, input_dim):
"""Generates synthetic binary classification data."""
key_x, key_noise = jax.random.split(key)
# Generate features (e.g., random points)
X = jax.random.normal(key_x, (num_samples, input_dim))
# Create a simple linear boundary + noise
true_weights = jnp.array([1.5, -1.0]) # Example weights
true_bias = 0.5
logits = jnp.dot(X, true_weights) + true_bias + jax.random.normal(key_noise, (num_samples,)) * 0.5
# Generate binary labels based on the boundary
y = (logits > 0).astype(jnp.float32) # Use float32 for BCE loss
return X, y
# --- 3. Model Definition (using Flax) ---
class SimpleMLP(nn.Module):
output_dim: int
hidden_dim: int
@nn.compact
def __call__(self, x):
x = nn.Dense(features=self.hidden_dim)(x)
x = nn.relu(x)
x = nn.Dense(features=self.output_dim)(x) # Output logits
return x
# --- 4. Loss Function ---
def binary_cross_entropy_loss(logits, labels):
"""Computes binary cross-entropy loss."""
# Use optax's numerically stable version
loss = optax.sigmoid_binary_cross_entropy(logits, labels)
return jnp.mean(loss) # Average over the batch
# --- 5. Training State (using Flax helper) ---
# Flax's TrainState is a common pattern to hold params, opt_state, and apply_fn
# It simplifies passing state around.
# We'll add the apply_fn (model.apply) and the optimizer to it.
class State(train_state.TrainState):
# You could add other things here, like metrics, etc.
pass
def create_train_state(key, model, learning_rate, input_dim):
"""Creates the initial training state."""
# Initialize model parameters
dummy_input = jnp.zeros((1, input_dim))
params = model.init(key, dummy_input)['params'] # Flax init returns a dict, get 'params'
# Create optimizer
optimizer = optax.adam(learning_rate)
# Create training state
return State.create(
apply_fn=model.apply, # The forward pass function
params=params,
tx=optimizer # The Optax optimizer
)
# --- 6. Training Step (JIT compiled) ---
@jax.jit # Compile the function for performance
def train_step(state: State, batch: tuple):
"""Performs a single training step."""
features, labels = batch
def loss_fn(params):
# Model forward pass
logits = state.apply_fn({'params': params}, features) # Pass params from the state
# Compute loss
loss = binary_cross_entropy_loss(logits.squeeze(), labels) # Squeeze logits to match labels shape
return loss
# Compute gradients using jax.grad
grad_fn = jax.grad(loss_fn)
grads = grad_fn(state.params)
# Apply gradients using Optax
new_state = state.apply_gradients(grads=grads) # TrainState handles apply_updates internally
# Compute metrics (e.g., loss) for logging
metrics = {'loss': loss_fn(state.params)} # Compute loss *before* update for logging
return new_state, metrics
# --- 7. Main Training Loop ---
def train(hparams: HParams):
key = jax.random.PRNGKey(hparams.seed)
data_key, init_key, train_key = jax.random.split(key, 3) # Split keys for different uses
# Generate data
X, y = generate_synthetic_data(data_key, hparams.dataset_size, hparams.input_dim)
# For simplicity, we'll use the full dataset as a single "batch"
# In a real scenario, you'd iterate over batches
full_batch = (X, y)
# Define model
model = SimpleMLP(output_dim=hparams.output_dim, hidden_dim=hparams.hidden_dim)
# Create initial training state
state = create_train_state(init_key, model, hparams.learning_rate, hparams.input_dim)
print(f"Starting training for {hparams.num_epochs} epochs...")
# Training loop
for epoch in tqdm(range(hparams.num_epochs), desc="Training"):
# In a batched scenario, you would loop through batches here
# and potentially split train_key inside the batch loop if needed
# e.g., for dropout which is absent in this simple model
# Perform one training step (on the full "batch")
# The state and metrics are DeviceArrays
state, metrics = train_step(state, full_batch)
# Log progress
if (epoch + 1) % 10 == 0 or epoch == 0:
# Use float() to pull value out of JAX array for printing
print(f"Epoch {epoch + 1}/{hparams.num_epochs}, Loss: {float(metrics['loss']):.4f}")
print("\nTraining finished.")
# You could optionally add evaluation here
# e.g., evaluate the final model state on a separate test set
# Example: Predict on the training data
final_logits = state.apply_fn({'params': state.params}, X).squeeze()
predictions = (jax.nn.sigmoid(final_logits) > 0.5).astype(jnp.float32)
accuracy = jnp.mean(predictions == y)
print(f"Final training accuracy: {float(accuracy):.4f}")
return state # Return final state
# --- Run the training ---
if __name__ == "__main__":
final_state = train(hparams)
# You can now access the trained parameters:
# trained_params = final_state.params
# print("\nTrained parameters example (first layer weights):")
# print(trained_params['Dense_0']['kernel'])
Explanation of Best Practices Demonstrated:
- Functional Programming: The
train_step function is pure. It takes the training state (containing parameters and optimizer state) and the batch as inputs and returns the new state and metrics. There are no side effects or mutation of global variables.
- State Management: The script uses
flax.training.train_state.TrainState. This is a standard Flax pattern for bundling model parameters, the optimizer state, and the model's apply_fn (forward pass function). It provides helper methods like apply_gradients.
- PRNG Keys: JAX's immutable random number generation is handled correctly. A single initial key is created and then explicitly
split for different purposes (data generation, model initialization, training steps). Keys are passed into functions that require randomness (though the simple MLP here doesn't use randomness in its forward pass).
jax.jit: The core computation (train_step) is decorated with @jax.jit. This compiles the Python function into optimized XLA (Accelerated Linear Algebra) operations for significant performance gains. JIT requires the function to be pure and its input/output shapes/dtypes to be consistent across calls after the first one.
jax.grad: Gradients are computed automatically using jax.grad. We define a nested loss_fn inside train_step which closes over the current batch and state.apply_fn. jax.grad(loss_fn) then gives a function that computes gradients of the loss_fn with respect to its first argument (params in this case).
- Flax for Models: Flax (
flax.linen) is used to define the neural network model. This handles parameter initialization and the forward pass (model.apply) cleanly.
- Optax for Optimization: Optax is used for defining the optimizer (Adam) and applying parameter updates based on the computed gradients.
TrainState.apply_gradients integrates with Optax.
- Clear Separation: Data generation, model definition, loss function, training step, and the main loop are kept separate.
- Configuration: Hyperparameters are grouped in a simple class for easy modification.
- Progress Reporting:
tqdm is used to show training progress, which is standard practice.
This script provides a solid foundation for more complex JAX training pipelines. For larger projects, you'd typically add things like data loading, batching, evaluation loops, checkpointing, logging to tools like TensorBoard (Flax has built-in support for this), multi-device training (jax.pmap), etc.