1# Copyright 2017 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"""Logic to update a Tensorflow model graph with quantization operations.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import print_function 20 21import collections 22from tensorflow.contrib.quantize.python import common 23 24 25class InputToOps(object): 26 """Holds a mapping from tensor's name to ops that take it as input.""" 27 28 def __init__(self, graph): 29 """Initializes mapping from tensor's name to ops that take it. 30 31 Helps find edges between ops faster and avoids iterating over the whole 32 graph. The mapping is of type Dict[str, Set[tf.Operation]]. 33 34 Note: while inserting operations into the graph, we do not update the 35 mapping, assuming that insertion points in the graph are never adjacent. 36 With that restriction, an out of date mapping still works fine. 37 38 Args: 39 graph: Graph to process. 40 """ 41 self.mapping = collections.defaultdict(set) 42 for op in (op for op in graph.get_operations()): 43 if op.name.startswith(common.SKIPPED_PREFIXES): 44 continue 45 for op_input in op.inputs: 46 self.mapping[op_input].add(op) 47 48 def ConsumerOperations(self, producer_op): 49 """Looks through outputs of producer_op, finds ops that take them as input. 50 51 Args: 52 producer_op: Operation containing outputs to process. 53 54 Returns: 55 A Set[Operation] containing all operations taking input from producer_op 56 outputs. 57 """ 58 result = set() 59 for inp in producer_op.outputs: 60 result.update(self.mapping[inp]) 61 return result 62