sagemaker-python-sdk icon indicating copy to clipboard operation
sagemaker-python-sdk copied to clipboard

`HyperparameterTuner` fails when it inherits v3 `ModelTrainer.tags`

Open Alex-Mesmer opened this issue 1 month ago • 0 comments

PySDK Version

  • [ ] PySDK V2 (2.x)
  • [x] PySDK V3 (3.x)

Describe the bug

ModelTrainer.tags is a list of v3 sagemaker.core.shapes.Tag objects. HyperparameterTuner.tune() inherits these tags through _prepare_tags_for_tuning().

The final tuning-request builder then treats each inherited Tag object as a boto-style dictionary:

tag_objects = [Tag(key=tag["Key"], value=tag["Value"]) for tag in self.tags]

This raises TypeError: 'Tag' object is not subscriptable before SageMaker creates the tuning job.

To reproduce

Set these environment variables:

export AWS_PROFILE="<aws-profile>"
export AWS_REGION="us-east-2"
export SAGEMAKER_ROLE_ARN="arn:aws:iam::<account-id>:role/<sagemaker-execution-role>"
export SAGEMAKER_BUCKET="<existing-bucket>"
export TRAINING_IMAGE_URI="257758044811.dkr.ecr.us-east-2.amazonaws.com/sagemaker-scikit-learn:1.4-2-py312-cpu-py3"

Run this script:

import os

import boto3
from sagemaker.core.helper.session_helper import Session
from sagemaker.core.parameter import IntegerParameter
from sagemaker.core.shapes import Tag
from sagemaker.core.training.configs import Compute, OutputDataConfig
from sagemaker.train import ModelTrainer
from sagemaker.train.tuner import HyperparameterTuner

region = os.environ["AWS_REGION"]
bucket = os.environ["SAGEMAKER_BUCKET"]
boto_session = boto3.Session(
    profile_name=os.environ["AWS_PROFILE"],
    region_name=region,
)
session = Session(
    boto_session=boto_session,
    default_bucket=bucket,
)

trainer = ModelTrainer(
    training_image=os.environ["TRAINING_IMAGE_URI"],
    role=os.environ["SAGEMAKER_ROLE_ARN"],
    sagemaker_session=session,
    compute=Compute(
        instance_type="ml.m5.large",
        instance_count=1,
        volume_size_in_gb=30,
    ),
    output_data_config=OutputDataConfig(
        s3_output_path=f"s3://{bucket}/output/",
    ),
    hyperparameters={},
    tags=[
        Tag(
            key="project",
            value="tuner-tag-reproduction",
        )
    ],
)

tuner = HyperparameterTuner(
    model_trainer=trainer,
    objective_metric_name="validation:accuracy",
    hyperparameter_ranges={
        "max_depth": IntegerParameter(
            min_value=1,
            max_value=3,
        )
    },
    max_jobs=1,
    max_parallel_jobs=1,
)

tuner.tune(
    inputs=f"s3://{bucket}/train/",
    job_name="tuner-tag-reproduction",
    wait=False,
)

The failure occurs before the tuning-job API call.

Expected behavior

HyperparameterTuner must accept the v3 Tag objects defined by ModelTrainer.tags. The tuner must preserve inherited tags in the tuning-job request.

One possible fix is to normalize tags before merging them:

from sagemaker.core.shapes import Tag


def _to_boto_tag(tag):
    if isinstance(tag, Tag):
        return {
            "Key": tag.key,
            "Value": tag.value,
        }
    if "key" in tag and "value" in tag:
        return {
            "Key": tag["key"],
            "Value": tag["value"],
        }
    return tag


self.tags = [_to_boto_tag(tag) for tag in self.tags or []]
model_trainer_tags = [
    _to_boto_tag(tag)
    for tag in (getattr(model_trainer, "tags", None) or [])
]

for tag in model_trainer_tags:
    if tag not in self.tags:
        self.tags.append(tag)

The existing request conversion can then create core Tag objects from the normalized dictionaries.

Screenshots or logs

Traceback (most recent call last):
  ...
  File "sagemaker/train/tuner.py", line 1280, in _start_tuning_job
    tag_objects = [Tag(key=tag["Key"], value=tag["Value"]) for tag in self.tags]
TypeError: 'Tag' object is not subscriptable

System information

  • SageMaker Python SDK version: 3.24.0
  • Framework name (eg. PyTorch) or algorithm (eg. KMeans): Not framework-specific
  • Framework version: N/A
  • Python version: 3.12.0
  • CPU or GPU: CPU, Apple Silicon (arm64)
  • Custom Docker image (Y/N): N

Additional context

The tuner inherits trainer tags during tune(), not during construction. The constructor succeeds and the failure occurs only when the request is prepared.

Passing boto-style tags directly to HyperparameterTuner(tags=...) does not fully avoid the failure. The tuner also merges the original ModelTrainer.tags objects into that list.

The same implementation is present in the SageMaker Python SDK v3.25.0 tagged source.

Alex-Mesmer avatar Oct 14 '26 17:10 Alex-Mesmer