← Back to Pull requests

feat(trainer): make RuntimeTrainer.image optional for BYOI #810

Open
kliushenkov opened this pull request with 330 lines diff across 10 files
View on GitHub
kliushenkov kliushenkov commented on Sep 30, 2026 07:34 UTC
Author

Summary


  • Make RuntimeTrainer.image default to Unknown so TrainingRuntime / ClusterTrainingRuntime can omit a pinned image for bring-your-own-image workflows.

  • Resolve TrainJob image as CustomTrainer / CustomTrainerContainer override → runtime image → clear ValueError; require a runtime image for BuiltinTrainer and when trainer is omitted.

  • Align get_runtime_packages across Kubernetes, container, and localprocess backends to raise when the runtime image is unset; validate container image before allocating workdir/network.
  • Fixes #494

    Test plan


  • Unit tests for image-less runtime parsing (Unknown), trainer override success, and missing-image failure

  • BuiltinTrainer / trainer-omitted paths raise when runtime image is unset

  • get_runtime_packages raises consistently when image is Unknown

  • CI unit tests on the PR

  • Manual smoke: client.train(runtime=..., trainer=CustomTrainer(..., image=...)) with an image-less runtime
  • Made with Cursor

    Diff: 330 lines (+317 / -13) across 10 files Reviewer: andreyvelich Review duration: 34691m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.56) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 330 lines diff across 10 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.94 · 5 substantive comment(s)
    0.94
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.347
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    14 items
    google-oss-prow[bot] google-oss-prow[bot] commented on Sep 30, 2026 07:34 UTC
    Bot

    [APPROVALNOTIFIER] This PR is NOT APPROVED

    This pull-request has been approved by:
    Once this PR has been reviewed and has the lgtm label, please assign electronic-waste for approval. For more information see the Kubernetes Code Review Process.

    The full list of commands accepted by this bot can be found here.

    <details open>
    Needs approval from an approver in each of these files:

  • OWNERS
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":["electronic-waste"]} -->

    andreyvelich andreyvelich commented on Oct 05, 2026 16:51 UTC
    Contributor

    /ok-to-test
    /retest

    andreyvelich andreyvelich commented on Oct 05, 2026 18:12 UTC
    Reviewer

    Thanks for working on this @kliushenkov! I left a few comments. Note: this review was done with the help of AI tools.

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/types/types.py:1
    @@ -278,6 +280,39 @@ class Runtime:
         pretrained_model: str | None = None
     
     
    +def is_trainer_image_set(image: str | None) -> bool:
    +    """Return True when image is a concrete container image (not unset/Unknown)."""
    +    return bool(image) and image != common_constants.UNKNOWN
    +
    +
    +def resolve_trainer_image(
    +    runtime: Runtime,
    +    trainer: CustomTrainer | CustomTrainerContainer,
    +) -> str:
    +    """Resolve the TrainJob image from trainer override or runtime default.
    +
    +    Args:
    +        runtime: Parsed training runtime.
    +        trainer: Job trainer that may supply an image override.
    +
    +    Returns:
    +        Concrete container image to use for the TrainJob.
    +
    +    Raises:
    +        ValueError: If neither the trainer nor the runtime provides an image.
    +    """
    +    if is_trainer_image_set(trainer.image):
    +        return trainer.image
    +
    +    if is_trainer_image_set(runtime.trainer.image):
    +        return runtime.trainer.image
    +
    +    raise ValueError(
    +        "Trainer image is required. Set CustomTrainer.image or CustomTrainerContainer.image, "
    +        "or configure an image on the TrainingRuntime / ClusterTrainingRuntime."
    +    )

    Please remove these helpers from the public types module (they become public API). Since RuntimeTrainer.image defaults to Unknown (like device), compare inline: runtime.trainer.image == common_constants.UNKNOWN. See suggestions below.

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/kubernetes/utils.py:1
    @@ -119,17 +120,26 @@ def get_runtime_trainer(
     
         trainer_container = get_runtime_trainer_container(replicated_jobs)
     
    -    if not (trainer_container and trainer_container.image):
    +    if not trainer_container:
             raise Exception(f"Runtime doesn't have trainer container {replicated_jobs}")
     
    +    image_set = types.is_trainer_image_set(trainer_container.image)
    +    # BuiltinTrainer has no job-level image override; runtime must define a concrete image.
    +    if framework == types.TORCH_TUNE and not image_set:
    +        raise ValueError("BuiltinTrainer runtimes require a container image on the TrainingRuntime")
    +
    +    # Custom trainer runtimes may omit image; callers supply it via CustomTrainer /
    +    # CustomTrainerContainer at TrainJob creation time.
    +    image = trainer_container.image if image_set else common_constants.UNKNOWN
    +
         trainer = types.RuntimeTrainer(
             trainer_type=(
                 types.TrainerType.BUILTIN_TRAINER
                 if framework == types.TORCH_TUNE
                 else types.TrainerType.CUSTOM_TRAINER
             ),
             framework=framework,
    -        image=trainer_container.image,
    +        image=image,

    This check is not needed: get_trainer_cr_from_builtin_trainer already fails at TrainJob creation, and raising here makes list_runtimes() fail entirely for one image-less TorchTune runtime. Please also drop the matching test_get_runtime_trainer_image case.

        trainer = types.RuntimeTrainer(
            trainer_type=(
                types.TrainerType.BUILTIN_TRAINER
                if framework == types.TORCH_TUNE
                else types.TrainerType.CUSTOM_TRAINER
            ),
            framework=framework,
            image=trainer_container.image or common_constants.UNKNOWN,
    

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/kubernetes/utils.py:1
    @@ -441,9 +451,8 @@ def get_trainer_cr_from_custom_trainer(
                 trainer.packages_to_install,
             )
     
    -    # Set the TrainJob trainer image if that is set.
    -    if trainer.image:
    -        trainer_cr.image = trainer.image
    +    # Set the TrainJob trainer image from trainer override or runtime default.
    +    trainer_cr.image = types.resolve_trainer_image(runtime, trainer)

    This now always pins the runtime image in the TrainJob spec, which changes behavior for every existing user. Only set the image when the user provides it, and fail only when both images are unset:

        # Set the TrainJob trainer image if that is set.
        if trainer.image:
            trainer_cr.image = trainer.image
        elif runtime.trainer.image == common_constants.UNKNOWN:
            raise ValueError("Trainer image is required. Set image in CustomTrainer or in the Runtime.")
    

    The runtime image used when custom trainer image unset test should then expect None.

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/kubernetes/utils.py:1
    @@ -465,6 +474,12 @@ def get_trainer_cr_from_builtin_trainer(
         if not isinstance(trainer.config, types.TorchTuneConfig):
             raise ValueError(f"The BuiltinTrainer config is invalid: {trainer.config}")
     
    +    if not types.is_trainer_image_set(runtime.trainer.image):

        if runtime.trainer.image == common_constants.UNKNOWN:
    

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/kubernetes/backend.py:1
    @@ -235,6 +235,9 @@ def get_runtime_packages(self, runtime: types.Runtime):
             if runtime.trainer.trainer_type == types.TrainerType.BUILTIN_TRAINER:
                 raise ValueError("Cannot get Runtime packages for BuiltinTrainer")
     
    +        if not types.is_trainer_image_set(runtime.trainer.image):

            if runtime.trainer.image == common_constants.UNKNOWN:
    

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/kubernetes/backend.py:1
    @@ -831,6 +834,13 @@ def _get_trainjob_spec(
                         f"The trainer type {type(trainer)} is not supported. "
                         "Please use CustomTrainer, CustomTrainerContainer, or BuiltinTrainer."
                     )
    +        elif not types.is_trainer_image_set(runtime.trainer.image):

            elif runtime.trainer.image == common_constants.UNKNOWN:
    

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/kubernetes/backend_test.py:1
    @@ -1261,6 +1279,7 @@ def test_get_runtime_packages(kubernetes_backend, test_case):
                     train_job_trainer=get_custom_trainer(
                         pip_index_urls=constants.DEFAULT_PIP_INDEX_URLS,
                         packages_to_install=["torch", "numpy"],
    +                    image="example.com/test-runtime",

    Please revert this: the TrainJob shouldn't get the runtime image when the user didn't set one.

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/container/backend.py:1
    @@ -240,6 +240,9 @@ def get_runtime_packages(self, runtime: types.Runtime):
             """
             Spawn a short-lived container to report Python version, pip list, and nvidia-smi.
             """
    +        if not types.is_trainer_image_set(runtime.trainer.image):

    Needs import kubeflow.common.constants as common_constants.

            if runtime.trainer.image == common_constants.UNKNOWN:
    

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/container/backend.py:1
    @@ -281,6 +284,9 @@ def train(
             if not isinstance(trainer, types.CustomTrainer):
                 raise ValueError(f"{self.__class__.__name__} supports only CustomTrainer in v1")
     
    +        # Resolve image before allocating workdir/network so invalid BYOI configs fail early.
    +        image = types.resolve_trainer_image(runtime, trainer)

            # Resolve image before allocating workdir/network so invalid configs fail early.
            image = trainer.image or runtime.trainer.image
            if image == common_constants.UNKNOWN:
                raise ValueError(
                    "Trainer image is required. Set image in CustomTrainer or in the Runtime."
                )
    

    Please add container backend_test.py cases: train() with an image-less runtime (succeeds with CustomTrainer.image, raises without it and creates no network/containers), and get_runtime_packages() raising when the image is unset.

    andreyvelich andreyvelich commented on code on Oct 05, 2026 18:12 UTC
    Code Review
    kubeflow/trainer/backends/localprocess/backend.py:1
    @@ -62,6 +62,9 @@ def get_runtime(self, name: str) -> types.Runtime:
             return runtime
     
         def get_runtime_packages(self, runtime: types.Runtime):
    +        if not types.is_trainer_image_set(runtime.trainer.image):
    +            raise ValueError("Cannot get Runtime packages: runtime image is unset")

    Local runtimes always have an image and this method doesn't use it, so this check can't fire. Please remove it and the matching test.

    Reviewers
    Assignees
    kliushenkov kliushenkov
    Labels
    risk: low confidence: 90.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 55.9% (MEDIUM) · Higher = larger blast radius
    55.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.9% · Lower = rushed or shallow review
    90.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.1% · Safe to merge
    5.1%
    Repository