Page
1
M A N N I N G Tiago Rodrigues Antão High performance techniques for large datasets
Page
2
Memory hierarchy with sizes and access times for a hypothetical but realistic modern desktop Type Size Access time CPU L1 cache 256 KB 2 ns L2 cache 1 MB 5 ns L3 cache 6 MB 30 ns RAM DIMM 8 GB 100 ns Secondary storage SSD 256 GB 50 µs HDD 2 TB 5 ms Tertiary storage NAS - Network Access Server 100 TB Network dependent Cloud proprietary 1 PB Provider dependent
Page
3
Fast Python HIGH PERFORMANCE TECHNIQUES FOR LARGE DATASETS TIAGO RODRIGUES ANTÃO M A N N I N G SHELTER ISLAND
Page
4
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2023 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Frances Lefkowitz 20 Baldwin Road Technical development editor: Al Krinker PO Box 761 Review editor: Mihaela Batinić Shelter Island, NY 11964 Production editor: Andy Marinkovich Copy editor: Alisa Larson Proofreader: Keri Hales Technical proofreader: Andy Miles Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617297939 Printed in the United States of America
Page
5
iii contents preface ix acknowledgments xi about this book xii about the author xvii about the cover illustration xviii PART 1 FOUNDATIONAL APPROACHES....................................1 1 An urgent need for efficiency in data processing 3 1.1 How bad is the data deluge? 4 1.2 Modern computing architectures and high- performance computing 7 Changes inside the computer 8 ■ Changes in the network 10 The cloud 11 1.3 Working with Python’s limitations 12 The Global Interpreter Lock 13 1.4 A summary of the solutions 14
Page
6
CONTENTSiv 2 Extracting maximum performance from built-in features 17 2.1 Profiling applications with both IO and computing workloads 18 Downloading data and computing minimum temperatures 19 Python’s built-in profiling module 21 ■ Using local caches to reduce network usage 22 2.2 Profiling code to detect performance bottlenecks 23 Visualizing profiling information 24 ■ Line profiling 25 The takeaway: Profiling code 27 2.3 Optimizing basic data structures for speed: Lists, sets, and dictionaries 28 Performance of list searches 28 ■ Searching using sets 29 List, set, and dictionary complexity in Python 30 2.4 Finding excessive memory allocation 32 Navigating the minefield of Python memory estimation 32 The memory footprint of some alternative representations 35 Using arrays as a compact representation alternative to lists 37 Systematizing what we have learned: Estimating memory usage of Python objects 38 ■ The takeaway: Estimating memory usage of Python objects 39 2.5 Using laziness and generators for big-data pipelining 39 Using generators instead of standard functions 40 3 Concurrency, parallelism, and asynchronous processing 43 3.1 Writing the scaffold of an asynchronous server 46 Implementing the scaffold for communicating with clients 48 Programming with coroutines 49 ■ Sending complex data from a simple synchronous client 50 ■ Alternative approaches to interprocess communication 52 ■ The takeaway: Asynchronous programming 52 3.2 Implementing a basic MapReduce engine 52 Understanding MapReduce frameworks 53 ■ Developing a very simple test scenario 54 ■ A first attempt at implementing a MapReduce framework 54 3.3 Implementing a concurrent version of a MapReduce engine 55 Using concurrent.futures to implement a threaded server 55 Asynchronous execution with futures 57 ■ The GIL and multithreading 59
Page
7
CONTENTS v 3.4 Using multiprocessing to implement MapReduce 60 A solution based on concurrent.futures 60 ■ A solution based on the multiprocessing module 62 ■ Monitoring the progress of the multiprocessing solution 63 ■ Transferring data in chunks 65 3.5 Tying it all together: An asynchronous multithreaded and multiprocessing MapReduce server 68 Architecting a complete high-performance solution 68 ■ Creating a robust version of the server 72 4 High-performance NumPy 75 4.1 Understanding NumPy from a performance perspective 76 Copies vs. views of existing arrays 76 ■ Understanding NumPy’s view machinery 81 ■ Making use of views for efficiency 86 4.2 Using array programming 88 The takeaway 89 ■ Broadcasting in NumPy 90 ■ Applying array programming 92 ■ Developing a vectorized mentality 94 4.3 Tuning NumPy’s internal architecture for performance 97 An overview of NumPy dependencies 97 ■ How to tune NumPy in your Python distribution 99 ■ Threads in NumPy 100 PART 2 HARDWARE ........................................................103 5 Re-implementing critical code with Cython 105 5.1 Overview of techniques for efficient code re-implementation 106 5.2 A whirlwind tour of Cython 107 A naive implementation in Cython 108 ■ Using Cython annotations to increase performance 110 ■ Why annotations are fundamental to performance 111 ■ Adding typing to function returns 113 5.3 Profiling Cython code 114 Using Python’s built-in profiling infrastructure 115 ■ Using line_profiler 116 5.4 Optimizing array access with Cython memoryviews 119 The takeaway 121 ■ Cleaning up all internal interactions with Python 121
Page
8
CONTENTSvi 5.5 Writing NumPy generalized universal functions in Cython 122 The takeaway 124 5.6 Advanced array access in Cython 124 Bypassing the GIL’s limitation on running multiple threads at a time 127 ■ Basic performance analysis 130 ■ A spacewar example using Quadlife 131 5.7 Parallelism with Cython 132 6 Memory hierarchy, storage, and networking 135 6.1 How modern hardware architectures affect Python performance 137 The counterintuitive effect of modern architectures on performance 137 ■ How CPU caching affects algorithm efficiency 138 ■ Modern persistent storage 139 6.2 Efficient data storage with Blosc 140 Compress data; save time 140 ■ Read speeds (and memory buffers) 142 ■ The effect of different compression algorithms on storage performance 143 ■ Using insights about data representation to increase compression 144 6.3 Accelerating NumPy with NumExpr 144 Fast expression processing 145 ■ How hardware architecture affects our results 146 ■ When NumExpr is not appropriate 147 6.4 The performance implications of using the local network 147 The sources of inefficiency with REST calls 148 ■ A naive client based on UDP and msgpack 148 ■ A UDP-based server 150 Dealing with basic recovery on the client side 151 ■ Other suggestions for optimizing network computing 152 PART 3 APPLICATIONS AND LIBRARIES FOR MODERN DATA PROCESSING ..............................................155 7 High-performance pandas and Apache Arrow 157 7.1 Optimizing memory and time when loading data 158 Compressed vs. uncompressed data 158 ■ Type inference of columns 160 ■ The effect of data type precision 162 ■ Recoding and reducing data 164
Page
9
CONTENTS vii 7.2 Techniques to increase data analysis speed 166 Using indexing to accelerate access 166 ■ Row iteration strategies 167 7.3 pandas on top of NumPy, Cython, and NumExpr 170 Explicit use of NumPy 170 ■ pandas on top of NumExpr 171 Cython and pandas 173 7.4 Reading data into pandas with Arrow 174 The relationship between pandas and Apache Arrow 175 Reading a CSV file 176 ■ Analyzing with Arrow 178 7.5 Using Arrow interop to delegate work to more efficient languages and systems 179 Implications of Arrow’s language interop architecture 179 Zero-copy operations on data with Arrow’s Plasma server 180 8 Storing big data 186 8.1 A unified interface for file access: fsspec 187 Using fsspec to search for files in a GitHub repo 187 ■ Using fsspec to inspect zip files 189 ■ Accessing files using fsspec 189 ■ Using URL chaining to traverse different filesystems transparently 190 ■ Replacing filesystem backends 190 ■ Interfacing with PyArrow 191 8.2 Parquet: An efficient format to store columnar data 191 Inspecting Parquet metadata 192 ■ Column encoding with Parquet 194 ■ Partitioning with datasets 196 8.3 Dealing with larger-than-memory datasets the old-fashioned way 197 Memory mapping files with NumPy 198 ■ Chunk reading and writing of data frames 199 8.4 Zarr for large-array persistence 201 Understanding Zarr’s internal structure 202 ■ Storage of arrays in Zarr 204 ■ Creating a new array 206 ■ Parallel reading and writing of Zarr arrays 208 PART 4 ADVANCED TOPICS..............................................211 9 Data analysis using GPU computing 213 9.1 Making sense of GPU computing power 215 Understanding the advantages of GPUs 215 ■ The relationship between CPUs and GPUs 217 ■ The internal architecture of GPUs 218 ■ Software architecture considerations 219
Page
10
CONTENTSviii 9.2 Using Numba to generate GPU code 220 Installation of GPU software for Python 220 ■ The basics of GPU programming with Numba 221 ■ Revisiting the Mandelbrot example using GPUs 224 ■ A NumPy version of the Mandelbrot code 227 9.3 Performance analysis of GPU code: The case of a CuPy application 228 GPU-based data analysis libraries 228 ■ Using CuPy: A GPU-based version of NumPy 229 ■ A basic interaction with CuPy 229 ■ Writing a Mandelbrot generator using Numba 230 ■ Writing a Mandelbrot generator using CUDA C 232 ■ Profiling tools for GPU code 234 10 Analyzing big data with Dask 238 10.1 Understanding Dask’s execution model 240 A pandas baseline for comparison 240 ■ Developing a Dask-based data frame solution 241 10.2 The computational cost of Dask operations 243 Partitioning data for processing 244 ■ Persisting intermediate computations 245 ■ Algorithm implementations over distributed data frames 246 ■ Repartitioning the data 249 ■ Persisting distributed data frames 251 10.3 Using Dask’s distributed scheduler 252 The dask.distributed architecture 253 ■ Running code using dask.distributed 257 ■ Dealing with datasets larger than memory 262 appendix A Setting up the environment 265 appendix B Using Numba to generate efficient low-level code 269 index 275
Page
11
ix preface A few years ago, a Python-based pipeline that my team was working on suddenly ground to a halt. A process just kept using CPU and was not finalizing. This function was critical to the company and we needed to solve the problem sooner rather than later. We looked at the algorithm and it seemed OK—in fact, it was quite a simple implementation. After many hours with several engineers looking at the problem, we found that it all boiled down to searching on a list—a very big list. The problem was trivially solved after converting the list into a set. We ended up with a much smaller data structure with search times in milliseconds, not hours. I had several epiphanies at that time: ■ It was a trivial problem, but our development process was not concerned with performance issues. For example, if we had routinely used a profiler, we would have discovered the performance bug in minutes, not hours. ■ This was a win-win situation: we ended up consuming less time and less mem- ory. Yes, in many cases, there are tradeoffs to be made, but in others, there are some really effective results with no downsides. ■ From a larger perspective, this situation was also a win-win. First, faster results are great for the company’s bottom line. Second, a good algorithm uses less CPU time, which means less electricity, and the use of less electricity (i.e., resources) is better for the planet. ■ While our single case doesn’t do much to save energy, it dawned on me that many programmers are designing similar solutions.
Page
12
PREFACEx I decided to write this book so other programmers could benefit from my epiphanies. My objective is to help seasoned Python programmers to design and implement solu- tions that are more efficient, along with with an understanding of the potential tradeoffs. I wanted to take a holistic approach to the subject by discussing pure Python and important Python libraries, taking an algorithmic perspective and considering modern hardware architectures and their implications, and discussing CPU and stor- age performance. I hope this book helps you to be more confident in approaching performance problems while developing in the Python ecosystem.
Page
13
xi acknowledgments I would like to thank development editor Frances Lefkowitz for her infinite patience. I would also like to thank my daughter and wife, who had to endure my absence the last few years while I was writing this book. Thanks also to the production team at Man- ning who helped create this book. To all the reviewers: Abhilash Babu Jyotheendra Babu, Andrea Smith, Biswanath Chowdhury, Brian Griner, Brian S Cole, Dan Sheikh, Dana Robinson, Daniel Vasquez, David Paccoud, David Patschke, Grzegorz Mika, James Liu, Jens Christian B. Madsen, Jeremy Chen, Kalyan Reddy, Lorenzo De Leon, Manu Sareena, Nik Piepenbreier, Noah Flynn, Or Golan, Paulo Nuin, Pegah T. Afshar, Richard Vaughan, Ruud Gijsen, Shashank Kalanithi, Simeon Leyzerzon, Simone Sguazza, Sriram Macharla, Sruti Shi- vakumar, Steve Love, Walter Alexander Mata López, William Jamir Silva, and Xie Yikuan—your suggestions helped make this a better book.
Page
14
xii about this book The purpose of this book is to help you write more efficient applications in the Python ecosystem. By more efficient, I mean that your code will use fewer CPU cycles, less storage space, and less network communication. The book takes a holistic approach to the problem of performance. We not only discuss code optimization techniques in pure Python, but we also consider the effi- cient use of widely used data libraries, like NumPy and pandas. Because Python is not sufficiently performant in some cases, we also consider Cython when we need more speed. In line with this holistic approach, we also discuss the impact of hardware on code design: we analyze the impact of modern computer architectures on algorithm performance. We also examine the effect of network architectures on efficiency, and we explore the usage of GPU computing for fast data analysis. Who should read this book? This book is intended for an intermediate to advanced audience. If you skim the table of contents, you should recognize most of the technologies, and you probably have used quite a few of them. Except for the sections on IO libraries and GPU computing, little introductory material is provided: you need to already know the basics. If you are currently writing code to be performant and facing real challenges in dealing with so much data efficiently, then this book is for you. To gain the most benefit from this book, you should have at least a couple of years of Python experience and know Python control structures and what lists, sets, and dic- tionaries are. You should have experience with some of the Python standard libraries
Page
15
ABOUT THIS BOOK xiii like os, sys, pickle, and multiprocessing. To take the best advantage of the techniques I present here, you should also have some level of exposure to standard data analysis libraries, like NumPy—with at least minimal exposure to arrays—and pandas—with some experience with data frames. It would be helpful if you are aware of, even if you have no direct exposure to, ways to accelerate Python code through either foreign language interfaces to C or Rust or know of alternative approaches, like Cython or Numba. Experience dealing with IO in Python will also help you. Given that IO libraries are less explored in the literature, we will start from the very beginning with formats like Apache Parquet and libraries like Zarr. You should know the basic shell commands of Linux terminals (or MacOS termi- nals). If you are on Windows, please have either a Unix-based shell installed or know your way around the command line or PowerShell. And, of course, you need Python software installed on your computer. In some cases, I will provide tips for the cloud, but cloud access or knowledge is not a requirement for reading this book. If you are interested in cloud approaches, then you should know how to do basic operations like creating instances and access- ing the storage of your cloud provider. While you do not have to be academically trained in the field, a basic notion of complexity costs will be helpful—for example, the intuitive notion that algorithms that scale linearly with data are better than algorithms that scale exponentially. If you plan on using GPU optimizations, you are not expected to know anything at this stage. How this book is organized: A road map The chapters in this book are mostly independent, and you can jump to whichever chapter is important to you. That being said, the book is divided into four parts. Part 1, Foundational Approaches (chapters 1–4), covers introductory material. ■ Chapter 1 introduces the problem and explains why we must pay attention to efficiency in computing and storage. It also introduces the book’s approach and offers suggestions for navigating it for your needs. ■ Chapter 2 covers the optimization of native Python. We also discuss the optimi- zation of Python data structures, code profiling, memory allocation, and lazy programming techniques. ■ Chapter 3 discusses concurrency and parallelism in Python and how to make the best use of multiprocessing and multithreading (including the limitations of parallel processing when using threads). This chapter also covers asynchro- nous processing as an efficient way to deal with multiple concurrent requests with low workloads, typical of web services. ■ Chapter 4 introduces NumPy, a library that allows you to process multidimen- sional arrays efficiently. NumPy is at the core of all modern data processing techniques, and as such, it is treated as a fundamental library. This chapter shares specific NumPy techniques to develop more efficient code, such as views, broadcasting, and array programming.
Page
16
ABOUT THIS BOOKxiv Part 2, Hardware (chapters 5 and 6), is mostly concerned with extracting the maxi- mum efficiency of common hardware and networks. ■ Chapter 5 covers Cython, a superset of Python that can generate very efficient code. Python is a high-level interpreted language and, as such, is not expected to be optimized for the hardware. There are several languages, such as C or Rust, that are designed to be as efficient as possible at the hardware level. Cython belongs to that domain of languages: while it is very close to Python, it compiles to C code. Generating the most efficient Cython code requires being mindful of how the code maps to an efficient implementation. In this chapter, we learn how to create efficient Cython code. ■ Chapter 6 discusses the effect of modern hardware architectures on the design of efficient Python code. Given the way modern computers are designed, some counterintuitive programming approaches may be more efficient than expected. For example, in some cases, dealing with compressed data may be faster than dealing with uncompressed data, even if we need to pay the price of uncompress- ing the algorithm. This chapter also covers the effect of CPU, memory, storage, and network on Python algorithm design. We discuss NumExpr, a library that can make NumPy code more efficient by using the properties of modern hardware architecture. Part 3, Applications and Libraries for Modern Data Processing (chapters 7 and 8), looks at the typical applications and libraries used in modern data processing. ■ Chapter 7 concentrates on using pandas, the data frame library used in Python, as efficiently as possible. We’ll look at pandas-related techniques to optimize code. Unlike most chapters in the book, this one builds from an earlier chapter. pandas works on top of NumPy, so we will draw from what we learn in chapter 4 and discover NumPy-related techniques to optimize pandas. We also look at how to optimize pandas with NumExpr and Cython. Finally, I introduce Arrow, a library that, among other functionalities, can be used to increase the perfor- mance of processing pandas data frames. ■ Chapter 8 examines the optimization of data persistence. We discuss Parquet, a library to process columnar data efficiently, and Zarr, which can process very large on-disk arrays. We also start a discussion about how to deal with datasets that are larger than memory. Part 4, Advanced Topics (chapters 9 and 10), deals with two final, and very different, approaches: working with GPUs and using the Dask library. ■ Chapter 9 looks at the uses of graphical processing units (GPUs) to process large datasets. We will see that the GPU computing model—using many simple processing units—is quite adequate to deal with modern data science problems. We use two different approaches to take advantage of GPUs. First, we will dis- cuss existing libraries that provide similar interfaces to libraries that you know,
Page
17
ABOUT THIS BOOK xv such as CuPy as a GPU version of NumPy. Second, we will cover how to generate code to run on GPUs from Python. ■ Chapter 10 discusses Dask, a library that allows you to write parallel code that scales out to many machines—either on-premises or in the cloud—while pro- viding familiar interfaces similar to NumPy and pandas. The book also includes two appendixes. ■ Appendix A walks you through the installation of software necessary to use the examples in this book. ■ Appendix B discusses Numba, an alternative to Cython to generate efficient low-level code. Cython and Numba are the main avenues to generate low-level code. To solve real-world problems, I recommend Numba. Why, then, did I ded- icate an entire chapter to Cython and put Numba at the back of the book? Because the main purpose of this book is to give you a solid foundation for writ- ing efficient code in the Python ecosystem, and Cython, with its extra hurdles, allows us to dig deeper in terms of understanding what is going on. About the code This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to high- light code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/fast-python. The complete code for the examples in the book is available for download from GitHub at https://github.com/ tiagoantao/python-performance, and from the Manning website at www.manning .com. I will update the repository when bugs are found or when major developments to Python and existing libraries require some revisions. As such, please expect some changes in the book repository. You will find a directory for each chapter in the repository. Whatever code style you prefer, I have adapted the code herein to work well in a printed book. For example, I tend to be partial to long and descriptive variable names, but these do not work well with the limitations of book form. I try to use expressive names and follow standard Python conventions like PEP8, but book legibil- ity takes precedence. The same is valid for type annotations: I would like to use them,
Page
18
ABOUT THIS BOOKxvi but they get in the way of code readability. In some very rare cases, I use an algorithm to increase readability, even though it doesn’t deal with all corner cases or add much to the explanation. In most cases, the code in this book will work with the standard Python interpreter. In some limited scenarios, IPython will be required, especially for the expedient per- formance analysis. You can also use Jupyter Notebook. Details about the installation can be found in appendix A. If any chapter or section requires special software, that will be noted in the appropriate place. liveBook discussion forum Purchase of Fast Python includes free access to liveBook, Manning’s online reading plat- form. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/book/fast-python/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook .manning.com/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We sug- gest you try asking the author some challenging questions lest their interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website for as long as the book is in print. Hardware and software You can use any operating system to run the code in this book. That being said, Linux is where most production code tends to be deployed, so that is the preferred system. MacOS X should also work without any adaptations. If you use Windows, I recom- mend that you install Windows Subsystem for Linux (WSL). An alternative to all operating systems is Docker. You can use the Docker images provided in the repository. Docker will provide a containerized Linux environment to run the code. I recommend you have at least 16 GB of memory and 150 GB of free disk space. Chapter 9, with GPU-related content, requires an NVIDIA GPU, at least based on the Pascal architecture; most GPUs released in the last five years should cover this require- ment. More details about preparing your computer and software to get the most from this book can be found in appendix A.
Page
19
xvii about the author TIAGO RODRIGUES ANTÃO has a BEng in Informatics and a PhD in bioinformatics. He currently works in the biotech field. Tiago uses Python with all its libraries to perform scientific computing and data engineering tasks. More often than not, he also uses low-level programming languages such as C and Rust to optimize critical parts of algo- rithms. He currently develops on an infrastructure based on Amazon AWS, but for most of his career, he used on-premises computing and scientific clusters. In addition to working in the industry, his experience with the academic side of sci- entific computing includes two data analysis post-docs at Cambridge University and Oxford University. As a research scientist at the University of Montana, he created, from scratch, the entire scientific computing infrastructure for the analysis of biologi- cal data. Tiago is one of the co-authors of Biopython, a major bioinformatics package written in Python, and is author of the book Bioinformatics with Python Cookbook (Packt, 2022), which is in its third edition. He has also authored and co-authored many important scientific articles in the field of bioinformatics.
Page
20
xviii about the cover illustration The figure on the cover of Fast Python is captioned “Bourgeoise de Passeau,” or “Bour- geoise of Passeau,” taken from a collection by Jacques Grasset de Saint-Sauveur, pub- lished in 1797. Each illustration is finely drawn and colored by hand. In those days, it was easy to identify where people lived and what their trade or sta- tion in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional cul- ture centuries ago, brought back to life by pictures from collections such as this one.