Sharing Memory with C

Contents
Python 3.8, released last week, adds a pickle protocol that can serialise a 100 MB NumPy array into 122 bytes. The other 100,000,000 bytes aren’t copied into the pickle at all. They’re handed to the caller as a buffer, the array’s own memory, to send however it likes. That works because of an interface that has been in Python 3 from the start and that most Python programmers never see: the buffer protocol, through which one object lends the raw memory behind it to another, with no copy, as long as the lender agrees to keep it still.
This post is about that protocol. It shows one block of bytes seen through four different objects at
the same address, measures what a view saves over a copy, then looks at what lending costs the
lender: memory that can’t be freed, a bytearray that can’t grow, an mmap that can’t close, and
the one case here where the bookkeeping failed and the program read memory that was gone.
This is Part 11 of a series on the CPython runtime. Part 9 met NumPy’s C numbers, and Part 10 wrote a C extension by hand. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.8.0, released on 14 October and built from its tag with Ubuntu 18.04’s gcc 7.3.0, with NumPy 1.17.3, released three days later. The note at the end says exactly where and how.
One buffer, four objects
PEP 3118, which arrived with Python 3.0, defines the protocol. An object that owns memory implements
a C function, bf_getbuffer, that fills in a Py_buffer describing it, and a consumer that wants the
memory asks for one. The struct, from Include/cpython/object.h in 3.8:
typedef struct bufferinfo {
void *buf;
PyObject *obj; /* owned reference */
Py_ssize_t len;
Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
pointed to by strides in simple case.*/
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
void *internal;
} Py_buffer;
buf is a plain C pointer to the first byte. format is a struct-module format string for one item
("B" for unsigned bytes, "d" for doubles), and ndim, shape and strides describe how the items
are laid out, so that a buffer can describe a 2-D array, or a slice of one, without copying. obj is
a reference to the lender, which keeps it alive while the buffer is held, and readonly says whether
the borrower may write. When the consumer is done, it calls PyBuffer_Release, and the lender’s
bf_releasebuffer runs.
Here is one 16-byte bytearray, lent three times:
import ctypes
import numpy as np
buf = bytearray(b"hello, world!!!!") # 16 bytes, owned by a bytearray
mv = memoryview(buf) # a view: no copy
arr = np.frombuffer(buf, dtype=np.uint8) # a NumPy array over the same bytes
c = (ctypes.c_char * 16).from_buffer(buf) # a C array over the same bytes
print("bytearray data at ", hex(ctypes.addressof(c)))
print("NumPy array data at", hex(arr.ctypes.data))
print("memoryview readonly", mv.readonly, " format", repr(mv.format), " itemsize", mv.itemsize, " shape", mv.shape)
c[0] = b"J" # write through the C array...
print("after c[0] = b'J': ", bytes(buf), mv[0], arr[0], bytes(mv[:5]))
$ python3 views.py
bytearray data at 0x710e19ff2bd0
NumPy array data at 0x710e19ff2bd0
memoryview readonly False format 'B' itemsize 1 shape (16,)
after c[0] = b'J': b'Jello, world!!!!' 74 74 b'Jello'
The ctypes array and the NumPy array report the same address for their data, because it’s the same
memory: the bytearray’s internal buffer. One write through the C array, c[0] = b"J", changes what
all four objects see: the bytearray now says “Jello”, the memoryview and the NumPy array both
read 74, which is ord("J"). No copy happened at any point. This is how NumPy reads image data from
Pillow, how socket.recv_into fills a NumPy array straight from the kernel, and how struct,
array, mmap and hashlib work on any buffer without converting it to bytes first.
One block of memory, four objects
A 16-byte bytearray, lent to a memoryview, a NumPy array and a ctypes array.
↓ every one of them points at the same bytes ↓
at 0x710e19ff2bd0 (ctypes) and 0x710e19ff2bd0 (NumPy) in the run: the same address
The write through the C array changed byte 0 for all four objects at once. Nothing was copied when the views were made, and nothing was copied when one of them wrote.
A view is not a copy
The difference shows at scale. Slicing bytes makes new bytes, copying every byte. Slicing a
memoryview makes another view of the same memory:
import time, tracemalloc
data = b"x" * 100_000_000 # 100 MB of bytes
for label, make in [("data[1:] (bytes slice)", lambda: data[1:]),
("memoryview(data)[1:] (view) ", lambda: memoryview(data)[1:])]:
tracemalloc.start()
t = time.perf_counter()
piece = make()
dt = time.perf_counter() - t
used = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
print("%s %8.3f ms %11d bytes allocated" % (label, dt * 1e3, used))
del piece
$ python3 slicing.py
data[1:] (bytes slice) 55.911 ms 100000032 bytes allocated
memoryview(data)[1:] (view) 0.010 ms 312 bytes allocated
The copy took 56 milliseconds and 100 MB of new memory. The view took 10 microseconds and 312
bytes, the size of the two memoryview objects involved (the full view and its slice) and a
Py_buffer each.
Code that parses a large binary format, a network protocol or a file, by slicing bytes copies the
input over and over. The same code over a memoryview copies nothing, and that’s the most common
reason the buffer protocol shows up in a profile.
What lending costs the lender
A view keeps its lender alive, all of it, however small the view:
import tracemalloc
tracemalloc.start()
big = bytearray(100_000_000)
tiny = memoryview(big)[:1] # one byte of it
del big # the name is gone...
print("after del big: %11d bytes still allocated" % tracemalloc.get_traced_memory()[0])
print("tiny.obj is the whole bytearray, len", len(tiny.obj))
tiny.release() # ...the memory goes with the last view
print("after release: %11d bytes still allocated" % tracemalloc.get_traced_memory()[0])
$ python3 pinned.py
after del big: 100000945 bytes still allocated
tiny.obj is the whole bytearray, len 100000000
after release: 1092 bytes still allocated
tiny is one byte, but its Py_buffer.obj is a reference to the whole bytearray, and the memory it
points into can’t be freed while it’s held. The same is true of a NumPy view (arr[:1] keeps the
whole of arr alive through arr[:1].base) and of any buffer a C extension still holds. A cache that
keeps small slices of large inputs keeps the inputs, which looks exactly like a memory leak.
The lender also promises not to move the memory while it’s lent. A bytearray that grows may have
to realloc its buffer to a new address, which would leave every borrower pointing at freed memory,
so it counts its exports and refuses:
import mmap
import numpy as np
buf = bytearray(16)
view = memoryview(buf)
try:
buf.append(1)
except BufferError as e:
print("append with a view alive:", e)
view.release()
buf.append(1)
print("append after release: len", len(buf))
with open("file.bin", "wb") as f:
f.write(bytes(range(256)) * 16)
f = open("file.bin", "r+b")
m = mmap.mmap(f.fileno(), 0)
mv = memoryview(m)
try:
m.close()
except BufferError as e:
print("m.close() with a memoryview alive:", e)
mv.release()
arr = np.frombuffer(m, dtype=np.uint8) # an array straight over the mapped file
print("arr[255] =", arr[255], " arr.base is m:", arr.base is m)
m.close() # no error this time
print("m.close() with the NumPy array alive: no error")
print("arr[255] after close =", arr[255]) # reads an unmapped page
$ python3 -u exports.py
append with a view alive: Existing exports of data: object cannot be re-sized
append after release: len 17
m.close() with a memoryview alive: cannot close exported pointers exist
arr[255] = 255 arr.base is m: True
m.close() with the NumPy array alive: no error
Segmentation fault
$ echo $?
139
The first two refusals are the protocol working. append fails while a memoryview exists,
because bytearray’s bf_getbuffer increments a counter, ob_exports, and its resize code checks it
(Objects/bytearrayobject.c):
if (self->ob_exports > 0) {
PyErr_SetString(PyExc_BufferError,
"Existing exports of data: object cannot be re-sized");
return -1;
}
After view.release(), the same append works. An mmap keeps the same count, and refuses to unmap
the file while a memoryview of it exists, with BufferError: cannot close exported pointers exist.
Then the NumPy array. np.frombuffer(m) made an array over the mapped file, and arr.base is m says
the array keeps the mmap object alive. But m.close() succeeded anyway, and the next read of
arr[255] killed the process with a segmentation fault. NumPy 1.17’s frombuffer evidently took the
pointer, kept a reference to the object, and released the buffer export straight away, so the mmap’s
export count was back to zero and it had no reason to refuse. Keeping the object alive isn’t the same
as holding the export: the mmap object outlived its mapping, and the array pointed into a page that
was no longer mapped. The protocol is only as safe as the bookkeeping on both sides, and here one
side’s was weaker than the protocol allows.
Shape and strides
A buffer can describe more than a flat run of bytes. NumPy arrays in particular are often views with a layout different from their memory’s:
import numpy as np
a = np.arange(12, dtype=np.int32).reshape(3, 4)
t = a.T
for name, x in (("a", a), ("a.T", t)):
m = memoryview(x)
print("%-4s shape %-7s strides %-8s c_contiguous %-5s f_contiguous %-5s same memory as a: %s" %
(name, m.shape, m.strides, m.c_contiguous, m.f_contiguous, np.shares_memory(x, a)))
print("a.T.tobytes()[:16] =", a.T.tobytes()[:16].hex(" ", 4)) # a copy, rearranged
print("bytes(memoryview(a))[:16] =", bytes(memoryview(a))[:16].hex(" ", 4))
m = memoryview(a).cast("B") # the same memory as raw bytes
print("cast('B'): format", repr(m.format), "shape", m.shape, "first bytes", bytes(m[:8]).hex(" "))
$ python3 strides.py
a shape (3, 4) strides (16, 4) c_contiguous True f_contiguous False same memory as a: True
a.T shape (4, 3) strides (4, 16) c_contiguous False f_contiguous True same memory as a: True
a.T.tobytes()[:16] = 00000000 04000000 08000000 01000000
bytes(memoryview(a))[:16] = 00000000 01000000 02000000 03000000
cast('B'): format 'B' shape (48,) first bytes 00 00 00 00 01 00 00 00
a is a 3 × 4 array of 4-byte ints, laid out row after row (C order): the next element in a row is 4
bytes on, the next row 16 bytes on, so its strides are (16, 4). a.T, the transpose, is not a copy.
It is the same memory described with the strides swapped, (4, 16), and so it’s Fortran-ordered
(column after column) rather than C-ordered. Both report sharing memory with a. Anything that needs
the transpose as a contiguous block of bytes, tobytes() here, has to copy and rearrange: its first
four values are 0, 4, 8, 1, walking down the original’s columns. A C function that assumes C order and
gets this buffer without checking the strides reads the original’s rows instead of the transpose’s.
(bytes.hex() with a separator, used here to space the output, is itself new in Python 3.8. Part 1
had to build the spaced hex by hand on 3.6.)
Pickle protocol 5: out-of-band buffers
Pickle has always copied: an array’s 100 MB went into the pickle’s bytes, then out again into a new
array on loading. PEP 574, new in 3.8, adds protocol 5, which lets an object give pickle its buffers
directly. With a buffer_callback, pickle hands each buffer to the callback instead of copying it into
the stream, and on loading the same buffers are passed back in:
import pickle, time
import numpy as np
arr = np.ones(100_000_000 // 8) # 100 MB of float64
t = time.perf_counter(); p4 = pickle.dumps(arr, protocol=4); t4 = time.perf_counter() - t
buffers = []
t = time.perf_counter(); p5 = pickle.dumps(arr, protocol=5, buffer_callback=buffers.append); t5 = time.perf_counter() - t
print("protocol 4: %11d bytes of pickle in %6.1f ms" % (len(p4), t4 * 1e3))
print("protocol 5: %11d bytes of pickle in %6.1f ms, plus %d out-of-band buffer of %d bytes" %
(len(p5), t5 * 1e3, len(buffers), buffers[0].raw().nbytes))
back = pickle.loads(p5, buffers=buffers)
print("loaded array shares memory with the original:", np.shares_memory(back, arr))
$ python3 oob.py
protocol 4: 100000164 bytes of pickle in 106.5 ms
protocol 5: 122 bytes of pickle in 0.1 ms, plus 1 out-of-band buffer of 100000000 bytes
loaded array shares memory with the original: True
Protocol 4 copied 100 MB into the pickle in 107 milliseconds. Protocol 5 produced 122 bytes of pickle
(the array’s type, shape and dtype) in a tenth of a millisecond, and one PickleBuffer lending the
array’s memory. Loading with those buffers gave back an array that shares memory with the original:
no copy at either end. It’s meant for frameworks that move data between processes (shared memory,
RDMA, sockets with sendmsg), which can now send the bulk of an object without serialising it, and
NumPy 1.16 and later already support it.
My first name for that script was pickle5.py, and it never ran: NumPy 1.17 tries import pickle5 at
start-up, to use the backport of this very protocol on older Pythons, and the script’s own directory
comes first on sys.path. So NumPy imported my script in the middle of its own initialisation, and my
script, which imports NumPy, found a half-initialised module: AttributeError: partially initialized module 'numpy' has no attribute 'ones' (most likely due to a circular import). Importing a module is
running it, and the search path decides which one, which is a later post’s subject.
Copying 100 MB, and lending it
CPython 3.8.0. Bar lengths are logarithmic so that both ends fit; the labels give the measured values.
Taking [1:] of 100 MB
Pickling a 100 MB array
Hover or focus a bar for details.
Time bars run from 1 µs to 1 s, memory bars from 1 byte to 1 GB, both logarithmic. The view and the out-of-band pickle copy nothing, which is why they are thousands of times cheaper.
What we covered
- The buffer protocol (PEP 3118) lets an object lend its memory as a
Py_buffer: a C pointer plus item format, shape and strides, and a reference that keeps the lender alive. - One
bytearraylent to amemoryview, a NumPy array and a ctypes array was the same memory at the same address, and one write was visible through all four. - Slicing 100 MB of
bytescopied it in 56 ms. Amemoryviewslice took 10 µs and 312 bytes. - A one-byte view kept 100 MB alive. Exports stopped a
bytearrayfrom resizing and anmmapfrom closing. NumPy 1.17’sfrombufferkept themmapobject but not the export, so the mapping could close under it, and the next read segfaulted. - Strides let a view describe a transpose without copying, and code that ignores them reads the wrong elements.
- Python 3.8’s pickle protocol 5 turned a 100 MB pickle into 122 bytes plus the array’s own buffer, loaded back without a copy.
The next post covers the rest of what changed underneath in 3.8: a new calling convention, a new way to configure the interpreter, and hooks that report what a Python process does.
A note on the evidence
What I ran, and where. Everything ran on CPython 3.8.0, built from the v3.8.0 tag with Ubuntu
18.04’s gcc 7.3.0, with NumPy 1.17.3 installed from PyPI with that interpreter’s pip, on a minimal 18.04
userland from the release archive, as a chroot on a 64-bit x86 machine. Each script was extracted from
this page and run as shown, with the outputs captured to files and pasted from them.
The numbers. The timings are single runs on an idle machine, and the ratios (thousands of times for
the slice, a thousand for the pickle) are the point. Allocated bytes are tracemalloc totals,
deterministic for this build. The addresses are one run’s.
What I worked out rather than read. That NumPy 1.17’s frombuffer releases the export immediately
is inferred from the behaviour: close() succeeded with the array alive, and a memoryview in the same
position blocked it. I didn’t read NumPy’s source to confirm the mechanism.
What I cited rather than ran. Py_buffer is quoted from Include/cpython/object.h, the export
check from Objects/bytearrayobject.c and the mmap message from Modules/mmapmodule.c, all at
v3.8.0. PEP 3118 (Python 3.0) and PEP 574 (3.8) are cited from the PEPs. NumPy’s support for protocol
5 and the pickle5 backport are from NumPy’s release notes and its numpy/compat/py3k.py, where I read
the import pickle5 as pickle line.
What I’d still change. The out-of-band pickle is shown in one process. The point of it is
cross-process transfer, and a demonstration over shared memory (multiprocessing.shared_memory, also
new in 3.8) would show the bytes not moving between two processes, not only within one.
Sharing Memory with C