
    AVh                        d 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 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! dZ"dZ#dZ$d Z%d! Z&d" Z' e!d#g$      ejP                  	 	 	 	 	 	 	 dKd%              Z)	 	 	 	 	 	 	 	 dLd&Z*d' Z+ e
jX                  d(      d)        Z- e
jX                  d*      d+        Z. e!d,      ejP                  	 	 dMd-              Z/ e!d.g$      ejP                  	 	 	 dNd/              Z0 e!d.d0g$      ejP                  	 	 dOd1              Z1 e
jd                  d2        e
jd                  d3       d4 Z3d5 Z4d6 Z5d7 Z6d8 Z7dPd9Z8d: Z9d; Z:d< Z;d= Z< e!d>g$      ejP                  	 	 	 	 dQd?              Z= e!d#g $      ejP                  	 	 	 	 dQd@              Z>	 	 	 	 dRdAZ? e!dB      ejP                  dPdC              Z@dD ZA e!dE      ejP                  dPdF              ZBdG ZCdH ZDdSdIZEdJ ZFy)Tz7CTC (Connectionist Temporal Classification) Operations.    N)context)def_function)constant_op)device)dtypes)function)ops)sparse_tensor)tensor_shape)	array_ops)array_ops_stack)custom_gradient)functional_ops)gen_array_ops)gen_ctc_ops)inplace_ops)
linalg_ops)map_fn)math_ops)nn_ops)
sparse_ops)_BroadcastMul)deprecation)dispatch)nest)	tf_exportapi_implementsapi_preferred_deviceCPUGPUc                      t        j                          j                  } | yt        j                  j	                  |       j
                  S )zCParses the current context and returns the device type, eg CPU/GPU.N)r   device_namer   
DeviceSpecfrom_stringdevice_type)current_devices    M/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/ctc_ops.py_get_context_device_typer(   6   s:    ??$00.				&	&~	6	B	BB    c                 N    t         | t        |i}t        j                  ||d      S )NF)funcexperimental_attributes	autograph)_DEFUN_API_NAME_ATTRIBUTE_DEFUN_DEVICE_ATTRIBUTEr   r   )unique_api_namepreferred_devicer+   function_attributess       r'   _generate_defun_backendr3   >   s4    / 
		)<
O Or)   znn.ctc_loss)v1c                 *    t        | |||||||d	      S )a  Computes the CTC (Connectionist Temporal Classification) Loss.

  This op implements the CTC loss as presented in (Graves et al., 2006).

  Input requirements:

  ```
  sequence_length(b) <= time for all b

  max(labels.indices(labels.indices[:, 1] == b, 2))
    <= sequence_length(b) for all b.
  ```

  Notes:

  This class performs the softmax operation for you, so inputs should
  be e.g. linear projections of outputs by an LSTM.

  The `inputs` Tensor's innermost dimension size, `num_classes`, represents
  `num_labels + 1` classes, where num_labels is the number of true labels, and
  the largest value `(num_classes - 1)` is reserved for the blank label.

  For example, for a vocabulary containing 3 labels `[a, b, c]`,
  `num_classes = 4` and the labels indexing is `{a: 0, b: 1, c: 2, blank: 3}`.

  Regarding the arguments `preprocess_collapse_repeated` and
  `ctc_merge_repeated`:

  If `preprocess_collapse_repeated` is True, then a preprocessing step runs
  before loss calculation, wherein repeated labels passed to the loss
  are merged into single labels.  This is useful if the training labels come
  from, e.g., forced alignments and therefore have unnecessary repetitions.

  If `ctc_merge_repeated` is set False, then deep within the CTC calculation,
  repeated non-blank labels will not be merged and are interpreted
  as individual labels.  This is a simplified (non-standard) version of CTC.

  Here is a table of the (roughly) expected first order behavior:

  * `preprocess_collapse_repeated=False`, `ctc_merge_repeated=True`

    Classical CTC behavior: Outputs true repeated classes with blanks in
    between, and can also output repeated classes with no blanks in
    between that need to be collapsed by the decoder.

  * `preprocess_collapse_repeated=True`, `ctc_merge_repeated=False`

    Never learns to output repeated classes, as they are collapsed
    in the input labels before training.

  * `preprocess_collapse_repeated=False`, `ctc_merge_repeated=False`

    Outputs repeated classes with blanks in between, but generally does not
    require the decoder to collapse/merge repeated classes.

  * `preprocess_collapse_repeated=True`, `ctc_merge_repeated=True`

    Untested.  Very likely will not learn to output repeated classes.

  The `ignore_longer_outputs_than_inputs` option allows to specify the behavior
  of the CTCLoss when dealing with sequences that have longer outputs than
  inputs. If true, the CTCLoss will simply return zero gradient for those
  items, otherwise an InvalidArgument error is returned, stopping training.

  Args:
    labels: An `int32` `SparseTensor`.
      `labels.indices[i, :] == [b, t]` means `labels.values[i]` stores the id
        for (batch b, time t). `labels.values[i]` must take on values in `[0,
        num_labels)`. See `core/ops/ctc_ops.cc` for more details.
    inputs: 3-D `float` `Tensor`.
      If time_major == False, this will be a `Tensor` shaped: `[batch_size,
        max_time, num_classes]`.
      If time_major == True (default), this will be a `Tensor` shaped:
        `[max_time, batch_size, num_classes]`. The logits.
    sequence_length: 1-D `int32` vector, size `[batch_size]`. The sequence
      lengths.
    preprocess_collapse_repeated: Boolean.  Default: False. If True, repeated
      labels are collapsed prior to the CTC calculation.
    ctc_merge_repeated: Boolean.  Default: True.
    ignore_longer_outputs_than_inputs: Boolean. Default: False. If True,
      sequences with longer outputs than inputs will be ignored.
    time_major: The shape format of the `inputs` Tensors. If True, these
      `Tensors` must be shaped `[max_time, batch_size, num_classes]`. If False,
      these `Tensors` must be shaped `[batch_size, max_time, num_classes]`.
      Using `time_major = True` (default) is a bit more efficient because it
      avoids transposes at the beginning of the ctc_loss calculation.  However,
      most TensorFlow data is batch-major, so by this function also accepts
      inputs in batch-major form.
    logits: Alias for inputs.

  Returns:
    A 1-D `float` `Tensor`, size `[batch]`, containing the negative log
      probabilities.

  Raises:
    TypeError: if labels is not a `SparseTensor`.

  References:
      Connectionist Temporal Classification - Labeling Unsegmented Sequence Data
      with Recurrent Neural Networks:
        [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891)
        ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf))
  F)	use_cudnn)_ctc_loss_impl)labelsinputssequence_lengthpreprocess_collapse_repeatedctc_merge_repeated!ignore_longer_outputs_than_inputs
time_majorlogitss           r'   ctc_lossr@   G   s-    b 
"'	
 	r)   c	           	         t        | t        j                        s$t        d|  dt	        |       j
                         t        j                  d|d|      }t        j                  |d      }|st        j                  |g d      }|j                  }	|	t        j                  t        j                  fv r$t!        j"                  |t        j$                        }|rt&        j(                  }
nt&        j*                  }
 |
|| j,                  | j.                  ||||      \  }}|	t        j                  t        j                  fv rt!        j"                  ||	      }|S )NzAExpected argument `labels` to be a SparseTensor. Received labels=z
 of type: r?   r9   name   r      )r;   r<   r=   )
isinstancer
   SparseTensor	TypeErrortype__name__r   deprecated_argument_lookupr	   convert_to_tensorr   	transposedtyper   float16bfloat16r   castfloat32r   ctc_loss_v2r@   indicesvalues)r8   r9   r:   r;   r<   r=   r>   r?   r6   
orig_dtypectc_loss_funcloss_s                r'   r7   r7      s+    
FM66	7
 ''-hjF|,,-/ 0 0
 11(FH28:&   h7&	  3F||*FNNFOO44]]66>>2F ++M((Mnnmm#?+(IK'$ FNNFOO44==z*D	+r)   c                 j    t        j                  | j                  d   d      }t        ||      d d d gS )NrE   zCurrently there is no way to take the second  derivative of ctc_loss due to the fused implementation's interaction  with tf.gradients())message)r   prevent_gradientoutputsr   )op	grad_lossrZ   grad_without_gradients       r'   _CTCLossGradImplrb      s>     $44jjm 	#8
94t	LLr)   CTCLossc                     t        | ||      S )zThe derivative provided by CTC Loss.

  Args:
     op: the CTCLoss op.
     grad_loss: The backprop for cost.

  Returns:
     The CTC Loss gradient.
  rb   r_   r`   rZ   s      r'   _CTCLossGradrg          
"i	++r)   	CTCLossV2c                     t        | ||      S )zThe derivative provided by CTC Loss V2.

  Args:
     op: the CTCLossV2 op.
     grad_loss: The backprop for cost.

  Returns:
     The CTC Loss V2 gradient.
  re   rf   s      r'   _CTCLossV2Gradrk     rh   r)   znn.ctc_greedy_decoderc                 v    t        j                  | |||      }|\  }}}}t        j                  |||      g|fS )a	  Performs greedy decoding on the logits given in input (best path).

  Given a tensor as `inputs`, the `blank_index` parameter defines the class
  index of the blank symbol.

  For example:

  If `blank_index` is equal to 1:

  >>> inf = float("inf")
  >>> logits = tf.constant([[[   0., -inf, -inf],
  ...                        [ -2.3, -inf, -0.1]],
  ...                       [[ -inf, -0.5, -inf],
  ...                        [ -inf, -inf, -0.1]],
  ...                       [[ -inf, -inf, -inf],
  ...                        [ -0.1, -inf, -2.3]]])
  >>> seq_lens = tf.constant([2, 3])
  >>> outputs = tf.nn.ctc_greedy_decoder(
  ...     logits,
  ...     seq_lens,
  ...     blank_index=1)

  Notes:

  - Unlike `ctc_beam_search_decoder`, `ctc_greedy_decoder` considers blanks
    as regular elements when computing the probability of a sequence.
  - Default `blank_index` is `(num_classes - 1)`, unless overriden.

  If `merge_repeated` is `True`, merge repeated classes in output.
  This means that if consecutive logits' maximum indices are the same,
  only the first of these is emitted.  The sequence `A B B * B * B` (where '*'
  is the blank label) becomes

    * `A B B B` if `merge_repeated=True`.
    * `A B B B B` if `merge_repeated=False`.

  Args:
    inputs: 3-D `float` `Tensor` sized `[max_time, batch_size, num_classes]`.
      The logits.
    sequence_length: 1-D `int32` vector containing sequence lengths, having size
      `[batch_size]`.
    merge_repeated: Boolean.  Default: True.
    blank_index: (Optional). Default: `num_classes - 1`. Define the class index
      to use for the blank label. Negative values will start from num_classes,
      ie, -1 will reproduce the ctc_greedy_decoder behavior of using
      num_classes - 1 for the blank symbol, which corresponds to the default.

  Returns:
    A tuple `(decoded, neg_sum_logits)` where

    decoded: A single-element list. `decoded[0]`
      is an `SparseTensor` containing the decoded outputs s.t.:

      `decoded.indices`: Indices matrix `(total_decoded_outputs, 2)`.
        The rows store: `[batch, time]`.

      `decoded.values`: Values vector, size `(total_decoded_outputs)`.
        The vector stores the decoded classes.

      `decoded.dense_shape`: Shape vector, size `(2)`.
        The shape values are: `[batch_size, max_decoded_length]`

    neg_sum_logits: A `float` matrix `(batch_size x 1)` containing, for the
        sequence found, the negative of the sum of the greatest logit at each
        timeframe.
  )merge_repeatedblank_index)r   ctc_greedy_decoderr
   rH   )	r9   r:   rm   rn   r^   
decoded_ixdecoded_valdecoded_shapelog_probabilitiess	            r'   ro   ro   )  s]    R **#	'
 AH=:{M+<%%j+&35 67H
J Jr)   znn.ctc_beam_search_decoderc           
          t        j                  | ||||      \  }}}}t        |||      D 	
cg c]  \  }	}
}t        j                  |	|
|       c}}
}	|fS c c}}
}	w )aY  Performs beam search decoding on the logits given in input.

  **Note** Although in general greedy search is a special case of beam-search
  with `top_paths=1` and `beam_width=1`, `ctc_beam_search_decoder` differs
  from `ctc_greedy_decoder` in the treatment of blanks when computing the
  probability of a sequence:
    - `ctc_beam_search_decoder` treats blanks as sequence termination
    - `ctc_greedy_decoder` treats blanks as regular elements

  If `merge_repeated` is `True`, merge repeated classes in the output beams.
  This means that if consecutive entries in a beam are the same,
  only the first of these is emitted.  That is, when the sequence is
  `A B B * B * B` (where '*' is the blank label), the return value is:

    * `A B` if `merge_repeated = True`.
    * `A B B B` if `merge_repeated = False`.

  Args:
    inputs: 3-D `float` `Tensor`, size `[max_time x batch_size x num_classes]`.
      The logits.
    sequence_length: 1-D `int32` vector containing sequence lengths, having size
      `[batch_size]`.
    beam_width: An int scalar >= 0 (beam search beam width).
    top_paths: An int scalar >= 0, <= beam_width (controls output size).
    merge_repeated: Boolean.  Default: True.

  Returns:
    A tuple `(decoded, log_probabilities)` where

    decoded: A list of length top_paths, where `decoded[j]`
      is a `SparseTensor` containing the decoded outputs:

      `decoded[j].indices`: Indices matrix `(total_decoded_outputs[j] x 2)`
        The rows store: [batch, time].

      `decoded[j].values`: Values vector, size `(total_decoded_outputs[j])`.
        The vector stores the decoded classes for beam j.

      `decoded[j].dense_shape`: Shape vector, size `(2)`.
        The shape values are: `[batch_size, max_decoded_length[j]]`.

    log_probability: A `float` matrix `(batch_size x top_paths)` containing
        sequence log-probabilities.
  )
beam_width	top_pathsrm   )r   ctc_beam_search_decoderzipr
   rH   )r9   r:   ru   rv   rm   decoded_ixsdecoded_valsdecoded_shapesrs   ixvalshapes               r'   rw   rw   |  s    j ))

') ?+|^-> "+|^L 
2sE   S%0 
  s   "Aznn.ctc_beam_search_decoder_v2c                 "    t        | |||d      S )a  Performs beam search decoding on the logits given in input.

  **Note** Although in general greedy search is a special case of beam-search
  with `top_paths=1` and `beam_width=1`, `ctc_beam_search_decoder` differs
  from `ctc_greedy_decoder` in the treatment of blanks when computing the
  probability of a sequence:
    - `ctc_beam_search_decoder` treats blanks as sequence termination
    - `ctc_greedy_decoder` treats blanks as regular elements

  Args:
    inputs: 3-D `float` `Tensor`, size `[max_time, batch_size, num_classes]`.
      The logits.
    sequence_length: 1-D `int32` vector containing sequence lengths, having size
      `[batch_size]`.
    beam_width: An int scalar >= 0 (beam search beam width).
    top_paths: An int scalar >= 0, <= beam_width (controls output size).

  Returns:
    A tuple `(decoded, log_probabilities)` where

    decoded: A list of length top_paths, where `decoded[j]`
      is a `SparseTensor` containing the decoded outputs:

      `decoded[j].indices`: Indices matrix `[total_decoded_outputs[j], 2]`;
        The rows store: `[batch, time]`.

      `decoded[j].values`: Values vector, size `[total_decoded_outputs[j]]`.
        The vector stores the decoded classes for beam `j`.

      `decoded[j].dense_shape`: Shape vector, size `(2)`.
        The shape values are: `[batch_size, max_decoded_length[j]]`.

    log_probability: A `float` matrix `[batch_size, top_paths]` containing
        sequence log-probabilities.
  F)r:   ru   rv   rm   )rw   )r9   r:   ru   rv   s       r'   ctc_beam_search_decoder_v2r     s!    X 
!%
 r)   CTCGreedyDecoderCTCBeamSearchDecoderc                    t        j                  d      5  t        j                  | d      } t        | d      }t        | d      }|dz   }d|z  }t	        j
                  |      }||z   }ddgg}t        j                  |dd |dd gd      }t        j                  ||gd      }	t        j                  |||	gd      }
t        j                  t        |
d      g      }t        j                  |
|||g	      }|t        j                  |      z  }t        j                  |dd       }t        j                  ||dd |dd gd      }
t        j                  t        j                   |
d      |ddg      }
t        j                   t	        j
                  |      d      g d
z  }|
t        j                   |d      z  }
t	        j"                  | ddddf   | ddddf         }dt	        j$                  |t&        j(                        z
  }|||g}t        j                  |
||      }t        j                   |d      |z   cddd       S # 1 sw Y   yxY w)a   Computes CTC alignment model transition matrix.

  Args:
    label_seq: tensor of shape [batch_size, max_seq_length]

  Returns:
    tensor of shape [batch_size, states, states] with a state transition matrix
    computed for each sequence of the batch.
  ctc_state_trans	label_seqrB   r   rE   rF   N)r~   )rE   r   r         ?)r	   
name_scoperM   _get_dimr   ranger   stackr   concatones
scatter_ndr   eye
zeros_liketileexpand_dimsequalrR   r   rS   )r   
batch_size
num_labelsnum_label_states
num_stateslabel_statesblank_statesstart_to_labelblank_to_labellabel_to_blankrU   rV   trans	batch_idxrepeatsbatched_shapelabel_to_labels                    r'   _ctc_state_transr     sL    ~~'( +<%%ikBI)Q'J)Q'J!A~%%J>>"23L"22L !fXN %**	ab	<,-q2N %**L,+GKN O "G^^Xgq123F  
J79E	Z^^J''E $$\!"%56I##	L$l1R&891>Gnngq)J1+=?G%%hnnZ&@!DyPIy$$Y22GnnYq#2#v.	!QR%0@AG8==&..99FZ8M))'6=IN  *^;W+< +< +<s   H(IIc                 >   t        | d      }|dz   }d}||z  }t        j                  t        j                  t        j                  dt        j
                        dz         t        j                        }t        j                  t        j                  |gt        j                        |d|d      }t        j                  | |d      }t        j                  |d|g      }	|	|z  }
d	|
z
  |z  }t        j                  |||g      }|t        j                  |      fS )
a  Computes CTC alignment initial and final state log probabilities.

  Create the initial/final state values directly as log values to avoid
  having to take a float64 log on tpu (which does not exist).

  Args:
    seq_lengths: int tensor of shape [batch_size], seq lengths in the batch.
    max_seq_length: int, max sequence length possible.

  Returns:
    initial_state_log_probs, final_state_log_probs
  r   rE   rF   g@,1 rO           )rU   depthon_value	off_valueaxis)r   r   r   )r   r   rR   logr   float64rS   r   one_hotzerosint32r   reshaperN   )seq_lengthsmax_seq_lengthr   r   num_duration_statesr   log_0initial_state_log_probslabel_final_state_maskduration_final_state_maskfinal_state_maskfinal_state_log_probss               r'   ctc_state_log_probsr   /  s    Q'*#a'"%55*
--ll8==FNN3f<=v~~O% &--oozl&,,? %,,)3'nnAz*,.1GG!11U:#++,A-7,DF 
!)"5"56K"L	LLr)   c                    t        | d      }|ddddddf   }t        j                  |dd|dz   g      }t        j                  | |      }t        j                  |d      }t        j                  |d      }t        j                  ||z  d      }t        j                  ||gd      }t        j                  |ddgddgddggt        j                  d      	      S )
z,Project ilabel log probs to state log probs.rE   N)r   r   r   rF      r   )constant_values)
r   r   r   r   r   r   
reduce_sumr   padr   )r8   r   ilabel_log_probsr   blankr   state_log_probss          r'   _ilabel_to_stater   W  s     fa(
1a!8
$%
..A'7!'; <
=%fJ7'!!'2'**+;!D''(87(BK/$$ou%=AF/	AAA/ll3'
) )r)   c                    t        | d      dz   }|ddddd|f   }|dddd|df   }t        j                  | dz
  |dz
  dt        j                  d            }t        j
                  |d      }t        j
                  |d      }t        j                  ||z   d      }t        j                  |dd	
      }t        j                  ||gd      S )z(Sum state log probs to ilabel log probs.rE   Nr   )r   r   r   r   r   r   rF   Tr   keepdimsr   )r   r   r   r   r   r   reduce_logsumexpr   )	r8   r   statesr   r   r   r   label_olabelsblank_olabelss	            r'   _state_to_olabelr   g  s     fa(1,1a 0001,1.//0,qj!^S!	#'
 !!'2'&&|!<,++L7,BK-++Lq4P-			=-8r	BBr)   c           
      :   t        | d      dz   }|ddddd|f   }|dddd|df   }|\  }}t        ||      }	t        |d      }
t        |d      }|dz
  }t        j                  |	g d      }t        j                  |||z  |
g      }t        j                  ||j                        |z  }|t        j                  |d      z   }t        j                  |ddg      }t        j                  ||||z  |
g	      }t        j                  ||||
g      }t        j                  |t        j                        }t        j                  ||||z  |
g	      }t        j                  ||||
g      }t        j                  ||t        j                  t        j                  |      t        j                   d
                  }t        j                  |g d      }|ddddddf   }t        j"                  |dd      }t        j$                  ||gd      S )zCSum state log probs to ilabel log probs using unique label indices.rE   Nr   )rE   rF   r   permr   r   r   rU   updatesr~   r   )rF   r   rE   rF   Tr   )r   _sum_statesr   rN   r   r   r   rO   r   r   	ones_liker   boolwherefillr~   r   r   r   )r8   r   r   uniquer   r   r   unique_y
unique_idx
mul_reduce
num_framesr   r   batch_state_majorbatch_offsetrU   scattermaskr   r   s                       r'   _state_to_olabel_uniquer   z  s    fa(1,1a 0001,1.//0,(J:|4*"*"*!#*))*9E''(9)3j)@*(MO
(..AJN,y,,\CC'gAw/'  *$j13' g
J
'KL'			.fkk	B$			*$j1
3$ 
		4*j*!E	F$OO
GnnY__W-x||C/@AC' %%gy9-1ab)-++Lq4P-			=-8r	BBr)   c                 b   t        | d      }t        |d      }t        j                  |       }t        |||      }t	        |      }	t        ||      \  }
}t        t        j                  |	      |
|||      \  }}|rt        ||||      }nt        |||      }t        j                  |      t        j                  |      z
  }t        | d      }t        j                  ||t        j                        }t        j                   |ddg      }t        j"                  |d      }||z  }| }||fS )a  Computes the CTC loss and gradients.

  Most users will want fwd_bwd.ctc_loss

  This function returns the computed gradient, it does not have a gradient
  of its own defined.

  Args:
    logits: tensor of shape [frames, batch_size, num_labels]
    labels: tensor of shape [batch_size, max_label_seq_length]
    label_length: tensor of shape [batch_size] Length of reference label
      sequence in labels.
    logit_length: tensor of shape [batch_size] Length of input sequence in
      logits.
    unique: (optional) unique label indices as computed by unique(labels) If
      supplied, enables an implementation that is faster and more memory
      efficient on TPU.

  Returns:
    loss: tensor of shape [batch_size]
    gradient: tensor of shape [frames, batch_size, num_labels]
  rF   rE   )state_trans_log_probsr   r   observed_log_probsr:   r   r   r   )r   r   log_softmaxr   r   r   _forward_backward_logr   r   r   r   expr   sequence_maskr   rS   rN   r   )r?   r8   label_lengthlogit_lengthr   r   max_label_seq_lengthr   r   state_trans_probsr   r   fwd_bwd_log_probslog_likelihoodolabel_log_probsgradmax_logit_length
logit_maskrY   s                      r'   ctc_loss_and_gradr     s@   0 "*!&!,''/$VZ9IJ/&v.3F(4*00&;$LL):;51("'$#^ .vz/@&J (
<MN	&	'(,,7G*H	H$
 fa(&&|5E'-~~7*"":QF;*$$Za8**$
$	tr)   c                     | j                   d   }t        j                  |g d      |z  g}|d gt        | j                        t        |      z
  z  z  }|S )NrE   rE   r   rE   )r^   r   r   lenr9   )r_   r`   rZ   r   s       r'   _ctc_loss_gradr     sP    	A$


Iz
2T
9	:$4&C		NSY.
//$	+r)   c           	      ~   |d d d d d |f   }|d d d d |dz   d f   }|d d d d ||dz   f   }t        j                  |||gd      }t        j                  | j                  t        j
                  | j                  |k  | j                  | j                  dz
        | j                        } t        | |||d      S )NrE   rF   r   Fr8   r9   r:   r>   r6   	r   r   r
   rH   rU   r   rV   dense_shaper7   r8   r?   r   logits_time_majorrn   part_before
part_after
part_blanks           r'   _ctc_loss_op_standardr     s    q!\k\)*+aK!O,,-*aKa778*[*jAJ&%%nnoofmmk16==mma')*0*<*<>& 
""
 r)   c                 ~   |d d d d d |f   }|d d d d |dz   d f   }|d d d d ||dz   f   }t        j                  |||gd      }t        j                  | j                  t        j
                  | j                  |k  | j                  dz   | j                        | j                        } t        | |||d      S )NrE   rF   r   Tr   r   r   s           r'   _ctc_loss_op_cudnnr    s    q!\k\)*+aK!O,,-*aKa778*ZjAJ&%%nnoofmmk16==13Dmm%&,&8&8:& 
""
 r)   c                 v    | j                   d   j                         | j                   d   j                         gS )NrF   r   )r9   	get_shape)r_   s    r'   _ctc_loss_shaper    s/    
))A,
 
 
"BIIaL$:$:$<	==r)   znn.ctc_loss_v2c           
      8   t        | t        j                        r|t        d      |dk  r|t	        |d      z  }|t	        |d      dz
  k7  rt        j                  |ddddd|f   |dddd|dz   df   |dddd||dz   f   gd      }t        j                  | j                  t        j                  | j                  |k  | j                  | j                  dz
        | j                        } t        | |||      S |d}t        | |||||||      S )	a  Computes CTC (Connectionist Temporal Classification) loss.

  This op implements the CTC loss as presented in (Graves et al., 2006).

  Notes:

  - Same as the "Classic CTC" in TensorFlow 1.x's tf.compat.v1.nn.ctc_loss
    setting of preprocess_collapse_repeated=False, ctc_merge_repeated=True
  - Labels may be supplied as either a dense, zero-padded tensor with a
    vector of label sequence lengths OR as a SparseTensor.
  - On TPU and GPU: Only dense padded labels are supported.
  - On CPU: Caller may use SparseTensor or dense padded labels but calling with
    a SparseTensor will be significantly faster.
  - Default blank label is 0 rather num_classes - 1, unless overridden by
    blank_index.

  Args:
    labels: tensor of shape [batch_size, max_label_seq_length] or SparseTensor
    logits: tensor of shape [frames, batch_size, num_labels], if
      logits_time_major == False, shape is [batch_size, frames, num_labels].
    label_length: tensor of shape [batch_size], None if labels is SparseTensor
      Length of reference label sequence in labels.
    logit_length: tensor of shape [batch_size] Length of input sequence in
      logits.
    logits_time_major: (optional) If True (default), logits is shaped [time,
      batch, logits]. If False, shape is [batch, time, logits]
    unique: (optional) Unique label indices as computed by
      ctc_unique_labels(labels).  If supplied, enable a faster, memory efficient
      implementation on TPU.
    blank_index: (optional) Set the class index to use for the blank label.
      Negative values will start from num_classes, ie, -1 will reproduce the
      ctc_loss behavior of using num_classes - 1 for the blank symbol. There is
      some memory/performance overhead to switching from the default of 0 as an
      additional shifted copy of the logits may be created.
    name: A name for this `Op`. Defaults to "ctc_loss_dense".

  Returns:
    loss: tensor of shape [batch_size], negative log probabilities.

  References:
      Connectionist Temporal Classification - Labeling Unsegmented Sequence Data
      with Recurrent Neural Networks:
        [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891)
        ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf))
  NzFArgument `blank_index` must be provided when labels is a SparseTensor.r   rF   rE   r   )r8   r9   r:   r>   r8   r?   r   r   r   r   rn   rC   )rG   r
   rH   
ValueErrorr   r   r   rU   r   rV   r   r@   ctc_loss_denser  s           r'   rT   rT     sO   n 223  QXfa((khvq)A--
A||#
$
A{Q''
(
A{;?22
3!
 &'(f ))
..
//&--+5v}} --!+-.4.@.@Bf
 $$	& & K	)
 r)   c           
         t        | t        j                        r(|t        d      |dk  r|t	        |d      z  }t        j                  |d      }| ||||d}t        j                         rNt               }	|	t        k(  xs |	du xr t        j                         dkD  }
|
rt        d
i |}|S t        d
i |}|S dt        t        j                                z   }t#        |t$        t              }t#        |t        t              } |d
i |} |j&                  d
i |}|j)                          |j+                          |S |d}t-        | |||||||	      S )a  Computes CTC (Connectionist Temporal Classification) loss.

  This op implements the CTC loss as presented in
  [Graves et al., 2006](https://www.cs.toronto.edu/~graves/icml_2006.pdf)

  Connectionist temporal classification (CTC) is a type of neural network output
  and associated scoring function, for training recurrent neural networks (RNNs)
  such as LSTM networks to tackle sequence problems where the timing is
  variable. It can be used for tasks like on-line handwriting recognition or
  recognizing phones in speech audio. CTC refers to the outputs and scoring, and
  is independent of the underlying neural network structure.

  Notes:

  - This class performs the softmax operation for you, so `logits` should be
    e.g. linear projections of outputs by an LSTM.
  - Outputs true repeated classes with blanks in between, and can also output
    repeated classes with no blanks in between that need to be collapsed by the
    decoder.
  - `labels` may be supplied as either a dense, zero-padded `Tensor` with a
    vector of label sequence lengths OR as a `SparseTensor`.
  - On TPU: Only dense padded `labels` are supported.
  - On CPU and GPU: Caller may use `SparseTensor` or dense padded `labels`
    but calling with a `SparseTensor` will be significantly faster.
  - Default blank label is `0` instead of `num_labels - 1` (where `num_labels`
    is the innermost dimension size of `logits`), unless overridden by
    `blank_index`.

  >>> tf.random.set_seed(50)
  >>> batch_size = 8
  >>> num_labels = 6
  >>> max_label_length = 5
  >>> num_frames = 12
  >>> labels = tf.random.uniform([batch_size, max_label_length],
  ...                            minval=1, maxval=num_labels, dtype=tf.int64)
  >>> logits = tf.random.uniform([num_frames, batch_size, num_labels])
  >>> label_length = tf.random.uniform([batch_size], minval=2,
  ...                                  maxval=max_label_length, dtype=tf.int64)
  >>> label_mask = tf.sequence_mask(label_length, maxlen=max_label_length,
  ...                               dtype=label_length.dtype)
  >>> labels *= label_mask
  >>> logit_length = [num_frames] * batch_size
  >>> with tf.GradientTape() as t:
  ...   t.watch(logits)
  ...   ref_loss = tf.nn.ctc_loss(
  ...       labels=labels,
  ...       logits=logits,
  ...       label_length=label_length,
  ...       logit_length=logit_length,
  ...       blank_index=0)
  >>> ref_grad = t.gradient(ref_loss, logits)

  Args:
    labels: `Tensor` of shape `[batch_size, max_label_seq_length]` or
      `SparseTensor`.
    logits: `Tensor` of shape `[frames, batch_size, num_labels]`. If
      `logits_time_major == False`, shape is `[batch_size, frames, num_labels]`.
    label_length: `Tensor` of shape `[batch_size]`. None, if `labels` is a
      `SparseTensor`. Length of reference label sequence in `labels`.
    logit_length: `Tensor` of shape `[batch_size]`. Length of input sequence in
      `logits`.
    logits_time_major: (optional) If True (default), `logits` is shaped [frames,
      batch_size, num_labels]. If False, shape is
      `[batch_size, frames, num_labels]`.
    unique: (optional) Unique label indices as computed by
      `ctc_unique_labels(labels)`.  If supplied, enable a faster, memory
      efficient implementation on TPU.
    blank_index: (optional) Set the class index to use for the blank label.
      Negative values will start from `num_labels`, ie, `-1` will reproduce the
      ctc_loss behavior of using `num_labels - 1` for the blank symbol. There is
      some memory/performance overhead to switching from the default of 0 as an
      additional shifted copy of `logits` may be created.
    name: A name for this `Op`. Defaults to "ctc_loss_dense".

  Returns:
    loss: A 1-D `float Tensor` of shape `[batch_size]`, containing negative log
    probabilities.

  Raises:
    ValueError: Argument `blank_index` must be provided when `labels` is a
    `SparseTensor`.

  References:
      Connectionist Temporal Classification - Labeling Unsegmented Sequence Data
      with Recurrent Neural Networks:
        [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891)
        ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf))

      https://en.wikipedia.org/wiki/Connectionist_temporal_classification
  NzJArgument `blank_index` must be provided when `labels` is a `SparseTensor`.r   rF   r?   rB   )r8   r?   r   r   rn   	ctc_loss_r   )rG   r
   rH   r  r   r	   rM   r   executing_eagerlyr(   _GPU_DEVICE_NAMEnum_gpusr  r   struuiduuid4r3   _CPU_DEVICE_NAMEget_concrete_functionadd_to_graphadd_gradient_functions_to_graphr  )r8   r?   r   r   r   r   rn   rC   paramsr%   can_use_gpuresapi_namectc_loss_op_standardctc_loss_op_cudnnconcrete_funcs                   r'   ctc_loss_v3r  s  s   H 223  QXfa((k""69F $."F   ",.k ** <4:G$4$4$6$: 
 
 *6* J $-f- J s4::<00h4X?O5JL1(<L2DF *6*c='==GGm  "335JK	)
 r)   c           
          t        j                  |d g      5  t        j                  d      t        j                   d       t        j                  d      t        j                  d      j                  }|t        j
                  t        j                  fv r$t        j                  t        j                        |st        j                  g d      |d	k7  ru|d	k  r|t        d
      z  }t        j                  dddd||dz   f   ddddd|f   dddd|dz   df   gd
      t        j                   |k   dz            g|r|\  }	}
|d	k7  rt        j                  |	|k  |	dz   |	      }	t        j                  |
d      dz   }t        |	d      }t        j                   ||      }t        j                  ||	t        j"                  |	            }	j%                  |	|
g       t&        j&                   fd       } | }|t        j
                  t        j                  fv rt        j                  ||      }|cddd       S # 1 sw Y   yxY w)a  Computes CTC (Connectionist Temporal Classification) loss.

  This op implements the CTC loss as presented in (Graves et al., 2006),
  using the batched forward backward algorithm described in (Sim et al., 2017).

  Notes:
    Significant differences from `tf.compat.v1.nn.ctc_loss`:
      Supports GPU and TPU (`tf.compat.v1.nn.ctc_loss` supports CPU only):
        For batched operations, GPU and TPU are significantly faster than using
        `ctc_loss` on CPU.
        This implementation runs on CPU, but significantly slower than ctc_loss.
      Blank label is 0 rather num_classes - 1, unless overridden by blank_index.
      Logits and labels are dense arrays with padding rather than SparseTensor.
      The only mode supported is the same as:
        preprocess_collapse_repeated=False, ctc_merge_repeated=True
        To collapse labels, the caller can preprocess label sequence first.

    The dense implementation supports both CPU, GPU and TPU. A fast path is
    provided that significantly improves memory use for large vocabulary if the
    caller preprocesses label sequences to get unique label indices on the CPU
    (eg. in the data input pipeline) using ctc_ops.unique and simplifies this in
    the optional "unique" kwarg. This is especially useful for TPU and GPU but
    also works with if used on CPU.

  Args:
    labels: tensor of shape [batch_size, max_label_seq_length]
    logits: tensor of shape [frames, batch_size, num_labels], if
      logits_time_major == False, shape is [batch_size, frames, num_labels].
    label_length: tensor of shape [batch_size] Length of reference label
      sequence in labels.
    logit_length: tensor of shape [batch_size] Length of input sequence in
      logits.
    logits_time_major: (optional) If True (default), logits is shaped [time,
      batch, logits]. If False, shape is [batch, time, logits]
    unique: (optional) Unique label indices as computed by unique(labels). If
      supplied, enable a faster, memory efficient implementation on TPU.
    blank_index: (optional) Set the class index to use for the blank label.
      Negative values will start from num_classes, ie, -1 will reproduce the
      ctc_loss behavior of using num_classes - 1 for the blank symbol. There is
      some memory/performance overhead to switching from the default of 0 as an
      additional shifted copy of the logits may be created.
    name: A name for this `Op`. Defaults to "ctc_loss_dense".

  Returns:
    loss: tensor of shape [batch_size], negative log probabilities.

  References:
      Connectionist Temporal Classification - Labeling Unsegmented Sequence Data
      with Recurrent Neural Networks:
        [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891)
        ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf))
      Improving the efficiency of forward-backward algorithm using batched
      computation in TensorFlow:
        [Sim et al., 2017](https://ieeexplore.ieee.org/document/8268944)
        ([pdf](http://bacchiani.net/resume/papers/ASRU2017.pdf))
  r  r?   rB   r8   r   r   rD   r   r   rF   NrE   r   c                 :   | j                  j                         |j                  
j                         |j                  	j                         |j                  j                         t        | |||      }|r||d<   t        di |fd}d   |fS )zCompute CTC loss.)r?   r8   r   r   r   c                     t        j                  | g d      d   z  g}|d gt              t        |      z
  z  z  }|S )Nr   rE   )r   r   r   )r`   r   argsresults     r'   r   z6ctc_loss_dense.<locals>.compute_ctc_loss.<locals>.grad  sD    !!)Z86!9DE#d)c$i/00r)   r   r  )	set_shaper~   dictr   )logits_tlabels_tlabel_length_tlogit_length_tunique_tkwargsr   r"  r!  r   r8   r   r?   s          @r'   compute_ctc_lossz(ctc_loss_dense.<locals>.compute_ctc_lossw  s     &&|112|112%%	'f
 
#x *6*f
 AY_r)   )r	   r   rM   rO   r   rP   rQ   r   rR   rS   r   rN   r   r   r   
reduce_maxr   r   extendr   )r8   r?   r   r   r   r   rn   rC   rW   r   r   label_mask_lenmax_label_length
label_maskr+  rY   r!  s   ````            @r'   r  r    s[   B ~~d,v|\BD A""69F""69F((NKL((NKLJfnnfoo66}}VV^^4f""6	:fa	qx**
A{;?22
3
A||#
$
A{Q''
(!
 &'(f v3VaZHfFL,7D#h
		??8k#98a<#+-!,,Za@1D#Ha0,,^=MN
??:x#,#7#7#AC
kk8Z()$$ %, T"Dfnnfoo66]]4,dCA A As   II11I:znn.collapse_repeatedc                    t        j                  |d| |g      5  t        j                  | d      } t        j                  |d      }t        j                  t        j
                  | ddddf   t        j                        t        j                  | ddddf   | ddddf         gd      }t        | d      }t        j                  ||	      }t        j                  ||      }t        j                  t        j                  |t        j                        d      }t        j                   |      }t        j                  ||	      }t        j"                  | dg      }	t        j"                  |dg      }
t        j"                  |dg      }t        j$                  t        |d
            }t        j&                  t        j(                  t        j*                  ||      d      t        j*                  |	|
      t        j,                  |            }t        | d
      }||g}t        j"                  ||      t        j                  ||j.                        fcddd       S # 1 sw Y   yxY w)al  Merge repeated labels into single labels.

  Args:
    labels: Tensor of shape [batch, max value in seq_length]
    seq_length: Tensor of shape [batch], sequence length of each batch element.
    name: A name for this `Op`. Defaults to "collapse_repeated_labels".

  Returns:
    A tuple `(collapsed_labels, new_seq_length)` where

    collapsed_labels: Tensor of shape [batch, max_seq_length] with repeated
    labels collapsed and padded to max_seq_length, eg:
    `[[A, A, B, B, A], [A, B, C, D, E]] => [[A, B, A, 0, 0], [A, B, C, D, E]]`

    new_seq_length: int tensor of shape [batch] with new sequence lengths.
  collapse_repeated_labelsr8   rB   
seq_lengthNrE   r   r   maxlenr   r   )r	   r   rM   r   r   r   r   r   r   	not_equalr   r   logical_andr   rR   r   r,  r   r   r   r   boolean_maskr~   rO   )r8   r3  rC   r0  r5  seq_masknew_seq_len
new_maxlenidx_maskflat_labelsflat_label_maskflat_idx_maskidxflatr   	new_shapes                   r'   collapse_repeatedrC    s   ( ~~d68LM ):""69F&&zEJ !!F1bqb5M6;;76!QR%=&CRC.9# ()	*J fa F&&z&AH%%j(;J %%j&,,/a9K $$[1J&&{:FH ##FRD1K''
RD9O%%h5M
..-3
4C %%""36Q@&&{ODoom,	.D &!$JZ(IdI.MM+z'7'78:Q): ): ):s   II,,I5c           	         t        j                  | dg      }t        j                  t        j                  |t
        j                        d         }t        j                  |t        j                  |       d         }t        j                  |dg      }t        j                  t        j                  ||      d      }t        j                  ||      }t        j                  |t        j                  |t
        j                        t        j                  |t
        j                              }t        j                  |t        j                  |             }	t        j                   |      }
t        j                  |	j"                  |	j$                  t        j                  |	j&                  d   t
        j                        t        j                  |
t
        j                        g      S )a"  Convert dense labels with sequence lengths to sparse tensor.

  Args:
    dense: tensor of shape [batch, max_length]
    length: int tensor of shape [batch] The length of each sequence in dense.

  Returns:
    tf.sparse.SparseTensor with values only for the valid elements of sequences.
  r   )out_typer   rE   r4  )rU   rV   r   )r   r   r   r   r~   r   int64r   r   r8  r
   rH   rR   r   r   sparse_reshaper,  rU   rV   r   )denselengthflat_valuesflat_indicesr   	flat_maskrU   rV   sparsereshaped
max_lengths              r'   dense_labels_to_sparserP    sa    !!%".+ookFLL9!<>,		 	 	0Fq0I	J$rd+)!!\95q:'!!+y9&%%]]66<<0//+EG& &&vyu/EF(""6**		#	#__
--,,Q/
>
--
FLL
1
	 	r)   znn.ctc_unique_labelsc                     t        j                  |d| g      5  t        j                  | d      } d }t        j                  || t        j
                  t        j                  g      cddd       S # 1 sw Y   yxY w)a  Get unique labels and indices for batched labels for `tf.nn.ctc_loss`.

  For use with `tf.nn.ctc_loss` optional argument `unique`: This op can be
  used to preprocess labels in input pipeline to for better speed/memory use
  computing the ctc loss on TPU.

  Example:
    ctc_unique_labels([[3, 4, 4, 3]]) ->
      unique labels padded with 0: [[3, 4, 0, 0]]
      indices of original labels in unique: [0, 1, 1, 0]

  Args:
    labels: tensor of shape [batch_size, max_label_length] padded with 0.
    name: A name for this `Op`. Defaults to "ctc_unique_labels".

  Returns:
    tuple of
      - unique labels, tensor of shape `[batch_size, max_label_length]`
      - indices into unique labels, shape `[batch_size, max_label_length]`
  ctc_unique_labelsr8   rB   c           	      ,   t        j                  |       }t        j                  |j                  dt	        |j
                  d      t	        |j                  d      z
  gg      }t        j                  |t        j                        }||j
                  gS Nr   )
r   r   r   yr   r@  r   rR   r   rF  )xurU  s      r'   _uniquez"ctc_unique_labels.<locals>._unique  sk    


1
a
--q(155!"4xQ7G"GHI
Ja
--6<<
(aZr)   r   N)r	   r   rM   r   r   rF  r   )r8   rC   rX  s      r'   rR  rR    sf    0 ~~d/&: 	N""69F ==&v||0LM	N 	N 	Ns   AA33A<c           	      Z   t        j                  d      5  t        j                  | d      } t        |d      }t	        j
                  |d      }t	        j                  | |dt        j                  d      d      }t        j                  ||z   d	      cd
d
d
       S # 1 sw Y   y
xY w)a  Take logsumexp for each unique state out of all label states.

  Args:
    idx: tensor of shape [batch, label_length] For each sequence, indices into a
      set of unique labels as computed by calling unique.
    states: tensor of shape [frames, batch, label_length] Log probabilities for
      each label state.

  Returns:
    tensor of shape [frames, batch_size, label_length], log probabilities summed
      for each unique label of the sequence.
  
sum_statesr@  rB   rF   r   r   rE   )r   r   r   r   r   N)
r	   r   rM   r   r   r   r   r   r   r   )r@  r   r   r   s       r'   r   r     s     ~~l# 
@


%
0C&!$J""62F,,s#G $$Vg%5B?
@ 
@ 
@s   BB!!B*c                      j                   j                  dk(  rddg}nC j                   j                  dk(  rg d}n%t        d  d j                   j                         t        j                   |      t        |d      } fd}t        |||d	
      }fd}	t        j                  |g      }
t        |d      }t        j                  ||t        j                        }t        j                  |ddg      }t        |	||f|
fd	d	      \  }}|dd |dd z   }t        j                  |dd	      }||z  }|t        j                  t        j                  |d            z  }|ddddf   |d   z   }||fS )a  Forward-backward algorithm computed in log domain.

  Args:
    state_trans_log_probs: tensor of shape [states, states] or if different
      transition matrix per batch [batch_size, states, states]
    initial_state_log_probs: tensor of shape [batch_size, states]
    final_state_log_probs: tensor of shape [batch_size, states]
    observed_log_probs: tensor of shape [frames, batch_size, states]
    sequence_length: tensor of shape [batch_size]

  Returns:
    forward backward log probabilities: tensor of shape [frames, batch, states]
    log_likelihood: tensor of shape [batch_size]

  Raises:
    ValueError: If state_trans_log_probs has unknown or incorrect rank.
  rF   rE   r   r   )r   rF   rE   zkRank of argument `state_trans_log_probs` must be known and equal to 2 or 3. Received state_trans_log_probs=z	 of rank c                     t        j                  | d      } | z  } t        j                  | d      } | |z  } t        j                  | dd      }| |z  } | S )NrE   r   r   Tr   )r   r   r   r   )state_log_probobs_log_problog_prob_sumr   s      r'   _forwardz'_forward_backward_log.<locals>._forwardW  sc    **>BN++N..~BGNl"N,,R$0Ll"Nr)   T)	inclusivec                 T   | \  }}|\  }}||z  }t        j                  |d      }|	z  }t        j                  |d      }t        j                  |dd      }||z  }|t        j                  |dg      |z  z  }t        j                  |d      }||z  }|
d|z
  z  z  }||fS )zBCalculate log probs and cumulative sum masked for sequence length.rE   r   r   Tr   r   )r   r   r   r   squeeze)accselemsr]  cum_log_sumr^  r   r_  batched_maskoutbwd_state_trans_log_probsr   s            r'   	_backwardz(_forward_backward_log.<locals>._backwardd  s    "&NKL$l"N**>BN//N..~BGN,,R$0Ll"N9$$\=DDK((A6L
<
'C C,$677Cr)   r   )reversera  Nr   r   )r~   ndimsr  r   rN   r   _scanr   r   r   rS   r   r   r   r   )r   r   r   r   r:   r   r   r`  fwdrj  zero_log_sumr5  r   bwdrf  r   fwd_bwd_log_probs_sumr   ri  s   ` `               @r'   r   r   5  s   *   &&!+q6D""((A-D
	22G1H I%++112	45 5
 (112GN*A.* 	"$;t	M#& *.,&*&		 	 &&..	I$			TA	/$$d+l+	#{ !"gAB'"33a$0,,x||I$9$9$Q$GHHq!Qw<+a.0.	N	**r)   c                     t        j                        D cg c]  }t        j                  |       c}t	        j
                  d         d   }fdt        j                        D cg c]  }t        j                  |       }}fd|D cg c]  }|j                   }	}t        |      r$t        j                  t        j                  g|	z   }
n&t        j                  t        j                  g|	z   |	z   }
fd} fd}rt	        j
                  d         d   dz
  n$t        j                  dt        j                        }g }st	        j
                  d         d   rdndz   }|D ]  }t	        j                  |gt	        j
                  |      gd      }t        j                  ||j                  d	      }r!t        j                   ||rdndz   gg|g      }|j#                  |        ||g|z   |z   }t%        |      D cg c]=  \  }}|j                  j&                  t        j                  t        j(                  fv r|? }}}t+        j,                         r|} || rU || } || rnI t/        j0                  |
 |      } t/        j0                  |
 |      }t3        j4                  ||||
      }|ddz    } |      S c c}w c c}w c c}w c c}}w )ab  Repeatedly applies callable `fn` to a sequence of elements.

  Implemented by functional_ops.While, tpu friendly, no gradient.

  This is similar to functional_ops.scan but significantly faster on tpu/gpu
  for the forward backward use case.

  Examples:
    scan(lambda a, e: a + e, [1.0, 2.0, 3.0], 1.0) => [2.0, 4.0, 7.0]

    Multiple accumulators:
      scan(lambda a, e: (a[0] + e, a[1] * e), [1.0, 2.0, 3.0], (0.0, 1.0))

    Multiple inputs:
      scan(lambda a, e: a + (e[0] * e[1]), (elems1, elems2), 0.0)

  Args:
    fn: callable, fn(accumulators, element) return new accumulator values. The
      (possibly nested) sequence of accumulators is the same as `initial` and
      the return value must have the same structure.
    elems: A (possibly nested) tensor which will be unpacked along the first
      dimension. The resulting slices will be the second argument to fn. The
      first dimension of all nested input tensors must be the same.
    initial: A tensor or (possibly nested) sequence of tensors with initial
      values for the accumulators.
    reverse: (optional) True enables scan and output elems in reverse order.
    inclusive: (optional) True includes the initial accumulator values in the
      output. Length of output will be len(elem sequence) + 1. Not meaningful if
      final_only is True.
    final_only: (optional) When True, return only the final accumulated values,
      not the concatenation of accumulated values for each input.

  Returns:
    A (possibly nested) sequence of tensors with the results of applying fn
    to tensors unpacked from elems and previous accumulator values.
  r   c                 2    t        j                  |       S N)	structureflat_sequencer   pack_sequence_as)rV  re  s    r'   <lambda>z_scan.<locals>.<lambda>  s    ..aP r)   c                 2    t        j                  |       S rt  rw  )rV  initials    r'   ry  z_scan.<locals>.<lambda>  s    4((7!L r)   c                     ~r| dk\  S | |k  S rT  r  )i	num_elemsr!  rk  s      r'   condz_scan.<locals>.cond  s    16/!i-/r)   c           	         | j                  g        r|}n
|d |d }}D cg c]  }t        j                  ||        }}  |       |            }t        j                  |      }rg }nArs| dz   n| }	t        |      D 
cg c]  \  }
}t        j                  |
|	gg|g      ! }}
}r| dz
  n| dz   } | |g|z   |z   S c c}w c c}}
w )z
Loop body.NrE   )r#  r   gatherr   flattenrx   r   tensor_scatter_update)r}  r~  r!  accumrh  eslices
flat_accumnew_outupdate_irV  rU  
final_only
flat_elemsfnra  
num_accumspack
pack_elemsrk  s               r'   bodyz_scan.<locals>.body  s    KKOe$d:;&75c.89iq!$9F9tE{Jv./Ee$Jg#GQh #z*a 
-
-a8*s
Cg  Aa!eAy>G#j00 :s   C$CrE   r   T)rO   init)hostmemrF   )r   r  r	   rM   r   r~   rO   r   r   r   r   constantr   r   emptyr   tensor_scatter_addappend	enumerate
base_dtyperF  r   r  r   Defunr   While)r  re  r{  rk  ra  r  rV  r~  flat_initialaccum_dtypesloop_dtypesr  r  init_ir^   num_outputsinitial_accum	out_shaperh  loop_inr}  r  loop_resultsr  r  r  r  s   ``````                 @@@@r'   rm  rm    s   L 37,,u2EFQ%%a(F*oojm,Q/)P*48LL4IJq#''*J,J	L$#/0a!''0,0< * <<.=K<<.=LK01 1.  oojm$Q'#,,QfllC 	 '	//*Q-03Iq1MK% ""=)//-8
91>ii}/B/BNc	..6'Qq123m_
 nnS Y')L8'g&Aq	
		fll;	; ' 
  L

<(l 
 (8>>;'-D'8>>;'-D!''tWMLQzA~&#	cS G K0js   K-8K2K7(AK<c                 z    t        j                  | j                  |         xs t        j                  |       |   S )zBGet value of tensor shape[i] preferring static value if available.)r   dimension_valuer~   r   )tensorr}  s     r'   r   r     s6    		%	%ll1o
 
5#//&1!45r)   )NNFTFTN)NNFTFTNF)TN)d   rE   T)r  rE   )N)TNNN)TNr   N)FFF)G__doc__r  tensorflow.python.eagerr   r   tensorflow.python.frameworkr   r   r   r   r	   r
   r   tensorflow.python.opsr   r   r   r   r   r   r   r   r   r   r   r   tensorflow.python.ops.nn_gradr   tensorflow.python.utilr   r   r    tensorflow.python.util.tf_exportr   r.   r/   r  r  r(   r3   add_dispatch_supportr@   r7   rb   RegisterGradientrg   rk   ro   rw   r   NotDifferentiabler   r   r   r   r   r   r   r   r  r  rT   r  r  rC  rP  rR  r   r   rm  r   r  r)   r'   <module>r     s'   >  + 0 3 . . 0 + 5 4 + 1 1 0 / - - , ( * ( , 7 . + ' 6, 0   CO }o	!*/ $/4x  xx #'05&*5:""3lM$ i 
, !
, k"
, #
, "#	 '+#'NJ  $NJb +,-	 (+&'+/	=  .=@ '-L,MN	 +.)*/  O/d   ( )   , -6<r%MP) C&)CX:z$$>
  !	
 #' [  "[| =R 	
 #' W  !W| &* BJ !"	;:  #;:|	D !"	N  #ND@6U+vod5r)   