@@ -47,6 +47,7 @@ def insert_temporal_loops(
4747 let_non_intermediate_tensors_respawn_in_backing_storage : bool ,
4848 explore_loop_orders : bool ,
4949):
50+ arch_node_names = [n .name for n in flattened_arch ]
5051 # First establish insertion points. Insertion points are:
5152 # - Below the last instance of the first memory
5253 # - Between any two TensorHolder nodes
@@ -84,6 +85,11 @@ def insert_temporal_loops(
8485 continue
8586 split_mapping .append ([m ])
8687
88+ for s in split_mapping :
89+ # Within each split mapping group, sort by arch levels.
90+ # This can help create places to put spatial loops
91+ s .sort (key = lambda tensor_holder : arch_node_names .index (tensor_holder .component ))
92+
8793 if sum (map (len , split_mapping )) != len (mapping ):
8894 raise RuntimeError ("BUG: number of storage nodes post-split != original" )
8995
@@ -160,12 +166,13 @@ def _get_next_storages(i: int, toll_allowed: bool = False) -> list[TensorHolder]
160166 cur_fanout .add (1 )
161167 if len (next_fanout ) == 0 : # Happens if we're inserting below all storage nodes
162168 next_fanout .add (float ("inf" ))
163- # Either it's main memory or we have one entry in the list, so there should only
164- # be one
165- assert len (cur_fanout ) == 1
166- assert len (next_fanout ) == 1
167- cur_fanout = next (iter (cur_fanout ))
168- next_fanout = next (iter (next_fanout ))
169+
170+ # These are used to check if fanouts increased and therefore spatial loops
171+ # may be placed, so we use the maximum.
172+ assert len (cur_fanout ) > 0
173+ assert len (next_fanout ) > 0
174+ cur_fanout = max (cur_fanout )
175+ next_fanout = max (next_fanout )
169176
170177 # Can't have loops above persistent tensor holders
171178 if next_persistent :
0 commit comments