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,)):
                    # A unary map iterates as its argument does, but its output
                    # has the mapped fill (e.g. a norm's (value, scale) tuples),
                    # which an aggregate over it reads.
                    arg_stats, iter_stats = visit_expr(arg)
                    return stats_factory.mapjoin(op, arg_stats), iter_stats
                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() | FillTable() | DimensionTable():
                    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 nest: where it is entered, what it visits, and where its walks step, where the tables of followed span the field of the loop wholly, as they are looked up wherever the others go. A table whose formats the nest doesn't list is taken to be sparse.

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 nest: where it is entered,
    what it visits, and where its walks step, where the tables of followed
    span the field of the loop wholly, as they are looked up wherever the
    others go. A table whose formats the nest doesn't list is taken to be
    sparse.
    """

    def __init__(self, nest: LoopNest[NS], followed: frozenset[Table]):
        self.nest = nest
        self.stats_factory = nest.stats_factory
        self.parent = set(nest.loops[:-1])
        self.idx = nest.loops[-1]
        self.dims = nest.dims
        self.exec_space = nest.exec_space
        # The merge steps only where every fiber it merges has positions at idx.
        self._merged_at_idx = (
            nest.merged(nest.arg, followed) if followed else nest.merge
        )
        self.merge_space = self.project(self._merged_at_idx)
        self._visited: NS | None = None

    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 walked(self, node: LogicExpression) -> NS | None:
        """
        Where the walks of node at the loop have fibers with entries, over
        parent, combined as node combines them, or None where it walks
        nothing. A merge of walks skips a fiber only where this is empty:
        under a product, wherever one walked fiber is; under a sum, only where
        all are.
        """
        match node:
            case MapJoin(Literal(op), args):
                parts = [part for arg in args if (part := self.walked(arg)) is not None]
                if not parts:
                    return None
                joins = []
                unions = []
                for part in parts:
                    annihilates = is_annihilator(op.ftype, part.fill_type)
                    (joins if annihilates else unions).append(
                        self.stats_factory.support(part)
                    )
                if unions:
                    joins.append(self.stats_factory.mapjoin(ffuncs.or_, *unions))
                return self.stats_factory.mapjoin(ffuncs.and_, *joins)
            case Table(Alias() as tns, idxs) if self.idx in idxs[
                tns.nfused :
            ] and self.protocol(node) not in (Follow(), Gallop()):
                stat = self.nest.stats[Table(tns, idxs)]
                projected = self.project(stat)
                projected.fill_type = stat.fill_type
                return projected
        return None

    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."""
        if self._visited is None:
            self._visited = self.stats_factory.mapjoin(
                ffuncs.and_,
                self.exec_space,
                self.stats_factory.support(self._merged_at_idx),
            )
        return self._visited

    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.
        """
        stat = self.nest.stats[Table(table.tns, table.idxs)]
        return self.stats_factory.mapjoin(
            ffuncs.and_, self.merge_space, self.project(stat, (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)

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.
    """
    stat = self.nest.stats[Table(table.tns, table.idxs)]
    return self.stats_factory.mapjoin(
        ffuncs.and_, self.merge_space, self.project(stat, (self.idx,))
    )

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."""
    if self._visited is None:
        self._visited = self.stats_factory.mapjoin(
            ffuncs.and_,
            self.exec_space,
            self.stats_factory.support(self._merged_at_idx),
        )
    return self._visited

walked(node)

Where the walks of node at the loop have fibers with entries, over parent, combined as node combines them, or None where it walks nothing. A merge of walks skips a fiber only where this is empty: under a product, wherever one walked fiber is; under a sum, only where all are.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def walked(self, node: LogicExpression) -> NS | None:
    """
    Where the walks of node at the loop have fibers with entries, over
    parent, combined as node combines them, or None where it walks
    nothing. A merge of walks skips a fiber only where this is empty:
    under a product, wherever one walked fiber is; under a sum, only where
    all are.
    """
    match node:
        case MapJoin(Literal(op), args):
            parts = [part for arg in args if (part := self.walked(arg)) is not None]
            if not parts:
                return None
            joins = []
            unions = []
            for part in parts:
                annihilates = is_annihilator(op.ftype, part.fill_type)
                (joins if annihilates else unions).append(
                    self.stats_factory.support(part)
                )
            if unions:
                joins.append(self.stats_factory.mapjoin(ffuncs.or_, *unions))
            return self.stats_factory.mapjoin(ffuncs.and_, *joins)
        case Table(Alias() as tns, idxs) if self.idx in idxs[
            tns.nfused :
        ] and self.protocol(node) not in (Follow(), Gallop()):
            stat = self.nest.stats[Table(tns, idxs)]
            projected = self.project(stat)
            projected.fill_type = stat.fill_type
            return projected
    return None

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 = loop_spaces(component, machine)
        idx = spaces.idx
        exec_space = spaces.exec_space
        inputs, walks, lookups = [], [], 0
        for node in PostOrderDFS(loop_arg(expr)):
            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 its class, with zeros in the blocks of the other classes. classify gives the class of each of rows, an integer from 0 to n_classes - 1, from its features. A linear model of this basis has separate coefficients for each class, 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 its
    class, with zeros in the blocks of the other classes. classify gives the
    class of each of rows, an integer from 0 to n_classes - 1, from its
    features. A linear model of this basis has separate coefficients for each
    class, so a feature can cost differently once, say, the working set
    exceeds a cache.
    """

    def __init__(
        self,
        basis: Basis[C],
        n_classes: int,
        classify: Callable[[np.ndarray], ArrayLike],
    ):
        super().__init__(basis)
        if n_classes < 1:
            raise ValueError(f"Expected at least one class, got {n_classes}")
        self.n_classes = n_classes
        self.classify = classify

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

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

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

    def transform(self, rows: np.ndarray) -> np.ndarray:
        classes = np.asarray(self.classify(rows), dtype=int).reshape(len(rows))
        if np.any((classes < 0) | (classes >= self.n_classes)):
            raise ValueError(
                f"Expected classes below {self.n_classes}, got {classes.max()}"
            )
        n = self.basis.n_features
        columns = classes[:, None] * n + np.arange(n)
        features = np.zeros((len(rows), self.n_features))
        np.put_along_axis(features, columns, rows, axis=1)
        return features

WithCopies

Bases: Basis[Prefix]

The rows of basis, where a prefix whose last loop reads a table out of the order it is stored in, the first time a prefix of the query does, also has the rows basis gives the copy concordize makes of it, so that a model of basis prices transposing the table as it prices any query which scatters.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
class WithCopies(Basis[Prefix]):
    """
    The rows of basis, where a prefix whose last loop reads a table out of the
    order it is stored in, the first time a prefix of the query does, also has
    the rows basis gives the copy concordize makes of it, so that a model of
    basis prices transposing the table as it prices any query which scatters.
    """

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

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

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

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

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

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

    def get_component_features(
        self,
        component: Prefix,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        rows = [self.basis.get_component_features(component, machine)]
        for tns, stat in transposed(component, machine):
            copy = transpose_copy(tns, stat, component.prefix)
            rows.append(
                self.basis.get_features(copy, {}, {tns: stat}, machine.stats_factory)
            )
        return np.concatenate(rows)

WriteBasis

Bases: LoopBasis, LoopOrderedForm

The writes to the levels of the output of a query which the last loop of each prefix reaches: those whose fields, and those of the levels above them, the prefix loops over, the last of them last. Where the loops up to a level are its fields in storage order, the level is written once for each of its indices, in order, and otherwise its writes scatter, as util.write_protocols infers. The element level is written with its parent. Besides the writes, a row has the entries of the region of the output the writes scatter into, which WriteClasses classes it by, a slice over the fields after the leading ones the loops visit in storage order, which a workspace fused over those could hold, or none where nothing scatters, and the distinct entries of the levels reached. Sizes are products of the extents of the fields, where a field which no table has, such as a unit dimension of the output alone, has one index.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
class WriteBasis(LoopBasis, LoopOrderedForm):
    """
    The writes to the levels of the output of a query which the last loop of
    each prefix reaches: those whose fields, and those of the levels above
    them, the prefix loops over, the last of them last. Where the loops up to a
    level are its fields in storage order, the level is written once for each
    of its indices, in order, and otherwise its writes scatter, as
    util.write_protocols infers. The element level is written with its parent.
    Besides the writes, a row has the entries of the region of the output the
    writes scatter into, which WriteClasses classes it by, a slice over the
    fields after the leading ones the loops visit in storage order, which a
    workspace fused over those could hold, or none where nothing scatters, and
    the distinct entries of the levels reached. Sizes are products of the
    extents of the fields, where a field which no table has, such as a unit
    dimension of the output alone, has one index.
    """

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

    @property
    def feature_names(self) -> tuple[str, ...]:
        return (
            "sequential_writes",
            "scatter_writes",
            "scattered_region",
            "distinct_outputs",
        )

    def get_component_features(
        self,
        component: Prefix,
        machine: StatsMachine[NS],
    ) -> np.ndarray:
        prefix, output_vars = component.prefix, written_fields(component)
        features = np.zeros((1, self.n_features))
        reached = [
            output_vars[: depth + 1]
            for depth in range(len(output_vars))
            if set(output_vars[: depth + 1]) <= set(prefix)
            and prefix[-1] in output_vars[: depth + 1]
        ]
        if not reached:
            return features
        dims: dict[Field, float] = {}
        for node in PostOrderDFS(component.expr):
            match node:
                case Table():
                    dims.update(machine(node).dim_sizes)

        def size(fields) -> float:
            return math.prod(dims.get(idx, 1.0) for idx in fields)

        spaces = loop_spaces(component, machine)
        visits = spaces.count(spaces.visited())
        output = machine(component.expr)
        for order in reached:
            features[0, 0 if prefix == order else 1] += visits
            distinct = restrict(machine.stats_factory, output, order)
            features[0, 3] += distinct.estimate_non_fill_values()
        if features[0, 1]:
            fused = 0
            while (
                fused < len(prefix)
                and prefix[fused : fused + 1] == output_vars[fused : fused + 1]
            ):
                fused += 1
            features[0, 2] = size(output_vars[fused:])
        return features

WriteClasses dataclass

The class of each row of WriteBasis, whether the region its writes scatter into exceeds the region cutoff. The default cutoff is the most entries a workspace can reset and copy out cheaply.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
@dataclass(frozen=True)
class WriteClasses:
    """
    The class of each row of WriteBasis, whether the region its writes
    scatter into exceeds the region cutoff. The default cutoff is the most
    entries a workspace can reset and copy out cheaply.
    """

    region: float = 100_000

    def __call__(self, rows: np.ndarray) -> np.ndarray:
        _, _, region, _ = rows.T
        return (region > self.region).astype(int)

WriteStrata

Bases: Stratify

The rows of WriteBasis in the classes of classes. A write which scatters into a region over the cutoff isn't staged in a workspace, but written into the output where it goes, so its region costs nothing.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
class WriteStrata(Stratify):
    """
    The rows of WriteBasis in the classes of classes. A write which scatters
    into a region over the cutoff isn't staged in a workspace, but written
    into the output where it goes, so its region costs nothing.
    """

    def __init__(self, classes: WriteClasses):
        super().__init__(WriteBasis(), N_WRITE_CLASSES, classes)

    def transform(self, rows: np.ndarray) -> np.ndarray:
        features = super().transform(rows)
        region = self.basis.feature_names.index("scattered_region")
        features[:, self.basis.n_features + region] = 0.0
        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)

loop_basis(classes=write_class)

The basis of the loop model, whose writes are of the classes of the region cutoff of classes.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def loop_basis(classes: WriteClasses = write_class) -> Basis[Prefix]:
    """The basis of the loop model, whose writes are of the classes of the
    region cutoff of classes."""
    return Affine(Concat(PigeonBasis(), WriteStrata(classes)))

loop_cost_model(data)

The loop model of data, which fit_physical_data wrote, whose writes are classed by its region cutoff if it was tuned. The fit times each loop order with its inputs stored in that order, so a table read out of the order it is stored in costs, besides, what the model prices the copy concordize makes of it at.

Source code in src/finch/autoschedule/cost_models/loop_cost_models.py
def loop_cost_model(data: Mapping[str, Any]) -> CostModel[Prefix]:
    """The loop model of data, which fit_physical_data wrote, whose writes are
    classed by its region cutoff if it was tuned. The fit times each loop order
    with its inputs stored in that order, so a table read out of the order it
    is stored in costs, besides, what the model prices the copy concordize
    makes of it at."""
    basis = WithCopies(
        loop_basis(WriteClasses(data.get("region_cutoff", write_class.region)))
    )
    return CostModel(basis, np.zeros(basis.n_features)).from_json(data)

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

rescans_a_root(loops, reads, protocols)

Whether reading reads with protocols at the last of loops, within the others, steps through the root level of a table, such as a vector, which has the same entries at every execution of the loop, where a sparse level of another read, whose fiber the enclosing loops choose, could lead the loop instead. A walk steps through the root again at every execution, and so does a gallop of it beside a walk, which ends no phase, or beside no other gallop; a gallop leapfrogging with that of another read doesn't. The length of the root is exact while DC stats bound the other fibers by the largest, so the model may price stepping through it below following it, which looks up only where the others lead. Reads whose protocols the program gives are not among reads.

Source code in src/finch/autoschedule/cost_models/protocol_cost_models.py
def rescans_a_root(
    loops: tuple[Field, ...],
    reads: Sequence[ProtocolChoice],
    protocols: Sequence[Protocol],
) -> bool:
    """
    Whether reading reads with protocols at the last of loops, within the
    others, steps through the root level of a table, such as a vector, which
    has the same entries at every execution of the loop, where a sparse level
    of another read, whose fiber the enclosing loops choose, could lead the
    loop instead. A walk steps through the root again at every execution, and
    so does a gallop of it beside a walk, which ends no phase, or beside no
    other gallop; a gallop leapfrogging with that of another read doesn't.
    The length of the root is exact while DC stats bound the other fibers by
    the largest, so the model may price stepping through it below following
    it, which looks up only where the others lead. Reads whose protocols the
    program gives are not among reads.
    """
    roots, leads = [], []
    for read, protocol in zip(reads, protocols, strict=True):
        level = read.alias.nfused + read.depth
        above = read.table.idxs[:level]
        if read.table.idxs[level] != loops[-1]:
            continue
        if not above:
            roots.append(protocol)
        elif read.option.filters and set(above) <= set(loops):
            leads.append(protocol)
    leapfrogs = Gallop() in leads and Walk() not in protocols
    return (
        len(loops) > 1
        and bool(leads)
        and any(p == Walk() or (p == Gallop() and not leapfrogs) for p in roots)
    )

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