Trainer & ModelState
Roxxel's Trainer is a curriculum-aware training orchestrator specifically designed for JAX and Flax NNX.
It handles training loops, dynamic sequence and batch transitions, metric logging, Orbax checkpointing, and model evaluations with minimal boilerplate.
Easiest Trainer Configuration
With Roxxel, you do not need to write custom training states, or explicitly instantiate checkpointers and loggers. Simply supply your model, optimizer, curriculum, and a loss_fn, along with a unified save_path directory.
import jax
import optax
from flax import nnx
from roxxel import Roxxel, Curriculum, Trainer
# 1. Define Flax NNX model and optimizer
model = nnx.Linear(10, 5, rngs=nnx.Rngs(42))
tx = optax.sgd(0.01)
optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)
# 2. Define the curriculum
phases = [{"steps": 1000, "batch_size": 4, "seq_len": 10}]
curriculum = Curriculum(primary_streamer=Roxxel("./data_*.rox"), phases=phases)
# 3. Define the loss function
def loss_fn(model, batch):
logits = model(batch[:, :-1].astype(jax.numpy.float32))
targets = batch[:, 1:].astype(jax.numpy.float32)
return jax.numpy.mean((logits - targets) ** 2)
# 4. Initialize the Trainer
# Setting save_path automatically initializes the checkpointer and logger
trainer = Trainer(
model=model,
optimizer=optimizer,
curriculum=curriculum,
loss_fn=loss_fn,
save_path="./run_delta",
checkpoint_every=100,
log_every=10
)
# 5. Run curriculum training
trainer.run()
Core Features
1. Automated ModelState Creation
When you pass a standard JAX model and optimizer separately, the trainer constructs a ModelState object internally. It maintains:
- state.model: Reference to the Flax NNX Module.
- state.optimizer: Reference to the Flax NNX Optimizer.
- state.step: An nnx.Variable representing the global optimization step.
If you already have a pre-constructed custom state object containing model and optimizer attributes, the trainer automatically detects it for backward compatibility.
2. Internal JIT Train Step Compilation
The Trainer automatically defines and compiles a standard Flax JIT training step (@nnx.jit) on initialization. It executes:
- Forward pass through your loss_fn.
- Gradient computation via nnx.value_and_grad.
- Optimizer parameters update.
- Step counter incrementation.
3. Strict Scalar Loss Expectation
The user-supplied loss_fn is expected to return a single JAX/float scalar loss value. Returning multiple outputs (such as auxiliary dictionaries, lists, or tuples) is not supported, ensuring clear separation of metric logging and core model optimization.
4. Automatic Resource Management
If save_path is passed, the trainer automatically initializes:
- A Checkpointer located in save_path/checkpoints.
- A Logger saving metrics and system logs directly inside save_path.
Alternatively, you can pass custom checkpointer and logger instances or individual overrides as paths directly to checkpointer and logger arguments.
The trainer automatically executes all process-critical training steps within the logger's asynchronous context manager to guarantee tracebacks are logged and flushing occurs even during training crashes. It also executes asynchronous checkpointer flushes and close routines in final cleanup hooks.
5. NaN Loss Validation Guard
During periodic logging (log_every) and checkpointing (checkpoint_every) intervals, the trainer materializes the loss value on the CPU. The trainer automatically validates that the loss value is not a NaN. If a NaN is detected, it immediately raises a ValueError to halt execution.
Because this validation is performed only on logging/checkpointing steps (where the CPU must block to retrieve the value anyway), it introduces zero extra host-device synchronization latency to the asynchronous JAX compilation pipeline.
API Reference
Trainer
roxxel.trainer.Trainer
Curriculum-aware pre-training orchestrator designed for JAX/Flax NNX.
Accepts the Curriculum schedule (which wraps the Roxxel dataset streamers) and manages the pre-training loop execution, boundary transitions, hot-swapping, asynchronous logging, evaluations, and Orbax checkpointing.
Source code in roxxel/trainer.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | |
__init__(model, optimizer, curriculum, loss_fn, save_path=None, checkpointer=None, logger=None, eval_fn=None, eval_every=500, checkpoint_every=100, log_every=100, seed=42, mesh=None, data_sharding=None, max_to_keep=3, timeout=1000, async_queue_depth=2, grad_accum_steps=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The JAX training state / model instance. If a pre-constructed state
object containing |
required |
optimizer
|
Optimizer
|
The Optax optimizer/Flax NNX optimizer instance. Can be None if a pre-constructed state is passed as the first argument. |
required |
curriculum
|
Curriculum
|
The curriculum schedule object. |
required |
loss_fn
|
callable
|
The loss function: loss_fn(model, batch) -> scalar. |
required |
save_path
|
str
|
The root directory where checkpoints and logs are saved.
If provided, |
None
|
checkpointer
|
(Checkpointer, str)
|
Asynchronous Checkpointer instance or directory path to automatically initialize it. |
None
|
logger
|
(Logger, str)
|
Asynchronous Logger instance or directory path to automatically initialize it. |
None
|
eval_fn
|
callable
|
Callback for periodic evaluations: eval_fn(state) -> str/None. |
None
|
eval_every
|
int
|
Run evaluations every N steps. Defaults to 500. |
500
|
checkpoint_every
|
int
|
Save checkpoint every N steps. Defaults to 100. |
100
|
log_every
|
int
|
Log training metrics every N steps. Defaults to 100. |
100
|
seed
|
int
|
Base random seed for stream replication. Defaults to 42. |
42
|
mesh
|
Mesh
|
JAX hardware mesh sharding specification. |
None
|
data_sharding
|
NamedSharding
|
JAX named sharding specification. |
None
|
max_to_keep
|
int
|
Max checkpoints to keep when initializing checkpointer path. Defaults to 3. |
3
|
timeout
|
int
|
Timeout for async operations when initializing checkpointer path. Defaults to 1000. |
1000
|
async_queue_depth
|
int
|
Maximum number of asynchronous steps to queue on device before blocking host to prevent memory buildup. Defaults to 2. |
2
|
grad_accum_steps
|
int
|
Number of micro-batches to accumulate gradients over. If None, defaults to 1 (no accumulation). |
None
|
Source code in roxxel/trainer.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
run()
Executes the curriculum training loop, automatically handling skips, resumptions, blending weights, and dynamic shape transitions at phase boundaries.
Source code in roxxel/trainer.py
ModelState
roxxel.trainer.ModelState
Bases: Module
Unified JAX/Flax NNX state module containing the model, optimizer, and step counter. Created internally by the Trainer.