Skip to content

looplets

Jumper dataclass

Bases: Looplet

A stepper which skips ahead, as in Finch.jl. Each phase of its loop ends at the furthest stop of the jumpers, so that the jumper which stops there takes its chunk, and the others step to it.

Source code in src/finch/compile/looplets.py
@dataclass
class Jumper(Looplet):
    """
    A stepper which skips ahead, as in Finch.jl. Each phase of its loop ends at
    the furthest stop of the jumpers, so that the jumper which stops there takes
    its chunk, and the others step to it.
    """

    preamble: Any = None
    stop: Callable = lambda ctx: None
    chunk: Looplet | None = None
    next: Callable[[Any], Any] = lambda ctx: None
    seek: Callable = lambda ctx, ext: (_ for _ in ()).throw(
        NotImplementedError("seek not implemented error")
    )

    @property
    def pass_request(self):
        return JumperPass()

    def stepper(self) -> Stepper:
        return Stepper(
            preamble=self.preamble,
            stop=self.stop,
            chunk=self.chunk,
            next=self.next,
            seek=self.seek,
        )

SequencePass

Bases: LoopletPass

Lowers one Sequence looplet at the time.

Source code in src/finch/compile/looplets.py
class SequencePass(LoopletPass):
    """
    Lowers one Sequence looplet at the time.
    """

    @property
    def priority(self):
        return 4

    @classmethod
    def get_sequence_variations(
        cls, ctx, seqs: list[Sequence], heads, tails, ext: SymbolicExtent
    ) -> list[tuple]:
        ext_start, ext_end = ext.get_start(), ext.get_end()

        match seqs:
            case []:
                return [(heads, tails, ext_start, ext_end)]
            case [Sequence() as seq, *tail]:
                split = seq.split(ctx, ext)
                left = cls.get_sequence_variations(
                    ctx,
                    tail,
                    heads + [seq],
                    tails,
                    SymbolicExtent(
                        ext_start,
                        ntn.Call(ntn.L(ffuncs.min), (ext_end, split)),
                    ),
                )
                right = cls.get_sequence_variations(
                    ctx,
                    tail,
                    heads,
                    tails + [seq],
                    SymbolicExtent(
                        ntn.Call(ntn.L(ffuncs.max), (ext_start, split)),
                        ext_end,
                    ),
                )
                return left + right
            case other:
                raise Exception(f"Invalid sequence: {other}")

    def __call__(self, ctx: LoopletContext, idx, ext: SymbolicExtent, body):
        found_seqs: list[Sequence] = []

        for node in PostOrderDFS(body):
            match node:
                case ntn.Looplet(Sequence() as seq, _):
                    found_seqs.append(seq)

        found_seqs = list({id(seq): seq for seq in found_seqs}.values())

        def sequence_node(
            node: ntn.NotationNode,
            heads: set[Sequence],
            tails: set[Sequence],
            parts: dict[int, Looplet],
        ):
            match node:
                case ntn.Access(
                    ntn.Looplet(Sequence() as tns, type_), mode, (j, *idxs)
                ) if j == idx:
                    # Every access of a sequence shares its part, so that the
                    # accesses of one tensor are lowered once.
                    if id(tns) not in parts:
                        if tns in heads:
                            parts[id(tns)] = tns.head(ctx, idx)  # type: ignore[call-arg]
                        elif tns in tails:
                            parts[id(tns)] = tns.tail(ctx, idx)
                        else:
                            raise Exception(f"Seq: {tns} not present.")
                    return ntn.Access(
                        ntn.Looplet(parts[id(tns)], type_), mode, (j, *idxs)
                    )

        variations = self.get_sequence_variations(ctx, found_seqs, [], [], ext)
        blocks = []

        for v in variations:
            heads, tails, subext_start, subext_end = v
            sub_body = PostWalk(
                partial(sequence_node, heads=heads, tails=tails, parts={})
            )(body)
            subext = SymbolicExtent(subext_start, subext_end)
            sub_ctx = ctx.scope()
            sub_ctx(subext, self.looplet_simplify(sub_body))
            blocks += sub_ctx.emit()

        ctx.exec(asm.Block(tuple(blocks)))