Skip to content

Index

GalleyLogicFactorizer

Bases: LogicFactorizer

LogicLoader stage that runs Galley on each Query body (see optimizer), then forwards the Plan to the downstream loader ctx.

Default optimizer="bfs" is exact layered branch-and-bound; "dfs" uses the DFS kernel. Greedy k=1 bounds are used only on the layered exact path, not inside branch_and_bound_dfs. cost_model estimates the cost of each reduction, and defaults to FLOPS_COST_MODEL.

Source code in src/finch/autoschedule/factorizer/galley_factorizer/galley_optimize.py
class GalleyLogicFactorizer(LogicFactorizer):
    """
    LogicLoader stage that runs Galley on each ``Query`` body (see ``optimizer``),
    then forwards the Plan to the downstream loader ``ctx``.

    Default ``optimizer="bfs"`` is exact layered branch-and-bound; ``"dfs"`` uses the
    DFS kernel. Greedy ``k=1`` bounds are used only on the layered exact path, not
    inside ``branch_and_bound_dfs``. ``cost_model`` estimates the cost of each
    reduction, and defaults to ``FLOPS_COST_MODEL``.
    """

    def __init__(
        self,
        ctx: LogicLoader,
        use_components: bool = True,
        *,
        optimizer: GalleyOptimizer = "bfs",
        cost_model: CostModel | None = None,
    ):
        self.ctx = ctx
        self.use_components = use_components
        self.optimizer = optimizer
        self.cost_model = cost_model

    def lower(
        self,
        term: LogicStatement,
        bindings: dict[Alias, TensorFType],
        stats: dict[Alias, TensorStats],
        stats_factory: StatsFactory,
    ):
        if not isinstance(term, Plan):
            raise ValueError(f"Unsupported program type: {type(term)}")
        logger.debug("Optimizing plan: %s", term)

        def transform(prgm, bindings):
            prgm = optimize_plan(
                prgm,
                stats_factory,
                stats,
                use_components=self.use_components,
                optimizer=self.optimizer,
                cost_model=self.cost_model,
            )
            return prgm, bindings

        # Galley only keeps the queries that compute produced aliases, so each
        # write to a bound tensor, including an in-place update, is renamed and
        # produced, then copied back to the tensor it updates. Galley only
        # reduces from literals, so aggregates which start from a tensor are
        # split first.
        term = split_aggregate_inits(desugar_query_into(term), bindings)
        term, bindings = with_unique_lhs(transform, term, bindings)
        assert isinstance(term, Plan)
        return self.ctx(flatten_plans(term), bindings, stats, stats_factory)

with_unique_lhs(f, root, bindings)

Ensures all left-hand sides (LHS) of queries are unique by inserting new tensors.

Source code in src/finch/autoschedule/factorizer/optimize.py
def with_unique_lhs(
    f, root: LogicStatement, bindings: dict[Alias, TensorFType]
) -> tuple[LogicStatement, dict[Alias, TensorFType]]:
    """
    Ensures all left-hand sides (LHS) of queries are unique by inserting new
    tensors.
    """

    spc = Namespace(root)
    for var in bindings:
        spc.freshen(var.name)
    renames: dict[Alias, Alias] = {}
    bound = set(bindings.keys())
    writes: dict[Alias, Alias] = {}

    def rule_0(node):
        match node:
            case Query(Table(Alias() as lhs, idxs), rhs):
                if lhs in bound:
                    var = HardAlias(spc.freshen(lhs.name))
                    renames[lhs] = var
                    if lhs in bindings:
                        writes[lhs] = var
                    return Query(Table(var, idxs), rhs)
                bound.add(lhs)
                return None
            case Alias() as a if a in renames:
                return renames[a]
            case Produces(args):
                return Produces(args + tuple(writes.values()))

    root = Rewrite(PostWalk(rule_0))(root)
    root, bindings = f(root, bindings)

    unrenames = {v: k for k, v in renames.items()}

    # Some produces may be renamed during the optimization,
    # so we need to be a bit careful here.
    def rule_1(node):
        match node:
            case Produces(args):
                n_writes = len(writes)
                v_post_list = args[-n_writes:] if n_writes else ()

                bodies: list[LogicStatement] = []
                for (k, _v_pre), v_post in zip(
                    writes.items(), v_post_list, strict=True
                ):
                    idxs = tuple(
                        Field(spc.freshen("i")) for _ in range(bindings[k].ndim)
                    )
                    bodies.append(Query(Table(k, idxs), Table(v_post, idxs)))

                v_post_to_k = dict(zip(v_post_list, writes.keys(), strict=True))
                args_2 = tuple(
                    v_post_to_k.get(a, unrenames.get(a, a))
                    for a in args[: len(args) - n_writes]
                )
                return Plan(tuple(bodies) + (Produces(args_2),))

    return (Rewrite(PostWalk(rule_1))(root), bindings)