{"nbformat": 4, "cells": [{"source": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Learning Rate Schedules\n\nSetting the learning rate for stochastic gradient descent (SGD) is crucially important when training neural networks because it controls both the speed of convergence and the ultimate performance of the network. One of the simplest learning rate strategies is to have a fixed learning rate throughout the training process. Choosing a small learning rate allows the optimizer find good solutions, but this comes at the expense of limiting the initial speed of convergence. Changing the learning rate over time can overcome this tradeoff.\n\nSchedules define how the learning rate changes over time and are typically specified for each epoch or iteration (i.e. batch) of training. Schedules differ from adaptive methods (such as AdaDelta and Adam) because they:\n\n* change the global learning rate for the optimizer, rather than parameter-wise learning rates\n* don't take feedback from the training process and are specified beforehand\n\nIn this tutorial, we visualize the schedules defined in `mx.lr_scheduler`, show how to implement custom schedules and see an example of using a schedule while training models. Since schedules are passed to `mx.optimizer.Optimizer` classes, these methods work with both Module and Gluon APIs.", "cell_type": "markdown", "metadata": {}}, {"source": "from __future__ import print_function\nimport math\nimport matplotlib.pyplot as plt\nimport mxnet as mx\nfrom mxnet.gluon import nn\nfrom mxnet.gluon.data.vision import transforms\nimport numpy as np\n%matplotlib inline", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "def plot_schedule(schedule_fn, iterations=1500):\n # Iteration count starting at 1\n iterations = [i+1 for i in range(iterations)]\n lrs = [schedule_fn(i) for i in iterations]\n plt.scatter(iterations, lrs)\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Learning Rate\")\n plt.show()", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "## Schedules\n\nIn this section, we take a look at the schedules in `mx.lr_scheduler`. All of these schedules define the learning rate for a given iteration, and it is expected that iterations start at 1 rather than 0. So to find the learning rate for the 100th iteration, you can call `schedule(100)`.\n\n### Stepwise Decay Schedule\n\nOne of the most commonly used learning rate schedules is called stepwise decay, where the learning rate is reduced by a factor at certain intervals. MXNet implements a `FactorScheduler` for equally spaced intervals, and `MultiFactorScheduler` for greater control. We start with an example of halving the learning rate every 250 iterations. More precisely, the learning rate will be multiplied by `factor` _after_ the `step` index and multiples thereafter. So in the example below the learning rate of the 250th iteration will be 1 and the 251st iteration will be 0.5.", "cell_type": "markdown", "metadata": {}}, {"source": "schedule = mx.lr_scheduler.FactorScheduler(step=250, factor=0.5)\nschedule.base_lr = 1\nplot_schedule(schedule)", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "Note: the `base_lr` is used to determine the initial learning rate. It takes a default value of 0.01 since we inherit from `mx.lr_scheduler.LRScheduler`, but it can be set as a property of the schedule. We will see later in this tutorial that `base_lr` is set automatically when providing the `lr_schedule` to `Optimizer`. Also be aware that the schedules in `mx.lr_scheduler` have state (i.e. counters, etc) so calling the schedule out of order may give unexpected results.\n\nWe can define non-uniform intervals with `MultiFactorScheduler` and in the example below we halve the learning rate _after_ the 250th, 750th (i.e. a step length of 500 iterations) and 900th (a step length of 150 iterations). As before, the learning rate of the 250th iteration will be 1 and the 251th iteration will be 0.5.", "cell_type": "markdown", "metadata": {}}, {"source": "schedule = mx.lr_scheduler.MultiFactorScheduler(step=[250, 750, 900], factor=0.5)\nschedule.base_lr = 1\nplot_schedule(schedule)", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "### Polynomial Schedule\n\nStepwise schedules and the discontinuities they introduce may sometimes lead to instability in the optimization, so in some cases smoother schedules are preferred. `PolyScheduler` gives a smooth decay using a polynomial function and reaches a learning rate of 0 after `max_update` iterations. In the example below, we have a quadratic function (`pwr=2`) that falls from 0.998 at iteration 1 to 0 at iteration 1000. After this the learning rate stays at 0, so nothing will be learnt from `max_update` iterations onwards.", "cell_type": "markdown", "metadata": {}}, {"source": "schedule = mx.lr_scheduler.PolyScheduler(max_update=1000, base_lr=1, pwr=2)\nplot_schedule(schedule)", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "Note: unlike `FactorScheduler`, the `base_lr` is set as an argument when instantiating the schedule.\n\nAnd we don't evaluate at `iteration=0` (to get `base_lr`) since we are working with schedules starting at `iteration=1`.\n\n### Custom Schedules\n\nYou can implement your own custom schedule with a function or callable class, that takes an integer denoting the iteration index (starting at 1) and returns a float representing the learning rate to be used for that iteration. We implement the Cosine Annealing Schedule in the example below as a callable class (see `__call__` method).", "cell_type": "markdown", "metadata": {}}, {"source": "class CosineAnnealingSchedule():\n def __init__(self, min_lr, max_lr, cycle_length):\n self.min_lr = min_lr\n self.max_lr = max_lr\n self.cycle_length = cycle_length\n \n def __call__(self, iteration):\n if iteration <= self.cycle_length:\n unit_cycle = (1 + math.cos(iteration * math.pi / self.cycle_length)) / 2\n adjusted_cycle = (unit_cycle * (self.max_lr - self.min_lr)) + self.min_lr\n return adjusted_cycle\n else:\n return self.min_lr\n\n\nschedule = CosineAnnealingSchedule(min_lr=0, max_lr=1, cycle_length=1000)\nplot_schedule(schedule)", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "## Using Schedules\n\nWhile training a simple handwritten digit classifier on the MNIST dataset, we take a look at how to use a learning rate schedule during training. Our demonstration model is a basic convolutional neural network. We start by preparing our `DataLoader` and defining the network. \n\nAs discussed above, the schedule should return a learning rate given an (1-based) iteration index.", "cell_type": "markdown", "metadata": {}}, {"source": "# Use GPU if one exists, else use CPU\nctx = mx.gpu() if mx.context.num_gpus() else mx.cpu()\n\n# MNIST images are 28x28. Total pixels in input layer is 28x28 = 784\nnum_inputs = 784\n# Clasify the images into one of the 10 digits\nnum_outputs = 10\n# 64 images in a batch\nbatch_size = 64\n\n# Load the training data\ntrain_dataset = mx.gluon.data.vision.MNIST(train=True).transform_first(transforms.ToTensor())\ntrain_dataloader = mx.gluon.data.DataLoader(train_dataset, batch_size, shuffle=True, num_workers=5)\n\n# Build a simple convolutional network\ndef build_cnn():\n net = nn.HybridSequential()\n with net.name_scope():\n # First convolution\n net.add(nn.Conv2D(channels=10, kernel_size=5, activation='relu'))\n net.add(nn.MaxPool2D(pool_size=2, strides=2))\n # Second convolution\n net.add(nn.Conv2D(channels=20, kernel_size=5, activation='relu'))\n net.add(nn.MaxPool2D(pool_size=2, strides=2))\n # Flatten the output before the fully connected layers\n net.add(nn.Flatten())\n # First fully connected layers with 512 neurons\n net.add(nn.Dense(512, activation=\"relu\"))\n # Second fully connected layer with as many neurons as the number of classes\n net.add(nn.Dense(num_outputs))\n return net\n \nnet = build_cnn()", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "We then initialize our network (technically deferred until we pass the first batch) and define the loss.", "cell_type": "markdown", "metadata": {}}, {"source": "# Initialize the parameters with Xavier initializer\nnet.collect_params().initialize(mx.init.Xavier(), ctx=ctx)\n# Use cross entropy loss\nsoftmax_cross_entropy = mx.gluon.loss.SoftmaxCrossEntropyLoss()", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "We're now ready to create our schedule, and in this example we opt for a stepwise decay schedule using `MultiFactorScheduler`. Since we're only training a demonstration model for a limited number of epochs (10 in total) we will exaggerate the schedule and drop the learning rate by 90% after the 4th, 7th and 9th epochs. We call these steps, and the drop occurs _after_ the step index. Schedules are defined for iterations (i.e. training batches), so we must represent our steps in iterations too.", "cell_type": "markdown", "metadata": {}}, {"source": "steps_epochs = [4, 7, 9]\n# assuming we keep partial batches, see `last_batch` parameter of DataLoader\niterations_per_epoch = math.ceil(len(train_dataset) / batch_size)\n# iterations just before starts of epochs (iterations are 1-indexed)\nsteps_iterations = [s*iterations_per_epoch for s in steps_epochs]\nprint(\"Learning rate drops after iterations: {}\".format(steps_iterations))", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": " Learning rate drops after iterations: [3752, 6566, 8442]", "cell_type": "markdown", "metadata": {}}, {"source": "schedule = mx.lr_scheduler.MultiFactorScheduler(step=steps_iterations, factor=0.1)", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "**We create our `Optimizer` and pass the schedule via the `lr_scheduler` parameter.** In this example we're using Stochastic Gradient Descent.", "cell_type": "markdown", "metadata": {}}, {"source": "sgd_optimizer = mx.optimizer.SGD(learning_rate=0.03, lr_scheduler=schedule)", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "And we use this optimizer (with schedule) in our `Trainer` and train for 10 epochs. Alternatively, we could have set the `optimizer` to the string `sgd`, and pass a dictionary of the optimizer parameters directly to the trainer using `optimizer_params`.", "cell_type": "markdown", "metadata": {}}, {"source": "trainer = mx.gluon.Trainer(params=net.collect_params(), optimizer=sgd_optimizer)", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "num_epochs = 10\n# epoch and batch counts starting at 1\nfor epoch in range(1, num_epochs+1):\n # Iterate through the images and labels in the training data\n for batch_num, (data, label) in enumerate(train_dataloader, start=1):\n # get the images and labels\n data = data.as_in_context(ctx)\n label = label.as_in_context(ctx)\n # Ask autograd to record the forward pass\n with mx.autograd.record():\n # Run the forward pass\n output = net(data)\n # Compute the loss\n loss = softmax_cross_entropy(output, label)\n # Compute gradients\n loss.backward()\n # Update parameters\n trainer.step(data.shape[0])\n\n # Show loss and learning rate after first iteration of epoch\n if batch_num == 1:\n curr_loss = mx.nd.mean(loss).asscalar()\n curr_lr = trainer.learning_rate\n print(\"Epoch: %d; Batch %d; Loss %f; LR %f\" % (epoch, batch_num, curr_loss, curr_lr))", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "We see that the learning rate starts at 0.03, and falls to 0.00003 by the end of training as per the schedule we defined.\n\n### Manually setting the learning rate: Gluon API only\n\nWhen using the method above you don't need to manually keep track of iteration count and set the learning rate, so this is the recommended approach for most cases. Sometimes you might want more fine-grained control over setting the learning rate though, so Gluon's `Trainer` provides the `set_learning_rate` method for this.\n\nWe replicate the example above, but now keep track of the `iteration_idx`, call the schedule and set the learning rate appropriately using `set_learning_rate`. We also use `schedule.base_lr` to set the initial learning rate for the schedule since we are calling the schedule directly and not using it as part of the `Optimizer`.", "cell_type": "markdown", "metadata": {}}, {"source": "net = build_cnn()\nnet.collect_params().initialize(mx.init.Xavier(), ctx=ctx)\n\nschedule = mx.lr_scheduler.MultiFactorScheduler(step=steps_iterations, factor=0.1)\nschedule.base_lr = 0.03\nsgd_optimizer = mx.optimizer.SGD()\ntrainer = mx.gluon.Trainer(params=net.collect_params(), optimizer=sgd_optimizer)\n\niteration_idx = 1\nnum_epochs = 10\n# epoch and batch counts starting at 1\nfor epoch in range(1, num_epochs + 1):\n # Iterate through the images and labels in the training data\n for batch_num, (data, label) in enumerate(train_dataloader, start=1):\n # get the images and labels\n data = data.as_in_context(ctx)\n label = label.as_in_context(ctx)\n # Ask autograd to record the forward pass\n with mx.autograd.record():\n # Run the forward pass\n output = net(data)\n # Compute the loss\n loss = softmax_cross_entropy(output, label)\n # Compute gradients\n loss.backward()\n # Update the learning rate\n lr = schedule(iteration_idx)\n trainer.set_learning_rate(lr)\n # Update parameters\n trainer.step(data.shape[0])\n # Show loss and learning rate after first iteration of epoch\n if batch_num == 1:\n curr_loss = mx.nd.mean(loss).asscalar()\n curr_lr = trainer.learning_rate\n print(\"Epoch: %d; Batch %d; Loss %f; LR %f\" % (epoch, batch_num, curr_loss, curr_lr))\n iteration_idx += 1", "cell_type": "code", "execution_count": null, "outputs": [], "metadata": {}}, {"source": "\n\n\n\n\n\n\n\n\n\n\n\nOnce again, we see the learning rate start at 0.03, and fall to 0.00003 by the end of training as per the schedule we defined.\n\n## Advanced Schedules\n\nWe have a related tutorial on Advanced Learning Rate Schedules that shows reference implementations of schedules that give state-of-the-art results. We look at cyclical schedules applied to a variety of cycle shapes, and many other techniques such as warm-up and cool-down.\n\n\n", "cell_type": "markdown", "metadata": {}}], "metadata": {"display_name": "", "name": "", "language": "python"}, "nbformat_minor": 2}