1# Copyright 2020 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================ 15"""Ops to manipulate hashmap of tensors.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import print_function 20 21# go/tf-wildcard-import 22# pylint: disable=wildcard-import 23from tensorflow.python.framework import ops 24from tensorflow.python.ops import array_ops 25from tensorflow.python.ops import control_flow_ops 26from tensorflow.python.ops import gen_map_ops 27from tensorflow.python.ops.gen_map_ops import * 28 29ops.NotDifferentiable("EmptyTensorMap") 30 31def empty_tensor_map(): 32 return gen_map_ops.empty_tensor_map() 33 34def tensor_map_size(input_handle): 35 return gen_map_ops.tensor_map_size(input_handle) 36 37def tensor_map_insert(input_handle, key, value): 38 return gen_map_ops.tensor_map_insert(input_handle, key, value) 39 40def tensor_map_lookup(input_handle, key, value_dtype): 41 return gen_map_ops.tensor_map_lookup(input_handle, key, value_dtype) 42 43def tensor_map_erase(input_handle, key, value_dtype): 44 return gen_map_ops.tensor_map_erase(input_handle, key, value_dtype) 45 46def tensor_map_has_key(input_handle, key): 47 return gen_map_ops.tensor_map_has_key(input_handle, key) 48 49 50def tensor_map_stack_keys(input_handle, key_dtype): 51 return gen_map_ops.tensor_map_stack_keys(input_handle, key_dtype) 52 53 54@ops.RegisterGradient("TensorMapLookup") 55def LookupGrad(op, dval): 56 _, k = op.inputs 57 map_grad = empty_tensor_map() 58 map_grad = tensor_map_insert(map_grad, k, dval) 59 key_grad = None 60 return map_grad, key_grad 61 62@ops.RegisterGradient("TensorMapInsert") 63def InsertGrad(op, dmap): 64 _, k, v = op.inputs 65 key_grad = None 66 (value_grad, map_grad) = control_flow_ops.cond( 67 tensor_map_has_key(dmap, k), lambda: 68 (tensor_map_lookup(dmap, k, v.dtype), tensor_map_erase(dmap, k, v.dtype)), 69 lambda: (array_ops.zeros_like(v), dmap)) 70 return map_grad, key_grad, value_grad 71 72@ops.RegisterGradient("TensorMapErase") 73def EraseGrad(op, dmap): 74 key_grad = None 75 map_grad = dmap 76 return map_grad, key_grad 77