Too much time spent in `ncclKernel AllReduce`?

Francois: <p>Hello,</p>
<p>I’m learning how to train a model using DDP <code>torch.nn.parallel.DistributedDataParallel</code>. I run my experiments in cluster with three GPU nodes, each node has one GPU (Nvidia T4). I’m (kind of) aware that my setup isn’t ideal. I’m not yet trying to get the last drop of FLOPS from my cluster, I’m simply stuck trying to get marginal improvement on train time when distributed across the three workers.</p>
<p>It looks like <strong>I’m missing something obvious</strong> can you help me find what ? More precisely I’m trying to figure out:</p>
<ul>
<li>Why my wall training time is only 40% faster when I distribute the training on three nodes ?</li>
<li>When distributing the training, is it expected that half of GPU time is spent on <code>ncclKernel_AllReduce_RING_LL_Sum_float</code> ?</li>
</ul>
<p>Below are more details on what I do, I know that’s a lot of reading and I don’t expect much… I’ll gladly take any advice one can offer <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=10" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>
<p>Thanks a lot !</p>
<hr>
<h2>
<a name="hardware-1" class="anchor" href="#hardware-1"></a>Hardware</h2>
<p>I use a kubernetes cluster with:</p>
<ul>
<li>Kubeflow CRDs (PyTorchJob, …)</li>
<li>7 Nodes, 3 nodes have one Telsa T4</li>
<li>A descent network connection between the nodes</li>
</ul>
<h2>
<a name="software-2" class="anchor" href="#software-2"></a>Software</h2>
<ul>
<li>I use pytorch 1.10.0</li>
<li>I use CUDA</li>
<li>I use NCCL backend</li>
<li>I train for 20 epochs</li>
<li>I use a 1024 batch-size</li>
<li>I train the model straight from the example in PyTorchJob’s git repository (see below)</li>
</ul>
<h2>
<a name="results-3" class="anchor" href="#results-3"></a>Results</h2>
<ul>
<li>Single node training (no distribution of any kind) :
<ul>
<li>Test accuracy at epoch 20 is 0.8386</li>
<li>WALL training time is 63.598 seconds</li>
</ul>
</li>
<li>Training with 3 nodes :
<ul>
<li>Test accuracy at epoch 20 is 0.7622</li>
<li>WALL training time is 38.594 seconds (measured on master)</li>
</ul>
</li>
</ul>
<h2>
<a name="profiling-4" class="anchor" href="#profiling-4"></a>Profiling</h2>
<p>I do profile using <code>torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1)</code> a step is an epoch.</p>
<h3>
<a name="using-three-gpus-5" class="anchor" href="#using-three-gpus-5"></a>Using three GPUs</h3>
<p>                    <a href="https://gist.githubusercontent.com/Fkawala/7f3baa0961c78fa9fd2ee7ce0a0f0eee/raw/1b1299749eced0f4809a317e924c86bbd7449b9f/3-nodes.merge.png" target="_blank" rel="noopener nofollow ugc" class="onebox">
            <img src="https://gist.githubusercontent.com/Fkawala/7f3baa0961c78fa9fd2ee7ce0a0f0eee/raw/1b1299749eced0f4809a317e924c86bbd7449b9f/3-nodes.merge.png" width="574" height="500">
          </a>

</p>
<h3>
<a name="for-one-single-gpu-6" class="anchor" href="#for-one-single-gpu-6"></a>For one single GPU</h3>
<p>                    <a href="https://gist.githubusercontent.com/Fkawala/7f3baa0961c78fa9fd2ee7ce0a0f0eee/raw/1b1299749eced0f4809a317e924c86bbd7449b9f/1-node.merge.png" target="_blank" rel="noopener nofollow ugc" class="onebox">
            <img src="https://gist.githubusercontent.com/Fkawala/7f3baa0961c78fa9fd2ee7ce0a0f0eee/raw/1b1299749eced0f4809a317e924c86bbd7449b9f/1-node.merge.png" width="672" height="500">
          </a>

</p>
<h2>
<a name="code-7" class="anchor" href="#code-7"></a>Code</h2>
<h3>
<a name="model-8" class="anchor" href="#model-8"></a>Model</h3>
<p>The Model has 431 080 trainable parameters :</p>
<pre><code class="lang-python">class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5, 1)
        self.conv2 = nn.Conv2d(20, 50, 5, 1)
        self.fc1 = nn.Linear(4 * 4 * 50, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 4 * 4 * 50)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)
</code></pre>
<h3>
<a name="complete-training-code-9" class="anchor" href="#complete-training-code-9"></a>Complete training code</h3>
<p>Complete training code (most of it comes from the pytorch operator example):</p>
<pre><code class="lang-python">import argparse
import logging
import os
import sys
import time
from typing import List, Any

import numpy as np
from torchvision import datasets, transforms

import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

WORLD_SIZE = int(os.environ.get('WORLD_SIZE', 0))
RANK = int(os.environ.get('RANK', 0))
EXPE_ID = os.environ.get('EXPE_ID', "no-expe-id")
POD_NAME = os.environ.get("K8S_POD_ID", "unknown pod name")


class MockProfiler(object):

    def __enter__(self):
        logging.debug(f"Entering {self}")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        logging.debug(f"Exiting {self}")

    def step(self):
        pass


class WallTime(object):

    def __init__(self, name):
        self.wall = 0
        self.name = name

    def __repr__(self):
        return f"WallTime({self.name}) @ {time.time()}"

    def __enter__(self):
        logging.debug(f"Entering {self}")
        self.wall = time.time_ns()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.wall -= time.time_ns()
        logging.debug(f"Exiting {self} after {abs(self.wall) / 1e9:.3f} WALL seconds")


class FashionMNISTInRam(datasets.FashionMNIST):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.buffer: List[Any] = [None] * len(self)

    def prefetch(self):
        for _ in range(len(self)):
            _ = self[_]
        return self

    def __getitem__(self, index: int):
        if self.buffer[index] is None:
            self.buffer[index] = super().__getitem__(index)
        return self.buffer[index]


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5, 1)
        self.conv2 = nn.Conv2d(20, 50, 5, 1)
        self.fc1 = nn.Linear(4 * 4 * 50, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 4 * 4 * 50)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)


def should_distribute():
    return dist.is_available() and WORLD_SIZE &gt; 1


def is_distributed():
    return dist.is_available() and dist.is_initialized()


def setup_logging():
    stderr_handler = logging.StreamHandler(stream=sys.stdout)
    formatter = logging.Formatter('[%(asctime)s on {}] %(message)s'.format(POD_NAME))
    stderr_handler.setLevel(logging.DEBUG)
    stderr_handler.setFormatter(formatter)
    logging.root.setLevel(logging.DEBUG)
    logging.root.addHandler(stderr_handler)


def setup_cli():
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')

    parser.add_argument('--batch-size', type=int, default=64, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                        help='input batch size for testing (default: 1000)')
    parser.add_argument('--epochs', type=int, default=1, metavar='N',
                        help='number of epochs to train (default: 10)')
    parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
                        help='learning rate (default: 0.01)')
    parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
                        help='SGD momentum (default: 0.5)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                        help='how many batches to wait before logging training status')
    parser.add_argument('--save-model', action='store_true', default=False,
                        help='For Saving the current Model')
    parser.add_argument('--dir', default='logs', metavar='L',
                        help='directory where summary logs are stored')
    if dist.is_available():
        parser.add_argument('--backend', type=str, help='Distributed backend',
                            choices=[dist.Backend.GLOO, dist.Backend.NCCL, dist.Backend.MPI],
                            default=dist.Backend.GLOO)
    return parser.parse_args()


def train(args, model, device, train_loader, optimizer, epoch):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % args.log_interval == 0:
            logging.info('Train Epoch: {} [{}/{} ({:.0f}%)]\tloss={:.4f}'.format(
                epoch, batch_idx * len(data), len(train_loader) * len(data),
                       100. * batch_idx / len(train_loader), loss.item()))


def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.max(1, keepdim=True)[1]  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    logging.info('accuracy={:.4f}'.format(float(correct) / len(test_loader.dataset)))


def main():
    args = setup_cli()
    torch.manual_seed(args.seed)
    use_cuda = not args.no_cuda and torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")
    is_master = RANK == 0

    if should_distribute():
        logging.info('Using distributed PyTorch with {} backend'.format(args.backend))
        dist.init_process_group(backend=args.backend)

    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
    with WallTime("data load"):
        train_set = FashionMNISTInRam('../data', train=True, download=True, transform=transform).prefetch()
        test_set = FashionMNISTInRam('../data', train=False, transform=transform).prefetch()
        kwargs = \
            {"sampler": torch.utils.data.distributed.DistributedSampler(
                train_set,
                num_replicas=WORLD_SIZE,
                rank=RANK,
                shuffle=True)} if is_distributed() else {"shuffle": True}

    test_loader = torch.utils.data.DataLoader(
        test_set,
        batch_size=args.test_batch_size,
        shuffle=False,
        num_workers=1,
        pin_memory=True)

    train_loader = torch.utils.data.DataLoader(
        train_set,
        batch_size=args.batch_size,
        num_workers=1,
        pin_memory=True,
        **kwargs)

    model = Net().to(device)

    if is_distributed():
        if not use_cuda:
            raise RuntimeError("Not using cuda")
        model = nn.parallel.DistributedDataParallel(
            model,
            broadcast_buffers=True,
            process_group=None,
            bucket_cap_mb=25,
            find_unused_parameters=False,
            check_reduction=False)

    optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
    profiler = MockProfiler()

    if is_master:
        trace_handler = torch.profiler.tensorboard_trace_handler(os.path.join(args.dir))
        profiler = torch.profiler.profile(
            schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1),
            activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ],
            on_trace_ready=trace_handler)

    model_parameters = filter(lambda p: p.requires_grad, model.parameters())
    params = sum([np.prod(p.size()) for p in model_parameters])
    logging.info(f"The model has {params} trainable parameters")

    with WallTime("training"):
        with profiler as p:
            for epoch in range(1, args.epochs + 1):
                if is_distributed():
                    train_loader.sampler.set_epoch(epoch)
                train(args, model, device, train_loader, optimizer, epoch)
                if is_master:
                    logging.info("Testing")
                    test(model, device, test_loader)
                p.step()


if __name__ == '__main__':
    setup_logging()
    logging.info(os.environ)
    with WallTime("main"):
        main()
</code></pre>
<h3>
<a name="kubeflow-crd-10" class="anchor" href="#kubeflow-crd-10"></a>Kubeflow CRD</h3>
<p>I run this POC using the dedicated CRD, which looks like:</p>
<pre><code class="lang-auto">apiVersion: "kubeflow.org/v1"
kind: "PyTorchJob"
metadata:
  name: "classif-minst-nccl"
spec:
  pytorchReplicaSpecs:
    Master:
      replicas: 1
      restartPolicy: OnFailure
      template:
        metadata:
          annotations:
            sidecar.istio.io/inject: "false"
        spec:
          containers:
            - name: pytorch
              imagePullPolicy: IfNotPresent
              image: debug-dist-pytroch-minst:$VERSION
              args: ["--backend", "nccl", "--dir", "/tmp/tb/nccl-$VERSION", "--epochs", "20", "--batch-size", "1024"]
              resources:
                limits:
                  nvidia.com/gpu: 1
    Worker:
      # The "replicas" value is 2 when doing distributed training 
      replicas: 0
      restartPolicy: OnFailure
      template:
        metadata:
          annotations:
            sidecar.istio.io/inject: "false"
        spec:
          containers:
            - name: pytorch
              image: debug-dist-pytroch-minst:$VERSION
              args: ["--backend", "nccl", "--dir", "/tmp/tb/nccl-$VERSION", "--epochs", "20", "--batch-size", "1024"]
              resources:
                limits:
                  nvidia.com/gpu: 1
</code></pre>
<h3>
<a name="docker-11" class="anchor" href="#docker-11"></a>Docker</h3>
<p>The docker image is simply:</p>
<pre><code class="lang-auto">FROM pytorch/pytorch:1.10.0-cuda11.3-cudnn8-runtime

RUN pip install tensorboardX==1.6.0
RUN mkdir -p /opt/mnist

WORKDIR /opt/mnist/src
ADD mnist.py /opt/mnist/src/mnist.py

RUN  chgrp -R 0 /opt/mnist \
  &amp;&amp; chmod -R g+rwX /opt/mnist

ENTRYPOINT ["python", "/opt/mnist/src/mnist.py"]
</code></pre>
<p><em>Thank a lot for reading until the end <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=10" title=":slight_smile:" class="emoji" alt=":slight_smile:"></em></p>

ptrblck: <ol>
<li>
<p>The achieved speedup would depend on your overall setup. You could profile the workload with Nsight Systems to see how long each call takes and where the bottleneck might be.</p>
</li>
<li>
<p>The fastest runner would have to wait for the others. Again, Nsight Systems might be useful here as it should show that other runners might still be executing code while one has to wait.</p>
</li>
</ol>

Yanli_Zhao: <p>long all reduce time could be due to 1) low network bandwidth 2) data loading or computation caused desync btw ranks, as <a class="mention" href="/u/ptrblck">@ptrblck</a>  mentioned fastest runner will wait for the others. Try to use simulated data and benchmark the performance.</p>
<p>One good way to profile is to use torch profiler and dump the trace to Chrome for viewing the event timelines</p>

Francois: <p>Hello <a class="mention" href="/u/ptrblck">@ptrblck</a> &amp; <a class="mention" href="/u/yanli_zhao">@Yanli_Zhao</a>, first thing first, thank you for messages, it helps !</p>
<h3><a name="heres-what-i-changed-1" class="anchor" href="#heres-what-i-changed-1"></a>Here’s what I changed :</h3>
<ul>
<li>
<p><code>dist.init_process_group(backend=args.backend)</code> is done once the data-set is fully loaded. The objective is to get ride of potential sources of desynchronization.</p>
</li>
<li>
<p>I added a simple model (29 330 trainable parameters, 14x smaller than the original model). My goal is to reduce the communication overhead in distributed training.</p>
</li>
<li>
<p>I removed the call to the <code>test</code> function from the master’s training loop.</p>
</li>
</ul>
<h3><a name="heres-what-i-observe-2" class="anchor" href="#heres-what-i-observe-2"></a>Here’s what I observe  :</h3>
<ul>
<li>
<p>Training times</p>
<ul>
<li>To train the simple model with 1 GPU takes 47.328 WALL seconds</li>
<li>To train simple model with 3 GPUs takes 23.765 WALL seconds</li>
<li>To train the original model with 3 GPUs takes 26.433  WALL seconds</li>
<li>Training time is divided by two when I triple the GPU capacity. This looks like slightly better but still a bit unsatisfying.)</li>
</ul>
</li>
<li>
<p>60% of the time is spent synchronizing (regardless of the model version: simple or original).</p>
<ul>
<li>When training the simple model most of the time is spent synchronizing</li>
<li>When training the original model most of the time is spent in data transfert.</li>
<li>Based on the above, I guess that my original observation about time being spent in <code>ncclKernel_AllReduce</code> was wrong.</li>
</ul>
</li>
<li>
<p>When training the simple model, the master is not spending time synchronizing. Would that indicates it is the slower node that others wait after ? or is that expected ? If this is expected, could the synchronizing time on node 1 and 2 be simply them waiting for the master doing the sum of all the weights ?</p>
</li>
</ul>
<h3><a name="more-details-3" class="anchor" href="#more-details-3"></a>More details</h3>
<p>For some reason until that point I did not noticed the “Distributed” view in the tensorboard “pytorch profiler” tool, it is quite insightful.</p>
<h3><a name="simpler-model-4" class="anchor" href="#simpler-model-4"></a>Simpler model</h3>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/6/3/63cf218f79a95f24473c2585a01bd44a47aa531e.png" data-download-href="https://discuss.pytorch.org/uploads/default/63cf218f79a95f24473c2585a01bd44a47aa531e" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/6/3/63cf218f79a95f24473c2585a01bd44a47aa531e_2_690x261.png" alt="image" data-base62-sha1="eeX2QretfSuP1PGpsUJBm4G8M22" width="690" height="261" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/6/3/63cf218f79a95f24473c2585a01bd44a47aa531e_2_690x261.png, https://discuss.pytorch.org/uploads/default/optimized/3X/6/3/63cf218f79a95f24473c2585a01bd44a47aa531e_2_1035x391.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/6/3/63cf218f79a95f24473c2585a01bd44a47aa531e_2_1380x522.png 2x" data-dominant-color="F0EEE9"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">3370×1276 151 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<h3><a name="original-model-5" class="anchor" href="#original-model-5"></a>Original model</h3>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/2/1/21a591424f35acaed444901eb8c1480f039cc807.png" data-download-href="https://discuss.pytorch.org/uploads/default/21a591424f35acaed444901eb8c1480f039cc807" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/2/1/21a591424f35acaed444901eb8c1480f039cc807_2_690x263.png" alt="image" data-base62-sha1="4NEtWXY87R40OoU9evVfSKhfHDh" width="690" height="263" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/2/1/21a591424f35acaed444901eb8c1480f039cc807_2_690x263.png, https://discuss.pytorch.org/uploads/default/optimized/3X/2/1/21a591424f35acaed444901eb8c1480f039cc807_2_1035x394.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/2/1/21a591424f35acaed444901eb8c1480f039cc807_2_1380x526.png 2x" data-dominant-color="E9EDEC"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">3359×1281 154 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<h3><a name="profiler-simple-model-6" class="anchor" href="#profiler-simple-model-6"></a>Profiler (simple model)</h3>
<p>As <a class="mention" href="/u/yanli_zhao">@Yanli_Zhao</a> suggested I loaded the profile in chrome but I’m not quite sure what I’m searching for. The dependencies of the <code>ncclKernel_AllReduce_RING_LL_Sum_float(ncclWorkElem)</code> do not look problematic to me (but I have no reference point of a working cluster to compare with). Below is a capture of chromium profiler.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/7/b/7bd6f405382d34f15aad101bcaa6be281b597a53.png" data-download-href="https://discuss.pytorch.org/uploads/default/7bd6f405382d34f15aad101bcaa6be281b597a53" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/7/b/7bd6f405382d34f15aad101bcaa6be281b597a53_2_690x288.png" alt="image" data-base62-sha1="hFxgmKlTNiR9dYjUJiF99EoG3T5" width="690" height="288" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/7/b/7bd6f405382d34f15aad101bcaa6be281b597a53_2_690x288.png, https://discuss.pytorch.org/uploads/default/optimized/3X/7/b/7bd6f405382d34f15aad101bcaa6be281b597a53_2_1035x432.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/7/b/7bd6f405382d34f15aad101bcaa6be281b597a53_2_1380x576.png 2x" data-dominant-color="EAEBEB"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">3770×1575 306 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<h3><a name="next-steps-7" class="anchor" href="#next-steps-7"></a>Next steps ?</h3>
<ul>
<li>Setup and use the Nsight Systems to get a grasp on what’s going on ?</li>
<li>Anything else ?</li>
</ul>
<hr>
<p>The simple model definition is below.</p>
<pre data-code-wrap="python"><code class="lang-python">class SimpleNet(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5, 1)
        self.fc = nn.Linear(20*12*12, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 20*12*12)
        x = self.fc(x)
        return F.log_softmax(x, dim=1)
</code></pre>
<hr>
<p><em>ps. I ran few tests using simulated data, it does not indicate that my test throttles on data I/O (which is  expected since I force load the dataset in ram beforehand).</em></p>

Yanli_Zhao: <p>as you mentioned and your profiling showed, for simpler model, other nodes are waiting for master, that is why synchronization time is long, maybe find out why they are waiting for master. for original model, also improve data transfer…?</p>

Francois: <p><a class="mention" href="/u/yanli_zhao">@Yanli_Zhao</a> thank you for helping me out !</p>
<p>As suggested by <a class="mention" href="/u/ptrblck">@ptrblck</a> I switched profiler and now use “nvidia nsight” profiler.</p>
<h2><a name="original-model-high-latency-in-data-transfert-but-low-in-synchronization-1" class="anchor" href="#original-model-high-latency-in-data-transfert-but-low-in-synchronization-1"></a>Original model (high latency in data transfert but low in synchronization)</h2>
<p>As expected there is not so much variance from one epoch to another. Each epoch describes a clear pattern and each epoch pattern has a “batch” sub-partern. The fact that those are low variance makes me think that the problem is not transient (<em>eg</em>. network throttling, …).</p>
<h3><a name="master-2" class="anchor" href="#master-2"></a>Master</h3>
<p>About a third (≈310ms per epoch) is spent in <code>cudaMemcpyAsync </code>. Each epoch starts with a suspiciously  longer call (≈110ms) to <code>cudaMemcpyAsync </code>. The picture below is a zoom on one epoch.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/c/9/c9238fdd9f97b835d080b9ffbb7abe6615468a7e.png" data-download-href="https://discuss.pytorch.org/uploads/default/c9238fdd9f97b835d080b9ffbb7abe6615468a7e" title="master"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/c/9/c9238fdd9f97b835d080b9ffbb7abe6615468a7e_2_690x288.png" alt="master" data-base62-sha1="sHma5zNRgvxJYz1rXT9uY4kPwbI" width="690" height="288" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/c/9/c9238fdd9f97b835d080b9ffbb7abe6615468a7e_2_690x288.png, https://discuss.pytorch.org/uploads/default/optimized/3X/c/9/c9238fdd9f97b835d080b9ffbb7abe6615468a7e_2_1035x432.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/c/9/c9238fdd9f97b835d080b9ffbb7abe6615468a7e_2_1380x576.png 2x" data-dominant-color="E6E7E7"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">master</span><span class="informations">3770×1575 423 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<h3><a name="worker-1-3" class="anchor" href="#worker-1-3"></a>Worker 1</h3>
<p>Could worker synchronization time be spent waiting for that first long call to <code>cudaMemcpyAsync </code> on master to be finished ?<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/d/4/d4c0639bb8147347dbb663edd67754d0188b83a2.png" data-download-href="https://discuss.pytorch.org/uploads/default/d4c0639bb8147347dbb663edd67754d0188b83a2" title="worker-0"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/d/4/d4c0639bb8147347dbb663edd67754d0188b83a2_2_690x288.png" alt="worker-0" data-base62-sha1="um5pL46s9gY90M57A7yKLt0rM6C" width="690" height="288" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/d/4/d4c0639bb8147347dbb663edd67754d0188b83a2_2_690x288.png, https://discuss.pytorch.org/uploads/default/optimized/3X/d/4/d4c0639bb8147347dbb663edd67754d0188b83a2_2_1035x432.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/d/4/d4c0639bb8147347dbb663edd67754d0188b83a2_2_1380x576.png 2x" data-dominant-color="E8E9E9"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">worker-0</span><span class="informations">3770×1575 255 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<h3><a name="no-distribution-4" class="anchor" href="#no-distribution-4"></a>No distribution</h3>
<p>For the reference, the suspiciously  longer call (≈110ms) to <code>cudaMemcpyAsync </code> does not occur when there is no distribution.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/5/2/52d1418ae87979662db8a7cb8f5c11a480d114fd.png" data-download-href="https://discuss.pytorch.org/uploads/default/52d1418ae87979662db8a7cb8f5c11a480d114fd" title="no-dist"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/5/2/52d1418ae87979662db8a7cb8f5c11a480d114fd_2_690x288.png" alt="no-dist" data-base62-sha1="bODtR3wSzKmuZyd53wjiB9lX8Gp" width="690" height="288" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/5/2/52d1418ae87979662db8a7cb8f5c11a480d114fd_2_690x288.png, https://discuss.pytorch.org/uploads/default/optimized/3X/5/2/52d1418ae87979662db8a7cb8f5c11a480d114fd_2_1035x432.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/5/2/52d1418ae87979662db8a7cb8f5c11a480d114fd_2_1380x576.png 2x" data-dominant-color="E9EAE9"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">no-dist</span><span class="informations">3770×1575 564 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Could that suspiciously long calls to <code>cudaMemcpyAsync</code> have something to do with hardware issue ?</p>

Francois: <p>Hello, my batch size is 1024, could my problem boil down to that batch size being too small ?</p>

lhama: <p>Hey <a class="mention" href="/u/francois">@Francois</a>, did you figure out the bottleneck? I am seeing similar profiler results.</p>