Debian Codegraph @

docs/pycon-2016-talk.rst

raw
1 Python Sorted Collections - PyCon 2016 Talk
2 ===========================================
3
4 * `Python Sorted Collections Video Recording on Youtube`_
5 * `Python Sorted Collections Slides`_
6
7 Hello, I’m here today to talk about `Python sorted collections`_. I’m excited
8 and a bit nervous to be up here in front of all you smart people. But I’m a
9 pretty smart guy myself and I really admire Python so let’s get started.
10
11 Every time I talk about `sorted collections`_, my wife hear’s sordid. We’ll see
12 today how many times I can confuse the on-site captioners. You’re probably more
13 familiar with sorted collections than you realize.
14
15 In the standard library we have `heapq`_, `bisect`_ and `queue.PriorityQueue`_
16 but they don't quite fill the gap. Behind the scenes, priority queue uses a
17 heap implementation. Another common mistake is to think that
18 `collections.OrderedDict`_ is a dictionary that maintains sort order but that’s
19 not the case.
20
21 I don't always import sorted types. But when I do, I expect them in the
22 standard library.
23
24 And here’s why. `Java`_, `C++`_ and `.NET`_ have them. `Python`_ has broken
25 into the top five of the TIOBE index but feels a bit more like `PHP`_ or
26 `Javascript`_ in this regard.
27
28 We also depend on external solutions: `Sqlite in-memory indexes`_,
29 `pandas.DataFrame indexes`_, and `Redis sorted sets`_. If you’ve ever issued a
30 “zadd” command to Redis then you used a sorted collection.
31
32 So what should be the API of sorted collection types in Python?
33
34 Well, a sorted list should be a `MutableSequence`_. Pretty close to the “list”
35 API. But there’s a sort order constraint that must be satisfied by “setitem”
36 and “insert” methods. Also should support a “key” argument like the “sorted”
37 builtin function. Given sorted order, “bisect_right” and “bisect_left” methods
38 make sense. You could also imagine an “add” method and “discard” method for
39 elements. Kind of like a multi-set in other languages. I’d also expect
40 “getitem”, “contains”, “count”, etc. to be faster than linear time.
41
42 A sorted dictionary should be a `MutableMapping`_. Pretty close to the
43 dictionary API. But iteration yields items in sorted order. Also should support
44 efficient positional indexing, something like a SequenceView.
45
46 Sorted set should be a `MutableSet`_. Pretty close to the “set” API. Sorted set
47 should also be a Sequence like the “tuple” API to support efficient positional
48 indexing.
49
50 The chorus and the refrain from core developers is: "Look to the `PyPI`_."
51 Which is good advice.
52
53 So let’s talk about your options with a bit of software archaeology.
54
55 `Blist`_ is the genesis of our story but it wasn’t really designed for sorted
56 collections. It’s written in C and the innovation here is the “blist” data
57 type. That’s a B-tree based replacement for CPython’s built-in list. Sorted
58 list, sorted dictionary, and sorted set were built on top of this “blist” data
59 type and it became the incumbent to beat. Also noteworthy is that the API was
60 rather well thought out.
61
62 There were some quirks; for example: the “pop” method returns the first element
63 rather than the last element in the sorted list.
64
65 `SortedCollection`_ is not a package. You can’t install this with “pip”. It’s
66 simply a Python recipe that Raymond Hettinger linked from the Python
67 docs. Couple innovations here though: it’s simple, it’s written in pure-Python,
68 and maintains a parallel list of keys. So we have efficient support for that
69 key-function parameter.
70
71 This is `bintrees`_. Still alive and kicking today. A few innovations here:
72 it’s written with Cython support to improve performance and has a few different
73 tree “backends.” You can create a red-black or AVL-tree depending on your
74 needs. There’s also some notion of accessing the nodes themselves and
75 customizing the tree traversal to slice by value rather than by index.
76
77 `Banyan`_ had a very short life but adds another couple innovations: it’s
78 incredibly fast and achieves that through C++ template meta-programming. It
79 also has a feature called tree-augmentation that will let you store metadata at
80 tree nodes. You can use this for interval trees if you need those.
81
82 Finally there’s `skiplistcollections`_. Couple significant things here: it’s
83 pure-Python but fast, even for large collections, and it uses a skip-list data
84 type rather than a binary tree.
85
86 Altogether, you go on PyPI and try to figure this out and it’s kind of like
87 this. It’s a mess. PyPI has really got to work better than using `Google`_ with
88 the site operator.
89
90 Couple others worth calling out: `rbtree`_ is another fast C-based
91 implementation. And there’s a few like treap, splay and scapegoat that are
92 contributions and experiments by `Dan Stromberg`_. He’s also done some
93 interesting benchmarking of the various tree types. There’s no silver bullet
94 when it comes to trees.
95
96 I love Python because there's one right way to do things. If I just want sorted
97 types, what’s the right answer?
98
99 I couldn’t find the right answer so I built it. The missing battery: `Sorted
100 Containers`_.
101
102 Here it is. This is the project home page. `Sorted Containers`_ is a `Python
103 sorted collections`_ library with `sorted list`_, `sorted dictionary`_, and
104 `sorted set`_ implementations. It’s pure-Python but it’s as fast as
105 C-extensions. It’s Python 2 and Python 3 compatible. It’s fully-featured. And
106 it’s extensively tested with 100% coverage and hours of stress.
107
108 `Performance`_ is a feature. That means graphs. Lots of them. There are 189
109 performance graphs in total. Let’s look at a few of them together.
110
111 Here’s the performance of adding a random value to a sorted list. I’m comparing
112 `Sorted Containers`_ with other competing implementations.
113
114 Notice the axes are log-log. So if performance differs by major tick marks then
115 one is actually ten times faster than the other.
116
117 We see here that `Sorted Containers`_ is in fact about ten times faster than
118 blist when it comes to adding random values to a sorted list. Notice also
119 Raymond’s recipe is just a list and that displays order n-squared runtime
120 complexity. That’s why it curves upwards.
121
122 Of all the sorted collections libraries, `Sorted Containers`_ is also fastest
123 at initialization. We’ll look at why soon.
124
125 `Sorted Containers`_ is not always fastest. But notice here the performance
126 improves with scale. You can see it there in blue. It starts in the middle of
127 the pack and has a lesser slope than competitors.
128
129 In short, `Sorted Containers`_ is kind of like a `B-tree`_ implementation. That
130 means you can configure the fan-out of nodes in the tree. We call that the
131 load parameter and there are extensive performance graphs of three different
132 `load parameters`_.
133
134 Here we see that a load factor of ten thousand is fastest for indexing a sorted
135 list.
136
137 Notice the axes now go up to ten million elements. I’ve actually scaled
138 `SortedList`_ all the way to ten billion elements. It was a really incredible
139 experiment. I had to rent the largest high-memory instance available from
140 Google Compute Engine. That benchmark required about 128 gigabytes of memory
141 and cost me about thirty dollars.
142
143 This is the performance of deleting a key from a sorted dictionary. Now the
144 smaller load-factor is fastest. The default load-factor is 1,000 and works well
145 for most scenarios. It’s a very sane default.
146
147 In addition to comparisons and load-factors, I also `benchmark
148 runtimes`_. Here’s CPython 2.7, CPython 3.5 and `PyPy`_ version 5. You can see
149 where the just-in-time compiler, the jit-compiler, kicks in. That’ll make
150 `Sorted Containers`_ another ten times faster.
151
152 Finally, I made a survey in 2015 on `Github`_ as to how people were using
153 sorted collections. I noticed patterns like priority queues, multi-sets,
154 nearest-neighbor algorithms, etc.
155
156 This is the priority queue workload which spends 40% of its time adding
157 elements, 40% popping elements, 10% discarding elements, and has a couple other
158 methods.
159
160 `Sorted Containers`_ is two to ten times faster in all of these scenarios.
161
162 We also have a lot of features. The API is nearly a drop-in replacement for the
163 “blist” and “rbtree” modules. But the quirks have been fixed so the “pop”
164 method returns the last element rather than the first.
165
166 Sorted lists are sorted so you can bisect them. Looking up the index of an
167 element is also very fast.
168
169 Bintrees introduced methods for tree traversal. And I’ve boiled those down to a
170 couple API methods. On line 3, we see “irange”. Irange iterates all keys from
171 bob to eve in sorted order.
172
173 Sorted dictionaries also have a sequence-like view called iloc. If you’re
174 coming from Pandas that should look familiar. Line 4 creates a list of the five
175 largest keys in the dictionary.
176
177 Similar to “irange” there is an “islice” method. Islice does positional index
178 slicing. In line 5 we create an iterator over the indexes 10 through 49
179 inclusive.
180
181 One of the benefits of being pure-Python: it’s easy to hack on. Over the years,
182 a few patterns have emerged and become recipes. All of these are available from
183 PyPI with pip install `sortedcollections`_.
184
185 If all that didn’t convince you that `Sorted Containers`_ is great then listen
186 to what `other smart people say`_ about it:
187
188 Alex Martelli says: Good stuff! ... I like the simple, effective implementation
189 idea of splitting the sorted containers into smaller “fragments” to avoid the
190 O(N) insertion costs.
191
192 Jeff Knupp writes: That last part, “fast as C-extensions,” was difficult to
193 believe. I would need some sort of performance comparison to be convinced this
194 is true. The author includes this in the docs. It is.
195
196 Kevin Samuel says: I’m quite amazed, not just by the code quality (it’s
197 incredibly readable and has more comment than code, wow), but the actual amount
198 of work you put at stuff that is not code: documentation, benchmarking,
199 implementation explanations. Even the git log is clean and the unit tests run
200 out of the box on Python 2 and 3.
201
202 If you’re new to sorted collections, I hope I’ve piqued your interest. Think
203 about the achievement here. `Sorted Containers`_ is pure-Python but as fast as
204 C-implementations. Let’s look under the hood of `Sorted Containers`_ at what
205 makes it so fast.
206
207 It really comes down to bisect for the heavy lifting. Bisect is a module in the
208 standard library that implements binary search on lists. There’s also a handy
209 method called insort that does a binary search and insertion for us in one
210 call. There’s no magic here, it’s just implemented in C and part of the
211 standard library.
212
213 Here’s the basic structure. It’s just a list of sublists. So there’s a member
214 variable called “lists” that points to sublists. Each of those is maintained in
215 sorted order. You’ll sometimes hear me refer to these as the top-level list and
216 its sublists.
217
218 There’s no need to wrap sublists in their own objects. They are just
219 lists. Simple is fast and efficient.
220
221 In addition to the list of sublists. There’s an index called the maxes
222 index. That simply stores the maximum value in each sublist. Now lists in
223 CPython are simply arrays of pointers so we’re not adding much overhead with
224 this index.
225
226 Let’s walk through testing membership with contains. Let’s look for element 14.
227
228 Let’s also walk through adding an element. Let’s add 5 to the sorted list.
229
230 Now numeric indexing is a little more complex. Numeric indexing uses a tree
231 packed densely into another list. I haven’t seen this structure described in
232 textbooks or research so I’d like to call it a “Jenks” index. But I’ll also
233 refer to it as the positional index.
234
235 Let’s build the positional index together.
236
237 Remember the positional index is a tree stored in a list, kind of like a heap.
238
239 Let’s use this to lookup index 8. Starting at the root, 18, compare index to
240 the left-child node. 8 is greater than 7 so we subtract 7 from 8 and move to
241 the right-child node. Again, now at node 11, compare index again to the
242 left-child node. 1 is less than 6, so we simply move to the left-child node. We
243 terminate at 6 because it’s a leaf node. Our final index is 1 and our final
244 position is 5. We calculate the top-level list index as the position minus the
245 offset. So our final coordinates are index 2 in the top-level list and index 1
246 in the sublist.
247
248 That’s it. Three lists maintain the elements, the maxes index, and the
249 positional index. We’ve used simple built-in types to construct complex
250 behavior.
251
252 Altogether that gets us to our first performance lesson.
253
254 Builtin types are fast. Like really fast. Builtin types are as fast as C and
255 benefit from years of optimizations.
256
257 Ok, let’s look at the contains method for a sorted list. This is the majority
258 of the code. We bisect the maxes index for the sublist index. Then we bisect
259 the sublist for the element index.
260
261 How many lines of Python code execute? 4.
262
263 How many instructions execute? Hundreds of lines of C-code.
264
265 Rather than programming in Python, I programmed against my interpreter. That’s
266 our next lesson.
267
268 Program your interpreter. The operations provided by the interpreter and
269 standard library are fast. They’re implemented in C. When you program your
270 interpreter, you write C code but in Python.
271
272 Now let’s talk about memory. This is very simplified. My apologies to those who
273 feel this is grossly simplified. Notice the limited sizes: a dozen registers,
274 kilobytes of L1 cache, megabytes of L3 cache. Some machines don’t even have an
275 L3 cache.
276
277 So keep overhead low. Keep related data packed together. Our sublists add
278 roughly one pointer per element. That’s all. It’s 66% less memory than binary
279 tree implementations.
280
281 Also, each memory tier has different performance. Memory slows down by a factor
282 of a thousand from registers to main memory. And the advertised price of memory
283 lookups is often the average random lookup time. But that’s only one common
284 pattern.
285
286 Sequential memory access patterns are so fast you almost don’t pay for them at
287 all. The processor predicts the memory you’ll need next and queues it for you.
288
289 Then there’s also data-dependent memory accesses which happen when you follow
290 pointers. So the next memory location is dependent on the current one. This is
291 typical in binary trees and it’s really slow. It’s as much as ten times slower
292 than random memory access.
293
294 Let’s think about adding elements again. Add calls bisect.insort which does a
295 binary search and then insert on the list.
296
297 Here is the code for insert in CPython. It is entirely sequential memory
298 accesses. Also the binary search process starts random but narrows the search
299 range and so improves locality of memory accesses.
300
301 By comparison, traditional binary trees use data-dependent memory access as
302 they repeatedly dereference pointers. We can sequentially shift a thousand
303 elements in memory in the time it takes to access a couple of binary nodes from
304 DRAM.
305
306 So memory is tiered. And caches are limited in size.
307
308 This is also why the slope of the performance curve for sorted list was less
309 than that for binary tree implementations. At scale, binary trees do more
310 data-dependent DRAM lookups than `Sorted Containers`_.
311
312 I said that initializing a sorted container is fast. Let’s look at why. Here’s
313 the initializer for a `SortedList`_. Notice it simply calls the sorted builtin
314 and then chops up the result into sublists and then initializes the maxes
315 index.
316
317 I think of this as a cheat. I’m using the power of `Timsort`_ to initialize the
318 container. And it turns out initialization is really common. The result is fast
319 and readable.
320
321 Also, how long does it take to initialize already sorted data? Linear
322 time. It’s just a couple mem-copy like operations.
323
324 Here’s another cheat. When we add an element to a sorted set, we add it to both
325 a set object and sorted list. This preserves the fast set membership tests.
326
327 Some purists will argue that `hashing`_ should not be necessary. They are
328 correct, but, if you can define comparisons, then you can probably define
329 hash. Remember that we’re solving real problems, not theoretical ones. If you
330 can reuse the builtin types, then cheat and do it.
331
332 So, if you can, cheat. The way to make things faster is to do less
333 work. There’s no way around that.
334
335 Another cheat I’ve mentioned regards the positional index. If you don’t need
336 numerical lookups, then don’t build the index. That’s a common scenario with
337 sorted dictionaries. We use less memory and run faster.
338
339 When it comes to runtime complexity, here’s the punchline: adding random
340 elements has an amortized cost proportional to the cube root of the container
341 size. That’s an unusual runtime complexity but it works quite well.
342
343 The surprising thing is that “n” stays relatively small in practice. For
344 example, creating a billion integers in CPython will take more than 30
345 gigabytes of memory which is already exceeding the limits of most machines.
346
347 We’ve also seen that memory is expensive. Allocations are costly. In the common
348 case, `Sorted Containers`_ allocates no more memory when adding elements.
349
350 If you’re doubtful about performance at scale, then I encourage you to read the
351 project docs. There’s a page called `Performance at Scale`_ and it talks
352 extensively about theory with benchmarks up to ten billion elements.
353
354 A little PSA before I continue: If you claim to be fast, you’ve got to have
355 measurements. Measure. Measure. Measure. `Big-O notation`_ is not a substitute
356 for benchmarks. Quite often, constants and coefficients that are ignored in
357 theory matter quite a lot in practice.
358
359 So: Measure. Measure. Measure.
360
361 This whole project in fact started with a measurement. I was timing how long it
362 took to add an element to a “blist” when I noticed that “bisect.insort” was
363 actually faster for a list with one thousand elements. It was so much faster in
364 fact, I thought “wow, I could do two inserts in a thousand-element list and
365 still be faster than “blist.” That thought eventually became the list of
366 sublists implementation that we have today.
367
368 So here’s the performance lessons: builtin types are fast; program your
369 interpreter; memory is tiered; cheat, if you can; and measure, measure,
370 measure.
371
372 A couple closing thoughts. Everything related to `Sorted Containers`_ is under
373 an open-source `Apache2 license`_. Contributors are very welcome. We’ve started
374 to create a little community around sorted collections.
375
376 I think it’s interesting to ask: is this worth a PEP? I’m personally on the
377 fence. I think sorted collections would contribute to Python’s maturity. But I
378 don’t know if any proposal could survive the inevitable bike-shedding. My
379 contribution is a pure-Python implementation that’s fast-enough for most
380 scenarios.
381
382 I’ll end with a quote from `Mark Summerfield`_. Mark and a couple other authors
383 have actually deprecated their modules in favor of `Sorted Containers`_. Mark
384 says: “Python’s ‘batteries included’ standard library seems to have a battery
385 missing. And the argument that ‘we never had it before’ has worn thin. It is
386 time that Python offered a full range of collection classes out of the box,
387 including sorted ones.”
388
389 Thanks for letting me share.
390
391 .. _`Python Sorted Collections Video Recording on Youtube`: https://www.youtube.com/watch?v=7z2Ki44Vs4E
392 .. _`Python Sorted Collections Slides`: http://bit.ly/soco-pycon
393 .. _`Python sorted collections`: http://www.grantjenks.com/docs/sortedcontainers/
394 .. _`heapq`: https://docs.python.org/3/library/heapq.html
395 .. _`bisect`: https://docs.python.org/3/library/bisect.html
396 .. _`queue.PriorityQueue`: https://docs.python.org/3/library/queue.html#queue.PriorityQueue
397 .. _`collections.OrderedDict`: https://docs.python.org/3/library/collections.html#collections.OrderedDict
398 .. _`Sqlite in-memory indexes`: https://www.sqlite.org/lang_createindex.html
399 .. _`pandas.DataFrame indexes`: http://pandas.pydata.org/pandas-docs/stable/indexing.html
400 .. _`Redis sorted sets`: https://redis.io/topics/data-types
401 .. _`MutableSequence`: https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes
402 .. _`PyPI`: https://pypi.org/
403 .. _`Dan Stromberg`: http://stromberg.dnsalias.org/~dstromberg/datastructures/
404 .. _`B-tree`: https://en.wikipedia.org/wiki/B-tree
405 .. _`PyPy`: http://pypy.org/
406 .. _`Github`: https://github.com/
407 .. _`Blist`: http://stutzbachenterprises.com/blist/
408 .. _`SortedCollection`: http://code.activestate.com/recipes/577197-sortedcollection/
409 .. _`bintrees`: https://pypi.org/project/bintrees/
410 .. _`Sorted Containers`: http://www.grantjenks.com/docs/sortedcontainers/
411 .. _`Banyan`: https://pythonhosted.org/Banyan/
412 .. _`skiplistcollections`: https://pypi.org/project/skiplistcollections/
413 .. _`Google`: https://www.google.com/
414 .. _`rbtree`: https://pypi.org/project/rbtree/
415 .. _`Sorted Containers`: http://www.grantjenks.com/docs/sortedcontainers/
416 .. _`sorted list`: http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html
417 .. _`sorted dictionary`: http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html
418 .. _`sorted set`: http://www.grantjenks.com/docs/sortedcontainers/sortedset.html
419 .. _`SortedList`: http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html
420 .. _`Performance`: http://www.grantjenks.com/docs/sortedcontainers/performance.html
421 .. _`Timsort`: https://en.wikipedia.org/wiki/Timsort
422 .. _`hashing`: https://en.wikipedia.org/wiki/Hash_function
423 .. _`Big-O notation`: https://en.wikipedia.org/wiki/Big_O_notation
424 .. _`Apache2 license`: http://www.apache.org/licenses/LICENSE-2.0
425 .. _`Mark Summerfield`: http://www.qtrac.eu/pysorted.html
426 .. _`benchmark runtimes`: http://www.grantjenks.com/docs/sortedcontainers/performance-runtime.html
427 .. _`sortedcollections`: http://www.grantjenks.com/docs/sortedcollections/
428 .. _`other smart people say`: http://www.grantjenks.com/docs/sortedcontainers/#testimonials
429 .. _`Performance at Scale`: http://www.grantjenks.com/docs/sortedcontainers/performance-scale.html
430 .. _`sorted collections`: http://www.grantjenks.com/docs/sortedcontainers/
431 .. _`Java`: https://www.java.com/
432 .. _`C++`: https://isocpp.org/
433 .. _`.NET`: https://www.microsoft.com/net
434 .. _`Python`: https://www.python.org/
435 .. _`PHP`: http://php.net/
436 .. _`Javascript`: https://en.wikipedia.org/wiki/ECMAScript
437 .. _`MutableMapping`: https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes
438 .. _`MutableSet`: https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes
439 .. _`load parameters`: http://www.grantjenks.com/docs/sortedcontainers/performance-load.html