Skip to content

Power law

Power-law prediction: log-log linear fits in the compute, one per predicted quantity.

  • LOSS: the loss on the (flops, loss) Pareto front, see arxiv.org/abs/2001.08361, above a fitted irreducible loss E: log10(loss - E) = slope * log10(flops) + intercept.

The LOSS and FULL fits skip the low-compute plateau of the front, if any, see scaling_regime_start. * COARSE: the model size on the learning-curve envelope (Chinchilla approach 1), with n_data = flops / (6 * n_params). * FULL: every searchable hyperparameter on the (flops, loss) Pareto front.

PowerLawCoarseInfo dataclass #

PowerLawCoarseInfo(
    slope: float,
    intercept: float,
    r_squared: float,
    slope_std_err: float,
)

The model size power law fit behind a coarse prediction.

PowerLawFullFit dataclass #

PowerLawFullFit(
    hp_fits: dict[str, LogLogPowerLawFit],
    pareto_ids: list[int],
    pareto_configs: list[dict[str, Any]],
    pareto_flops: list[float],
    pareto_losses: list[float],
    fit_start: int = 0,
)

One power law per searchable HP, plus the Pareto front it was fitted on.

The HPs are fitted on the front from fit_start on, past its low-compute plateau.

PowerLawLossInfo dataclass #

PowerLawLossInfo(
    slope: float,
    intercept: float,
    r_squared: float,
    slope_std_err: float,
    num_pareto_points: int,
    predicted_loss: float,
    predicted_loss_upper: float,
    predicted_loss_lower: float,
    irreducible_loss: float = 0.0,
)

The loss power law fit and its prediction at one compute budget.

compute_full_pareto #

compute_full_pareto(
    *,
    configs: list[dict[str, Any]],
    losses: list[float],
    flops: list[float]
) -> tuple[
    list[int],
    list[dict[str, Any]],
    list[float],
    list[float],
]

(ids, configs, flops, losses) of the (flops, loss) Pareto front.

Source code in scalefm/prediction/power_law.py
def compute_full_pareto(
    *,
    configs: list[dict[str, Any]],
    losses: list[float],
    flops: list[float],
) -> tuple[list[int], list[dict[str, Any]], list[float], list[float]]:
    """(ids, configs, flops, losses) of the (flops, loss) Pareto front."""
    pareto_result = pareto_front(losses, flops)
    if pareto_result is None:
        raise ValueError("Could not compute Pareto front from losses/flops")

    pareto_flops, pareto_losses, pareto_ids = pareto_result
    pareto_configs = [configs[i] for i in pareto_ids]
    return pareto_ids, pareto_configs, pareto_flops, pareto_losses

fit_coarse #

fit_coarse(
    rows: list[Row] | list[list[Row]],
) -> LogLogPowerLawFit

Fit log10(n_params) against log10(flops) on the compute optimal rows.

Source code in scalefm/prediction/power_law.py
def fit_coarse(rows: list[Row] | list[list[Row]]) -> LogLogPowerLawFit:
    """Fit log10(n_params) against log10(flops) on the compute optimal rows."""
    rows_for_fit, _all_rows = prepare_rows_for_coarse_prediction(rows)

    rows_arr = np.asarray(rows_for_fit, dtype=float)
    if rows_arr.ndim != 2 or rows_arr.shape[1] != 4:
        raise ValueError("rows must be a 2D array-like with shape (n, 4)")

    params_arr = rows_arr[:, 0]
    data_arr = rows_arr[:, 1]
    flops_arr = rows_arr[:, 3]
    mask = (
        np.isfinite(params_arr)
        & np.isfinite(data_arr)
        & np.isfinite(flops_arr)
        & (params_arr > 0)
        & (data_arr > 0)
        & (flops_arr > 0)
    )
    if not np.any(mask):
        raise ValueError("rows do not contain any finite positive loss/flop values")

    fit_result = fit_power_law(
        np.asarray(flops_arr[mask], dtype=float),
        np.asarray(params_arr[mask], dtype=float),
    )
    if fit_result is None:
        raise ValueError(
            "Could not fit a power law to the model size from the provided rows"
        )
    return fit_result

fit_from_row #

fit_from_row(row: ndarray) -> LogLogPowerLawFit | None

Deserialize a fit row, None for a failed fit.

Only a NaN slope/intercept means the fit failed: linregress legitimately returns NaN r_squared/stderr (division by zero) when the fitted quantity is constant across the Pareto front, even though slope/intercept are perfectly valid.

Source code in scalefm/prediction/power_law.py
def fit_from_row(row: np.ndarray) -> LogLogPowerLawFit | None:
    """Deserialize a fit row, None for a failed fit.

    Only a NaN slope/intercept means the fit failed: `linregress` legitimately returns
    NaN r_squared/stderr (division by zero) when the fitted quantity is constant across
    the Pareto front, even though slope/intercept are perfectly valid.
    """
    row = np.asarray(row, dtype=float)
    if np.any(np.isnan(row[:2])):
        return None
    # Rows without an offset were written before it was fitted
    slope, intercept, r_squared, slope_std_err, intercept_std_err, num_points = row[:6]
    offset = float(row[6]) if len(row) > 6 and np.isfinite(row[6]) else 0.0
    return LogLogPowerLawFit(
        slope=float(slope),
        intercept=float(intercept),
        r_squared=float(r_squared),
        slope_std_err=float(slope_std_err),
        intercept_std_err=float(intercept_std_err),
        num_points=int(num_points) if np.isfinite(num_points) else 0,
        offset=offset,
    )

fit_full #

fit_full(
    *,
    space: SearchSpace,
    configs: list[dict[str, Any]],
    losses: list[float],
    flops: list[float]
) -> PowerLawFullFit

Fit one power law per searchable HP on the Pareto front of the configs, past its low-compute plateau, see scaling_regime_start.

Source code in scalefm/prediction/power_law.py
def fit_full(
    *,
    space: SearchSpace,
    configs: list[dict[str, Any]],
    losses: list[float],
    flops: list[float],
) -> PowerLawFullFit:
    """Fit one power law per searchable HP on the Pareto front of the configs, past
    its low-compute plateau, see `scaling_regime_start`.
    """
    pareto_ids, pareto_configs, pareto_flops, pareto_losses = compute_full_pareto(
        configs=configs, losses=losses, flops=flops
    )
    start = scaling_regime_start(pareto_flops, pareto_losses)
    hp_fits = fit_hp_power_laws(
        space=space,
        pareto_configs=pareto_configs[start:],
        pareto_flops=pareto_flops[start:],
    )
    return PowerLawFullFit(
        hp_fits=hp_fits,
        pareto_ids=pareto_ids,
        pareto_configs=pareto_configs,
        pareto_flops=pareto_flops,
        pareto_losses=pareto_losses,
        fit_start=start,
    )

fit_hp_power_laws #

fit_hp_power_laws(
    *,
    space: SearchSpace,
    pareto_configs: list[dict[str, Any]],
    pareto_flops: list[float]
) -> dict[str, LogLogPowerLawFit]

Fit one power law per searchable HP, independent of any target_flops.

Source code in scalefm/prediction/power_law.py
def fit_hp_power_laws(
    *,
    space: SearchSpace,
    pareto_configs: list[dict[str, Any]],
    pareto_flops: list[float],
) -> dict[str, LogLogPowerLawFit]:
    """Fit one power law per searchable HP, independent of any target_flops."""
    x_flops = np.asarray(pareto_flops, dtype=float)

    hp_fits: dict[str, LogLogPowerLawFit] = {}
    for param_name, param in space.searchables.items():
        hp_values_param: list[float] = []
        for config in pareto_configs:
            if param_name not in config:
                raise ValueError(f"HP '{param_name}' is missing from config: {config}")
            hp_values_param.append(float(config[param_name]))

        fit_result = fit_power_law(
            x_flops,
            np.asarray(hp_values_param, dtype=float),
            log_scale=_fits_in_log_space(param),
        )
        if fit_result is None:
            raise ValueError(
                f"Not enough valid data points to fit scaling law for HP '{param_name}'"
            )
        hp_fits[param_name] = fit_result

    return hp_fits

fit_loss #

fit_loss(rows: list[Row]) -> LogLogPowerLawFit

Fit log10(loss - E) = slope * log10(flops) + intercept on the (flops, loss) Pareto front, with the irreducible loss E (the offset of the fit) in [0, min(loss)), see fit_power_law_with_offset.

Only the front past its low-compute plateau is fit, see scaling_regime_start.

Source code in scalefm/prediction/power_law.py
def fit_loss(rows: list[Row]) -> LogLogPowerLawFit:
    """Fit `log10(loss - E) = slope * log10(flops) + intercept` on the (flops, loss)
    Pareto front, with the irreducible loss E (the `offset` of the fit) in
    `[0, min(loss))`, see `fit_power_law_with_offset`.

    Only the front past its low-compute plateau is fit, see `scaling_regime_start`.
    """
    rows_arr = np.asarray(rows, dtype=float)
    if rows_arr.ndim != 2 or rows_arr.shape[1] != 4:
        raise ValueError("rows must be a 2D array-like with shape (n, 4)")

    losses_arr = rows_arr[:, 2]
    flops_arr = rows_arr[:, 3]
    mask = (
        np.isfinite(losses_arr)
        & np.isfinite(flops_arr)
        & (losses_arr > 0)
        & (flops_arr > 0)
    )
    if not np.any(mask):
        raise ValueError("rows do not contain any finite positive loss/flop values")

    res = pareto_front(losses_arr[mask], flops_arr[mask])
    if not res:
        raise ValueError("Could not compute a Pareto front from the provided rows")

    pareto_flops, pareto_losses, _pareto_indices = res
    start = scaling_regime_start(pareto_flops, pareto_losses)
    fit_result = fit_power_law_with_offset(
        np.asarray(pareto_flops[start:], dtype=float),
        np.asarray(pareto_losses[start:], dtype=float),
    )
    if fit_result is None:
        raise ValueError("Could not fit a power law to the loss from the provided rows")
    return fit_result

fit_to_row #

fit_to_row(fit: LogLogPowerLawFit | None) -> list[float]

Serialize a fit to a fixed-width row; a failed fit becomes an all-NaN row.

Source code in scalefm/prediction/power_law.py
def fit_to_row(fit: LogLogPowerLawFit | None) -> list[float]:
    """Serialize a fit to a fixed-width row; a failed fit becomes an all-NaN row."""
    if fit is None:
        return [float("nan")] * ROW_WIDTH
    return [
        fit.slope,
        fit.intercept,
        fit.r_squared,
        fit.slope_std_err,
        fit.intercept_std_err,
        float(fit.num_points),
        fit.offset,
    ]

predict_coarse #

predict_coarse(
    fit: LogLogPowerLawFit, target_flop: float
) -> tuple[tuple[float, float], PowerLawCoarseInfo]

The compute optimal (n_params, n_data) the power law predicts at a budget.

Source code in scalefm/prediction/power_law.py
def predict_coarse(
    fit: LogLogPowerLawFit, target_flop: float
) -> tuple[tuple[float, float], PowerLawCoarseInfo]:
    """The compute optimal `(n_params, n_data)` the power law predicts at a budget."""
    if target_flop <= 0:
        raise ValueError("target_flop must be positive for a log-log power law")

    predicted_param, _upper, _lower = predict_from_loglog_fit(
        fit=fit, target_flop=target_flop, z_score=1.96
    )
    info = PowerLawCoarseInfo(
        slope=fit.slope,
        intercept=fit.intercept,
        r_squared=fit.r_squared,
        slope_std_err=fit.slope_std_err,
    )
    predicted_n_param = float(predicted_param)
    if not np.isfinite(predicted_n_param) or predicted_n_param <= 0:
        raise ValueError("Could not predict a positive n_param from the power law")
    predicted_n_data = float(target_flop / (6.0 * predicted_n_param))
    if not np.isfinite(predicted_n_data) or predicted_n_data <= 0:
        raise ValueError("Could not derive a positive n_data from the predicted n_param")

    return (predicted_n_param, predicted_n_data), info

predict_full #

predict_full(
    fit: PowerLawFullFit,
    space: SearchSpace,
    target_flops: float,
) -> dict[str, Any]

The config whose HPs the per-HP power laws extrapolate to target_flops, and in fitted_config the values of the power laws in the bounds of the space, before they are rounded to it.

Source code in scalefm/prediction/power_law.py
def predict_full(
    fit: PowerLawFullFit, space: SearchSpace, target_flops: float
) -> dict[str, Any]:
    """The config whose HPs the per-HP power laws extrapolate to `target_flops`, and
    in `fitted_config` the values of the power laws in the bounds of the space, before
    they are rounded to it.
    """
    extrapolated_config: dict[str, Any] = {}
    fitted_config: dict[str, float] = {}
    for param_name, param in space.searchables.items():
        predicted_hp, _, _ = predict_from_loglog_fit(
            fit.hp_fits[param_name],
            target_flops,
            log_scale=_fits_in_log_space(param),
        )
        predicted_hp = np.clip(predicted_hp, param.domain.lower, param.domain.upper)
        fitted_config[param_name] = float(predicted_hp)
        predicted_hp = _snap_to_log_base_grid(float(predicted_hp), param)
        extrapolated_config[param_name] = param.domain.cast_one(
            float(predicted_hp), frm=param.domain
        )

    return {
        "extrapolated_config": extrapolated_config,
        "fitted_config": fitted_config,
        "pareto_ids": fit.pareto_ids,
        "pareto_configs": fit.pareto_configs,
        "pareto_flops": fit.pareto_flops,
        "pareto_losses": fit.pareto_losses,
        "pareto_fit_start": fit.fit_start,
    }

predict_loss #

predict_loss(
    fit: LogLogPowerLawFit, target_flop: float
) -> tuple[float, PowerLawLossInfo]

The loss the power law predicts at target_flop.

Source code in scalefm/prediction/power_law.py
def predict_loss(
    fit: LogLogPowerLawFit, target_flop: float
) -> tuple[float, PowerLawLossInfo]:
    """The loss the power law predicts at `target_flop`."""
    if target_flop <= 0:
        raise ValueError("target_flop must be positive for a log-log power law")

    predicted_loss, predicted_loss_upper, predicted_loss_lower = predict_from_loglog_fit(
        fit=fit,
        target_flop=target_flop,
        z_score=1.96,
    )
    info = PowerLawLossInfo(
        slope=fit.slope,
        intercept=fit.intercept,
        r_squared=fit.r_squared,
        slope_std_err=fit.slope_std_err,
        num_pareto_points=fit.num_points,
        predicted_loss=predicted_loss,
        predicted_loss_upper=predicted_loss_upper,
        predicted_loss_lower=predicted_loss_lower,
        irreducible_loss=fit.offset,
    )
    return predicted_loss, info

prepare_rows_for_coarse_prediction #

prepare_rows_for_coarse_prediction(
    rows: list[Row] | list[list[Row]],
) -> tuple[list[Row], list[Row]]

Rows to fit the model size on, and all rows.

Plain rows keep the lowest loss per flops value; grouped learning-curve rows become their loss envelope.

Source code in scalefm/prediction/power_law.py
def prepare_rows_for_coarse_prediction(
    rows: list[Row] | list[list[Row]],
) -> tuple[list[Row], list[Row]]:
    """Rows to fit the model size on, and all rows.

    Plain rows keep the lowest loss per flops value; grouped learning-curve rows
    become their loss envelope.
    """
    all_rows = flatten_rows(rows)

    if rows and isinstance(rows[0], tuple):
        unique_flops_min_loss: dict[float, Row] = {}
        for row in all_rows:
            n_param, n_data, loss, flop = row
            if not (
                np.isfinite(n_param)
                and np.isfinite(n_data)
                and np.isfinite(loss)
                and np.isfinite(flop)
            ):
                continue
            if n_param <= 0 or n_data <= 0 or loss <= 0 or flop <= 0:
                continue

            existing = unique_flops_min_loss.get(float(flop))
            if existing is None or float(loss) < float(existing[2]):
                unique_flops_min_loss[float(flop)] = (
                    float(n_param),
                    float(n_data),
                    float(loss),
                    float(flop),
                )

        selected_rows = [
            unique_flops_min_loss[f] for f in sorted(unique_flops_min_loss.keys())
        ]
        return selected_rows, all_rows

    if not rows:
        return [], []

    return _learning_curve_envelope(cast("list[list[Row]]", rows)), all_rows

smoothed_learning_curves #

smoothed_learning_curves(
    curves: list[list[Row]],
) -> list[tuple[float, ndarray, ndarray]] | None

Every learning curve as _learning_curve_envelope sees it.

Returns one (n_params, flops, loss) per usable curve, interpolated on the shared log-flops grid and Gaussian smoothed, or None if the curves span no flops range. Curves with fewer than two usable points are left out.

Source code in scalefm/prediction/power_law.py
def smoothed_learning_curves(
    curves: list[list[Row]],
) -> list[tuple[float, np.ndarray, np.ndarray]] | None:
    """Every learning curve as `_learning_curve_envelope` sees it.

    Returns one (n_params, flops, loss) per usable curve, interpolated on the shared
    log-flops grid and Gaussian smoothed, or None if the curves span no flops range.
    Curves with fewer than two usable points are left out.
    """
    log_flops_grid = _log_flops_grid(curves)
    if log_flops_grid is None:
        return None
    smoothed_curves = []
    for curve in curves:
        smoothed = _smoothed_curve(curve, log_flops_grid)
        if smoothed is None:
            continue
        n_params, covered, log_loss, _log_data = smoothed
        smoothed_curves.append(
            (n_params, 10.0 ** log_flops_grid[covered], 10.0**log_loss)
        )
    return smoothed_curves