Skip to content

Instantly share code, notes, and snippets.

@ilyarudyak
Created October 20, 2021 17:28
Show Gist options
  • Save ilyarudyak/aa4fc2c64016e7136bf85ddff76e7ff2 to your computer and use it in GitHub Desktop.
Save ilyarudyak/aa4fc2c64016e7136bf85ddff76e7ff2 to your computer and use it in GitHub Desktop.
convolution layer backprop (cs231n assignment2)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "increased-teens",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"=========== You can safely ignore the message below if you are NOT working on ConvolutionalNetworks.ipynb ===========\n",
"\tYou will need to compile a Cython extension for a portion of this assignment.\n",
"\tThe instructions to do this will be given in a section of the notebook below.\n"
]
}
],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import numpy as np\n",
"\n",
"from cs231n.classifiers.cnn import *\n",
"from cs231n.data_utils import get_CIFAR10_data\n",
"from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient\n",
"from cs231n.layers import *\n",
"from cs231n.fast_layers import *\n",
"from cs231n.solver import Solver\n",
"\n",
"from collections import OrderedDict\n",
"\n",
"%load_ext autoreload\n",
"%autoreload 2"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "agreed-telephone",
"metadata": {},
"outputs": [],
"source": [
"def rel_error(x, y):\n",
" \"\"\" returns relative error \"\"\"\n",
" return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))"
]
},
{
"cell_type": "markdown",
"id": "surprised-ferry",
"metadata": {},
"source": [
"## 01 - backward pass"
]
},
{
"cell_type": "markdown",
"id": "weighted-license",
"metadata": {},
"source": [
"### 01-1 theory (1st attempt)"
]
},
{
"cell_type": "markdown",
"id": "common-progress",
"metadata": {},
"source": [
"Let's start from the simple example (based on [this post](https://neodelphis.github.io/convnet/maths/python/english/2019/07/10/convnet-bp-en.html)). Suppose we have only 1 channel and `stride` is also equal to 1. Our input data $X$ is `4x4`, filter is `2x2` and output is `3x3`.\n",
"\n",
"$$\n",
"X = \\begin{bmatrix} x_{11} & \\dots & x_{14} \\\\ \\dots & \\dots & \\dots \\\\ x_{41} & \\dots & x_{44} \\end{bmatrix}\n",
"$$\n",
"\n",
"$$\n",
"W = \\begin{bmatrix} w_{11} & w_{12} \\\\ \\dots & \\dots \\\\ w_{21} & w_{22} \\end{bmatrix}\n",
"$$\n",
"\n",
"$$\n",
"Y = \\begin{bmatrix} y_{11} & \\dots & y_{13} \\\\ \\dots & \\dots & \\dots \\\\ y_{31} & \\dots & y_{33} \\end{bmatrix}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "congressional-shower",
"metadata": {},
"source": [
"It's important to notice that $y_{11}$ depends only on the 1st segment of $X$ of shape `2x2`:\n",
"\n",
"\n",
"$$\n",
"y_{11} = x_{11} w_{11} + x_{12} w_{12} + x_{21} w_{21} + x_{22} w_{22} \\\\\n",
"y_{12} = x_{12} w_{11} + x_{13} w_{12} + x_{22} w_{21} + x_{23} w_{22} \\\\\n",
"y_{13} = x_{13} w_{11} + x_{14} w_{12} + x_{23} w_{21} + x_{24} w_{22}\n",
"$$\n",
"\n",
"$$\n",
"y_{21} = x_{21} w_{11} + x_{22} w_{12} + x_{31} w_{21} + x_{32} w_{22} \\\\\n",
"y_{22} = x_{22} w_{11} + x_{23} w_{12} + x_{32} w_{21} + x_{33} w_{22} \\\\\n",
"y_{23} = x_{23} w_{11} + x_{24} w_{12} + x_{33} w_{21} + x_{34} w_{22}\n",
"$$\n",
"\n",
"$$\n",
"y_{31} = x_{31} w_{11} + x_{32} w_{12} + x_{41} w_{21} + x_{42} w_{22} \\\\\n",
"y_{32} = x_{32} w_{11} + x_{33} w_{12} + x_{42} w_{21} + x_{43} w_{22} \\\\\n",
"y_{33} = x_{33} w_{11} + x_{34} w_{12} + x_{43} w_{21} + x_{44} w_{22}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "olympic-conditioning",
"metadata": {},
"source": [
"On what $y$ does $w_{11}$ depend? On all of them: $y_{11} \\dots y_{33}$. But what can we say about this product? It's actually sum of the element-by-element product of $W$ and a segment of $X$. If we look at equations above we'll see that this is the upper-corner `3x3` of $X$. And for $w_{12}$ it moves to the right. So actually $dW = X * dY$ where $*$ stands for convolution. \n",
"\n",
"$$\n",
"\\frac{\\partial L}{\\partial w_{11}} =\n",
"\\sum_{ij}\n",
"\\frac{\\partial L}{\\partial y_{ij}}\n",
"\\frac{\\partial y_{ij}}{\\partial w_{11}} = \n",
"\\sum_{ij}\n",
"\\frac{\\partial L}{\\partial y_{ij}}\n",
"x_{ij} =\n",
"\\frac{\\partial L}{\\partial y_{11}} x_{11} + \n",
"\\frac{\\partial L}{\\partial y_{12}} x_{12} +\n",
"\\dots +\n",
"\\frac{\\partial L}{\\partial y_{33}} x_{33}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "exceptional-gauge",
"metadata": {},
"source": [
"Unfortunately this approach doesn't work with $stride \\neq 1$. Let's continue our example - suppose we have the same $X$ and $W$ as before but we have $stride = 2$. In this case we have $Y$ $2 \\times 2$."
]
},
{
"cell_type": "markdown",
"id": "graphic-maintenance",
"metadata": {},
"source": [
"$$\n",
"y_{11} = x_{11} w_{11} + x_{12} w_{12} + x_{21} w_{21} + x_{22} w_{22} \\\\\n",
"y_{12} = x_{13} w_{11} + x_{14} w_{12} + x_{23} w_{21} + x_{24} w_{22} \\\\\n",
"y_{21} = x_{31} w_{11} + x_{32} w_{12} + x_{41} w_{21} + x_{42} w_{22} \\\\\n",
"y_{22} = x_{33} w_{11} + x_{34} w_{12} + x_{43} w_{21} + x_{44} w_{22} \n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "median-glory",
"metadata": {},
"source": [
"So if we consider a gradient with respect to $w_{11}$ then we'll get elements from 1st and 3d columns of $X$ (so there's a gap between them). This of course can't be interpreted as convolution of $X$ and $dY$."
]
},
{
"cell_type": "markdown",
"id": "yellow-allah",
"metadata": {},
"source": [
"### 01-2 theory (2nd approach)"
]
},
{
"cell_type": "markdown",
"id": "close-circulation",
"metadata": {},
"source": [
"Let's continue our computations from example above with $stride = 2$."
]
},
{
"cell_type": "markdown",
"id": "mounted-principle",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial L}{\\partial w_{11}} =\n",
"\\frac{\\partial L}{\\partial y_{11}} x_{11} + \n",
"\\frac{\\partial L}{\\partial y_{12}} x_{13} +\n",
"\\frac{\\partial L}{\\partial y_{21}} x_{31} +\n",
"\\frac{\\partial L}{\\partial y_{22}} x_{33}\n",
"$$\n",
"\n",
"$$\n",
"\\frac{\\partial L}{\\partial w_{12}} =\n",
"\\frac{\\partial L}{\\partial y_{11}} x_{12} + \n",
"\\frac{\\partial L}{\\partial y_{12}} x_{14} +\n",
"\\frac{\\partial L}{\\partial y_{21}} x_{32} +\n",
"\\frac{\\partial L}{\\partial y_{22}} x_{34}\n",
"$$\n",
"\n",
"$$\n",
"\\frac{\\partial L}{\\partial w_{21}} =\n",
"\\frac{\\partial L}{\\partial y_{11}} x_{21} + \n",
"\\frac{\\partial L}{\\partial y_{12}} x_{23} +\n",
"\\frac{\\partial L}{\\partial y_{21}} x_{41} +\n",
"\\frac{\\partial L}{\\partial y_{22}} x_{43}\n",
"$$\n",
"\n",
"$$\n",
"\\frac{\\partial L}{\\partial w_{22}} =\n",
"\\frac{\\partial L}{\\partial y_{11}} x_{22} + \n",
"\\frac{\\partial L}{\\partial y_{12}} x_{24} +\n",
"\\frac{\\partial L}{\\partial y_{21}} x_{42} +\n",
"\\frac{\\partial L}{\\partial y_{22}} x_{44}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "worth-oxford",
"metadata": {},
"source": [
"So as we may see the first segment of our matrix $X$ is multiplied by the first element of the upstream gradient:\n",
"\n",
"$$\n",
"\\begin{bmatrix} x_{11} & x_{12} \\\\ x_{21} & x_{22} \\end{bmatrix} * \n",
"\\frac{\\partial L}{\\partial y_{11}}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "aerial-timer",
"metadata": {},
"source": [
"Let's write X as a block matrix:\n",
"\n",
"$$\n",
"X = \n",
"\\begin{bmatrix} X_{11} & X_{12} \\\\ X_{21} & X_{22} \\end{bmatrix}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "floppy-mission",
"metadata": {},
"source": [
"Then we may write gradient with respect to $Y$ as a sum of this blocks multiplied by the upstream gradient:\n",
"\n",
"$$\n",
"\\frac{\\partial L}{\\partial w} =\n",
"\\frac{\\partial L}{\\partial y_{11}} X_{11} + \n",
"\\frac{\\partial L}{\\partial y_{12}} X_{12} +\n",
"\\frac{\\partial L}{\\partial y_{21}} X_{21} +\n",
"\\frac{\\partial L}{\\partial y_{22}} X_{22}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "corporate-cooper",
"metadata": {},
"source": [
"This means that we may use the same loops we used for the forward pass and multiply a segment by an element of the gradient."
]
},
{
"cell_type": "markdown",
"id": "corrected-clinic",
"metadata": {},
"source": [
"### 01-3 testing and debugging "
]
},
{
"cell_type": "markdown",
"id": "guided-delay",
"metadata": {},
"source": [
"So here's testing and debugging for the approach above. We use the same sizes of matrices and the testing code from the original assignment 2."
]
},
{
"cell_type": "markdown",
"id": "matched-pitch",
"metadata": {},
"source": [
"### ===DEBUGGING==="
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "surprising-belgium",
"metadata": {},
"outputs": [],
"source": [
"np.random.seed(231)\n",
"\n",
"N, C, H, W = 1, 1, 4, 4\n",
"F, C, HH, WW = 1, 1, 2, 2\n",
"stride, pad = 2, 0"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "square-macedonia",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2, 2)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"H_out = int(1 + (H + 2 * pad - HH) / stride)\n",
"W_out = int(1 + (W + 2 * pad - WW) / stride)\n",
"\n",
"H_out, W_out"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "previous-conditions",
"metadata": {},
"outputs": [],
"source": [
"x = np.random.randn(N, C, H, W)\n",
"w = np.random.randn(F, C, HH, WW)\n",
"b = np.random.randn(F,)\n",
"dout = np.random.randn(N, F, H_out, W_out)\n",
"conv_param = {'stride': stride, 'pad': pad}"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "respiratory-mumbai",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[ 0.41794341, 1.39710028, -1.78590431, -0.70882773],\n",
" [-0.07472532, -0.77501677, -0.1497979 , 1.86172902],\n",
" [-1.4255293 , -0.3763567 , -0.34227539, 0.29490764],\n",
" [-0.83732373, 0.95218767, 1.32931659, 0.52465245]]]])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "important-verification",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[[[0.26207083, 0.14320173],\n",
" [0.90101716, 0.23185863]]]])"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dout"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "instructional-approval",
"metadata": {},
"outputs": [],
"source": [
"dx_num = eval_numerical_gradient_array(lambda x: conv_forward_naive(x, w, b, conv_param)[0], x, dout)\n",
"dw_num = eval_numerical_gradient_array(lambda w: conv_forward_naive(x, w, b, conv_param)[0], w, dout)\n",
"db_num = eval_numerical_gradient_array(lambda b: conv_forward_naive(x, w, b, conv_param)[0], b, dout)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "indoor-integrity",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ho=0 wo=0\n",
"x_seg=[[[ 0.41794341 1.39710028]\n",
" [-0.07472532 -0.77501677]]]\n",
"dout=0.2620708288499113\n",
"\n",
"ho=0 wo=1\n",
"x_seg=[[[-1.78590431 -0.70882773]\n",
" [-0.1497979 1.86172902]]]\n",
"dout=0.14320172528233172\n",
"\n",
"ho=1 wo=0\n",
"x_seg=[[[-1.4255293 -0.3763567 ]\n",
" [-0.83732373 0.95218767]]]\n",
"dout=0.9010171565792489\n",
"\n",
"ho=1 wo=1\n",
"x_seg=[[[-0.34227539 0.29490764]\n",
" [ 1.32931659 0.52465245]]]\n",
"dout=0.23185862873793547\n",
"\n"
]
}
],
"source": [
"out, cache = conv_forward_naive(x, w, b, conv_param)\n",
"dx, dw, db = conv_backward_naive(dout, cache)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "micro-gossip",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Testing conv_backward_naive function\n",
"dw error: 3.6708814180770935e-10\n"
]
}
],
"source": [
"# Your errors should be around e-8 or less.\n",
"print('Testing conv_backward_naive function')\n",
"# print('dx error: ', rel_error(dx, dx_num))\n",
"print('dw error: ', rel_error(dw, dw_num))\n",
"# print('db error: ', rel_error(db, db_num))"
]
},
{
"cell_type": "markdown",
"id": "seventh-perry",
"metadata": {},
"source": [
"### ===DEBUGGING==="
]
},
{
"cell_type": "markdown",
"id": "certain-murder",
"metadata": {},
"source": [
"So looks like our approach works in this simple case. Actually we may shange parameters above ($N$, $F$, $stride$ and so on) and we'll get the correct result yet again. "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
from builtins import range
import numpy as np
def affine_forward(x, w, b):
"""Computes the forward pass for an affine (fully connected) layer.
The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N
examples, where each example x[i] has shape (d_1, ..., d_k). We will
reshape each input into a vector of dimension D = d_1 * ... * d_k, and
then transform it to an output vector of dimension M.
Inputs:
- x: A numpy array containing input data, of shape (N, d_1, ..., d_k)
- w: A numpy array of weights, of shape (D, M)
- b: A numpy array of biases, of shape (M,)
Returns a tuple of:
- out: output, of shape (N, M)
- cache: (x, w, b)
"""
out = None
###########################################################################
# TODO: Copy over your solution from Assignment 1. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
N = x.shape[0]
x_reshaped = x.reshape(N, -1)
out = x_reshaped @ w + b
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
cache = (x, w, b)
return out, cache
def affine_backward(dout, cache):
"""Computes the backward pass for an affine (fully connected) layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
- b: Biases, of shape (M,)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Gradient with respect to w, of shape (D, M)
- db: Gradient with respect to b, of shape (M,)
"""
x, w, b = cache
dx, dw, db = None, None, None
###########################################################################
# TODO: Copy over your solution from Assignment 1. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
N = x.shape[0]
x_reshaped = x.reshape(N, -1)
dx = dout @ w.T
dw = x_reshaped.T @ dout
db = np.sum(dout, axis=0)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dw, db
def relu_forward(x):
"""Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x
"""
out = None
###########################################################################
# TODO: Copy over your solution from Assignment 1. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
out = np.maximum(x, 0)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
cache = x
return out, cache
def relu_backward(dout, cache):
"""Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
dx, x = None, cache
###########################################################################
# TODO: Copy over your solution from Assignment 1. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
dx = x.copy()
dx[x <= 0] = 0
dx[x > 0] = 1
dx = dout * dx
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx
def softmax_loss(x, y):
"""Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth
class for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
loss, dx = None, None
###########################################################################
# TODO: Copy over your solution from Assignment 1. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
N, _ = x.shape
x_mod = x - np.max(x, axis=1, keepdims=True)
x_mod_exp = np.exp(x_mod)
probs = x_mod_exp / np.sum(x_mod_exp, axis=1, keepdims=True)
loss = -np.sum(np.log(probs[np.arange(N), y]))
loss /= N
dx = probs.copy()
dx[np.arange(N), y] -= 1
dx /= N
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return loss, dx
def batchnorm_forward(x, gamma, beta, bn_param):
"""Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running mean of the
mean and variance of each feature, and these averages are used to normalize
data at test-time.
At each timestep we update the running averages for mean and variance using
an exponential decay based on the momentum parameter:
running_mean = momentum * running_mean + (1 - momentum) * sample_mean
running_var = momentum * running_var + (1 - momentum) * sample_var
Note that the batch normalization paper suggests a different test-time
behavior: they compute sample mean and variance for each feature using a
large number of training images rather than using a running average. For
this implementation we have chosen to use running averages instead since
they do not require an additional estimation step; the torch7
implementation of batch normalization also uses running averages.
Input:
- x: Data of shape (N, D)
- gamma: Scale parameter of shape (D,)
- beta: Shift paremeter of shape (D,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: of shape (N, D)
- cache: A tuple of values needed in the backward pass
"""
mode = bn_param.get('mode', 'train')
eps = bn_param.get('eps', 1e-5)
momentum = bn_param.get('momentum', 0.9)
N, D = x.shape
running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))
running_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))
out, cache = None, None
if mode == 'train':
#######################################################################
# TODO: Implement the training-time forward pass for batch norm. #
# Use minibatch statistics to compute the mean and variance, use #
# these statistics to normalize the incoming data, and scale and #
# shift the normalized data using gamma and beta. #
# #
# You should store the output in the variable out. Any intermediates #
# that you need for the backward pass should be stored in the cache #
# variable. #
# #
# You should also use your computed sample mean and variance together #
# with the momentum variable to update the running mean and running #
# variance, storing your result in the running_mean and running_var #
# variables. #
# #
# Note that though you should be keeping track of the running #
# variance, you should normalize the data based on the standard #
# deviation (square root of variance) instead! #
# Referencing the original paper (https://arxiv.org/abs/1502.03167) #
# might prove to be helpful. #
#######################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
sample_mean = np.mean(x, axis=0, keepdims=True)
sample_var = np.var(x, axis=0, keepdims=True)
x_hat = (x - sample_mean) / np.sqrt(sample_var + eps)
out = gamma * x_hat + beta
running_mean = momentum * running_mean + (1 - momentum) * sample_mean
running_var = momentum * running_var + (1 - momentum) * sample_var
cache = {}
cache['x'] = x
cache['x_hat'] = x_hat
cache['gamma'] = gamma
cache['beta'] = beta
cache['sample_mean'] = sample_mean
cache['sample_var'] = sample_var
cache['eps'] = eps
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
#######################################################################
# END OF YOUR CODE #
#######################################################################
elif mode == 'test':
#######################################################################
# TODO: Implement the test-time forward pass for batch normalization. #
# Use the running mean and variance to normalize the incoming data, #
# then scale and shift the normalized data using gamma and beta. #
# Store the result in the out variable. #
#######################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
out = (x - running_mean) / np.sqrt(running_var + eps)
out = gamma * out + beta
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
#######################################################################
# END OF YOUR CODE #
#######################################################################
else:
raise ValueError(f'invalid forward batchnorm mode: {mode}')
# Store the updated running means back into bn_param
bn_param['running_mean'] = running_mean
bn_param['running_var'] = running_var
return out, cache
def batchnorm_backward(dout, cache):
"""Backward pass for batch normalization.
For this implementation, you should write out a computation graph for
batch normalization on paper and propagate gradients backward through
intermediate nodes.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from batchnorm_forward.
Returns a tuple of:
- dx: Gradient with respect to inputs x, of shape (N, D)
- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)
- dbeta: Gradient with respect to shift parameter beta, of shape (D,)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for batch normalization. Store the #
# results in the dx, dgamma, and dbeta variables. #
# Referencing the original paper (https://arxiv.org/abs/1502.03167) #
# might prove to be helpful. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# unpacking the cache
x = cache['x']
N = x.shape[0]
x_hat = cache['x_hat']
gamma = cache['gamma']
beta = cache['beta']
sample_mean = cache['sample_mean']
sample_var = cache['sample_var']
eps = cache['eps']
# grads of coefficients
dgamma = np.sum(dout * x_hat, axis=0)
dbeta = np.sum(dout, axis=0)
# grad of dx (using detailed graph)
# (1) out:y grad:dout
# f(x, y) = x * y
# x = x_hat; y = gamma
dx_hat = dout * gamma # (N, D)
# (2) out:x_hat grad:dx_hat
# f(x, y) = x * y
# x = x - mu; y = 1 / sqrt(var + eps)
dx2 = dx_hat / np.sqrt(sample_var + eps) # (N, D)
dy2 = np.sum(dx_hat * x_hat * np.sqrt(sample_var + eps), axis=0) # (D,)
# (3) out:1 / sqrt(var + eps) grad:dy2
# f(x) = 1 / x
# x = sqrt(var + eps)
dx3 = dy2 * (-1 / np.sqrt(sample_var + eps) ** 2) # (D,)
# (4) out:sqrt(var + eps) grad:dx3
# f(x) = sqrt(x)
# x = var + eps
dx4 = dx3 * .5 / np.sqrt(sample_var + eps) # (D,)
# (5) out:var grad:dx4
# f(x) = sum(x) / N
# x = (x - mu) ** 2
dx5 = dx4 * np.ones_like(x) / N # (N, D)
# (6) out:var grad:dx5
# f(x) = x ** 2
# x = x - mu
dx6 = dx5 * 2 * (x - sample_mean) # (N, D)
# add 2 grads with respect to x
dx = dx2 + dx6
# (7) out:x - mu grad:dx
# f(x, y) = x - y
# x = x; y = mu
dx7 = dx # (N, D)
dy7 = -np.sum(dx, axis=0) # (D,)
# (8) out:mu grad:dy7
# f(x) = sum(x) / N
# x = x
dx8 = dy7 * np.ones_like(x) / N
# add 2 grads with respect to x
dx = dx7 + dx8
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
def batchnorm_backward_alt2(dout, cache):
"""Backward pass for batch normalization.
For this implementation, you should write out a computation graph for
batch normalization on paper and propagate gradients backward through
intermediate nodes.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from batchnorm_forward.
Returns a tuple of:
- dx: Gradient with respect to inputs x, of shape (N, D)
- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)
- dbeta: Gradient with respect to shift parameter beta, of shape (D,)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for batch normalization. Store the #
# results in the dx, dgamma, and dbeta variables. #
# Referencing the original paper (https://arxiv.org/abs/1502.03167) #
# might prove to be helpful. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# unpacking the cache
x = cache['x']
N = x.shape[0]
x_hat = cache['x_hat']
gamma = cache['gamma']
beta = cache['beta']
sample_mean = cache['sample_mean']
sample_var = cache['sample_var']
eps = cache['eps']
# grads of coefficients
dgamma = np.sum(dout * x_hat, axis=0)
dbeta = np.sum(dout, axis=0)
# grad of dx (exactly like in the paper)
dx_hat = gamma * dout
dvar = np.sum(dx_hat * (x - sample_mean), axis=0) * (-.5) * np.power(sample_var + eps, -1.5)
dmean = (np.sum(dx_hat, axis=0) * (-1 / np.sqrt(sample_var + eps)) +
dvar * (-2 / N) * np.sum(x - sample_mean, axis=0))
# print(np.round(np.sum(x - sample_mean, axis=0), decimals=10))
dx = (dx_hat * (1 / np.sqrt(sample_var + eps)) +
dvar * (2 / N) * (x - sample_mean) + dmean / N)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
def batchnorm_backward_alt(dout, cache):
"""Alternative backward pass for batch normalization.
For this implementation you should work out the derivatives for the batch
normalizaton backward pass on paper and simplify as much as possible. You
should be able to derive a simple expression for the backward pass.
See the jupyter notebook for more hints.
Note: This implementation should expect to receive the same cache variable
as batchnorm_backward, but might not use all of the values in the cache.
Inputs / outputs: Same as batchnorm_backward
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for batch normalization. Store the #
# results in the dx, dgamma, and dbeta variables. #
# #
# After computing the gradient with respect to the centered inputs, you #
# should be able to compute gradients with respect to the inputs in a #
# single statement; our implementation fits on a single 80-character line.#
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# unpacking the cache
x = cache['x']
N = x.shape[0]
x_hat = cache['x_hat']
gamma = cache['gamma']
beta = cache['beta']
sample_mean = cache['sample_mean']
sample_var = cache['sample_var']
eps = cache['eps']
# grads of coefficients
dgamma = np.sum(dout * x_hat, axis=0)
dbeta = np.sum(dout, axis=0)
dx_hat = gamma * dout
dx = (dx_hat -
np.sum(dx_hat, axis=0) / N -
np.sum(dx_hat * x_hat, axis=0) * x_hat / N
)
dx /= np.sqrt(sample_var + eps)
# yet another formula
# dx = (dout - (dgamma * x_hat + dbeta) / N) * gamma
# dx /= np.sqrt(sample_var + eps)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
def layernorm_forward(x, gamma, beta, ln_param):
"""Forward pass for layer normalization.
During both training and test-time, the incoming data is normalized per data-point,
before being scaled by gamma and beta parameters identical to that of batch normalization.
Note that in contrast to batch normalization, the behavior during train and test-time for
layer normalization are identical, and we do not need to keep track of running averages
of any sort.
Input:
- x: Data of shape (N, D)
- gamma: Scale parameter of shape (D,)
- beta: Shift paremeter of shape (D,)
- ln_param: Dictionary with the following keys:
- eps: Constant for numeric stability
Returns a tuple of:
- out: of shape (N, D)
- cache: A tuple of values needed in the backward pass
"""
out, cache = None, None
eps = ln_param.get("eps", 1e-5)
###########################################################################
# TODO: Implement the training-time forward pass for layer norm. #
# Normalize the incoming data, and scale and shift the normalized data #
# using gamma and beta. #
# HINT: this can be done by slightly modifying your training-time #
# implementation of batch normalization, and inserting a line or two of #
# well-placed code. In particular, can you think of any matrix #
# transformations you could perform, that would enable you to copy over #
# the batch norm code and leave it almost unchanged? #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# 1st approach - just change axis of sum
# sample_mean = np.mean(x, axis=1, keepdims=True)
# sample_var = np.var(x, axis=1, keepdims=True)
# x_hat = (x - sample_mean) / np.sqrt(sample_var + eps)
# out = gamma * x_hat + beta
# 2nd approach - apply axis=0 to x.T
# sample_mean = np.mean(x.T, axis=0, keepdims=True) # (N,)
# sample_var = np.var(x.T, axis=0, keepdims=True) # (N,)
# x_hat = (x.T - sample_mean) / np.sqrt(sample_var + eps) # (D, N)
# out = gamma * x_hat.T + beta # (N, D)
# cache = {}
# cache['x'] = x # (N, D)
# cache['x_hat'] = x_hat.T # (N, D)
# cache['gamma'] = gamma # (D,)
# cache['beta'] = beta # (D,)
# cache['sample_mean'] = sample_mean # (N,)
# cache['sample_var'] = sample_var # (N,)
# cache['eps'] = eps
# 3d approach - use batchnorm_forward()
out, cache = batchnorm_forward(x.T, gamma.reshape(-1, 1),
beta.reshape(-1, 1), ln_param)
out = out.T
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return out, cache
def layernorm_backward(dout, cache):
"""Backward pass for layer normalization.
For this implementation, you can heavily rely on the work you've done already
for batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from layernorm_forward.
Returns a tuple of:
- dx: Gradient with respect to inputs x, of shape (N, D)
- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)
- dbeta: Gradient with respect to shift parameter beta, of shape (D,)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for layer norm. #
# #
# HINT: this can be done by slightly modifying your training-time #
# implementation of batch normalization. The hints to the forward pass #
# still apply! #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# unpacking the cache
x = cache['x']
N = x.shape[0]
x_hat = cache['x_hat']
gamma = cache['gamma']
beta = cache['beta']
sample_mean = cache['sample_mean']
sample_var = cache['sample_var']
eps = cache['eps']
dgamma = np.sum(dout * x_hat.T, axis=0)
dbeta = np.sum(dout, axis=0)
dx_hat = gamma * dout.T
dx = (dx_hat -
np.sum(dx_hat, axis=0) / N -
np.sum(dx_hat * x_hat, axis=0) * x_hat / N
)
dx /= np.sqrt(sample_var + eps)
dx = dx.T
# 2nd approach - using batchnorm_backward_alt directly
# dx, _, _ = batchnorm_backward_alt(dout.T, cache)
# dx = dx.T
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
def dropout_forward(x, dropout_param):
"""Forward pass for inverted dropout.
Note that this is different from the vanilla version of dropout.
Here, p is the probability of keeping a neuron output, as opposed to
the probability of dropping a neuron output.
See http://cs231n.github.io/neural-networks-2/#reg for more details.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We keep each neuron output with probability p.
- mode: 'test' or 'train'. If the mode is train, then perform dropout;
if the mode is test, then just return the input.
- seed: Seed for the random number generator. Passing seed makes this
function deterministic, which is needed for gradient checking but not
in real networks.
Outputs:
- out: Array of the same shape as x.
- cache: tuple (dropout_param, mask). In training mode, mask is the dropout
mask that was used to multiply the input; in test mode, mask is None.
"""
p, mode = dropout_param["p"], dropout_param["mode"]
if "seed" in dropout_param:
np.random.seed(dropout_param["seed"])
mask = None
out = None
if mode == "train":
#######################################################################
# TODO: Implement training phase forward pass for inverted dropout. #
# Store the dropout mask in the mask variable. #
#######################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
mask = (np.random.rand(*x.shape) < p) / p
out = x * mask
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
#######################################################################
# END OF YOUR CODE #
#######################################################################
elif mode == "test":
#######################################################################
# TODO: Implement the test phase forward pass for inverted dropout. #
#######################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
out = x
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
#######################################################################
# END OF YOUR CODE #
#######################################################################
cache = (dropout_param, mask)
out = out.astype(x.dtype, copy=False)
return out, cache
def dropout_backward(dout, cache):
"""Backward pass for inverted dropout.
Inputs:
- dout: Upstream derivatives, of any shape
- cache: (dropout_param, mask) from dropout_forward.
"""
dropout_param, mask = cache
mode = dropout_param["mode"]
dx = None
if mode == "train":
#######################################################################
# TODO: Implement training phase backward pass for inverted dropout #
#######################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
dx = dout * mask
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
#######################################################################
# END OF YOUR CODE #
#######################################################################
elif mode == "test":
dx = dout
return dx
def conv_forward_naive(x, w, b, conv_param):
"""A naive implementation of the forward pass for a convolutional layer.
The input consists of N data points, each with C channels, height H and
width W. We convolve each input with F different filters, where each filter
spans all C channels and has height HH and width WW.
Input:
- x: Input data of shape (N, C, H, W)
- w: Filter weights of shape (F, C, HH, WW)
- b: Biases, of shape (F,)
- conv_param: A dictionary with the following keys:
- 'stride': The number of pixels between adjacent receptive fields in the
horizontal and vertical directions.
- 'pad': The number of pixels that will be used to zero-pad the input.
During padding, 'pad' zeros should be placed symmetrically (i.e equally on both sides)
along the height and width axes of the input. Be careful not to modfiy the original
input x directly.
Returns a tuple of:
- out: Output data, of shape (N, F, H', W') where H' and W' are given by
H' = 1 + (H + 2 * pad - HH) / stride
W' = 1 + (W + 2 * pad - WW) / stride
- cache: (x, w, b, conv_param)
"""
out = None
###########################################################################
# TODO: Implement the convolutional forward pass. #
# Hint: you can use the function np.pad for padding. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# initialize output
N, C, H, W = x.shape
F, C, HH, WW = w.shape
s, pad = conv_param['stride'], conv_param['pad']
H_out = int(1 + (H + 2 * pad - HH) / s)
W_out = int(1 + (W + 2 * pad - WW) / s)
out = np.zeros((N, F, H_out, W_out))
# pad x with 0s for H, W axis only
# (0, 0) means NO padding, (1, 1) - padding from both sides
x_pad = np.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)))
# iterate over examples in x_pad
for n in range(N):
# iterate over filters
for f in range(F):
# iterate over x_pad with a filter
for ho in range(H_out):
for wo in range(W_out):
# compute np.sum(x_seg * filter) + b
x_seg = x_pad[n, :, ho*s:ho*s+HH, wo*s:wo*s+WW]
out[n, f, ho, wo] = np.sum(x_seg * w[f]) + b[f]
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
cache = (x, w, b, conv_param)
return out, cache
def conv_backward_naive(dout, cache):
"""A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b
"""
dx, dw, db = None, None, None
###########################################################################
# TODO: Implement the convolutional backward pass. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# unpack the cache
x, w, b, conv_param = cache
N, C, H, W = x.shape
F, C, HH, WW = w.shape
s, pad = conv_param['stride'], conv_param['pad']
H_out = int(1 + (H + 2 * pad - HH) / s)
W_out = int(1 + (W + 2 * pad - WW) / s)
# pad x with 0s for H, W axis only
# (0, 0) means NO padding, (1, 1) - padding from both sides
x_pad = np.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)))
# initialize gradients
dx = np.zeros_like(x)
dx_pad = np.zeros_like(x_pad)
dw = np.zeros_like(w)
db = np.zeros_like(b)
# iterate over examples in x
for n in range(N):
# iterate over filters in w
for f in range(F):
# iterate over x_pad with dout as a filter
for ho in range(H_out):
for wo in range(W_out):
print(f'ho={ho} wo={wo}')
# compute np.sum(x_seg * dout)
x_seg = x_pad[n, :, ho*s:ho*s+HH, wo*s:wo*s+WW]
print(f'x_seg={x_seg}')
dw[f] += x_seg * dout[n, f, ho, wo]
print(f'dout={dout[n, f, ho, wo]}\n')
# remove padding
# dx[:, :, :, :] = dx_pad[:, :, pad:-pad, pad:-pad]
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dw, db
def max_pool_forward_naive(x, pool_param):
"""A naive implementation of the forward pass for a max-pooling layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The width of each pooling region
- 'stride': The distance between adjacent pooling regions
No padding is necessary here, eg you can assume:
- (H - pool_height) % stride == 0
- (W - pool_width) % stride == 0
Returns a tuple of:
- out: Output data, of shape (N, C, H', W') where H' and W' are given by
H' = 1 + (H - pool_height) / stride
W' = 1 + (W - pool_width) / stride
- cache: (x, pool_param)
"""
out = None
###########################################################################
# TODO: Implement the max-pooling forward pass #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
cache = (x, pool_param)
return out, cache
def max_pool_backward_naive(dout, cache):
"""A naive implementation of the backward pass for a max-pooling layer.
Inputs:
- dout: Upstream derivatives
- cache: A tuple of (x, pool_param) as in the forward pass.
Returns:
- dx: Gradient with respect to x
"""
dx = None
###########################################################################
# TODO: Implement the max-pooling backward pass #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx
def spatial_batchnorm_forward(x, gamma, beta, bn_param):
"""Computes the forward pass for spatial batch normalization.
Inputs:
- x: Input data of shape (N, C, H, W)
- gamma: Scale parameter, of shape (C,)
- beta: Shift parameter, of shape (C,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance. momentum=0 means that
old information is discarded completely at every time step, while
momentum=1 means that new information is never incorporated. The
default of momentum=0.9 should work well in most situations.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: Output data, of shape (N, C, H, W)
- cache: Values needed for the backward pass
"""
out, cache = None, None
###########################################################################
# TODO: Implement the forward pass for spatial batch normalization. #
# #
# HINT: You can implement spatial batch normalization by calling the #
# vanilla version of batch normalization you implemented above. #
# Your implementation should be very short; ours is less than five lines. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return out, cache
def spatial_batchnorm_backward(dout, cache):
"""Computes the backward pass for spatial batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, C, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, C, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (C,)
- dbeta: Gradient with respect to shift parameter, of shape (C,)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for spatial batch normalization. #
# #
# HINT: You can implement spatial batch normalization by calling the #
# vanilla version of batch normalization you implemented above. #
# Your implementation should be very short; ours is less than five lines. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
def spatial_groupnorm_forward(x, gamma, beta, G, gn_param):
"""Computes the forward pass for spatial group normalization.
In contrast to layer normalization, group normalization splits each entry in the data into G
contiguous pieces, which it then normalizes independently. Per-feature shifting and scaling
are then applied to the data, in a manner identical to that of batch normalization and layer
normalization.
Inputs:
- x: Input data of shape (N, C, H, W)
- gamma: Scale parameter, of shape (1, C, 1, 1)
- beta: Shift parameter, of shape (1, C, 1, 1)
- G: Integer mumber of groups to split into, should be a divisor of C
- gn_param: Dictionary with the following keys:
- eps: Constant for numeric stability
Returns a tuple of:
- out: Output data, of shape (N, C, H, W)
- cache: Values needed for the backward pass
"""
out, cache = None, None
eps = gn_param.get("eps", 1e-5)
###########################################################################
# TODO: Implement the forward pass for spatial group normalization. #
# This will be extremely similar to the layer norm implementation. #
# In particular, think about how you could transform the matrix so that #
# the bulk of the code is similar to both train-time batch normalization #
# and layer normalization! #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return out, cache
def spatial_groupnorm_backward(dout, cache):
"""Computes the backward pass for spatial group normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, C, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, C, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (1, C, 1, 1)
- dbeta: Gradient with respect to shift parameter, of shape (1, C, 1, 1)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for spatial group normalization. #
# This will be extremely similar to the layer norm implementation. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
pass
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment