EXPERIMENTAL: A context manager for overriding gradient functions. This context manager can be used to override the gradient function that will be used for ops within the scope of the context. For example: ```python @tf.RegisterGradient("CustomSquare") def _custom_square_g
(self, op_type_map)
| 4881 | # pylint: disable=g-doc-return-or-yield |
| 4882 | @tf_contextlib.contextmanager |
| 4883 | def gradient_override_map(self, op_type_map): |
| 4884 | """EXPERIMENTAL: A context manager for overriding gradient functions. |
| 4885 | |
| 4886 | This context manager can be used to override the gradient function |
| 4887 | that will be used for ops within the scope of the context. |
| 4888 | |
| 4889 | For example: |
| 4890 | |
| 4891 | ```python |
| 4892 | @tf.RegisterGradient("CustomSquare") |
| 4893 | def _custom_square_grad(op, grad): |
| 4894 | # ... |
| 4895 | |
| 4896 | with tf.Graph().as_default() as g: |
| 4897 | c = tf.constant(5.0) |
| 4898 | s_1 = tf.square(c) # Uses the default gradient for tf.square. |
| 4899 | with g.gradient_override_map({"Square": "CustomSquare"}): |
| 4900 | s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the |
| 4901 | # gradient of s_2. |
| 4902 | ``` |
| 4903 | |
| 4904 | Args: |
| 4905 | op_type_map: A dictionary mapping op type strings to alternative op type |
| 4906 | strings. |
| 4907 | |
| 4908 | Returns: |
| 4909 | A context manager that sets the alternative op type to be used for one |
| 4910 | or more ops created in that context. |
| 4911 | |
| 4912 | Raises: |
| 4913 | TypeError: If `op_type_map` is not a dictionary mapping strings to |
| 4914 | strings. |
| 4915 | """ |
| 4916 | if not isinstance(op_type_map, dict): |
| 4917 | raise TypeError("op_type_map must be a dictionary mapping " |
| 4918 | "strings to strings") |
| 4919 | # The saved_mappings dictionary stores any currently-set mappings that |
| 4920 | # will be overridden by this context manager. |
| 4921 | saved_mappings = {} |
| 4922 | # Install the given label |
| 4923 | for op_type, mapped_op_type in op_type_map.items(): |
| 4924 | if not (isinstance(op_type, six.string_types) and |
| 4925 | isinstance(mapped_op_type, six.string_types)): |
| 4926 | raise TypeError("op_type_map must be a dictionary mapping " |
| 4927 | "strings to strings") |
| 4928 | try: |
| 4929 | saved_mappings[op_type] = self._gradient_override_map[op_type] |
| 4930 | except KeyError: |
| 4931 | pass |
| 4932 | self._gradient_override_map[op_type] = mapped_op_type |
| 4933 | try: |
| 4934 | yield # The code within the context runs here. |
| 4935 | finally: |
| 4936 | # Remove the labels set for this context, and restore any saved labels. |
| 4937 | for op_type, mapped_op_type in op_type_map.items(): |
| 4938 | try: |
| 4939 | self._gradient_override_map[op_type] = saved_mappings[op_type] |
| 4940 | except KeyError: |
no outgoing calls