콘텐츠로 이동

Static Evaluation

static 연산은 컴파일 시점에 실행됩니다. 다음 스크립트는 for_each, fold/empty_list/append, if_else의 사용 예를 보여 주며, launch=False를 지정해 **프론트엔드 MLIR**을 출력합니다. 디바이스 쪽 출력은 없으며, 실행했을 때의 수치 결과도 보장하지 않습니다.

static_evaluation.py를 내려받거나, 다음 명령을 실행하십시오.

1
python "$DOCS_ROOT/docs/legato-language/tutorials/code/static_evaluation.py"
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
"""Compile-time unrolling, folding and branching; inspect frontend MLIR."""

import os
from pathlib import Path

import legato
import legato.language.types as lt
import legato.model.bertha as bertha
from legato.language import arith

# Store compiler artifacts and optional simulator logs in a configurable directory.
OUTPUT = Path(os.environ.get("LEGATO_EXAMPLE_OUTPUT", "legato_example_output"))


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def static_for_each(
    to_add: lt.integer("int64"),
    num_cores: lt.constexpr(lt.integer("int64")),
):
    """Unroll per-core scalar expressions in frontend IR."""
    device = legato.get_context().get_device()

    def add_one(core_id):
        return arith.cast(core_id, lt.integer("int64")) + to_add

    with device.get_all_cores():
        core_range = legato.range(
            arith.cast(0, lt.index()),
            arith.cast(num_cores, lt.index()),
        )
        legato.static.for_each(core_range, add_one)


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def build_static_list(
    to_add: lt.integer("int64"),
    core_ids: lt.constexpr(lt.list(lt.integer("int64"))),
):
    """Fold and cast a constexpr list before emitting per-core expressions."""
    empty = legato.static.empty_list(lt.integer("int32"))
    casted_core_ids = legato.static.fold(
        core_ids,
        lambda core_id, acc: legato.static.append(acc, arith.cast(core_id, lt.integer("int32"))),
        empty,
    )

    def add_one(x: lt.integer("int32")):
        return x + arith.cast(to_add, lt.integer("int32"))

    device = legato.get_context().get_device()
    with device.get_all_cores():
        legato.static.for_each(casted_core_ids, add_one)


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def static_branch():
    """Select a branch at compile time; this entry point is not launched."""
    device = legato.get_context().get_device()
    with device.get_all_cores():
        x = 0

        def on_true():
            return x + 1

        def on_false():
            return x + 2

        result = legato.static.if_else(True, on_true, on_false)
        yield result


def verify_static_for_each():
    """Emit the unrolled 32-core expressions."""
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        static_for_each(5, 32)


def verify_build_static_list():
    """Emit the three constexpr list elements."""
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        build_static_list(5, [0, 1, 2])


def verify_static_branch():
    """Emit the selected branch's value, one."""
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        static_branch()


def main():
    """Compile three illustrative entry points without launching them."""
    verify_static_for_each()
    verify_build_static_list()
    verify_static_branch()


if __name__ == "__main__":
    main()

static evaluation은 제어에 쓰이는 값을 컴파일 시점에 인터프리터가 평가하는 경우에만 사용하십시오. 디바이스 런타임 값에는 일반 연산자와 제어 흐름을 사용하십시오. static_branch는 런타임 인자가 없으므로 의도적으로 launch하지 않습니다. 인자가 없을 때 현재 생성되는 launch ABI가 null 인자 배열을 거부하기 때문입니다.