Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Distributed tests: take every MASTER_PORT from the shared rendezvous helper (#15679)

Daniel Han3c63f72932dd
diff --git a/tests/python/test_block_compile_ddp_no_split.py b/tests/python/test_block_compile_ddp_no_split.py
index 5b4907079c1..d66d3e8d881 100644
--- a/tests/python/test_block_compile_ddp_no_split.py
+++ b/tests/python/test_block_compile_ddp_no_split.py
@@ -12,7 +12,6 @@ from __future__ import annotations
import os
import queue as queue_module
-import socket
import sys
import pytest
@@ -33,9 +32,8 @@ pytestmark = [
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _run(recompute_miss = False):
diff --git a/tests/python/test_grpo_ddp_gradient_sync.py b/tests/python/test_grpo_ddp_gradient_sync.py
index f38c40c3f7e..2a8e4f4acb1 100644
--- a/tests/python/test_grpo_ddp_gradient_sync.py
+++ b/tests/python/test_grpo_ddp_gradient_sync.py
@@ -5,7 +5,6 @@
from __future__ import annotations
import os
-import socket
import sys
import pytest
@@ -18,9 +17,8 @@ pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "two gloo rank
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def test_grpo_training_step_averages_gradients_like_ddp():
diff --git a/tests/python/test_plain_trainer_ddp_gc.py b/tests/python/test_plain_trainer_ddp_gc.py
index 7e22546224c..ef48acca7b3 100644
--- a/tests/python/test_plain_trainer_ddp_gc.py
+++ b/tests/python/test_plain_trainer_ddp_gc.py
@@ -8,7 +8,6 @@ from __future__ import annotations
import os
import queue as queue_module
-import socket
import sys
import pytest
@@ -31,9 +30,8 @@ def _failed(results):
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _run(cases):
diff --git a/tests/python/test_sentence_transformer_ddp_gc.py b/tests/python/test_sentence_transformer_ddp_gc.py
index 1c772253254..ddb42a20f50 100644
--- a/tests/python/test_sentence_transformer_ddp_gc.py
+++ b/tests/python/test_sentence_transformer_ddp_gc.py
@@ -5,7 +5,6 @@
from __future__ import annotations
import os
-import socket
import sys
import pytest
@@ -21,9 +20,8 @@ _DIST_ENV = ("WORLD_SIZE", "RANK", "LOCAL_RANK", "LOCAL_WORLD_SIZE")
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _tiny_checkpoint(path, arch):
diff --git a/tests/python/test_sentence_transformer_fsdp2_save.py b/tests/python/test_sentence_transformer_fsdp2_save.py
index 99b0df4741d..a3c6e42823e 100644
--- a/tests/python/test_sentence_transformer_fsdp2_save.py
+++ b/tests/python/test_sentence_transformer_fsdp2_save.py
@@ -8,7 +8,6 @@ from __future__ import annotations
import os
import queue as queue_module
-import socket
import sys
import pytest
@@ -30,9 +29,8 @@ def _failed(results):
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _tiny_bert(path):
diff --git a/tests/test_cudnn_sdpa_grad_layout_dtensor.py b/tests/test_cudnn_sdpa_grad_layout_dtensor.py
index 5b68697df8e..7686b514f93 100644
--- a/tests/test_cudnn_sdpa_grad_layout_dtensor.py
+++ b/tests/test_cudnn_sdpa_grad_layout_dtensor.py
@@ -6,7 +6,6 @@ raises "aten.copy_.default got mixed torch.Tensor and DTensor"."""
import json
import os
-import socket
import subprocess
import sys
import textwrap
@@ -66,9 +65,8 @@ def _context_parallel_available():
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
@pytest.mark.gpu
diff --git a/tests/test_ddp_comm_defaults.py b/tests/test_ddp_comm_defaults.py
index 17481048cd1..38ff54d62ad 100644
--- a/tests/test_ddp_comm_defaults.py
+++ b/tests/test_ddp_comm_defaults.py
@@ -7,7 +7,6 @@ from __future__ import annotations
import ast
import os
import pathlib
-import socket
import sys
import pytest
@@ -43,9 +42,8 @@ _UTILS = pathlib.Path(__file__).resolve().parents[1] / "unsloth" / "models" / "_
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
@pytest.fixture(scope = "module")
diff --git a/tests/test_ddp_find_unused_default.py b/tests/test_ddp_find_unused_default.py
index c894dbf8138..de3c1baff94 100644
--- a/tests/test_ddp_find_unused_default.py
+++ b/tests/test_ddp_find_unused_default.py
@@ -391,7 +391,5 @@ def test_full_finetune_vlm_text_only_batches_train_under_ddp(tmp_path):
def _free_port():
- import socket
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
diff --git a/tests/test_fast_inference_torchrun_agreement.py b/tests/test_fast_inference_torchrun_agreement.py
index 6d668dcd83d..224c46fa305 100644
--- a/tests/test_fast_inference_torchrun_agreement.py
+++ b/tests/test_fast_inference_torchrun_agreement.py
@@ -11,7 +11,6 @@ Trainer's collectives, and both waited out the group timeout.
import ast
import json
import os
-import socket
import subprocess
import sys
import textwrap
@@ -136,9 +135,8 @@ def test_agreement_follows_the_last_per_card_gate():
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def test_mixed_gpu_torchrun_ranks_take_the_same_path(tmp_path):
diff --git a/tests/test_moe_dw_accumulate.py b/tests/test_moe_dw_accumulate.py
index 2a754ca64ca..98b19fb9de8 100644
--- a/tests/test_moe_dw_accumulate.py
+++ b/tests/test_moe_dw_accumulate.py
@@ -5,7 +5,6 @@
import os
import re
-import socket
import sys
from pathlib import Path
@@ -439,9 +438,8 @@ def test_compiled_fullgraph_zero_breaks_and_matches_eager(monkeypatch):
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _ddp_worker(rank, world, port, inplace, bucket_view, out_path):
diff --git a/tests/test_parallel_general_gloo.py b/tests/test_parallel_general_gloo.py
index 633d1577926..7ef5a994270 100644
--- a/tests/test_parallel_general_gloo.py
+++ b/tests/test_parallel_general_gloo.py
@@ -16,7 +16,6 @@ if multiprocessing.parent_process() is not None or getattr(
import importlib.machinery # noqa: E402
import importlib.util # noqa: E402
-import socket # noqa: E402
import sys # noqa: E402
import tempfile # noqa: E402
import types # noqa: E402
@@ -574,9 +573,8 @@ def _worker(rank, world, port, case, tmp):
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _spawn(case, world = 2):
diff --git a/tests/test_pp_fsdp2_gloo.py b/tests/test_pp_fsdp2_gloo.py
index 029c823ab49..c9f857f2b55 100644
--- a/tests/test_pp_fsdp2_gloo.py
+++ b/tests/test_pp_fsdp2_gloo.py
@@ -12,7 +12,6 @@ if multiprocessing.parent_process() is not None or getattr(
):
os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts
-import socket # noqa: E402
import sys # noqa: E402
import tempfile # noqa: E402
@@ -372,9 +371,8 @@ CASES = {
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _worker(rank, world, port, case, tmp, kwargs):
diff --git a/tests/test_pp_native_gloo.py b/tests/test_pp_native_gloo.py
index 4c6a4838a5a..dfdecf06577 100644
--- a/tests/test_pp_native_gloo.py
+++ b/tests/test_pp_native_gloo.py
@@ -13,7 +13,6 @@ if multiprocessing.parent_process() is not None or getattr(
import importlib.machinery # noqa: E402
import importlib.util # noqa: E402
-import socket # noqa: E402
import sys # noqa: E402
import tempfile # noqa: E402
import types # noqa: E402
@@ -500,9 +499,8 @@ CASES = {
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _worker(rank, world, port, case, tmp, kwargs):
diff --git a/tests/test_rendezvous_port_everywhere.py b/tests/test_rendezvous_port_everywhere.py
new file mode 100644
index 00000000000..87e6ea61eab
--- /dev/null
+++ b/tests/test_rendezvous_port_everywhere.py
@@ -0,0 +1,98 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Every distributed test takes MASTER_PORT from tests/_rendezvous_port.py.
+
+A port from ``bind(("127.0.0.1", 0))`` is in the kernel's ephemeral range, and it is released before rank 0
+listens on it, so another xdist worker's gloo connection can take it first and the ranks die with
+EADDRINUSE. That happened to test_tp_native_gloo.py in Repo tests (CPU, gloo) after #14334 had moved most,
+but not all, of the distributed tests onto the shared helper.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+TESTS = Path(__file__).resolve().parent
+# Studio tests pick ports for HTTP servers they start themselves, not for a torch rendezvous.
+SKIP = {TESTS / "studio", TESTS / "_rendezvous_port.py"}
+RENDEZVOUS = ("MASTER_PORT", "master_port", "init_process_group", "TCPStore")
+
+
+def _test_files():
+ for path in sorted(TESTS.rglob("*.py")):
+ if any(path == s or s in path.parents for s in SKIP):
+ continue
+ yield path
+
+
+def _binds_port_zero(tree: ast.AST) -> bool:
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "bind"
+ and node.args
+ and isinstance(node.args[0], ast.Tuple)
+ and len(node.args[0].elts) == 2
+ and isinstance(node.args[0].elts[1], ast.Constant)
+ and node.args[0].elts[1].value == 0
+ ):
+ return True
+ return False
+
+
+def _offenders():
+ found = []
+ for path in _test_files():
+ source = path.read_text(encoding = "utf-8")
+ if not any(word in source for word in RENDEZVOUS):
+ continue # a port for a server the test starts itself, not a torch rendezvous
+ tree = ast.parse(source)
+ name = path.relative_to(TESTS.parent).as_posix()
+ free_port = [
+ n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "_free_port"
+ ]
+ if any("_rendezvous_port" not in ast.unparse(fn) for fn in free_port):
+ found.append(f"{name}: _free_port does not use tests._rendezvous_port")
+ elif _binds_port_zero(tree):
+ found.append(f"{name}: binds port 0 for a torch rendezvous")
+ return found
+
+
+def test_distributed_tests_take_their_port_from_the_shared_helper():
+ offenders = _offenders()
+ assert not offenders, "use tests._rendezvous_port.free_port():\n" + "\n".join(offenders)
+
+
+ "body, reason",
+ [
+ (
+ "def _free_port():\n with socket.socket() as s:\n s.bind(('127.0.0.1', 0))\n"
+ " return s.getsockname()[1]\n\n\nos.environ['MASTER_PORT'] = str(_free_port())\n",
+ "_free_port does not use tests._rendezvous_port",
+ ),
+ (
+ "with socket.socket() as s:\n s.bind(('127.0.0.1', 0))\n port = s.getsockname()[1]\n"
+ "os.environ['MASTER_PORT'] = str(port)\n",
+ "binds port 0 for a torch rendezvous",
+ ),
+ ],
+)
+def test_the_check_catches_a_raw_bind_zero(tmp_path, monkeypatch, body, reason):
+ bad = tmp_path / "test_raw_port.py"
+ bad.write_text("import os\nimport socket\n\n" + body, encoding = "utf-8")
+ monkeypatch.setitem(globals(), "TESTS", tmp_path)
+ monkeypatch.setitem(globals(), "_test_files", lambda: iter([bad]))
+ assert _offenders() == [f"{tmp_path.name}/test_raw_port.py: {reason}"]
+
+
[email protected]("worker", ["gw0", "gw3", "gw11"])
+def test_the_helper_stays_below_the_ephemeral_range(monkeypatch, worker):
+ from tests._rendezvous_port import HIGH, free_port
+ monkeypatch.setenv("PYTEST_XDIST_WORKER", worker)
+ assert free_port() < HIGH
diff --git a/tests/test_token_budget_batches.py b/tests/test_token_budget_batches.py
index c7af5080be3..b4ed5134a3b 100644
--- a/tests/test_token_budget_batches.py
+++ b/tests/test_token_budget_batches.py
@@ -630,12 +630,11 @@ dist.destroy_process_group()
@pytest.mark.parametrize("other, expected", [("8,8", (1, 1)), ("4,5,3,6,2,4,6,4,6", (3, 3))])
def test_ddp_ranks_split_only_when_every_rank_needs_the_same_count(tmp_path, other, expected):
- import socket
import subprocess
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- port = s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+
+ port = free_port()
env = dict(
__import__("os").environ,
MASTER_ADDR = "127.0.0.1",
diff --git a/tests/test_tp_native_gloo.py b/tests/test_tp_native_gloo.py
index 9716f4c5afc..8a4113a9d5b 100644
--- a/tests/test_tp_native_gloo.py
+++ b/tests/test_tp_native_gloo.py
@@ -11,7 +11,6 @@ if multiprocessing.parent_process() is not None or getattr(
):
os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts
-import socket # noqa: E402
import sys # noqa: E402
import tempfile # noqa: E402
@@ -36,9 +35,8 @@ _ADAM_EPS = 1e-6
def _free_port():
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
+ from tests._rendezvous_port import free_port
+ return free_port()
def _grads(model):