A fastai Learner from Scratch
This final chapter (other than the conclusion and the online chapters) is going to look a bit different. It contains far more code and far less prose than the previous chapters. We will introduce new Python keywords and libraries without discussing them. This chapter is meant to be the start of a significant research project for you. You see, we are going to implement many of the key pieces of the fastai and PyTorch APIs from scratch, building on nothing other than the components that we developed in <<chapter_foundations>>! The key goal here is to end up with your own Learner class, and some callbacks—enough to be able to train a model on Imagenette, including examples of each of the key techniques we've studied. On the way to building Learner, we will create our own version of Module, Parameter, and parallel DataLoader so you have a very good idea of what those PyTorch classes do.
The end-of-chapter questionnaire is particularly important for this chapter. This is where we will be pointing you in the many interesting directions that you could take, using this chapter as your starting point. We suggest that you follow along with this chapter on your computer, and do lots of experiments, web searches, and whatever else you need to understand what's going on. You've built up the skills and expertise to do this in the rest of this book, so we think you are going to do great!
Let's begin by gathering (manually) some data.
Data
Have a look at the source to untar_data to see how it works. We'll use it here to access the 160-pixel version of Imagenette for use in this chapter:
To access the image files, we can use get_image_files:
Or we could do the same thing using just Python's standard library, with glob:
If you look at the source for get_image_files, you'll see it uses Python's os.walk; this is a faster and more flexible function than glob, so be sure to try it out.
We can open an image with the Python Imaging Library's Image class:
That's going to be the basis of our independent variable. For our dependent variable, we can use Path.parent from pathlib. First we'll need our vocab:
...and the reverse mapping, thanks to L.val2idx:
That's all the pieces we need to put together our Dataset.
Dataset
A Dataset in PyTorch can be anything that supports indexing (__getitem__) and len:
We need a list of training and validation filenames to pass to Dataset.__init__:
Now we can try it out:
As you see, our dataset is returning the independent and dependent variables as a tuple, which is just what we need. We'll need to be able to collate these into a mini-batch. Generally this is done with torch.stack, which is what we'll use here:
Here's a mini-batch with two items, for testing our collate:
Now that we have a dataset and a collation function, we're ready to create DataLoader. We'll add two more things here: an optional shuffle for the training set, and a ProcessPoolExecutor to do our preprocessing in parallel. A parallel data loader is very important, because opening and decoding a JPEG image is a slow process. One CPU core is not enough to decode images fast enough to keep a modern GPU busy. Here's our DataLoader class:
Let's try it out with our training and validation datasets:
This data loader is not much slower than PyTorch's, but it's far simpler. So if you're debugging a complex data loading process, don't be afraid to try doing things manually to help you see exactly what's going on.
For normalization, we'll need image statistics. Generally it's fine to calculate these on a single training mini-batch, since precision isn't needed here:
Our Normalize class just needs to store these stats and apply them (to see why the to_device is needed, try commenting it out, and see what happens later in this notebook):
We always like to test everything we build in a notebook, as soon as we build it:
Here tfm_x isn't just applying Normalize, but is also permuting the axis order from NHWC to NCHW (see <<chapter_convolutions>> if you need a reminder of what these acronyms refer to). PIL uses HWC axis order, which we can't use with PyTorch, hence the need for this permute.
That's all we need for the data for our model. So now we need the model itself!
Module and Parameter
To create a model, we'll need Module. To create Module, we'll need Parameter, so let's start there. Recall that in <<chapter_collab>> we said that the Parameter class "doesn't actually add any functionality (other than automatically calling requires_grad_ for us). It's only used as a "marker" to show what to include in parameters." Here's a definition which does exactly that:
The implementation here is a bit awkward: we have to define the special __new__ Python method and use the internal PyTorch method _make_subclass because, as at the time of writing, PyTorch doesn't otherwise work correctly with this kind of subclassing or provide an officially supported API to do this. This may have been fixed by the time you read this, so look on the book's website to see if there are updated details.
Our Parameter now behaves just like a tensor, as we wanted:
Now that we have this, we can define Module:
The key functionality is in the definition of parameters:
This means that we can ask any Module for its parameters, and it will return them, including all its child modules (recursively). But how does it know what its parameters are? It's thanks to implementing Python's special __setattr__ method, which is called for us any time Python sets an attribute on a class. Our implementation includes this line:
As you see, this is where we use our new Parameter class as a "marker"—anything of this class is added to our params.
Python's __call__ allows us to define what happens when our object is treated as a function; we just call forward (which doesn't exist here, so it'll need to be added by subclasses). Before we do, we'll call a hook, if it's defined. Now you can see that PyTorch hooks aren't doing anything fancy at all—they're just calling any hooks that have been registered.
Other than these pieces of functionality, our Module also provides cuda and training attributes, which we'll use shortly.
Now we can create our first Module, which is ConvLayer:
We're not implementing F.conv2d from scratch, since you should have already done that (using unfold) in the questionnaire in <<chapter_foundations>>. Instead, we're just creating a small class that wraps it up along with bias and weight initialization. Let's check that it works correctly with Module.parameters:
And that we can call it (which will result in forward being called):
In the same way, we can implement Linear:
and test if it works:
Let's also create a testing module to check that if we include multiple parameters as attributes, they are all correctly registered:
Since we have a conv layer and a linear layer, each of which has weights and biases, we'd expect four parameters in total:
We should also find that calling cuda on this class puts all these parameters on the GPU:
We can now use those pieces to create a CNN.
Simple CNN
As we've seen, a Sequential class makes many architectures easier to implement, so let's make one:
The forward method here just calls each layer in turn. Note that we have to use the register_modules method we defined in Module, since otherwise the contents of layers won't appear in parameters.
important: All The Code is Here: Remember that we're not using any PyTorch functionality for modules here; we're defining everything ourselves. So if you're not sure what
register_modulesdoes, or why it's needed, have another look at our code forModuleto see what we wrote!
We can create a simplified AdaptivePool that only handles pooling to a 1×1 output, and flattens it as well, by just using mean:
That's enough for us to create a CNN!
Let's see if our parameters are all being registered correctly:
Now we can try adding a hook. Note that we've only left room for one hook in Module; you could make it a list, or use something like Pipeline to run a few as a single function:
We have data and model. Now we need a loss function.
Loss
We've already seen how to define "negative log likelihood":
Well actually, there's no log here, since we're using the same definition as PyTorch. That means we need to put the log together with softmax:
Combining these gives us our cross-entropy loss:
Note that the formula:
gives a simplification when we compute the log softmax, which was previously defined as (x.exp()/(x.exp().sum(-1))).log():
Then, there is a more stable way to compute the log of the sum of exponentials, called the LogSumExp trick. The idea is to use the following formula:
where is the maximum of .
Here's the same thing in code:
We'll put that into a function:
so we can use it for our log_softmax function:
Which gives the same result as before:
We can use these to create cross_entropy:
Let's now combine all those pieces together to create a Learner.
Learner
We have data, a model, and a loss function; we only need one more thing before we can fit a model, and that's an optimizer! Here's SGD:
As we've seen in this book, life is easier with a Learner. The Learner class needs to know our training and validation sets, which means we need DataLoaders to store them. We don't need any other functionality, just a place to store them and access them:
Now we're ready to create our Learner class:
This is the largest class we've created in the book, but each method is quite small, so by looking at each in turn you should be able to follow what's going on.
The main method we'll be calling is fit. This loops with:
and at each epoch calls self.one_epoch for each of train=True and then train=False. Then self.one_epoch calls self.one_batch for each batch in dls.train or dls.valid, as appropriate (after wrapping the DataLoader in fastprogress.progress_bar. Finally, self.one_batch follows the usual set of steps to fit one mini-batch that we've seen throughout this book.
Before and after each step, Learner calls self, which calls __call__ (which is standard Python functionality). __call__ uses getattr(cb,name) on each callback in self.cbs, which is a Python built-in function that returns the attribute (a method, in this case) with the requested name. So, for instance, self('before_fit') will call cb.before_fit() for each callback where that method is defined.
As you can see, Learner is really just using our standard training loop, except that it's also calling callbacks at appropriate times. So let's define some callbacks!
Callbacks
In Learner.__init__ we have:
In other words, every callback knows what learner it is used in. This is critical, since otherwise a callback can't get information from the learner, or change things in the learner. Because getting information from the learner is so common, we make that easier by defining Callback as a subclass of GetAttr, with a default attribute of learner:
GetAttr is a fastai class that implements Python's standard __getattr__ and __dir__ methods for you, such that any time you try to access an attribute that doesn't exist, it passes the request along to whatever you have defined as _default.
For instance, we want to move all model parameters to the GPU automatically at the start of fit. We could do this by defining before_fit as self.learner.model.cuda(); however, because learner is the default attribute, and we have SetupLearnerCB inherit from Callback (which inherits from GetAttr), we can remove the .learner and just call self.model.cuda():
In SetupLearnerCB we also move each mini-batch to the GPU, by calling to_device(self.batch) (we could also have used the longer to_device(self.learner.batch). Note however that in the line self.learner.batch = tfm_x(xb),yb we can't remove .learner, because here we're setting the attribute, not getting it.
Before we try our Learner out, let's create a callback to track and print progress. Otherwise we won't really know if it's working properly:
Now we're ready to use our Learner for the first time!
It's quite amazing to realize that we can implement all the key ideas from fastai's Learner in so little code! Let's now add some learning rate scheduling.
Scheduling the Learning Rate
If we're going to get good results, we'll want an LR finder and 1cycle training. These are both annealing callbacks—that is, they are gradually changing hyperparameters as we train. Here's LRFinder:
This shows how we're using CancelFitException, which is itself an empty class, only used to signify the type of exception. You can see in Learner that this exception is caught. (You should add and test CancelBatchException, CancelEpochException, etc. yourself.) Let's try it out, by adding it to our list of callbacks:
And take a look at the results:
Now we can define our OneCycle training callback:
We'll try an LR of 0.1:
Let's fit for a while and see how it looks (we won't show all the output in the book—try it in the notebook to see the results):
Finally, we'll check that the learning rate followed the schedule we defined (as you see, we're not using cosine annealing here):
Conclusion
We have explored how the key concepts of the fastai library are implemented by re-implementing them in this chapter. Since it's mostly full of code, you should definitely try to experiment with it by looking at the corresponding notebook on the book's website. Now that you know how it's built, as a next step be sure to check out the intermediate and advanced tutorials in the fastai documentation to learn how to customize every bit of the library.
Questionnaire
tip: Experiments: For the questions here that ask you to explain what some function or class is, you should also complete your own code experiments.
What is
glob?How do you open an image with the Python imaging library?
What does
L.mapdo?What does
Selfdo?What is
L.val2idx?What methods do you need to implement to create your own
Dataset?Why do we call
convertwhen we open an image from Imagenette?What does
~do? How is it useful for splitting training and validation sets?Does
~work with theLorTensorclasses? What about NumPy arrays, Python lists, or pandas DataFrames?What is
ProcessPoolExecutor?How does
L.range(self.ds)work?What is
__iter__?What is
first?What is
permute? Why is it needed?What is a recursive function? How does it help us define the
parametersmethod?Write a recursive function that returns the first 20 items of the Fibonacci sequence.
What is
super?Why do subclasses of
Moduleneed to overrideforwardinstead of defining__call__?In
ConvLayer, why doesinitdepend onact?Why does
Sequentialneed to callregister_modules?Write a hook that prints the shape of every layer's activations.
What is "LogSumExp"?
Why is
log_softmaxuseful?What is
GetAttr? How is it helpful for callbacks?Reimplement one of the callbacks in this chapter without inheriting from
CallbackorGetAttr.What does
Learner.__call__do?What is
getattr? (Note the case difference toGetAttr!)Why is there a
tryblock infit?Why do we check for
model.traininginone_batch?What is
store_attr?What is the purpose of
TrackResults.before_epoch?What does
model.cudado? How does it work?Why do we need to check
model.traininginLRFinderandOneCycle?Use cosine annealing in
OneCycle.
Further Research
Write
resnet18from scratch (refer to <<chapter_resnet>> as needed), and train it with theLearnerin this chapter.Implement a batchnorm layer from scratch and use it in your
resnet18.Write a Mixup callback for use in this chapter.
Add momentum to SGD.
Pick a few features that you're interested in from fastai (or any other library) and implement them in this chapter.
Pick a research paper that's not yet implemented in fastai or PyTorch and implement it in this chapter.
Port it over to fastai.
Submit a pull request to fastai, or create your own extension module and release it.
Hint: you may find it helpful to use
nbdevto create and deploy your package.