다음은 XlaBuilder
인터페이스에 정의된 작업의 의미 체계를 설명합니다. 일반적으로 이러한 작업은 xla_data.proto
의 RPC 인터페이스에 정의된 작업에 일대일로 매핑됩니다.
명명법에 대한 참고 사항: XLA가 다루는 일반화된 데이터 유형은 일부 균일 유형(예: 32비트 부동 소수점)의 요소를 포함하는 N차원 배열입니다. 문서 전체에서 배열은 임의 차원 배열을 나타내는 데 사용됩니다. 편의를 위해 특별한 경우에는 보다 구체적이고 친숙한 이름이 사용됩니다. 예를 들어 벡터 는 1차원 배열이고 행렬 은 2차원 배열입니다.
결국
XlaBuilder::AfterAll
도 참조하십시오.
AfterAll은 다양한 수의 토큰을 가져와 단일 토큰을 생성합니다. 토큰은 순서를 강제하기 위해 부작용 작업 사이에 스레드될 수 있는 기본 유형입니다. AfterAll
집합 작업 후 작업을 주문하기 위한 토큰의 조인으로 사용할 수 있습니다.
AfterAll(operands)
인수 | 유형 | 의미론 |
---|---|---|
operands | XlaOp | 가변적인 토큰 수 |
올게더
XlaBuilder::AllGather
도 참조하십시오.
복제본 간에 연결을 수행합니다.
AllGather(operand, all_gather_dim, shard_count, replica_group_ids, channel_id)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 복제본 간에 연결할 배열입니다. |
all_gather_dim | int64 | 연결 차원. |
replica_groups | int64 의 벡터로 구성된 벡터 | 연결이 수행되는 그룹입니다. |
channel_id | 선택적 int64 | 모듈 간 통신을 위한 선택적 채널 ID입니다. |
-
replica_groups
는 연결이 수행되는 복제본 그룹 목록입니다(현재 복제본의 복제 ID는ReplicaId
사용하여 검색할 수 있음). 각 그룹의 복제본 순서는 입력이 결과에 있는 순서를 결정합니다.replica_groups
비어 있거나(이 경우 모든 복제본은0
부터N - 1
순서가 지정된 단일 그룹에 속함) 복제본 수와 동일한 수의 요소를 포함해야 합니다. 예를 들어,replica_groups = {0, 2}, {1, 3}
복제본0
과2
,1
과3
간에 연결을 수행합니다. -
shard_count
는 각 복제본 그룹의 크기입니다.replica_groups
비어 있는 경우에 필요합니다. -
channel_id
모듈 간 통신에 사용됩니다.channel_id
동일한all-gather
작업만 서로 통신할 수 있습니다.
출력 형태는 all_gather_dim
이 shard_count
배 더 큰 입력 형태입니다. 예를 들어 두 개의 복제본이 있고 피연산자의 값이 두 복제본에서 각각 [1.0, 2.5]
및 [3.0, 5.25]
인 경우 all_gather_dim
이 0
인 이 op의 출력 값은 [1.0, 2.5, 3.0, 5.25]
됩니다. [1.0, 2.5, 3.0, 5.25]
두 복제본 모두에서.
올리듀스
XlaBuilder::AllReduce
도 참조하십시오.
복제본 전체에서 사용자 지정 계산을 수행합니다.
AllReduce(operand, computation, replica_group_ids, channel_id)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 복제본 전체에서 줄이기 위한 어레이 또는 비어 있지 않은 어레이 튜플. |
computation | XlaComputation | 축소 계산 |
replica_groups | int64 의 벡터로 구성된 벡터 | 감소가 수행되는 그룹 |
channel_id | 선택적 int64 | 모듈 간 통신을 위한 선택적 채널 ID |
-
operand
배열의 튜플인 경우 튜플의 각 요소에 대해 모두 축소가 수행됩니다. -
replica_groups
축소가 수행되는 복제본 그룹 목록입니다(현재 복제본의 복제 ID는ReplicaId
사용하여 검색할 수 있음).replica_groups
비어 있거나(이 경우 모든 복제본이 단일 그룹에 속함) 복제본 수와 동일한 수의 요소를 포함해야 합니다. 예를 들어,replica_groups = {0, 2}, {1, 3}
복제본0
과2
,1
과3
사이에서 축소를 수행합니다. -
channel_id
모듈 간 통신에 사용됩니다.channel_id
동일한all-reduce
작업만 서로 통신할 수 있습니다.
출력 형태는 입력 형태와 동일합니다. 예를 들어 두 개의 복제본이 있고 피연산자의 값이 두 복제본에서 각각 [1.0, 2.5]
및 [3.0, 5.25]
인 경우 이 연산 및 합계 계산의 출력 값은 둘 다에서 [4.0, 7.75]
가 됩니다. 복제품. 입력이 튜플이면 출력도 튜플입니다.
AllReduce
의 결과를 계산하려면 각 복제본에서 하나의 입력이 필요하므로 한 복제본이 다른 복제본보다 AllReduce
노드를 더 많이 실행하면 이전 복제본은 영원히 대기합니다. 복제본이 모두 동일한 프로그램을 실행하고 있기 때문에 발생하는 방법은 많지 않지만 while 루프의 조건이 인피드의 데이터에 따라 달라지고 입력된 데이터로 인해 while 루프가 더 많이 반복되는 경우가 가능합니다. 다른 복제본보다 한 복제본에서.
모두모두
XlaBuilder::AllToAll
도 참조하십시오.
AllToAll은 모든 코어에서 모든 코어로 데이터를 보내는 집합 작업입니다. 두 단계가 있습니다.
- 산란 단계. 각 코어에서 피연산자는
split_dimensions
따라split_count
수의 블록으로 분할되고 블록은 모든 코어로 분산됩니다. 예를 들어 i번째 블록은 i번째 코어로 전송됩니다. - 수집 단계. 각 코어는
concat_dimension
따라 수신된 블록을 연결합니다.
참여 코어는 다음과 같이 구성할 수 있습니다.
-
replica_groups
: 각 ReplicaGroup에는 계산에 참여하는 복제 ID 목록이 포함됩니다(현재 복제본의 복제 ID는ReplicaId
사용하여 검색할 수 있음). AllToAll은 지정된 순서로 하위 그룹 내에서 적용됩니다. 예를 들어,replica_groups = { {1,2,3}, {4,5,0} }
복제본{1, 2, 3}
내에서 그리고 수집 단계에서 AllToAll이 적용되고 수신된 블록이 그러면 복제본 4, 5, 0 내에서 또 다른 AllToAll이 적용되고 연결 순서도 4, 5, 0이 됩니다.replica_groups
가 비어 있으면 모든 복제본은 하나에 속합니다. 그룹, 모양의 연결 순서대로.
전제 조건:
-
split_dimension
에서 피연산자의 차원 크기는split_count
로 나눌 수 있습니다. - 피연산자의 모양이 튜플이 아닙니다.
AllToAll(operand, split_dimension, concat_dimension, split_count, replica_groups)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | n차원 입력 배열 |
split_dimension | int64 | 피연산자가 분할되는 차원의 이름을 지정하는 간격 [0, n) 의 값 |
concat_dimension | int64 | 분할 블록이 연결되는 차원의 이름을 지정하는 간격 [0, n) 의 값 |
split_count | int64 | 이 작업에 참여하는 코어 수입니다. replica_groups 가 비어 있으면 복제본의 수여야 합니다. 그렇지 않으면 각 그룹의 복제본 수와 같아야 합니다. |
replica_groups | ReplicaGroup 벡터 | 각 그룹에는 복제 ID 목록이 포함되어 있습니다. |
아래는 Alltoall의 예를 보여줍니다.
XlaBuilder b("alltoall");
auto x = Parameter(&b, 0, ShapeUtil::MakeShape(F32, {4, 16}), "x");
AllToAll(x, /*split_dimension=*/1, /*concat_dimension=*/0, /*split_count=*/4);

이 예에서는 Alltoall에 참여하는 4개의 코어가 있습니다. 각 코어에서 피연산자는 차원 1을 따라 4개의 부분으로 분할되므로 각 부분의 모양은 f32[4,4]입니다. 4개의 부품이 모든 코어에 흩어져 있습니다. 그런 다음 각 코어는 수신된 부품을 차원 0을 따라 코어 0-4 순서로 연결합니다. 따라서 각 코어의 출력은 모양이 f32[16,4]입니다.
BatchNormGrad
알고리즘에 대한 자세한 설명은 XlaBuilder::BatchNormGrad
및 원본 배치 정규화 문서를 참조하십시오.
배치 노름의 변화도를 계산합니다.
BatchNormGrad(operand, scale, mean, variance, grad_output, epsilon, feature_index)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 정규화할 n차원 배열(x) |
scale | XlaOp | 1차원 배열(\(\gamma\)) |
mean | XlaOp | 1차원 배열(\(\mu\)) |
variance | XlaOp | 1차원 배열(\(\sigma^2\)) |
grad_output | XlaOp | BatchNormTraining (\( \nabla y\))에 전달된 기울기 |
epsilon | float | 엡실론 값(\(\epsilon\)) |
feature_index | int64 | operand 의 기능 차원에 대한 인덱스 |
기능 차원의 각 기능에 대해( feature_index
operand
에 있는 기능 차원의 인덱스임) 연산은 다른 모든 차원에서 operand
, offset
및 scale
에 대한 그래디언트를 계산합니다. feature_index
는 operand
의 기능 차원에 대한 유효한 인덱스여야 합니다.
세 가지 기울기는 다음 공식으로 정의됩니다(4차원 배열을 operand
차원 인덱스 l
, 배치 크기 m
및 공간 크기 w
및 h
로 4차원 배열을 피연산자로 가정).
\[ \begin{split} c_l&= \frac{1}{mwh}\sum_{i=1}^m\sum_{j=1}^w\sum_{k=1}^h \left( \nabla y_{ijkl} \frac{x_{ijkl} - \mu_l}{\sigma^2_l+\epsilon} \right) \\\\ d_l&= \frac{1}{mwh}\sum_{i=1}^m\sum_{j=1}^w\sum_{k=1}^h \nabla y_{ijkl} \\\\ \nabla x_{ijkl} &= \frac{\gamma_{l} }{\sqrt{\sigma^2_{l}+\epsilon} } \left( \nabla y_{ijkl} - d_l - c_l (x_{ijkl} - \mu_{l}) \right) \\\\ \nabla \gamma_l &= \sum_{i=1}^m\sum_{j=1}^w\sum_{k=1}^h \left( \nabla y_{ijkl} \frac{x_{ijkl} - \mu_l}{\sqrt{\sigma^2_{l}+\epsilon} } \right) \\\\\ \nabla \beta_l &= \sum_{i=1}^m\sum_{j=1}^w\sum_{k=1}^h \nabla y_{ijkl} \end{split} \]
입력 mean
및 variance
배치 및 공간 차원에서 모멘트 값을 나타냅니다.
출력 유형은 세 개의 핸들로 구성된 튜플입니다.
출력 | 유형 | 의미론 |
---|---|---|
grad_operand | XlaOp | 입력 operand 에 대한 기울기(\( \nabla x\)) |
grad_scale | XlaOp | 입력 scale 에 대한 기울기(\( \nabla \gamma\)) |
grad_offset | XlaOp | 입력 offset 에 대한 기울기(\( \nabla \beta\)) |
BatchNormInference
알고리즘에 대한 자세한 설명은 XlaBuilder::BatchNormInference
및 원본 배치 정규화 문서를 참조하십시오.
배치 및 공간 차원에서 배열을 정규화합니다.
BatchNormInference(operand, scale, offset, mean, variance, epsilon, feature_index)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 정규화할 n차원 배열 |
scale | XlaOp | 1차원 배열 |
offset | XlaOp | 1차원 배열 |
mean | XlaOp | 1차원 배열 |
variance | XlaOp | 1차원 배열 |
epsilon | float | 엡실론 값 |
feature_index | int64 | operand 의 기능 차원에 대한 인덱스 |
기능 차원의 각 기능에 대해( feature_index
는 operand
의 피처 인덱스임) 작업은 다른 모든 차원의 평균과 분산을 계산하고 평균과 분산을 사용하여 operand
의 각 요소를 정규화합니다. feature_index
는 operand
의 기능 차원에 대한 유효한 인덱스여야 합니다.
BatchNormInference
각 배치에 대한 mean
및 variance
계산하지 않고 BatchNormTraining
호출하는 것과 같습니다. 대신 입력 mean
과 variance
추정값으로 사용합니다. 이 작업의 목적은 추론의 대기 시간을 줄이는 것이므로 이름은 BatchNormInference
입니다.
출력은 입력 operand
와 모양이 같은 n차원의 정규화된 배열입니다.
BatchNormTraining
알고리즘에 대한 자세한 설명은 XlaBuilder::BatchNormTraining
및 the original batch normalization paper
참조하십시오.
배치 및 공간 차원에서 배열을 정규화합니다.
BatchNormTraining(operand, scale, offset, epsilon, feature_index)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 정규화할 n차원 배열(x) |
scale | XlaOp | 1차원 배열(\(\gamma\)) |
offset | XlaOp | 1차원 배열(\(\beta\)) |
epsilon | float | 엡실론 값(\(\epsilon\)) |
feature_index | int64 | operand 의 기능 차원에 대한 인덱스 |
기능 차원의 각 기능에 대해( feature_index
는 operand
의 피처 인덱스임) 작업은 다른 모든 차원의 평균과 분산을 계산하고 평균과 분산을 사용하여 operand
의 각 요소를 정규화합니다. feature_index
는 operand
의 기능 차원에 대한 유효한 인덱스여야 합니다.
알고리즘은 공간 차원의 크기로 w
및 h
가 있는 m
요소를 포함하는 operand
\(x\) 의 각 배치에 대해 다음과 같이 진행됩니다( operand
4차원 배열이라고 가정).
기능 차원의 각 기능
l
에 대한 배치 평균 \(\mu_l\) 계산합니다:\(\mu_l=\frac{1}{mwh}\sum_{i=1}^m\sum_{j=1}^w\sum_{k=1}^h x_{ijkl}\)배치 분산 계산 \(\sigma^2_l\):\(\sigma^2_l=\frac{1}{mwh}\sum_{i=1}^m\sum_{j=1}^w\sum_{k=1}^h (x_{ijkl} - \mu_l)^2\)
정규화, 크기 조정 및 이동:\(y_{ijkl}=\frac{\gamma_l(x_{ijkl}-\mu_l)}{\sqrt[2]{\sigma^2_l+\epsilon} }+\beta_l\)
일반적으로 작은 숫자인 엡실론 값이 0으로 나누기 오류를 방지하기 위해 추가됩니다.
출력 유형은 세 XlaOp
의 튜플입니다.
출력 | 유형 | 의미론 |
---|---|---|
output | XlaOp | 입력 operand (y)와 모양이 같은 n차원 배열 |
batch_mean | XlaOp | 1차원 배열(\(\mu\)) |
batch_var | XlaOp | 1차원 배열(\(\sigma^2\)) |
batch_mean
및 batch_var
위의 공식을 사용하여 배치 및 공간 차원에서 계산된 모멘트입니다.
BitcastConvertType
XlaBuilder::BitcastConvertType
도 참조하십시오.
TensorFlow의 tf.bitcast
와 유사하게 데이터 셰이프에서 대상 셰이프로 요소별 비트캐스트 작업을 수행합니다. 입력 및 출력 크기는 일치해야 합니다. 예를 들어 s32
요소는 비트캐스트 루틴을 통해 f32
요소가 되고 하나의 s32
요소는 4개의 s8
요소가 됩니다. Bitcast는 낮은 수준의 캐스트로 구현되므로 부동 소수점 표현이 다른 기계는 다른 결과를 제공합니다.
BitcastConvertType(operand, new_element_type)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 희미한 D가 있는 유형 T의 배열 |
new_element_type | PrimitiveType | 유형 U |
피연산자의 크기와 대상 모양이 일치해야 하며 변환 전후에 프리미티브 크기의 비율로 변경되는 마지막 차원을 제외하고는 일치해야 합니다.
소스 및 대상 요소 유형은 튜플이 아니어야 합니다.
폭이 다른 프리미티브 타입으로 비트캐스트 변환
BitcastConvert
HLO 명령은 출력 요소 유형 T'
의 크기가 입력 요소 T
의 크기와 같지 않은 경우를 지원합니다. 전체 작업은 개념적으로 비트캐스트이며 기본 바이트를 변경하지 않으므로 출력 요소의 모양이 변경되어야 합니다. B = sizeof(T), B' = sizeof(T')
의 경우 두 가지 가능한 경우가 있습니다.
먼저, B > B'
일 때 출력 모양은 B/B'
크기의 새로운 최하위 차원을 얻습니다. 예를 들어:
f16[10,2]{1,0} %output = f16[10,2]{1,0} bitcast-convert(f32[10]{0} %input)
규칙은 유효 스칼라에 대해 동일하게 유지됩니다.
f16[2]{0} %output = f16[2]{0} bitcast-convert(f32[] %input)
또는 B' > B
의 경우 명령어는 입력 형태의 마지막 논리 차원이 B'/B
와 같아야 하며 이 차원은 변환 중에 삭제됩니다.
f32[10]{0} %output = f32[10]{0} bitcast-convert(f16[10,2]{1,0} %input)
서로 다른 비트폭 간의 변환은 요소별로 이루어지지 않습니다.
방송
XlaBuilder::Broadcast
참조하십시오.
배열의 데이터를 복제하여 배열에 차원을 추가합니다.
Broadcast(operand, broadcast_sizes)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 복제할 배열 |
broadcast_sizes | ArraySlice<int64> | 새 차원의 크기 |
새 차원은 왼쪽에 삽입됩니다. 즉, broadcast_sizes
값이 {a0, ..., aN}
이고 피연산자 모양이 차원 {b0, ..., bM}
이면 출력의 모양은 차원 {a0, ..., aN, b0, ..., bM}
.
새 차원은 피연산자의 복사본으로 인덱스합니다.
output[i0, ..., iN, j0, ..., jM] = operand[j0, ..., jM]
예를 들어 operand
값이 2.0f
인 스칼라 f32
이고 broadcast_sizes
{2, 3}
인 경우 결과는 모양이 f32[2, 3]
인 배열이 되고 결과의 모든 값은 2.0f
가 됩니다.
BroadcastInDim
XlaBuilder::BroadcastInDim
도 참조하십시오.
배열의 데이터를 복제하여 배열의 크기와 순위를 확장합니다.
BroadcastInDim(operand, out_dim_size, broadcast_dimensions)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 복제할 배열 |
out_dim_size | ArraySlice<int64> | 대상 형상의 치수 크기 |
broadcast_dimensions | ArraySlice<int64> | 피연산자 모양의 각 차원이 해당하는 대상 모양의 차원 |
브로드캐스트와 유사하지만 차원을 아무 곳에나 추가하고 크기 1로 기존 차원을 확장할 수 있습니다.
operand
out_dim_size
에서 설명하는 모양으로 브로드캐스트됩니다. broadcast_dimensions
대상 모양의 차원에 operand
의 크기를 매핑합니다. 즉, 피연산자의 i번째 차원은 출력 모양의 broadcast_dimension[i]번째 차원에 매핑됩니다. operand
의 차원은 크기가 1이거나 매핑되는 출력 모양의 차원과 같은 크기여야 합니다. 나머지 차원은 크기 1의 차원으로 채워집니다. Degenerate-dimension 브로드캐스트는 이러한 degenerate 차원을 따라 브로드캐스트하여 출력 모양에 도달합니다. 의미 체계는 방송 페이지 에 자세히 설명되어 있습니다.
부르다
XlaBuilder::Call
도 참조하십시오.
주어진 인수로 계산을 호출합니다.
Call(computation, args...)
인수 | 유형 | 의미론 |
---|---|---|
computation | XlaComputation | 임의 유형의 N 매개변수를 사용하여 T_0, T_1, ..., T_{N-1} -> S 유형 계산 |
args | N XlaOp 의 시퀀스 | 임의 유형의 N 인수 |
args
의 개수와 유형은 computation
변수와 일치해야 합니다. args
없을 수 있습니다.
촐레스키
XlaBuilder::Cholesky
도 참조하십시오.
대칭(Hermitian) 양의 정부호 행렬 배치의 Cholesky 분해를 계산합니다.
Cholesky(a, lower)
인수 | 유형 | 의미론 |
---|---|---|
a | XlaOp | 복소수 또는 부동 소수점 유형의 rank > 2 배열. |
lower | bool | a 의 위쪽 또는 아래쪽 삼각형을 사용할지 여부. |
lower
가 true
이면 \( a = l
. l^T \)과 같은 하부 삼각 행렬 l
계산합니다. lower
가 false
이면 \( a = u^T . u \)와 같은 상위 삼각 행렬 u
를 계산합니다.
입력 데이터는 lower
의 값에 따라 a
의 아래/위 삼각형에서만 읽습니다. 다른 삼각형의 값은 무시됩니다. 출력 데이터는 동일한 삼각형으로 반환됩니다. 다른 삼각형의 값은 구현에 따라 정의되며 무엇이든 될 수 있습니다.
a
의 순위가 2보다 크면 a
행렬의 배치로 취급되며 여기서 마이너 2 차원을 제외한 모든 차원은 배치 차원입니다.
a
대칭(Hermitian) 양의 정부호가 아닌 경우 결과는 구현에 따라 정의됩니다.
집게
XlaBuilder::Clamp
도 참조하십시오.
최소값과 최대값 사이의 범위 내로 피연산자를 고정합니다.
Clamp(min, operand, max)
인수 | 유형 | 의미론 |
---|---|---|
min | XlaOp | T 유형의 배열 |
operand | XlaOp | T 유형의 배열 |
max | XlaOp | T 유형의 배열 |
피연산자와 최소값 및 최대값이 주어지면 최소값과 최대값 사이의 범위에 있으면 피연산자를 반환하고, 그렇지 않으면 피연산자가 이 범위 미만이면 최소값을 반환하고 피연산자가 이 범위를 초과하면 최대값을 반환합니다. 즉, clamp(a, x, b) = min(max(a, x), b)
.
3개의 어레이는 모두 모양이 동일해야 합니다. 대안으로, broadcast 의 제한된 형식으로 min
및/또는 max
는 T
유형의 스칼라일 수 있습니다.
스칼라 min
및 max
의 예:
let operand: s32[3] = {-1, 5, 9};
let min: s32 = 0;
let max: s32 = 6;
==>
Clamp(min, operand, max) = s32[3]{0, 5, 6};
무너지다
XlaBuilder::Collapse
및 tf.reshape
작업도 참조하십시오.
배열의 차원을 하나의 차원으로 축소합니다.
Collapse(operand, dimensions)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | T 유형의 배열 |
dimensions | int64 벡터 | T 차원의 순서대로 연속적인 하위 집합입니다. |
축소는 피연산자 차원의 지정된 하위 집합을 단일 차원으로 바꿉니다. 입력 인수는 T 유형의 임의 배열과 차원 인덱스의 컴파일 타임 상수 벡터입니다. 차원 인덱스는 순서대로(낮은 차원 번호에서 높은 차원 번호로) T 차원의 연속적인 하위 집합이어야 합니다. 따라서 {0, 1, 2}, {0, 1} 또는 {1, 2}는 모두 유효한 차원 집합이지만 {1, 0} 또는 {0, 2}는 그렇지 않습니다. 이들은 원래 치수 크기의 곱과 동일한 새 치수 크기로 치수 순서에서 동일한 위치에 있는 하나의 새 치수로 대체됩니다. dimensions
에서 가장 낮은 차원 번호는 이러한 차원을 축소하는 루프 중첩에서 가장 느리게 변하는 차원(가장 큰 차원)이고 가장 높은 차원 번호는 가장 빠르게 변하는 차원(가장 작은 차원)입니다. 보다 일반적인 접기 순서가 필요한 경우 tf.reshape
연산자를 참조하십시오.
예를 들어 v가 24개 요소의 배열이라고 가정합니다.
let v = f32[4x2x3] { { {10, 11, 12}, {15, 16, 17} },
{ {20, 21, 22}, {25, 26, 27} },
{ {30, 31, 32}, {35, 36, 37} },
{ {40, 41, 42}, {45, 46, 47} } };
// Collapse to a single dimension, leaving one dimension.
let v012 = Collapse(v, {0,1,2});
then v012 == f32[24] {10, 11, 12, 15, 16, 17,
20, 21, 22, 25, 26, 27,
30, 31, 32, 35, 36, 37,
40, 41, 42, 45, 46, 47};
// Collapse the two lower dimensions, leaving two dimensions.
let v01 = Collapse(v, {0,1});
then v01 == f32[4x6] { {10, 11, 12, 15, 16, 17},
{20, 21, 22, 25, 26, 27},
{30, 31, 32, 35, 36, 37},
{40, 41, 42, 45, 46, 47} };
// Collapse the two higher dimensions, leaving two dimensions.
let v12 = Collapse(v, {1,2});
then v12 == f32[8x3] { {10, 11, 12},
{15, 16, 17},
{20, 21, 22},
{25, 26, 27},
{30, 31, 32},
{35, 36, 37},
{40, 41, 42},
{45, 46, 47} };
CollectivePermute
XlaBuilder::CollectivePermute
도 참조하십시오.
CollectivePermute는 데이터 교차 복제본을 송수신하는 집합 작업입니다.
CollectivePermute(operand, source_target_pairs)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | n차원 입력 배열 |
source_target_pairs | <int64, int64> 벡터 | (source_replica_id, target_replica_id) 쌍의 목록입니다. 각 쌍에 대해 피연산자는 원본 복제본에서 대상 복제본으로 전송됩니다. |
source_target_pair
에는 다음과 같은 제한 사항이 있습니다.
- 두 쌍은 동일한 대상 복제본 ID를 가져서는 안 되며 동일한 원본 복제본 ID를 가져서도 안 됩니다.
- 레플리카 ID가 쌍의 대상이 아닌 경우 해당 레플리카의 출력은 입력과 동일한 모양의 0(s)으로 구성된 텐서입니다.
사슬 같이 잇다
XlaBuilder::ConcatInDim
도 참조하십시오.
Concatenate는 여러 배열 피연산자에서 배열을 구성합니다. 배열은 각 입력 배열 피연산자와 동일한 순위(서로 동일한 순위여야 함)이며 지정된 순서대로 인수를 포함합니다.
Concatenate(operands..., dimension)
인수 | 유형 | 의미론 |
---|---|---|
operands | N XlaOp 의 시퀀스 | 차원이 [L0, L1, ...]인 T 유형의 N 배열. N >= 1이 필요합니다. |
dimension | int64 | operands 간에 연결할 차원의 이름을 지정하는 간격 [0, N) 의 값입니다. |
dimension
를 제외하고 모든 치수는 동일해야 합니다. 이는 XLA가 "비정형" 배열을 지원하지 않기 때문입니다. 또한 순위 0 값은 연결할 수 없습니다(연결이 발생하는 차원의 이름을 지정할 수 없기 때문).
1차원 예:
Concat({ {2, 3}, {4, 5}, {6, 7} }, 0)
>>> {2, 3, 4, 5, 6, 7}
2차원 예:
let a = {
{1, 2},
{3, 4},
{5, 6},
};
let b = {
{7, 8},
};
Concat({a, b}, 0)
>>> {
{1, 2},
{3, 4},
{5, 6},
{7, 8},
}
도표:

가정 어구
XlaBuilder::Conditional
도 참조하십시오.
Conditional(pred, true_operand, true_computation, false_operand, false_computation)
인수 | 유형 | 의미론 |
---|---|---|
pred | XlaOp | PRED 유형의 스칼라 |
true_operand | XlaOp | \(T_0\)유형의 인수 |
true_computation | XlaComputation | \(T_0 \to S\)유형의 XlaComputation |
false_operand | XlaOp | \(T_1\)유형의 인수 |
false_computation | XlaComputation | \(T_1 \to S\)유형의 XlaComputation |
pred
가 true
이면 true_computation
실행하고 pred
가 false
이면 false_computation
실행하고 결과를 반환합니다.
true_computation
은 \(T_0\) 유형의 단일 인수를 가져와야 하며 동일한 유형이어야 하는 true_operand
로 호출됩니다. false_computation
은 \(T_1\) 유형의 단일 인수를 가져와야 하며 동일한 유형이어야 하는 false_operand
로 호출됩니다. true_computation
과 false_computation
의 반환 값의 유형은 동일해야 합니다.
pred
값에 따라 true_computation
및 false_computation
중 하나만 실행됩니다.
Conditional(branch_index, branch_computations, branch_operands)
인수 | 유형 | 의미론 |
---|---|---|
branch_index | XlaOp | S32 유형의 스칼라 |
branch_computations | N XlaComputation 의 시퀀스 | \( T_0 \to S , T_1 \to S , ..., T_{N-1} \to S \)유형의 XlaComputations |
branch_operands | N XlaOp 의 시퀀스 | \( T_0 , T_1 , ..., T_{N-1} \)유형의 인수 |
branch_computations[branch_index]
실행하고 결과를 반환합니다. branch_index
가 < 0 또는 >= N인 S32
이면 branch_computations[N-1]
기본 분기로 실행됩니다.
각 branch_computations[b]
T_b
유형의 단일 인수를 가져와야 하며 동일한 유형이어야 하는 branch_operands[b]
로 호출됩니다. 각 branch_computations[b]
의 반환 값 유형은 동일해야 합니다.
branch_index
의 값에 따라 branch_computations
중 하나만 실행됩니다.
전환(컨볼루션)
XlaBuilder::Conv
도 참조하십시오.
ConvWithGeneralPadding과 같지만 패딩은 약식으로 SAME 또는 VALID로 지정됩니다. SAME 패딩은 스트라이드를 고려하지 않을 때 출력이 입력과 동일한 모양을 갖도록 입력( lhs
)을 0으로 채웁니다. VALID 패딩은 단순히 패딩이 없음을 의미합니다.
ConvWithGeneralPadding(컨볼루션)
XlaBuilder::ConvWithGeneralPadding
도 참조하십시오.
신경망에서 사용되는 종류의 컨벌루션을 계산합니다. 여기서 컨볼루션은 n차원 기본 영역을 가로질러 이동하는 n차원 창으로 생각할 수 있으며 창의 각 가능한 위치에 대해 계산이 수행됩니다.
인수 | 유형 | 의미론 |
---|---|---|
lhs | XlaOp | 순위 n+2 입력 배열 |
rhs | XlaOp | 커널 가중치의 순위 n+2 배열 |
window_strides | ArraySlice<int64> | 커널 보폭의 nd 배열 |
padding | ArraySlice< pair<int64, int64>> | (낮음, 높음) 패딩의 nd 배열 |
lhs_dilation | ArraySlice<int64> | nd lhs 확장 인자 배열 |
rhs_dilation | ArraySlice<int64> | nd rhs 팽창 인자 배열 |
feature_group_count | int64 | 기능 그룹의 수 |
batch_group_count | int64 | 일괄 그룹 수 |
n을 공간 차원의 수라고 합니다. lhs
인수는 기본 영역을 설명하는 순위 n+2 배열입니다. 물론 rhs도 입력이지만 이를 입력이라고 합니다. 신경망에서 이들은 입력 활성화입니다. n+2 차원은 다음과 같습니다.
-
batch
: 이 차원의 각 좌표는 컨볼루션이 수행되는 독립적인 입력을 나타냅니다. -
z/depth/features
: 기본 영역의 각 (y,x) 위치에는 이 차원으로 들어가는 연관된 벡터가 있습니다. -
spatial_dims
: 창이 이동하는 기본 영역을 정의하는n
공간 차원을 설명합니다.
rhs
인수는 컨벌루션 필터/커널/창을 설명하는 랭크 n+2 배열입니다. 차원은 이 순서대로 다음과 같습니다.
-
output-z
: 출력의z
차원입니다. -
input-z
: 이 차원의 크기에feature_group_count
곱한 값은 lhs에서z
차원의 크기와 같아야 합니다. -
spatial_dims
: 기본 영역을 가로질러 이동하는 nd 창을 정의하는n
공간 차원을 설명합니다.
window_strides
인수는 공간 차원에서 컨볼루션 창의 보폭을 지정합니다. 예를 들어 첫 번째 공간 차원의 보폭이 3이면 첫 번째 공간 인덱스가 3으로 나누어지는 좌표에만 창을 배치할 수 있습니다.
padding
인수는 기본 영역에 적용할 0 패딩의 양을 지정합니다. 패딩의 양은 음수일 수 있습니다. 음수 패딩의 절대값은 컨볼루션을 수행하기 전에 지정된 차원에서 제거할 요소의 수를 나타냅니다. padding[0]
차원 y
에 대한 패딩을 지정하고 padding[1]
차원 x
에 대한 패딩을 지정합니다. 각 쌍에는 첫 번째 요소로 낮은 패딩이 있고 두 번째 요소로 높은 패딩이 있습니다. 낮은 패딩은 낮은 지수 방향으로 적용되고 높은 패딩은 높은 지수 방향으로 적용됩니다. 예를 들어 padding[1]
이 (2,3)
이면 두 번째 공간 차원에서 왼쪽에 2개의 0, 오른쪽에 3개의 0이 패딩됩니다. 패딩을 사용하는 것은 컨볼루션을 수행하기 전에 동일한 0 값을 입력( lhs
)에 삽입하는 것과 같습니다.
lhs_dilation
및 rhs_dilation
인수는 각 공간 차원에서 각각 lhs 및 rhs에 적용할 팽창 계수를 지정합니다. 공간 차원의 팽창 계수가 d이면 해당 차원의 각 항목 사이에 암시적으로 d-1 구멍이 배치되어 배열의 크기가 증가합니다. 구멍은 컨볼루션의 경우 0을 의미하는 no-op 값으로 채워집니다.
rhs의 확장은 atrous convolution이라고도 합니다. 자세한 내용은 tf.nn.atrous_conv2d
참조하세요. lhs의 확장은 전치 컨벌루션이라고도 합니다. 자세한 내용은 tf.nn.conv2d_transpose
참조하세요.
feature_group_count
인수(기본값 1)는 그룹화된 컨볼루션에 사용할 수 있습니다. feature_group_count
입력 및 출력 기능 차원의 제수여야 합니다. feature_group_count
가 1보다 크면 개념적으로 입력 및 출력 기능 차원과 rhs
출력 기능 차원이 feature_group_count
많은 그룹으로 균등하게 분할되며 각 그룹은 기능의 연속 하위 시퀀스로 구성됩니다. rhs
의 입력 기능 차원은 lhs
입력 기능 차원을 feature_group_count
로 나눈 값과 같아야 합니다(따라서 이미 입력 기능 그룹의 크기가 있음). i번째 그룹은 feature_group_count
많은 개별 컨볼루션을 계산하기 위해 함께 사용됩니다. 이러한 회선의 결과는 출력 기능 차원에서 함께 연결됩니다.
깊이별 컨벌루션의 경우 feature_group_count
인수는 입력 기능 차원으로 설정되고 필터는 [filter_height, filter_width, in_channels, channel_multiplier]
에서 [filter_height, filter_width, 1, in_channels * channel_multiplier]
로 재구성됩니다. 자세한 내용은 tf.nn.depthwise_conv2d
참조하세요.
batch_group_count
(기본값 1) 인수는 역전파 중에 그룹화된 필터에 사용할 수 있습니다. batch_group_count
lhs
(입력) 배치 차원 크기의 제수여야 합니다. batch_group_count
1보다 크면 출력 배치 차원의 크기가 input batch / batch_group_count
여야 함을 의미합니다. batch_group_count
는 출력 기능 크기의 제수여야 합니다.
출력 모양의 크기는 다음 순서로 되어 있습니다.
-
batch
: 이 차원의 크기에batch_group_count
곱한 값은batch
차원의 크기(lhs)와 같아야 합니다. -
z
: 커널의output-z
와 같은 크기(rhs
). -
spatial_dims
: 컨벌루션 창의 각 유효 배치에 대한 하나의 값입니다.
위의 그림은 batch_group_count
필드가 작동하는 방식을 보여줍니다. 효과적으로 각 lhs 배치를 batch_group_count
그룹으로 나누고 출력 기능에 대해 동일한 작업을 수행합니다. 그런 다음 각 그룹에 대해 쌍별 컨볼루션을 수행하고 출력 기능 차원을 따라 출력을 연결합니다. 다른 모든 차원(기능 및 공간)의 작동 의미 체계는 동일하게 유지됩니다.
컨벌루션 창의 유효한 배치는 보폭과 패딩 후 기본 영역의 크기에 의해 결정됩니다.
컨볼루션이 무엇을 하는지 설명하려면 2d 컨볼루션을 고려하고 출력에서 고정 batch
, z
, y
, x
좌표를 선택합니다. 그런 다음 (y,x)
는 기본 영역(예: 공간 차원을 해석하는 방법에 따라 왼쪽 위 모서리) 내의 창 모서리 위치입니다. 이제 각 2d 포인트가 1d 벡터와 연결되는 기본 영역에서 가져온 2d 창이 있으므로 3d 상자를 얻습니다. 컨벌루션 커널에서 출력 좌표 z
를 고정했기 때문에 3d 상자도 있습니다. 두 상자의 크기가 같으므로 두 상자 사이의 요소별 곱의 합을 구할 수 있습니다(내적과 유사). 그것이 출력 값입니다.
예를 들어 output-z
가 5이면 창의 각 위치는 출력의 z
차원으로 출력에 5개의 값을 생성합니다. 이 값은 컨벌루션 커널의 어느 부분이 사용되는지에 따라 다릅니다. 각 output-z
좌표에 사용되는 별도의 3d 값 상자가 있습니다. 따라서 각각에 대해 서로 다른 필터가 있는 5개의 개별 컨볼루션으로 생각할 수 있습니다.
다음은 패딩 및 스트라이드가 있는 2d 컨볼루션의 의사 코드입니다.
for (b, oz, oy, ox) { // output coordinates
value = 0;
for (iz, ky, kx) { // kernel coordinates and input z
iy = oy*stride_y + ky - pad_low_y;
ix = ox*stride_x + kx - pad_low_x;
if ((iy, ix) inside the base area considered without padding) {
value += input(b, iz, iy, ix) * kernel(oz, iz, ky, kx);
}
}
output(b, oz, oy, ox) = value;
}
ConvertElementType
XlaBuilder::ConvertElementType
도 참조하십시오.
C++의 요소별 static_cast
유사하게 데이터 셰이프에서 대상 셰이프로 요소별 변환 작업을 수행합니다. 치수는 일치해야 하며 변환은 요소별로 이루어집니다. 예를 들어 s32
요소는 s32
에서 f32
로의 변환 루틴을 통해 f32
요소가 됩니다.
ConvertElementType(operand, new_element_type)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | 희미한 D가 있는 유형 T의 배열 |
new_element_type | PrimitiveType | 유형 U |
피연산자의 크기와 대상 모양이 일치해야 합니다. 소스 및 대상 요소 유형은 튜플이 아니어야 합니다.
T=s32
에서 U=f32
로의 변환은 반올림과 같은 정규화 int-to-float 변환 루틴을 수행합니다.
let a: s32[3] = {0, 1, 2};
let b: f32[3] = convert(a, f32);
then b == f32[3]{0.0, 1.0, 2.0}
CrossReplicaSum
합계 계산으로 AllReduce
수행합니다.
커스텀콜
XlaBuilder::CustomCall
도 참조하십시오.
계산 내에서 사용자 제공 함수를 호출합니다.
CustomCall(target_name, args..., shape)
인수 | 유형 | 의미론 |
---|---|---|
target_name | string | 함수의 이름입니다. 이 기호 이름을 대상으로 하는 호출 명령이 방출됩니다. |
args | N XlaOp 의 시퀀스 | 함수에 전달될 임의 유형의 N 인수. |
shape | Shape | 함수의 출력 형태 |
인수의 인수 또는 유형에 관계없이 함수 시그니처는 동일합니다.
extern "C" void target_name(void* out, void** in);
예를 들어 다음과 같이 CustomCall을 사용하는 경우:
let x = f32[2] {1,2};
let y = f32[2x3] { {10, 20, 30}, {40, 50, 60} };
CustomCall("myfunc", {x, y}, f32[3x3])
다음은 myfunc
구현의 예입니다.
extern "C" void myfunc(void* out, void** in) {
float (&x)[2] = *static_cast<float(*)[2]>(in[0]);
float (&y)[2][3] = *static_cast<float(*)[2][3]>(in[1]);
EXPECT_EQ(1, x[0]);
EXPECT_EQ(2, x[1]);
EXPECT_EQ(10, y[0][0]);
EXPECT_EQ(20, y[0][1]);
EXPECT_EQ(30, y[0][2]);
EXPECT_EQ(40, y[1][0]);
EXPECT_EQ(50, y[1][1]);
EXPECT_EQ(60, y[1][2]);
float (&z)[3][3] = *static_cast<float(*)[3][3]>(out);
z[0][0] = x[1] + y[1][0];
// ...
}
사용자 제공 함수는 부작용이 없어야 하며 실행은 멱등적이어야 합니다.
점
XlaBuilder::Dot
도 참조하십시오.
Dot(lhs, rhs)
인수 | 유형 | 의미론 |
---|---|---|
lhs | XlaOp | T 유형의 배열 |
rhs | XlaOp | T 유형의 배열 |
이 연산의 정확한 의미 체계는 피연산자의 순위에 따라 다릅니다.
입력 | 산출 | 의미론 |
---|---|---|
벡터 [n] dot 벡터 [n] | 스칼라 | 벡터 내적 |
행렬 [mxk] dot 벡터 [k] | 벡터 [m] | 행렬-벡터 곱셈 |
매트릭스[mxk] dot 매트릭스[kxn] | 행렬 [mxn] | 행렬-행렬 곱셈 |
연산은 lhs
의 두 번째 차원(또는 순위가 1인 경우 첫 번째 차원)과 rhs
의 첫 번째 차원에 대한 곱의 합계를 수행합니다. 이것이 "약정된" 차원입니다. lhs
와 rhs
의 축약된 차원은 크기가 같아야 합니다. 실제로 벡터, 벡터/행렬 곱셈 또는 행렬/행렬 곱셈 간의 내적을 수행하는 데 사용할 수 있습니다.
도트제너럴
XlaBuilder::DotGeneral
도 참조하십시오.
DotGeneral(lhs, rhs, dimension_numbers)
인수 | 유형 | 의미론 |
---|---|---|
lhs | XlaOp | T 유형의 배열 |
rhs | XlaOp | T 유형의 배열 |
dimension_numbers | DotDimensionNumbers | 계약 및 배치 치수 번호 |
점으로 하지만 'lhs' 및 'rhs' 모두에 대해 축소 및 배치 치수 번호를 지정할 수 있습니다.
DotDimensionNumbers 필드 | 유형 | 의미론 |
---|---|---|
'lhs_contracting_dimensions' | 반복 int64 | 'lhs' 축소 치수 번호 |
'rhs_contracting_dimensions' | 반복 int64 | 'rhs' 축소 치수 번호 |
'lhs_batch_dimensions' | 반복 int64 | 'lhs' 배치 치수 번호 |
'rhs_batch_dimensions' | 반복 int64 | 'rhs' 배치 치수 번호 |
DotGeneral은 'dimension_numbers'에 지정된 축소 치수에 대한 제품의 합계를 수행합니다.
'lhs' 및 'rhs'의 연결된 축소 치수 번호는 동일할 필요는 없지만 치수 크기는 동일해야 합니다.
축소 치수 번호의 예:
lhs = { {1.0, 2.0, 3.0},
{4.0, 5.0, 6.0} }
rhs = { {1.0, 1.0, 1.0},
{2.0, 2.0, 2.0} }
DotDimensionNumbers dnums;
dnums.add_lhs_contracting_dimensions(1);
dnums.add_rhs_contracting_dimensions(1);
DotGeneral(lhs, rhs, dnums) -> { {6.0, 12.0},
{15.0, 30.0} }
'lhs' 및 'rhs'의 연관된 배치 치수 번호는 치수 크기가 동일해야 합니다.
배치 치수 번호의 예(배치 크기 2, 2x2 매트릭스):
lhs = { { {1.0, 2.0},
{3.0, 4.0} },
{ {5.0, 6.0},
{7.0, 8.0} } }
rhs = { { {1.0, 0.0},
{0.0, 1.0} },
{ {1.0, 0.0},
{0.0, 1.0} } }
DotDimensionNumbers dnums;
dnums.add_lhs_contracting_dimensions(2);
dnums.add_rhs_contracting_dimensions(1);
dnums.add_lhs_batch_dimensions(0);
dnums.add_rhs_batch_dimensions(0);
DotGeneral(lhs, rhs, dnums) -> { { {1.0, 2.0},
{3.0, 4.0} },
{ {5.0, 6.0},
{7.0, 8.0} } }
입력 | 산출 | 의미론 |
---|---|---|
[b0, m, k] dot [b0, k, n] | [b0, m, n] | 배치 재료 |
[b0, b1, m, k] dot [b0, b1, k, n] | [b0, b1, m, n] | 배치 재료 |
결과 차원 번호는 배치 차원으로 시작하여 'lhs' 비축약/비배치 차원, 마지막으로 'rhs' 비축약/비배치 차원으로 이어집니다.
다이나믹슬라이스
XlaBuilder::DynamicSlice
도 참조하십시오.
DynamicSlice는 dynamic start_indices
의 입력 배열에서 하위 배열을 추출합니다. 각 차원의 슬라이스 크기는 각 차원에서 독점 슬라이스 간격의 끝점을 지정하는 size_indices
로 전달됩니다: [start, start + size). start_indices
의 형태는 rank == 1이어야 하며 차원 크기는 operand
의 rank와 동일해야 합니다.
DynamicSlice(operand, start_indices, size_indices)
인수 | 유형 | 의미론 |
---|---|---|
operand | XlaOp | T 유형의 N차원 배열 |
start_indices | N XlaOp 의 시퀀스 | 각 차원에 대한 슬라이스의 시작 인덱스를 포함하는 N개의 정수 스칼라 목록입니다. Value must be greater than or equal to zero. |
size_indices | ArraySlice<int64> | List of N integers containing the slice size for each dimension. Each value must be strictly greater than zero, and start + size must be less than or equal to the size of the dimension to avoid wrapping modulo dimension size. |
The effective slice indices are computed by applying the following transformation for each index i
in [1, N)
before performing the slice:
start_indices[i] = clamp(start_indices[i], 0, operand.dimension_size[i] - size_indices[i])
This ensures that the extracted slice is always in-bounds with respect to the operand array. If the slice is in-bounds before the transformation is applied, the transformation has no effect.
1-dimensional example:
let a = {0.0, 1.0, 2.0, 3.0, 4.0}
let s = {2}
DynamicSlice(a, s, {2}) produces:
{2.0, 3.0}
2-dimensional example:
let b =
{ {0.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0},
{9.0, 10.0, 11.0} }
let s = {2, 1}
DynamicSlice(b, s, {2, 2}) produces:
{ { 7.0, 8.0},
{10.0, 11.0} }
DynamicUpdateSlice
See also XlaBuilder::DynamicUpdateSlice
.
DynamicUpdateSlice generates a result which is the value of the input array operand
, with a slice update
overwritten at start_indices
. The shape of update
determines the shape of the sub-array of the result which is updated. The shape of start_indices
must be rank == 1, with dimension size equal to the rank of operand
.
DynamicUpdateSlice(operand, update, start_indices)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | N dimensional array of type T |
update | XlaOp | N dimensional array of type T containing the slice update. Each dimension of update shape must be strictly greater than zero, and start + update must be less than or equal to the operand size for each dimension to avoid generating out-of-bounds update indices. |
start_indices | sequence of N XlaOp | List of N scalar integers containing the starting indices of the slice for each dimension. Value must be greater than or equal to zero. |
The effective slice indices are computed by applying the following transformation for each index i
in [1, N)
before performing the slice:
start_indices[i] = clamp(start_indices[i], 0, operand.dimension_size[i] - update.dimension_size[i])
This ensures that the updated slice is always in-bounds with respect to the operand array. If the slice is in-bounds before the transformation is applied, the transformation has no effect.
1-dimensional example:
let a = {0.0, 1.0, 2.0, 3.0, 4.0}
let u = {5.0, 6.0}
let s = {2}
DynamicUpdateSlice(a, u, s) produces:
{0.0, 1.0, 5.0, 6.0, 4.0}
2-dimensional example:
let b =
{ {0.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0},
{9.0, 10.0, 11.0} }
let u =
{ {12.0, 13.0},
{14.0, 15.0},
{16.0, 17.0} }
let s = {1, 1}
DynamicUpdateSlice(b, u, s) produces:
{ {0.0, 1.0, 2.0},
{3.0, 12.0, 13.0},
{6.0, 14.0, 15.0},
{9.0, 16.0, 17.0} }
Element-wise binary arithmetic operations
See also XlaBuilder::Add
.
A set of element-wise binary arithmetic operations is supported.
Op(lhs, rhs)
Where Op
is one of Add
(addition), Sub
(subtraction), Mul
(multiplication), Div
(division), Rem
(remainder), Max
(maximum), Min
(minimum), LogicalAnd
(logical AND), or LogicalOr
(logical OR).
Arguments | Type | Semantics |
---|---|---|
lhs | XlaOp | left-hand-side operand: array of type T |
rhs | XlaOp | right-hand-side operand: array of type T |
The arguments' shapes have to be either similar or compatible. See the broadcasting documentation about what it means for shapes to be compatible. The result of an operation has a shape which is the result of broadcasting the two input arrays. In this variant, operations between arrays of different ranks are not supported, unless one of the operands is a scalar.
When Op
is Rem
, the sign of the result is taken from the dividend, and the absolute value of the result is always less than the divisor's absolute value.
Integer division overflow (signed/unsigned division/remainder by zero or signed division/remainder of INT_SMIN
with -1
) produces an implementation defined value.
An alternative variant with different-rank broadcasting support exists for these operations:
Op(lhs, rhs, broadcast_dimensions)
Where Op
is the same as above. This variant of the operation should be used for arithmetic operations between arrays of different ranks (such as adding a matrix to a vector).
The additional broadcast_dimensions
operand is a slice of integers used to expand the rank of the lower-rank operand up to the rank of the higher-rank operand. broadcast_dimensions
maps the dimensions of the lower-rank shape to the dimensions of the higher-rank shape. The unmapped dimensions of the expanded shape are filled with dimensions of size one. Degenerate-dimension broadcasting then broadcasts the shapes along these degenerate dimensions to equalize the shapes of both operands. The semantics are described in detail on the broadcasting page .
Element-wise comparison operations
See also XlaBuilder::Eq
.
A set of standard element-wise binary comparison operations is supported. Note that standard IEEE 754 floating-point comparison semantics apply when comparing floating-point types.
Op(lhs, rhs)
Where Op
is one of Eq
(equal-to), Ne
(not equal-to), Ge
(greater-or-equal-than), Gt
(greater-than), Le
(less-or-equal-than), Lt
(less-than). Another set of operators, EqTotalOrder, NeTotalOrder, GeTotalOrder, GtTotalOrder, LeTotalOrder, and LtTotalOrder, provide the same functionalities, except that they additionally support a total order over the floating point numbers, by enforcing -NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN.
Arguments | Type | Semantics |
---|---|---|
lhs | XlaOp | left-hand-side operand: array of type T |
rhs | XlaOp | right-hand-side operand: array of type T |
The arguments' shapes have to be either similar or compatible. See the broadcasting documentation about what it means for shapes to be compatible. The result of an operation has a shape which is the result of broadcasting the two input arrays with the element type PRED
. In this variant, operations between arrays of different ranks are not supported, unless one of the operands is a scalar.
An alternative variant with different-rank broadcasting support exists for these operations:
Op(lhs, rhs, broadcast_dimensions)
Where Op
is the same as above. This variant of the operation should be used for comparison operations between arrays of different ranks (such as adding a matrix to a vector).
The additional broadcast_dimensions
operand is a slice of integers specifying the dimensions to use for broadcasting the operands. The semantics are described in detail on the broadcasting page .
Element-wise unary functions
XlaBuilder supports these element-wise unary functions:
Abs(operand)
Element-wise abs x -> |x|
.
Ceil(operand)
Element-wise ceil x -> ⌈x⌉
.
Cos(operand)
Element-wise cosine x -> cos(x)
.
Exp(operand)
Element-wise natural exponential x -> e^x
.
Floor(operand)
Element-wise floor x -> ⌊x⌋
.
Imag(operand)
Element-wise imaginary part of a complex (or real) shape. x -> imag(x)
. If the operand is a floating point type, returns 0.
IsFinite(operand)
Tests whether each element of operand
is finite, ie, is not positive or negative infinity, and is not NaN
. Returns an array of PRED
values with the same shape as the input, where each element is true
if and only if the corresponding input element is finite.
Log(operand)
Element-wise natural logarithm x -> ln(x)
.
LogicalNot(operand)
Element-wise logical not x -> !(x)
.
Logistic(operand)
Element-wise logistic function computation x -> logistic(x)
.
PopulationCount(operand)
Computes the number of bits set in each element of operand
.
Neg(operand)
Element-wise negation x -> -x
.
Real(operand)
Element-wise real part of a complex (or real) shape. x -> real(x)
. If the operand is a floating point type, returns the same value.
Rsqrt(operand)
Element-wise reciprocal of square root operation x -> 1.0 / sqrt(x)
.
Sign(operand)
Element-wise sign operation x -> sgn(x)
where
\[\text{sgn}(x) = \begin{cases} -1 & x < 0\\ -0 & x = -0\\ NaN & x = NaN\\ +0 & x = +0\\ 1 & x > 0 \end{cases}\]
using the comparison operator of the element type of operand
.
Sqrt(operand)
Element-wise square root operation x -> sqrt(x)
.
Cbrt(operand)
Element-wise cubic root operation x -> cbrt(x)
.
Tan(operand)
Element-wise tangent x -> tan(x)
.
Tanh(operand)
Element-wise hyperbolic tangent x -> tanh(x)
.
Round(operand)
Element-wise rounding, ties away from zero.
RoundNearestEven(operand)
Element-wise rounding, ties to nearest even.
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | The operand to the function |
The function is applied to each element in the operand
array, resulting in an array with the same shape. It is allowed for operand
to be a scalar (rank 0).
Fft
The XLA FFT operation implements the forward and inverse Fourier Transforms for real and complex inputs/outputs. Multidimensional FFTs on up to 3 axes are supported.
See also XlaBuilder::Fft
.
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | The array we are Fourier transforming. |
fft_type | FftType | See the table below. |
fft_length | ArraySlice<int64> | The time-domain lengths of the axes being transformed. This is needed in particular for IRFFT to right-size the innermost axis, since RFFT(fft_length=[16]) has the same output shape as RFFT(fft_length=[17]) . |
FftType | Semantics |
---|---|
FFT | Forward complex-to-complex FFT. Shape is unchanged. |
IFFT | Inverse complex-to-complex FFT. Shape is unchanged. |
RFFT | Forward real-to-complex FFT. Shape of the innermost axis is reduced to fft_length[-1] // 2 + 1 if fft_length[-1] is a non-zero value, omitting the reversed conjugate part of the transformed signal beyond the Nyquist frequency. |
IRFFT | Inverse real-to-complex FFT (ie takes complex, returns real). Shape of the innermost axis is expanded to fft_length[-1] if fft_length[-1] is a non-zero value, inferring the part of the transformed signal beyond the Nyquist frequency from the reverse conjugate of the 1 to fft_length[-1] // 2 + 1 entries. |
Multidimensional FFT
When more than 1 fft_length
is provided, this is equivalent to applying a cascade of FFT operations to each of the innermost axes. Note that for the real->complex and complex->real cases, the innermost axis transform is (effectively) performed first (RFFT; last for IRFFT), which is why the innermost axis is the one which changes size. Other axis transforms will then be complex->complex.
Implementation details
CPU FFT is backed by Eigen's TensorFFT. GPU FFT uses cuFFT.
Gather
The XLA gather operation stitches together several slices (each slice at a potentially different runtime offset) of an input array.
General Semantics
See also XlaBuilder::Gather
. For a more intuitive description, see the "Informal Description" section below.
gather(operand, start_indices, offset_dims, collapsed_slice_dims, slice_sizes, start_index_map)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | The array we're gathering from. |
start_indices | XlaOp | Array containing the starting indices of the slices we gather. |
index_vector_dim | int64 | The dimension in start_indices that "contains" the starting indices. See below for a detailed description. |
offset_dims | ArraySlice<int64> | The set of dimensions in the output shape that offset into an array sliced from operand. |
slice_sizes | ArraySlice<int64> | slice_sizes[i] is the bounds for the slice on dimension i . |
collapsed_slice_dims | ArraySlice<int64> | The set of dimensions in each slice that are collapsed away. These dimensions must have size 1. |
start_index_map | ArraySlice<int64> | A map that describes how to map indices in start_indices to legal indices into operand. |
indices_are_sorted | bool | Whether the indices are guaranteed to be sorted by the caller. |
unique_indices | bool | Whether the indices are guaranteed to be unique by the caller. |
For convenience, we label dimensions in the output array not in offset_dims
as batch_dims
.
The output is an array of rank batch_dims.size
+ offset_dims.size
.
The operand.rank
must equal the sum of offset_dims.size
and collapsed_slice_dims.size
. Also, slice_sizes.size
has to be equal to operand.rank
.
If index_vector_dim
is equal to start_indices.rank
we implicitly consider start_indices
to have a trailing 1
dimension (ie if start_indices
was of shape [6,7]
and index_vector_dim
is 2
then we implicitly consider the shape of start_indices
to be [6,7,1]
).
The bounds for the output array along dimension i
is computed as follows:
If
i
is present inbatch_dims
(ie is equal tobatch_dims[k]
for somek
) then we pick the corresponding dimension bounds out ofstart_indices.shape
, skippingindex_vector_dim
(ie pickstart_indices.shape.dims
[k
] ifk
<index_vector_dim
andstart_indices.shape.dims
[k
+1
] otherwise).If
i
is present inoffset_dims
(ie equal tooffset_dims
[k
] for somek
) then we pick the corresponding bound out ofslice_sizes
after accounting forcollapsed_slice_dims
(ie we pickadjusted_slice_sizes
[k
] whereadjusted_slice_sizes
isslice_sizes
with the bounds at indicescollapsed_slice_dims
removed).
Formally, the operand index In
corresponding to a given output index Out
is calculated as follows:
Let
G
= {Out
[k
] fork
inbatch_dims
}. UseG
to slice out a vectorS
such thatS
[i
] =start_indices
[Combine(G
,i
)] where Combine(A, b) inserts b at positionindex_vector_dim
into A. Note that this is well defined even ifG
is empty -- ifG
is empty thenS
=start_indices
.Create a starting index,
S
in
, intooperand
usingS
by scatteringS
usingstart_index_map
. More precisely:S
in
[start_index_map
[k
]] =S
[k
] ifk
<start_index_map.size
.S
in
[_
] =0
otherwise.
Create an index
O
in
intooperand
by scattering the indices at the offset dimensions inOut
according to thecollapsed_slice_dims
set. More precisely:O
in
[remapped_offset_dims
(k
)] =Out
[offset_dims
[k
]] ifk
<offset_dims.size
(remapped_offset_dims
is defined below).O
in
[_
] =0
otherwise.
In
isO
in
+S
in
where + is element-wise addition.
remapped_offset_dims
is a monotonic function with domain [ 0
, offset_dims.size
) and range [ 0
, operand.rank
) \ collapsed_slice_dims
. So if, eg, offset_dims.size
is 4
, operand.rank
is 6
and collapsed_slice_dims
is { 0
, 2
} then remapped_offset_dims
is { 0
→ 1
, 1
→ 3
, 2
→ 4
, 3
→ 5
}.
If indices_are_sorted
is set to true then XLA can assume that start_indices
are sorted (in ascending start_index_map
order) by the user. If they are not then the semantics is implementation defined.
If unique_indices
is set to true then XLA can assume that all element scattered to are unique. So XLA could use non-atomic operations. If unique_indices
is set to true and the indices being scattered to are not unique then the semantics is implementation defined.
Informal Description and Examples
Informally, every index Out
in the output array corresponds to an element E
in the operand array, computed as follows:
We use the batch dimensions in
Out
to look up a starting index fromstart_indices
.We use
start_index_map
to map the starting index (whose size may be less than operand.rank) to a "full" starting index into theoperand
.We dynamic-slice out a slice with size
slice_sizes
using the full starting index.We reshape the slice by collapsing the
collapsed_slice_dims
dimensions. Since all collapsed slice dimensions must have a bound of 1, this reshape is always legal.We use the offset dimensions in
Out
to index into this slice to get the input element,E
, corresponding to output indexOut
.
index_vector_dim
is set to start_indices.rank
- 1
in all of the examples that follow. More interesting values for index_vector_dim
do not change the operation fundamentally, but make the visual representation more cumbersome.
To get an intuition on how all of the above fits together, let's look at an example that gathers 5 slices of shape [8,6]
from a [16,11]
array. The position of a slice into the [16,11]
array can be represented as an index vector of shape S64[2]
, so the set of 5 positions can be represented as a S64[5,2]
array.
The behavior of the gather operation can then be depicted as an index transformation that takes [ G
, O
0
, O
1
], an index in the output shape, and maps it to an element in the input array in the following way:
We first select an ( X
, Y
) vector from the gather indices array using G
. The element in the output array at index [ G
, O
0
, O
1
] is then the element in the input array at index [ X
+ O
0
, Y
+ O
1
].
slice_sizes
is [8,6]
, which decides the range of O 0
and O 1
, and this in turn decides the bounds of the slice.
This gather operation acts as a batch dynamic slice with G
as the batch dimension.
The gather indices may be multidimensional. For instance, a more general version of the example above using a "gather indices" array of shape [4,5,2]
would translate indices like this:
Again, this acts as a batch dynamic slice G
0
and G
1
as the batch dimensions. The slice size is still [8,6]
.
The gather operation in XLA generalizes the informal semantics outlined above in the following ways:
We can configure which dimensions in the output shape are the offset dimensions (dimensions containing
O
0
,O
1
in the last example). The output batch dimensions (dimensions containingG
0
,G
1
in the last example) are defined to be the output dimensions that are not offset dimensions.The number of output offset dimensions explicitly present in the output shape may be smaller than the input rank. These "missing" dimensions, which are listed explicitly as
collapsed_slice_dims
, must have a slice size of1
. Since they have a slice size of1
the only valid index for them is0
and eliding them does not introduce ambiguity.The slice extracted from the "Gather Indices" array ((
X
,Y
) in the last example) may have fewer elements than the input array rank, and an explicit mapping dictates how the index should be expanded to have the same rank as the input.
As a final example, we use (2) and (3) to implement tf.gather_nd
:
G
0
and G
1
are used to slice out a starting index from the gather indices array as usual, except the starting index has only one element, X
. Similarly, there is only one output offset index with the value O
0
. However, before being used as indices into the input array, these are expanded in accordance to "Gather Index Mapping" ( start_index_map
in the formal description) and "Offset Mapping" ( remapped_offset_dims
in the formal description) into [ X
, 0
] and [ 0
, O
0
] respectively, adding up to [ X
, O
0
]. In other words, the output index [ G
0
, G
1
, O
0
] maps to the input index [ GatherIndices
[ G
0
, G
1
, 0
], O
0
] which gives us the semantics for tf.gather_nd
.
slice_sizes
for this case is [1,11]
. Intuitively this means that every index X
in the gather indices array picks an entire row and the result is the concatenation of all these rows.
GetDimensionSize
See also XlaBuilder::GetDimensionSize
.
Returns the size of the given dimension of the operand. The operand must be array shaped.
GetDimensionSize(operand, dimension)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | n dimensional input array |
dimension | int64 | A value in the interval [0, n) that specifies the dimension |
SetDimensionSize
See also XlaBuilder::SetDimensionSize
.
Sets the dynamic size of XlaOp's given dimension. The operand must be array shaped.
SetDimensionSize(operand, size, dimension)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | n dimensional input array. |
size | XlaOp | int32 representing the runtime dynamic size. |
dimension | int64 | A value in the interval [0, n) that specifies the dimension. |
Pass through the operand as result, with dynamic dimension tracked by the compiler.
Padded values will be ignored by downstream reduction ops.
let v: f32[10] = f32[10]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
let five: s32 = 5;
let six: s32 = 6;
// Setting dynamic dimension size doesn't change the upper bound of the static
// shape.
let padded_v_five: f32[10] = set_dimension_size(v, five, /*dimension=*/0);
let padded_v_six: f32[10] = set_dimension_size(v, six, /*dimension=*/0);
// sum == 1 + 2 + 3 + 4 + 5
let sum:f32[] = reduce_sum(padded_v_five);
// product == 1 * 2 * 3 * 4 * 5
let product:f32[] = reduce_product(padded_v_five);
// Changing padding size will yield different result.
// sum == 1 + 2 + 3 + 4 + 5 + 6
let sum:f32[] = reduce_sum(padded_v_six);
GetTupleElement
See also XlaBuilder::GetTupleElement
.
Indexes into a tuple with a compile-time-constant value.
The value must be a compile-time-constant so that shape inference can determine the type of the resulting value.
This is analogous to std::get<int N>(t)
in C++. Conceptually:
let v: f32[10] = f32[10]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
let s: s32 = 5;
let t: (f32[10], s32) = tuple(v, s);
let element_1: s32 = gettupleelement(t, 1); // Inferred shape matches s32.
See also tf.tuple
.
Infeed
See also XlaBuilder::Infeed
.
Infeed(shape)
Argument | Type | Semantics |
---|---|---|
shape | Shape | Shape of the data read from the Infeed interface. The layout field of the shape must be set to match the layout of the data sent to the device; otherwise its behavior is undefined. |
Reads a single data item from the implicit Infeed streaming interface of the device, interpreting the data as the given shape and its layout, and returns a XlaOp
of the data. Multiple Infeed operations are allowed in a computation, but there must be a total order among the Infeed operations. For example, two Infeeds in the code below have a total order since there is a dependency between the while loops.
result1 = while (condition, init = init_value) {
Infeed(shape)
}
result2 = while (condition, init = result1) {
Infeed(shape)
}
Nested tuple shapes are not supported. For an empty tuple shape, the Infeed operation is effectively a no-op and proceeds without reading any data from the Infeed of the device.
Iota
See also XlaBuilder::Iota
.
Iota(shape, iota_dimension)
Builds a constant literal on device rather than a potentially large host transfer. Creates an array that has specified shape and holds values starting at zero and incrementing by one along the specified dimension. For floating-point types, the produced array is equivalent to ConvertElementType(Iota(...))
where the Iota
is of integral type and the conversion is to the floating-point type.
Arguments | Type | Semantics |
---|---|---|
shape | Shape | Shape of the array created by Iota() |
iota_dimension | int64 | The dimension to increment along. |
For example, Iota(s32[4, 8], 0)
returns
[[0, 0, 0, 0, 0, 0, 0, 0 ],
[1, 1, 1, 1, 1, 1, 1, 1 ],
[2, 2, 2, 2, 2, 2, 2, 2 ],
[3, 3, 3, 3, 3, 3, 3, 3 ]]
Iota(s32[4, 8], 1)
returns
[[0, 1, 2, 3, 4, 5, 6, 7 ],
[0, 1, 2, 3, 4, 5, 6, 7 ],
[0, 1, 2, 3, 4, 5, 6, 7 ],
[0, 1, 2, 3, 4, 5, 6, 7 ]]
Map
See also XlaBuilder::Map
.
Map(operands..., computation)
Arguments | Type | Semantics |
---|---|---|
operands | sequence of N XlaOp s | N arrays of types T 0..T {N-1} |
computation | XlaComputation | computation of type T_0, T_1, ..., T_{N + M -1} -> S with N parameters of type T and M of arbitrary type |
dimensions | int64 array | array of map dimensions |
Applies a scalar function over the given operands
arrays, producing an array of the same dimensions where each element is the result of the mapped function applied to the corresponding elements in the input arrays.
The mapped function is an arbitrary computation with the restriction that it has N inputs of scalar type T
and a single output with type S
. The output has the same dimensions as the operands except that the element type T is replaced with S.
For example: Map(op1, op2, op3, computation, par1)
maps elem_out <- computation(elem1, elem2, elem3, par1)
at each (multi-dimensional) index in the input arrays to produce the output array.
OptimizationBarrier
Blocks any optimization pass from moving computations across the barrier.
Ensures that all inputs are evaluated before any operators that depend on the barrier's outputs.
Pad
See also XlaBuilder::Pad
.
Pad(operand, padding_value, padding_config)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | array of type T |
padding_value | XlaOp | scalar of type T to fill in the added padding |
padding_config | PaddingConfig | padding amount on both edges (low, high) and between the elements of each dimension |
Expands the given operand
array by padding around the array as well as between the elements of the array with the given padding_value
. padding_config
specifies the amount of edge padding and the interior padding for each dimension.
PaddingConfig
is a repeated field of PaddingConfigDimension
, which contains three fields for each dimension: edge_padding_low
, edge_padding_high
, and interior_padding
.
edge_padding_low
and edge_padding_high
specify the amount of padding added at the low-end (next to index 0) and the high-end (next to the highest index) of each dimension respectively. The amount of edge padding can be negative -- the absolute value of negative padding indicates the number of elements to remove from the specified dimension.
interior_padding
specifies the amount of padding added between any two elements in each dimension; it may not be negative. Interior padding occurs logically before edge padding, so in the case of negative edge padding, elements are removed from the interior-padded operand.
This operation is a no-op if the edge padding pairs are all (0, 0) and the interior padding values are all 0. The figure below shows examples of different edge_padding
and interior_padding
values for a two-dimensional array.

Recv
See also XlaBuilder::Recv
.
Recv(shape, channel_handle)
Arguments | Type | Semantics |
---|---|---|
shape | Shape | shape of the data to receive |
channel_handle | ChannelHandle | unique identifier for each send/recv pair |
Receives data of the given shape from a Send
instruction in another computation that shares the same channel handle. Returns a XlaOp for the received data.
The client API of Recv
operation represents synchronous communication. However, the instruction is internally decomposed into 2 HLO instructions ( Recv
and RecvDone
) to enable asynchronous data transfers. See also HloInstruction::CreateRecv
and HloInstruction::CreateRecvDone
.
Recv(const Shape& shape, int64 channel_id)
Allocates resources required to receive data from a Send
instruction with the same channel_id. Returns a context for the allocated resources, which is used by a following RecvDone
instruction to wait for the completion of the data transfer. The context is a tuple of {receive buffer (shape), request identifier (U32)} and it can only be used by a RecvDone
instruction.
RecvDone(HloInstruction context)
Given a context created by a Recv
instruction, waits for the data transfer to complete and returns the received data.
Reduce
See also XlaBuilder::Reduce
.
Applies a reduction function to one or more arrays in parallel.
Reduce(operands..., init_values..., computation, dimensions)
Arguments | Type | Semantics |
---|---|---|
operands | Sequence of N XlaOp | N arrays of types T_0, ..., T_{N-1} . |
init_values | Sequence of N XlaOp | N scalars of types T_0, ..., T_{N-1} . |
computation | XlaComputation | computation of type T_0, ..., T_{N-1}, T_0, ..., T_{N-1} -> Collate(T_0, ..., T_{N-1}) . |
dimensions | int64 array | unordered array of dimensions to reduce. |
Where:
- N is required to be greater or equal to 1.
- The computation has to be "roughly" associative (see below).
- All input arrays must have the same dimensions.
- All initial values have to form an identity under
computation
. - If
N = 1
,Collate(T)
isT
. - If
N > 1
,Collate(T_0, ..., T_{N-1})
is a tuple ofN
elements of typeT
.
This operation reduces one or more dimensions of each input array into scalars. The rank of each returned array is rank(operand) - len(dimensions)
. The output of the op is Collate(Q_0, ..., Q_N)
where Q_i
is an array of type T_i
, the dimensions of which are described below.
Different backends are allowed to reassociate the reduction computation. This can lead to numerical differences, as some reduction functions like addition are not associative for floats. However, if the range of the data is limited, floating-point addition is close enough to being associative for most practical uses.
Examples
When reducing across one dimension in a single 1D array with values [10, 11, 12, 13]
, with reduction function f
(this is computation
) then that could be computed as
f(10, f(11, f(12, f(init_value, 13)))
but there are also many other possibilities, eg
f(init_value, f(f(10, f(init_value, 11)), f(f(init_value, 12), f(init_value, 13))))
The following is a rough pseudo-code example of how reduction could be implemented, using summation as the reduction computation with an initial value of 0.
result_shape <- remove all dims in dimensions from operand_shape
# Iterate over all elements in result_shape. The number of r's here is equal
# to the rank of the result
for r0 in range(result_shape[0]), r1 in range(result_shape[1]), ...:
# Initialize this result element
result[r0, r1...] <- 0
# Iterate over all the reduction dimensions
for d0 in range(dimensions[0]), d1 in range(dimensions[1]), ...:
# Increment the result element with the value of the operand's element.
# The index of the operand's element is constructed from all ri's and di's
# in the right order (by construction ri's and di's together index over the
# whole operand shape).
result[r0, r1...] += operand[ri... di]
Here's an example of reducing a 2D array (matrix). The shape has rank 2, dimension 0 of size 2 and dimension 1 of size 3:

Results of reducing dimensions 0 or 1 with an "add" function:

Note that both reduction results are 1D arrays. The diagram shows one as column and another as row just for visual convenience.
For a more complex example, here is a 3D array. Its rank is 3, dimension 0 of size 4, dimension 1 of size 2 and dimension 2 of size 3. For simplicity, the values 1 to 6 are replicated across dimension 0.

Similarly to the 2D example, we can reduce just one dimension. If we reduce dimension 0, for example, we get a rank-2 array where all values across dimension 0 were folded into a scalar:
| 4 8 12 |
| 16 20 24 |
If we reduce dimension 2, we also get a rank-2 array where all values across dimension 2 were folded into a scalar:
| 6 15 |
| 6 15 |
| 6 15 |
| 6 15 |
Note that the relative order between the remaining dimensions in the input is preserved in the output, but some dimensions may get assigned new numbers (since the rank changes).
We can also reduce multiple dimensions. Add-reducing dimensions 0 and 1 produces the 1D array [20, 28, 36]
.
Reducing the 3D array over all its dimensions produces the scalar 84
.
Variadic Reduce
When N > 1
, reduce function application is slightly more complex, as it is applied simultaneously to all inputs. The operands are supplied to the computation in the following order:
- Running reduced value for the first operand
- ...
- Running reduced value for the N'th operand
- Input value for the first operand
- ...
- Input value for the N'th operand
For example, consider the following reduction function, which can be used to compute the max and the argmax of a 1-D array in parallel:
f: (Float, Int, Float, Int) -> Float, Int
f(max, argmax, value, index):
if value >= max:
return (value, index)
else:
return (max, argmax)
For 1-D Input arrays V = Float[N], K = Int[N]
, and init values I_V = Float, I_K = Int
, the result f_(N-1)
of reducing across the only input dimension is equivalent to the following recursive application:
f_0 = f(I_V, I_K, V_0, K_0)
f_1 = f(f_0.first, f_0.second, V_1, K_1)
...
f_(N-1) = f(f_(N-2).first, f_(N-2).second, V_(N-1), K_(N-1))
Applying this reduction to an array of values, and an array of sequential indices (ie iota), will co-iterate over the arrays, and return a tuple containing the maximal value and the matching index.
ReducePrecision
See also XlaBuilder::ReducePrecision
.
Models the effect of converting floating-point values to a lower-precision format (such as IEEE-FP16) and back to the original format. The number of exponent and mantissa bits in the lower-precision format can be specified arbitrarily, although all bit sizes may not be supported on all hardware implementations.
ReducePrecision(operand, mantissa_bits, exponent_bits)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | array of floating-point type T . |
exponent_bits | int32 | number of exponent bits in lower-precision format |
mantissa_bits | int32 | number of mantissa bits in lower-precision format |
The result is an array of type T
. The input values are rounded to the nearest value representable with the given number of mantissa bits (using "ties to even" semantics), and any values that exceed the range specified by the number of exponent bits are clamped to positive or negative infinity. NaN
values are retained, although they may be converted to canonical NaN
values.
The lower-precision format must have at least one exponent bit (in order to distinguish a zero value from an infinity, since both have a zero mantissa), and must have a non-negative number of mantissa bits. The number of exponent or mantissa bits may exceed the corresponding value for type T
; the corresponding portion of the conversion is then simply a no-op.
ReduceScatter
See also XlaBuilder::ReduceScatter
.
ReduceScatter is a collective operation that effectively does an AllReduce and then scatters the result by splitting it into shard_count
blocks along the scatter_dimension
and replica i
in the replica group receives the ith
shard.
ReduceScatter(operand, computation, scatter_dim, shard_count, replica_group_ids, channel_id)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | Array or a non-empty tuple of arrays to reduce across replicas. |
computation | XlaComputation | Reduction computation |
scatter_dimension | int64 | Dimension to scatter. |
shard_count | int64 | Number of blocks to split scatter_dimension |
replica_groups | vector of vectors of int64 | Groups between which the reductions are performed |
channel_id | optional int64 | Optional channel ID for cross-module communication |
- When
operand
is a tuple of arrays, the reduce-scatter is performed on each element of the tuple. -
replica_groups
is a list of replica groups between which the reduction is performed (replica id for the current replica can be retrieved usingReplicaId
). The order of replicas in each group determines the order in which the all-reduce result will be scattered.replica_groups
must either be empty (in which case all replicas belong to a single group), or contain the same number of elements as the number of replicas. When there are more than one replica groups, they all must be of the same size. For example,replica_groups = {0, 2}, {1, 3}
performs reduction between the replicas0
and2
, and1
and3
and then scatters the result. -
shard_count
is the size of each replica group. We need this in cases wherereplica_groups
are empty. Ifreplica_groups
is not empty,shard_count
must be equal to the size of each replica group. -
channel_id
is used for cross-module communication: onlyreduce-scatter
operations with the samechannel_id
can communicate with each other.
The output shape is the input shape with the scatter_dimension
made shard_count
times smaller. For example, if there are two replicas and the operand has the value [1.0, 2.25]
and [3.0, 5.25]
respectively on the two replicas, then the output value from this op where scatter_dim
is 0
will be [4.0]
for the first replica and [7.5]
for the second replica.
ReduceWindow
See also XlaBuilder::ReduceWindow
.
Applies a reduction function to all elements in each window of a sequence of N multi-dimensional arrays, producing a single or a tuple of N multi-dimensional arrays as output. Each output array has the same number of elements as the number of valid positions of the window. A pooling layer can be expressed as a ReduceWindow
. Similar to Reduce
, the applied computation
is always passed the init_values
on the left-hand side.
ReduceWindow(operands..., init_values..., computation, window_dimensions, window_strides, padding)
Arguments | Type | Semantics |
---|---|---|
operands | N XlaOps | A sequence of N multi-dimensional arrays of types T_0,..., T_{N-1} , each representing the base area on which the window is placed. |
init_values | N XlaOps | The N starting values for the reduction, one for each of the N operands. See Reduce for details. |
computation | XlaComputation | Reduction function of type T_0, ..., T_{N-1}, T_0, ..., T_{N-1} -> Collate(T_0, ..., T_{N-1}) , to apply to elements in each window of all the input operands. |
window_dimensions | ArraySlice<int64> | array of integers for window dimension values |
window_strides | ArraySlice<int64> | array of integers for window stride values |
base_dilations | ArraySlice<int64> | array of integers for base dilation values |
window_dilations | ArraySlice<int64> | array of integers for window dilation values |
padding | Padding | padding type for window (Padding::kSame, which pads so as to have the same output shape as input if the stride is 1, or Padding::kValid, which uses no padding and "stops" the window once it no longer fits) |
Where:
- N is required to be greater or equal to 1.
- All input arrays must have the same dimensions.
- If
N = 1
,Collate(T)
isT
. - If
N > 1
,Collate(T_0, ..., T_{N-1})
is a tuple ofN
elements of type(T0,...T{N-1})
.
Below code and figure shows an example of using ReduceWindow
. Input is a matrix of size [4x6] and both window_dimensions and window_stride_dimensions are [2x3].
// Create a computation for the reduction (maximum).
XlaComputation max;
{
XlaBuilder builder(client_, "max");
auto y = builder.Parameter(0, ShapeUtil::MakeShape(F32, {}), "y");
auto x = builder.Parameter(1, ShapeUtil::MakeShape(F32, {}), "x");
builder.Max(y, x);
max = builder.Build().value();
}
// Create a ReduceWindow computation with the max reduction computation.
XlaBuilder builder(client_, "reduce_window_2x3");
auto shape = ShapeUtil::MakeShape(F32, {4, 6});
auto input = builder.Parameter(0, shape, "input");
builder.ReduceWindow(
input,
/*init_val=*/builder.ConstantLiteral(LiteralUtil::MinValue(F32)),
*max,
/*window_dimensions=*/{2, 3},
/*window_stride_dimensions=*/{2, 3},
Padding::kValid);

Stride of 1 in a dimension specifies that the position of a window in the dimension is 1 element away from its adjacent window. In order to specify that no windows overlap with each other, window_stride_dimensions should be equal to window_dimensions. The figure below illustrates the use of two different stride values. Padding is applied to each dimension of the input and the calculations are the same as though the input came in with the dimensions it has after padding.

For a non-trivial padding example, consider computing reduce-window minimum (initial value is MAX_FLOAT
) with dimension 3
and stride 2
over the input array [10000, 1000, 100, 10, 1]
. Padding kValid
computes minimums over two valid windows: [10000, 1000, 100]
and [100, 10, 1]
, resulting in the output [100, 1]
. Padding kSame
first pads the array so that the shape after the reduce-window would be the same as input for stride one by adding initial elements on both sides, getting [MAX_VALUE, 10000, 1000, 100, 10, 1, MAX_VALUE]
. Running reduce-window over the padded array operates on three windows [MAX_VALUE, 10000, 1000]
, [1000, 100, 10]
, [10, 1, MAX_VALUE]
, and yields [1000, 10, 1]
.
The evaluation order of the reduction function is arbitrary and may be non-deterministic. Therefore, the reduction function should not be overly sensitive to reassociation. See the discussion about associativity in the context of Reduce
for more details.
ReplicaId
See also XlaBuilder::ReplicaId
.
Returns the unique ID (U32 scalar) of the replica.
ReplicaId()
The unique ID of each replica is an unsigned integer in the interval [0, N)
, where N
is the number of replicas. Since all the replicas are running the same program, a ReplicaId()
call in the program will return a different value on each replica.
Reshape
See also XlaBuilder::Reshape
and the Collapse
operation.
Reshapes the dimensions of an array into a new configuration.
Reshape(operand, new_sizes)
Reshape(operand, dimensions, new_sizes)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | array of type T |
dimensions | int64 vector | order in which dimensions are collapsed |
new_sizes | int64 vector | vector of sizes of new dimensions |
Conceptually, reshape first flattens an array into a one-dimensional vector of data values, and then refines this vector into a new shape. The input arguments are an arbitrary array of type T, a compile-time-constant vector of dimension indices, and a compile-time-constant vector of dimension sizes for the result. The values in the dimension
vector, if given, must be a permutation of all of T's dimensions; the default if not given is {0, ..., rank - 1}
. The order of the dimensions in dimensions
is from slowest-varying dimension (most major) to fastest-varying dimension (most minor) in the loop nest which collapses the input array into a single dimension. The new_sizes
vector determines the size of the output array. The value at index 0 in new_sizes
is the size of dimension 0, the value at index 1 is the size of dimension 1, and so on. The product of the new_size
dimensions must equal the product of the operand's dimension sizes. When refining the collapsed array into the multidimensional array defined by new_sizes
, the dimensions in new_sizes
are ordered from slowest varying (most major) and to fastest varying (most minor).
For example, let v be an array of 24 elements:
let v = f32[4x2x3] { { {10, 11, 12}, {15, 16, 17} },
{ {20, 21, 22}, {25, 26, 27} },
{ {30, 31, 32}, {35, 36, 37} },
{ {40, 41, 42}, {45, 46, 47} } };
In-order collapse:
let v012_24 = Reshape(v, {0,1,2}, {24});
then v012_24 == f32[24] {10, 11, 12, 15, 16, 17, 20, 21, 22, 25, 26, 27,
30, 31, 32, 35, 36, 37, 40, 41, 42, 45, 46, 47};
let v012_83 = Reshape(v, {0,1,2}, {8,3});
then v012_83 == f32[8x3] { {10, 11, 12}, {15, 16, 17},
{20, 21, 22}, {25, 26, 27},
{30, 31, 32}, {35, 36, 37},
{40, 41, 42}, {45, 46, 47} };
Out-of-order collapse:
let v021_24 = Reshape(v, {1,2,0}, {24});
then v012_24 == f32[24] {10, 20, 30, 40, 11, 21, 31, 41, 12, 22, 32, 42,
15, 25, 35, 45, 16, 26, 36, 46, 17, 27, 37, 47};
let v021_83 = Reshape(v, {1,2,0}, {8,3});
then v021_83 == f32[8x3] { {10, 20, 30}, {40, 11, 21},
{31, 41, 12}, {22, 32, 42},
{15, 25, 35}, {45, 16, 26},
{36, 46, 17}, {27, 37, 47} };
let v021_262 = Reshape(v, {1,2,0}, {2,6,2});
then v021_262 == f32[2x6x2] { { {10, 20}, {30, 40},
{11, 21}, {31, 41},
{12, 22}, {32, 42} },
{ {15, 25}, {35, 45},
{16, 26}, {36, 46},
{17, 27}, {37, 47} } };
As a special case, reshape can transform a single-element array to a scalar and vice versa. For example,
Reshape(f32[1x1] { {5} }, {0,1}, {}) == 5;
Reshape(5, {}, {1,1}) == f32[1x1] { {5} };
Rev (reverse)
See also XlaBuilder::Rev
.
Rev(operand, dimensions)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | array of type T |
dimensions | ArraySlice<int64> | dimensions to reverse |
Reverses the order of elements in the operand
array along the specified dimensions
, generating an output array of the same shape. Each element of the operand array at a multidimensional index is stored into the output array at a transformed index. The multidimensional index is transformed by reversing the index in each dimension to be reversed (ie, if a dimension of size N is one of the reversing dimensions, its index i is transformed into N - 1 - i).
One use for the Rev
operation is to reverse the convolution weight array along the two window dimensions during the gradient computation in neural networks.
RngNormal
See also XlaBuilder::RngNormal
.
Constructs an output of a given shape with random numbers generated following the \(N(\mu, \sigma)\) normal distribution. The parameters \(\mu\) and\(\sigma\), and output shape have to have a floating point elemental type. The parameters furthermore have to be scalar valued.
RngNormal(mu, sigma, shape)
Arguments | Type | Semantics |
---|---|---|
mu | XlaOp | Scalar of type T specifying mean of generated numbers |
sigma | XlaOp | Scalar of type T specifying standard deviation of generated numbers |
shape | Shape | Output shape of type T |
RngUniform
See also XlaBuilder::RngUniform
.
Constructs an output of a given shape with random numbers generated following the uniform distribution over the interval \([a,b)\). The parameters and output element type have to be a boolean type, an integral type or a floating point types, and the types have to be consistent. The CPU and GPU backends currently only support F64, F32, F16, BF16, S64, U64, S32 and U32. Furthermore, the parameters need to be scalar valued. If \(b <= a\) the result is implementation-defined.
RngUniform(a, b, shape)
Arguments | Type | Semantics |
---|---|---|
a | XlaOp | Scalar of type T specifying lower limit of interval |
b | XlaOp | Scalar of type T specifying upper limit of interval |
shape | Shape | Output shape of type T |
RngBitGenerator
Generates an output with a given shape filled with uniform random bits using the specified algorithm (or backend default) and returns an updated state (with the same shape as initial state) and the generated random data.
Initial state is the initial state of the current random number generation. It and the required shape and valid values are dependent on the algorithm used.
The output is guaranteed to be a deterministic function of the initial state but it is not guaranteed to be deterministic between backends and different compiler versions.
RngBitGenerator(algorithm, key, shape)
Arguments | Type | Semantics |
---|---|---|
algorithm | RandomAlgorithm | PRNG algorithm to be used. |
initial_state | XlaOp | Initial state for the PRNG algorithm. |
shape | Shape | Output shape for generated data. |
Available values for algorithm
:
rng_default
: Backend specific algorithm with backend specific shape requirements.rng_three_fry
: ThreeFry counter-based PRNG algorithm. Theinitial_state
shape isu64[2]
with arbitrary values. Salmon et al. SC 2011. Parallel random numbers: as easy as 1, 2, 3.rng_philox
: Philox algorithm to generate random numbers in parallel. Theinitial_state
shape isu64[3]
with arbitrary values. Salmon et al. SC 2011. Parallel random numbers: as easy as 1, 2, 3.
Scatter
The XLA scatter operation generates a sequence of results which are the values of the input array operands
, with several slices (at indices specified by scatter_indices
) updated with the sequence of values in updates
using update_computation
.
See also XlaBuilder::Scatter
.
scatter(operands..., scatter_indices, updates..., update_computation, index_vector_dim, update_window_dims, inserted_window_dims, scatter_dims_to_operand_dims)
Arguments | Type | Semantics |
---|---|---|
operands | Sequence of N XlaOp | N arrays of types T_0, ..., T_N to be scattered into. |
scatter_indices | XlaOp | Array containing the starting indices of the slices that must be scattered to. |
updates | Sequence of N XlaOp | N arrays of types T_0, ..., T_N . updates[i] contains the values that must be used for scattering operands[i] . |
update_computation | XlaComputation | Computation to be used for combining the existing values in the input array and the updates during scatter. This computation should be of type T_0, ..., T_N, T_0, ..., T_N -> Collate(T_0, ..., T_N) . |
index_vector_dim | int64 | The dimension in scatter_indices that contains the starting indices. |
update_window_dims | ArraySlice<int64> | The set of dimensions in updates shape that are window dimensions . |
inserted_window_dims | ArraySlice<int64> | The set of window dimensions that must be inserted into updates shape. |
scatter_dims_to_operand_dims | ArraySlice<int64> | A dimensions map from the scatter indices to the operand index space. This array is interpreted as mapping i to scatter_dims_to_operand_dims[i] . It has to be one-to-one and total. |
indices_are_sorted | bool | Whether the indices are guaranteed to be sorted by the caller. |
Where:
- N is required to be greater or equal to 1.
-
operands
[0
], ...,operands
[N-1
] must all have the same dimensions. -
updates
[0
], ...,updates
[N-1
] must all have the same dimensions. - If
N = 1
,Collate(T)
isT
. - If
N > 1
,Collate(T_0, ..., T_N)
is a tuple ofN
elements of typeT
.
If index_vector_dim
is equal to scatter_indices.rank
we implicitly consider scatter_indices
to have a trailing 1
dimension.
We define update_scatter_dims
of type ArraySlice<int64>
as the set of dimensions in updates
shape that are not in update_window_dims
, in ascending order.
The arguments of scatter should follow these constraints:
Each
updates
array must be of rankupdate_window_dims.size + scatter_indices.rank - 1
.Bounds of dimension
i
in eachupdates
array must conform to the following:- If
i
is present inupdate_window_dims
(ie equal toupdate_window_dims
[k
] for somek
), then the bound of dimensioni
inupdates
must not exceed the corresponding bound ofoperand
after accounting for theinserted_window_dims
(ieadjusted_window_bounds
[k
], whereadjusted_window_bounds
contains the bounds ofoperand
with the bounds at indicesinserted_window_dims
removed). - If
i
is present inupdate_scatter_dims
(ie equal toupdate_scatter_dims
[k
] for somek
), then the bound of dimensioni
inupdates
must be equal to the corresponding bound ofscatter_indices
, skippingindex_vector_dim
(iescatter_indices.shape.dims
[k
], ifk
<index_vector_dim
andscatter_indices.shape.dims
[k+1
] otherwise).
- If
update_window_dims
must be in ascending order, not have any repeating dimension numbers, and be in the range[0, updates.rank)
.inserted_window_dims
must be in ascending order, not have any repeating dimension numbers, and be in the range[0, operand.rank)
.operand.rank
must equal the sum ofupdate_window_dims.size
andinserted_window_dims.size
.scatter_dims_to_operand_dims.size
must be equal toscatter_indices.shape.dims
[index_vector_dim
], and its values must be in the range[0, operand.rank)
.
For a given index U
in each updates
array, the corresponding index I
in the corresponding operands
array into which this update has to be applied is computed as follows:
- Let
G
= {U
[k
] fork
inupdate_scatter_dims
}. UseG
to look up an index vectorS
in thescatter_indices
array such thatS
[i
] =scatter_indices
[Combine(G
,i
)] where Combine(A, b) inserts b at positionsindex_vector_dim
into A. - Create an index
S
in
intooperand
usingS
by scatteringS
using thescatter_dims_to_operand_dims
map. More formally:-
S
in
[scatter_dims_to_operand_dims
[k
]] =S
[k
] ifk
<scatter_dims_to_operand_dims.size
. -
S
in
[_
] =0
otherwise.
-
- Create an index
W
in
into eachoperands
array by scattering the indices atupdate_window_dims
inU
according toinserted_window_dims
. More formally:-
W
in
[window_dims_to_operand_dims
(k
)] =U
[k
] ifk
is inupdate_window_dims
, wherewindow_dims_to_operand_dims
is the monotonic function with domain [0
,update_window_dims.size
) and range [0
,operand.rank
) \inserted_window_dims
. (For example, ifupdate_window_dims.size
is4
,operand.rank
is6
, andinserted_window_dims
is {0
,2
} thenwindow_dims_to_operand_dims
is {0
→1
,1
→3
,2
→4
,3
→5
}). -
W
in
[_
] =0
otherwise.
-
-
I
isW
in
+S
in
where + is element-wise addition.
In summary, the scatter operation can be defined as follows.
- Initialize
output
withoperands
, ie for all indicesJ
, for all indicesO
in theoperands
[J
] array:
output
[J
][O
] =operands
[J
][O
] - For every index
U
in theupdates
[J
] array and the corresponding indexO
in theoperand
[J
] array, ifO
is a valid index foroutput
:
(output
[0
][O
], ...,output
[N-1
][O
]) =update_computation
(output
[0
][O
], ..., ,output
[N-1
][O
],updates
[0
][U
], ...,updates
[N-1
][U
])
The order in which updates are applied is non-deterministic. So, when multiple indices in updates
refer to the same index in operands
, the corresponding value in output
will be non-deterministic.
Note that the first parameter that is passed into the update_computation
will always be the current value from the output
array and the second parameter will always be the value from the updates
array. This is important specifically for cases when the update_computation
is not commutative .
If indices_are_sorted
is set to true then XLA can assume that start_indices
are sorted (in ascending start_index_map
order) by the user. If they are not then the semantics is implementation defined.
Informally, the scatter op can be viewed as an inverse of the gather op, ie the scatter op updates the elements in the input that are extracted by the corresponding gather op.
For a detailed informal description and examples, refer to the "Informal Description" section under Gather
.
Select
See also XlaBuilder::Select
.
Constructs an output array from elements of two input arrays, based on the values of a predicate array.
Select(pred, on_true, on_false)
Arguments | Type | Semantics |
---|---|---|
pred | XlaOp | array of type PRED |
on_true | XlaOp | array of type T |
on_false | XlaOp | array of type T |
The arrays on_true
and on_false
must have the same shape. This is also the shape of the output array. The array pred
must have the same dimensionality as on_true
and on_false
, with the PRED
element type.
For each element P
of pred
, the corresponding element of the output array is taken from on_true
if the value of P
is true
, and from on_false
if the value of P
is false
. As a restricted form of broadcasting , pred
can be a scalar of type PRED
. In this case, the output array is taken wholly from on_true
if pred
is true
, and from on_false
if pred
is false
.
Example with non-scalar pred
:
let pred: PRED[4] = {true, false, false, true};
let v1: s32[4] = {1, 2, 3, 4};
let v2: s32[4] = {100, 200, 300, 400};
==>
Select(pred, v1, v2) = s32[4]{1, 200, 300, 4};
Example with scalar pred
:
let pred: PRED = true;
let v1: s32[4] = {1, 2, 3, 4};
let v2: s32[4] = {100, 200, 300, 400};
==>
Select(pred, v1, v2) = s32[4]{1, 2, 3, 4};
Selections between tuples are supported. Tuples are considered to be scalar types for this purpose. If on_true
and on_false
are tuples (which must have the same shape!) then pred
has to be a scalar of type PRED
.
SelectAndScatter
See also XlaBuilder::SelectAndScatter
.
This operation can be considered as a composite operation that first computes ReduceWindow
on the operand
array to select an element from each window, and then scatters the source
array to the indices of the selected elements to construct an output array with the same shape as the operand array. The binary select
function is used to select an element from each window by applying it across each window, and it is called with the property that the first parameter's index vector is lexicographically less than the second parameter's index vector. The select
function returns true
if the first parameter is selected and returns false
if the second parameter is selected, and the function must hold transitivity (ie, if select(a, b)
and select(b, c)
are true
, then select(a, c)
is also true
) so that the selected element does not depend on the order of the elements traversed for a given window.
The function scatter
is applied at each selected index in the output array. It takes two scalar parameters:
- Current value at the selected index in the output array
- The scatter value from
source
that applies to the selected index
It combines the two parameters and returns a scalar value that's used to update the value at the selected index in the output array. Initially, all indices of the output array are set to init_value
.
The output array has the same shape as the operand
array and the source
array must have the same shape as the result of applying a ReduceWindow
operation on the operand
array. SelectAndScatter
can be used to backpropagate the gradient values for a pooling layer in a neural network.
SelectAndScatter(operand, select, window_dimensions, window_strides, padding, source, init_value, scatter)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | array of type T over which the windows slide |
select | XlaComputation | binary computation of type T, T -> PRED , to apply to all elements in each window; returns true if the first parameter is selected and returns false if the second parameter is selected |
window_dimensions | ArraySlice<int64> | array of integers for window dimension values |
window_strides | ArraySlice<int64> | array of integers for window stride values |
padding | Padding | padding type for window (Padding::kSame or Padding::kValid) |
source | XlaOp | array of type T with the values to scatter |
init_value | XlaOp | scalar value of type T for the initial value of the output array |
scatter | XlaComputation | binary computation of type T, T -> T , to apply each scatter source element with its destination element |
The figure below shows examples of using SelectAndScatter
, with the select
function computing the maximal value among its parameters. Note that when the windows overlap, as in the figure (2) below, an index of the operand
array may be selected multiple times by different windows. In the figure, the element of value 9 is selected by both of the top windows (blue and red) and the binary addition scatter
function produces the output element of value 8 (2 + 6).

The evaluation order of the scatter
function is arbitrary and may be non-deterministic. Therefore, the scatter
function should not be overly sensitive to reassociation. See the discussion about associativity in the context of Reduce
for more details.
Send
See also XlaBuilder::Send
.
Send(operand, channel_handle)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | data to send (array of type T) |
channel_handle | ChannelHandle | unique identifier for each send/recv pair |
Sends the given operand data to a Recv
instruction in another computation that shares the same channel handle. Does not return any data.
Similar to the Recv
operation, the client API of Send
operation represents synchronous communication, and is internally decomposed into 2 HLO instructions ( Send
and SendDone
) to enable asynchronous data transfers. See also HloInstruction::CreateSend
and HloInstruction::CreateSendDone
.
Send(HloInstruction operand, int64 channel_id)
Initiates an asynchronous transfer of the operand to the resources allocated by the Recv
instruction with the same channel id. Returns a context, which is used by a following SendDone
instruction to wait for the completion of the data transfer. The context is a tuple of {operand (shape), request identifier (U32)} and it can only be used by a SendDone
instruction.
SendDone(HloInstruction context)
Given a context created by a Send
instruction, waits for the data transfer to complete. The instruction does not return any data.
Scheduling of channel instructions
The execution order of the 4 instructions for each channel ( Recv
, RecvDone
, Send
, SendDone
) is as below.

-
Recv
happens beforeSend
-
Send
happens beforeRecvDone
-
Recv
happens beforeRecvDone
-
Send
happens beforeSendDone
When the backend compilers generate a linear schedule for each computation that communicates via channel instructions, there must not be cycles across the computations. For example, below schedules lead to deadlocks.

Slice
See also XlaBuilder::Slice
.
Slicing extracts a sub-array from the input array. The sub-array is of the same rank as the input and contains the values inside a bounding box within the input array where the dimensions and indices of the bounding box are given as arguments to the slice operation.
Slice(operand, start_indices, limit_indices, strides)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | N dimensional array of type T |
start_indices | ArraySlice<int64> | List of N integers containing the starting indices of the slice for each dimension. Values must be greater than or equal to zero. |
limit_indices | ArraySlice<int64> | List of N integers containing the ending indices (exclusive) for the slice for each dimension. Each value must be greater than or equal to the respective start_indices value for the dimension and less than or equal to the size of the dimension. |
strides | ArraySlice<int64> | List of N integers that decides the input stride of the slice. The slice picks every strides[d] element in dimension d . |
1-dimensional example:
let a = {0.0, 1.0, 2.0, 3.0, 4.0}
Slice(a, {2}, {4}) produces:
{2.0, 3.0}
2-dimensional example:
let b =
{ {0.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0},
{9.0, 10.0, 11.0} }
Slice(b, {2, 1}, {4, 3}) produces:
{ { 7.0, 8.0},
{10.0, 11.0} }
Sort
See also XlaBuilder::Sort
.
Sort(operands, comparator, dimension, is_stable)
Arguments | Type | Semantics |
---|---|---|
operands | ArraySlice<XlaOp> | The operands to sort. |
comparator | XlaComputation | The comparator computation to use. |
dimension | int64 | The dimension along which to sort. |
is_stable | bool | Whether stable sorting should be used. |
If only one operand is provided:
If the operand is a rank-1 tensor (an array), the result is a sorted array. If you want to sort the array into ascending order, the comparator should perform a less-than comparison. Formally, after the array is sorted, it holds for all index positions
i, j
withi < j
that eithercomparator(value[i], value[j]) = comparator(value[j], value[i]) = false
orcomparator(value[i], value[j]) = true
.If the operand has higher rank, the operand is sorted along the provided dimension. For example, for a rank-2 tensor (a matrix), a dimension value of
0
will independently sort every column, and a dimension value of1
will independently sort each row. If no dimension number is provided, then the last dimension is chosen by default. For the dimension which is sorted, the same sorting order applies as in the rank-1 case.
If n > 1
operands are provided:
All
n
operands must be tensors with the same dimensions. The element types of the tensors may be different.All operands are sorted together, not individually. Conceptually the operands are treated as a tuple. When checking whether the elements of each operand at index positions
i
andj
need to be swapped, the comparator is called with2 * n
scalar parameters, where parameter2 * k
corresponds to the value at positioni
from thek-th
operand, and parameter2 * k + 1
corresponds to the value at positionj
from thek-th
operand. Usually, the comparator would thus compare parameters2 * k
and2 * k + 1
with each other and possibly use other parameter pairs as tie breakers.The result is a tuple that consists of the operands in sorted order (along the provided dimension, as above). The
i-th
operand of the tuple corresponds to thei-th
operand of Sort.
For example, if there are three operands operand0 = [3, 1]
, operand1 = [42, 50]
, operand2 = [-3.0, 1.1]
, and the comparator compares only the values of operand0
with less-than, then the output of the sort is the tuple ([1, 3], [50, 42], [1.1, -3.0])
.
If is_stable
is set to true, the sort is guaranteed to be stable, that is, if there are elements which are considered to be equal by the comparator, the relative order of the equal values is preserved. Two elements e1
and e2
are equal if and only if comparator(e1, e2) = comparator(e2, e1) = false
. By default, is_stable
is set to false.
Top-K
See also the jax.lax.top_k
operation.
TopK(operand)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | N-dimensional array |
k | int64 | Integer specifying the number of top entries. |
comparator | XlaComputation | The comparator computation to use. |
Returns top k
values and their indices as a tuple, along the last dimension of the operand using the given comparator
(for usual topk behavior, it should be strict-greater-than operation).
For example, given strict >
operator, k=1
and the following operand of shape f32[2,3]
:
[[0.1, 0.3, 0.1], [0.7, 0.2, -0.1]]
The TopK application returns the following tuple of shape (f32[2,1], s32[2,1])
:
([[0.3], [0.7]], [[1], [0]])
Transpose
See also the tf.reshape
operation.
Transpose(operand)
Arguments | Type | Semantics |
---|---|---|
operand | XlaOp | The operand to transpose. |
permutation | ArraySlice<int64> | How to permute the dimensions. |
Permutes the operand dimensions with the given permutation, so ∀ i . 0 ≤ i < rank ⇒ input_dimensions[permutation[i]] = output_dimensions[i]
.
This is the same as Reshape(operand, permutation, Permute(permutation, operand.shape.dimensions)).
TriangularSolve
See also XlaBuilder::TriangularSolve
.
Solves systems of linear equations with lower or upper triangular coefficient matrices by forward- or back-substitution. Broadcasting along leading dimensions, this routine solves one of the matrix systems op(a) * x = b
, or x * op(a) = b
, for the variable x
, given a
and b
, where op(a)
is either op(a) = a
, or op(a) = Transpose(a)
, or op(a) = Conj(Transpose(a))
.
TriangularSolve(a, b, left_side, lower, unit_diagonal, transpose_a)
Arguments | Type | Semantics |
---|---|---|
a | XlaOp | a rank > 2 array of a complex or floating-point type with shape [..., M, M] . |
b | XlaOp | a rank > 2 array of the same type with shape [..., M, K] if left_side is true, [..., K, M] otherwise. |
left_side | bool | indicates whether to solve a system of the form op(a) * x = b ( true ) or x * op(a) = b ( false ). |
lower | bool | whether to use the upper or lower triangle of a . |
unit_diagonal | bool | if true , the diagonal elements of a are assumed to be 1 and not accessed. |
transpose_a | Transpose | whether to use a as is, transpose it or take its conjugate transpose. |
Input data is read only from the lower/upper triangle of a
, depending on the value of lower
. Values from the other triangle are ignored. Output data is returned in the same triangle; the values in the other triangle are implementation-defined and may be anything.
If the rank of a
and b
are greater than 2, they are treated as batches of matrices, where all except the minor 2 dimensions are batch dimensions. a
and b
must have equal batch dimensions.
Tuple
See also XlaBuilder::Tuple
.
A tuple containing a variable number of data handles, each of which has its own shape.
This is analogous to std::tuple
in C++. Conceptually:
let v: f32[10] = f32[10]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
let s: s32 = 5;
let t: (f32[10], s32) = tuple(v, s);
Tuples can be deconstructed (accessed) via the GetTupleElement
operation.
While
See also XlaBuilder::While
.
While(condition, body, init)
Arguments | Type | Semantics |
---|---|---|
condition | XlaComputation | XlaComputation of type T -> PRED which defines the termination condition of the loop. |
body | XlaComputation | XlaComputation of type T -> T which defines the body of the loop. |
init | T | Initial value for the parameter of condition and body . |
Sequentially executes the body
until the condition
fails. This is similar to a typical while loop in many other languages except for the differences and restrictions listed below.
- A
While
node returns a value of typeT
, which is the result from the last execution of thebody
. - The shape of the type
T
is statically determined and must be the same across all iterations.
The T parameters of the computations are initialized with the init
value in the first iteration and are automatically updated to the new result from body
in each subsequent iteration.
One main use case of the While
node is to implement the repeated execution of training in neural networks. Simplified pseudocode is shown below with a graph that represents the computation. The code can be found in while_test.cc
. The type T
in this example is a Tuple
consisting of an int32
for the iteration count and a vector[10]
for the accumulator. For 1000 iterations, the loop keeps adding a constant vector to the accumulator.
// Pseudocode for the computation.
init = {0, zero_vector[10]} // Tuple of int32 and float[10].
result = init;
while (result(0) < 1000) {
iteration = result(0) + 1;
new_vector = result(1) + constant_vector[10];
result = {iteration, new_vector};
}
