Skip to content

LDA with Loky backend uses the same set of "randomly" chosen docs in each iteration, undermining randomness #35566

Backlog

Description

@itamarst

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.

Introduce yourself

Working on free-threading as part of Probabl+Quansight NASA contract, but encountered this Loky bug.

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

  • LDA does a series of iterations.
  • In each iteration (_e_step()) it calls _update_doc_distribution() with a RandomState instance, with these calls being either sequentially or in parallel. _update_doc_distribution() uses this RandomState to choose some values.
    • If sequential, the RandomState changes over time so different iterations pick different values.
    • If parallel with Loky backend, the RandomState is picked on each call, and so each iteration picks the exact same values.

If this is fine, this could be a potential optimization for Loky. If this is not fine, it should be fixed.

Steps/Code to Reproduce

I forced Loky as backend, setting n_jobs to 2, and added some debug prints in _update_doc_distribution:

def _update_doc_distribution(...):
    # ...
    if random_state:
        doc_topic_distr = random_state.gamma(100.0, 0.01, (n_samples, n_topics)).astype(
            X.dtype, copy=False
        )
        from joblib import hash
        import os
        print("Randomly chosen data's hash:", hash(doc_topic_distr), "in worker", os.getpid())
    else:
        doc_topic_distr = np.ones((n_samples, n_topics), dtype=X.dtype)
    # ...

Expected Results

Different iterations should have different randomly selected data, as is the case in sequential execution.

Actual Results

Same data is selected each time:

Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314105
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314104
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314105
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314105
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314104
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314104
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314105
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314104
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314105
Randomly chosen data's hash: 64a2b8d0e0e57f9261ba009bc899e60f in worker 314104

Versions

System:                           
    python: 3.14.6 free-threading build (main, Jul 23 2026, 14:45:09) [Clang 22.1.3 ]                                                                                        executable: /home/itamarst/devel/scikit-learn/venv314t/bin/python
   machine: Linux-7.2.6-76070206-generic-x86_64-with-glibc2.43
                                           
Python dependencies:
      sklearn: 1.10.dev0
          pip: 26.2.1  
   setuptools: 84.0.0
        numpy: 2.5.3    
        scipy: 1.18.1                                                                 
       Cython: 3.3.0 
       pandas: 3.0.6
   matplotlib: 3.11.2
       joblib: 1.6.0
threadpoolctl: 3.7.0
     narwhals: 2.26.0

Interest in fixing the bug

I can fix it, yes.

Activity

  1. added
    Needs Triage
    on Nov 30, 2026
  2. changed the title [-]LDA with Loky backend uses the same set of docs in each iteration, undermining randomness[/-] [+]LDA with Loky backend uses the same set of "randomly" chosen docs in each iteration, undermining randomness[/+] on Nov 30, 2026
  3. itamarst commented on Nov 30, 2026

    @itamarst
    ContributorAuthor

    A potential fix is would look something like this:

    # In LatentDirechletAllocation._e_step():
    
            def advance(rand):
                if rand is not None:
                    # Advance RandomState:
                    rand.bytes(1)
                return rand
    
            results = parallel(
                delayed(_update_doc_distribution)(
                    X[idx_slice, :],
                    self.exp_dirichlet_component_,
                    self.doc_topic_prior_,
                    self.max_doc_update_iter,
                    self.mean_change_tol,
                    cal_sstats,
                    advance(random_state),
                )
                for idx_slice in gen_even_slices(X.shape[0], n_jobs)
            )

    It could be once per _e_step(), rather than once per parallel task, if it's OK or desirable for different parallel tasks to have the same document distribution (in which case maybe random number usage should happen once, in _e_step, not in _update_doc_distribution).

  4. itamarst commented on Nov 30, 2026

    @itamarst
    ContributorAuthor

    I may end up fixing this in #35524 once I have some guidance.

  5. ogrisel commented on Nov 30, 2026

    @ogrisel
    Member

    The sequential behavior is very likely the correct algorithm and we need to manage the RNG state to behave consistently for both process-based and thread-based parallelism.

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