콘텐츠로 이동

정적 평가

Legato의 Static Evaluation

Legato는 제어 흐름(control flow)과 데이터 구성(data-construction)을 위한 "static" 유틸리티를 몇 가지 제공하며, 이들은 모두 전부 컴파일 시점에 실행됩니다. 이 유틸리티는 IR에 반복문과 분기를 만들어 넣지 않고, 컴파일러가 코드를 생성하는 동안 호스트 인터프리터에서 실행됩니다. 덕분에 다음과 같은 이점이 있습니다.

  • 런타임 오버헤드 없이 커널을 특수화: 무엇을 실행할지 컴파일 시점에 결정하고 반복을 미리 펼쳐(unroll) 둡니다.
  • Python의 일반적인 추상화 수단 활용: 람다와 함수를 그대로 써서 읽기 쉽고 리팩토링하기 쉬운 코드를 작성할 수 있습니다.
  • 구현 단순화: 컴파일 시점에 내리는 결정을 IR에 넣지 않고, 동작이 예측 가능하고 타입 검사가 이루어지는 인터프리터에서 처리합니다.

Static 제어 흐름과 dynamic 제어 흐름

  • Dynamic 제어 흐름(커널 본문에서 동적 값에 대해 쓰는 보통의 for, while, if)은 디바이스에서 실행되는 IR 반복문/분기를 만듭니다.
  • Static 제어 흐름(legato.static.* 유틸리티)은 호스트 컴파일러에서 실행됩니다.
    static 구문의 결과는 상수, 컴파일 시점 리스트, 또는 동적 반복문/분기를 만들지 않고 IR을 합성하는 컴파일러 쪽 동작입니다.

while, 가장 가까운 반복문의 break, 지원되는 상태 타입과 현재 백엔드 제약은 런타임 제어 흐름을 참고하십시오.

static 구문은 입력이 컴파일 시점(인터프리터) 값이어야 합니다.
static 값이 필요한 자리에 동적 값을 넘기면 Legato가 분명한 에러로 잘못된 사용을 알려 줍니다.

평가 전략: 가능한 한 많이 컴파일 시점에

Legato 컴파일러는 가능하면 어떤 식이든 컴파일 시점에 적극적으로 평가하고, 꼭 필요할 때만 런타임(디바이스) 계산을 만듭니다. 이렇게 런타임 비용을 최소화합니다.

  • 입력을 컴파일 시점에 알 수 있으면, 컴파일러는 그 값으로 fold하고 펼칩니다.
  • 입력이 동적이면, 컴파일러는 디바이스가 계산하도록 IR을 생성합니다.

달리 말해 컴파일러는 할 수 있는 모든 연산을 "왼쪽으로 밀어" 런타임 코드를 군더더기 없이 유지합니다.

Constexpr 값과 런타임 값, 그리고 컴파일 캐시

  • **Constexpr 값**은 컴파일 시점에 값이 확정되는 값입니다(정적). 파라미터를 constexpr로 표시하는 것은, 코드 생성 중에 컴파일러가 그 값을 사용할 수 있어야 한다고 알리는 것입니다.
  • **런타임 값**은 디바이스에서 계산되므로, 컴파일 시점 결정에는 사용할 수 없습니다.

Legato는 @legato.compile 데코레이터가 붙은 함수에 대해, constexpr 파라미터 값을 키로 삼아 컴파일 결과(variant)를 캐시합니다. constexpr 파라미터가 바뀌면 특수화(specialization)가 달라지므로, 새 조합에 맞춰 함수를 다시 컴파일하고 캐시를 갱신합니다.

@legato.primitive로 장식된 함수는 별도의 실행 캐시를 두지 않습니다. 호출자의 모듈 안에서 컴파일하며, 본문을 생성할 때 constexpr 값을 사용할 수 있습니다. 프론트엔드 MLIR에는 primitive 함수와 func.call이 남을 수 있습니다. 인라인이나 호출 제거가 모든 출력 단계에서 보장되지는 않습니다.

예: 이 constexpr primitive의 본문 산술은 상수로 접히지만, 프론트엔드 함수 호출은 남을 수 있습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@legato.primitive(backend=get_bertha)
def add_primitive(a: lt.constexpr(lt.integer("int64")), b: lt.constexpr(lt.integer("int64"))) -> lt.integer("int64"):
    c = a + b   # 컴파일러가 계산
    return c

@legato.compile(backend=get_bertha)
def call_primitive(lhs: lt.constexpr(lt.integer("int64")), rhs: lt.constexpr(lt.integer("int64"))):
    add_primitive(lhs, rhs)  # 본문 덧셈은 fold되지만 호출은 남을 수 있습니다.

# 첫 호출은 (lhs=1, rhs=2)에 대한 @legato.compile wrapper를 컴파일해 캐시하고,
# constexpr 값을 사용할 수 있는 primitive 본문을 생성합니다
with legato.session(output_type=legato.OutputType.MLIR, launch=False):
    call_primitive(1, 2)
# 다른 constexpr 입력(예: 3, 4)은 @legato.compile 함수의 새 캐시 변형을 만들고
# 새 constexpr 값을 사용할 수 있는 primitive 본문을 생성합니다
with legato.session(output_type=legato.OutputType.MLIR, launch=False):
    call_primitive(3, 4)

예: constexpr와 런타임이 섞이면 컴파일 시점에 부분적으로 평가하고, 동적 작업은 디바이스에 남깁니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@legato.primitive(backend=get_bertha)
def add_primitive(a: lt.constexpr(lt.integer("int64")), b: lt.integer("int64")) -> lt.integer("int64"):
    # 컴파일러가 상수 `a`를 생성된 코드에 새겨 넣습니다
    c = a + b
    return c

@legato.compile(backend=get_bertha)
def call_primitive(lhs: lt.constexpr(lt.integer("int64")), rhs: lt.integer("int64")):
    add_primitive(lhs, rhs)

# 캐시 특수화는 @legato.compile 함수의 `lhs`를 키로 합니다.
# 각 변형은 해당 `lhs` 값으로 primitive 본문을 컴파일합니다.
with legato.session(output_type=legato.OutputType.MLIR, launch=False):
    call_primitive(1, 2)
    call_primitive(4, 2)

빠른 시작: static.for_each로 컴파일 시점 반복

인터프리터 iterable을 컴파일 시점에 순회하려면 legato.static.for_each(iterable, func)를 사용하십시오. 컴파일러가 반복문을 완전히 펼치며, 코드를 생성하는 동안 원소마다 func를 호출합니다.

테스트에서 가져온 예(range로 계산한 코어 id 순회):

1
2
3
4
5
6
7
8
@legato.compile(backend=get_bertha)
def test_static_for_each(to_add: lt.integer("int64"), num_cores: lt.constexpr(lt.integer("int64"))):
    device = legato.get_context().get_device()
    with device.get_all_cores():
        # range는 constexpr 경계로 만들어지므로 인터프리터 값입니다
        range_value = legato.range(arith.cast(0, lt.index()), arith.cast(num_cores, lt.index()))
        # 본문은 컴파일 시점에 실행되고, 덧셈은 원소마다 생성된 IR에 새겨집니다
        legato.static.for_each(range_value, lambda x: arith.cast(x, lt.integer("int64")) + to_add)

이름 있는 함수를 넘길 수도 있습니다.

1
2
3
4
5
def add_one(x):
    return arith.cast(x, lt.integer("int64")) + to_add

with device.get_all_cores():
    legato.static.for_each(range_value, add_one)

static.if_else로 컴파일 시점 조건 분기

legato.static.if_else(condition, on_true, on_false)는 인터프리터 bool 값 condition에 따라 인자 없는 두 분기 중 하나를 컴파일 시점에 고릅니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@legato.compile(backend=get_bertha)
def test_static_if_else():
    device = legato.get_context().get_device()
    with device.get_all_cores():
        condition = True  # constexpr
        x = 0
        x = x - 1

        def on_true():
            return x + 1

        def on_false():
            return x + 2

        legato.static.if_else(condition, on_true, on_false)

        x = -100
        condition = False
        legato.static.if_else(condition, on_true, on_false)

선택된 분기만 생성된 IR에 들어가고, 다른 분기는 완전히 빠집니다.

static.fold와 static.fold_back으로 컴파일 시점 fold

legato.static.fold(iterable, func, initial)는 인터프리터 iterable을 컴파일 시점에 인터프리터 값 하나로 줄입니다. 그 결과는 생성된 IR에 상수로 넣을 수 있습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@legato.compile(backend=get_bertha)
def test_fold():
    device = legato.get_context().get_device()
    total = legato.static.fold(
        legato.range(arith.cast(0, lt.index()), arith.cast(10, lt.index())),
        lambda x, acc: x + acc,
        0,
    )
    with device.get_all_cores():
        x = total

legato.static.fold_back은 같은 reduction을 오른쪽에서 왼쪽으로 수행합니다 (함수가 결합 법칙을 만족하지 않거나 순서가 중요할 때 유용합니다).

컴파일 시점 리스트 다루기: static.empty_list와 static.append

Legato는 리스트를 전부 컴파일 시점에 만들고 변환하는 것을 지원합니다. 이 리스트는 원소 타입 정보를 가지며 컴파일러가 검증합니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@legato.compile(backend=get_bertha)
def test_static_for_each_with_list(to_add: lt.integer("int32"), core_ids: lt.constexpr(lt.list(lt.integer("int64")))):
    device = legato.get_context().get_device()

    # int32의 빈 constexpr 리스트를 만듭니다
    empty_list = legato.static.empty_list(lt.integer("int32"))

    # constexpr Python 리스트를 인터프리터 Legato 리스트로 fold합니다
    casted_core_ids = legato.static.fold(
        core_ids,
        lambda core_id, acc: legato.static.append(acc, arith.cast(core_id, lt.integer("int32"))),
        empty_list,
    )

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

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

API 요약

  • legato.static.for_each(iterable, func): 인터프리터 iterable에 대한 반복문을 컴파일 시점에 펼칩니다. func(elem)은 인터프리터 callable이어야 하며, 컴파일러가 원소마다 그 본문을 호출해 IR을 합성합니다.
  • legato.static.fold(iterable, func, initial): 컴파일 시점의 left-fold이며 인터프리터 결과를 반환합니다. func(elem, acc)는 다음 인터프리터 누적값(accumulator)을 반환합니다.
  • legato.static.fold_back(iterable, func, initial): right-fold 변형입니다(func(acc, elem)).
  • legato.static.empty_list(dtype): 원소 타입이 dtype(컴파일 시점 타입 값)인 빈 인터프리터 리스트를 만듭니다.
  • legato.static.append(list_value, value): 인터프리터 리스트에 value를 추가하며, 원소 타입이 같아야 합니다.
  • legato.static.if_else(condition, if_true, if_false): 컴파일 시점에 한 분기를 골라 실행합니다. 선택된 분기만 IR에 들어갑니다.

각 함수는 인자가 인터프리터(컴파일 시점) 값이어야 합니다. 동적 값을 넘기면 Legato는 "expected interpreted value" 같은 diagnostic이나 타입 불일치 알림을 냅니다.

왜 static evaluation인가?

  • 비용 없는 특수화: epilogue를 켤지, 알고리즘 변형 중 무엇을 고를지 같은 결정을 디바이스 코드에 동적 분기를 넣지 않고 컴파일 시점에 내릴 수 있습니다.
  • 펼쳐진 패턴: 코어별 설정, 고정된 집합에 대한 tiling, 반복되는 IR 조각 생성 같은 흔한 패턴을 for_each로 간결하게 표현하며 완전히 펼칩니다.
  • 더 안전한 메타프로그래밍: Legato는 경계에서 타입과 인터프리터 여부를 검증해 에러를 일찍 잡습니다(예: 컴파일 시점 리스트에 타입이 다른 값을 추가하는 경우).

이는 CuTe의 철학과 같습니다. 컴파일 시점 제어(예: cutlass.range_constexpr, cutlass.const_expr)는 런타임 오버헤드 없이 특수화된 커널을 만들고, 동적 제어는 디바이스에서 실행되는 IR 분기/반복문을 만듭니다. CuTe DSL: Control Flow를 참고하십시오.

권장 사항

  • 경계/데이터를 컴파일 시점에 알 수 있으면 static 구문을, 런타임 입력에 의존하면 dynamic 구문을 쓰십시오.
  • static 람다는 순수하게 유지하십시오(값이나 IR을 만드는 callable을 반환). 런타임에만 있는 상태에 의존하지 마십시오.
  • 컴파일 시점 리스트 계산은 명시적인 원소 타입을 준 legato.static.empty_list에서 시작하고, fold 안에서 legato.static.append로 추가해 constexpr Python 시퀀스를 타입이 있는 인터프리터 리스트로 변환하십시오.

저장소의 관련 예제

  • 이 API를 다루는 테스트는 legato/src/tests/test_static_evaluation.py에 있습니다.
  • 구현은 legato/src/legato/language/operations/static.py에 있습니다.

참고 자료