In v0.100.3, we quietly rolled out support for GIL-free multi-threading for spaCy’s syntactic dependency parsing and named entity recognition models. Because these models take up a lot of memory, we’ve wanted to release the global interpretter lock (GIL) around them for a long time. When we finally did, it seemed a little too good to be true, so we delayed celebration — and then quickly moved on to other things. It’s now past time for a write-up.
This is mostly an implementation post, but to me, implementation is the pain and
the product is the pleasure. So, let’s start with the pay-off. The pay-off is
.pipe() method, which adds data-streaming capabilities to spaCy:
.pipe() method accepts an iterator (above,
texts), and produces an
iterator. Internally, a buffer is accumulated (given by the
argument, and multiple threads are allowed to work on the batch simultaneously.
Once the batch is complete, the processed documents are yielded from the
Each document is processed independently, so if your batch size is large enough, and OpenMP is enabled, you should be able to work all your cores with only one copy of the spaCy models in memory. spaCy is designed for web-scale data processing — we want you to be able to perform sophisticated linguistic analysis on whole dumps of the Common Crawl. With effective shared memory parallelism, those jobs are many times cheaper.
|Method||Number threads||Seconds 1|
- Seconds to parse 20,000 documents, with 1, 2 or 4 threads. Lower is better.
The loop condition uses the
doc = nlp(text)function, instead of the
.pipemethod to show the overhead incurred from the minibatched stream processing (within measurement error).
Endless ink has been spilled about the CPython Global Interpretter Lock (GIL). It isn’t a problem for most code, but for spaCy, it really is. Computers may be fast and getting faster, but the internet is big and getting bigger. We have a lot fo text to process, and we’d like to use our machines efficiently.
Python maintains reference counts in a global data structure. When you create or delete a Python object, its reference count has to change. However, the data structure holding the reference counts is not thread-safe. To change the reference counts, you therefore need to acquire the global interpretter lock.
One way around the GIL is therefore to avoid the need for Python variables. This is what I’ve done with spaCy. More specifically, spaCy is a Python library, but it’s not actually written in Python. It’s implemented in Cython, and transpiled into a C++ extension module.
In ordinary Python code, you can have a list of numbers like this:
In Cython, you can write exactly the same code, but the code is not interpreted by Python directly. Instead, it’s transpiled into C or C++ code, which calls the Python C-API. Here’s some of the resulting code:
You can’t call any of those functions if you’re not holding the GIL. But you can
call plain old C and C++ functions, such as
nogil keyword allows you to declare that a function is safe to call
even if you’re not already holding the GIL. You can read more about releasing
the GIL with Cython
The disadvantages of writing with
nogil semantics are obvious — you’re limited
to writing C with (arguably) nicer syntax. If
you’ve never tried it, I think it’s an interesting exercise to do without the
Python semantics. It does make you appreciate what the language is providing.
Probably the thing I miss most are the exceptions and the lists. The Python
unicode object is also very useful.
Here’s the implementation of the Parser.pipe method in spaCy. This method does the following:
- Buffers the texts into temporary work arrays
- Releases the GIL
- Iterates over the work arrays in an OpenMP
- Calls the
Parser.parseC()method for each unit of work (each document)
The actual mechanics of the multi-threading are super simple, because NLP is
(often) embarrassingly parallel — every document is parsed independently, so we
just need to make a
prange loop over a stream of texts. The
is an auto-magical work-sharing loop, that manages the OpenMP semantics for you.
You still need to reason about false-sharing, thread safety, etc — all the parts
that make writing multi-threaded code fundamentally challenging. But, at least
the calling syntax is clean, and a few incidental details are taken care of for
I couldn’t tell you that multi-threading the parser was easy. At least, not with a straight face. I’ve never written a significant Java program, but I imagine writing multi-threaded Java is significantly easier. Using Cython, the task was at least possible. But it definitely wasn’t easy.
If you count my time in academia, I’ve been writing statistical parsers in
Cython for a five or six years now, and I’ve always wanted to release the GIL
around the parsing loop. By late 2015 I had the machine learning, hash table,
outer parsing loop, and most of the feature extraction as
nogil functions. But
had a complicated interface, and was implemented as a
cdef class. I couldn’t
create this object or store it in a container without acquiring the GIL.
The break-through came when I figured out an undocumented way to write a C++
class in Cython. This allowed me to hollow out the existing
cdef class that
controlled the parser state. I proxied its interface to the inner C++ class,
method by method. This way I could keep the code working, and make sure I didn’t
introduce any subtle bugs into the feature calculation.
You can see the inner class
If you navigate around the git history of this file, you can see the patches
where I implemented the
Natural language processing (NLP) programs have some peculiar performance characterstics. The algorithms and data structures involved are often rather complicated, and the numeric calculations being performed are often quite trivial.
spaCy’s parser and named entity recognition system have to make two or three predictions on each word of the input document, using a linear model. All of the complexity is in the feature extraction and state management code, and the computational bottle-neck ends up being retrieval of the weights data from main memory.
When we finally switch over to a neural network model, the considerations will be a little bit different. It’s possible to implement the parser such that you’re stepping forward through multiple sentences at once. However, that has its own challenges. I think it’s both easier and more effective to parallelise the outer loop, so I expect the work put into the current implementation will serve us well.