Skip to content

Speed up score() for quantile forecasts: reshape once, and compute WIS components and coverage from the quantile matrix #1237

Open

Description

@nickreich

Summary

With the default metrics, scoring quantile forecasts reshapes the data into intervals six times, and spends about as long again preparing the inputs. On the example below (120k forecasts, 23 quantile levels), score() takes about 20 s:

  • About 7 s is score.forecast_quantile() collapsing each forecast to one row with list columns. It orders and toString()s the quantile levels within every group of by = forecast_unit. One setorderv() plus matrix(..., byrow = TRUE) builds the same observed vector and predicted matrix in 0.15 s, when every forecast has the same quantile levels. That is the common case, and it can be checked cheaply; otherwise fall back to the current path.
  • About 10 s is the metric functions themselves, almost all of it reshaping rather than arithmetic:
    • wis(), overprediction_quantile(), underprediction_quantile() and dispersion_quantile() each call wis(), which calls quantile_to_interval() (a dcast), so the same reshape is built 4 times.
    • interval_coverage() reshapes again for each interval range.
    • bias_quantile() loops over forecasts with sapply().
  • About 2 s is validation.

When weigh = TRUE (the default), WIS is the mean of the quantile scores, as noted in the docs since #1202. Its components and the interval coverages can be read straight off the predicted matrix, by matching lower/upper quantile columns. Matrix versions of wis, dispersion, overprediction, underprediction and both coverages take 0.08 s, against about 8 s, and agree with score() to within about 1e-12.

For context, this is in the scoring path of hubverse evaluation dashboards (hubEvals / hubPredEvalsData). There score() runs on several million quantile rows per evaluation set, and the builds take hours.

Reproducible example

reprex
library(scoringutils)
library(data.table)
#> 
#> Attaching package: 'data.table'
#> The following object is masked from 'package:base':
#> 
#>     %notin%

# Simulated quantile forecasts: 120,000 forecasts with 23 quantile levels each (same generator as the first example)
make_forecasts <- function(n_models = 20, n_locations = 50, n_dates = 30, n_horizons = 4) {
  set.seed(1)
  q <- c(0.01, 0.025, seq(0.05, 0.95, by = 0.05), 0.975, 0.99)
  units <- CJ(model = paste0("m", seq_len(n_models)), location = sprintf("%02d", seq_len(n_locations)),
              date = seq_len(n_dates), horizon = seq_len(n_horizons) - 1L)
  units[, `:=`(mu = exp(rnorm(.N, 4, 1)), observed = rpois(.N, 60))]
  dt <- units[, .(quantile_level = q), by = names(units)]
  dt[, predicted := pmax(0, qnorm(quantile_level, mu, mu / 3))][, mu := NULL]
  dt[]
}
fc <- as_forecast_quantile(make_forecasts())

# score() with the default metrics
metrics <- get_metrics(fc)
names(metrics)
#> [1] "wis"                  "overprediction"       "underprediction"     
#> [4] "dispersion"           "bias"                 "interval_coverage_50"
#> [7] "interval_coverage_90" "ae_median"
system.time(scores <- score(fc, metrics))
#>    user  system elapsed 
#>  27.946   1.140  20.373

# Before calling the metrics, score.forecast_quantile() collapses each forecast to one row with list columns,
# ordering within every group and building a string key of its quantile levels:
forecast_unit <- get_forecast_unit(fc)
system.time(
  as.data.table(fc)[, .(predicted = list(predicted[order(quantile_level)]), observed = unique(observed),
                        quantile_level = list(sort(quantile_level, na.last = TRUE)),
                        scoringutils_quantile_level = toString(sort(quantile_level, na.last = TRUE))),
                    by = forecast_unit]
)
#>    user  system elapsed 
#>   6.707   0.064   6.866
# One sort and a reshape give the same observed vector and predicted matrix (one row per forecast) that the
# metrics receive (after checking that every forecast has the same quantile levels)
system.time({
  dt <- setorderv(as.data.table(fc), c(forecast_unit, "quantile_level"))
  quantile_level <- sort(unique(dt$quantile_level))
  stopifnot(dt[, .N, by = forecast_unit][, all(N == length(quantile_level))],
            all(dt$quantile_level == quantile_level))
  predicted <- matrix(dt$predicted, ncol = length(quantile_level), byrow = TRUE)
  observed <- dt$observed[seq(1, nrow(dt), by = length(quantile_level))]
})
#>    user  system elapsed 
#>   0.264   0.025   0.153

# Time per metric: the four WIS components each call wis(), which reshapes into intervals with
# quantile_to_interval() (a dcast); each coverage level reshapes again; bias loops over forecasts with sapply()
sapply(metrics, function(f) system.time(f(observed, predicted, quantile_level))[["elapsed"]])
#>                  wis       overprediction      underprediction 
#>                1.575                1.424                1.307 
#>           dispersion                 bias interval_coverage_50 
#>                1.298                2.154                1.157 
#> interval_coverage_90            ae_median 
#>                1.183                0.001

# Matrix versions. With weigh = TRUE (the default), WIS is the mean of the quantile scores, and its components
# can be read off the matched lower/upper quantile columns without building intervals.
wis_components <- function(observed, predicted, quantile_level) {
  lower <- which(quantile_level < 0.5)
  upper <- match(round(1 - quantile_level[lower], 10), round(quantile_level, 10))
  med <- predicted[, quantile_level == 0.5]
  alpha <- 2 * quantile_level[lower]
  denom <- length(lower) + 0.5                      # intervals have weight 1, the median 0.5
  list(
    wis = rowMeans(2 * sweep((observed <= predicted) * 1, 2, quantile_level) * (predicted - observed)),
    dispersion = drop((predicted[, upper] - predicted[, lower]) %*% (alpha / 2)) / denom,
    overprediction = (rowSums(pmax(predicted[, lower] - observed, 0)) + 0.5 * pmax(med - observed, 0)) / denom,
    underprediction = (rowSums(pmax(observed - predicted[, upper], 0)) + 0.5 * pmax(observed - med, 0)) / denom
  )
}
coverage_fast <- function(observed, predicted, quantile_level, interval_range) {
  l <- match(round((100 - interval_range) / 200, 10), round(quantile_level, 10))
  u <- match(round(1 - (100 - interval_range) / 200, 10), round(quantile_level, 10))
  observed >= predicted[, l] & observed <= predicted[, u]
}
system.time({
  fast <- wis_components(observed, predicted, quantile_level)
  fast$interval_coverage_50 <- coverage_fast(observed, predicted, quantile_level, 50)
  fast$interval_coverage_90 <- coverage_fast(observed, predicted, quantile_level, 90)
})
#>    user  system elapsed 
#>   0.072   0.009   0.082

# Identical to scoringutils
ref <- setorderv(as.data.table(scores), forecast_unit)
sapply(names(fast), function(m) max(abs(ref[[m]] - fast[[m]])))
#>                  wis           dispersion       overprediction 
#>         1.136868e-12         5.684342e-14         6.821210e-13 
#>      underprediction interval_coverage_50 interval_coverage_90 
#>         3.552714e-14         0.000000e+00         0.000000e+00
packageVersion("scoringutils")
#> [1] '2.3.0'

Possible approach

In score.forecast_quantile():

  1. Build observed and predicted with one sort and a reshape when all forecasts share the same quantile levels. Fall back to the current split() by quantile-level set otherwise.
  2. Give wis() and the decomposition metrics a matrix path:
    • if weigh = TRUE, count_median_twice = FALSE and separate_results = FALSE, use the quantile-score identity for WIS;
    • otherwise use the lower/upper column match shown above, for the components and for weigh = FALSE.
      This removes quantile_to_interval() from the scoring path, or at least computes it once and shares it between the metrics.
  3. Make interval_coverage() index the two quantile columns it needs instead of reshaping.
  4. Vectorise bias_quantile() over rows of the predicted matrix.

The matrix code above is a sketch: it assumes symmetric intervals and a median, and has no NA handling. It's meant to show the size of the gain, not to be the final code.

Activity

  1. nickreich commented on Nov 10, 2026

    @nickreich
    ContributorAuthor

    We are running into some serious bottlenecks when doing some repeated large-scale scoring jobs, and Claude insists that something like the above would help things take less memory, run faster, and generally be more efficient. Any thoughts about whether this (or something similar) might be on the docket for upcoming work? @seabbs @nikosbosse

  2. seabbs commented on Nov 10, 2026

    @seabbs
    Contributor

    It sounds like the proposal above doesn't fit with the modular patterns of scoring utils as written. I believe the repeats are happening however.

    As a first pass if you have spare tokens it might be useful to reframe the reprex above around some modifications to scoringutils so we can get a sense of how impactful they would be across the code base or if they are quite minor (which may be the case). This doesn't need to be the internal changes needed but needs to explore thte contract between metrics etc in the package.

  3. nikosbosse commented on Nov 10, 2026

    @nikosbosse
    Collaborator

    CLAUDE: I tried this as modifications inside scoringutils rather than a rewrite, see draft PR #1256. Three internal changes take score() on the example above from 12.3s to 2.2s, with identical scores and no change to any metric's signature:

    1. score.forecast_quantile(): build observed and predicted with one sort when all forecasts share the same quantile levels, falling back to the current path otherwise.
    2. quantile_to_interval_numeric(): build the interval table from matrix columns instead of dcast() (0.72s → 0.04s per call; it is called six times with the default metrics).
    3. bias_quantile(): vectorise over forecasts (1.42s → 0.03s).

    So the contract between score() and the metrics can stay as it is. The metrics still each do their own reshape, but it is now cheap enough that sharing it between them is not worth the coupling, and the matrix version of wis() proposed above is not needed. Most of the remaining time is validation (see #1238).

  4. nickreich commented on Nov 11, 2026

    @nickreich
    ContributorAuthor

    Thanks, y'all!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions