ColossalAI icon indicating copy to clipboard operation
ColossalAI copied to clipboard

[BUG]: Error on Single GPU Training

Open willfant opened this issue 4 years ago • 7 comments

🐛 Describe the bug

I was triyng to train a simple classification model to test but when I run the trainer I got some errors that are not clear. Am I missing something? I'm using a single GPU .

To Reproduce:

import colossalai

colossalai.launch_from_torch(config='./config.py')
import numpy as np 
import pandas as pd
import seaborn as sns

import torch
import torch.nn as nn
import torch.optim as optim

from colossalai.core import global_context as gpc
from colossalai.logging import get_dist_logger
from colossalai.utils import get_dataloader
from colossalai.nn.lr_scheduler import CosineAnnealingLR

logger = get_dist_logger()

torch.manual_seed(123)
np.random.seed(123)

print("Preparing data.....")
X_train = pd.read_csv('X_train.csv')
y_train = pd.read_csv('y_train.csv')
X_test = pd.read_csv('X_test.csv')
y_test = pd.read_csv('y_test.csv')

LEARNING_RATE = 0.001
print("tensor.....")
X_train = torch.tensor(np.array(X_train), dtype=torch.float)
y_train = torch.tensor(np.array(y_train), dtype=torch.float)

X_test = torch.tensor(np.array(X_test), dtype=torch.float)
y_test = torch.tensor(np.array(y_test), dtype=torch.float)
print("tensordataset.....")
train_data = torch.utils.data.TensorDataset(X_train, y_train)
test_data = torch.utils.data.TensorDataset(X_test, y_test)
print("get_dataloader.....")

train_loader = get_dataloader(dataset=train_data,shuffle=True, batch_size=gpc.config.BATCH_SIZE,num_workers=1,pin_memory=True)
test_loader = get_dataloader(dataset=test_data,add_sampler=False, batch_size=gpc.config.BATCH_SIZE,num_workers=1,pin_memory=True)

print("creating model.....")
class BinaryClassification(nn.Module):
    def __init__(self):
        super().__init__()
        #30 -> 16 -> 16 -> 1
        self.dense0 = nn.Linear(7, 32)
        torch.nn.init.uniform_(self.dense0.weight)
        self.activation0 = nn.ReLU()
        self.dense1 = nn.Linear(32, 32)
        torch.nn.init.uniform_(self.dense1.weight)
        self.activation1 = nn.ReLU()
        self.dense2 = nn.Linear(32, 1)
        torch.nn.init.uniform_(self.dense2.weight)
        self.output = nn.Sigmoid()

    def forward(self, X):
        X = self.dense0(X)
        X = self.activation0(X)
        X = self.dense1(X)
        X = self.activation1(X)
        X = self.dense2(X)
        X = self.output(X)
        return X

model = BinaryClassification()

criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr = 0.001, weight_decay= 0.0001)
lr_scheduler = CosineAnnealingLR(optimizer, total_steps=gpc.config.NUM_EPOCHS)

engine, train_dataloader, test_dataloader, _ = colossalai.initialize(model,
                                                                     optimizer,
                                                                     criterion,
                                                                     train_loader,
                                                                     test_loader)



print("Start Training.....")
for epoch in range(gpc.config.NUM_EPOCHS):
    # execute a training iteration
    engine.train()
    for input, label in train_dataloader:
        input = input.cuda()
        label = label.cuda()
        
        # set gradients to zero
        engine.zero_grad()
        
        # run forward pass
        output = engine(input)
        
        # compute loss value and run backward pass
        train_loss = engine.criterion(output, label)
        engine.backward(train_loss)
        
        # update parameters
        engine.step()
        
    # update learning rate
    lr_scheduler.step()
    
    # execute a testing iteration
    engine.eval()
    correct = 0
    total = 0
    for input, label in test_dataloader:
        input = input.cuda()
        label = label.cuda()
        
        # run prediction without back-propagation
        with torch.no_grad():
            output = engine(input)
            test_loss = engine.criterion(output, label)
        
        # compute the number of correct prediction
        pred = torch.argmax(output, dim=-1)
        correct += torch.sum(pred == label)
        total += input.size(0)

    logger.info(
        f"Epoch {epoch} - train loss: {train_loss:.5}, test loss: {test_loss:.5}, acc: {correct / total:.5}, lr: {lr_scheduler.get_last_lr()[0]:.5g}", ranks=[0])

print(model.state_dict())
torch.save(model.state_dict(), 'checkpoint3.pth')

Expected Behavior The training should run without errors

Error:

ERROR:torch.distributed.elastic.multiprocessing.api:failed (exitcode: -9) local_rank: 0 (pid: 1671) of binary: /home/willfant/virtual/venv/bin/python3
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py", line 193, in <module>
    main()
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py", line 189, in main
    launch(args)
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py", line 174, in launch
    run(args)
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/run.py", line 715, in run
    elastic_launch(
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launcher/api.py", line 131, in __call__
    return launch_agent(self._config, self._entrypoint, list(args))
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launcher/api.py", line 245, in launch_agent
    raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
=====================================================
colosal.py FAILED
-----------------------------------------------------
Failures:
  <NO_OTHER_FAILURES>
-----------------------------------------------------
Root Cause (first observed failure):
[0]:
  time      : 2022-06-01_01:17:56
  host      : DESKTOP-5KVE0HV.localdomain
  rank      : 0 (local_rank: 0)
  exitcode  : -9 (pid: 1671)
  error_file: <N/A>
  traceback : Signal 9 (SIGKILL) received by PID 1671

Environment

SO: Ubuntu Torch: 1.11 Cuda: 11.3 GC: Nvidia RTX 2070

willfant avatar Jun 01 '22 09:06 willfant

Can you please show me the config file? Additionally, I think there should be some other error trackback above the multiprocesssing errors, can you please add those info as well?

YuliangLiu0306 avatar Jun 02 '22 04:06 YuliangLiu0306

hey @YuliangLiu0306. Please find below my config file and the full log:

This is command I send to run the script

python3 -m torch.distributed.launch --nproc_per_node 1 --master_addr localhost --master_port 29500 colosal.py

Log

/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py:178: FutureWarning: The module torch.distributed.launch is deprecated
and will be removed in future. Use torchrun.
Note that --use_env is set by default in torchrun.
If your script expects `--local_rank` argument to be set, please
change it to read from `os.environ['LOCAL_RANK']` instead. See
https://pytorch.org/docs/stable/distributed.html#launch-utility for
further instructions

  warnings.warn(
[06/02/22 14:10:05] INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:1 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:1 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:2 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:2 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:3 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:3 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:4 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:4 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:5 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:5 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:6 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:6 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:7 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:7 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:8 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:8 with 1 nodes.
                    INFO     colossalai - colossalai - INFO: /home/willfant/virtual/venv/lib/python3.8/site-packages/col
                             ossalai/context/parallel_context.py:521 set_device
                    INFO     colossalai - colossalai - INFO: process rank 0 is bound to device 0
[06/02/22 14:10:15] INFO     colossalai - colossalai - INFO: /home/willfant/virtual/venv/lib/python3.8/site-packages/col
                             ossalai/context/parallel_context.py:557 set_seed
                    INFO     colossalai - colossalai - INFO: initialized seed on rank 0, numpy: 1024, python random:
                             1024, ParallelMode.DATA: 1024, ParallelMode.TENSOR: 1024,the default parallel seed is
                             ParallelMode.DATA.
                    INFO     colossalai - colossalai - INFO:
                             /home/willfant/virtual/venv/lib/python3.8/site-packages/colossalai/initialize.py:117 launch
                    INFO     colossalai - colossalai - INFO: Distributed environment is initialized, data parallel size:
                             1, pipeline parallel size: 1, tensor parallel size: 1
Preparing data.....
ERROR:torch.distributed.elastic.multiprocessing.api:failed (exitcode: -9) local_rank: 0 (pid: 13156) of binary: /home/willfant/virtual/venv/bin/python3
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py", line 193, in <module>
    main()
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py", line 189, in main
    launch(args)
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py", line 174, in launch
    run(args)
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/run.py", line 715, in run
    elastic_launch(
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launcher/api.py", line 131, in __call__
    return launch_agent(self._config, self._entrypoint, list(args))
  File "/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launcher/api.py", line 245, in launch_agent
    raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
======================================================
colosal.py FAILED
------------------------------------------------------
Failures:
  <NO_OTHER_FAILURES>
------------------------------------------------------
Root Cause (first observed failure):
[0]:
  time      : 2022-06-02_14:10:23
  host      : DESKTOP-5KVE0HV.localdomain
  rank      : 0 (local_rank: 0)
  exitcode  : -9 (pid: 13156)
  error_file: <N/A>
  traceback : Signal 9 (SIGKILL) received by PID 13156
======================================================

Config File

from colossalai.amp import AMP_TYPE

BATCH_SIZE = 512
NUM_EPOCHS = 10

fp16 = dict(
    mode=AMP_TYPE.NAIVE
)

willfant avatar Jun 02 '22 13:06 willfant

Just to give an update. I removed this code torch.manual_seed(123) np.random.seed(123) from my script and now the trainer continues without errors. In this case, Colossal-AI alreay set the seed and for some reason has some conflit with the manual seed we set in the script?

I can see that the train loss and accuracy are not updating but I believe that is not related with colossal-ai

Here is my current log without the manual seed:

/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/distributed/launch.py:178: FutureWarning: The module torch.distributed.launch is deprecated
and will be removed in future. Use torchrun.
Note that --use_env is set by default in torchrun.
If your script expects `--local_rank` argument to be set, please
change it to read from `os.environ['LOCAL_RANK']` instead. See
https://pytorch.org/docs/stable/distributed.html#launch-utility for
further instructions

  warnings.warn(
[06/02/22 14:18:16] INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:1 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:1 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:2 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:2 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:3 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:3 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:4 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:4 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:5 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:5 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:6 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:6 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:7 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:7 with 1 nodes.
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Added key:
                             store_based_barrier_key:8 to store for rank: 0
                    INFO     colossalai - torch.distributed.distributed_c10d - INFO: Rank 0: Completed store-based
                             barrier for key:store_based_barrier_key:8 with 1 nodes.
                    INFO     colossalai - colossalai - INFO: /home/willfant/virtual/venv/lib/python3.8/site-packages/col
                             ossalai/context/parallel_context.py:521 set_device
                    INFO     colossalai - colossalai - INFO: process rank 0 is bound to device 0
[06/02/22 14:18:27] INFO     colossalai - colossalai - INFO: /home/willfant/virtual/venv/lib/python3.8/site-packages/col
                             ossalai/context/parallel_context.py:557 set_seed
                    INFO     colossalai - colossalai - INFO: initialized seed on rank 0, numpy: 1024, python random:
                             1024, ParallelMode.DATA: 1024, ParallelMode.TENSOR: 1024,the default parallel seed is
                             ParallelMode.DATA.
                    INFO     colossalai - colossalai - INFO:
                             /home/willfant/virtual/venv/lib/python3.8/site-packages/colossalai/initialize.py:117 launch
                    INFO     colossalai - colossalai - INFO: Distributed environment is initialized, data parallel size:
                             1, pipeline parallel size: 1, tensor parallel size: 1
Preparing data.....
tensor.....
tensordataset.....
get_dataloader.....
creating model.....
[06/02/22 14:18:37] INFO     colossalai - colossalai - INFO:
                             /home/willfant/virtual/venv/lib/python3.8/site-packages/colossalai/initialize.py:266
                             initialize
                    INFO     colossalai - colossalai - INFO:
                             ========== Your Config ========
                             {'BATCH_SIZE': 512,
                              'NUM_EPOCHS': 10,
                              'fp16': {'mode': <AMP_TYPE.NAIVE: 'naive'>}}
                             ================================

                    INFO     colossalai - colossalai - INFO:
                             /home/willfant/virtual/venv/lib/python3.8/site-packages/colossalai/initialize.py:278
                             initialize
                    INFO     colossalai - colossalai - INFO: cuDNN benchmark = True, deterministic = False
                    WARNING  colossalai - colossalai - WARNING:
                             /home/willfant/virtual/venv/lib/python3.8/site-packages/colossalai/initialize.py:304
                             initialize
                    WARNING  colossalai - colossalai - WARNING: Initializing an non ZeRO model with optimizer class
                    WARNING  colossalai - colossalai - WARNING:
                             /home/willfant/virtual/venv/lib/python3.8/site-packages/colossalai/initialize.py:436
                             initialize
                    WARNING  colossalai - colossalai - WARNING: No PyTorch DDP or gradient handler is set up, please
                             make sure you do not need to all-reduce the gradients after a training step.
Start Training.....
/home/willfant/virtual/venv/lib/python3.8/site-packages/torch/optim/lr_scheduler.py:131: UserWarning: Detected call of `lr_scheduler.step()` before `optimizer.step()`. In PyTorch 1.1.0 and later, you should call them in the opposite order: `optimizer.step()` before `lr_scheduler.step()`.  Failure to do this will result in PyTorch skipping the first value of the learning rate schedule. See more details at https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate
  warnings.warn("Detected call of `lr_scheduler.step()` before `optimizer.step()`. "
[06/02/22 14:20:06] INFO     colossalai - colossalai - INFO: colosal.py:123 <module>
                    INFO     colossalai - colossalai - INFO: Epoch 0 - train loss: 1.3133, test loss: 1.3133, acc:
                             511.31, lr: 0.00097553
[06/02/22 14:21:29] INFO     colossalai - colossalai - INFO: colosal.py:123 <module>
                    INFO     colossalai - colossalai - INFO: Epoch 1 - train loss: 1.3133, test loss: 1.3133, acc:
                             511.31, lr: 0.00090451

willfant avatar Jun 02 '22 13:06 willfant

Thank you for the updating. In my view, the bug happens during data preparing(I got this conclusion from print info), which means either there are some errors in your csv files, or pandas.csv_read cant work correctly with manual seed.

YuliangLiu0306 avatar Jun 02 '22 19:06 YuliangLiu0306

Hey. Thanks for your fast reply. I think that the problem is not in pd.csv_read + Manual seed because using a normal nn only with pytorch works just fine. Unless there's some incompatibility with colossalai. But just to confirm, should we set the seed or colossal already does that for us?

Thanks again!

willfant avatar Jun 02 '22 20:06 willfant

Hi, I tried to reproducing the bug, but nothing happens when I add the setting manual seed code to those programs which could work correctly before setting seed manually. We do set seeds during initializing, but it's okay for users to set seeds again. I recommend you to try some examples in our examples repositoryhttps://github.com/hpcaitech/ColossalAI-Examples/tree/develop.

YuliangLiu0306 avatar Jun 03 '22 05:06 YuliangLiu0306

Hi. Alright! Thank you for your help. I'll close the bug then.

willfant avatar Jun 03 '22 08:06 willfant