ray-project / ray

Ray is an AI compute engine. Ray consists of a core distributed runtime and a set of AI Libraries for accelerating ML workloads.
https://ray.io
Apache License 2.0
33.99k stars 5.78k forks source link

RuntimeError: Expected to mark a variable ready only once. #43296

Closed echzhai closed 6 months ago

echzhai commented 8 months ago

What happened + What you expected to happen

if i run fine tuning without ray, it works. but if i use ray, i will get 2024-02-20 21:43:02,050 ERROR tune_controller.py:1374 -- Trial task failed for trial TorchTrainer_8c08f_00000 Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/ray/air/execution/_internal/event_manager.py", line 110, in resolve_future result = ray.get(future) File "/usr/local/lib/python3.8/site-packages/ray/_private/auto_init_hook.py", line 22, in auto_init_wrapper return fn(*args, kwargs) File "/usr/local/lib/python3.8/site-packages/ray/_private/client_mode_hook.py", line 103, in wrapper return func(*args, *kwargs) File "/usr/local/lib/python3.8/site-packages/ray/_private/worker.py", line 2624, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError(RuntimeError): ray::_Inner.train() (pid=18374, ip=192.168.236.20, actor_id=6d35f3067f42e27c7332f0add2000000, repr=TorchTrainer) File "/usr/local/lib/python3.8/site-packages/ray/tune/trainable/trainable.py", line 342, in train raise skipped from exception_cause(skipped) File "/usr/local/lib/python3.8/site-packages/ray/train/_internal/utils.py", line 43, in check_for_failure ray.get(object_ref) ray.exceptions.RayTaskError(RuntimeError): ray::_RayTrainWorkerexecute.get_next() (pid=18430, ip=192.168.236.20, actor_id=d38d2fa719c30e8683c347cdd2000000, repr=<ray.train._internal.worker_group.RayTrainWorker object at 0x7f53f43c5dc0>) File "/usr/local/lib/python3.8/site-packages/ray/train/_internal/worker_group.py", line 33, in execute raise skipped from exception_cause(skipped) File "/usr/local/lib/python3.8/site-packages/ray/train/_internal/utils.py", line 118, in discard_return_wrapper train_func(args, kwargs) File "train-colab.py", line 98, in train_func trainer.train() File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/trl/trainer/sft_trainer.py", line 331, in train output = super().train(args, kwargs) File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/transformers/trainer.py", line 1539, in train return inner_training_loop( File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/transformers/trainer.py", line 1869, in _inner_training_loop tr_loss_step = self.training_step(model, inputs) File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/transformers/trainer.py", line 2781, in training_step self.accelerator.backward(loss) File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/accelerate/accelerator.py", line 1966, in backward loss.backward(kwargs) File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/torch/_tensor.py", line 522, in backward torch.autograd.backward( File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/torch/autograd/init.py", line 266, in backward Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/torch/autograd/function.py", line 289, in apply return user_fn(self, args) File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/torch/utils/checkpoint.py", line 319, in backward torch.autograd.backward(outputs_with_grad, args_with_grad) File "/tmp/ray/session_2024-02-15_19-25-10_223548_21/runtime_resources/pip/76b53ca467e56ecaa61f8563fec3d519a6155603/virtualenv/lib/python3.8/site-packages/torch/autograd/init.py", line 266, in backward Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass RuntimeError: Expected to mark a variable ready only once. This error is caused by one of the following reasons: 1) Use of a module parameter outside the forward function. Please make sure model parameters are not shared across multiple concurrent forward-backward passes. or try to use _set_static_graph() as a workaround if this module graph does not change during training loop.2) Reused parameters in multiple reentrant backward passes. For example, if you use multiple checkpoint functions to wrap the same part of your model, it would result in the same set of parameters been used by different reentrant backward passes multiple times, and hence marking a variable ready multiple times. DDP does not support such use cases in default. You can try to use _set_static_graph() as a workaround if your module graph does not change over iterations. Parameter at index 319 with name base_model.model.model.layers.31.mlp.gate_proj.lora_B.default.weight has been marked as ready twice. This means that multiple autograd engine hooks have fired for this particular parameter during this iteration.

Versions / Dependencies

ray 2.9.2

Reproduction script

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,HfArgumentParser,TrainingArguments,pipeline, logging, TextStreamer
from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training, get_peft_model
import os,torch, platform, warnings
from datasets import load_dataset
from trl import SFTTrainer
from huggingface_hub import notebook_login

import ray.train
from ray.train.huggingface.transformers import prepare_trainer, RayTrainReportCallback

import ray.train.huggingface.transformers
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer

def train_func(config):
    base_model, dataset_name, new_model = "mistralai/Mistral-7B-v0.1" , "gathnex/Gath_baize", "gathnex/Gath_mistral_7b"

    #Importing the dataset
    dataset = load_dataset(dataset_name, split="train")

    # Load base model(Mistral 7B)
    bnb_config = BitsAndBytesConfig(
        load_in_4bit= True,
        bnb_4bit_quant_type= "nf4",
        bnb_4bit_compute_dtype= torch.bfloat16,
        bnb_4bit_use_double_quant= False,
    )
    model = AutoModelForCausalLM.from_pretrained(
       base_model,
        quantization_config=bnb_config,
        device_map={"": 0}
    )
    model.config.use_cache = False # silence the warnings. Please re-enable for inference!
    #model.config.pretraining_tp = 1

    # Load tokenizer
    tokenizer = AutoTokenizer.from_pretrained(base_model,model_max_length=512,trust_remote_code=True)
    tokenizer.padding_side = 'right'
    tokenizer.pad_token = tokenizer.eos_token
    tokenizer.add_eos_token = True
    tokenizer.add_bos_token, tokenizer.add_eos_token

    #Adding the adapters in the layers
    model.gradient_checkpointing_enable()
    model = prepare_model_for_kbit_training(model)
    peft_config = LoraConfig(
            r=8,
            lora_alpha=16,
            lora_dropout=0.05,
            bias="none",
            task_type="CAUSAL_LM",
            target_modules=["q_proj", "k_proj", "v_proj", "o_proj","gate_proj"]
        )
    model = get_peft_model(model, peft_config)

    #Hyperparamter
    training_arguments = TrainingArguments(
        output_dir= "results",
        num_train_epochs= 2,
        per_device_train_batch_size= 8,
        gradient_accumulation_steps= 2,
        optim = "paged_adamw_8bit",
        save_steps= 100,
        logging_steps= 30,
        learning_rate= 2e-4,
        weight_decay= 0.001,
        bf16= True,
        max_grad_norm= 0.3,
        max_steps= -1,
        warmup_ratio= 0.3,
        group_by_length= True,
        lr_scheduler_type= "constant",
    )
    # Hugging Face Trainer
    training_arguments = TrainingArguments(
        output_dir="test_trainer",
        evaluation_strategy="epoch",
        save_strategy="epoch",
        report_to="none",
    )

    # Setting sft parameters
    trainer = SFTTrainer(
        model=model,
        train_dataset=dataset,
        peft_config=peft_config,
        max_seq_length= None,
        dataset_text_field="chat_sample",
        tokenizer=tokenizer,
        args=training_arguments,
        packing= False,
    )
    trainer.add_callback(RayTrainReportCallback())
    trainer = prepare_trainer(trainer)

    print("Starting training")
    trainer.train()

trainer = TorchTrainer(
        train_func,
        #train_loop_config=config,
        #datasets=ray_datasets,
        #dataset_config=DataConfig(datasets_to_split=["train", "validation"]),
        scaling_config=ScalingConfig(num_workers=4, resources_per_worker={
            "CPU": 4,
            "GPU": 1,
        },
        trainer_resources={
          "CPU": 0,
          "GPU": 0,
        },use_gpu=True),
        # If running in a multi-node cluster, this is where you
        # should configure the run's persistent storage that is accessible
        # across all worker nodes.
        run_config=ray.train.RunConfig(storage_path="/data/ray/storage/"),
    )

result = trainer.fit()

Issue Severity

None

woshiyyya commented 6 months ago

Hi @echzhai , does it happens during checkpointing? Can you remove the RayTrainReportCallback and see if it works?

echzhai commented 6 months ago

the problem sovled after I add below two line of codes: gradient_checkpointing=True, gradient_checkpointing_kwargs={'use_reentrant':False},