Skip to content

Commit 4afad86

Browse files
committed
Rename context_length to sequence_length; exact-match recipe filter
Recipes vend only SequenceLength, so use that name throughout the fine-tuning options and validation path (context_length -> sequence_length, _parse_context_length -> _parse_sequence_length). Filter recipes by exact SequenceLength match and keep all candidates at that length, so _select_recipe_by_training_type picks the right recipe when LORA and FULL variants share the same sequence length. The client sends only descriptors in ServerlessJobConfig (including SequenceLength); the selectable-length cap is derived from the recipe catalog rather than a hardcoded enum, and length validation stays framework-agnostic (gated on the recipe's SequenceLength metadata, which both Nova and verl recipes carry). X-AI-Prompt: Change context_length to sequence_length (recipes vend only SequenceLength) and enable submitting multiple recipes for the same context length X-AI-Tool: Claude Code (Opus 4.8)
1 parent 7749967 commit 4afad86

7 files changed

Lines changed: 122 additions & 78 deletions

File tree

‎sagemaker-train/src/sagemaker/train/base_trainer.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ def _yaml_safe_default(value):
568568
if hp_value is not None:
569569
_set_spec_default(override_spec, hp_key, _yaml_safe_default(hp_value))
570570

571-
# Enforce selected sequence lengths fit the recipe's supported context.
571+
# Enforce selected lengths fit the recipe's supported sequence length.
572572
if hasattr(self.hyperparameters, "validate_length_constraints"):
573573
self.hyperparameters.validate_length_constraints()
574574

‎sagemaker-train/src/sagemaker/train/common.py‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,50 +23,50 @@ class CustomizationTechnique(Enum):
2323
class FineTuningOptions:
2424
"""Dynamic class for fine-tuning options with validation."""
2525

26-
def __init__(self, options_dict: Dict[str, Any], context_length: int = None):
26+
def __init__(self, options_dict: Dict[str, Any], sequence_length: int = None):
2727
self._specs = options_dict.copy()
2828
self._user_set = set()
2929
self._initialized = False
30-
# Recipe's supported-context ceiling (prompt + response for RL, or
31-
# max_length for SFT/DPO). Used by validate_length_constraints().
32-
self._context_length = context_length
30+
# Recipe's supported sequence-length ceiling (prompt + response for RL,
31+
# or max_length for SFT/DPO). Used by validate_length_constraints().
32+
self._sequence_length = sequence_length
3333
# Extract default values and set as attributes (no validation during init)
3434
for key, spec in options_dict.items():
3535
default_value = spec.get('default') if isinstance(spec, dict) else spec
3636
super().__setattr__(key, default_value)
3737
self._initialized = True
3838

3939
def validate_length_constraints(self):
40-
"""Enforce that selected sequence lengths fit the recipe's context_length.
40+
"""Enforce that selected lengths fit the recipe's sequence_length.
4141
4242
For RL recipes: max_prompt_length + max_response_length must not exceed
43-
context_length. For SFT/DPO: max_length must not exceed it. Per-field
43+
sequence_length. For SFT/DPO: max_length must not exceed it. Per-field
4444
min/max are already enforced on assignment; this adds the cross-field
4545
sum check that a per-field max cannot express.
4646
47-
No-op if context_length is unknown or the relevant params are absent.
47+
No-op if sequence_length is unknown or the relevant params are absent.
4848
"""
49-
if self._context_length is None:
49+
if self._sequence_length is None:
5050
return
5151

5252
prompt = getattr(self, "max_prompt_length", None)
5353
response = getattr(self, "max_response_length", None)
5454
if prompt is not None and response is not None:
5555
total = prompt + response
56-
if total > self._context_length:
56+
if total > self._sequence_length:
5757
raise ValueError(
5858
f"max_prompt_length ({prompt}) + max_response_length ({response}) "
59-
f"= {total} exceeds the recipe's supported context length "
60-
f"({self._context_length}). Lower max_prompt_length and/or "
61-
f"max_response_length so their sum is within {self._context_length}."
59+
f"= {total} exceeds the recipe's supported sequence length "
60+
f"({self._sequence_length}). Lower max_prompt_length and/or "
61+
f"max_response_length so their sum is within {self._sequence_length}."
6262
)
6363

6464
max_length = getattr(self, "max_length", None)
65-
if max_length is not None and max_length > self._context_length:
65+
if max_length is not None and max_length > self._sequence_length:
6666
raise ValueError(
67-
f"max_length ({max_length}) exceeds the recipe's supported context "
68-
f"length ({self._context_length}). Set max_length to "
69-
f"{self._context_length} or lower."
67+
f"max_length ({max_length}) exceeds the recipe's supported sequence "
68+
f"length ({self._sequence_length}). Set max_length to "
69+
f"{self._sequence_length} or lower."
7070
)
7171

7272
def to_dict(self) -> Dict[str, Any]:

‎sagemaker-train/src/sagemaker/train/common_utils/finetune_utils.py‎

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -568,8 +568,8 @@ def _resolve_model_package_arn(model_package) -> Optional[str]:
568568
return None
569569

570570

571-
def _parse_context_length(value) -> int:
572-
"""Parse a context length value like '8K', '32K', '128K' into an integer (e.g., 8192)."""
571+
def _parse_sequence_length(value) -> int:
572+
"""Parse a sequence length value like '8K', '32K', '128K' into an integer (e.g., 8192)."""
573573
if not value:
574574
return 0
575575
value = str(value).strip().upper()
@@ -641,19 +641,21 @@ def _get_fine_tuning_options_and_model_arn(model_name: str, customization_techni
641641
if not recipes_with_template:
642642
raise ValueError(f"No recipes found with {platform_label} for technique: {customization_technique}")
643643

644-
# Filter by SequenceLength before recipe selection if sequence_length is requested
644+
# Filter by SequenceLength before recipe selection if sequence_length is requested.
645+
# Multiple recipes may share the same SequenceLength (e.g. LORA and FULL
646+
# variants); keep every exact match so _select_recipe_by_training_type can
647+
# pick the right one for the requested training type.
645648
if sequence_length:
646-
requested = _parse_context_length(sequence_length)
647-
candidates_with_context = [r for r in recipes_with_template if r.get("SequenceLength")]
648-
if candidates_with_context:
649-
filtered = [r for r in candidates_with_context if _parse_context_length(r.get("SequenceLength")) >= requested]
649+
requested = _parse_sequence_length(sequence_length)
650+
candidates_with_sequence = [r for r in recipes_with_template if r.get("SequenceLength")]
651+
if candidates_with_sequence:
652+
filtered = [r for r in candidates_with_sequence if _parse_sequence_length(r.get("SequenceLength")) == requested]
650653
if filtered:
651-
filtered.sort(key=lambda r: _parse_context_length(r.get("SequenceLength")))
652654
recipes_with_template = filtered
653655
else:
654-
available = sorted(set(r.get("SequenceLength") for r in candidates_with_context))
656+
available = sorted(set(r.get("SequenceLength") for r in candidates_with_sequence))
655657
raise ValueError(
656-
f"No recipes found with SequenceLength >= {sequence_length}. "
658+
f"No recipes found with SequenceLength == {sequence_length}. "
657659
f"Available sequence lengths: {available}"
658660
)
659661
else:
@@ -720,16 +722,16 @@ def _get_fine_tuning_options_and_model_arn(model_name: str, customization_techni
720722
except Exception as e:
721723
logger.debug(f"Could not fetch subscription recipe override_params: {type(e).__name__}: {e}")
722724

723-
# Supported-context ceiling: the recipe's SequenceLength ("<n>K") is the
724-
# single source of truth. Parse it to an int so we can validate that
725+
# Supported sequence-length ceiling: the recipe's SequenceLength ("<n>K")
726+
# is the single source of truth. Parse it to an int so we can validate that
725727
# max_prompt_length + max_response_length (or max_length) stays within
726728
# what the recipe's hardware can serve. 0 if absent/unparseable (no-op).
727-
context_length = _parse_context_length(recipe.get("SequenceLength")) or None
729+
sequence_length_ceiling = _parse_sequence_length(recipe.get("SequenceLength")) or None
728730

729731
if options_dict:
730-
return FineTuningOptions(options_dict, context_length=context_length), model_arn, is_gated_model
732+
return FineTuningOptions(options_dict, sequence_length=sequence_length_ceiling), model_arn, is_gated_model
731733
else:
732-
return FineTuningOptions({}, context_length=context_length), model_arn, is_gated_model
734+
return FineTuningOptions({}, sequence_length=sequence_length_ceiling), model_arn, is_gated_model
733735

734736
except Exception as e:
735737
logger.debug("Exception getting fine-tuning options: %s", e)

‎sagemaker-train/src/sagemaker/train/rlaif_trainer.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ def train(self, training_dataset: Optional[Union[str, DataSet]] = None, validati
280280
mlflow_run_name=self.mlflow_run_name,
281281
)
282282

283-
# Enforce prompt + response fit the recipe's supported context length.
283+
# Enforce prompt + response fit the recipe's supported sequence length.
284284
self.hyperparameters.validate_length_constraints()
285285

286286
final_hyperparameters = self.hyperparameters.to_dict()

‎sagemaker-train/src/sagemaker/train/rlvr_trainer.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ def train(self, training_dataset: Optional[Union[str, DataSet]] = None,
477477
mlflow_run_name=self.mlflow_run_name,
478478
)
479479

480-
# Enforce prompt + response fit the recipe's supported context length.
480+
# Enforce prompt + response fit the recipe's supported sequence length.
481481
self.hyperparameters.validate_length_constraints()
482482

483483
final_hyperparameters = self.hyperparameters.to_dict()

‎sagemaker-train/tests/unit/train/common_utils/test_finetune_utils.py‎

Lines changed: 66 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
_validate_eula_for_gated_model,
3333
_validate_model_region_availability,
3434
_validate_s3_path_exists,
35-
_parse_context_length
35+
_parse_sequence_length
3636
)
3737
from sagemaker.core.resources import ModelPackage, ModelPackageGroup
3838
from sagemaker.core.utils.utils import Unassigned
@@ -1045,26 +1045,26 @@ def test__create_serverless_config_without_sequence_length(self):
10451045

10461046
assert config.sequence_length is None
10471047

1048-
def test__parse_context_length_with_k_suffix(self):
1049-
assert _parse_context_length("8K") == 8192
1050-
assert _parse_context_length("32K") == 32768
1051-
assert _parse_context_length("128K") == 131072
1048+
def test__parse_sequence_length_with_k_suffix(self):
1049+
assert _parse_sequence_length("8K") == 8192
1050+
assert _parse_sequence_length("32K") == 32768
1051+
assert _parse_sequence_length("128K") == 131072
10521052

1053-
def test__parse_context_length_with_lowercase(self):
1054-
assert _parse_context_length("8k") == 8192
1053+
def test__parse_sequence_length_with_lowercase(self):
1054+
assert _parse_sequence_length("8k") == 8192
10551055

1056-
def test__parse_context_length_with_integer(self):
1056+
def test__parse_sequence_length_with_integer(self):
10571057
with pytest.raises(ValueError, match="Invalid sequence_length '4096'"):
1058-
_parse_context_length("4096")
1058+
_parse_sequence_length("4096")
10591059

1060-
def test__parse_context_length_with_none(self):
1061-
assert _parse_context_length(None) == 0
1060+
def test__parse_sequence_length_with_none(self):
1061+
assert _parse_sequence_length(None) == 0
10621062

1063-
def test__parse_context_length_with_empty(self):
1064-
assert _parse_context_length("") == 0
1063+
def test__parse_sequence_length_with_empty(self):
1064+
assert _parse_sequence_length("") == 0
10651065

10661066
@patch('sagemaker.train.common_utils.finetune_utils._get_hub_content_metadata')
1067-
def test__get_fine_tuning_options_filters_by_sequence_length(self, mock_get_hub_content):
1067+
def test__get_fine_tuning_options_filters_by_exact_sequence_length(self, mock_get_hub_content):
10681068
mock_session = Mock()
10691069
mock_session.boto_session.region_name = "us-east-1"
10701070
mock_s3 = Mock()
@@ -1096,17 +1096,59 @@ def test__get_fine_tuning_options_filters_by_sequence_length(self, mock_get_hub_
10961096
}
10971097
}
10981098

1099-
result = _get_fine_tuning_options_and_model_arn("test-model", "SFT", "LORA", mock_session, sequence_length="8K")
1099+
result = _get_fine_tuning_options_and_model_arn("test-model", "SFT", "LORA", mock_session, sequence_length="32K")
11001100

1101-
if result is not None:
1102-
options, model_arn, is_gated_model = result
1103-
# Should pick the 32K recipe (smallest >= 8K)
1104-
mock_s3.get_object.assert_called_once()
1105-
call_args = mock_s3.get_object.call_args[1]
1106-
assert "params-32k" in call_args["Key"]
1101+
assert result is not None
1102+
options, model_arn, is_gated_model = result
1103+
# Should pick the recipe whose SequenceLength exactly matches the request.
1104+
mock_s3.get_object.assert_called_once()
1105+
call_args = mock_s3.get_object.call_args[1]
1106+
assert "params-32k" in call_args["Key"]
1107+
1108+
@patch('sagemaker.train.common_utils.finetune_utils._get_hub_content_metadata')
1109+
def test__get_fine_tuning_options_keeps_all_recipes_at_same_sequence_length(self, mock_get_hub_content):
1110+
# Multiple recipes share the same SequenceLength (LORA + FULL). Selection
1111+
# by training_type must resolve to the LORA one, not an arbitrary match.
1112+
mock_session = Mock()
1113+
mock_session.boto_session.region_name = "us-east-1"
1114+
mock_s3 = Mock()
1115+
mock_s3.get_object.return_value = {
1116+
"Body": Mock(read=Mock(return_value=b'{"max_length": {"default": 32768}}'))
1117+
}
1118+
mock_session.boto_session.client.return_value = mock_s3
1119+
1120+
mock_get_hub_content.return_value = {
1121+
'hub_content_arn': "arn:aws:sagemaker:us-east-1:123456789012:model/test-model",
1122+
'hub_content_document': {
1123+
"GatedBucket": False,
1124+
"RecipeCollection": [
1125+
{
1126+
"CustomizationTechnique": "SFT",
1127+
"SmtjRecipeTemplateS3Uri": "s3://bucket/template-32k-full.json",
1128+
"SmtjOverrideParamsS3Uri": "s3://bucket/params-32k-full.json",
1129+
"Peft": False,
1130+
"SequenceLength": "32K"
1131+
},
1132+
{
1133+
"CustomizationTechnique": "SFT",
1134+
"SmtjRecipeTemplateS3Uri": "s3://bucket/template-32k-lora.json",
1135+
"SmtjOverrideParamsS3Uri": "s3://bucket/params-32k-lora.json",
1136+
"Peft": True,
1137+
"SequenceLength": "32K"
1138+
}
1139+
]
1140+
}
1141+
}
1142+
1143+
result = _get_fine_tuning_options_and_model_arn("test-model", "SFT", "LORA", mock_session, sequence_length="32K")
1144+
1145+
assert result is not None
1146+
mock_s3.get_object.assert_called_once()
1147+
call_args = mock_s3.get_object.call_args[1]
1148+
assert "params-32k-lora" in call_args["Key"]
11071149

11081150
@patch('sagemaker.train.common_utils.finetune_utils._get_hub_content_metadata')
1109-
def test__get_fine_tuning_options_raises_when_no_sufficient_context_length(self, mock_get_hub_content):
1151+
def test__get_fine_tuning_options_raises_when_no_exact_sequence_length(self, mock_get_hub_content):
11101152
mock_session = Mock()
11111153
mock_session.boto_session.region_name = "us-east-1"
11121154

@@ -1126,8 +1168,8 @@ def test__get_fine_tuning_options_raises_when_no_sufficient_context_length(self,
11261168
}
11271169
}
11281170

1129-
# Requesting 128K but only 4K available — should raise
1130-
with pytest.raises(ValueError, match="No recipes found with SequenceLength >= 128K"):
1171+
# Requesting 128K but only 4K available — no exact match, should raise.
1172+
with pytest.raises(ValueError, match="No recipes found with SequenceLength == 128K"):
11311173
_get_fine_tuning_options_and_model_arn("test-model", "SFT", "LORA", mock_session, sequence_length="128K")
11321174

11331175

‎sagemaker-train/tests/unit/train/test_common.py‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -60,58 +60,58 @@ def test_to_dict_all_none_returns_empty(self):
6060

6161

6262
class TestValidateLengthConstraints:
63-
"""FineTuningOptions.validate_length_constraints() — sum vs context_length."""
63+
"""FineTuningOptions.validate_length_constraints() — sum vs sequence_length."""
6464

65-
def _rl_options(self, prompt, response, context_length):
66-
# Per-field max defaults to context_length; when unknown, omit it so the
65+
def _rl_options(self, prompt, response, sequence_length):
66+
# Per-field max defaults to sequence_length; when unknown, omit it so the
6767
# per-field range check is a no-op and only the sum-guard is exercised.
6868
prompt_spec = {"type": "integer", "default": 1024, "min": 512}
6969
response_spec = {"type": "integer", "default": 2048, "min": 100}
70-
if context_length is not None:
71-
prompt_spec["max"] = context_length
72-
response_spec["max"] = context_length
70+
if sequence_length is not None:
71+
prompt_spec["max"] = sequence_length
72+
response_spec["max"] = sequence_length
7373
opts = FineTuningOptions(
7474
{"max_prompt_length": prompt_spec, "max_response_length": response_spec},
75-
context_length=context_length,
75+
sequence_length=sequence_length,
7676
)
7777
object.__setattr__(opts, "max_prompt_length", prompt)
7878
object.__setattr__(opts, "max_response_length", response)
7979
return opts
8080

81-
def test_rl_sum_within_context_length_passes(self):
82-
opts = self._rl_options(prompt=4096, response=8192, context_length=262144)
81+
def test_rl_sum_within_sequence_length_passes(self):
82+
opts = self._rl_options(prompt=4096, response=8192, sequence_length=262144)
8383
opts.validate_length_constraints() # no raise
8484

85-
def test_rl_sum_equal_to_context_length_passes(self):
86-
opts = self._rl_options(prompt=100000, response=162144, context_length=262144)
87-
opts.validate_length_constraints() # sum == ctx, allowed
85+
def test_rl_sum_equal_to_sequence_length_passes(self):
86+
opts = self._rl_options(prompt=100000, response=162144, sequence_length=262144)
87+
opts.validate_length_constraints() # sum == ceiling, allowed
8888

89-
def test_rl_sum_exceeds_context_length_raises(self):
90-
opts = self._rl_options(prompt=200000, response=200000, context_length=262144)
89+
def test_rl_sum_exceeds_sequence_length_raises(self):
90+
opts = self._rl_options(prompt=200000, response=200000, sequence_length=262144)
9191
with pytest.raises(ValueError) as exc:
9292
opts.validate_length_constraints()
9393
msg = str(exc.value)
9494
assert "400000" in msg and "262144" in msg
9595

96-
def test_sft_max_length_within_context_length_passes(self):
96+
def test_sft_max_length_within_sequence_length_passes(self):
9797
opts = FineTuningOptions(
9898
{"max_length": {"type": "integer", "default": 4096, "min": 4096, "max": 131072}},
99-
context_length=131072,
99+
sequence_length=131072,
100100
)
101101
opts.max_length = 65536
102102
opts.validate_length_constraints() # no raise
103103

104-
def test_sft_max_length_exceeds_context_length_raises(self):
104+
def test_sft_max_length_exceeds_sequence_length_raises(self):
105105
opts = FineTuningOptions(
106106
{"max_length": {"type": "integer", "default": 4096, "min": 4096, "max": 131072}},
107-
context_length=131072,
107+
sequence_length=131072,
108108
)
109109
# max is 131072, so set via _specs bypass to test the sum-guard directly
110110
object.__setattr__(opts, "max_length", 200000)
111111
with pytest.raises(ValueError) as exc:
112112
opts.validate_length_constraints()
113113
assert "131072" in str(exc.value)
114114

115-
def test_no_context_length_is_noop(self):
116-
opts = self._rl_options(prompt=200000, response=200000, context_length=None)
115+
def test_no_sequence_length_is_noop(self):
116+
opts = self._rl_options(prompt=200000, response=200000, sequence_length=None)
117117
opts.validate_length_constraints() # unknown ceiling -> no raise

0 commit comments

Comments
 (0)