Skip to main content

A lightweight Python package that supplies batteries-included abstractions for PyTorch workflows

Project description

torch-batteries

PyPI version License: MIT Docs

torch-batteries
Image generated by AI

A lightweight Python package that supplies batteries-included abstractions for:

  • Data loading pipelines
  • Model training loops
  • Evaluation workflows
  • Metrics computation
  • Experiment tracking (Weights & Biases)

Designed to reduce boilerplate and standardize experiment code.

Installation

pip install torch-batteries

Quick Start

Define workflow steps directly on a PyTorch model with @charge. Return StepOutput to expose the same predictions used for the loss to automatic metrics:

import torch
from torch import nn
from torch.nn import functional as F

from torch_batteries import Battery, Event, EventContext, StepOutput, charge


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.linear = nn.Linear(10, 1)

    @charge(Event.TRAIN_STEP)
    def training_step(self, context: EventContext) -> StepOutput:
        inputs, targets = context["batch"]
        predictions = self.linear(inputs)
        return StepOutput(
            loss=F.mse_loss(predictions, targets),
            predictions=predictions,
            targets=targets,
        )


model = Model()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
battery = Battery(
    model,
    optimizer=optimizer,
    metrics={"mae": lambda pred, target: F.l1_loss(pred, target)},
)
results = battery.train(train_loader, val_loader=None, epochs=10)

Automatic metrics are the functions passed to Battery(metrics=...). They use the predictions and targets returned in StepOutput and are averaged across each phase without an additional model forward pass.

Optional Dependencies

For experiment tracking with Weights & Biases:

pip install torch-batteries[wandb]

Examples

Explore practical examples demonstrating torch-batteries features:

Example Description Notebook Colab
Function Fitting with MLP Train a neural network to approximate a polynomial function using the event-driven training approach function_fitting.ipynb Open In Colab
Image Classification with CNN Train a Convolutional Neural Network (CNN) for image classification image_classification.ipynb Open In Colab
Learning Rate Sweep with Early Stopping Conduct a learning rate sweep on MNIST classification with aggressive early stopping and log results to Weights & Biases lr_sweep_early_stopping.ipynb Open In Colab

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

torch_batteries-0.7.0.tar.gz (34.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

torch_batteries-0.7.0-py3-none-any.whl (42.6 kB view details)

Uploaded Python 3

File details

Details for the file torch_batteries-0.7.0.tar.gz.

File metadata

  • Download URL: torch_batteries-0.7.0.tar.gz
  • Upload date:
  • Size: 34.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for torch_batteries-0.7.0.tar.gz
Algorithm Hash digest
SHA256 8d031523504ca13e03d65c5bfb400698fc6db40142c05b62941095911f353391
MD5 f366a27f1187079aca9233bd98b27823
BLAKE2b-256 5a3c3eebbd0dc9b5b72cd8c4ce9c9d0b1a84522b19f1d8e01ce1c13e1b7833c0

See more details on using hashes here.

File details

Details for the file torch_batteries-0.7.0-py3-none-any.whl.

File metadata

File hashes

Hashes for torch_batteries-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2881409d1b5ee18cf6fc02a8fc1aa017c483386f919b84237f3f296e3da2b6cb
MD5 69f1670ed8e3225676ec7bd8c50527f5
BLAKE2b-256 c38f5e1b7df728cbf817c77b686f3d361c8f4145da826cafe2d288c853f98e2b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page