You kick off a grid search, walk away for coffee, come back, and the CPU monitor says one core is busy while thirty sit idle. The culprit is rarely your model code; it is the glue around it. joblib is that glue — the small library underneath scikit-learn that turns a Python for loop into a process fan-out and turns an expensive function into a disk cache. When it works you never see it, and when it misbehaves you get frozen notebooks, spawned-but-idle workers, or a cache directory that quietly swallows tens of gigabytes.
The second pain is numeric: you hand a 4 GB feature matrix to a multiprocessing pool and watch memory double, because pickling the argument for every worker means a full copy per process. joblib’s answer is memory mapping — big arrays are written once to a temporary file and every worker maps the same physical pages instead of holding private copies. That single trick is why scikit-learn can parallelize estimators over data that is larger than your RAM.
The third pain is recompute: a crash at 90% of a long feature-extraction job, or an notebook re-run that repeats yesterday’s expensive call. Memory is joblib’s memoization layer — it hashes your function and its inputs, stores the output on disk, and hands back the stored bytes when the hash matches. Getting that hash to be stable across sessions is surprisingly subtle, and the source shows just how many corner cases (memory-mapped arrays, interned dtypes, changing bytecode) it has to absorb.
Overview of joblib's main layers: the user-facing API of Parallel and delayed, the dispatch loop that batches tasks, pluggable backends topped by loky, the memmapping executor that transports large arrays, the numpy-aware pickle stream, and the Memory cache sitting on store backends.
Reading the overview from left to right:
- delayed, L656 wraps a callable and its arguments into an inert tuple, so nothing executes until Parallel consumes it.
- Parallel, L962 is the engine class; its
__call__starts the dispatch loop and yields results as they complete. - parallel_config, L224 is the context-manager stack that lets an outer caller pin
n_jobsand the backend for inner calls. - dispatch_one_batch, L1465 pops the next chunk of pre-dispatched tasks and submits one batch to the backend.
- AutoBatchingMixin, L448 adaptively resizes batches so each dispatch hides scheduling overhead.
- LokyBackend, L722 is the default process backend; it owns a reusable loky worker pool.
- NumpyArrayWrapper, L64 carries array metadata through the custom pickle stream so raw bytes can be memory-mapped on load.
- Memory, L963 configures the disk store and hands out the
cachedecorator for memoization.
The detail view goes one level deeper, and it is worth opening before reading the sections below.
Detailed view: `BatchedCalls` and `BatchCompletionCallBack` inside the dispatch loop, the backend class hierarchy from `ParallelBackendBase` down to `LokyBackend`, the `MemmappingExecutor` plus its reducers and the loky resource tracker, the numpy pickle pair with its array wrapper and compressor registry, and the `Memory` class hierarchy over the filesystem store backend and hashers.
The dispatch loop: from delayed tuples to finished batches
Everything starts with Parallel(n_jobs=8)([delayed(f)(x) for x in tasks]). The iterable you pass is consumed lazily: _start wraps it with pre_dispatch, which defaults to '2 * n_jobs' (parallel.py, L1048). That means only twice as many tasks as there are workers are queued up front — the point is bounded memory when tasks carry large arguments.
Each submitted batch is not a bare function. BatchedCalls (parallel.py, L591) is a small callable that holds a list of (func, args, kwargs) triples and executes them one by one on the worker; it is also what allows nested calls like Parallel(n_jobs=1) inside a worker to find their backend. Completion is tracked by BatchCompletionCallBack (parallel.py, L692), which stamps the dispatch-to-finish duration and reports it back through backend.batch_completed, and increments n_completed_tasks for the progress bar driven by print_progress.
The retrieval side is deliberately decoupled: _retrieve (parallel.py, L1784) waits on finished batches, registers outcomes, and raises the first exception fast via _raise_error_fast so a crashing worker does not leave you waiting for the whole queue. With n_jobs=1 the whole machinery short-circuits into _get_sequential_output, which is the same loop without any transport at all.
Backends and the 0.2-second batch target
All backends implement one abstract contract, ParallelBackendBase (_parallel_backends.py, L104): configure, effective_n_jobs, apply_async, and abort semantics for nested parallelism. Four built-ins ship in the file: SequentialBackend for n_jobs=1, ThreadingBackend (L554) for work that releases the GIL, MultiprocessingBackend over the classic pool, and LokyBackend (L722), which the module registry sets as the default at import time (DEFAULT_BACKEND = "loky", parallel.py, L65). Third parties plug in with register_parallel_backend (parallel.py, L910); joblib itself registers a dask bridge, DaskDistributedBackend (_dask.py, L143), which maps Parallel calls onto dask distributed clients when both packages are importable.
The most interesting engineering lives in AutoBatchingMixin (_parallel_backends.py, L448). Dispatching one task per IPC message wastes time on protocol overhead when tasks are tiny; dispatching one giant batch starves workers when tasks are uneven. The mixin tracks a smoothed (exponentially weighted, 0.8/0.2) batch duration (L542) and retunes compute_batch_size so a batch lands between MIN_IDEAL_BATCH_DURATION = 0.2 seconds and MAX_IDEAL_BATCH_DURATION = 2 seconds (L455). Grow slowly (capped at 2× per step), shrink fast — the comments cite the auto-batching benchmark script in benchmarks/ as the source of those constants. If your tasks each take minutes, batch_size="auto" converges to 1 and behaves like plain multiprocessing; if they take microseconds, it climbs until IPC cost is hidden.
Memmapping: how big arrays skip the pickle copy
When the loky backend starts workers it does not use a raw executor. LokyBackend calls get_memmapping_executor (_parallel_backends.py, L757), and MemmappingExecutor (executor.py, L23) is where the transport decisions happen. It reuses a single executor across successive Parallel calls when the constructor arguments match (the reuse check is at executor.py, L46) — that is why back-to-back scikit-learn fits do not respawn a worker pool each time. On top of the executor it installs a pair of reducers from get_memmapping_reducers (_memmapping_reducer.py, L527).
The forward reducer, ArrayMemmapForwardReducer (_memmapping_reducer.py, L353), checks each ndarray argument: if a.nbytes > self._max_nbytes (L430) — the Parallel default is '1M', i.e. one megabyte — the array is dumped once to <pid>-<thread>-<uuid>.pkl inside the shared temporary folder (L451) and workers receive a memory map of that file instead of bytes. The loky resource tracker registers the file (L478) so it is unlinked only when all processes have released their mappings, and TemporaryResourcesManager cleans the folder on executor shutdown. Arrays flowing the other way (results) are deliberately reduced backward into plain in-memory copies by reduce_array_memmap_backward (L337), so a worker writing into a memmap can never silently corrupt the caller’s view.
From a 16-byte pad to MD5 tags: build facts in the numbers
The persistence layer is full of small, hard-won constants. The custom pickle stream starts array payloads at 16-byte-aligned offsets (NUMPY_ARRAY_ALIGNMENT_BYTES = 16, numpy_pickle.py, L61) — one padding-length byte, then filler — so the array body can be memory-mapped straight from the file even when compressed wrappers shift offsets. Writes go through an nditer with a 16 MiB buffer (L126) to hide the Python loop; arrays of Python objects fall back to nested pickle protocol 5 (L131). A subtle overflow bug is handled explicitly: the element count is computed by casting shape entries to int64 to prevent a multiplication overflow (L170, referencing issue #859).
On the memoization side, hashing is a subclassed Pickler. NumpyHasher (hashing.py, L183) hashes ndarray contents from a raw C-contiguous buffer instead of pickling them, then replaces the object with a tagged tuple (klass, ("HASHED", dtype, shape, strides)) (L249) so two views of the same bytes with different dtypes hash differently — and, under coerce_mmap=True, a memmap and its in-memory twin hash the same. Interned dtypes get their own _HASHED_DTYPE escape hatch (L266) because pickle memoization would otherwise make [np.dtype('f4'), np.dtype('f4')] and its round-tripped twin disagree. The default digest is md5 (hash(obj, hash_name="md5", ...), hashing.py, L272). Compression is a registry of wrappers — zlib, gzip, bz2, lzma, xz and optional lz4 — selected by filename extension in compressor.py (register_compressor, L47). All of this ships in a package whose __init__ declares version 1.7.dev0 (init.py, L109) with zero mandatory dependencies beyond CPython’s standard library, which is exactly why the GIL-bound threading backend (_parallel_backends.py, L557) and pickle protocol details matter so much to its design.
Memory: hashing your way to a cache hit
Memory(location=...) (memory.py, L963) builds a store backend through _store_backend_factory (L108) — the shipped backend is FileSystemStoreBackend (_store_backends.py, L508) — and hands out cache (L1048), which wraps your function into a MemorizedFunc (L360). A call first hashes the function identity and its arguments (hashing.hash, L658), checks the store, and on a miss computes, persists the output and the input payload, and records duration metadata. Shelved results come back as MemorizedResult (L166) handles that load lazily, optionally memory-mapping numpy outputs when mmap_mode is set — which is how the cache hands a 10 GB array to the caller without reading it.
The store itself enforces hygiene: _concurrency_safe_write (_store_backends.py, L395) writes to a temporary file and renames atomically so two concurrent runs cannot interleave a half-written result, and enforce_store_limits (L317) evicts entries by size, count or age — the expires_after helper (memory.py, L1252) builds the age policy. Staleness is caught by _check_previous_func_code (L692): when your function’s bytecode changes, the old cache is invalidated (with a warning) rather than silently reused.
Honest Limits
joblib does not solve distributed computing on a cluster by itself — the loky backend is single-host, and the dask bridge delegates scheduling to dask rather than reimplementing it; for clusters you are configuring a different backend, not scaling this one. The memmapping magic only applies to numpy arrays; a dict of tensors or a pandas frame is pickled byte-for-byte, so the “zero-copy” promise stops at the ndarray boundary. Enjoyed this post? Never miss out on future posts by following us batch_size="auto" heuristics were tuned on benchmarks for small-to-medium tasks and can oscillate for extremely bimodal workloads. Memoization hashes what it can see: if your function reads a file, a database, or a random seed outside its arguments, the cache will happily return stale data — ignore and cache_validation_callback exist precisely because the default hash cannot know your side effects. And while the store is concurrency-safe for writes, it is not a transactional database; long-running jobs killed mid-call can leave orphaned temporary folders that the resource tracker reaps only on a healthy interpreter exit. The test suite is pytest-based, with joblib/testing.py exposing pytest helpers and the root conftest.py, L5 wiring skip conditions for missing optional deps like lz4 — it is the honest map of what is guaranteed, so read it before betting production workloads on edge behaviors.