result_type re-walks the promotion lattice on every call
backend.result_type is called by every op that reconciles operand dtypes, and on each call it re-walks the dtype promotion lattice from scratch via _lattice_result_type. Its arguments are a small, highly repetitive set of dtype combinations, so the same walk is recomputed over and over.
Master already memoizes three helpers inside that walk (_least_upper_bound, _respect_weak_type, _resolve_weak_type, all added while closing #23272), but result_type and _lattice_result_type themselves are still uncached, so the per-call Python work — building the promotion inputs, the generator expression, and the reduction over arguments — is paid every time.
Measured on numpy backend, 120k calls over 6 common dtype pairs:
| per call | |
|---|---|
master (c6a3b948e) |
1.150 µs |
| with the lattice walk memoized | 0.370 µs |
That is ~3.1x faster, saving roughly 0.78 µs per call.
Memoizing the walk is safe, but two details matter:
floatx()must be part of the cache key. Weak-type promotion depends on the currentfloatx, so aset_floatxcall must not be able to return a stale entry.- Each argument must be tagged with its type.
tf.DType.__hash__and__eq__are coerced to match plain Python ints —hash(tf.float32) == hash(1)andtf.float32 == 1isTrue. With an untagged key, a cachedtf.float32entry would make a later, invalidresult_type(1)return"float32"instead of raising.
The float8 rejection has to stay outside the cache so it keeps raising on every call rather than only the first, and unhashable arguments need to fall through to the uncached walk so they are still rejected.
This was originally carved out of #23182 and tracked under #23272, but #23272 was closed as completed once the standardize_dtype half landed, leaving this half without an issue.
Part of the per-call Python-dispatch overhead series in #22561. Fixed by #23336.
Source: keras-team/keras