Skip to content

Investigate SAG/SAGA solver #23180

Open
Open

Description

@lorentzenchr

Description

The newly introduced tight tests for Ridge in #22910 together with the random seed fixture in #22749 revealed some shortcomings of the sag and saga solver, some are already mentioned in #21305:

  1. It shows some random behavior even with fixed random seed.
  2. The tol needs to be set much smaller to receive comparable results with the other solvers of Ridge.
  3. Saga seems more stable on dense data X, and often needs much more iterations on sparse X.
  4. fit_intercept=True seems to converge slower.

Ideally, the cause for both issues can be identified and fixed.

Some links for context

#23014
#23017
#23026
#23152
#23177
#25198

Activity

  1. added
    Needs Triage
    on Apr 21, 2022
  2. added and removed
    Needs Triage
    on Apr 21, 2022
  3. jeremiedbb commented on Apr 21, 2022

    @jeremiedbb
    Member

    It shows some random behavior even with fixed random seed.

    Actually the randomness will probably be fixed by #23181
    It was probably not randomness from the solver but from the CI runs. The fact that when it failed it was always with sag and saga still shows that something is not going as expected.

  4. ogrisel commented on May 9, 2022

    @ogrisel
    Member

    If it can reach the same results with a small values of tol, it does not seem like a bug to me.

    Are there any example where the solvers do not converge to the same solution even with a small tol?

  5. lorentzenchr commented on May 31, 2022

    @lorentzenchr
    MemberAuthor

    The point is that sag/saga often needs orders of magnitude smaller tol. In test_ridge.py it's 1e-15 vs 1e-10. We could (and do) live with that. Maybe there is room to improve on that.

  6. ogrisel commented on Oct 14, 2022

    @ogrisel
    Member

    Coming back to this issue, I think it would be interesting to find a way to normalize the tol criterion between all ridge solvers including sag/saga so that they approximately mean the same thing.

  7. added
    Moderate
    on Oct 14, 2022
  8. glevv commented on Oct 28, 2022

    @glevv
    Contributor

    could this be connected to #24679 ?

  9. TomDLT commented on Nov 22, 2022

    @TomDLT
    Member

    could this be connected to #24679 ?

    No. The linked issue is a potential mistake on the prox operator in SAGA. However, the prox operator is not used in Ridge, because the prox operator is only used for L1 regularization. Therefore, this potential mistake should not affect Ridge convergence.

    edit: #24679 was not a mistake.

  10. lorentzenchr commented on Oct 7, 2023

    @lorentzenchr
    MemberAuthor

    Maybe it's related to the scaling of the objective similar to #24752?

  11. moved this to Discussion in Losses and solverson May 17, 2024
  12. mariam851 commented on Dec 25, 2025

    @mariam851

    I'm interested in investigating this issue. I'll start by looking into why SAG/SAGA requires a much smaller tol in test_ridge.py.

  13. ogrisel commented on Feb 9, 2026

    @ogrisel
    Member

    Possibly related (convergence problems when fitting with sample_weight != None): #31536.

  14. glevv commented on Nov 12, 2026

    @glevv
    Contributor

    Yep, I guess that's just how these solvers work.
    TL;DR: the stopping criterion of SAG and SAGA (tol) measures how much the coefficients changed over the last epoch, not how far they are from the solution. Some inputs will easily show this discrepancy, but for others it doesn't really matter. The only 'fix' (if it is even possible to call it that) is to rewrite the stopping criteria algorithm.

    AI Ahead

    sag and saga stop when the largest coefficient change over one pass through the data, divided by the largest coefficient, drops below tol. That measures how fast the solver is still moving, not how far it is from the solution. When convergence is slow, the per-pass change is small long before the answer is close.

    for idx in range(n_features * n_classes):
    max_weight = fmax{{name_suffix}}(max_weight, fabs(weights[idx]))
    max_change = fmax{{name_suffix}}(max_change, fabs(weights[idx] - previous_weights[idx]))
    previous_weights[idx] = weights[idx]
    if ((max_weight != 0 and max_change / max_weight <= tol)
    or max_weight == 0 and max_change == 0):
    if verbose:
    end_time = time(NULL)
    with gil:
    print("convergence after %d epochs took %d seconds" %
    (n_iter + 1, end_time - start_time))
    break

    Gap grows with how ill-conditioned the data is. sparse_cg and lsqr stop on the residual and didn’t show this once tol was 1e-8 or smaller.
    The solver stops when the change reaches tol, while the answer is still about 250 times further away than tol.
    Small example in Python

    import warnings
    import numpy as np
    from sklearn.linear_model import Ridge
    
    warnings.simplefilter("ignore")  # ConvergenceWarning from the max_iter refit below
    
    # 200 x 10 design matrix with condition number 100
    rng = np.random.RandomState(0)
    n, p, cond = 200, 10, 100
    U, _ = np.linalg.qr(rng.randn(n, p))
    V, _ = np.linalg.qr(rng.randn(p, p))
    X = U @ np.diag(np.logspace(0, -np.log10(cond), p)) @ V.T * np.sqrt(n)
    y = X @ rng.randn(p) + 0.1 * rng.randn(n)
    
    kw = dict(alpha=1e-2, solver="sag", fit_intercept=False, random_state=0)
    exact = Ridge(alpha=1e-2, solver="cholesky", fit_intercept=False).fit(X, y).coef_
    rel = lambda a, b: np.max(np.abs(a - b)) / np.max(np.abs(a))
    
    for tol in (1e-4, 1e-6):
        m = Ridge(tol=tol, max_iter=10**6, **kw).fit(X, y)
        n_iter = int(m.n_iter_[0])
        prev = Ridge(tol=0, max_iter=n_iter - 1, **kw).fit(X, y).coef_  # one epoch earlier
        print(f"tol={tol:g}: epochs={n_iter}, change at stop={rel(m.coef_, prev):.1e}, "
              f"error vs exact={rel(exact, m.coef_):.1e}")`

    As a 'fix' - estimate the remaining error from how fast the per-pass changes are shrinking

    # Number of epochs used to estimate the rate of convergence in the stopping
    # criterion.
    cdef enum:
        RATE_WINDOW = 10
    
    # the relative change of the weights over the last epochs (ring buffer), used
    # to estimate the rate of convergence in the stopping criteria
    
    cdef double[RATE_WINDOW + 1] change_hist
    cdef int n_hist = 0
    cdef int lag
    cdef double change
    cdef double rho
    cdef bint converged
    
    converged = False
    if max_weight == 0:
        converged = max_change == 0
    else:
        change = max_change / max_weight
        if change == 0:
            converged = True
        elif n_iter > 0:
            # The change of the first epoch is not used: it is relative
            # to previous_weights, which is initialized with zeros.
            change_hist[n_hist % (RATE_WINDOW + 1)] = change
            n_hist += 1
            lag = n_hist - 1
            if lag > RATE_WINDOW:
                lag = RATE_WINDOW
            if lag > 0:
                rho = pow(
                    change / change_hist[(n_hist - 1 - lag) % (RATE_WINDOW + 1)],
                    1.0 / lag,
                )
                if rho < 1:
                    converged = change * rho / (1 - rho) <= tol
    if converged:
        ...  # same verbose print and break as before

    This is not tested beyond L2: L1 penalties, sample weights, multiclass, sparse input and fitted intercepts are still untested.

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

    BugModeratehelp wantedmodule:linear_model

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions