Skip to main content

reloading

pypi badge

A Python utility to reload a loop body from source on each iteration without losing state

Useful for editing source code during training of deep learning models. This lets you e.g. add logging, print statistics or save the model without restarting the training and, therefore, without losing the training progress.

Demo

Install

pip install reloading

Usage

To reload the body of a for loop from source before each iteration, simply wrap the iterator with reloading, e.g.

from reloading import reloading

for i in reloading(range(10)):
    # this code will be reloaded before each iteration
    print(i)

To reload a function from source before each execution, decorate the function definition with @reloading, e.g.

from reloading import reloading

@reloading
def some_function():
    # this code will be reloaded before each invocation
    pass

Additional Options

Pass the keyword argument every to reload only on every n-th invocation or iteration. E.g.

for i in reloading(range(1000), every=10):
    # this code will only be reloaded before every 10th iteration
    # this can help to speed-up tight loops
    pass

@reloading(every=10)
def some_function():
    # this code with only be reloaded before every 10th invocation
    pass

Pass forever=True instead of an iterable to create an endless reloading loop, e.g.

for i in reloading(forever=True):
    # this code will loop forever and reload from source before each iteration
    pass

Examples

Here are the short snippets of how to use reloading with your favourite library. For complete examples, check out the examples folder.

PyTorch

for epoch in reloading(range(NB_EPOCHS)):
    # the code inside this outer loop will be reloaded before each epoch

    for images, targets in dataloader:
        optimiser.zero_grad()
        predictions = model(images)
        loss = F.cross_entropy(predictions, targets)
        loss.backward()
        optimiser.step()

Here is a full PyTorch example.

fastai

@reloading
def update_learner(learner):
    # this function will be reloaded from source before each epoch so that you
    # can make changes to the learner while the training is running
    pass

class LearnerUpdater(LearnerCallback):
    def on_epoch_begin(self, **kwargs):
        update_learner(self.learn)

path = untar_data(URLs.MNIST_SAMPLE)
data = ImageDataBunch.from_folder(path)
learn = cnn_learner(data, models.resnet18, metrics=accuracy, 
                    callback_fns=[LearnerUpdater])
learn.fit(10)

Here is a full fastai example.

Keras

@reloading
def update_model(model):
    # this function will be reloaded from source before each epoch so that you
    # can make changes to the model while the training is running using
    # K.set_value()
    pass

class ModelUpdater(Callback):
    def on_epoch_begin(self, epoch, logs=None):
        update_model(self.model)

model = Sequential()
model.add(Dense(64, activation='relu', input_dim=20))
model.add(Dense(10, activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
              optimizer=sgd,
              metrics=['accuracy'])

model.fit(x_train, y_train,
          epochs=200,
          batch_size=128,
          callbacks=[ModelUpdater()])

Here is a full Keras example.

TensorFlow

for epoch in reloading(range(NB_EPOCHS)):
    # the code inside this outer loop will be reloaded from source
    # before each epoch so that you can change it during training
  
    train_loss.reset_states()
    train_accuracy.reset_states()
    test_loss.reset_states()
    test_accuracy.reset_states()
  
    for images, labels in tqdm(train_ds):
      train_step(images, labels)
  
    for test_images, test_labels in tqdm(test_ds):
      test_step(test_images, test_labels)

Here is a full TensorFlow example.

Testing

Make sure you have python and python3 available in your path, then run:

$ python3 reloading/test_reloading.py

Download files

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

Source Distribution

reloading-1.1.1.tar.gz (7.8 kB view details)

Uploaded Source

Built Distribution

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

reloading-1.1.1-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file reloading-1.1.1.tar.gz.

File metadata

  • Download URL: reloading-1.1.1.tar.gz
  • Upload date:
  • Size: 7.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.4.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.9.1

File hashes

Hashes for reloading-1.1.1.tar.gz
Algorithm Hash digest
SHA256 5a493e658ce7e6a8013af6efe9cc1ae422907a0b0c788bc04666f1f819cb9a8a
MD5 0a572450ae35a4e56ab3e315f7c754c3
BLAKE2b-256 2eea239fb1b52c4f611c438f057b9ee5eced1923306649369f72f6c6bfff6937

See more details on using hashes here.

File details

Details for the file reloading-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: reloading-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 8.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.4.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.9.1

File hashes

Hashes for reloading-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e213d04f6011101502fa32c874f6ba136ce53f36f12183925ea5c28d38ea7bf5
MD5 99c0ad38806d9756fd2c418af23883d9
BLAKE2b-256 6a49b6cbdcb25e3268ca2fddf27c2483d3778fb9ab47f516866e580930bf4206

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 Sentry Error logging StatusPage Status page