Learner, Metrics, and Basic Callbacks

Open In Colab

Basic class for handling the training loop

  1. /usr/local/lib/python3.8/dist-packages/torch/cuda/__init__.py:52: UserWarning: CUDA initialization: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx (Triggered internally at /pytorch/c10/cuda/CUDAFunctions.cpp:100.)
  2. return torch._C._cuda_getDeviceCount() > 0

You probably want to jump directly to the definition of Learner.

Utils function

replacing_yield[source]

replacing_yield(o, attr, val)

Context manager to temporarily replace an attribute

  1. class _A:
  2. def __init__(self, a): self.a = a
  3. @contextmanager
  4. def a_changed(self, v): return replacing_yield(self, 'a', v)
  5. a = _A(42)
  6. with a.a_changed(32):
  7. test_eq(a.a, 32)
  8. test_eq(a.a, 42)

mk_metric[source]

mk_metric(m)

Convert m to an AvgMetric, unless it’s already a Metric

See the class Metric below for more information.

save_model[source]

save_model(file, model, opt, with_opt=True, pickle_protocol=2)

Save model to file along with opt (if available, and if with_opt)

file can be a Path object, a string or an opened file object. pickle_protocol is passed along to torch.save

load_model[source]

load_model(file, model, opt, with_opt=True, device=None, strict=True)

Load model from file along with opt (if available, and if with_opt)

file can be a Path object, a string or an opened file object. If a device is passed, the model is loaded on it, otherwise it’s loaded on the CPU.

If strict is True, the file must exactly contain weights for every parameter key in model, if strict is False, only the keys that are in the saved model are loaded in model.

class Learner[source]

Learner(dls, model, loss_func=None, opt_func=Adam, lr=0.001, splitter=trainable_params, cbs=None, metrics=None, path=None, model_dir='models', wd=None, wd_bn_bias=False, train_bn=True, moms=(0.95, 0.85, 0.95)) :: GetAttr

Group together a model, some dls and a loss_func to handle training

opt_func will be used to create an optimizer when Learner.fit is called, with lr as a default learning rate. splitter is a function that takes self.model and returns a list of parameter groups (or just one parameter group if there are no different parameter groups). The default is trainable_params, which returns all trainable parameters of the model.

cbs is one or a list of Callbacks to pass to the Learner. Callbacks are used for every tweak of the training loop. Each Callback is registered as an attribute of Learner (with camel case). At creation, all the callbacks in defaults.callbacks (TrainEvalCallback, Recorder and ProgressCallback) are associated to the Learner.

metrics is an optional list of metrics, that can be either functions or Metrics (see below).

path and model_dir are used to save and/or load models. Often path will be inferred from dls, but you can override it or pass a Path object to model_dir. Make sure you can write in path/model_dir!

wd is the default weight decay used when training the model; moms, the default momentums used in Learner.fit_one_cycle. wd_bn_bias controls if weight decay is applied to BatchNorm layers and bias.

Lastly, train_bn controls if BatchNorm layers are trained even when they are supposed to be frozen according to the splitter. Our empirical experiments have shown that it’s the best behavior for those layers in transfer learning.

PyTorch interop

You can use regular PyTorch functionality for most of the arguments of the Learner, although the experience will be smoother with pure fastai objects and you will be able to use the full functionality of the library. The expectation is that the training loop will work smoothly even if you did not use fastai end to end. What you might lose are interpretation objects or showing functionality. The list below explains how to use plain PyTorch objects for all the arguments and what you might lose.

The most important is opt_func. If you are not using a fastai optimizer, you will need to write a function that wraps your PyTorch optimizer in an OptimWrapper. See the optimizer module for more details. This is to ensure the library’s schedulers/freeze API work with your code.

  • dls is a DataLoaders object, that you can create from standard PyTorch dataloaders. By doing so, you will lose all showing functionality like show_batch/show_results. You can check the data block API or the mid-level data API tutorial to learn how to use fastai to gather your data!
  • model is a standard PyTorch model. You can use anyone you like, just make sure it accepts the number of inputs you have in your DataLoaders and returns as many outputs as you have targets.
  • loss_func can be any loss function you like. It needs to be one of fastai’s if you want to use Learn.predict or Learn.get_preds, or you will have to implement special methods (see more details after the BaseLoss documentation).

Training loop

Now let’s look at the main thing the Learner class implements: the training loop.

Learner.fit[source]

Learner.fit(n_epoch, lr=None, wd=None, cbs=None, reset_opt=False)

Fit self.model for n_epoch using cbs. Optionally reset_opt.

Uses lr and wd if they are provided, otherwise use the defaults values given by the lr and wd attributes of Learner.

All the examples use synth_learner which is a simple Learner training a linear regression model.

  1. learn = synth_learner(lr=0.1)
  2. learn(_before_epoch)
  3. learn.model = learn.model.cpu()
  4. xb,yb = learn.dls.one_batch()
  5. init_loss = learn.loss_func(learn.model(xb), yb)
  6. learn.fit(10)
  7. xb,yb = learn.dls.one_batch()
  8. final_loss = learn.loss_func(learn.model(xb), yb)
  9. assert final_loss < init_loss, (final_loss,init_loss)

Learner.one_batch[source]

Learner.one_batch(i, b)

Train or evaluate self.model on batch (xb,yb)

This is an internal method called by Learner.fit. If passed, i is the index of this iteration in the epoch. In training mode, this does a full training step on the batch (compute predictions, loss, gradients, update the model parameters and zero the gradients). In validation mode, it stops at the loss computation. Training or validation is controlled internally by the TrainEvalCallback through the training attribute.

Nothing is returned, but the attributes x, y, pred, loss of the Learner are set with the proper values:

  1. b = learn.dls.one_batch()
  2. learn.one_batch(0, b)
  3. test_eq(learn.x, b[0])
  4. test_eq(learn.y, b[1])
  5. out = learn.model(learn.x)
  6. test_eq(learn.pred, out)
  7. test_eq(learn.loss, learn.loss_func(out, b[1]))

Learner.all_batches[source]

Learner.all_batches()

Train or evaluate self.model on all the batches of self.dl

Learner.create_opt[source]

Learner.create_opt()

Create an optimizer with default hyper-parameters

This method is called internally to create the optimizer, the hyper-parameters are then adjusted by what you pass to Learner.fit or your particular schedulers (see callback.schedule).

  1. learn = synth_learner(n_train=5, cbs=VerboseCallback())
  2. assert learn.opt is None
  3. learn.create_opt()
  4. assert learn.opt is not None
  5. test_eq(learn.opt.hypers[0]['lr'], learn.lr)
  1. after_create

Callback handling

We only describe the basic functionality linked to Callbacks here. To learn more about Callbacks an how to write them, check the callback.core module documentation.

Let’s first see how the Callbacks become attributes of Learner:

  1. class TstCallback(Callback):
  2. def batch_begin(self): self.learn.a = self.a + 1
  3. tst_learn = synth_learner()
  4. test_eq(len(tst_learn.cbs), 1)
  5. assert isinstance(tst_learn.cbs[0], TrainEvalCallback)
  6. assert hasattr(tst_learn, ('train_eval'))
  7. tst_learn = synth_learner(cbs=TstCallback())
  8. test_eq(len(tst_learn.cbs), 2)
  9. assert isinstance(tst_learn.cbs[1], TstCallback)
  10. assert hasattr(tst_learn, ('tst'))

Learner.__call__[source]

Learner.__call__(event_name)

Call event_name for all Callbacks in self.cbs

This how the Callbacks are called internally. For instance a VerboseCallback just prints the event names (can be useful for debugging):

  1. learn = synth_learner(cbs=VerboseCallback())
  2. learn('after_fit')
  1. after_create
  2. after_fit

Learner.add_cb[source]

Learner.add_cb(cb)

Add cb to the list of Callback and register self as their learner

  1. learn = synth_learner()
  2. learn.add_cb(TestTrainEvalCallback())
  3. test_eq(len(learn.cbs), 2)
  4. assert isinstance(learn.cbs[1], TestTrainEvalCallback)
  5. test_eq(learn.train_eval.learn, learn)

Learner.add_cbs[source]

Learner.add_cbs(cbs)

Add cbs to the list of Callback and register self as their learner

  1. learn.add_cbs([TestTrainEvalCallback(), TestTrainEvalCallback()])
  2. test_eq(len(learn.cbs), 4)

Learner.added_cbs[source]

Learner.added_cbs(cbs)

Context manage that temporarily adds cbs

  1. learn = synth_learner()
  2. test_eq(len(learn.cbs), 1)
  3. with learn.added_cbs(TestTrainEvalCallback()):
  4. test_eq(len(learn.cbs), 2)

Learner.ordered_cbs[source]

Learner.ordered_cbs(event)

List of Callbacks, in order, for an event in the training loop

By order, we mean using the internal ordering of the Callbacks (see callback.core for more information on how it works).

  1. learn = synth_learner()
  2. learn.add_cb(TestTrainEvalCallback())
  3. learn.ordered_cbs('before_fit')
  1. [TrainEvalCallback, TestTrainEvalCallback]

Learner.remove_cb[source]

Learner.remove_cb(cb)

Add cb from the list of Callback and deregister self as their learner

  1. learn = synth_learner()
  2. learn.add_cb(TestTrainEvalCallback())
  3. cb = learn.cbs[1]
  4. learn.remove_cb(learn.cbs[1])
  5. test_eq(len(learn.cbs), 1)
  6. assert cb.learn is None
  7. assert not getattr(learn,'test_train_eval',None)

cb can simply be the class of the Callback we want to remove (in which case all instances of that callback are removed).

  1. learn = synth_learner()
  2. learn.add_cbs([TestTrainEvalCallback(), TestTrainEvalCallback()])
  3. learn.remove_cb(TestTrainEvalCallback)
  4. test_eq(len(learn.cbs), 1)
  5. assert not getattr(learn,'test_train_eval',None)

Learner.remove_cbs[source]

Learner.remove_cbs(cbs)

Remove cbs from the list of Callback and deregister self as their learner

Elements of cbs can either be types of callbacks or actual callbacks of the Learner.

  1. learn = synth_learner()
  2. learn.add_cbs([TestTrainEvalCallback() for _ in range(3)])
  3. cb = learn.cbs[1]
  4. learn.remove_cbs(learn.cbs[1:])
  5. test_eq(len(learn.cbs), 1)

Learner.removed_cbs[source]

Learner.removed_cbs(cbs)

Context manage that temporarily removes cbs

Elements of cbs can either be types of callbacks or actual callbacks of the Learner.

  1. learn = synth_learner()
  2. learn.add_cb(TestTrainEvalCallback())
  3. with learn.removed_cbs(learn.cbs[1]):
  4. test_eq(len(learn.cbs), 1)
  5. test_eq(len(learn.cbs), 2)

Learner.show_training_loop[source]

Learner.show_training_loop()

Show each step in the training loop

At each step, callbacks are shown in order, which can help debugging.

  1. learn = synth_learner()
  2. learn.show_training_loop()
  1. Start Fit
  2. - before_fit : [TrainEvalCallback]
  3. Start Epoch Loop
  4. - before_epoch : []
  5. Start Train
  6. - before_train : [TrainEvalCallback]
  7. Start Batch Loop
  8. - before_batch : []
  9. - after_pred : []
  10. - after_loss : []
  11. - before_backward: []
  12. - before_step : []
  13. - after_step : []
  14. - after_cancel_batch: []
  15. - after_batch : [TrainEvalCallback]
  16. End Batch Loop
  17. End Train
  18. - after_cancel_train: []
  19. - after_train : []
  20. Start Valid
  21. - before_validate: [TrainEvalCallback]
  22. Start Batch Loop
  23. - **CBs same as train batch**: []
  24. End Batch Loop
  25. End Valid
  26. - after_cancel_validate: []
  27. - after_validate : []
  28. End Epoch Loop
  29. - after_cancel_epoch: []
  30. - after_epoch : []
  31. End Fit
  32. - after_cancel_fit: []
  33. - after_fit : []

before_batch_cb[source]

before_batch_cb(f)

Shortcut for creating a Callback on the before_batch event, which takes and returns xb,yb

In order to change the data passed to your model, you will generally want to hook into the before_batch event, like so:

  1. class TstCallback(Callback):
  2. def before_batch(self):
  3. self.learn.xb = self.xb + 1000
  4. self.learn.yb = self.yb - 1000

Since that is so common, we provide the before_batch_cb decorator to make it easier.

  1. @before_batch_cb
  2. def cb(self, xb, yb): return xb+1000,yb-1000

Serializing

Learner.save[source]

Learner.save(file, with_opt=True, pickle_protocol=2)

Save model and optimizer state (if with_opt) to self.path/self.model_dir/file

file can be a Path, a string or a buffer. pickle_protocol is passed along to torch.save.

Learner.load[source]

Learner.load(file, device=None, with_opt=True, strict=True)

Load model and optimizer state (if with_opt) from self.path/self.model_dir/file using device

file can be a Path, a string or a buffer. Use device to load the model/optimizer state on a device different from the one it was saved.

  1. with tempfile.TemporaryDirectory() as d:
  2. learn = synth_learner(path=d)
  3. learn.fit(1)
  4. #Test save created a file
  5. learn.save('tmp')
  6. assert (Path(d)/'models/tmp.pth').exists()
  7. #Test load did load the model
  8. learn1 = synth_learner(path=d)
  9. learn1 = learn1.load('tmp')
  10. test_eq(learn.a, learn1.a)
  11. test_eq(learn.b, learn1.b)
  12. test_eq(learn.opt.state_dict(), learn1.opt.state_dict())

Learner.export[source]

Learner.export(fname='export.pkl', pickle_module=pickle, pickle_protocol=2)

Export the content of self without the items and the optimizer state for inference

The Learner is saved in self.path/fname, using pickle_protocol. Note that serialization in Python saves the names of functions, not the code itself. Therefore, any custom code you have for models, data transformation, loss function etc… should be put in a module that you will import in your training environment before exporting, and in your deployment environment before loading it.

load_learner[source]

load_learner(fname, cpu=True, pickle_module=pickle)

Load a Learner object in fname, optionally putting it on the cpu

Warning: load_learner requires all your custom code be in the exact same place as when exporting your Learner (the main script, or the module you imported it from).

fastai provides to_detach which by default detachs tensor gradients, and gathers (calling maybe_gather) tensors from all ranks if running in distributed data parallel (DDP) mode.

When running in DDP mode all ranks need to have the same batch size, and DistributedDL takes care of padding batches as needed; however when gathering all tensors (e.g. for calculating metrics, inference, etc.) we need to discard the padded items. DistributedDL provides a method to_detach that removes padding appropriately.

Calling to_detach_from_dl with learn as a learner will attempt to find a to_detach method in the learner’s last used DataLoader dl and use that one if found, otherwise it will resort to the vanilla to_detach.

to_detach_from_dl[source]

to_detach_from_dl(learn:Learner'>, <class 'NoneType'>), b:object, cpu:bool=True, gather:bool=True)

class Metric[source]

Metric()

Blueprint for defining a metric

Metrics can be simple averages (like accuracy) but sometimes their computation is a little bit more complex and can’t be averaged over batches (like precision or recall), which is why we need a special class for them. For simple functions that can be computed as averages over batches, we can use the class AvgMetric, otherwise you’ll need to implement the following methods.

Note: If your Metric has state depending on tensors, don’t forget to store it on the CPU to avoid any potential memory leaks.

Metric.reset[source]

Metric.reset()

Reset inner state to prepare for new computation

Metric.accumulate[source]

Metric.accumulate(learn)

Use learn to update the state with new results

Metric.value[source]

The value of the metric

Metric.name[source]

Name of the Metric, camel-cased and with Metric removed

class AvgMetric[source]

AvgMetric(func) :: Metric

Average the values of func taking into account potential different batch sizes

  1. learn = synth_learner()
  2. tst = AvgMetric(lambda x,y: (x-y).abs().mean())
  3. t,u = torch.randn(100),torch.randn(100)
  4. tst.reset()
  5. for i in range(0,100,25):
  6. learn.pred,learn.yb = t[i:i+25],(u[i:i+25],)
  7. tst.accumulate(learn)
  8. test_close(tst.value, (t-u).abs().mean())

class AvgLoss[source]

AvgLoss() :: Metric

Average the losses taking into account potential different batch sizes

  1. tst = AvgLoss()
  2. t = torch.randn(100)
  3. tst.reset()
  4. for i in range(0,100,25):
  5. learn.yb,learn.loss = t[i:i+25],t[i:i+25].mean()
  6. tst.accumulate(learn)
  7. test_close(tst.value, t.mean())

class AvgSmoothLoss[source]

AvgSmoothLoss(beta=0.98) :: Metric

Smooth average of the losses (exponentially weighted with beta)

  1. tst = AvgSmoothLoss()
  2. t = torch.randn(100)
  3. tst.reset()
  4. val = tensor(0.)
  5. for i in range(4):
  6. learn.loss = t[i*25:(i+1)*25].mean()
  7. tst.accumulate(learn)
  8. val = val*0.98 + t[i*25:(i+1)*25].mean()*(1-0.98)
  9. test_close(val/(1-0.98**(i+1)), tst.value)

class ValueMetric[source]

ValueMetric(func, metric_name=None) :: Metric

Use to include a pre-calculated metric value (for instance calculated in a Callback) and returned by func

  1. def metric_value_fn(): return 5e-3
  2. vm = ValueMetric(metric_value_fn, 'custom_value_metric')
  3. test_eq(vm.value, 5e-3)
  4. test_eq(vm.name, 'custom_value_metric')
  5. vm = ValueMetric(metric_value_fn)
  6. test_eq(vm.name, 'metric_value_fn')

class Recorder[source]

Recorder(add_time=True, train_metrics=False, valid_metrics=True, beta=0.98) :: Callback

Callback that registers statistics (lr, loss and metrics) during training

By default, metrics are computed on the validation set only, although that can be changed by adjusting train_metrics and valid_metrics. beta is the weight used to compute the exponentially weighted average of the losses (which gives the smooth_loss attribute to Learner).

The logger attribute of a Learner determines what happens to those metrics. By default, it just print them:

  1. def tst_metric(out, targ): return F.mse_loss(out, targ)
  2. learn = synth_learner(n_train=5, metrics=tst_metric)
  3. # pat = r"[tensor(d.d*), tensor(d.d*), tensor(d.d*), 'dd:dd']"
  4. pat = r"[d, d+.d+, d+.d+, d+.d+, 'dd:dd']"
  5. test_stdout(lambda: learn.fit(1), pat, regex=True)

Internals

Recorder.before_fit[source]

Recorder.before_fit()

Prepare state for training

Recorder.before_epoch[source]

Recorder.before_epoch()

Set timer if self.add_time=True

Recorder.before_validate[source]

Recorder.before_validate()

Reset loss and metrics state

Recorder.after_batch[source]

Recorder.after_batch()

Update all metrics and records lr and smooth loss in training

Recorder.after_epoch[source]

Recorder.after_epoch()

Store and log the loss/metric values

Plotting tools

Recorder.plot_loss[source]

Recorder.plot_loss(skip_start=5, with_valid=True)

Plot the losses from skip_start and onward

Inference functions

Learner.validate[source]

Learner.validate(ds_idx=1, dl=None, cbs=None)

Validate on dl with potential new cbs.

  1. learn = synth_learner(n_train=5, metrics=tst_metric)
  2. res = learn.validate()
  3. test_eq(res[0], res[1])
  4. x,y = learn.dls.valid_ds.tensors
  5. test_close(res[0], F.mse_loss(learn.model(x), y), 1e-3)

Learner.get_preds[source]

Learner.get_preds(ds_idx=1, dl=None, with_input=False, with_decoded=False, with_loss=False, act=None, inner=False, reorder=True, cbs=None, save_preds=None, save_targs=None, concat_dim=0)

Get the predictions and targets on the ds_idx-th dbunchset or dl, optionally with_input and with_loss

with_decoded will also return the decoded predictions using the decodes function of the loss function (if it exists). For instance, fastai’s CrossEntropyFlat takes the argmax or predictions in its decodes.

Depending on the loss_func attribute of Learner, an activation function will be picked automatically so that the predictions make sense. For instance if the loss is a case of cross-entropy, a softmax will be applied, or if the loss is binary cross entropy with logits, a sigmoid will be applied. If you want to make sure a certain activation function is applied, you can pass it with act.

save_preds and save_targs should be used when your predictions are too big to fit all in memory. Give a Path object that points to a folder where the predictions and targets will be saved.

concat_dim is the batch dimension, where all the tensors will be concatenated.

inner is an internal attribute that tells get_preds it’s called internally, inside another training loop, to avoid recursion errors.

Note: If you want to use the option with_loss=True on a custom loss function, make sure you have implemented a reduction attribute that supports ’none’

  1. learn = synth_learner(n_train=5, metrics=tst_metric)
  2. preds,targs = learn.get_preds()
  3. x,y = learn.dls.valid_ds.tensors
  4. test_eq(targs, y)
  5. test_close(preds, learn.model(x))
  6. preds,targs = learn.get_preds(act = torch.sigmoid)
  7. test_eq(targs, y)
  8. test_close(preds, torch.sigmoid(learn.model(x)))

Learner.predict[source]

Learner.predict(item, rm_type_tfms=None, with_input=False)

Prediction on item, fully decoded, loss function decoded and probabilities

It returns a tuple of three elements with, in reverse order,

  • the prediction from the model, potentially passed through the activation of the loss function (if it has one)
  • the decoded prediction, using the potential decodes method from it
  • the fully decoded prediction, using the transforms used to build the Datasets/DataLoaders

rm_type_tfms is a deprecated argument that should not be used and will be removed in a future version. with_input will add the decoded inputs to the result.

  1. class _FakeLossFunc(Module):
  2. reduction = 'none'
  3. def forward(self, x, y): return F.mse_loss(x,y)
  4. def activation(self, x): return x+1
  5. def decodes(self, x): return 2*x
  6. class _Add1(Transform):
  7. def encodes(self, x): return x+1
  8. def decodes(self, x): return x-1
  9. learn = synth_learner(n_train=5)
  10. dl = TfmdDL(Datasets(torch.arange(50), tfms = [L(), [_Add1()]]))
  11. learn.dls = DataLoaders(dl, dl)
  12. learn.loss_func = _FakeLossFunc()
  13. inp = tensor([2.])
  14. out = learn.model(inp).detach()+1 #applying model + activation
  15. dec = 2*out #decodes from loss function
  16. full_dec = dec-1 #decodes from _Add1
  17. test_eq(learn.predict(inp), [full_dec,dec,out])
  18. test_eq(learn.predict(inp, with_input=True), [inp,full_dec,dec,out])

Learner.show_results[source]

Learner.show_results(ds_idx=1, dl=None, max_n=9, shuffle=True, **kwargs)

Show some predictions on ds_idx-th dataset or dl

Will show max_n samples (unless the batch size of ds_idx or dl is less than max_n, in which case it will show as many samples) and shuffle the data unless you pass false to that flag. kwargs are application-dependent.

We can’t show an example on our synthetic Learner, but check all the beginners tutorials which will show you how that method works across applications.

The last functions in this section are used internally for inference, but should be less useful to you.

Learner.no_logging[source]

Learner.no_logging()

Context manager to temporarily remove logger

  1. learn = synth_learner(n_train=5, metrics=tst_metric)
  2. with learn.no_logging():
  3. test_stdout(lambda: learn.fit(1), '')
  4. test_eq(learn.logger, print)

Learner.loss_not_reduced[source]

Learner.loss_not_reduced()

A context manager to evaluate loss_func with reduction set to none.

This requires your loss function to either have a reduction attribute or a reduction argument (like all fastai and PyTorch loss functions).

Transfer learning

Learner.freeze_to[source]

Learner.freeze_to(n)

Freeze parameter groups up to n

Learner.freeze[source]

Learner.freeze()

Freeze up to last parameter group

Learner.unfreeze[source]

Learner.unfreeze()

Unfreeze the entire model

TTA

Learner.tta[source]

Learner.tta(ds_idx=1, dl=None, n=4, item_tfms=None, batch_tfms=None, beta=0.25, use_max=False)

Return predictions on the ds_idx dataset or dl using Test Time Augmentation

In practice, we get the predictions n times with the transforms of the training set and average those. The final predictions are (1-beta) multiplied by this average + beta multiplied by the predictions obtained with the transforms of the dataset. Set beta to None to get a tuple of the predictions and tta results. You can also use the maximum of all predictions instead of an average by setting use_max=True.

If you want to use new transforms, you can pass them with item_tfms and batch_tfms.


Company logo

©2021 fast.ai. All rights reserved.
Site last generated: Mar 31, 2021