mrshenli Sorry for the late reply. Say I want to train the DDP model on 4 gpus and restore it as DDP  on 2. I created an mnist example to illustrate my case while following your example. This whole script is borrowed from mnist, modified and split into three scripts:

mnist_common.py

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import argparse
from torchvision import datasets, transforms
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import DataLoader


def cleanup():
    dist.destroy_process_group()


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout2d(0.25)
        self.dropout2 = nn.Dropout2d(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output


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, non_blocking=True), \
                       target.to(device, non_blocking=True)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()


def test(args, 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, non_blocking=True), \
                           target.to(device, non_blocking=True)
            output = model(data)
            test_loss += F.nll_loss(
                output,
                target,
                reduction='sum').item()
            pred = output.argmax(dim=1, keepdim=True)
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    if args.local_rank == 0:
        print('Test set: Average loss: {:.4f},'
              ' Accuracy: {}/{} ({:.2f}%)'.format(
            test_loss, correct, len(test_loader.dataset),
            100. * correct / len(test_loader.dataset)))


# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size',
                    type=int,
                    default=64,
                    metavar='N',
                    help='input batch size for training')
parser.add_argument('--test-batch-size',
                    type=int,
                    default=1000,
                    metavar='N',
                    help='input batch size for testing')
parser.add_argument('--epochs', type=int, default=14, metavar='N',
                    help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
                    help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
                    help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--seed', type=int, default=1, metavar='S',
                    help='random seed (default: 1)')
parser.add_argument('--local_rank', type=int)
args = parser.parse_args()

train_dataset = datasets.MNIST(
    '../data',
    train=True,
    download=False,
    transform=transforms.Compose([
       transforms.ToTensor(),
       transforms.Normalize((0.1307,), (0.3081,))
    ]))
train_sampler = DistributedSampler(
    train_dataset,
    num_replicas=torch.cuda.device_count(),
    rank=args.local_rank)
train_loader = DataLoader(train_dataset,
                          batch_size=args.batch_size,
                          shuffle=(train_sampler is None),
                          num_workers=0,
                          pin_memory=True,
                          sampler=train_sampler)
test_loader = DataLoader(
    datasets.MNIST(
        '../data',
        train=False,
        transform=transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.1307,), (0.3081,))
        ])),
    batch_size=args.test_batch_size,
    shuffle=True,
    num_workers=0,
    pin_memory=True,)


mnist_train.py

from __future__ import print_function
import torch
import torch.optim as optim
import torch.distributed as dist
import torch.backends.cudnn as cudnn
from torch.optim.lr_scheduler import StepLR
from torch.nn.parallel import DistributedDataParallel as DDP
from mnist_common import args, Net, train_loader, train_sampler,\
    test_loader, train, test, cleanup


def main(args):
    dist.init_process_group(backend='nccl',
                            init_method='tcp://localhost:23456',
                            rank=args.local_rank,
                            world_size=torch.cuda.device_count())
    torch.manual_seed(args.seed)
    torch.cuda.set_device(args.local_rank)
    cudnn.benchmark = True

    model = Net()
    model = model.to([args.local_rank][0])  # distribute the model
    # Should we set the output_device value in DPP?
    model = DDP(model, device_ids=[args.local_rank])
    # , output_device=[args.local_rank][0])

    optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
    scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
    for epoch in range(1, args.epochs + 1):
        train_sampler.set_epoch(epoch)
        train(args, model, args.local_rank,
              train_loader, optimizer, epoch)
        test(args, model, args.local_rank, test_loader)
        scheduler.step(epoch)

    # I intend to save the model
    # AFTER some training not, not before
    if args.local_rank == 0:
        torch.save(model, "mnist_cnn.pt")
    dist.barrier()
    cleanup()


if __name__ == '__main__':
    main(args)

Also I intend to test the model, only after training (sometimes up to a few days) has finished, by restoring the saved weights (or model).
2) mnist_test.py
from __future__ import print_function
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from mnist_common import args, Net, test_loader, test, cleanup


def main(args):
    dist.init_process_group(backend='nccl',
                            init_method='tcp://localhost:23456',
                            rank=args.local_rank,
                            world_size=2)
    torch.manual_seed(args.seed)
    torch.cuda.set_device(args.local_rank)

    model = torch.load("mnist_cnn.pt",
                       map_location=torch.device(args.local_rank))
    model = DDP(model, device_ids=[args.local_rank])
    print(f"Rank {args.local_rank} "
          f"test on device {list(model.parameters())[0].device}")

    test(args, model, args.local_rank, test_loader)
    cleanup()


if __name__ == '__main__':
    main(args)

The mnist_train.py runs sucessfully using
python -m torch.distributed.launch nproc_per_node=4 (or 2) mnist_train.py.
but when i run the test script using
python -m torch.distributed.launch nproc_per_node=2 mnist_test.py.
I get the following:
Rank 0 test on device cuda:0
Rank 1 test on device cuda:1
Test set: Average loss: 0.0274, Accuracy: 9913/10000 (99.13%)

RuntimeError: Expected tensor for argument #1 input to have 
the same device as tensor for argument #2 weight; 
but device 0 does not equal 1 
(while checking arguments for cudnn_convolution)