#23698·keras

result_type re-walks the promotion lattice on every call

Author: pctablet505Created Sep 21, 2026Updated Sep 28, 2026
Labelstype:Bugpython

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 current floatx, so a set_floatx call 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) and tf.float32 == 1 is True. With an untagged key, a cached tf.float32 entry would make a later, invalid result_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.