Repository navigation
Description
🐛 Describe the bug
I am trying to finetune a qwen3 model using transformers (huggingface), peft, pytorch. The code perfectly works in a non distributed environment: e.g. running python QwenFineTuning.py. however running in a distributed way via torchrun QwenFineTuning.py throws me an error, although it is initialized.
There was a similar issue with the same error message: #150401 but this one relates to reinforcement learning which I am not using.
Error message:
No label_names provided for model class `PeftModelForCausalLM`. Since `PeftModel` hides base models input arguments, if label_names is not given, label_names can't be set automatically within `Trainer`. Note that empty label_names list will be used instead.
[Rank 0] Distributed initialized.
--> Error
[rank0]: Traceback (most recent call last):
[rank0]: File "/workspace/QwenFineTuning.py", line 97, in <module>
[rank0]: trainer.train()
[rank0]: File "/venv/main/lib/python3.12/site-packages/transformers/trainer.py", line 2206, in train
[rank0]: return inner_training_loop(
[rank0]: ^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/transformers/trainer.py", line 2362, in _inner_training_loop
[rank0]: model, self.optimizer = self.accelerator.prepare(self.model, self.optimizer)
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/accelerate/accelerator.py", line 1438, in prepare
[rank0]: result = tuple(
[rank0]: ^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/accelerate/accelerator.py", line 1439, in <genexpr>
[rank0]: self._prepare_one(obj, first_pass=True, device_placement=d) for obj, d in zip(args, device_placement)
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/accelerate/accelerator.py", line 1281, in _prepare_one
[rank0]: return self.prepare_model(obj, device_placement=device_placement)
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/accelerate/accelerator.py", line 1585, in prepare_model
[rank0]: model = torch.nn.parallel.DistributedDataParallel(
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/nn/parallel/distributed.py", line 827, in __init__
[rank0]: _sync_module_states(
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/distributed/utils.py", line 323, in _sync_module_states
[rank0]: _sync_params_and_buffers(process_group, module_states, broadcast_bucket_size, src)
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/distributed/utils.py", line 334, in _sync_params_and_buffers
[rank0]: dist._broadcast_coalesced(
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/_compile.py", line 32, in inner
[rank0]: return disable_fn(*args, **kwargs)
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 745, in _fn
[rank0]: return fn(*args, **kwargs)
[rank0]: ^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/distributed/tensor/_api.py", line 346, in __torch_dispatch__
[rank0]: return DTensor._op_dispatcher.dispatch(
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/distributed/tensor/_dispatch.py", line 167, in dispatch
[rank0]: op_info = self.unwrap_to_op_info(op_call, args, kwargs)
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: File "/venv/main/lib/python3.12/site-packages/torch/distributed/tensor/_dispatch.py", line 400, in unwrap_to_op_info
[rank0]: assert mesh is not None, f"found no DeviceMesh from dtensor args for {op_call}!"
[rank0]: ^^^^^^^^^^^^^^^^
[rank0]: AssertionError: found no DeviceMesh from dtensor args for c10d.broadcast_.default!
E0609 15:28:48.910000 5118 torch/distributed/elastic/multiprocessing/api.py:869] failed (exitcode: 1) local_rank: 0 (pid: 5185) of binary: /venv/main/bin/python3.12
Traceback (most recent call last):
File "/venv/main/bin/torchrun", line 8, in <module>
sys.exit(main())
^^^^^^
File "/venv/main/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 355, in wrapper
return f(*args, **kwargs)
^^^^^^^^^^^^^^^^^^
File "/venv/main/lib/python3.12/site-packages/torch/distributed/run.py", line 918, in main
run(args)
File "/venv/main/lib/python3.12/site-packages/torch/distributed/run.py", line 909, in run
elastic_launch(
File "/venv/main/lib/python3.12/site-packages/torch/distributed/launcher/api.py", line 138, in __call__
return launch_agent(self._config, self._entrypoint, list(args))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/venv/main/lib/python3.12/site-packages/torch/distributed/launcher/api.py", line 269, in launch_agent
raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
============================================================
QwenFineTuning.py FAILED
------------------------------------------------------------
Failures:
<NO_OTHER_FAILURES>
------------------------------------------------------------
Root Cause (first observed failure):
[0]:
time : 2025-06-09_15:28:48
host : 5fb4be8fc32f
rank : 0 (local_rank: 0)
exitcode : 1 (pid: 5185)
error_file: <N/A>
traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html
============================================================
my code:
from transformers import Trainer, TrainingArguments, AutoModelForCausalLM
from datasets import Dataset, load_from_disk
from peft import LoraConfig, get_peft_model
peft_config = LoraConfig(
r=64, # Rank of the low-rank matrices
lora_alpha=16, # Scaling factor
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], # Attention projection layers
lora_dropout=0.1, # Dropout for LoRA layers
bias="none", # Do not train bias parameters
task_type="CAUSAL_LM" # Task type for causal language modeling
)
class ZeroLossAbortCallback(TrainerCallback):
def on_log(self, args, state, control, **kwargs):
loss = state.log_history[-1].get("loss", None)
if loss is not None and abs(loss) < 1e-5:
print("🚨 Loss is near zero! Aborting training.")
control.should_training_stop = True
control.should_save = False
control.should_evaluate = False
model_name = "Qwen/Qwen3-8B"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map="auto",
)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenized_train = load_from_disk('/workspace/dataset_tokenized_2048/train')
tokenized_val = load_from_disk('/workspace/dataset_tokenized_2048/val')
data_collator = DataCollatorWithPadding(
tokenizer=tokenizer, padding=True
)
training_args = TrainingArguments(
output_dir="./results",
overwrite_output_dir=True,
num_train_epochs=3,
per_device_train_batch_size=2,
gradient_accumulation_steps=16,
save_steps=1000,
logging_steps=25,
save_total_limit=2,
prediction_loss_only=True,
bf16=True,
remove_unused_columns=False,
learning_rate=2e-4,
warmup_steps=500,
weight_decay=0.01,
fsdp=False,
# gradient_checkpointing=True,
# report_to=None,
# deepspeed="deepspeed_config.json",
)
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=tokenized_train,
eval_dataset=tokenized_val,
callbacks=[ZeroLossAbortCallback()]
)
import torch.distributed as dist
if dist.is_available() and dist.is_initialized():
print(f"[Rank {dist.get_rank()}] Distributed initialized.")
else:
print("[Rank 0] WARNING: Distributed NOT initialized.")
trainer.train()
model.save_pretrained("./fine-tuned-qwen")
tokenizer.save_pretrained("./fine-tuned-qwen")
Versions
Collecting environment information...
PyTorch version: 2.6.0+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A
OS: Ubuntu 24.04.2 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
Clang version: Could not collect
CMake version: version 3.28.3
Libc version: glibc-2.39
Python version: 3.12.3 (main, Feb 4 2025, 14:48:35) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-139-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.8.93
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA H100 80GB HBM3
Nvidia driver version: 570.133.20
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.8.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 46 bits physical, 57 bits virtual
Byte Order: Little Endian
CPU(s): 208
On-line CPU(s) list: 0-207
Vendor ID: GenuineIntel
Model name: Intel(R) Xeon(R) Platinum 8470
CPU family: 6
Model: 143
Thread(s) per core: 2
Core(s) per socket: 52
Socket(s): 2
Stepping: 8
Frequency boost: enabled
CPU(s) scaling MHz: 45%
CPU max MHz: 2001.0000
CPU min MHz: 800.0000
BogoMIPS: 4000.00
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
Virtualization: VT-x
L1d cache: 4.9 MiB (104 instances)
L1i cache: 3.3 MiB (104 instances)
L2 cache: 208 MiB (104 instances)
L3 cache: 210 MiB (2 instances)
NUMA node(s): 2
NUMA node0 CPU(s): 0-51,104-155
NUMA node1 CPU(s): 52-103,156-207
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Versions of relevant libraries:
[pip3] numpy==2.3.0
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-cusparselt-cu12==0.6.2
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] torch==2.6.0
[pip3] triton==3.2.0
[conda] Could not collect
cc @H-Huang @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k
Activity
mhsbz commentedon Jun 11, 2025
same here
xgl0626 commentedon Jun 11, 2025
我也才遇到了,还以为是显卡的问题或者包的问题
weifengpy commentedon Jun 11, 2025
device_map="cuda"resolves the problem. for torchrun +device_map="auto", the model is loaded with TP and hence have DTensor model.parameters().I modified your script to illustrate my point
legolasflagstaff commentedon Jun 16, 2025
I am not sure about this fix, because when we load very large models we don't want to assign the device. No?
weifengpy commentedon Jun 16, 2025
oh, sorry for the confusion. we didn assign device, device="cuda" or device="cpu". just not "auto"
twoflypig commentedon Jun 17, 2025
The same error occurs because the communication operator is not registered for Dtensor, resulting in the args still being in tuple form, see https://github.com/pytorch/pytorch/blob/v2.7.0/torch/distributed/tensor/_dispatch.py#L343
https://github.com/pytorch/pytorch/blob/v2.7.0/torch/distributed/tensor/_dispatch.py#L373
and the device_mesh cannot be obtained here.
However, the direct cause is that the communication operator should not be directly called on Dtensor.
yuvrajpant56 commentedon Jun 28, 2025
assert compute_mesh is not None, (
[rank0]: AssertionError: found no DeviceMesh from dtensor args for c10d.broadcast_.default!
[rank0]:[W628 18:11:21.687256061 ProcessGroupNCCL.cpp:1479] 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())
guy please solve this issue...
weifengpy commentedon Jun 29, 2025
change devic_map=auto to device_map=cuda, it fixes the issue
parthchadha commentedon Jul 8, 2025
@weifengpy this won't work when you are dealing with large models that won't fit on a single GPU. Forcing device_map="cuda" will force each process to load the model in GPU memory. Is there a plan to fix this issue?
weifengpy commentedon Jul 8, 2025
device_map="cpu" also help
it's resolved at HF side:
huggingface/transformers#38942
using HF latest codebase, device_map=auto would work
mistysesame commentedon Jul 11, 2025
I still got this error
AssertionError: found no DeviceMesh from dtensor args for c10d.broadcast_.default!if I usetp_plan='auto'and not providedevice_map. The cause of this error is exactly what @twoflypig mentioned above. However I don't know where the problematic call toc10d.broadcast_is from.If I add
device_map(set to any value), then I got this error:"ValueError:
tp_plananddevice_mapare mutually exclusive. Choose either one for parallelization."