Skip to content

BUG: silent overflow in np.prod #21219

Open

Description

@h-vetinari

While writing tests for factorial2 in scipy, I found that np.prod silently creates garbage values. I'm pretty sure it has to do with silently overflowing and wrapping with int32, hence it's probably relevant that the below is happening on windows.

>>> from functools import reduce
>>> from operator import mul
>>> import numpy as np
>>> from scipy.special import factorial2
>>> n = 20
>>> factorial2(n, exact=True)
3715891200
>>> reduce(mul, list(range(n, 0, -2)), 1)
3715891200
>>> np.prod(list(range(n, 0, -2)))
-579076096
>>> np.iinfo(np.int32).max
2147483647
>>> np.iinfo(np.int32).min + (3715891200 - (np.iinfo(np.int32).max + 1))
-579076096
>>> np.__version__
'1.22.3'

IMO this should implicitly bump the type (and error loudly when overflow happens...)

Activity

  1. charris commented on Mar 19, 2022

    @charris
    Member

    This is because the default integer conversion of Python int is C long, which is always 32 bits on Windows. This works on 64 bit Linux because C long is 64 bits. We are going to change this default type to 32 bits on 32 bit platforms and 64 bits platforms on 64 bit platforms, i.e., make the Windows default the same as the Linux default. Another option would be to make the conversion 64 bits on all platforms, both 32 and 64 bit, but that would not be quite as efficient.

    The C long type was inherited from ancient Python, which had two integer types, int and long. The int type was C long and the long type was the unbounded version that is still around, renamed int in Python 3 when the C long type was dropped.

  2. h-vetinari commented on Mar 20, 2022

    @h-vetinari
    ContributorAuthor

    I'm aware of (most of) the historical context, we already discussed this in several places, e.g. #12525 🙃

    But I continue to think that we're not obligated to expose the sharp edges of C's broken integer hierarchy and conversions. As a user, I value:

    1. Correctness
    2. Safety
    3. Accuracy
    4. Performance

    It depends on the application if 3./4. are switched, but I think it's a very good baseline, particularly for library code. The higher performance moves up that list, the less suited the respective code is for a widely used library. In this case, we have neither correctness nor safety, and so it's IMO besides the point to talk about efficiency.

    I think we should detect overflow and progress through the integer hierarchy (at least to int64, and hopefully further once there's a portable int128 type in 1-2 decades, if C - despite the squabbling compiler vendors - ever gets its s*** together), and where that's not possible either warn, error or (in an ideal world...) provide an option to bail out to (unlimited) python ints.

    As a programmer in python, I don't want to have to care about the hardware abstraction below my integers (except to squeeze performance); if I'm feeding ints into np.product, it's already a strong sign I care about the fact that they're integers - otherwise, I could just indicate my preference for performance by casting them to floats beforehand.

    I know it's an extremely thorny problem (the intmax article is a terrifyingly good illustration of that), but I don't think that's a good enough reason to give up fixing the issues around it as best as the circumstances allow. I think we have some room left for improvement. :)

  3. seberg commented on Mar 21, 2022

    @seberg
    Member

    @h-vetinari I think it all comes down to basically the same thing every time. That is: we need to figure out how to get there and to do that someone has to commit some concrete and serious cycles, unfortunately.
    There are multiple options, and my changes to the ufunc/casting machinery add possibilities we did not have before.

    I agree about correctness trumping performance. But if we can only do this with serious slowdowns, then I am pessimistic. I would not be surprised about a lot of complaints if integer math is 50% slower for "no good reason because I know overflow doesn't happen".

    The question is more, what to do?

    1. Simplest: Reuse floating point overflow errors (like scalars), assuming it doesn't slow things down absurdly...
    2. Introduce a new np.errstate that defaults to warning for integer overflow (integer div-by-zero is interesting as well, but arguably should maybe just raise outright)?
      • Would we need a "fast" loop? If the np.errstate disables integer warnings/errors, we could design API to allow using a faster loop that ignores integer overflows. That is, assuming there is serious speed difference. If there is not, fast loop == slow loop.
      • Figure out how to give the warnings. Right now NEP 42/43 says that the inner-loop has to do it except for the floating point warning flags, but we could change/refine that.

    With respect to adding API, I think it is pretty clear on how. But probably still time consuming to nail down completely. The first point may be to find out if integer overflow checking can be done at a low performance penalty.

  4. mattip commented on Mar 22, 2022

    @mattip
    Member

    @seiko2plus do you know if baseline SIMD operations (SSE2, NEON) have an inexpensive mechanism for detecting integer operation overflow?

  5. seiko2plus commented on Mar 23, 2022

    @seiko2plus
    Member

    Both x86 and ARM don't offer any kind of instructions for traping integer overflow, emulating it can add 5-20% overhead for vectorized loops and x3 for scalars.
    see:

    however, it's better to avoid integer overflow or wraparound(unsigned) from the first place. in general, reduction operations should be handled by FPU to increase the accuracy no matter what performance regression is.

  6. InessaPawson commented on Mar 9, 2023

    @InessaPawson
    Member

    @rgommers Now that np.product has been deprecated (#23314), do you think we can close this issue?

  7. changed the title [-]BUG: silent overflow in np.product[/-] [+]BUG: silent overflow in np.prod[/+] on Mar 9, 2023
  8. rgommers commented on Mar 9, 2023

    @rgommers
    Member

    @rgommers Now that np.product has been deprecated (#23314), do you think we can close this issue?

    No, product is only an alias for prod, so prod still has this issue - nothing changed. I have edited the title and reproducer to use prod.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions