집합 연산¶
collective는 DeviceMesh의 rank들 사이에서 이루어지는 데이터 교환을 조율합니다.
디바이스 컨텍스트 밖에서 CollectiveGroup을 만든 뒤,
참여하는 각 rank의 코어에서 같은 연산을 같은 순서로 호출하십시오.
여섯 가지 연산은 내부적으로 채널을 사용하지만,
커널에서는 개별 채널이 아니라 그룹을 지정합니다.
현재 구현은 직접 교환(direct exchange) 방식을 사용합니다.
예를 들어 rank가 4개인 all_reduce는 각 입력 전체를 피어 rank 3개에 보내므로, 전송이 모두 12번 일어납니다.
이는 통신 패턴을 설명한 것일 뿐, synchronization barrier나 대역폭 보장을 뜻하지는 않습니다.
예제¶
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 | |
입력과 출력은 각 rank의 로컬 DRAM 텐서입니다.
memcpy가 입력을 SRAM으로 load하고, reduction된 값을 출력에 직접 store합니다.
fused 커널이라면 그 대신, 직접 계산한 SRAM 값을 collective에 넘기고
그 결과를 다음 연산에서 사용할 수 있습니다. 아래의 tp_matmul_all_reduce_two를 참고하십시오.
그룹은 두 with 블록 밖에서 만듭니다.
그래야 따로 trace되는 rank별 프로그램이 그룹의 채널을 공유할 수 있습니다.
코어 블록은 rank마다 직접 작성하십시오.
legato.static.for_each는 한 블록 안에서 연산을 반복할 뿐, 여러 rank에 걸쳐 반복하지는 않기 때문입니다.
제약¶
| 규칙 | 이유 | 어기면 생기는 일 |
|---|---|---|
| 모든 rank가 같은 호출을 같은 순서로 해야 합니다 | k번째 collective는 모든 참여자에서 같은 연산, 같은 root를 갖습니다 | 서로 맞지 않는 호출은 trace 중에 거부되고, 호출이 빠지면 every message needs both가 보고됩니다 |
| 모든 rank가 같은 원소 타입과 shape을 넘겨야 합니다 | 메시지 하나의 payload 타입은 하나뿐입니다 | passes bf16[2, 256], but another rank passed bf16[1, 256] |
| 한 번 보낸 값은 이후에 읽을 수는 있지만 덮어쓸 수는 없습니다 | 컴파일러는 첫 send 이후에 소스 저장 공간을 수정하는 것을 보수적으로 거부합니다 | DIC source storage is modified after first send |
| 마지막 차원이 SRAM word를 온전히 채워야 합니다 | 전송 단위가 128 B word이므로, bf16에서는 64의 배수여야 합니다 | is not a multiple of the 128 B SRAM word |
| 호출을 런타임 루프나 분기 안에 둘 수 없습니다 | 메시지마다 저장 공간과 주소 slot이 컴파일 시점에 예약됩니다 | legato.static.for_each를 안내하는 help |
| 코어마다 한 번씩, 그 코어 자신의 블록에서 호출해야 합니다 | 전송 계층은 채널 연산을 단일 코어 컨텍스트에서 lowering합니다 | call it from each core's own get_core block |
여러 코어에 걸친 그룹은 코어 수만큼의 독립된 collective와 같습니다. lane은 코어 ID가 같은 코어끼리만 짝지어지므로, rank 0의 코어 1은 rank 1의 코어 1과 통신하고, 코어 0과는 결코 통신하지 않습니다.
Payload pieces¶
Legato에는 concat이 없고, view는 보낼 수 없습니다.
그래서 all_gather와 all_to_all은 하나로 합친 텐서가 아니라 **rank마다 값 하나**를 반환하고,
reduce_scatter와 all_to_all은 **rank마다 piece 하나**를 별도의 인자로 받습니다.
값을 합치거나 쪼개는 일은 호출자의 몫이며,
복사의 소스와 목적지로는 쓸 수 있는 legato.tensor.view와 memcpy를 사용해 처리합니다.
all_to_all_two 커널은 이 복사 과정을 코드로 직접 보여 줍니다.
즉 입력 행 j를 rank j로 보낼 piece에 복사하고,
rank r에서 받은 piece를 출력 행 r에 복사합니다.
그룹¶
CollectiveGroup(mesh)와 CollectiveGroup(mesh, None)은 mesh의 활성 코어를 모두 선택합니다.
None은 mesh의 활성 코어에 제한을 두지 않는다는 뜻이므로, 어떤 코어가 선택되는지는 mesh 구성에 따라 정해집니다.
참여할 코어를 고정하려면 코어 ID 하나를 넘기거나, 서로 다른 ID로 이루어진 리스트나 튜플을 넘기십시오.
1 2 3 | |
코어 선택은 컴파일 시점에 확정됩니다. 선택이 비어 있거나, ID가 중복되거나, 비활성 코어 ID가 포함되어 있으면 거부됩니다. 선택된 각 코어는 다른 rank에서 코어 ID가 같은 코어와 통신합니다. 다만 이 경우에도 collective는 선택된 각 코어 자신의 블록에서 호출해야 합니다. 모든 코어를 선택한다고 해서 호출이 자동으로 복제되거나, 코어 ID가 다른 코어 사이에서 값이 reduction되는 것은 아닙니다.
CollectiveGroup¶
1 | |
The participants every collective in this kernel refers to. Call it outside every device context.
Parameters:
mesh: TheComputeModelMeshthis kernel compiles for.cores(int | list[int] | tuple[int, ...] | None): A core ID or a nonempty collection of distinct core IDs. Omitted orNoneselects every active core in the mesh. Call each collective from each selected core's ownget_core(c)block. Default:None.
Rooted operations¶
reduce¶
1 | |
Sum value over every rank onto root.
Parameters:
group(Value): A collective group created bylegato.collective.CollectiveGroup.value(Value): This rank's contribution, with the same element type and shape on every rank.root(Value | int): The rank that receives the sum. Defaults to rank 0. Default:0.
Returns:
- (
Callable[[CodeGenerator], Value | None]): The sum on the root and the originalvalueon other ranks.
broadcast¶
1 | |
Give every rank the root's value.
Parameters:
group(Value): A collective group created bylegato.collective.CollectiveGroup.value(Value): The root's input. Other ranks pass a value with the same element type and shape; its contents are ignored.root(Value | int): The rank supplying the value. Defaults to rank 0. Default:0.
Returns:
- (
Callable[[CodeGenerator], Value | None]): The root's value on every rank.
Symmetric operations¶
all_reduce¶
1 | |
Sum value over every rank.
Parameters:
group(Value): A collective group created bylegato.collective.CollectiveGroup.value(Value): This rank's contribution, with the same element type and shape on every rank.
Returns:
- (
Callable[[CodeGenerator], Value | None]): The sum on every rank, accumulated in source-rank order.
all_gather¶
1 | |
Gather every rank's value on every rank.
Parameters:
group(Value): A collective group created bylegato.collective.CollectiveGroup.value(Value): This rank's contribution, with the same element type and shape on every rank.
Returns:
- (
Callable[[CodeGenerator], Value | None]): A tuple of values in source-rank order, not a concatenated tensor.
reduce_scatter¶
1 | |
Sum piece r over every rank onto rank r.
Parameters:
group(Value): A collective group created bylegato.collective.CollectiveGroup.*pieces(Value): This rank's contributions, one per destination rank in rank order. All pieces on all ranks must have the same element type and shape. Default:().
Returns:
- (
Callable[[CodeGenerator], Value | None]): This rank's reduced piece, accumulated in source-rank order.
all_to_all¶
1 | |
Send piece j to rank j and receive one piece from every rank.
Parameters:
group(Value): A collective group created bylegato.collective.CollectiveGroup.*pieces(Value): This rank's inputs, one per destination rank in rank order. All pieces on all ranks must have the same element type and shape. Default:().
Returns:
- (
Callable[[CodeGenerator], Value | None]): A tuple of received pieces in source-rank order, including this rank's own piece.
수치 특성¶
reduction은 각 rank의 기여분을 소스 rank 순서대로 더합니다.
그 결과 all_reduce에서는 모든 rank의 덧셈 순서가 같아집니다.
bf16 덧셈에서는 결합 법칙이 성립하지 않으므로 이 순서가 중요합니다.
예를 들어 입력이 (256, 1, 1, -256)일 때 각 rank가 자기 기여분부터 더해 나간다면,
rank 3은 rank 0~2와 다른 결과를 얻을 수 있습니다.
Tensor-parallel 예제¶
multi_device_test/dic_collective.py::tp_matmul_all_reduce_two는
커널에서 계산한 SRAM 값을 collective에 직접 넘기는 방법을 보여 줍니다.
각 rank는 X @ W_column[r]로 hidden shard(piece)를 계산한 뒤,
hidden[r] @ W_row[r]로 [10,128] 크기의 부분합을 계산합니다.
all_reduce는 두 부분합을 더해 두 rank 모두에 같은 출력을 돌려줍니다.
tp_matmul_reduce_scatter_all_gather_two는 같은 matmul을 수행한 뒤
각 부분합을 [5,128] piece 두 개로 나눕니다.
reduce_scatter가 서로 대응하는 piece끼리 더해 rank마다 piece 하나씩을 남기고,
all_gather가 그 두 piece를 모두 각 rank에 돌려줍니다.
peer-window 백엔드는 legato.session(transport_backend=backend)로 명시적으로 넘기십시오.
MeshLauncher는 모든 rank를 enqueue한 다음에 런타임 완료를 기다립니다.
이때 시차(stagger)를 두지 않으며, 완료와 정리(cleanup)가 끝난 뒤에 반환합니다.
grant 순서를 보장하거나 하드웨어의 원격 읽기(remote-read) timeout을 늘려 주지는 않습니다.
dense TP 하드웨어 테스트는 RankArgs로 각 rank의 로컬 텐서를 바인딩하고,
MeshPlacement로 rank를 디바이스 번호(ordinal)에 대응시킨 뒤, 출력을 PyTorch 결과와 비교합니다.
할당받은 디바이스 두 개를 대상으로, legato/ 디렉터리에서 실행하십시오.
1 2 3 4 | |
테스트 케이스가 통과했다는 것은 해당 커널과 launch 구성이 검증되었다는 뜻일 뿐, 임의의 launch 시차(skew)나 모든 collective까지 검증되었다는 뜻은 아닙니다.