B
    d                 @   s  d Z ddlZddlZddlZddlZddl	m
Z ddl	mZ ddl	mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlm Z! ddl"m#Z# ddl$m%Z& e&dgde!'ddG dd dZ(G dd dZ)G dd de)Z*G dd de)Z+G dd dZ,dd Z-dd  Z.d!d" Z/d#d$ Z0d%d& Z1d'd( Z2d)d* Z3dAd,d-Z4d.d/ Z5d0d1 Z6d2d3 Z7d4d5 fd6d7Z8dBd8d9Z9d:d; Z:e&d<gde!'ddddd=d5 fd>d?Z;dd?d@d9d;gZ<e#e=e< dS )Ca	  Define tflite op hints (intrinsic operations).

This essentially allows defining a TensorFlow API for tflite operations in
Python with hints on how they are represented in TensorFlow Lite. This basically
is a form of tflite intrinsic. It wraps a subpart of a TensorFlow execution
graph and is useful for LSTMs and other complicated TensorFlow constructions
that are difficult to pattern match in TOCO, but are represented by a single
accelerated tflite op.

Example:
  def tflite_cool_activation(input):
    # A cool activation function.
    custom = tf.lite.OpHint("cool_activation")
    input, = custom.add_inputs(input)
    output = tf.sigmoid(input) * input
    output, = custom.add_outputs(output)
    return output

  image = tf.compat.v1.placeholder(tf.float32, (1, 16, 16, 1))
  output = tf.identity(tflite_cool_activation(image))

  session = tf.compat.v1.Session()

  graphdef_to_convert = tf.lite.experimental.convert_op_hints_to_stubs(session)
  tflite_graph = tf.compat.v1.lite.toco_convert(
      graphdef_to_convert, [image], [output], allow_custom_ops=True)
  with open("/tmp/graph.fb", "wb") as fp:
    fp.write(tflite_graph)

How does it work?:

OpHint is a helper that you use when defining a vanilla python function.
It allows you to wrap arguments with tf.identities with some custom attributes.
These attributes allow you to find the original block of ops that was created.
For example, if you use cool_activation above you essentially get:

a_input = tf.identity()
result = tf.multiply(tf.sigmoid(a_input), a_input)
output = tf.identity()

a_input, output are identities that have parameters representing
what argument they are, what the name of the function they should turn into
in tf lite as well as a guid that uniquely identifies a particular invocation.

Once you have built your whole tensorflow graph, you can run it and train it
as usual, but after you have done that, you need to convert the graph into
a form that replaces these subgraphs wrapped in identities to stub ops. These
ops don't actually exist in the normal TensorFlow runtime, but will be
understood by toco later. The generated TensorFlow Lite flatbuffer file will
contain a custom operator called "cool_activation". Developer needs to implement
and register this operator in TensorFlow Lite in order to do inference.
    N)attr_value_pb2)	graph_pb2)node_def_pb2)dtypes)ops)tensor_util)_bfs_for_reachable_nodes)_extract_graph_summary)	array_ops)compat)deprecation)remove_undocumented)	tf_exportzlite.OpHint)Zv1zxPlease follow instructions under https://www.tensorflow.org/lite/convert/operation_fusion for operationfusion in tflite.c               @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZG dd dZd ddZdd Zdd Zdd Zdd Zdd Zdd ZdS )!OpHinta  A class that helps build tflite function invocations.

  It allows you to take a bunch of TensorFlow ops and annotate the construction
  such that toco knows how to convert it to tflite. This embeds a pseudo
  function in a TensorFlow graph. This allows embedding high-level API usage
  information in a lower level TensorFlow implementation so that an alternative
  implementation can be substituted later.

  Essentially, any "input" into this pseudo op is fed into an identity, and
  attributes are added to that input before being used by the constituent ops
  that make up the pseudo op. A similar process is done to any output that
  is to be exported from the current op.

  Z_tflite_function_nameZ_tflite_function_uuidZ_tflite_function_input_indexZ_tflite_function_output_indexZ_tflite_function_sort_indexZ_tflite_function_aggregateZ_tflite_input_indicesZ_tflite_ophint_levelZ&_tflite_children_ophint_inputs_mappingstackfirstlastc               @   s,   e Zd ZdZd
ddZdd Zddd	ZdS )zOpHint.OpHintArgumentTrackerzConceptually tracks indices of arguments of "OpHint functions".

    The inputs and arguments of these functions both use an instance
    of the class so they can have independent numbering.
       Nc             C   sB   || _ || _d| _t | _i | _i | _|| _|| _|| _	|| _
dS )a%  Initialize ophint argument.

      Args:
        function_name: Name of the function that this tracks arguments for.
        unique_function_id: UUID of function that this tracks arguments for.
        node_name_prefix: How identities that are created are named.
        attr_name: Name of attribute to use to store the index for this hint.
          i.e. FUNCTION_INPUT_INDEX or FUNCTION_OUTPUT_INDEX
        level: Hierarchical level of the Ophint node, a number.
        children_inputs_mappings: Inputs/Outputs mapping for children hints.
      r   N)_function_name_unique_function_id_next_global_indexset_used_global_indices_tag_to_global_index_tag_to_next_sort_index_node_name_prefix
_attr_name_level_children_inputs_mappings)selffunction_nameZunique_function_idZnode_name_prefix	attr_namelevelchildren_inputs_mappings r$   P/var/www/html/venv/lib/python3.7/site-packages/tensorflow/lite/python/op_hint.py__init__   s    z%OpHint.OpHintArgumentTracker.__init__c             C   sV   |dkr| j }n|| jkr"td|}| j| x| j | jkrP|  j d7  _ q4W |S )as  Return the next unused argument index in order or use an override.

      Args:
        index_override: An index to use instead of the next available or None
          to use the next available.

      Returns:
        A valid global_index to use for the next hint argument.

      Raises:
        ValueError: If the index_override is already used by another hint.
      Nz0Index %d was already used by another call to addr   )r   r   
ValueErroradd)r   index_overrideglobal_indexr$   r$   r%   _get_new_global_index   s    
z2OpHint.OpHintArgumentTracker._get_new_global_indexc       
   	   C   s  |dkr(|dk	rt d| |}d}n|dkr8t d|| jkr^| || j|< d| j|< n*|r|| j| krt d||| j| f | j| }| j| }| j|  d7  < | j}d| j| j||||f }tj||d}	|	j	
tjtjt| jd	 |	j	
tjtjt| jd	 |	j	
| jtj|d
 |	j	
tjtj| jd
 | jrz|	j	
tjtjtt| jd	 |dk	r|	j	
tjtj|d
 |dk	r|	j	
tjtjt|d	 |	S )a  Return a wrapped tensor of an input tensor as an argument.

      Args:
        arg: A TensorFlow tensor that should be considered an argument.
        tag: String tag to identify arguments that should be packed.
        name: Name of argument. This is included in the Identity hint op names.
        aggregate: Strategy to aggregate.
        Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
          and OpHint.AGGREGATE_STACK.
          Note, aggregate is only valid if tag is specified.
        index_override: Specify what input/output index should this be in the
          final stub. i.e. add(arg0, index=1); add(arg1, index=0) will make the
          final stub be as stub_func(inputs[arg1, arg0], outputs=[]) rather than
          the default call order based ordering.

      Returns:
        A tensor representing the wrapped argument.

      Raises:
        ValueError: When indices are not consistent.
      Nz*You must specify `tag` if using aggregate.z*You must specify `aggregate` if using tag.r   z,Tag %r was called with two indices %r and %rr   z%s-%s-%s-%r-%r-%s)name)s)i)r'   r+   r   r   r   r   r   
_array_opsidentityop	_set_attrr   FUNCTION_NAME_ATTR_attr_value_pb2	AttrValue_compatas_bytesFUNCTION_UUID_ATTRr   FUNCTION_LEVEL_ATTRr   r   CHILDREN_INPUTS_MAPPINGS_jsondumpsFUNCTION_SORT_INDEX_ATTRFUNCTION_AGGREGATE_ATTR)
r   argtagr,   Z	aggregater)   r*   Z
sort_indexuuidZidentity_opr$   r$   r%   r(      sb    







z OpHint.OpHintArgumentTracker.add)r   N)NNNN)__name__
__module____qualname____doc__r&   r+   r(   r$   r$   r$   r%   OpHintArgumentTracker   s    
 rF   r   Nc             K   s   || _ || _| jdkr$|dks2tnt|ts2t|| _| jdk	rN| | j t j	| _
|| _d| _t| j | j
dtj|| j| _t| j | j
dtj|| j| _dS )a  Create a OpHint.

    Args:
      function_name: Name of the function (the custom op name in tflite)
      level: OpHint level.
      children_inputs_mappings: Children OpHint inputs/outputs mapping.
        children_inputs_mappings should like below:
        "parent_first_child_input":
            [{"parent_input_index": num, "child_input_index": num}, ...]
        "parent_last_child_output":
            [{"parent_output_index": num, "child_output_index": num}, ...]
        "internal_children_input_output":
            [{"child_input_index": num, "child_output_index": num}, ...]
      **kwargs: Keyword arguments of any constant attributes for the function.
    r   NFZ	InputHintZ
OutputHint)r   r   AssertionError
isinstancedictr   "_validate_children_inputs_mappings_uuiduuid1hexr   Z_attrs_to_store_laterZ_stored_attrsr   rF   FUNCTION_INPUT_INDEX_ATTR_inputsFUNCTION_OUTPUT_INDEX_ATTR_outputs)r   r    r"   r#   kwargsr$   r$   r%   r&   3  s$    



zOpHint.__init__c             C   st   t |tstd|kstd|ks&td|ks2tdd }||d ddg ||d dd	g ||d d
d	g dS )zValidate children inputs mappings is in the right format.

    Args:
      children_inputs_mappings: the Children ophint inputs/outputs mapping.
    parent_first_child_inputparent_last_child_outputinternal_children_input_outputc             S   s:   x4| D ],}t |tstx|D ]}||kstqW qW d S )N)rH   rI   rG   )ZdictlistkeysZdiktkeyr$   r$   r%   assert_dictlist_has_keysh  s    

zKOpHint._validate_children_inputs_mappings.<locals>.assert_dictlist_has_keysparent_ophint_input_indexfirst_child_ophint_input_indexparent_output_indexchild_output_indexchild_input_indexN)rH   rI   rG   )r   r#   rX   r$   r$   r%   rJ   [  s    

z)OpHint._validate_children_inputs_mappingsc             C   s0   t |}|j|tj|jjjd jd d S )Nvalue)tensor)	_opsZconvert_to_tensorr1   r2   r4   r5   node_defattrr_   )r   Zdest_opr,   r^   Ztensor_valuer$   r$   r%   _setattrx  s    
zOpHint._setattrc             O   s   | j j||S )aO  Add a wrapped input argument to the hint.

    Args:
      *args: The input tensor.
      **kwargs:
        "name" label
        "tag" a tag to group multiple arguments that will be aggregated. I.e.
          a string like 'cool_input'. Basically multiple inputs can be added
          to the same hint for parallel operations that will eventually be
          combined. An example would be static_rnn which creates multiple copies
          of state or inputs.
        "aggregate" aggregation strategy that is valid only for tag non None.
          Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
          and OpHint.AGGREGATE_STACK.
        "index_override" The global index to use. This corresponds to the
          argument order in the final stub that will be generated.
    Returns:
      The wrapped input tensor.
    )rO   r(   )r   argsrR   r$   r$   r%   	add_input  s    zOpHint.add_inputc             O   s   | j j||S )aR  Add a wrapped output argument to the hint.

    Args:
      *args: The output tensor.
      **kwargs:
        "name" label
        "tag" a tag to group multiple arguments that will be aggregated. I.e.
          a string like 'cool_input'. Basically multiple inputs can be added
          to the same hint for parallel operations that will eventually be
          combined. An example would be static_rnn which creates multiple copies
          of state or inputs.
        "aggregate" aggregation strategy that is valid only for tag non None.
          Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
          and OpHint.AGGREGATE_STACK.
        "index_override" The global index to use. This corresponds to the
          argument order in the final stub that will be generated.
    Returns:
      The wrapped output tensor.
    )rQ   r(   )r   rd   rR   r$   r$   r%   
add_output  s    zOpHint.add_outputc                s:   d|kr$ fddt ||d D S  fdd|D S dS )aM  Add a sequence of inputs to the function invocation.

    Args:
      *args: List of inputs to be converted (should be Tf.Tensor).
      **kwargs: This allows 'names' which should be a list of names.

    Returns:
      Wrapped inputs (identity standins that have additional metadata). These
      are also are also tf.Tensor's.
    namesc                s    g | ]\}} j j||d qS ))r,   )rO   r(   ).0r?   r,   )r   r$   r%   
<listcomp>  s   z%OpHint.add_inputs.<locals>.<listcomp>c                s   g | ]} j |qS r$   )rO   r(   )rh   r?   )r   r$   r%   ri     s    N)zip)r   rd   rR   r$   )r   r%   
add_inputs  s    
zOpHint.add_inputsc                s:   d|kr$ fddt ||d D S  fdd|D S dS )a  Add a sequence of outputs to the function invocation.

    Args:
      *args: List of outputs to be converted (should be tf.Tensor).
      **kwargs: See

    Returns:
      Wrapped outputs (identity standins that have additional metadata). These
      are also tf.Tensor's.
    rg   c                s    g | ]\}} j j||d qS ))r,   )rQ   r(   )rh   r?   r,   )r   r$   r%   ri     s   z&OpHint.add_outputs.<locals>.<listcomp>c                s   g | ]} j |qS r$   )rQ   r(   )rh   r?   )r   r$   r%   ri     s    N)rj   )r   rd   rR   r$   )r   r%   add_outputs  s    
zOpHint.add_outputs)r   N)rB   rC   rD   rE   r3   r8   rN   rP   r=   r>   TFLITE_INPUT_INDICESr9   r:   AGGREGATE_STACKAGGREGATE_FIRSTAGGREGATE_LASTrF   r&   rJ   rc   re   rf   rk   rl   r$   r$   r$   r%   r   X   s.     
%r   c               @   s    e Zd ZdZdd Zdd ZdS )_LiteOperanda  Abstract operand for a tflite hint function._dynamic_rnn_loop.

  This is a base class that handles representing arguments to an OpHint.
  It also is able to serialize operands to the stubbed graph_def.
  Child classes are responsible for being able to
  store information about the hint identity operators. They are also responsible
  for knowing how to serialize to output graphdefs.

  Typically this will be implemented by holding one or more identity nodes
  that were previously discovered as hints.
  c             C   s   ~t ddS )a6  This adds the node(s) to out_graphdef and returns the input node name.

    Args:
      out_graphdef: A graphdef that is ready to have this input added.

    Returns:
      The output that the stub should use as an input for this operand.

    Raises:
      RuntimeError: if the method is not implemented.
    zUnimplemented abstract method.N)RuntimeError)r   out_graphdefr$   r$   r%   #aggregate_and_return_name_for_input  s    z0_LiteOperand.aggregate_and_return_name_for_inputc             C   s   ~~~t ddS )a  Add node(s) to graph representing output operands and returns type.

    Args:
      fused_op_name: name of the fused op stub name.
      output_index: Output index that we are currently processing from stub.
      out_graphdef: The destination graphdef we are currently building up.

    Returns:
      The datatype of this identity.

    Raises:
      RuntimeError: if the method is not implemented.
    zUnimplemented abstract method.N)rr   )r   fused_op_nameoutput_indexrs   r$   r$   r%   $aggregate_and_return_name_for_output  s    z1_LiteOperand.aggregate_and_return_name_for_outputN)rB   rC   rD   rE   rt   rw   r$   r$   r$   r%   rq     s   rq   c               @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )_LiteSingleOperandz:A simple operand that is non-aggregated (i.e. most hints).c             C   s    t |  || _t|j| _d S )N)rq   r&   node_tensor_name_baser,   )r   ry   r$   r$   r%   r&     s    
z_LiteSingleOperand.__init__c             C   s   | j gS )N)r,   )r   r$   r$   r%   flatten	  s    z_LiteSingleOperand.flattenc             C   s   | j S )N)r,   )r   rs   r$   r$   r%   rt     s    z6_LiteSingleOperand.aggregate_and_return_name_for_inputc             C   sF   t | j}|jd d = |jt|| |j|g | jjd jS )Ntype)	_copydeepcopyry   inputappend_tensorflow_output_nameextendrb   r.   )r   ru   indexrs   output_noder$   r$   r%   rw     s
    z7_LiteSingleOperand.aggregate_and_return_name_for_outputc             C   s
   t | jS )N)strr,   )r   r$   r$   r%   __str__  s    z_LiteSingleOperand.__str__N)	rB   rC   rD   rE   r&   r{   rt   rw   r   r$   r$   r$   r%   rx     s   rx   c               @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )_LiteAggregateOperandzAn operand for a tflite hint function that is aggregated from many.

  For example, an LSTM is a grid of operators that are all related. Inputs
  going into them may need to be fused, so they should all be tracked as
  related arguments.
  c             C   s&   t |  || _i | _i | _d | _d S )N)rq   r&   aggregationrg   nodes	flattened)r   r   r$   r$   r%   r&   #  s
    
z_LiteAggregateOperand.__init__c             C   s   t |j| j|< || j|< d S )N)rz   r,   rg   r   )r   sortry   r$   r$   r%   r(   *  s    z_LiteAggregateOperand.addc             C   s   | j sdgt| j | _ x | j D ]\}}|| j |< q$W x| jD ]}|dkrBtdqBW | jtjkrx| j dd | _ n:| jtjkr| j dd | _ n| jtj	krnt
d| j | j S )zAReturn a list of all the node protos in aggregation sorted order.NzAggregate was missing argument.r   z%Invalid aggregation type %r specified)r   lenr   itemsrr   r   r   ro   rp   rn   r'   )r   idxry   nr$   r$   r%   flatten_nodes.  s     
z#_LiteAggregateOperand.flatten_nodesc             C   s   dd |   D S )z=Return a list of all node names in aggregation sorted sorter.c             S   s   g | ]}t |jqS r$   )rz   r,   )rh   xr$   r$   r%   ri   D  s    z1_LiteAggregateOperand.flatten.<locals>.<listcomp>)r   )r   r$   r$   r%   r{   B  s    z_LiteAggregateOperand.flattenc             C   s   |   }| jtjks | jtjkr0t|dks0tt|dkrV| jtjkrVt|d j	S t
 }d|_d|d j	 |_	t||jd _|d jd j|jd _x|D ]}|jt|j	 qW |j|g |j	S dS )a  This adds the nodes to out_graphdef and returns an aggregated output.

    In particular, if you have 4 inputs to a hint stub, this will be the
    node that you can use as an output. I.e. you have 4 timesteps from a
    static rnn, then a fused UnidirectionalLSTM will expect 1 input with
    all 4 time steps. So here we make a pack and return the output name of
    that pack.

    Args:
      out_graphdef: A graphdef that is ready to have this input added.

    Returns:
      The name of a pack that aggregates this node.
    r   r   PackzOpHintStack-%sNTN)r   r   r   ro   rp   r   rG   rn   rz   r,   _node_def_pb2NodeDefr1   rb   r.   r|   r   r   ry   r   )r   rs   r   new_nodediscreter$   r$   r%   rt   F  s    
z9_LiteAggregateOperand.aggregate_and_return_name_for_inputc             C   s"  |   }| jtjks | jtjkr0t|dks0tt|dkrb| jtjkrbt|d }|	|||S t
 }d|_d|d j |_t||jd _|d jd j}||jd _|jt|| |j|g xLt|D ]@\}}	t|	}
|
jdd= |
jt|j| |j|
g qW |S dS )aY  This adds to `out_graphdef` all the unaggregated outputs.

    I.e. we are outputting from a fused stub, but we need to make it compatible
    with the unfused original graph so we insert an unpack. Ideally in a later
    stage the unpack -> pack sequences will be removed.

    Args:
      fused_op_name: The name of the stub we are in the process of fusing.
      output_index: The output output_index this object represents.
      out_graphdef: The graphdef we are in the process of buildings

    Returns:
      The type of the aggregated output (so we can finish building the stub
      op).
    r   r   UnpackzOpHintUnstack-%snumr   N)r   r   r   ro   rp   r   rG   rn   rx   rw   r   r   r1   r,   rb   r.   r|   r   r   r   ry   r   	enumerater}   r~   )r   ru   rv   rs   r   Ztemp_opZ
stack_nodeoutput_typer   r   r   r$   r$   r%   rw   f  s.    

z:_LiteAggregateOperand.aggregate_and_return_name_for_outputc             C   s6   d| j  }x&| j D ]\}}|d||f 7 }qW |S )Nz			AGGREGATE %s
z
			%d: %s
)r   rg   	iteritems)r   r-   r   valr$   r$   r%   r     s    
z_LiteAggregateOperand.__str__N)rB   rC   rD   rE   r&   r(   r   r{   rt   rw   r   r$   r$   r$   r%   r     s    ,r   c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_LiteFuncCalla  Represent a TensorFlow Lite custom function.

  This is uses to accumulate found hints in the graphdef into a single
  conceptual unit.

  Attributes:
    inputs: inputs to the op (hash from index # to argument)
    outputs: outputs to the op (hash from index # to argument)
    function_name: the tflite custom op name to use
    uuid: a unique call id for this particular call  (i.e. multiple function
      calls would have the same function_name but different uuids.
    params: A param name to key value for op constant data. I.e. for axis on a
      reduction, strides on a convolution, etc.
    level: Level of the OpHint.
    children_inputs_mappings: If the Ophint has children, children inputs
      mappings indicate how their inputs & outputs are mapped.
  c             C   s.   i | _ i | _d | _d | _i | _d| _i | _d S )Nr   )inputsoutputsr    rA   paramsr"   r#   )r   r$   r$   r%   r&     s    z_LiteFuncCall.__init__c             C   s   dd }|| j || jfS )zReturn a list of inputs and outputs in a flattened format.

    Returns:
      Tuple of (inputs, outputs). where input and output i a list of names.
    c             S   s(   g }x|   D ]}||  qW |S )N)valuesr   r{   )Zinput_or_output_dictZflattened_itemsitemr$   r$   r%   _flatten  s    z<_LiteFuncCall.flattened_inputs_and_outputs.<locals>._flatten)r   r   )r   r   r$   r$   r%   flattened_inputs_and_outputs  s    z*_LiteFuncCall.flattened_inputs_and_outputsc             C   s<   dd }d|| j  }d|| j }d| j| j| j||f S )Nc             S   s2   d}x(|   D ]\}}|d| t| 7 }qW |S )N z		%d:
)r   r   )r   r-   r   r   r$   r$   r%   format_args  s    z*_LiteFuncCall.__str__.<locals>.format_argsz	Inputs
z		Outputs
zAtflite function %s call %s level %d 
	inputs:
		%s
	outputs:
		%s)r   r   r    rA   r"   )r   r   Z
inputs_strZoutputs_strr$   r$   r%   r     s
    z_LiteFuncCall.__str__N)rB   rC   rD   rE   r&   r   r   r$   r$   r$   r%   r     s   	r   c       
      C   sf  t t}xT| D ]J}|j}tj|ks|tj js6q|tj j}|| }||_|tj j|_	|tj
 j|_tj|kr|tj jnd}|dkrd}d}tj|krt|tj j}tj|krtt|tj j|_dd }tj|kr||j|tj j||| tj|kr*||j|tj j||| x2|D ]*}	|	dr0||	 j|j|	dd< q0W qW |S )zLook at the all the input nodes and return a list of LiteFuncCall objs.

  Args:
    nodes: A TensorFlow graph_def to look for LiteFuncCalls.

  Returns:
    a list of `LifeFuncCall` objects in the form

  Nr   c             S   s>   |dkrt || |< n$|| kr*t|| |< | | || dS )z.Add a given index into the function structure.N)rx   r   r(   )stuffr   r   operandr   r$   r$   r%   put_operand  s
    z-_find_all_hints_in_nodes.<locals>.put_operandZ_tflite_attr_z_tflite_attr_,r   )_collectionsdefaultdictr   rb   r   r8   r-   rA   r3   r    r9   r.   r"   r=   r>   r6   Zas_textr:   r;   loadsr#   rN   r   rP   r   
startswithr_   r   replace)
r   Z
func_callsry   rb   rA   Zcall_defr   r   r   ar$   r$   r%   _find_all_hints_in_nodes  s>    




	


"r   c             C   s   t dd t| D S )Nc             s   s    | ]\}}t |j|fV  qd S )N)rz   r,   )rh   r   ry   r$   r$   r%   	<genexpr>  s    z5_extract_topology_sequence_mapping.<locals>.<genexpr>)rI   r   )r   r$   r$   r%   "_extract_topology_sequence_mapping  s    r   c             C   s   g }xX| j D ]N}x8t|jD ]*\}}|j| |kr||j|  |j|< qW |t| qW t| j }t|}g }xR| D ]F}	|		 \}}
||
d  }x|
D ]}t
||| }qW |||	f q~W |jdd d dd |D }||fS )a  Find children hints and all nodes inside the while loop.

  Args:
    function_def: Function def of the while loop.
    nodes_mapping: While loop input_arg : real node name.

  Returns:
    Ordered children hints and all re-mapped nodes inside the while loop.
  r   c             S   s   | d S )Nr   r$   )tupr$   r$   r%   <lambda>7      z4_find_children_hints_in_while_loop.<locals>.<lambda>)rW   c             S   s   g | ]}|d  qS )r   r$   )rh   r   r$   r$   r%   ri   8  s    z6_find_children_hints_in_while_loop.<locals>.<listcomp>)ra   r   r   r   r}   r~   r   r   r   r   minr   )function_defnodes_mapping	new_nodesry   r.   _name_to_seq_numchildren_hintsZchildren_hints_qhintoutput_namesseqZoutput_nameZordered_children_hintsr$   r$   r%   "_find_children_hints_in_while_loop  s$    


r   c             C   s~  t |\}}}|  \}}t||}t||}t|}g }	t }
|
j|j |
j|j t }x|j	D ] }|
j	
t|g t|j}||krn||krn||krn|jdks|jdkrn|jd jj}|j}x|jjD ]}|jj|kr|jj}t|t|ks
ti }x$t|D ]\}}|| ||j< qW t||\}}|dd |D  |	
| |
j	
| qW qnW |	|
|fS )a  Find all children hints.

  For a given OpHint, we find all children hints inside it, we also copy all the
  nodes inside function defs (if applicable) to the original graph_def, they are
  returned in a list as well.

  Args:
    call: Parent OpHint that contains children ophints.
    graph_def: Original graph def.

  Returns:
    Ordered children hints inside the parent ophint; new graph def that contains
    nodes inside function defs (if applicable); nodes inside function defs.
  WhileZStatelessWhilebodyc             S   s   g | ]
}|j qS r$   )r,   )rh   r   r$   r$   r%   ri   j  s    z(_find_children_hints.<locals>.<listcomp>)r	   r   r   r   
_graph_pb2GraphDeflibraryCopyFromversionsry   r   r}   r~   rz   r,   r1   rb   funcr   function	signatureZ	input_argr   rG   r   r   update)call	graph_defname_to_input_namer   input_namesr   reachable_by_inputreachable_by_outputoutput_nodes_setr   outfunction_def_nodesry   r   Z	body_nameZinputs_outside_loopr   Zfunction_inputsr   r.   Zfunction_inputZchildren_hints_in_loopr   r$   r$   r%   _find_children_hints<  s@    


r   c             C   s$   |  dr| dd S | dd S )a#  Removes the device assignment code from a tensor.

  e.g. _tensor_name_base("foo:3") => "foo"

  Args:
    full_tensor_name: A tensor name that is annotated with a device placement
      (this is what tensor flow introspection gives).

  Returns:
    A name without any device assignment.
  ^r   N:r   )r   split)Zfull_tensor_namer$   r$   r%   rz   q  s    
rz   c             C   s   |dkr| S d| |f S )Nr   z%s:%dr$   )Ztensor_namerv   r$   r$   r%   r     s    r   c                sn   | g}t   x\|rh| } | ||krD||krDtd| |f ||kr| fdd|| D 7 }qW dS )a{  Checks to make sure node only connects to predecessor graph through inputs.

  Args:
    n: Node to check
    reachable_by_input: Nodes that are reachable by all inputs of subgraph
    input_nodes_set: The set of nodes that are "inputs".
    name_to_input_name: Maps from name to the list of inputs.

  Raises:
    TypeError: If the given node uses items past inputs directly.
  z)Node %s uses input %s not in input_nodes.c                s   g | ]}| kr|qS r$   r$   )rh   
input_node)visitedr$   r%   ri     s    z*_check_subgraph_closed.<locals>.<listcomp>N)r   popr(   	TypeError)r   r   Zinput_nodes_setr   next_to_visitZcurrent_noder$   )r   r%   _check_subgraph_closed  s    
r   Tc                s(  |dkrt  }t|\}} |  \}}t||}t||}	t |}
g }t  }xf|jD ]\}t|j}||	kr||kr||
kr|| qV||kr||kr|| qV|sV|| qVW t	
 }tt| fddd}x$|D ]}|jt|| g qW t| j }|  t| j }|  t }t }dtt j |_d|_|jd tjtj j!d |jd tjt"#d	gtj d
gd |j|g t$|d
 }xLt%|D ]@}||kr| j| }|&|}|j'| n|j'|j qW |jt(j) jj*| | j+|_| j,|_|j|g g }t$|d
 }xNt%|D ]B}||krv| j| }|-|j||}n|jd j*}|| qLW ||jd jj.dd< d|jd _/xR|D ]J}d}x || D ]}||krd}qW |r|jt|| g qW |j0|j0 |j1|j1 |S )a  Given a graph_def, converts `call` into a stub and returns a new graph_def.

  Args:
    call: A single function call to be converted.
    graph_def: A graph_def to use as input (that has call obviously).
    function_def_nodes: Nodes inside the function def those are not connected to
      the graph.
    is_last_run: Whether it is the last run for a given pass (for OpHint has
      children).

  Returns:
    A new transformed graph-def that has call as a stub (single op).

  Note: after this process, the graph_def can no longer be loaded into
      the tensorflow runtime, so all future manipulations are done in graph_def
      level.
  Nc                s    |  S )Nr$   )r   )r   r$   r%   r     r   z1_convert_single_op_hint_to_stub.<locals>.<lambda>)rW   ZConstZdtype)r|   r^   r   r   )r_   r|   Z_output_typesFZ_output_quantizedT)2r   r	   r   r   ry   rz   r,   r(   r   r   r   sortedlistr   r}   r~   r   rV   r   r   r   r   r   rK   rL   rM   r1   rb   r   r4   r5   _dtypesZfloat32Zas_datatype_enum_tensor_utilZmake_tensor_protomaxrangert   r   r   rm   r.   r    rA   rw   r|   br   r   )r   r   r   Zis_last_runr   name_to_noder   r   r   r   r   Znodes_after_fuseZnodes_deleted_by_fusery   r   r   Zreachable_by_input_sortedZsorted_input_indicesZsorted_output_indicesr   Zoptional_input_nodeZ	max_indexZ	cur_indexr   Z
input_nameZoutput_dtypesZmax_output_indexoutputZoutput_dtypeZshould_keepr$   )r   r%   _convert_single_op_hint_to_stub  s    













r   c                sd  t | \}}}~d}t }|j| j |j| j x | jD ]}t|j}|	dsj|j
	dsjqB|g}t t }	|d}
d}x|rN|d }| |d= || }|j	d}|j	d}|j
dks|s|r|j
dkr||O }|fdd	|| D 7 }n4|s$|r:|j
d
kr:|	|j ||M }nd}
P |j qW |
rBt|	dkrB|d}xV| jD ]L}|jkrqpx4||j D ]&}t|}|kr|krd}qW qpW |s|rB|	 }|| jd  xn| jD ]d}t|j}|krt|} fdd	t|| |jdd D |jdd< |j|g qW |dfS qBW | dfS )zRemoves a stack->unstack pattern from in_graph_def in a returned graph.

  Args:
    in_graph_def: Graph def to use as input.

  Returns:
    Simplified tuple (graph_def, changed_something) where changed_something
    is true if anything was done.
  TZOpHintStackr   Fr   ZOpHintUnstackZIdentityc                s   g | ]}| kr|qS r$   r$   )rh   r   )r   r$   r%   ri   O  s    z7_remove_one_redundant_stack_unstack.<locals>.<listcomp>r   r   c                s    g | ]\}}|kr n|qS r$   r$   )rh   strippedZnon_stripped)	end_input	pack_noder$   r%   ri   t  s   N)r	   r   r   r   r   r   ry   rz   r,   r   r1   r   r(   r   r   r   r}   r~   rj   r   )Zin_graph_defr   r   r   Zdo_generic_pack_unpackr   r   Z	node_namer   Zunpack_nodesZmatches_patternZis_hint_created_stackZcurrent_node_namery   Zis_op_hint_stackZis_op_hint_unstackZno_external_dependencyZother_nZinput_tensorZinput_opendr   r$   )r   r   r   r%   #_remove_one_redundant_stack_unstack#  sv    







r   c             C   s$   | }~ d}x|rt |\}}qW |S )NT)r   )r   currZchanged_stuffr$   r$   r%   _remove_redundant_stack_unstack}  s    r   c             C   s$   | dkr |  }t|}|d S | S )Nr   )rV   r   )Zoriginal_indexr   Znode_indicesr$   r$   r%   _get_correct_mapping  s
    r   c             C   s   d S )Nr$   )sessr   r$   r$   r%   r     r   r   c          	   C   sP  t | j}g }x"| D ]}||j|jf qW |jdd d x(tt|d ddD ]}|| \}}qXW | }~ xtt|d ddD ]}|| \}}|dkr(t	|| |\}	}}
t|	dkst
|| j}xt|	D ]\}}|dkr@x|d D ]<}t|d	 || j}t|d
 |j}|| j| |j|< qW nTxR|d D ]F}t|d |j}t|d |	|d  j}|	|d  j| |j|< qJW |t|	d krxJ|d D ]>}t|d || j}t|d |j}|| j| |j|< qW qW xJt|	D ]$\}}t|||
|t|	d k}qW qt|| |}||d qW t|}|S )a-  Converts a graph_def to a new graph_def where all op hints are stubbed.

  Args:
    graph_def: A graph def that we should convert.
    write_callback: A function pointer that can be used to write intermediate
      steps of graph transformation (optional).

  Returns:
    A new stubbed graph_def.
  c             S   s   | d S )Nr   r$   )r   r$   r$   r%   r     r   z3_convert_op_hints_to_stubs_helper.<locals>.<lambda>)rW   r   r      r   rS   rY   rZ   rU   r]   r\   rT   r[   initial)r   ry   r   r   r"   rA   r   r   r   r   rG   r#   r   r   r   r   r   r   )r   write_callbackhintsZhints_qr   r.   r"   Z	hint_uuidZcurr_graph_defr   r   r#   jZ
child_hintmappingZparent_input_indexr]   Zinput_indexrv   r[   r\   r$   r$   r%   !_convert_op_hints_to_stubs_helper  sd    




r   c             C   sp   | dk	r|dk	rt dg }| dk	r2t| jj}n|dk	rDt|j}x&| D ]}| \}}|| qNW |S )a  Find all Ophints output nodes in the graph.

  This is used to get all the output nodes those are ophinted, it is important
  for operation like convert_variables_to_constants keep all ophints structure.
  Note: only one of session or graph_def should be used, not both.
  Why this can be useful? Some TensorFlow ops (e.g. bidirectional rnn), can
  generate multiple outputs for unfused subgraph. If not all output nodes are
  consumed, graph optimization can potentially drop the unused nodes and cause
  ophints in an invalid states (due to missing ophinted output nodes). So it's
  important for us to find all those hinted output nodes and make sure they're
  not discarded away.

  Args:
    session: A TensorFlow session that contains the graph to convert.
    graph_def: A graph def that we should convert.

  Returns:
    A list of OpHints output nodes.
  Raises:
    ValueError: If both session and graph_def are provided.
  Nz*Provide only one of session and graph_def.)r'   r   r   ry   r   r   r   )sessionr   Zhinted_outputs_nodesr   r   r   Zoutput_nodesr$   r$   r%   find_all_hinted_output_nodes  s    
r   c             C   s>   | d krt dd}x$| jD ]}|j}tj|krd}P qW |S )NzMust provide the graph_def.FT)r'   ry   rb   r   rN   )r   Zophint_convertedry   rb   r$   r$   r%   is_ophint_converted   s    
r   z+lite.experimental.convert_op_hints_to_stubsc             C   s   d S )Nr$   )r   commentsr$   r$   r%   r     r   c             C   sJ   | dk	r|dk	rt d| dk	r,t| j|S |dk	r>t||S t ddS )a  Converts a graphdef with LiteOp hints into stub operations.

  This is used to prepare for toco conversion of complex intrinsic usages.
  Note: only one of session or graph_def should be used, not both.

  Args:
    session: A TensorFlow session that contains the graph to convert.
    graph_def: A graph def that we should convert.
    write_callback: A function pointer that can be used to write intermediate
      steps of graph transformation (optional).

  Returns:
    A new graphdef with all ops contained in OpHints being replaced by
    a single op call with the right parameters.
  Raises:
    ValueError: If both session and graph_def are provided.
  Nz*Provide only one of session and graph_def.z+Must specify session or graph_def as input.)r'   r   r   )r   r   r   r$   r$   r%   convert_op_hints_to_stubs  s    
r   Zconvert_op_hints_to_stubs_new)NT)NN)>rE   collectionsr   copyr}   jsonr;   rA   rK   Ztensorflow.core.frameworkr   r4   r   r   r   r   Ztensorflow.python.frameworkr   r   r   r`   r   r   Z+tensorflow.python.framework.graph_util_implr   r	   Ztensorflow.python.opsr
   r/   Ztensorflow.python.utilr   r6   r   Z_deprecationZtensorflow.python.util.all_utilr   Z tensorflow.python.util.tf_exportr   Z
_tf_export
deprecatedr   rq   rx   r   r   r   r   r   r   rz   r   r   r   r   r   r   r   r   r   r   Z_allowed_symbolsrB   r$   r$   r$   r%   <module>B   sn   
  y/~<A!5 
|Z	L
#
