[deepspeed] Bittensor dataset causes hanging
Author: benproton
Pull request: no

### System Info

    transformers version: 4.27.0.dev0
    Platform: Linux-5.15.0-58-generic-x86_64-with-glibc2.35
    Python version: 3.10.6
    Huggingface_hub version: 0.12.0
    PyTorch version (GPU?): 1.12.0+cu113 (True)
    Tensorflow version (GPU?): not installed (NA)
    Flax version (CPU?/GPU?/TPU?): not installed (NA)
    Jax version: not installed
    JaxLib version: not installed
    Using GPU in script?: yes, via deepspeed
    Using distributed or parallel set-up in script?: yes, via deepspeed

### Who can help?

@stas00 

### Information

- [ ] The official example scripts
- [X] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [X] My own task or dataset (give details below)

### Reproduction

I've been trying to use the Trainer with deepspeed using the following guide: https://huggingface.co/docs/transformers/v4.25.1/en/main_classes/deepspeed#trainer-deepspeed-integration

Below is my python code:

```
#!/usr/bin/env python
# coding=utf-8
# Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Fine-tuning the library models for sequence to sequence.
"""
# You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.

import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import numpy as np
from datasets import Dataset, DatasetDict, load_dataset

import evaluate
import transformers
from transformers import (
    AutoConfig,
    AutoTokenizer,
    HfArgumentParser,
    M2M100Tokenizer,
    MBart50Tokenizer,
    MBart50TokenizerFast,
    MBartTokenizer,
    MBartTokenizerFast,
    Trainer,
    TrainingArguments,
    AutoModelForCausalLM,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version

import bittensor
from itertools import chain
from tqdm.auto import tqdm



# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.27.0.dev0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/translation/requirements.txt")

logger = logging.getLogger(__name__)

# A list of all multilingual tokenizer which require src_lang and tgt_lang attributes.
MULTILINGUAL_TOKENIZERS = [MBartTokenizer, MBartTokenizerFast, MBart50Tokenizer, MBart50TokenizerFast, M2M100Tokenizer]


@dataclass
class ModelArguments:
    """
    Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
    """

    model_name_or_path: str = field(
        metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
    )
    config_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
    )
    tokenizer_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
    )
    cache_dir: Optional[str] = field(
        default=None,
        metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
    )
    use_fast_tokenizer: bool = field(
        default=True,
        metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
    )
    model_revision: str = field(
        default="main",
        metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
    )
    use_auth_token: bool = field(
        default=False,
        metadata={
            "help": (
                "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
                "with private models)."
            )
        },
    )


@dataclass
class DataTrainingArguments:
    """
    Arguments pertaining to what data we are going to input our model for training and eval.
    """

    source_lang: str = field(default=None, metadata={"help": "Source language id for translation."})
    target_lang: str = field(default=None, metadata={"help": "Target language id for translation."})

    dataset_name: Optional[str] = field(
        default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
    )
    dataset_config_name: Optional[str] = field(
        default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
    )
    train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a jsonlines)."})
    validation_file: Optional[str] = field(
        default=None,
        metadata={
            "help": "An optional input evaluation data file to evaluate the metrics (sacrebleu) on a jsonlines file."
        },
    )
    test_file: Optional[str] = field(
        default=None,
        metadata={"help": "An optional input test data file to evaluate the metrics (sacrebleu) on a jsonlines file."},
    )
    overwrite_cache: bool = field(
        default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
    )
    preprocessing_num_workers: Optional[int] = field(
        default=None,
        metadata={"help": "The number of processes to use for the preprocessing."},
    )
    max_source_length: Optional[int] = field(
        default=1024,
        metadata={
            "help": (
                "The maximum total input sequence length after tokenization. Sequences longer "
                "than this will be truncated, sequences shorter will be padded."
            )
        },
    )
    max_target_length: Optional[int] = field(
        default=128,
        metadata={
            "help": (
                "The maximum total sequence length for target text after tokenization. Sequences longer "
                "than this will be truncated, sequences shorter will be padded."
            )
        },
    )
    val_max_target_length: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "The maximum total sequence length for validation target text after tokenization. Sequences longer "
                "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`."
                "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used "
                "during ``evaluate`` and ``predict``."
            )
        },
    )
    pad_to_max_length: bool = field(
        default=False,
        metadata={
            "help": (
                "Whether to pad all samples to model maximum sentence length. "
                "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
                "efficient on GPU but very bad for TPU."
            )
        },
    )
    max_train_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of training examples to this "
                "value if set."
            )
        },
    )
    max_eval_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
                "value if set."
            )
        },
    )
    max_predict_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of prediction examples to this "
                "value if set."
            )
        },
    )
    num_beams: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
                "which is used during ``evaluate`` and ``predict``."
            )
        },
    )
    ignore_pad_token_for_loss: bool = field(
        default=True,
        metadata={
            "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
        },
    )
    source_prefix: Optional[str] = field(
        default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
    )
    forced_bos_token: Optional[str] = field(
        default=None,
        metadata={
            "help": (
                "The token to force as the first generated token after the :obj:`decoder_start_token_id`.Useful for"
                " multilingual models like :doc:`mBART <../model_doc/mbart>` where the first generated token needs to"
                " be the target language token.(Usually it is the target language token)"
            )
        },
    )

    def __post_init__(self):
        if self.dataset_name is None and self.train_file is None and self.validation_file is None:
            raise ValueError("Need either a dataset name or a training/validation file.")

        # accepting both json and jsonl file extensions, as
        # many jsonlines files actually have a .json extension
        valid_extensions = ["json", "jsonl"]

        if self.train_file is not None:
            extension = self.train_file.split(".")[-1]
            assert extension in valid_extensions, "`train_file` should be a jsonlines file."
        if self.validation_file is not None:
            extension = self.validation_file.split(".")[-1]
            assert extension in valid_extensions, "`validation_file` should be a jsonlines file."
        if self.val_max_target_length is None:
            self.val_max_target_length = self.max_target_length

def load_raw_datasets(name: str, confName: str) -> DatasetDict:

    if name == "bittensor":

        dataset = bittensor.dataset(
            no_tokenizer=True,
            # batch_size=cfg.training.train_batch_size,
            # block_size=cfg.dataset.block_size,
        )
        dataloader = dataset.dataloader(1000)
        bittensor_dataset = {"text": []}
        for batch in tqdm(dataloader, desc="Loading data from bittensor IPFS"):
            bittensor_dataset["text"].extend(batch)
        raw_datasets = Dataset.from_dict(bittensor_dataset)

        dataset.close()  # Avoid leaving threadqueue running.
        return raw_datasets

    if os.path.exists(name):
        data_files = {"text": name}
        dataset_args = {}

        extension = os.path.splitext(name)[-1].lstrip(".")

        if extension == "txt":
            extension = "text"
            dataset_args["keep_linebreaks"] = True
        raw_datasets = load_dataset(
            extension, data_files=data_files, **dataset_args)
        raw_datasets = raw_datasets["text"]
    else:
        raw_datasets = load_dataset(name, confName)

    return raw_datasets


def load_model_and_tokenizer(model_args: ModelArguments):
    config = AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )
    tokenizer = AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
        cache_dir=model_args.cache_dir,
        use_fast=model_args.use_fast_tokenizer,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )
    model = AutoModelForCausalLM.from_pretrained(
        model_args.model_name_or_path,
        from_tf=bool(".ckpt" in model_args.model_name_or_path),
        config=config,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )

    # tokenizer.pad_token = cfg.tokenizer.pad_token
    if tokenizer.pad_token is None and tokenizer.eos_token is not None:
        tokenizer.pad_token = tokenizer.eos_token

    # model = AutoModelForCausalLM.from_pretrained(
    #     name,
    #     from_tf=bool(".ckpt" in name),
    #     config=config,
    # )
    # model.to('cuda')

    # model.resize_token_embeddings(len(tokenizer))

    # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
    # on a small vocab and want a smaller embedding size, remove this test.
    embedding_size = model.get_input_embeddings().weight.shape[0]
    if len(tokenizer) > embedding_size:
        model.resize_token_embeddings(len(tokenizer))

    return tokenizer, model


def preprocess(blockSize, tokenizer, raw_datasets):

    # First we tokenize all the texts.
    column_names = raw_datasets.column_names
    text_column_name = "text" if "text" in column_names else column_names["train"][0]
    if True is True:
        pad = False
    else:
        pad = "max_length"

    def group_texts(examples):
        # print(examples)
        # Concatenate all texts.
        concatenated_examples = {
            k: list(chain(*examples[k])) for k in examples.keys()}
        # print(concatenated_examples)
        total_length = len(concatenated_examples[list(examples.keys())[0]])
        if total_length >= blockSize:
            total_length = (
                total_length // blockSize
            ) * blockSize
        # Split by chunks of max_len.
        result = {
            k: [
                t[i: i + blockSize]
                for i in range(0, total_length, blockSize)
            ]
            for k, t in concatenated_examples.items()
        }
        result["labels"] = result["input_ids"].copy()
        return result

    def tokenize_fn(examples):
        #         result = tokenizer(
        #             examples[text_column_name],
        #             padding=pad,
        #             truncation=True,
        #             max_length=cfg.dataset.block_size,
        #         )
        #         result["labels"] = result["input_ids"].copy()
        #         return result
        return tokenizer(examples[text_column_name])

    tokenized_datasets = raw_datasets.map(
        tokenize_fn,
        batched=True,
        remove_columns=text_column_name,
        load_from_cache_file=not False,
        desc="Running tokenizer on dataset",
    )

    lm_datasets = tokenized_datasets.map(
        group_texts,
        batched=True,
        num_proc=None,
        load_from_cache_file=not False,
        desc=f"Grouping texts in chunks of {blockSize}",
    )

    return lm_datasets


def main():
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
    else:
        model_args, data_args, training_args = parser.parse_args_into_dataclasses()

    # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
    # information sent is the one passed as arguments along with your Python/PyTorch versions.
    send_example_telemetry("run_translation", model_args, data_args)

    # Setup logging
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
        datefmt="%m/%d/%Y %H:%M:%S",
        handlers=[logging.StreamHandler(sys.stdout)],
    )

    log_level = training_args.get_process_log_level()
    logger.setLevel(log_level)
    datasets.utils.logging.set_verbosity(log_level)
    transformers.utils.logging.set_verbosity(log_level)
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()

    # Log on each process the small summary:
    logger.warning(
        f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
        + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
    )
    logger.info(f"Training/evaluation parameters {training_args}")

    tokenizer, model = load_model_and_tokenizer(model_args)
    
    dataset = load_raw_datasets("bittensor", None)
    # dataset = load_raw_datasets("wikitext", "wikitext-2-raw-v1")

    tokenized_datasets = preprocess(2, tokenizer, dataset)
    if "train" not in tokenized_datasets.column_names:
        tokenized_datasets = tokenized_datasets.train_test_split(
            test_size=5 / 100
        )
        tokenized_datasets_test_valid = tokenized_datasets["test"].train_test_split(
            test_size=0.5
        )
        tokenized_datasets["test"] = tokenized_datasets_test_valid["train"]
        tokenized_datasets["validation"] = tokenized_datasets_test_valid["test"]

    train_dataset = tokenized_datasets["train"]
    eval_dataset = tokenized_datasets["validation"]

    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset,
        eval_dataset=eval_dataset,
        # tokenizer=tokenizer,
        # compute_metrics=compute_metrics,
    )

    trainer.train()


if __name__ == "__main__":
    main()`
```

The JSON config I'm using for deepspeed is:
```
{
    "fp16": {
        "enabled": "auto",
        "loss_scale": 0,
        "loss_scale_window": 1000,
        "initial_scale_power": 16,
        "hysteresis": 2,
        "min_loss_scale": 1
    },

    "bf16": {
        "enabled": "auto"
    },

    "optimizer": {
        "type": "AdamW",
        "params": {
            "lr": "auto",
            "betas": "auto",
            "eps": "auto",
            "weight_decay": "auto"
        }
    },

    "scheduler": {
        "type": "WarmupLR",
        "params": {
            "warmup_min_lr": "auto",
            "warmup_max_lr": "auto",
            "warmup_num_steps": "auto"
        }
    },

    "zero_optimization": {
        "stage": 3,
        "offload_optimizer": {
            "device": "none",
            "pin_memory": false
        },
        "offload_param": {
            "device": "none",
            "pin_memory": false
        },
        "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": true
    },

    "gradient_accumulation_steps": "auto",
    "gradient_clipping": "auto",
    "steps_per_print": 2000,
    "train_batch_size": "auto",
    "train_micro_batch_size_per_gpu": "auto",
    "wall_clock_breakdown": false
}
```

My program works great when using a hugging face dataset, however when I try using the bittensor dataset the program always just hangs early on, either while training or while evaluating with nothing obvious appearing in the logs. Any ideas? Is there anything I can do to determine what is causing the hanging? Thanks.

### Expected behavior

The program runs to completion without hanging or at the very least, indicates what is causing the hanging.

Comments:
Your report is almost perfect, @benproton - but how do I run your program?

Please show me the cmd args for both - a good and the hanging run, since until I can reproduce it I can't help you.

Also were you able to use `py-spy` that I linked to yesterday  https://github.com/stas00/toolbox/blob/master/pytorch/torch-distributed-hanging-solutions.md to see where the program hangs? It is surprisingly easy to use.

Sure my bad:
Hanging run with bittensor:
`deepspeed examples/pytorch/translation/run-text-gen.py      --deepspeed tests/deepspeed/ds_config_zero3.json        --model_name_or_path EleutherAI/gpt-neo-1.3B    --output_dir=EleutherAI/gpt-neo-1.3B-aB    --evaluation_strategy steps     --eval_steps 50         --num_train_epochs 4    --dataset_name bittensor        --save_strategy no      --warmup_steps 20       --lr_scheduler_type cosine_with_restarts   --weight_decay 0.2      --learning_rate 0.00006`

In the code I gave I've actually hard-coded the bittensor data set i.e.:
`dataset = load_raw_datasets("bittensor", None)`

For a successful run you can comment that line and uncomment this line below:
`# dataset = load_raw_datasets("wikitext", "wikitext-2-raw-v1")`

Many thanks

Thank you for the remaining information I needed.

Using it I was successful at reproducing the hanging with just 2 gpus and while reducing your setup to a much smaller setup:

```
deepspeed run-text-gen.py --deepspeed ds_config_zero3.json \
--model_name_or_path EleutherAI/gpt-neo-125m \
--output_dir=EleutherAI/gpt-neo-1.3B-aB --evaluation_strategy steps \
--eval_steps 50 --num_train_epochs 4 --dataset_name bittensor --save_strategy \
no --warmup_steps 20 --lr_scheduler_type cosine_with_restarts --weight_decay \
0.2 --learning_rate 0.00006 --per_device_train_batch_size 1 \
--per_device_eval_batch_size 1
```

happened during eval:

```
[INFO|trainer.py:1683] 2023-02-10 19:14:47,595 >> ***** Running training *****
[INFO|trainer.py:1684] 2023-02-10 19:14:47,595 >>   Num examples = 6441
[INFO|trainer.py:1685] 2023-02-10 19:14:47,595 >>   Num Epochs = 4
[INFO|trainer.py:1686] 2023-02-10 19:14:47,595 >>   Instantaneous batch size per device = 1
[INFO|trainer.py:1687] 2023-02-10 19:14:47,595 >>   Total train batch size (w. parallel, distributed & accumulation) = 2
[INFO|trainer.py:1688] 2023-02-10 19:14:47,595 >>   Gradient Accumulation steps = 1
[INFO|trainer.py:1689] 2023-02-10 19:14:47,595 >>   Total optimization steps = 12884
[INFO|trainer.py:1690] 2023-02-10 19:14:47,596 >>   Number of trainable parameters = 0
  0%|▍                                                                                                 | 50/12884 [00:15<58:55,  3.63it/s][INFO|trainer.py:3011] 2023-02-10 19:15:02,688 >> ***** Running Evaluation *****
[INFO|trainer.py:3013] 2023-02-10 19:15:02,688 >>   Num examples = 170
[INFO|trainer.py:3016] 2023-02-10 19:15:02,688 >>   Batch size = 1
                                                                                                                                         60%|████████████████████████████████████████████████████████████▌                                        | 51/85 [00:05<00:03,  9.22it/s]
```

getting `py-spy` traces:
```
Thread 246134 (active): "MainThread"
    _prepare_input (transformers/trainer.py:2518)
    <dictcomp> (transformers/trainer.py:2508)
    _prepare_input (transformers/trainer.py:2508)
    _prepare_inputs (transformers/trainer.py:2526)
    prediction_step (transformers/trainer.py:3273)
    evaluation_loop (transformers/trainer.py:3056)
    evaluate (transformers/trainer.py:2875)
    _maybe_log_save_evaluate (transformers/trainer.py:2180)
    _inner_training_loop (transformers/trainer.py:1920)
    train (transformers/trainer.py:1576)
    main (run-text-gen.py:461)
    <module> (run-text-gen.py:465)
Thread 246240 (idle): "Thread-1"
    wait (threading.py:306)
    wait (threading.py:558)
    run (tqdm/_monitor.py:60)
    _bootstrap_inner (threading.py:932)
    _bootstrap (threading.py:890)
Thread 246551 (idle): "Thread-3"
    wait (threading.py:306)
    wait (threading.py:558)
    run (tqdm/_monitor.py:60)
    _bootstrap_inner (threading.py:932)
    _bootstrap (threading.py:890)
Thread 246733 (idle): "Thread-4"
    wait (threading.py:306)
    get (queue.py:179)
    run (tensorboard/summary/writer/event_file_writer.py:227)
    _bootstrap_inner (threading.py:932)
    _bootstrap (threading.py:890)
Thread 246735 (idle): "APScheduler"
    wait (threading.py:306)
    wait (threading.py:558)
    _main_loop (apscheduler/schedulers/blocking.py:30)
    run (threading.py:870)
    _bootstrap_inner (threading.py:932)
    _bootstrap (threading.py:890)
Thread 246739 (idle)
Thread 246740 (idle)
Thread 246793 (idle): "ThreadPoolExecutor-2_0"
    _worker (concurrent/futures/thread.py:78)
    run (threading.py:870)
    _bootstrap_inner (threading.py:932)
    _bootstrap (threading.py:890)
    
    
Thread 246135 (idle): "MainThread"
    backward (torch/autograd/__init__.py:197)
    backward (torch/_tensor.py:488)
    backward (deepspeed/runtime/fp16/loss_scaler.py:51)
    backward (deepspeed/runtime/zero/stage3.py:2096)
    wrapped_fn (deepspeed/utils/nvtx.py:9)
    backward (deepspeed/runtime/engine.py:1968)
    wrapped_fn (deepspeed/utils/nvtx.py:9)
    training_step (transformers/trainer.py:2604)
    _inner_training_loop (transformers/trainer.py:1843)
    train (transformers/trainer.py:1576)
    main (run-text-gen.py:461)
    <module> (run-text-gen.py:465)
Thread 246251 (idle): "Thread-1"
    wait (threading.py:306)
    wait (threading.py:558)
    run (tqdm/_monitor.py:60)
    _bootstrap_inner (threading.py:932)
    _bootstrap (threading.py:890)
Thread 246533 (idle): "Thread-3"
    wait (threading.py:306)
    wait (threading.py:558)
    run (tqdm/_monitor.py:60)
    _bootstrap_inner (threading.py:932)
    _bootstrap (threading.py:890)
Thread 246741 (idle)
Thread 246742 (active)
    synchronize (torch/cuda/streams.py:219)
    __reduce_and_partition_ipg_grads (deepspeed/runtime/zero/stage3.py:1153)
    decorate_context (torch/autograd/grad_mode.py:27)
    wrapped_fn (deepspeed/utils/nvtx.py:9)
    reduce_independent_p_g_buckets_and_remove_grads (deepspeed/runtime/zero/stage3.py:1102)
    reduce_ready_partitions_and_remove_grads (deepspeed/runtime/zero/stage3.py:1342)
    reduce_partition_and_remove_grads (deepspeed/runtime/zero/stage3.py:1066)
    wrapped_fn (deepspeed/utils/nvtx.py:9)    
```

So this is some sort of gpu synchronization issue.

As you can see one of the processes is in training, while the other is in eval stages which is very wrong and doesn't make much sense.

I have never seen this sort of hanging.

I will try to analyse it when I get a chance and get back to you, @benproton 



ok, the hanging has nothing to do with deepspeed, you can set it to `"stage": 0,` which completely disables deepspeed and it still hangs in eval. This looks more like some kind of network issue where it blocks on fetching new data but no new data comes.

`bitternsor`appears to have issues itself, as when you kill the main process it continues running multiple python processes. 

so please feel free to close the issue, since your hanging isn't an issue in Transformers or Deepspeed.

And I gave you information on how to debug this on your own if you'd like to proceed with figuring it out.

Ok, got it, @stas00 thank you for investigating. Happy to close the issue but out of interest, here is the original script I've been trying to adapt to deepspeed/Trainer:  https://github.com/opentensor/clm_model_tuning/blob/320145eb796dd1c28916245a294d9bfa8578bf5a/finetune_using_clm.py

If there's anything glaring you can see I'm getting wrong or if there's any additional pointers you can think of I'd be truly grateful. Thanks again.

I'm not sure you understand what the problem is - the issue isn't on your side - the issue is on the bittensor side - you're not using a normal dataset, but a network-based one - so it predownloads some data at the start and then later it blocks not giving any data to the evaluator or trainer. 


```
Thread 246134 (active): "MainThread"
    _prepare_input (transformers/trainer.py:2518)
    <dictcomp> (transformers/trainer.py:2508)
    _prepare_input (transformers/trainer.py:2508)
    _prepare_inputs (transformers/trainer.py:2526)
    prediction_step (transformers/trainer.py:3273)
    evaluation_loop (transformers/trainer.py:3056)
```

it is waiting for the worker to feed it data.

That's also why it's inconsistent and appears to hang in a different place every time

so it is possible that if you wait for a long time it'll unblock 

The simplest test is to just use the dataloader alone in a short script and drain it fast iterating over the batches - I'm 99% sure it'll hang too. I think it's a good experiment to run.

> here is the original script

Accelerate supports deepspeed - same setup, so you can use the original script with deepspeed no problem. https://huggingface.co/docs/accelerate/usage_guides/deepspeed

Ahhhh... finally got it now thanks. I'll look into getting it locally. I learn something new with each of your comments, appreciated man.