Skip to content

runner

GENERATOR_FIXED_ARGS module-attribute

Python
GENERATOR_FIXED_ARGS = 2

Leading positional arguments the runner passes to a generator itself: the model and the overrides.

RUNTIME_FIXED_ARGS module-attribute

Python
RUNTIME_FIXED_ARGS = 3

Leading positional arguments the runner passes to a runtime itself: the model, the runtime manager, and the state.

OBJECTIVE_FIXED_ARGS module-attribute

Python
OBJECTIVE_FIXED_ARGS = 3

Leading positional arguments the runner passes to an objective itself: the model, the telemetry path, and the state.

MojoGenerator

Bases: Protocol

Definition of a function that generates a MojoModel model instance.

MojoRuntime

Bases: Protocol

Definition of a function that executes a generated MojoModel model.

MojoObjective

Bases: Protocol

Definition of a function that scores a completed Mojo simulation.

BaseConfig

Bases: MojoBaseModel

n_proc class-attribute instance-attribute

Python
n_proc: int = DEFAULT_N_PROC

Number of proccesses to allow.

This value is used to determine how many parallel jobs can be run. It is also used for the discovery of trial status. Using a value of 1 will result in the slowest runtime, but highest reliability.

Important

Be a good citizen. Use a reasonable number if you are working on a shared resource. You are a jerk if you use everything.

resume class-attribute instance-attribute

Python
resume: bool = DEFAULT_RESUME

Whether to resume a study if the study already exists.

padding class-attribute instance-attribute

Python
padding: int | None = Field(default=None, ge=1)

Zero-padding width of the trial folder names (for example 3 gives trial_007). When unset, the width is derived from n_trial so every trial in a job sorts consistently; set it when a process only knows about one trial of a larger job, such as a SLURM worker.

padding_style property

Python
padding_style: str

This dynamically defines the padding style for trial numbers. This is helpful to ensure the filesystem consistently sorts the trials.

Examples: - Suppose you n_trials is 2000 (and the nominal trial_num is 0) - This method would return 04d - Trial number 0 maps to 0000 - Trial number 123 maps to 0123 - Trial number 1999 will still map to 1999

MonteCarloConfig

Bases: BaseConfig

n_trial class-attribute instance-attribute

Python
n_trial: int = DEFAULT_MC_N_TRIAL

Number of trials to run.

You are able to resume a previous job and modify the number of runs desired by changing this value. A job already in progress will not be dynamically stopped though if you change this value at runtime.

n_proc class-attribute instance-attribute

Python
n_proc: int = DEFAULT_N_PROC

Number of proccesses to allow.

This value is used to determine how many parallel jobs can be run. It is also used for the discovery of trial status. Using a value of 1 will result in the slowest runtime, but highest reliability.

Important

Be a good citizen. Use a reasonable number if you are working on a shared resource. You are a jerk if you use everything.

resume class-attribute instance-attribute

Python
resume: bool = DEFAULT_RESUME

Whether to resume a study if the study already exists.

padding class-attribute instance-attribute

Python
padding: int | None = Field(default=None, ge=1)

Zero-padding width of the trial folder names (for example 3 gives trial_007). When unset, the width is derived from n_trial so every trial in a job sorts consistently; set it when a process only knows about one trial of a larger job, such as a SLURM worker.

padding_style property

Python
padding_style: str

This dynamically defines the padding style for trial numbers. This is helpful to ensure the filesystem consistently sorts the trials.

Examples: - Suppose you n_trials is 2000 (and the nominal trial_num is 0) - This method would return 04d - Trial number 0 maps to 0000 - Trial number 123 maps to 0123 - Trial number 1999 will still map to 1999

OptimizerConfig

Bases: BaseConfig

n_trial class-attribute instance-attribute

Python
n_trial: int = DEFAULT_OP_N_TRIAL

Number of trials to run.

study_name class-attribute instance-attribute

Python
study_name: str = DEFAULT_OP_STUDY_NAME

Unique identifier for the Optuna study.

direction instance-attribute

Python
direction: Direction

Whether we want to find the lowest or highest objective value.

timeout class-attribute instance-attribute

Python
timeout: float | None = DEFAULT_OP_TIMEOUT

Stop the study after this many seconds, regardless of trial count.

storage class-attribute instance-attribute

Python
storage: str | None = DEFAULT_OP_STORAGE

Database URL (e.g., 'sqlite:///study.db') for multi-node persistence.

sampler class-attribute instance-attribute

Python
sampler: Sampler = DEFAULT_OP_SAMPLER

The search algorithm. TPE is generally best for noisy physics.

evals_per_trial class-attribute instance-attribute

Python
evals_per_trial: int = Field(
    default=DEFAULT_OP_EVALS_PER_TRIAL, ge=1
)

Number of times to run the sim with different seeds per trial. The average score is returned to Optuna.

Reduces 'lucky' trials in noisy physics.

refine_search_factor class-attribute instance-attribute

Python
refine_search_factor: float | None = Field(
    default=DEFAULT_OP_REFINE_SEARCH_FACTOR, gt=0, lt=1
)

If set (e.g., 0.5), and resume is True, the Runner will shrink the search space bounds by this factor around the current best trial to focus on local refinement.

Smaller values will more aggressively refine the search space.

prune_failed_trials class-attribute instance-attribute

Python
prune_failed_trials: bool = DEFAULT_OP_PRUNE_FAILED_TRIALS

Whether to immediately stop trials that violate physical constraints (e.g., Mujoco instability) to save compute time.

n_proc class-attribute instance-attribute

Python
n_proc: int = DEFAULT_N_PROC

Number of proccesses to allow.

This value is used to determine how many parallel jobs can be run. It is also used for the discovery of trial status. Using a value of 1 will result in the slowest runtime, but highest reliability.

Important

Be a good citizen. Use a reasonable number if you are working on a shared resource. You are a jerk if you use everything.

resume class-attribute instance-attribute

Python
resume: bool = DEFAULT_RESUME

Whether to resume a study if the study already exists.

padding class-attribute instance-attribute

Python
padding: int | None = Field(default=None, ge=1)

Zero-padding width of the trial folder names (for example 3 gives trial_007). When unset, the width is derived from n_trial so every trial in a job sorts consistently; set it when a process only knows about one trial of a larger job, such as a SLURM worker.

padding_style property

Python
padding_style: str

This dynamically defines the padding style for trial numbers. This is helpful to ensure the filesystem consistently sorts the trials.

Examples: - Suppose you n_trials is 2000 (and the nominal trial_num is 0) - This method would return 04d - Trial number 0 maps to 0000 - Trial number 123 maps to 0123 - Trial number 1999 will still map to 1999

Trial dataclass

Python
Trial(
    trial_num: int,
    base_dir: Path,
    xml_name: str,
    model_config_name: str | None,
    padding_style: str,
)

Handles the lifecycle of a single simulation run.

The Trial object is responsible for the 'dirty work' of a Monte Carlo run: - Creating directories - Writing the MJCF XML - Saving the configuration snapshot - Triggering the physics runtime.

trial_num instance-attribute

Python
trial_num: int

Unique identifier for this trial iteration.

base_dir instance-attribute

Python
base_dir: Path

Root directory where all simulation trials are stored.

xml_name instance-attribute

Python
xml_name: str

Filename for the generated MJCF XML (e.g., 'model.xml').

model_config_name instance-attribute

Python
model_config_name: str | None

Filename for the serialized MojoModel configuration (e.g., 'config.json').

padding_style instance-attribute

Python
padding_style: str

Format specifier for directory naming (e.g., '04d').

trial_dir property

Python
trial_dir: Path

The absolute path to this trial's unique workspace.

Example

If base_dir is './sims' and trial_num is 7 with '03d' padding, this returns './sims/trial_007'.

xml_path property

Python
xml_path: Path

The full path to the MJCF XML file for this trial.

model_config_path property

Python
model_config_path: Path

The full path to the JSON configuration file for this trial.

named_value_path property

Python
named_value_path: Path

The full path to the JSON NamedValue file for this trial.

run

Python
run(
    generator: MojoGenerator,
    runtime: MojoRuntime | None,
    seed: int | None,
    overrides: NamedValueDict[NDArray],
    args: Sequence[Any],
    kwargs: Mapping[str, Any],
) -> tuple[MojoModel | None, TrialStatus, MjState | None]

Executes the complete simulation pipeline for this trial.

This method coordinates three main phases: 1. Generation: Calls the user-provided generator to build a MojoModel model. 2. Persistence: Creates the workspace and writes the model/config to disk. 3. Execution: Triggers the physics runtime if one is provided.

Parameters:

Name Type Description Default
generator MojoGenerator

Function that returns a MojoModel instance.

required
runtime MojoRuntime | None

Optional function to run the simulation (MuJoCo).

required
seed int | None

Seed to use to define the trial.

required
overrides NamedValueDict[NDArray]

Key-value pairs that override random distributions.

required
args Sequence[Any]

Positional arguments passed to the generator and the runtime.

required
kwargs Mapping[str, Any]

Keyword arguments, each function receiving only the ones it accepts.

required

Returns:

Type Description
tuple[MojoModel | None, TrialStatus, MjState | None]

The MojoModel object for the trial or None if there was a failure prior to generating the MojoModel and the status of the trial.

Source code in src/mujoco_mojo/utils/runner.py
Python
def run(
    self,
    generator: MojoGenerator,
    runtime: MojoRuntime | None,
    seed: int | None,
    overrides: NamedValueDict[NDArray],
    args: Sequence[Any],
    kwargs: Mapping[str, Any],
) -> tuple[MojoModel | None, TrialStatus, MjState | None]:
    """
    Executes the complete simulation pipeline for this trial.

    This method coordinates three main phases:
    1.  **Generation**: Calls the user-provided generator to build a `MojoModel` model.
    2.  **Persistence**: Creates the workspace and writes the model/config to disk.
    3.  **Execution**: Triggers the physics runtime if one is provided.

    Args:
        generator: Function that returns a `MojoModel` instance.
        runtime: Optional function to run the simulation (MuJoCo).
        seed: Seed to use to define the trial.
        overrides: Key-value pairs that override random distributions.
        args: Positional arguments passed to the generator and the runtime.
        kwargs: Keyword arguments, each function receiving only the ones it accepts.

    Returns:
        The `MojoModel` object for the trial or None if there was a failure prior to generating the MojoModel and the status of the trial.

    """
    status = TrialStatus(trial_num=self.trial_num)
    status._path = self.trial_dir / TRIAL_STATUS_FNAME

    # set up a per-trial log file capturing everything logged during this trial
    self.trial_dir.mkdir(parents=True, exist_ok=True)
    trial_log_handler = get_trial_log_handler(self.trial_dir / "mojo.log")
    root_logger = logging.getLogger()
    root_logger.addHandler(trial_log_handler)

    with status.record_step(step_name="pending"):
        pass

    from mujoco_mojo.runtime.requirements_manager import RequirementSatisfied
    from mujoco_mojo.runtime.runtime_manager import SimulationStopped

    result = None
    state = None
    runtime_manager: RuntimeManager | None = None
    try:
        # 1. Generate
        with status.record_step(step_name="generating"):
            logger.info(f"Generating trial_num={self.trial_num}")
            mojo_model = (
                MojoModel()
                .with_overrides(overrides=overrides)
                .with_seed(seed=seed)
                .with_trial_num(self.trial_num)
            )
            mojo_model = generator(
                mojo_model,
                overrides,
                *args,
                **select_kwargs(generator, GENERATOR_FIXED_ARGS, args, kwargs),
            )
            mojo_model._trial_dir = self.trial_dir

            # 2. Setup Workspace & Save Metadata
            logger.info(f"Saving trial_num={self.trial_num} to {self.trial_dir}")

            # bundle assets, this remaps DepPath attributes to point to the shared asset dir
            rel_to_xml = Path(
                os.path.relpath(self.shared_asset_dir, self.trial_dir)
            )
            mojo_model.mjcf.bundle_assets(
                target_dir=self.shared_asset_dir, rel_to_xml=rel_to_xml
            )

            # save XML (with modified DepPath)
            if runtime is None:
                mojo_model.mjcf.write_xml(self.xml_path)
            if self.model_config_name:
                mojo_model.dump_to_path(self.model_config_path)
            self.named_value_path.write_text(mojo_model.named.model_dump_json())

        with status.record_step(step_name="solving"):
            # 3. Execute (if runtime provided)
            if runtime is not None:
                logger.info(f"Executing trial_num={self.trial_num} runtime")
                import mujoco_mojo.runtime as rt

                runtime_manager = rt.RuntimeManager(
                    signal_manager=rt.SignalManager(
                        export_path=self.trial_dir
                        / rt.SignalManager.default_output_name(),
                        unit_system=mojo_model.us,
                    )
                )
                runtime_manager._mojo_model = mojo_model
                state = mojo_model.mjcf.prep_for_sim(
                    self.xml_path, unit_system=mojo_model.us
                )
                result = runtime(
                    mojo_model,
                    runtime_manager,
                    state,
                    *args,
                    **select_kwargs(runtime, RUNTIME_FIXED_ARGS, args, kwargs),
                )
                status.requirements = runtime_manager.requirement_results
            else:
                logger.info(
                    f"No runtime definition was provided for trial_num={self.trial_num} so MuJoCo will not be run."
                )
                result = mojo_model
                state = None

        # serialize again in case new named values were added during the run
        if self.model_config_name:
            mojo_model.dump_to_path(self.model_config_path)
        self.named_value_path.write_text(mojo_model.named.model_dump_json())

        # clear unpicklable collision managers before returing to avoid multiprocessing serialization erros
        mojo_model.clear_unpickleable_data()

        status.step = "done"
        if status.requirements and not all(r.passed for r in status.requirements):
            status.completion = Completion.FAILURE
        else:
            status.completion = Completion.SUCCESS

    except (BdbQuit, KeyboardInterrupt):
        logger.warning("Quit command detected. Exiting execution...")
        raise
    except RequirementSatisfied:
        # a live requirement ended the trial early as a success: complete
        # normally, with the outcome decided by the requirement results
        status.step = "done"
        if runtime_manager is not None:
            status.requirements = runtime_manager.requirement_results
        if status.requirements and not all(r.passed for r in status.requirements):
            status.completion = Completion.FAILURE
        else:
            status.completion = Completion.SUCCESS
    except SimulationStopped:
        status.step = "done"
        status.completion = Completion.TERMINATED
        if runtime_manager is not None:
            status.requirements = runtime_manager.requirement_results
    except Exception as e:
        status.step = "done"
        status.completion = Completion.ERROR
        logger.exception(
            f"Trial {self.trial_num} failed with the following error: {e}"
        )
    finally:
        status.dump_to_path(status._path)
        root_logger.removeHandler(trial_log_handler)
        trial_log_handler.close()

    return result, status, state

MojoRunner dataclass

Python
MojoRunner(
    generator: MojoGenerator,
    generator_path: str | None = None,
    runtime: MojoRuntime | None = DEFAULT_RUNTIME,
    runtime_path: str | None = None,
    objective: MojoObjective | None = None,
    objective_path: str | None = None,
    seed: int | None = DEFAULT_SEED,
    workdir: Path = DEFAULT_WORKDIR,
    model_config_name: str
    | None = DEFAULT_MODEL_CONFIG_NAME,
    xml_name: str = DEFAULT_XML_NAME,
    config: MonteCarloConfig
    | OptimizerConfig = MonteCarloConfig(),
    args: list[Any] = list(),
    kwargs: dict[str, Any] = dict(),
)

args class-attribute instance-attribute

Python
args: list[Any] = field(default_factory=list)

Positional arguments passed to the generator, the runtime, and the objective.

kwargs class-attribute instance-attribute

Python
kwargs: dict[str, Any] = field(default_factory=dict)

Keyword arguments shared by the generator, the runtime, and the objective. Each receives only the ones it accepts (all of them if it takes **kwargs).

slurm_trial_id property

Python
slurm_trial_id: int | None

Returns the current SLURM task ID if running as part of an array job.

shared_argument_flags

Python
shared_argument_flags() -> str

The --arg and --kwarg options that hand this runner's arguments to another mujoco-mojo process, such as a SLURM worker.

Source code in src/mujoco_mojo/utils/runner.py
Python
def shared_argument_flags(self) -> str:
    """The `--arg` and `--kwarg` options that hand this runner's arguments to another `mujoco-mojo` process, such as a SLURM worker."""
    flags = [f'--arg "{a}"' for a in self.args]
    flags += [f'--kwarg "{k}={v}"' for k, v in self.kwargs.items()]
    return " ".join(flags)

validate_kwargs

Python
validate_kwargs() -> None

Raises ValueError if a keyword argument is accepted by none of the generator, the runtime, and the objective.

Each function is only given the keywords it accepts, so a misspelled one would otherwise be dropped silently. A function that takes **kwargs accepts everything, which turns the check off.

Source code in src/mujoco_mojo/utils/runner.py
Python
def validate_kwargs(self) -> None:
    """
    Raises `ValueError` if a keyword argument is accepted by none of the generator, the runtime, and the objective.

    Each function is only given the keywords it accepts, so a misspelled one would otherwise be dropped silently. A function that takes `**kwargs` accepts everything, which turns the check off.
    """
    targets: dict[str, tuple[Callable[..., Any], int]] = {
        "generator": (self.generator, GENERATOR_FIXED_ARGS)
    }
    if self.runtime is not None:
        targets["runtime"] = (self.runtime, RUNTIME_FIXED_ARGS)
    if self.objective is not None:
        targets["objective"] = (self.objective, OBJECTIVE_FIXED_ARGS)
    validate_shared_kwargs(self.kwargs, self.args, targets)

run

Python
run(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    execution_mode: ExecutionMode = LOCAL,
    trial_nums: list[int] | None = None,
) -> bool

Vectors a job to be either computed locally or to be orchestrated by SLURM.

Source code in src/mujoco_mojo/utils/runner.py
Python
def run(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    execution_mode: ExecutionMode = ExecutionMode.LOCAL,
    trial_nums: list[int] | None = None,
) -> bool:
    """Vectors a job to be either computed locally or to be orchestrated by SLURM."""
    self._prepare_run(clean_workdir, cleanup_delay)

    match execution_mode:
        case ExecutionMode.LOCAL:
            return self.run_local(
                global_overrides=global_overrides,
                trial_nums=trial_nums,
            )
        case ExecutionMode.SLURM:
            return self.orchestrate_slurm(
                global_overrides=global_overrides,
                trial_nums=trial_nums,
            )
        case _:
            msg = f"No run command has been configured for execution mode {execution_mode}"
            logger.error(msg)
            raise NotImplementedError(msg)

orchestrate_slurm

Python
orchestrate_slurm(
    global_overrides: NamedValueDict[NDArray],
    trial_nums: list[int] | None = None,
) -> bool

Generates an sbatch script and submits the job array to SLURM for a given config.

Source code in src/mujoco_mojo/utils/runner.py
Python
def orchestrate_slurm(
    self,
    global_overrides: NamedValueDict[NDArray],
    trial_nums: list[int] | None = None,
) -> bool:
    """Generates an sbatch script and submits the job array to SLURM for a given config."""
    (self.workdir / "logs").mkdir(exist_ok=True)

    from rich.console import Console

    Console().print(
        "[dim]Tip: set '[slurm]' entries in ~/.mujoco-mojo/settings.toml (or a project-local "
        "./.mujoco-mojo/settings.toml, via `mujoco-mojo settings set --project`) to auto-inject "
        "extra #SBATCH lines (prefix a key with 'sbatch.', e.g. 'sbatch.account') and/or "
        "environment variables (any other key) into the generated submission script.[/dim]"
    )

    if isinstance(self.config, MonteCarloConfig):
        try:
            had_fails = self.orchestrate_slurm_monte_carlo(
                global_overrides=global_overrides,
                trial_nums=trial_nums,
            )
        except (BdbQuit, KeyboardInterrupt):
            print("\n")
            logger.error("Aborted SLURM orchestration!")
            had_fails = True
    else:
        msg = f"A SLURM configuration for {self.config.__class__.__name__} has not been implemented."
        logger.error(msg)
        raise NotImplementedError(msg)
    return had_fails

execute_single_trial

Python
execute_single_trial(
    trial_num: int,
    seed: int | None,
    overrides_payload: dict[str, Any],
) -> tuple[MojoModel | None, TrialStatus, MjState | None]

Helper to package a Trial and run it.

The model and state are live in-process objects; callers that need to cross a ProcessPoolExecutor boundary (i.e. parallel MC) must use _execute_trial_subprocess instead, which drops the non-picklable objects before the result is serialized back.

Returns (mojo_model, trial_status, state).

Source code in src/mujoco_mojo/utils/runner.py
Python
def execute_single_trial(
    self, trial_num: int, seed: int | None, overrides_payload: dict[str, Any]
) -> tuple[MojoModel | None, TrialStatus, MjState | None]:
    """
    Helper to package a Trial and run it.

    The model and state are live in-process objects; callers that need to cross a ProcessPoolExecutor boundary (i.e. parallel MC) must use `_execute_trial_subprocess` instead, which drops the non-picklable objects before the result is serialized back.

    Returns `(mojo_model, trial_status, state)`.
    """
    overrides = NamedValueDict[NDArray].model_validate(overrides_payload)

    trial = Trial(
        trial_num=trial_num,
        base_dir=self.workdir,
        xml_name=self.xml_name,
        model_config_name=self.model_config_name,
        padding_style=self.config.padding_style,
    )

    mojo_model, trial_status, state = trial.run(
        generator=self.generator,
        runtime=self.runtime,
        seed=seed,
        overrides=overrides,
        args=self.args,
        kwargs=self.kwargs,
    )

    # write distribution tables from this process so they never need to
    # cross the pickle boundary; FileLock serializes concurrent workers,
    # and the inner exists() check ensures only the first one writes
    if mojo_model is not None and mojo_model.dists:
        stochas_dir = self.workdir / STOCHAS_DIR_NAME
        stochas_dir.mkdir(exist_ok=True)
        dists_json_path = stochas_dir / STOCHAS_DISTS_FNAME
        with FileLock(stochas_dir / ".dists.lock"):
            if not dists_json_path.exists():
                mojo_model.dists.to_tables(stochas_dir)
                tmp = stochas_dir / "dists.tmp.json"
                tmp.write_text(mojo_model.dists.model_dump_json(), encoding="utf-8")
                tmp.replace(dists_json_path)

    return mojo_model, trial_status, state

run_monte_carlo

Python
run_monte_carlo(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool

Orchestrates a Monte Carlo job.

Source code in src/mujoco_mojo/utils/runner.py
Python
def run_monte_carlo(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool:
    """Orchestrates a Monte Carlo job."""
    if self.slurm_trial_id is not None:
        tn = self.slurm_trial_id
        logger.info(f"SLURM Worker detected. Executing Trial {tn}")
        _mojo_model, trial_status, _ = self.execute_single_trial(
            trial_num=tn,
            seed=self.seed,
            overrides_payload=global_overrides.model_dump(),
        )

        return trial_status.completion == Completion.ERROR

    job_trial_nums = trial_nums if trial_nums else self.config.trial_nums

    # initialize the status tracker
    status_tracker = JobStatus(
        workdir=self.workdir.resolve(),
        job_type=JobType.MONTE_CARLO,
        execution_mode=ExecutionMode.LOCAL,
        n_proc=self.config.n_proc,
        seed=self.seed,
        padding_style=self.config.padding_style,
        generator=MojoRunner.inspect_protocol(self.generator),
        runtime=MojoRunner.inspect_protocol(self.runtime),
        objective=MojoRunner.inspect_protocol(self.objective),
        args_used=describe_args(self.args),
        kwargs_used=describe_kwargs(self.kwargs),
        trial_nums=job_trial_nums,
    )

    # decide which trials to execute
    if self.config.resume:
        self._renumber_trial_folders(
            self.workdir.resolve(), self.config.padding_style
        )
        status_tracker.refresh_from_disk(n_proc=self.config.n_proc)
    status_tracker.dump_to_path(self.workdir / JOB_STATUS_FNAME)

    to_run = status_tracker.pending_trial_nums

    if not to_run:
        logger.info("All trials were already completed. Nothing to do.")
        return bool(status_tracker.unsuccessful_trial_nums)

    if self.config.is_parallel:
        logger.info(
            f"Running {len(to_run)} trials with {self.config.n_proc} processors. {status_tracker.n_done}/{self.config.n_trial} ({status_tracker.progress:.2%}) trials completed."
        )
        # needed for logging on Windows
        with multiprocessing.Manager() as m:
            log_queue = m.Queue()

            parent_log_level = logging.getLogger().getEffectiveLevel()
            listener = QueueListener(log_queue, *logging.getLogger().handlers)
            listener.start()

            executor = ProcessPoolExecutor(
                max_workers=self.config.n_proc,
                initializer=worker_init,
                initargs=(log_queue, parent_log_level),
            )
            try:
                future_to_tn = {
                    executor.submit(
                        self._execute_trial_subprocess,
                        tn,
                        self.seed,
                        global_overrides.model_dump(),
                    ): tn
                    for tn in to_run
                }
                for f in as_completed(future_to_tn):
                    tn = future_to_tn[f]
                    try:
                        trial_status = f.result()
                        status_tracker.update_trial(status=trial_status)
                    except (BdbQuit, KeyboardInterrupt):
                        # user is quitting from breakpoint() or CTRL+C
                        raise
                    except Exception as e:
                        logger.exception(f"Trial {tn} failed: {e}")
                        status_tracker.update_trial(
                            status=TrialStatus(
                                trial_num=tn, completion=Completion.ERROR
                            )
                        )
                    status_tracker.generate_report()
            except (BdbQuit, KeyboardInterrupt):
                # allows killing the job with one CTRL+C
                logger.warning("Interrupt recieved. Stopping all trials.")
                executor.shutdown(wait=False, cancel_futures=True)
                raise
            finally:
                listener.stop()
                executor.shutdown(wait=True)
    else:
        for tn in to_run:
            try:
                _, trial_status, _ = self.execute_single_trial(
                    trial_num=tn,
                    seed=self.seed,
                    overrides_payload=global_overrides.model_dump(),
                )
                status_tracker.update_trial(
                    status=trial_status,
                )
            except (BdbQuit, KeyboardInterrupt):
                # user is quitting from breakpoint() or CTRL+C
                raise
            except Exception as e:
                logger.exception(f"A trial failed with error: {e}")
                status_tracker.update_trial(
                    status=TrialStatus(trial_num=tn, completion=Completion.ERROR)
                )
            status_tracker.generate_report()

    status_tracker.generate_report(alert_generation=True)
    return bool(status_tracker.unsuccessful_trial_nums)

get_slurm_array_string staticmethod

Python
get_slurm_array_string(ids: list[int]) -> str

Collapses [0, 1, 2, 5, 6] into '0-2,5-6' for SLURM.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_array_string(ids: list[int]) -> str:
    """Collapses [0, 1, 2, 5, 6] into '0-2,5-6' for SLURM."""
    if not ids:
        return ""

    ranges = []
    # Identify groups of consecutive integers
    for _, group in itertools.groupby(
        enumerate(sorted(ids)), lambda x: x[1] - x[0]
    ):
        group = list(group)
        start = group[0][1]
        end = group[-1][1]
        if start == end:
            ranges.append(str(start))
        else:
            ranges.append(f"{start}-{end}")

    return ",".join(ranges)

get_slurm_partitions staticmethod

Python
get_slurm_partitions() -> tuple[list[str], str | None]

Queries sinfo for available partitions and identifies the default.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_partitions() -> tuple[list[str], str | None]:
    """Queries sinfo for available partitions and identifies the default."""
    try:
        result = subprocess.run(
            ["sinfo", "-h", "--format=%P"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            raw_partitions = [
                p.strip() for p in result.stdout.splitlines() if p.strip()
            ]

            default_partition = None
            clean_partitions = []

            for p in raw_partitions:
                if p.endswith("*"):
                    name = p.replace("*", "")
                    default_partition = name
                    clean_partitions.append(name)
                else:
                    clean_partitions.append(p)

            return sorted(list(set(clean_partitions))), default_partition
    except Exception:
        pass
    return [], None

normalize_to_mb staticmethod

Python
normalize_to_mb(mem_str: str) -> int

Converts SLURM memory strings (e.g., '1000', '1G', '1024M', '125.9G') to integer MB, or 0 if the string isn't a recognizable size. See mujoco_mojo.utils.slurm.normalize_to_mb.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def normalize_to_mb(mem_str: str) -> int:
    """Converts SLURM memory strings (e.g., '1000', '1G', '1024M', '125.9G') to integer MB, or 0 if the string isn't a recognizable size. See `mujoco_mojo.utils.slurm.normalize_to_mb`."""
    return normalize_to_mb(mem_str)

format_bytes staticmethod

Python
format_bytes(mb_value: int) -> str

Scales MB back up to the most readable unit (G, T, etc.), with at most one decimal place. The value is rounded down, never up, so a limit shown to the user is never larger than the real limit; normalize_to_mb reads the result back.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def format_bytes(mb_value: int) -> str:
    """Scales MB back up to the most readable unit (G, T, etc.), with at most one decimal place. The value is rounded down, never up, so a limit shown to the user is never larger than the real limit; `normalize_to_mb` reads the result back."""
    units = ["M", "G", "T", "P"]
    value = float(mb_value)
    unit_index = 0

    # keep dividing by 1024 for as long as the next unit is reached
    while value >= 1024 and unit_index < len(units) - 1:
        value /= 1024
        unit_index += 1

    # floor to one decimal: rounding up could show more memory than the node has
    floored = math.floor(value * 10) / 10
    # if it's a whole number (like 1.0G), show it as 1G, otherwise one decimal place (like 1.5G)
    if floored.is_integer():
        return f"{int(floored)}{units[unit_index]}"
    return f"{floored:.1f}{units[unit_index]}"

get_slurm_node_mem_limit staticmethod

Python
get_slurm_node_mem_limit(partition_name: str) -> str

Finds the MINIMUM RealMemory limit, normalized to MB.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_node_mem_limit(partition_name: str) -> str:
    """Finds the MINIMUM RealMemory limit, normalized to MB."""
    try:
        # 1. Get nodes from partition
        part_info = subprocess.run(
            ["scontrol", "show", "partition", partition_name, "-o"],
            capture_output=True,
            text=True,
        ).stdout
        node_match = re.search(r"\bNodes=(\S+)", part_info)
        if not node_match:
            return "<UNKNOWN>"

        # 2. Get node info (can handle ranges like c[1-2])
        node_info = subprocess.run(
            ["scontrol", "show", "node", node_match.group(1), "-o"],
            capture_output=True,
            text=True,
        ).stdout

        # 3. Find all RealMemory values (capturing optional suffixes)
        # Regex captures digits and any trailing letters (like G or M)
        mem_matches = re.findall(r"\bRealMemory=(\d+(?:\.\d+)?[KMGTP]?)", node_info)
        if mem_matches:
            # Normalize every match to MB and find the lowest one
            min_mb = min(MojoRunner.normalize_to_mb(m) for m in mem_matches)
            return MojoRunner.format_bytes(min_mb)

    except Exception:
        pass

    return "<UNKNOWN>"

get_slurm_cpu_limit staticmethod

Python
get_slurm_cpu_limit(partition_name: str) -> str

Finds the minimum of the max allowed CPUs (CPUTot) among nodes in a partition.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_cpu_limit(partition_name: str) -> str:
    """Finds the minimum of the max allowed CPUs (CPUTot) among nodes in a partition."""
    try:
        # 1. Get the nodes in the partition
        part_cmd = ["scontrol", "show", "partition", partition_name, "-o"]
        part_info = subprocess.run(part_cmd, capture_output=True, text=True).stdout

        node_match = re.search(r"\bNodes=(\S+)", part_info)
        if not node_match:
            return "<UNKNOWN>"

        # 2. Get the node info
        node_cmd = ["scontrol", "show", "node", node_match.group(1), "-o"]
        nodes_info = subprocess.run(node_cmd, capture_output=True, text=True).stdout

        # 3. Find all CPUTot values (The total physical/logical CPUs on the node)
        cpu_values = re.findall(r"\bCPUTot=(\d+)", nodes_info)

        if cpu_values:
            # Find the minimum to ensure any node can handle the task
            return str(min(int(v) for v in cpu_values))

    except Exception:
        pass

    return "<UNKNOWN>"

slurm_time_to_seconds staticmethod

Python
slurm_time_to_seconds(time_str: str) -> int

Converts a SLURM time limit to total seconds, or -1 for UNLIMITED. See mujoco_mojo.utils.slurm.slurm_time_to_seconds.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def slurm_time_to_seconds(time_str: str) -> int:
    """Converts a SLURM time limit to total seconds, or -1 for `UNLIMITED`. See `mujoco_mojo.utils.slurm.slurm_time_to_seconds`."""
    return slurm_time_to_seconds(time_str)

get_slurm_time_limit staticmethod

Python
get_slurm_time_limit(partition_name: str) -> str

Finds the MaxTime limit for a specific partition.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_time_limit(partition_name: str) -> str:
    """Finds the MaxTime limit for a specific partition."""
    try:
        # Get partition info
        part_cmd = ["scontrol", "show", "partition", partition_name, "-o"]
        part_info = subprocess.run(part_cmd, capture_output=True, text=True).stdout

        # Look for MaxTime= followed by the time string (e.g., 1-00:00:00 or UNLIMITED)
        time_match = re.search(r"\bMaxTime=(\S+)", part_info)
        if time_match:
            return str(time_match.group(1))

    except Exception:
        pass

    return "<UNKNOWN>"

get_max_array_size staticmethod

Python
get_max_array_size() -> int

Queries the global SLURM configuration for MaxArraySize.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_max_array_size() -> int:
    """Queries the global SLURM configuration for MaxArraySize."""
    try:
        result = subprocess.run(
            ["scontrol", "show", "config"], capture_output=True, text=True
        ).stdout
        match = re.search(r"MaxArraySize=(\d+)", result)
        return int(match.group(1)) if match else 1001
    except Exception:
        return 1001

slurm_mojo_command staticmethod

Python
slurm_mojo_command() -> Path

The mujoco-mojo executable next to the running interpreter, which the compute nodes use to run each trial.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def slurm_mojo_command() -> Path:
    """The `mujoco-mojo` executable next to the running interpreter, which the compute nodes use to run each trial."""
    return Path(sys.executable).parent.resolve() / "mujoco-mojo"

prepare_slurm_job

Python
prepare_slurm_job(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> SlurmJob | None

Sets up the workdir for a SLURM submission without asking anything.

Creates the logs folder, persists the global overrides for the workers, writes job_status.json, and works out which trials still need to run (honoring resume).

Returns:

Type Description
SlurmJob | None

The job, or None when every trial was already completed.

Source code in src/mujoco_mojo/utils/runner.py
Python
def prepare_slurm_job(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> SlurmJob | None:
    """
    Sets up the workdir for a SLURM submission without asking anything.

    Creates the logs folder, persists the global overrides for the workers, writes `job_status.json`, and works out which trials still need to run (honoring `resume`).

    Returns:
        The job, or `None` when every trial was already completed.

    """
    (self.workdir / "logs").mkdir(parents=True, exist_ok=True)

    # persist overrides so workers can access them
    overrides_path = self.workdir.resolve() / "global_overrides.json"
    has_overrides = len(global_overrides) > 0
    if has_overrides:
        logger.info(f"Persisting global overrides to {overrides_path}")
        overrides_path.write_text(global_overrides.model_dump_json())

    job_trial_nums = trial_nums if trial_nums else self.config.trial_nums
    status_tracker = JobStatus(
        workdir=self.workdir.resolve(),
        job_type=JobType.MONTE_CARLO,
        execution_mode=ExecutionMode.SLURM,
        n_proc=self.config.n_proc,
        seed=self.seed,
        padding_style=self.config.padding_style,
        generator=MojoRunner.inspect_protocol(self.generator),
        runtime=MojoRunner.inspect_protocol(self.runtime),
        objective=MojoRunner.inspect_protocol(self.objective),
        args_used=describe_args(self.args),
        kwargs_used=describe_kwargs(self.kwargs),
        trial_nums=job_trial_nums,
    )

    # decide which trials to execute
    if self.config.resume:
        self._renumber_trial_folders(
            self.workdir.resolve(), self.config.padding_style
        )
        status_tracker.refresh_from_disk(n_proc=self.config.n_proc)
    status_tracker.dump_to_path(self.workdir / JOB_STATUS_FNAME)

    to_run = status_tracker.pending_trial_nums
    if not to_run:
        logger.info("All trials were already completed. Nothing to do.")
        return None
    logger.info(f"{len(to_run)} trials were identified for running.")

    return SlurmJob(
        status=status_tracker,
        to_run=to_run,
        overrides_path=overrides_path,
        has_overrides=has_overrides,
    )

slurm_worker_command

Python
slurm_worker_command(job: SlurmJob) -> str

What each array task runs: one trial, picked by the array index, on a single process.

Source code in src/mujoco_mojo/utils/runner.py
Python
def slurm_worker_command(self, job: SlurmJob) -> str:
    """What each array task runs: one trial, picked by the array index, on a single process."""
    runtime_flag = f'--runtime "{self.runtime_path}"' if self.runtime_path else ""
    seed_flag = f"--seed {self.seed}" if self.seed is not None else ""
    overrides_flag = (
        f'--overrides "{job.overrides_path}"' if job.has_overrides else ""
    )
    return (
        f"{self.slurm_mojo_command()} run single "
        f'--generator "{self.generator_path}" '
        f"{runtime_flag} {seed_flag} {overrides_flag} "
        f'--workdir "{self.workdir.resolve()}" '
        f"{self.shared_argument_flags()} "
        f"--padding {self.config.padding_width} "  # name the trial folder like the orchestrator expects
        f"--trial-num $SLURM_ARRAY_TASK_ID "  # execute its own trial_num
        f"--execution-mode local "  # using local since slurm will just send us back to this method
        f"--n-proc 1"  # a worker only needs 1 process
    )

write_slurm_script

Python
write_slurm_script(
    job: SlurmJob, config: SlurmConfig, console: Console
) -> Path

Writes mujoco_mojo_submit.sh for job, adding the extra #SBATCH lines and environment variables from the settings files (and printing what they are).

Source code in src/mujoco_mojo/utils/runner.py
Python
def write_slurm_script(
    self, job: SlurmJob, config: SlurmConfig, console: Console
) -> Path:
    """Writes `mujoco_mojo_submit.sh` for `job`, adding the extra `#SBATCH` lines and environment variables from the settings files (and printing what they are)."""
    from mujoco_mojo.settings import MujocoMojoSettings

    slurm_settings = MujocoMojoSettings().slurm
    _print_slurm_extras(console, slurm_settings)

    script = build_submission_script(
        job_name=config.job_name or f"mojo-sim-{job.status.id}",
        array_range=self.get_slurm_array_string(job.to_run),
        workdir=self.workdir.resolve(),
        config=config,
        worker_command=self.slurm_worker_command(job),
        extra_sbatch_lines=slurm_settings.sbatch_lines(),
        extra_env_lines=slurm_settings.env_lines(),
    )
    script_path = (self.workdir / "mujoco_mojo_submit.sh").resolve()
    script_path.write_text(script, encoding="utf-8")
    logger.info(f"SLURM submission script written to {script_path}")
    return script_path

submit_slurm_script

Python
submit_slurm_script(
    job: SlurmJob, script_path: Path
) -> SlurmSubmission

Runs sbatch on the script and, once it is accepted, saves the SLURM job id in job_status.json so the job can be looked up (and watched) later.

Source code in src/mujoco_mojo/utils/runner.py
Python
def submit_slurm_script(self, job: SlurmJob, script_path: Path) -> SlurmSubmission:
    """Runs `sbatch` on the script and, once it is accepted, saves the SLURM job id in `job_status.json` so the job can be looked up (and watched) later."""
    logger.info(f"Submitting {len(job.to_run)} trials...")
    try:
        result = subprocess.run(
            ["sbatch", "--parsable", str(script_path)],
            capture_output=True,
            text=True,
        )
    except OSError as exc:
        return SlurmSubmission(script_path, message=f"Could not run sbatch: {exc}")
    if result.returncode != 0:
        return SlurmSubmission(
            script_path, message=(result.stderr or result.stdout).strip()
        )

    job_id = parse_job_id(result.stdout)
    job.status.slurm_job_id = job_id
    job.status.dump_to_path(self.workdir / JOB_STATUS_FNAME)
    return SlurmSubmission(
        script_path,
        submitted=True,
        job_id=job_id,
        message=f"Submitted batch job {job_id}"
        if job_id
        else result.stdout.strip(),
    )

slurm_limit_problems

Python
slurm_limit_problems(
    job: SlurmJob, config: SlurmConfig
) -> list[str]

Everything in the request that exceeds what the cluster reports (CPUs, memory, and time for the partition, and the array size). Limits SLURM cannot report are not checked.

Source code in src/mujoco_mojo/utils/runner.py
Python
def slurm_limit_problems(self, job: SlurmJob, config: SlurmConfig) -> list[str]:
    """Everything in the request that exceeds what the cluster reports (CPUs, memory, and time for the partition, and the array size). Limits SLURM cannot report are not checked."""
    partition = config.partition or ""
    checks = (
        cpu_problem(config.cpus_per_task, self.get_slurm_cpu_limit(partition)),
        mem_problem(config.mem, self.get_slurm_node_mem_limit(partition)),
        time_problem(config.time_limit, self.get_slurm_time_limit(partition)),
        array_problem(len(job.to_run), self.get_max_array_size()),
    )
    return [problem for problem in checks if problem is not None]

submit_slurm

Python
submit_slurm(
    config: SlurmConfig,
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    *,
    submit: bool = True,
    skip_checks: bool = False,
    console: Console | None = None,
) -> SlurmSubmission | None

Initializes a workdir and submits it to SLURM from a SlurmConfig, without asking anything.

Parameters:

Name Type Description Default
config SlurmConfig

The resources to request.

required
global_overrides NamedValueDict[NDArray]

Overrides persisted for the workers.

NamedValueDict[NDArray]()
trial_nums list[int] | None

Specific trials to run, instead of all of them.

None
clean_workdir bool

Wipe the workdir first.

False
cleanup_delay int

Seconds of countdown before wiping.

10
submit bool

Run sbatch. When False the workdir and script are written and nothing is submitted.

True
skip_checks bool

Submit even if the request exceeds a limit the cluster reports.

False
console Console | None

Where to print what happened.

None

Returns:

Type Description
SlurmSubmission | None

What was written and submitted, or None when every trial was already completed.

Raises:

Type Description
ValueError

If generator_path is not set (or runtime_path, when there is a runtime), or the request exceeds a cluster limit and skip_checks is not set.

Source code in src/mujoco_mojo/utils/runner.py
Python
def submit_slurm(
    self,
    config: SlurmConfig,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    *,
    submit: bool = True,
    skip_checks: bool = False,
    console: Console | None = None,
) -> SlurmSubmission | None:
    """
    Initializes a workdir and submits it to SLURM from a `SlurmConfig`, without asking anything.

    Args:
        config: The resources to request.
        global_overrides: Overrides persisted for the workers.
        trial_nums: Specific trials to run, instead of all of them.
        clean_workdir: Wipe the workdir first.
        cleanup_delay: Seconds of countdown before wiping.
        submit: Run `sbatch`. When `False` the workdir and script are written and nothing is submitted.
        skip_checks: Submit even if the request exceeds a limit the cluster reports.
        console: Where to print what happened.

    Returns:
        What was written and submitted, or `None` when every trial was already completed.

    Raises:
        ValueError: If `generator_path` is not set (or `runtime_path`, when there is a runtime), or the request exceeds a cluster limit and `skip_checks` is not set.

    """
    from rich.console import Console

    if not isinstance(self.config, MonteCarloConfig):
        msg = f"A SLURM configuration for {self.config.__class__.__name__} has not been implemented."
        logger.error(msg)
        raise NotImplementedError(msg)

    # the workers are separate `mujoco-mojo` processes that import each function by its dotted path
    missing = []
    if self.generator_path is None:
        missing.append("generator_path")
    if (
        self.runtime is not None
        and self.runtime is not DEFAULT_RUNTIME
        and self.runtime_path is None
    ):
        missing.append("runtime_path")
    if missing:
        msg = f"Set {' and '.join(missing)} (for example 'sim.generate') so the compute nodes can import the function."
        logger.error(msg)
        raise ValueError(msg)

    console = console or Console()
    self._prepare_run(clean_workdir, cleanup_delay)
    job = self.prepare_slurm_job(global_overrides, trial_nums)
    if job is None:
        console.print(
            "[green]All trials were already completed.[/] Nothing to submit."
        )
        return None

    if not skip_checks:
        problems = self.slurm_limit_problems(job, config)
        if problems:
            msg = (
                "The request exceeds what the cluster reports:\n  - "
                + "\n  - ".join(problems)
                + "\nChange the request, or skip these checks to submit anyway."
            )
            logger.error(msg)
            raise ValueError(msg)

    script_path = self.write_slurm_script(job, config, console)
    if not submit:
        console.print(
            f"\n[yellow]Nothing was submitted.[/] The workdir is ready; submit it with:\n[bold green]sbatch {script_path}[/]"
        )
        return SlurmSubmission(script_path)

    submission = self.submit_slurm_script(job, script_path)
    if submission.submitted:
        console.print(f"\n[bold green]Success![/] {submission.message}")
    else:
        logger.error(f"SLURM Submission Failed: {submission.message}")
    return submission

orchestrate_slurm_monte_carlo

Python
orchestrate_slurm_monte_carlo(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool

Orchestrates a Monte Carlo SLURM submission interactively.

Prompts for the resources (checking each against the partition's limits), collects them in a SlurmConfig, and then hands everything to the same code submit_slurm uses. Just before submitting it offers to keep watching the job, which keeps job_status.json and the runtime report current (see watch_job).

Source code in src/mujoco_mojo/utils/runner.py
Python
def orchestrate_slurm_monte_carlo(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool:
    """
    Orchestrates a Monte Carlo SLURM submission interactively.

    Prompts for the resources (checking each against the partition's limits), collects them in a `SlurmConfig`, and then hands everything to the same code `submit_slurm` uses. Just before submitting it offers to keep watching the job, which keeps `job_status.json` and the runtime report current (see `watch_job`).
    """
    from rich.console import Console
    from rich.markup import escape
    from rich.prompt import Confirm, IntPrompt, Prompt

    console = Console()
    project_root = Path.cwd().resolve()

    job = self.prepare_slurm_job(global_overrides, trial_nums)
    if job is None:
        return False

    def proceed_despite(message: str, note: str = "") -> bool:
        console.print(f"\n[bold red]WARNING:[/] {message}")
        if note:
            console.print(f"[red]{note}[/]\n")
        return Confirm.ask("Do you want to proceed anyway?", default=False)

    # ask for sbatch settings with a bunch of console inputs with default values
    available_partitions, default_partition = self.get_slurm_partitions()

    console.print(
        "\n[bold cyan]MuJoCo Mojo Orchestrator: SLURM Resource Setup[/bold cyan]"
    )
    console.print(f"\t            [dim]Python:[/dim] {sys.executable}")
    console.print(f"\t              [dim]Root:[/dim] {project_root}")
    console.print(f"\t[dim]mujoco-mojo binary:[/dim] {self.slurm_mojo_command()}\n")

    # Standard colors only for Rich compatibility
    job_name = Prompt.ask(
        "  [white]Job Name[/]", default=f"mojo-sim-{job.status.id}"
    )
    if available_partitions:
        # Use the actual SLURM default if we found one, otherwise the first in list
        initial_default = (
            default_partition if default_partition else available_partitions[0]
        )

        partition = Prompt.ask(
            "  [white]Partition[/]",
            choices=available_partitions,
            default=initial_default,
        )
    else:
        partition = Prompt.ask(
            "  [white]Partition[/] [dim](optional)[/]", default=""
        )

    # === get partition limits ===
    cpu_limit = self.get_slurm_cpu_limit(partition)
    mem_limit = self.get_slurm_node_mem_limit(partition)
    time_limit_hint = self.get_slurm_time_limit(partition)

    # === get cpus per task ===
    cpus_per_task = max(
        1,
        IntPrompt.ask(
            f"  [white]CPUs per task[/] [dim](Node Limit: {cpu_limit})[/]",
            default=1,
        ),
    )
    if problem := cpu_problem(cpus_per_task, cpu_limit):
        if not proceed_despite(problem):
            return True

    # === get memory ===
    while True:
        mem_text = Prompt.ask(
            f"  [white]Memory per node[/] (e.g., 256M or 1.5G) [dim](Node Limit: {mem_limit})[/]",
            default="" if mem_limit == UNKNOWN_LIMIT else mem_limit,
        ).strip()
        if not mem_text or normalize_to_mb(mem_text) > 0:
            break
        console.print(
            f"[bold red]ERROR:[/] '{escape(mem_text)}' is not a memory size. "
            "Use a number with an optional unit, for example 512M or 1.5G."
        )
    mem = mem_text or None
    if problem := mem_problem(mem, mem_limit):
        if not proceed_despite(
            problem, "This job will likely be rejected by SLURM."
        ):
            return True

    # === get time ===
    while True:
        time_limit = Prompt.ask(
            f"  [white]Time limit[/] (e.g., 01:00:00 or 1-12:00:00) [dim](Partition Limit: {time_limit_hint})[/]",
            default="01:00:00",
        ).strip()
        try:
            slurm_time_to_seconds(time_limit)
            break
        except ValueError:
            console.print(
                f"[bold red]ERROR:[/] '{escape(time_limit)}' is not a SLURM time limit."
            )
    if problem := time_problem(time_limit, time_limit_hint):
        if not proceed_despite(problem):
            return True

    # === get concurrency throttle ===
    max_concurrent_text = Prompt.ask(
        "  [white]Max concurrent tasks[/] [dim](blank = no limit, let SLURM decide)[/]",
        default="",
    )
    if max_concurrent_text and not max_concurrent_text.isdigit():
        console.print(
            f"\n[bold red]WARNING:[/] '{escape(max_concurrent_text)}' is not a number. Ignoring."
        )
        max_concurrent_text = ""
    max_concurrent = (
        int(max_concurrent_text) if max_concurrent_text.strip("0") else None
    )

    # === the project root ===
    add_root_to_pythonpath = True
    if str(project_root) not in os.getenv("PYTHONPATH", ""):
        console.print(
            f"\n[yellow]Warning:[/] Project root [italic]{project_root}[/] is not in your PYTHONPATH."
        )
        add_root_to_pythonpath = Confirm.ask(
            "Should Mojo automatically include it in the SLURM submission?",
            default=True,
        )

    config = SlurmConfig(
        job_name=job_name,
        partition=partition or None,
        cpus_per_task=cpus_per_task,
        mem=mem,
        time_limit=time_limit,
        max_concurrent=max_concurrent,
        add_root_to_pythonpath=add_root_to_pythonpath,
        project_root=project_root,
    )

    if problem := array_problem(len(job.to_run), self.get_max_array_size()):
        console.print(f"\n[bold red]ERROR:[/] {problem}")
        if not Confirm.ask("Proceed anyway?", default=False):
            return True

    script_path = self.write_slurm_script(job, config, console)

    watch_cmd = (
        f'mujoco-mojo run watch-workdir --workdir "{self.workdir.resolve()}"'
    )

    # final submission
    if not Confirm.ask(
        f"\n[cyan]Submit {len(job.to_run)} trials to SLURM now?[/]", default=True
    ):
        # deferred submission; the status file already exists, so the watcher works
        # for a job submitted by hand too
        console.print(
            f"\n[yellow]Orchestration complete.[/] Submit manually with:\n[bold green]sbatch {script_path}[/]"
        )
        console.print(
            f"\n[dim]To keep the status file and runtime report current once it is running, run:[/] [green]{watch_cmd}[/]"
        )
        return False

    # asked now because the status file the watcher keeps current already exists
    watch = Confirm.ask(
        "Keep the job status and runtime report up to date until the job finishes?",
        default=True,
    )

    submission = self.submit_slurm_script(job, script_path)
    if not submission.submitted:
        logger.error(f"SLURM Submission Failed: {submission.message}")
        console.print(
            f"\n[bold red]SLURM submission failed:[/] {escape(submission.message)}"
        )
        return True

    job_id = submission.job_id or "UNKNOWN"
    console.print(f"\n[bold green]Success![/] {submission.message}")

    # === Monitoring Dashboard ===
    console.print("\n[bold cyan]Monitoring Status:[/bold cyan]")
    console.print(f"  - [white]Check status:[/]       [green]squeue -j {job_id}[/]")
    console.print(
        f"  - [white]Watch live:[/]         [green]watch -n 1 squeue -j {job_id}[/]"
    )
    console.print(
        f"  - [white]View first log:[/]     [green]tail -f {self.workdir.resolve()}/logs/trial_0.log[/]"
    )
    console.print(f"  - [white]Cancel all trials:[/]  [green]scancel {job_id}[/]")
    console.print(
        f"\n[dim]Logs are being written to: {self.workdir.resolve()}/logs/[/]"
    )

    if not watch:
        console.print(
            f"\n[dim]To keep the status file and runtime report current later, run:[/] [green]{watch_cmd}[/]"
        )
        return False

    try:
        watch_job(self.workdir, n_proc=max(1, self.config.n_proc), console=console)
    except KeyboardInterrupt:
        console.print(
            f"\n[yellow]Stopped watching.[/] The job keeps running. Resume with: [green]{watch_cmd}[/]"
        )
    return False

accepted_kwarg_names

Python
accepted_kwarg_names(
    func: Callable[..., Any],
    n_fixed: int,
    args: Sequence[Any],
) -> set[str] | None

The keyword names func can take once n_fixed leading arguments and the positional args are bound to it.

A name bound positionally is excluded, since passing it again by keyword would raise. Returns None when func takes **kwargs, or its signature cannot be read, because it then accepts anything.

Source code in src/mujoco_mojo/utils/runner.py
Python
def accepted_kwarg_names(
    func: Callable[..., Any], n_fixed: int, args: Sequence[Any]
) -> set[str] | None:
    """
    The keyword names `func` can take once `n_fixed` leading arguments and the positional `args` are bound to it.

    A name bound positionally is excluded, since passing it again by keyword would raise. Returns `None` when `func` takes `**kwargs`, or its signature cannot be read, because it then accepts anything.
    """
    try:
        parameters = list(inspect.signature(func).parameters.values())
    except (TypeError, ValueError):
        return None
    if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters):
        return None

    positional = [
        p
        for p in parameters
        if p.kind
        in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
    ]
    bound = {p.name for p in positional[: n_fixed + len(args)]}
    named = {
        p.name
        for p in parameters
        if p.kind
        in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
    }
    return named - bound

select_kwargs

Python
select_kwargs(
    func: Callable[..., Any],
    n_fixed: int,
    args: Sequence[Any],
    kwargs: Mapping[str, Any],
) -> dict[str, Any]

The part of kwargs that func accepts (all of it if func takes **kwargs), so one shared set of keyword arguments can go to several functions with different signatures.

Source code in src/mujoco_mojo/utils/runner.py
Python
def select_kwargs(
    func: Callable[..., Any],
    n_fixed: int,
    args: Sequence[Any],
    kwargs: Mapping[str, Any],
) -> dict[str, Any]:
    """The part of `kwargs` that `func` accepts (all of it if `func` takes `**kwargs`), so one shared set of keyword arguments can go to several functions with different signatures."""
    names = accepted_kwarg_names(func, n_fixed, args)
    if names is None:
        return dict(kwargs)
    return {key: value for key, value in kwargs.items() if key in names}

validate_shared_kwargs

Python
validate_shared_kwargs(
    kwargs: Mapping[str, Any],
    args: Sequence[Any],
    targets: Mapping[str, tuple[Callable[..., Any], int]],
) -> None

Raises ValueError if a keyword argument is accepted by none of targets, which maps a role (such as "generator") to its function and its number of fixed leading arguments.

A function that takes **kwargs accepts every key, so nothing is checked when any target does; this catches a misspelled key, which filtering would otherwise silently drop.

Source code in src/mujoco_mojo/utils/runner.py
Python
def validate_shared_kwargs(
    kwargs: Mapping[str, Any],
    args: Sequence[Any],
    targets: Mapping[str, tuple[Callable[..., Any], int]],
) -> None:
    """
    Raises `ValueError` if a keyword argument is accepted by none of `targets`, which maps a role (such as `"generator"`) to its function and its number of fixed leading arguments.

    A function that takes `**kwargs` accepts every key, so nothing is checked when any target does; this catches a misspelled key, which filtering would otherwise silently drop.
    """
    if not kwargs or not targets:
        return
    accepted: dict[str, set[str]] = {}
    for role, (func, n_fixed) in targets.items():
        names = accepted_kwarg_names(func, n_fixed, args)
        if names is None:
            return
        accepted[role] = names

    unknown = sorted(set(kwargs) - set().union(*accepted.values()))
    if not unknown:
        return
    detail = "; ".join(
        f"{role}: {sorted(names) if names else 'none'}"
        for role, names in accepted.items()
    )
    msg = f"Keyword argument(s) {unknown} are not accepted by the generator, runtime, or objective they are passed to. Keywords each one accepts - {detail}."
    logger.error(msg)
    raise ValueError(msg)