Multiprocessing best practices
Note
When a Tensor is sent to another process, the
Tensor data is shared. If torch.Tensor.grad is
not None, it is also shared. After a Tensor without
a torch.Tensor.grad field is sent to the other process, it
creates a standard process-specific .grad Tensor that
is not automatically shared across all processes, unlike how the
Tensor’s data has been shared.
This allows implementation of various training methods, like Hogwild, A3C, or any
others that require asynchronous operation.
Warning
You should be careful about having global statements, that are not guarded
with an if __name__ == '__main__'. If a different start method than
fork is used, they will be executed in all subprocesses.
model
,
device
,
dataset
,
dataloader_kwargs
):
torch
.
manual_seed
(
args
.
seed
+
rank
)
torch
.
set_num_threads
(
floor
(
N
/
M
))
train_loader
=
torch
.
utils
.
data
.
DataLoader
(
dataset
,
**
dataloader_kwargs
)
optimizer
=
optim
.
SGD
(
model
.
parameters
(),
lr
=
args
.
lr
,
momentum
=
args
.
momentum
)
for
epoch
in
range
(
1
,
args
.
epochs
+
1
):
train_epoch
(
epoch
,
args
,
model
,
device
,
train_loader
,
optimizer
)
Set num_thread for each process using
torch.set_num_threads(floor(N/M)), where you replace N with the
number of vCPUs available and M with the chosen number of processes. The
appropriate num_thread value will vary depending on the specific
task at hand. However, as a general guideline, the maximum value for the
num_thread should be floor(N/M) to avoid CPU oversubscription.
In the mnist_hogwild training example, after avoiding CPU over
subscription, you can achieve a 30x performance boost.