Reference Deployment Guide for RDMA accelerated Caffe2 with an NVIDIA GPU Card over 100Gb Infiniband Network running on Docker Containers

Version 17

    In this document we will demonstrate a distributed deployment procedure of RDMA accelerated Caffe2 running on Docker Containers and Mellanox end-to-end 100 Gb/s Infiniband (IB) solution.

    This document describes the process of building the Caffe2 from sources for Ubuntu 16.04.3 LTS and Docker 8.03.0-ce on four physical servers.







    What is Caffe2 ?

    Caffe2 is a deep learning framework that provides an easy and straightforward way for you to experiment with deep learning and leverage community contributions of new models and algorithms. You can bring your creations to scale using the power of GPUs in the cloud or to the masses on mobile with Caffe2’s cross-platform libraries. Caffe2 supports Cuda 9.0 & CuDNN 7.1 (req. registration), in this guide we will use the installing from sources from their website for a much easier installation. In order to use Caffe2 with GPU support, you must have an NVIDIA GPU with a minimum compute capability of 3.0.


    What's Docker ?

    Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package. (from What is Docker? |


    Mellanox’s Machine Learning

    Mellanox Solutions accelerate many of the world’s leading artificial intelligence and machine learning platforms and wide range of applications, ranging from security, finance, and image and voice recognition, to self-driving cars and smart cities. Mellanox solutions enable companies and organizations such as Baidu, NVIDIA,, Facebook, PayPal and more to leverage machine learning platforms to enhance their competitive advantage.

    In this post we will show how to build most efficient Machine Learning cluster enhanced by native RDMA over 100Gbps IB network.


    Setup Overview

    Before you start, make sure you are aware of the distributed training, see  following link for more info.

    In the distributed Caffe2 configuration described in this guide, we are using the following hardware specification.



    This document, does not cover the server’s storage aspect. You should configure the servers with the storage components appropriate to your use case (Data Set size)

    Setup Logical Design

    Server Logical Design



    Server Wiring

    In our reference we'll wire only 1st port to IB switch and will be not use the 2nd port.

    We'll cover the procedure late in Installing Mellanox OFED section.


    Server Block Diagram


    Docker Network Diagram

    Network Configuration

    Each server is connected to the SB7700 switch by a 100Gb IB copper cable. The switch port connectivity in our case is as follow:

    • 1st -8th ports – connected to Worker servers

    Server typeServer nameIP and NICS               
    Internal networkExternal network
    Node Server 01clx-mld-41ib0: From DHCP (reserved)
    Node Server 02clx-mld-42ib0: From DHCP (reserved)
    Node Server 03clx-mld-43ib0: From DHCP (reserved)
    Node Server 04clx-mld-44ib0: From DHCP (reserved)
    Node Server 05clx-mld-45ib0: From DHCP (reserved)
    Node Server 06clx-mld-46ib0: From DHCP (reserved)
    Node Server 07clx-mld-47ib0: From DHCP (reserved)
    Node Server 08clx-mld-48ib0: From DHCP (reserved)

    Server names with network configuration provided below

    Server type
    Deployment Guide


    Required a Host Software

    Prior to install Caffe2, the following software must be installed.


    Disable a Nouveau kernel Driver on a Host


    Prior to installing NVIDIA last drivers and CUDA in Ubuntu 16.04, the Nouveau kernel driver must be disabled. To disable it, follow the procedure below.


    1. Check that the Nouveau kernel driver is loaded.
      $ lsmod |grep nouv
    2. Remove all NVIDIA packages.

      Skip this step if your system is fresh installed.
      $ sudo apt-get remove nvidia* && sudo apt autoremove
    3. Install the packages below for the build kernel.

      $ sudo apt-get install dkms build-essential linux-headers-generic -y
    4. Block and disable the Nouveau kernel driver.
      $ sudo vim /etc/modprobe.d/blacklist.conf
    5. Insert the follow lines to the blacklist.conf file.
      blacklist nouveau
      blacklist lbm-nouveau
      options nouveau modeset=0
      alias nouveau off
      alias lbm-nouveau off
    6. Disable the Nouveau kernel module and update the initramfs image.  (Although the nouveau-kms.conf file may not exist, it will not affect this step).
      $ echo options nouveau modeset=0 | sudo tee -a /etc/modprobe.d/nouveau-kms.conf
      $ sudo update-initramfs -u
    7. Reboot
      $ sudo reboot
    8. Check that the Nouveau kernel drive is not loaded.
      $ lsmod |grep nouveau

    Update Ubuntu Software Packages

    To update/upgrade Ubuntu software packages, run the commands below.

    $ sudo apt-get update            # Fetches the list of available update
    $ sudo apt-get upgrade -y        # Strictly upgrades the current packages


    Install the NVIDIA Drivers


    The 390 (or later) NVIDIA drivers must be installed. To install them, you can use the Ubuntu built (when installing the additional drivers) after updating the driver packages.

    1. Go to the NVIDIA’s website (
    2. Download the latest version of the driver. The example below uses a Linux 64-bit driver (NVIDIA-Linux-x86_64-390.12_1).
    3. Exit the GUI (as the drivers for graphic devices are running at a low level).
      $ sudo service lightdm stop
    4. Set the RunLevel to 3 with the program init.
      $ sudo init 3
    5. Once you accept the download please follow the steps listed below.
      $ sudo dpkg -i nvidia-driver-local-repo-ubuntu1604-390.12_1.0-1_amd64.deb
      $ sudo apt-get update
      $ sudo apt-get install cuda-drivers
      During the run, you will be asked to confirm several things such as the pre-install of something failure, no 32-bit libraries and more.
    6. Once installed using additional drivers, restart your computer.
      $ sudo reboot


    Verify the Installation

    Make sure the NVIDIA driver can work correctly with the installed GPU card.

    $ lsmod |grep nvidia



    Run the nvidia-debugdump utility to collect internal GPU information.

    $ nvidia-debugdump -l

    Run the nvidia-smi utility to check the NVIDIA System Management Interface.

    $ nvidia-smi

    Enable the Subnet Manager(SM) on the IB Switch

    There are three options to select the best place to locate the SM:

    1. Enabling the SM on one of the managed switches. This is a very convenient and quick operation and make Infiniband ‘plug & play’ easily.
    2. Run /etc/init.d/opensmd on one or more servers. It is recommended to run the SM on a server in case there are 648 nodes or more.
    3. Use Unified Fabric Management (UFM®) Appliance dedicated server. UFM offers much more than the SM. UFM needs more compute power than the existing switches have, but does not require an expensive server. It does represent additional cost for the dedicated server.

    We'll explain options 1 and 2 only


    Option 1: Configuring the SM on a Switch MLNX-OS® all Mellanox switch systems.
    To enable the SM on one of the managed switches follow the next steps.

    1. Login to the switch and enter to config mode:
      Mellanox MLNX-OS Switch Management

      switch login: admin
      Last login: Wed Aug 12 23:39:01 on ttyS0

      Mellanox Switch

      switch [standalone: master] > enable
      switch [standalone: master] # conf t
      switch [standalone: master] (config)#
    2. Run the command:
      switch [standalone: master] (config)#ib sm
      switch [standalone: master] (config)#
    3. Check if the SM is running. Run:
      switch [standalone: master] (config)#show ib sm
      switch [standalone: master] (config)#

    To save the configuration (permanently), run:

    switch (config) # configuration write



    Option 2: Configuring the SM on a Server (Skip this procedure if you enable SM on switch)

    To start up OpenSM on a server, simply run opensm from the command line on your management node by typing:

    # opensm


    Start OpenSM automatically on the head node by editing the /etc/opensm/opensm.conf file.

    Create a configuration file by running:

    # opensm –config /etc/opensm/opensm.conf

    Edit /etc/opensm/opensm.conf file with the following line:


    Upon initial installation, OpenSM is configured and running with a default routing algorithm. When running a multi-tier fat-tree cluster, it is recommended to change the following options to create the most efficient routing algorithm delivering the highest performance:


    For full details on other configurable attributes of OpenSM, see the “OpenSM – Subnet Manager” chapter of the Mellanox OFED for Linux User Manual.


    Installation Mellanox OFED for Ubuntu

    This chapter describes how to install and test the Mellanox OFED for Linux package on a single host machine with Mellanox ConnectX®-5 adapter card installed. For more information click on Mellanox OFED for Linux User Manual.


    Downloading Mellanox OFED

    1. Verify that the system has a Mellanox network adapter (HCA/NIC) installed.
      # lspci -v | grep Mellanox
      The following example shows a system with an installed Mellanox HCA:
    2. Download the ISO image according to you OS to your host.
      The image’s name has the format
      MLNX_OFED_LINUX-<ver>-<OS label><CPUarch>.iso. You can download it from: > Products > Software > InfiniBand/VPI Drivers > Mellanox OFED Linux (MLNX_OFED) > Download.
    3. Use the MD5SUM utility to confirm the downloaded file’s integrity. Run the following command and compare the result to the value provided on the download page.
      # md5sum MLNX_OFED_LINUX-<ver>-<OS label>.tgz

    Installing Mellanox OFED

    MLNX_OFED is installed by running the mlnxofedinstall script. The installation script, performs the following:

    • Discovers the currently installed kernel
    • Uninstalls any software stacks that are part of the standard operating system distribution or another vendor's commercial stack
    • Installs the MLNX_OFED_LINUX binary RPMs (if they are available for the current kernel)
    • Identifies the currently installed InfiniBand and Ethernet network adapters and automatically upgrades the firmware

    The installation script removes all previously installed Mellanox OFED packages and re-installs from scratch. You will be prompted to acknowledge the deletion of the old packages.

    1. Log into the installation machine as root.
    2. Copy the downloaded tgz to /tmp
    3. Mount the ISO image on your machine.
      # cd /tmp# tar -xzvf MLNX_OFED_LINUX-4.2- cd MLNX_OFED_LINUX-4.2-
    4. Run the installation script.
      # ./mlnxofedinstall --all --force
    5. Restart openbd and
    6. Reboot after the installation finished successfully.
      # /etc/init.d/openibd restart# reboot
      By default both ConnectX®-5 VPI ports are initialized as Infiniband ports.
    7. Check the ports’ mode is Infiniband
      # ibv_devinfo

    8. If you see the following - You need to change the interfaces port type to Infiniband
      Change the interfaces port type to Infiniband mode ConnectX®-5 ports can be individually configured to work as Infiniband or Ethernet ports.
      Change the mode to Infiniband. Use the mlxconfig script after the driver is loaded.
      * LINK_TYPE_P1=1 is a Infiniband mode
      a. Start mst and see ports names
      # mst start
      # mst status
      b. Change the mode of both ports to Infiniband:
      # mlxconfig -d /dev/mst/mt4121_pciconf0 s LINK_TYPE_P1=1
         Port 1 set to IB mode

      c. Queries Infiniband devices and prints about them information that is available for use from userspace.
      # ibv_devinfo
    9. Run the ibdev2netdev utility to see all the associations between the Ethernet devices and the IB devices/ports.
      # ibdev2netdev
      # ifconfig ib0 netmask
    10. Insert to the /etc/network/interfaces file the lines below after the following lines:
      # vim /etc/network/interfacesauto eno1iface eno1 inet dhcp
      The new lines:
      auto ib0
      iface ib0 inet static
      # vim /etc/network/interfaces

      auto eno1
      iface eno1 inet dhcp

      auto ib0
      iface ib0 inet static
    11. Check the network configuration is set correctly.
      # ifconfig -a


    Docker installing and configured

    Uninstall old versions

    To uninstall old versions, we recommend run following command:

    $ sudo apt-get remove docker docker-engine

    It’s OK if apt-get reports that none of these packages are installed.

    The contents of /var/lib/docker/, including images, containers, volumes, and networks, are preserved.


    Install Docker CE

    For Ubuntu 16.04 and higher, the Linux kernel includes support for OverlayFS, and Docker CE will use the overlay2 storage driver by default.


    Install using the repository

    Before you install Docker CE for the first time on a new host machine, you need to set up the Docker repository. Afterward, you can install and update Docker from the repository.


    Set Up the repository

    1. Update the apt package index:
      $ sudo apt-get update
    2. Install packages to allow apt to use a repository over HTTPS:
      $ sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
    3. Add Docker’s official GPG key:
      $ sudo curl -fsSL | sudo apt-key add -

      Verify that the key fingerprint is 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88.
      $ sudo apt-key fingerprint 0EBFCD88
      pub   4096R/0EBFCD88 2017-02-22
      Key fingerprint = 9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
      uid                  Docker Release (CE deb) <>
      sub   4096R/F273FCD8 2017-02-22


    Install Docker CE

    Install the latest version of Docker CE, or go to the next step to install a specific version. Any existing installation of Docker is replaced.

    $ sudo add-apt-repository "deb [arch=amd64]  $(lsb_release -cs) stable"
    $ sudo apt-get update
    $ sudo apt-get install docker-ce


    Customize the docker0 bridge

    The recommended way to configure the Docker daemon is to use the daemon.json file, which is located in /etc/docker/ on Linux. If the file does not exist, create it. You can specify one or more of the following settings to configure the default bridge network

         "bip": "",
         "fixed-cidr": "",
         "mtu": 1500,
         "dns": ["",""]

    The same options are presented as flags to dockerd, with an explanation for each:

    • --bip=CIDR: supply a specific IP address and netmask for the docker0 bridge, using standard CIDR notation. For example:
    • --fixed-cidr=CIDR: restrict the IP range from the docker0 subnet, using standard CIDR notation. For example:
    • --mtu=BYTES: override the maximum packet length on docker0. For example: 1500.
    • --dns=[]: The DNS servers to use. For example: --dns=,


    Restart Docker after making changes to the daemon.json file.

    $ sudo /etc/init.d/docker restart


    Set communicating to the outside world

    Check ip forwarding is enabled in kernel:

    $ sysctl net.ipv4.conf.all.forwarding

    net.ipv4.conf.all.forwarding = 1

    If disabled

    net.ipv4.conf.all.forwarding = 0

    please enable and check again:

    $ sysctl net.ipv4.conf.all.forwarding=1


    For security reasons, Docker configures the iptables rules to prevent traffic forwarding to containers from outside the host machine. Docker sets the default policy of the FORWARD chain to DROP.

    To override this default behavior you can manually change the default policy:

    $ sudo iptables -P FORWARD ACCEPT


    Add IP route with specific subnet

    On each host you shall add routing to container subnet on other hosts. Please see example for routing to be added on one host-41:

    host-41$ sudo ip route add via
    host-41$ sudo ip route add via
    host-41$ sudo ip route add via

    A quick check on each host

    Give your environment a quick test by spawning simple container:

    $ docker run hello-world


    Create or pull a base image and run Container


    Docker can build images automatically by reading the instructions from a Dockerfile.

    A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.


    1. Create an empty directory.
    2. Enter the new directory, create a file called Dockerfile, copy-and-paste the following content into that file, and save it.
      Take note of the comments that explain each statement in your new Dockerfile.

    FROM nvidia/cuda:9.0-cudnn7-devel-ubuntu16.04

    LABEL maintainer="Boris KOvalev"


    # caffe2 install with gpu support


    #  Set MOFED directory, image and working directory








    WORKDIR /tmp/


    RUN apt-get update && apt-get install -y --no-install-recommends \

        iproute2 \

        lsb-release \

        redis-tools \

        libhiredis-dev \

        iputils-ping \

        net-tools \

        ethtool \

        perl \

        pciutils \

        libnl-route-3-200 \

        kmod \

        libnuma1 \

        lsof \

        linux-headers-4.4.0-92-generic \

        python-libxml2 \

        build-essential \

        cmake \

        git \

        libgflags-dev \

        libgoogle-glog-dev \

        libgtest-dev \

        libiomp-dev \

        libleveldb-dev \

        liblmdb-dev \

        libopencv-dev \

        libprotobuf-dev \

        libsnappy-dev \

        protobuf-compiler \

        python-dev \

        python-numpy \

        python-pip \

        python-pydot \

        python-setuptools \

        python-scipy \

        wget \

        && rm -rf /var/lib/apt/lists/*


    RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \

        pip install --no-cache-dir \

        flask \

        future \

        graphviz \

        hypothesis \

        jupyter \

        matplotlib \

        numpy \

        protobuf \

        pydot \

        python-nvd3 \

        pyyaml \

        requests \

        scikit-image \

        scipy \

        setuptools \

        six \




    ########## Mellanox OFED INSTALLATION STEPS ###################


        tar -xzvf ${MOFED_IMAGE} && \

        ${MOFED_DIR}/mlnxofedinstall --user-space-only --without-fw-update --all -q && \

        cd .. && \

        rm -rf ${MOFED_DIR} && \

        rm -rf *.tgz


    ########## CAFFE 2 INSTALLATION STEPS ###################


    RUN git clone --branch master --recursive

    RUN cd caffe2 && mkdir build && cd build \

        && cmake .. \

        -DCUDA_ARCH_NAME=Manual \

        -DCUDA_ARCH_BIN="60 61" \

        -DCUDA_ARCH_PTX="61" \

        -DUSE_NNPACK=OFF \


        -DUSE_GLOO=ON \

        -DUSE_REDIS=ON \

        -DUSE_IBVERBS=ON \

        -DUSE_MPI=OFF \

        && make -j"$(nproc)" install \

        && ldconfig \

        && make clean \

        && cd .. \

        && rm -rf build


    ENV PYTHONPATH /usr/local

    Build Docker Image and run the container

    1. Now run the build command. This creates a Docker image, which we’re going to tag using -t so it has a friendly name.
      $ nvidia-docker build -t caffe2mofed421 .
    2. Where is your built image? It’s in your machine’s local Docker image registry:
      $ nvidia-docker image
    3. Run a Docker Container in not privileged mode from the remote repository by:
      $ NV_GPU=0 nvidia-docker run --privileged -it -v /data:/data --network host --name=caffe2 caffe2mofed421 bash

    Verify CUDA in the container

    Ensure you are in the container. Run the nvidia-smi utility to check the NVIDIA System Management Interface.

    containerID$ nvidia-smi

    Validate Caffe2 in the container

    To validate the Caffe2 installation run the following commands:

    containerID$ python -m caffe2.python.operator_test.relu_op_test

    Validate MOFED

    Check the mofed version and uverbs:

    containerID$ ofed_info -s
    containerID$ ls /dev/infiniband/uverbs1

    Run Bandwidth stress over IB in container.:


    ib_write_bw -a -d mlx5_0 &


    ib_write_bw -a -F $server_IP -d mlx5_0 --report_gbits

    In this way you can run Bandwidth stress over IB between containers.


    Distributed Caffe2 run - sample

    To run distributed Caffe2, I use GLOO (is included in Caffe2) with Redis.

    I use a converted lmdb imagenet dataset in my runs. See an Appendix A to How to Create Imagenet ILSVRC2012 LMDB

    On each container please run the sample command:

    # python /caffe2/caffe2/python/examples/ --train_data /data/ilsvrc12_train_lmdb/ --test_data /data/ilsvrc12_val_lmdb --batch_size 32 --run_id 1 --epoch_size 10000 --num_epochs 2 --image_size 256 --num_gpus 1 --redis_host --redis_port 5555 --num_shards 32 --shard_id 0 --dtype float16 --float16_compute --distributed_transport ibverbs --distributed_interfaces mlx5_0

    # python /caffe2/caffe2/python/examples/ --train_data /data/ilsvrc12_train_lmdb/ --test_data /data/ilsvrc12_val_lmdb --batch_size 32 --run_id 1 --epoch_size 10000 --num_epochs 2 --image_size 256 --num_gpus 1 --redis_host --redis_port 5555 --num_shards 32 --shard_id 1 --dtype float16 --float16_compute --distributed_transport ibverbs --distributed_interfaces mlx5_0


    # python /caffe2/caffe2/python/examples/ --train_data /data/ilsvrc12_train_lmdb/ --test_data /data/ilsvrc12_val_lmdb --batch_size 32 --run_id 1 --epoch_size 10000 --num_epochs 2 --image_size 256 --num_gpus 1 --redis_host --redis_port 5555 --num_shards 32 --shard_id 31 --dtype float16 --float16_compute --distributed_transport ibverbs --distributed_interfaces mlx5_0




    Appendix A

    You need to have installed Caffe on bare metal or on Docker(preferred).



    How to Create Imagenet ILSVRC2012 LMDB · rioyokotalab/caffe Wiki · GitHub


    If you don't have, please download the Imagenet ILSVRC2012 dataset.




    # Development kit (Task 1 & 2), 2.5MB


    md5sum ILSVRC2012_devkit_t12.tar.gz


    # Development kit (Task 3), 22MB


    md5sum ILSVRC2012_devkit_t3.tar.gz


    # Training images (Task 1 & 2), 138GB


    md5sum ILSVRC2012_img_train.tar


    # Training images (Task 3), 728MB


    md5sum ILSVRC2012_img_train_t3.tar


    # Validation images (all tasks), 6.3GB


    md5sum ILSVRC2012_img_val.tar


    # Test images (all tasks), 13GB


    md5sum ILSVRC2012_img_test.tar

      md5sum is command to check correctness of download.


    Run Caffe container by:

    # nvidia-docker run --privileged -it -v /data:/data --network host --name=caffe caffe bash         # -v /data folder when you save your ILSVRC2012 dataset


    Use following script to unzip after unzip ILSVRC2012_img_train.tar and ILSVRC2012_img_val.tar



    for filepath in ${files}
      filename=`basename ${filepath} .tar`
      mkdir ${filename}
      tar -xf ${filename}.tar -C ${filename}


    After that , by using caffe script ,Let's create a lmdb

    1. get label data
      $ cd $CAFFE_HOME/data/ilsvrc12/
      $ ./
      det_synset_words.txt synsets.txt test.txt val.txt imagenet_mean.binaryproto synset_words.txt train.txt
    2. edit $CAFFE_HOME/examples/imagenet/

      #!/usr/bin/env sh

      # Create the imagenet lmdb inputs

      # N.B. set the path to the imagenet train + val data dirs

      set -e






      # Set RESIZE=true to resize the images to 256x256. Leave as false if images have

      # already been resized using another tool.


      if $RESIZE; then



    3. then , execute ./
    4. edit $CAFFE_HOME/examples/imagenet/

      #!/usr/bin/env sh
      # Compute the mean image from the imagenet training lmdb
      # N.B. this is available in data/ilsvrc12


      $TOOLS/compute_image_mean $EXAMPLE/ilsvrc12_train_lmdb \ 

      echo "Done."

    5. And execute ./