Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiprocessing bug on macOS #159

Open
anishathalye opened this issue Apr 2, 2022 · 8 comments
Open

Multiprocessing bug on macOS #159

anishathalye opened this issue Apr 2, 2022 · 8 comments
Labels
bug Something isn't working

Comments

@anishathalye
Copy link
Member

anishathalye commented Apr 2, 2022

macOS 12.1 (on Intel hardware) + Python 3.9.10, cleanlab 3f17be6. Running the code below causes an infinite loop of exceptions.

To reproduce, save this as bug.py and run it:

import numpy as np
from cleanlab.count import compute_confident_joint
from cleanlab.filter import find_label_issues

pred_probs = \
np.array(
[[0.8, 0.2],
 [0.7, 0.3],
 [0.1, 0.9],
 [0.3, 0.7]])
labels = np.array([0, 0, 1, 1])

cj = compute_confident_joint(labels, pred_probs, calibrate=False)
print(f'confident joint: {cj}')

issues = find_label_issues(labels, pred_probs)
print(f'label issues: {issues}')

Output:

confident joint: [[1 0]
 [0 1]]
confident joint: [[1 0]
 [0 1]]
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 125, in _main
    prepare(preparation_data)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 268, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/Users/anish/src/bug.py", line 16, in <module>
    issues = find_label_issues(labels, pred_probs)
  File "/Users/anish/src/cleanlab/cleanlab/filter.py", line 524, in find_label_issues
    with multiprocessing.Pool(
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/context.py", line 119, in Pool
    return Pool(processes, initializer, initargs, maxtasksperchild,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 212, in __init__
    self._repopulate_pool()
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 303, in _repopulate_pool
    return self._repopulate_pool_static(self._ctx, self.Process,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 326, in _repopulate_pool_static
    w.start()
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 121, in start
    self._popen = self._Popen(self)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/context.py", line 284, in _Popen
    return Popen(process_obj)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 32, in __init__
    super().__init__(process_obj)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_fork.py", line 19, in __init__
    self._launch(process_obj)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 42, in _launch
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 134, in _check_not_importing_main
    raise RuntimeError('''
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
confident joint: [[1 0]
 [0 1]]
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 125, in _main
    prepare(preparation_data)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 268, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/Users/anish/src/bug.py", line 16, in <module>
    issues = find_label_issues(labels, pred_probs)
  File "/Users/anish/src/cleanlab/cleanlab/filter.py", line 524, in find_label_issues
    with multiprocessing.Pool(
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/context.py", line 119, in Pool
    return Pool(processes, initializer, initargs, maxtasksperchild,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 212, in __init__
    self._repopulate_pool()
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 303, in _repopulate_pool
    return self._repopulate_pool_static(self._ctx, self.Process,
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/pool.py", line 326, in _repopulate_pool_static
    w.start()
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 121, in start
    self._popen = self._Popen(self)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/context.py", line 284, in _Popen
    return Popen(process_obj)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 32, in __init__
    super().__init__(process_obj)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_fork.py", line 19, in __init__
    self._launch(process_obj)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 42, in _launch
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 134, in _check_not_importing_main
    raise RuntimeError('''
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
...

On a different platform (Debian 10, Linux 4.19.0-11-amd64, Python 3.7.3), this bug does not occur, and running the code produces the expected output:

confident joint: [[1 0]
 [0 1]]
label issues: [False False False False]

The user can work around the issue with the following, but we should fix cleanlab so that the above version of the code works.

import numpy as np
from cleanlab.count import compute_confident_joint
from cleanlab.filter import find_label_issues

def main():
    pred_probs = \
    np.array(
    [[0.8, 0.2],
     [0.7, 0.3],
     [0.1, 0.9],
     [0.3, 0.7]])
    labels = np.array([0, 0, 1, 1])

    cj = compute_confident_joint(labels, pred_probs, calibrate=False)
    print(f'confident joint: {cj}')

    issues = find_label_issues(labels, pred_probs)
    print(f'label issues: {issues}')

if __name__ == '__main__':
    main()

This code produces the expected output on macOS.

@anishathalye anishathalye added the bug Something isn't working label Apr 2, 2022
@anishathalye anishathalye self-assigned this Apr 2, 2022
@anishathalye
Copy link
Member Author

Never mind, I thought that the difference in behavior between macOS and Linux meant that we could support even code that avoids the if __name__ == '__main__': main() idiom on all platforms, but I don't think any library that uses multiprocessing attempts to support this. The code works fine with the idiom, and it also works fine in the REPL on macOS, so this is a non-issue.

@anishathalye
Copy link
Member Author

Re-opening this issue because I think we do want to address it in some way.

Issue and root cause

Adding a bit more context and explanation here. Consider the following simple demo program:

import multiprocessing

def inc(x):
    return x + 1

pool = multiprocessing.Pool(2)
print(pool.map(inc, [1, 2, 3, 4]))

Linux

This works on Linux, because multiprocessing on Linux uses the fork() syscall to start a new process. It works this way with both Python 2 and Python 3.

macOS

On macOS, the behavior of this program depends on whether you use Python 2, Python 3.0-3.7, or Python 3.8+. Python 2's multiprocessing and Python 3.0-3.7's multiprocessing uses the fork() syscall, and it works as expected.

Python 3.8+ on macOS uses the "spawn" start method by default. This creates a new process running the Python interpreter, and it imports the module, which is problematic if importing the module has side effects. We can override the default fork method on 3.8+ to make the above example work:

import multiprocessing

def inc(x):
    return x + 1

multiprocessing.set_start_method('fork')
pool = multiprocessing.Pool(2)
print(pool.map(inc, [1, 2, 3, 4]))

Unfortunately, this is considered unsafe and can lead to crashes of the subprocess. The proper fix is to make importing the module side-effect free:

import multiprocessing

def inc(x):
    return x + 1

if __name__ == '__main__':
    pool = multiprocessing.Pool(2)
    print(pool.map(inc, [1, 2, 3, 4]))

Windows

Windows does not have a fork() syscall (it has a CreateProcess() syscall), so the "fork" start method is not available on Windows; even with Python 2, multiprocessing uses "spawn". The Python 2 docs explain restrictions with using multiprocessing on Windows that are a result of this limitation. The fix here is the same as above, making importing the module side-effect-free.

Where does this leave us?

This issue — supporting multiprocessing in this way, where importing the module has side effects — seems unfixable. However, since multiple people have independently run into this problem, maybe we can do something better than just giving up.

If we can detect that importing the module has side effects, perhaps we can give a better error message (and explain how to fix the issue), or perhaps we can disable multiprocessing (so that the user's program still works) and print out a warning that they can get a speedup by fixing the issue.

@anishathalye anishathalye reopened this Jun 28, 2022
@jwmueller
Copy link
Member

When it is None, we could internally set n_jobs = 1 for Windows/Mac as a temporary fix for now?
I imagine this code will anyway change a lot after performance optimization.

@anishathalye
Copy link
Member Author

That seems fine; it also seems okay to leave it as-is (it's been this way for a long time, and other libraries also have this issue).

@cgnorthcutt
Copy link
Member

Agree - also seems ok to leave as is for now.

@anishathalye anishathalye removed their assignment Aug 26, 2022
@jwmueller
Copy link
Member

User reported running into this problem in our Slack community:
https://cleanlab-community.slack.com/archives/C031BGERG3Z/p1673638948598819

@jwmueller
Copy link
Member

Report from another user (Robin) who encountered this issue in PyCharm, but the same code worked in a Jupyter Notebook.

Their problem was solvable in two ways: either set n_jobs=1, or use the solution proposed above to wrap code like this:

def main():
    # your code here

if __name__ == '__main__':
    main()

@tataganesh
Copy link
Contributor

I can reproduce this issue on MacOS Ventura 13.5.2 (Apple M1) with python 3.10.12 when using the Datalab interface for finding issues.

Example -

import numpy as np
from cleanlab import Datalab

features = np.random.random((100, 2))
labels = np.array([0] * 50 + [1] * 50)
pred_probs = features / features.sum(axis=1, keepdims=True)

lab = Datalab(data={"features": features, "y": labels}, label_name="y")
lab.find_issues(features=features, pred_probs=pred_probs)

Output

Finding label issues ...
Finding label issues ...
Finding label issues ...
Finding label issues ...
Finding label issues ...
Finding label issues ...
Finding label issues ...
Finding label issues ...
Finding label issues ...
Error in label: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Finding outlier issues ...
Fitting OOD estimator based on provided features ...
Finding near_duplicate issues ...
Finding non_iid issues ...
Failed to check for these issue types: [LabelIssueManager]

Audit complete. 8 issues found in the dataset.
Finding outlier issues ...
Fitting OOD estimator based on provided features ...
Finding near_duplicate issues ...
Finding non_iid issues ...

Audit complete. 45 issues found in the dataset.

No problems when running on jupyter. @jwmueller's suggestion of wrapping the code works well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants