dspy.Refine

dspy.Refine

dspy.Refine는 모듈을 다른 rollout ID로 temperature=1.0에서 최대 N번 실행해 가장 좋은 예측을 반환하는 방식으로 모듈을 개선(refine)합니다.

출처: 문서

본문

dspy.Refine(
    module: Module,
    N: int,
    reward_fn: Callable[[dict, Prediction], float],
    threshold: float,
    fail_count: int | None = None,
)
  • Bases: Module(callbacks=None)

이 모듈은 주어진 모듈을 서로 다른 rollout 식별자로 여러 번 실행하고, 지정된 threshold를 초과하는 첫 번째 예측 또는 가장 높은 보상을 받은 예측을 선택합니다. 어떤 예측도 threshold를 충족하지 못하면 미래 예측을 개선하기 위해 자동으로 피드백을 생성합니다.

Parameters:

Name Type Description Default
module Module 개선할 모듈. required
N int 모듈을 실행할 횟수. required
reward_fn Callable 보상 함수. required
threshold float 보상 함수에 대한 threshold. required
fail_count Optional[int] 에러를 발생시키기 전에 모듈이 실패할 수 있는 횟수. None

Examples

import dspy

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))

# Define a QA module with chain of thought
qa = dspy.ChainOfThought("question -> answer")

# Define a reward function that checks for one-word answers
def one_word_answer(args, pred):
    return 1.0 if len(pred.answer.split()) == 1 else 0.0

# Create a refined module that tries up to 3 times
best_of_3 = dspy.Refine(module=qa, N=3, reward_fn=one_word_answer, threshold=1.0)

# Use the refined module
result = best_of_3(question="What is the capital of Belgium?").answer
# Returns: Brussels

소스 코드는 dspy/predict/refine.py에 있습니다.

def __init__(
    self,
    module: Module,
    N: int,  # noqa: N803
    reward_fn: Callable[[dict, Prediction], float],
    threshold: float,
    fail_count: int | None = None,
):
    """
    Refines a module by running it up to N times with different rollout IDs at `temperature=1.0`
    and returns the best prediction.

    This module runs the provided module multiple times with varying rollout identifiers and selects
    ...
    """

Methods

def forward(self, **kwargs):
    lm = self.module.get_lm() or dspy.settings.lm
    start = lm.kwargs.get("rollout_id", 0)
    rollout_ids = [start + i for i in range(self.N)]
    best_pred, best_trace, best_reward = None, None, -float("inf")
    advice = None
    adapter = dspy.settings.adapter or dspy.ChatAdapter()

    for idx, rid in enumerate(rollout_ids):
        lm_ = lm.copy(rollout_id=rid, temperature=1.0)
        mod = self.module.deepcopy()
        mod.set_lm(lm_)

        predictor2name = {predictor: name for name, predictor in mod.named_predictors()}
        signature2name = {predictor.signature: name for name, predictor in mod.named_predictors()}
        module_names = [name for name, _ in mod.named_predictors()]

        try:
            with dspy.context(trace=[]):
                if not advice:
                    ...

forward는 N개의 rollout ID를 만들고, 각각에 대해 모듈을 깊은 복사해 temperature=1.0의 LM을 설정한 뒤 실행합니다. 각 실행의 보상을 reward_fn으로 계산해 가장 좋은 예측을 추적하고, threshold를 넘는 예측이 없으면 피드백(advice)을 생성해 다음 실행에 반영합니다.

그 외 상속받은 메서드

Refine는 Module/BaseModule/Parameter에서 공통 메서드를 상속받습니다. 자세한 설명은 Predict 페이지를 참고하세요.

  • __call__(*args, **kwargs) -> Prediction — 모듈 호출.
  • acall(*args, **kwargs) -> Prediction (async) — 비동기 호출.
  • batch(...) — dspy.Example 리스트를 Parallel로 병렬 처리.
  • deepcopy() / dump_state(json_mode=True) — 복사·상태 내보내기.
  • get_lm() / set_lm(lm) — 언어 모델 조회·설정.
  • inspect_history(n=1, file=None) — LM 호출 기록 표시.
  • load(...) / load_state(...) — 상태 불러오기.
  • map_named_predictors(func) — named predictor에 함수 적용.
  • named_parameters() / named_predictors() / named_sub_modules() / parameters() / predictors() — 구조 탐색.
  • reset_copy() — 복사 후 초기화.
  • save(...) — 모듈 저장.

더 알아보기 (Learn more)