Skip to content

Commit 7749967

Browse files
committed
Validate customer sequence lengths against the recipe's SequenceLength
Enforce that customer-selected lengths fit the recipe's supported sequence length: - RL: max_prompt_length + max_response_length <= SequenceLength - SFT/DPO: max_length (dataset_max_len) <= SequenceLength FineTuningOptions.validate_length_constraints() checks this and is wired into the RL/base trainers. The ceiling comes from the recipe's SequenceLength metadata ('<n>K'), parsed to an int via _parse_context_length; no-op when absent. (Recipes side unified on the SequenceLength metadata field; the former ContextLength field was dropped, so read SequenceLength here.)
1 parent d0dc2f4 commit 7749967

6 files changed

Lines changed: 117 additions & 4 deletions

File tree

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,10 @@ 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.
572+
if hasattr(self.hyperparameters, "validate_length_constraints"):
573+
self.hyperparameters.validate_length_constraints()
574+
571575
# Build hyperparameters early to inject into recipe template before runtime.
572576
final_hyperparameters = self.hyperparameters.to_dict()
573577
_validate_hyperparameter_values(final_hyperparameters)

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

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,52 @@ class CustomizationTechnique(Enum):
2222

2323
class FineTuningOptions:
2424
"""Dynamic class for fine-tuning options with validation."""
25-
26-
def __init__(self, options_dict: Dict[str, Any]):
25+
26+
def __init__(self, options_dict: Dict[str, Any], context_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
3033
# Extract default values and set as attributes (no validation during init)
3134
for key, spec in options_dict.items():
3235
default_value = spec.get('default') if isinstance(spec, dict) else spec
3336
super().__setattr__(key, default_value)
3437
self._initialized = True
38+
39+
def validate_length_constraints(self):
40+
"""Enforce that selected sequence lengths fit the recipe's context_length.
41+
42+
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
44+
min/max are already enforced on assignment; this adds the cross-field
45+
sum check that a per-field max cannot express.
46+
47+
No-op if context_length is unknown or the relevant params are absent.
48+
"""
49+
if self._context_length is None:
50+
return
51+
52+
prompt = getattr(self, "max_prompt_length", None)
53+
response = getattr(self, "max_response_length", None)
54+
if prompt is not None and response is not None:
55+
total = prompt + response
56+
if total > self._context_length:
57+
raise ValueError(
58+
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}."
62+
)
63+
64+
max_length = getattr(self, "max_length", None)
65+
if max_length is not None and max_length > self._context_length:
66+
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."
70+
)
3571

3672
def to_dict(self) -> Dict[str, Any]:
3773
"""Convert back to dictionary for hyperparameters with string values."""

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -720,10 +720,16 @@ def _get_fine_tuning_options_and_model_arn(model_name: str, customization_techni
720720
except Exception as e:
721721
logger.debug(f"Could not fetch subscription recipe override_params: {type(e).__name__}: {e}")
722722

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+
# max_prompt_length + max_response_length (or max_length) stays within
726+
# what the recipe's hardware can serve. 0 if absent/unparseable (no-op).
727+
context_length = _parse_context_length(recipe.get("SequenceLength")) or None
728+
723729
if options_dict:
724-
return FineTuningOptions(options_dict), model_arn, is_gated_model
730+
return FineTuningOptions(options_dict, context_length=context_length), model_arn, is_gated_model
725731
else:
726-
return FineTuningOptions({}), model_arn, is_gated_model
732+
return FineTuningOptions({}, context_length=context_length), model_arn, is_gated_model
727733

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

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,9 @@ 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.
284+
self.hyperparameters.validate_length_constraints()
285+
283286
final_hyperparameters = self.hyperparameters.to_dict()
284287

285288
# Resolve is_multimodal: auto-detect from training dataset if not explicitly set

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,9 @@ 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.
481+
self.hyperparameters.validate_length_constraints()
482+
480483
final_hyperparameters = self.hyperparameters.to_dict()
481484

482485
# Apply recipe/overrides if provided (overrides > recipe > Hub defaults)

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,64 @@ def test_to_dict_all_none_returns_empty(self):
5454
})
5555
result = options.to_dict()
5656
assert result == {}
57+
58+
59+
import pytest
60+
61+
62+
class TestValidateLengthConstraints:
63+
"""FineTuningOptions.validate_length_constraints() — sum vs context_length."""
64+
65+
def _rl_options(self, prompt, response, context_length):
66+
# Per-field max defaults to context_length; when unknown, omit it so the
67+
# per-field range check is a no-op and only the sum-guard is exercised.
68+
prompt_spec = {"type": "integer", "default": 1024, "min": 512}
69+
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
73+
opts = FineTuningOptions(
74+
{"max_prompt_length": prompt_spec, "max_response_length": response_spec},
75+
context_length=context_length,
76+
)
77+
object.__setattr__(opts, "max_prompt_length", prompt)
78+
object.__setattr__(opts, "max_response_length", response)
79+
return opts
80+
81+
def test_rl_sum_within_context_length_passes(self):
82+
opts = self._rl_options(prompt=4096, response=8192, context_length=262144)
83+
opts.validate_length_constraints() # no raise
84+
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
88+
89+
def test_rl_sum_exceeds_context_length_raises(self):
90+
opts = self._rl_options(prompt=200000, response=200000, context_length=262144)
91+
with pytest.raises(ValueError) as exc:
92+
opts.validate_length_constraints()
93+
msg = str(exc.value)
94+
assert "400000" in msg and "262144" in msg
95+
96+
def test_sft_max_length_within_context_length_passes(self):
97+
opts = FineTuningOptions(
98+
{"max_length": {"type": "integer", "default": 4096, "min": 4096, "max": 131072}},
99+
context_length=131072,
100+
)
101+
opts.max_length = 65536
102+
opts.validate_length_constraints() # no raise
103+
104+
def test_sft_max_length_exceeds_context_length_raises(self):
105+
opts = FineTuningOptions(
106+
{"max_length": {"type": "integer", "default": 4096, "min": 4096, "max": 131072}},
107+
context_length=131072,
108+
)
109+
# max is 131072, so set via _specs bypass to test the sum-guard directly
110+
object.__setattr__(opts, "max_length", 200000)
111+
with pytest.raises(ValueError) as exc:
112+
opts.validate_length_constraints()
113+
assert "131072" in str(exc.value)
114+
115+
def test_no_context_length_is_noop(self):
116+
opts = self._rl_options(prompt=200000, response=200000, context_length=None)
117+
opts.validate_length_constraints() # unknown ceiling -> no raise

0 commit comments

Comments
 (0)