# Loading a checkpoint in the DataParallel setting: Questions

**URL:** <https://discuss.pytorch.org/t/loading-a-checkpoint-in-the-dataparallel-setting-questions/26511>\
**Category:** Uncategorized\
**Created:** [October 4, 2018, 5:21am UTC](https://discuss.pytorch.org/t/loading-a-checkpoint-in-the-dataparallel-setting-questions/26511 "2018-10-04T05:21:20Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![jerinphilip](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jerinphilip/32/66888_2.png) [@jerinphilip](https://discuss.pytorch.org/u/jerinphilip)\
**Post date:** [October 4, 2018, 5:21am UTC](https://discuss.pytorch.org/t/loading-a-checkpoint-in-the-dataparallel-setting-questions/26511/1 "2018-10-04T05:21:20Z")

</div>

I was stuck trying to load a checkpoint trained using DataParallel and a bunch of things seem to have worked so far for me. It took several iterations to fix, and I had to find the following after many attempts of searching. I feel there’s still some things I’m doing wrong, and am hoping this thread would help.

## DataParallel Training from start

I found that the usage(gpu0) = gpu1 + gpu2 + gpu3 + gpu0, which was due to computing loss outside. The following confused me, since it said loss can be outside.

> [@Is the loss function paralleled when using DataParallel?](https://discuss.pytorch.org/t/is-the-loss-function-paralleled-when-using-dataparallel/3346):
>
> When using [DataParallel](http://pytorch.org/docs/_modules/torch/nn/parallel/data_parallel.html) to wrap my module, do I need to do anything to also parallelize the loss functions? For example, let’s say that I have large batch size and large output tensors to compute MSE against a target. This operation would benefit from splitting the batch across multiple GPUs, but I’m not sure if the following code does that: model = MyModule() model = nn.parallel.DataParallel(model, device\_ids=range(args.number\_gpus)) model.cuda() output = model(data) criterion = nn.MSELoss()…

The methods in the below thread meanwhile worked, once I put `model + loss` inside `DataParallel`, it balanced GPU memory to some extent.

> [@DataParallel imbalanced memory usage](https://discuss.pytorch.org/t/dataparallel-imbalanced-memory-usage/22551):
>
> Hi there, I’m going to re-edit the whole thread to introduce a unlikely behavior with DataParallel Right now there are several recent posts about this topic and I would like to summarize the problem. Right now it seems there is an imbalaced usage of GPUs when calling DataParallel. [](https://discuss.pytorch.org/uploads/default/optimized/2X/5/5aba409800ca4813fc11eead25b891e4befe3dd8_1_690x119.png) From my experience and other users’ explanations I will explain why this happens: Using DataParallel there are 4 types of data to consider: Input Output Ground-truth Opti…

## DataParallel Training from checkpoint

Everytime I tried to load it directly, I was getting out of memory error without even reaching the peak batch size I could achieve from the above setting. Eventually, loading weights to CPU first and then `load_state_dict` on the model from that worked to balance the memory imbalance across GPUs. I believe the following thread partially helped me out:

> [@GPU memory usage increases by ~90% after torch.load](https://discuss.pytorch.org/t/gpu-memory-usage-increases-by-90-after-torch-load/9213/2):
>
> Yes, I have experienced the same situation before. This is quiet annoying ! I will bump on OOM if I would like to resume training from a checkpoint.

## Current Status

There is still an imbalance. I’m using 3 1080 Tis (1-3) with 11GB max memory. Attempts to increase further gives me OOM, while clearly [2] and [3] has free space.

![Screenshot%20from%202018-10-04%2010-38-27](https://discuss.pytorch.org/uploads/default/original/2X/6/61f0c9f2619ef7ba2aa0e202e8290401d6fcbd8f.png)

The following is the main training routine, at this point:

```auto
    def checkpoint(model, opt, checkpoint_path):
        _payload = {
            "model": model.module.state_dict(),
            "opt": opt.state_dict()
        }

        with open(checkpoint_path, "wb+") as fp:
            torch.save(_payload, fp)

    def load(model, opt, checkpoint_path):
        _payload = torch.load(checkpoint_path, map_location=torch.device("cpu"))
        model.module.load_state_dict(_payload["model"])
        opt.load_state_dict(_payload["opt"])

    args = Args()
    model = MaskedMLE.build_model(args, task)
    reduce = True
    max_epochs = 80 

    criterion = nn.NLLLoss(ignore_index=dataset.vocab.pad())
    model = LossGenerator(model, criterion)
    checkpoint_path = "/scratch/jerin/best_checkpoint.pt"
    model = model.to(device)
    model = DataParallel(model)
    opt = optim.Adam(model.parameters())
    if os.path.exists(checkpoint_path):
       load(model, opt, checkpoint_path)

    for epoch in tqdm(range(max_epochs), total=max_epochs, desc='epoch'):
        pbar = tqdm_progress_bar(loader, epoch=epoch)
        meters["loss"].reset()
        count = 0
        for src, src_lens, tgt, tgt_lens in pbar:
            count += 1
            opt.zero_grad()
            src, tgt = src.to(device), tgt.to(device)
            loss = model(src, src_lens, tgt)
            loss.sum().backward()
            meters['loss'].update(loss.mean().item())
            pbar.log(meters)
            opt.step()

        avg_loss = meters["loss"].avg
        meters['epoch'].update(avg_loss)
        checkpoint(model, opt, checkpoint_path)

```

What are further improvements I could do? Could someone explain the internals of these things (loading, checkpoint) and best practices?

---

<div class="post-metadata">

**Author:** ![kaixin](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/kaixin/32/33299_2.png) [@kaixin](https://discuss.pytorch.org/u/kaixin)\
**Post date:** [October 4, 2018, 6:18am UTC](https://discuss.pytorch.org/t/loading-a-checkpoint-in-the-dataparallel-setting-questions/26511/2 "2018-10-04T06:18:13Z")

</div>

If I understand the source code of `DataParallel` correctly, you could try commenting this line `model = model.to(device)`. Also, try specifying the `output_device` for `DataParallel` to see if it works.

---

<div class="post-metadata">

**Author:** ![jerinphilip](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jerinphilip/32/66888_2.png) [@jerinphilip](https://discuss.pytorch.org/u/jerinphilip)\
**Post date:** [October 4, 2018, 8:00am UTC](https://discuss.pytorch.org/t/loading-a-checkpoint-in-the-dataparallel-setting-questions/26511/3 "2018-10-04T08:00:33Z")

</div>

I tried a bunch of the combos.

- Commenting out `model = model.to(device)` gets me `Broadcast not implemented for CPUTensors...`
- Looking at the source now, if all outputs have to be gathered at one device, wouldn’t that increase the usage on device\_ids[0] anyway? Is there anyway to circumvent this?

---

<div class="post-metadata">

**Author:** ![JuanFMontesinos](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/juanfmontesinos/32/76115_2.png) [@JuanFMontesinos](https://discuss.pytorch.org/u/JuanFMontesinos)\
**Post date:** [October 4, 2018, 2:19pm UTC](https://discuss.pytorch.org/t/loading-a-checkpoint-in-the-dataparallel-setting-questions/26511/4 "2018-10-04T14:19:49Z")

</div>

Your main problem is you are using Adam. Adam parameters take memory from the main gpu to store its parameters. As far as I know there is nothing you can do. The bigger your model is, the worse this problem will be.  
You can try to ask some developer if there is a way of spliting the memory usage of adam among all the gpus but, as you could see in the thread i opened, I got no answer.

---

<div class="post-metadata">

**Author:** ![jerinphilip](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jerinphilip/32/66888_2.png) [@jerinphilip](https://discuss.pytorch.org/u/jerinphilip)\
**Post date:** [October 4, 2018, 2:47pm UTC](https://discuss.pytorch.org/t/loading-a-checkpoint-in-the-dataparallel-setting-questions/26511/5 "2018-10-04T14:47:22Z")

</div>

Can you link the thread corresponding to adam here? Or is it the one I mentioned above?
