AI Logic

Architectures

Highway Networks

Updated:

Architecture of Highway Networks. Left: the overall pipeline used in the paper's analysis (a plain fully connected layer reduces to 50 dimensions, 49 stacked highway layers, and a softmax output layer). Right: inside a highway layer (the transform H and transform gate T are computed from the input, and HΓ—T is added to inputΓ—(1βˆ’T) to form the output)

Background and Overview

Highway Networks are networks that attach to each layer a learned gate that decides whether to transform the input or carry it through unchanged, making it possible to train very deep networks with ordinary gradient descent. They were proposed in 2015 by Srivastava, Greff, and Schmidhuber at IDSIA, a research institute in Switzerland. The name comes from the idea of building paths along which information flows across layers without obstruction ("information highways").

At the time, it was known that deeper networks give better accuracy, but simply stacking more layers made training stall. Workarounds included careful initialization, multi-stage training, and auxiliary losses attached to intermediate layers. Inspired by the gates of LSTM, Highway Networks tackled the problem by changing the network architecture itself.

The main results of the paper are as follows.

  • On MNIST, comparing depths of 10, 20, 50, and 100 layers, plain networks became harder to train as depth increased, while Highway Networks trained as well at 100 layers as at 10.
  • Preliminary experiments confirmed that SGD training does not stall even for networks with more than 1000 layers.
  • On CIFAR-10, networks of a depth that could previously be trained only with a two-stage method guided by the outputs of a separate shallow network (FitNets) reached equal or better accuracy with ordinary single-stage training.

Together with ResNet, Highway Networks were among the first methods to show that networks with more than 100 layers can be trained. The residual connection of ResNet can be seen as Highway Networks with the gate removed, always adding the input as is.

Theory: Mixing "Transform" and "Carry" with Gates

The idea of Highway Networks is to make each layer's output a weighted sum of "the transformed value" and "the input itself", with the proportion determined by a gate.

A layer of a plain network applies a transform HH (usually a fully connected layer and an activation function) to the input x\boldsymbol{x} to produce the output y\boldsymbol{y} (biases and layer indices omitted).

y=H(x,WH)\boldsymbol{y} = H(\boldsymbol{x}, \boldsymbol{W}_H)

A layer of a Highway Network (a highway layer) produces its output as follows.

  1. Transform the input x\boldsymbol{x} to compute H(x)H(\boldsymbol{x}).
  2. From the same input, compute the transform gate T(x)T(\boldsymbol{x}). Its values lie between 0 and 1 and express, element by element, how much of the transformed value to use.
  3. Use 1βˆ’T(x)1 - T(\boldsymbol{x}) as the carry gate, the proportion of the input to carry through unchanged.
  4. Multiply each pair element-wise and add them to form the output.
y=H(x,WH)β‹…T(x,WT)+xβ‹…(1βˆ’T(x,WT))\boldsymbol{y} = H(\boldsymbol{x}, \boldsymbol{W}_H) \cdot T(\boldsymbol{x}, \boldsymbol{W}_T) + \boldsymbol{x} \cdot \big(1 - T(\boldsymbol{x}, \boldsymbol{W}_T)\big)

Here β‹…\cdot denotes the element-wise product. The transform gate is a fully connected layer followed by the sigmoid function Οƒ\sigma.

T(x)=Οƒ(WT⊀x+bT)T(\boldsymbol{x}) = \sigma(\boldsymbol{W}_T^\top \boldsymbol{x} + \boldsymbol{b}_T)

The paper presents the general form y=Hβ‹…T+xβ‹…C\boldsymbol{y} = H \cdot T + \boldsymbol{x} \cdot C, in which a carry gate CC is also learned separately, and then sets C=1βˆ’TC = 1 - T for simplicity.

At the extreme values of the gate, a highway layer behaves as follows.

Transform gate TTOutput y\boldsymbol{y}Derivative of output w.r.t. input
0Carries the input x\boldsymbol{x} unchangedIdentity matrix II
1Transformed value H(x)H(\boldsymbol{x}) (same as a plain layer)Hβ€²(x)H'(\boldsymbol{x})

A layer whose gate is close to 0 passes both the input and the gradient through almost unchanged. As a result, even when many layers are stacked, there is a path along which signals and gradients arrive without weakening. Because the gate is a sigmoid, it never becomes exactly 0 or 1 and moves smoothly between the two behaviors.

Matching shapes

Because of the addition, x\boldsymbol{x}, y\boldsymbol{y}, H(x)H(\boldsymbol{x}), and T(x)T(\boldsymbol{x}) must all have the same dimension. To change the size of the representation, either subsample or zero-pad x\boldsymbol{x}, or change the dimension with a plain layer without gates. The paper uses the latter. The left side of the figure at the top of the article shows the network used in the paper's analysis: a first plain fully connected layer reduces the input to 50 dimensions, followed by 49 stacked highway layers.

Convolutional highway layers

Highway layers can be built in the same form with convolutions. Both HH and TT are convolutions with the same receptive field size, and zero padding keeps the output's height and width equal to the input's. The paper's convolutional highway layers use ReLU as the activation function of HH.

Training: Starting the Gate Bias Negative

The key to training deep Highway Networks is to initialize the transform gate bias bT\boldsymbol{b}_T to a negative value.

With bT\boldsymbol{b}_T set to βˆ’1-1 or βˆ’3-3, T(x)T(\boldsymbol{x}) is close to 0 at the start of training, so each layer begins in the "carry" behavior, passing the input through almost unchanged. However many dozens of layers are stacked, training starts from a state close to a shallow network. This follows the practice of biasing LSTM gates at initialization to make long-range dependencies easier to learn.

The paper notes the following about this scheme.

  • Independent of the form of HH: In plain deep networks, an initialization that preserves signal variance in the forward and backward passes (Xavier initialization or He initialization) must be chosen to match the form of HH, such as its activation function. In Highway Networks, training progressed with the negative bias alone, whether WH\boldsymbol{W}_H was initialized from various zero-mean distributions or the activation function was changed.
  • Rule-of-thumb values: While recommending that the initial bias be tuned as a hyperparameter, the paper suggests βˆ’1-1, βˆ’2-2, and βˆ’3-3 for convolutional highway networks of depth about 10, 20, and 30.

All experiments use SGD with momentum. In the MNIST optimization experiments the learning rate decays exponentially; in the others it is reduced by a fixed factor at fixed intervals.

Why Deep Networks Remain Trainable

The paper analyzes why Highway Networks remain trainable at great depth and how the gates are used after training.

A path for information and gradients

In a layer whose transform gate is close to 0, the output is nearly equal to the input, and the derivative of the output with respect to the input is nearly the identity matrix. In backpropagation the derivatives of the layers are multiplied together, so stacking dozens of plain layers tends to shrink the gradient (the vanishing gradient problem). Layers with a large carry proportion pass the gradient to the previous layer almost unchanged, so the learning signal reaches the first layers even in deep networks.

As an everyday analogy, each layer is a fork between a "local road" (transform) and an "expressway" (carry through unchanged), and a traffic signal (the gate) decides how much of each to use for each input. Layers that are not needed are bypassed via the expressway, so information is less likely to be lost along the way even with many layers.

Gates are used differently for each input

Examining 50-layer fully connected Highway Networks (MNIST and CIFAR-100) revealed the following.

  • The transform gate biases often decreased further from their initial values (βˆ’2-2 and βˆ’4-4). Yet on average the gates were open, and for a given input only a few gates were strongly open. The paper interprets this as the negative bias being used not to close the gates but to make them selective.
  • The outputs of the layers changed little across many layers; most of the change happened in the early layers (about 15 layers for MNIST and about 40 for CIFAR-100).
  • The average gate activity differed by class, so the network routed information differently depending on the input.

The network itself decides how much depth it needs

When all transform gates of a single layer are set to 0 (bypassing that layer) and the change in performance is measured, bypassing layers 15 to 45 on MNIST had almost no effect, and about 60% of the layers did not contribute to the result. On the harder CIFAR-100, by contrast, bypassing any of the first 40 or so layers degraded performance. Simple problems let extra layers rest, while hard problems use all of them.

The paper cites, as an advantage of gating, the ability to change the flow of information depending on the input, unlike fixed shortcuts. The ResNet paper, on the other hand, points out as a difference from ResNet that when the gate closes, the layer no longer learns a residual.

Experimental Results

Depth and ease of training (MNIST, Figure 1 of the paper)

Networks with a plain fully connected first layer followed by 9, 19, 49, or 99 fully connected layers were compared. Each layer had 50 units in Highway Networks and 71 in plain networks, matching the parameters per layer (about 5000). The learning rate, momentum, activation function (ReLU or tanh), and so on were each chosen by 100 runs of random search.

  • Plain networks trained well at 10 and 20 layers (mean training loss below 10βˆ’410^{-4}), but degraded sharply when made deeper.
  • Highway Networks trained as well at 50 and 100 layers as at 10 and 20.
  • At 100 layers, the training loss of Highway Networks was more than 100 times lower than that of plain networks of similar size.
  • Highway Networks converged faster than plain networks at every depth.

CIFAR-10: comparison with FitNets (test accuracy %, Table 2 of the paper)

FitNets train deep, thin networks in two stages, guided by the outputs of a shallow teacher network. Highway Networks use ordinary single-stage training.

NetworkLayersParametersAccuracy (%)
Teacher network5~9M90.18
FitNet A11~250K89.01
FitNet B19~2.5M91.61
Highway A (same shape as FitNet A)11~236K89.18
Highway B (same shape as FitNet B)19~2.3M92.46
Highway C32~1.25M91.20

Highway C is a 32-layer network alternating 3Γ—3 and 1Γ—1 receptive fields; it outperformed the teacher network with fewer parameters.

CIFAR-10 and CIFAR-100: comparison with methods of the time (test accuracy %, with translation and horizontal-flip data augmentation; Table 3 of the paper)

NetworkCIFAR-10CIFAR-100
Maxout90.6261.42
Network In Network91.1964.32
Deeply Supervised Net92.0365.43
All-CNN92.7566.29
Highway Networks92.4067.76

In this experiment, following Network In Network, the final fully connected layer is replaced with a 1Γ—1 convolution and global average pooling. The hyperparameters chosen on CIFAR-10 were reused unchanged for CIFAR-100. On CIFAR-100 this was the best result. The Highway Networks figures are the best of 5 runs; the means are 92.31% and 67.61%, respectively.

Practical Considerations

Keep the following points in mind when using Highway Networks.

  • Start the transform gate bias negative: If the bias is initialized to 0, the gates start about half open and the carry path does not work well enough. Start from the paper's rule of thumb (βˆ’1-1, βˆ’2-2, βˆ’3-3 for convolutional networks of depth 10, 20, 30) and adjust for the depth.
  • Use plain layers where shapes change: The input and output of a highway layer must have the same dimension. Where the number of channels or the spatial size changes, use a plain layer without gates (or pooling).
  • More parameters and computation: The transform gate TT has weights of the same size as HH. At the same width, the parameters and computation per layer roughly double. In the paper's MNIST experiments, the widths were set to 50 and 71 to match the number of parameters.
  • Reading the reported numbers: The paper's CIFAR results give both the best of 5 runs and the mean Β± standard deviation. When comparing with other methods, make sure to compare the same kind of value.

The Highway Networks paper examines training loss (ease of optimization) and test accuracy (generalization) in separate experiments. A lower training loss at greater depth does not guarantee higher test accuracy. When choosing the depth, check accuracy on validation data.

Comparison with Other Models

Comparing Highway Networks with other networks that likewise have "paths that skip layers" from the same viewpoint gives the following.

NetworkForm of the skip pathOpening/closing the pathExtra parametersHow earlier-layer information is combined
Plain networkNoneβ€”β€”β€”
Highway NetworksHβ‹…T+xβ‹…(1βˆ’T)H \cdot T + \boldsymbol{x} \cdot (1 - T)A gate decides per inputGate weights (same size as HH)Weighted sum
ResNetF(x)+xF(\boldsymbol{x}) + \boldsymbol{x}Always openNone (except where shapes change)Addition
DenseNetConcatenates the outputs of all earlier layers as inputAlways openNoneConcatenation

Removing the gate from Highway Networks and always adding HH and the input one-to-one gives the form of ResNet's residual connection. The ResNet paper compares, on CIFAR-10, a 19-layer Highway Network (2.3M parameters, 7.54% error) with a 110-layer ResNet (1.7M parameters, 6.43% error). The DenseNet paper cites Highway Networks as one of the first methods to train networks with more than 100 layers using gates and bypass paths, and notes that bypass paths were thought to be the key to easing training.

The idea of using a gate to decide "how much new value to use and how much of the previous value to keep" is also the same as the mechanism by which LSTM and GRU carry information along the time axis. Highway Networks can be seen as applying it along the layer axis (depth).

Rough guidelines for choosing are as follows.

  • Building a deep image network: Today, ResNet's gate-free residual connection is the common choice. It adds no parameters and is simple to implement.
  • Routing differently per input: When the flow of information should be adjusted by gates, highway layers are an option.
  • Investigating the role of each layer: As in the paper, closing gates to bypass layers reveals how much each layer contributes to the result.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
Example of a highway layer from Highway Networks (Srivastava et al. 2015), built exactly as in Eq. (3) of the paper
  y = H(x)Β·T(x) + xΒ·(1 βˆ’ T(x)), T(x) = Οƒ(W_T x + b_T), with b_T initialized to a negative value (Sec. 2.2)
PyTorch has no built-in highway layer
"""


class HighwayLayer(nn.Module):
  def __init__(self, dim, gate_bias=-2.0):
    super().__init__()
    self.H = nn.Linear(dim, dim)                 # Transform (here, fully connected layer + ReLU)
    self.T = nn.Linear(dim, dim)                 # Transform gate
    nn.init.constant_(self.T.bias, gate_bias)    # Negative, so the layer initially leans toward carrying the input

  def forward(self, x):
    h = F.relu(self.H(x))
    t = torch.sigmoid(self.T(x))                 # 0 to 1: per element, how much of the transformed value to use
    return h * t + x * (1 - t)                   # Carry gate is C = 1 βˆ’ T


class ConvHighwayLayer(nn.Module):
  """Convolutional highway layer: H and T use the same receptive field; zero padding keeps height and width"""
  def __init__(self, channels, kernel_size=3, gate_bias=-1.0):
    super().__init__()
    pad = kernel_size // 2
    self.H = nn.Conv2d(channels, channels, kernel_size, padding=pad)
    self.T = nn.Conv2d(channels, channels, kernel_size, padding=pad)
    nn.init.constant_(self.T.bias, gate_bias)

  def forward(self, x):
    t = torch.sigmoid(self.T(x))
    return F.relu(self.H(x)) * t + x * (1 - t)


class HighwayMLP(nn.Module):
  """Same shape as the paper's analysis: a plain first FC layer to 50 dims, 49 highway layers, then a softmax output layer"""
  def __init__(self, in_dim=784, width=50, num_highway=49, num_classes=10):
    super().__init__()
    self.first = nn.Linear(in_dim, width)        # Where the dimension changes, use a plain layer without gates
    self.layers = nn.Sequential(*[HighwayLayer(width) for _ in range(num_highway)])
    self.out = nn.Linear(width, num_classes)

  def forward(self, x):
    x = F.relu(self.first(x.flatten(1)))
    return self.out(self.layers(x))              # Softmax is applied inside the loss function (cross_entropy)


model = HighwayMLP()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)   # The paper uses SGD with momentum
images, labels = torch.randn(32, 1, 28, 28), torch.randint(0, 10, (32,))

model.train()                                    # No dropout or BN, so train/eval behave the same
loss = F.cross_entropy(model(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()

# The "bypass a layer" experiment of Sec. 4.2: output when one layer's transform gate is set to 0
model.eval()
with torch.no_grad():
  x = F.relu(model.first(images.flatten(1)))
  for i, layer in enumerate(model.layers):
    x = x if i == 10 else layer(x)               # Only the 11th layer becomes y = x (T = 0)
  lesioned_logits = model.out(x)

conv_layer = ConvHighwayLayer(16)
print(conv_layer(torch.randn(2, 16, 32, 32)).shape)   # torch.Size([2, 16, 32, 32])

FAQ

Q. How do Highway Networks differ from ResNet?
A.

Both have a path that skips layers and carries the input forward, but Highway Networks decide how open that path is for each input with a gate T(x)T(\boldsymbol{x}), giving the output Hβ‹…T+xβ‹…(1βˆ’T)H \cdot T + \boldsymbol{x} \cdot (1 - T). ResNet has no gate and always adds the input as is: F(x)+xF(\boldsymbol{x}) + \boldsymbol{x}. ResNet therefore has no extra parameters, while Highway Networks gain parameters for the gates in exchange for being able to change the flow of information depending on the input.

Q. Why is the transform gate bias set negative?
A.

So that each layer carries its input through almost unchanged at the start of training. With a negative bias, the sigmoid output TT is close to 0 and the output is nearly the input x\boldsymbol{x}. Even with dozens of layers, training starts from a state close to a shallow network, and signals and gradients are less likely to weaken along the way. The paper suggests βˆ’1-1, βˆ’2-2, and βˆ’3-3 for convolutional networks of depth about 10, 20, and 30.

Q. How are Highway Networks related to LSTM?
A.

The paper states that the mechanism of regulating information flow with gates was inspired by LSTM. LSTM carries information over long spans along the time axis, using gates to decide "how much of the previous state to keep". Highway Networks apply the same idea along the layer axis (depth), using gates to decide "how much of the input to carry unchanged to the next layer". The initialization that biases the gates at the start also follows a technique used for LSTM gates.

References

  1. Srivastava, R. K., Greff, K., & Schmidhuber, J. (2015). Highway Networks. ICML 2015 Deep Learning Workshop. arXiv:1505.00387.
  2. Srivastava, R. K., Greff, K., & Schmidhuber, J. (2015). Training Very Deep Networks. NeurIPS 2015. arXiv:1507.06228.
  3. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  4. Huang, G., Liu, Z., van der Maaten, L., & Weinberger, K. Q. (2017). Densely Connected Convolutional Networks. CVPR 2017. arXiv:1608.06993.