torch.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from typing import Dict, Optional, cast
  2. import torch
  3. from einops._torch_specific import apply_for_scriptable_torch
  4. from . import RearrangeMixin, ReduceMixin
  5. from ._einmix import _EinmixMixin
  6. __author__ = "Alex Rogozhnikov"
  7. class Rearrange(RearrangeMixin, torch.nn.Module):
  8. def forward(self, input):
  9. recipe = self._multirecipe[input.ndim]
  10. return apply_for_scriptable_torch(recipe, input, reduction_type="rearrange", axes_dims=self._axes_lengths)
  11. def _apply_recipe(self, x):
  12. # overriding parent method to prevent it's scripting
  13. pass
  14. class Reduce(ReduceMixin, torch.nn.Module):
  15. def forward(self, input):
  16. recipe = self._multirecipe[input.ndim]
  17. return apply_for_scriptable_torch(recipe, input, reduction_type=self.reduction, axes_dims=self._axes_lengths)
  18. def _apply_recipe(self, x):
  19. # overriding parent method to prevent it's scripting
  20. pass
  21. class EinMix(_EinmixMixin, torch.nn.Module):
  22. def _create_parameters(self, weight_shape, weight_bound, bias_shape, bias_bound):
  23. self.weight = torch.nn.Parameter(
  24. torch.zeros(weight_shape).uniform_(-weight_bound, weight_bound), requires_grad=True
  25. )
  26. if bias_shape is not None:
  27. self.bias = torch.nn.Parameter(
  28. torch.zeros(bias_shape).uniform_(-bias_bound, bias_bound), requires_grad=True
  29. )
  30. else:
  31. self.bias = None
  32. def _create_rearrange_layers(
  33. self,
  34. pre_reshape_pattern: Optional[str],
  35. pre_reshape_lengths: Optional[Dict],
  36. post_reshape_pattern: Optional[str],
  37. post_reshape_lengths: Optional[Dict],
  38. ):
  39. self.pre_rearrange = None
  40. if pre_reshape_pattern is not None:
  41. self.pre_rearrange = Rearrange(pre_reshape_pattern, **cast(dict, pre_reshape_lengths))
  42. self.post_rearrange = None
  43. if post_reshape_pattern is not None:
  44. self.post_rearrange = Rearrange(post_reshape_pattern, **cast(dict, post_reshape_lengths))
  45. def forward(self, input):
  46. if self.pre_rearrange is not None:
  47. input = self.pre_rearrange(input)
  48. result = torch.einsum(self.einsum_pattern, input, self.weight)
  49. if self.bias is not None:
  50. result += self.bias
  51. if self.post_rearrange is not None:
  52. result = self.post_rearrange(result)
  53. return result