콘텐츠로 이동

데코레이터와 세션

Legato는 데코레이터로 컴파일 진입점과 그 안에서 조합해 쓸 재사용 함수를 정의합니다.

@legato.compile

@legato.compile(backend=...)은 사용자가 직접 호출하는 컴파일 진입점(entry point)을 만듭니다. backend 인자(Argument)는 활성 MLIR 컨텍스트를 받아 compute model을 반환하는 callable(호출 가능한 객체)입니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import legato
import legato.model.bertha as bertha


def get_bertha(ctx):
    return bertha.Bertha(ctx, "bertha")


@legato.compile(backend=get_bertha)
def kernel(
    x: legato.get_model().tensor_type(
        legato.types.float("bfloat16"), [10, 64], "shared_memory"
    ),
):
    device = legato.get_context().get_device()
    with device.get_core(0):
        yield x

컴파일된 함수는 다른 컴파일된 Legato 함수가 아니라 Python에서 호출합니다.
또한 컴파일된 함수를 실행하려면 legato.session(...) 안에서 실행해야 합니다.

1
2
with legato.session(output_type=legato.OutputType.MLIR, output_path="test-output"):
    kernel(input_tensor)

세션과 출력 타입

legato.session(output_type, output_path)은 컴파일러 artifact(디스크에 남기는 결과 파일)의 종류와 저장 위치를 제어하는 세션입니다. C 컴파일러로 치면 .o나 실행 파일에 해당합니다.

지원하는 OutputType 값은 다음과 같습니다. (artifact의 종류)

  • legato.OutputType.MLIR (보안 모드에서는 비활성화)
  • legato.OutputType.CORE_IR(보안 모드에서는 비활성화)
  • legato.OutputType.BACKEND_IR(보안 모드에서는 비활성화)
  • legato.OutputType.ASM(보안 모드에서는 비활성화)
  • legato.OutputType.BINARY

output_path를 지정하면 artifact과 로그는 그 경로 안의 함수별 디렉터리에 기록됩니다.
output_type과 output_path가 모두 None이면 Legato는 자체 캐시 디렉터리와 로그 디렉터리를 사용합니다.

param_kinds

@legato.compile은 param_kinds를 받아 각 파라미터를 생성된 영역 중 어디에서 사용할 수 있는지 기술합니다.

유효한 값은 다음과 같습니다.

  • "universal": 파라미터를 모든 executor 영역에서 사용할 수 있습니다.
  • "top": 파라미터를 top executor에서 사용하기 위한 것입니다.
  • "core": 파라미터를 core executor에서 사용하기 위한 것입니다.
1
2
3
4
5
6
@legato.compile(
    backend=get_bertha,
    param_kinds={"a": "universal", "weight": "top", "out": "core"},
)
def matmul_kernel(a, weight, out):
    ...

이 옵션은 입력, 가중치, 출력을 서로 다른 곳에 배치해야 하는 커널에서 유용합니다.
인자 배치(placement)는 컴파일 시점과 런타임, 두 단계로 이루어지며 param_kinds는 그중 컴파일 시점 부분을 담당합니다. 런타임 부분, 즉 호출 시 각 인자를 대상 디바이스에 바인딩하는 방법은 Argument Binding에서 다룹니다.

@legato.primitive

@legato.primitive(backend=...)은 컴파일된 함수나 다른 primitive에서 호출하는 재사용 가능한 Legato 코드를 정의합니다. primitive 호출은 호출자(Caller)의 일부로 컴파일되며, Python에서 직접 호출하지 않습니다.

프론트엔드 MLIR에는 primitive 함수와 이를 호출하는 func.call이 남을 수 있습니다. 인라인 여부는 이후 컴파일러 패스에 따라 결정됩니다. 데코레이터가 모든 출력 단계에서 호출 제거를 보장하지는 않습니다.

1
2
3
4
5
6
7
8
9
@legato.primitive(backend=get_bertha)
def add_pair(a: legato.types.integer("int64"), b: legato.types.integer("int64")) -> legato.types.integer("int64"):
    return a + b


@legato.compile(backend=get_bertha)
def caller(a: legato.types.integer("int64"), b: legato.types.integer("int64")):
    with legato.get_context().get_device().get_core(0):
        add_pair(a, b)

primitive는 값을 반환할 수 있습니다.
컴파일 진입점은 Python 반환값이 아니라 컴파일러 artifact와 store 같은 부수 효과(Side Effect)를 만들어 내기 위한 것입니다.

Constexpr 파라미터

파라미터 값을 컴파일 시점에 알아야 할 때는 legato.types.constexpr(...)를 사용하십시오.
constexpr 값이 다르면 서로 다른 컴파일 특수화(Specialization)가 만들어집니다.

1
2
3
4
5
6
7
8
9
@legato.compile(backend=get_bertha)
def static_loop(
    value: legato.types.integer("int64"),
    count: legato.types.constexpr(legato.types.integer("int64")),
):
    device = legato.get_context().get_device()
    with device.get_all_cores():
        rng = legato.range(0, count)
        legato.static.for_each(rng, lambda i: value + i)