gh-111545: Add PyHash_Double() function#112095
Conversation
|
numpy has a
Proposed API has a single argument and cannot be used as a drop-in replacement for Py_hash_t hash = PyHash_Double(value);
if (hash == -1) {
return _Py_HashPointer(obj);
}
return hash;Problem: Since numpy already has a The Python now uses the identity for the hash when the value is a NaN, see gh-87641. In Python 3.9, By the way, in Python 3.13,
|
Sorry, something went wrong.
|
Another slice of Python history. In Python 3.2, |
Sorry, something went wrong.
|
I'm not a fan of signed number of hash. For example, I prefer to avoid it when using modulo operator ( The signed |
Sorry, something went wrong.
Draft PR gh-112096. I prefer to only start with
|
Sorry, something went wrong.
Sorry, something went wrong.
b3697b6 to
46fef17
Compare
November 15, 2023 02:45
|
I merged a first change to make this PR smaller and so easier to review. The PR #112098 added documentation and tests on the PyHash_GetFuncDef() function which was added by PEP 456. |
Sorry, something went wrong.
|
The PR adds
If needed, a second function can be added: Py_hash_t PyHash_DoubleOrPointer(double value, const void *ptr)=> Compute value hash, or compute ptr hash if value is not-a-number (NaN). For me, it's surprising that when passing a Python object in Or do you prefer to just expose |
Sorry, something went wrong.
I think, this attribute should be deprecated (or just removed?). |
Sorry, something went wrong.
If you consider that something should be changed, you can open a new issue about |
Sorry, something went wrong.
serhiy-storchaka
left a comment
There was a problem hiding this comment.
This PR contains many cosmetic changes, but also some changes that can affect performance in theory (like adding the "else" branch or adding additional check for -1). Please make precise benchmarks for this. Also consult with previous authors of this code.
To make PyHash_Double a replacement of _PyHash_Double you need Py_HashPointer. Maybe add it first?
BTW, should it be PyHash_Double or Py_HashDouble?
Sorry, something went wrong.
|
In terms of the proposed C API guidleines: this violates the one where negative results are reserved for errors. Actually, hashes might be a good argument for only reserving -1 for errors, leaving the other negative numbers mean success. |
Sorry, something went wrong.
24c3f6d to
a58dcd1
Compare
November 15, 2023 12:12
* Add again _PyHASH_NAN constant. * _Py_HashDouble(NULL, value) now returns _PyHASH_NAN. * Add tests: Modules/_testcapi/hash.c and Lib/test/test_capi/test_hash.py.
a58dcd1 to
772690a
Compare
November 15, 2023 12:14
|
I updated the PR to address @serhiy-storchaka and @encukou's comments. @serhiy-storchaka and @encukou: Please review the updated PR. The API changed to: The interesting case is that obj can be Changes:
|
Sorry, something went wrong.
|
Stepping back, I think I figured out why this API seems awkward to me. The actual use case the proposed function allows is implementing a custom object that needs to hash the same as a Python double, where NaN should be hashable (like Python doubles are). That use case is what Python needs, and I assume it's what NumPy needs, but IMO it's unnecessarily limited -- which makes the function well suited for an internal (or unstable) function, but worse for public API. With a signature like: int PyHash_Double(double value, Py_hash_t *result)
// -> 1 for non-NaN (*result is set to the hash)
// -> 0 for NaN (*result is set to 0)the function would cover the more general use case as well. The docs can note that when implementing hash for a custom object, if you get a 0 result you can:
(I'll leave the fallibility argument to the WG repos, just noting that this API would allow adding -1 as a possible result.) |
Sorry, something went wrong.
|
FWIW, I also find the proposed API ( The signature proposed by @encukou looks reasonable to me. I don't want to get involved in the discussion about error returns, but if we really wanted to we could have a documented sentinel hash value that's only ever returned for NaNs (e.g., 2**62). |
Sorry, something went wrong.
There is The problem with |
Sorry, something went wrong.
|
The first PR version used the API: The second PR version changed the API to Well, nobody (including me, to be honest) likes So I wrote PR #112449 which implements the API proposed by @encukou: |
Sorry, something went wrong.
|
I like the simpler API proposed in this PR more, my only concern is about performance. Can the difference be observed in microbenchmarks or it is insignificant? Instead of checking the result of the function, the user code can check the argument before calling the function: if (Py_IS_NAN(value)) {
return _Py_HashPointer(obj);
}
return PyHash_Double(value);As for names, "Hash" is a verb, and "Double" is an object. |
Sorry, something went wrong.
|
I don't see this used in tight loops, so I'd go for the prettier API even if it's a few instructions slower. (Note that NumPy uses it for scalars -- degenerate arrays of size 1 -- to ensure compatibility with Python doubles.) +1 on the naming note, |
Sorry, something went wrong.
Yes, I'm rather familiar with the history here. :-) I was simply suggesting that if we picked and documented a value that's not used for the hash of any non-NaN, then the hash value itself could be a way of detecting NaNs after the fact. In any case, I was just mentioning this as a possibility. I'd prefer a more direct method of NaN detection, like what you have currently implemented (or not having the API do NaN detection at all, but leave that to the user to do separately if necessary). |
Sorry, something went wrong.
|
I ran microbenchmarks on 3 different APIs. Measured performance is between 13.6 ns and 14.7 ns. The maximum difference is 1.1 ns: 1.08x slower. It seems like the current _Py_HashDouble() API is the fastest. In the 3 APIs, the C double input value is passed through the I expected I wrote 3 benchmarks on:
Results using CPU isolation, Python built with
I added benchmark code in I added an artificial test on the hash value to use it in the benchmark, so the compiler doesn't remove the whole function call, and the code is a little bit more realistic. (A) assembly code: (B) assembly code: (C) assembly code: Change used to benchmark (A) and (B). Measuring (C) requires minor changes. diff --git a/Modules/_testinternalcapi.c b/Modules/_testinternalcapi.c
index 4607a3faf17..9b671acf916 100644
--- a/Modules/_testinternalcapi.c
+++ b/Modules/_testinternalcapi.c
@@ -1625,6 +1625,51 @@ get_type_module_name(PyObject *self, PyObject *type)
}
+static PyObject *
+test_bench_private_hash_double(PyObject *Py_UNUSED(module), PyObject *args)
+{
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "n", &loops)) {
+ return NULL;
+ }
+ PyObject *obj = Py_None;
+ double d = 1.0;
+
+ _PyTime_t t1 = _PyTime_GetPerfCounter();
+ for (Py_ssize_t i=0; i < loops; i++) {
+ Py_hash_t hash = _Py_HashDouble(obj, d);
+ if (hash == -1) {
+ return NULL;
+ }
+ }
+ _PyTime_t t2 = _PyTime_GetPerfCounter();
+
+ return PyFloat_FromDouble(_PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
+static PyObject *
+test_bench_public_hash_double(PyObject *Py_UNUSED(module), PyObject *args)
+{
+ Py_ssize_t loops;
+ if (!PyArg_ParseTuple(args, "n", &loops)) {
+ return NULL;
+ }
+ double d = 1.0;
+
+ _PyTime_t t1 = _PyTime_GetPerfCounter();
+ for (Py_ssize_t i=0; i < loops; i++) {
+ Py_hash_t hash;
+ if (PyHash_Double(d, &hash) == 0) {
+ return NULL;
+ }
+ }
+ _PyTime_t t2 = _PyTime_GetPerfCounter();
+
+ return PyFloat_FromDouble(_PyTime_AsSecondsDouble(t2 - t1));
+}
+
+
static PyMethodDef module_functions[] = {
{"get_configs", get_configs, METH_NOARGS},
{"get_recursion_depth", get_recursion_depth, METH_NOARGS},
@@ -1688,6 +1733,8 @@ static PyMethodDef module_functions[] = {
{"restore_crossinterp_data", restore_crossinterp_data, METH_VARARGS},
_TESTINTERNALCAPI_TEST_LONG_NUMBITS_METHODDEF
{"get_type_module_name", get_type_module_name, METH_O},
+ {"bench_private_hash_double", test_bench_private_hash_double, METH_VARARGS},
+ {"bench_public_hash_double", test_bench_public_hash_double, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
Bench script for (A), private API: import pyperf
import _testinternalcapi
runner = pyperf.Runner()
runner.bench_time_func('bench', _testinternalcapi.bench_private_hash_double)Bench script for (B) and (C), public API: import pyperf
import _testinternalcapi
runner = pyperf.Runner()
runner.bench_time_func('bench', _testinternalcapi.bench_public_hash_double) |
Sorry, something went wrong.
|
Other benchmark results using PGO:
These numbers are surprising. |
Sorry, something went wrong.
I wrote PR #112476 to run this benchmark differently. Results look better (less surprising, more reliable than my previous benchmark). Results with CPU isolation,
API (A) and (C) have the same performance. API (B) is 0.9 ns slower than (A) and (C): it is 1.07x slower than (A) and (C). I ran the benchmark with |
Sorry, something went wrong.
If we only care about performance, an alternative is API (D):
Note: Passing non-NULL is_nan or passing NULL is_nan has no significant impact on API (D) performance. It may be interesting if you know that the number cannot be NaN. |
Sorry, something went wrong.
It would be interesting to design the C API namespace in a similar way than Python packages and Python package sub-modules: But Python C API is far from respecting such design :-) The "Py_" namespace is a giant bag full of "anything". |
Sorry, something went wrong.
|
By the way, see also PR #112096 which adds PyHash_Pointer() function. |
Sorry, something went wrong.
|
How much it makes difference if remove the check for NaN from the function, but add it before calling the function, like in #112095 (comment) ? |
Sorry, something went wrong.
|
As far as I know, microbenchmarks at this level are susceptible to “random” variations due to code layout. An individual function should be benchmarked in a variety of calling situations to get a meaningful result. (But to reiterate: I don't think this is the place for micro-optimizations.) |
Sorry, something went wrong.
It would be bad to return the same hash value for +inf, -inf and NaN values. Current code: if (!Py_IS_FINITE(v)) {
if (Py_IS_INFINITY(v))
return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
else
return _Py_HashPointer(inst); // v is NaN
} |
Sorry, something went wrong.
We can take it in account in the API design. Now we know that the API I don't think that 0.9 ns is a significant difference. If a workflow is impacted by 0.9 ns per function call, maybe they should copy PyHash_Double() code and design a very specialized flavor for their workflow (ex: remove code for infinity and NaN, and inline all code). In terms of performance, I think that any proposed API is fine. |
Sorry, something went wrong.
|
@serhiy-storchaka @encukou: Do you prefer
I think that now that I read previous discussions, I prefer |
Sorry, something went wrong.
|
Yeah, |
Sorry, something went wrong.
First, I proposed I'm not fully comfortable with this API neither. I close this PR. Let's continue the discussion in PR #112449 which implements the API proposed by @encukou. |
Sorry, something went wrong.
Cleanup PyHash_Double() implementation based _Py_HashDouble():
Add tests: Modules/_testcapi/hash.c and Lib/test/test_capi/test_hash.py.
_Py_HashDoublepublic again as "unstable" API #111545📚 Documentation preview 📚: https://cpython-previews--112095.org.readthedocs.build/