Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion nemo_run/run/ray/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,14 @@ def __post_init__(self) -> None: # noqa: D401 – simple implementation
raise ValueError(f"Unsupported executor: {self.executor.__class__}")

backend_cls = backend_map[self.executor.__class__]
self.backend = backend_cls(name=self.name, executor=self.executor)
if isinstance(self.executor, SlurmExecutor):
# SlurmRayJob derives its cluster_dir from cluster_name at construction
# time, so it must be passed in rather than set on the instance after.
self.backend = backend_cls(
name=self.name, executor=self.executor, cluster_name=self.cluster_name
)
else:
self.backend = backend_cls(name=self.name, executor=self.executor)

if isinstance(self.executor, LeptonExecutor):
self.backend.cluster_name = self.cluster_name
Expand Down
25 changes: 20 additions & 5 deletions nemo_run/run/ray/slurm.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,15 @@ def create(
if status["job_id"] is not None:
job_state = status["state"]
if job_state in ["PENDING", "RUNNING", "CONFIGURING"]:
if command is not None or command_groups is not None:
raise RuntimeError(
f"Ray cluster '{name}' already exists with ID {status['job_id']} "
f"and is currently in {job_state} state. Submitting a new command "
f"into an already-running cluster is not yet supported, so the "
f"given command was NOT executed. Cancel the existing cluster "
f"first, or call create() without a command to just ensure the "
f"cluster keeps running."
)
logger.debug(
f"Ray cluster '{name}' already exists with ID {status['job_id']} "
f"and is currently in {job_state} state. "
Expand Down Expand Up @@ -1073,23 +1082,29 @@ class SlurmRayJob:
Parameters
----------
name : str
Logical name of the Ray cluster (not necessarily the Slurm job-name).
Logical name of this Ray job (not necessarily the Slurm job-name).
job_id : str
Numeric Slurm job id returned by ``sbatch``.
cluster_dir : str
Remote directory where cluster artefacts (logs, SBATCH script, etc.) are stored.
executor : SlurmExecutor
The executor used to submit/run the job. We only need it for its tunnel.
cluster_name : str, optional
Name of an existing RayCluster to target. If not provided, defaults to *name*,
so a cluster is created (or reused) under the job's own name as before.
"""

name: str
executor: SlurmExecutor
cluster_name: Optional[str] = None

# ---------------------------------------------------------------------
# Internals
# ---------------------------------------------------------------------
def __post_init__(self):
self.cluster_dir = os.path.join(self.executor.tunnel.job_dir, self.name)
self.cluster_dir = os.path.join(
self.executor.tunnel.job_dir, self.cluster_name or self.name
)
self.job_id = None

def _logs_path(self) -> str:
Expand Down Expand Up @@ -1203,9 +1218,9 @@ def status(self, display: bool = True) -> dict[str, Any]:
if self.job_id is None:
self.job_id = get_last_job_id(self.cluster_dir, self.executor)

cluster = SlurmRayCluster(name=self.name, executor=self.executor)
cluster = SlurmRayCluster(name=self.cluster_name or self.name, executor=self.executor)
if self.job_id is not None:
cluster.cluster_map[self.name] = str(self.job_id)
cluster.cluster_map[cluster.name] = str(self.job_id)

status_info = cluster.status(display=False)

Expand Down Expand Up @@ -1363,7 +1378,7 @@ def start(
# ------------------------------------------------------------------
# Spin up / reuse the Ray *cluster* (Slurm array job)
# ------------------------------------------------------------------
cluster = SlurmRayCluster(name=self.name, executor=self.executor)
cluster = SlurmRayCluster(name=self.cluster_name or self.name, executor=self.executor)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stage code under the selected cluster directory.

Failure: With tunnel.job_dir="/tmp/test_jobs", a container image, no additional container mounts, and SlurmRayJob(name="test-job", cluster_name="shared-cluster", executor=executor), starting against an absent or terminal cluster still stages the workdir at /tmp/test_jobs/test-job/code (start(), lines 1286–1290; the packager branch also uses that root). This changed constructor instead creates the cluster under /tmp/test_jobs/shared-cluster. SlurmRayRequest.materialize() mounts only the cluster directory and logs by default (lines 278–283), while setting the container working directory to the staged code path. That working directory is therefore unavailable inside the head/worker containers, so startup fails instead of executing the command. Previously, the staging and mounted cluster directories coincided.

Correction: In SlurmRayJob.start(), replace the staging-root assignment at line 1286 with:

cluster_dir = os.path.join(self.executor.tunnel.job_dir, self.cluster_name or self.name)

Both workdir and packager branches then derive their remote destination from the effective cluster directory, restoring the invariant that the staged code is inside the default container mount. Keep the local packager scratch directory and archive name job-specific; those are not cluster-identity paths. This suggested replacement has been traced through the inspected branches but must be verified before adoption.

Preservation and acceptance — proposed checks, not executed:

  • Set a container image on the existing job fixture, use distinct names, patch only job.status(), and dry-run through the real cluster implementation. Assert the rendered script contains both /tmp/test_jobs/shared-cluster:/tmp/test_jobs/shared-cluster and --container-workdir=/tmp/test_jobs/shared-cluster/code, and does not reference /tmp/test_jobs/test-job/code.
  • Mock staging and submission for a non-dry run. For an explicit workdir, assert the rsync destination and create(workdir=...) are /tmp/test_jobs/shared-cluster/code. Repeat with workdir=None and a mock packager for SSH and local tunnels; retain package(..., "test-job") while checking the same remote destination.
  • With cluster_name=None or cluster_name="test-job", retain /tmp/test_jobs/test-job/code and the existing initialization assertion /tmp/test_jobs/test-job. Keep test_start_dryrun's dryrun=True forwarding assertion.
  • Retain the active-cluster tests: supplied commands and command groups raise with was NOT executed, while test_create_cluster_already_exists without commands returns None.

job_id = cluster.create(
pre_ray_start_commands=pre_ray_start_commands,
dryrun=dryrun,
Expand Down
43 changes: 43 additions & 0 deletions test/run/ray/test_slurm.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,25 @@ def test_create_cluster_already_exists(self, cluster):

assert job_id is None

def test_create_cluster_already_exists_with_command_raises(self, cluster, mock_tunnel):
"""A command must never be silently dropped when a cluster is reused."""
with patch.object(cluster, "status") as mock_status:
mock_status.return_value = {"job_id": "12345", "state": "RUNNING"}

with pytest.raises(RuntimeError, match="was NOT executed"):
cluster.create(command="python train.py", workdir="/remote/code")

# No sbatch script should ever be submitted for the reused cluster.
mock_tunnel.put.assert_not_called()

def test_create_cluster_already_exists_with_command_groups_raises(self, cluster):
"""Same guard applies to command_groups, not just the primary command."""
with patch.object(cluster, "status") as mock_status:
mock_status.return_value = {"job_id": "12345", "state": "PENDING"}

with pytest.raises(RuntimeError, match="was NOT executed"):
cluster.create(command_groups=[["echo", "a"], ["echo", "b"]])

def test_create_dryrun(self, cluster, capsys):
"""Test dry run mode."""
job_id = cluster.create(dryrun=True)
Expand Down Expand Up @@ -545,6 +564,14 @@ def test_job_initialization(self, job):
assert job.cluster_dir == "/tmp/test_jobs/test-job"
assert job.job_id is None

def test_job_initialization_with_cluster_name(self, basic_executor):
"""cluster_name, when set, targets the cluster's own directory, not the job's name."""
job = SlurmRayJob(name="test-job", executor=basic_executor, cluster_name="shared-cluster")

assert job.name == "test-job"
assert job.cluster_name == "shared-cluster"
assert job.cluster_dir == "/tmp/test_jobs/shared-cluster"

def test_logs_path(self, job):
"""Test logs path construction."""
expected_path = "/tmp/test_jobs/test-job/logs/ray-job.log"
Expand Down Expand Up @@ -651,6 +678,22 @@ def test_start_with_workdir(self, mock_rsync, mock_mkdtemp, job, mock_tunnel):
mock_cluster.create.assert_called_once()
assert job.job_id == "12345"

def test_start_uses_cluster_name_when_set(self, basic_executor):
"""start() must attach to cluster_name's cluster, not the job's own name."""
job = SlurmRayJob(name="test-job", executor=basic_executor, cluster_name="shared-cluster")

with patch("nemo_run.run.ray.slurm.SlurmRayCluster") as mock_cluster_class:
mock_cluster = Mock()
mock_cluster.create.return_value = None
mock_cluster_class.return_value = mock_cluster

with patch.object(job, "status"):
job.start(command="python train.py", workdir="/workspace", dryrun=True)

mock_cluster_class.assert_called_once_with(
name="shared-cluster", executor=basic_executor
)

def test_start_dryrun(self, job):
"""Test starting job in dryrun mode."""
with patch("nemo_run.run.ray.slurm.SlurmRayCluster") as mock_cluster_class:
Expand Down
Loading