Returns a context manager that specifies an op to colocate with. Note: this function is not for public use, only for internal libraries. For example: ```python a = tf.Variable([1.0]) with g.colocate_with(a): b = tf.constant(1.0) c = tf.add(a, b) ``` `b` an
(self, op, ignore_existing=False)
| 4246 | |
| 4247 | @tf_contextlib.contextmanager |
| 4248 | def colocate_with(self, op, ignore_existing=False): |
| 4249 | """Returns a context manager that specifies an op to colocate with. |
| 4250 | |
| 4251 | Note: this function is not for public use, only for internal libraries. |
| 4252 | |
| 4253 | For example: |
| 4254 | |
| 4255 | ```python |
| 4256 | a = tf.Variable([1.0]) |
| 4257 | with g.colocate_with(a): |
| 4258 | b = tf.constant(1.0) |
| 4259 | c = tf.add(a, b) |
| 4260 | ``` |
| 4261 | |
| 4262 | `b` and `c` will always be colocated with `a`, no matter where `a` |
| 4263 | is eventually placed. |
| 4264 | |
| 4265 | **NOTE** Using a colocation scope resets any existing device constraints. |
| 4266 | |
| 4267 | If `op` is `None` then `ignore_existing` must be `True` and the new |
| 4268 | scope resets all colocation and device constraints. |
| 4269 | |
| 4270 | Args: |
| 4271 | op: The op to colocate all created ops with, or `None`. |
| 4272 | ignore_existing: If true, only applies colocation of this op within the |
| 4273 | context, rather than applying all colocation properties on the stack. |
| 4274 | If `op` is `None`, this value must be `True`. |
| 4275 | |
| 4276 | Raises: |
| 4277 | ValueError: if op is None but ignore_existing is False. |
| 4278 | |
| 4279 | Yields: |
| 4280 | A context manager that specifies the op with which to colocate |
| 4281 | newly created ops. |
| 4282 | """ |
| 4283 | if op is None and not ignore_existing: |
| 4284 | raise ValueError("Trying to reset colocation (op is None) but " |
| 4285 | "ignore_existing is not True") |
| 4286 | op = _op_to_colocate_with(op, self) |
| 4287 | |
| 4288 | # By default, colocate_with resets the device function stack, |
| 4289 | # since colocate_with is typically used in specific internal |
| 4290 | # library functions where colocation is intended to be "stronger" |
| 4291 | # than device functions. |
| 4292 | # |
| 4293 | # In the future, a caller may specify that device_functions win |
| 4294 | # over colocation, in which case we can add support. |
| 4295 | device_fn_tmp = self._device_function_stack |
| 4296 | self._device_function_stack = traceable_stack.TraceableStack() |
| 4297 | |
| 4298 | if ignore_existing: |
| 4299 | current_stack = self._colocation_stack |
| 4300 | self._colocation_stack = traceable_stack.TraceableStack() |
| 4301 | |
| 4302 | if op is not None: |
| 4303 | # offset refers to the stack frame used for storing code location. |
| 4304 | # We use 4, the sum of 1 to use our caller's stack frame and 3 |
| 4305 | # to jump over layers of context managers above us. |