Skip to main content

Flax-Pilot

Flax-Pilot aims to simplify the process of writing training loops for Google's Flax framework. As someone new to Flax, I started this project to deepen my understanding. This module represents a beginner's exploration into building efficient training workflows, emphasizing the need for further expertise to refine and expand its capabilities. Future plans include integrating multiple optimizer training, diverse metric modules, callbacks, and advancing towards more complex training loops, aiming to enhance its functionality and versatility. Flax-Pilot supports distributed training, ensuring scalability and efficiency across multiple devices.

As of 27-7-2024, the trainer is available as package PyPI version for GPU & CPU.

How to Use?

🛠️ Write a flax.linen Module

import flax.linen as nn
class CNN(nn.Module):
    @nn.compact
    def __call__(self, x, deterministic):
        x = nn.Conv(features=32, kernel_size=(3, 3))(x)
        x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
        x = x.reshape((x.shape[0], -1))  
        x = nn.Dense(features=256)(x)
        x = nn.Dropout(rate=0.5, deterministic=deterministic)(x)
        x = nn.Dense(features=10)(x)
        return x

🔧 Define Optimizer, Input Shapes, and Dict of Loss & Metric Trackers

Loss trackers (lt) takes in scalar loss value and averages it throughout training.
Metric trackers (mt) takes in y_true, y_pred and computes metric score and averages throughout training.

import optax as tx

opt = tx.adam(0.0001)
input_shape = {'x': (1, 28, 28, 1)}

from fpilot import Trackers as tr

# Create tracker instances.
loss_metric_tracker_dict = {
    'lt': {'loss': tr.Mean()},
    'mt': {'F1': tr.F1Score(threshold=0.6, num_classes=10, average='macro')}
}

🧮 Create loss_fn

A function that takes these certain params as written below in the code and returns scalar loss, dict of loss, mutable variables and tracker updates.

Key names lt, mt shouldn't be changed anywhere, as training loops depend on those keys. Subkey names, loss, F1 are free to be changed but must match across loss_metric_tracker_dict and loss_metric_value_dict.

import optax as tx

# This fn's 1st return value is differentiated wrt the fn's first param.
def loss_fn(params, mut_variables, apply, sample, deterministic, det_key, step, objective):
    x, y = sample
    yp = apply(params, x, deterministic=deterministic, rngs={'dropout': det_key})
    
    # No mutable vars in this model so,
    mut_variables = {}
    
    loss = tx.softmax_cross_entropy(y, yp).mean()
    loss_metric_value_dict = {'lt': {'loss': loss}, 'mt': {'F1': (y, yp)}}
    return loss, mut_variables, loss_metric_value_dict

🏋️ Create Trainer Instance

from fpilot import Trainer

trainer = Trainer(CNN(), input_shape, optimizer, loss_fn, loss_metric_tracker_dict)

📈 Train the Model & Evaluate

train_ds = ... # tf.data.Dataset as numpy iterator
val_ds = ... # tf.data.Dataset as numpy iterator
train_steps, val_steps = 10000, 1000 # steps per epoch
ckpt_path = "/saved/model/model_1"  # If set to None, no checkpoints will be saved during training.

trainer.train(epochs, train_ds, val_ds, train_steps, val_steps, ckpt_path)

What's next?

  • Seperate package for TPU.
  • Callbacks.
  • TensorBoard logging.

Demo

Demo notebooks will be available in code section here.

Metadata

Release files for flax-pilot 0.2.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flax-pilot 0.2.5
File Size Uploaded
flax_pilot-0.2.5.tar.gz 11.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for flax-pilot 0.2.5
File Interpreter ABI Platform
flax_pilot-0.2.5-py3-none-any.whl Python 3 none any Details

Total release size: 24.6 kB

Release files / flax_pilot-0.2.5.tar.gz

Download URL flax_pilot-0.2.5.tar.gz
Size 11.5 kB
Tags Source
SHA-256 checksum
How to use checksums
3744726db00b28f97ca692a57c612062831143f5ed78500dbcfa51772e555600
BLAKE2b-256 checksum
How to use checksums
3b3055293780ee787967b227d44811a57660e4c7fa20694ad27756612467fba4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.11.10

Release files / flax_pilot-0.2.5-py3-none-any.whl

Download URL flax_pilot-0.2.5-py3-none-any.whl
Size 13.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
be6012227abde802a8e28c261d7bc0a43631b3b91e0c733602417a9fc9939c19
BLAKE2b-256 checksum
How to use checksums
92ca9b5645b239b5c347209e619a391ee9b6d704c8d36509f9e04f8ab4674e94
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.11.10

Release history Release notifications | RSS feed

This release

0.2.5 This release

2 release files

0.2.4

2 release files

0.2.3

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.13

2 release files

0.1.12

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page