Compiling einstein sums optimally
It seems that the general problem of finding the optimal contraction order is NP-hard [1]. A recent paper on approximately optimizing the contraction order, and containing relevant references, is [2].
[1] Chi-Chung, Lam, P. Sadayappan, and Rephael Wenger. &quot;On optimizing a class of multi-dimensional loops with reduction for parallel execution.&quot; Parallel Processing Letters 7.02 (1997): 157-168.
[2] Schindler, Frank, and Adam Jermyn. &quot;Algorithms for tensor network contraction ordering.&quot; Machine Learning: Science and Technology (2020).