From d02f0663f42a49be51b4ade0bc62793e57bf0412 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 4 Dec 2017 11:52:35 +0100 Subject: [PATCH 01/31] TST non-regression test for no-copy dump of bytes --- dev-requirements.txt | 1 + tests/cloudpickle_test.py | 16 +++++++++++ tests/testutils.py | 56 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) diff --git a/dev-requirements.txt b/dev-requirements.txt index 98698f3d3..2c267805d 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -2,5 +2,6 @@ pytest pytest-cov mock +psutil # Code coverage uploader for Travis: codecov diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 23cbb3dbc..068aefa1d 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -9,6 +9,7 @@ import itertools import logging from operator import itemgetter, attrgetter +import os import pickle import platform import random @@ -45,6 +46,7 @@ from .testutils import subprocess_pickle_echo from .testutils import assert_run_python_script +from .testutils import CountingByteSink, PeakMemoryMonitor def pickle_depickle(obj, protocol=cloudpickle.DEFAULT_PROTOCOL): @@ -862,6 +864,20 @@ def test_function_pickle_compat_0_4_1(self): b'\x14NtR.') self.assertEquals(42, cloudpickle.loads(pickled)(42)) + def test_nocopy_bytes(self): + sink = CountingByteSink() + biggish_data = b'0' * int(2e8) # 200 MB + pickler = cloudpickle.CloudPickler(sink, protocol=self.protocol) + with PeakMemoryMonitor() as monitor: + pickler.dump(biggish_data) + + # Check that temporary datastructures used when dumping are no larger + # than 100 MB which is much smaller than the bytes to be pickled. + assert monitor.base_mem > len(biggish_data) + assert (monitor.peak_mem - monitor.base_mem) < 100e6 + + assert sink.written > len(biggish_data) + class Protocol2CloudPickleTest(CloudPickleTest): diff --git a/tests/testutils.py b/tests/testutils.py index a8187baf3..818037fc4 100644 --- a/tests/testutils.py +++ b/tests/testutils.py @@ -3,9 +3,12 @@ import os.path as op import tempfile from subprocess import Popen, check_output, PIPE, STDOUT, CalledProcessError +import gc +import multiprocessing as mp from cloudpickle import dumps from pickle import loads +import pytest try: from suprocess import TimeoutExpired @@ -110,5 +113,58 @@ def assert_run_python_script(source_code, timeout=5): os.unlink(source_file) +def monitor_worker(pid, queue, stop_event, delay=0.05): + import psutil + p = psutil.Process(pid) + peak = 0 + + def make_measurement(peak): + mem = p.memory_info().rss + if mem > peak: + peak = mem + return peak + + # Make measurements every 'delay' seconds until we receive the stop event: + while not stop_event.wait(timeout=delay): + peak = make_measurement(peak) + + # Make one last measurement in case memory has increased just before + # receiving the stop event: + peak = make_measurement(peak) + queue.put(peak) + + +class PeakMemoryMonitor: + + def __enter__(self): + psutil = pytest.importorskip("psutil") + pid = os.getpid() + gc.collect() + self.base_mem = psutil.Process(pid).memory_info().rss + self.queue = q = mp.Queue() + self.stop_event = e = mp.Event() + self.worker = mp.Process(target=monitor_worker, args=(pid, q, e)) + self.worker.start() + return self + + def __exit__(self, exc_type, exc_value, tb): + self.stop_event.set() + if exc_type is not None: + self.worker.terminate() + return False + else: + self.peak_mem = self.queue.get() + return True + + +class CountingByteSink(object): + + def __init__(self): + self.written = 0 + + def write(self, data): + self.written += len(data) + + if __name__ == '__main__': pickle_echo() From 516e4641a06ee077dc0ddab0d200a99163c41852 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 4 Dec 2017 14:44:37 +0100 Subject: [PATCH 02/31] Backport nocopy dump for large bytes object from bpo-31993 --- cloudpickle/cloudpickle.py | 89 ++++++++++++++++++++++++++++++++++++++ tests/cloudpickle_test.py | 2 + 2 files changed, 91 insertions(+) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index e5aab0591..4b2b59520 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -42,6 +42,7 @@ """ from __future__ import print_function +import codecs import dis from functools import partial import imp @@ -249,6 +250,68 @@ def _walk_global_ops(code): yield op, instr.arg +class _Framer: + """Backport of Python 3.7 framer""" + + _FRAME_SIZE_TARGET = 64 * 1024 + + def __init__(self, file_write): + self.file_write = file_write + self.current_frame = None + + def start_framing(self): + self.current_frame = io.BytesIO() + + def end_framing(self): + if self.current_frame and self.current_frame.tell() > 0: + self.commit_frame(force=True) + self.current_frame = None + + def commit_frame(self, force=False): + if self.current_frame: + f = self.current_frame + if f.tell() >= self._FRAME_SIZE_TARGET or force: + data = f.getbuffer() + write = self.file_write + # Issue a single call to the write nethod of the underlying + # file object for the frame opcode with the size of the + # frame. The concatenation is expected to be less expensive + # than issuing an additional call to write. + write(pickle.FRAME + struct.pack(" 0xffffffff and self.proto >= 4: + self._write_large_bytes(pickle.BINBYTES8 + struct.pack("= self.framer._FRAME_SIZE_TARGET: + self._write_large_bytes(pickle.BINBYTES + struct.pack(" Date: Mon, 4 Dec 2017 16:29:28 +0100 Subject: [PATCH 03/31] Nocopy support for contiguous memoryviews --- cloudpickle/cloudpickle.py | 45 ++++++++++++++++++++++---------------- tests/cloudpickle_test.py | 35 ++++++++++++++++++----------- 2 files changed, 48 insertions(+), 32 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 4b2b59520..a1c655609 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -340,28 +340,35 @@ def dump(self, obj): msg = """Could not pickle object as excessively deep recursion required.""" raise pickle.PicklingError(msg) - def save_bytes(self, obj): - if self.proto < 3: - if not obj: # bytes object is empty - self.save_reduce(bytes, (), obj=obj) + if PY3: + def save_bytes(self, obj): + if self.proto < 3: + if not obj: # bytes object is empty + self.save_reduce(bytes, (), obj=obj) + else: + self.save_reduce(codecs.encode, + (str(obj, 'latin1'), 'latin1'), obj=obj) + return + n = len(obj) + if n <= 0xff: + self.write(pickle.SHORT_BINBYTES + struct.pack(" 0xffffffff and self.proto >= 4: + self._write_large_bytes(pickle.BINBYTES8 + struct.pack("= self.framer._FRAME_SIZE_TARGET: + self._write_large_bytes(pickle.BINBYTES + struct.pack(" 0xffffffff and self.proto >= 4: - self._write_large_bytes(pickle.BINBYTES8 + struct.pack("= self.framer._FRAME_SIZE_TARGET: - self._write_large_bytes(pickle.BINBYTES + struct.pack(" len(biggish_data) - assert (monitor.peak_mem - monitor.base_mem) < 100e6 - - assert sink.written > len(biggish_data) + biggish_data_bytes = b'0' * int(2e8) # 200 MB + biggish_data_view = memoryview(biggish_data_bytes) + for biggish_data in [biggish_data_bytes, biggish_data_view]: + pickler = cloudpickle.CloudPickler(sink, protocol=self.protocol) + with PeakMemoryMonitor() as monitor: + pickler.dump(biggish_data) + + # Check that temporary datastructures used when dumping are no + # larger than 100 MB which is much smaller than the bytes to be + # pickled. + assert monitor.base_mem > len(biggish_data) + assert (monitor.peak_mem - monitor.base_mem) < 100e6 + + assert sink.written > len(biggish_data) class Protocol2CloudPickleTest(CloudPickleTest): From 3e6f98ebf032acb9c8672ec8246fbb035fc4ba0f Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 4 Dec 2017 18:57:56 +0100 Subject: [PATCH 04/31] from struct import pack --- cloudpickle/cloudpickle.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index a1c655609..25eb02374 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -52,7 +52,7 @@ import opcode import operator import pickle -import struct +from struct import pack import sys import traceback import types @@ -277,7 +277,7 @@ def commit_frame(self, force=False): # file object for the frame opcode with the size of the # frame. The concatenation is expected to be less expensive # than issuing an additional call to write. - write(pickle.FRAME + struct.pack(" 0xffffffff and self.proto >= 4: - self._write_large_bytes(pickle.BINBYTES8 + struct.pack("= self.framer._FRAME_SIZE_TARGET: - self._write_large_bytes(pickle.BINBYTES + struct.pack(" Date: Tue, 5 Dec 2017 13:51:35 +0100 Subject: [PATCH 05/31] WIP reduce memoryviews --- cloudpickle/cloudpickle.py | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 25eb02374..6b7a348c9 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -43,6 +43,7 @@ from __future__ import print_function import codecs +import ctypes import dis from functools import partial import imp @@ -250,6 +251,25 @@ def _walk_global_ops(code): yield op, instr.arg +def _memoryview_from_bytes(data, format, readonly): + if not readonly: + # Force the memory buffer writable: this is a violation of the + # immutability of Python bytes object but this should be safe because: + # - data has just been allocated from reading from the pickle stream + # and will never be used outside of the scope of this reducer. + # - bytes objects are not interned. + buffer = ctypes.cast(data, ctypes.POINTER(ctypes.c_char)) + addr = ctypes.addressof(buffer.contents) + array = (ctypes.c_char * len(data)).from_address(addr) + view = memoryview(array) + else: + view = memoryview(data) + if hasattr(view, 'cast'): + return view.cast(format) + else: + return view + + class _Framer: """Backport of Python 3.7 framer""" @@ -341,7 +361,7 @@ def dump(self, obj): raise pickle.PicklingError(msg) if PY3: - def save_bytes(self, obj): + def save_bytes(self, obj, skip_memoize=False): if self.proto < 3: if not obj: # bytes object is empty self.save_reduce(bytes, (), obj=obj) @@ -358,17 +378,25 @@ def save_bytes(self, obj): self._write_large_bytes(pickle.BINBYTES + pack(" Date: Tue, 5 Dec 2017 16:37:53 +0100 Subject: [PATCH 06/31] WIP add test for memoryview of integer array --- cloudpickle/cloudpickle.py | 2 +- tests/cloudpickle_test.py | 18 +++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 6b7a348c9..1e71674bc 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -265,7 +265,7 @@ def _memoryview_from_bytes(data, format, readonly): else: view = memoryview(data) if hasattr(view, 'cast'): - return view.cast(format) + return view.cast('B').cast(format) else: return view diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 350258f68..2ba981878 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -1,5 +1,6 @@ from __future__ import division +import array import abc import collections import base64 @@ -9,7 +10,6 @@ import itertools import logging from operator import itemgetter, attrgetter -import os import pickle import platform import random @@ -136,8 +136,20 @@ def test_buffer(self): def test_memoryview(self): buffer_obj = memoryview(b"Hello") - self.assertEqual(pickle_depickle(buffer_obj, protocol=self.protocol), - buffer_obj.tobytes()) + assert buffer_obj.readonly + cloned = pickle_depickle(buffer_obj, protocol=self.protocol) + self.assertEqual(cloned.tobytes(), buffer_obj.tobytes()) + assert cloned.readonly + + @pytest.mark.skipif(sys.version_info < (3, 4), + reason="array does not implement the buffer protocol") + def test_memoryview_from_integer_array(self): + buffer_obj = memoryview(array.array('l', range(12))) + assert buffer_obj.format == 'l' + cloned = pickle_depickle(buffer_obj, protocol=self.protocol) + self.assertEqual(cloned.tobytes(), buffer_obj.tobytes()) + assert cloned.format == 'l' + assert not cloned.readonly def test_large_memoryview(self): buffer_obj = memoryview(b"Hello!" * int(1e7)) From f7341ac45f37347372683232345cf64fea396152 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Tue, 5 Dec 2017 19:21:55 +0100 Subject: [PATCH 07/31] Workaround bug in Python 3.4 and partial impl of memview in PyPy --- cloudpickle/cloudpickle.py | 15 +++++++++++---- tests/cloudpickle_test.py | 5 ++++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 1e71674bc..55dff89af 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -65,8 +65,9 @@ # communication speed over compatibility: DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL +PY_MAJOR_MINOR = sys.version_info[:2] -if sys.version < '3': +if PY_MAJOR_MINOR[0] < 3: from pickle import Pickler try: from cStringIO import StringIO @@ -264,9 +265,11 @@ def _memoryview_from_bytes(data, format, readonly): view = memoryview(array) else: view = memoryview(data) - if hasattr(view, 'cast'): + if PY_MAJOR_MINOR >= (3, 5) or (PY_MAJOR_MINOR == (3, 4) and readonly): return view.cast('B').cast(format) else: + # Python 2.7 does not support casting and Python 3.4 has a bug when + # casting buffers from ctypes: # https://bugs.python.org/issue19803 return view @@ -386,11 +389,15 @@ def save_memoryview(self, obj): n = len(obj) self.save(_memoryview_from_bytes) self.write(pickle.MARK) - if n <= 0xff or self.proto < 3 or not obj.c_contiguous: + # PyPy3 does not implement the 'c_contiguous' attribute at this time. + c_contiguous = getattr(obj, 'c_contiguous', False) + if n <= 0xff or self.proto < 3 or not c_contiguous: + # Make a contiguous copy prior as a bytes object prior to + # serialization. self.save(obj.tobytes()) else: # Large contiguous views can benefit from nocopy semantics with - # recent versions of the pickle protocol + # recent versions of the pickle protocol. self.save_bytes(obj, skip_memoize=True) self.save(obj.format) self.save(obj.readonly) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 2ba981878..6a58d7a94 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -148,9 +148,12 @@ def test_memoryview_from_integer_array(self): assert buffer_obj.format == 'l' cloned = pickle_depickle(buffer_obj, protocol=self.protocol) self.assertEqual(cloned.tobytes(), buffer_obj.tobytes()) - assert cloned.format == 'l' assert not cloned.readonly + if sys.version_info >= (3, 5): + # Python 3.4 is affected by https://bugs.python.org/issue19803 + assert cloned.format == 'l' + def test_large_memoryview(self): buffer_obj = memoryview(b"Hello!" * int(1e7)) self.assertEqual(pickle_depickle(buffer_obj, protocol=self.protocol), From ed2b2af7d44ad1da5352fde2cca15eeca5f1ba4e Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Tue, 5 Dec 2017 20:01:07 +0100 Subject: [PATCH 08/31] Better comments and tests --- cloudpickle/cloudpickle.py | 13 ++++++---- tests/cloudpickle_test.py | 51 +++++++++++++++++++++++++++----------- tests/testutils.py | 9 ------- 3 files changed, 44 insertions(+), 29 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 55dff89af..9c599edb7 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -254,16 +254,19 @@ def _walk_global_ops(code): def _memoryview_from_bytes(data, format, readonly): if not readonly: - # Force the memory buffer writable: this is a violation of the - # immutability of Python bytes object but this should be safe because: - # - data has just been allocated from reading from the pickle stream - # and will never be used outside of the scope of this reducer. - # - bytes objects are not interned. + # Forcibly render the recently unpickled bytes buffer writable: + # this is a violation of the immutability of a Python bytes object but + # this should be safe because: + # - data is a temporary variable that has just been allocated from + # reading from the pickle stream and will never be used outside of + # the scope of this reducer. + # - bytes objects are not subject to interning. buffer = ctypes.cast(data, ctypes.POINTER(ctypes.c_char)) addr = ctypes.addressof(buffer.contents) array = (ctypes.c_char * len(data)).from_address(addr) view = memoryview(array) else: + # A memoryview of a bytes object is readonly by default. view = memoryview(data) if PY_MAJOR_MINOR >= (3, 5) or (PY_MAJOR_MINOR == (3, 4) and readonly): return view.cast('B').cast(format) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 6a58d7a94..11ad59c90 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -46,7 +46,7 @@ from .testutils import subprocess_pickle_echo from .testutils import assert_run_python_script -from .testutils import CountingByteSink, PeakMemoryMonitor +from .testutils import PeakMemoryMonitor def pickle_depickle(obj, protocol=cloudpickle.DEFAULT_PROTOCOL): @@ -885,14 +885,24 @@ def test_function_pickle_compat_0_4_1(self): b'\x14NtR.') self.assertEquals(42, cloudpickle.loads(pickled)(42)) - def test_nocopy_bytes(self): - if self.protocol < 3: - pytest.skip("test_nocopy_bytes requires protocol 3 or more") - sink = CountingByteSink() - biggish_data_bytes = b'0' * int(2e8) # 200 MB - biggish_data_view = memoryview(biggish_data_bytes) - for biggish_data in [biggish_data_bytes, biggish_data_view]: - pickler = cloudpickle.CloudPickler(sink, protocol=self.protocol) + +class Protocol2CloudPickleTest(CloudPickleTest): + + protocol = 2 + + +@pytest.mark.skipif(sys.version_info[:2] < (3, 5), + reason="nocopy memoryview only supprted on Python 3.5+") +@pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="memoryview.c_contiguous is missing") +def test_nocopy_bytes(tmpdir): + tmpfile = str(tmpdir.join('biggish.pkl')) + size = int(2e8) # 200 MB + biggish_data_bytes = b'0' * size + biggish_data_view = memoryview(biggish_data_bytes) + for biggish_data in [biggish_data_bytes, biggish_data_view]: + with open(tmpfile, 'wb') as f: + pickler = cloudpickle.CloudPickler(f) with PeakMemoryMonitor() as monitor: pickler.dump(biggish_data) @@ -902,12 +912,23 @@ def test_nocopy_bytes(self): assert monitor.base_mem > len(biggish_data) assert (monitor.peak_mem - monitor.base_mem) < 100e6 - assert sink.written > len(biggish_data) - - -class Protocol2CloudPickleTest(CloudPickleTest): - - protocol = 2 + with open(tmpfile, 'rb') as f: + with PeakMemoryMonitor() as monitor: + reconstructed = cloudpickle.load(f) + + # Check that loading does not make a memory copy (it allocates) + # a single binary buffer + # XXX: the 'newly_allocated < 2 * size' check is too lax + newly_allocated = monitor.peak_mem - monitor.base_mem + assert size <= newly_allocated < 2 * size + + assert len(reconstructed) == len(biggish_data) + if biggish_data is biggish_data_bytes: + assert reconstructed == biggish_data_bytes + else: + assert reconstructed.readonly + assert reconstructed.format == biggish_data_view.format + assert reconstructed.tobytes() == biggish_data_bytes if __name__ == '__main__': diff --git a/tests/testutils.py b/tests/testutils.py index 818037fc4..26c3cfd41 100644 --- a/tests/testutils.py +++ b/tests/testutils.py @@ -157,14 +157,5 @@ def __exit__(self, exc_type, exc_value, tb): return True -class CountingByteSink(object): - - def __init__(self): - self.written = 0 - - def write(self, data): - self.written += len(data) - - if __name__ == '__main__': pickle_echo() From 5cfe1e301c993ac7a587146cff697c549765af29 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Tue, 5 Dec 2017 20:04:37 +0100 Subject: [PATCH 09/31] test_nocopy_readonly_bytes works on Py34 --- tests/cloudpickle_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 11ad59c90..f65b986a5 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -891,11 +891,11 @@ class Protocol2CloudPickleTest(CloudPickleTest): protocol = 2 -@pytest.mark.skipif(sys.version_info[:2] < (3, 5), - reason="nocopy memoryview only supprted on Python 3.5+") +@pytest.mark.skipif(sys.version_info[:2] < (3, 4), + reason="nocopy memoryview only supported on Python 3.4+") @pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason="memoryview.c_contiguous is missing") -def test_nocopy_bytes(tmpdir): +def test_nocopy_readonly_bytes(tmpdir): tmpfile = str(tmpdir.join('biggish.pkl')) size = int(2e8) # 200 MB biggish_data_bytes = b'0' * size From 070d2bf8ee39c1398062cfa4ccefa643bc073b1d Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Tue, 5 Dec 2017 22:47:43 +0100 Subject: [PATCH 10/31] More precise memory measurements and more tolerant check --- tests/cloudpickle_test.py | 2 +- tests/testutils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index f65b986a5..6d4872923 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -920,7 +920,7 @@ def test_nocopy_readonly_bytes(tmpdir): # a single binary buffer # XXX: the 'newly_allocated < 2 * size' check is too lax newly_allocated = monitor.peak_mem - monitor.base_mem - assert size <= newly_allocated < 2 * size + assert 0.9 * size < newly_allocated < 2 * size assert len(reconstructed) == len(biggish_data) if biggish_data is biggish_data_bytes: diff --git a/tests/testutils.py b/tests/testutils.py index 26c3cfd41..aa1e4d203 100644 --- a/tests/testutils.py +++ b/tests/testutils.py @@ -113,7 +113,7 @@ def assert_run_python_script(source_code, timeout=5): os.unlink(source_file) -def monitor_worker(pid, queue, stop_event, delay=0.05): +def monitor_worker(pid, queue, stop_event, delay=0.010): import psutil p = psutil.Process(pid) peak = 0 From 5437bf5d6f47812e24f6899b6ef3a8cd49228e29 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Wed, 6 Dec 2017 10:25:45 +0100 Subject: [PATCH 11/31] Fix segfault by missing reference + wrong nbytes measurement --- cloudpickle/cloudpickle.py | 3 ++- tests/cloudpickle_test.py | 54 +++++++++++++++++++++++++++++--------- tests/testutils.py | 1 + 3 files changed, 45 insertions(+), 13 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 9c599edb7..00373752e 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -264,6 +264,7 @@ def _memoryview_from_bytes(data, format, readonly): buffer = ctypes.cast(data, ctypes.POINTER(ctypes.c_char)) addr = ctypes.addressof(buffer.contents) array = (ctypes.c_char * len(data)).from_address(addr) + array._base = data # keep a reference to bytes obj to avoid early GC view = memoryview(array) else: # A memoryview of a bytes object is readonly by default. @@ -375,7 +376,7 @@ def save_bytes(self, obj, skip_memoize=False): self.save_reduce(codecs.encode, (str(obj, 'latin1'), 'latin1'), obj=obj) return - n = len(obj) + n = getattr(obj, 'nbytes', len(obj)) if n <= 0xff: self.write(pickle.SHORT_BINBYTES + pack(" 0xffffffff and self.proto >= 4: diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 6d4872923..1ed70f4c7 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -902,15 +902,14 @@ def test_nocopy_readonly_bytes(tmpdir): biggish_data_view = memoryview(biggish_data_bytes) for biggish_data in [biggish_data_bytes, biggish_data_view]: with open(tmpfile, 'wb') as f: - pickler = cloudpickle.CloudPickler(f) with PeakMemoryMonitor() as monitor: - pickler.dump(biggish_data) + cloudpickle.dump(biggish_data, f) - # Check that temporary datastructures used when dumping are no - # larger than 100 MB which is much smaller than the bytes to be - # pickled. - assert monitor.base_mem > len(biggish_data) - assert (monitor.peak_mem - monitor.base_mem) < 100e6 + # Check that temporary datastructures used when dumping are no + # larger than 100 MB which is much smaller than the bytes to be + # pickled. + assert monitor.base_mem > size + assert monitor.newly_allocated < 100e6 with open(tmpfile, 'rb') as f: with PeakMemoryMonitor() as monitor: @@ -919,10 +918,9 @@ def test_nocopy_readonly_bytes(tmpdir): # Check that loading does not make a memory copy (it allocates) # a single binary buffer # XXX: the 'newly_allocated < 2 * size' check is too lax - newly_allocated = monitor.peak_mem - monitor.base_mem - assert 0.9 * size < newly_allocated < 2 * size + assert 0.9 * size < monitor.newly_allocated < 2 * size - assert len(reconstructed) == len(biggish_data) + assert len(reconstructed) == size if biggish_data is biggish_data_bytes: assert reconstructed == biggish_data_bytes else: @@ -931,5 +929,37 @@ def test_nocopy_readonly_bytes(tmpdir): assert reconstructed.tobytes() == biggish_data_bytes -if __name__ == '__main__': - unittest.main() +@pytest.mark.skipif(sys.version_info[:2] < (3, 5), + reason="nocopy writable memoryview only supported on " + "Python 3.5+") +@pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="memoryview.c_contiguous is missing") +def test_nocopy_writable_memoryview(tmpdir): + tmpfile = str(tmpdir.join('biggish.pkl')) + size = int(2e8) # 200 MB + biggish_array = array.array('l', range(size // 8)) + biggish_array_view = memoryview(biggish_array) + with open(tmpfile, 'wb') as f: + with PeakMemoryMonitor() as monitor: + cloudpickle.dump(biggish_array_view, f) + + # Check that temporary datastructures used when dumping are no + # larger than 100 MB which is much smaller than the bytes to be + # pickled. + assert monitor.base_mem > size + assert monitor.newly_allocated < 100e6 + + with open(tmpfile, 'rb') as f: + with PeakMemoryMonitor() as monitor: + reconstructed = cloudpickle.load(f) + + # Check that loading does not make a memory copy (it allocates) + # a single binary buffer + # XXX: the 'newly_allocated < 2 * size' check is too lax + assert 0.9 * size < monitor.newly_allocated < 2 * size + + assert reconstructed.nbytes == size + assert not reconstructed.readonly + assert reconstructed.format == biggish_array_view.format + for a, b in zip(reconstructed, range(size // 8)): + assert a == b diff --git a/tests/testutils.py b/tests/testutils.py index aa1e4d203..306bd5bd5 100644 --- a/tests/testutils.py +++ b/tests/testutils.py @@ -154,6 +154,7 @@ def __exit__(self, exc_type, exc_value, tb): return False else: self.peak_mem = self.queue.get() + self.newly_allocated = self.peak_mem - self.base_mem return True From 224a548900ed33b28647032c97aefbc541fc8a92 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Wed, 6 Dec 2017 14:17:37 +0100 Subject: [PATCH 12/31] tighter memory tests --- tests/cloudpickle_test.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 1ed70f4c7..5194904a6 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -897,6 +897,7 @@ class Protocol2CloudPickleTest(CloudPickleTest): reason="memoryview.c_contiguous is missing") def test_nocopy_readonly_bytes(tmpdir): tmpfile = str(tmpdir.join('biggish.pkl')) + mem_tol = int(5e7) # 50 MB size = int(2e8) # 200 MB biggish_data_bytes = b'0' * size biggish_data_view = memoryview(biggish_data_bytes) @@ -909,16 +910,18 @@ def test_nocopy_readonly_bytes(tmpdir): # larger than 100 MB which is much smaller than the bytes to be # pickled. assert monitor.base_mem > size - assert monitor.newly_allocated < 100e6 + assert monitor.newly_allocated < mem_tol with open(tmpfile, 'rb') as f: with PeakMemoryMonitor() as monitor: - reconstructed = cloudpickle.load(f) + # C-based pickle.load allocates a temporary variable on Python + # 3.5 and 3.6 while the Python-based pickle._load + # implementation does not have this problem + reconstructed = pickle._load(f) # Check that loading does not make a memory copy (it allocates) # a single binary buffer - # XXX: the 'newly_allocated < 2 * size' check is too lax - assert 0.9 * size < monitor.newly_allocated < 2 * size + assert size - mem_tol < monitor.newly_allocated < size + mem_tol assert len(reconstructed) == size if biggish_data is biggish_data_bytes: @@ -936,6 +939,7 @@ def test_nocopy_readonly_bytes(tmpdir): reason="memoryview.c_contiguous is missing") def test_nocopy_writable_memoryview(tmpdir): tmpfile = str(tmpdir.join('biggish.pkl')) + mem_tol = int(5e7) # 50 MB size = int(2e8) # 200 MB biggish_array = array.array('l', range(size // 8)) biggish_array_view = memoryview(biggish_array) @@ -947,16 +951,18 @@ def test_nocopy_writable_memoryview(tmpdir): # larger than 100 MB which is much smaller than the bytes to be # pickled. assert monitor.base_mem > size - assert monitor.newly_allocated < 100e6 + assert monitor.newly_allocated < mem_tol with open(tmpfile, 'rb') as f: with PeakMemoryMonitor() as monitor: - reconstructed = cloudpickle.load(f) + # C-based pickle.load allocates a temporary variable on Python 3.5 + # and 3.6 while the Python-based pickle._load implementation does + # not have this problem + reconstructed = pickle._load(f) # Check that loading does not make a memory copy (it allocates) # a single binary buffer - # XXX: the 'newly_allocated < 2 * size' check is too lax - assert 0.9 * size < monitor.newly_allocated < 2 * size + assert size - mem_tol < monitor.newly_allocated < size + mem_tol assert reconstructed.nbytes == size assert not reconstructed.readonly From ec85e7565f62d8810999e472295657e5f7f6c0ef Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Wed, 6 Dec 2017 15:05:49 +0100 Subject: [PATCH 13/31] Try to make memory checks more deterministic on travis --- tests/cloudpickle_test.py | 9 +++++---- tests/testutils.py | 14 ++++++++++---- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 5194904a6..bfc667784 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -898,7 +898,7 @@ class Protocol2CloudPickleTest(CloudPickleTest): def test_nocopy_readonly_bytes(tmpdir): tmpfile = str(tmpdir.join('biggish.pkl')) mem_tol = int(5e7) # 50 MB - size = int(2e8) # 200 MB + size = int(5e8) # 500 MB biggish_data_bytes = b'0' * size biggish_data_view = memoryview(biggish_data_bytes) for biggish_data in [biggish_data_bytes, biggish_data_view]: @@ -940,9 +940,11 @@ def test_nocopy_readonly_bytes(tmpdir): def test_nocopy_writable_memoryview(tmpdir): tmpfile = str(tmpdir.join('biggish.pkl')) mem_tol = int(5e7) # 50 MB - size = int(2e8) # 200 MB + size = int(5e8) # 500 MB biggish_array = array.array('l', range(size // 8)) biggish_array_view = memoryview(biggish_array) + assert not biggish_array_view.readonly + with open(tmpfile, 'wb') as f: with PeakMemoryMonitor() as monitor: cloudpickle.dump(biggish_array_view, f) @@ -967,5 +969,4 @@ def test_nocopy_writable_memoryview(tmpdir): assert reconstructed.nbytes == size assert not reconstructed.readonly assert reconstructed.format == biggish_array_view.format - for a, b in zip(reconstructed, range(size // 8)): - assert a == b + assert reconstructed == biggish_array_view diff --git a/tests/testutils.py b/tests/testutils.py index 306bd5bd5..7fcfdaa0c 100644 --- a/tests/testutils.py +++ b/tests/testutils.py @@ -113,7 +113,7 @@ def assert_run_python_script(source_code, timeout=5): os.unlink(source_file) -def monitor_worker(pid, queue, stop_event, delay=0.010): +def monitor_worker(pid, queue, started_event, stop_event, delay=0.010): import psutil p = psutil.Process(pid) peak = 0 @@ -124,6 +124,9 @@ def make_measurement(peak): peak = mem return peak + peak = make_measurement(peak) + started_event.set() + # Make measurements every 'delay' seconds until we receive the stop event: while not stop_event.wait(timeout=delay): peak = make_measurement(peak) @@ -140,11 +143,14 @@ def __enter__(self): psutil = pytest.importorskip("psutil") pid = os.getpid() gc.collect() - self.base_mem = psutil.Process(pid).memory_info().rss self.queue = q = mp.Queue() - self.stop_event = e = mp.Event() - self.worker = mp.Process(target=monitor_worker, args=(pid, q, e)) + e_started = mp.Event() + self.stop_event = e_stop = mp.Event() + self.worker = mp.Process(target=monitor_worker, + args=(pid, q, e_started, e_stop)) self.worker.start() + e_started.wait() + self.base_mem = psutil.Process(pid).memory_info().rss return self def __exit__(self, exc_type, exc_value, tb): From 5185527003e2edde16e579b8957efc01573db906 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Wed, 6 Dec 2017 18:08:59 +0100 Subject: [PATCH 14/31] nocopy numpy arrays --- dev-requirements.txt | 3 ++ tests/cloudpickle_test.py | 67 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/dev-requirements.txt b/dev-requirements.txt index 2c267805d..a991e676f 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -5,3 +5,6 @@ mock psutil # Code coverage uploader for Travis: codecov + +# nocopy tests with pydata libraries +numpy diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index bfc667784..e50a5e60a 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -970,3 +970,70 @@ def test_nocopy_writable_memoryview(tmpdir): assert not reconstructed.readonly assert reconstructed.format == biggish_array_view.format assert reconstructed == biggish_array_view + + +@pytest.mark.skipif(sys.version_info[:2] < (3, 5), + reason="nocopy writable memoryview only supported on " + "Python 3.5+") +@pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="memoryview.c_contiguous is missing") +def test_nocopy_numpy_array(): + np = pytest.importorskip("numpy") + + shape = (int(1e5), 1000) + data = np.arange(np.prod(shape)).reshape(shape) + mem_tol = int(5e7) # 50 MB + size = data.nbytes # 800 MB + + def array_builder(buffer, dtype, shape, strides): + return np.lib.stride_tricks.as_strided( + np.frombuffer(buffer, dtype), shape=shape, strides=strides) + + def reduce_ndarray(a): + """Memoryview based reducer for numpy arrays""" + return array_builder, (memoryview(a), a.dtype, a.shape, a.strides) + + class ChunksAppender: + + def __init__(self): + self.raw_chunks = [] + + def write(self, data): + # Append reference to raw chunks without triggering any memory + # copy. The bytes will be consumed in a delayed manner after the + # end of the pickling process by the call to materialize. + self.raw_chunks.append(data) + + def materialize(self): + # Concatenate all memoryview and bytes chunks into a single + # bytes object make many memory copies along the way. + return b"".join([c.tobytes() if hasattr(c, 'tobytes') else c + for c in self.raw_chunks]) + + appender = ChunksAppender() + pickler = cloudpickle.CloudPickler(appender) + pickler.dispatch_table = pickle.dispatch_table.copy() + pickler.dispatch_table[np.ndarray] = reduce_ndarray + + # Check that pickling does not make any memory copy of the large data + # buffer of the pandas dataframe: + with PeakMemoryMonitor() as monitor: + pickler.dump(data) + + assert monitor.newly_allocated < mem_tol + + pickled = appender.materialize() + assert size - mem_tol < len(pickled) < size + mem_tol + + with PeakMemoryMonitor() as monitor: + reconstructed_array = pickle._loads(pickled) + + # Check that loading does not make a memory copy (it allocates) + # a single binary buffer + assert size - mem_tol < monitor.newly_allocated < size + mem_tol + np.testing.assert_array_equal(data, reconstructed_array) + + # Reconstructed array is writable + reconstructed_array[:] = 1 + data[:] = 2 + assert data[0, 0] != reconstructed_array[0, 0] From d0ecba6e2e1388569e77cced7f7403d62ddd02ac Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Thu, 7 Dec 2017 22:51:13 +0100 Subject: [PATCH 15/31] Preserve shape at the memoryview level when possible --- cloudpickle/cloudpickle.py | 5 ++-- tests/cloudpickle_test.py | 52 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 00373752e..6087b5192 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -252,7 +252,7 @@ def _walk_global_ops(code): yield op, instr.arg -def _memoryview_from_bytes(data, format, readonly): +def _memoryview_from_bytes(data, format, readonly, shape): if not readonly: # Forcibly render the recently unpickled bytes buffer writable: # this is a violation of the immutability of a Python bytes object but @@ -270,7 +270,7 @@ def _memoryview_from_bytes(data, format, readonly): # A memoryview of a bytes object is readonly by default. view = memoryview(data) if PY_MAJOR_MINOR >= (3, 5) or (PY_MAJOR_MINOR == (3, 4) and readonly): - return view.cast('B').cast(format) + return view.cast('B').cast(format, shape) else: # Python 2.7 does not support casting and Python 3.4 has a bug when # casting buffers from ctypes: # https://bugs.python.org/issue19803 @@ -405,6 +405,7 @@ def save_memoryview(self, obj): self.save_bytes(obj, skip_memoize=True) self.save(obj.format) self.save(obj.readonly) + self.save(obj.shape) self.write(pickle.TUPLE) self.write(pickle.REDUCE) self.memoize(obj) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index e50a5e60a..6b2a48b73 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -173,6 +173,58 @@ def test_sliced_and_non_contiguous_memoryview(self): self.assertEqual(pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()) + def test_complex_memoryviews(self): + # Use numpy to generate complex memory layouts to be able to test the + # preservation of all memoryview attributes. Note that cloudpickle + # does not guarantee nocopy semantics for all of those cases but + # it should reconstruct the same memory layout in any-case. + # np = pytest.importorskip("numpy") + import numpy as np + arrays = [ + np.arange(12).reshape(3, 4), + np.arange(12).reshape(3, 4).astype(np.float32), + ] + if cloudpickle.PY3: + # There is a bug when calling .tobytes() on non-c-contiguous numpy + # memoryviews under Python 2.7. + arrays += [ + np.asfortranarray(np.arange(12).reshape(3, 4)), + np.arange(12).reshape(3, 4)[:, 1:-1], + np.arange(12).reshape(3, 4)[1:-1, :], + np.asfortranarray(np.arange(12).reshape(3, 4))[:, 1:-1], + np.asfortranarray(np.arange(12).reshape(3, 4))[1:-1, :], + ] + readonly_arrays = [] + for a in arrays: + a = a.copy() + a.flags.writeable = False + readonly_arrays.append(a) + arrays += readonly_arrays + + for a in arrays: + readonly = not a.flags.writeable + original_view = memoryview(a) + cloned_view = pickle_depickle(original_view, + protocol=self.protocol) + assert original_view.readonly == readonly + assert original_view.readonly == cloned_view.readonly + + if (cloudpickle.PY_MAJOR_MINOR > (3, 4) + or (cloudpickle.PY_MAJOR_MINOR == (3, 4) and readonly)): + # Python 2.7 does not support casting memoryviews. + # Python 3.4 has a bug that prevents casting when the buffer + # is backed by a ctypes array. + assert original_view.format == cloned_view.format + assert original_view.shape == cloned_view.shape + + assert original_view.tobytes() == cloned_view.tobytes() + + if (cloudpickle.PY_MAJOR_MINOR >= (3, 4) + and platform.python_implementation() != 'PyPy'): + # Cloned view is always C contiguous irrespective of + # the original view contiguity and layout (C vs Fortran). + assert cloned_view.c_contiguous + def test_lambda(self): self.assertEqual(pickle_depickle(lambda: 1)(), 1) From 4a46a98066b025c8f890e129b3e37173f3c52321 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Fri, 8 Dec 2017 00:25:57 +0100 Subject: [PATCH 16/31] Fix support for transposed numpy arrays: nocopy pandas and scipy! --- dev-requirements.txt | 2 + tests/cloudpickle_test.py | 79 ++++++++++++++++++++++++--------------- 2 files changed, 51 insertions(+), 30 deletions(-) diff --git a/dev-requirements.txt b/dev-requirements.txt index a991e676f..5a25b6e6e 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -8,3 +8,5 @@ codecov # nocopy tests with pydata libraries numpy +pandas; platform_python_implementation != "PyPy" +scipy; platform_python_implementation != "PyPy" diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 6b2a48b73..5b7ac0ec0 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -1029,21 +1029,39 @@ def test_nocopy_writable_memoryview(tmpdir): "Python 3.5+") @pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason="memoryview.c_contiguous is missing") -def test_nocopy_numpy_array(): +def test_nocopy_pydata(): np = pytest.importorskip("numpy") + pd = pytest.importorskip("pandas") + sp = pytest.importorskip("scipy.sparse") + mem_tol = 30e6 shape = (int(1e5), 1000) data = np.arange(np.prod(shape)).reshape(shape) - mem_tol = int(5e7) # 50 MB - size = data.nbytes # 800 MB - - def array_builder(buffer, dtype, shape, strides): - return np.lib.stride_tricks.as_strided( - np.frombuffer(buffer, dtype), shape=shape, strides=strides) + data_with_zeros = data.copy() + data_with_zeros[::2] = 0 + csr = sp.csr_matrix(data_with_zeros) + + large_pydata_objects = [ + (data, data.nbytes), + (data.T, data.nbytes), + (pd.DataFrame(data), data.nbytes), + (csr, csr.indptr.nbytes + csr.indices.nbytes + csr.data.nbytes), + ] + + def array_builder(buffer, dtype, shape, transpose): + a = np.lib.stride_tricks.as_strided( + np.frombuffer(buffer, dtype), shape=shape) + return a.T if transpose else a def reduce_ndarray(a): """Memoryview based reducer for numpy arrays""" - return array_builder, (memoryview(a), a.dtype, a.shape, a.strides) + if a.flags.f_contiguous: + # convert to c-contiguous to benefit from nocopy semantics. + a = a.T + transpose = True + else: + transpose = False + return array_builder, (memoryview(a), a.dtype, a.shape, transpose) class ChunksAppender: @@ -1062,30 +1080,31 @@ def materialize(self): return b"".join([c.tobytes() if hasattr(c, 'tobytes') else c for c in self.raw_chunks]) - appender = ChunksAppender() - pickler = cloudpickle.CloudPickler(appender) - pickler.dispatch_table = pickle.dispatch_table.copy() - pickler.dispatch_table[np.ndarray] = reduce_ndarray - - # Check that pickling does not make any memory copy of the large data - # buffer of the pandas dataframe: - with PeakMemoryMonitor() as monitor: - pickler.dump(data) + for obj, size in large_pydata_objects: + appender = ChunksAppender() + pickler = cloudpickle.CloudPickler(appender) + pickler.dispatch_table = pickle.dispatch_table.copy() + pickler.dispatch_table[np.ndarray] = reduce_ndarray - assert monitor.newly_allocated < mem_tol + # Check that pickling does not make any memory copy of the large data + # buffer of the pandas dataframe: + with PeakMemoryMonitor() as monitor: + pickler.dump(obj) - pickled = appender.materialize() - assert size - mem_tol < len(pickled) < size + mem_tol + assert monitor.newly_allocated < mem_tol - with PeakMemoryMonitor() as monitor: - reconstructed_array = pickle._loads(pickled) + pickled = appender.materialize() + assert size - mem_tol < len(pickled) < size + mem_tol - # Check that loading does not make a memory copy (it allocates) - # a single binary buffer - assert size - mem_tol < monitor.newly_allocated < size + mem_tol - np.testing.assert_array_equal(data, reconstructed_array) + with PeakMemoryMonitor() as monitor: + cloned_obj = pickle._loads(pickled) - # Reconstructed array is writable - reconstructed_array[:] = 1 - data[:] = 2 - assert data[0, 0] != reconstructed_array[0, 0] + # Check that loading does not make a memory copy (it allocates) + # a single binary buffer + assert size - mem_tol < monitor.newly_allocated < size + mem_tol + if sp.issparse(obj): + np.testing.assert_array_equal(obj.toarray(), cloned_obj.toarray()) + elif isinstance(obj, pd.DataFrame): + np.testing.assert_array_equal(obj.values, cloned_obj.values) + else: + np.testing.assert_array_equal(obj, cloned_obj) From 52309aea42c15e3e26cba6c6e9a8768e2087f9f8 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Fri, 8 Dec 2017 00:51:39 +0100 Subject: [PATCH 17/31] skip broken test with old PyPy and make test_nocopy_pydata faster --- tests/cloudpickle_test.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 5b7ac0ec0..567bceb30 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -173,6 +173,8 @@ def test_sliced_and_non_contiguous_memoryview(self): self.assertEqual(pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()) + @pytest.mark.skipif(platform.python_implementation() == 'PyPy', + reason="cast is broken on PyPy < 5.9.0") def test_complex_memoryviews(self): # Use numpy to generate complex memory layouts to be able to test the # preservation of all memoryview attributes. Note that cloudpickle @@ -1034,15 +1036,15 @@ def test_nocopy_pydata(): pd = pytest.importorskip("pandas") sp = pytest.importorskip("scipy.sparse") - mem_tol = 30e6 - shape = (int(1e5), 1000) + mem_tol = 50e6 # 50 MB + shape = (int(2e5), 100) data = np.arange(np.prod(shape)).reshape(shape) data_with_zeros = data.copy() data_with_zeros[::2] = 0 csr = sp.csr_matrix(data_with_zeros) large_pydata_objects = [ - (data, data.nbytes), + (data, data.nbytes), # 160 MB (data.T, data.nbytes), (pd.DataFrame(data), data.nbytes), (csr, csr.indptr.nbytes + csr.indices.nbytes + csr.data.nbytes), From 5c49c519fe0eee8979abecb80cba3ef4725b6ee6 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Fri, 8 Dec 2017 01:04:12 +0100 Subject: [PATCH 18/31] do not build pandas from source on travis for Python 3.4 --- dev-requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dev-requirements.txt b/dev-requirements.txt index 5a25b6e6e..77bcf06c2 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -8,5 +8,5 @@ codecov # nocopy tests with pydata libraries numpy -pandas; platform_python_implementation != "PyPy" -scipy; platform_python_implementation != "PyPy" +pandas; platform_python_implementation != "PyPy" and python_version >= '3.5' +scipy; platform_python_implementation != "PyPy" and python_version >= '3.5' From fca7ec7242bb976a1931107bc722c218167a3d45 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Fri, 8 Dec 2017 19:33:14 +0100 Subject: [PATCH 19/31] Use reference counting to ensure safe mutability of bytes buffer --- cloudpickle/cloudpickle.py | 85 ++++++++++++++++++++++++++++++-------- tests/cloudpickle_test.py | 5 +-- 2 files changed, 70 insertions(+), 20 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 6087b5192..6b4196528 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -252,20 +252,65 @@ def _walk_global_ops(code): yield op, instr.arg -def _memoryview_from_bytes(data, format, readonly, shape): +def _memoryview_from_bytes(data_holder, format, readonly, shape): + """Build a memoryview from raw bytes read from the pickle stream + + This function tries its best not to allocate any extra memory when not + necessary. + + The actual data is provided in a data_holder which is expected to be a + single item list holding the actual bytes object. This makes it easier + to use sys.getrefcount to detect whether or not the bytes are referenced + elsewhere or not. + + If readonly is False and the backing bytes in data_holder are referenced + from other objects, then the bytes contents are copied into a newly + allocated mutable buffer. Otherwise the memory allocated for the bytes + object is directly reused by the new memoryview. + + Python 2 memoryviews doe not support being cast so that the + format and shape parameters are ignored. + + Reference counting cannot be used in PyPy to detect if it is safe to mutate + the bytes object. If readonly is False, a new mutable buffer is always + allocated. + """ + # If the following call to sys.getrefcount returns 2 it means that there is + # one reference from data_holder and one from the temporary arguments + # datastructure of the sys.getrefcount call. It is therefore safe to reuse + # the memory buffer of the bytes object as writeable buffer to back the + # memoryview: this buffer is no longer unreachable from anywhere else. + if hasattr(sys, 'getrefcount'): + safe_to_mutate = sys.getrefcount(data_holder[0]) <= 2 + else: + # PyPy does not use reference counting. Is there a way to detect if + # a bytes objects can be mutated safely? + safe_to_mutate = False + data = data_holder[0] + del data_holder[:] if not readonly: - # Forcibly render the recently unpickled bytes buffer writable: - # this is a violation of the immutability of a Python bytes object but - # this should be safe because: - # - data is a temporary variable that has just been allocated from - # reading from the pickle stream and will never be used outside of - # the scope of this reducer. - # - bytes objects are not subject to interning. - buffer = ctypes.cast(data, ctypes.POINTER(ctypes.c_char)) - addr = ctypes.addressof(buffer.contents) - array = (ctypes.c_char * len(data)).from_address(addr) - array._base = data # keep a reference to bytes obj to avoid early GC - view = memoryview(array) + if safe_to_mutate: + buffer = ctypes.cast(data, ctypes.POINTER(ctypes.c_char)) + addr = ctypes.addressof(buffer.contents) + array = (ctypes.c_char * len(data)).from_address(addr) + # Store a reference to the backing bytes object to make GC work + # correctly. We hide the object itself in a closure to hide + # it from the unsuspecting users. + + @property + def _hidden_buffer_ref(): + raise AttributeError("Access to buffer with id %d is unsafe" + % id(data)) + array._hidden_buffer_ref = _hidden_buffer_ref + + view = memoryview(array) + else: + # This buffer is referenced by external objects: for instance empty + # and single bytes objects are interned under Python 3. Longer + # bytes objects in Python (from the str type) can also be interned. + # Force a copy into a new mutable buffer to avoid a violation of + # the unmutability of bytes. + view = memoryview(bytearray(data)) else: # A memoryview of a bytes object is readonly by default. view = memoryview(data) @@ -390,19 +435,25 @@ def save_bytes(self, obj, skip_memoize=False): dispatch[bytes] = save_bytes def save_memoryview(self, obj): - n = len(obj) + # Python 2 views doe not have nbytes + n = getattr(obj, 'nbytes', len(obj)) self.save(_memoryview_from_bytes) self.write(pickle.MARK) - # PyPy3 does not implement the 'c_contiguous' attribute at this time. + # wrap bytes buffer in a singleton list that is expected to hold + # the only reference to the bytes obj when unpickling. + self.write(pickle.MARK) c_contiguous = getattr(obj, 'c_contiguous', False) if n <= 0xff or self.proto < 3 or not c_contiguous: - # Make a contiguous copy prior as a bytes object prior to - # serialization. + # Make a contiguous copy as a bytes object prior to serialization. + # TODO: find a way to disable memoization in this case. Memoization + # will prevent _memoryview_from_bytes to ensure safe mutability + # via reference counting. self.save(obj.tobytes()) else: # Large contiguous views can benefit from nocopy semantics with # recent versions of the pickle protocol. self.save_bytes(obj, skip_memoize=True) + self.write(pickle.LIST) # data_holder self.save(obj.format) self.save(obj.readonly) self.save(obj.shape) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 567bceb30..dae0a6fef 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -180,11 +180,10 @@ def test_complex_memoryviews(self): # preservation of all memoryview attributes. Note that cloudpickle # does not guarantee nocopy semantics for all of those cases but # it should reconstruct the same memory layout in any-case. - # np = pytest.importorskip("numpy") - import numpy as np + np = pytest.importorskip("numpy") arrays = [ np.arange(12).reshape(3, 4), - np.arange(12).reshape(3, 4).astype(np.float32), + np.arange(12000).reshape(3000, 4).astype(np.float32), ] if cloudpickle.PY3: # There is a bug when calling .tobytes() on non-c-contiguous numpy From f3a4560846202ae8300e930b16faf9e253fa660b Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 11:26:14 +0100 Subject: [PATCH 20/31] Safely mutate non-interned Python 2 strings --- cloudpickle/cloudpickle.py | 38 +++++++++++++++++++++++++++++--------- dev-requirements.txt | 2 +- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 6b4196528..c34fd8a32 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -252,7 +252,21 @@ def _walk_global_ops(code): yield op, instr.arg -def _memoryview_from_bytes(data_holder, format, readonly, shape): +class _Py2StrStruct(ctypes.Structure): + _fields_ = [ + ("ob_refcnt", ctypes.c_long), + ("ob_type", ctypes.c_void_p), + ("ob_size", ctypes.c_ulong), + ('ob_shash', ctypes.c_long), + ('ob_sstate', ctypes.c_int), + ('ob_sval', ctypes.c_char), + ] + + def is_interned(self): + return self.ob_sstate != 0 + + +def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): """Build a memoryview from raw bytes read from the pickle stream This function tries its best not to allocate any extra memory when not @@ -274,6 +288,9 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape): Reference counting cannot be used in PyPy to detect if it is safe to mutate the bytes object. If readonly is False, a new mutable buffer is always allocated. + + **kwargs are left ignored. Those are used to add flexibility to implement + backward compatible changes in future versions of cloudpickle. """ # If the following call to sys.getrefcount returns 2 it means that there is # one reference from data_holder and one from the temporary arguments @@ -287,9 +304,15 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape): # a bytes objects can be mutated safely? safe_to_mutate = False data = data_holder[0] + if safe_to_mutate and isinstance(data, str): + # Python 2 str instances are bytes that can be interned, make sure + # that this is not the case. + safe_to_mutate = not _Py2StrStruct.from_address(id(data)).is_interned() del data_holder[:] if not readonly: - if safe_to_mutate: + # Python 3.4 implementation of memoryviews backed by ctypes buffers + # has a bug: # https://bugs.python.org/issue19803 + if safe_to_mutate and PY_MAJOR_MINOR != (3, 4): buffer = ctypes.cast(data, ctypes.POINTER(ctypes.c_char)) addr = ctypes.addressof(buffer.contents) array = (ctypes.c_char * len(data)).from_address(addr) @@ -297,12 +320,10 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape): # correctly. We hide the object itself in a closure to hide # it from the unsuspecting users. - @property def _hidden_buffer_ref(): - raise AttributeError("Access to buffer with id %d is unsafe" - % id(data)) + raise TypeError("Access to mutable buffer with id %d is unsafe" + % id(data)) array._hidden_buffer_ref = _hidden_buffer_ref - view = memoryview(array) else: # This buffer is referenced by external objects: for instance empty @@ -314,11 +335,10 @@ def _hidden_buffer_ref(): else: # A memoryview of a bytes object is readonly by default. view = memoryview(data) - if PY_MAJOR_MINOR >= (3, 5) or (PY_MAJOR_MINOR == (3, 4) and readonly): + if PY_MAJOR_MINOR >= (3, 4): return view.cast('B').cast(format, shape) else: - # Python 2.7 does not support casting and Python 3.4 has a bug when - # casting buffers from ctypes: # https://bugs.python.org/issue19803 + # Python 2.7 does not support casting. return view diff --git a/dev-requirements.txt b/dev-requirements.txt index 77bcf06c2..14b15c10c 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -8,5 +8,5 @@ codecov # nocopy tests with pydata libraries numpy -pandas; platform_python_implementation != "PyPy" and python_version >= '3.5' +pandas; platform_python_implementation != "PyPy" scipy; platform_python_implementation != "PyPy" and python_version >= '3.5' From dc3a8616f37d3a49c583aff1b8eec47b4eb74496 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 12:22:11 +0100 Subject: [PATCH 21/31] Add missing test file + protect safety of bytes singleton --- cloudpickle/cloudpickle.py | 5 +- tests/memoryview_test.py | 99 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 tests/memoryview_test.py diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index c34fd8a32..13f3f0538 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -297,8 +297,11 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): # datastructure of the sys.getrefcount call. It is therefore safe to reuse # the memory buffer of the bytes object as writeable buffer to back the # memoryview: this buffer is no longer unreachable from anywhere else. + # Note under Python 3, single byte bytes can be mapped to singletons + # which are not safe to mutate. if hasattr(sys, 'getrefcount'): - safe_to_mutate = sys.getrefcount(data_holder[0]) <= 2 + safe_to_mutate = (sys.getrefcount(data_holder[0]) <= 2 + and len(data_holder[0]) > 1) else: # PyPy does not use reference counting. Is there a way to detect if # a bytes objects can be mutated safely? diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py new file mode 100644 index 000000000..0cd7743ef --- /dev/null +++ b/tests/memoryview_test.py @@ -0,0 +1,99 @@ +import sys +from cloudpickle.cloudpickle import _memoryview_from_bytes +from cloudpickle.cloudpickle import _Py2StrStruct +import pytest + + +@pytest.mark.skipif(sys.version_info[:2] == (3, 4), + reason="https://bugs.python.org/issue19803") +def test_safe_mutable_bytes(): + if sys.version_info[0] >= 3: + buffer = bytes([1, 2, 3]) + else: + # Make the buffer large enough to avoid Python 2 string interning. + buffer = (u'0123' * 100000).encode('ascii') + buffer_id = id(buffer) + buffer_size = len(buffer) + buffer_holder = [buffer] + # Delete the local direct reference to the buffer + del buffer + + # There are no external reference to the bytes object in buffer_holder, + # the _memoryview_from_bytes function can safely reuse the memory + # allocated for the bytes object to expose it as a mutable buffer to back + # the memoryview. + view = _memoryview_from_bytes(buffer_holder, 'B', False, (buffer_size,)) + assert not view.readonly + assert len(buffer_holder) == 0 + + # CPython 2 and PyPy do not expose the obj attribute. + if hasattr(view, 'obj'): + # The last reference to the original bytes object is hold in a closure + # to discourage direct access by the user: + with pytest.raises(TypeError) as exc_info: + view.obj._hidden_buffer_ref() + msg = "Access to mutable buffer with id %d is unsafe" % buffer_id + assert exc_info.value.args[0] == msg + + # It's possible to mutate the content of the buffer + view[:] = b'\x00' * buffer_size + + +def test_never_mutate_singleton_bytes(): + for i in range(256): + buffer_holder = [bytes([i])] + view = _memoryview_from_bytes(buffer_holder, 'B', False, (1,)) + assert not view.readonly + if hasattr(view, 'obj'): + assert not hasattr(view.obj, '_hidden_buffer_ref') + + +def test_unsafe_mutable_bytes_with_external_references(): + buffer = u"\x01\x02\x03".encode('ascii') + buffer_holder = [buffer] + + # The local 'buffer' variable still holds a reference to the bytes object + # instance: _memoryview_from_bytes cannot safely reuse the same buffer. + # Instead new mutable memory is allocated to back the buffer. + view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) + assert not view.readonly + assert len(buffer_holder) == 0 + if hasattr(view, 'obj'): + # CPython 2 and PyPy does not expose the 'obj attribute'. + assert not hasattr(view.obj, '_hidden_buffer_ref') + + # Check that changing the content of the view does not change the content + # of original buffer: + view[:] = b'\x00\x00\x00' + assert buffer == b"\x01\x02\x03" + + +@pytest.mark.skipif(sys.version_info[0] != 2, + reason="Test relies on Python 2 str interning") +def test_py2_interned_string_detection(): + s1 = (lambda x: 'some python 2 ' + x.encode('ascii'))(u'string') + s2 = intern('some python 2 string') + s3 = intern('some python 2 string') + assert s1 == s2 + assert s1 is not s2 + assert s2 is s3 + assert not _Py2StrStruct.from_address(id(s1)).is_interned() + assert _Py2StrStruct.from_address(id(s2)).is_interned() + assert _Py2StrStruct.from_address(id(s3)).is_interned() + + +@pytest.mark.skipif(sys.version_info[0] != 2, + reason="Test relies on Python 2 str interning") +def test_unsafe_mutable_bytes_with_python_2_interning(): + buffer_holder = [intern(u"\x01\x02\x03".encode('ascii'))] + view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) + assert not view.readonly + assert len(buffer_holder) == 0 + + # Create a new interned buffer with the same original content + interned_buffer = intern(b"\x01\x02\x03") + + # Mutate the view pointing the to the original buffer + view[:] = b'\x00\x00\x00' + assert interned_buffer == b'\x01\x02\x03' + From f24fb627ec412a3ed081ad681d007aec0d649905 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 15:35:27 +0100 Subject: [PATCH 22/31] Extract _safe_to_mutate to improve testability --- cloudpickle/cloudpickle.py | 49 +++++++++++++++++++++++--------------- tests/memoryview_test.py | 40 ++++++++++++++++++++++++++----- 2 files changed, 64 insertions(+), 25 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 13f3f0538..e412054dd 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -52,6 +52,7 @@ import logging import opcode import operator +import platform import pickle from struct import pack import sys @@ -253,6 +254,7 @@ def _walk_global_ops(code): class _Py2StrStruct(ctypes.Structure): + """Map the memory layout of a CPython 2 str to access its interned state""" _fields_ = [ ("ob_refcnt", ctypes.c_long), ("ob_type", ctypes.c_void_p), @@ -266,6 +268,32 @@ def is_interned(self): return self.ob_sstate != 0 +def _safe_to_mutate(data_holder): + if platform.python_implementation() != 'CPython': + # sys.getrefcount and ob_sstate are not always available on other + # platforms (e.g. PyPy): better be conservative. + return False + + if len(data_holder[0]) <= 1: + # Under CPython 3, single byte bytes can be mapped to singletons which + # are not safe to mutate. + return False + + # If the following call to sys.getrefcount returns 2 it means that + # there is one reference from data_holder and one from the temporary + # arguments datastructure of the sys.getrefcount call. It is therefore + # safe to reuse the memory buffer of the bytes object as writeable + # buffer to back the memoryview: this buffer is no longer reachable + # from anywhere else. + safe_to_mutate = sys.getrefcount(data_holder[0]) <= 2 + data = data_holder[0] + if safe_to_mutate and isinstance(data, str): + # Python 2 str instances are bytes that can be interned, make sure + # that this is not the case. + safe_to_mutate = not _Py2StrStruct.from_address(id(data)).is_interned() + return safe_to_mutate + + def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): """Build a memoryview from raw bytes read from the pickle stream @@ -292,25 +320,8 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): **kwargs are left ignored. Those are used to add flexibility to implement backward compatible changes in future versions of cloudpickle. """ - # If the following call to sys.getrefcount returns 2 it means that there is - # one reference from data_holder and one from the temporary arguments - # datastructure of the sys.getrefcount call. It is therefore safe to reuse - # the memory buffer of the bytes object as writeable buffer to back the - # memoryview: this buffer is no longer unreachable from anywhere else. - # Note under Python 3, single byte bytes can be mapped to singletons - # which are not safe to mutate. - if hasattr(sys, 'getrefcount'): - safe_to_mutate = (sys.getrefcount(data_holder[0]) <= 2 - and len(data_holder[0]) > 1) - else: - # PyPy does not use reference counting. Is there a way to detect if - # a bytes objects can be mutated safely? - safe_to_mutate = False + safe_to_mutate = _safe_to_mutate(data_holder) data = data_holder[0] - if safe_to_mutate and isinstance(data, str): - # Python 2 str instances are bytes that can be interned, make sure - # that this is not the case. - safe_to_mutate = not _Py2StrStruct.from_address(id(data)).is_interned() del data_holder[:] if not readonly: # Python 3.4 implementation of memoryviews backed by ctypes buffers @@ -333,7 +344,7 @@ def _hidden_buffer_ref(): # and single bytes objects are interned under Python 3. Longer # bytes objects in Python (from the str type) can also be interned. # Force a copy into a new mutable buffer to avoid a violation of - # the unmutability of bytes. + # the imnmutability of bytes. view = memoryview(bytearray(data)) else: # A memoryview of a bytes object is readonly by default. diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py index 0cd7743ef..76168319b 100644 --- a/tests/memoryview_test.py +++ b/tests/memoryview_test.py @@ -1,4 +1,6 @@ import sys +import platform +from cloudpickle.cloudpickle import _safe_to_mutate from cloudpickle.cloudpickle import _memoryview_from_bytes from cloudpickle.cloudpickle import _Py2StrStruct import pytest @@ -22,6 +24,7 @@ def test_safe_mutable_bytes(): # the _memoryview_from_bytes function can safely reuse the memory # allocated for the bytes object to expose it as a mutable buffer to back # the memoryview. + assert _safe_to_mutate(buffer_holder) view = _memoryview_from_bytes(buffer_holder, 'B', False, (buffer_size,)) assert not view.readonly assert len(buffer_holder) == 0 @@ -41,7 +44,14 @@ def test_safe_mutable_bytes(): def test_never_mutate_singleton_bytes(): for i in range(256): - buffer_holder = [bytes([i])] + if sys.version_info[0] >= 3: + buffer_holder = [bytes([i])] + else: + buffer_holder = [chr(i)] + assert not _safe_to_mutate(buffer_holder) + + # In this case, a new read-write buffer is allocated to back the + # memoryview. view = _memoryview_from_bytes(buffer_holder, 'B', False, (1,)) assert not view.readonly if hasattr(view, 'obj'): @@ -54,7 +64,9 @@ def test_unsafe_mutable_bytes_with_external_references(): # The local 'buffer' variable still holds a reference to the bytes object # instance: _memoryview_from_bytes cannot safely reuse the same buffer. - # Instead new mutable memory is allocated to back the buffer. + assert not _safe_to_mutate(buffer_holder) + + # Instead new mutable memory is allocated to back the buffer: view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) assert not view.readonly assert len(buffer_holder) == 0 @@ -70,10 +82,15 @@ def test_unsafe_mutable_bytes_with_external_references(): @pytest.mark.skipif(sys.version_info[0] != 2, reason="Test relies on Python 2 str interning") +@pytest.mark.skipif(platform.python_implementation != 'CPython', + reason="Test requires access to ob_sstate field.") def test_py2_interned_string_detection(): - s1 = (lambda x: 'some python 2 ' + x.encode('ascii'))(u'string') - s2 = intern('some python 2 string') - s3 = intern('some python 2 string') + def process_str(original): + """Return non-interned version of original str object""" + return ' '.join(x for x in original.split(' ')) + s1 = process_str('some python 2 str') + s2 = intern('some python 2 str') + s3 = intern('some python 2 str') assert s1 == s2 assert s1 is not s2 assert s2 is s3 @@ -81,11 +98,23 @@ def test_py2_interned_string_detection(): assert _Py2StrStruct.from_address(id(s2)).is_interned() assert _Py2StrStruct.from_address(id(s3)).is_interned() + # Interned CPython str buffers are never safe to mutate even without + # external references. + buffer_holder = [intern(process_str('other python 2 str'))] + assert not _safe_to_mutate(buffer_holder) + + # Non-interned CPython str buffers without any external references are + # safe to mutate: + buffer_holder = [process_str('other python 2 str')] + assert _safe_to_mutate(buffer_holder) + @pytest.mark.skipif(sys.version_info[0] != 2, reason="Test relies on Python 2 str interning") def test_unsafe_mutable_bytes_with_python_2_interning(): buffer_holder = [intern(u"\x01\x02\x03".encode('ascii'))] + + assert not _safe_to_mutate(buffer_holder) view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) assert not view.readonly assert len(buffer_holder) == 0 @@ -96,4 +125,3 @@ def test_unsafe_mutable_bytes_with_python_2_interning(): # Mutate the view pointing the to the original buffer view[:] = b'\x00\x00\x00' assert interned_buffer == b'\x01\x02\x03' - From 02f21f522ba3eaff8b69be80d521e2b56f956317 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 15:41:04 +0100 Subject: [PATCH 23/31] wording --- cloudpickle/cloudpickle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index e412054dd..43aaa82f9 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -331,8 +331,8 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): addr = ctypes.addressof(buffer.contents) array = (ctypes.c_char * len(data)).from_address(addr) # Store a reference to the backing bytes object to make GC work - # correctly. We hide the object itself in a closure to hide - # it from the unsuspecting users. + # correctly. We hide the object itself in a closure to prevent + # unsuspecting users to access it. def _hidden_buffer_ref(): raise TypeError("Access to mutable buffer with id %d is unsafe" From 401fb2d7be27fc80db32b9779ad25199eada33d6 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 15:43:34 +0100 Subject: [PATCH 24/31] Small reorg, better wording. --- cloudpickle/cloudpickle.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 43aaa82f9..7dbab533e 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -323,7 +323,10 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): safe_to_mutate = _safe_to_mutate(data_holder) data = data_holder[0] del data_holder[:] - if not readonly: + if readonly: + # A memoryview of a bytes object is readonly by default. + view = memoryview(data) + else: # Python 3.4 implementation of memoryviews backed by ctypes buffers # has a bug: # https://bugs.python.org/issue19803 if safe_to_mutate and PY_MAJOR_MINOR != (3, 4): @@ -340,15 +343,13 @@ def _hidden_buffer_ref(): array._hidden_buffer_ref = _hidden_buffer_ref view = memoryview(array) else: - # This buffer is referenced by external objects: for instance empty - # and single bytes objects are interned under Python 3. Longer - # bytes objects in Python (from the str type) can also be interned. - # Force a copy into a new mutable buffer to avoid a violation of - # the imnmutability of bytes. + # This buffer can be referenced by external objects: for instance + # empty and single bytes objects are interned under Python 3. + # Longer bytes objects in Python (from the str type) can also be + # interned. Force a copy into a new mutable buffer to avoid a + # violation of the imnmutability of bytes. view = memoryview(bytearray(data)) - else: - # A memoryview of a bytes object is readonly by default. - view = memoryview(data) + if PY_MAJOR_MINOR >= (3, 4): return view.cast('B').cast(format, shape) else: From 4d198fbc4c899398988ec70180821cdc56559ad1 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 15:49:41 +0100 Subject: [PATCH 25/31] cosmit --- cloudpickle/cloudpickle.py | 5 +++-- tests/memoryview_test.py | 14 +++++++------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 7dbab533e..3972756e7 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -268,7 +268,8 @@ def is_interned(self): return self.ob_sstate != 0 -def _safe_to_mutate(data_holder): +def _is_safe_to_mutate(data_holder): + """Helper function, see _memoryview_from_bytes for details.""" if platform.python_implementation() != 'CPython': # sys.getrefcount and ob_sstate are not always available on other # platforms (e.g. PyPy): better be conservative. @@ -320,7 +321,7 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): **kwargs are left ignored. Those are used to add flexibility to implement backward compatible changes in future versions of cloudpickle. """ - safe_to_mutate = _safe_to_mutate(data_holder) + safe_to_mutate = _is_safe_to_mutate(data_holder) data = data_holder[0] del data_holder[:] if readonly: diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py index 76168319b..218e8c3a1 100644 --- a/tests/memoryview_test.py +++ b/tests/memoryview_test.py @@ -1,6 +1,6 @@ import sys import platform -from cloudpickle.cloudpickle import _safe_to_mutate +from cloudpickle.cloudpickle import _is_safe_to_mutate from cloudpickle.cloudpickle import _memoryview_from_bytes from cloudpickle.cloudpickle import _Py2StrStruct import pytest @@ -24,7 +24,7 @@ def test_safe_mutable_bytes(): # the _memoryview_from_bytes function can safely reuse the memory # allocated for the bytes object to expose it as a mutable buffer to back # the memoryview. - assert _safe_to_mutate(buffer_holder) + assert _is_safe_to_mutate(buffer_holder) view = _memoryview_from_bytes(buffer_holder, 'B', False, (buffer_size,)) assert not view.readonly assert len(buffer_holder) == 0 @@ -48,7 +48,7 @@ def test_never_mutate_singleton_bytes(): buffer_holder = [bytes([i])] else: buffer_holder = [chr(i)] - assert not _safe_to_mutate(buffer_holder) + assert not _is_safe_to_mutate(buffer_holder) # In this case, a new read-write buffer is allocated to back the # memoryview. @@ -64,7 +64,7 @@ def test_unsafe_mutable_bytes_with_external_references(): # The local 'buffer' variable still holds a reference to the bytes object # instance: _memoryview_from_bytes cannot safely reuse the same buffer. - assert not _safe_to_mutate(buffer_holder) + assert not _is_safe_to_mutate(buffer_holder) # Instead new mutable memory is allocated to back the buffer: view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) @@ -101,12 +101,12 @@ def process_str(original): # Interned CPython str buffers are never safe to mutate even without # external references. buffer_holder = [intern(process_str('other python 2 str'))] - assert not _safe_to_mutate(buffer_holder) + assert not _is_safe_to_mutate(buffer_holder) # Non-interned CPython str buffers without any external references are # safe to mutate: buffer_holder = [process_str('other python 2 str')] - assert _safe_to_mutate(buffer_holder) + assert _is_safe_to_mutate(buffer_holder) @pytest.mark.skipif(sys.version_info[0] != 2, @@ -114,7 +114,7 @@ def process_str(original): def test_unsafe_mutable_bytes_with_python_2_interning(): buffer_holder = [intern(u"\x01\x02\x03".encode('ascii'))] - assert not _safe_to_mutate(buffer_holder) + assert not _is_safe_to_mutate(buffer_holder) view = _memoryview_from_bytes(buffer_holder, 'B', False, (3,)) assert not view.readonly assert len(buffer_holder) == 0 From 80867ed1058434d1fc2c4a6b51dc14930637465a Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 15:55:37 +0100 Subject: [PATCH 26/31] Better comment --- tests/cloudpickle_test.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index dae0a6fef..5875a576f 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -1057,7 +1057,10 @@ def array_builder(buffer, dtype, shape, transpose): def reduce_ndarray(a): """Memoryview based reducer for numpy arrays""" if a.flags.f_contiguous: - # convert to c-contiguous to benefit from nocopy semantics. + # Transposing a F-contiguous array makes it possible to take + # a C-contiguous memoryview of it so as to benefit from nocopy + # semantics. The array will be transposed by to its original layout + # at unpickling time by array_builder. a = a.T transpose = True else: From 82e508affac1c56e6d23e8c7c5f0df8745b58f5f Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Mon, 11 Dec 2017 18:53:47 +0100 Subject: [PATCH 27/31] Fixed wrong assertions in tests for PyPy --- cloudpickle/cloudpickle.py | 4 +++- tests/memoryview_test.py | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 3972756e7..df3daf94e 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -61,6 +61,8 @@ import weakref +RUNNING_CPYTHON = platform.python_implementation() == 'CPython' + # cloudpickle is meant for inter process communication: we expect all # communicating processes to run the same Python version hence we favor # communication speed over compatibility: @@ -270,7 +272,7 @@ def is_interned(self): def _is_safe_to_mutate(data_holder): """Helper function, see _memoryview_from_bytes for details.""" - if platform.python_implementation() != 'CPython': + if not RUNNING_CPYTHON: # sys.getrefcount and ob_sstate are not always available on other # platforms (e.g. PyPy): better be conservative. return False diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py index 218e8c3a1..164437eaa 100644 --- a/tests/memoryview_test.py +++ b/tests/memoryview_test.py @@ -6,6 +6,9 @@ import pytest +RUNNING_CPYTHON = platform.python_implementation() == 'CPython' + + @pytest.mark.skipif(sys.version_info[:2] == (3, 4), reason="https://bugs.python.org/issue19803") def test_safe_mutable_bytes(): @@ -23,14 +26,17 @@ def test_safe_mutable_bytes(): # There are no external reference to the bytes object in buffer_holder, # the _memoryview_from_bytes function can safely reuse the memory # allocated for the bytes object to expose it as a mutable buffer to back - # the memoryview. - assert _is_safe_to_mutate(buffer_holder) + # the memoryview when running CPython. + if RUNNING_CPYTHON: + assert _is_safe_to_mutate(buffer_holder) + else: + assert not _is_safe_to_mutate(buffer_holder) view = _memoryview_from_bytes(buffer_holder, 'B', False, (buffer_size,)) assert not view.readonly assert len(buffer_holder) == 0 # CPython 2 and PyPy do not expose the obj attribute. - if hasattr(view, 'obj'): + if hasattr(view, 'obj') and RUNNING_CPYTHON: # The last reference to the original bytes object is hold in a closure # to discourage direct access by the user: with pytest.raises(TypeError) as exc_info: From 78cb82f31fc6a904d70600ae99a80545a5b0df2d Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Tue, 12 Dec 2017 20:12:31 +0100 Subject: [PATCH 28/31] Single element bytes mutation is actually safe --- cloudpickle/cloudpickle.py | 17 ++++++------ tests/memoryview_test.py | 55 +++++++++++++++++++++++++++++++++----- 2 files changed, 57 insertions(+), 15 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index df3daf94e..998cc6019 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -277,11 +277,6 @@ def _is_safe_to_mutate(data_holder): # platforms (e.g. PyPy): better be conservative. return False - if len(data_holder[0]) <= 1: - # Under CPython 3, single byte bytes can be mapped to singletons which - # are not safe to mutate. - return False - # If the following call to sys.getrefcount returns 2 it means that # there is one reference from data_holder and one from the temporary # arguments datastructure of the sys.getrefcount call. It is therefore @@ -304,8 +299,8 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): necessary. The actual data is provided in a data_holder which is expected to be a - single item list holding the actual bytes object. This makes it easier - to use sys.getrefcount to detect whether or not the bytes are referenced + single item list holding the actual bytes object. This makes it easier to + use sys.getrefcount to detect whether or not the bytes are referenced elsewhere or not. If readonly is False and the backing bytes in data_holder are referenced @@ -313,8 +308,12 @@ def _memoryview_from_bytes(data_holder, format, readonly, shape, **kwargs): allocated mutable buffer. Otherwise the memory allocated for the bytes object is directly reused by the new memoryview. - Python 2 memoryviews doe not support being cast so that the - format and shape parameters are ignored. + CPython 2 str buffers can be interned. This method introspect the ob_sstate + field to check if it is the case or not. If the buffer is interned a new + read-write buffer is allocated to ensure safety. + + Python 2 memoryviews doe not support being cast so that the format and + shape parameters are ignored. Reference counting cannot be used in PyPy to detect if it is safe to mutate the bytes object. If readonly is False, a new mutable buffer is always diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py index 164437eaa..fadf6cf4b 100644 --- a/tests/memoryview_test.py +++ b/tests/memoryview_test.py @@ -48,21 +48,64 @@ def test_safe_mutable_bytes(): view[:] = b'\x00' * buffer_size -def test_never_mutate_singleton_bytes(): +@pytest.mark.skipif(sys.version_info[0] < 3 or not RUNNING_CPYTHON, + reason="Test relies on CPython 3 implementation details") +def test_mutate_py3_single_element_bytes(): + """Check the safety of mutating a single element bytes instance. + + The _memoryview_from_bytes relies on implementation details of the + CPython 3 interpreter when deciding whether it is safe to mutate the + existing buffer or not. + + In particular it assumes that when a singleton bytes instance is implicitly + interned, it has always at least one external reference somewhere else in + the interpreter and the _safe_to_mutate will therefore always return False. + + If this assumption is ever violated in some future version of CPython, + this test will fail and will tell the cloudpickle maintainers that safety + of mutating singleton bytes is no longer guaranteed. + + This test is therefore a canary test for future Python 3 versions + """ + # Single element bytes can be singleton (implicitly interned), for instance + # when they are sliced from a larger bytes object or when encoding a + # single symbol unicode string. + joined_bytes = bytes(range(256)) + implicitly_interned_bytes = [] for i in range(256): - if sys.version_info[0] >= 3: - buffer_holder = [bytes([i])] - else: - buffer_holder = [chr(i)] + assert sys.getrefcount(joined_bytes[i:i + 1]) >= 2 + buffer_holder = [joined_bytes[i:i + 1]] assert not _is_safe_to_mutate(buffer_holder) + implicitly_interned_bytes.append(buffer_holder[0]) + assert chr(i).encode('latin1') is implicitly_interned_bytes[i] + assert joined_bytes[i:i + 1] is implicitly_interned_bytes[i] # In this case, a new read-write buffer is allocated to back the # memoryview. view = _memoryview_from_bytes(buffer_holder, 'B', False, (1,)) assert not view.readonly - if hasattr(view, 'obj'): + if sys.version_info[:2] != (3, 4): assert not hasattr(view.obj, '_hidden_buffer_ref') + # Single item bytes instances are not interned when using the bytes([i]) + # constructor and this case, they can be mutated safely, they will not + # impact the implicitly interned bytes singleton instances. + for i in range(256): + buffer_holder = [bytes([i])] + assert buffer_holder[0] is not implicitly_interned_bytes[i] + assert _is_safe_to_mutate(buffer_holder) + view = _memoryview_from_bytes(buffer_holder, 'B', False, (1,)) + if sys.version_info[:2] != (3, 4): + with pytest.raises(TypeError): + view.obj._hidden_buffer_ref() + view[:] = b'\x00' + assert view.tobytes() == b'\x00' + + # The singleton are not impacted by the changes in the views + for i in range(256): + assert implicitly_interned_bytes[i] is not bytes([i]) + assert implicitly_interned_bytes[i] == bytes([i]) + def test_unsafe_mutable_bytes_with_external_references(): buffer = u"\x01\x02\x03".encode('ascii') From 53ef28227dae614f6a7e75314f5e7ed7ed2637a7 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Tue, 12 Dec 2017 21:26:56 +0100 Subject: [PATCH 29/31] Improve tests --- tests/memoryview_test.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py index fadf6cf4b..a6f53e54e 100644 --- a/tests/memoryview_test.py +++ b/tests/memoryview_test.py @@ -92,6 +92,7 @@ def test_mutate_py3_single_element_bytes(): # impact the implicitly interned bytes singleton instances. for i in range(256): buffer_holder = [bytes([i])] + assert buffer_holder[0] == implicitly_interned_bytes[i] assert buffer_holder[0] is not implicitly_interned_bytes[i] assert _is_safe_to_mutate(buffer_holder) view = _memoryview_from_bytes(buffer_holder, 'B', False, (1,)) @@ -101,10 +102,28 @@ def test_mutate_py3_single_element_bytes(): view[:] = b'\x00' assert view.tobytes() == b'\x00' - # The singleton are not impacted by the changes in the views + # The singleton are not impacted by the changes in the views. for i in range(256): - assert implicitly_interned_bytes[i] is not bytes([i]) assert implicitly_interned_bytes[i] == bytes([i]) + assert implicitly_interned_bytes[i] is not bytes([i]) + + +@pytest.mark.skipif(sys.version_info[0] < 3, + reason="Test checks assumption on Python 3 implementation") +def test_check_no_explicit_py3_bytes_interning(): + """Ensure that Python 3+ does not allow explicit interning for bytes. + + The _memoryview_from_bytes function makes the assumption that it is not + possible to explicitly intern bytes objects. If this assumption is ever + violated in future versions of Python, the implementation of + _memoryview_from_bytes will have to be updated accordingly to preserve the + safety of directly reusing a bytes buffer to a mutable memoryview. + + This is a canary test: this does not actually test anything in cloudpickle + besides assumptions made on the language implementation. + """ + with pytest.raises(TypeError): + sys.intern(b'some bytes instance') def test_unsafe_mutable_bytes_with_external_references(): From 137dd346977df792b23490fda344818f0621ba71 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Tue, 12 Dec 2017 22:52:17 +0100 Subject: [PATCH 30/31] Cosmetics. --- cloudpickle/cloudpickle.py | 17 +++++++++-------- tests/memoryview_test.py | 10 +++++----- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 998cc6019..c70add9f2 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -277,12 +277,11 @@ def _is_safe_to_mutate(data_holder): # platforms (e.g. PyPy): better be conservative. return False - # If the following call to sys.getrefcount returns 2 it means that - # there is one reference from data_holder and one from the temporary - # arguments datastructure of the sys.getrefcount call. It is therefore - # safe to reuse the memory buffer of the bytes object as writeable - # buffer to back the memoryview: this buffer is no longer reachable - # from anywhere else. + # If the following call to sys.getrefcount returns 2, it means that there + # is one reference from data_holder and one from the temporary arguments + # datastructure of the sys.getrefcount call. It is therefore safe to reuse + # the memory buffer of the bytes object as writeable buffer to back the + # memoryview: this buffer is no longer reachable from anywhere else. safe_to_mutate = sys.getrefcount(data_holder[0]) <= 2 data = data_holder[0] if safe_to_mutate and isinstance(data, str): @@ -415,8 +414,10 @@ def write_large_bytes(self, header, payload): # object. Be careful not to concatenate the header and the payload # prior to calling 'write' as we do not want to allocate a large # temporary bytes object. - # We intentionally do not insert a protocol 4 frame opcode to make - # it possible to optimize file.read calls in the loader. + # We intentionally do not insert a protocol 4 frame opcode to make it + # possible to optimize file.read calls in the loader and pass the + # resulting bytes as a preallocated data buffer for more complex + # datastructures such as memoryviews or numpy arrays. write(header) write(payload) diff --git a/tests/memoryview_test.py b/tests/memoryview_test.py index a6f53e54e..9490bf258 100644 --- a/tests/memoryview_test.py +++ b/tests/memoryview_test.py @@ -23,10 +23,10 @@ def test_safe_mutable_bytes(): # Delete the local direct reference to the buffer del buffer - # There are no external reference to the bytes object in buffer_holder, - # the _memoryview_from_bytes function can safely reuse the memory - # allocated for the bytes object to expose it as a mutable buffer to back - # the memoryview when running CPython. + # There are no external reference to the bytes object in buffer_holder, the + # _memoryview_from_bytes function can safely reuse the memory allocated for + # the bytes object to expose it as a mutable buffer to back the memoryview + # when running CPython. if RUNNING_CPYTHON: assert _is_safe_to_mutate(buffer_holder) else: @@ -88,7 +88,7 @@ def test_mutate_py3_single_element_bytes(): assert not hasattr(view.obj, '_hidden_buffer_ref') # Single item bytes instances are not interned when using the bytes([i]) - # constructor and this case, they can be mutated safely, they will not + # constructor and in this case, they can be mutated safely, they will not # impact the implicitly interned bytes singleton instances. for i in range(256): buffer_holder = [bytes([i])] From 0dbff612eb45c76740342ab3513d77482fd266a1 Mon Sep 17 00:00:00 2001 From: Olivier Grisel Date: Wed, 13 Dec 2017 16:07:48 +0100 Subject: [PATCH 31/31] Nocopy semantics for numpy arrays for Python 3 enabled by default --- cloudpickle/cloudpickle.py | 55 +++++++++++++++++++++++++- dev-requirements.txt | 2 +- tests/cloudpickle_test.py | 79 +++++++++++++++++++++++++++----------- 3 files changed, 112 insertions(+), 24 deletions(-) diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index c70add9f2..5260896ef 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -60,6 +60,11 @@ import types import weakref +try: + import numpy as np +except ImportError: + np = None + RUNNING_CPYTHON = platform.python_implementation() == 'CPython' @@ -352,12 +357,52 @@ def _hidden_buffer_ref(): view = memoryview(bytearray(data)) if PY_MAJOR_MINOR >= (3, 4): - return view.cast('B').cast(format, shape) + if len(data) > 0: + return view.cast('B').cast(format, shape) + else: + return view.cast('B').cast(format) else: # Python 2.7 does not support casting. return view +def _np_array_builder(buffer, dtype, shape, transpose, writeable, **kwargs): + """Rebuild a numpy array from raw bytes & metadata + + kwargs is ignored. It gives flexibility to implement backward compatible + changes in future versions of cloudpickle. + """ + a = np.lib.stride_tricks.as_strided( + np.frombuffer(buffer, dtype), shape=shape) + if writeable is False: + # buffer is expected to be reconstructed by _memoryview_from_bytes + # which can be a mutable buffer even if the original numpy array + # was readonly. + a.flags.writeable = False + return a.T if transpose else a + + +def _reduce_ndarray(a): + """Memoryview based reducer for numpy arrays + + Note that this reducer is only used under Python 3 as it is not possible + to rebuild a numpy array from a memoryview under Python 2. + """ + transpose = False + if a.flags.f_contiguous: + # Transposing a F-contiguous array makes it possible to take + # a C-contiguous memoryview of it so as to benefit from nocopy + # semantics. The array will be transposed by to its original layout + # at unpickling time by array_builder. + a = a.T + transpose = True + elif not a.flags.c_contiguous: + # Make a copy to be able to extract a contiguous memoryview. + a = np.ascontiguousarray(a) + return _np_array_builder, (memoryview(a), a.dtype, a.shape, transpose, + a.flags.writeable) + + class _Framer: """Backport of Python 3.7 framer""" @@ -424,8 +469,16 @@ def write_large_bytes(self, header, payload): class CloudPickler(Pickler): + # Lookup table for save_*(self, obj) methods with access to the pickler. dispatch = Pickler.dispatch.copy() + # Custom reducers (without access to the pickler): only used in Python 3 + dispatch_table = pickle.dispatch_table.copy() + + # Register a reducer for numpy arrays by default. + if np is not None: + dispatch_table[np.ndarray] = _reduce_ndarray + def __init__(self, file, protocol=None): if protocol is None: protocol = DEFAULT_PROTOCOL diff --git a/dev-requirements.txt b/dev-requirements.txt index 14b15c10c..77bcf06c2 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -8,5 +8,5 @@ codecov # nocopy tests with pydata libraries numpy -pandas; platform_python_implementation != "PyPy" +pandas; platform_python_implementation != "PyPy" and python_version >= '3.5' scipy; platform_python_implementation != "PyPy" and python_version >= '3.5' diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index 5875a576f..3031733db 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -141,6 +141,15 @@ def test_memoryview(self): self.assertEqual(cloned.tobytes(), buffer_obj.tobytes()) assert cloned.readonly + def test_empty_memoryview(self): + for view in [memoryview(b""), memoryview(b"hello")[1:1]]: + assert view.readonly + cloned = pickle_depickle(view, protocol=self.protocol) + self.assertEqual(cloned.tobytes(), view.tobytes()) + assert cloned.readonly + assert cloned.shape == (0,) + assert cloned.format == 'B' + @pytest.mark.skipif(sys.version_info < (3, 4), reason="array does not implement the buffer protocol") def test_memoryview_from_integer_array(self): @@ -226,6 +235,53 @@ def test_complex_memoryviews(self): # the original view contiguity and layout (C vs Fortran). assert cloned_view.c_contiguous + def test_numpy_arrays(self): + # Check that numpy arrays with various memory layouts are properly + # handled. Note that the fact that this can be done without additional + # memory copies depends on the Python version, implementation and + # contiguity of the original aray. Checking nocopy semantics are not + # the goal of this test but are instead addressed in separate, + # implementation specific tests. + np = pytest.importorskip("numpy") + arrays = [ + np.arange(12).reshape(3, 4), + np.arange(12).reshape(3, 2, 2), + np.arange(12000).reshape(3000, 4).astype(np.float32), + np.asfortranarray(np.arange(12).reshape(3, 4)), + np.arange(12).reshape(3, 4)[:, 1:-1], + np.arange(12).reshape(3, 4)[1:-1, :], + np.asfortranarray(np.arange(12).reshape(3, 4))[:, 1:-1], + np.asfortranarray(np.arange(12).reshape(3, 4))[1:-1, :], + np.array([]), + np.array(1), + np.array(1)[()], + ] + readonly_arrays = [] + for a in arrays: + try: + a = a.copy() + a.flags.writeable = False + readonly_arrays.append(a) + except ValueError: + # Cannot set flags on array scalars. + pass + arrays += readonly_arrays + + for original in arrays: + cloned = pickle_depickle(original, protocol=self.protocol) + assert original.dtype == cloned.dtype + assert original.shape == cloned.shape + np.testing.assert_array_equal(original, cloned) + + if original.flags.f_contiguous: + assert cloned.flags.f_contiguous + else: + assert cloned.flags.c_contiguous + if sys.version_info[0] > 2: + # Under Python 2, the non-optimized reducer of numpy is used + # and it does not preserve the writeable flag. + assert original.flags.writeable == cloned.flags.writeable + def test_lambda(self): self.assertEqual(pickle_depickle(lambda: 1)(), 1) @@ -1049,24 +1105,6 @@ def test_nocopy_pydata(): (csr, csr.indptr.nbytes + csr.indices.nbytes + csr.data.nbytes), ] - def array_builder(buffer, dtype, shape, transpose): - a = np.lib.stride_tricks.as_strided( - np.frombuffer(buffer, dtype), shape=shape) - return a.T if transpose else a - - def reduce_ndarray(a): - """Memoryview based reducer for numpy arrays""" - if a.flags.f_contiguous: - # Transposing a F-contiguous array makes it possible to take - # a C-contiguous memoryview of it so as to benefit from nocopy - # semantics. The array will be transposed by to its original layout - # at unpickling time by array_builder. - a = a.T - transpose = True - else: - transpose = False - return array_builder, (memoryview(a), a.dtype, a.shape, transpose) - class ChunksAppender: def __init__(self): @@ -1086,14 +1124,11 @@ def materialize(self): for obj, size in large_pydata_objects: appender = ChunksAppender() - pickler = cloudpickle.CloudPickler(appender) - pickler.dispatch_table = pickle.dispatch_table.copy() - pickler.dispatch_table[np.ndarray] = reduce_ndarray # Check that pickling does not make any memory copy of the large data # buffer of the pandas dataframe: with PeakMemoryMonitor() as monitor: - pickler.dump(obj) + cloudpickle.dump(obj, appender) assert monitor.newly_allocated < mem_tol