Standalone Deep Learning

KAIST Idea factory YouTube lecture


Theory


Advanced Optimizations


Batch Gradient Descent

\[\theta = \theta - \eta\nabla J(\theta)\]
  • \(\theta\) : Parameter set of the model
  • \(\eta\) : Learning rate
  • \(J(\theta)\)

Problem:

  • Consumes a lot of memory

  • Since a large amount of data must be trained at once, gradient computation is slow ⇒ optimization is also slow


Stochastic Gradient Descent

  • stochastic ↔ Deterministic
  • Uses mini-batches
    • Has a stochastic gradient depending on the mini-batch
  • Through many iterations it converges similarly to BGD while computing gradients faster than BGD
  • The stochasticity also increases the likelihood of avoiding the problem of getting stuck in local minima

💡

Problem & Motivation

  • The problem of getting stuck in local minima and saddle points
  • A fixed learning rate for all parameters

    ⇒ A step size (= learning rate) that does not reflect how far training has progressed hinders finding the optimal solution

  • An oscillating training path ⇒ slowdown

Advanced Optimization Algorithms

Figure

Saddle Point

Figure

Long Valley

Figure


Momentum SGD

torch.optim.SGD(momentum=0.9)

Figure

\[\theta = \theta - v_t \\ v_t = \gamma v_{t-1} + \eta \nabla_\theta J(\theta)\]
  • \(v_t\): the actual step (next velocity)

    : Determines the next step by adding the past velocity (\(v_{t-1}\)) and the gradient

  • A method that imparts inertia

    ⇒ Effect of preventing oscillation

    ⇒ Effect of escaping shallow local minima

  • \(\gamma\) : a value between 0 and 1 that makes \(v\) decay rather than grow infinitely

Problem:

  • Even after reaching the global minimum, it is hard to stop or slow down due to inertia

Nesterov Accelerated Gradient (NAG)

torch.optim.SGD(nesterov=True)

Figure

\[\theta = \theta - v_t \\ v_t = \gamma v_{t-1} + \eta \nabla_\theta J(\theta - \gamma v_{t-1})\]
  • Solves the overshooting problem of Momentum SGD
  • Takes a step accounting for momentum, then computes and uses the gradient in advance at the new position that considers momentum

AdaGrad

torch.optim.Adagrad()

\[\theta_{t+1} = \theta - {\eta \over \sqrt{G_t + \epsilon}}\cdot \nabla_\theta J(\theta_t)\\ G_t = G_{t-1} + (\nabla_\theta J(\theta_t))^2\]
  • Reduces the step size when the slope of the loss function is large, and increases the step size when the slope is gentle
  • A large slope = large change of the surface = large change of the gradient = compute the surface’s amount of change by summing the magnitudes of the gradients
  • \(\epsilon\) is a very small constant that prevents the denominator from becoming 0

Problem:

  • Since positive values are added to G, it keeps increasing ⇒ the step size gradually converges toward 0

    • It is correct that the step size should get smaller, but it becomes so small that a problem arises where learning barely happens
AdaDelta
  • Applies the idea that if \(\theta\) has a physical quantity, the units must be matched
  • Works on its own without needing to specify an initial learning rate

RMSProp

torch.optim.RMSprop()

\[\theta_{t+1} = \theta - {\eta \over \sqrt{G_t + \epsilon}}\cdot \nabla_\theta J(\theta_t)\\ G_t = \gamma G_{t-1} + (1-\gamma)(\nabla_\theta J(\theta_t))^2\]
  • Solves the problem AdaGrad has by re-adjusting G at every computation through \(\gamma\), which takes a value between 0 and 1

Adam

torch.optim.Adam()

\[m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t\\ v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2\] \[\hat{m}_t = {m_t \over 1-\beta_1^t} , \ \ \ \ \hat{v}_t = {v_t \over 1-\beta_2^t} \\ \theta_{t+1} = \theta_t - {\eta \over {\sqrt{\hat{v_t} + \epsilon}}}\hat{m}_t\]
  • A combination of the two approaches: Momentum + Adaptive Step size
  • \(m_t\) handles momentum, and \(v_t\) handles the adaptive learning rate

💡

Why \(m_t\) and \(v_t\) are divided from \(\hat{m}_t, \hat{v}_t\) to obtain \(1-\beta_1^t, 1-\beta_2^t\)

: In actual use, \(\beta_1\) : usually 0.9, \(\beta_2\) : usually 0.999… are used

Practice


💡

Motivation

  • How can many training result datasets be visualized?
  • Put the results into a dictionary and append them one by one to a list?

    ⇒ If the process has to be terminated midway, all the previous results are lost

  • Wouldn’t it be fine to save the experiment results to the hard disk?

Using JSON to Handle Results

  • JSON: JavaScript Object Notation
    • A text-based data exchange standard for easily exchanging and storing data
  • So how should the experiment data be stored?
    • The following must be considered:
      1. A new result using the same experiment settings should overwrite the existing file
      2. The maximum file name length must not be exceeded

    ⇒ Set the file name as experiment name + hash of the experiment setting values.json

  • Hash
    • A technique that converts data of arbitrary length (Key) into data of fixed size (Value)
    • Composed of letters + numbers
    • deterministic

Handling Visualization of Multiple Experiment Results


Module Importing & Data Preparation

Module Importing
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import argparse
import numpy as np
import time
from copy import deepcopy # Add Deepcopy for args
Data Preparation
# Image to Tensor conversion and normalizing data
transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

# Partitioning train set & validation set
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
trainset, valset = torch.utils.data.random_split(trainset, [40000, 10000])
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform)

# Grouping Data sets with dictionary                                       
partition = {'train': trainset, 'val':valset, 'test':testset}

Model Architecture

Full code
class MLP(nn.Module):
    def __init__(self, in_dim, out_dim, hid_dim, n_layer, act, dropout, use_bn, use_xavier):
        super(MLP, self).__init__()
        self.in_dim = in_dim
        self.out_dim = out_dim
        self.hid_dim = hid_dim
        self.n_layer = n_layer
        self.act = act
        self.dropout = dropout # dropo
        self.use_bn = use_bn # batch normalization
        self.use_xavier = use_xavier # xavier initialization
			  
			  # ====== Create Linear Layers ====== #
        self.fc1 = nn.Linear(self.in_dim, self.hid_dim)

        self.linears = nn.ModuleList()
        self.bns = nn.ModuleList()
        for i in range(self.n_layer-1):
            self.linears.append(nn.Linear(self.hid_dim, self.hid_dim))
            if self.use_bn:
                self.bns.append(nn.BatchNorm1d(self.hid_dim))

        self.fc2 = nn.Linear(self.hid_dim, self.out_dim)

        # ====== Create Activation Function ====== #
        if self.act == 'relu':
            self.act = nn.ReLU()
        elif self.act == 'tanh':
            self.act == nn.Tanh()
        elif self.act == 'sigmoid':
            self.act = nn.Sigmoid()
        else:
            raise ValueError('no valid activation function selected!')

        # ====== Create Regularization Layer ======= #
        self.dropout = nn.Dropout(self.dropout)
        if self.use_xavier:
            self.xavier_init()

    def forward(self, x):
        x = self.act(self.fc1(x))
        for i in range(len(self.linears)):
            x = self.act(self.linears[i](x))
            x = self.bns[i](x)
            x = self.dropout(x)
        x = self.fc2(x)
        return x

    def xavier_init(self):
        for linear in self.linears:
            nn.init.xavier_normal_(linear.weight)
            linear.bias.data.fill_(0.01)
Batch Normalization
  • initializing

     # use_bn이 true일 때만 n-1개의 배치 정규화 레이어 추가
     for i in range(self.n_layer-1):
         self.linears.append(nn.Linear(self.hid_dim, self.hid_dim))
         if self.use_bn:
             self.bns.append(nn.BatchNorm1d(self.hid_dim))
    
  • forward

     def forward(self, x): 
             x = self.act(self.fc1(x))
               
             # self.linears, self.bns 각 요소에 대해 for문 돌기
             for i in range(len(self.linears)):
                 x = self.act(self.linears[i](x))
                 x = self.bns[i](x)
                 x = self.dropout(x)
             x = self.fc2(x)
               
             return x
    
    • In this case, batch normalization and dropout are performed immediately after passing through the activation function
    • If use_bn is false, self.bns is an empty list, so there is no need to check the true/false value of use_bn in the forward part
Regularization Layers
# ====== Create Regularization Layer ======= #
        self.dropout = nn.Dropout(self.dropout)
        # use_xavier가 true일 경우 xavier_init()실행
        if self.use_xavier:
            self.xavier_init()
      
    def xavier_init(self):
        for linear in self.linears:
            nn.init.xavier_normal_(linear.weight)
            linear.bias.data.fill_(0.01)
  • In the case of xavier initialization, the weight and bias are initialized while iterating over every linear layer
  • nn.init.xavier_normal_(linear.weight) : initializes the weights of the linear layer
  • linear.bias.data.fill_(0.01) : initializes the bias of each linear layer to 0.01

Functionalized Training, Validation, Testing

Train Function
def train(net, partition, optimizer, criterion, args):
    trainloader = torch.utils.data.DataLoader(partition['train'],
                                              batch_size=args.train_batch_size,
                                              shuffle=True, num_workers=2)
    net.train()

    correct = 0
    total = 0
    train_loss = 0.0
    # get the inputs; data is a list of [inputs, labels]
    for i, data in enumerate(trainloader, 0):
        optimizer.zero_grad() # [21.01.05 오류 수정] 매 Epoch 마다 .zero_grad()가 실행되는 것을 매 iteration 마다 실행되도록 수정했습니다.

        # get the inputs
        inputs, labels = data
        inputs = inputs.view(-1, 3072) # .view()로 차원 맞추기. For reshaping data (but of same num of elements)

        inputs = inputs.cuda()
        labels = labels.cuda()
        outputs = net(inputs) # 3072 X 100 shape

        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        train_loss += loss.item()
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    train_loss = train_loss / len(trainloader)
    train_acc = 100 * correct / total
    return net, train_loss, train_acc
Validation Function
def validate(net, partition, criterion, args):
    valloader = torch.utils.data.DataLoader(partition['val'],
                                            batch_size=args.test_batch_size,
                                            shuffle=False, num_workers=2)
    net.eval()

    correct = 0
    total = 0
    val_loss = 0
    with torch.no_grad():
        for data in valloader:
            images, labels = data
            images = images.view(-1, 3072)
            images = images.cuda()
            labels = labels.cuda()
            outputs = net(images)

            loss = criterion(outputs, labels)

            val_loss += loss.item()
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

        val_loss = val_loss / len(valloader)
        val_acc = 100 * correct / total
    return val_loss, val_acc
Testing Function
def test(net, partition, args):
    testloader = torch.utils.data.DataLoader(partition['test'],
                                             batch_size=args.test_batch_size,
                                             shuffle=False, num_workers=2)
    net.eval()

    correct = 0
    total = 0
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            images = images.view(-1, 3072)
            images = images.cuda()
            labels = labels.cuda()

            outputs = net(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

        test_acc = 100 * correct / total
    return test_acc

Experiment Function

Full code
def experiment(partition, args):

    net = MLP(args.in_dim, args.out_dim, args.hid_dim, args.n_layer, args.act, args.dropout, args.use_bn, args.use_xavier)
    net.cuda()

    criterion = nn.CrossEntropyLoss()
    if args.optim == 'SGD':
        optimizer = optim.RMSprop(net.parameters(), lr=args.lr, weight_decay=args.l2)
    elif args.optim == 'RMSprop':
        optimizer = optim.RMSprop(net.parameters(), lr=args.lr, weight_decay=args.l2)
    elif args.optim == 'Adam':
        optimizer = optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.l2)
    else:
        raise ValueError('In-valid optimizer choice')

    # ===== List for epoch-wise data ====== #
    train_losses = []
    val_losses = []
    train_accs = []
    val_accs = []
    # ===================================== #

    for epoch in range(args.epoch):  # loop over the dataset multiple times
        ts = time.time()
        net, train_loss, train_acc = train(net, partition, optimizer, criterion, args)
        val_loss, val_acc = validate(net, partition, criterion, args)
        te = time.time()

        # ====== Add Epoch Data ====== #
        train_losses.append(train_loss)
        val_losses.append(val_loss)
        train_accs.append(train_acc)
        val_accs.append(val_acc)
        # ============================ #

        print(f'Epoch {epoch}, Acc(train/val): {train_acc:2.2f}/{val_acc:2.2f}, Loss(train/val) {train_loss:2.2f}/{val_loss:2.2f}. Took {te-ts:2.2f} sec')

  test_acc = test(net, partition, args)

	# ======= Add Result to Dictionary ======= #
	result = {}
	result['train_losses'] = train_losses
	result['val_losses'] = val_losses
	result['train_accs'] = train_accs
	result['val_accs'] = val_accs
	result['train_acc'] = train_acc
	result['val_acc'] = val_acc
	result['test_acc'] = test_acc
	
	# Experiment 함수가 반환하는 값: Dictionary 두개
	return vars(args), result
Per Epoch
for epoch in range(args.epoch):  # loop over the dataset multiple times
    ts = time.time()
    net, train_loss, train_acc = train(net, partition, optimizer, criterion, args)
    val_loss, val_acc = validate(net, partition, criterion, args)
    te = time.time()

    # ====== Add Epoch Data ====== #
    train_losses.append(train_loss)
    val_losses.append(val_loss)
    train_accs.append(train_acc)
    val_accs.append(val_acc)
    # ============================ #

    print(f'Epoch {epoch+1}, Acc(train/val): {train_acc:2.2f}/{val_acc:2.2f}, Loss(train/val) {train_loss:2.2f}/{val_loss:2.2f}. Took {te-ts:2.2f} sec')

test_acc = test(net, partition, args)
  • te-ts: for measuring the time taken for training
  • All parameters of the train, validate, and test functions, except criterion, are managed in args
  • At every epoch, train_loss, val_loss, train_acc, and val_acc are each stored in a list
Result to Dictionary
# ======= Add Result to Dictionary ======= #
result = {}
result['train_losses'] = train_losses
result['val_losses'] = val_losses
result['train_accs'] = train_accs
result['val_accs'] = val_accs
result['train_acc'] = train_acc
result['val_acc'] = val_acc
result['test_acc'] = test_acc

# Experiment 함수가 반환하는 값: 세팅, 결과 Dictionary
return vars(args), result

Managing Results

Module Import & Function Define
import hashlib
import json
from os import listdir
from os.path import isfile, join
import pandas as pd

# experiment 함수로부터 반환된 세팅, 결과값 .json으로 저장
def save_exp_result(setting, result):
    exp_name = setting['exp_name']
    # del을 통해 epoch, test batch size가 바뀌어도 같은 파일로 저장되도록 함
    del setting['epoch']
    del setting['test_batch_size'] 

    hash_key = hashlib.sha1(str(setting).encode()).hexdigest()[:6]
    filename = './results/{}-{}.json'.format(exp_name, hash_key)
    result.update(setting) # Dict 합치기
    with open(filename, 'w') as f:
        json.dump(result, f)

# 저장한 exp  result를 pandas Dataframe 형태로 불러옴
def load_exp_result(exp_name):
    dir_path = './results'
    filenames = [f for f in listdir(dir_path) if isfile(join(dir_path, f)) if '.json' in f]
    list_result = []
    for filename in filenames:
        if exp_name in filename:
            with open(join(dir_path, filename), 'r') as infile:
                results = json.load(infile)
                list_result.append(results)
    df = pd.DataFrame(list_result) # .drop(columns=[])
    return df
Hyperparameters & Applications
# ====== Random Seed Initialization ====== #
seed = 123
np.random.seed(seed)
torch.manual_seed(seed)

parser = argparse.ArgumentParser()
args = parser.parse_args("")
args.exp_name = "exp1_n_layer_hid_dim"

# ====== Model Capacity ====== #
args.in_dim = 3072
args.out_dim = 10
args.hid_dim = 100
args.act = 'relu'

# ====== Regularization ======= #
args.dropout = 0.2
args.use_bn = True
args.l2 = 0.00001
args.use_xavier = True

# ====== Optimizer & Training ====== #
args.optim = 'Adam' #'RMSprop' #SGD, RMSprop, ADAM...
args.lr = 0.0015
args.epoch = 10

args.train_batch_size = 256
args.test_batch_size = 1024

# ====== Experiment Variable ====== #
name_var1 = 'n_layer'
name_var2 = 'hid_dim'
list_var1 = [1, 2, 3]
list_var2 = [500, 300]

for var1 in list_var1:
    for var2 in list_var2:
		    # 사용자의 오류 방지
		    # args.name_var1 = var1과 같은 과정
        setattr(args, name_var1, var1)
        setattr(args, name_var2, var2)
        print(args)

        setting, result = experiment(partition, deepcopy(args))
        save_exp_result(setting, result)

💡

deep copy and shallow copy

  • shallow copy: copies only the address value of the object
    • Independence between the two copied mutable variables does NOT hold
  • deep copy: copies the value into a different memory space

    ⇒ Used to maintain the independence of mutable objects

💡

Why is deepcopy used in setting, result = experiment(partition, deepcopy(args))?

  • args is changed for each experiment → this is to ensure that these changes do not affect other experiments

Visualizing

Module Import
import seaborn as sns # 시각화를 위한 library
import matplotlib.pyplot as plt
Accuracy Comparison by Hidden Dimension
df = load_exp_result('exp1')

fig, ax = plt.subplots(1, 3)
fig.set_size_inches(15, 6)
sns.set_style("darkgrid", {"axes.facecolor": ".9"})

# hue: 범례(색으로 구분됨)
sns.barplot(x='n_layer', y='train_acc', hue='hid_dim', data=df, ax=ax[0])
sns.barplot(x='n_layer', y='val_acc', hue='hid_dim', data=df, ax=ax[1])
sns.barplot(x='n_layer', y='test_acc', hue='hid_dim', data=df, ax=ax[2])

Figure

Train Loss vs. Validation Loss
var1 = 'n_layer'
var2 = 'hid_dim'

df = load_exp_result('exp1')
list_v1 = df[var1].unique() # [2,3,1]
list_v2 = df[var2].unique() # [30, 500]
list_data = []

for value1 in list_v1:
    for value2 in list_v2:
        row = df.loc[df[var1]==value1]
        row = row.loc[df[var2]==value2]

        train_losses = list(row.train_losses)[0]
        val_losses = list(row.val_losses)[0]

        for epoch, train_loss in enumerate(train_losses):
            list_data.append({'type':'train', 'loss':train_loss, 'epoch':epoch, var1:value1, var2:value2})
        for epoch, val_loss in enumerate(val_losses):
            list_data.append({'type':'val', 'loss':val_loss, 'epoch':epoch, var1:value1, var2:value2})

df = pd.DataFrame(list_data)
# .FacetGrid(): plot이 그려질 grid 생성
g = sns.FacetGrid(df, row=var2, col=var1, hue='type', margin_titles=True, sharey=False)
# 각 subplot에서 plt.plot을 이용해서 plot 그리기
g = g.map(plt.plot, 'epoch', 'loss', marker='.') 
g.add_legend()
g.fig.suptitle('Train loss vs Val loss')
plt.subplots_adjust(top=0.89)

Figure

  • Visualization of 5-dimensional data: train_loss and val_loss as epochs increase when n_layer and hid_dim vary
  • Since it is high-dimensional data, it cannot be visualized all at once like the bar plot above
Train Accuracy vs. Validation Accuracy
var1 = 'n_layer'
var2 = 'hid_dim'

df = load_exp_result('exp1')
list_v1 = df[var1].unique()
list_v2 = df[var2].unique()
list_data = []

for value1 in list_v1:
    for value2 in list_v2:
        row = df.loc[df[var1]==value1]
        row = row.loc[df[var2]==value2]

        train_accs = list(row.train_accs)[0]
        val_accs = list(row.val_accs)[0]
        test_acc = list(row.test_acc)[0]

        for epoch, train_acc in enumerate(train_accs):
            list_data.append({'type':'train', 'Acc':train_acc, 'test_acc':test_acc, 'epoch':epoch, var1:value1, var2:value2})
        for epoch, val_acc in enumerate(val_accs):
            list_data.append({'type':'val', 'Acc':val_acc, 'test_acc':test_acc, 'epoch':epoch, var1:value1, var2:value2})

df = pd.DataFrame(list_data)
g = sns.FacetGrid(df, row=var2, col=var1, hue='type', margin_titles=True, sharey=False)
g = g.map(plt.plot, 'epoch', 'Acc', marker='.') 

def show_acc(x, y, metric, **kwargs):
    plt.scatter(x, y, alpha=0.3, s=1)
    metric = "Test Acc: {:1.3f}".format(list(metric.values)[0])
    plt.text(0.05, 0.95, metric,  horizontalalignment='left', verticalalignment='center', transform=plt.gca().transAxes, bbox=dict(facecolor='yellow', alpha=0.5, boxstyle="round,pad=0.1"))
g = g.map(show_acc, 'epoch', 'Acc', 'test_acc')

g.add_legend()
g.fig.suptitle('Train Accuracy vs Val Accuracy')

plt.subplots_adjust(top=0.89)

Figure

Utilizing the Method

  1. From the results visualized in args.exp_name = “exp1_n_layer_hid_dim”, fix n_layer and hid_dim
  2. Add the fixed hyperparameters to args
  3. Decide the hyperparameters to try varying again, like args.exp_name = “exp2_lr_dropout”, change the exp name, and run the experiment again
    • It is better to check the optimizer separately on its own
    • It is useful to compare minor parameters against each other
  4. Repeat until the optimal result is found