GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ENH: Improve performance for np.result_type by eendebakpt · Pull Request #28710 · numpy/numpy

Conversation

@eendebakpt

@eendebakpt eendebakpt commented Apr 15, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Improve performance of np.result_type

  • Use NPY_ALLOC_WORKSPACE in array_result_type
  • Avoid increfs/decrefs in PyArray_ResultType
  • Fast path for array method lookup on dtypes
  • Fast path for identical arguments to np.result_type

Benchmark:

result_type(x): Mean +- std dev: [main] 156 ns +- 8 ns -> [pr] 135 ns +- 2 ns: 1.16x faster
result_type(x, x): Mean +- std dev: [main] 195 ns +- 5 ns -> [pr] 150 ns +- 4 ns: 1.30x faster
result_type(x, x32): Mean +- std dev: [main] 207 ns +- 5 ns -> [pr] 174 ns +- 5 ns: 1.18x faster
result_type(x, x32, x): Mean +- std dev: [main] 224 ns +- 11 ns -> [pr] 191 ns +- 5 ns: 1.17x faster
result_type(d, d): Mean +- std dev: [main] 269 ns +- 12 ns -> [pr] 177 ns +- 7 ns: 1.52x faster
result_type(d, d32): Mean +- std dev: [main] 276 ns +- 10 ns -> [pr] 214 ns +- 6 ns: 1.29x faster
result_type(d, d32, x): Mean +- std dev: [main] 303 ns +- 11 ns -> [pr] 245 ns +- 9 ns: 1.23x faster

Geometric mean: 1.26x faster

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

jorenham reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
eendebakpt added 4 commits April 14, 2025 22:13
@eendebakpt
ENH: Improve np.result_type performance
757f48b
@eendebakpt
use borrowed references
ec968e3
@eendebakpt
fast path for equal dtype arguments
4419d7c
@eendebakpt
fast path in array method lookup for dtypes
4b41258
@eendebakpt eendebakpt mentioned this pull request Apr 15, 2025
ENH: Improve performance of np.linalg._linalg._commonType #28686
Open
@eendebakpt

eendebakpt commented Apr 15, 2025

Copy link
Copy Markdown
Contributor Author

There are 2 failing tests due to a warning: ‘arr’ may be used uninitialized [-Wmaybe-uninitialized]. I think this is a false positive: the buffer buf is not initialized, but we are not using the buffer contents in the comparison (we are comparing the buffer address, which is initialized).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@eendebakpt eendebakpt changed the title Draft: ENH: Improve performance for np.result_type ENH: Improve performance for np.result_type Apr 15, 2025
@mattip

mattip commented Apr 15, 2025

Copy link
Copy Markdown
Member

It seems the NPY_ALLOC_WORKSPACE macro could use a tweak to avoid that warning, could you try that?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@eendebakpt
fix compiler warning
112b54e
@eendebakpt

eendebakpt commented Apr 15, 2025

Copy link
Copy Markdown
Contributor Author

It was not a false positive after all, the arr could be uninitialized for the zero argument case.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

mhvk
mhvk reviewed Apr 15, 2025
View reviewed changes

@mhvk mhvk left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apart from the change to LookupSpecial, this looks good. If that one was important for the speed-up, I would suggest to put the test where the call is made rather than change it for everything.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread numpy/_core/src/common/get_attr_string.h Outdated
return 0;
}

/* We do not need to check for special attributes on array descriptor types */

@mhvk mhvk Apr 15, 2025

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is a good idea - PyArray_LookupSpecial is used also to look for __array_ufunc__ and __array_function__ and I don't think those paths should be made slower for result_type.

p.s. Separately, is this actually used with result_type?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@eendebakpt eendebakpt Apr 15, 2025

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will remove this one, the speed gain is not major. This path is being used if result_type as called with dtype arguments (not with exact ndarray arguments), I think because the np._result_type is wrapped by array_function_from_c_func_and_dispatcher.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@mhvk mhvk Apr 15, 2025

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be OK to exclude dtypes in the dispatcher, but probably better in a separate PR.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread numpy/_core/src/multiarray/convert_datatype.c
/* Copy all dtypes into a single array defining non-value-based behaviour */
for (npy_intp i=0; i < ndtypes; i++) {
all_DTypes[i] = NPY_DTYPE(descrs[i]);
Py_INCREF(all_DTypes[i]);

@mhvk mhvk Apr 15, 2025

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems safe, since we are holding on to descrs, but best to check with @seberg

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@ngoldbaum ngoldbaum Apr 15, 2025

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Borrowed references can be unsafe on the free-threaded build. That said, these are references to immortal (?) DType objects. The question mark there is that in principle someone could delete a DType in one thread and then another thread could hold the last reference to it here.

I have no idea if, in practice, we actually allow deleting DTypes or if that's a true goal for us to support.

Another option is to only drop the reference counting on the GIL-enabled build, since borrowed references should always be safe on the GIL-enabled build.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@eendebakpt eendebakpt Apr 15, 2025

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My reasoning: here descrs is passed as an argument to PyArray_ResultType which means the elements of descrs cannot (or should not!?) be deleted by another thread. Since descrs objects are not deleted, the type of the descr should be safe to use.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

mhvk and ngoldbaum reacted with thumbs up emoji
All reactions
  • 👍 2 reactions
Comment thread numpy/_core/src/multiarray/multiarraymodule.c Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread numpy/_core/src/multiarray/multiarraymodule.c Resolved

Uh oh!

There was an error while loading. Please reload this page.

@eendebakpt
review comments
9e836b8
eendebakpt
eendebakpt commented Apr 15, 2025
View reviewed changes
Comment thread numpy/_core/src/multiarray/convert_datatype.c
/* Copy all dtypes into a single array defining non-value-based behaviour */
for (npy_intp i=0; i < ndtypes; i++) {
all_DTypes[i] = NPY_DTYPE(descrs[i]);
Py_INCREF(all_DTypes[i]);

@eendebakpt eendebakpt Apr 15, 2025

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My reasoning: here descrs is passed as an argument to PyArray_ResultType which means the elements of descrs cannot (or should not!?) be deleted by another thread. Since descrs objects are not deleted, the type of the descr should be safe to use.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

mhvk and ngoldbaum reacted with thumbs up emoji
All reactions
  • 👍 2 reactions
Comment thread numpy/_core/src/multiarray/convert_datatype.c
@@ -1628,14 +1627,10 @@ PyArray_ResultType(
all_descriptors[i_all] = PyArray_DTYPE(arrs[i]);

@eendebakpt eendebakpt Apr 15, 2025

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part is not touched by the PR, but is this safe in the free-threading build? The arrs is passed so is safe, but PyArray_DTYPE gets a borrowed reference and another thread can replace the array dtype.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@eendebakpt eendebakpt Apr 15, 2025

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is a reproducer:

import unittest
from threading import Thread, Barrier
from test.support import threading_helper
import numpy as np

threading_helper.requires_working_threading(module=True)

class ItertoolsThreading(unittest.TestCase):

    
    @threading_helper.reap_threads
    def test_result_type(self):
        number_of_threads = 6
        number_of_iterations = 25
        number_of_cycles = 800

        barrier = Barrier(number_of_threads)
        
        x = np.array([1., 2., 3., 4.], np.dtype([('f1', [('f1', '<i2')])]))
        y = np.array([1, 2,], np.dtype([('f1', [('f1', '<i2')])]))
        
        def work(it):
            barrier.wait()
            for _ in range(number_of_cycles):
                #print(f'{it=} {_}')
                x.dtype = np.dtype([('f1', [('f1', '<i2')])]) # single reference
                y.dtype = np.dtype([('f1', [('f1', '<i2')])]) # single reference
                np.result_type(x, y)
               
               

        for it in range(number_of_iterations):
            print(f'iteration {it}')
            worker_threads = []
            for ii in range(number_of_threads):
                worker_threads.append(
                    Thread(target=work, args=[ii]))

            with threading_helper.start_threads(worker_threads):
                pass

            barrier.reset()

        print('done')

if __name__ == "__main__":
    unittest.main()

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@ngoldbaum ngoldbaum Apr 15, 2025

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you file an issue for this? This is kind of a weird thing to do so I’m not very worried but maybe there’s a simple workaround.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@eendebakpt eendebakpt mentioned this pull request Apr 16, 2025
BUG: Numpy crashing when concurrent threads change the dtype of an array #28727
Closed
seberg
seberg approved these changes Apr 23, 2025
View reviewed changes

@seberg seberg left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM and previous reviewers seemed happy, so merging, thanks.

(IIRC one of the worst performance parts result_type was that it is often called on objects where we have to do a __array_function__ lookup that fails. Hopefully, future Python versions will allow us to speed this up.)

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@seberg
seberg merged commit 9ead596 into numpy:main Apr 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@mhvk mhvk mhvk left review comments
@ngoldbaum ngoldbaum ngoldbaum left review comments
@seberg seberg seberg approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

5 participants

@eendebakpt @mattip @seberg @mhvk @ngoldbaum
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.