콘텐츠로 이동

채널 연산

채널은 값을 한 디바이스 유닛에서 다른 유닛으로 옮깁니다. 채널은 깊이 1의 rendezvous FIFO(보내는 쪽과 받는 쪽이 만나야 진행되는 큐)입니다. 즉 write는 같은 lane의 이전 메시지가 소비될 때까지 블로킹되고, read는 메시지가 하나 준비될 때까지 블로킹되며, 메시지는 write한 순서대로 도착합니다. 채널을 정하는 것은 endpoint뿐이며, 채널 자체에는 payload 타입이 없습니다. 그래서 각 write는 건네받은 값을 그대로 보내며, 한 채널에서 연이어 보내는 메시지끼리 dtype과 shape이 달라도 됩니다.

각 텐서 메시지는 lane마다 serving 버퍼(staging 복사를 거친다면 복사한 뒤의 버퍼)와 receiving 버퍼에 대해 타입이 지정된 LayoutMapAttr를 선언합니다. 현재 이 규약에서는 레이아웃이 row-major여야 합니다. producer는 자신의 텐서 레이아웃을 그대로 유지하며, 지원되는 소스 가운데 staging이 필요한 것은 serving 버퍼로 복사됩니다. 할당 과정에서 붙은 padding은 payload로 전송되지 않습니다.

소스 컨텍스트 안에서는 코어 0이 가진 값을 write 연산이 채널로 옮깁니다. 목적지 컨텍스트 안에서는 read 연산이 채널에서 값을 꺼내 top 유닛의 result에 넣습니다.

그림 1 — 채널 하나, 소스에서 목적지로. legato.Channel(src, dst)는 어떤 디바이스 컨텍스트도 열리기 전에 소스 유닛과 목적지 유닛을 짝지어 채널을 만듭니다. 소스 쪽 컨텍스트 안에서는 write가 값을 큐에 넣고, 목적지 쪽 컨텍스트 안에서는 read가 아직 읽지 않은 값 중 가장 오래된 것을 꺼냅니다. 각 호출이 올바른 쪽에서 실행되기만 하면, 큐는 다른 코드와 어떤 순서로 섞여 있든 반복해서 쓰고 읽을 수 있습니다.

소스 컨텍스트에서는 write 호출 하나가 두 활성 유닛을 모두 아우르므로, 코어 0과 코어 1이 각각 가진 값이 공유 write 연산 하나로 들어갑니다. 이 연산은 채널 ch0과 ch1로 fan-out됩니다. 목적지 컨텍스트에서는 read를 채널마다 한 번씩 호출하므로 각 채널이 별도의 read 연산으로 이어지고, 각 read 연산은 top 유닛의 result0 또는 result1에 값을 넣습니다.

그림 2 — write 하나에 채널 여러 개, read는 채널마다 하나. 코어에서 top으로 가는 쌍마다 legato.Channel(src, dst)를 따로 만드십시오. 여러 코어를 묶은 컨텍스트 안에서 write를 한 번 호출하면 문장 하나로 값이 각 코어의 채널에 fan-out됩니다. 반면 device.get_top()은 항상 유닛 하나뿐이므로, top 쪽에서는 채널마다 read를 따로 호출해 읽습니다.

채널 만들기

Channel

1
Channel(src, dst = None) -> Callable[[CodeGenerator], Value | None]

Create a depth-1 rendezvous FIFO between two device executors.

Must be called outside of any device context, so the channel can be shared into both the source-side and the destination-side with blocks.

Parameters:

  • src: The source executor, or the channel's full lanes as an EndpointPair or a sequence of them when dst is omitted.
  • dst: The destination executor. Omit it when src already names the lanes. Default: None.

Returns:

  • (Callable[[CodeGenerator], Value | None]): One channel covering every requested lane.

Example:

1
2
3
4
5
6
7
8
9
@legato.compile(backend=get_backend)
def fn(value: legato.types.integer("int64")):
    device = legato.get_context().get_device()
    channel = legato.Channel(device.get_core(0), device.get_top())
    with device.get_core(0):
        legato.write(channel, value)
    with device.get_top():
        result = legato.read(channel)
        yield result

Write

write

1
write(channels: Value, data: Value) -> Callable[[CodeGenerator], Value | None]

Send one message through the lanes of channels the active context owns.

Must be called from a device context whose units are source endpoints of channels. On a cross-device channel the value's own element type and logical shape become the wire payload, so successive messages need not agree; on a core-to-top channel the value must be an integer scalar.

Parameters:

  • channels (Value): A channel created by legato.Channel(), or a tuple of them.
  • data (Value): The value to send.

Read

read

1
read(channels: Value, payload_type = None) -> Callable[[CodeGenerator], Value | None]

Receive the next message on the lanes of channels the active context owns.

Must be called from a device context whose units are destination endpoints of channels. The k-th read on a lane pairs with its k-th write.

Parameters:

  • channels (Value): A channel created by legato.Channel(), or a tuple of them.
  • payload_type: The expected payload, needed on a cross-device channel only when the matching write has not been traced yet. Default: None.

Returns:

  • (Callable[[CodeGenerator], Value | None]): The received value, or a tuple of them when channels is a tuple.

예제

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@legato.compile(backend=get_backend)
def fn(value: legato.types.integer("int64")):
    device = legato.get_context().get_device()
    channel = legato.Channel(device.get_core(0), device.get_top())

    with device.get_core(0):
        legato.write(channel, value)

    with device.get_top():
        result = legato.read(channel)
        yield result

legato.Channel은 디바이스 컨텍스트 밖에서 호출합니다. 그래야 채널을 소스 쪽과 목적지 쪽 with 블록 모두에서 공유할 수 있습니다. 한 lane의 k번째 read는 그 lane의 k번째 write와 짝이 되므로, 채널 하나는 handshake 한 번이 아니라 일련의 메시지를 차례로 나릅니다.

두 종류의 lane

현재 백엔드가 지원하는 endpoint와 payload 조합은 다음과 같습니다.

Endpoint Payload 런타임 루프
코어와 같은 디바이스의 top 컨텍스트 정수 scalar 허용
서로 다른 rank의 같은 코어 ID 정적 텐서 허용 안 함

이 API로 같은 디바이스의 두 코어를 짝지을 수는 없습니다.

EVT0 텐서 전송에서는 수신 측이 자신의 SRAM 목적지 주소를 export합니다. 런타임은 암묵적인 코어 인자 slot을 통해 이 주소를 송신 측에 전달합니다. 컴파일된 artifact에는 이 피어 주소 binding이 기록됩니다. AddressSlotBinding의 rank / core는 송신 측을, peer_rank / peer_core는 수신 측을 나타냅니다. descriptor ABI 2는 이 방향을 사용하므로, descriptor ABI 1로 만든 캐시된 바이너리와 manifest는 다시 컴파일하십시오.

디바이스 간 lane은 정적으로 스케줄됩니다

디바이스 간 메시지의 소스 SRAM은 컴파일 시점에 예약되므로, 이번 릴리스의 소프트웨어 컴파일러에서는 다음 조건을 지켜야 합니다.

  • 각 lane의 write 횟수와 read 횟수는 컴파일 시점 상수여야 하고 서로 같아야 하며, 한 채널의 모든 lane이 나르는 메시지 수도 같아야 합니다.
  • 두 호출 모두 런타임 루프나 분기 안에 둘 수 없습니다.
  • 짝이 되는 write보다 먼저 trace되는 read는 타입을 가져올 값이 없으므로 payload를 직접 명시해야 합니다.

이 조건들은 현재 lowering 경로에 적용되는 컴파일러 제약입니다. 이번 소프트웨어 릴리스가 컴파일할 수 있는 범위를 설명할 뿐, 하드웨어 자체가 런타임에 의존하는 루프나 분기를 지원할 수 없다는 뜻은 아닙니다.

현재의 저장 공간 진행 검사(storage progress check)는 분기와 루프가 없는 직선 코드(straight-line code)인 각 코어 함수에서 추적 대상 SRAM root를 따라갑니다. 소스를 처음 전송한 뒤에는 그 소스에 쓰는 것을 거부하고, top에서 코어로 가는 정적 공급이 receive 바이트와 맞는지 확인합니다. 다만 전역적인 진행이나 원격 측의 완료까지 증명하지는 않으며, 소스 SRAM은 할당기가 전송용으로 계속 예약해 둡니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
mesh = legato.get_context().get_mesh()
rank0, rank1 = mesh.get_device(0), mesh.get_device(1)
channel = legato.Channel(mesh.pair_cores_by_id(rank0, rank1))

with rank0.get_core(0):
    legato.write(channel, first)
    legato.write(channel, second)

with rank1.get_core(0):
    head = legato.read(channel)
    tail = legato.read(channel)

수신 측이 먼저 trace되는 경우에는 read가 받을 payload를 직접 넘기십시오.

1
2
3
4
with rank1.get_core(0):
    received = legato.read(channel, legato.types.tensor(legato.types.float("bfloat16"), (1, 64)))
with rank0.get_core(0):
    legato.write(channel, value)

여러 lane

legato.Channel(src, dst)는 소스 endpoint 하나에서 목적지 endpoint 하나로 가는 lane 하나를 만듭니다. lane이 여러 개인 채널을 만들려면 EndpointPair 값의 시퀀스를 넘기십시오. 그러면 채널 하나로 rank 쌍의 모든 코어를 아우를 수 있습니다. mesh.pair_cores_by_id는 같은 번호의 코어끼리 짝지은 pointwise 집합을 만들어 주며, write와 read는 활성 컨텍스트가 소유한 lane을 선택합니다.

1
2
3
4
channel = legato.Channel(mesh.pair_cores_by_id(rank0, rank1))

with rank0.get_cores([0, 1]):
    legato.write(channel, value)      # 코어 0과 코어 1의 lane에 씀

코어에서 top으로 가는 lane의 경우에는 쌍을 명시적으로 넘기십시오.

1
2
3
4
5
6
7
channel = legato.Channel([
    legato.EndpointPair(device.get_core(0), top),
    legato.EndpointPair(device.get_core(1), top),
])

with device.get_cores([0, 1]):
    legato.write(channel, value)

여러 코어의 텐서 전송

Bertha EVT0에서는 get_all_cores()나 get_cores(...) 그룹 안에서 텐서 채널을 컴파일할 수 있습니다. 선택된 코어는 각자 자신의 값을 피어 rank의 같은 번호 코어로 보냅니다. 이는 rank 사이에서 코어별로 이루어지는 pointwise 통신이며, 코어 ID가 서로 다른 코어의 값을 합치지는 않습니다.

서로 호환되는 코어는 전송 프로그램 하나를 공유하면서도 export와 import 기록은 코어별로 따로 유지할 수 있습니다. [1, 3]처럼 일부 코어만 선택한 그룹도 지원하며, 선택된 코어를 송신 측 블록과 수신 측 블록에서 서로 다르게 나누어도 됩니다. 앞선 전송 때문에 코어마다 주소 slot이 달라지면, 컴파일러가 필요한 전송 명령어를 분리하고 각 코어의 binding을 보존합니다. slot 번호는 코어마다 따로 매겨집니다. 예를 들어 송신 코어 네 개가 각각 slot 0을 사용할 수 있습니다.

아래 전체 스크립트는 두 rank 사이의 코어 4개 전송을 컴파일한 뒤, ELF 바이너리 두 개를 검사하고 모든 송신 코어의 피어 코어와 바이트 수를 확인합니다. launch는 하지 않으며, 하드웨어에서 수치를 검증했다는 뜻도 아닙니다. channel_multi_core.py를 내려받으십시오. SDK 설정은 예제 실행하기를 참고하십시오.

1
HA_TOOLCHAIN=1 python "$DOCS_ROOT/docs/legato-language/tutorials/code/channel_multi_core.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
"""Compile a four-core EVT0 tensor channel between two ranks without launching."""

import os
from pathlib import Path

import torch

import legato
from legato.model.bertha import BerthaDeviceMesh

OUTPUT = Path(os.environ.get("LEGATO_EXAMPLE_OUTPUT", "legato_example_output"))


@legato.compile(backend=lambda ctx: BerthaDeviceMesh(ctx, "channel_mesh", 2, num_cores=4))
def multi_core_transfer(value: legato.types.tensor(legato.types.float("bfloat16"), (1, 64))):
    """Send each core's tensor to the same-numbered core on the peer rank."""
    mesh = legato.get_context().get_mesh()
    source, peer = mesh.get_device(0), mesh.get_device(1)
    # Pair core N on the source rank with core N on the peer rank.
    channel = legato.Channel(mesh.pair_cores_by_id(source, peer))

    with source.get_all_cores():
        legato.write(channel, value)
    with peer.get_all_cores():
        received = legato.read(channel)
        yield received


def main():
    """Compile both ranks and verify their per-core address-slot bindings."""
    # CPU tensors describe the compiled payload; no device or simulator is initialized.
    value = torch.zeros((1, 64), dtype=torch.bfloat16)
    with legato.session(output_type=legato.OutputType.BINARY, output_path=str(OUTPUT), launch=False):
        # Only rank zero consumes the input argument. The receiver gets its value through the channel.
        multi_core_transfer(legato.RankArgs({0: value}))

    # Compilation produces one ELF binary for each logical rank.
    (artifacts,) = multi_core_transfer.mesh_artifacts.values()
    assert {artifact.rank for artifact in artifacts} == {0, 1}
    for artifact in artifacts:
        assert Path(artifact.path).read_bytes().startswith(b"\x7fELF")

    # Each sender core's slot zero points to the same-numbered receiver core's SRAM.
    bindings = tuple(binding for artifact in artifacts for binding in artifact.address_slot_bindings)
    assert {(b.rank, b.core, b.slot, b.peer_rank, b.peer_core, b.size_bytes) for b in bindings} == {
        (0, core, 0, 1, core, 128) for core in range(4)
    }
    assert {artifact.rank: artifact.address_slot_count for artifact in artifacts} == {0: 1, 1: 0}


if __name__ == "__main__":
    main()

배치 제약

  • write는 채널의 소스 endpoint인 유닛들의 디바이스 컨텍스트에서 실행해야 하고, read는 목적지 endpoint인 유닛들의 컨텍스트에서 실행해야 합니다.
  • 채널은 자신을 만든 컴파일에 속하며, 다른 컴파일에서는 재사용할 수 없습니다.