Implementation of case that allows for different cond functions. Args: cond_fn: method that has signature and semantics of `cond` above. pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor, and a callable which returns a list of tensors. default: Optional callable th
(cond_fn,
pred_fn_pairs,
default,
exclusive,
name,
allow_python_preds=False,
**cond_kwargs)
| 3132 | |
| 3133 | |
| 3134 | def _case_helper(cond_fn, |
| 3135 | pred_fn_pairs, |
| 3136 | default, |
| 3137 | exclusive, |
| 3138 | name, |
| 3139 | allow_python_preds=False, |
| 3140 | **cond_kwargs): |
| 3141 | """Implementation of case that allows for different cond functions. |
| 3142 | |
| 3143 | Args: |
| 3144 | cond_fn: method that has signature and semantics of `cond` above. |
| 3145 | pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor, and a |
| 3146 | callable which returns a list of tensors. |
| 3147 | default: Optional callable that returns a list of tensors. |
| 3148 | exclusive: True iff at most one predicate is allowed to evaluate to `True`. |
| 3149 | name: A name for this operation (optional). |
| 3150 | allow_python_preds: if true, pred_fn_pairs may contain Python bools in |
| 3151 | addition to boolean Tensors |
| 3152 | **cond_kwargs: keyword arguments that will be passed to `cond_fn`. |
| 3153 | |
| 3154 | Returns: |
| 3155 | The tensors returned by the first pair whose predicate evaluated to True, or |
| 3156 | those returned by `default` if none does. |
| 3157 | |
| 3158 | Raises: |
| 3159 | TypeError: If `pred_fn_pairs` is not a list/dictionary. |
| 3160 | TypeError: If `pred_fn_pairs` is a list but does not contain 2-tuples. |
| 3161 | TypeError: If `fns[i]` is not callable for any i, or `default` is not |
| 3162 | callable. |
| 3163 | """ |
| 3164 | predicates, actions = _case_verify_and_canonicalize_args( |
| 3165 | pred_fn_pairs, exclusive, name, allow_python_preds) |
| 3166 | with ops.name_scope(name, "case", [predicates]): |
| 3167 | if default is None: |
| 3168 | default, predicates, actions = _case_create_default_action( |
| 3169 | predicates, actions) |
| 3170 | fn = default |
| 3171 | # To eval conditions in direct order we create nested conditions in reverse: |
| 3172 | # cond_fn(c[0], true_fn=.., false_fn=cond_fn(c[1], ...)) |
| 3173 | for predicate, action in reversed(list(zip(predicates, actions))): |
| 3174 | fn = functools.partial( |
| 3175 | cond_fn, predicate, true_fn=action, false_fn=fn, **cond_kwargs) |
| 3176 | if exclusive: |
| 3177 | with ops.control_dependencies([ |
| 3178 | _assert_at_most_n_true( |
| 3179 | predicates, n=1, msg="Input error: exclusive=True") |
| 3180 | ]): |
| 3181 | return fn() |
| 3182 | else: |
| 3183 | return fn() |
| 3184 | |
| 3185 | |
| 3186 | def _indexed_case_verify_and_canonicalize_args(branch_fns, default, |
no test coverage detected