Skip to content

Index

Affine

Bases: RowMap[C]

The features of each row of a basis followed by a 1, so a linear model of them adds a constant to the cost of each row.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class Affine(RowMap[C]):
    """
    The features of each row of a basis followed by a 1, so a linear model of
    them adds a constant to the cost of each row.
    """

    @property
    def n_features(self) -> int:
        return self.basis.n_features + 1

    @property
    def feature_names(self) -> tuple[str, ...]:
        return (*self.basis.feature_names, "constant")

    @property
    def ridge(self) -> np.ndarray:
        return np.append(self.basis.ridge, 1.0)

    def transform(self, rows: np.ndarray) -> np.ndarray:
        return np.hstack([rows, np.ones((len(rows), 1))])

Basis

Bases: Form, Generic[C]

A basis describes a logic statement by the features of its components, such as queries, loop prefixes, or tensor levels. components yields the components of a program, advancing the StatsMachine past each statement after yielding its components, and get_component_features gives a component one row of n_features for each independently priced part of it. Like a Stage, a Basis inherits the form of statements it accepts. ridge weights the penalty on the square of each coefficient of a linear model of the basis, and feature_names names each feature, by default by its index.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class Basis(Form, Generic[C]):
    """
    A basis describes a logic statement by the features of its components,
    such as queries, loop prefixes, or tensor levels. components yields the
    components of a program, advancing the StatsMachine past each statement
    after yielding its components, and get_component_features gives a
    component one row of n_features for each independently priced part of
    it. Like a Stage, a Basis inherits the form of statements it accepts.
    ridge weights the penalty on the square of each coefficient of a linear
    model of the basis, and feature_names names each feature, by default by
    its index.
    """

    @property
    @abstractmethod
    def n_features(self) -> int: ...

    @property
    def feature_names(self) -> tuple[str, ...]:
        return tuple(str(i) for i in range(self.n_features))

    @property
    def ridge(self) -> np.ndarray:
        return np.ones(self.n_features)

    @abstractmethod
    def components(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, Any],
        machine: StatsMachine[NS],
    ) -> Iterator[C]: ...

    @abstractmethod
    def get_component_features(
        self,
        component: C,
        machine: StatsMachine[NS],
    ) -> np.ndarray: ...

    def get_features(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, Any],
        stats: Mapping[Alias, TensorStats],
        stats_factory: StatsFactory,
    ) -> np.ndarray:
        machine = StatsMachine(stats_factory, dict(stats))
        features = [
            self.get_component_features(component, machine)
            for component in self.components(term, bindings, machine)
        ]
        return np.concatenate([np.empty((0, self.n_features)), *features])

ByKind

Bases: Concat[C], Generic[C, K]

The features of each component under the basis of its kind, which key returns, by default the kind attribute of the component. The features of a component fill the columns of its basis, and the other columns are zero, so a linear model has separate coefficients for each kind.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class ByKind(Concat[C], Generic[C, K]):
    """
    The features of each component under the basis of its kind, which key
    returns, by default the kind attribute of the component. The features of a
    component fill the columns of its basis, and the other columns are zero,
    so a linear model has separate coefficients for each kind.
    """

    def __init__(
        self,
        bases: Mapping[K, Basis[C]],
        key: Callable[[C], K] = by_kind,
    ):
        super().__init__(*bases.values())
        self.by_kind = dict(bases)
        self.key = key

    @property
    def feature_names(self) -> tuple[str, ...]:
        return tuple(
            f"{kind}.{name}"
            for kind, basis in self.by_kind.items()
            for name in basis.feature_names
        )

    def get_component_features(
        self,
        component: C,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        kind = self.key(component)
        start = 0
        for other, basis in self.by_kind.items():
            if other == kind:
                rows = basis.get_component_features(component, machine)
                features = np.zeros((len(rows), self.n_features))
                features[:, start : start + basis.n_features] = rows
                return features
            start += basis.n_features
        raise KeyError(kind)

Concat

Bases: Basis[C]

The features of several bases of the same kind of component, side by side.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class Concat(Basis[C]):
    """The features of several bases of the same kind of component, side by side."""

    def __init__(self, *bases: Basis[C]):
        if not bases:
            raise ValueError(f"{type(self).__name__} requires at least one basis")
        self.bases = bases

    @property
    def n_features(self) -> int:
        return sum(basis.n_features for basis in self.bases)

    @property
    def feature_names(self) -> tuple[str, ...]:
        return tuple(name for basis in self.bases for name in basis.feature_names)

    @property
    def ridge(self) -> np.ndarray:
        return np.concatenate([basis.ridge for basis in self.bases])

    def validate_inputs(self, *inputs):
        for basis in self.bases:
            basis.validate_inputs(*inputs)

    def components(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, Any],
        machine: StatsMachine[NS],
    ) -> Iterator[C]:
        return self.bases[0].components(term, bindings, machine)

    def get_component_features(
        self,
        component: C,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        return np.concatenate(
            [basis.get_component_features(component, machine) for basis in self.bases],
            axis=1,
        )

CostModel

Bases: Form, Generic[C]

A linear cost model weights the features its basis gives the components of a logic statement by its coefficients, and sums over their rows, so the cost of a program is the sum of the costs of its components, which predict_component_cost prices one at a time. Runtimes are measured for whole programs, so fit takes the features of each program, as get_features returns them, with its runtime, and finds the nonnegative coefficients which minimize the sum of the squared relative errors of the predicted runtimes, so that fast programs count as much as slow ones, and the cost of a row of nonnegative features is nonnegative, penalized by alpha times the ridge weights of the basis. The runtimes must be positive, and a fit to no programs is zero. to_json writes the coefficients with the names of their features, which from_json checks against the basis of the model it reads them into.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class CostModel(Form, Generic[C]):
    """
    A linear cost model weights the features its basis gives the components
    of a logic statement by its coefficients, and sums over their rows, so
    the cost of a program is the sum of the costs of its components, which
    predict_component_cost prices one at a time. Runtimes are measured for
    whole programs, so fit takes the features of each program, as
    get_features returns them, with its runtime, and finds the nonnegative
    coefficients which minimize the sum of the squared relative errors of the
    predicted runtimes, so that fast programs count as much as slow ones, and
    the cost of a row of nonnegative features is nonnegative, penalized by
    alpha times the ridge weights of the basis. The runtimes must be
    positive, and a fit to no programs is zero. to_json writes the
    coefficients with the names of their features, which from_json checks
    against the basis of the model it reads them into.
    """

    def __init__(self, basis: Basis[C], coefficients: ArrayLike):
        self.basis = basis
        self.coefficients = np.asarray(coefficients, dtype=float)
        if self.coefficients.shape != (basis.n_features,):
            raise ValueError(
                f"Expected {basis.n_features} coefficients, "
                f"got shape {self.coefficients.shape}"
            )

    def validate_inputs(self, *inputs):
        self.basis.validate_inputs(*inputs)

    def predict(self, features: np.ndarray) -> float:
        return float(features.sum(axis=0) @ self.coefficients)

    def predict_component_cost(
        self,
        component: C,
        machine: StatsMachine[NS],
    ) -> float:
        return self.predict(self.basis.get_component_features(component, machine))

    def get_features(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, Any],
        stats: Mapping[Alias, TensorStats],
        stats_factory: StatsFactory,
    ) -> np.ndarray:
        return self.basis.get_features(term, bindings, stats, stats_factory)

    def predict_cost(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, Any],
        stats: Mapping[Alias, TensorStats],
        stats_factory: StatsFactory,
    ) -> float:
        return self.predict(self.get_features(term, bindings, stats, stats_factory))

    def to_json(self) -> dict[str, Any]:
        return {
            "feature_names": list(self.basis.feature_names),
            "coefficients": self.coefficients.tolist(),
        }

    def from_json(self, data: Mapping[str, Any]) -> "CostModel[C]":
        names = list(self.basis.feature_names)
        if data["feature_names"] != names:
            raise ValueError(
                f"Expected the coefficients of {names}, got {data['feature_names']}"
            )
        return type(self)(self.basis, data["coefficients"])

    def fit(
        self,
        features: Sequence[np.ndarray],
        runtimes: ArrayLike,
        alpha: float = 0.0,
    ) -> "CostModel[C]":
        n = self.basis.n_features
        runtimes = np.asarray(runtimes, dtype=float)
        if np.any(runtimes <= 0):
            raise ValueError(f"Expected positive runtimes, got {runtimes.min()}")
        # Dividing the features of each program by its runtime makes the
        # residuals relative errors, which least squares fits to a target of
        # ones. The ridge penalty is least squares against extra rows of zeros.
        sums = np.array([rows.sum(axis=0) for rows in features]).reshape(-1, n)
        design = np.concatenate(
            [sums / runtimes[:, None], np.diag(np.sqrt(alpha * self.basis.ridge))]
        )
        target = np.concatenate([np.ones(len(runtimes)), np.zeros(n)])
        coefficients, _ = nnls(design, target)
        return type(self)(self.basis, coefficients)

DenseLevelOption

Bases: LevelOption

Storage features are positions and slots.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class DenseLevelOption(LevelOption):
    """Storage features are positions and slots."""

    kind = "dense"
    feature_names = ("positions", "slots")
    # A dense level is only looked up, so that it never decides where a loop
    # goes.
    protocols = (Follow(), Extrude(), Laminate())
    default_protocol = Follow()
    filters = False

    def next_num_pos(self, stats, stats_factory, depth, num_pos, over):
        return num_pos * stats.get_dim_size(stats.index_order[depth])

    def get_storage_features(
        self, stats, stats_factory, depth, num_pos, idx_size, pos_size, val_size, over
    ):
        return np.array(
            [num_pos, self.next_num_pos(stats, stats_factory, depth, num_pos, over)]
        )

ElementLevelOption

Bases: LevelOption

The element level at the rank of a tensor stores one value for each position. Storage features are values and value bytes.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class ElementLevelOption(LevelOption):
    """
    The element level at the rank of a tensor stores one value for each
    position. Storage features are values and value bytes.
    """

    kind = "element"
    feature_names = ("values", "value_bytes")
    # A value is looked up at the position of its parent, and written with it.
    protocols = (Follow(), Extrude(), Laminate())
    default_protocol = Follow()
    # An element has no field, and a value at every position.
    filters = False

    def next_num_pos(self, stats, stats_factory, depth, num_pos, over):
        # The element level has no child, so its positions pass through.
        return num_pos

    def get_storage_features(
        self, stats, stats_factory, depth, num_pos, idx_size, pos_size, val_size, over
    ):
        return np.array([num_pos, num_pos * val_size])

FactorizeBasis

Bases: Basis[Statement]

A basis where each query statement is a component, in program order. get_component_features returns one row for each statement.

Source code in src/finch/autoschedule/cost_models/factorize_cost_models.py
class FactorizeBasis(Basis[Statement]):
    """
    A basis where each query statement is a component, in program order.
    get_component_features returns one row for each statement.
    """

    def components(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, TensorFType],
        machine: StatsMachine[NS],
    ) -> Iterator[Statement]:
        match term:
            case Plan(bodies):
                for body in bodies:
                    yield from self.components(body, bindings, machine)
            case Fuse(_, body):
                yield from self.components(body, bindings, machine)
            case Query() | QueryInto():
                yield Statement(term)
                machine(term)
            case Produces():
                return
            case _:
                raise ValueError(f"Unsupported statement type: {term}")

FlopsBasis

Bases: FactorizeBasis, AliasedForm

FlopsBasis counts the non-fill values in the iteration space of each query, and in the output it materializes. Each query is a component.

Source code in src/finch/autoschedule/cost_models/factorize_cost_models.py
class FlopsBasis(FactorizeBasis, AliasedForm):
    """
    FlopsBasis counts the non-fill values in the iteration space of each
    query, and in the output it materializes. Each query is a component.
    """

    @property
    def n_features(self) -> int:
        return 2

    @property
    def feature_names(self) -> tuple[str, ...]:
        return ("iterations", "outputs")

    def get_component_features(
        self,
        component: Statement,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        stats_factory = machine.stats_factory

        def visit_expr(expr: LogicExpression) -> tuple[NS, NS]:
            """Return the stats of the output of expr, and of its iteration space."""
            match expr:
                case Aggregate(Literal(op), Literal(init), arg, idxs):
                    iter_stats, _ = visit_expr(arg)
                    out_stats = stats_factory.aggregate(op, init, idxs, iter_stats)
                    return out_stats, iter_stats
                case Aggregate(Literal(op), init, arg, idxs):
                    # A tensor init is folded into the reduction.
                    iter_stats, _ = visit_expr(arg)
                    init_stats, _ = visit_expr(init)
                    out_stats = stats_factory.aggregate(op, None, idxs, iter_stats)
                    out_stats = stats_factory.mapjoin(op, init_stats, out_stats)
                    return out_stats, iter_stats
                case MapJoin(Literal(op), (arg,)):
                    return visit_expr(arg)
                case MapJoin(Literal(op), args):
                    out_stats = stats_factory.mapjoin(
                        op, *(visit_expr(arg)[0] for arg in args)
                    )
                    return out_stats, out_stats
                case Reorder(arg, idxs):
                    out_stats, iter_stats = visit_expr(arg)
                    return stats_factory.reorder(out_stats, idxs), iter_stats
                case Relabel(arg, idxs):
                    out_stats, iter_stats = visit_expr(arg)
                    return stats_factory.relabel(out_stats, idxs), iter_stats
                case Table() | Literal():
                    out_stats = machine(expr)
                    return out_stats, out_stats
                case _:
                    raise ValueError(f"Unsupported expression type: {expr}")

        match component.stmt:
            case Query(Table(Alias()), rhs):
                out_stats, iter_stats = visit_expr(rhs)
                return np.array(
                    [
                        [
                            iter_stats.estimate_non_fill_values(),
                            out_stats.estimate_non_fill_values(),
                        ]
                    ],
                    dtype=float,
                )
            case QueryInto() as stmt:
                return self.get_component_features(Statement(stmt.as_query()), machine)
            case stmt:
                raise ValueError(f"Unsupported statement type: {stmt}")

LevelOption

Bases: ABC

A kind of level, which gives the storage features feature_names names, and the positions it passes to its child, from the stats of the tensor, the zero-based depth of the level, and the num_pos positions entering it. A tensor which stores one slice that fixes the fields of over is described by its largest slice. A level which filters has a fiber only where it has an entry, so a lookup which finds none runs nothing within it.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class LevelOption(ABC):
    """
    A kind of level, which gives the storage features feature_names names, and
    the positions it passes to its child, from the stats of the tensor, the
    zero-based depth of the level, and the num_pos positions entering it. A
    tensor which stores one slice that fixes the fields of over is described by
    its largest slice. A level which filters has a fiber only where it has an
    entry, so a lookup which finds none runs nothing within it.
    """

    kind: ClassVar[str]
    feature_names: ClassVar[tuple[str, ...]]
    protocols: ClassVar[tuple[Protocol, ...]]
    default_protocol: ClassVar[Protocol]
    filters: ClassVar[bool]

    @abstractmethod
    def next_num_pos(
        self, stats: NS, stats_factory: StatsFactory[NS], depth: int, num_pos, over
    ): ...

    @abstractmethod
    def get_storage_features(
        self,
        stats: NS,
        stats_factory: StatsFactory[NS],
        depth: int,
        num_pos,
        idx_size: int,
        pos_size: int,
        val_size: int,
        over: tuple[Field, ...],
    ) -> np.ndarray: ...

LoopBasis

Bases: Basis[Prefix]

A basis where each loop prefix, including the empty prefix, is a component, as prefixes yields them, and get_component_features returns one row for each prefix. Models used with branch-and-bound loop search must predict nonnegative component costs.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
class LoopBasis(Basis[Prefix]):
    """
    A basis where each loop prefix, including the empty prefix, is a component,
    as prefixes yields them, and get_component_features returns one row for
    each prefix. Models used with branch-and-bound loop search must predict
    nonnegative component costs.
    """

    def components(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, Any],
        machine: StatsMachine[NS],
    ) -> Iterator[Prefix]:
        return prefixes(term, machine, formats=bindings)

LoopDepthBasis

Bases: FactorizeBasis, AliasedForm

LoopDepthBasis counts the fields each query loops over, so that a greedy search reduces the indices which keep the deepest loop nest shallow. It needs only the shapes of its statistics. Each query is a component.

Source code in src/finch/autoschedule/cost_models/factorize_cost_models.py
class LoopDepthBasis(FactorizeBasis, AliasedForm):
    """
    LoopDepthBasis counts the fields each query loops over, so that a greedy
    search reduces the indices which keep the deepest loop nest shallow. It
    needs only the shapes of its statistics. Each query is a component.
    """

    @property
    def n_features(self) -> int:
        return 1

    @property
    def feature_names(self) -> tuple[str, ...]:
        return ("loop_depth",)

    def get_component_features(
        self,
        component: Statement,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        match component.stmt:
            case Query(Table(Alias()), Aggregate(_, init, arg, _)):
                return np.array([[len({*arg.fields(), *init.fields()})]], dtype=float)
            case Query(Table(Alias()), rhs):
                return np.array([[len(rhs.fields())]], dtype=float)
            case QueryInto() as stmt:
                return self.get_component_features(Statement(stmt.as_query()), machine)
            case stmt:
                raise ValueError(f"Unsupported statement type: {stmt}")

LoopSpaces

Bases: Generic[NS]

The spaces of the last loop of a nonempty loop prefix: where it is entered, what it visits, and where its walks step, from the stats of the tables it merges, restricted as their formats and protocols allow, as unrestricted says. A table whose formats the prefix doesn't list is taken to be sparse, and a table without protocols walks the field of the loop.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
class LoopSpaces(Generic[NS]):
    """
    The spaces of the last loop of a nonempty loop prefix: where it is
    entered, what it visits, and where its walks step, from the stats of the
    tables it merges, restricted as their formats and protocols allow, as
    unrestricted says. A table whose formats the prefix doesn't list is taken
    to be sparse, and a table without protocols walks the field of the loop.
    """

    def __init__(self, component: Prefix, machine: StatsMachine[NS]):
        self.machine = machine
        self.stats_factory = machine.stats_factory
        self.parent = set(component.prefix[:-1])
        self.idx = component.prefix[-1]
        match component.expr:
            case Aggregate(arg=arg):
                self.arg = arg
            case expr:
                self.arg = expr
        # The extent of each field, from the tables which read it, and the
        # field of each level of each and whether it doesn't filter, outermost
        # first, where the formats list level options.
        self.dims: dict[Field, float] = {}
        self.levels: dict[Table, list[tuple[Field, bool]]] = {}
        formats = component.formats or {}
        for node in PostOrderDFS(self.arg):
            match node:
                case Table(Alias() as tns, idxs) if idxs:
                    self.dims.update(self.machine(node).dim_sizes)
                    match formats.get(tns.unfused):
                        case [*options]:
                            self.levels[node] = [
                                (idxs[tns.nfused + depth], not option.filters)
                                for depth, option in enumerate(options)
                                if tns.nfused + depth < len(idxs)
                            ]
        # The loop is entered wherever the formats let the enclosing loops go,
        # and its merge steps only where every fiber it merges has positions
        # at idx.
        self.exec_space = self.stats_factory.support(self.merged(self.arg))
        self.merge_space = self.project(self.merged(self.arg, (self.idx,)))

    def project(self, stat: NS, fields=(), followed=()) -> NS:
        """
        The support of stat over parent and fields, less the fields of
        followed, which it spans wholly.
        """
        return restrict(self.stats_factory, stat, {*self.parent, *fields} - {*followed})

    def protocol(self, node: Term) -> Protocol:
        """The protocol node reads the field of the loop with."""
        match node:
            case Table(_, idxs, (_, *_) as protocols) if self.idx in idxs:
                return protocols[idxs.index(self.idx)]
        return DefaultProtocol()

    def unrestricted(self, table: Table, fields) -> set[Field]:
        """
        The fields of fields which table doesn't restrict: the field of the
        loop where table follows it, since it is looked up wherever the others
        go, and those of the dense levels down to the deepest level of the
        rest, from the sparse level above them, which have a fiber at every
        slot of it, so the positions of the level are the entries of the
        sparse one, at every slot of the dense ones.
        """
        unrestricted = set()
        if self.idx in fields and self.protocol(table) == Follow():
            unrestricted.add(self.idx)
        run: set[Field] = set()
        trailing: set[Field] = set()
        for idx, dense in self.levels.get(table, ()):
            run = run | {idx} if dense else set()
            if idx in fields and idx not in unrestricted:
                trailing = run
        return unrestricted | trailing

    def merged(self, node: LogicExpression, fields=()) -> NS:
        """
        Where a merge of the inputs of node visits parent and fields: where
        every fiber it merges has positions, as the formats give them.
        """
        # A merge coiterates the projections of the inputs, so it visits more
        # of parent than the projection of their result.
        followed: set[Field] = set()
        match node:
            case MapJoin(Literal(op), args):
                return self.stats_factory.mapjoin(
                    op, *(self.merged(arg, fields) for arg in args)
                )
            case Table():
                followed = self.unrestricted(node, {*self.parent, *fields})
        stat = self.machine(node)
        projected = self.project(stat, fields, followed)
        # The fill decides whether a mapjoin joins or unions it.
        projected.fill_type = stat.fill_type
        return projected

    def extent(self, stat: NS, fields) -> float:
        """The points of stat over fields, spanning all of those it lacks."""
        count = stat.estimate_non_fill_values()
        for idx in fields:
            if idx not in stat.index_order:
                count *= self.dims.get(idx, 1.0)
        return count

    def count(self, stat: NS) -> float:
        return self.extent(stat, (*self.parent, self.idx))

    def executions(self) -> float:
        return self.extent(self.exec_space, self.parent)

    def iterations(self) -> float:
        return self.count(self.visited())

    def visited(self) -> NS:
        """Where the loop visits idx, which its walks and gallops restrict."""
        return self.stats_factory.mapjoin(
            ffuncs.and_,
            self.exec_space,
            self.stats_factory.support(self.merged(self.arg, (self.idx,))),
        )

    def located(self, stat: NS, fields) -> float:
        """
        The distinct points of stat at fields: the positions of a level of
        those fields which the loop reaches in stat, however often it runs.
        """
        if any(idx not in fields for idx in stat.index_order):
            stat = restrict(self.stats_factory, stat, fields)
        return self.extent(stat, fields)

    def stepped(self, table: Table) -> NS:
        """
        The entries of table at idx which a walk of it steps through: those
        where the merge steps, since it steps through nothing where another
        fiber it merges has no positions.
        """
        return self.stats_factory.mapjoin(
            ffuncs.and_,
            self.merge_space,
            self.project(self.machine(table), (self.idx,)),
        )

    def walk(self, table: Table) -> float:
        return self.count(self.stepped(table))

extent(stat, fields)

The points of stat over fields, spanning all of those it lacks.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def extent(self, stat: NS, fields) -> float:
    """The points of stat over fields, spanning all of those it lacks."""
    count = stat.estimate_non_fill_values()
    for idx in fields:
        if idx not in stat.index_order:
            count *= self.dims.get(idx, 1.0)
    return count

located(stat, fields)

The distinct points of stat at fields: the positions of a level of those fields which the loop reaches in stat, however often it runs.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def located(self, stat: NS, fields) -> float:
    """
    The distinct points of stat at fields: the positions of a level of
    those fields which the loop reaches in stat, however often it runs.
    """
    if any(idx not in fields for idx in stat.index_order):
        stat = restrict(self.stats_factory, stat, fields)
    return self.extent(stat, fields)

merged(node, fields=())

Where a merge of the inputs of node visits parent and fields: where every fiber it merges has positions, as the formats give them.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def merged(self, node: LogicExpression, fields=()) -> NS:
    """
    Where a merge of the inputs of node visits parent and fields: where
    every fiber it merges has positions, as the formats give them.
    """
    # A merge coiterates the projections of the inputs, so it visits more
    # of parent than the projection of their result.
    followed: set[Field] = set()
    match node:
        case MapJoin(Literal(op), args):
            return self.stats_factory.mapjoin(
                op, *(self.merged(arg, fields) for arg in args)
            )
        case Table():
            followed = self.unrestricted(node, {*self.parent, *fields})
    stat = self.machine(node)
    projected = self.project(stat, fields, followed)
    # The fill decides whether a mapjoin joins or unions it.
    projected.fill_type = stat.fill_type
    return projected

project(stat, fields=(), followed=())

The support of stat over parent and fields, less the fields of followed, which it spans wholly.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def project(self, stat: NS, fields=(), followed=()) -> NS:
    """
    The support of stat over parent and fields, less the fields of
    followed, which it spans wholly.
    """
    return restrict(self.stats_factory, stat, {*self.parent, *fields} - {*followed})

protocol(node)

The protocol node reads the field of the loop with.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def protocol(self, node: Term) -> Protocol:
    """The protocol node reads the field of the loop with."""
    match node:
        case Table(_, idxs, (_, *_) as protocols) if self.idx in idxs:
            return protocols[idxs.index(self.idx)]
    return DefaultProtocol()

stepped(table)

The entries of table at idx which a walk of it steps through: those where the merge steps, since it steps through nothing where another fiber it merges has no positions.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def stepped(self, table: Table) -> NS:
    """
    The entries of table at idx which a walk of it steps through: those
    where the merge steps, since it steps through nothing where another
    fiber it merges has no positions.
    """
    return self.stats_factory.mapjoin(
        ffuncs.and_,
        self.merge_space,
        self.project(self.machine(table), (self.idx,)),
    )

unrestricted(table, fields)

The fields of fields which table doesn't restrict: the field of the loop where table follows it, since it is looked up wherever the others go, and those of the dense levels down to the deepest level of the rest, from the sparse level above them, which have a fiber at every slot of it, so the positions of the level are the entries of the sparse one, at every slot of the dense ones.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def unrestricted(self, table: Table, fields) -> set[Field]:
    """
    The fields of fields which table doesn't restrict: the field of the
    loop where table follows it, since it is looked up wherever the others
    go, and those of the dense levels down to the deepest level of the
    rest, from the sparse level above them, which have a fiber at every
    slot of it, so the positions of the level are the entries of the
    sparse one, at every slot of the dense ones.
    """
    unrestricted = set()
    if self.idx in fields and self.protocol(table) == Follow():
        unrestricted.add(self.idx)
    run: set[Field] = set()
    trailing: set[Field] = set()
    for idx, dense in self.levels.get(table, ()):
        run = run | {idx} if dense else set()
        if idx in fields and idx not in unrestricted:
            trailing = run
    return unrestricted | trailing

visited()

Where the loop visits idx, which its walks and gallops restrict.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def visited(self) -> NS:
    """Where the loop visits idx, which its walks and gallops restrict."""
    return self.stats_factory.mapjoin(
        ffuncs.and_,
        self.exec_space,
        self.stats_factory.support(self.merged(self.arg, (self.idx,))),
    )

PigeonBasis

Bases: LoopBasis, LoopOrderedForm

PigeonBasis counts iteration, operation, output, lookup, and dense iteration costs across loop prefixes. The empty prefix charges the non-fill values of the output once, and a nonempty prefix charges its last loop: a walk steps through the stored indices of its table, a gallop or a follow instead visits the indices where the expression runs, charging a lookup at each, and the dense iterations of a loop are those it would make if its tables were dense, so that none could restrict it: its whole extent, wherever its enclosing loops run.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
class PigeonBasis(LoopBasis, LoopOrderedForm):
    """
    PigeonBasis counts iteration, operation, output, lookup, and dense
    iteration costs across loop prefixes. The empty prefix charges the
    non-fill values of the output once, and a nonempty prefix charges its last
    loop: a walk steps through the stored indices of its table, a gallop or a
    follow instead visits the indices where the expression runs, charging a
    lookup at each, and the dense iterations of a loop are those it would make
    if its tables were dense, so that none could restrict it: its whole
    extent, wherever its enclosing loops run.
    """

    @property
    def n_features(self) -> int:
        return 5

    @property
    def feature_names(self) -> tuple[str, ...]:
        return ("iterations", "operations", "outputs", "lookups", "dense_iterations")

    def get_component_features(
        self,
        component: Prefix,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        prefix, expr, output_vars = (
            component.prefix,
            component.expr,
            component.output_vars,
        )
        stats_factory = machine.stats_factory
        out_space = machine(expr)
        if output_vars is not None:
            if any(idx not in output_vars for idx in out_space.index_order):
                out_space = restrict(stats_factory, out_space, output_vars)
            out_space = stats_factory.reorder(out_space, output_vars)
        if not prefix:
            return np.array(
                [[0.0, 0.0, out_space.estimate_non_fill_values(), 0.0, 0.0]]
            )
        spaces = LoopSpaces(component, machine)
        idx = spaces.idx
        exec_space = spaces.exec_space
        inputs, walks, lookups = [], [], 0
        for node in PostOrderDFS(spaces.arg):
            match node:
                case Table(_, idxs) if idx in idxs:
                    stat = machine(node)
                    inputs.append(stat)
                    match spaces.protocol(node):
                        case Follow() | Gallop():
                            lookups += 1
                        case _:
                            walks.append(spaces.project(stat, (idx,)))
        iterations = spaces.executions()
        lookup_cost = 0.0
        if lookups:
            visited = spaces.visited()
            # The loop steps through the tables it walks, and visits the rest.
            steps = stats_factory.mapjoin(ffuncs.or_, visited, *walks)
            iterations = spaces.count(
                stats_factory.mapjoin(ffuncs.and_, exec_space, steps)
            )
            lookup_cost = spaces.count(visited) * lookups
        elif inputs:
            iterations = spaces.count(
                stats_factory.mapjoin(
                    ffuncs.and_, exec_space, stats_factory.mapjoin(ffuncs.or_, *walks)
                )
            )
        out_cost = 0.0
        if idx in out_space.index_order:
            out_cost = spaces.project(out_space).estimate_non_fill_values()
        return np.array(
            [
                [
                    iterations,
                    spaces.executions() * len(inputs),
                    out_cost,
                    lookup_cost,
                    spaces.count(exec_space),
                ]
            ]
        )

Prefix dataclass

An outermost-first loop prefix of expr, the right-hand side of a query. output_vars orders the output of the query, when there is one, and output is the tensor it writes. formats, which bases that price formatted tensors need, lists the level options each alias stores, outermost first, as level_formats lists them.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
@dataclass(frozen=True)
class Prefix:
    """
    An outermost-first loop prefix of expr, the right-hand side of a query.
    output_vars orders the output of the query, when there is one, and output
    is the tensor it writes. formats, which bases that price formatted tensors
    need, lists the level options each alias stores, outermost first, as
    level_formats lists them.
    """

    prefix: tuple[Field, ...]
    expr: LogicExpression
    output_vars: tuple[Field, ...] | None = None
    formats: Mapping[Alias, Any] | None = field(default=None, compare=False, hash=False)
    output: Alias | Literal | None = None

ProtocolBasis

Bases: ByKind[ProtocolChoice, str]

The accesses of the levels of each formatted tensor, each under the basis of the kind of its level and, within it, of its protocol, so that a linear model prices each feature of an access by both.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class ProtocolBasis(ByKind[ProtocolChoice, str]):
    """
    The accesses of the levels of each formatted tensor, each under the basis
    of the kind of its level and, within it, of its protocol, so that a
    linear model prices each feature of an access by both.
    """

    def __init__(self):
        super().__init__(
            {
                option.kind: ByKind(
                    dict.fromkeys(protocol_names(option), AccessBasis()),
                    access_protocol,
                )
                for option in KINDS
            },
            option_kind,
        )

ProtocolChoice dataclass

An access of the level of a tensor at a zero-based stored depth by a query, at the last loop of prefix, which reaches the level: the last loop over a field of the levels from the root to it, or, for the element level at the rank of the tensor, to the last of them. table is the read, in the expression of prefix, or, if write, the table of the output of the query, and options are the kinds of the levels of the tensor, outermost first.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
@dataclass(frozen=True)
class ProtocolChoice:
    """
    An access of the level of a tensor at a zero-based stored depth by a query,
    at the last loop of prefix, which reaches the level: the last loop over a
    field of the levels from the root to it, or, for the element level at the
    rank of the tensor, to the last of them. table is the read, in the
    expression of prefix, or, if write, the table of the output of the query,
    and options are the kinds of the levels of the tensor, outermost first.
    """

    prefix: Prefix
    table: Table
    depth: int
    options: Sequence[LevelOption]
    write: bool = False

    @property
    def option(self) -> LevelOption:
        return self.options[self.depth]

    @property
    def alias(self) -> Alias:
        match self.table.tns:
            case Alias() as tns:
                return tns
        raise ValueError(f"Expected a table of an alias, got {self.table}")

    @property
    def parent_fields(self) -> tuple[Field, ...]:
        """The fields of the levels above the level."""
        return self.table.idxs[: self.alias.nfused + self.depth]

    @property
    def fields(self) -> tuple[Field, ...]:
        """The fields of the level and of the levels above it."""
        return self.table.idxs[: self.alias.nfused + self.depth + 1]

    @property
    def protocol(self) -> Protocol:
        if self.write:
            # An update which reduces into its output has the output's table
            # as the init of its aggregate, as QueryInto.as_query writes it.
            match self.prefix.expr:
                case Aggregate(Literal(op), Table(), _, _) if op != ffuncs.overwrite:
                    return Laminate()
            return Extrude() if self.prefix.prefix == self.fields else Laminate()
        protocols = self.table.protocols
        proto = protocols[self.alias.nfused + self.depth] if protocols else None
        if proto is None or proto == DefaultProtocol():
            return self.option.default_protocol
        return proto

fields property

The fields of the level and of the levels above it.

parent_fields property

The fields of the levels above the level.

Quadratic

Bases: RowMap[C]

The products of each pair of features of each row of a basis, flattened row-major, so a linear model of them sums a quadratic form of each row.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class Quadratic(RowMap[C]):
    """
    The products of each pair of features of each row of a basis, flattened
    row-major, so a linear model of them sums a quadratic form of each row.
    """

    @property
    def n_features(self) -> int:
        return self.basis.n_features**2

    @property
    def feature_names(self) -> tuple[str, ...]:
        names = self.basis.feature_names
        return tuple(f"{a}*{b}" for a in names for b in names)

    def transform(self, rows: np.ndarray) -> np.ndarray:
        return np.einsum("ij,ik->ijk", rows, rows).reshape(len(rows), -1)

RowMap

Bases: Basis[C]

A basis whose rows are a function, transform, of the rows of another basis for the same components.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class RowMap(Basis[C]):
    """
    A basis whose rows are a function, transform, of the rows of another
    basis for the same components.
    """

    def __init__(self, basis: Basis[C]):
        self.basis = basis

    def validate_inputs(self, *inputs):
        self.basis.validate_inputs(*inputs)

    def components(
        self,
        term: LogicStatement,
        bindings: Mapping[Alias, Any],
        machine: StatsMachine[NS],
    ) -> Iterator[C]:
        return self.basis.components(term, bindings, machine)

    @abstractmethod
    def transform(self, rows: np.ndarray) -> np.ndarray: ...

    def get_component_features(
        self,
        component: C,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        return self.transform(self.basis.get_component_features(component, machine))

SparseByteMapLevelOption

Bases: LevelOption

A bytemap flags each of its slots with a byte, and lists the slots which are occupied, so its children are allocated densely. Storage features are positions, slots, entries, and the bytes of its pointers and list.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class SparseByteMapLevelOption(LevelOption):
    """
    A bytemap flags each of its slots with a byte, and lists the slots which
    are occupied, so its children are allocated densely. Storage features are
    positions, slots, entries, and the bytes of its pointers and list.
    """

    kind = "sparse_bytemap"
    feature_names = ("positions", "slots", "entries", "position_bytes")
    protocols = (
        DefaultProtocol(),
        Walk(),
        Gallop(),
        Follow(),
        Extrude(),
        Laminate(),
    )
    default_protocol = Walk()
    filters = True

    def next_num_pos(self, stats, stats_factory, depth, num_pos, over):
        return num_pos * stats.get_dim_size(stats.index_order[depth])

    def get_storage_features(
        self, stats, stats_factory, depth, num_pos, idx_size, pos_size, val_size, over
    ):
        slots = self.next_num_pos(stats, stats_factory, depth, num_pos, over)
        nnz_l = nnz_after(stats, stats_factory, depth, over)
        return np.array([num_pos, slots, nnz_l, (num_pos + 1 + nnz_l) * pos_size])

SparseHashLevelOption

Bases: LevelOption

Storage features are positions, entries, position bytes, and index bytes.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class SparseHashLevelOption(LevelOption):
    """Storage features are positions, entries, position bytes, and index bytes."""

    kind = "sparse_hash"
    feature_names = ("positions", "entries", "position_bytes", "index_bytes")
    protocols = (DefaultProtocol(), Walk(), Follow(), Extrude(), Laminate())
    default_protocol = Walk()
    filters = True

    def next_num_pos(self, stats, stats_factory, depth, num_pos, over):
        return nnz_after(stats, stats_factory, depth, over)

    def get_storage_features(
        self, stats, stats_factory, depth, num_pos, idx_size, pos_size, val_size, over
    ):
        nnz_l = nnz_after(stats, stats_factory, depth, over)
        return np.array([num_pos, nnz_l, (num_pos + 1) * pos_size, nnz_l * idx_size])

SparseListLevelOption

Bases: LevelOption

Storage features are positions, entries, position bytes, and index bytes.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class SparseListLevelOption(LevelOption):
    """Storage features are positions, entries, position bytes, and index bytes."""

    kind = "sparse_list"
    feature_names = ("positions", "entries", "position_bytes", "index_bytes")
    # A list appends each entry after the last, so it's only extruded.
    protocols = (DefaultProtocol(), Walk(), Gallop(), Follow(), Extrude())
    default_protocol = Walk()
    filters = True

    def next_num_pos(self, stats, stats_factory, depth, num_pos, over):
        return nnz_after(stats, stats_factory, depth, over)

    def get_storage_features(
        self, stats, stats_factory, depth, num_pos, idx_size, pos_size, val_size, over
    ):
        nnz_l = nnz_after(stats, stats_factory, depth, over)
        return np.array([num_pos, nnz_l, (num_pos + 1) * pos_size, nnz_l * idx_size])

Statement dataclass

A Query or QueryInto of a program.

Source code in src/finch/autoschedule/cost_models/factorize_cost_models.py
@dataclass(frozen=True)
class Statement:
    """A Query or QueryInto of a program."""

    stmt: LogicStatement

StorageBasis

Bases: ByKind[ProtocolChoice, str]

The storage of the levels each access writes, each under the basis of the kind of its level.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
class StorageBasis(ByKind[ProtocolChoice, str]):
    """The storage of the levels each access writes, each under the basis of
    the kind of its level."""

    def __init__(self):
        super().__init__(
            {option.kind: LevelBasis(option) for option in KINDS}, option_kind
        )

Stratify

Bases: RowMap[C]

The features of each row of a basis, in the block of columns of the regime of the row, with zeros in the blocks of the other regimes. The regime of a row is the number of thresholds its feature at index feature meets or exceeds. A linear model of this basis has separate coefficients for each regime, so a feature can cost differently once, say, the working set exceeds a cache.

Source code in src/finch/autoschedule/cost_models/cost_models.py
class Stratify(RowMap[C]):
    """
    The features of each row of a basis, in the block of columns of the
    regime of the row, with zeros in the blocks of the other regimes. The
    regime of a row is the number of thresholds its feature at index feature
    meets or exceeds. A linear model of this basis has separate coefficients
    for each regime, so a feature can cost differently once, say, the working
    set exceeds a cache.
    """

    def __init__(self, basis: Basis[C], feature: int, thresholds: ArrayLike):
        super().__init__(basis)
        if not 0 <= feature < basis.n_features:
            raise ValueError(
                f"Expected 0 <= feature < {basis.n_features}, got {feature}"
            )
        self.feature = feature
        self.thresholds = np.asarray(thresholds, dtype=float)
        if self.thresholds.ndim != 1 or not np.all(np.diff(self.thresholds) > 0):
            raise ValueError(f"Expected increasing thresholds, got {thresholds}")

    @property
    def n_regimes(self) -> int:
        return len(self.thresholds) + 1

    @property
    def n_features(self) -> int:
        return self.n_regimes * self.basis.n_features

    @property
    def feature_names(self) -> tuple[str, ...]:
        return tuple(
            f"regime{regime}.{name}"
            for regime in range(self.n_regimes)
            for name in self.basis.feature_names
        )

    @property
    def ridge(self) -> np.ndarray:
        return np.tile(self.basis.ridge, self.n_regimes)

    def transform(self, rows: np.ndarray) -> np.ndarray:
        n = self.basis.n_features
        regime = np.searchsorted(self.thresholds, rows[:, self.feature], side="right")
        columns = regime[:, None] * n + np.arange(n)
        features = np.zeros((len(rows), self.n_features))
        np.put_along_axis(features, columns, rows, axis=1)
        return features

TransposeBasis

Bases: LoopBasis, LoopOrderedForm

Count dense and sparse transposed entries, charging each input once per query, at the first prefix whose last loop reads it out of its stored order.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
class TransposeBasis(LoopBasis, LoopOrderedForm):
    """
    Count dense and sparse transposed entries, charging each input once per
    query, at the first prefix whose last loop reads it out of its stored
    order.
    """

    @property
    def n_features(self) -> int:
        return 2

    @property
    def feature_names(self) -> tuple[str, ...]:
        return ("dense_transposes", "sparse_transposes")

    def get_component_features(
        self,
        component: Prefix,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        prefix, expr = component.prefix, component.expr
        features = np.zeros((1, self.n_features))
        if not prefix:
            return features

        match expr:
            case Aggregate(arg=arg):
                pass
            case _:
                arg = expr
        for node in set(PostOrderDFS(arg)):
            match node:
                case Table(_, idxs) if prefix[-1] in idxs:
                    stat = machine(node)
                case _:
                    continue
            order = stat.index_order
            parent = tuple(idx for idx in prefix[:-1] if idx in order)
            if parent == order[: len(parent)] and prefix[-1] != order[len(parent)]:
                nnz = stat.estimate_non_fill_values()
                space = stat.get_dim_space_size(order)
                dense = 0 < space < float("inf") and nnz / space > 0.1
                features[0, 0 if dense else 1] += nnz
        return features

allowed_options(alias, depth, term, options)

The options which can take the level of alias at a depth in term: those which support the protocols term reads and writes it with.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def allowed_options(
    alias: Alias, depth: int, term: LogicStatement, options: Sequence[LevelOption]
) -> list[LevelOption]:
    """
    The options which can take the level of alias at a depth in term: those
    which support the protocols term reads and writes it with.
    """
    protocols = read_protocols(alias, depth, term) | write_protocols(alias, depth, term)
    return [option for option in options if protocols <= set(option.protocols)]

level_accesses(prefix, formats)

The reads of levels at the last loop of prefix, then the writes of the levels of its output, if formats lists the options of its levels, with the write of its element level where the last of them is reached.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def level_accesses(
    prefix: Prefix, formats: Mapping[Alias, Sequence[LevelOption]]
) -> Iterator[ProtocolChoice]:
    """
    The reads of levels at the last loop of prefix, then the writes of the
    levels of its output, if formats lists the options of its levels, with the
    write of its element level where the last of them is reached.
    """
    yield from level_reads(prefix, formats)
    loops, idxs = prefix.prefix, prefix.output_vars
    match prefix.output:
        case Alias() as tns if loops and idxs is not None and tns.unfused in formats:
            options = formats[tns.unfused]
            table = Table(tns, idxs)
            rank = len(idxs) - tns.nfused
            for depth in reached_depths(loops, idxs, tns.nfused):
                yield ProtocolChoice(prefix, table, depth, options, write=True)
                if depth == rank - 1 and len(options) > rank:
                    yield ProtocolChoice(prefix, table, rank, options, write=True)

level_formats(bindings)

The options of the levels each alias of bindings stores, outermost first and ending with its element level, as the bases of formatted programs take them. A binding is either such a list, or a format, whose options level_options lists. An alias whose format stores a level of no option is left out.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def level_formats(bindings: Mapping[Alias, Any]) -> dict[Alias, Sequence[LevelOption]]:
    """
    The options of the levels each alias of bindings stores, outermost first
    and ending with its element level, as the bases of formatted programs take
    them. A binding is either such a list, or a format, whose options
    level_options lists. An alias whose format stores a level of no option is
    left out.
    """
    formats: dict[Alias, Sequence[LevelOption]] = {}
    for alias, fmt in bindings.items():
        match fmt:
            case TensorFType():
                options = level_options(fmt)
                if options is not None:
                    formats[alias] = [*options, ElementLevelOption()]
            case _:
                formats[alias] = fmt
    return formats

level_options(fmt)

The options of the levels which a fiber tensor of the format fmt stores, outermost first and without its element level, or None where fmt isn't a fiber tensor or stores a level of no option.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def level_options(fmt: TensorFType) -> list[LevelOption] | None:
    """
    The options of the levels which a fiber tensor of the format fmt stores,
    outermost first and without its element level, or None where fmt isn't a
    fiber tensor or stores a level of no option.
    """
    match fmt:
        case FiberTensorFType(lvl_t=lvl):
            pass
        case _:
            return None
    options = []
    while True:
        match lvl:
            case ElementLevelFType():
                return options
            case _ if type(lvl) in LEVEL_FTYPES:
                options.append(LEVEL_FTYPES[type(lvl)])
                lvl = lvl.lvl_t
            case _:
                return None

level_reads(prefix, formats)

The levels which the tables of the query of prefix read at its last loop: those of the tensors of formats, whose options list the levels each alias stores, outermost first. A table which occurs several times reads each level once.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def level_reads(
    prefix: Prefix, formats: Mapping[Alias, Sequence[LevelOption]]
) -> Iterator[ProtocolChoice]:
    """
    The levels which the tables of the query of prefix read at its last loop:
    those of the tensors of formats, whose options list the levels each alias
    stores, outermost first. A table which occurs several times reads each
    level once.
    """
    loops = prefix.prefix
    if not loops:
        return
    match prefix.expr:
        case Aggregate(arg=arg):
            pass
        case arg:
            pass
    for table in dict.fromkeys(PostOrderDFS(arg)):
        match table:
            case Table(Alias() as tns, idxs) if tns.unfused in formats:
                options = formats[tns.unfused]
                for depth in reached_depths(loops, idxs, tns.nfused):
                    yield ProtocolChoice(prefix, table, depth, options)

nnz_after(stats, stats_factory, depth, over=())

Return the non-fill entries of the first depth + 1 levels of stats, in the largest slice which fixes the fields of over.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def nnz_after(stats: NS, stats_factory: StatsFactory[NS], depth: int, over: tuple = ()):
    """
    Return the non-fill entries of the first depth + 1 levels of stats, in the
    largest slice which fixes the fields of over.
    """
    reduce_fields = tuple(stats.index_order[depth + 1 :])
    if reduce_fields:
        stats = stats_factory.aggregate(
            ffuncs.or_, False, reduce_fields, stats_factory.support(stats)
        )
    return stats.estimate_non_fill_values(over=over)

prefixes(term, machine, loop_order=(), formats=None)

The loop prefixes of each query of term, including the empty prefix, in query order and from the shortest to the longest, advancing machine past each query after its prefixes. The loop order of a query is the fields of its enclosing Fuse nodes.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def prefixes(
    term: LogicStatement,
    machine: StatsMachine[NS],
    loop_order: tuple[Field, ...] = (),
    formats: Mapping[Alias, Any] | None = None,
) -> Iterator[Prefix]:
    """
    The loop prefixes of each query of term, including the empty prefix, in
    query order and from the shortest to the longest, advancing machine past
    each query after its prefixes. The loop order of a query is the fields of
    its enclosing Fuse nodes.
    """
    match term:
        case Plan(bodies):
            for body in bodies:
                yield from prefixes(body, machine, loop_order, formats)
            return
        case Fuse(idx, body):
            yield from prefixes(body, machine, (*loop_order, idx), formats)
            return
        case QueryInto(Table(), _, Literal()):
            machine(term)
            return
        case Produces():
            return
        case Query(Table(lhs, lhs_idxs), expr):
            pass
        case QueryInto(Table(lhs, lhs_idxs), _, _):
            expr = term.as_query().rhs
        case _:
            raise ValueError(f"Unsupported statement type: {term}")

    for n in range(len(loop_order) + 1):
        yield Prefix(loop_order[:n], expr, lhs_idxs, formats, output=lhs)
    machine(term)

read_options(option, idxs, nfused, depth, loop_order)

The protocols which a table of idxs, whose first nfused fields are fused, can read a level of option at a zero-based stored depth with under loop_order. A walk or a gallop steps through the level at the loop over its field, so that loop must come after the loops over the fields of the levels above it. Otherwise the level is reached inside the loop over its field, where it can only be followed.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def read_options(
    option: LevelOption,
    idxs: tuple[Field, ...],
    nfused: int,
    depth: int,
    loop_order: tuple[Field, ...],
) -> list[Protocol]:
    """
    The protocols which a table of idxs, whose first nfused fields are fused,
    can read a level of option at a zero-based stored depth with under
    loop_order. A walk or a gallop steps through the level at the loop over its
    field, so that loop must come after the loops over the fields of the levels
    above it. Otherwise the level is reached inside the loop over its field,
    where it can only be followed.
    """
    pos = loop_order.index(idxs[nfused + depth])
    in_order = all(loop_order.index(idx) < pos for idx in idxs[: nfused + depth])
    return [
        proto
        for proto in READ_PROTOCOLS
        if proto in option.protocols and (in_order or proto == Follow())
    ]

read_protocols(alias, depth, term)

The protocols which term reads the level of alias at a depth with. A read which gives no protocol takes whichever the level supports, which the protocol optimizer chooses, so it constrains nothing.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def read_protocols(alias: Alias, depth: int, term: LogicStatement) -> set[Protocol]:
    """
    The protocols which term reads the level of alias at a depth with. A read
    which gives no protocol takes whichever the level supports, which the
    protocol optimizer chooses, so it constrains nothing.
    """
    protocols = set()
    for node in PostOrderDFS(term):
        match node:
            case Query(_, rhs) | QueryInto(_, _, rhs):
                for table in PostOrderDFS(rhs):
                    match table:
                        case Table(Alias() as tns, idxs, (_, *_) as protos) if (
                            tns.unfused == alias.unfused
                            and tns.nfused + depth < len(idxs)
                            and protos[tns.nfused + depth] != DefaultProtocol()
                        ):
                            protocols.add(protos[tns.nfused + depth])
    return protocols

write_protocols(alias, depth, term)

The protocols which term writes the level of alias at a zero-based stored depth with, as util.write_protocols infers them under the loops of the enclosing Fuse nodes. An update which reduces into alias laminates what it already stores, but one which overwrites it or sets it to a literal starts it again.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def write_protocols(alias: Alias, depth: int, term: LogicStatement) -> set[Protocol]:
    """
    The protocols which term writes the level of alias at a zero-based stored
    depth with, as util.write_protocols infers them under the loops of the
    enclosing Fuse nodes. An update which reduces into alias laminates what it
    already stores, but one which overwrites it or sets it to a literal starts
    it again.
    """
    protocols = set()

    def visit(stmt: LogicStatement, loop_order: tuple[Field, ...]):
        match stmt:
            case Plan(bodies):
                for body in bodies:
                    visit(body, loop_order)
            case Fuse(idx, body):
                visit(body, (*loop_order, idx))
            case QueryInto(Table(), _, Literal()):
                return
            case QueryInto(Table(Alias() as lhs, _), Literal(op), _) if (
                lhs.unfused == alias.unfused and op != ffuncs.overwrite
            ):
                protocols.add(Laminate())
            case Query(Table(Alias() as lhs, idxs), _) | QueryInto(
                Table(Alias() as lhs, idxs), _, _
            ) if lhs.unfused == alias.unfused and idxs:
                protocols.add(util.write_protocols(idxs, loop_order, lhs.nfused)[depth])

    visit(term, ())
    return protocols