Skip to content

base64 module: optimize via SIMD for performance #124951

Open

Description

@gpshead

Performance enhancement

Proposal:

https://pypi.org/project/pybase64/ aka https://github.com/mayeut/pybase64 (BSD licensed) exists. On top of some of its own SIMD code for base64 module extra features (character translation)^, it links against https://github.com/aklomp/base64, a BSD licensed C99 library with SIMD acceleration giving 5-20x performance on base64 encoding and decoding operations vs our existing generic byte based base64 C code.

We could adopt a bunch of the pybase64 code to make the default base64 module experience better - it is relatively straight forward extension module code (as one would expect). On the other hand, I expect pybase64 to still be where new development and further improvements in this space continue to happen as people who care strongly about performance need the latest and greatest from PyPI regardless of their current CPython version. (looping in @mayeut for thoughts on that)

Practicalities: Library availability? we'd vendor a libbase64 build for use on our binary distributions. I don't think it is currently widely available (? I only did a quick search on Ubuntu) as a package on Linux distributions though so we'd currently need to vendor our own copy in tree to be fair and match the good performance there (yuck, but ideally only temporary until distros pick it up as a package of its own, consider it similar to a Modules/_decimal/libmpdec/ situation - our configure.ac finds an installed one & distros link against that)

Risks: It is a new C library dependency. Security concerns within it thus become our own. As base64 is frequently used to process untrusted input. But its surface of possible problems is limited (very simple data format). We should ensure the library gets proper oss-fuzz test coverage before adoption (@aklomp for visibility).


^ bytes.translate, bytearray.translate, or str.translate might benefit from similar SIMD treatment - which would be better from a CPython perspective than only doing that within this module? If so, lets file a new issue just for that bit.


❯ python -m pybase64 benchmark `which python`
pybase64 1.4.0 (C extension active - NEON)  # running on my Apple M3
bench: altchars=None, validate=False
pybase64._pybase64.encodebytes:   4776.815 MB/s (5,936,128 bytes -> 8,018,983 bytes)
pybase64._pybase64.b64encode:    11989.872 MB/s (5,936,128 bytes -> 7,914,840 bytes)
pybase64._pybase64.b64decode:     3039.329 MB/s (7,914,840 bytes -> 5,936,128 bytes)
base64.encodebytes:                292.876 MB/s (5,936,128 bytes -> 8,018,983 bytes)
base64.b64encode:                  601.307 MB/s (5,936,128 bytes -> 7,914,840 bytes)
base64.b64decode:                  492.088 MB/s (7,914,840 bytes -> 5,936,128 bytes)
bench: altchars=None, validate=True
pybase64._pybase64.b64encode:    12327.286 MB/s (5,936,128 bytes -> 7,914,840 bytes)
pybase64._pybase64.b64decode:     8611.733 MB/s (7,914,840 bytes -> 5,936,128 bytes)
base64.b64encode:                  597.389 MB/s (5,936,128 bytes -> 7,914,840 bytes)
base64.b64decode:                  472.430 MB/s (7,914,840 bytes -> 5,936,128 bytes)
bench: altchars=b'-_', validate=False
pybase64._pybase64.b64encode:     1287.615 MB/s (5,936,128 bytes -> 7,914,840 bytes)
pybase64._pybase64.b64decode:     2524.966 MB/s (7,914,840 bytes -> 5,936,128 bytes)
base64.b64encode:                  473.320 MB/s (5,936,128 bytes -> 7,914,840 bytes)
base64.b64decode:                  406.411 MB/s (7,914,840 bytes -> 5,936,128 bytes)
bench: altchars=b'-_', validate=True
pybase64._pybase64.b64encode:     1283.111 MB/s (5,936,128 bytes -> 7,914,840 bytes)
pybase64._pybase64.b64decode:     6745.809 MB/s (7,914,840 bytes -> 5,936,128 bytes)
base64.b64encode:                  464.526 MB/s (5,936,128 bytes -> 7,914,840 bytes)
base64.b64decode:                  391.959 MB/s (7,914,840 bytes -> 5,936,128 bytes)

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

If we spawn Discuss threads around this, lets edit and drop links here.

Linked PRs

Activity

  1. added
    type-feature
    performance
    stdlib
    on Oct 3, 2024
  2. rruuaanng commented on Oct 4, 2024

    @rruuaanng
    Contributor

    I think this is a good idea, but it seems that relying too much on external C libraries may cause instability (such as many linking and compilation problems). Do you have any better solution to this problem?

  3. gpshead commented on Oct 4, 2024

    @gpshead
    MemberAuthor

    We're not really concerned about that. We aleady link against a bunch of libraries and have vendored a few (as much as we try to avoid that), including some involving SIMD code, in the past.

  4. picnixz commented on Oct 4, 2024

    @picnixz
    Member

    For the performances themselves, they are worth the inclusion IMO (base64 is very common in web applications)

    I don't think it is currently widely available

    The default base64 lib comes with coreutils IIRC (at least on most Linux distributions). But for SIMD support, I don't know of any that is well-known (there is an Alpine Linux package for that though which directly uses the lib you linked but well.. that's the only one).

    yuck, but ideally only temporary until distros pick it up as a package of its own

    Yes, but that could give distros more confidence and reasons in pushing it into a proper libbase64-devel package. We could also cut off some parts that are not needed and platforms that are not supported

    bytes.translate, bytearray.translate, or str.translate might benefit from similar SIMD treatment

    I think it's a good idea to make built-in functions faster when possible if the cost of introducing the overall machinary is not too much (but yes, let's open a separate issue if needs arise).

  5. corona10 commented on Oct 6, 2024

    @corona10
    Member

    From a general approach, I am not sure it's worth maintaining SIMD-related logic in CPython.
    (I know that we already have such logic from some modules, but most of them are vendored libraries..)
    There have been several attempts to accelerate the JSON module by using SIMD too (and they are actively managed by 3rd parties). Are we going to do the same thing? or do we have any criteria for what to accelerate from CPython or what to accelerate from 3rd party side?

  6. gpshead commented on Oct 6, 2024

    @gpshead
    MemberAuthor

    FWIW, we already have SIMD and/or accelerated instruction use in hashlib code (and I expect to add more, as HACL* can provide it to us - our goal is to eliminate the need to link hashlib against openssl).

    base64 is a much simpler obvious use for SIMD as the algorithm is dead simple and clearly amenable to doing a lot of well patterned simple math at once. And is frequently done on bulk data due to how common standards embed binary in text using it.

    It feels like the kind of thing that a C version of, if written in the appropriate manner, might get a compiler to auto-vectorize? But tricking compilers into doing that for you instead of explicitly just doing what you wanted to happen can be less maintainable.

    In general though I wouldn't reach for SIMD on things like our main data types unless it demonstrated a meaningful measurable performance suite win. (bytes.translate is rather niche in that regard)

    JSON is a similarly important widely used bulk data format. A lot more complicated to use SIMD on. There are a variety of libraries out there doing it. If anyone wants to consider a behavior compatible version doing that as the json stdlib module, that belongs in its own issue.


    A more interesting library to consider linking against than what I opened with may be https://github.com/simdutf/simdutf which covers UTF8 & friends as well as base64. (though it is C++ and I believe we've so far avoided requiring C++ linkage within CPython itself?)

    Unrelated other than the SIMD theme - https://pypi.org/project/stringzilla/. It does things that even adopting simplest conservative versions of them for use by our CPython internals in a compatible manner might be enough to show up on the performance suite. Someone would need to take on trying it and testing to find out.

  7. gpshead commented on Oct 6, 2024

    @gpshead
    MemberAuthor

    do we have any criteria for what to accelerate from CPython or what to accelerate from 3rd party side?

    My #.1 criteria is maintainability. #.2 criteria is "is it widely used on enough data to matter?" with a #.3 feeding into that of "Would doing this reduce the need to train people to always use a special PyPI package instead of the stdlib for their common task that either can do because of a performance concern?"

  8. removed
    type-feature
    on Oct 6, 2024
  9. added a commit that references this issue on Jan 2, 2026
  10. added a commit that references this issue on Feb 15, 2026
  11. TkTech commented on Oct 18, 2026

    @TkTech
    Contributor

    The maintainer of simdutf (@lemire) has just published their own fastpybase64 that's up to ~80x faster than the current stdlib and ~13x faster than pybase64, as a drop-in replacement. Given the simdutf project's rapid development pace and the relative niche of needing SIMD-accelerated base64 functions, it may be better to leave this one to the community.

    https://github.com/simdutf/fastpybase64

  12. gpshead commented on Oct 18, 2026

    @gpshead
    MemberAuthor

    What i'd like from the stdlib is not the absolute fastest; third party packages will always be ahead there (fastpybase64 looks tasty!). but for us to ship easy to maintain wins as those benefit everybody's collective CPU&Power usage, even those who haven't thought about their overall performance yet. So i'll keep this open, but agreed the priority isn't high.

  13. added
    type-feature
    on Oct 18, 2026
  14. 11 remaining items

  15. added a commit that references this issue on Nov 22, 2026
  16. picnixz commented on Nov 22, 2026

    @picnixz
    Member

    Personally I am rather against adding SIMD under any forms in CPython for multiple reasons:

    • there exist good 3rd party libs that do it well for many platforms and have a faster release cycle; this is my main objection.
    • we need to consider the various tiers and compilers;
    • the Rust for CPython project may give simpler ways of adding such bindings.

    More precisely, I would rather see a consistent use of SIMD when possible and as much as possible only if this is a decision taken for the entire project and not just some parts here and there. However I believe that this should be first a PEP. We don't want any kind of SIMD support detection to be in multiple places IMO.

    In particular, even your PR is something I would rather not see merged actually. I do not see a compelling reason to add SIMD for limited cases or platforms and later add better versions. I would rather have the best version we can have first or leave it entirely to PyPI packages.

  17. gpshead commented on Nov 22, 2026

    @gpshead
    MemberAuthor

    That PR looks pretty clean. FWIW creating implementations is easy - I had Claude do that a year ago in main...gpshead:cpython:claude/vectorize-base64-c-S7Hku while exploring the space (including over-optimizing). The more interesting part of deciding which shapes to accept which is really what @picnixz is getting at.

    I do not think we should aim for best but we should aim for not leaving easy wins behind because we get stuck assuming we need the best or perfect thing. cpython is not about being the best at anything. It never will be. It's a base to build upon. Provide something good and it simplifies users lives as they don't need to reach elsewhere as often and when they want best they will add that complication regardless.

    The PR above is a good example. I like it. It doesn't require detection and dynamic dispatch at all, it's a clear 5x. Nor did my vectorizing of hex encode/decode.

    It is too easy to over-design for dynamic selection. In reality it's a trivial boolean runtime check for the cases where it is worth using.

  18. StanFromIreland commented on Nov 23, 2026

    @StanFromIreland
    Member

    I agree with Bénédikt here, this is getting too platform specific.

    The PR is ~cleanish for what it is, but it is 250 lines of intrinsics that only benefit AArch64. The x86-64 follow-up would again need runtime dispatch, which we have no agreed home for yet, and what about other architectures? As noted above, these implementations share very little, so we would end up maintaining several separate copies of the same algorithm, each of which can only be tested on its own hardware.

    I would rather we decide how (and whether) we want to do SIMD across the project first, including where CPU feature detection lives, than merge one architecture now and work the rest out later. Until then, people who need the throughput already have pybase64 and fastpybase64, and the scalar fast path from gh-143262 seems a reasonable baseline for everyone else.

  19. Zheng-Xu commented on Nov 27, 2026

    @Zheng-Xu

    NEON is mandatory for AArch64. For this base64 optimization, there is no detection at all. A unified way of implementing OS, arch specific optimizations can reduce potential maintenance effort.

    Compile time detection may cause deployment issues if the target machine supports less ISA features than expected, unless we build for a specific target(e.g. Android phone).

    Runtime CPU(ISA) features detection can be more flexible and benefit cases beyond SIMD, such as atomic(LSE on AArch64), CRC, etc. It can be started with just detecting the ISA and limited OS(Linux). A rough idea of runtime ISA feature detection can like below:

    • Use global variable record the ISA feature
      • The dispatch cost of branches on constant value should be low (modern BRPT hides the cost)
    • Detection:
      • cpu.c --> cpu_<ARCH>.h --> cpu_<ARCH>_<OS>.h
      • initconfig.c // allow features overwritten by CLI options
    • Use point:
    // xxx_aarch64.c
    __attribute__((target("+<ISA_feat_1>")) func_aarch64_with_feat_1();
    __attribute__((target("+<ISA_feat_2>")) func_aarch64_with_feat_2();
    
    // xxx.c
    func_generic();
    func() {
    #if defined(__aarch64__)
      if (has_aarch64_feat_1) return func_aarch64_with_feat_1();
      if (has_aarch64_feat_2) return func_aarch64_with_feat_2();
    #endif
      return func_generic();
    }
    
  20. picnixz commented on Nov 28, 2026

    @picnixz
    Member

    NEON is mandatory for AArch64

    I am no expert in aarch64 but has it ALWAYS been the case or is it only for recent aarch64? if it's even possible to have aarch64 without NEON then we can't base our decision on that. For static/dynamic detection, my PR already does everything that's needed (except that I'm not entirely sure that cross compilation support is fully correct out-there).

    initconfig.c // allow features overwritten by CLI options

    That would be a nightmare to maintain IMO and very fragile. And if we want to have this kind of things, it's a PEP, not just an issue, sorry (looks similar to JVM options to disable AVX for instance).

    The suggested interface would also mean many more code paths, and thus increasing any maintenance cost. I really think we should not try to be the fastest if this costs us more files and code to be added while leaving others without those performance gains (e.g. x86-64 here). I'm really more in favor of shifting all the burden of SIMD to 3rd party libs and try on our side to be as universal as possible. At some point, if you are really worried about performance, Python may not be the best language for your product in this case.

  21. added 2 commits that reference this issue on Nov 28, 2026
  22. gpshead commented on Nov 29, 2026

    @gpshead
    MemberAuthor

    I am no expert in aarch64 but has it ALWAYS been the case or is it only for recent aarch64?

    Yes. Always. No arm64 hardware exists without it. On top of that, all Linux, Windows, and macOS require NEON to be present on aarch64. (IIUC neon was technically marked optional in the original armv8.0-a spec but nobody ever took ARM up on that, and would never consider it optional in any hardware design as a result given the ecosystem needs).

    It really is one of the easiest to adopt.

  23. gpshead commented on Nov 29, 2026

    @gpshead
    MemberAuthor

    I put up a draft of an x86_64 SSSE3 based base64 that is effectively an "available everywhere" for x86_64 lowest common denominator acceleration.

    It technically uses feature detection but is trivial, not worth centralizing on its own. Also no need for a way to turn it off. (Detecting things more advanced than that such as avx2 or the relevant avx512 pieces is more complicated and would be worth the mentioned feature detection centralization)

  24. added a commit that references this issue on Nov 29, 2026
  25. changed the title [-]`base64` module: Link against SIMD library for 10x performance.[/-] [+]`base64` module: optimize via SIMD for performance[/+] on Nov 29, 2026
  26. Zheng-Xu commented on Nov 30, 2026

    @Zheng-Xu

    initconfig.c // allow features overwritten by CLI options

    That would be a nightmare to maintain IMO and very fragile. And if we want to have this kind of things, it's a PEP, not just an issue, sorry (looks similar to JVM options to disable AVX for instance).

    This is more for debugging purpose. So that we can temporarily disable the optimization path for comparison. To make things simpler, we can only have one option to disable all architecture optimizations.

    The suggested interface would also mean many more code paths, and thus increasing any maintenance cost.

    I feel centralized ISA detection can be more maintainable than scattered around. Also some internal functions(bytes, str, popcount, etc.) will also be difficult to be replaced by 3rdparty libs.

  27. added a commit that references this issue on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancestdlibtype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions