Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

fix(teleprompt): raise a clear error when student predictors have no LM set (#10569)

Adityabc8af7ed3d5e
diff --git a/dspy/teleprompt/bettertogether.py b/dspy/teleprompt/bettertogether.py
index 1294c5722..fe47b6981 100644
--- a/dspy/teleprompt/bettertogether.py
+++ b/dspy/teleprompt/bettertogether.py
@@ -10,6 +10,7 @@ from dspy.primitives.module import Module
from dspy.teleprompt.bootstrap_finetune import (
BootstrapFinetune,
all_predictors_have_lms,
+ assert_all_predictors_have_lms,
kill_lms,
launch_lms,
prepare_student,
@@ -308,7 +309,7 @@ class BetterTogether(Teleprompter):
self, student: Module, teacher: Module | list[Module] | None
) -> tuple[Module, list[Module] | None]:
student = prepare_student(student)
- all_predictors_have_lms(student)
+ assert_all_predictors_have_lms(student, role="student")
if not teacher:
return student, None
diff --git a/dspy/teleprompt/bootstrap_finetune.py b/dspy/teleprompt/bootstrap_finetune.py
index 3437c9a3d..9c54cd4e5 100644
--- a/dspy/teleprompt/bootstrap_finetune.py
+++ b/dspy/teleprompt/bootstrap_finetune.py
@@ -247,6 +247,31 @@ def all_predictors_have_lms(program: Module) -> bool:
return all(pred.lm for pred in program.predictors())
+def assert_all_predictors_have_lms(program: Module, role: str = "program") -> None:
+ """Raise ValueError if any predictor in the program has no LM set.
+
+ This is the asserting counterpart of ``all_predictors_have_lms``, for callers
+ that require every predictor to carry an LM before compiling. Calling the
+ predicate on its own validates nothing, since its result is easy to drop.
+
+ Args:
+ program: Program whose predictors should all have an LM set.
+ role: How to refer to the program in the error message, e.g. ``"student"``.
+
+ Raises:
+ ValueError: If at least one predictor has no LM set.
+ """
+ named = list(program.named_predictors())
+ missing = [name for name, pred in named if not pred.lm]
+ if missing:
+ raise ValueError(
+ f"The {role} program must have a language model set on every predictor, "
+ f"but these have none: {missing}. "
+ f"Assign an LM to them; `{role}.set_lm(lm)` sets every predictor and "
+ f"overwrites LMs that are already set."
+ )
+
+
def copy_program_with_lms(program: Module) -> Module:
pred_lms = [pred.lm for pred in program.predictors()]
program = program.deepcopy()
diff --git a/tests/teleprompt/test_bettertogether.py b/tests/teleprompt/test_bettertogether.py
index 8f4ee4988..5579f26c3 100644
--- a/tests/teleprompt/test_bettertogether.py
+++ b/tests/teleprompt/test_bettertogether.py
@@ -245,6 +245,76 @@ def test_valset_ratio_validation():
assert "must be in range [0, 1)" in str(e)
+def test_compile_requires_student_lms():
+ """Student predictors without an LM must fail fast with a clear error.
+
+ ``all_predictors_have_lms`` is a predicate, so calling it for its side
+ effects validated nothing and compilation only failed later inside
+ ``launch_lms`` with ``AttributeError: 'NoneType' object has no attribute
+ 'launch'``.
+ """
+ optimizer = BetterTogether(metric=simple_metric, p=SimpleOptimizer())
+ # Deliberately no student.set_lm(...), despite the docstring requiring it.
+ student = SimpleModule("input -> output")
+
+ with pytest.raises(ValueError, match=r"student\.set_lm\(lm\)"):
+ optimizer.compile(student, trainset=trainset, valset=valset, strategy="p")
+
+
+def test_compile_names_the_predictors_missing_an_lm():
+ """The error lists exactly the predictors that are missing an LM."""
+ optimizer = BetterTogether(metric=simple_metric, p=SimpleOptimizer())
+
+ class TwoPredictorModule(dspy.Module):
+ def __init__(self):
+ super().__init__()
+ self.qa = Predict("input -> output")
+ self.summarize = Predict("input -> output")
+
+ def forward(self, **kwargs):
+ return self.qa(**kwargs)
+
+ student = TwoPredictorModule()
+ # Only the first predictor has an LM set.
+ student.qa.set_lm(DummyLM([{"output": "test"}]))
+
+ with pytest.raises(ValueError) as excinfo:
+ optimizer.compile(student, trainset=trainset, valset=valset, strategy="p")
+
+ assert "summarize" in str(excinfo.value)
+ assert "'qa'" not in str(excinfo.value)
+
+
+def test_error_message_warns_that_set_lm_overwrites():
+ """The advice must warn that set_lm replaces every predictor's LM.
+
+ Module.set_lm assigns to all named parameters, so recommending it bare
+ would silently drop LMs deliberately set on other predictors (flagged in
+ review on https://github.com/stanfordnlp/dspy/pull/10569).
+ """
+ optimizer = BetterTogether(metric=simple_metric, p=SimpleOptimizer())
+ student = SimpleModule("input -> output")
+
+ with pytest.raises(ValueError) as excinfo:
+ optimizer.compile(student, trainset=trainset, valset=valset, strategy="p")
+
+ message = str(excinfo.value)
+ assert "student.set_lm(lm)" in message
+ assert "overwrite" in message
+
+
+def test_compile_accepts_student_with_all_lms_set():
+ """A student whose predictors all have an LM passes the check."""
+ optimizer = BetterTogether(metric=simple_metric, p=SimpleOptimizer())
+ student = SimpleModule("input -> output")
+ student.set_lm(DummyLM([{"output": "test"}]))
+
+ prepared, teacher = optimizer._prepare_student_and_teacher(student, None)
+
+ assert prepared is student
+ assert teacher is None
+
+
def test_optimizer_compile_args_validation():
"""Test that optimizer_compile_args is validated correctly."""
optimizer = BetterTogether(metric=simple_metric)