Skip to content

joblib breaks automatic memory mapping with large arrays: multiprocessing pool self.value out of range for 'i' format code #3313

Closed

Description

@laszlosandor

This reproduces a question from StackOverflow.

The following code runs fine with smaller test samples, like 10^5 for n_samples. At least for the number below (10^6), the run breaks with the ensuing output. This is reproducible on 64-bit Windows Server 2012, with Python 2.7.7 from Anaconda 2.0.1, and I put the pool.py from Anaconda's multiprocessing package and parallel.py from scikit-learn's external package on my Dropbox for reference. All packages are the highest version numbers compatible with Py2k from repo.continuum.io/pkgs/{free|pro}/win-64/, I could not use conda to install a consistent install base.

The test script is:

import numpy as np
import sklearn
from sklearn.linear_model import SGDClassifier
from sklearn import grid_search
import multiprocessing as mp


def main():
    print("Started.")

    print("numpy:", np.__version__)
    print("sklearn:", sklearn.__version__)

    n_samples = 1000000
    n_features = 1000

    X_train = np.random.randn(n_samples, n_features)
    y_train = np.random.randint(0, 2, size=n_samples)

    print("input data size: %.3fMB" % (X_train.nbytes / 1e6))

    model = SGDClassifier(penalty='elasticnet', n_iter=10, shuffle=True)
    param_grid = [{
        'alpha' : 10.0 ** -np.arange(1,7),
        'l1_ratio': [.05, .15, .5, .7, .9, .95, .99, 1],
    }]
    gs = grid_search.GridSearchCV(model, param_grid, n_jobs=8, verbose=100)
    gs.fit(X_train, y_train)
    print(gs.grid_scores_)

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

This results in the output:

Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Started.
('numpy:', '1.8.1')
('sklearn:', '0.15.0b1')
input data size: 8000.000MB
Fitting 3 folds for each of 48 candidates, totalling 144 fits
Memmaping (shape=(1000000L, 1000L), dtype=float64) to new file c:\users\laszlos\appdata\local\temp\4\joblib_memmaping_pool_6172_78765976\6172-284752304-75223296-0.pkl
Failed to save <type 'numpy.ndarray'> to .npy file:
Traceback (most recent call last):
  File "C:\Anaconda\lib\site-packages\sklearn\externals\joblib\numpy_pickle.py", line 240, in save
    obj, filename = self._write_array(obj, filename)
  File "C:\Anaconda\lib\site-packages\sklearn\externals\joblib\numpy_pickle.py", line 203, in _write_array
    self.np.save(filename, array)
  File "C:\Anaconda\lib\site-packages\numpy\lib\npyio.py", line 453, in save
    format.write_array(fid, arr)
  File "C:\Anaconda\lib\site-packages\numpy\lib\format.py", line 406, in write_array
    array.tofile(fp)
ValueError: 1000000000 requested and 268435456 written

Memmaping (shape=(1000000L, 1000L), dtype=float64) to old file c:\users\laszlos\appdata\local\temp\4\joblib_memmaping_pool_6172_78765976\6172-284752304-75223296-0.pkl
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Vendor:  Continuum Analytics, Inc.
Package: mkl
Message: trial mode expires in 28 days
Traceback (most recent call last):
  File "S:\laszlo\gridsearch_largearray.py", line 33, in <module>
    main()
  File "S:\laszlo\gridsearch_largearray.py", line 28, in main
    gs.fit(X_train, y_train)
  File "C:\Anaconda\lib\site-packages\sklearn\grid_search.py", line 597, in fit
    return self._fit(X, y, ParameterGrid(self.param_grid))
  File "C:\Anaconda\lib\site-packages\sklearn\grid_search.py", line 379, in _fit
    for parameters in parameter_iterable
  File "C:\Anaconda\lib\site-packages\sklearn\externals\joblib\parallel.py", line 651, in __call__
    self.retrieve()
  File "C:\Anaconda\lib\site-packages\sklearn\externals\joblib\parallel.py", line 503, in retrieve
    self._output.append(job.get())
  File "C:\Anaconda\lib\multiprocessing\pool.py", line 558, in get
    raise self._value
struct.error: integer out of range for 'i' format code

Activity

  1. changed the title [-]with large arrays, multiprocessing pool self.value out of range for 'i' format code[/-] [+]joblib breaks automatic memory mapping with large arrays: multiprocessing pool self.value out of range for 'i' format code[/+] on Jun 26, 2014
  2. ogrisel commented on Jun 26, 2014

    @ogrisel
    Member

    Are you running anaconda 32bit or 64bit? With 32bit python under windows you are limited to 2GB per Python process and you get really weird error message when memory breaks. Please retry with 64bit Python.

  3. laszlosandor commented on Jun 26, 2014

    @laszlosandor
    Author

    I am definitely running 64-bit. At least as I can verify: all my packages
    are from
    repo.continuum.io/pkgs/pro/win-64/
    and
    repo.continuum.io/pkgs/free/win-64/

    I can verify that whenever I see a Python version number, it says 2.7.7
    64-bit…

    Thanks!

    On Thu, Jun 26, 2014 at 5:30 PM, Olivier Grisel [email protected]
    wrote:

    Are you running anaconda 32bit or 64bit? With 32bit python under windows
    you are limited to 2GB per Python process and you get really weird error
    message when memory breaks. Please retry with 64bit Python.

    —
    Reply to this email directly or view it on GitHub
    https://github.com/scikit-learn/scikit-learn/issues/3313#issuecomment-47240777
    .

  4. ogrisel commented on Jun 26, 2014

    @ogrisel
    Member

    Alright I will try to reproduce the same setup tomorrow on a big windows VM.

  5. ogrisel commented on Jun 27, 2014

    @ogrisel
    Member

    Alright I played a bit on a rackspace box with 30GB RAM and Anaconda 64bit. I don't think there is a bug in joblib / memmaping. The problem is that the way the GridSearchCV currently works will trigger too many copies of the data (via the CV folds) for the memmaping to be of any use.

    I think this is a design problem of a our GridSearchCV object which is not suitable for such large training sets.

    As a workaround I would recommend you to try a parameter search tool I wrote on top of IPython.parallel in the pydata/pyrallel github repo. See the included example notebooks as usage examples. This parameter search tool memory maps the precomputed CV folds which makes it much more efficient from a memory usage point of view.

    The same strategy could be workable with joblib / GridSearchCV but that would require a significant refactoring and maybe introduce backward compat issues in terms of public API.

  6. jnothman commented on Jun 27, 2014

    @jnothman
    Member

    Part of the problem is that our CV generators sometimes produce slices
    over the training data, but we always use fancy indexing which necessitates
    a copy. The simplest change would return a slice from safe_mask when
    possible (maybe only when permitted by a flag), which should not result in
    a copy for memmapped data. Do you agree this might help in this case, given
    appropriately-constructed CV portions?

    Copy-minimal slicing in sparse matrices (cross-validation over CSR) would
    also be a nicety, but without changing scipy.sparse, we need to do this
    locally, and incur O(n_samples) memory for rewriting indptr (because
    scipy.sparse requires indptr[0] == 0).

    On 27 June 2014 12:50, Olivier Grisel [email protected] wrote:

    Alright I played a bit on a rackspace box with 30GB RAM and Anaconda
    64bit. I don't think there is a bug in joblib / memmaping. The problem is
    that the way the GridSearchCV currently works will trigger too many copies
    of the data (via the CV folds) for the memmaping to be of any use.

    I think this is a design problem of a our GridSearchCV object which is not
    suitable for such large training sets.

    As a workaround I would recommend you to try a parameter search tool I
    wrote on top of IPython.parallel in the pydata/pyrallel
    https://github.com/pydata/pyrallel github repo. See the included
    example notebooks as usage examples. This parameter search tool memory maps
    the precomputed CV folds which makes it much more efficient from a memory
    usage point of view.

    The same strategy could be workable with joblib / GridSearchCV but that
    would require a significant refactoring and maybe introduce backward compat
    issues in terms of public API.

    —
    Reply to this email directly or view it on GitHub
    https://github.com/scikit-learn/scikit-learn/issues/3313#issuecomment-47373219
    .

  7. GaelVaroquaux commented on Jun 28, 2014

    @GaelVaroquaux
    Member

    I think this is a design problem of a our GridSearchCV object which is not
    suitable for such large training sets.

    The way to address these issues is to have a transformer that takes
    hashes or indices of the samples, and loads the corresponding data. This
    pattern enables to work on very large datasets.

  8. laszlosandor commented on Jun 28, 2014

    @laszlosandor
    Author

    You mean this is already easy, or you mean this should be the way forward?

    On Sat, Jun 28, 2014 at 1:36 PM, Gael Varoquaux [email protected]
    wrote:

    I think this is a design problem of a our GridSearchCV object which is not
    suitable for such large training sets.
    The way to address these issues is to have a transformer that takes
    hashes or indices of the samples, and loads the corresponding data. This

    pattern enables to work on very large datasets.

    Reply to this email directly or view it on GitHub:
    https://github.com/scikit-learn/scikit-learn/issues/3313#issuecomment-47425172

  9. GaelVaroquaux commented on Jun 28, 2014

    @GaelVaroquaux
    Member

    You mean this is already easy, or you mean this should be the way forward?

    You need to write your own transformer and persistence model. So it is
    application-specific and requires some coding. But I don't think that big
    datasets can be tackled in a generic way.

  10. ogrisel commented on Jun 30, 2014

    @ogrisel
    Member

    2014-06-27 19:00 GMT+02:00 jnothman [email protected]:

    Part of the problem is that our CV generators sometimes produce slices
    over the training data, but we always use fancy indexing which
    necessitates
    a copy. The simplest change would return a slice from safe_mask when
    possible (maybe only when permitted by a flag), which should not result in
    a copy for memmapped data. Do you agree this might help in this case,
    given
    appropriately-constructed CV portions?

    The only CV scheme that produces slices is non-stratified KFold. It's the
    exception rather than the rule.

    A better solution would be to precompute the CV folds in the master process
    and dump them on the hard drive for memory mapping in the worker processes.
    But even this is a

    For really large datasets the only solution is to make sure that all the
    steps in your pipeline support out-of-core estimation and execute multiple
    passes over your data, one for each non-stateless layer in your pipeline.
    But this is a lot of work to implement and would only work for estimators
    that have a partial_fit method.

    Olivier
    http://twitter.com/ogrisel - http://github.com/ogrisel

  11. GaelVaroquaux commented on Jun 30, 2014

    @GaelVaroquaux
    Member

    A better solution would be to precompute the CV folds in the master process
    and dump them on the hard drive for memory mapping in the worker processes.

    One pattern that would work is to pass in the subroutine the indices of
    the train and the full data, rather than the train data. This is a
    pattern we are starting to use heavily in our internal code at parietal.
    As far as I can tell, it requires only refactoring internal code, and
    therefore it might be an option for scikit-learn.

  12. ogrisel commented on Jun 30, 2014

    @ogrisel
    Member

    I ran more tests with large-ish data inputs (couple of GB of data) under Windows and I think I found the cause of problem reported by @laszlosandor: currently joblib.Parallel memory maps input data with mmap_mode='c' by default: this copy-on-write setting seems to cause windows to exhaust the paging file and sometimes triggers "[error 1455] the paging file is too small for this operation to complete" errors. Setting mmap_mode='r' or mmap_mode='r+' does not trigger that problem. I will run tests to see if I can change the default mode in the next version of joblib.

  13. GaelVaroquaux commented on Jun 30, 2014

    @GaelVaroquaux
    Member

    operation to complete" errors. Setting mmap_mode='r' or mmap_mode='r+'
    does not trigger that problem. I will run tests to see if I can change
    the default mode in the next version of joblib.

    Should we do that only on windows? mmap_mode='r' is clearly the best
    option in general.

  14. ogrisel commented on Jun 30, 2014

    @ogrisel
    Member

    I would rather have a consistent behavior across platforms. mmap_mode='r' is problematic as it might cause Parallel calls to raise exceptions that would not have been raise with n_jobs=1.

    mmap_mode='r+' is actually a good default in my opinion: it will make the Parallel mode to behave more consistently whatever the value of n_jobs.

  15. ogrisel commented on Jun 30, 2014

    @ogrisel
    Member

    Actually mmap_mode='r' might be better. Silent concurrent modification of input data is probably never expected by the user and it would be better to raise an exception to be on the safe side.

  16. 31 remaining items

  17. ogrisel commented on Sep 1, 2014

    @ogrisel
    Member

    @FlxLaurens this is probably not related as this happens later than @laszlosandor's crash. Can you give us the complete traceback of the error you get under linux?

  18. ogrisel commented on Sep 1, 2014

    @ogrisel
    Member

    BTW I think this would better be done as a new issue as I think it's unrelated.

  19. ogrisel commented on Sep 10, 2014

    @ogrisel
    Member

    IOError: [Errno 28] No space left on device

    Your data is just too big to be memmap in the default folder /dev/shm on linux. You can point it to a different folder by setting the JOBLIB_TEMP_FOLDER environment variable.

  20. ogrisel commented on Sep 17, 2014

    @ogrisel
    Member

    Thanks for you analysis. I will create a new issue for that. As docker is likely to be a popular target runtime environment in the future we need to have better defaults in joblib or at least more informative error messages.

  21. modified the milestone: 0.19 on Sep 29, 2016
  22. jnothman commented on Jun 14, 2017

    @jnothman
    Member

    @ogrisel, I can't tell at a glance what needs to be done here. Can we close this and open a new issue?

  23. modified the milestones: 0.20, 0.19 on Jun 14, 2017
  24. GaelVaroquaux commented on Jun 15, 2017

    @GaelVaroquaux
    Member

    I think that we should close. Things have massively changed since.

  25. uwaisiqbal commented on May 16, 2018

    @uwaisiqbal

    I am getting this error when running learning_curve. Are there any suggestions or fixes I can try to resolve the issue???

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

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions