annotate.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # mypy: allow-untyped-defs
  2. from torch.fx.proxy import Proxy
  3. from ._compatibility import compatibility
  4. @compatibility(is_backward_compatible=False)
  5. def annotate(val, type):
  6. """
  7. Annotates a Proxy object with a given type.
  8. This function annotates a val with a given type if a type of the val is a torch.fx.Proxy object
  9. Args:
  10. val (object): An object to be annotated if its type is torch.fx.Proxy.
  11. type (object): A type to be assigned to a given proxy object as val.
  12. Returns:
  13. The given val.
  14. Raises:
  15. RuntimeError: If a val already has a type in its node.
  16. """
  17. if isinstance(val, Proxy):
  18. if val.node.type:
  19. raise RuntimeError(
  20. f"Tried to annotate a value that already had a type on it!"
  21. f" Existing type is {val.node.type} "
  22. f"and new type is {type}. "
  23. f"This could happen if you tried to annotate a function parameter "
  24. f"value (in which case you should use the type slot "
  25. f"on the function signature) or you called "
  26. f"annotate on the same value twice"
  27. )
  28. else:
  29. val.node.type = type
  30. return val
  31. else:
  32. return val