Repository navigation
Closed
Labels
Description
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
Datta0 commentedon Jan 21, 2026
Hey @dajuanmaoa this might be a restriction from accelerate? It says
You might want to set
load_in_4bit=Falseand try?Let me know if you face errors even after that
dajuanmaoa commentedon Jan 29, 2026
I try
load_in_4bit=FalseThe errors that occurred look the same to me. And I am not using a quantized model; I am usingQwen3-VL-2B-InstructChengHu98 commentedon Feb 3, 2026
Is multi-GPU GRPO with vllm=True actually working for anyone, or is it currently unsupported?
dajuanmaoa commentedon Feb 3, 2026
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.ChengHu98 commentedon Feb 3, 2026
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
sea-comet commentedon Feb 9, 2026
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 !
Fix multi-GPU loading for quantized models in distributed training (#…
Fix multi-GPU loading for quantized models in distributed training (u…