Skip to main content

Tests License PyPI - Version PyPI - Python Version

⚠️The package is under development, expect bugs and breaking changes!

Torch Training Loop

Simple Keras-inspired Training Loop for Pytorch.

Installation

pip install torch-training-loop

Features

  • Simple API for training Torch models;
  • Support training DataParallel and DistributedDataParallel models;
  • Support Keras-like callbacks for logging metrics to Tensorboard, model checkpoint, and early stopping;
  • Show training & validation progress via tqdm;
  • Display metrics during training & validation via torcheval.

Usage

This package consists of two main classes for training Torch models: TrainingLoop and SimpleTrainingStep. In order to train a torch model, you need to initiate these two classes:

import torch
from torch.optim import Adam
from torcheval.metrics import MulticlassAccuracy
from training_loop import TrainingLoop, SimpleTrainingStep
from training_loop.callbacks import EarlyStopping

model = ...
# Support training DataParallel models.
# model = DataParallel(model)

train_dataloader = ...
val_dataloader = ...

loop = TrainingLoop(
    model,
    step=SimpleTrainingStep(
        optimizer_fn=lambda params: Adam(params, lr=0.0001),
        loss=torch.nn.CrossEntropyLoss(),
        metrics=('accuracy', MulticlassAccuracy(num_classes=10)),
    ),
    device='cuda',
)
loop.fit(
    train_dataloader,
    val_dataloader,
    epochs=10,
    callbacks=[
        EarlyStopping(monitor='val_loss', mode='min', patience=20),
    ],
)

In the above example, initializing the SimpleTrainingStep class and calling the fit() method of the TrainingLoop class are very similar to that of Keras API. Additionally, you can also train DistributedDataParallel models to utilize multigpus setup. Currently, it only supports training on single-node multigpus machines.

from contextlib import contextmanager
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.optim import Adam
from torcheval.metrics import MulticlassAccuracy
from training_loop import SimpleTrainingStep
from training_loop.distributed import DistributedTrainingLoop


@contextmanager
def setup_ddp(rank, world_size):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'
    dist.init_process_group('nccl', rank=rank, world_size=world_size)
    try:
        yield
    finally:
        os.environ.pop('MASTER_ADDR')
        os.environ.pop('MASTER_PORT')
        dist.destroy_process_group()


def train_ddp(rank, world_size):
    with setup_ddp(rank, world_size):
        model = ...
        model = DDP(model, device_ids=[rank])

        train_loader = ...
        val_loader = ...

        loop = DistributedTrainingLoop(
            model,
            step=SimpleTrainingStep(
                optimizer_fn=lambda params: Adam(params, lr=0.0001),
                loss=torch.nn.CrossEntropyLoss(),
                metrics=('accuracy', MulticlassAccuracy(num_classes=10)),
            ),
            device=rank,
            rank=rank,
        )

        loop.fit(train_loader, val_loader, epochs=1)


def main():
    world_size = torch.cuda.device_count()

    mp.spawn(
        train_ddp,
        args=(world_size, ),
        nprocs=world_size,
        join=True,
    )

    return 0


if __name__ == '__main__':
    exit(main())

You can find more examples and documentation in the source code and in the examples folder.

License

Distributed under the MIT License. See LICENSE.txt for more information.

Metadata

Release files for torch-training-loop 0.1.3

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

Source distribution (sdist)

Source distribution for torch-training-loop 0.1.3
File Size Uploaded Provenance
torch_training_loop-0.1.3.tar.gz 20.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for torch-training-loop 0.1.3
File Interpreter ABI Platform
torch_training_loop-0.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 44.9 kB

Release files / torch_training_loop-0.1.3.tar.gz

Download URL torch_training_loop-0.1.3.tar.gz
Size 20.1 kB
Tags Source
SHA-256 checksum
How to use checksums
5d95a7d604c3b0993a7450969146aa1ba358aee3027f771db9a56c2b1ab7c4b0
BLAKE2b-256 checksum
How to use checksums
802e666a7da0f862ee67f71984ae700a91ce1fe833e4ced0c6ec8076573b99c0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.12.1 Linux/6.2.0-1018-azure

Release files / torch_training_loop-0.1.3-py3-none-any.whl

Download URL torch_training_loop-0.1.3-py3-none-any.whl
Size 24.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e7484adbcdeaacd6ddaf6b84dd8e6755d2076509153c6fd0922fbc5f96e40e1
BLAKE2b-256 checksum
How to use checksums
38474a1502da69d0c7536a5d98f2c7465fee2df681cfaac108ba50eed754a44a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.12.1 Linux/6.2.0-1018-azure

Security for torch-training-loop 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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