To incorporate half-precision (float16) into your training script using JAX and Flax, you'll need to make several adjustments. Utilizing half-precision can help reduce memory usage and potentially increase training speed, especially on hardware that supports fast float16 operations (like NVIDIA GPUs with Tensor Cores).
Below are the steps and modifications to your script to enable half-precision training:
-
Enable Float16 Computations in JAX:
- Set the default dtype for JAX to
float16 where applicable.
- Ensure that model parameters and inputs are cast to
float16.
- Use mixed precision to maintain optimizer states in
float32 to preserve numerical stability.
-
Modify the Model Initialization:
- Ensure that the RWKV model supports
float16. If not, you may need to modify the model definition to handle mixed precision.
- Initialize the model parameters in
float16.
-
Adjust the Training Loop:
- Cast input batches to
float16 before feeding them into the model.
- Ensure that loss computations and gradients are handled appropriately with mixed precision.
-
Update Optimizer:
- Optax's Adam optimizer works well with mixed precision by maintaining optimizer states in
float32 while parameters can be in float16.
Here's the revised script with these modifications:
# train_rwkv_flax.py
import jax
import jax.numpy as jnp
from flax.training import train_state
from flax import linen as nn
import optax
import wandb
from transformers import AutoTokenizer
from datasets import load_dataset
from dataclasses import dataclass
import numpy as np
import os
from rwkv_flax import RWKV, Config # Ensure rwkv_flax.py is in the same directory or adjust the import accordingly
from typing import Any
# Enable float16 mixed precision
jax.config.update("jax_enable_x64", False) # Ensure we're not using float64
dtype = jnp.float16
# Define the training state using Flax's train_state with mixed precision
@dataclass
class TrainStateWithBatchStats(train_state.TrainState):
batch_stats: Any = None # Modify as needed, if using batch normalization or similar
# Function to create the training state with mixed precision
def create_train_state(rng, model, learning_rate):
# Initialize parameters with float16
params = model.init(rng, jnp.ones((1, 2), dtype=jnp.int32))['params']
params = jax.tree_map(lambda x: x.astype(dtype), params)
# Use Optax's mix precision utilities if necessary
# Here, we keep optimizer states in float32 for stability
tx = optax.adam(learning_rate, eps=1e-8)
return train_state.TrainState.create(
apply_fn=model.apply,
params=params,
tx=tx
)
# Define the loss function (Cross-Entropy Loss)
def compute_loss(logits, labels):
# Ensure logits are in float32 for numerical stability during softmax
logits = logits.astype(jnp.float32)
labels = labels.astype(jnp.int32)
one_hot = jax.nn.one_hot(labels, logits.shape[-1])
loss = optax.softmax_cross_entropy(logits=logits, labels=one_hot)
return loss.mean()
# Define the training step with mixed precision
@jax.jit
def train_step(state, batch):
# Cast input_ids to int32 and labels to int32
input_ids = batch['input_ids'].astype(jnp.int32)
labels = batch['labels'].astype(jnp.int32)
def loss_fn(params):
logits = state.apply_fn({'params': params}, input_ids)
loss = compute_loss(logits, labels)
return loss, logits
grad_fn = jax.value_and_grad(loss_fn, has_aux=True)
(loss, logits), grads = grad_fn(state.params)
# Cast gradients to float32 for optimizer
grads = jax.tree_map(lambda g: g.astype(jnp.float32), grads)
state = state.apply_gradients(grads=grads)
return state, loss
# Load dataset and tokenizer
def get_dataset(tokenizer, block_size=128):
base_url = "https://huggingface.co/datasets/chengjunyan1/smollm-12.5-corpus/resolve/main/fineweb-edu-dedup/"
data_files = {"train": base_url+"train-0000[1]-of-00237.parquet"} #,2,3,4,5,6
ds = load_dataset("parquet", data_files=data_files, keep_in_memory=True)
ds = ds.select_columns(['text'])
dataset = ds["train"]
def tokenize_function(examples):
# Use padding and truncation as needed
return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=block_size)
tokenized = dataset.map(
tokenize_function,
batched=True,
remove_columns=['text']
)
def group_texts(examples):
concatenated = {k: sum(examples[k], []) for k in examples.keys()}
total_length = len(concatenated[list(concatenated.keys())[0]])
total_length = (total_length // block_size) * block_size
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
for k, t in concatenated.items()
}
result['labels'] = result['input_ids'].copy()
return result
lm_dataset = tokenized.map(
group_texts,
batched=True,
batch_size=128,
#num_proc=60,
)
lm_dataset = lm_dataset.with_format('jax', columns=['input_ids', 'labels'])
return lm_dataset
# Initialize wandb
wandb.init(
project="RWKV-Flax-Training",
config=Config(),
save_code=True,
)
config = wandb.config
# Initialize tokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2") # Replace with appropriate tokenizer
# Load dataset
dataset = get_dataset(tokenizer)
train_loader = jax.device_put(dataset)
# Initialize model
rng = jax.random.PRNGKey(0)
model = RWKV(cfg=config, dtype=dtype) # Ensure RWKV accepts dtype
train_rng, init_rng = jax.random.split(rng)
state = create_train_state(init_rng, model, learning_rate=1e-4)
# Training loop parameters
num_epochs = 3
batch_size = 32
steps_per_epoch = len(dataset) // batch_size
# Start training
for epoch in range(num_epochs):
epoch_loss = 0.0
for step, batch in enumerate(train_loader.shard(jax.local_device_count(), index=jax.process_index())):
# Cast input_ids and labels to appropriate dtype if not already
batch = {
'input_ids': batch['input_ids'].astype(jnp.int32),
'labels': batch['labels'].astype(jnp.int32)
}
state, loss = train_step(state, batch)
epoch_loss += loss
if step % 100 == 0:
print(f"Epoch {epoch}, Step {step}, Loss: {loss}")
wandb.log({"epoch": epoch, "step": step, "loss": loss})
avg_loss = epoch_loss / steps_per_epoch
wandb.log({"epoch": epoch, "avg_loss": avg_loss})
print(f"Epoch {epoch} completed. Average Loss: {avg_loss}")
# Save the trained model
if jax.process_index() == 0:
model_dir = "rwkv_flax_model"
os.makedirs(model_dir, exist_ok=True)
# Convert parameters to float32 before saving to prevent precision loss when loading
params_fp32 = jax.tree_map(lambda x: x.astype(jnp.float32), state.params)
# Save each parameter array separately to handle nested structures
for param_name, param in jax.tree_util.tree_flatten(params_fp32)[0]:
np.save(os.path.join(model_dir, f"{param_name}.npy"), np.array(param))
wandb.save(os.path.join(model_dir, "*.npy"))
wandb.finish()
Explanation of Changes
-
Mixed Precision Configuration:
- Disable float64:
jax.config.update("jax_enable_x64", False) ensures that JAX does not use float64, which can interfere with float16 operations.
- Set dtype: Defined
dtype = jnp.float16 to use across the model and computations.
-
Model Initialization:
- Parameter Casting: After initializing the model parameters, they are cast to
float16 using jax.tree_map.
- Model Definition: Ensure that the
RWKV model from rwkv_flax accepts a dtype parameter and utilizes it internally for all layers. If not, you’ll need to modify the RWKV class accordingly.
-
Loss Function:
- Logits Casting: Cast logits to
float32 before applying softmax_cross_entropy to maintain numerical stability.
-
Training Step:
- Input Casting: Explicitly cast
input_ids and labels to int32 to match expected data types.
- Gradient Casting: Cast gradients back to
float32 to maintain optimizer stability since optimizer states are maintained in float32.
-
Dataset Tokenization:
- Padding and Truncation: Added
padding='max_length' and truncation=True with max_length=block_size to ensure uniform input sizes, which is important for batch processing.
-
Model Saving:
- Parameter Conversion: Before saving, parameters are converted back to
float32 to prevent precision loss. Depending on your use case, you might choose to save them in float16 if supported downstream.
- Saving Individual Parameters: Saving each parameter separately can help manage complex nested parameter structures.
-
Additional Recommendations:
- WandB Configuration: Enabled
save_code=True in to keep track of the exact script used for training.
Potential Considerations
-
Hardware Support: Ensure that your hardware (e.g., GPUs) efficiently supports float16 operations. NVIDIA GPUs with Tensor Cores (like the V100, RTX 30 series, A100) are optimal for mixed-precision training.
-
Numerical Stability: While mixed precision can speed up training and reduce memory usage, it might introduce numerical instability. Monitor training loss and consider using techniques like loss scaling if necessary.
-
RWKV Model Compatibility: Ensure that the RWKV model's implementation in rwkv_flax.py fully supports mixed precision. If not, you might need to modify the model's layers to handle different dtypes appropriately.
-
Optimizer States: Keeping optimizer states in float32 is crucial for maintaining training stability, especially when working with float16 parameters.
-
Batch Normalization and Other Layers: If your model uses layers that are sensitive to precision (like BatchNorm), ensure they are correctly configured to handle float16 or use float32 where necessary.
By following these modifications, your training script should now utilize half-precision computations, potentially offering benefits in terms of memory efficiency and training speed. Always validate the model's performance and training stability when making such changes.