Skip to content

Dictionary modifications to enable optimizations. #30

Closed

Description

@markshannon

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:

  1. Loading from builtins. If globals->keys == EXPECTED_KEYS and key not in EXPECTED_KEYS and EXPECTED_KEYS is immutable, then we can read from builtins without have to check globals. If the values in globals change, but the keys don't (as would be the case for global variables) then we still get fast access to builtins.

  2. Loading a method. Functions are non-overriding descriptors, so to cache a function in LOAD_METHOD we just need to check that obj->dict->keys == EXPECTED_KEYS provided that key not in EXPECTED_KEYS and EXPECTED_KEYS is 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.

Activity

  1. ericsnowcurrently commented on Mar 26, 2021

    @ericsnowcurrently
    Collaborator

    Interesting points

    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.

    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.

    More variants of the 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.

    This implies to me that every lookup would involve one less pointer indirection, one more variable lookup, and some extra branching.

  2. markshannon commented on Mar 29, 2021

    @markshannon
    MemberAuthor

    I was describing the status quo, shared dictionary keys cannot have keys removed.

  3. markshannon commented on Jun 10, 2021

    @markshannon
    MemberAuthor

    To do list:

    • Add version number to dictionary keys
    • Write PEP to repeal PEP 509 (We might want version number for some dicts, but we don't want to be compelled to have them)
  4. self-assigned this
    on Jun 10, 2021
  5. gvanrossum commented on Jun 10, 2021

    @gvanrossum
    Collaborator

    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?

  6. JelleZijlstra commented on Jun 10, 2021

    @JelleZijlstra
    Contributor

    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_tag in CPython is in the implementation of LOAD_GLOBAL, so it shouldn't be needed for internal use cases after Mark's proposed change.

  7. markshannon commented on Jun 30, 2021

    @markshannon
    MemberAuthor

    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 😉

  8. gvanrossum commented on Jun 30, 2021

    @gvanrossum
    Collaborator

    What kind of C API does PEP 509 offer? Let's hope it's not part of the stable API.

  9. markshannon commented on Jul 16, 2021

    @markshannon
    MemberAuthor

    Another thing we should consider is the nature of the contract regarding dictionary ordering.
    E.g.

    class C:
        def __init__(order):
            if order:
                self.a = 1; self.b = 2
            else:
                self.b = 2; self. a = 1

    Now C(True) is the same as C(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.

  10. gvanrossum commented on Jul 16, 2021

    @gvanrossum
    Collaborator
  11. markshannon commented on Jul 26, 2021

    @markshannon
    MemberAuthor

    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.

  12. markshannon commented on Jul 29, 2021

    @markshannon
    MemberAuthor

    See also #77

  13. markshannon commented on Sep 21, 2021

    @markshannon
    MemberAuthor

    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:

    • keys: Common header followed by array of 8 or 16 strings/hash pairs.
    • values: 64bit insertion order vector followed by size values.

    Since shared keys are small, we can dispense with hashing and probing, and use a linear scan.

    Reads

    d['a']

    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

    d['a'] = 1

    Because we need to check to whether value == NULL for 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 order vector:

    values->order = (values->order << 4) | index;

    Deletion

    Deletion becomes a lot cheaper. Although we need to update the order vector, that is a very cheap operation compared to having to create a new combined keys object.

  14. kmod commented on Sep 22, 2021

    @kmod

    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

  15. markshannon commented on Sep 23, 2021

    @markshannon
    MemberAuthor
  16. markshannon commented on Sep 23, 2021

    @markshannon
    MemberAuthor

    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.

  17. kmod commented on Sep 23, 2021

    @kmod

    Ah I didn't see that you added a keys version, yes ours is similar to that.

  18. markshannon commented on Nov 9, 2021

    @markshannon
    MemberAuthor

    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.

  19. moved this from Todo to Done in Fancy CPython Boardon Jan 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions