ความหมายการดำเนินงาน

ข้อมูลต่อไปนี้จะอธิบายความหมายของการดำเนินการที่กำหนดไว้ในอินเทอร์เฟ XlaBuilder โดยทั่วไปแล้ว การดำเนินการเหล่านี้จะแมปแบบหนึ่งต่อหนึ่งกับการดำเนินการที่กำหนดไว้ในอินเทอร์เฟซ RPC ใน xla_data.proto

หมายเหตุเกี่ยวกับการตั้งชื่อ: ประเภทข้อมูลทั่วไปที่ XLA เกี่ยวข้องคือองค์ประกอบการเก็บอาร์เรย์ N มิติของประเภทเครื่องแบบบางประเภท (เช่น 32 บิตทศนิยม) ตลอดทั้งเอกสารประกอบ อาร์เรย์ ถูกใช้เพื่อแสดงอาร์เรย์มิติตามอำเภอใจ เพื่อความสะดวก กรณีพิเศษจะมีชื่อเฉพาะเจาะจงและคุ้นเคยมากขึ้น ตัวอย่างเช่น เวกเตอร์ เป็นอาร์เรย์ 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 มิติการต่อข้อมูล
shard_count 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 ใช้สำหรับการสื่อสารข้ามโมดูล: เฉพาะการดำเนินการ all-gather ที่มี channel_id เดียวกันเท่านั้นที่สามารถสื่อสารระหว่างกันได้

รูปร่างเอาต์พุตคือรูปร่างอินพุตโดยที่ all_gather_dim ทำให้ shard_count ใหญ่ขึ้นเป็นเท่า ตัวอย่างเช่น หากมีสองเรพลิกาและตัวถูกดำเนินการมีค่า [1.0, 2.5] และ [3.0, 5.25] ตามลำดับบนเรพลิกาทั้งสอง ดังนั้นค่าเอาต์พุตจาก op นี้ โดยที่ all_gather_dim เป็น 0 จะเป็น [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 คือรายการของกลุ่มเรพลิกาที่มีการดำเนินการลดขนาด (รหัสแบบจำลองสำหรับเรพลิกาปัจจุบันสามารถดึงข้อมูลได้โดยใช้ ReplicaId ) replica_groups จะต้องว่างเปล่า (ในกรณีนี้ เรพลิกาทั้งหมดอยู่ในกลุ่มเดียว) หรือมีจำนวนองค์ประกอบเท่ากันกับจำนวนเรพลิกา ตัวอย่างเช่น replica_groups = {0, 2}, {1, 3} ดำเนินการลดระหว่างเรพลิกา 0 และ 2 และ 1 และ 3
  • channel_id ใช้สำหรับการสื่อสารข้ามโมดูล: เฉพาะการดำเนินการ all-reduce ที่มี channel_id เดียวกันเท่านั้นที่สามารถสื่อสารระหว่างกันได้

รูปร่างผลลัพธ์จะเหมือนกับรูปร่างอินพุต ตัวอย่างเช่น หากมีสองเรพลิกาและตัวถูกดำเนินการมีค่า [1.0, 2.5] และ [3.0, 5.25] ตามลำดับบนทั้งสองเรพลิกา ดังนั้นค่าเอาท์พุตจากการคำนวณ op นี้และการคำนวณผลรวมจะเป็น [4.0, 7.75] บนทั้งสองเรพลิกา แบบจำลอง หากอินพุตเป็นสิ่งทูเปิล เอาต์พุตก็จะเป็นทูเพิลเช่นกัน

การคำนวณผลลัพธ์ของ AllReduce จำเป็นต้องมีหนึ่งอินพุตจากแต่ละเรพลิกา ดังนั้นหากเรพลิกาหนึ่งรันโหนด AllReduce มากกว่าครั้งอื่น เรพลิกาเดิมจะรอตลอดไป เนื่องจากเรพลิกาทั้งหมดกำลังรันโปรแกรมเดียวกัน จึงมีหลายวิธีที่จะเกิดขึ้นได้ แต่เป็นไปได้เมื่อเงื่อนไขของ while loop ขึ้นอยู่กับข้อมูลจากการป้อนเข้า และข้อมูลที่ถูกป้อนเข้าทำให้ while loop วนซ้ำมากขึ้น บนแบบจำลองหนึ่งมากกว่าอีกแบบจำลองหนึ่ง

ออลทูออล

ดูเพิ่มเติมที่ XlaBuilder::AllToAll

AllToAll เป็นการดำเนินการแบบรวมที่ส่งข้อมูลจากคอร์ทั้งหมดไปยังคอร์ทั้งหมด มีสองขั้นตอน:

  1. เฟสกระจาย. ในแต่ละคอร์ ตัวถูกดำเนินการจะถูกแบ่งออกเป็นจำนวน split_count ของบล็อกตาม split_dimensions และบล็อกจะกระจัดกระจายไปยังคอร์ทั้งหมด เช่น บล็อกที่ ith ถูกส่งไปยังคอร์ที่ i
  2. เฟสรวมตัว. แต่ละคอร์จะเชื่อมบล็อกที่ได้รับเข้าด้วยกันตาม concat_dimension

แกนที่เข้าร่วมสามารถกำหนดค่าได้โดย:

  • replica_groups : แต่ละ ReplicaGroup มีรายการรหัสแบบจำลองที่มีส่วนร่วมในการคำนวณ (รหัสแบบจำลองสำหรับแบบจำลองปัจจุบันสามารถดึงข้อมูลได้โดยใช้ ReplicaId ) AllToAll จะถูกนำไปใช้ภายในกลุ่มย่อยตามลำดับที่ระบุ ตัวอย่างเช่น replica_groups = { {1,2,3}, {4,5,0} } หมายความว่า AllToAll จะถูกนำไปใช้ภายในแบบจำลอง {1, 2, 3} และในเฟสรวบรวม และบล็อกที่ได้รับจะ ถูกต่อกันในลำดับเดียวกันคือ 1, 2, 3 จากนั้น AllToAll อื่นจะถูกใช้ภายในเรพลิกา 4, 5, 0 และลำดับการต่อกันก็คือ 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 แต่ละกลุ่มจะมีรายการรหัสจำลอง

ด้านล่างแสดงตัวอย่างของ 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);

ในตัวอย่างนี้ มี 4 คอร์ที่เข้าร่วม Alltoall ในแต่ละคอร์ ตัวถูกดำเนินการจะถูกแบ่งออกเป็น 4 ส่วนตามมิติ 1 ดังนั้นแต่ละส่วนจึงมีรูปร่าง 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 ):

\[ \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 แสดงถึงค่าโมเมนต์ระหว่างแบทช์และมิติเชิงพื้นที่

ประเภทเอาต์พุตคือ tuple ของสามจุดจับ:

เอาท์พุต พิมพ์ ความหมาย
grad_operand XlaOp การไล่ระดับสีด้วยความเคารพต่อ operand อินพุต (\( \nabla x\))
grad_scale XlaOp การไล่ระดับสีตาม scale อินพุต (\( \nabla \gamma\))
grad_offset XlaOp การไล่ระดับสีที่เกี่ยวข้องกับอินพุต offset (\( \nabla \beta\))

การอนุมานแบบ BatchNorm

ดูเพิ่มเติมที่ 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 เทียบเท่ากับการเรียก BatchNormTraining โดยไม่มีการคำนวณ mean และ variance สำหรับแต่ละชุด โดยจะใช้ mean อินพุตและ variance แทนเป็นค่าประมาณ วัตถุประสงค์ของการดำเนินการนี้คือเพื่อลดเวลาแฝงในการอนุมาน จึงเป็นที่มาของชื่อ BatchNormInference

เอาต์พุตเป็นอาเรย์มาตรฐานขนาด n มิติที่มีรูปร่างเหมือนกับ operand อินพุต

การฝึกอบรม BatchNorm

ดูเพิ่มเติมที่ 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

อัลกอริทึมจะเป็นดังนี้สำหรับแต่ละชุดใน operand \(x\) ที่มีองค์ประกอบ m โดยมี w และ h เป็นขนาดของมิติเชิงพื้นที่ (สมมติว่า operand เป็นอาร์เรย์ 4 มิติ):

  • คำนวณค่าเฉลี่ยแบทช์ \(\mu_l\) สำหรับแต่ละคุณลักษณะ 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\)

ค่าเอปไซลอนซึ่งโดยปกติจะเป็นตัวเลขเล็กๆ จะถูกเพิ่มเข้าไปเพื่อหลีกเลี่ยงข้อผิดพลาดในการหารด้วยศูนย์

ประเภทเอาต์พุตคือสิ่งอันดับสามของ XlaOp :

เอาท์พุต พิมพ์ ความหมาย
output XlaOp อาร์เรย์มิติที่มีรูปร่างเหมือนกับตัว operand อินพุต (y)
batch_mean XlaOp อาร์เรย์ 1 มิติ (\(\mu\))
batch_var XlaOp อาร์เรย์ 1 มิติ (\(\sigma^2\))

batch_mean และ batch_var คือช่วงเวลาที่คำนวณระหว่างแบตช์และมิติเชิงพื้นที่โดยใช้สูตรด้านบน

BitcastConvertType

ดูเพิ่มเติมที่ XlaBuilder::BitcastConvertType

คล้ายกับ tf.bitcast ใน TensorFlow ดำเนินการบิตคาสต์ตามองค์ประกอบตั้งแต่รูปร่างข้อมูลไปจนถึงรูปร่างเป้าหมาย ขนาดอินพุตและเอาต์พุตต้องตรงกัน: เช่น องค์ประกอบ s32 กลายเป็นองค์ประกอบ f32 ผ่านรูทีนบิตคาสต์ และองค์ประกอบ s32 หนึ่งรายการจะกลายเป็นองค์ประกอบ s8 สี่องค์ประกอบ Bitcast ถูกนำมาใช้เป็นการร่ายระดับต่ำ ดังนั้นเครื่องที่มีการแสดงจุดลอยตัวต่างกันจะให้ผลลัพธ์ที่แตกต่างกัน

BitcastConvertType(operand, new_element_type)

ข้อโต้แย้ง พิมพ์ ความหมาย
operand XlaOp อาร์เรย์ประเภท T พร้อม dims D
new_element_type PrimitiveType ประเภท U

ขนาดของตัวถูกดำเนินการและรูปร่างเป้าหมายจะต้องตรงกัน นอกเหนือจากมิติสุดท้ายซึ่งจะเปลี่ยนแปลงตามอัตราส่วนของขนาดดั้งเดิมก่อนและหลังการแปลง

ประเภทองค์ประกอบต้นทางและปลายทางต้องไม่เป็นสิ่งอันดับ

การแปลง Bitcast เป็นประเภทดั้งเดิมที่มีความกว้างต่างกัน

คำสั่ง 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 เป็นสเกลาร์ f32 ที่มีค่า 2.0f และ broadcast_sizes คือ {2, 3} ผลลัพธ์จะเป็นอาร์เรย์ที่มีรูปร่าง f32[2, 3] และค่าทั้งหมดในผลลัพธ์จะเป็น 2.0f

ออกอากาศInDim

ดูเพิ่มเติมที่ XlaBuilder::BroadcastInDim

ขยายขนาดและอันดับของอาร์เรย์โดยการทำซ้ำข้อมูลในอาร์เรย์

BroadcastInDim(operand, out_dim_size, broadcast_dimensions)

ข้อโต้แย้ง พิมพ์ ความหมาย
operand XlaOp อาร์เรย์ที่จะทำซ้ำ
out_dim_size ArraySlice<int64> ขนาดของมิติของรูปร่างเป้าหมาย
broadcast_dimensions ArraySlice<int64> มิติใดในรูปร่างเป้าหมายแต่ละมิติของรูปร่างตัวถูกดำเนินการจะสอดคล้องกัน

คล้ายกับ Broadcast แต่อนุญาตให้เพิ่มมิติได้ทุกที่และขยายมิติที่มีอยู่ด้วยขนาด 1

operand ถูกถ่ายทอดไปยังรูปร่างที่อธิบายโดย out_dim_size broadcast_dimensions จะจับคู่ขนาดของ operand กับขนาดของรูปร่างเป้าหมาย กล่าวคือ มิติที่ i ของตัวถูกดำเนินการจะถูกแมปกับมิติของ Broadcast_Dimension[i]' ของรูปร่างเอาต์พุต มิติของ operand ต้องมีขนาด 1 หรือมีขนาดเท่ากันกับมิติในรูปร่างเอาต์พุตที่แมปไว้ มิติที่เหลือจะเต็มไปด้วยมิติขนาด 1 จากนั้นการถ่ายทอดมิติที่เสื่อมทรามจะออกอากาศตามมิติที่เสื่อมถอยเหล่านี้เพื่อให้ได้รูปร่างเอาท์พุต ความหมายมีการอธิบายโดยละเอียดใน หน้าการออกอากาศ

เรียก

ดูเพิ่มเติมที่ XlaBuilder::Call

เรียกใช้การคำนวณด้วยอาร์กิวเมนต์ที่กำหนด

Call(computation, args...)

ข้อโต้แย้ง พิมพ์ ความหมาย
computation XlaComputation การคำนวณประเภท T_0, T_1, ..., T_{N-1} -> S พร้อมพารามิเตอร์ N ประเภทตามอำเภอใจ
args ลำดับของ N XlaOp s ไม่มีข้อโต้แย้งประเภทใดก็ได้

ความสมบูรณ์และประเภทของ args ต้องตรงกับพารามิเตอร์ของ computation อนุญาตให้ไม่มี args

โชเลสกี้

ดูเพิ่มเติมที่ XlaBuilder::Cholesky

คำนวณ การสลายตัวของ Cholesky ของชุดเมทริกซ์แน่นอนเชิงบวกแบบสมมาตร (เฮอร์มิเทียน)

Cholesky(a, lower)

ข้อโต้แย้ง พิมพ์ ความหมาย
a XlaOp อันดับ > 2 อาร์เรย์ของประเภทจุดเชิงซ้อนหรือจุดลอยตัว
lower bool ว่าจะใช้สามเหลี่ยมบนหรือล่าง a

หาก lower เป็น true ให้คำนวณเมทริกซ์สามเหลี่ยมล่าง l เช่นนั้น \( a = l . l^T \)หาก lower เป็น false ให้คำนวณเมทริกซ์สามเหลี่ยม u เช่นนั้น \( a = u^T . u \)

ข้อมูลอินพุตจะอ่านได้จากสามเหลี่ยมล่าง/บนของ a เท่านั้น ขึ้นอยู่กับค่าของ lower ค่าจากสามเหลี่ยมอื่นจะถูกละเว้น ข้อมูลเอาต์พุตจะถูกส่งกลับในรูปสามเหลี่ยมเดียวกัน ค่าในสามเหลี่ยมอีกอันเป็นค่าที่กำหนดโดยการดำเนินการและอาจเป็นอะไรก็ได้

หากอันดับของ a มากกว่า 2 a จะถือเป็นชุดของเมทริกซ์ โดยที่ทั้งหมดยกเว้นมิติรอง 2 จะเป็นมิติชุด

หาก a ไม่แน่นอนเชิงบวกแบบสมมาตร (เฮอร์มิเทียน) ผลลัพธ์จะเป็นการนำไปปฏิบัติ

ที่หนีบ

ดูเพิ่มเติมที่ XlaBuilder::Clamp

หนีบตัวถูกดำเนินการให้อยู่ในช่วงระหว่างค่าต่ำสุดและค่าสูงสุด

Clamp(min, operand, max)

ข้อโต้แย้ง พิมพ์ ความหมาย
min XlaOp อาร์เรย์ประเภท T
operand XlaOp อาร์เรย์ประเภท T
max XlaOp อาร์เรย์ประเภท T

เมื่อกำหนดตัวถูกดำเนินการและค่าต่ำสุดและสูงสุด จะส่งคืนค่าตัวถูกดำเนินการหากอยู่ในช่วงระหว่างค่าต่ำสุดและสูงสุด มิฉะนั้นจะส่งกลับค่าต่ำสุดหากตัวถูกดำเนินการต่ำกว่าช่วงนี้ หรือค่าสูงสุดหากตัวถูกดำเนินการอยู่เหนือช่วงนี้ นั่นคือ clamp(a, x, b) = min(max(a, x), b)

ทั้งสามอาร์เรย์จะต้องมีรูปร่างเหมือนกัน อีกทางหนึ่ง เนื่องจากเป็นรูปแบบ การออกอากาศ ที่จำกัด 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 :

  • สองคู่ไม่ควรมีรหัสเรพลิกาเป้าหมายเดียวกัน และไม่ควรมีรหัสเรพลิกาแหล่งที่มาเดียวกัน
  • หากรหัสเรพลิกาไม่ใช่เป้าหมายในคู่ใดๆ เอาต์พุตบนเรพลิกานั้นจะเป็นเทนเซอร์จะประกอบด้วย 0 ที่มีรูปร่างเหมือนกับอินพุต

เชื่อมต่อกัน

ดูเพิ่มเติมที่ XlaBuilder::ConcatInDim

เชื่อมต่อการเขียนอาร์เรย์จากตัวถูกดำเนินการอาร์เรย์หลายตัว อาร์เรย์มีอันดับเดียวกันกับตัวถูกดำเนินการอาร์เรย์อินพุตแต่ละตัว (ซึ่งจะต้องมีอันดับเดียวกัน) และมีอาร์กิวเมนต์ตามลำดับที่ระบุไว้

Concatenate(operands..., dimension)

ข้อโต้แย้ง พิมพ์ ความหมาย
operands ลำดับของ N XlaOp อาร์เรย์ N ประเภท T ที่มีขนาด [L0, L1, ...] ต้องใช้ N >= 1
dimension int64 ค่าในช่วง [0, N) ที่ตั้งชื่อมิติที่จะต่อกันระหว่าง operands

ยกเว้น dimension มิติทั้งหมดจะต้องเหมือนกัน เนื่องจาก XLA ไม่รองรับอาร์เรย์ "ragged" โปรดทราบว่าไม่สามารถต่อค่าอันดับ 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 XlaComputation ประเภท \(T_0 \to S\)
false_operand XlaOp อาร์กิวเมนต์ประเภท \(T_1\)
false_computation XlaComputation XlaComputation ประเภท \(T_1 \to S\)

ดำเนินการ true_computation หาก pred เป็น true , false_computation หาก pred เป็น false และส่งกลับผลลัพธ์

true_computation ต้องใช้อาร์กิวเมนต์ประเภท \(T_0\) ในอาร์กิวเมนต์เดียว และจะถูกเรียกใช้ด้วย true_operand ซึ่งต้องเป็นประเภทเดียวกัน false_computation ต้องใช้อาร์กิวเมนต์ประเภท \(T_1\) ในอาร์กิวเมนต์เดียว และจะถูกเรียกใช้ด้วย false_operand ซึ่งต้องเป็นประเภทเดียวกัน ประเภทของค่าที่ส่งคืนของ true_computation และ false_computation จะต้องเหมือนกัน

โปรดทราบว่าจะมีการดำเนินการ true_computation และ false_computation เพียงรายการเดียวเท่านั้น ขึ้นอยู่กับค่าของ pred

Conditional(branch_index, branch_computations, branch_operands)

ข้อโต้แย้ง พิมพ์ ความหมาย
branch_index XlaOp สเกลาร์ประเภท S32
branch_computations ลำดับของ N XlaComputation XlaComputations ประเภท \( T_0 \to S , T_1 \to S , ..., T_{N-1} \to S \)
branch_operands ลำดับของ N XlaOp อาร์กิวเมนต์ประเภท \( T_0 , T_1 , ..., T_{N-1} \)

ดำเนินการ branch_computations[branch_index] และส่งคืนผลลัพธ์ หาก branch_index เป็น S32 ซึ่งเป็น < 0 หรือ >= N ดังนั้น branch_computations[N-1] จะถูกดำเนินการเป็นสาขาเริ่มต้น

แต่ละ branch_computations[b] จะต้องรับอาร์กิวเมนต์ประเภท T_b เดียวและจะถูกเรียกใช้ด้วย branch_operands[b] ซึ่งต้องเป็นประเภทเดียวกัน ประเภทของค่าที่ส่งคืนของแต่ละ branch_computations[b] จะต้องเหมือนกัน

โปรดทราบว่าจะมีการดำเนินการ branch_computations เพียงรายการเดียวเท่านั้น ขึ้นอยู่กับค่าของ branch_index

Conv. (การบิด)

ดูเพิ่มเติมที่ XlaBuilder::Conv

ในฐานะ ConvWithGeneralPadding แต่ช่องว่างภายในจะถูกระบุแบบสั้นว่า SAME หรือ VALID SAME padding จะรองอินพุต ( lhs ) ด้วยศูนย์เพื่อให้เอาต์พุตมีรูปร่างเหมือนกับอินพุตเมื่อไม่ได้คำนึงถึงการก้าวย่าง การเติมที่ถูกต้องนั้นหมายความว่าไม่มีการเติม

ConvWithGeneralPadding (การบิด)

ดูเพิ่มเติมที่ XlaBuilder::ConvWithGeneralPadding

คำนวณการบิดแบบที่ใช้ในโครงข่ายประสาทเทียม ในที่นี้ การบิดสามารถคิดได้ว่าเป็นหน้าต่างขนาด n เคลื่อนที่ผ่านพื้นที่ฐานขนาด n มิติ และทำการคำนวณสำหรับแต่ละตำแหน่งที่เป็นไปได้ของหน้าต่าง

ข้อโต้แย้ง พิมพ์ ความหมาย
lhs XlaOp อันดับ n+2 อาร์เรย์ของอินพุต
rhs XlaOp อันดับ n+2 อาร์เรย์ของน้ำหนักเคอร์เนล
window_strides ArraySlice<int64> อาร์เรย์ลำดับที่ 2 ของความก้าวหน้าของเคอร์เนล
padding ArraySlice< pair<int64, int64>> อาร์เรย์ลำดับที่ 3 ของช่องว่างภายใน (ต่ำ, สูง)
lhs_dilation ArraySlice<int64> อาร์เรย์ปัจจัยการขยายและ 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 ควรเท่ากับขนาดของมิติ z ในหน่วย lhs
  • spatial_dims : อธิบายมิติ n พื้นที่ที่กำหนดหน้าต่างลำดับที่เคลื่อนผ่านพื้นที่ฐาน

อาร์กิวเมนต์ window_strides ระบุก้าวย่างของหน้าต่างแบบหมุนวนในมิติเชิงพื้นที่ ตัวอย่างเช่น หากก้าวในมิติอวกาศแรกคือ 3 หน้าต่างจะวางได้เฉพาะในพิกัดที่ดัชนีอวกาศแรกหารด้วย 3 ลงตัวเท่านั้น

อาร์กิวเมนต์ padding จะระบุจำนวนการเติมเป็นศูนย์ที่จะใช้กับพื้นที่ฐาน จำนวนการเติมสามารถเป็นลบได้ -- ค่าสัมบูรณ์ของการเติมลบจะระบุจำนวนองค์ประกอบที่จะลบออกจากมิติที่ระบุก่อนที่จะทำการบิด padding[0] ระบุช่องว่างภายในสำหรับมิติ y และ padding[1] ระบุช่องว่างภายในสำหรับมิติ x แต่ละคู่มีช่องว่างภายในต่ำเป็นองค์ประกอบแรกและมีช่องว่างภายในสูงเป็นองค์ประกอบที่สอง การเสริมต่ำจะใช้ในทิศทางของดัชนีด้านล่าง ในขณะที่การเสริมสูงจะใช้ในทิศทางของดัชนีที่สูงกว่า ตัวอย่างเช่น หาก padding[1] คือ (2,3) ก็จะมีช่องว่างภายใน 2 ศูนย์ทางด้านซ้ายและ 3 ศูนย์ทางด้านขวาในมิติเชิงพื้นที่ที่สอง การใช้ช่องว่างภายในเทียบเท่ากับการแทรกค่าศูนย์เดียวกันเหล่านั้นลงในอินพุต ( lhs ) ก่อนที่จะทำการบิด

อาร์กิวเมนต์ lhs_dilation และ rhs_dilation ระบุปัจจัยการขยายที่จะใช้กับ lhs และ rhs ตามลำดับในแต่ละมิติเชิงพื้นที่ หากปัจจัยการขยายในมิติเชิงพื้นที่คือ d ดังนั้นรู d-1 จะถูกวางโดยปริยายระหว่างแต่ละรายการในมิตินั้น ซึ่งจะทำให้ขนาดของอาร์เรย์เพิ่มขึ้น หลุมนั้นเต็มไปด้วยค่า no-op ซึ่งสำหรับการบิดหมายถึงศูนย์

การขยายตัวของ rhs เรียกอีกอย่างว่าการบิดแบบรุนแรง ดูรายละเอียดเพิ่มเติมที่ 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-th ถูกใช้ร่วมกันเพื่อคำนวณ 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 และทำเช่นเดียวกันกับคุณสมบัติเอาต์พุต จากนั้น สำหรับแต่ละกลุ่มเหล่านี้ เราจะทำการบิดแบบคู่และต่อเอาต์พุตตามมิติคุณลักษณะเอาต์พุต ความหมายในการดำเนินงานของมิติอื่นๆ ทั้งหมด (คุณลักษณะและเชิงพื้นที่) ยังคงเหมือนเดิม

ตำแหน่งที่ถูกต้องของหน้าต่างหมุนวนจะพิจารณาจากก้าวย่างและขนาดของพื้นที่ฐานหลังการเสริม

เพื่ออธิบายว่าการบิดตัวทำอะไร ให้พิจารณาการบิดแบบ 2 มิติ และเลือกพิกัด batch ช์คงที่ , z , y , x ในเอาต์พุต จากนั้น (y,x) คือตำแหน่งของมุมหนึ่งของหน้าต่างภายในพื้นที่ฐาน (เช่น มุมซ้ายบน ขึ้นอยู่กับว่าคุณตีความมิติเชิงพื้นที่อย่างไร) ตอนนี้เรามีหน้าต่าง 2 มิติ ซึ่งนำมาจากพื้นที่ฐาน โดยที่จุด 2 มิติแต่ละจุดเชื่อมโยงกับเวกเตอร์ 1 มิติ ดังนั้นเราจึงได้กล่อง 3 มิติ จากเคอร์เนล Convolutional เนื่องจากเราแก้ไขพิกัดเอาต์พุต z เราจึงมีกล่อง 3 มิติด้วย กล่องทั้งสองมีขนาดเท่ากัน ดังนั้นเราจึงสามารถหาผลรวมของผลิตภัณฑ์เชิงองค์ประกอบระหว่างกล่องทั้งสองได้ (คล้ายกับผลคูณดอท) นั่นคือมูลค่าเอาท์พุต

โปรดทราบว่าหาก output-z เช่น 5 แต่ละตำแหน่งของหน้าต่างจะสร้างค่า 5 ค่าในเอาต์พุตเป็นมิติ z ของเอาต์พุต ค่าเหล่านี้แตกต่างกันไปตามส่วนของเคอร์เนลแบบหมุนวนที่ใช้ - มีค่ากล่อง 3 มิติแยกต่างหากที่ใช้สำหรับแต่ละพิกัดเอาต์พุต output-z คุณจึงคิดว่ามันเป็นการโน้มน้าว 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;
}

แปลง ElementType

ดูเพิ่มเติมที่ XlaBuilder::ConvertElementType

คล้ายกับ static_cast แบบใช้องค์ประกอบใน C++ ดำเนินการแปลงตามองค์ประกอบจากรูปร่างข้อมูลไปเป็นรูปร่างเป้าหมาย มิติข้อมูลต้องตรงกัน และการแปลงเป็นองค์ประกอบที่ชาญฉลาด เช่น องค์ประกอบ s32 กลายเป็นองค์ประกอบ f32 ผ่านรูทีนการแปลง s32 -to- f32

ConvertElementType(operand, new_element_type)

ข้อโต้แย้ง พิมพ์ ความหมาย
operand XlaOp อาร์เรย์ประเภท T พร้อม dims D
new_element_type PrimitiveType ประเภท U

ขนาดของตัวถูกดำเนินการและรูปร่างเป้าหมายต้องตรงกัน ประเภทองค์ประกอบต้นทางและปลายทางต้องไม่เป็นสิ่งอันดับ

การแปลงเช่น T=s32 ถึง U=f32 จะดำเนินการรูทีนการแปลงจากภายในเป็นทศนิยมให้เป็นมาตรฐาน เช่น ปัดเศษไปเป็นคู่ที่ใกล้เคียงที่สุด

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 s อาร์กิวเมนต์ N ประเภทที่กำหนดเองซึ่งจะถูกส่งผ่านไปยังฟังก์ชัน
shape Shape รูปร่างเอาท์พุตของฟังก์ชัน

ลายเซ็นของฟังก์ชันจะเหมือนกัน โดยไม่คำนึงถึง arity หรือประเภทของ args:

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];
  // ...
}

ฟังก์ชันที่ผู้ใช้ระบุจะต้องไม่มีผลข้างเคียง และการดำเนินการจะต้องเป็นแบบ idempotent

จุด

ดูเพิ่มเติมที่ XlaBuilder::Dot

Dot(lhs, rhs)

ข้อโต้แย้ง พิมพ์ ความหมาย
lhs XlaOp อาร์เรย์ประเภท T
rhs XlaOp อาร์เรย์ประเภท T

ความหมายที่แน่นอนของการดำเนินการนี้ขึ้นอยู่กับอันดับของตัวถูกดำเนินการ:

ป้อนข้อมูล เอาท์พุต ความหมาย
เวกเตอร์ [n] เวกเตอร์ dot [n] สเกลาร์ ผลคูณดอทเวกเตอร์
เมทริกซ์ [mxk] dot อทเวกเตอร์ [k] เวกเตอร์ [ม.] การคูณเมทริกซ์-เวกเตอร์
เมทริกซ์ [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 หมายเลขมิติการทำสัญญาและแบทช์

เป็น Dot แต่อนุญาตให้ระบุหมายเลขมิติการทำสัญญาและแบทช์สำหรับทั้ง 'lhs' และ 'rhs'

เขตข้อมูล DotDimensionNumbers พิมพ์ ความหมาย
'lhs_contracting_ขนาด' ซ้ำแล้วซ้ำอีก int64 หมายเลขมิติการทำสัญญา 'lhs'
'rhs_contracting_ขนาด' ซ้ำแล้วซ้ำอีก int64 'rhs' หมายเลขมิติการทำสัญญา
'lhs_batch_ขนาด' ซ้ำแล้วซ้ำอีก int64 หมายเลขมิติแบทช์ 'lhs'
'rhs_batch_ขนาด' ซ้ำแล้วซ้ำอีก int64 หมายเลขมิติแบทช์ 'rhs'

DotGeneral ดำเนินการผลรวมของผลิตภัณฑ์เหนือมิติการทำสัญญาที่ระบุใน ' dimensions_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, ม, k] dot [b0, k, n] [b0, ม, น] แบทช์มัทมัล
[b0, b1, m, k] dot [b0, b1, k, n] [b0, b1, ม, น] แบทช์มัทมัล

ตามมาว่าหมายเลขมิติผลลัพธ์จะเริ่มต้นด้วยมิติชุดงาน ตามด้วยมิติ 'lhs' ที่ไม่หดตัว/ไม่ใช่ชุดงาน และสุดท้ายคือมิติ 'rhs' ที่ไม่หดตัว/ไม่ใช่ชุดงาน

ไดนามิกสไลซ์

ดูเพิ่มเติมที่ XlaBuilder::DynamicSlice

DynamicSlice แยกอาร์เรย์ย่อยออกจากอาร์เรย์อินพุตที่ start_indices แบบไดนามิก ขนาดของชิ้นในแต่ละมิติจะถูกส่งผ่านใน size_indices ซึ่งระบุจุดสิ้นสุดของช่วงเวลาเฉพาะของชิ้นในแต่ละมิติ: [start, start + size) รูปร่างของ start_indices จะต้องมีอันดับ == 1 โดยมีขนาดมิติเท่ากับอันดับของ operand

DynamicSlice(operand, start_indices, size_indices)

ข้อโต้แย้ง พิมพ์ ความหมาย
operand XlaOp อาร์เรย์มิติ N ประเภท T
start_indices ลำดับของ 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.
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), Atan2 (arctangent of y/x), LogicalAnd (logical AND), LogicalOr (logical OR), or LogicalXor (logical XOR).

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⌉ .

Clz(operand) Element-wise counting of the number of leading zeros x -> clz(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) .

Log1p(operand) Element-wise natural logarithm of a number plus one x -> ln(x + 1)

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:

  1. If i is present in batch_dims (ie is equal to batch_dims[k] for some k ) then we pick the corresponding dimension bounds out of start_indices.shape , skipping index_vector_dim (ie pick start_indices.shape.dims [ k ] if k < index_vector_dim and start_indices.shape.dims [ k + 1 ] otherwise).

  2. If i is present in offset_dims (ie equal to offset_dims [ k ] for some k ) then we pick the corresponding bound out of slice_sizes after accounting for collapsed_slice_dims (ie we pick adjusted_slice_sizes [ k ] where adjusted_slice_sizes is slice_sizes with the bounds at indices collapsed_slice_dims removed).

Formally, the operand index In corresponding to a given output index Out is calculated as follows:

  1. Let G = { Out [ k ] for k in batch_dims }. Use G to slice out a vector S such that S [ i ] = start_indices [Combine( G , i )] where Combine(A, b) inserts b at position index_vector_dim into A. Note that this is well defined even if G is empty -- if G is empty then S = start_indices .

  2. Create a starting index, S in , into operand using S by scattering S using start_index_map . More precisely:

    1. S in [ start_index_map [ k ]] = S [ k ] if k < start_index_map.size .

    2. S in [ _ ] = 0 otherwise.

  3. Create an index O in into operand by scattering the indices at the offset dimensions in Out according to the collapsed_slice_dims set. More precisely:

    1. O in [ remapped_offset_dims ( k )] = Out [ offset_dims [ k ]] if k < offset_dims.size ( remapped_offset_dims is defined below).

    2. O in [ _ ] = 0 otherwise.

  4. In is O 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 { 01 , 13 , 24 , 35 }.

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 from start_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 the operand .

  • 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 index Out .

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:

  1. 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 containing G 0 , G 1 in the last example) are defined to be the output dimensions that are not offset dimensions.

  2. 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 of 1 . Since they have a slice size of 1 the only valid index for them is 0 and eliding them does not introduce ambiguity.

  3. 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) is T .
  • If N > 1 , Collate(T_0, ..., T_{N-1}) is a tuple of N elements of type T .

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 using ReplicaId ). 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 replicas 0 and 2 , and 1 and 3 and then scatters the result.
  • shard_count is the size of each replica group. We need this in cases where replica_groups are empty. If replica_groups is not empty, shard_count must be equal to the size of each replica group.
  • channel_id is used for cross-module communication: only reduce-scatter operations with the same channel_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) is T .
  • If N > 1 , Collate(T_0, ..., T_{N-1}) is a tuple of N 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 :

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) is T .
  • If N > 1 , Collate(T_0, ..., T_N) is a tuple of N elements of type T .

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 rank update_window_dims.size + scatter_indices.rank - 1 .

  • Bounds of dimension i in each updates array must conform to the following:

    • If i is present in update_window_dims (ie equal to update_window_dims [ k ] for some k ), then the bound of dimension i in updates must not exceed the corresponding bound of operand after accounting for the inserted_window_dims (ie adjusted_window_bounds [ k ], where adjusted_window_bounds contains the bounds of operand with the bounds at indices inserted_window_dims removed).
    • If i is present in update_scatter_dims (ie equal to update_scatter_dims [ k ] for some k ), then the bound of dimension i in updates must be equal to the corresponding bound of scatter_indices , skipping index_vector_dim (ie scatter_indices.shape.dims [ k ], if k < index_vector_dim and scatter_indices.shape.dims [ k+1 ] otherwise).
  • 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 of update_window_dims.size and inserted_window_dims.size .

  • scatter_dims_to_operand_dims.size must be equal to scatter_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:

  1. Let G = { U [ k ] for k in update_scatter_dims }. Use G to look up an index vector S in the scatter_indices array such that S [ i ] = scatter_indices [Combine( G , i )] where Combine(A, b) inserts b at positions index_vector_dim into A.
  2. Create an index S in into operand using S by scattering S using the scatter_dims_to_operand_dims map. More formally:
    1. S in [ scatter_dims_to_operand_dims [ k ]] = S [ k ] if k < scatter_dims_to_operand_dims.size .
    2. S in [ _ ] = 0 otherwise.
  3. Create an index W in into each operands array by scattering the indices at update_window_dims in U according to inserted_window_dims . More formally:
    1. W in [ window_dims_to_operand_dims ( k )] = U [ k ] if k is in update_window_dims , where window_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, if update_window_dims.size is 4 , operand.rank is 6 , and inserted_window_dims is { 0 , 2 } then window_dims_to_operand_dims is { 01 , 13 , 24 , 35 }).
    2. W in [ _ ] = 0 otherwise.
  4. I is W in + S in where + is element-wise addition.

In summary, the scatter operation can be defined as follows.

  • Initialize output with operands , ie for all indices J , for all indices O in the operands [ J ] array:
    output [ J ][ O ] = operands [ J ][ O ]
  • For every index U in the updates [ J ] array and the corresponding index O in the operand [ J ] array, if O is a valid index for output :
    (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:

  1. Current value at the selected index in the output array
  2. 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 before Send
  • Send happens before RecvDone
  • Recv happens before RecvDone
  • Send happens before SendDone

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 with i < j that either comparator(value[i], value[j]) = comparator(value[j], value[i]) = false or comparator(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 of 1 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 and j need to be swapped, the comparator is called with 2 * n scalar parameters, where parameter 2 * k corresponds to the value at position i from the k-th operand, and parameter 2 * k + 1 corresponds to the value at position j from the k-th operand. Usually, the comparator would thus compare parameters 2 * k and 2 * 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 the i-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 type T , which is the result from the last execution of the body .
  • 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};
}