__init__.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # mypy: allow-untyped-defs
  2. from torch.nn.parameter import ( # usort: skip
  3. Buffer as Buffer,
  4. Parameter as Parameter,
  5. UninitializedBuffer as UninitializedBuffer,
  6. UninitializedParameter as UninitializedParameter,
  7. )
  8. from torch.nn.modules import * # usort: skip # noqa: F403
  9. from torch.nn import (
  10. attention as attention,
  11. functional as functional,
  12. init as init,
  13. modules as modules,
  14. parallel as parallel,
  15. parameter as parameter,
  16. utils as utils,
  17. )
  18. from torch.nn.parallel import DataParallel as DataParallel
  19. def factory_kwargs(kwargs):
  20. r"""Return a canonicalized dict of factory kwargs.
  21. Given kwargs, returns a canonicalized dict of factory kwargs that can be directly passed
  22. to factory functions like torch.empty, or errors if unrecognized kwargs are present.
  23. This function makes it simple to write code like this::
  24. class MyModule(nn.Module):
  25. def __init__(self, **kwargs):
  26. factory_kwargs = torch.nn.factory_kwargs(kwargs)
  27. self.weight = Parameter(torch.empty(10, **factory_kwargs))
  28. Why should you use this function instead of just passing `kwargs` along directly?
  29. 1. This function does error validation, so if there are unexpected kwargs we will
  30. immediately report an error, instead of deferring it to the factory call
  31. 2. This function supports a special `factory_kwargs` argument, which can be used to
  32. explicitly specify a kwarg to be used for factory functions, in the event one of the
  33. factory kwargs conflicts with an already existing argument in the signature (e.g.
  34. in the signature ``def f(dtype, **kwargs)``, you can specify ``dtype`` for factory
  35. functions, as distinct from the dtype argument, by saying
  36. ``f(dtype1, factory_kwargs={"dtype": dtype2})``)
  37. """
  38. if kwargs is None:
  39. return {}
  40. simple_keys = {"device", "dtype", "memory_format"}
  41. expected_keys = simple_keys | {"factory_kwargs"}
  42. if not kwargs.keys() <= expected_keys:
  43. raise TypeError(f"unexpected kwargs {kwargs.keys() - expected_keys}")
  44. # guarantee no input kwargs is untouched
  45. r = dict(kwargs.get("factory_kwargs", {}))
  46. for k in simple_keys:
  47. if k in kwargs:
  48. if k in r:
  49. raise TypeError(
  50. f"{k} specified twice, in **kwargs and in factory_kwargs"
  51. )
  52. r[k] = kwargs[k]
  53. return r