numpy_pickle.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. """Utilities for fast persistence of big data, with optional compression."""
  2. # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
  3. # Copyright (c) 2009 Gael Varoquaux
  4. # License: BSD Style, 3 clauses.
  5. import pickle
  6. import os
  7. import warnings
  8. try:
  9. from pathlib import Path
  10. except ImportError:
  11. Path = None
  12. from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR
  13. from .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile
  14. from .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,
  15. BZ2CompressorWrapper, LZMACompressorWrapper,
  16. XZCompressorWrapper, LZ4CompressorWrapper)
  17. from .numpy_pickle_utils import Unpickler, Pickler
  18. from .numpy_pickle_utils import _read_fileobject, _write_fileobject
  19. from .numpy_pickle_utils import _read_bytes, BUFFER_SIZE
  20. from .numpy_pickle_compat import load_compatibility
  21. from .numpy_pickle_compat import NDArrayWrapper
  22. # For compatibility with old versions of joblib, we need ZNDArrayWrapper
  23. # to be visible in the current namespace.
  24. # Explicitly skipping next line from flake8 as it triggers an F401 warning
  25. # which we don't care.
  26. from .numpy_pickle_compat import ZNDArrayWrapper # noqa
  27. from .backports import make_memmap
  28. # Register supported compressors
  29. register_compressor('zlib', ZlibCompressorWrapper())
  30. register_compressor('gzip', GzipCompressorWrapper())
  31. register_compressor('bz2', BZ2CompressorWrapper())
  32. register_compressor('lzma', LZMACompressorWrapper())
  33. register_compressor('xz', XZCompressorWrapper())
  34. register_compressor('lz4', LZ4CompressorWrapper())
  35. ###############################################################################
  36. # Utility objects for persistence.
  37. class NumpyArrayWrapper(object):
  38. """An object to be persisted instead of numpy arrays.
  39. This object is used to hack into the pickle machinery and read numpy
  40. array data from our custom persistence format.
  41. More precisely, this object is used for:
  42. * carrying the information of the persisted array: subclass, shape, order,
  43. dtype. Those ndarray metadata are used to correctly reconstruct the array
  44. with low level numpy functions.
  45. * determining if memmap is allowed on the array.
  46. * reading the array bytes from a file.
  47. * reading the array using memorymap from a file.
  48. * writing the array bytes to a file.
  49. Attributes
  50. ----------
  51. subclass: numpy.ndarray subclass
  52. Determine the subclass of the wrapped array.
  53. shape: numpy.ndarray shape
  54. Determine the shape of the wrapped array.
  55. order: {'C', 'F'}
  56. Determine the order of wrapped array data. 'C' is for C order, 'F' is
  57. for fortran order.
  58. dtype: numpy.ndarray dtype
  59. Determine the data type of the wrapped array.
  60. allow_mmap: bool
  61. Determine if memory mapping is allowed on the wrapped array.
  62. Default: False.
  63. """
  64. def __init__(self, subclass, shape, order, dtype, allow_mmap=False):
  65. """Constructor. Store the useful information for later."""
  66. self.subclass = subclass
  67. self.shape = shape
  68. self.order = order
  69. self.dtype = dtype
  70. self.allow_mmap = allow_mmap
  71. def write_array(self, array, pickler):
  72. """Write array bytes to pickler file handle.
  73. This function is an adaptation of the numpy write_array function
  74. available in version 1.10.1 in numpy/lib/format.py.
  75. """
  76. # Set buffer size to 16 MiB to hide the Python loop overhead.
  77. buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
  78. if array.dtype.hasobject:
  79. # We contain Python objects so we cannot write out the data
  80. # directly. Instead, we will pickle it out with version 2 of the
  81. # pickle protocol.
  82. pickle.dump(array, pickler.file_handle, protocol=2)
  83. else:
  84. for chunk in pickler.np.nditer(array,
  85. flags=['external_loop',
  86. 'buffered',
  87. 'zerosize_ok'],
  88. buffersize=buffersize,
  89. order=self.order):
  90. pickler.file_handle.write(chunk.tobytes('C'))
  91. def read_array(self, unpickler):
  92. """Read array from unpickler file handle.
  93. This function is an adaptation of the numpy read_array function
  94. available in version 1.10.1 in numpy/lib/format.py.
  95. """
  96. if len(self.shape) == 0:
  97. count = 1
  98. else:
  99. # joblib issue #859: we cast the elements of self.shape to int64 to
  100. # prevent a potential overflow when computing their product.
  101. shape_int64 = [unpickler.np.int64(x) for x in self.shape]
  102. count = unpickler.np.multiply.reduce(shape_int64)
  103. # Now read the actual data.
  104. if self.dtype.hasobject:
  105. # The array contained Python objects. We need to unpickle the data.
  106. array = pickle.load(unpickler.file_handle)
  107. else:
  108. # This is not a real file. We have to read it the
  109. # memory-intensive way.
  110. # crc32 module fails on reads greater than 2 ** 32 bytes,
  111. # breaking large reads from gzip streams. Chunk reads to
  112. # BUFFER_SIZE bytes to avoid issue and reduce memory overhead
  113. # of the read. In non-chunked case count < max_read_count, so
  114. # only one read is performed.
  115. max_read_count = BUFFER_SIZE // min(BUFFER_SIZE,
  116. self.dtype.itemsize)
  117. array = unpickler.np.empty(count, dtype=self.dtype)
  118. for i in range(0, count, max_read_count):
  119. read_count = min(max_read_count, count - i)
  120. read_size = int(read_count * self.dtype.itemsize)
  121. data = _read_bytes(unpickler.file_handle,
  122. read_size, "array data")
  123. array[i:i + read_count] = \
  124. unpickler.np.frombuffer(data, dtype=self.dtype,
  125. count=read_count)
  126. del data
  127. if self.order == 'F':
  128. array.shape = self.shape[::-1]
  129. array = array.transpose()
  130. else:
  131. array.shape = self.shape
  132. return array
  133. def read_mmap(self, unpickler):
  134. """Read an array using numpy memmap."""
  135. offset = unpickler.file_handle.tell()
  136. if unpickler.mmap_mode == 'w+':
  137. unpickler.mmap_mode = 'r+'
  138. marray = make_memmap(unpickler.filename,
  139. dtype=self.dtype,
  140. shape=self.shape,
  141. order=self.order,
  142. mode=unpickler.mmap_mode,
  143. offset=offset)
  144. # update the offset so that it corresponds to the end of the read array
  145. unpickler.file_handle.seek(offset + marray.nbytes)
  146. return marray
  147. def read(self, unpickler):
  148. """Read the array corresponding to this wrapper.
  149. Use the unpickler to get all information to correctly read the array.
  150. Parameters
  151. ----------
  152. unpickler: NumpyUnpickler
  153. Returns
  154. -------
  155. array: numpy.ndarray
  156. """
  157. # When requested, only use memmap mode if allowed.
  158. if unpickler.mmap_mode is not None and self.allow_mmap:
  159. array = self.read_mmap(unpickler)
  160. else:
  161. array = self.read_array(unpickler)
  162. # Manage array subclass case
  163. if (hasattr(array, '__array_prepare__') and
  164. self.subclass not in (unpickler.np.ndarray,
  165. unpickler.np.memmap)):
  166. # We need to reconstruct another subclass
  167. new_array = unpickler.np.core.multiarray._reconstruct(
  168. self.subclass, (0,), 'b')
  169. return new_array.__array_prepare__(array)
  170. else:
  171. return array
  172. ###############################################################################
  173. # Pickler classes
  174. class NumpyPickler(Pickler):
  175. """A pickler to persist big data efficiently.
  176. The main features of this object are:
  177. * persistence of numpy arrays in a single file.
  178. * optional compression with a special care on avoiding memory copies.
  179. Attributes
  180. ----------
  181. fp: file
  182. File object handle used for serializing the input object.
  183. protocol: int, optional
  184. Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL.
  185. """
  186. dispatch = Pickler.dispatch.copy()
  187. def __init__(self, fp, protocol=None):
  188. self.file_handle = fp
  189. self.buffered = isinstance(self.file_handle, BinaryZlibFile)
  190. # By default we want a pickle protocol that only changes with
  191. # the major python version and not the minor one
  192. if protocol is None:
  193. protocol = pickle.DEFAULT_PROTOCOL
  194. Pickler.__init__(self, self.file_handle, protocol=protocol)
  195. # delayed import of numpy, to avoid tight coupling
  196. try:
  197. import numpy as np
  198. except ImportError:
  199. np = None
  200. self.np = np
  201. def _create_array_wrapper(self, array):
  202. """Create and returns a numpy array wrapper from a numpy array."""
  203. order = 'F' if (array.flags.f_contiguous and
  204. not array.flags.c_contiguous) else 'C'
  205. allow_mmap = not self.buffered and not array.dtype.hasobject
  206. wrapper = NumpyArrayWrapper(type(array),
  207. array.shape, order, array.dtype,
  208. allow_mmap=allow_mmap)
  209. return wrapper
  210. def save(self, obj):
  211. """Subclass the Pickler `save` method.
  212. This is a total abuse of the Pickler class in order to use the numpy
  213. persistence function `save` instead of the default pickle
  214. implementation. The numpy array is replaced by a custom wrapper in the
  215. pickle persistence stack and the serialized array is written right
  216. after in the file. Warning: the file produced does not follow the
  217. pickle format. As such it can not be read with `pickle.load`.
  218. """
  219. if self.np is not None and type(obj) in (self.np.ndarray,
  220. self.np.matrix,
  221. self.np.memmap):
  222. if type(obj) is self.np.memmap:
  223. # Pickling doesn't work with memmapped arrays
  224. obj = self.np.asanyarray(obj)
  225. # The array wrapper is pickled instead of the real array.
  226. wrapper = self._create_array_wrapper(obj)
  227. Pickler.save(self, wrapper)
  228. # A framer was introduced with pickle protocol 4 and we want to
  229. # ensure the wrapper object is written before the numpy array
  230. # buffer in the pickle file.
  231. # See https://www.python.org/dev/peps/pep-3154/#framing to get
  232. # more information on the framer behavior.
  233. if self.proto >= 4:
  234. self.framer.commit_frame(force=True)
  235. # And then array bytes are written right after the wrapper.
  236. wrapper.write_array(obj, self)
  237. return
  238. return Pickler.save(self, obj)
  239. class NumpyUnpickler(Unpickler):
  240. """A subclass of the Unpickler to unpickle our numpy pickles.
  241. Attributes
  242. ----------
  243. mmap_mode: str
  244. The memorymap mode to use for reading numpy arrays.
  245. file_handle: file_like
  246. File object to unpickle from.
  247. filename: str
  248. Name of the file to unpickle from. It should correspond to file_handle.
  249. This parameter is required when using mmap_mode.
  250. np: module
  251. Reference to numpy module if numpy is installed else None.
  252. """
  253. dispatch = Unpickler.dispatch.copy()
  254. def __init__(self, filename, file_handle, mmap_mode=None):
  255. # The next line is for backward compatibility with pickle generated
  256. # with joblib versions less than 0.10.
  257. self._dirname = os.path.dirname(filename)
  258. self.mmap_mode = mmap_mode
  259. self.file_handle = file_handle
  260. # filename is required for numpy mmap mode.
  261. self.filename = filename
  262. self.compat_mode = False
  263. Unpickler.__init__(self, self.file_handle)
  264. try:
  265. import numpy as np
  266. except ImportError:
  267. np = None
  268. self.np = np
  269. def load_build(self):
  270. """Called to set the state of a newly created object.
  271. We capture it to replace our place-holder objects, NDArrayWrapper or
  272. NumpyArrayWrapper, by the array we are interested in. We
  273. replace them directly in the stack of pickler.
  274. NDArrayWrapper is used for backward compatibility with joblib <= 0.9.
  275. """
  276. Unpickler.load_build(self)
  277. # For backward compatibility, we support NDArrayWrapper objects.
  278. if isinstance(self.stack[-1], (NDArrayWrapper, NumpyArrayWrapper)):
  279. if self.np is None:
  280. raise ImportError("Trying to unpickle an ndarray, "
  281. "but numpy didn't import correctly")
  282. array_wrapper = self.stack.pop()
  283. # If any NDArrayWrapper is found, we switch to compatibility mode,
  284. # this will be used to raise a DeprecationWarning to the user at
  285. # the end of the unpickling.
  286. if isinstance(array_wrapper, NDArrayWrapper):
  287. self.compat_mode = True
  288. self.stack.append(array_wrapper.read(self))
  289. # Be careful to register our new method.
  290. dispatch[pickle.BUILD[0]] = load_build
  291. ###############################################################################
  292. # Utility functions
  293. def dump(value, filename, compress=0, protocol=None, cache_size=None):
  294. """Persist an arbitrary Python object into one file.
  295. Read more in the :ref:`User Guide <persistence>`.
  296. Parameters
  297. -----------
  298. value: any Python object
  299. The object to store to disk.
  300. filename: str, pathlib.Path, or file object.
  301. The file object or path of the file in which it is to be stored.
  302. The compression method corresponding to one of the supported filename
  303. extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used
  304. automatically.
  305. compress: int from 0 to 9 or bool or 2-tuple, optional
  306. Optional compression level for the data. 0 or False is no compression.
  307. Higher value means more compression, but also slower read and
  308. write times. Using a value of 3 is often a good compromise.
  309. See the notes for more details.
  310. If compress is True, the compression level used is 3.
  311. If compress is a 2-tuple, the first element must correspond to a string
  312. between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma'
  313. 'xz'), the second element must be an integer from 0 to 9, corresponding
  314. to the compression level.
  315. protocol: int, optional
  316. Pickle protocol, see pickle.dump documentation for more details.
  317. cache_size: positive int, optional
  318. This option is deprecated in 0.10 and has no effect.
  319. Returns
  320. -------
  321. filenames: list of strings
  322. The list of file names in which the data is stored. If
  323. compress is false, each array is stored in a different file.
  324. See Also
  325. --------
  326. joblib.load : corresponding loader
  327. Notes
  328. -----
  329. Memmapping on load cannot be used for compressed files. Thus
  330. using compression can significantly slow down loading. In
  331. addition, compressed files take extra extra memory during
  332. dump and load.
  333. """
  334. if Path is not None and isinstance(filename, Path):
  335. filename = str(filename)
  336. is_filename = isinstance(filename, str)
  337. is_fileobj = hasattr(filename, "write")
  338. compress_method = 'zlib' # zlib is the default compression method.
  339. if compress is True:
  340. # By default, if compress is enabled, we want the default compress
  341. # level of the compressor.
  342. compress_level = None
  343. elif isinstance(compress, tuple):
  344. # a 2-tuple was set in compress
  345. if len(compress) != 2:
  346. raise ValueError(
  347. 'Compress argument tuple should contain exactly 2 elements: '
  348. '(compress method, compress level), you passed {}'
  349. .format(compress))
  350. compress_method, compress_level = compress
  351. elif isinstance(compress, str):
  352. compress_method = compress
  353. compress_level = None # Use default compress level
  354. compress = (compress_method, compress_level)
  355. else:
  356. compress_level = compress
  357. if compress_method == 'lz4' and lz4 is None:
  358. raise ValueError(LZ4_NOT_INSTALLED_ERROR)
  359. if (compress_level is not None and
  360. compress_level is not False and
  361. compress_level not in range(10)):
  362. # Raising an error if a non valid compress level is given.
  363. raise ValueError(
  364. 'Non valid compress level given: "{}". Possible values are '
  365. '{}.'.format(compress_level, list(range(10))))
  366. if compress_method not in _COMPRESSORS:
  367. # Raising an error if an unsupported compression method is given.
  368. raise ValueError(
  369. 'Non valid compression method given: "{}". Possible values are '
  370. '{}.'.format(compress_method, _COMPRESSORS))
  371. if not is_filename and not is_fileobj:
  372. # People keep inverting arguments, and the resulting error is
  373. # incomprehensible
  374. raise ValueError(
  375. 'Second argument should be a filename or a file-like object, '
  376. '%s (type %s) was given.'
  377. % (filename, type(filename))
  378. )
  379. if is_filename and not isinstance(compress, tuple):
  380. # In case no explicit compression was requested using both compression
  381. # method and level in a tuple and the filename has an explicit
  382. # extension, we select the corresponding compressor.
  383. # unset the variable to be sure no compression level is set afterwards.
  384. compress_method = None
  385. for name, compressor in _COMPRESSORS.items():
  386. if filename.endswith(compressor.extension):
  387. compress_method = name
  388. if compress_method in _COMPRESSORS and compress_level == 0:
  389. # we choose the default compress_level in case it was not given
  390. # as an argument (using compress).
  391. compress_level = None
  392. if cache_size is not None:
  393. # Cache size is deprecated starting from version 0.10
  394. warnings.warn("Please do not set 'cache_size' in joblib.dump, "
  395. "this parameter has no effect and will be removed. "
  396. "You used 'cache_size={}'".format(cache_size),
  397. DeprecationWarning, stacklevel=2)
  398. if compress_level != 0:
  399. with _write_fileobject(filename, compress=(compress_method,
  400. compress_level)) as f:
  401. NumpyPickler(f, protocol=protocol).dump(value)
  402. elif is_filename:
  403. with open(filename, 'wb') as f:
  404. NumpyPickler(f, protocol=protocol).dump(value)
  405. else:
  406. NumpyPickler(filename, protocol=protocol).dump(value)
  407. # If the target container is a file object, nothing is returned.
  408. if is_fileobj:
  409. return
  410. # For compatibility, the list of created filenames (e.g with one element
  411. # after 0.10.0) is returned by default.
  412. return [filename]
  413. def _unpickle(fobj, filename="", mmap_mode=None):
  414. """Internal unpickling function."""
  415. # We are careful to open the file handle early and keep it open to
  416. # avoid race-conditions on renames.
  417. # That said, if data is stored in companion files, which can be
  418. # the case with the old persistence format, moving the directory
  419. # will create a race when joblib tries to access the companion
  420. # files.
  421. unpickler = NumpyUnpickler(filename, fobj, mmap_mode=mmap_mode)
  422. obj = None
  423. try:
  424. obj = unpickler.load()
  425. if unpickler.compat_mode:
  426. warnings.warn("The file '%s' has been generated with a "
  427. "joblib version less than 0.10. "
  428. "Please regenerate this pickle file."
  429. % filename,
  430. DeprecationWarning, stacklevel=3)
  431. except UnicodeDecodeError as exc:
  432. # More user-friendly error message
  433. new_exc = ValueError(
  434. 'You may be trying to read with '
  435. 'python 3 a joblib pickle generated with python 2. '
  436. 'This feature is not supported by joblib.')
  437. new_exc.__cause__ = exc
  438. raise new_exc
  439. return obj
  440. def load_temporary_memmap(filename, mmap_mode, unlink_on_gc_collect):
  441. from ._memmapping_reducer import JOBLIB_MMAPS, add_maybe_unlink_finalizer
  442. obj = load(filename, mmap_mode)
  443. JOBLIB_MMAPS.add(obj.filename)
  444. if unlink_on_gc_collect:
  445. add_maybe_unlink_finalizer(obj)
  446. return obj
  447. def load(filename, mmap_mode=None):
  448. """Reconstruct a Python object from a file persisted with joblib.dump.
  449. Read more in the :ref:`User Guide <persistence>`.
  450. WARNING: joblib.load relies on the pickle module and can therefore
  451. execute arbitrary Python code. It should therefore never be used
  452. to load files from untrusted sources.
  453. Parameters
  454. -----------
  455. filename: str, pathlib.Path, or file object.
  456. The file object or path of the file from which to load the object
  457. mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
  458. If not None, the arrays are memory-mapped from the disk. This
  459. mode has no effect for compressed files. Note that in this
  460. case the reconstructed object might no longer match exactly
  461. the originally pickled object.
  462. Returns
  463. -------
  464. result: any Python object
  465. The object stored in the file.
  466. See Also
  467. --------
  468. joblib.dump : function to save an object
  469. Notes
  470. -----
  471. This function can load numpy array files saved separately during the
  472. dump. If the mmap_mode argument is given, it is passed to np.load and
  473. arrays are loaded as memmaps. As a consequence, the reconstructed
  474. object might not match the original pickled object. Note that if the
  475. file was saved with compression, the arrays cannot be memmapped.
  476. """
  477. if Path is not None and isinstance(filename, Path):
  478. filename = str(filename)
  479. if hasattr(filename, "read"):
  480. fobj = filename
  481. filename = getattr(fobj, 'name', '')
  482. with _read_fileobject(fobj, filename, mmap_mode) as fobj:
  483. obj = _unpickle(fobj)
  484. else:
  485. with open(filename, 'rb') as f:
  486. with _read_fileobject(f, filename, mmap_mode) as fobj:
  487. if isinstance(fobj, str):
  488. # if the returned file object is a string, this means we
  489. # try to load a pickle file generated with an version of
  490. # Joblib so we load it with joblib compatibility function.
  491. return load_compatibility(fobj)
  492. obj = _unpickle(fobj, filename, mmap_mode)
  493. return obj