Skip to content

[Bug] TypeError in compiler.py with DDP: distributed_function returns None on non-main ranks when dist is not initialized #3687

Closed

Description

@MosRat
  1. Did you update? pip install --upgrade unsloth unsloth_zoo
    Yes.
    unsloth: 2025.11.6
    unsloth-zoo: 2025.12.1
  2. Colab or Kaggle or local / cloud
    Local environment.
  3. Number GPUs used, use nvidia-smi
    2 GPUs.
  4. Which notebook? Please link!
    Running a local script via torchrun.
  5. Which Unsloth version, TRL version, transformers version, PyTorch version?
  • Unsloth: 2025.11.6
  • Unsloth-Zoo: 2025.12.1
  • PyTorch: 2.9.0+cu128
  • Command: torchrun --nproc_per_node=2 unsloth-cli.py
  1. 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 > 0
function_location = os.path.join(compile_folder, f"{name}.py") # TypeError here

unsloth_zoo/utils.py inside distributed_function is the root cause
https://github.com/unslothai/unsloth-zoo/blob/c46b0a36252327da5f910b4bc4db45b130d9f847/unsloth_zoo/utils.py#L98

print(f"{torch_distributed_is_initialized()} {torch_distributed_is_torchelastic_launched()} {is_main_process()}")

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

Activity

  1. MosRat commented on Dec 8, 2025

    @MosRat
    Author

    Did you try our new DDP guide? https://docs.unsloth.ai/basics/multi-gpu-training-with-unsloth/ddp

    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 for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in 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

    This is the same error I put above.

  2. Sasha5017 commented on Dec 8, 2025

    @Sasha5017

    I have the same error, were you able to solve it?

  3. zoeyma111 commented on Dec 8, 2025

    @zoeyma111

    same error

  4. Sasha5017 commented on Dec 10, 2025

    @Sasha5017

    @MosRat did you solve this problem?

  5. MosRat commented on Dec 10, 2025

    @MosRat
    Author

    @MosRat did you solve this problem?

    You can just modified .venv/lib/python3.12/site-packages/unsloth_zoo/utils.py line 98 distributed_function as follow:

    def distributed_function(n = 1, function = None, *args, **kwargs):
        assert function is not None
    
        # Not launched distributed at all
        if not is_distributed() or not torch_distributed_is_initialized():
            out = function(*args, **kwargs)
            return out if n == 1 else out
    
        # Multi-process: only main executes the function
        if is_main_process():
            out = function(*args, **kwargs)
            obj_list = [out] if n == 1 else list(out)
        else:
            obj_list = [None for _ in range(n)]
        # print(f"{torch_distributed_is_initialized()} ")
        # If the process group is initialized, we can synchronize / share the result
        if torch_distributed_is_initialized():
            # Broadcast result to all ranks
            dist.broadcast_object_list(obj_list, src = 0)
            # Barrier to make sure everyone waits until main is done
            dist.barrier()
    
        return obj_list[0] if n == 1 else obj_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:

    def get_compile_folder(use_tempfile = False):
        location, UNSLOTH_COMPILE_USE_TEMP = distributed_function(2, _get_compile_folder, use_tempfile)
        if location is not None:
            location = UNSLOTH_COMPILE_LOCATION
        return location, UNSLOTH_COMPILE_USE_TEMP
    pass

    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

  6. Sasha5017 commented on Dec 10, 2025

    @Sasha5017

    @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(),
    )

  7. ZoeycircleMa commented on Dec 11, 2025

    @ZoeycircleMa

    @Sasha5017 @MosRat thank you guys, seems to work now. Will let you know if there is any update!

  8. djsaunde commented on Dec 15, 2025

    @djsaunde
    Contributor

    This is solved in unsloth-zoo main branch. We'll make a release that includes the fix shortly. CC @danielhanchen

  9. MosRat commented on Dec 15, 2025

    @MosRat
    Author

    I've tried the latest version (clone from github) and it works, thanks for your work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions