helpers.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Optional
  15. from torch import Tensor
  16. def _check_input(
  17. x: Tensor, y: Optional[Tensor] = None, zero_diagonal: Optional[bool] = None
  18. ) -> tuple[Tensor, Tensor, bool]:
  19. """Check that input has the right dimensionality and sets the ``zero_diagonal`` argument if user has not set it.
  20. Args:
  21. x: tensor of shape ``[N,d]``
  22. y: if provided, a tensor of shape ``[M,d]``
  23. zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
  24. """
  25. if x.ndim != 2:
  26. raise ValueError(f"Expected argument `x` to be a 2D tensor of shape `[N, d]` but got {x.shape}")
  27. if y is not None:
  28. if y.ndim != 2 or y.shape[1] != x.shape[1]:
  29. raise ValueError(
  30. "Expected argument `y` to be a 2D tensor of shape `[M, d]` where"
  31. " `d` should be same as the last dimension of `x`"
  32. )
  33. zero_diagonal = False if zero_diagonal is None else zero_diagonal
  34. else:
  35. y = x.clone()
  36. zero_diagonal = True if zero_diagonal is None else zero_diagonal
  37. return x, y, zero_diagonal
  38. def _reduce_distance_matrix(distmat: Tensor, reduction: Optional[str] = None) -> Tensor:
  39. """Reduction of distance matrix.
  40. Args:
  41. distmat: a ``[N,M]`` matrix
  42. reduction: string determining how to reduce along last dimension
  43. """
  44. if reduction == "mean":
  45. return distmat.mean(dim=-1)
  46. if reduction == "sum":
  47. return distmat.sum(dim=-1)
  48. if reduction is None or reduction == "none":
  49. return distmat
  50. raise ValueError(f"Expected reduction to be one of `['mean', 'sum', None]` but got {reduction}")