You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Bug] TypeError in compiler.py with DDP: distributed_function returns None on non-main ranks when dist is not initialized #3687
Which trainer? SFTTrainer, GRPOTrainer etc
SFTTrainer
Description of the Bug
I encountered a TypeError when running distributed training using torchrun. The error happens in unsloth_zoo/compiler.py because compile_folder is None on non-main processes.
This causes unsloth_zoo/compiler.py to crash:
compile_folder, UNSLOTH_COMPILE_USE_TEMP=get_compile_folder(use_tempfile=False)
# compile_folder is None on rank > 0function_location=os.path.join(compile_folder, f"{name}.py") # TypeError here
Output during crash:False True False (on non-main rank).
Put Minimal code to reproduce error here ###Remove Hugging Face token###
uv init --python 3.12 # set torch+cu128 index in pyproject.toml
uv add torch torchvision bitsandbytes transformers
uv add git+https://github.com/unslothai/unsloth.git
uv add git+https://github.com/unslothai/unsloth-zoo.git
uv run torchrun --nproc_per_node=2 unsloth-cli.py # copied from https://github.com/unslothai/unsloth/blob/main/unsloth-cli.py
Yes, I just follow the new DDP guide, run uv venv –python 3.12 && source .venv/bin/activate then
git clone https://github.com/unslothai/unsloth.git
cd unsloth
pip install .
Run torchrun --nproc_per_node=2 unsloth-cli.py will raise an error say missing unsloth_zoo, numpy, torchvision, bitsandbyte.
I just install them with pip and rerun torchrun --nproc_per_node=2 unsloth-cli.py
# It is a node with 8xA100 40GB
(unsloth-ddp) User@gpu01:~/workspace/unsloth_ddp/unsloth$CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node=2 unsloth-cli.py
W1208 14:17:57.459000 168918 torch/distributed/run.py:803]
W1208 14:17:57.459000 168918 torch/distributed/run.py:803] *****************************************
W1208 14:17:57.459000 168918 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable foreach process to be 1in default, to avoid your system being overloaded, please further tune the variable foroptimal performancein your application as needed.
W1208 14:17:57.459000 168918 torch/distributed/run.py:803] *****************************************
🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
🦥 Unsloth Zoo will now patch everything to make training faster!
🦥 Unsloth Zoo will now patch everything to make training faster!
Traceback (most recent call last):
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth-cli.py", line 393, in<module>
run(args)
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth-cli.py", line 38, in run
from unsloth import FastLanguageModel
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth/__init__.py", line 249, in<module>
from .models import *
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth/models/__init__.py", line 15, in<module>
from .llama import FastLlamaModel
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth/models/llama.py", line 3427, in<module>
PatchFastRL(FastLanguageModel = FastLlamaModel)
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth/models/rl.py", line 1322, in PatchFastRL
patch_trl_rl_trainers()
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth/models/rl.py", line 1315, in patch_trl_rl_trainers
_patch_trl_rl_trainers(trainer)
File "/home/User/workspace/unsloth_ddp/unsloth/unsloth/models/rl.py", line 990, in _patch_trl_rl_trainers
created_module = create_new_function(
^^^^^^^^^^^^^^^^^^^^
File "/home/User/workspace/unsloth_ddp/.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py", line 571, in create_new_function
function_location = os.path.join(compile_folder, f"{name}.py")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen posixpath>", line 76, in join
TypeError: expected str, bytes or os.PathLike object, not NoneType
W1208 14:18:07.731000 168918 torch/distributed/elastic/multiprocessing/api.py:908] Sending process 168982 closing signal SIGTERM
E1208 14:18:07.947000 168918 torch/distributed/elastic/multiprocessing/api.py:882] failed (exitcode: 1) local_rank: 1 (pid: 168983) of binary: /home/User/workspace/unsloth_ddp/.venv/bin/python3
Traceback (most recent call last):
File "/home/User/workspace/unsloth_ddp/.venv/bin/torchrun", line 10, in<module>sys.exit(main())
^^^^^^
File "/home/User/workspace/unsloth_ddp/.venv/lib/python3.12/site-packages/torch/distributed/elastic/multiprocessing/errors/__init__.py", line 357, in wrapper
return f(*args, **kwargs)
^^^^^^^^^^^^^^^^^^
File "/home/User/workspace/unsloth_ddp/.venv/lib/python3.12/site-packages/torch/distributed/run.py", line 936, in main
run(args)
File "/home/User/workspace/unsloth_ddp/.venv/lib/python3.12/site-packages/torch/distributed/run.py", line 927, in run
elastic_launch(
File "/home/User/workspace/unsloth_ddp/.venv/lib/python3.12/site-packages/torch/distributed/launcher/api.py", line 156, in __call__
return launch_agent(self._config, self._entrypoint, list(args))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/User/workspace/unsloth_ddp/.venv/lib/python3.12/site-packages/torch/distributed/launcher/api.py", line 293, in launch_agent
raise ChildFailedError(
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:
============================================================
unsloth-cli.py FAILED
------------------------------------------------------------
Failures:
<NO_OTHER_FAILURES>
------------------------------------------------------------
Root Cause (first observed failure):
[0]:
time: 2025-12-08_14:18:07
host : gpu01
rank : 1 (local_rank: 1)
exitcode : 1 (pid: 168983)
error_file: <N/A>
traceback : To enable traceback see: https://pytorch.org/docs/stable/elastic/errors.html
You can just modified .venv/lib/python3.12/site-packages/unsloth_zoo/utils.py line 98 distributed_function as follow:
defdistributed_function(n=1, function=None, *args, **kwargs):
assertfunctionisnotNone# Not launched distributed at allifnotis_distributed() ornottorch_distributed_is_initialized():
out=function(*args, **kwargs)
returnoutifn==1elseout# Multi-process: only main executes the functionifis_main_process():
out=function(*args, **kwargs)
obj_list= [out] ifn==1elselist(out)
else:
obj_list= [Nonefor_inrange(n)]
# print(f"{torch_distributed_is_initialized()} ")# If the process group is initialized, we can synchronize / share the resultiftorch_distributed_is_initialized():
# Broadcast result to all ranksdist.broadcast_object_list(obj_list, src=0)
# Barrier to make sure everyone waits until main is donedist.barrier()
returnobj_list[0] ifn==1elseobj_list
Or you can just hardcode UNSLOTH_COMPILE_LOCATION to locations in .venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py line 308 get_compile_folder:
This seemed to help, and everything went smoothly into training. If anything goes wrong, I'll describe it here. But instead of balanced, I also used this function:
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = Config.model_name,
max_seq_length = 2048, # Context length - can be longer, but uses more memory
load_in_4bit = True, # 4bit uses much less memory
load_in_8bit = False, # A bit more accurate, uses 2x memory
full_finetuning = False, # We have full finetuning now!
# token = "hf_...", # use one if using gated models
device_map = get_device_map(),
)
Activity
shimmyshimmer commentedon Dec 8, 2025
Did you try our new DDP guide? https://docs.unsloth.ai/basics/multi-gpu-training-with-unsloth/ddp
MosRat commentedon Dec 8, 2025
Yes, I just follow the new DDP guide, run
uv venv –python 3.12 && source .venv/bin/activatethenRun
torchrun --nproc_per_node=2 unsloth-cli.pywill raise an error say missingunsloth_zoo,numpy,torchvision,bitsandbyte.I just install them with pip and rerun
torchrun --nproc_per_node=2 unsloth-cli.pyThis is the same error I put above.
Sasha5017 commentedon Dec 8, 2025
I have the same error, were you able to solve it?
zoeyma111 commentedon Dec 8, 2025
same error
Sasha5017 commentedon Dec 10, 2025
@MosRat did you solve this problem?
MosRat commentedon Dec 10, 2025
You can just modified
.venv/lib/python3.12/site-packages/unsloth_zoo/utils.pyline 98distributed_functionas follow:Or you can just hardcode UNSLOTH_COMPILE_LOCATION to locations in
.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.pyline 308get_compile_folder:It can made it just work until training logs printed, but im not sure about it will cause other bugs during training progress as I encounter #3705
Sasha5017 commentedon Dec 10, 2025
@MosRat @zoeyma111
This seemed to help, and everything went smoothly into training. If anything goes wrong, I'll describe it here. But instead of balanced, I also used this function:
def get_device_map() -> "str | dict[str, int]":
world_size = int(os.environ.get("WORLD_SIZE", "1"))
if world_size <= 1:
return "balanced"
local_rank = int(os.environ.get("LOCAL_RANK", os.environ.get("RANK", 0)))
torch.cuda.set_device(local_rank)
return {"": local_rank}
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = Config.model_name,
max_seq_length = 2048, # Context length - can be longer, but uses more memory
load_in_4bit = True, # 4bit uses much less memory
load_in_8bit = False, # A bit more accurate, uses 2x memory
full_finetuning = False, # We have full finetuning now!
# token = "hf_...", # use one if using gated models
device_map = get_device_map(),
)
ZoeycircleMa commentedon Dec 11, 2025
@Sasha5017 @MosRat thank you guys, seems to work now. Will let you know if there is any update!
djsaunde commentedon Dec 15, 2025
This is solved in
unsloth-zoomainbranch. We'll make a release that includes the fix shortly. CC @danielhanchenMosRat commentedon Dec 15, 2025
I've tried the latest version (clone from github) and it works, thanks for your work