Troubleshooting Parallel Training and Validation on the Same GPU with Multiple Threads

Aru: <p>Hello, PyTorch community! I would like to inquire about a thread parallelism issue regarding parallel training and validation on the same GPU using two threads.</p>
<p>Here is the basic scenario I am facing: I am training a model in the main thread and saving it after each training epoch. Then, I start a new thread which loads the recently saved model with its weights, and performs validation steps on the same GPU where the model is trained. I hope that since training and validation are on two different threads and they use different CUDA streams, they should be able to execute in parallel, thus reducing the overall training time.</p>
<p>However, the results don’t seem to reflect this. Through PyTorch’s built-in profiler tool, I have found that when both the training and validation threads exist, there still seems to be some sort of “serial ordering” between operations in different CUDA streams. To illustrate this more clearly, here is the profiler result, in different period:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/f/9/f920293fcbada346cd7b2b621e8497371acb5fc4.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/f920293fcbada346cd7b2b621e8497371acb5fc4" title="Profiler"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/f/9/f920293fcbada346cd7b2b621e8497371acb5fc4_2_517x282.jpeg" alt="Profiler" data-base62-sha1="zxRNi9l9gBWhP26Qk77AcQMBhOc" width="517" height="282" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/f/9/f920293fcbada346cd7b2b621e8497371acb5fc4_2_517x282.jpeg, https://discuss.pytorch.org/uploads/default/optimized/3X/f/9/f920293fcbada346cd7b2b621e8497371acb5fc4_2_775x423.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/f/9/f920293fcbada346cd7b2b621e8497371acb5fc4_2_1034x564.jpeg 2x" data-dominant-color="E4E6E8"><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">Profiler</span><span class="informations">1920×1051 170 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>[1]: when only the main thread is training the model<br>
[2]: when two threads are simultaneously training and validating on one GPU<br>
[3]: when the main thread finished model training and only the thread for validation remains</p>
<p>As you can see, the “gaps” between operators within the same CUDA stream in [2] are significantly larger, thus the actual execution time in parallel threads way is almost the same with sequentially execution way.<br>
If we zoom in further on the second image, like [4], it appears that the operations on the two CUDA streams are not executing asynchronously with each other.</p>
<p>I have confirmed that my GPU memory is sufficient to conduct both model training and validation simultaneously (on NVIDIA 3090 and A800, same results). Have I misunderstood something? Is this indeed a feasible method for reducing training time? Thank you in advance！</p>
<p>Here is a summary of my code:</p>
<pre data-code-wrap="python"><code class="lang-python">self.thread_pool = ThreadPoolExecutor(max_workers=1)

# Main loop
for _ in range(self.max_epoch):
    self._train(train_dataloader)
    self._save_model(copy.deepcopy(self.epoch))
    self.thread_pool.submit(
        self._valid, valid_dataloader, copy.deepcopy(self.epoch)
    )
    self.epoch += 1


def _train(train_dataloader):
    self.model.train()

    stream = torch.cuda.Stream()
    with torch.cuda.stream(stream):
        for idx, (X, y) in enumerate(train_dataloader):
            self.optimizer.zero_grad()
            X = X.to(self.get_device(), non_blocking=True)
            y = y.to(self.get_device(), non_blocking=True)

            with autocast():
                pred = self.model(X)
                loss = self.loss_fn(pred, y)
            self.scaler.scale(loss).backward()
            self.scaler.step(self.optimizer)
            self.scaler.update()
            self.scheduler.step()


@torch.no_grad()
def _valid(valid_dataloader, epoch):
    model = self._load_model(epoch)  # Load recently saved model in this separate thread
    model.eval()

    stream = torch.cuda.Stream()
    with torch.cuda.stream(stream):
        for idx, (X, y) in enumerate(valid_dataloader):
            X = X.to(self.get_device(), non_blocking=True)
            y = y.to(self.get_device(), non_blocking=True)
            with autocast():
                pred = model(X)
                loss = self.loss_fn(pred, y)
</code></pre>
<p>Env: PyTorch 2.2.2+cu118</p>

ptrblck: <p>If you are using Python’s multi-threading you should be aware of the GIL and its limitations.<br>
Besides that your device would not only need to provide enough memory but also compute resources. Details including a great GTC talk can be found <a href="https://discuss.pytorch.org/t/running-independent-nn-module-instances-in-nn-modulelist-truly-in-parallel-in-pytorch/188166/3">here</a>.</p>