Skip to content

Qwen3_VL_(8B)-Vision-GRPO.ipynb failed when use multiple GPUs #3914

Closed

Description

@dajuanmaoa

I used my own dataset for GRPO training. When I use a single GPU with the command CUDA_VISIBLE_DEVICES=1 torchrun --nproc_per_node=1 train/train_unsloth_qwen3-2b.py, the training completes successfully.
However, when I try to use multiple GPUs, CUDA_VISIBLE_DEVICES=1,2 torchrun --nproc_per_node=2 trian/train_unsloth_qwen3-2b.py。 I encounter the following error, and I'm not sure where the issue lies.

Dataset preparation complete!
Final dataset features: {'describe': {'结论': Value('string'), '详细描述': Value('string')}, 'answer': Value('string'), 'image': Image(mode=None, decode=True), 'prompt': List({'content': List({'text': Value('string'), 'type': Value('string')}), 'role': Value('string')})}

Example of a processed data entry:
==((====))==  Unsloth 2026.1.2: Fast Qwen3_Vl patching. Transformers: 4.57.1. vLLM: 0.13.0.
   \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 2. Max memory: 23.643 GB. Platform: Linux.
O^O/ \_/ \    Torch: 2.9.0+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.0
\        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post1. FA2 = True]
 "-____-"     Free license: http://github.com/unslothai/unsloth
Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
==((====))==  Unsloth 2026.1.2: Fast Qwen3_Vl patching. Transformers: 4.57.1. vLLM: 0.13.0.
   \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 2. Max memory: 23.643 GB. Platform: Linux.
O^O/ \_/ \    Torch: 2.9.0+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.0
\        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post1. FA2 = True]
 "-____-"     Free license: http://github.com/unslothai/unsloth
Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!

============================================================
开始训练
============================================================
[rank1]: Traceback (most recent call last):
[rank1]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 885, in <module>
[rank1]:     trainer.train()
[rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 63, in wrapper
[rank1]:     output = f(self, *args, **kwargs)
[rank1]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
[rank1]:     return inner_training_loop(
[rank1]:   File "<string>", line 128, in _fast_inner_training_loop
[rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1559, in prepare
[rank1]:     result = tuple(
[rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1560, in <genexpr>
[rank1]:     self._prepare_one(obj, first_pass=True, device_placement=d) for obj, d in zip(args, device_placement)
[rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1402, in _prepare_one
[rank1]:     return self.prepare_model(obj, device_placement=device_placement)
[rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1816, in prepare_model
[rank1]:     raise ValueError(
[rank1]: ValueError: You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`
[accelerate.utils.other|WARNING]Detected kernel version 3.10.0, which is below the recommended minimum of 5.5.0; this can cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher.

============================================================
开始训练
============================================================
The model is already on multiple devices. Skipping the move to device specified in `args`.
W0121 01:29:31.987000 11775 torch/distributed/elastic/multiprocessing/api.py:908] Sending process 11848 closing signal SIGTERM
E0121 01:29:32.554000 11775 torch/distributed/elastic/multiprocessing/api.py:882] failed (exitcode: 1) local_rank: 1 (pid: 11849) of binary: /usr/bin/python
Traceback (most recent call last):
  File "/usr/local/bin/torchrun", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.10/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 357, in wrapper
    return f(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 936, in main
    run(args)
  File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 927, in run
    elastic_launch(
  File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 156, in __call__
    return launch_agent(self._config, self._entrypoint, list(args))
  File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 293, in launch_agent
    raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
============================================================
trian/train_unsloth_qwen3-2b.py FAILED
------------------------------------------------------------
Failures:
  <NO_OTHER_FAILURES>
------------------------------------------------------------
Root Cause (first observed failure):
[0]:
  time      : 2026-01-21_01:29:31
  host      : 7_153
  rank      : 1 (local_rank: 1)
  exitcode  : 1 (pid: 11849)
  error_file: <N/A>
  traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html

Here is my complete code.

def load_and_prepare_power_safety_dataset(
    jsonl_path, 
    image_size=(512, 512), 
    split="train",
):
    
    # 1. --- 加载原始JSONL数据 ---
    # 使用 "imagefolder" 可以方便地让datasets库知道这是一个与图像相关的本地数据集
    # 确保您的jsonl文件和图像文件在同一个目录结构下,或者使用绝对路径
    print("Step 1: Loading raw JSONL dataset...")
    dataset_dict = load_test_data(jsonl_path,split)
    dataset_dict = Dataset.from_list(dataset_dict)
    # 从 DatasetDict 中选择指定的 split
    if isinstance(dataset_dict, dict):
        dataset = dataset_dict[split]
    else:
        # 如果返回的是单个 Dataset,直接使用
        dataset = dataset_dict

    # 2. --- 图像预处理 ---
    # 包括加载、转换色彩空间(RGB)和调整尺寸
    def preprocess_image(example):
        # 从文件路径加载图像为PIL对象
        image = Image.open(example["images"])
        
        # 确保图像是RGB格式,这是所有VLM训练的标准要求
        if image.mode != "RGB":
            image = image.convert("RGB")
        
        # 调整图像尺寸以统一输入大小,节省显存
        #image = image.resize(image_size)
        
        # 将处理好的PIL Image对象放入一个新的'image'列
        example["image"] = image
        return example

    print(f"Step 2: Preprocessing images to size {image_size} and RGB format...")
    dataset = dataset.map(preprocess_image)

    # 3. --- 构建对话模板 ---
    # 这是最关键的一步,它定义了模型要学习的任务格式
    # GRPO 训练需要 prompt 字段,而不是 conversations 字段

    def create_structured_conversation(example):
        # a. 构建用户的提问文本
        # 我们引导模型先给结论,再给理由,并使用特定标签包裹
        user_prompt_text = (f"{example['question']}\n"
        f"请先在 {CONCLUSION_START} 和 {CONCLUSION_END} 标签之间给出'是的'或'否'的结论,"
        f"然后在 {REASON_START} 和 {REASON_END} 标签之间给出详细的理由。")
      
        # b. 构建 GRPO 所需的 prompt 格式(role/content 格式)
        # 参考代码中的格式,使用 role: "user" 和 content 数组
        prompt = [
            {
                "role": "user",
                "content": [
                    {"type": "image"},  # 图像占位符
                    {"type": "text", "text": user_prompt_text},  # 文本内容
                ],
            },
        ]
        
        # c. 保存 prompt、image 和用于 reward 函数的字段
        example["prompt"] = prompt
        example["answer"] = example['answer']  # 保留用于 reward 函数
        example["describe"] = example['describe']  # 保留用于 reward 函数
        return example
        #return {"prompt": prompt, "image": example["images"], "answer": example["answer"],"describe": example['describe']}


    print("Step 3: Creating structured conversational template...")
    dataset = dataset.map(create_structured_conversation)
    
    # 4. --- 清理不必要的列 ---
    # 保持数据集整洁,只留下训练所需的字段
    print("Step 4: Cleaning up dataset columns...")
    # 获取原始所有列名
    original_columns = list(dataset.features)
    # 计算需要保留的列
    columns_to_keep = ["image", "prompt", "answer", "describe"]
    # 计算需要移除的列
    columns_to_remove = [col for col in original_columns if col not in columns_to_keep]
    if "image" not in original_columns: # 如果原始数据没有image列(比如只有images),避免报错
        columns_to_remove.append("images")
    
    dataset = dataset.remove_columns(list(set(columns_to_remove)))


    print("\nDataset preparation complete!")
    print("Final dataset features:", dataset.features)
    print("\nExample of a processed data entry:")
    #print(dataset[0])
    
    return dataset
train_dataset = load_and_prepare_power_safety_dataset(jsonl_path=train_dir,split="train")
test_dataset = load_and_prepare_power_safety_dataset(jsonl_path=test_dir,split="test")

model, tokenizer = FastVisionModel.from_pretrained(
    model_name = "/data/models/unsloth/Qwen3-VL-2B-Instruct",
    max_seq_length = max_seq_length,
    load_in_4bit = True,#False, # False for LoRA 16bit
    fast_inference = False, # Enable vLLM fast inference
    gpu_memory_utilization = 0.9, # Reduce if out of memory
    local_files_only = True, # 只使用本地文件,不连接 HuggingFace
    #device_map = "balanced",
    #device_map = {'':torch.cuda.current_device()}
    #prepare_for_finetuning_ddp=True,
)

"""In Unsloth, we share vLLM's weights directly, reducing VRAM usage by > 50%. vLLM also does not yet support LoRA on the vision layers, so we can only add them on the language layers. Vision GRPO still works though!"""

model = FastVisionModel.get_peft_model(
    model,
    finetune_vision_layers     = False, # False if not finetuning vision layers
    finetune_language_layers   = True,  # False if not finetuning language layers
    finetune_attention_modules = True,  # False if not finetuning attention layers
    finetune_mlp_modules       = True,  # False if not finetuning MLP layers

    r = 16,           # The larger, the higher the accuracy, but might overfit
    lora_alpha = 16,  # Recommended alpha == r at least
    lora_dropout = 0,
    bias = "none",
    random_state = 3407,
    use_rslora = False,  # We support rank stabilized LoRA
    loftq_config = None, # And LoftQ
    use_gradient_checkpointing = "unsloth", # Reduces memory usage
   # use_gradient_checkpointing = False,
    # target_modules = "all-linear", # Optional now! Can specify a list if needed
)

# image = train_dataset[100]["image"]
# prompt = train_dataset[100]["prompt"]
# inputs = tokenizer(
#     image,
#     prompt,
#     add_special_tokens = False,
#     return_tensors = "pt",
# ).to("cuda")

# from transformers import TextStreamer
# text_streamer = TextStreamer(tokenizer, skip_prompt = True)
# _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 1024,
#                    use_cache = True, temperature = 1.0, min_p = 0.1)


from trl import GRPOConfig, GRPOTrainer

# 配置训练参数
training_args = GRPOConfig(
    learning_rate = 5e-6,
    adam_beta1 = 0.9,
    adam_beta2 = 0.99,
    weight_decay = 0.1,
    warmup_ratio = 0.1,
    lr_scheduler_type = "cosine",
    optim = "adamw_8bit",
    logging_steps = 1,
    log_completions = False,
    per_device_train_batch_size = 4,
    per_device_eval_batch_size = 4,
    gradient_accumulation_steps = 1,
    num_generations = 2,
    max_prompt_length = 1024,
    max_completion_length = 1024,
    num_train_epochs = 3,
    save_steps = 10,  # 每60步保存一次并测试
    do_eval = True,
    eval_steps =10,
    eval_strategy ="steps",
    load_best_model_at_end=True,
    metric_for_best_model="eval_loss",
    max_grad_norm = 0.1,
    report_to = "tensorboard",  # 使用 TensorBoard 保存训练曲线
    output_dir = os.path.join(run_output_dir, "checkpoints"),  # Checkpoint 保存目录
    logging_dir = os.path.join(run_output_dir, "logs"),  # TensorBoard 日志目录

    # Below enables GSPO:
    importance_sampling_level = "sequence",
    mask_truncated_completions = False,
    loss_type = "dr_grpo",
)

# # 创建自定义 Callback(直接传入 model 和 tokenizer)
# best_checkpoint_callback = BestCheckpointCallback(
#     test_dir=test_data_dir,
#     output_dir=run_output_dir,
#     model=model,
#     tokenizer=tokenizer,
#     max_samples=100  # 每次测试使用100个样本
# )

# 创建 Trainer
trainer = GRPOTrainer(
    model = model,
    args = training_args,
    processing_class = tokenizer,
    reward_funcs = [
        formatting_reward_func,
        correctness_reward_func,
    ],
    train_dataset = train_dataset,
    eval_dataset = test_dataset,
    #callbacks = [best_checkpoint_callback],  # 添加自定义 Callback
)

# 训练模型
print(f"\n{'='*60}")
print("开始训练")
print(f"{'='*60}")
trainer.train()

Activity

  1. Datta0 commented on Jan 21, 2026

    @Datta0
    Contributor

    Hey @dajuanmaoa this might be a restriction from accelerate? It says

    ValueError: You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`
    

    You might want to set load_in_4bit=False and try?
    Let me know if you face errors even after that

  2. dajuanmaoa commented on Jan 29, 2026

    @dajuanmaoa
    Author

    Hey @dajuanmaoa this might be a restriction from accelerate? It says

    ValueError: You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`
    

    You might want to set load_in_4bit=False and try? Let me know if you face errors even after that

    I try load_in_4bit=False The errors that occurred look the same to me. And I am not using a quantized model; I am using Qwen3-VL-2B-Instruct

    Example of a processed data entry:
    ==((====))==  Unsloth 2026.1.2: Fast Qwen3_Vl patching. Transformers: 4.57.1. vLLM: 0.13.0.
       \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 2. Max memory: 23.643 GB. Platform: Linux.
    O^O/ \_/ \    Torch: 2.9.0+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.0
    \        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post1. FA2 = True]
     "-____-"     Free license: http://github.com/unslothai/unsloth
    Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
    ==((====))==  Unsloth 2026.1.2: Fast Qwen3_Vl patching. Transformers: 4.57.1. vLLM: 0.13.0.
       \\   /|    NVIDIA GeForce RTX 4090. Num GPUs = 2. Max memory: 23.643 GB. Platform: Linux.
    O^O/ \_/ \    Torch: 2.9.0+cu128. CUDA: 8.9. CUDA Toolkit: 12.8. Triton: 3.5.0
    \        /    Bfloat16 = TRUE. FA [Xformers = 0.0.33.post1. FA2 = True]
     "-____-"     Free license: http://github.com/unslothai/unsloth
    Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
    [accelerate.utils.other|WARNING]Detected kernel version 3.10.0, which is below the recommended minimum of 5.5.0; this can cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher.
    
    ============================================================
    开始训练
    ============================================================
    [rank1]: Traceback (most recent call last):
    [rank1]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 885, in <module>
    [rank1]:     trainer.train()
    [rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 63, in wrapper
    [rank1]:     output = f(self, *args, **kwargs)
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
    [rank1]:     return inner_training_loop(
    [rank1]:   File "<string>", line 128, in _fast_inner_training_loop
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1559, in prepare
    [rank1]:     result = tuple(
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1560, in <genexpr>
    [rank1]:     self._prepare_one(obj, first_pass=True, device_placement=d) for obj, d in zip(args, device_placement)
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1402, in _prepare_one
    [rank1]:     return self.prepare_model(obj, device_placement=device_placement)
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/accelerate/accelerator.py", line 1816, in prepare_model
    [rank1]:     raise ValueError(
    [rank1]: ValueError: You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`
    
    ============================================================
    开始训练
    ============================================================
    The model is already on multiple devices. Skipping the move to device specified in `args`.
    W0129 01:14:50.058000 72211 torch/distributed/elastic/multiprocessing/api.py:908] Sending process 72277 closing signal SIGTERM
    E0129 01:14:50.574000 72211 torch/distributed/elastic/multiprocessing/api.py:882] failed (exitcode: 1) local_rank: 1 (pid: 72278) of binary: /usr/bin/python
    Traceback (most recent call last):
      File "/usr/local/bin/torchrun", line 8, in <module>
        sys.exit(main())
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 357, in wrapper
        return f(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 936, in main
        run(args)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 927, in run
        elastic_launch(
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 156, in __call__
        return launch_agent(self._config, self._entrypoint, list(args))
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 293, in launch_agent
        raise ChildFailedError(
    torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
    ============================================================
    trian/train_unsloth_qwen3-2b.py FAILED
    
  3. ChengHu98 commented on Feb 3, 2026

    @ChengHu98

    Is multi-GPU GRPO with vllm=True actually working for anyone, or is it currently unsupported?

  4. dajuanmaoa commented on Feb 3, 2026

    @dajuanmaoa
    Author

    Is multi-GPU GRPO with vllm=True actually working for anyone, or is it currently unsupported?

    After adding vllm=Trueto the GRPOTrainer, I encountered the following error:AttributeError: 'DistributedDataParallel' object has no attribute 'config',and I am using the latest version of the Unsloth library.

    pip list
    unsloth                           2026.1.4
    unsloth_zoo                       2026.1.4
    torch                             2.9.0
    torch-tensorrt                    2.3.0a0
    torchao                           0.15.0
    torchaudio                        2.9.0
    torchdata                         0.7.1a0
    torchtext                         0.17.0a0
    torchvision                       0.24.0
    transformer-engine                1.3.0+5b90b7f
    transformers                      4.57.1
    
    # 创建 Trainer
    trainer = GRPOTrainer(
        model = model,
        args = training_args,
        processing_class = tokenizer,
        reward_funcs = [
            formatting_reward_func,
            correctness_reward_func,
        ],
        train_dataset = train_dataset,
        eval_dataset = test_dataset,
        vllm=True
        # 移除 max_seq_length=50000,避免与内部逻辑冲突
        #callbacks = [best_checkpoint_callback],  # 添加自定义 Callback
    )
    
    ============================================================
    开始训练
    ============================================================
    The model is already on multiple devices. Skipping the move to device specified in `args`.
    Unsloth is running with multi GPUs - the effective batch size is multiplied by 2
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 480 | Num Epochs = 3 | Total steps = 360
    O^O/ \_/ \    Batch size per device = 4 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 2 | Total batch size (4 x 1 x 2) = 8
     "-____-"     Trainable parameters = 17,432,576 of 2,144,964,608 (0.81% trained)
    Unsloth is running with multi GPUs - the effective batch size is multiplied by 2
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 480 | Num Epochs = 3 | Total steps = 360
    O^O/ \_/ \    Batch size per device = 4 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 2 | Total batch size (4 x 1 x 2) = 8
     "-____-"     Trainable parameters = 17,432,576 of 2,144,964,608 (0.81% trained)
      0%|                                                                   | 0/360 [00:00<?, ?it/s]`generation_config` default values have been modified to match model-specific defaults: {'temperature': 0.7, 'top_p': 0.8}. If this is not desired, please set these values explicitly.
    `generation_config` default values have been modified to match model-specific defaults: {'temperature': 0.7, 'top_p': 0.8}. If this is not desired, please set these values explicitly.
    [rank1]: Traceback (most recent call last):
    [rank1]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 919, in <module>
    [rank1]:     trainer.train()
    [rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 64, in wrapper
    [rank1]:     output = f(self, *args, **kwargs)
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
    [rank1]:     return inner_training_loop(
    [rank1]:   File "<string>", line 328, in _fast_inner_training_loop
    [rank1]:   File "<string>", line 40, in _unsloth_training_step
    [rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3409, in compute_loss
    [rank1]:     logit_softcapping = getattr(model.config, "final_logit_softcapping", 0)  # Gemma
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1964, in __getattr__
    [rank1]:     raise AttributeError(
    [rank1]: AttributeError: 'DistributedDataParallel' object has no attribute 'config'
    [rank0]: Traceback (most recent call last):
    [rank0]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 919, in <module>
    [rank0]:     trainer.train()
    [rank0]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 64, in wrapper
    [rank0]:     output = f(self, *args, **kwargs)
    [rank0]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
    [rank0]:     return inner_training_loop(
    [rank0]:   File "<string>", line 328, in _fast_inner_training_loop
    [rank0]:   File "<string>", line 40, in _unsloth_training_step
    [rank0]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3409, in compute_loss
    [rank0]:     logit_softcapping = getattr(model.config, "final_logit_softcapping", 0)  # Gemma
    [rank0]:   File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1964, in __getattr__
    [rank0]:     raise AttributeError(
    [rank0]: AttributeError: 'DistributedDataParallel' object has no attribute 'config'
    [rank0]:[W203 06:29:04.635676507 ProcessGroupNCCL.cpp:1524] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())
    W0203 06:29:05.519000 2809 torch/distributed/elastic/multiprocessing/api.py:908] Sending process 2875 closing signal SIGTERM
    E0203 06:29:06.036000 2809 torch/distributed/elastic/multiprocessing/api.py:882] failed (exitcode: 1) local_rank: 1 (pid: 2876) of binary: /usr/bin/python
    Traceback (most recent call last):
      File "/usr/local/bin/torchrun", line 8, in <module>
        sys.exit(main())
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 357, in wrapper
        return f(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 936, in main
        run(args)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 927, in run
        elastic_launch(
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 156, in __call__
        return launch_agent(self._config, self._entrypoint, list(args))
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 293, in launch_agent
        raise ChildFailedError(
    torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
    ============================================================
    trian/train_unsloth_qwen3-2b.py FAILED
    ------------------------------------------------------------
    Failures:
      <NO_OTHER_FAILURES>
    ------------------------------------------------------------
    Root Cause (first observed failure):
    [0]:
      time      : 2026-02-03_06:29:05
      host      : 7_153
      rank      : 1 (local_rank: 1)
      exitcode  : 1 (pid: 2876)
      error_file: <N/A>
      traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html
    ============================================================
    
  5. ChengHu98 commented on Feb 3, 2026

    @ChengHu98

    Is multi-GPU GRPO with vllm=True actually working for anyone, or is it currently unsupported?

    After adding vllm=Trueto the GRPOTrainer, I encountered the following error:AttributeError: 'DistributedDataParallel' object has no attribute 'config',and I am using the latest version of the Unsloth library.

    pip list
    unsloth                           2026.1.4
    unsloth_zoo                       2026.1.4
    torch                             2.9.0
    torch-tensorrt                    2.3.0a0
    torchao                           0.15.0
    torchaudio                        2.9.0
    torchdata                         0.7.1a0
    torchtext                         0.17.0a0
    torchvision                       0.24.0
    transformer-engine                1.3.0+5b90b7f
    transformers                      4.57.1
    
    # 创建 Trainer
    trainer = GRPOTrainer(
        model = model,
        args = training_args,
        processing_class = tokenizer,
        reward_funcs = [
            formatting_reward_func,
            correctness_reward_func,
        ],
        train_dataset = train_dataset,
        eval_dataset = test_dataset,
        vllm=True
        # 移除 max_seq_length=50000,避免与内部逻辑冲突
        #callbacks = [best_checkpoint_callback],  # 添加自定义 Callback
    )
    
    ============================================================
    开始训练
    ============================================================
    The model is already on multiple devices. Skipping the move to device specified in `args`.
    Unsloth is running with multi GPUs - the effective batch size is multiplied by 2
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 480 | Num Epochs = 3 | Total steps = 360
    O^O/ \_/ \    Batch size per device = 4 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 2 | Total batch size (4 x 1 x 2) = 8
     "-____-"     Trainable parameters = 17,432,576 of 2,144,964,608 (0.81% trained)
    Unsloth is running with multi GPUs - the effective batch size is multiplied by 2
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 480 | Num Epochs = 3 | Total steps = 360
    O^O/ \_/ \    Batch size per device = 4 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 2 | Total batch size (4 x 1 x 2) = 8
     "-____-"     Trainable parameters = 17,432,576 of 2,144,964,608 (0.81% trained)
      0%|                                                                   | 0/360 [00:00<?, ?it/s]`generation_config` default values have been modified to match model-specific defaults: {'temperature': 0.7, 'top_p': 0.8}. If this is not desired, please set these values explicitly.
    `generation_config` default values have been modified to match model-specific defaults: {'temperature': 0.7, 'top_p': 0.8}. If this is not desired, please set these values explicitly.
    [rank1]: Traceback (most recent call last):
    [rank1]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 919, in <module>
    [rank1]:     trainer.train()
    [rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 64, in wrapper
    [rank1]:     output = f(self, *args, **kwargs)
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
    [rank1]:     return inner_training_loop(
    [rank1]:   File "<string>", line 328, in _fast_inner_training_loop
    [rank1]:   File "<string>", line 40, in _unsloth_training_step
    [rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3409, in compute_loss
    [rank1]:     logit_softcapping = getattr(model.config, "final_logit_softcapping", 0)  # Gemma
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1964, in __getattr__
    [rank1]:     raise AttributeError(
    [rank1]: AttributeError: 'DistributedDataParallel' object has no attribute 'config'
    [rank0]: Traceback (most recent call last):
    [rank0]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 919, in <module>
    [rank0]:     trainer.train()
    [rank0]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 64, in wrapper
    [rank0]:     output = f(self, *args, **kwargs)
    [rank0]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
    [rank0]:     return inner_training_loop(
    [rank0]:   File "<string>", line 328, in _fast_inner_training_loop
    [rank0]:   File "<string>", line 40, in _unsloth_training_step
    [rank0]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3409, in compute_loss
    [rank0]:     logit_softcapping = getattr(model.config, "final_logit_softcapping", 0)  # Gemma
    [rank0]:   File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1964, in __getattr__
    [rank0]:     raise AttributeError(
    [rank0]: AttributeError: 'DistributedDataParallel' object has no attribute 'config'
    [rank0]:[W203 06:29:04.635676507 ProcessGroupNCCL.cpp:1524] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())
    W0203 06:29:05.519000 2809 torch/distributed/elastic/multiprocessing/api.py:908] Sending process 2875 closing signal SIGTERM
    E0203 06:29:06.036000 2809 torch/distributed/elastic/multiprocessing/api.py:882] failed (exitcode: 1) local_rank: 1 (pid: 2876) of binary: /usr/bin/python
    Traceback (most recent call last):
      File "/usr/local/bin/torchrun", line 8, in <module>
        sys.exit(main())
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 357, in wrapper
        return f(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 936, in main
        run(args)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 927, in run
        elastic_launch(
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 156, in __call__
        return launch_agent(self._config, self._entrypoint, list(args))
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 293, in launch_agent
        raise ChildFailedError(
    torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
    ============================================================
    trian/train_unsloth_qwen3-2b.py FAILED
    ------------------------------------------------------------
    Failures:
      <NO_OTHER_FAILURES>
    ------------------------------------------------------------
    Root Cause (first observed failure):
    [0]:
      time      : 2026-02-03_06:29:05
      host      : 7_153
      rank      : 1 (local_rank: 1)
      exitcode  : 1 (pid: 2876)
      error_file: <N/A>
      traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html
    ============================================================
    

    I’ve managed to get multi-GPU training working by installing Unsloth from source. With this setup, multi-GPU training works when vllm=False. However, in practice, the performance is significantly slower than single-GPU training in my case

  6. sea-comet commented on Feb 9, 2026

    @sea-comet

    Hello, I still encounter this error: AttributeError: 'DistributedDataParallel' object has no attribute 'config' after installing Unsloth from source. How did you do it? Did you use pip install -U git+https://github.com/unslothai/unsloth.git ? Thank u !

    Is multi-GPU GRPO with vllm=True actually working for anyone, or is it currently unsupported?

    After adding vllm=Trueto the GRPOTrainer, I encountered the following error:AttributeError: 'DistributedDataParallel' object has no attribute 'config',and I am using the latest version of the Unsloth library.

    pip list
    unsloth                           2026.1.4
    unsloth_zoo                       2026.1.4
    torch                             2.9.0
    torch-tensorrt                    2.3.0a0
    torchao                           0.15.0
    torchaudio                        2.9.0
    torchdata                         0.7.1a0
    torchtext                         0.17.0a0
    torchvision                       0.24.0
    transformer-engine                1.3.0+5b90b7f
    transformers                      4.57.1
    
    # 创建 Trainer
    trainer = GRPOTrainer(
        model = model,
        args = training_args,
        processing_class = tokenizer,
        reward_funcs = [
            formatting_reward_func,
            correctness_reward_func,
        ],
        train_dataset = train_dataset,
        eval_dataset = test_dataset,
        vllm=True
        # 移除 max_seq_length=50000,避免与内部逻辑冲突
        #callbacks = [best_checkpoint_callback],  # 添加自定义 Callback
    )
    
    ============================================================
    开始训练
    ============================================================
    The model is already on multiple devices. Skipping the move to device specified in `args`.
    Unsloth is running with multi GPUs - the effective batch size is multiplied by 2
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 480 | Num Epochs = 3 | Total steps = 360
    O^O/ \_/ \    Batch size per device = 4 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 2 | Total batch size (4 x 1 x 2) = 8
     "-____-"     Trainable parameters = 17,432,576 of 2,144,964,608 (0.81% trained)
    Unsloth is running with multi GPUs - the effective batch size is multiplied by 2
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 480 | Num Epochs = 3 | Total steps = 360
    O^O/ \_/ \    Batch size per device = 4 | Gradient accumulation steps = 1
    \        /    Data Parallel GPUs = 2 | Total batch size (4 x 1 x 2) = 8
     "-____-"     Trainable parameters = 17,432,576 of 2,144,964,608 (0.81% trained)
      0%|                                                                   | 0/360 [00:00<?, ?it/s]`generation_config` default values have been modified to match model-specific defaults: {'temperature': 0.7, 'top_p': 0.8}. If this is not desired, please set these values explicitly.
    `generation_config` default values have been modified to match model-specific defaults: {'temperature': 0.7, 'top_p': 0.8}. If this is not desired, please set these values explicitly.
    [rank1]: Traceback (most recent call last):
    [rank1]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 919, in <module>
    [rank1]:     trainer.train()
    [rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 64, in wrapper
    [rank1]:     output = f(self, *args, **kwargs)
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
    [rank1]:     return inner_training_loop(
    [rank1]:   File "<string>", line 328, in _fast_inner_training_loop
    [rank1]:   File "<string>", line 40, in _unsloth_training_step
    [rank1]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3409, in compute_loss
    [rank1]:     logit_softcapping = getattr(model.config, "final_logit_softcapping", 0)  # Gemma
    [rank1]:   File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1964, in __getattr__
    [rank1]:     raise AttributeError(
    [rank1]: AttributeError: 'DistributedDataParallel' object has no attribute 'config'
    [rank0]: Traceback (most recent call last):
    [rank0]:   File "/data/home/mayao/RL/trian/train_unsloth_qwen3-2b.py", line 919, in <module>
    [rank0]:     trainer.train()
    [rank0]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 64, in wrapper
    [rank0]:     output = f(self, *args, **kwargs)
    [rank0]:   File "/usr/local/lib/python3.10/dist-packages/transformers/trainer.py", line 2325, in train
    [rank0]:     return inner_training_loop(
    [rank0]:   File "<string>", line 328, in _fast_inner_training_loop
    [rank0]:   File "<string>", line 40, in _unsloth_training_step
    [rank0]:   File "/data/home/mayao/RL/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 3409, in compute_loss
    [rank0]:     logit_softcapping = getattr(model.config, "final_logit_softcapping", 0)  # Gemma
    [rank0]:   File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1964, in __getattr__
    [rank0]:     raise AttributeError(
    [rank0]: AttributeError: 'DistributedDataParallel' object has no attribute 'config'
    [rank0]:[W203 06:29:04.635676507 ProcessGroupNCCL.cpp:1524] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())
    W0203 06:29:05.519000 2809 torch/distributed/elastic/multiprocessing/api.py:908] Sending process 2875 closing signal SIGTERM
    E0203 06:29:06.036000 2809 torch/distributed/elastic/multiprocessing/api.py:882] failed (exitcode: 1) local_rank: 1 (pid: 2876) of binary: /usr/bin/python
    Traceback (most recent call last):
      File "/usr/local/bin/torchrun", line 8, in <module>
        sys.exit(main())
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 357, in wrapper
        return f(*args, **kwargs)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 936, in main
        run(args)
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/run.py", line 927, in run
        elastic_launch(
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 156, in __call__
        return launch_agent(self._config, self._entrypoint, list(args))
      File "/usr/local/lib/python3.10/dist-packages/torch/distributed/launcher/api.py", line 293, in launch_agent
        raise ChildFailedError(
    torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
    ============================================================
    trian/train_unsloth_qwen3-2b.py FAILED
    ------------------------------------------------------------
    Failures:
      <NO_OTHER_FAILURES>
    ------------------------------------------------------------
    Root Cause (first observed failure):
    [0]:
      time      : 2026-02-03_06:29:05
      host      : 7_153
      rank      : 1 (local_rank: 1)
      exitcode  : 1 (pid: 2876)
      error_file: <N/A>
      traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html
    ============================================================
    

    I’ve managed to get multi-GPU training working by installing Unsloth from source. With this setup, multi-GPU training works when vllm=False. However, in practice, the performance is significantly slower than single-GPU training in my case

  7. added a commit that references this issue on Feb 9, 2026
    da1eacc
  8. added a commit that references this issue on May 14, 2026
    c98312f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions