콘텐츠로 이동

커스텀 연산 API

torch_ha가 torch.ops.lpu 네임스페이스에 등록하는 커스텀 연산입니다. paged KV 캐시용 vmm_* 연산은 VMM API에 있습니다. 시그니처는 등록된 연산 스키마 표기입니다.


레이아웃과 메모리

함수 시그니처 비고
empty_with_kind (SymInt[] size, str kind, SymInt[]? stride=None, *, ScalarType dtype, Device device, int? alignment=None) -> Tensor 디바이스 레이아웃(kind)을 지정해 할당. alignment(바이트, 4096 이상의 2의 거듭제곱)를 주면 스토리지 시작 주소를 그 배수로 정렬
set_storage_meta_ (Tensor t, SymInt[] storage_sizes, SymInt[] storage_strides, SymInt? kind=None) -> () 스토리지 레이아웃 메타데이터를 기록. 칩 정보는 현재 디바이스에서 가져옴. lpu 텐서만 받음
get_storage_meta (Tensor t) -> (SymInt[], SymInt[], str, int?) (storage_sizes, storage_strides, chip, kind). 기록이 없으면 ([], [], "", kind)

set_storage_meta_와 get_storage_meta는 torch.compile이 추적하지 않는 레이아웃 메타데이터를 다루므로, 그래프에 들어가지 않고 break가 발생합니다.

set_storage_meta_는 백엔드 개발용이므로 주의해서 사용하십시오

데이터는 그대로 두고 백엔드가 기록한 레이아웃 정보만 덮어씁니다. 스토리지의 실제 배치와 맞지 않는 값을 넣으면 이후 커널이 잘못된 stride로 버퍼를 읽습니다.

텐서 kind

empty_with_kind가 받는 kind 문자열입니다. 대소문자는 구분하지 않으며, 목록에 없는 이름을 주면 에러가 발생하며 지원되는 목록이 표시됩니다. 괄호 안 숫자는 HaTensorKind 값으로, set_storage_meta_와 get_storage_meta의 kind에 쓰입니다.

kind hart.HaTensorKind 배치 자동 적용
dram_word_interleaved DRAM_WORD_INTERLEAVED (5) DRAM word 단위로 채널에 인터리브 기본값. 그 밖의 텐서와 vmm_create_kv_pool
mpu_tensor MPU_TENSOR (6) MPU 연산용 행렬 레이아웃 —
mpu_tensor_transposed MPU_TENSOR_TRANSPOSED (7) mpu_tensor의 전치 형태. 하드웨어가 전치해 읽으며 matmul 오른쪽 피연산자에 씀 nn.Linear 가중치
single_pass_interleaved SINGLE_PASS_INTERLEAVED (8) 채널마다 전체의 1/N을 연속된 한 덩어리로 배치 nn.Embedding 가중치
row_interleaved ROW_INTERLEAVED (3) 행 단위로 채널에 인터리브 —
max_rows_interleaved MAX_ROWS_INTERLEAVED (4) 여러 행을 한 덩어리로 묶어 채널에 인터리브 —

"자동 적용" 의 경우 텐서를 lpu로 옮기거나 만들 때 따로 지정하지 않아도 붙는 kind입니다. 디바이스 시맨틱 §2.2를 참고하세요.


양자화 가중치

가중치 변환기를 호출하는 연산입니다. 양자화된 가중치는 랭크 1 int8/uint8 텐서(블롭)로 다루고, 블롭의 양자화 방식과 논리 shape·dtype은 quant_weight_stamp_로 기록합니다.

함수 시그니처 비고
quant_weight_pack (Tensor weight, *, Tensor? scale=None, Tensor? weight_zero_point=None, Tensor? bias=None, Tensor? mx_block_scale=None, Tensor? output_zero_point=None, int[] weight_shape, ScalarType weight_dtype, ScalarType output_dtype, str quantization_type="output_channel", int input_channel_group_size=0, bool channel_wise_packing=True, str? architecture=None) -> Tensor 호스트에서 변환해 CPU uint8 블롭을 반환
quant_weight_converted_size (int[] weight_shape, ScalarType weight_dtype, *, bool has_bias, ScalarType output_dtype, str quantization_type="output_channel", int input_channel_group_size=0, str? architecture=None) -> int quant_weight_pack 결과의 바이트 수. 할당 전에 크기를 정할 때 사용
quant_weight_stamp_ (Tensor(a!) self, str quantization_type, int[] logical_shape, ScalarType logical_dtype) -> Tensor(a!) 블롭에 양자화 정책, 논리 shape, 논리 dtype을 기록. 데이터 배치는 바꾸지 않음
quant_weight_meta (Tensor self) -> (str, int[], str) 기록된 (quantization_type, logical_shape, logical_dtype). logical_dtype은 "UInt4" 같은 ScalarType 이름. 기록이 없으면 에러
항목 값
quantization_type (pack, converted_size) "output_channel", "none"
quantization_type (stamp_) "none", "output_channel", "input_channel_wise", "token_wise", "mxfp"
architecture 디바이스가 있으면 생략하십시오. 현재 디바이스를 기준으로 변환하며, 다른 값을 주면 에러
블롭 배치 channel_wise_packing=False 출력은 dram_word_interleaved, True 출력은 single_pass_interleaved로 할당
logical_shape 양수 [K, N], [E, K, N], [r, s, c, m] 중 하나
logical_dtype uint4, int4, uint8, int8, float8_*, float4_e2m1fn_x2

quant_weight_pack은 scale과 weight_zero_point를 출력 채널당 한 값으로 다루므로 input_channel_wise, token_wise, mxfp 정책은 거부합니다. 이 정책들을 쓰려면 가중치 변환기를 직접 호출해야 합니다.


디버깅

안정된 API가 아닙니다

진단용 연산입니다. 시그니처와 반환값이 릴리즈 사이에 바뀔 수 있으므로 상태를 확인하거나 이유를 출력하는 데만 쓰고, 제품 코드의 동작을 이 값에 맞추지 마십시오.

함수 시그니처 비고
eager_status () -> (bool ready, str reason, str[] kernels, str legato, bool built) ready는 eager 커널을 쓸 수 있는지, reason은 쓸 수 없는 이유(쓸 수 있으면 빈 문자열). kernels는 실행할 수 있는 커널 이름, legato는 커널을 빌드한 legato 버전, built는 빌드에 eager 커널이 들어 있는지. ready가 True여도 커널이 받지 않는 dtype이나 shape은 거절됨

eager 커널 경로는 연산 §3.1을 보십시오.


집합 연산 fast path

torch.compile 그래프 안에서 집합 연산을 graph break 없이 캡처하기 위한 연산입니다. 텐서를 받는 lccl_* 연산에는 Meta 커널이 있어 FakeTensor로 트레이싱됩니다. c10d "lccl" 백엔드와 같은 communicator를 씁니다 — 분산 §4.1을 보십시오.

함수 시그니처 비고
lccl_comm_handle (str group_name) -> int 프로세스 그룹의 communicator 핸들. 그룹이 lccl 백엔드가 아니면 에러
lccl_all_reduce (Tensor input, str reduce_op, int comm_handle) -> Tensor out-of-place
lccl_all_reduce_ (Tensor(a!) input, str reduce_op, int comm_handle) -> Tensor(a!) in-place
lccl_broadcast_ (Tensor(a!) tensor, int root, int comm_handle) -> Tensor(a!) in-place
lccl_all_gather (Tensor input, int world_size, int comm_handle) -> Tensor 출력 dim 0이 입력의 world_size배
lccl_reduce_scatter (Tensor input, str reduce_op, int world_size, int comm_handle) -> Tensor 출력 dim 0이 입력의 1/world_size
lccl_reduce (Tensor input, str reduce_op, int root, int comm_handle) -> Tensor root에서만 결과가 유효
lccl_gather (Tensor input, int root, int world_size, int comm_handle) -> Tensor root에 dim 0 방향으로 이어 붙여 모음
lccl_scatter (Tensor input, int root, int world_size, int comm_handle) -> Tensor 이 랭크의 조각을 반환
lccl_all_to_all (Tensor input, int comm_handle) -> Tensor shape와 dtype 유지
lccl_send (Tensor input, int peer, int comm_handle) -> () point-to-point 송신
lccl_recv (Tensor(a!) output, int peer, int comm_handle) -> Tensor(a!) output을 채움
lccl_group_start () -> () 이후 호출하는 point-to-point 연산을 모아 둠
lccl_group_end () -> () 모은 연산을 한 번에 실행

reduce_op에는 "sum", "prod", "max", "min", "avg"를 넘길 수 있습니다. 실제로 지원되는 집합 연산과 리덕션 조합은 LCCL 지원 매트릭스를 보십시오.


예제

eager_status

eager 커널 경로를 쓸 수 없을 때 그 이유를 출력합니다. 이때 import torch 중에도 torch_ha eager kernels are unusable; eager ops will raise: <이유> 경고가 로그에 남습니다.

예제
1
2
3
4
5
import torch

ready, reason = torch.ops.lpu.eager_status()[:2]
if not ready:
    print(reason)  # 예: torch_ha and hart are from different releases; install matching versions (err=…)

empty_with_kind

kind를 지정해 할당하고, 값은 copy_로 채웁니다.

예제
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import torch

w = torch.ops.lpu.empty_with_kind(
    [1024, 1024], "mpu_tensor_transposed", dtype=torch.bfloat16, device="lpu:0"
)
w.copy_(torch.randn(1024, 1024, dtype=torch.bfloat16))

aligned = torch.ops.lpu.empty_with_kind(
    [8192], "dram_word_interleaved", dtype=torch.bfloat16, device="lpu:0",
    alignment=4096,
)

get_storage_meta

기록된 레이아웃 메타데이터를 읽습니다.

예제
1
2
3
4
5
import torch

sizes, strides, chip, kind = torch.ops.lpu.get_storage_meta(t)
if not chip:
    print("기록된 메타데이터 없음")

lccl_all_gather

각 랭크의 텐서를 dim 0으로 이어 붙입니다.

예제
1
2
3
4
5
import torch
import torch.distributed as dist

handle = torch.ops.lpu.lccl_comm_handle(dist.group.WORLD.group_name)
out = torch.ops.lpu.lccl_all_gather(x, dist.get_world_size(), handle)

lccl_all_reduce

결과를 새 텐서로 돌려줍니다.

예제
1
2
3
4
5
import torch
import torch.distributed as dist

handle = torch.ops.lpu.lccl_comm_handle(dist.group.WORLD.group_name)
out = torch.ops.lpu.lccl_all_reduce(x, "sum", handle)

lccl_all_reduce_

입력 텐서를 결과로 덮어씁니다.

예제
1
2
3
import torch

torch.ops.lpu.lccl_all_reduce_(x, "sum", handle)

lccl_all_to_all

shape와 dtype은 그대로 두고 랭크 사이에 조각을 교환합니다.

예제
1
2
3
import torch

out = torch.ops.lpu.lccl_all_to_all(x, handle)

lccl_broadcast_

root의 값으로 모든 랭크의 텐서를 덮어씁니다.

예제
1
2
3
import torch

torch.ops.lpu.lccl_broadcast_(x, 0, handle)

lccl_comm_handle

프로세스 그룹 이름으로 핸들을 얻어 lccl_* 연산에 넘깁니다.

예제
1
2
3
4
5
6
import torch
import torch.distributed as dist

dist.init_process_group("lccl")
group_name = dist.distributed_c10d._get_default_group().group_name
handle = torch.ops.lpu.lccl_comm_handle(group_name)

lccl_gather

모든 랭크의 텐서를 root에 dim 0으로 모읍니다.

예제
1
2
3
4
import torch
import torch.distributed as dist

out = torch.ops.lpu.lccl_gather(x, 0, dist.get_world_size(), handle)

lccl_group_end

lccl_group_start 이후 모은 point-to-point 연산을 실행합니다.

예제
1
2
3
4
5
6
import torch

torch.ops.lpu.lccl_group_start()
torch.ops.lpu.lccl_send(x, peer, handle)
torch.ops.lpu.lccl_recv(y, peer, handle)
torch.ops.lpu.lccl_group_end()

lccl_group_start

양방향 교환은 그룹으로 감싸야 교착 상태에 빠지지 않습니다.

예제
1
2
3
4
5
6
import torch

torch.ops.lpu.lccl_group_start()
torch.ops.lpu.lccl_send(x, peer, handle)
torch.ops.lpu.lccl_recv(y, peer, handle)
torch.ops.lpu.lccl_group_end()

lccl_recv

미리 할당한 output을 채웁니다.

예제
1
2
3
4
import torch

y = torch.empty(4, 8, dtype=torch.bfloat16).to("lpu")
torch.ops.lpu.lccl_recv(y, src_rank, handle)

lccl_reduce

root가 아닌 랭크의 결과는 정의되지 않습니다.

예제
1
2
3
4
5
6
import torch
import torch.distributed as dist

out = torch.ops.lpu.lccl_reduce(x, "sum", 0, handle)
if dist.get_rank() == 0:
    print(out.cpu())

lccl_reduce_scatter

리덕션 결과 중 이 랭크의 조각만 돌려줍니다.

예제
1
2
3
4
import torch
import torch.distributed as dist

out = torch.ops.lpu.lccl_reduce_scatter(x, "sum", dist.get_world_size(), handle)

lccl_scatter

root의 버퍼를 나눠 이 랭크의 조각을 돌려줍니다.

예제
1
2
3
4
import torch
import torch.distributed as dist

out = torch.ops.lpu.lccl_scatter(x, 0, dist.get_world_size(), handle)

lccl_send

텐서 전체를 peer로 보냅니다.

예제
1
2
3
import torch

torch.ops.lpu.lccl_send(x, dst_rank, handle)

quant_weight_converted_size

블롭을 할당하기 전에 필요한 바이트 수를 구합니다.

예제
1
2
3
4
5
import torch

nbytes = torch.ops.lpu.quant_weight_converted_size(
    [K, N], torch.uint4, has_bias=True, output_dtype=torch.bfloat16
)

quant_weight_meta

기록된 양자화 정보를 읽습니다.

예제
1
2
3
4
import torch

policy, shape, dtype = torch.ops.lpu.quant_weight_meta(w)
# ("output_channel", [K, N], "UInt4")

quant_weight_pack

양자화된 가중치를 호스트에서 블롭으로 변환합니다.

예제
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import torch

blob = torch.ops.lpu.quant_weight_pack(
    packed_uint4,                 # uint4 두 개를 바이트 하나에 담은 가중치
    scale=scale,
    weight_zero_point=zero_point,
    bias=bias,
    weight_shape=[K, N],
    weight_dtype=torch.uint4,
    output_dtype=torch.bfloat16,
    channel_wise_packing=False,
)

quant_weight_stamp_

블롭을 알맞은 kind로 디바이스에 올린 뒤 양자화 정보를 기록합니다.

예제
1
2
3
4
5
6
7
import torch

w = torch.ops.lpu.empty_with_kind(
    [blob.numel()], "dram_word_interleaved", dtype=torch.int8, device="lpu:0"
)
w.copy_(blob.view(torch.int8))
torch.ops.lpu.quant_weight_stamp_(w, "output_channel", [K, N], torch.uint4)

set_storage_meta_

스토리지 레이아웃 메타데이터를 직접 기록합니다. 백엔드 개발용입니다.

예제
1
2
3
4
5
6
import hart
import torch

torch.ops.lpu.set_storage_meta_(
    t, [8, 512], [512, 1], kind=hart.HaTensorKind.DRAM_WORD_INTERLEAVED.value
)

함께 보기