-
Notifications
You must be signed in to change notification settings - Fork 1.3k
feat(train): Add inherited list_supported_models to BaseTrainer #6187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jam-jee
merged 3 commits into
aws:master
from
jam-jee:feat/trainer-list-supported-models
Aug 19, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -102,6 +102,37 @@ class BaseTrainer(ABC): | |
| training_image: Optional[str] = None | ||
| latest_training_job: Optional[TrainingJob] = None | ||
|
|
||
| @classmethod | ||
| @_telemetry_emitter( | ||
| feature=Feature.MODEL_CUSTOMIZATION, | ||
| func_name="BaseTrainer.list_supported_models", | ||
| ) | ||
| def list_supported_models(cls, session=None) -> List[str]: | ||
| """Return the models that support this trainer's fine-tuning technique. | ||
|
|
||
| Queries SageMakerPublicHub for all models whose ``RecipeCollection`` | ||
| contains a FineTuning recipe for this trainer's customization technique | ||
| (``cls._customization_technique``, e.g. ``"SFT"``, ``"DPO"``, | ||
| ``"RLVR"``, ``"RLAIF"``, ``"CPT"``). | ||
|
|
||
| Args: | ||
| session: Optional boto3 session. | ||
|
|
||
| Returns: | ||
| Sorted list of hub content model names supporting the technique. | ||
| """ | ||
| from sagemaker.train.common_utils.recipe_utils import _list_hub_models_by_recipe | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit[non-blocking]: We can move the import to above |
||
|
|
||
| technique = getattr(cls, "_customization_technique", None) | ||
| if not technique: | ||
| raise NotImplementedError( | ||
| f"{cls.__name__} does not define a customization technique and " | ||
| "cannot list supported models." | ||
| ) | ||
| return _list_hub_models_by_recipe( | ||
| recipe_type="FineTuning", technique=technique, session=session | ||
| ) | ||
|
|
||
| def __init__( | ||
| self, | ||
| sagemaker_session: Optional[Session] = None, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
sagemaker-train/tests/integ/train/test_trainer_list_supported_models_integration.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"). You | ||
| # may not use this file except in compliance with the License. A copy of | ||
| # the License is located at | ||
| # | ||
| # http://aws.amazon.com/apache2.0/ | ||
| # | ||
| # or in the "license" file accompanying this file. This file is | ||
| # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF | ||
| # ANY KIND, either express or implied. See the License for the specific | ||
| # language governing permissions and limitations under the License. | ||
| """Integration tests for ``BaseTrainer.list_supported_models`` across the | ||
| fine-tuning trainers (SFT / RLVR / RLAIF / DPO / CPT). | ||
|
|
||
| These tests run against real SageMaker services in prod us-west-2 and query the | ||
| active SageMaker hub (the integ harness pins a private ``SAGEMAKER_HUB_NAME`` in | ||
| ``conftest.py``; falls back to ``SageMakerPublicHub``). | ||
|
|
||
| They verify the contract that unit tests (which mock the hub) cannot: that each | ||
| trainer's ``_customization_technique`` string matches how the live hub tags its | ||
| FineTuning recipes. Rather than assert a hard non-empty count -- which is brittle | ||
| because the pinned hub may not carry every technique -- the test independently | ||
| scans the hub once and asserts ``list_supported_models`` returns exactly the set | ||
| of models tagged for that technique (whether that is zero or many). A helper | ||
| regression that (for example) required a ``_{strategy}`` suffix -- and so dropped | ||
| suffix-less techniques like CPT (``@recipe:finetuning_cpt``) -- would surface | ||
| here as a mismatch against the oracle. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import collections | ||
| import os | ||
|
|
||
| import boto3 | ||
| import pytest | ||
| from sagemaker.core.helper.session_helper import Session | ||
| from sagemaker.train.sft_trainer import SFTTrainer | ||
| from sagemaker.train.rlvr_trainer import RLVRTrainer | ||
| from sagemaker.train.rlaif_trainer import RLAIFTrainer | ||
| from sagemaker.train.dpo_trainer import DPOTrainer | ||
| from sagemaker.train.cpt_trainer import CPTTrainer | ||
|
|
||
| _REGION = "us-west-2" | ||
| _FINETUNING_PREFIX = "@recipe:finetuning_" | ||
|
|
||
| # (trainer class, expected customization technique string) | ||
| _TRAINER_CASES = [ | ||
| pytest.param(SFTTrainer, "SFT", id="SFT"), | ||
| pytest.param(RLVRTrainer, "RLVR", id="RLVR"), | ||
| pytest.param(RLAIFTrainer, "RLAIF", id="RLAIF"), | ||
| pytest.param(DPOTrainer, "DPO", id="DPO"), | ||
| pytest.param(CPTTrainer, "CPT", id="CPT"), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def sagemaker_session(): | ||
| boto_session = boto3.Session(region_name=_REGION) | ||
| yield Session(boto_session=boto_session) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def hub_finetuning_models(sagemaker_session): | ||
| """Independent oracle: scan the active hub once and map technique token -> | ||
| sorted list of model names tagged with a matching FineTuning recipe. | ||
|
|
||
| Built independently of the SDK helper (groups by the token immediately after | ||
| ``@recipe:finetuning_``), so it can catch a regression in that helper rather | ||
| than merely re-deriving it. | ||
| """ | ||
| client = sagemaker_session.boto_session.client("sagemaker", region_name=_REGION) | ||
| hub_name = os.environ.get("SAGEMAKER_HUB_NAME", "SageMakerPublicHub") | ||
| mapping: dict[str, set] = collections.defaultdict(set) | ||
| next_token = None | ||
| while True: | ||
| kwargs = {"HubName": hub_name, "HubContentType": "Model"} | ||
| if next_token: | ||
| kwargs["NextToken"] = next_token | ||
| response = client.list_hub_contents(**kwargs) | ||
| for summary in response.get("HubContentSummaries", []): | ||
| name = summary.get("HubContentName") | ||
| if not name: | ||
| continue | ||
| for keyword in summary.get("HubContentSearchKeywords", []): | ||
| kwl = keyword.lower() | ||
| if kwl.startswith(_FINETUNING_PREFIX): | ||
| token = kwl[len(_FINETUNING_PREFIX):].split("_")[0] | ||
| mapping[token].add(name) | ||
| next_token = response.get("NextToken") | ||
| if not next_token: | ||
| break | ||
| return {tech: sorted(names) for tech, names in mapping.items()} | ||
|
|
||
|
|
||
| class TestTrainerListSupportedModels: | ||
| """List supported models per fine-tuning technique (requires API access).""" | ||
|
|
||
| @pytest.mark.parametrize("trainer_cls,expected_technique", _TRAINER_CASES) | ||
| def test_list_supported_models( | ||
| self, trainer_cls, expected_technique, sagemaker_session, hub_finetuning_models | ||
| ): | ||
| """Each trainer resolves its technique and returns exactly the hub models | ||
| tagged for it.""" | ||
| # Sanity: the class attribute the inherited method keys off is set. | ||
| assert trainer_cls._customization_technique == expected_technique | ||
|
|
||
| result = trainer_cls.list_supported_models( | ||
| session=sagemaker_session.boto_session | ||
| ) | ||
|
|
||
| # Structural contract: a sorted, de-duplicated list of non-empty strings. | ||
| assert isinstance(result, list) | ||
| assert all(isinstance(name, str) and name for name in result) | ||
| assert result == sorted(result) | ||
| assert len(set(result)) == len(result) | ||
|
|
||
| # Correctness contract: exactly the models the active hub tags for this | ||
| # technique (may legitimately be empty if the pinned hub carries none). | ||
| expected = hub_finetuning_models.get(expected_technique.lower(), []) | ||
| assert result == expected | ||
|
|
||
| def test_public_hub_has_models_for_core_techniques(self, hub_finetuning_models): | ||
| """Guard against a silent all-empty hub / broken scan: only meaningful | ||
| against the public hub, where these techniques are known to be tagged. | ||
| Skipped when a private test hub is pinned.""" | ||
| if os.environ.get("SAGEMAKER_HUB_NAME", "SageMakerPublicHub") != "SageMakerPublicHub": | ||
| pytest.skip("private hub pinned; model population is environment-specific") | ||
| for technique in ("sft", "dpo", "rlvr", "rlaif", "cpt"): | ||
| assert hub_finetuning_models.get(technique), ( | ||
| f"public hub returned no models for technique '{technique}'" | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
non blocking but a callout: we might not be able to trace which Trainer is used to list supported models.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good point. But I dont think we need granular list_supported_models metrics ATM.