Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Quadratic time internal base conversions #90716

Open
tim-one opened this issue Jan 28, 2022 · 22 comments
Open

Quadratic time internal base conversions #90716

tim-one opened this issue Jan 28, 2022 · 22 comments
Labels
interpreter-core Interpreter core (Objects, Python, Grammar, and Parser dirs) performance Performance or resource usage

Comments

@tim-one
Copy link
Member

tim-one commented Jan 28, 2022

BPO 46558
Nosy @tim-one, @cfbolz, @sweeneyde
Files
  • todecstr.py
  • todecstr.py
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = <Date 2022-01-28.03:12:39.839>
    created_at = <Date 2022-01-28.02:31:44.271>
    labels = ['interpreter-core', 'performance']
    title = 'Quadratic time internal base conversions'
    updated_at = <Date 2022-01-31.06:11:48.110>
    user = 'https://github.com/tim-one'

    bugs.python.org fields:

    activity = <Date 2022-01-31.06:11:48.110>
    actor = 'tim.peters'
    assignee = 'none'
    closed = True
    closed_date = <Date 2022-01-28.03:12:39.839>
    closer = 'tim.peters'
    components = ['Interpreter Core']
    creation = <Date 2022-01-28.02:31:44.271>
    creator = 'tim.peters'
    dependencies = []
    files = ['50593', '50595']
    hgrepos = []
    issue_num = 46558
    keywords = []
    message_count = 9.0
    messages = ['411962', '411966', '411969', '411971', '412120', '412122', '412172', '412191', '412192']
    nosy_count = 3.0
    nosy_names = ['tim.peters', 'Carl.Friedrich.Bolz', 'Dennis Sweeney']
    pr_nums = []
    priority = 'normal'
    resolution = 'wont fix'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = 'performance'
    url = 'https://bugs.python.org/issue46558'
    versions = []

    @tim-one
    Copy link
    Member Author

    tim-one commented Jan 28, 2022

    Our internal base conversion algorithms between power-of-2 and non-power-of-2 bases are quadratic time, and that's been annoying forever ;-) This applies to int<->str and int<->decimal.Decimal conversions. Sometimes the conversion is implicit, like when comparing an int to a Decimal.

    For example:

    >> a = 1 << 1000000000 # yup! a billion and one bits
    >> s = str(a)

    I gave up after waiting for over 8 hours, and the computation apparently can't be interrupted.

    In contrast, using the function in the attached todecstr.py gets the result in under a minute:

    >>> a = 1 << 1000000000
    >>> s = todecstr(a)
    >>> len(s)
    301029996

    That builds an equal decimal.Decimal in a "clever" recursive way, and then just applies str to _that_.

    That's actually a best case for the function, which gets major benefit from the mountains of trailing 0 bits. A worst case is all 1-bits, but that still finishes in under 5 minutes:

    >>> a = 1 << 1000000000
    >>> s2 = todecstr(a - 1)
    >>> len(s2)
    301029996
    >>> s[-10:], s2[-10:]
    ('1787109376', '1787109375')

    A similar kind of function could certainly be written to convert from Decimal to int much faster, but it would probably be less effective. These things avoid explicit division entirely, but fat multiplies are key, and Decimal implements a fancier * algorithm than Karatsuba.

    Not for the faint of heart ;-)

    @tim-one tim-one added interpreter-core Interpreter core (Objects, Python, Grammar, and Parser dirs) performance Performance or resource usage labels Jan 28, 2022
    @sweeneyde
    Copy link
    Member

    sweeneyde commented Jan 28, 2022

    Is this similar to https://bugs.python.org/issue3451 ?

    @tim-one
    Copy link
    Member Author

    tim-one commented Jan 28, 2022

    Dennis, partly, although that was more aimed at speeding division, while the approach here doesn't use division at all.

    However, thinking about it, the implementation I attached doesn't actually for many cases (it doesn't build as much of the power tree in advance as may be needed). Which I missed because all the test cases I tried had mountains of trailing 0 or 1 bits, not mixtures.

    So I'm closing this anyway, at least until I can dream up an approach that always works. Thanks!

    @tim-one
    Copy link
    Member Author

    tim-one commented Jan 28, 2022

    Changed the code so that inner() only references one of the O(log log n) powers of 2 we actually precomputed (it could get lost before if lo was non-zero but within n had at least one leading zero bit - now we pass the conceptual width instead of computing it on the fly).

    @tim-one
    Copy link
    Member Author

    tim-one commented Jan 30, 2022

    The test case here is a = (1 << 100000000) - 1, a solid string of 100 million 1 bits. The goal is to convert to a decimal string.

    Methods:

    native: str(a)

    numeral: the Python numeral() function from bpo-3451's div.py after adapting to use the Python divmod_fast() from the same report's fast_div.py.

    todecstr: from the Python file attached to this report.

    gmp: str() applied to gmpy2.mpz(a).

    Timings:

    native: don't know; gave up after waiting over 2 1/2 hours.
    numeral: about 5 1/2 minutes.
    todecstr: under 30 seconds. (*)
    gmp: under 6 seconds.

    So there's room for improvement ;-)

    But here's the thing: I've lost count of how many times someone has whipped up a pure-Python implementation of a bigint algorithm that leaves CPython in the dust. And they're generally pretty easy in Python.

    But then they die there, because converting to C is soul-crushing, losing the beauty and elegance and compactness to mountains of low-level details of memory-management, refcounting, and checking for errors after every tiny operation.

    So a new question in this endless dilemma: _why_ do we need to convert to C? Why not leave the extreme cases to far-easier to write and maintain Python code? When we're cutting runtime from hours down to minutes, we're focusing on entirely the wrong end to not settle for 2 minutes because it may be theoretically possible to cut that to 1 minute by resorting to C.

    (*) I hope this algorithm tickles you by defying expectations ;-) It essentially stands numeral() on its head by splitting the input by a power of 2 instead of by a power of 10. As a result no divisions are used. But instead of shifting decimal digits into place, it has to multiply the high-end pieces by powers of 2. That seems insane on the face of it, but hard to argue with the clock ;-) The "tricks" here are that the O(log log n) powers of 2 needed can be computed efficiently in advance of any splitting, and that all the heavy arithmetic is done in the decimal module, which implements fancier-than-Karatsuba multiplication and whose values can be converted to decimal strings very quickly.

    @tim-one
    Copy link
    Member Author

    tim-one commented Jan 30, 2022

    Addendum: the "native" time (for built in str(a)) in the msg above turned out to be over 3 hours and 50 minutes.

    @cfbolz
    Copy link
    Mannequin

    cfbolz mannequin commented Jan 30, 2022

    Somebody pointed me to V8's implementation of str(bigint) today:

    https://github.com/v8/v8/blob/main/src/bigint/tostring.cc

    They say that they can compute str(factorial(1_000_000)) (which is 5.5 million decimal digits) in 1.5s:

    https://twitter.com/JakobKummerow/status/1487872478076620800

    As far as I understand the code (I suck at C++) they recursively split the bigint into halves using % 10^n at each recursion step, but pre-compute and cache the divisors' inverses.

    @tim-one
    Copy link
    Member Author

    tim-one commented Jan 31, 2022

    The factorial of a million is much smaller than the case I was looking at. Here are rough timings on my box, for computing the decimal string from the bigint (and, yes, they all return the same string):

    native: 475 seconds (about 8 minutes)
    numeral: 22.3 seconds
    todecstr: 4.10 seconds
    gmp: 0.74 seconds

    "They recursively split the bigint into halves using % 10^n at each recursion step". That's the standard trick for "output" conversions. Beyond that, there are different ways to try to use "fat" multiplications instead of division. The recursive splitting all on its own can help, but dramatic speedups need dramatically faster multiplication.

    todecstr treats it as an "input" conversion instead, using the decimal module to work mostly in base 10. That, by itself, reduces the role of division (to none at all in the Python code), and decimal has a more advanced multiplication algorithm than CPython's bigints have.

    @tim-one
    Copy link
    Member Author

    tim-one commented Jan 31, 2022

    todecstr treats it as an "input" conversion instead, ...

    Worth pointing this out since it doesn't seem widely known: "input" base conversions are _generally_ faster than "output" ones. Working in the destination base (or a power of it) is generally simpler.

    In the math.factorial(1000000) example, it takes CPython more than 3x longer for str() to convert it to base 10 than for int() to reconstruct the bigint from that string. Not an O() thing (they're both quadratic time in CPython today).

    @ezio-melotti ezio-melotti transferred this issue from another repository Apr 10, 2022
    @adamant-pwn
    Copy link

    adamant-pwn commented Sep 5, 2022

    Hi, why is this issue closed? What needs to be done to make it through?

    @tim-one
    Copy link
    Member Author

    tim-one commented Sep 5, 2022

    It's closed because nobody appears to be both willing and able to pursue it.

    But it's on the edge regardless. In general, any number of huge-int algorithms could be greatly speeded, but that's a massive undertaking. It's why GMP exists, to push such things as far as possible, regardless of implementation complexity, effort, or bulk. Very capable GMP bindings for Python are already available (gmpy2).

    As the timings here suggest, GMP will generally be faster than anything we may do anyway, because GMP never reaches a point where its authors say "good enough already".

    That said, I expect the single most valuable bigint speedup CPython could implement would be to bigint division, along the lines of gh-47701. That could indirectly give major speed boosts to bigint->str and bigint modular pow() too.

    @bjorn-martinsson
    Copy link

    bjorn-martinsson commented Sep 6, 2022

    Why do you need fast division? Why not just implement str to int convertion using this

    12345678 = 1234 * 10^4 + 5678 = (12 * 10^2 + 34) * 10^4 + (56 * 10^2 + 78) = ...
    

    style of d&c?

    This would be simple to implement and would only require multiplication.

    If $M(n)$ is the time it takes to multiply two $n$ bit numbers, then the cost of string to int convertion using this d&q is
    $T(n) = 2 T(n/2) + M(n)$.

    If multiplication is done using Karatsuba ( $M(n) = O(n^{1.58})$ ) then $T(n) = 3 M(n)$.
    If multiplication is done in $M(n) = O(n \log n)$ time, then $T(n) = O(n \log^2 n)$.

    Since Python currently uses Karatsuba for its big ints multiplication, this simple str to int convertion algorithm would run in $O(n^{1.58})$.

    @adamant-pwn
    Copy link

    adamant-pwn commented Sep 6, 2022

    Yep, even simplest divide and conquer with native multiplication would already provide significant speed-up.

    @bjorn-martinsson
    Copy link

    bjorn-martinsson commented Sep 6, 2022

    Also if you want something slightly smarter, since 10 is $2 * 5$ you can use bitshifts.

    12345678 = 1234 * 10^4 + 5678 = ((1234 * 5^4) << 4) + 5678
    

    @bjorn-martinsson
    Copy link

    bjorn-martinsson commented Sep 6, 2022

    I made an implementation of the basic d&q algorithm to test it out

    pow5 = [5]
    while len(pow5) <= 22:
        pow5.append(pow5[-1] * pow5[-1])
    
    def str_to_int(s):
        def _str_to_int(l, r):
            if r - l <= 3000:
                return int(s[l:r])
            lg_split = (r - l - 1).bit_length() - 1
            split = 1 << lg_split
            return ((_str_to_int(l, r - split) * pow5[lg_split]) << split) + _str_to_int(r - split, r)
        return _str_to_int(0, len(s))

    Running this locally, str_to_int is as fast as int at about 3000 digits.
    For 40000 digits str_to_int takes 0.00722 s and int takes 0.0125 s.
    For 400000 digits str_to_int takes 0.272 s and int takes 1.27 s.
    For 4000000 digits str_to_int takes 10.3 s and int takes 127 s.

    Clearly str_to_int is subquadratic, with same time complexity as Karatsuba. While int is quadratic. Also worth noting is that with a faster big int mult, str_to_int would definitely run a lot faster.

    @bjorn-martinsson
    Copy link

    bjorn-martinsson commented Sep 6, 2022

    I also tried out str_to_int with GMP (gmpy2.mpz) integers instead of Python's big integers to see what faster big int multiplication could lead to.

    For 40000 digits str_to_int with GMP takes 0.000432 s.
    For 400000 digits str_to_int with GMP takes 0.00817 s.
    For 4000000 digits str_to_int with GMP takes 0.132 s.

    So what Python actually needs is faster big int multiplication. With that you'd get a really fast string to int converter for free.

    @tim-one
    Copy link
    Member Author

    tim-one commented Sep 6, 2022

    All the earlier timing examples here were of int->str, not of str->int. For the latter case, which you're looking at, splitting a decimal string by a power of 10 is indeed trivial (conceptually - but by the time you finish coding it all in C, with all the memory-management, refcounting, and error-checking cruft debugged, not so much 😉).

    As already noted, the report's todecstr() does the harder int->str direction without division too, relying instead on faster-than-Karatsuba multiplication, by doing most of the arithmetic in a power-of-10 base to begin with (via the decimal module, which does implement one faster-than-Karatsuba multiplication method). Python's bigints are represented internally in a power-of-2 base, and there is no linear-time way to split one by a power of 10. So todecstr() doesn't even try to; instead it splits by various powers of 2.

    But faster native bigint division could nevertheless buy a major speedup for int->str, as already demonstrated near the start here by showing timings for the numeral() function. Much faster than str(), although still much slower than todecstr().

    And it could also buy major speedups for modular pow(), which is increasingly visible as people playing with crypto schemes move to fatter keys.

    And it would, tautologically, speed bigint division too, which is a bottleneck all on its own in some apps.

    @gpshead
    Copy link
    Member

    gpshead commented Sep 6, 2022

    And it would, tautologically, speed bigint division too, which is a bottleneck all on its own in some apps.

    It would be useful to have practical examples of actual Python applications that would benefit from any of:
    a) high performance huge int MUL or DIV
    b) high performance huge int to decimal or other non-binary-power base conversion.
    c) high performance huge int from decimal string conversion.

    Including if they've adopted a third party library for this math and would no longer have any need for that if improved.

    Where "high performance" means more than constant-time faster than what CPython int offers today. I'll leave the definition of "huge" up to you, but if the need is less than 5 of CPython's current implementation detail 30-bit value digits I'm skeptical. :)

    Bigint's really feel like a neat computer science toy most of the time. We've got them, but what actually uses integers larger than 64 or 128 bits?

    Similarly, once numbers get huge, what is the point of converting them to and from decimal? Decimal is for humans and humans don't readily comprehend precise numbers that large let alone type them correctly.

    @tim-one
    Copy link
    Member Author

    tim-one commented Sep 6, 2022

    "Practical applications" isn't really the name of this game 😉.

    Most complaints come from more-or-less newbies, who, e.g., play around in an interactive shell, and are surprised to find that sometimes the shell seems to freeze (but is really just waiting for a quadratic-time, or worse, bigint operation to finish).

    People who know what they're doing find many uses for big bigints, but more of a theoretical, research, educational, or recreational bent. Like, algorithm design, combinatorics, number theory, or contributing to the wonderful On-Line Encyclopedia of Integer Sequences. They also come as incidental side effects of using power tools, like in a symbolic math package computing symbolic power series or (for related reasons) symbolic high derivatives (integer coefficients and/or denominators often grow at an exponential rate across terms). Or they can be almost the whole banana, such as scaling an ill-conditioned float matrix to use exact bigint arithmetic instead to compute an exact matrix inverse or determinant (where sticking to floats the result could be pure noise due to compounding rounding errors).

    Not all that long ago, a number of people worked on adding "gonzo" optimizations to math.comb(). I played along, but was vocally disinclined to do ever more. Of course GMP still runs circles around CPython for many comb() bigint arguments. Such efforts would, IMO, have been better spent on speeding bigint // (which, as a matter of course, would also give another speed boost to comb() - and to any number of other bigint algorithms in users' own Python code - // is a fundamental building block, not "an application").

    @bjorn-martinsson
    Copy link

    bjorn-martinsson commented Sep 6, 2022

    One good example of using big integers are math people using Python for some quick calculations. When you use functions like factorial, it is easy to get pretty big integers. I also think that math people generally prefer decimal numbers over hex.

    Another example would be working with fractions. Just adding fractional numbers makes their denominators and numerators grow really quickly. I also don't think fractions support hex. Both reading and printing requires decimal as far as I can tell. For example you can do fractions.Fraction('1/2') but not fractions.Fraction('0x1/0x2').

    The examples I've given above is the type of scripts that wont appear in things like Google's codebase, even if they are relatively common use cases.

    Another important thing to note is that programmers trust the built in functions in Python to just work. That is the fundamental reason why int <=> str became an issue in the first place. This is also a great argument for why it is important to fix the time complexity issues with big ints.

    @nascheme
    Copy link
    Member

    nascheme commented Sep 8, 2022

    I think Tim's suggestion of switching to a Python implementation of a more efficient algorithm for large inputs would be a good approach. It is reasonable to not want to maintain a complicated high-performance algorithm written in C. This would be an interesting project for a student or someone wanting a challenge. Calling into Python from C is not too hard to do. Use a C-API to import a Python module and call a function inside of it.

    @gpshead
    Copy link
    Member

    gpshead commented Sep 8, 2022

    I'm reopening this as we seem to have agreement that doing something nicer here now that we've got a default limit is a good thing.

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    interpreter-core Interpreter core (Objects, Python, Grammar, and Parser dirs) performance Performance or resource usage
    Projects
    None yet
    Development

    No branches or pull requests

    6 participants