(
sp_mat: "torch.Tensor", p: float, fill_value: float = 0.0
)
| 10 | |
| 11 | |
| 12 | def sparse_dropout( |
| 13 | sp_mat: "torch.Tensor", p: float, fill_value: float = 0.0 |
| 14 | ) -> "torch.Tensor": |
| 15 | import torch |
| 16 | |
| 17 | r"""Dropout function for sparse matrix. This function will return a new sparse matrix with the same shape as the input sparse matrix, but with some elements dropped out. |
| 18 | |
| 19 | Args: |
| 20 | ``sp_mat`` (``torch.Tensor``): The sparse matrix with format ``torch.sparse_coo_tensor``. |
| 21 | ``p`` (``float``): Probability of an element to be dropped. |
| 22 | ``fill_value`` (``float``): The fill value for dropped elements. Defaults to ``0.0``. |
| 23 | """ |
| 24 | device = sp_mat.device |
| 25 | sp_mat = sp_mat.coalesce() |
| 26 | assert 0 <= p <= 1 |
| 27 | if p == 0: |
| 28 | return sp_mat |
| 29 | p = torch.ones(sp_mat._nnz(), device=device) * p |
| 30 | keep_mask = torch.bernoulli(1 - p).to(device) |
| 31 | fill_values = torch.logical_not(keep_mask) * fill_value |
| 32 | new_sp_mat = torch.sparse_coo_tensor( |
| 33 | sp_mat._indices(), |
| 34 | sp_mat._values() * keep_mask + fill_values, |
| 35 | size=sp_mat.size(), |
| 36 | device=sp_mat.device, |
| 37 | dtype=sp_mat.dtype, |
| 38 | ) |
| 39 | return new_sp_mat |
no test coverage detected