Skip to content

loop_ordering

AbstractLoopOrderer

Bases: LogicLoopOrderer

Source code in src/finch/autoschedule/loop_orderer/loop_ordering.py
class AbstractLoopOrderer(LogicLoopOrderer):
    def __init__(self, ctx: LogicLoader | None = None):
        if ctx is None:
            ctx = MockLogicLoader()
        self.ctx = ctx

    @abstractmethod
    def set_loop_orders(
        self,
        prgm: Plan,
        stats: dict[Alias, TensorStats],
        stats_factory: StatsFactory,
    ) -> Plan:
        """
        prgm, with the loop order of each query set, priced from the stats of
        the tensors it reads alone, whatever their formats, as galloping does,
        since the workspacer may copy its inputs into any format.
        """

    def lower(
        self,
        prgm: Plan,
        bindings: dict[Alias, TensorFType],
        stats: dict[Alias, TensorStats],
        stats_factory: StatsFactory,
    ):
        def loop_order_transform(prgm, bindings):
            prgm = drop_internal_reorders(prgm)
            assert isinstance(prgm, Plan)
            prgm = self.set_loop_orders(prgm, stats, stats_factory)
            prgm = push_relabels(prgm)
            assert isinstance(prgm, Plan)
            prgm = concordize(prgm, bindings)
            prgm = propagate_copy_queries(prgm, bindings)
            prgm = flatten_plans(prgm)
            return prgm, bindings

        stmt, bindings = with_unique_lhs(loop_order_transform, prgm, bindings)
        assert isinstance(stmt, Plan)
        # Copies include those which write renamed inputs back.
        stmt = with_copy_loop_orders(flatten_plans(stmt))
        return self.ctx(stmt, bindings, stats, stats_factory)

set_loop_orders(prgm, stats, stats_factory) abstractmethod

prgm, with the loop order of each query set, priced from the stats of the tensors it reads alone, whatever their formats, as galloping does, since the workspacer may copy its inputs into any format.

Source code in src/finch/autoschedule/loop_orderer/loop_ordering.py
@abstractmethod
def set_loop_orders(
    self,
    prgm: Plan,
    stats: dict[Alias, TensorStats],
    stats_factory: StatsFactory,
) -> Plan:
    """
    prgm, with the loop order of each query set, priced from the stats of
    the tensors it reads alone, whatever their formats, as galloping does,
    since the workspacer may copy its inputs into any format.
    """

concordize(root, bindings)

Read every Table of a query in the loop order of its enclosing Fuse nodes. A Table stored in another order reads a transposed copy of its tensor instead, which is made after each statement that writes the tensor. Copies may read their argument in any order.

Source code in src/finch/autoschedule/loop_orderer/loop_ordering.py
def concordize(
    root: LogicStatement, bindings: dict[Alias, TensorFType]
) -> LogicStatement:
    """
    Read every Table of a query in the loop order of its enclosing Fuse nodes.
    A Table stored in another order reads a transposed copy of its tensor
    instead, which is made after each statement that writes the tensor. Copies
    may read their argument in any order.
    """
    needed_swizzles: dict[Alias, dict[tuple[int, ...], Alias]] = {}
    namespace = Namespace(root)

    def swizzle(rhs: LogicExpression, loop_order: tuple[Field, ...]):
        def rule(ex):
            match ex:
                case Table(Alias(_) as var, idxs_1, protocols) if not is_subsequence(
                    intersect(idxs_1, loop_order), loop_order
                ):
                    idxs_subseq = with_subsequence(
                        intersect(loop_order, idxs_1), idxs_1
                    )
                    perm = tuple(idxs_1.index(idx) for idx in idxs_subseq)
                    return Table(
                        needed_swizzles.setdefault(var, {}).setdefault(
                            perm, HardAlias(namespace.freshen(var.name))
                        ),
                        idxs_subseq,
                        tuple(protocols[p] for p in perm) if protocols else (),
                    )

        return Rewrite(PostWalk(rule))(rhs)

    def concordant(stmt: LogicStatement, loop_order: tuple[Field, ...]):
        match stmt:
            case Plan(bodies):
                return Plan(tuple(concordant(body, loop_order) for body in bodies))
            case Fuse(idx, body):
                return Fuse(idx, concordant(body, (*loop_order, idx)))
            case Query(_, Table()):
                return stmt
            case Query(lhs, rhs):
                return Query(lhs, swizzle(rhs, loop_order))
            case QueryInto(lhs, op, rhs):
                return QueryInto(lhs, op, swizzle(rhs, loop_order))
        return stmt

    def _get_swizzle_queries(lhs: Alias) -> tuple[Query, ...]:
        ndims = len(next(iter(needed_swizzles[lhs].items()))[0])
        idxs = tuple([Field(f"i_{i}") for i in range(ndims)])
        return tuple(
            Query(Table(alias, tuple(idxs[p] for p in perm)), Table(lhs, idxs))
            for perm, alias in needed_swizzles[lhs].items()
        )

    assert isinstance(root, Plan)
    root = flatten_plans(root)
    match root:
        case Plan((*bodies, Produces() as prod)):
            bodies = [concordant(body, ()) for body in bodies]
            # Consider also aliases from input arguments.
            stmts: list[LogicStatement] = [
                query
                for alias in bindings
                if alias in needed_swizzles
                for query in _get_swizzle_queries(alias)
            ]
            for body in bodies:
                stmts.append(body)
                swizzled: set[Alias] = set()
                for node in PostOrderDFS(body):
                    match node:
                        case Query(Table(Alias() as lhs, _), _) | QueryInto(
                            Table(Alias() as lhs, _), _, _
                        ) if lhs in needed_swizzles and lhs not in swizzled:
                            swizzled.add(lhs)
                            stmts.extend(_get_swizzle_queries(lhs))
            return Plan((*stmts, prod))
        case _:
            raise Exception(f"Invalid root: {root}")

drop_internal_reorders(root)

Remove the Reorders within the right-hand side of each aggregate query and in-place update, whose fields are ordered by their left-hand tables.

Source code in src/finch/autoschedule/loop_orderer/loop_ordering.py
def drop_internal_reorders(root: LogicStatement) -> LogicStatement:
    """
    Remove the Reorders within the right-hand side of each aggregate query and
    in-place update, whose fields are ordered by their left-hand tables.
    """

    def reorder_remover(ex):
        match ex:
            case Reorder(arg_2, _):
                return arg_2

    def rule(stmt):
        match stmt:
            case Query(lhs, Aggregate(op, init, arg, idxs_2)):
                arg_1 = Rewrite(PostWalk(reorder_remover))(arg)
                return Query(lhs, Aggregate(op, init, arg_1, idxs_2))
            case QueryInto(lhs, op, arg):
                arg_1 = Rewrite(PostWalk(reorder_remover))(arg)
                return QueryInto(lhs, op, arg_1)

    return Rewrite(PostWalk(rule))(root)

galloping(expr)

expr, with every table galloping over each field it stores. The workspacer may copy an input into any format, so the loops are priced from the stats of the tables alone, as if every table galloped: a loop visits where every table it merges has entries, and looks each up there.

Source code in src/finch/autoschedule/loop_orderer/loop_ordering.py
def galloping(expr: LogicExpression) -> LogicExpression:
    """
    expr, with every table galloping over each field it stores. The workspacer
    may copy an input into any format, so the loops are priced from the stats
    of the tables alone, as if every table galloped: a loop visits where every
    table it merges has entries, and looks each up there.
    """

    def read(node):
        match node:
            case Table(Alias() as tns, idxs):
                stored = len(idxs) - tns.nfused
                protocols = (DefaultProtocol(),) * tns.nfused + (Gallop(),) * stored
                return Table(tns, idxs, protocols)
        return None

    return Rewrite(PostWalk(read))(expr)

with_copy_loop_orders(root)

Set the loop order of each copy, which visits the fields of its argument in the order it stores them, and then the fields only its left-hand table has. A transposing copy reads its argument in order and scatters into its left-hand table, rather than reading a sparse argument out of order.

Source code in src/finch/autoschedule/loop_orderer/loop_ordering.py
def with_copy_loop_orders(root: Plan) -> Plan:
    """
    Set the loop order of each copy, which visits the fields of its argument in
    the order it stores them, and then the fields only its left-hand table has.
    A transposing copy reads its argument in order and scatters into its
    left-hand table, rather than reading a sparse argument out of order.
    """

    def loop_ordered(stmt: LogicStatement) -> LogicStatement:
        match stmt:
            case Query(Table(_, lhs_idxs), Table(_, idxs)):
                return fuse_loop_order(stmt, (*idxs, *setdiff(lhs_idxs, idxs)))
        return stmt

    return Plan(tuple(loop_ordered(body) for body in root.bodies))

with_loop_order(stmt, loop_order)

Set the loop order of an aggregate query or in-place update by wrapping it in a Fuse node for each field of the loop order, followed by the fields which only the table it writes has, such as output-only unit dimensions. The loop order may visit the fields of that table out of the order it stores them in, in which case the query scatters into the table.

Source code in src/finch/autoschedule/loop_orderer/loop_ordering.py
def with_loop_order(
    stmt: LogicStatement, loop_order: tuple[Field, ...]
) -> LogicStatement:
    """
    Set the loop order of an aggregate query or in-place update by wrapping it
    in a Fuse node for each field of the loop order, followed by the fields
    which only the table it writes has, such as output-only unit dimensions.
    The loop order may visit the fields of that table out of the order it
    stores them in, in which case the query scatters into the table.
    """
    match stmt:
        case Query(Table(_, lhs_idxs), Aggregate()) | QueryInto(
            Table(_, lhs_idxs), _, _
        ):
            loop_order = (*loop_order, *setdiff(lhs_idxs, loop_order))
            return fuse_loop_order(stmt, loop_order)
        case _:
            raise ValueError(f"Expected an aggregate or in-place query, got {stmt}")