|
7 | 7 |
|
8 | 8 | import torch |
9 | 9 |
|
10 | | -try: # Optional heuristic provider |
11 | | - import omeco # type: ignore |
12 | | -except Exception: # pragma: no cover - optional dependency |
13 | | - omeco = None |
| 10 | +import omeco |
14 | 11 |
|
15 | 12 | from .network import TensorNode |
16 | 13 | from .primitives import Backpointer, tropical_reduce_max |
@@ -45,59 +42,86 @@ class ContractionTree: |
45 | 42 | nodes: Tuple[TensorNode, ...] |
46 | 43 |
|
47 | 44 |
|
48 | | -def _build_var_graph(nodes: Iterable[TensorNode]) -> dict[int, set[int]]: |
49 | | - graph: dict[int, set[int]] = {} |
| 45 | +def _infer_var_sizes(nodes: Iterable[TensorNode]) -> dict[int, int]: |
| 46 | + sizes: dict[int, int] = {} |
50 | 47 | for node in nodes: |
51 | | - vars = list(node.vars) |
| 48 | + for var, dim in zip(node.vars, node.values.shape): |
| 49 | + if var in sizes and sizes[var] != dim: |
| 50 | + raise ValueError( |
| 51 | + f"Variable {var} has inconsistent sizes: {sizes[var]} vs {dim}." |
| 52 | + ) |
| 53 | + sizes[var] = int(dim) |
| 54 | + return sizes |
| 55 | + |
| 56 | + |
| 57 | +def _extract_leaf_index(node_dict: dict) -> int | None: |
| 58 | + for key in ("leaf", "leaf_index", "index", "tensor"): |
| 59 | + if key in node_dict: |
| 60 | + value = node_dict[key] |
| 61 | + if isinstance(value, int): |
| 62 | + return value |
| 63 | + return None |
| 64 | + |
| 65 | + |
| 66 | +def _elim_order_from_tree_dict(tree_dict: dict, ixs: list[list[int]]) -> list[int]: |
| 67 | + total_counts: dict[int, int] = {} |
| 68 | + for vars in ixs: |
52 | 69 | for var in vars: |
53 | | - graph.setdefault(var, set()).update(v for v in vars if v != var) |
54 | | - return graph |
55 | | - |
56 | | - |
57 | | -def _min_fill_order(graph: dict[int, set[int]]) -> list[int]: |
58 | | - order: list[int] = [] |
59 | | - graph = {k: set(v) for k, v in graph.items()} |
60 | | - while graph: |
61 | | - best_var = None |
62 | | - best_fill = None |
63 | | - best_degree = None |
64 | | - for var, neighbors in graph.items(): |
65 | | - fill = 0 |
66 | | - neighbor_list = list(neighbors) |
67 | | - for i in range(len(neighbor_list)): |
68 | | - for j in range(i + 1, len(neighbor_list)): |
69 | | - if neighbor_list[j] not in graph[neighbor_list[i]]: |
70 | | - fill += 1 |
71 | | - degree = len(neighbors) |
72 | | - if best_fill is None or (fill, degree) < (best_fill, best_degree): |
73 | | - best_var = var |
74 | | - best_fill = fill |
75 | | - best_degree = degree |
76 | | - if best_var is None: |
77 | | - break |
78 | | - neighbors = list(graph[best_var]) |
79 | | - for i in range(len(neighbors)): |
80 | | - for j in range(i + 1, len(neighbors)): |
81 | | - graph[neighbors[i]].add(neighbors[j]) |
82 | | - graph[neighbors[j]].add(neighbors[i]) |
83 | | - for neighbor in neighbors: |
84 | | - graph[neighbor].discard(best_var) |
85 | | - graph.pop(best_var, None) |
86 | | - order.append(best_var) |
87 | | - return order |
88 | | - |
89 | | - |
90 | | -def choose_order(nodes: list[TensorNode], heuristic: str = "min_fill") -> list[int]: |
91 | | - """Select elimination order over variable indices.""" |
92 | | - if heuristic == "omeco" and omeco is not None: |
93 | | - if hasattr(omeco, "min_fill_order"): |
94 | | - return list(omeco.min_fill_order([node.vars for node in nodes])) |
95 | | - graph = _build_var_graph(nodes) |
96 | | - if heuristic in ("min_fill", "omeco"): |
97 | | - return _min_fill_order(graph) |
98 | | - if heuristic == "min_degree": |
99 | | - return sorted(graph, key=lambda v: len(graph[v])) |
100 | | - raise ValueError(f"Unknown heuristic: {heuristic!r}") |
| 70 | + total_counts[var] = total_counts.get(var, 0) + 1 |
| 71 | + |
| 72 | + eliminated: set[int] = set() |
| 73 | + |
| 74 | + def visit(node: dict) -> tuple[dict[int, int], list[int]]: |
| 75 | + leaf_index = _extract_leaf_index(node) |
| 76 | + if leaf_index is not None: |
| 77 | + counts: dict[int, int] = {} |
| 78 | + for var in ixs[leaf_index]: |
| 79 | + counts[var] = counts.get(var, 0) + 1 |
| 80 | + return counts, [] |
| 81 | + |
| 82 | + children = node.get("children", []) |
| 83 | + if not isinstance(children, list) or not children: |
| 84 | + return {}, [] |
| 85 | + |
| 86 | + counts: dict[int, int] = {} |
| 87 | + order: list[int] = [] |
| 88 | + for child in children: |
| 89 | + child_counts, child_order = visit(child) |
| 90 | + order.extend(child_order) |
| 91 | + for var, count in child_counts.items(): |
| 92 | + counts[var] = counts.get(var, 0) + count |
| 93 | + |
| 94 | + newly_eliminated = [ |
| 95 | + var |
| 96 | + for var, count in counts.items() |
| 97 | + if count == total_counts.get(var, 0) and var not in eliminated |
| 98 | + ] |
| 99 | + for var in sorted(newly_eliminated): |
| 100 | + eliminated.add(var) |
| 101 | + order.append(var) |
| 102 | + return counts, order |
| 103 | + |
| 104 | + _, order = visit(tree_dict) |
| 105 | + remaining = sorted([var for var in total_counts if var not in eliminated]) |
| 106 | + return order + remaining |
| 107 | + |
| 108 | + |
| 109 | +def choose_order(nodes: list[TensorNode], heuristic: str = "omeco") -> list[int]: |
| 110 | + """Select elimination order over variable indices using omeco.""" |
| 111 | + if heuristic != "omeco": |
| 112 | + raise ValueError("Only the 'omeco' heuristic is supported.") |
| 113 | + ixs = [list(node.vars) for node in nodes] |
| 114 | + sizes = _infer_var_sizes(nodes) |
| 115 | + method = omeco.GreedyMethod() if hasattr(omeco, "GreedyMethod") else None |
| 116 | + tree = ( |
| 117 | + omeco.optimize_code(ixs, [], sizes, method) |
| 118 | + if method is not None |
| 119 | + else omeco.optimize_code(ixs, [], sizes) |
| 120 | + ) |
| 121 | + tree_dict = tree.to_dict() if hasattr(tree, "to_dict") else tree |
| 122 | + if not isinstance(tree_dict, dict): |
| 123 | + raise ValueError("omeco.optimize_code did not return a usable tree.") |
| 124 | + return _elim_order_from_tree_dict(tree_dict, ixs) |
101 | 125 |
|
102 | 126 |
|
103 | 127 | def build_contraction_tree(order: Iterable[int], nodes: list[TensorNode]) -> ContractionTree: |
|
0 commit comments