torch.triu_indices
function triu_indices(row: number, col: number, options?: IndicesOptions): [Tensor, Tensor]function triu_indices(row: number, col: number, offset: number, options?: IndicesOptions): [Tensor, Tensor]Returns the row and column indices of the upper triangular part of a matrix.
Generates two 1-D tensors containing the row and column indices of all elements in the upper triangular region (on and above specified diagonal). Essential for:
- Sparse tensor construction: Creating indices for sparse upper triangular matrices
- Element selection: Extracting upper triangular elements via advanced indexing
- Structured sparsity: Defining sparsity patterns (e.g., causal attention)
- Matrix visualization: Plotting or printing only upper triangular structure
- Batch operations: Processing multiple triangular subproblems efficiently
- Memory optimization: Storing only non-zero upper triangular elements
Returns two 1-D tensors: (row_indices, col_indices) where row_indices[i] and col_indices[i] give the position of the i-th upper triangular element.
- Data type: Returns 1-D tensors, typically 'int32'
- Symmetry: Complementary to tril_indices
Parameters
rownumber- Number of rows in matrix
colnumber- Number of columns in matrix
optionsIndicesOptionsoptional- Tensor options (dtype: 'int32' or 'float32', device, etc.)
Returns
Examples
// Get indices for 3×3 upper triangle
const [rows, cols] = torch.triu_indices(3, 3);
// rows: [0, 0, 0, 1, 1, 2], cols: [0, 1, 2, 1, 2, 2]See Also
- PyTorch torch.triu_indices()
- tril_indices - Get lower triangular indices
- triu - Extract upper triangular part directly