summaryrefslogtreecommitdiffstats
path: root/training/lr.py
blob: 0c5ce9e66ee528fa07c73ca31491c4a2eeca50c9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import math
import copy

import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.optim.lr_scheduler import LambdaLR
from tqdm.auto import tqdm

from training.util import AverageMeter


class LRFinder():
    def __init__(self, accelerator, model, optimizer, train_dataloader, val_dataloader, loss_fn):
        self.accelerator = accelerator
        self.model = model
        self.optimizer = optimizer
        self.train_dataloader = train_dataloader
        self.val_dataloader = val_dataloader
        self.loss_fn = loss_fn

        # self.model_state = copy.deepcopy(model.state_dict())
        # self.optimizer_state = copy.deepcopy(optimizer.state_dict())

    def run(self, min_lr, skip_start=10, skip_end=5, num_epochs=100, num_train_batches=1, num_val_batches=math.inf, smooth_f=0.05, diverge_th=5):
        best_loss = None
        best_acc = None

        lrs = []
        losses = []
        accs = []

        lr_scheduler = get_exponential_schedule(self.optimizer, min_lr, num_epochs)

        steps = min(num_train_batches, len(self.train_dataloader))
        steps += min(num_val_batches, len(self.val_dataloader))
        steps *= num_epochs

        progress_bar = tqdm(
            range(steps),
            disable=not self.accelerator.is_local_main_process,
            dynamic_ncols=True
        )
        progress_bar.set_description("Epoch X / Y")

        for epoch in range(num_epochs):
            progress_bar.set_description(f"Epoch {epoch + 1} / {num_epochs}")

            avg_loss = AverageMeter()
            avg_acc = AverageMeter()

            self.model.train()

            for step, batch in enumerate(self.train_dataloader):
                if step >= num_train_batches:
                    break

                with self.accelerator.accumulate(self.model):
                    loss, acc, bsz = self.loss_fn(batch)

                    self.accelerator.backward(loss)

                    self.optimizer.step()
                    self.optimizer.zero_grad(set_to_none=True)

                if self.accelerator.sync_gradients:
                    progress_bar.update(1)

            self.model.eval()

            with torch.inference_mode():
                for step, batch in enumerate(self.val_dataloader):
                    if step >= num_val_batches:
                        break

                    loss, acc, bsz = self.loss_fn(batch)
                    avg_loss.update(loss.detach_(), bsz)
                    avg_acc.update(acc.detach_(), bsz)

                    progress_bar.update(1)

            lr_scheduler.step()

            loss = avg_loss.avg.item()
            acc = avg_acc.avg.item()

            if epoch == 0:
                best_loss = loss
                best_acc = acc
            else:
                if smooth_f > 0:
                    loss = smooth_f * loss + (1 - smooth_f) * losses[-1]
                    acc = smooth_f * acc + (1 - smooth_f) * accs[-1]
                if loss < best_loss:
                    best_loss = loss
                if acc > best_acc:
                    best_acc = acc

            lr = lr_scheduler.get_last_lr()[0]

            lrs.append(lr)
            losses.append(loss)
            accs.append(acc)

            progress_bar.set_postfix({
                "loss": loss,
                "loss/best": best_loss,
                "acc": acc,
                "acc/best": best_acc,
                "lr": lr,
            })

            # self.model.load_state_dict(self.model_state)
            # self.optimizer.load_state_dict(self.optimizer_state)

            if loss > diverge_th * best_loss:
                print("Stopping early, the loss has diverged")
                break

        if skip_end == 0:
            lrs = lrs[skip_start:]
            losses = losses[skip_start:]
            accs = accs[skip_start:]
        else:
            lrs = lrs[skip_start:-skip_end]
            losses = losses[skip_start:-skip_end]
            accs = accs[skip_start:-skip_end]

        fig, ax_loss = plt.subplots()

        ax_loss.plot(lrs, losses, color='red')
        ax_loss.set_xscale("log")
        ax_loss.set_xlabel("Learning rate")
        ax_loss.set_ylabel("Loss")

        ax_acc = ax_loss.twinx()
        ax_acc.plot(lrs, accs, color='blue')
        ax_acc.set_ylabel("Accuracy")

        print("LR suggestion: steepest gradient")
        min_grad_idx = None

        try:
            min_grad_idx = (np.gradient(np.array(losses))).argmin()
        except ValueError:
            print(
                "Failed to compute the gradients, there might not be enough points."
            )

        if min_grad_idx is not None:
            print("Suggested LR: {:.2E}".format(lrs[min_grad_idx]))
            ax_loss.scatter(
                lrs[min_grad_idx],
                losses[min_grad_idx],
                s=75,
                marker="o",
                color="red",
                zorder=3,
                label="steepest gradient",
            )
            ax_loss.legend()


def get_exponential_schedule(optimizer, min_lr, num_epochs, last_epoch=-1):
    def lr_lambda(current_epoch: int):
        return min_lr + ((current_epoch / num_epochs) ** 10) * (1 - min_lr)

    return LambdaLR(optimizer, lr_lambda, last_epoch)