torch.coalesce
时间: 2023-10-12 17:18:39 浏览: 49
torch.coalesce is a function in PyTorch that performs coalescing on a sparse tensor. Coalescing is the process of merging adjacent non-zero elements in a sparse tensor to reduce the number of non-zero elements and make the tensor more efficient for computation.
The function takes a sparse tensor as input and returns a coalesced version of the tensor. It operates on the indices and values of the sparse tensor and merges adjacent indices that have the same value.
Here is the syntax of the function:
```
torch.coalesce(input_tensor)
```
where `input_tensor` is the sparse tensor to be coalesced.
Example:
```python
import torch
# Create a sparse tensor
indices = torch.tensor([[0, 1], [2, 3], [2, 3]])
values = torch.tensor([1, 2, 3])
sparse_tensor = torch.sparse_coo_tensor(indices.t(), values, size=(4, 4))
# Coalesce the sparse tensor
coalesced_tensor = torch.coalesce(sparse_tensor)
print("Sparse tensor:")
print(sparse_tensor)
print("Coalesced tensor:")
print(coalesced_tensor)
```
Output:
```
Sparse tensor:
tensor(indices=tensor([[0, 2, 2],
[1, 3, 3]]),
values=tensor([1, 2, 3]))
Coalesced tensor:
tensor(indices=tensor([[0, 2],
[1, 3]]),
values=tensor([1, 5]))
```
In this example, we create a sparse tensor with three non-zero elements. We then use `torch.coalesce()` to merge adjacent indices that have the same value. The resulting coalesced tensor has only two non-zero elements, which makes it more efficient for computation.