autograd.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. from dataclasses import dataclass
  2. import re
  3. from typing import Optional, Sequence, Set, List, Tuple, Match
  4. from torchgen.api import cpp
  5. from torchgen.api.types import Binding, NamedCType
  6. from torchgen.model import (
  7. NativeFunction,
  8. Type,
  9. SchemaKind,
  10. NativeFunctionsViewGroup,
  11. )
  12. from torchgen.utils import IDENT_REGEX
  13. # Represents a saved attribute involved in backward calculation.
  14. # Note that it can be a derived property of an input argument, e.g.:
  15. # we could save `other.scalar_type()` instead of the entire `other` tensor.
  16. @dataclass(frozen=True)
  17. class SavedAttribute:
  18. # The NamedCType holds the updated name and cpp type of the attribute
  19. # for the name, Suffix is appended if it's derived property, e.g.: `other_scalar_type`
  20. nctype: NamedCType
  21. # The expression to read the derived property at save time, e.g.:
  22. # `other.scalar_type()`.
  23. expr: str
  24. # Represents a backward formula that calculates derivatives for one
  25. # or more tensors.
  26. @dataclass(frozen=True)
  27. class Derivative:
  28. # The formula string (legit C++ expression).
  29. # Note that expressions against input arguments have been replaced with the
  30. # corresponding saved attributes.
  31. # E.g.:
  32. # raw formula: `mul_tensor_backward(grad, self, other.scalar_type())`
  33. # here: `mul_tensor_backward(grad, self, other_scalar_type)`
  34. formula: str
  35. # The formula string before input argument replacement
  36. original_formula: str
  37. # Names of the arguments for which this formula calculates derivatives.
  38. var_names: Tuple[str, ...]
  39. # Saved inputs that are referenced by the formula.
  40. saved_inputs: Tuple[SavedAttribute, ...]
  41. # Saved outputs that are referenced by the formula.
  42. saved_outputs: Tuple[SavedAttribute, ...]
  43. # Gradients that are referenced by name in the formula.
  44. named_gradients: Set[str]
  45. # Represents a forward formula that calculates forward derivatives
  46. # for one tensor.
  47. @dataclass(frozen=True)
  48. class ForwardDerivative:
  49. # The formula string (legit C++ expression).
  50. # Note that special keywords such as "linear" or "element_wise" have been
  51. # replaced by the automatically generated formula.
  52. formula: str
  53. # Name of the output arguments for which this formula calculates forward
  54. # derivatives
  55. var_names: Tuple[str, ...]
  56. # Type of the output arguments for which this formula calculates forward
  57. # derivatives
  58. var_types: Tuple[Type, ...]
  59. # Inputs for which the forward derivatives are required for this formula
  60. required_inputs_fw_grad: Optional[Tuple[str, ...]]
  61. # Inputs for which the primal is required for this formula
  62. required_inputs_primal: Optional[Tuple[str, ...]]
  63. # Flag to specify if this formula requires the original value of self
  64. # This is only used by inplace operations
  65. required_original_self_value: bool
  66. # If this formula is specified in derivatives.yaml or if we are re-using the
  67. # out of place formula for inplace
  68. is_reusing_outplace_formula: bool
  69. # Represents differentiability info for a NativeFunction.
  70. @dataclass(frozen=True)
  71. class DifferentiabilityInfo:
  72. # The base name read from derivatives.yaml.
  73. name: str
  74. # The matching native function.
  75. #
  76. # There can be multiple NativeFunction having the same base name:
  77. # - different overloads with different types of input arguments;
  78. # - in-place/out/functional variants of the same function;
  79. #
  80. # We first use the schema string (under the 'name' key) in derivatives.yaml
  81. # to find the NativeFunction having the same schema string.
  82. # Then we find the in-place/out/functional variants of the matching function.
  83. # Among these variants, we choose the one having the same name as the
  84. # derivatives.yaml entry. If there is no exact match, then we choose the
  85. # in-place variant.
  86. # TODO: maybe the logic to search for all variants is no longer necessary?
  87. func: NativeFunction
  88. # The name of the generated autograd function.
  89. # It's set only if we will calculate a derivative, i.e.
  90. # 'args_with_derivatives' is not empty.
  91. op: Optional[str]
  92. # The derivatives formulae for this function.
  93. # Note that the length of this sequence is the number of differentiable inputs
  94. derivatives: Sequence[Derivative]
  95. # The forward derivatives formulae for this function.
  96. # Note that the length of this sequence is the number of differentiable outputs
  97. forward_derivatives: Sequence[ForwardDerivative]
  98. # The union of 'saved_inputs' of all 'derivatives'.
  99. all_saved_inputs: Sequence[SavedAttribute]
  100. # The union of 'saved_outputs' of all 'derivatives'.
  101. all_saved_outputs: Sequence[SavedAttribute]
  102. # All named gradients that are available for use, in the same
  103. # order as in the grads vector.
  104. available_named_gradients: Sequence[str]
  105. # The named gradients that are used in any of the derivatives.
  106. # Invariant: all(name in available_named_gradients for name in used_named_gradients)
  107. used_named_gradients: Set[str]
  108. # The function's input arguments for which it calculates derivatives.
  109. # It's the union of 'var_names' of all 'derivatives', sorted by the
  110. # argument order in the function schema.
  111. args_with_derivatives: Sequence[Binding]
  112. # Names of arguments whose derivative formula is 'non_differentiable'.
  113. non_differentiable_arg_names: Sequence[str]
  114. # Raw data read from derivatives.yaml.
  115. output_differentiability: Optional[List[bool]]
  116. # output_differentiability in derivatives.yaml can be a list of
  117. # conditions that express if the output is differentiable. In this case,
  118. # the number of conditions must match the number of outputs
  119. # (NB: we only support one condition right now).
  120. # output_differentiability gets populated with True for each condition,
  121. # while output_differentiability_conditions gets populated with the conditions
  122. output_differentiability_conditions: Optional[List[str]]
  123. @property
  124. def has_derivatives(self) -> bool:
  125. return len(self.args_with_derivatives) > 0
  126. # Generates a new DifferentiabilityInfo using the exact same set of derivative information,
  127. # but with a new operator name.
  128. # This is used when generating "copy" variants of view ops,
  129. # which are able to use the exact same derivative formula as the original view op
  130. # See Note [Codegen'd {view}_copy Operators]
  131. def create_view_copy_from_view_derivative(
  132. self, g: NativeFunctionsViewGroup
  133. ) -> Optional["DifferentiabilityInfo"]:
  134. if g.view_copy is None:
  135. return None
  136. f = g.view_copy
  137. name_split_by_period = self.name.split(".", maxsplit=2)
  138. # Append a "_copy" to the base name of the operator (but keep the overload name the same)
  139. view_copy_name = f"{name_split_by_period[0]}_copy." + ".".join(
  140. name_split_by_period[1:]
  141. )
  142. view_copy_op_name = None if self.op is None else f"{self.op}_copy"
  143. return DifferentiabilityInfo(
  144. # Use the "_copy" version of name/func/op
  145. name=view_copy_name,
  146. func=f,
  147. op=view_copy_op_name,
  148. # But keep all derivative info the same
  149. derivatives=self.derivatives,
  150. forward_derivatives=self.forward_derivatives,
  151. all_saved_inputs=self.all_saved_inputs,
  152. all_saved_outputs=self.all_saved_outputs,
  153. available_named_gradients=self.available_named_gradients,
  154. used_named_gradients=self.used_named_gradients,
  155. args_with_derivatives=self.args_with_derivatives,
  156. non_differentiable_arg_names=self.non_differentiable_arg_names,
  157. output_differentiability=self.output_differentiability,
  158. output_differentiability_conditions=self.output_differentiability_conditions,
  159. )
  160. def uses_ident(info: Optional[DifferentiabilityInfo], ident: str) -> bool:
  161. if info is None:
  162. return False
  163. for derivative in info.derivatives:
  164. formula = derivative.formula
  165. if re.search(IDENT_REGEX.format(ident), formula):
  166. return True
  167. return False
  168. def uses_retain_variables(info: Optional[DifferentiabilityInfo]) -> bool:
  169. return uses_ident(info, "retain_variables")
  170. def uses_single_grad(info: Optional[DifferentiabilityInfo]) -> bool:
  171. return uses_ident(info, "grad")
  172. # Represents a differentiable `Argument`.
  173. # How is it different from the `Argument` type?
  174. # - It's processed Arguments which are differentiable and only used in the
  175. # context of the autograd codegen;
  176. # - It can represent SelfArgument or regular Argument but not TensorOptionsArgument;
  177. @dataclass(frozen=True)
  178. class DifferentiableInput:
  179. name: str
  180. type: Type
  181. # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
  182. cpp_type: str
  183. # Represents a differentiable `Return`.
  184. # How it it different from the `Return` type?
  185. # - The name in `Return` is optional. Here it is always populated using the same
  186. # `cpp.return_names()` method.
  187. # TODO: some cpp naming logic (e.g. resolving name conflict) might be irrelevant?
  188. # - It's processed Returns which are differentiable, in compliance with the
  189. # `output_differentiability` field defined in derivatives.yaml (if specified),
  190. # and are only used in the context of the autograd codegen;
  191. @dataclass(frozen=True)
  192. class DifferentiableOutput:
  193. name: str
  194. type: Type
  195. # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
  196. cpp_type: str
  197. @dataclass(frozen=True)
  198. class NativeFunctionWithDifferentiabilityInfo:
  199. func: NativeFunction
  200. info: Optional[DifferentiabilityInfo]
  201. fw_derivatives: Sequence[ForwardDerivative]
  202. # TODO: Update comment below since it is out of date.
  203. def dispatch_strategy(fn: NativeFunctionWithDifferentiabilityInfo) -> str:
  204. """How are we going to call the underlying implementation of a
  205. declaration? There are two strategies:
  206. - use_derived: we want to call the implementation on CPUDoubleType
  207. (or a similar, derived Type instance). Because these derived
  208. instances deal in Tensors, not Variables (it's a completely different
  209. object, so it doesn't dispatch back to VariableType), code on
  210. this dispatch path needs to wrap/unwrap tensors. If the
  211. derived implementation takes and returns tensors, the
  212. implementation is usually differentiable (although we also use
  213. the derived dispatch path for non-differentiable functions
  214. that we still want to dispatch on the derived Type instance;
  215. e.g., size())
  216. - use_type: we want to call the implementation on Type, because
  217. it is implemented concretely, and the functions it invokes will
  218. get dispatched back to VariableType (which will ensure that they
  219. are differentiable.)
  220. """
  221. if fn.func.is_abstract or (fn.info is not None and fn.info.has_derivatives):
  222. # If the function is abstract (not implemented on at::Type), we must
  223. # call the implementation on the derived type with unpacked tensors.
  224. # If the function has a derivative specified and is concrete, we could
  225. # call either implementation. We prefer the calling the derived
  226. # type's implementation with unpacked tensors because it is more
  227. # performant in some cases: any internal calls to other ATen functions
  228. # won't have the history tracked.
  229. # If the function has a type dispatched argument (i.e. is a factory),
  230. # we prefer calling the derived type's implementation both because it is
  231. # more performant and to ensure factory functions return tensors with _version
  232. # of 0 (probably not strictly necessary, but nice to have to keeps versions simple
  233. # to understand.
  234. return "use_derived"
  235. else:
  236. # If the function is concrete (we don't have to override it) and we
  237. # didn't declare it in derivatives.yaml, we'll assume that it is
  238. # actually implemented out of differentiable functions. (This
  239. # assumption might not hold, but then you'll see gradcheck fail.)
  240. return "use_type"
  241. def match_differentiability_info(
  242. native_functions: List[NativeFunction],
  243. differentiability_infos: Sequence[DifferentiabilityInfo],
  244. ) -> List[NativeFunctionWithDifferentiabilityInfo]:
  245. """Sets the "derivative" key on declarations to matching autograd function
  246. In-place functions will use the out-of-place derivative definition if there
  247. is no in-place specific derivative.
  248. """
  249. info_by_schema = {info.func.func: info for info in differentiability_infos}
  250. functional_info_by_signature = {
  251. info.func.func.signature(strip_default=True): info
  252. for info in differentiability_infos
  253. if info.func.func.kind() == SchemaKind.functional
  254. }
  255. non_functional_info_by_signature = {
  256. info.func.func.signature(strip_default=True): info
  257. for info in differentiability_infos
  258. if info.func.func.kind() != SchemaKind.functional
  259. }
  260. def find_info(f: NativeFunction) -> Tuple[Optional[DifferentiabilityInfo], bool]:
  261. # (1) Check for an exact match
  262. if f.func in info_by_schema:
  263. return info_by_schema[f.func], True
  264. # (2) If no exact match, check if the out-of-place variant
  265. # of this operator has a match.
  266. # i.e mul() for mul_() or mul_out()
  267. f_sig = f.func.signature(strip_default=True)
  268. if f_sig in functional_info_by_signature:
  269. return functional_info_by_signature[f_sig], False
  270. # (3) Some operators have a derivative explicitly defined for the mutable
  271. # variant, but get a code-generated out-of-place variant which does *not*
  272. # come with a derivative formula.
  273. # For the generated out-of-place variant, use the mutable variant's formula
  274. # if it exists.
  275. if "generated" in f.tags and f_sig in non_functional_info_by_signature:
  276. info = non_functional_info_by_signature[f_sig]
  277. # See https://github.com/pytorch/pytorch/pull/76320/files#r874816389
  278. assert not any(
  279. "self" in str(inpt.nctype.name) for inpt in info.all_saved_inputs
  280. ), f"""\
  281. Attempted to convert a derivative formula for a mutable operator
  282. to be used by automatically by its functional variant ("{str(f.func)}").
  283. this is not currently supported (we'd need to fix up the formula in the codegen)."""
  284. return info, False
  285. return None, False
  286. result: List[NativeFunctionWithDifferentiabilityInfo] = []
  287. for f in native_functions:
  288. info, is_exact_match = find_info(f)
  289. # Currently, the '.strides()' to 'strides_or_error' replacement does not support
  290. # 'self' derivatives of an inplace function, so we must check for this case.
  291. if f.func.kind() == SchemaKind.inplace and (info is not None):
  292. for derivative in info.derivatives:
  293. if "self" in derivative.var_names:
  294. for saved_input in derivative.saved_inputs:
  295. assert "strides_or_error" not in saved_input.expr, (
  296. "Calling '.strides()' in the 'self' derivative formula of an "
  297. f"in-place function is not supported: {f.func}"
  298. )
  299. # For functions that have a single def for out-of-place and inplace (like abs())
  300. if info and info.forward_derivatives:
  301. forward_derivatives = info.forward_derivatives
  302. if f.func.kind() == SchemaKind.inplace:
  303. # For inplace functions there is a little bit of work to do:
  304. # 1) Validate the formula and make sure the input that is modified in not used:
  305. # - If there is a formula for the inplace variant of the function (is_exact_match == True) then
  306. # we make sure that the original value of the input that is being modified inplace (self_p) is
  307. # not used in the formula. Note that the formula can use "original_self_p" here and that would
  308. # trigger a clone of the original input.
  309. # - If we are re-using the out of place formula (is_exact_match == False) then we replace every
  310. # occurrence of self_p and self_t by original_self_p and original_self_t. These will be
  311. # populated by cloned version of the original input (either the clone done by the backward AD
  312. # logic if self is also used in a backward formula or a special clone that we add).
  313. # 2) At this point, there cannot be a self_p in the formula.
  314. # 3) Change "result" into "self_p" as by design, in the inplace function codegen, the result is
  315. # simply called self (as it is modified inplace).
  316. # 4) Update the required primals data in case it used to contain "result" but should now contain
  317. # "self"
  318. # 5) If it is not an exact match, the user formula is not modifying the existing forward grad
  319. # inplace as it should. So add some code that makes sure that we do so if the forward grad
  320. # already exists.
  321. assert (
  322. len(info.forward_derivatives) == 1
  323. ) # Only single output inplace should exist
  324. fw_info = info.forward_derivatives[0]
  325. formula = fw_info.formula
  326. def replace_self_with_original_self(formula: str, postfix: str) -> str:
  327. def repl(m: Match[str]) -> str:
  328. return f"{m.group(1)}original_self{postfix}{m.group(2)}"
  329. return re.sub(IDENT_REGEX.format(f"self{postfix}"), repl, formula)
  330. if re.search(IDENT_REGEX.format("self_p"), formula):
  331. if is_exact_match:
  332. # For manually defined formulas, don't allow the original value to be used
  333. raise RuntimeError(
  334. f'The formula for "{f.func.name}" is using the original value of self '
  335. "that is being modified inplace. This would lead to wrong forward gradients. "
  336. 'Please use "result" in the formula only.'
  337. )
  338. else:
  339. # When the original formula is out of place, we save a clone of the primal
  340. # value to be able to access this value if needed
  341. # replace "self_p"/"self_t" from the formula by "original_self_p"/"original_self_t"
  342. formula = replace_self_with_original_self(formula, "_p")
  343. formula = replace_self_with_original_self(formula, "_t")
  344. # replace "result" from the formula by "self_p"
  345. def repl(m: Match[str]) -> str:
  346. return f"{m.group(1)}self_p{m.group(2)}"
  347. formula = re.sub(IDENT_REGEX.format("result"), repl, formula)
  348. required_primals = fw_info.required_inputs_primal
  349. if re.search(IDENT_REGEX.format("self_p"), formula):
  350. required_primals = (
  351. required_primals + ("self",) if required_primals else ("self",)
  352. )
  353. if not is_exact_match:
  354. # NOTE [In-place forward AD formula Optimization]
  355. #
  356. # This optimization transforms the formula to directly do inplace, i.e.
  357. # instead of self_t.copy_(self_t.op()) we do self_t.op_() when the following are met:
  358. #
  359. # 1) the formula satisfies the pattern: "self_t.op(*args)"
  360. # 2) "op" in (1) needs to be the same as the op the derivative is for
  361. #
  362. # (2) may seem too strict, but currently the only ops that satisfy (1) also satisfy (2)
  363. # If there is a need, we can relax (2) to allow any op that has an in-place variant
  364. is_single_method_on_self_t = False
  365. match = re.fullmatch(r"self_t.([\w]*)\((.*)\)", formula)
  366. if match:
  367. op_name, between_parens = match.group(1), match.group(2)
  368. # We want to...
  369. # Match: self_t.op1(other_p.op2(arg))
  370. # Avoid: self_t.op1(args) + self_t.op2(args)
  371. # Avoid: self_t.op1(other_p.op2(arg)) + self_t.op2(args)
  372. def check_parens_nest_level_gt_zero(s: str) -> bool:
  373. level = 1
  374. for ch in s:
  375. if ch == ")":
  376. level -= 1
  377. if level == 0:
  378. return False
  379. if ch == "(":
  380. level += 1
  381. return True
  382. is_single_method_on_self_t = check_parens_nest_level_gt_zero(
  383. between_parens
  384. )
  385. directly_do_inplace = (
  386. is_single_method_on_self_t and op_name == info.name
  387. )
  388. if directly_do_inplace:
  389. formula = f"self_t_raw.defined() ? self_t_raw.{op_name}_({between_parens}) : {formula}"
  390. else:
  391. # Make sure that the forward grad is modified inplace when the original formula
  392. # is out of place
  393. formula = f"self_t_raw.defined() ? self_t_raw.copy_({formula}) : {formula}"
  394. required_original_self_value = bool(
  395. re.search(IDENT_REGEX.format("original_self_p"), formula)
  396. )
  397. forward_derivatives = [
  398. ForwardDerivative(
  399. formula=formula,
  400. var_names=("self",),
  401. var_types=fw_info.var_types,
  402. required_inputs_fw_grad=fw_info.required_inputs_fw_grad,
  403. required_inputs_primal=required_primals,
  404. required_original_self_value=required_original_self_value,
  405. is_reusing_outplace_formula=not is_exact_match,
  406. ),
  407. ]
  408. else:
  409. forward_derivatives = []
  410. result.append(
  411. NativeFunctionWithDifferentiabilityInfo(
  412. func=f, info=info, fw_derivatives=forward_derivatives
  413. )
  414. )
  415. return result
  416. def is_differentiable(
  417. name: str, type: Type, info: Optional[DifferentiabilityInfo]
  418. ) -> bool:
  419. return type.is_tensor_like() and (
  420. info is None or name not in info.non_differentiable_arg_names
  421. )
  422. def gen_differentiable_outputs(
  423. fn: NativeFunctionWithDifferentiabilityInfo,
  424. ) -> List[DifferentiableOutput]:
  425. f = fn.func
  426. info = fn.info
  427. outputs: List[DifferentiableOutput] = [
  428. DifferentiableOutput(
  429. name=name, type=ret.type, cpp_type=cpp.return_type(ret).cpp_type()
  430. )
  431. for name, ret in zip(cpp.return_names(f), f.func.returns)
  432. ]
  433. output_differentiability = info.output_differentiability if info else None
  434. if output_differentiability is not None:
  435. if len(output_differentiability) != len(outputs):
  436. raise RuntimeError(
  437. f"The length of output_differentiability ({len(output_differentiability)}), "
  438. f"does not match the number of outputs ({len(outputs)})."
  439. )
  440. differentiable_outputs: List[DifferentiableOutput] = []
  441. if False in output_differentiability and f.func.kind() == SchemaKind.inplace:
  442. raise RuntimeError(
  443. "output_differentiability=False for inplace operation (version_counter won't get updated)"
  444. )
  445. for differentiable, output in zip(output_differentiability, outputs):
  446. if differentiable:
  447. differentiable_outputs.append(output)
  448. return differentiable_outputs
  449. candidate_differentiable_outputs = list(
  450. filter(lambda r: is_differentiable(r.name, r.type, info), outputs)
  451. )
  452. if uses_single_grad(info):
  453. return candidate_differentiable_outputs[:1]
  454. else:
  455. return candidate_differentiable_outputs