Skip to content

LinearSVC crammer_singer reports a garbage n_iter_ #34029

Closed

Description

@Fazel94

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

TL;DR LinearSVC(multi_class="crammer_singer") with ≥3 classes returns a
garbage n_iter_ and raises a spurious ConvergenceWarning on nearly every fit
(even at max_iter=10_000_000). The Crammer–Singer solver is a single joint
optimization over all classes
, so it inherently has exactly one iteration
count — unlike the one-vs-rest path, which trains nr_class independent binary
solvers and genuinely has one n_iter per class. The bug is that the readout
machinery treats CS as if it were OvR with per-class counts: in
sklearn/svm/src/liblinear/linear.cpp, train() correctly allocates one
int for model_->n_iter in the MCSVM_CS branch, but get_n_iter() copies
nr_class slots — it guards the binary case (nr_class == 2) but not
MCSVM_CS, so slots [1..K-1] are out-of-bounds heap reads (non-deterministic
across processes). _fit_liblinear then warns off max(n_iter_).

One-line fix:
treat MCSVM_CS as a single slot in get_n_iter().

Describe the bug and give evidence about its user-facing impact

For LinearSVC(multi_class="crammer_singer") with three or more classes,
clf.n_iter_ does not report the number of iterations the Crammer–Singer solver
actually ran. It reports a large, run-to-run unstable integer drawn from
out-of-bounds reads of the LIBLINEAR heap. As a downstream consequence,
_fit_liblinear then compares this garbage value against max_iter and emits
ConvergenceWarning on essentially every fit — including fits where the solver
converged in a few thousand epochs and max_iter is set to 10_000_000.

User-facing impact:

  • clf.n_iter_ is not a usable signal for CS. It changes between Python
    processes (ASLR re-rolls the heap layout on each execve), so any code that
    inspects it — hyper-parameter search summaries, learning-curve diagnostics,
    user-written convergence checks — sees noise.

  • Because the garbage almost always exceeds max_iter, ConvergenceWarning
    fires on every CS fit with K ≥ 3, even when the solver has converged. The
    recommended remedy (raising max_iter) doesn't help.

  • Every a few times even 10_000_000 max_iter raises convergence warning.

Steps/Code to Reproduce

import warnings
from sklearn.datasets import load_digits
from sklearn.svm import LinearSVC
from sklearn.exceptions import ConvergenceWarning

X, y = load_digits(return_X_y=True)   # K=10 classes; any K>=3 triggers the bug

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always", ConvergenceWarning)
    clf = LinearSVC(
        multi_class="crammer_singer",
        max_iter=10_000_000,   # absurdly large — bug still fires
        random_state=0,
        dual=True,
    ).fit(X, y)
    warn_fired = any(
        issubclass(w.category, ConvergenceWarning) for w in caught
    )

print("clf.n_iter_      :", clf.n_iter_)
print("ConvergenceWarn? :", warn_fired)

On my machine it fires 3 out of 10 times which is obviously absurd.

Mechanism — three cooperating defects:

  1. Allocation site (sklearn/svm/src/liblinear/linear.cpp): train()
    allocates exactly one int for model_->n_iter in the MCSVM_CS branch
    and writes only slot [0]:

    model_->n_iter = Malloc(int, 1);
    // ...
    model_->n_iter[0] = Solver.Solve(model_->w);
  2. Out-of-bounds read : get_n_iter() copies
    nr_class slots into the caller's buffer. There is a special case for
    nr_class == 2 (the binary path, which also allocates one slot), but no
    case for MCSVM_CS:

    void get_n_iter(const model *model_, int* n_iter)
    {
        int labels = model_->nr_class;
        if (labels == 2)      // binary special-cased correctly...
            labels = 1;
                              // ...but MCSVM_CS with K>=3 still loops K times
        if (model_->n_iter != NULL)
            for (int i = 0; i < labels; i++)
                n_iter[i] = model_->n_iter[i];   // slots [1..K-1] are OOB reads
    }
  3. Warning fired off the wrong value (sklearn/svm/_base.py):

    n_iter_max = max(n_iter_)   # dominated by heap garbage in slots [1..K-1]
    if n_iter_max >= max_iter:
        warnings.warn("Liblinear failed to converge, ...")

    LinearSVC._classes.py then stores self.n_iter_ = n_iter_.max().item(),
    exposing the same garbage value to the user as a scalar int.

Expected Results

clf.n_iter_ is a small positive integer reflecting the number of CS epochs
actually run (a few thousand on this dataset), and ConvergenceWarning is not
raised because the solver converged well within max_iter.

Actual Results

clf.n_iter_ is a large integer that has no relation to the number of epochs the
solver ran, and changes between Python processes. Example output on Linux x86_64
/ glibc:

clf.n_iter_      : 856261606
ConvergenceWarn? : True

The warning text is the standard one:

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.

The internal n_iter_ buffer (the numpy array _fit_liblinear returns before
LinearSVC.fit collapses it to a scalar via .max().item()) shows what is
actually happening:

slot 0 (real epoch count) : 8401       ← solver converged; well below max_iter=10_000_000
slots 1..9 (garbage)      : [25114, 0, 0, -244463840, 232920324, 1249, 0, 2, 0]
max(n_iter_)              : 232920324  ← heap contents reinterpreted as int32; this is what becomes clf.n_iter_

Versions

System:
    python: 3.12.2 | packaged by conda-forge | (main, Feb 16 2024, 20:50:58) [GCC 12.3.0]
executable: ...
   machine: Linux-6.8.0-111-generic-x86_64-with-glibc2.35

Python dependencies:
      sklearn: 1.9.dev0
          pip: 26.0.1
   setuptools: None
        numpy: 2.4.4
        scipy: 1.17.1
       Cython: 3.2.4
       pandas: 3.0.2
   matplotlib: 3.10.9
       joblib: 1.5.3
threadpoolctl: 3.6.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 4
         prefix: libscipy_openblas
       filepath: ...
        version: 0.3.31.188.0
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 4
         prefix: libscipy_openblas
       filepath: ...
        version: 0.3.30
threading_layer: pthreads
   architecture: Haswell

       user_api: openmp
   internal_api: openmp
    num_threads: 4
         prefix: libgomp
       filepath: ...
        version: None

Interest in fixing the bug

Yes, I do.

Activity

  1. added
    Needs Triage
    on May 16, 2026
  2. beanscg commented on Jun 9, 2026

    @beanscg

    I did a source pass on current main, and I think the narrow regression target is _fit_liblinear, not LinearSVC parameter validation.

    Current path I checked:

    • _get_liblinear_solver_type(..., multi_class="crammer_singer") returns solver type 4.
    • _fit_liblinear forwards that solver type into liblinear.train_wrap.
    • Immediately after, _fit_liblinear computes n_iter_max = max(n_iter_) and uses it to emit ConvergenceWarning when n_iter_max >= max_iter.

    So if the Crammer-Singer train_wrap result contains an uninitialized or otherwise invalid n_iter_ value, both public surfaces fail together: clf.n_iter_ is garbage and the convergence warning becomes a false positive.

    The regression shape I would add after triage is:

    • fit a small 3-class LinearSVC(multi_class="crammer_singer", max_iter=10_000_000) case,
    • assert n_iter_ is stable and bounded by max_iter,
    • assert no ConvergenceWarning is emitted for the converged fixture.

    That would pin the bug at the Python/liblinear return boundary while leaving the eventual fix open.

  3. AhmedKhan-GH commented on Jul 6, 2026

    @AhmedKhan-GH

    I would like to work on this issue!

  4. Fazel94 commented on Jul 6, 2026

    @Fazel94
    ContributorAuthor

    @AhmedKhan-GH The issue is still in "Needs Triage" stage, and PRs right now would almost automatically close.
    We have to wait for the maintainers to review this, in the case it is triaged as a bug then fixing it would be possible.

  5. lorentzenchr commented on Jul 16, 2026

    @lorentzenchr
    Member

    @Fazel94 Can you check if the issue is fixed on current main branch?

  6. Fazel94 commented on Jul 16, 2026

    @Fazel94
    ContributorAuthor

    @lorentzenchr it is indeed fixed.

  7. lorentzenchr commented on Jul 16, 2026

    @lorentzenchr
    Member

    Thanks for checking.

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

    BugNeeds Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions