DeepSpeed icon indicating copy to clipboard operation
DeepSpeed copied to clipboard

[BUG] DeepSpeed hangs during evaluation under multi-GPU

Open kai-0430 opened this issue 1 year ago • 7 comments

Edit - 1 The same problem occurs when using ZeRO2 with offloading.

Describe the bug I am trying to train Llama2-7B-fp16 using 4 V100. I use ZeRO-3 without offloading, with huggingFace trainer. However, the training hagns during the 1st evaluation (validation), or after the 1st evaluation completed. The process is then killed due to NCCL timeout:

{'loss': 1.7157, 'grad_norm': 0.0, 'learning_rate': 0.0, 'epoch': 0.02}
{'eval_loss': 1.8737543821334839, 'eval_runtime': 14.4006, 'eval_samples_per_second': 3.194, 'eval_steps_per_second': 0.833, 'epoch': 0.02}
 2%|▏         | 1/42 [02:52<1:48:00, 158.06s/i[rank0]:[E ProcessGroupNCCL.cpp:523] [Rank 0] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=9314, OpType=_REDUCE_SCATTER_BASE, NumelIn=131072000, NumelOut=32768000, Timeout(ms)=600000) 

It's so weired since during training the forward/backward pass seems fine. Why it hangs during evaluation??

What I've tried:

  • set NCCL_P2P_DISABLE=1
  • set NCCL_P2P_LEVEL=NVL
  • adjust stage3_max_live_parameters and stage3_max_reuse_distance
  • enable/disable fp16 mixed-precision training
  • Check that IOMMU is disabled (NCCL Troubleshooting)
  • Set NCCL_DEBUG=INFO and there is no warning or error message

To Reproduce

Here is the ds_config.json file:

{
    "train_batch_size": "auto",
    "train_micro_batch_size_per_gpu": "auto",
    "gradient_accumulation_steps": "auto",
    "gradient_clipping": "auto",
    
    "dump_state": true,
    "wall_clock_breakdown": true,
    
    "fp16": {
        "enabled": false,
        "loss_scale": 0,
        "loss_scale_window": 1000,
        "initial_scale_power": 16,
        "hysteresis": 2,
        "min_loss_scale": 1
    },
    "bf16": {
        "enabled": false
    },
    "zero_optimization": {
        "stage": 3,
        "overlap_comm": true,
        "contiguous_gradients": true,
        "sub_group_size": 1e9,
        "reduce_bucket_size": "auto",
        "stage3_prefetch_bucket_size": "auto",
        "stage3_param_persistence_threshold": "auto",
        "stage3_max_live_parameters": 1e9,
        "stage3_max_reuse_distance": 1e9,
        "stage3_gather_16bit_weights_on_model_save": false
    },
    "activation_checkpointing": {
        "partition_activations": true,
        "cpu_checkpointing": true,
        "contiguous_memory_optimization": true,
        "number_checkpoints": 4
    }
}

Here is my code:

import os
import torch
from transformers import LlamaForCausalLM, LlamaTokenizer
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers import TrainerCallback
from transformers import default_data_collator, Trainer, TrainingArguments
import datasets
from torch.utils.data import Dataset
from contextlib import nullcontext
import deepspeed
from tqdm import tqdm
from itertools import chain


class ConcatDataset(Dataset):
    def __init__(self, dataset, chunk_size=2048):
        self.dataset = dataset
        self.chunk_size = chunk_size
        self.samples = []

        buffer = {
            "input_ids": [],
            "attention_mask": [],
            "labels": [],
            }

        for sample in tqdm(self.dataset, desc="Preprocessing dataset", dynamic_ncols=True):
            buffer["input_ids"] = buffer["input_ids"] + sample["input_ids"]
            buffer["attention_mask"] = buffer["attention_mask"] + sample["attention_mask"]
            buffer["labels"] = buffer["input_ids"]

            while len(next(iter(buffer.values()))) > self.chunk_size:
                self.samples.append({k: v[:self.chunk_size] for k,v in buffer.items()})
                buffer = {k: v[self.chunk_size:] for k,v in buffer.items()}
        
    def __getitem__(self, idx):
        return self.samples[idx]

    def __len__(self):
        return len(self.samples)


def get_corpus(tokenizer, corpus, p=1e-2):
    # load dataset    
    raw_dataset = datasets.load_dataset(corpus, split='train', num_proc=16)
    
    # Subsampling dataset
    dataset = raw_dataset.filter(lambda example, idx: idx % (1/p) == 0, with_indices=True, num_proc=16)  # num_proc=16,
    
    # Train/Test split
    split_dataset = dataset.train_test_split(test_size=1e-2) #1e-2
    train_dataset = split_dataset["train"]
    eval_dataset  = split_dataset["test"]

    # Apply prompt form
    prompt = (
        f"{{text}}{{eos_token}}"
    )
    def apply_prompt_template(sample):
        return {
            "text": prompt.format(
                text=sample["text"],
                eos_token=tokenizer.eos_token,
            )
        }
    train_dataset = train_dataset.map(apply_prompt_template, remove_columns=list(train_dataset.features), num_proc=16)
    eval_dataset = eval_dataset.map(apply_prompt_template, remove_columns=list(eval_dataset.features), num_proc=16)
    
    
    # Tokenize and Concate
    train_dataset = train_dataset.map(
        lambda sample: tokenizer(sample["text"]),
        batched=True,
        remove_columns=list(train_dataset.features),
        num_proc=16,
    )
    train_dataset = ConcatDataset(train_dataset, chunk_size=4096)
    
    eval_dataset = eval_dataset.map(
        lambda sample: tokenizer(sample["text"]),
        batched=True,
        remove_columns=list(eval_dataset.features),
        num_proc=16,
    )
    eval_dataset = ConcatDataset(eval_dataset, chunk_size=4096)
    
    return train_dataset, eval_dataset


def get_training_argument(output_dir, ds_config):

    training_args = TrainingArguments(
        
        num_train_epochs = 1,
        
        optim = "adamw_torch",
        learning_rate = 1e-4,
        weight_decay = 1e-3,
        lr_scheduler_type = "linear",
        warmup_ratio = 0.1,
        
        gradient_accumulation_steps = 4,      # 32
        per_device_train_batch_size = 1,
        per_device_eval_batch_size = 1,
        gradient_checkpointing = True,
        
        dataloader_pin_memory = True,
        dataloader_num_workers = 8,
        
        output_dir = output_dir,
        overwrite_output_dir = True,
        # fp16=True,
        
        # evaluation strategies
        evaluation_strategy = "steps",      # "steps", "no"
        #eval_steps=10,                     # Linked to logging_steps
        
        # logging strategies
        logging_dir = f"{output_dir}/logs",
        logging_strategy = "steps",
        logging_steps = 1,                  # 0.02
        
        save_strategy = "no",               # "steps"
        max_steps = -1,                     # 
        
        # *** deepspeed ***
        deepspeed = ds_config,
        log_level = "info",              # info, debug
    )
    return training_args



def main():
    torch.manual_seed(42)

    model_id="TheBloke/Llama-2-7B-fp16"
    dataset_path="togethercomputer/RedPajama-Data-1T-Sample"
    output_dir="./output"
    ds_config="./ds_zero3_config.json"
    DO_SAVE = False

    tokenizer = AutoTokenizer.from_pretrained(model_id)

    train_dataset, eval_dataset = get_corpus(tokenizer, corpus=dataset_path, p=1e-2)
    
    # *** For DeepSpeed, the TrainingArguments object must be created before calling the model from_pretrained(). ***
    training_args = get_training_argument(output_dir, ds_config)

    # In DeepSeed ZeRO-3, use the deepspeed.zero.Init() context manager to initialize a model faster. 
    with deepspeed.zero.Init():
        model = AutoModelForCausalLM.from_pretrained(
            model_id,
            # device_map='auto',
            torch_dtype=torch.float32,
        )
        model.gradient_checkpointing_enable()
    
    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset,
        eval_dataset=eval_dataset,
        data_collator=default_data_collator,
    )
    trainer.train()

    if DO_SAVE is True:
        model.save_pretrained(output_dir)
        tokenizer.save_pretrained(output_dir)


if __name__ == "__main__":
    main()

Expected behavior Train and validate without error.

ds_report output

[2024-04-10 20:16:45,241] [INFO] [real_accelerator.py:191:get_accelerator] Setting ds_accelerator to cuda (auto detect)
--------------------------------------------------
DeepSpeed C++/CUDA extension op report
--------------------------------------------------
NOTE: Ops not installed will be just-in-time (JIT) compiled at
      runtime if needed. Op compatibility means that your system
      meet the required dependencies to JIT install the op.
--------------------------------------------------
JIT compiled ops requires ninja
ninja .................. [OKAY]
--------------------------------------------------
op name ................ installed .. compatible
--------------------------------------------------
 [WARNING]  async_io requires the dev libaio .so object and headers but these were not found.
 [WARNING]  async_io: please install the libaio-dev package with apt
 [WARNING]  If libaio is already installed (perhaps from source), try setting the CFLAGS and LDFLAGS environment variables to where it can be found.
async_io ............... [NO] ....... [NO]
fused_adam ............. [NO] ....... [OKAY]
cpu_adam ............... [NO] ....... [OKAY]
cpu_adagrad ............ [NO] ....... [OKAY]
cpu_lion ............... [NO] ....... [OKAY]
 [WARNING]  Please specify the CUTLASS repo directory as environment variable $CUTLASS_PATH
evoformer_attn ......... [NO] ....... [NO]
fused_lamb ............. [NO] ....... [OKAY]
fused_lion ............. [NO] ....... [OKAY]
inference_core_ops ..... [NO] ....... [OKAY]
cutlass_ops ............ [NO] ....... [OKAY]
transformer_inference .. [NO] ....... [OKAY]
quantizer .............. [NO] ....... [OKAY]
ragged_device_ops ...... [NO] ....... [OKAY]
ragged_ops ............. [NO] ....... [OKAY]
random_ltd ............. [NO] ....... [OKAY]
 [WARNING]  sparse_attn requires a torch version >= 1.5 and < 2.0 but detected 2.2
 [WARNING]  using untested triton version (2.2.0), only 1.0.0 is known to be compatible
sparse_attn ............ [NO] ....... [NO]
spatial_inference ...... [NO] ....... [OKAY]
transformer ............ [NO] ....... [OKAY]
stochastic_transformer . [NO] ....... [OKAY]
--------------------------------------------------
DeepSpeed general environment info:
torch install path ............... ['/home/u2826839/.local/lib/python3.11/site-packages/torch']
torch version .................... 2.2.2+cu121
deepspeed install path ........... ['/home/u2826839/.local/lib/python3.11/site-packages/deepspeed']
deepspeed info ................... 0.14.0, unknown, unknown
torch cuda version ............... 12.1
torch hip version ................ None
nvcc version ..................... 12.3
deepspeed wheel compiled w. ...... torch 2.2, cuda 12.1
shared memory (/dev/shm) size .... 111.76 GB

System info (please complete the following information):

  • OS: Ubuntu 22.04.3 LTS
  • Kernel version: Linux 3.10.0-1127.el7.x86_64
  • GPU count and types: one machine with 4 A100s
  • Python: 3.11.8
  • torch: 2.2.2
  • transformers: 4.39.2
  • accelerate: 0.28.0
  • deepspeed: 0.14.0

Launcher context Here is how I run my code.

deepspeed llama2_ds_v2.py

Additional context Use py-spy command, pgrep -P $(pgrep -o deepspeed) | xargs -I {} py-spy dump --pid {}. It shows:

Process 23297: /work/u2826839/anaconda/envs/llama-med/bin/python -u -m deepspeed.launcher.launch --world_info=eyJsb2NhbGhvc3QiOiBbMCwgMSwgMiwgM119 --master_addr=127.0.0.1 --master_port=29500 --enable_each_rank_log=None llama2_ds_v2.py
Python v3.11.8 (/work/u2826839/anaconda/envs/llama-med/bin/python3.11)

Thread 23297 (idle): "MainThread"
    main (deepspeed/launcher/launch.py:352)
    <module> (deepspeed/launcher/launch.py:356)
    _run_code (<frozen runpy>:88)
    _run_module_as_main (<frozen runpy>:198)

I also tried my script on 2 A100, but the same problem happens.

Also, I tried the accelerate launcher, and the trouble still occurs.

I am not sure where the problem comes from:

  • my script
  • Linux kernel too old
  • deepspeed library
  • accelerate/huggingFace library
  • GPU configuration

I saw this "On Linux with kernel version < 5.5, hanging processes have been reported. To avoid this problem, upgrade your system to a later kernel version." in this website. My kernel version is 3.10.0. I'm not sure whether it is the cause. For my case, installing a new kernel is not an easy solution.

Any suggestions are greatly appreciated.

kai-0430 avatar Apr 10 '24 12:04 kai-0430

The same problem

jacklanda avatar Apr 19 '24 02:04 jacklanda

@kai-0430 Can you provide the output of nvidia-smi topo -m

jomayeri avatar Apr 22 '24 20:04 jomayeri

@jomayeri Sure. For the setting of 4 A100s, they have NVLink interconnecting them. But no matter if NCCL_P2P_DISABLE=1 or not, the hanging always occur. topo_on_TWCC

Here is another issue. After I turn off the validation (evaluation), similar situation happens at the end of an epoch. It hangs at the following moment (1) At the last step (2) After the last step, the training loss is shown, but the program hangs and fails to complete. (3) At the second-to-last step

For (1), setting dataloader_drop_last=True can seemingly solve. For (2), I set NCCL_IB_DISABLE="1" according to this, and set report_to="none" in the training argument due to the logger sync issue according to this and this. After solving (1) and (2), it appears that the training can be completed. But I found when I enlarge the dataset size from 0.01B tokens to 0.1B tokens, case (3) happen. Here is the output of py-spy dump. It seems to get stuck at the backward. Then after 10 minute, NCCL timeout with opType ALLREDUCE.

Thread 36455 (idle): "MainThread"
    backward (torch/autograd/__init__.py:266)
    backward (torch/_tensor.py:522)
    backward (deepspeed/runtime/fp16/loss_scaler.py:63)
    backward (deepspeed/runtime/zero/stage_1_and_2.py:2051)
    backward (deepspeed/runtime/engine.py:1976)
    wrapped_fn (deepspeed/utils/nvtx.py:15)
    backward (accelerate/utils/deepspeed.py:166)
    backward (accelerate/accelerator.py:1995)
    training_step (transformers/trainer.py:3045)
    _inner_training_loop (transformers/trainer.py:2118)
    train (transformers/trainer.py:1780)
    main (llama2_ds_v3.py:232)
    <module> (llama2_ds_v3.py:240)
Thread 36635 (idle): "Thread-1"
    wait (threading.py:331)
    wait (threading.py:629)
    run (tqdm/_monitor.py:60)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 1020 (idle): "Thread-11"
    wait (threading.py:331)
    wait (threading.py:629)
    run (tqdm/_monitor.py:60)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2867 (idle): "Thread-15 (_pin_memory_loop)"
    select (selectors.py:415)
    wait (multiprocessing/connection.py:947)
    _poll (multiprocessing/connection.py:440)
    poll (multiprocessing/connection.py:257)
    get (multiprocessing/queues.py:113)
    do_one_step (torch/utils/data/_utils/pin_memory.py:30)
    _pin_memory_loop (torch/utils/data/_utils/pin_memory.py:53)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2938 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2939 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2940 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2941 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2942 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2943 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2944 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2945 (idle): "QueueFeederThread"
    wait (threading.py:327)
    _feed (multiprocessing/queues.py:231)
    run (threading.py:982)
    _bootstrap_inner (threading.py:1045)
    _bootstrap (threading.py:1002)
Thread 2963 (idle)
Thread 2964 (idle)
Thread 2962 (active)
    _flatten_dense_tensors (torch/_utils.py:526)
    allreduce_bucket (deepspeed/runtime/zero/stage_1_and_2.py:1477)
    allreduce_and_copy_with_multiple_ranks (deepspeed/runtime/zero/stage_1_and_2.py:1000)
    allreduce_and_scatter (deepspeed/runtime/zero/stage_1_and_2.py:1027)
    average_tensor (deepspeed/runtime/zero/stage_1_and_2.py:1123)
    reduce_ipg_grads (deepspeed/runtime/zero/stage_1_and_2.py:1363)
    reduce_independent_p_g_buckets_and_remove_grads (deepspeed/runtime/zero/stage_1_and_2.py:928)
    reduce_ready_partitions_and_remove_grads (deepspeed/runtime/zero/stage_1_and_2.py:1412)
    reduce_partition_and_remove_grads (deepspeed/runtime/zero/stage_1_and_2.py:899)
    backward (torch/autograd/__init__.py:266)
    backward (torch/utils/checkpoint.py:319)
    apply (torch/autograd/function.py:289)
Thread 2965 (idle)

kai-0430 avatar Apr 23 '24 03:04 kai-0430

This seems to be a systems issue. If you run without DeepSpeed does the hang also occur?

jomayeri avatar Apr 24 '24 22:04 jomayeri

Thank for your reply! @jomayeri If I run training without DeepSpeed (use 4 V100 but only one is active at a time), the hang won't occur. I was curious about whether this is an issue of DeepSpeed or not, so I tried another distributed training method, the FSDP integrated in Accelerate package. Surprisingly, the hang also occurs! This issue doesn't solely occur in DeepSpeed in my case. So, what system issues could be causing it? I want to figure out possible soultions to make it work.

kai-0430 avatar Apr 26 '24 13:04 kai-0430

Thank for your reply! @jomayeri If I run training without DeepSpeed (use 4 V100 but only one is active at a time), the hang won't occur. I was curious about whether this is an issue of DeepSpeed or not, so I tried another distributed training method, the FSDP integrated in Accelerate package. Surprisingly, the hang also occurs! This issue doesn't solely occur in DeepSpeed in my case. So, what system issues could be causing it? I want to figure out possible soultions to make it work.

I guess it could be the issue happened in the accelerate / transformer. Hence, I filed a related issue here.

Have you tried to use the original FSDP API of Pytorch to conduct parallel training in DDP?

jacklanda avatar Apr 26 '24 15:04 jacklanda

No, I haven't. Maybe I'll try it these days.

kai-0430 avatar Apr 29 '24 05:04 kai-0430

hey @kai-0430 , did you able to solve this issue?

Oguzhanercan avatar Jun 11 '24 11:06 Oguzhanercan