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
Comments
|
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:
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)
301029996That 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 ;-) |
|
Is this similar to https://bugs.python.org/issue3451 ? |
|
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! |
|
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 |
|
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. 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 |
|
Addendum: the "native" time (for built in str(a)) in the msg above turned out to be over 3 hours and 50 minutes. |
|
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. |
|
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) "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 |
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). |
|
Hi, why is this issue closed? What needs to be done to make it through? |
|
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 ( 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 |
|
Why do you need fast division? Why not just implement str to int convertion using this style of d&c? This would be simple to implement and would only require multiplication. If If multiplication is done using Karatsuba ( Since Python currently uses Karatsuba for its big ints multiplication, this simple str to int convertion algorithm would run in |
|
Yep, even simplest divide and conquer with native multiplication would already provide significant speed-up. |
|
Also if you want something slightly smarter, since 10 is |
|
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, Clearly |
|
I also tried out For 40000 digits str_to_int with GMP takes 0.000432 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. |
|
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 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 And it could also buy major speedups for modular 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: 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 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. |
|
"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 |
|
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 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 |
|
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. |
|
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. |
tim-one commentedJan 28, 2022
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:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: