Skip to content

Pipeline eval

Encapsulating the call to the users evaluate_pipeline.

EvaluatePipelineReturn module-attribute #

EvaluatePipelineReturn: TypeAlias = (
    Exception | UserResultDict | dict
)

The type of things evaluate_pipeline can return.

  • Exception: The evaluation failed.
  • Mapping[str, Any]: A dict which follows the layout of UserResultDict.

UserResult dataclass #

UserResult(
    objective_to_minimize: float | None = None,
    cost: float | None = None,
    learning_curve: (
        list[float] | list[list[float]] | None
    ) = None,
    extra: dict[str, Any] = dict(),
    exception: Exception | None = None,
    inference_cost: float | None = None,
    downstream_performances: dict[str, float] = dict(),
    n_params: float | None = None,
    n_data: float | None = None,
)

The parsed values out of the possibilities the user can return from the evaluate_pipeline_function().

See UserResultDict for the possibilities.

parse classmethod #

parse(
    user_result: EvaluatePipelineReturn,
    *,
    default_objective_to_minimize_value: float | None,
    default_cost_value: float | None = None,
    default_learning_curve: (
        Literal["objective_to_minimize"]
        | list[float]
        | None
    ) = None
) -> UserResult

Parse the return type a user can provide from evaluate_pipeline.

Source code in scalefm/state/pipeline_eval.py
@classmethod
def parse(  # noqa: C901, PLR0912, PLR0915
    cls,
    user_result: EvaluatePipelineReturn,
    *,
    default_objective_to_minimize_value: float | None,
    default_cost_value: float | None = None,
    default_learning_curve: Literal["objective_to_minimize"]
    | list[float]
    | None = None,
) -> UserResult:
    """Parse the return type a user can provide from `evaluate_pipeline`."""
    objective_to_minimize: float | None
    cost: float | None
    learning_curve: list[float] | list[list[float]] | None
    extra_info: dict[str, Any]
    exception: Exception | None

    match user_result:
        # An Error
        case Exception():
            objective_to_minimize = default_objective_to_minimize_value
            match default_learning_curve:
                case "objective_to_minimize":
                    learning_curve = (  # obj_to_minimize as the curve, if any
                        [objective_to_minimize]  # type: ignore
                        if objective_to_minimize is not None
                        else None
                    )
                case None | Sequence():
                    learning_curve = default_learning_curve  # type: ignore
                case _:
                    raise ValueError(
                        "The default learning curve should be either None or"
                        f" 'objective_to_minimize'. Got {default_learning_curve}"
                    )

            return UserResult(
                objective_to_minimize=default_objective_to_minimize_value,
                cost=default_cost_value,
                learning_curve=learning_curve,
                exception=user_result,
                extra={},
            )

        # A UserResultDict, the most annoying to parse out as theoretically
        # the could provide everything)
        case Mapping():
            _result = dict(user_result)

            popped_exception = _result.pop("exception", None)
            if (
                not isinstance(popped_exception, Exception)
                and popped_exception is not None
            ):
                raise ValueError(
                    "The 'exception' should be an exception or None,"
                    f" but got {popped_exception}"
                )
            exception = popped_exception

            popped_obj = _result.pop(
                "objective_to_minimize", default_objective_to_minimize_value
            )
            match popped_obj:
                case None:
                    objective_to_minimize = popped_obj
                case int() | float() | np.number():
                    objective_to_minimize = float(popped_obj)
                case Sequence():
                    raise ValueError(
                        "Multi-objective optimization is not supported, the"
                        " 'objective_to_minimize' should be a single float."
                        f" Got {popped_obj}"
                    )
                case _:
                    raise ValueError(
                        "The 'objective_to_minimize' should be either a float or"
                        f" None. Got {popped_obj}"
                    )

            popped_cost = _result.pop("cost", default_cost_value)
            match popped_cost:
                case None:
                    cost = popped_cost
                case int() | float() | np.number():
                    cost = float(popped_cost)
                case _:
                    raise ValueError(
                        "The 'cost' should be either a float or None."
                        f" Got {popped_cost}"
                    )
            # A successful evaluation needs its training cost
            if exception is None and cost is None:
                raise ValueError(
                    "The result has no 'cost'. Return the training cost, e.g. its"
                    " FLOPs, or pass a `cost_estimator` to `scalefm.acquire()`."
                )

            # Learning curve is annoying as we have a cross product of possible
            # learning curve returns and what to do if there is a default.
            popped_curve = _result.pop("learning_curve", None)
            match popped_curve:
                case Sequence():
                    learning_curve = list(popped_curve)
                case None:
                    # If no learning curve, see what to do with the default
                    match default_learning_curve:
                        case None:
                            learning_curve = None
                        case "objective_to_minimize":
                            learning_curve = (
                                [objective_to_minimize]  # type: ignore
                                if objective_to_minimize is not None
                                else None
                            )
                        case Sequence():
                            learning_curve = default_learning_curve  # type: ignore
                        case _:
                            raise ValueError(
                                "The default learning curve should be either None, "
                                " 'objective_to_minimize' or sequence."
                                f" Got {default_learning_curve}"
                            )
                case _:
                    raise ValueError(
                        "The 'learning_curve' should be either a sequence of floats"
                        f" or None. Got {popped_curve}"
                    )

            popped_extra_info = _result.pop("info_dict", {})
            if not isinstance(popped_extra_info, Mapping):
                raise ValueError(
                    "The 'info_dict' should be a dictionary, but got"
                    f" {popped_extra_info}"
                )
            extra_info = dict(popped_extra_info)

            # Legacy
            if "learning_curve" in extra_info:
                raise ValueError(
                    "Please provide 'learning_curve' in the top level of the"
                    " dictionary, not in 'info_dict'."
                )

            return UserResult(
                objective_to_minimize=objective_to_minimize,
                cost=cost,
                extra=extra_info,
                learning_curve=learning_curve,
                exception=exception,
                inference_cost=_result.pop("inference_cost", None),
                downstream_performances=_result.pop("downstream_performances", None)
                or {},
                n_params=_result.pop("n_params", None),
                n_data=_result.pop("n_data", None),
            )

        case _:
            raise ValueError(
                "The result should be a dictionary with at least"
                " 'objective_to_minimize' and 'cost', or an exception."
                f" Got {user_result}"
            )

UserResultDict #

Bases: TypedDict

The type of things you can include when returning a dictionary from evaluate_pipeline.

objective_to_minimize and cost are required, the other fields are optional. If an exception is provided, we count the trial as having failed.

cost instance-attribute #

cost: float | None

The training cost of the evaluation, e.g. its FLOPs. Required, unless a cost_estimator is passed to scalefm.acquire().

downstream_performances instance-attribute #

downstream_performances: Mapping[str, float] | None

The model's performance on downstream tasks, by name, e.g. {"hellaswag_acc": 0.41}. The scaling plots draw each of them over the cost.

exception instance-attribute #

exception: Exception | None

The exception that occured.

inference_cost instance-attribute #

inference_cost: float | None

The cost of using the trained model once, e.g. the FLOPs of one forward pass. The scaling plots are also drawn over it.

info_dict instance-attribute #

info_dict: Mapping[str, Any] | None

Extra information that will be stored with the trials result.

learning_curve instance-attribute #

learning_curve: (
    Sequence[float] | Sequence[Sequence[float]] | None
)

The learning curve for this configuration: the loss at each checkpoint, or rows of (n_data, flops, loss), which Chinchilla approach 1 and the power law fit on.

n_data instance-attribute #

n_data: float | None

The amount of training data, e.g. the number of tokens.

n_params instance-attribute #

n_params: float | None

The number of parameters of the model.

objective_to_minimize instance-attribute #

objective_to_minimize: float | None

The objective value to minimize, e.g. the loss.

evaluate_trial #

evaluate_trial(
    trial: Trial,
    *,
    evaluation_fn: Callable[..., Any],
    default_report_values: DefaultReportValues
) -> tuple[Trial, Report | None]

Evaluates a trial from a user and parses the results into a Report.

Source code in scalefm/state/pipeline_eval.py
def evaluate_trial(
    trial: Trial,
    *,
    evaluation_fn: Callable[..., Any],
    default_report_values: DefaultReportValues,
) -> tuple[Trial, Report | None]:
    """Evaluates a trial from a user and parses the results into a `Report`."""
    trial_location = Path(trial.metadata.location)
    prev_trial_location = (
        Path(trial.metadata.previous_trial_location)
        if trial.metadata.previous_trial_location is not None
        else None
    )

    params = {
        "pipeline_directory": trial_location,
        "previous_pipeline_directory": prev_trial_location,
        "pipeline_id": trial.id,
    }
    sigkeys = inspect.signature(evaluation_fn).parameters.keys()
    injectable_params = {key: val for key, val in params.items() if key in sigkeys}
    report = _eval_trial(
        trial=trial,
        fn=evaluation_fn,
        default_report_values=default_report_values,
        **injectable_params,
    )
    return trial, report