Repository navigation
Description
There are a couple of modifications to the dict that we can make to enable optimizations.
These changes aren't designed to speedup dictionary operations (although they shouldn't slow them down) but to allow a larger range of speculative optimizations.
Exploit the immutability of shared dict keys.
Shared keys can only be added to, never removed from. By setting the dk_usable field to zero, no more keys can be added and the dict-keys becomes immutable.
Here are a couple of examples uses:
-
Loading from builtins. If
globals->keys == EXPECTED_KEYSandkey not in EXPECTED_KEYSandEXPECTED_KEYSis immutable, then we can read frombuiltinswithout have to checkglobals. If the values inglobalschange, but the keys don't (as would be the case for global variables) then we still get fast access to builtins. -
Loading a method. Functions are non-overriding descriptors, so to cache a function in
LOAD_METHODwe just need to check thatobj->dict->keys == EXPECTED_KEYSprovided thatkey not in EXPECTED_KEYSandEXPECTED_KEYSis immutable.
We can achieve the same general effect by versioning the keys, dict_key->version == EXPECTED_VERSION, which would require an extra memory access to check, but wouldn't leak keys as we wouldn't need to hold a reference to EXPECTED_KEYS.
More variants of the lookup function.
The dictionary implements its internal specialization (split-keys, str-only, general) via a function pointer to the relevant lookup function.
By replacing this function pointer with a pair of enums, one for loads and one for stores, would allow additional specializations to insert out-of-line guards, and other special cases.
For example, one way to optimize builtin loads, is to replace them with constant loads, and discard the optimized code should the builtin dict change. We could implement this by specializing the store function of the builtin dict to invalidate all optimized (quickened) code should any value change.
This would leave (on 64bit machines) 6 bytes spare for a keys version, which would be plenty since we only need a version when we want to optimize, not for every change.
Remove the version number from dictionaries
The above optimizations mean that we have no use for the dict version, so we can remove it and save 8 bytes per dict.
LOAD_GLOBAL_BUILTIN example
By making the global's key immutable and adding the ability to de-optimize to the builtin dictionary, LOAD_GLOBAL can be specialized to the highly efficient LOAD_GLOBAL_BUILTIN:
if (UNLIKELY(globals->keys != EXPECTED_KEYS)) {
goto maybe_deopt_load_global_builtin; // Handles counter, etc.
}
saturating_increment(counter);
INCREF(cached_value);
PUSH(cached_value);Not only is this about as fast as we can get without JIT compilation, it also works when there is a variable in the global dictionary.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
ericsnowcurrently commentedon Mar 26, 2021
Interesting points
At first it sounded like you were describing the status quo but I'm guessing this is the modification. Is that right? If so, currently shared keys current can be removed from?
Also, if I understood correctly, the general idea is that in many cases (especially with runtime-internal usage, e.g. builtins) modification of a dict object is in its values and not its keys. So we should orient the dict code around that case and optimize for it and let code that modifies the keys incur the slower path.
This implies to me that every lookup would involve one less pointer indirection, one more variable lookup, and some extra branching.
markshannon commentedon Mar 29, 2021
I was describing the status quo, shared dictionary keys cannot have keys removed.
markshannon commentedon Jun 10, 2021
To do list:
gvanrossum commentedon Jun 10, 2021
Are there any remaining uses in CPython itself for dict version numbers?
Repealing a PEP can take years (deprecation etc.), so hopefully the presence of a redundant version number doesn't stop us from doing anything?
JelleZijlstra commentedon Jun 10, 2021
Dict versions are PEP 509 (https://www.python.org/dev/peps/pep-0509/), not PEP 590, for those like me who were confused.
The only use of
ma_version_tagin CPython is in the implementation of LOAD_GLOBAL, so it shouldn't be needed for internal use cases after Mark's proposed change.markshannon commentedon Jun 30, 2021
Since PEP 509 (not 590 🙂) has no observable effect, there should be no need for a deprecation period.
In fact, since it is impossible to tell if the version is there, we could claim that the implementation still conforms to PEP 509 after we remove the version number 😉
gvanrossum commentedon Jun 30, 2021
What kind of C API does PEP 509 offer? Let's hope it's not part of the stable API.
markshannon commentedon Jul 16, 2021
Another thing we should consider is the nature of the contract regarding dictionary ordering.
E.g.
Now
C(True)is the same asC(False)by any reasonable measure.C(True).__dict__ == C(False).__dict__but keys are not shared and large amounts of memory is wasted in
[C(x) for x in range(1000_000)]which appears to violate PEP 412.
This example is a bit contrived, but similar things happen when attributes have a default per-class value, or are added in methods other than
__init__.Is it reasonable to specify that dictionary order only applies to explicit dictionaries, and that the order of keys in an objects dictionary is not specified before the dictionary is explicitly accessed?
Doing so would allow us to store objects in an efficient format as we would not need to create dictionaries at all (just the values) for most instances of many classes.
gvanrossum commentedon Jul 16, 2021
markshannon commentedon Jul 26, 2021
One more modification to consider is to make all dictionaries into split dictionaries.
#72 is simpler (at least in terms of the pictures 🙂) if all dictionaries are split.
For efficiency, if we know that the keys will not be shared, then the keys and values can still be allocated in a single block of memory. Instead of an array of key/hash/values triples, we would have an array of key/hash pairs followed by an array of values.
This would have worse locality of memory, but simplify the code, possibly improving branch prediction.
I suspect that there would be a slowdown for explicitly dictionary accesses, but might be a win thanks to better attribute access.
FWIW, in the original HotPy all dictionaries were split dictionaries.
markshannon commentedon Jul 29, 2021
See also #77
markshannon commentedon Sep 21, 2021
Rather than change the semantics of dictionary order, which would be a hard sell I suspect, we want a format for shared keys that can handle different insertion orderings.
To support sharing keys with different ordering we need to maintain the order, but not in the keys.
To support Compact layout of Plain Python Objects we can't put it in the dict, so it must go in the values.
Most shared keys are small-ish. It should be tolerable to limit the size of shared keys. #72 suggests an upper limit of 20 for compact objects. If we drop that to 16, it is possible to store the insertion order for the dictionary in a 64bit value (16*4 bits).
So here is what a new key-sharing dict might look like:
sizevalues.Since shared keys are small, we can dispense with hashing and probing, and use a linear scan.
Reads
First we need to perform a linear scan over the keys. Modern CPUs like linear scans, so this should be faster than hash probing for small arrays. Otherwise the operation is unchanged.
The main performance advantage will be in improved specialization of
LOAD_ATTR.Insertion
Because we need to check to whether
value == NULLfor reference counting, we already know whether this insertion inserted a new key without any additional checks.If the insertion inserts a new key, then we push the index into the
ordervector:Deletion
Deletion becomes a lot cheaper. Although we need to update the
ordervector, that is a very cheap operation compared to having to create a new combined keys object.kmod commentedon Sep 22, 2021
For what it's worth, in Pyston we add a version field to the dictionary key objects, and we use the dictionary (values) version for our inline caches.
@undingen
markshannon commentedon Sep 23, 2021
@kmod Like this? https://github.com/python/cpython/blob/main/Include/internal/pycore_dict.h#L46
markshannon commentedon Sep 23, 2021
In the original HotPy, dictionary keys were immutable, so the cache just needed to check the address of the keys.
Using a version number does involve an extra (dependent) memory read, but doesn't leak references as did my original scheme.
kmod commentedon Sep 23, 2021
Ah I didn't see that you added a keys version, yes ours is similar to that.
markshannon commentedon Nov 9, 2021
We now have key versions, better sharing and lazily created dictionaries. We might want dictionary listeners at some point, but we can make another issue for that.