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 17# go/tf-wildcard-import 18# pylint: disable=wildcard-import 19from tensorflow.python.framework import ops 20from tensorflow.python.ops import array_ops 21from tensorflow.python.ops import control_flow_ops 22from tensorflow.python.ops import gen_map_ops 23from tensorflow.python.ops.gen_map_ops import * 24 25ops.NotDifferentiable("EmptyTensorMap") 26 27def empty_tensor_map(): 28 return gen_map_ops.empty_tensor_map() 29 30def tensor_map_size(input_handle): 31 return gen_map_ops.tensor_map_size(input_handle) 32 33def tensor_map_insert(input_handle, key, value): 34 return gen_map_ops.tensor_map_insert(input_handle, key, value) 35 36def tensor_map_lookup(input_handle, key, value_dtype): 37 return gen_map_ops.tensor_map_lookup(input_handle, key, value_dtype) 38 39def tensor_map_erase(input_handle, key, value_dtype): 40 return gen_map_ops.tensor_map_erase(input_handle, key, value_dtype) 41 42def tensor_map_has_key(input_handle, key): 43 return gen_map_ops.tensor_map_has_key(input_handle, key) 44 45 46def tensor_map_stack_keys(input_handle, key_dtype): 47 return gen_map_ops.tensor_map_stack_keys(input_handle, key_dtype) 48 49 50@ops.RegisterGradient("TensorMapLookup") 51def LookupGrad(op, dval): 52 _, k = op.inputs 53 map_grad = empty_tensor_map() 54 map_grad = tensor_map_insert(map_grad, k, dval) 55 key_grad = None 56 return map_grad, key_grad 57 58@ops.RegisterGradient("TensorMapInsert") 59def InsertGrad(op, dmap): 60 _, k, v = op.inputs 61 key_grad = None 62 (value_grad, map_grad) = control_flow_ops.cond( 63 tensor_map_has_key(dmap, k), lambda: 64 (tensor_map_lookup(dmap, k, v.dtype), tensor_map_erase(dmap, k, v.dtype)), 65 lambda: (array_ops.zeros_like(v), dmap)) 66 return map_grad, key_grad, value_grad 67 68@ops.RegisterGradient("TensorMapErase") 69def EraseGrad(op, dmap): 70 key_grad = None 71 map_grad = dmap 72 return map_grad, key_grad 73