AI Logic

Architectures

Xception

Updated:

Xception architecture. Left: the overall flow (the entry flow with two convolutions and three modules, the middle module repeated 8 times, the exit flow, global average pooling, an optional fully connected layer, and logistic regression). Right: inside the entry module and the middle module (sequences of ReLU and separable convolutions with residual connections), and the order of computation in a separable convolution (a depthwise 3×3 convolution followed by a 1×1 convolution)

Background and overview

Xception is a convolutional neural network that replaces every module of GoogLeNet (Inception) with depthwise separable convolutions and connects them with residual connections. It was published in 2016 by François Chollet (the creator of Keras) at Google and accepted to CVPR 2017. The name is short for "Extreme Inception."

An ordinary convolution uses a single filter to learn both "patterns across height and width (spatial correlations)" and "which channels to combine (cross-channel correlations)" at the same time. Inception modules partly separate these two jobs by first mixing channels with a 1×1 convolution and then looking at the spatial dimensions with 3×3 and similar convolutions. Xception makes a stronger hypothesis: these two can be learned completely separately. The depthwise separable convolution is a direct embodiment of that hypothesis, and the whole network is built from it alone.

The main results of the paper are as follows:

  • On ImageNet, it achieves slightly higher top-1 accuracy than Inception V3, which has nearly the same number of parameters (about 23 million) (78.2% → 79.0%).
  • On JFT, an internal dataset of 350 million images and 17,000 classes, the evaluation metric (MAP@100 on FastEval14k) improves by 4.3% relative.
  • Because the parameter counts are nearly equal, the paper argues the gain comes not from a larger model but from using parameters more efficiently.

Another feature is its simple structure. Xception is "a linear stack of depthwise separable convolution layers with residual connections," and like VGG it can be written in a few dozen lines of code. It is easier to define and modify than Inception V3, whose modules branch into many paths.

Theory: taking the Inception hypothesis to the extreme

Xception starts from the view that "an Inception module sits between an ordinary convolution and a depthwise separable convolution." The paper develops the idea in the following order:

  1. Simplify the Inception module and keep only the 3×3 convolution branches (dropping the average pooling branch). Each branch applies a 1×1 convolution followed by a 3×3 convolution.
  2. This form is exactly equivalent to "applying one large 1×1 convolution, splitting its output channels into several non-overlapping segments, and applying a 3×3 convolution to each segment."
  3. What happens if the number of segments is pushed to the maximum, applying a separate 3×3 convolution to every single output channel? This is the "extreme" Inception module.
  4. This extreme form is almost the same as a depthwise separable convolution (a per-channel spatial convolution plus a 1×1 convolution).

Ordered by the number of segments, the ordinary convolution and the depthwise separable convolution sit at the two ends of a single scale.

FormNumber of segments the 3×3 convolution is applied toHandling of spatial and channel dimensions
Ordinary convolution (preceded by a 1×1 convolution)1 (all channels together)Learned jointly
Inception module3 to 4 (splitting hundreds of channels)Partly separated
Depthwise separable convolutionEqual to the number of channelsFully separated

Intermediate numbers of segments correspond to the number of groups in a grouped convolution.

Depthwise separable convolution

Let the input have MM channels, the output NN channels, and the filter size be 3×33 \times 3. A depthwise separable convolution computes in two stages (notation follows the depthwise separable convolution article).

G^k,l,m=∑i,jK^i,j,m Fk+i−1, l+j−1, m(depthwise convolution: spatial only, per channel)\hat{G}_{k,l,m} = \sum_{i,j} \hat{K}_{i,j,m} \, F_{k+i-1,\, l+j-1,\, m} \qquad \text{(depthwise convolution: spatial only, per channel)} Gk,l,n=∑mPm,n G^k,l,m(1×1 convolution: mixes only channels, per pixel)G_{k,l,n} = \sum_{m} P_{m,n} \, \hat{G}_{k,l,m} \qquad \text{(1×1 convolution: mixes only channels, per pixel)}

FF is the input feature map, K^\hat{K} is the depthwise convolution weight (the mm-th filter applies only to the mm-th channel), and PP is the M×NM \times N weight of the 1×1 convolution. The number of weights drops from 3⋅3⋅M⋅N3 \cdot 3 \cdot M \cdot N for an ordinary convolution to 3⋅3⋅M+M⋅N3 \cdot 3 \cdot M + M \cdot N. For Xception's middle layers (M=N=728M = N = 728), 4,769,856 weights become 536,536, about 1/8.9.

Two differences from the extreme Inception module

The paper notes two differences between the extreme Inception module and the usual depthwise separable convolution:

  • Order of operations: Inception applies the 1×1 convolution first, while the depthwise separable convolution applies the spatial convolution first. Since the layers are stacked, the paper considers this difference unimportant.
  • Activation in between: Inception places a ReLU after both operations, while depthwise separable convolutions are usually implemented without an activation in between. Xception uses the form without one, and verifies this experimentally (see a later section).

SeparableConv2D in TensorFlow and Keras is this depthwise separable convolution. It is different from what image processing calls a "separable convolution," which splits a 3×3 kernel into 3×1 and 1×3 (spatial separation).

Overall architecture and training setup

Xception extracts features with 36 convolutional layers, followed by logistic regression (a layer that outputs class probabilities). The 36 layers are grouped into 14 modules, and all modules except the first and last have linear residual connections (shortcuts). Every convolution and separable convolution (depthwise separable convolution) is followed by batch normalization.

An image passes through the following three flows in order (Figure 5 of the paper; left of the figure at the top of the article).

  1. Entry flow: A 299×299 image goes through a 3×3 convolution (32 channels, stride 2) and a 3×3 convolution (64 channels). It then passes through three entry modules. Each module applies "ReLU, separable convolution" twice and halves the height and width with 3×3 max pooling (stride 2). The shortcut goes through a 1×1 convolution (stride 2) to match shapes. The channels grow to 128, 256, and 728, giving a 19×19×728 feature map.
  2. Middle flow: A module that applies "ReLU, separable convolution (728 channels)" three times and adds an identity shortcut is repeated 8 times. The shape stays 19×19×728.
  3. Exit flow: After a module of the same form as the entry modules (728 and 1024 channels, max pooling, 1×1 convolution shortcut), it applies a separable convolution (1536 channels) with ReLU and a separable convolution (2048 channels) with ReLU. Global average pooling produces a 2048-dimensional vector, optionally followed by fully connected layers, and logistic regression outputs class probabilities.

All separable convolutions use a depth multiplier of 1, meaning the depthwise convolution does not increase the number of channels.

Training setup (Sections 4.2 to 4.3 of the paper)

The paper trains both models with the same setup as Inception V3.

ItemImageNetJFT
OptimizerSGD, momentum 0.9RMSprop, momentum 0.9
Learning rateStarts at 0.045, multiplied by 0.94 every 2 epochsStarts at 0.001, multiplied by 0.9 every 3 million samples
Weight decay10−510^{-5} (Inception V3's 4×10−54 \times 10^{-5} did not suit Xception)Same
Dropout0.5 before logistic regressionNone (the data is large, so overfitting is unlikely)
Auxiliary classifierNot usedNot used
InferenceUses Polyak averaging (an average of weights during training)Same

Training used 60 NVIDIA K80 GPUs; each ImageNet experiment took about 3 days, and JFT took over a month. The JFT models were not trained to convergence.

Why accuracy improves at the same parameter count

Since Xception and Inception V3 have nearly the same number of parameters (within 3.5%), the paper attributes the accuracy gap not to "model size" but to "how the parameters are used."

  • Learning spatial and channel dimensions separately: In an ordinary convolution, a single filter represents both "which pattern" and "which combination of channels" at once, so many of its weights are spent on representing combinations. Learning them separately allows more channels or layers for the same number of weights.
  • Residual connections enable deep stacking: The paper also trained Xception without residual connections on ImageNet. With residual connections, both training progress and final accuracy were clearly better (Figure 9). The paper also notes, however, that using the same training setup for the model without residual connections may have been an unfair comparison.
  • No activation in between: Compared with inserting ReLU or ELU between the depthwise convolution and the 1×1 convolution, inserting nothing gave faster training and higher final accuracy (Figure 10).

The paper highlights the third point because the opposite result (an intermediate activation helps) had been reported for Inception modules. Its explanation is as follows. In an Inception module, the spatial convolution is applied to "deep" features with dozens of channels, so an activation is helpful. A depthwise convolution acts on "shallow" single-channel features, so applying ReLU there sets negative values to 0 and loses information, which may actually hurt.

As an everyday analogy, an ordinary convolution is like "deciding how to cut the ingredients and how to combine them together for each dish." Xception first only prepares each ingredient (spatial), and then only decides the combination (channel). Splitting the work lets it make many more dishes for the same effort.

The paper states that Xception's result does not mean "depthwise separable convolution is optimal." There may be even better points between ordinary convolutions and depthwise separable convolutions (with an intermediate number of segments), which it leaves as future work. An intermediate number of segments corresponds to a grouped convolution, which the contemporaneous ResNeXt uses.

Experimental results

ImageNet accuracy (validation data, single crop, single model; Table 1 of the paper)

Modeltop-1top-5
VGG-160.7150.901
ResNet-1520.7700.933
Inception V3 (no auxiliary classifier)0.7820.941
Xception0.7900.945

The VGG-16 and ResNet-152 numbers are included for reference. Xception is slightly higher than Inception V3 and also surpasses the values reported by He et al. for ResNet-50, 101, and 152.

Accuracy on JFT (MAP@100 on FastEval14k; Table 2 of the paper)

ModelWithout FC layersWith FC layers (2 layers × 4096 units)
Inception V36.366.50
Xception6.706.78

MAP@100 is mAP computed over the top 100 predictions, with each class weighted by how often it appears in social media images. The JFT results are pre-convergence values (30 million updates, about a month). Without FC layers, the improvement is 4.3% relative.

The paper suggests the gap is larger on JFT than on ImageNet because Inception V3 was designed with ImageNet in mind and may be over-fit to that task. Since Xception's training setup is still the one tuned for Inception V3, the paper says Xception might do even better on ImageNet with a setup searched for it.

Size and training speed (ImageNet, 60 K80 GPUs; Table 3 of the paper)

ModelParametersSteps per second
Inception V323,626,72831
Xception22,855,95228

The parameter counts are nearly equal, and Xception is slightly slower. The paper expects that optimizing the implementation of depthwise convolutions would make it faster than Inception V3.

Practical considerations

Keep the following points in mind when using Xception:

  • Fewer parameters do not necessarily mean faster: In the paper, training was about 10% slower than Inception V3, which has nearly the same parameter count (31 vs. 28 steps per second). The paper sees speed as depending on the implementation of depthwise convolutions, so check it with the library and hardware you use.
  • Input is 299×299: Xception in the paper takes 299×299 images as input (Figure 5). When comparing with models evaluated on 224×224 images, keep the difference in input size in mind.
  • The training setup is the one for Inception V3: The paper's numbers come from a setup tuned for Inception V3. Only weight decay was changed to 10−510^{-5}, because Inception V3's value did not fit.

In a separable convolution, no activation is inserted between the depthwise convolution and the 1×1 convolution. MobileNet inserts batch normalization and ReLU in between, so this is easy to mix up when reusing components. In the Xception paper, inserting ReLU or ELU in between slowed training and lowered accuracy.

Comparison with other models

Comparing Xception with image classification networks of the same period from the same perspective gives the following:

NetworkBasic componentSpatial and channel dimensionsResidual connectionsStructural simplicity
VGG3×3 ordinary convolutionsLearned jointlyNoSimple (stack identical layers)
ResNet1×1 and 3×3 ordinary convolutions (bottleneck)Learned jointlyYesSimple
Inception V3 (improved GoogLeNet)Branching modules (1×1 followed by 3×3, etc.)Separated by the number of branches (3 to 4)NoComplex (branch shapes differ per module)
ResNeXtBottleneck 3×3 replaced by a grouped convolutionSeparated by the number of groupsYesSimple (parallel branches of the same shape)
XceptionDepthwise separable convolutionsFully separatedYes (12 modules)Simple (stack identical layers)
MobileNetDepthwise separable convolutions (BN and ReLU in between)Fully separatedNoSimple

The difference from Inception V3 is how far the module separates the spatial and channel dimensions. Xception maximizes the separation and, in exchange, makes the structure uniform and simple. MobileNet uses the same component but with a different goal. Xception aims to raise accuracy at about the same size as Inception V3, while MobileNet aims for a small, fast model that runs on smartphones and similar devices.

Rough guidelines for choosing:

  • Raising accuracy at about the same size as the Inception family: Xception is a candidate. Its simple structure also makes it easy to modify.
  • Prioritizing lightness and speed: Choose a model designed for efficiency, such as MobileNet.
  • Prioritizing availability of pretrained weights and tooling: Trying ResNet first is common. torchvision does not include Xception, so in PyTorch you either build it yourself or use an external library.

PyTorch example

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

"""
Build Xception following Figure 5 of the paper (not included in torchvision)
- Separable conv = depthwise 3×3 conv (groups=in_ch) -> 1×1 conv -> BN. No activation in between
- 3 entry modules -> 8 middle modules -> 1 exit module -> separable 1536, 2048 -> global average pooling
"""


class SeparableConv2d(nn.Sequential):
  def __init__(self, in_ch, out_ch):
    super().__init__(
      nn.Conv2d(in_ch, in_ch, 3, padding=1, groups=in_ch, bias=False),   # depthwise: spatial only, per channel
      nn.Conv2d(in_ch, out_ch, 1, bias=False),                           # 1×1: mixes channels (no ReLU in between)
      nn.BatchNorm2d(out_ch),                                            # BN after every separable conv
    )


class DownBlock(nn.Module):
  """Entry/exit module: (ReLU-SepConv) × 2 -> 3×3 max pooling (stride 2); shortcut is a 1×1 conv (stride 2)"""
  def __init__(self, in_ch, mid_ch, out_ch, first_relu=True):
    super().__init__()
    self.body = nn.Sequential(
      nn.ReLU() if first_relu else nn.Identity(),   # only the first entry module has no leading ReLU
      SeparableConv2d(in_ch, mid_ch),
      nn.ReLU(),
      SeparableConv2d(mid_ch, out_ch),
      nn.MaxPool2d(3, stride=2, padding=1),
    )
    self.shortcut = nn.Sequential(nn.Conv2d(in_ch, out_ch, 1, stride=2, bias=False), nn.BatchNorm2d(out_ch))

  def forward(self, x):
    return self.body(x) + self.shortcut(x)


class MiddleBlock(nn.Module):
  """Middle module: (ReLU-SepConv 728) × 3; shortcut is the identity"""
  def __init__(self, ch=728):
    super().__init__()
    self.body = nn.Sequential(*[m for _ in range(3) for m in (nn.ReLU(), SeparableConv2d(ch, ch))])

  def forward(self, x):
    return self.body(x) + x


class Xception(nn.Module):
  def __init__(self, num_classes=1000, drop_rate=0.5):
    super().__init__()
    self.entry = nn.Sequential(
      nn.Conv2d(3, 32, 3, stride=2, bias=False), nn.BatchNorm2d(32), nn.ReLU(),
      nn.Conv2d(32, 64, 3, bias=False), nn.BatchNorm2d(64), nn.ReLU(),
      DownBlock(64, 128, 128, first_relu=False),
      DownBlock(128, 256, 256),
      DownBlock(256, 728, 728),
    )
    self.middle = nn.Sequential(*[MiddleBlock(728) for _ in range(8)])   # repeated 8 times
    self.exit = nn.Sequential(
      DownBlock(728, 728, 1024),
      SeparableConv2d(1024, 1536), nn.ReLU(),
      SeparableConv2d(1536, 2048), nn.ReLU(),
      nn.AdaptiveAvgPool2d(1),
    )
    self.dropout = nn.Dropout(drop_rate)          # 0.5 before logistic regression on ImageNet
    self.fc = nn.Linear(2048, num_classes)        # combined with softmax to give class probabilities

  def forward(self, x):
    x = self.exit(self.middle(self.entry(x))).flatten(1)
    return self.fc(self.dropout(x))


model = Xception()
print(sum(p.numel() for p in model.parameters()) / 1e6, "M")   # 22,855,952 in Table 3 of the paper (differs slightly depending on how BN etc. are counted)
x = torch.randn(2, 3, 299, 299)
print(model.entry(x).shape)                     # [2, 728, 19, 19]

optimizer = torch.optim.SGD(model.parameters(), lr=0.045, momentum=0.9, weight_decay=1e-5)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=2, gamma=0.94)   # call once per epoch: ×0.94 every 2 epochs
model.train()                                   # BN uses mini-batch statistics; dropout is active
loss = F.cross_entropy(model(x), torch.randint(0, 1000, (2,)))
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                    # BN uses running mean and variance; dropout is off
with torch.no_grad():
  probs = model(x).softmax(dim=1)

FAQ

Q. What is the difference between Xception and Inception V3?
A.

Their modules differ. An Inception V3 module runs 3 to 4 parallel branches that apply a 1×1 convolution followed by a 3×3 or similar convolution, splitting the channels into a few segments before looking at the spatial dimensions. Xception is built only from depthwise separable convolutions, where the number of segments equals the number of channels, and adds residual connections. With nearly the same parameter count (about 23 million), ImageNet top-1 accuracy rose from 78.2% to 79.0%.

Q. Are Xception and MobileNet the same thing?
A.

Both use depthwise separable convolutions as their basic component, but they are different models. Xception aims to raise accuracy at about the same size as Inception V3 (about 23 million parameters, 299×299 input), uses residual connections, and puts no activation between the depthwise convolution and the 1×1 convolution. MobileNet aims for a small, fast model that runs on smartphones and similar devices, and inserts batch normalization and ReLU in between.

Q. Why is there no ReLU after the depthwise convolution?
A.

Because in the paper's experiments, leaving it out gave faster training and higher final accuracy (ReLU and ELU were both tried and compared). The paper suggests that the output of a depthwise convolution consists of "shallow" single-channel features, so applying ReLU there sets negative values to 0 and loses information. For Inception modules, which apply spatial convolutions to features with dozens of channels, the opposite was reported: inserting an activation helps.

References

  1. Chollet, F. (2017). Xception: Deep Learning with Depthwise Separable Convolutions. CVPR 2017. arXiv:1610.02357.
  2. Szegedy, C., Vanhoucke, V., Ioffe, S., Shlens, J., & Wojna, Z. (2016). Rethinking the Inception Architecture for Computer Vision. CVPR 2016. arXiv:1512.00567.
  3. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  4. Howard, A. G., et al. (2017). MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications. arXiv:1704.04861.