--- title: "Numerical stability of fastglm" author: "Jared Huling" date: "2026-11-17" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Numerical stability of fastglm} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- A fitted model is useful only if the reported estimate is the maximum of the likelihood, or the software says that it is not. This vignette describes how *fastglm* makes that distinction for generalized linear models, negative binomial, hurdle, zero-inflated, and ordinal models, and it reports a simulation study that compares *fastglm* with `stats::glm.fit()`, *glm2*, `MASS::glm.nb()`, *pscl*, and *ordinal* on designs where fitting is difficult. # Failure modes of iteratively reweighted least squares Most of these models are fit by iteratively reweighted least squares (IRLS), or by alternating such fits with updates of a dispersion or mixing parameter. Four problems recur. - **Invalid steps.** Many links restrict the linear predictor: a square-root or identity link for Poisson data requires a positive mean, and a log link for binomial data requires probabilities below one. A full IRLS step can leave that region, and the software must shorten or redirect it. - **Maxima on the boundary.** For such links the maximum itself can lie on the boundary of the valid region, for example where a fitted Poisson mean is zero. Halving the whole step every time it leaves the region then stalls the fit short of the maximum. - **Flat likelihoods.** When the likelihood changes little in some direction, as it does in the dispersion parameter of a nearly Poisson negative binomial model, a rule based on the change in the coefficients or in the log likelihood can fail to stop, or can stop early. - **False convergence.** If a step is shortened to nothing, the change between iterations is small wherever the fit stopped, and a rule based on that change reports convergence away from the maximum. The first two are easy to see in a Poisson model with an identity link whose fitted mean reaches zero for some covariate values. ``` r set.seed(1) n <- 1000 x1 <- runif(n); x2 <- runif(n) y <- rpois(n, pmax(0.3 + 2 * x1 - 1.6 * x2, 0.03)) X <- cbind(1, x1, x2) tryCatch(glm.fit(X, y, family = poisson("identity")), error = conditionMessage) #> Warning in log(y/mu): NaNs produced #> [1] "no valid set of coefficients has been found: please supply starting values" fit <- fastglm(X, y, family = poisson("identity")) #> Warning: fastglm: the estimate is on the boundary of the valid region for this #> family and link (convergence.reason = 'converged_boundary'); Wald standard #> errors and tests are not reliable c(converged = fit$converged, reason = fit$convergence.reason) #> converged reason #> "TRUE" "converged_boundary" ``` `glm.fit()` cannot find a valid starting point, while *fastglm* converges to the maximum, which lies on the boundary, and says so: the warning and `convergence.reason = "converged_boundary"` indicate that Wald standard errors do not have their usual justification for this estimate. # Convergence checks and step safeguards in fastglm *fastglm* reports convergence only when one more step is predicted to change the deviance negligibly (the Fisher or Newton decrement is below `tol` relative to the deviance), not merely when the last step changed little. Steps that leave the valid region are handled in three ways: 1. An invalid first update from the starting means is halved toward the intercept-only fit, which is valid whenever the mean response is. 2. When a later update leaves the region, the observation that leaves first is held partway to its bound and the step is recomputed for the remaining coefficients, so a fit whose maximum lies on the boundary reaches it. A held observation is released if its Lagrange multiplier shows that moving it back inside would improve the likelihood. 3. A step is used only if it decreases the deviance. Models with an outer loop, such as the negative binomial dispersion or the zero-inflation mixture, use the same rule for the joint parameters, and the negative binomial fit also compares the Poisson limit (`theta = Inf`), where the likelihood can be highest. The reason for stopping is returned with the fit: | `convergence.reason` | Meaning | |---|---| | `"converged"` | the maximum, certified by the decrement | | `"converged_boundary"` | the maximum, on the boundary of the valid region (Wald inference not reliable) | | `"theta_infinite"` | negative binomial: the likelihood is highest in the Poisson limit | | `"theta_boundary"` | zero-inflated negative binomial: the zero-inflated Poisson limit | | `"score_and_predictor_step"` | ordinal models: the maximum, certified by the score and step | | `"iteration_limit"`, `"step_halving_failed"`, `"not_converged"`, `"ordering_boundary"` | not converged; the estimate is not certified as a maximum | # Simulation study of convergence across model classes The designs below were chosen to exercise these problems, and each was simulated 50 times. ``` r designs <- unique(results[, c("design", "model", "label")]) designs <- designs[order(designs$design), ] knitr::kable(data.frame(Design = designs$design, Model = designs$label), row.names = FALSE) ``` |Design |Model | |:------|:------------------------------------------------| |D1 |Poisson regression, identity link, prior weights | |D2 |Poisson regression, square-root link, offset | |D3 |Binomial regression, identity link | |D4 |Log-binomial regression | |D5 |Gamma regression, inverse link (interior) | |D6 |Logistic regression (interior) | |D7 |Negative binomial, square-root link | |D8 |Negative binomial, identity link | |D9 |Negative binomial, log link, near Poisson | |D10 |Negative binomial, log link, theta = 0.03 | |D11 |Hurdle negative binomial, theta = 0.15 | |D12 |Zero-inflated negative binomial, theta = 1.2 | |D13 |Zero-inflated Poisson | |D14 |Partial proportional odds, logit link | |D15 |Partial proportional odds, probit link | Every fit is scored by a criterion computed from its coefficients, not by the value the package reports: minus the deviance for generalized linear models, the log likelihood otherwise, and for the hurdle model the log likelihood of the count part. The reference maximum for each data set is the best of an independent optimizer and all fits: a convex program (CVXR) for the generalized linear models, whose deviances are convex; an active-set constrained optimizer (SLSQP) or BFGS for the negative binomial models, with the Poisson limit as a candidate; BFGS from several starts for the hurdle and zero-inflated models; and a barrier method under the ordering constraints for the ordinal models. No reference was started at a *fastglm* solution. A fit is then - **ok** if it is reported as converged and is within 1e-6 (relative) of the reference maximum; - a **false convergence** if it is reported as converged and is further below; - **not converged** if it is not reported as converged; - an **error** if it stops with an error. ``` r methods <- c(fastglm_dense = "fastglm", fastglm_sparse = "fastglm (sparse)", fastglm_stream = "fastglm (streamed)", glm.fit = "glm.fit", glm2 = "glm2", glm.nb = "MASS::glm.nb", hurdle = "pscl::hurdle", zeroinfl = "pscl::zeroinfl", clm = "ordinal::clm") classes <- c("ok", "false convergence", "not converged", "error") results$Method <- factor(methods[results$method], levels = methods) results$Class <- factor(results$class, levels = classes) # One row per design and method, one column per outcome class; the design is # printed only on its first row. summary_table <- function(model) { z <- results[results$model %in% model, ] out <- do.call(rbind, lapply(split(z, list(z$design, z$Method), drop = TRUE), function(r) data.frame(Design = r$design[1], Method = as.character(r$Method[1]), t(as.vector(table(r$Class))), check.names = FALSE))) out <- out[order(out$Design, factor(out$Method, levels = methods)), ] out$Design <- as.character(out$Design) out$Design[duplicated(out$Design)] <- "" knitr::kable(out, row.names = FALSE, align = "llrrrr", col.names = c("Design", "Method", "ok", "false convergence", "not converged", "error")) } # One palette for every figure: fastglm variants share the dominant colour and # differ by shape; comparison packages use recessive greys and blues. method_colour <- c("fastglm" = "#C0392B", "fastglm (sparse)" = "#C0392B", "fastglm (streamed)" = "#C0392B", "glm.fit" = "#4A4A4A", "glm2" = "#8C8C8C", "MASS::glm.nb" = "#2E86C1", "pscl::hurdle" = "#5DADE2", "pscl::zeroinfl" = "#5DADE2", "ordinal::clm" = "#1F618D") method_shape <- c("fastglm" = 16, "fastglm (sparse)" = 17, "fastglm (streamed)" = 15, "glm.fit" = 4, "glm2" = 3, "MASS::glm.nb" = 1, "pscl::hurdle" = 2, "pscl::zeroinfl" = 2, "ordinal::clm" = 0) # One panel per design and one row per method, so that no two methods share a # position; a line from zero to each count makes the comparison by length. plot_ok <- function(model, ncol = 2L) { z <- results[results$model %in% model, ] ok <- aggregate(cbind(ok = class == "ok") ~ design + label + Method, data = z, FUN = sum) ok$Method <- factor(ok$Method, levels = rev(levels(droplevels(ok$Method)))) ok <- ok[order(ok$design), ] ok$panel <- factor(paste0(ok$design, ": ", ok$label), levels = unique(paste0(ok$design, ": ", ok$label))) ggplot(ok, aes(ok, Method, colour = Method, shape = Method)) + geom_segment(aes(x = 0, xend = ok, yend = Method), linewidth = 0.5, alpha = 0.5) + geom_point(size = 2.4) + facet_wrap(~ panel, ncol = ncol, scales = "free_y", labeller = label_wrap_gen(width = if (ncol > 2L) 26 else 40)) + scale_x_continuous(limits = c(0, 50), breaks = seq(0, 50, 10), expand = expansion(add = 1.5)) + scale_colour_manual(values = method_colour) + scale_shape_manual(values = method_shape) + labs(x = "fits at the maximum (of 50 data sets)", y = NULL) + theme_bw(base_size = 10) + theme(legend.position = "none", panel.grid.minor = element_blank(), panel.grid.major.y = element_blank(), strip.background = element_rect(fill = "grey95"), strip.text = element_text(hjust = 0)) } ``` ## Generalized linear models Designs D1 to D4 have maxima on the boundary of the valid region (identity and square-root links for Poisson data, identity and log links for binomial data); D5 and D6 are interior controls. *fastglm* was fit with a dense design, a sparse (`dgCMatrix`) design, and in four chunks with `fastglm_streaming()`. ``` r summary_table("glm") ``` |Design |Method | ok| false convergence| not converged| error| |:------|:------------------|--:|-----------------:|-------------:|-----:| |D1 |fastglm | 49| 0| 1| 0| | |fastglm (sparse) | 49| 0| 1| 0| | |fastglm (streamed) | 49| 0| 1| 0| | |glm.fit | 0| 0| 0| 50| | |glm2 | 0| 0| 0| 50| |D2 |fastglm | 50| 0| 0| 0| | |fastglm (sparse) | 50| 0| 0| 0| | |fastglm (streamed) | 50| 0| 0| 0| | |glm.fit | 0| 0| 0| 50| | |glm2 | 0| 0| 0| 50| |D3 |fastglm | 49| 0| 1| 0| | |fastglm (sparse) | 49| 0| 1| 0| | |fastglm (streamed) | 49| 0| 1| 0| | |glm.fit | 0| 0| 0| 50| | |glm2 | 0| 0| 0| 50| |D4 |fastglm | 50| 0| 0| 0| | |fastglm (sparse) | 50| 0| 0| 0| | |fastglm (streamed) | 50| 0| 0| 0| | |glm.fit | 0| 0| 0| 50| | |glm2 | 0| 0| 0| 50| |D5 |fastglm | 50| 0| 0| 0| | |fastglm (sparse) | 50| 0| 0| 0| | |fastglm (streamed) | 50| 0| 0| 0| | |glm.fit | 50| 0| 0| 0| | |glm2 | 50| 0| 0| 0| |D6 |fastglm | 50| 0| 0| 0| | |fastglm (sparse) | 50| 0| 0| 0| | |fastglm (streamed) | 50| 0| 0| 0| | |glm.fit | 50| 0| 0| 0| | |glm2 | 50| 0| 0| 0| ``` r plot_ok("glm") ```
plot of chunk glm-plot
plot of chunk nb-plot
plot of chunk count-plot
plot of chunk ordinal-plot
plot of chunk nb12-plot