paths.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. """
  2. Contains the path technology behind opt_einsum in addition to several path helpers
  3. """
  4. import functools
  5. import heapq
  6. import itertools
  7. import random
  8. from collections import Counter, OrderedDict, defaultdict
  9. import numpy as np
  10. from . import helpers
  11. __all__ = [
  12. "optimal", "BranchBound", "branch", "greedy", "auto", "auto_hq", "get_path_fn", "DynamicProgramming",
  13. "dynamic_programming"
  14. ]
  15. _UNLIMITED_MEM = {-1, None, float('inf')}
  16. class PathOptimizer(object):
  17. """Base class for different path optimizers to inherit from.
  18. Subclassed optimizers should define a call method with signature::
  19. def __call__(self, inputs, output, size_dict, memory_limit=None):
  20. \"\"\"
  21. Parameters
  22. ----------
  23. inputs : list[set[str]]
  24. The indices of each input array.
  25. outputs : set[str]
  26. The output indices
  27. size_dict : dict[str, int]
  28. The size of each index
  29. memory_limit : int, optional
  30. If given, the maximum allowed memory.
  31. \"\"\"
  32. # ... compute path here ...
  33. return path
  34. where ``path`` is a list of int-tuples specifiying a contraction order.
  35. """
  36. def _check_args_against_first_call(self, inputs, output, size_dict):
  37. """Utility that stateful optimizers can use to ensure they are not
  38. called with different contractions across separate runs.
  39. """
  40. args = (inputs, output, size_dict)
  41. if not hasattr(self, '_first_call_args'):
  42. # simply set the attribute as currently there is no global PathOptimizer init
  43. self._first_call_args = args
  44. elif args != self._first_call_args:
  45. raise ValueError("The arguments specifiying the contraction that this path optimizer "
  46. "instance was called with have changed - try creating a new instance.")
  47. def __call__(self, inputs, output, size_dict, memory_limit=None):
  48. raise NotImplementedError
  49. def ssa_to_linear(ssa_path):
  50. """
  51. Convert a path with static single assignment ids to a path with recycled
  52. linear ids. For example::
  53. >>> ssa_to_linear([(0, 3), (2, 4), (1, 5)])
  54. [(0, 3), (1, 2), (0, 1)]
  55. """
  56. ids = np.arange(1 + max(map(max, ssa_path)), dtype=np.int32)
  57. path = []
  58. for ssa_ids in ssa_path:
  59. path.append(tuple(int(ids[ssa_id]) for ssa_id in ssa_ids))
  60. for ssa_id in ssa_ids:
  61. ids[ssa_id:] -= 1
  62. return path
  63. def linear_to_ssa(path):
  64. """
  65. Convert a path with recycled linear ids to a path with static single
  66. assignment ids. For example::
  67. >>> linear_to_ssa([(0, 3), (1, 2), (0, 1)])
  68. [(0, 3), (2, 4), (1, 5)]
  69. """
  70. num_inputs = sum(map(len, path)) - len(path) + 1
  71. linear_to_ssa = list(range(num_inputs))
  72. new_ids = itertools.count(num_inputs)
  73. ssa_path = []
  74. for ids in path:
  75. ssa_path.append(tuple(linear_to_ssa[id_] for id_ in ids))
  76. for id_ in sorted(ids, reverse=True):
  77. del linear_to_ssa[id_]
  78. linear_to_ssa.append(next(new_ids))
  79. return ssa_path
  80. def calc_k12_flops(inputs, output, remaining, i, j, size_dict):
  81. """
  82. Calculate the resulting indices and flops for a potential pairwise
  83. contraction - used in the recursive (optimal/branch) algorithms.
  84. Parameters
  85. ----------
  86. inputs : tuple[frozenset[str]]
  87. The indices of each tensor in this contraction, note this includes
  88. tensors unavaiable to contract as static single assignment is used ->
  89. contracted tensors are not removed from the list.
  90. output : frozenset[str]
  91. The set of output indices for the whole contraction.
  92. remaining : frozenset[int]
  93. The set of indices (corresponding to ``inputs``) of tensors still
  94. available to contract.
  95. i : int
  96. Index of potential tensor to contract.
  97. j : int
  98. Index of potential tensor to contract.
  99. size_dict dict[str, int]
  100. Size mapping of all the indices.
  101. Returns
  102. -------
  103. k12 : frozenset
  104. The resulting indices of the potential tensor.
  105. cost : int
  106. Estimated flop count of operation.
  107. """
  108. k1, k2 = inputs[i], inputs[j]
  109. either = k1 | k2
  110. shared = k1 & k2
  111. keep = frozenset.union(output, *map(inputs.__getitem__, remaining - {i, j}))
  112. k12 = either & keep
  113. cost = helpers.flop_count(either, shared - keep, 2, size_dict)
  114. return k12, cost
  115. def _compute_oversize_flops(inputs, remaining, output, size_dict):
  116. """
  117. Compute the flop count for a contraction of all remaining arguments. This
  118. is used when a memory limit means that no pairwise contractions can be made.
  119. """
  120. idx_contraction = frozenset.union(*map(inputs.__getitem__, remaining))
  121. inner = idx_contraction - output
  122. num_terms = len(remaining)
  123. return helpers.flop_count(idx_contraction, inner, num_terms, size_dict)
  124. def optimal(inputs, output, size_dict, memory_limit=None):
  125. """
  126. Computes all possible pair contractions in a depth-first recursive manner,
  127. sieving results based on ``memory_limit`` and the best path found so far.
  128. Returns the lowest cost path. This algorithm scales factoriallly with
  129. respect to the elements in the list ``input_sets``.
  130. Parameters
  131. ----------
  132. inputs : list
  133. List of sets that represent the lhs side of the einsum subscript.
  134. output : set
  135. Set that represents the rhs side of the overall einsum subscript.
  136. size_dict : dictionary
  137. Dictionary of index sizes.
  138. memory_limit : int
  139. The maximum number of elements in a temporary array.
  140. Returns
  141. -------
  142. path : list
  143. The optimal contraction order within the memory limit constraint.
  144. Examples
  145. --------
  146. >>> isets = [set('abd'), set('ac'), set('bdc')]
  147. >>> oset = set('')
  148. >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
  149. >>> optimal(isets, oset, idx_sizes, 5000)
  150. [(0, 2), (0, 1)]
  151. """
  152. inputs = tuple(map(frozenset, inputs))
  153. output = frozenset(output)
  154. best = {'flops': float('inf'), 'ssa_path': (tuple(range(len(inputs))), )}
  155. size_cache = {}
  156. result_cache = {}
  157. def _optimal_iterate(path, remaining, inputs, flops):
  158. # reached end of path (only ever get here if flops is best found so far)
  159. if len(remaining) == 1:
  160. best['flops'] = flops
  161. best['ssa_path'] = path
  162. return
  163. # check all possible remaining paths
  164. for i, j in itertools.combinations(remaining, 2):
  165. if i > j:
  166. i, j = j, i
  167. key = (inputs[i], inputs[j])
  168. try:
  169. k12, flops12 = result_cache[key]
  170. except KeyError:
  171. k12, flops12 = result_cache[key] = calc_k12_flops(inputs, output, remaining, i, j, size_dict)
  172. # sieve based on current best flops
  173. new_flops = flops + flops12
  174. if new_flops >= best['flops']:
  175. continue
  176. # sieve based on memory limit
  177. if memory_limit not in _UNLIMITED_MEM:
  178. try:
  179. size12 = size_cache[k12]
  180. except KeyError:
  181. size12 = size_cache[k12] = helpers.compute_size_by_dict(k12, size_dict)
  182. # possibly terminate this path with an all-terms einsum
  183. if size12 > memory_limit:
  184. new_flops = flops + _compute_oversize_flops(inputs, remaining, output, size_dict)
  185. if new_flops < best['flops']:
  186. best['flops'] = new_flops
  187. best['ssa_path'] = path + (tuple(remaining), )
  188. continue
  189. # add contraction and recurse into all remaining
  190. _optimal_iterate(path=path + ((i, j), ),
  191. inputs=inputs + (k12, ),
  192. remaining=remaining - {i, j} | {len(inputs)},
  193. flops=new_flops)
  194. _optimal_iterate(path=(), inputs=inputs, remaining=set(range(len(inputs))), flops=0)
  195. return ssa_to_linear(best['ssa_path'])
  196. # functions for comparing which of two paths is 'better'
  197. def better_flops_first(flops, size, best_flops, best_size):
  198. return (flops, size) < (best_flops, best_size)
  199. def better_size_first(flops, size, best_flops, best_size):
  200. return (size, flops) < (best_size, best_flops)
  201. _BETTER_FNS = {
  202. 'flops': better_flops_first,
  203. 'size': better_size_first,
  204. }
  205. def get_better_fn(key):
  206. return _BETTER_FNS[key]
  207. # functions for assigning a heuristic 'cost' to a potential contraction
  208. def cost_memory_removed(size12, size1, size2, k12, k1, k2):
  209. """The default heuristic cost, corresponding to the total reduction in
  210. memory of performing a contraction.
  211. """
  212. return size12 - size1 - size2
  213. def cost_memory_removed_jitter(size12, size1, size2, k12, k1, k2):
  214. """Like memory-removed, but with a slight amount of noise that breaks ties
  215. and thus jumbles the contractions a bit.
  216. """
  217. return random.gauss(1.0, 0.01) * (size12 - size1 - size2)
  218. _COST_FNS = {
  219. 'memory-removed': cost_memory_removed,
  220. 'memory-removed-jitter': cost_memory_removed_jitter,
  221. }
  222. class BranchBound(PathOptimizer):
  223. """
  224. Explores possible pair contractions in a depth-first recursive manner like
  225. the ``optimal`` approach, but with extra heuristic early pruning of branches
  226. as well sieving by ``memory_limit`` and the best path found so far. Returns
  227. the lowest cost path. This algorithm still scales factorially with respect
  228. to the elements in the list ``input_sets`` if ``nbranch`` is not set, but it
  229. scales exponentially like ``nbranch**len(input_sets)`` otherwise.
  230. Parameters
  231. ----------
  232. nbranch : None or int, optional
  233. How many branches to explore at each contraction step. If None, explore
  234. all possible branches. If an integer, branch into this many paths at
  235. each step. Defaults to None.
  236. cutoff_flops_factor : float, optional
  237. If at any point, a path is doing this much worse than the best path
  238. found so far was, terminate it. The larger this is made, the more paths
  239. will be fully explored and the slower the algorithm. Defaults to 4.
  240. minimize : {'flops', 'size'}, optional
  241. Whether to optimize the path with regard primarily to the total
  242. estimated flop-count, or the size of the largest intermediate. The
  243. option not chosen will still be used as a secondary criterion.
  244. cost_fn : callable, optional
  245. A function that returns a heuristic 'cost' of a potential contraction
  246. with which to sort candidates. Should have signature
  247. ``cost_fn(size12, size1, size2, k12, k1, k2)``.
  248. """
  249. def __init__(self, nbranch=None, cutoff_flops_factor=4, minimize='flops', cost_fn='memory-removed'):
  250. self.nbranch = nbranch
  251. self.cutoff_flops_factor = cutoff_flops_factor
  252. self.minimize = minimize
  253. self.cost_fn = _COST_FNS.get(cost_fn, cost_fn)
  254. self.better = get_better_fn(minimize)
  255. self.best = {'flops': float('inf'), 'size': float('inf')}
  256. self.best_progress = defaultdict(lambda: float('inf'))
  257. @property
  258. def path(self):
  259. return ssa_to_linear(self.best['ssa_path'])
  260. def __call__(self, inputs, output, size_dict, memory_limit=None):
  261. """
  262. Parameters
  263. ----------
  264. input_sets : list
  265. List of sets that represent the lhs side of the einsum subscript
  266. output_set : set
  267. Set that represents the rhs side of the overall einsum subscript
  268. idx_dict : dictionary
  269. Dictionary of index sizes
  270. memory_limit : int
  271. The maximum number of elements in a temporary array
  272. Returns
  273. -------
  274. path : list
  275. The contraction order within the memory limit constraint.
  276. Examples
  277. --------
  278. >>> isets = [set('abd'), set('ac'), set('bdc')]
  279. >>> oset = set('')
  280. >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
  281. >>> optimal(isets, oset, idx_sizes, 5000)
  282. [(0, 2), (0, 1)]
  283. """
  284. self._check_args_against_first_call(inputs, output, size_dict)
  285. inputs = tuple(map(frozenset, inputs))
  286. output = frozenset(output)
  287. size_cache = {k: helpers.compute_size_by_dict(k, size_dict) for k in inputs}
  288. result_cache = {}
  289. def _branch_iterate(path, inputs, remaining, flops, size):
  290. # reached end of path (only ever get here if flops is best found so far)
  291. if len(remaining) == 1:
  292. self.best['size'] = size
  293. self.best['flops'] = flops
  294. self.best['ssa_path'] = path
  295. return
  296. def _assess_candidate(k1, k2, i, j):
  297. # find resulting indices and flops
  298. try:
  299. k12, flops12 = result_cache[k1, k2]
  300. except KeyError:
  301. k12, flops12 = result_cache[k1, k2] = calc_k12_flops(inputs, output, remaining, i, j, size_dict)
  302. try:
  303. size12 = size_cache[k12]
  304. except KeyError:
  305. size12 = size_cache[k12] = helpers.compute_size_by_dict(k12, size_dict)
  306. new_flops = flops + flops12
  307. new_size = max(size, size12)
  308. # sieve based on current best i.e. check flops and size still better
  309. if not self.better(new_flops, new_size, self.best['flops'], self.best['size']):
  310. return None
  311. # compare to how the best method was doing as this point
  312. if new_flops < self.best_progress[len(inputs)]:
  313. self.best_progress[len(inputs)] = new_flops
  314. # sieve based on current progress relative to best
  315. elif new_flops > self.cutoff_flops_factor * self.best_progress[len(inputs)]:
  316. return None
  317. # sieve based on memory limit
  318. if (memory_limit not in _UNLIMITED_MEM) and (size12 > memory_limit):
  319. # terminate path here, but check all-terms contract first
  320. new_flops = flops + _compute_oversize_flops(inputs, remaining, output, size_dict)
  321. if new_flops < self.best['flops']:
  322. self.best['flops'] = new_flops
  323. self.best['ssa_path'] = path + (tuple(remaining), )
  324. return None
  325. # set cost heuristic in order to locally sort possible contractions
  326. size1, size2 = size_cache[inputs[i]], size_cache[inputs[j]]
  327. cost = self.cost_fn(size12, size1, size2, k12, k1, k2)
  328. return cost, flops12, new_flops, new_size, (i, j), k12
  329. # check all possible remaining paths
  330. candidates = []
  331. for i, j in itertools.combinations(remaining, 2):
  332. if i > j:
  333. i, j = j, i
  334. k1, k2 = inputs[i], inputs[j]
  335. # initially ignore outer products
  336. if k1.isdisjoint(k2):
  337. continue
  338. candidate = _assess_candidate(k1, k2, i, j)
  339. if candidate:
  340. heapq.heappush(candidates, candidate)
  341. # assess outer products if nothing left
  342. if not candidates:
  343. for i, j in itertools.combinations(remaining, 2):
  344. if i > j:
  345. i, j = j, i
  346. k1, k2 = inputs[i], inputs[j]
  347. candidate = _assess_candidate(k1, k2, i, j)
  348. if candidate:
  349. heapq.heappush(candidates, candidate)
  350. # recurse into all or some of the best candidate contractions
  351. bi = 0
  352. while (self.nbranch is None or bi < self.nbranch) and candidates:
  353. _, _, new_flops, new_size, (i, j), k12 = heapq.heappop(candidates)
  354. _branch_iterate(path=path + ((i, j), ),
  355. inputs=inputs + (k12, ),
  356. remaining=(remaining - {i, j}) | {len(inputs)},
  357. flops=new_flops,
  358. size=new_size)
  359. bi += 1
  360. _branch_iterate(path=(), inputs=inputs, remaining=set(range(len(inputs))), flops=0, size=0)
  361. return self.path
  362. def branch(inputs, output, size_dict, memory_limit=None, **optimizer_kwargs):
  363. optimizer = BranchBound(**optimizer_kwargs)
  364. return optimizer(inputs, output, size_dict, memory_limit)
  365. branch_all = functools.partial(branch, nbranch=None)
  366. branch_2 = functools.partial(branch, nbranch=2)
  367. branch_1 = functools.partial(branch, nbranch=1)
  368. def _get_candidate(output, sizes, remaining, footprints, dim_ref_counts, k1, k2, cost_fn):
  369. either = k1 | k2
  370. two = k1 & k2
  371. one = either - two
  372. k12 = (either & output) | (two & dim_ref_counts[3]) | (one & dim_ref_counts[2])
  373. cost = cost_fn(helpers.compute_size_by_dict(k12, sizes), footprints[k1], footprints[k2], k12, k1, k2)
  374. id1 = remaining[k1]
  375. id2 = remaining[k2]
  376. if id1 > id2:
  377. k1, id1, k2, id2 = k2, id2, k1, id1
  378. cost = cost, id2, id1 # break ties to ensure determinism
  379. return cost, k1, k2, k12
  380. def _push_candidate(output, sizes, remaining, footprints, dim_ref_counts, k1, k2s, queue, push_all, cost_fn):
  381. candidates = (_get_candidate(output, sizes, remaining, footprints, dim_ref_counts, k1, k2, cost_fn) for k2 in k2s)
  382. if push_all:
  383. # want to do this if we e.g. are using a custom 'choose_fn'
  384. for candidate in candidates:
  385. heapq.heappush(queue, candidate)
  386. else:
  387. heapq.heappush(queue, min(candidates))
  388. def _update_ref_counts(dim_to_keys, dim_ref_counts, dims):
  389. for dim in dims:
  390. count = len(dim_to_keys[dim])
  391. if count <= 1:
  392. dim_ref_counts[2].discard(dim)
  393. dim_ref_counts[3].discard(dim)
  394. elif count == 2:
  395. dim_ref_counts[2].add(dim)
  396. dim_ref_counts[3].discard(dim)
  397. else:
  398. dim_ref_counts[2].add(dim)
  399. dim_ref_counts[3].add(dim)
  400. def _simple_chooser(queue, remaining):
  401. """Default contraction chooser that simply takes the minimum cost option.
  402. """
  403. cost, k1, k2, k12 = heapq.heappop(queue)
  404. if k1 not in remaining or k2 not in remaining:
  405. return None # candidate is obsolete
  406. return cost, k1, k2, k12
  407. def ssa_greedy_optimize(inputs, output, sizes, choose_fn=None, cost_fn='memory-removed'):
  408. """
  409. This is the core function for :func:`greedy` but produces a path with
  410. static single assignment ids rather than recycled linear ids.
  411. SSA ids are cheaper to work with and easier to reason about.
  412. """
  413. if len(inputs) == 1:
  414. # Perform a single contraction to match output shape.
  415. return [(0, )]
  416. # set the function that assigns a heuristic cost to a possible contraction
  417. cost_fn = _COST_FNS.get(cost_fn, cost_fn)
  418. # set the function that chooses which contraction to take
  419. if choose_fn is None:
  420. choose_fn = _simple_chooser
  421. push_all = False
  422. else:
  423. # assume chooser wants access to all possible contractions
  424. push_all = True
  425. # A dim that is common to all tensors might as well be an output dim, since it
  426. # cannot be contracted until the final step. This avoids an expensive all-pairs
  427. # comparison to search for possible contractions at each step, leading to speedup
  428. # in many practical problems where all tensors share a common batch dimension.
  429. inputs = list(map(frozenset, inputs))
  430. output = frozenset(output) | frozenset.intersection(*inputs)
  431. # Deduplicate shapes by eagerly computing Hadamard products.
  432. remaining = {} # key -> ssa_id
  433. ssa_ids = itertools.count(len(inputs))
  434. ssa_path = []
  435. for ssa_id, key in enumerate(inputs):
  436. if key in remaining:
  437. ssa_path.append((remaining[key], ssa_id))
  438. remaining[key] = next(ssa_ids)
  439. else:
  440. remaining[key] = ssa_id
  441. # Keep track of possible contraction dims.
  442. dim_to_keys = defaultdict(set)
  443. for key in remaining:
  444. for dim in key - output:
  445. dim_to_keys[dim].add(key)
  446. # Keep track of the number of tensors using each dim; when the dim is no longer
  447. # used it can be contracted. Since we specialize to binary ops, we only care about
  448. # ref counts of >=2 or >=3.
  449. dim_ref_counts = {
  450. count: set(dim for dim, keys in dim_to_keys.items() if len(keys) >= count) - output
  451. for count in [2, 3]
  452. }
  453. # Compute separable part of the objective function for contractions.
  454. footprints = {key: helpers.compute_size_by_dict(key, sizes) for key in remaining}
  455. # Find initial candidate contractions.
  456. queue = []
  457. for dim, keys in dim_to_keys.items():
  458. keys = sorted(keys, key=remaining.__getitem__)
  459. for i, k1 in enumerate(keys[:-1]):
  460. k2s = keys[1 + i:]
  461. _push_candidate(output, sizes, remaining, footprints, dim_ref_counts, k1, k2s, queue, push_all, cost_fn)
  462. # Greedily contract pairs of tensors.
  463. while queue:
  464. con = choose_fn(queue, remaining)
  465. if con is None:
  466. continue # allow choose_fn to flag all candidates obsolete
  467. cost, k1, k2, k12 = con
  468. ssa_id1 = remaining.pop(k1)
  469. ssa_id2 = remaining.pop(k2)
  470. for dim in k1 - output:
  471. dim_to_keys[dim].remove(k1)
  472. for dim in k2 - output:
  473. dim_to_keys[dim].remove(k2)
  474. ssa_path.append((ssa_id1, ssa_id2))
  475. if k12 in remaining:
  476. ssa_path.append((remaining[k12], next(ssa_ids)))
  477. else:
  478. for dim in k12 - output:
  479. dim_to_keys[dim].add(k12)
  480. remaining[k12] = next(ssa_ids)
  481. _update_ref_counts(dim_to_keys, dim_ref_counts, k1 | k2 - output)
  482. footprints[k12] = helpers.compute_size_by_dict(k12, sizes)
  483. # Find new candidate contractions.
  484. k1 = k12
  485. k2s = set(k2 for dim in k1 for k2 in dim_to_keys[dim])
  486. k2s.discard(k1)
  487. if k2s:
  488. _push_candidate(output, sizes, remaining, footprints, dim_ref_counts, k1, k2s, queue, push_all, cost_fn)
  489. # Greedily compute pairwise outer products.
  490. queue = [(helpers.compute_size_by_dict(key & output, sizes), ssa_id, key) for key, ssa_id in remaining.items()]
  491. heapq.heapify(queue)
  492. _, ssa_id1, k1 = heapq.heappop(queue)
  493. while queue:
  494. _, ssa_id2, k2 = heapq.heappop(queue)
  495. ssa_path.append((min(ssa_id1, ssa_id2), max(ssa_id1, ssa_id2)))
  496. k12 = (k1 | k2) & output
  497. cost = helpers.compute_size_by_dict(k12, sizes)
  498. ssa_id12 = next(ssa_ids)
  499. _, ssa_id1, k1 = heapq.heappushpop(queue, (cost, ssa_id12, k12))
  500. return ssa_path
  501. def greedy(inputs, output, size_dict, memory_limit=None, choose_fn=None, cost_fn='memory-removed'):
  502. """
  503. Finds the path by a three stage algorithm:
  504. 1. Eagerly compute Hadamard products.
  505. 2. Greedily compute contractions to maximize ``removed_size``
  506. 3. Greedily compute outer products.
  507. This algorithm scales quadratically with respect to the
  508. maximum number of elements sharing a common dim.
  509. Parameters
  510. ----------
  511. inputs : list
  512. List of sets that represent the lhs side of the einsum subscript
  513. output : set
  514. Set that represents the rhs side of the overall einsum subscript
  515. size_dict : dictionary
  516. Dictionary of index sizes
  517. memory_limit : int
  518. The maximum number of elements in a temporary array
  519. choose_fn : callable, optional
  520. A function that chooses which contraction to perform from the queu
  521. cost_fn : callable, optional
  522. A function that assigns a potential contraction a cost.
  523. Returns
  524. -------
  525. path : list
  526. The contraction order (a list of tuples of ints).
  527. Examples
  528. --------
  529. >>> isets = [set('abd'), set('ac'), set('bdc')]
  530. >>> oset = set('')
  531. >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
  532. >>> greedy(isets, oset, idx_sizes)
  533. [(0, 2), (0, 1)]
  534. """
  535. if memory_limit not in _UNLIMITED_MEM:
  536. return branch(inputs, output, size_dict, memory_limit, nbranch=1, cost_fn=cost_fn)
  537. ssa_path = ssa_greedy_optimize(inputs, output, size_dict, cost_fn=cost_fn, choose_fn=choose_fn)
  538. return ssa_to_linear(ssa_path)
  539. def _tree_to_sequence(c):
  540. """
  541. Converts a contraction tree to a contraction path as it has to be
  542. returned by path optimizers. A contraction tree can either be an int
  543. (=no contraction) or a tuple containing the terms to be contracted. An
  544. arbitrary number (>= 1) of terms can be contracted at once. Note that
  545. contractions are commutative, e.g. (j, k, l) = (k, l, j). Note that in
  546. general, solutions are not unique.
  547. Parameters
  548. ----------
  549. c : tuple or int
  550. Contraction tree
  551. Returns
  552. -------
  553. path : list[set[int]]
  554. Contraction path
  555. Examples
  556. --------
  557. >>> _tree_to_sequence(((1,2),(0,(4,5,3))))
  558. [(1, 2), (1, 2, 3), (0, 2), (0, 1)]
  559. """
  560. # ((1,2),(0,(4,5,3))) --> [(1, 2), (1, 2, 3), (0, 2), (0, 1)]
  561. #
  562. # 0 0 0 (1,2) --> ((1,2),(0,(3,4,5)))
  563. # 1 3 (1,2) --> (0,(3,4,5))
  564. # 2 --> 4 --> (3,4,5)
  565. # 3 5
  566. # 4 (1,2)
  567. # 5
  568. #
  569. # this function iterates through the table shown above from right to left;
  570. if type(c) == int:
  571. return []
  572. c = [c] # list of remaining contractions (lower part of columns shown above)
  573. t = [] # list of elementary tensors (upper part of colums)
  574. s = [] # resulting contraction sequence
  575. while len(c) > 0:
  576. j = c.pop(-1)
  577. s.insert(0, tuple())
  578. for i in sorted([i for i in j if type(i) == int]):
  579. s[0] += (sum(1 for q in t if q < i), )
  580. t.insert(s[0][-1], i)
  581. for i in [i for i in j if type(i) != int]:
  582. s[0] += (len(t) + len(c), )
  583. c.append(i)
  584. return s
  585. def _find_disconnected_subgraphs(inputs, output):
  586. """
  587. Finds disconnected subgraphs in the given list of inputs. Inputs are
  588. connected if they share summation indices. Note: Disconnected subgraphs
  589. can be contracted independently before forming outer products.
  590. Parameters
  591. ----------
  592. inputs : list[set]
  593. List of sets that represent the lhs side of the einsum subscript
  594. output : set
  595. Set that represents the rhs side of the overall einsum subscript
  596. Returns
  597. -------
  598. subgraphs : list[set[int]]
  599. List containing sets of indices for each subgraph
  600. Examples
  601. --------
  602. >>> _find_disconnected_subgraphs([set("ab"), set("c"), set("ad")], set("bd"))
  603. [{0, 2}, {1}]
  604. >>> _find_disconnected_subgraphs([set("ab"), set("c"), set("ad")], set("abd"))
  605. [{0}, {1}, {2}]
  606. """
  607. subgraphs = []
  608. unused_inputs = set(range(len(inputs)))
  609. i_sum = set.union(*inputs) - output # all summation indices
  610. while len(unused_inputs) > 0:
  611. g = set()
  612. q = [unused_inputs.pop()]
  613. while len(q) > 0:
  614. j = q.pop()
  615. g.add(j)
  616. i_tmp = i_sum & inputs[j]
  617. n = {k for k in unused_inputs if len(i_tmp & inputs[k]) > 0}
  618. q.extend(n)
  619. unused_inputs.difference_update(n)
  620. subgraphs.append(g)
  621. return subgraphs
  622. def _bitmap_select(s, seq):
  623. """Select elements of ``seq`` which are marked by the bitmap set ``s``.
  624. E.g.:
  625. >>> list(_bitmap_select(0b11010, ['A', 'B', 'C', 'D', 'E']))
  626. ['B', 'D', 'E']
  627. """
  628. return (x for x, b in zip(seq, bin(s)[:1:-1]) if b == '1')
  629. def _dp_calc_legs(g, all_tensors, s, inputs, i1_cut_i2_wo_output, i1_union_i2):
  630. """Calculates the effective outer indices of the intermediate tensor
  631. corresponding to the subgraph ``s``.
  632. """
  633. # set of remaining tensors (=g-s)
  634. r = g & (all_tensors ^ s)
  635. # indices of remaining indices:
  636. if r:
  637. i_r = set.union(*_bitmap_select(r, inputs))
  638. else:
  639. i_r = set()
  640. # contraction indices:
  641. i_contract = i1_cut_i2_wo_output - i_r
  642. return i1_union_i2 - i_contract
  643. def _dp_compare_flops(cost1, cost2, i1_union_i2, size_dict, cost_cap, s1, s2, xn, g, all_tensors, inputs,
  644. i1_cut_i2_wo_output, memory_limit, cntrct1, cntrct2):
  645. """Performs the inner comparison of whether the two subgraphs (the bitmaps
  646. ``s1`` and ``s2``) should be merged and added to the dynamic programming
  647. search. Will skip for a number of reasons:
  648. 1. If the number of operations to form ``s = s1 | s2`` including previous
  649. contractions is above the cost-cap.
  650. 2. If we've already found a better way of making ``s``.
  651. 3. If the intermediate tensor corresponding to ``s`` is going to break the
  652. memory limit.
  653. """
  654. cost = cost1 + cost2 + helpers.compute_size_by_dict(i1_union_i2, size_dict)
  655. if cost <= cost_cap:
  656. s = s1 | s2
  657. if s not in xn or cost < xn[s][1]:
  658. i = _dp_calc_legs(g, all_tensors, s, inputs, i1_cut_i2_wo_output, i1_union_i2)
  659. mem = helpers.compute_size_by_dict(i, size_dict)
  660. if memory_limit is None or mem <= memory_limit:
  661. xn[s] = (i, cost, (cntrct1, cntrct2))
  662. def _dp_compare_size(cost1, cost2, i1_union_i2, size_dict, cost_cap, s1, s2, xn, g, all_tensors, inputs,
  663. i1_cut_i2_wo_output, memory_limit, cntrct1, cntrct2):
  664. """Like ``_dp_compare_flops`` but sieves the potential contraction based
  665. on the size of the intermediate tensor created, rather than the number of
  666. operations, and so calculates that first.
  667. """
  668. s = s1 | s2
  669. i = _dp_calc_legs(g, all_tensors, s, inputs, i1_cut_i2_wo_output, i1_union_i2)
  670. mem = helpers.compute_size_by_dict(i, size_dict)
  671. cost = max(cost1, cost2, mem)
  672. if cost <= cost_cap:
  673. if s not in xn or cost < xn[s][1]:
  674. if memory_limit is None or mem <= memory_limit:
  675. xn[s] = (i, cost, (cntrct1, cntrct2))
  676. def simple_tree_tuple(seq):
  677. """Make a simple left to right binary tree out of iterable ``seq``.
  678. >>> tuple_nest([1, 2, 3, 4])
  679. (((1, 2), 3), 4)
  680. """
  681. return functools.reduce(lambda x, y: (x, y), seq)
  682. def _dp_parse_out_single_term_ops(inputs, all_inds, ind_counts):
  683. """Take ``inputs`` and parse for single term index operations, i.e. where
  684. an index appears on one tensor and nowhere else.
  685. If a term is completely reduced to a scalar in this way it can be removed
  686. to ``inputs_done``. If only some indices can be summed then add a 'single
  687. term contraction' that will perform this summation.
  688. """
  689. i_single = {i for i, c in enumerate(all_inds) if ind_counts[c] == 1}
  690. inputs_parsed, inputs_done, inputs_contractions = [], [], []
  691. for j, i in enumerate(inputs):
  692. i_reduced = i - i_single
  693. if not i_reduced:
  694. # input reduced to scalar already - remove
  695. inputs_done.append((j, ))
  696. else:
  697. # if the input has any index reductions, add single contraction
  698. inputs_parsed.append(i_reduced)
  699. inputs_contractions.append((j, ) if i_reduced != i else j)
  700. return inputs_parsed, inputs_done, inputs_contractions
  701. class DynamicProgramming(PathOptimizer):
  702. """
  703. Finds the optimal path of pairwise contractions without intermediate outer
  704. products based a dynamic programming approach presented in
  705. Phys. Rev. E 90, 033315 (2014) (the corresponding preprint is publically
  706. available at https://arxiv.org/abs/1304.6112). This method is especially
  707. well-suited in the area of tensor network states, where it usually
  708. outperforms all the other optimization strategies.
  709. This algorithm shows exponential scaling with the number of inputs
  710. in the worst case scenario (see example below). If the graph to be
  711. contracted consists of disconnected subgraphs, the algorithm scales
  712. linearly in the number of disconnected subgraphs and only exponentially
  713. with the number of inputs per subgraph.
  714. Parameters
  715. ----------
  716. minimize : {'flops', 'size'}, optional
  717. Whether to find the contraction that minimizes the number of
  718. operations or the size of the largest intermediate tensor.
  719. cost_cap : {True, False, int}, optional
  720. How to implement cost-capping:
  721. * True - iteratively increase the cost-cap
  722. * False - implement no cost-cap at all
  723. * int - use explicit cost cap
  724. search_outer : bool, optional
  725. In rare circumstances the optimal contraction may involve an outer
  726. product, this option allows searching such contractions but may well
  727. slow down the path finding considerably on all but very small graphs.
  728. """
  729. def __init__(self, minimize='flops', cost_cap=True, search_outer=False):
  730. # set whether inner function minimizes against flops or size
  731. self.minimize = minimize
  732. self._check_contraction = {
  733. 'flops': _dp_compare_flops,
  734. 'size': _dp_compare_size,
  735. }[self.minimize]
  736. # set whether inner function considers outer products
  737. self.search_outer = search_outer
  738. self._check_outer = {
  739. False: lambda x: x,
  740. True: lambda x: True,
  741. }[self.search_outer]
  742. self.cost_cap = cost_cap
  743. def __call__(self, inputs, output, size_dict, memory_limit=None):
  744. """
  745. Parameters
  746. ----------
  747. inputs : list
  748. List of sets that represent the lhs side of the einsum subscript
  749. output : set
  750. Set that represents the rhs side of the overall einsum subscript
  751. size_dict : dictionary
  752. Dictionary of index sizes
  753. memory_limit : int
  754. The maximum number of elements in a temporary array
  755. Returns
  756. -------
  757. path : list
  758. The contraction order (a list of tuples of ints).
  759. Examples
  760. --------
  761. >>> n_in = 3 # exponential scaling
  762. >>> n_out = 2 # linear scaling
  763. >>> s = dict()
  764. >>> i_all = []
  765. >>> for _ in range(n_out):
  766. >>> i = [set() for _ in range(n_in)]
  767. >>> for j in range(n_in):
  768. >>> for k in range(j+1, n_in):
  769. >>> c = oe.get_symbol(len(s))
  770. >>> i[j].add(c)
  771. >>> i[k].add(c)
  772. >>> s[c] = 2
  773. >>> i_all.extend(i)
  774. >>> o = DynamicProgramming()
  775. >>> o(i_all, set(), s)
  776. [(1, 2), (0, 4), (1, 2), (0, 2), (0, 1)]
  777. """
  778. ind_counts = Counter(itertools.chain(*inputs, output))
  779. all_inds = tuple(ind_counts)
  780. # convert all indices to integers (makes set operations ~10 % faster)
  781. symbol2int = {c: j for j, c in enumerate(all_inds)}
  782. inputs = [set(symbol2int[c] for c in i) for i in inputs]
  783. output = set(symbol2int[c] for c in output)
  784. size_dict = {symbol2int[c]: v for c, v in size_dict.items() if c in symbol2int}
  785. size_dict = [size_dict[j] for j in range(len(size_dict))]
  786. inputs, inputs_done, inputs_contractions = _dp_parse_out_single_term_ops(inputs, all_inds, ind_counts)
  787. if not inputs:
  788. # nothing left to do after single axis reductions!
  789. return _tree_to_sequence(simple_tree_tuple(inputs_done))
  790. # a list of all neccessary contraction expressions for each of the
  791. # disconnected subgraphs and their size
  792. subgraph_contractions = inputs_done
  793. subgraph_contractions_size = [1] * len(inputs_done)
  794. if self.search_outer:
  795. # optimize everything together if we are considering outer products
  796. subgraphs = [set(range(len(inputs)))]
  797. else:
  798. subgraphs = _find_disconnected_subgraphs(inputs, output)
  799. # the bitmap set of all tensors is computed as it is needed to
  800. # compute set differences: s1 - s2 transforms into
  801. # s1 & (all_tensors ^ s2)
  802. all_tensors = (1 << len(inputs)) - 1
  803. for g in subgraphs:
  804. # dynamic programming approach to compute x[n] for subgraph g;
  805. # x[n][set of n tensors] = (indices, cost, contraction)
  806. # the set of n tensors is represented by a bitmap: if bit j is 1,
  807. # tensor j is in the set, e.g. 0b100101 = {0,2,5}; set unions
  808. # (intersections) can then be computed by bitwise or (and);
  809. x = [None] * 2 + [dict() for j in range(len(g) - 1)]
  810. x[1] = OrderedDict((1 << j, (inputs[j], 0, inputs_contractions[j])) for j in g)
  811. # convert set of tensors g to a bitmap set:
  812. g = functools.reduce(lambda x, y: x | y, (1 << j for j in g))
  813. # try to find contraction with cost <= cost_cap and increase
  814. # cost_cap successively if no such contraction is found;
  815. # this is a major performance improvement; start with product of
  816. # output index dimensions as initial cost_cap
  817. subgraph_inds = set.union(*_bitmap_select(g, inputs))
  818. if self.cost_cap is True:
  819. cost_cap = helpers.compute_size_by_dict(subgraph_inds & output, size_dict)
  820. elif self.cost_cap is False:
  821. cost_cap = float('inf')
  822. else:
  823. cost_cap = self.cost_cap
  824. # set the factor to increase the cost by each iteration (ensure > 1)
  825. cost_increment = max(min(map(size_dict.__getitem__, subgraph_inds)), 2)
  826. while len(x[-1]) == 0:
  827. for n in range(2, len(x[1]) + 1):
  828. xn = x[n]
  829. # try to combine solutions from x[m] and x[n-m]
  830. for m in range(1, n // 2 + 1):
  831. for s1, (i1, cost1, cntrct1) in x[m].items():
  832. for s2, (i2, cost2, cntrct2) in x[n - m].items():
  833. # can only merge if s1 and s2 are disjoint
  834. # and avoid e.g. s1={0}, s2={1} and s1={1}, s2={0}
  835. if (not s1 & s2) and (m != n - m or s1 < s2):
  836. i1_cut_i2_wo_output = (i1 & i2) - output
  837. # maybe ignore outer products:
  838. if self._check_outer(i1_cut_i2_wo_output):
  839. i1_union_i2 = i1 | i2
  840. self._check_contraction(cost1, cost2, i1_union_i2, size_dict, cost_cap, s1, s2,
  841. xn, g, all_tensors, inputs, i1_cut_i2_wo_output,
  842. memory_limit, cntrct1, cntrct2)
  843. # increase cost cap for next iteration:
  844. cost_cap = cost_increment * cost_cap
  845. i, cost, contraction = list(x[-1].values())[0]
  846. subgraph_contractions.append(contraction)
  847. subgraph_contractions_size.append(helpers.compute_size_by_dict(i, size_dict))
  848. # sort the subgraph contractions by the size of the subgraphs in
  849. # ascending order (will give the cheapest contractions); note that
  850. # outer products should be performed pairwise (to use BLAS functions)
  851. subgraph_contractions = [
  852. subgraph_contractions[j]
  853. for j in sorted(range(len(subgraph_contractions_size)), key=subgraph_contractions_size.__getitem__)
  854. ]
  855. # build the final contraction tree
  856. tree = simple_tree_tuple(subgraph_contractions)
  857. return _tree_to_sequence(tree)
  858. def dynamic_programming(inputs, output, size_dict, memory_limit=None, **kwargs):
  859. optimizer = DynamicProgramming(**kwargs)
  860. return optimizer(inputs, output, size_dict, memory_limit)
  861. _AUTO_CHOICES = {}
  862. for i in range(1, 5):
  863. _AUTO_CHOICES[i] = optimal
  864. for i in range(5, 7):
  865. _AUTO_CHOICES[i] = branch_all
  866. for i in range(7, 9):
  867. _AUTO_CHOICES[i] = branch_2
  868. for i in range(9, 15):
  869. _AUTO_CHOICES[i] = branch_1
  870. def auto(inputs, output, size_dict, memory_limit=None):
  871. """Finds the contraction path by automatically choosing the method based on
  872. how many input arguments there are.
  873. """
  874. N = len(inputs)
  875. return _AUTO_CHOICES.get(N, greedy)(inputs, output, size_dict, memory_limit)
  876. _AUTO_HQ_CHOICES = {}
  877. for i in range(1, 6):
  878. _AUTO_HQ_CHOICES[i] = optimal
  879. for i in range(6, 17):
  880. _AUTO_HQ_CHOICES[i] = dynamic_programming
  881. def auto_hq(inputs, output, size_dict, memory_limit=None):
  882. """Finds the contraction path by automatically choosing the method based on
  883. how many input arguments there are, but targeting a more generous
  884. amount of search time than ``'auto'``.
  885. """
  886. from .path_random import random_greedy_128
  887. N = len(inputs)
  888. return _AUTO_HQ_CHOICES.get(N, random_greedy_128)(inputs, output, size_dict, memory_limit)
  889. _PATH_OPTIONS = {
  890. 'auto': auto,
  891. 'auto-hq': auto_hq,
  892. 'optimal': optimal,
  893. 'branch-all': branch_all,
  894. 'branch-2': branch_2,
  895. 'branch-1': branch_1,
  896. 'greedy': greedy,
  897. 'eager': greedy,
  898. 'opportunistic': greedy,
  899. 'dp': dynamic_programming,
  900. 'dynamic-programming': dynamic_programming
  901. }
  902. def register_path_fn(name, fn):
  903. """Add path finding function ``fn`` as an option with ``name``.
  904. """
  905. if name in _PATH_OPTIONS:
  906. raise KeyError("Path optimizer '{}' already exists.".format(name))
  907. _PATH_OPTIONS[name.lower()] = fn
  908. def get_path_fn(path_type):
  909. """Get the correct path finding function from str ``path_type``.
  910. """
  911. if path_type not in _PATH_OPTIONS:
  912. raise KeyError("Path optimizer '{}' not found, valid options are {}.".format(
  913. path_type, set(_PATH_OPTIONS.keys())))
  914. return _PATH_OPTIONS[path_type]