
    AVh1                       d 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 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 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jX                  Z- e.h d       Z/d! Z0	 	 	 dd"Z1 G d# d$      Z2dd%Z3 e+d&g '      e$jh                  	 dd(              Z5 e+d&g'      e$jh                  	 	 	 	 	 	 	 dd)              Z6ejn                  j                   e6_          e+d*      e$jh                  	 	 	 dd+              Z8 G d, d-      Z9d. Z:d/ Z;d0 Z< e+d1g'      e$jh                  	 	 	 	 	 	 dd2              Z= e+d1g '      e$jh                  	 	 	 	 	 dd3              Z> e#j~                   e#j~                  e=j                   d4d5      d6d7      e>_         	 	 	 	 	 	 	 dd9Z@ G d: d;      ZA e+d<g'      e$jh                  	 	 	 	 	 dd=              ZB e+d<g '      e$jh                  	 	 	 	 	 dd>              ZC e+d?      e$jh                  dd@              ZDddAZE e+dBg'      e$jh                   e#j                  ddCd8dDE       e#j                  ddFd8dGE      	 	 	 	 	 	 	 	 	 ddH                            ZG e+dBg '      e$jh                  	 	 	 ddI              ZH e+dJ      e$jh                  	 	 	 	 ddK              ZI e+dLg '      e$jh                  	 	 	 ddM              ZJ e+dLg'      e$jh                  dddd8dGg dNddfdO              ZK e+dPg'      e$jh                  d8dGg dNdfdQ              ZL e+dRg'      e$jh                  ddddd8dGg dNddf	dS              ZM e+dTg'      e$jh                  	 	 	 	 	 	 	 	 	 	 ddU              ZN e+dTg '      e$jh                  	 	 	 	 ddV              ZOdW ZP e+dX      e$jh                  	 ddY              ZQ e+dZg'      e$jh                   e#j                  dZ      dGg dNdfd[                     ZS e+d\d]d\g'      e$jh                   e#j                  d]      dGg dNdfd^                     ZT e+d_d`d_g'      e$jh                   e#j                  d`      dGg dNdfda                     ZU	 	 ddbZV e+dcg '      e$jh                  	 	 	 dde              ZW e+dcg'      e$jh                  dddddg dfddfdg              ZX e#j~                  ej                  j                   d6d7      eW_         ej                  j                   eX_          e+dhg'      e$jh                  	 	 	 	 	 	 	 	 	 ddi              ZZ e+dhg '      e$jh                  	 	 	 	 ddj              Z[eIeOe[fZ\ e+dk      e$jh                  	 	 	 	 ddl              Z] e+dm      e$jh                  ddn              Z^ddoZ_ e+dpg'      e$jh                  ddq              Z` e+dpg '      e$jh                  ddr              Zae`j                   ea_          e+ds      e$j                  e$jh                  ddt                     Zc e+du      e$j                  e$jh                  ddv                     Zd e+dwg '      e$j                  e$jh                  ddy                     Zedz Zfdd{Zg e+d|d}g '      e$jh                  dd~              Zh e+d|d}g'      e$jh                   e#jP                  ddd      dd                     Ziehj                   ei_          e+ddg'      e$j                  e$jh                   e#jP                  ddd      dd                            Zj e+ddg '      e$jh                  dd              Zkd Zl e+dg '      e$jh                  dd              Zm e+dg'      e$jh                   e(ddd      	 dd                     ZndZo e+dg'      e$jh                   e#j                  deo      	 	 	 	 	 dd                     Zqd Zr e+dg'      e$jh                  	 	 	 dd              Zs e+dg '      e$jh                  dd              Zt e+ddg'      e$jh                  dd              Zu e+ddg'      e$jh                  	 	 dd              Zv e+dg '      e$jh                  dd              Zw e+d      e$jh                  dd              Zx e+d      e$jh                  dd              Zy e+ddg'      e$jh                  dd              Zz e+dg'      e$jh                  	 	 	 dd              Z{ e+d      e$jh                  dd              Z| e+d      e$jh                  dd              Z} e+d      e$jh                  dd              Z~ e+dg '      e$jh                  dGe
j                  dxdfd              Z e+dg'      e$jh                  	 	 	 	 	 dd              Zej                  j                   e_          ej                  dd      d        Z ej                  dd      d        Z ej                  dd      d        Z ej                  dd      d        Z e+dg'      e$jh                  dd              ZddZd Z e+dg'      e$jh                   e#jP                  ddd      	 	 dd                     Z e+dg '      e$jh                  dd              Z e+d      e$jh                  dd              Z e+d      e$jh                  dd              Zd Z e+dd      e$jh                  dd8e
j                   dfdÄ              Z e+ddū      e$jh                  	 	 	 	 	 ddƄ              Z e+ddȫ      e$jh                  	 	 	 	 	 ddɄ              ZddʄZ e+dg'      e$jh                   e#j                  dd̬      	 	 	 	 	 	 dd̈́                     Z e+dg '      e$jh                  	 	 	 	 d d΄              Z e+dg'      e$jh                   e#j                  ddЬ      	 	 	 	 	 	 ddф                     Z e+dg '      e$jh                  	 	 	 	 d d҄              Z ej                  dd      dԄ        Z e+dg'      e$jh                  ddք              Z e+dg '      e$jh                  	 ddׄ              Z e+ddg'      e$jh                  ddڄ              Z e+ddg '      e$jh                  ddۄ              Z  e+dg'       e$jh                  ej<                              Z  e+dg'       e$jh                  ej>                              Z  e+dg'       e$jh                  ej@                              Z  e+dg'       e$jh                  ejB                              Z e+dg '      e$jh                  dd              Z e$j                  ejF                          e$j                  ejH                          e$j                  ejJ                          e$j                  ejL                         y(  a9  Primitive Neural Net (NN) Operations.

## Notes on padding

Several neural network operations, such as `tf.nn.conv2d` and
`tf.nn.max_pool2d`, take a `padding` parameter, which controls how the input is
padded before running the operation. The input is padded by inserting values
(typically zeros) before and after the tensor in each spatial dimension. The
`padding` parameter can either be the string `'VALID'`, which means use no
padding, or `'SAME'` which adds padding according to a formula which is
described below. Certain ops also allow the amount of padding per dimension to
be explicitly specified by passing a list to `padding`.

In the case of convolutions, the input is padded with zeros. In case of pools,
the padded input values are ignored. For example, in a max pool, the sliding
window ignores padded values, which is equivalent to the padded values being
`-infinity`.

### `'VALID'` padding

Passing `padding='VALID'` to an op causes no padding to be used. This causes the
output size to typically be smaller than the input size, even when the stride is
one. In the 2D case, the output size is computed as:

```python
out_height = ceil((in_height - filter_height + 1) / stride_height)
out_width  = ceil((in_width - filter_width + 1) / stride_width)
```

The 1D and 3D cases are similar. Note `filter_height` and `filter_width` refer
to the filter size after dilations (if any) for convolutions, and refer to the
window size for pools.

### `'SAME'` padding

With `'SAME'` padding, padding is applied to each spatial dimension. When the
strides are 1, the input is padded such that the output size is the same as the
input size. In the 2D case, the output size is computed as:

```python
out_height = ceil(in_height / stride_height)
out_width  = ceil(in_width / stride_width)
```

The amount of padding used is the smallest amount that results in the output
size. The formula for the total amount of padding per dimension is:

```python
if (in_height % strides[1] == 0):
  pad_along_height = max(filter_height - stride_height, 0)
else:
  pad_along_height = max(filter_height - (in_height % stride_height), 0)
if (in_width % strides[2] == 0):
  pad_along_width = max(filter_width - stride_width, 0)
else:
  pad_along_width = max(filter_width - (in_width % stride_width), 0)
```

Finally, the padding on the top, bottom, left and right are:

```python
pad_top = pad_along_height // 2
pad_bottom = pad_along_height - pad_top
pad_left = pad_along_width // 2
pad_right = pad_along_width - pad_left
```

Note that the division by 2 means that there might be cases when the padding on
both sides (top vs bottom, right vs left) are off by one. In this case, the
bottom and right sides always get the one additional padded pixel. For example,
when pad_along_height is 5, we pad 2 pixels at the top and 3 pixels at the
bottom. Note that this is different from existing libraries such as PyTorch and
Caffe, which explicitly specify the number of padded pixels and always pad the
same number of pixels on both sides.

Here is an example of `'SAME'` padding:

>>> in_height = 5
>>> filter_height = 3
>>> stride_height = 2
>>>
>>> in_width = 2
>>> filter_width = 2
>>> stride_width = 1
>>>
>>> inp = tf.ones((2, in_height, in_width, 2))
>>> filter = tf.ones((filter_height, filter_width, 2, 2))
>>> strides = [stride_height, stride_width]
>>> output = tf.nn.conv2d(inp, filter, strides, padding='SAME')
>>> output.shape[1]  # output_height: ceil(5 / 2)
3
>>> output.shape[2] # output_width: ceil(2 / 1)
2

### Explicit padding

Certain ops, like `tf.nn.conv2d`, also allow a list of explicit padding amounts
to be passed to the `padding` parameter. This list is in the same format as what
is passed to `tf.pad`, except the padding must be a nested list, not a tensor.
For example, in the 2D case, the list is in the format `[[0, 0], [pad_top,
pad_bottom], [pad_left, pad_right], [0, 0]]` when `data_format` is its default
value of `'NHWC'`. The two `[0, 0]` pairs  indicate the batch and channel
dimensions have no padding, which is required, as only spatial dimensions can
have padding.

For example:

>>> inp = tf.ones((1, 3, 3, 1))
>>> filter = tf.ones((2, 2, 1, 1))
>>> strides = [1, 1]
>>> padding = [[0, 0], [1, 2], [0, 1], [0, 0]]
>>> output = tf.nn.conv2d(inp, filter, strides, padding=padding)
>>> tuple(output.shape)
(1, 5, 3, 1)
>>> # Equivalently, tf.pad can be used, since convolutions pad with zeros.
>>> inp = tf.pad(inp, padding)
>>> # 'VALID' means to use no padding in conv2d (we already padded inp)
>>> output2 = tf.nn.conv2d(inp, filter, strides, padding='VALID')
>>> tf.debugging.assert_equal(output, output2)

### Difference between convolution and pooling layers
How padding is used in convolution layers and pooling layers is different. For
convolution layers, padding is filled with values of zero, and padding is
multiplied with kernels. For pooling layers, padding is excluded from the
computation. For example when applying average pooling to a 4x4 grid, how much
padding is added will not impact the output. Here is an example that
demonstrates the difference.

>>> x_in = np.array([[
...   [[2], [2]],
...   [[1], [1]],
...   [[1], [1]]]])
>>> kernel_in = np.array([  # simulate the avg_pool with conv2d
...  [ [[0.25]], [[0.25]] ],
...  [ [[0.25]], [[0.25]] ]])
>>> x = tf.constant(x_in, dtype=tf.float32)
>>> kernel = tf.constant(kernel_in, dtype=tf.float32)
>>> conv_out = tf.nn.conv2d(x, kernel, strides=[1, 1, 1, 1], padding='SAME')
>>> pool_out = tf.nn.avg_pool(x, [2, 2], strides=[1, 1, 1, 1], padding='SAME')
>>> print(conv_out.shape, pool_out.shape)
(1, 3, 2, 1) (1, 3, 2, 1)
>>> tf.reshape(conv_out, [3, 2]).numpy()  # conv2d takes account of padding
array([[1.5 , 0.75],
       [1.  , 0.5 ],
       [0.5 , 0.25]], dtype=float32)
>>> tf.reshape(pool_out, [3, 2]).numpy()  # avg_pool excludes padding
array([[1.5, 1.5],
       [1. , 1. ],
       [1. , 1. ]], dtype=float32)

API docstring: tensorflow.nn
    N)context)config)constant_op)dtypes)errors_impl)
graph_util)ops)random_seed)tensor)tensor_shape)tensor_util)	array_ops)array_ops_stack)	check_ops)gen_math_ops)
gen_nn_ops)math_ops)nn_grad)
random_ops)stateless_random_ops)	variables)*)device_context)deprecation)dispatch)collections_abc)deprecated_args)deprecated_argument_lookup)	tf_export>
   NHCNWCNHWCNWHCNDHWCNDWHCNHDWCNHWDCNWDHCNWHDCc                    | 	dg|dz   z  S t        | t              rnYt        | t              rt        |       } n=t        | t              r| g} n)t        | t        j
                        s| g} nt        |       } t        |       }||dz   k(  r| S |dk(  r| |z  } n$||k7  rt        | d| d|dz    d| d|  d|       |dk(  rddg| z   S dg| z   dgz   S )z%Formats a value input for gen_nn_ops.      z should be of length 1, z or z. Received: = of length )
isinstancelisttupleintr   Sizedlen
ValueError)valuenchannel_indexname	len_values        L/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/nn_ops.py_get_sequencer<      s    ]3!a%= t%KE%GEe_223GEKE%j) !a%L !^AIEA~
v5aSQUG D""&q{9+G H H aq6E>3;!    c           	          t        j                  |d| |g      5 }t        j                  | d      } | j                  }t        j                  |d      }|j                  }t	        ||||||      }	 |	| |      cddd       S # 1 sw Y   yxY w)ax  Computes sums of N-D convolutions (actually cross correlation).

  It is required that 1 <= N <= 3.

  This is used to implement the more generic `convolution` function, which
  extends the interface of this function with a `dilation_rate` parameter.

  Args:

    input: Rank N+2 tensor of type T of shape
      `[batch_size] + input_spatial_shape + [in_channels]` if `data_format`
      does not start with `"NC"`, or
      `[batch_size, in_channels] + input_spatial_shape` if `data_format` starts
      with `"NC"`.
    filter: Rank N+2 tensor of type T of shape
      `filter_spatial_shape + [in_channels, out_channels]`.  Rank of either
      `input` or `filter` must be known.
    padding: Padding method to use, must be either "VALID" or "SAME".
    data_format: A string or None.  Specifies whether the channel dimension of
      the `input` and output is the last dimension (default, or if `data_format`
      does not start with "NC"), or the second dimension (if `data_format`
      starts with "NC").  For N=1, the valid values are "NWC" (default) and
      "NCW".  For N=2, the valid values are "NHWC" (default) and "NCHW".
      For N=3, the valid values are "NDHWC" (default) and "NCDHW".
    strides: Sequence of N positive integers, defaults to `[1] * N`.
    name: Name prefix to use.

  Returns:
    Rank N+2 tensor of type T of shape
    `[batch_size] + output_spatial_shape + [out_channels]`, where
    if padding == "SAME":
      output_spatial_shape = input_spatial_shape
    if padding == "VALID":
      output_spatial_shape = input_spatial_shape - filter_spatial_shape + 1.

  Raises:
    ValueError: if ranks are incompatible.

  non_atrous_convolutioninputr9   filter)filter_shapepaddingdata_formatstridesr9   N)r	   
name_scopeconvert_to_tensorshape_NonAtrousConvolution)
r@   rB   rD   rE   rF   r9   scopeinput_shaperC   ops
             r;   _non_atrous_convolutionrN     s    \ ~~d4ufoF %!!%g6E++K""69F<<L	!
B eV  s   A BBc                   ,    e Zd ZdZ	 	 	 	 ddZd Zd Zy)rJ   av  Helper class for _non_atrous_convolution.

  Note that this class assumes that shapes of input and filter passed to
  `__call__` are compatible with `input_shape` and filter_shape passed to the
  constructor.

  Args:
    input_shape: static input shape, i.e. input.shape.
    filter_shape: static filter shape, i.e. filter.shape.
    padding: see _non_atrous_convolution.
    data_format: see _non_atrous_convolution.
    strides: see _non_atrous_convolution.
    name: see _non_atrous_convolution.
    num_batch_dims: (Optional.)  The number of batch dimensions in the input;
     if not provided, the default of `1` is used.
  Nc           
      &   |j                   !|j                  |j                   |z
  dz         }|| _        || _        |j                   !|j                  |j                   |z   dz
        }|j                   t	        d| d|j
                         |j                   dk  s|j                   |z
  dz   dkD  rt	        d|j
                   d|       |j                   |z
  dz
  }|dg|z  }n+t        |      |k7  rt	        d| d	| d
t        |             |dk(  r:|d}n|dvrt	        d|       |d   | _        || _        | j                  | _
        y |dk(  r[||dk(  rd}dgt        |      z   dgz   }n$|dk(  rddgt        |      z   }nt	        d|       || _        || _        t        | _
        y |dk(  rY||dk(  rdgt        |      z   dgz   }n$|dk(  rddgt        |      z   }nt	        d|       || _        || _        t        | _
        y y )Nr+   z9Rank of convolution must be known. Received: input_shape=	 of rank       ze`input_shape.rank - num_batch_dims + 1` must be at least 3 and at most 5. Received: input_shape.rank=z and num_batch_dims=`len(strides)` should be . Received: strides=r.   r!   >   NCWr!   NCHWr"   <`data_format` must be 'NWC' or 'NCW'. Received: data_format=r   r,   r"   rW   z>`data_format` must be 'NHWC' or 'NCHW'. Received: data_format=r$   NCDHWz@`data_format` must be 'NDHWC' or 'NCDHW'. Received: data_format=)ndims	with_rankrD   r9   r5   rankr4   rF   rE   _conv1dconv_opr0   conv2d_conv3d_expanded_batch)	selfrL   rC   rD   rE   rF   r9   num_batch_dims	conv_dimss	            r;   __init__z_NonAtrousConvolution.__init__S  s    $!++


n
,q
02lDLDI %))


~
-
13k ##.-y9I9I8JLM M 1 1 1N BQ F J00;0@0@/A B*+-. . !!N2Q6Iig	W	"%i[ 1&i{3w<.BC C A~		<< 22=@ A 	AQZdl$d\\dl	a		v 5#W%+& a&4=( 22=@ A 	Adl$ddl	a		w 6#W%+'!a&4=( 22=@ A 	Adl$d+dl 
r=   c                 $    t        ||||||      S )N)r6   filtersstriderD   rE   r9   conv1d)ra   r@   rB   rF   rD   rE   r9   s          r;   r]   z_NonAtrousConvolution._conv1d  s!     r=   c                     | j                  ||| j                  | j                  | j                  | j                        S )N)r@   rB   rF   rD   rE   r9   )r^   rF   rD   rE   r9   ra   inprB   s      r;   __call__z_NonAtrousConvolution.__call__  s<    <<$$YY   r=   NNNr+   )__name__
__module____qualname____doc__rd   r]   rm    r=   r;   rJ   rJ   A  s&    , E,Tr=   rJ   c                    t        j                  |d| g      5  t        j                  | d      } | j                  }|| d }|j	                         st        j                  |       | d }|d|  }|j	                         st        j                  |       d|  }t        |t        j                        r)t        j                  | dg|j                         z         }n.t        j                  | t        j                  dg|fd            } ||      }|j                  | d }	|	j	                         st        j                  |      | d }	t        j                  |t        j                  ||	fd            }
|
j                  | j                  d|  |
j                  | d z          |
cddd       S # 1 sw Y   yxY w)a*  Returns `unsqueeze_batch(op(squeeze_batch(inp)))`.

  Where `squeeze_batch` reshapes `inp` to shape
  `[prod(inp.shape[:-inner_rank])] + inp.shape[-inner_rank:]`
  and `unsqueeze_batch` does the reverse reshape but on the output.

  Args:
    inp: A tensor with dims `batch_shape + inner_shape` where `inner_shape`
      is length `inner_rank`.
    op: A callable that takes a single input tensor and returns a single.
      output tensor.
    inner_rank: A python integer.
    name: A string.

  Returns:
    `unsqueeze_batch_op(squeeze_batch(inp))`.
  squeeze_batch_dimsr@   rA   Naxis)r	   rG   rH   rI   is_fully_definedr   r/   r   TensorShapereshapeas_listconcat	set_shape)rl   rM   
inner_rankr9   rI   inner_shapebatch_shapeinp_reshapedout_reshapedout_inner_shapeouts              r;   ru   ru     s   $ ~~d03%8 


'
2CIIE%K'')OOC(*6k*%K'')OOC(:+6k+|778&&sRD;3F3F3H,HIl&&
y"{ 3"=?l l#L"((*6O++-!5zklCo


i&&_'EBOQC MM#))Lj[)CIIzkl,CCD9  s   FF55F>znn.dilation2d)v1c                 ^    |dk7  rt        d|       t        j                  | |||||      S )a	  Computes the grayscale dilation of 4-D `input` and 3-D `filters` tensors.

  The `input` tensor has shape `[batch, in_height, in_width, depth]` and the
  `filters` tensor has shape `[filter_height, filter_width, depth]`, i.e., each
  input channel is processed independently of the others with its own
  structuring function. The `output` tensor has shape
  `[batch, out_height, out_width, depth]`. The spatial dimensions of the output
  tensor depend on the `padding` algorithm. We currently only support the
  default "NHWC" `data_format`.

  In detail, the grayscale morphological 2-D dilation is the max-sum correlation
  (for consistency with `conv2d`, we use unmirrored filters):

      output[b, y, x, c] =
         max_{dy, dx} input[b,
                            strides[1] * y + rates[1] * dy,
                            strides[2] * x + rates[2] * dx,
                            c] +
                      filters[dy, dx, c]

  Max-pooling is a special case when the filter has size equal to the pooling
  kernel size and contains all zeros.

  Note on duality: The dilation of `input` by the `filters` is equal to the
  negation of the erosion of `-input` by the reflected `filters`.

  Args:
    input: A `Tensor`. Must be one of the following types: `float32`, `float64`,
      `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`,
      `uint32`, `uint64`.
      4-D with shape `[batch, in_height, in_width, depth]`.
    filters: A `Tensor`. Must have the same type as `input`.
      3-D with shape `[filter_height, filter_width, depth]`.
    strides: A list of `ints` that has length `>= 4`.
      The stride of the sliding window for each dimension of the input
      tensor. Must be: `[1, stride_height, stride_width, 1]`.
    padding: A `string` from: `"SAME", "VALID"`.
      The type of padding algorithm to use. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A `string`, only `"NHWC"` is currently supported.
    dilations: A list of `ints` that has length `>= 4`.
      The input stride for atrous morphological dilation. Must be:
      `[1, rate_height, rate_width, 1]`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `input`.
  r"   Q`data_format` values other  than 'NHWC' are not supported. Received: data_format=r@   rB   rF   ratesrD   r9   )r5   r   
dilation2dr@   rf   rF   rD   rE   	dilationsr9   s          r;   dilation2d_v2r     sR    v F
 99DG H H 
		U&-'.%.'.$(
* *r=   c                 n    t        d|d|      }t        d|d|      }t        j                  | |||||      S )Nrf   rB   r   r   )r   r   r   )r@   rB   rF   r   rD   r9   rf   r   s           r;   dilation2d_v1r   )  s?     &i(FK&
$[)We
L%			ufgugt	LLr=   znn.with_space_to_batchc           	          t        j                  | d      } | j                  }fd}t        |||||||      }	 |	| d      S )a|  Performs `op` on the space-to-batch representation of `input`.

  This has the effect of transforming sliding window operations into the
  corresponding "atrous" operation in which the input is sampled at the
  specified `dilation_rate`.

  In the special case that `dilation_rate` is uniformly 1, this simply returns:

    op(input, num_spatial_dims, padding)

  Otherwise, it returns:

    batch_to_space_nd(
      op(space_to_batch_nd(input, adjusted_dilation_rate, adjusted_paddings),
         num_spatial_dims,
         "VALID")
      adjusted_dilation_rate,
      adjusted_crops),

  where:

    adjusted_dilation_rate is an int64 tensor of shape [max(spatial_dims)],
    adjusted_{paddings,crops} are int64 tensors of shape [max(spatial_dims), 2]

  defined as follows:

  We first define two int64 tensors `paddings` and `crops` of shape
  `[num_spatial_dims, 2]` based on the value of `padding` and the spatial
  dimensions of the `input`:

  If `padding = "VALID"`, then:

    paddings, crops = required_space_to_batch_paddings(
      input_shape[spatial_dims],
      dilation_rate)

  If `padding = "SAME"`, then:

    dilated_filter_shape =
      filter_shape + (filter_shape - 1) * (dilation_rate - 1)

    paddings, crops = required_space_to_batch_paddings(
      input_shape[spatial_dims],
      dilation_rate,
      [(dilated_filter_shape - 1) // 2,
       dilated_filter_shape - 1 - (dilated_filter_shape - 1) // 2])

  Because `space_to_batch_nd` and `batch_to_space_nd` assume that the spatial
  dimensions are contiguous starting at the second dimension, but the specified
  `spatial_dims` may not be, we must adjust `dilation_rate`, `paddings` and
  `crops` in order to be usable with these operations.  For a given dimension,
  if the block size is 1, and both the starting and ending padding and crop
  amounts are 0, then space_to_batch_nd effectively leaves that dimension alone,
  which is what is needed for dimensions not part of `spatial_dims`.
  Furthermore, `space_to_batch_nd` and `batch_to_space_nd` handle this case
  efficiently for any number of leading and trailing dimensions.

  For 0 <= i < len(spatial_dims), we assign:

    adjusted_dilation_rate[spatial_dims[i] - 1] = dilation_rate[i]
    adjusted_paddings[spatial_dims[i] - 1, :] = paddings[i, :]
    adjusted_crops[spatial_dims[i] - 1, :] = crops[i, :]

  All unassigned values of `adjusted_dilation_rate` default to 1, while all
  unassigned values of `adjusted_paddings` and `adjusted_crops` default to 0.

  Note in the case that `dilation_rate` is not uniformly 1, specifying "VALID"
  padding is equivalent to specifying `padding = "SAME"` with a filter_shape of
  `[1]*N`.

  Advanced usage. Note the following optimization: A sequence of
  `with_space_to_batch` operations with identical (not uniformly 1)
  `dilation_rate` parameters and "VALID" padding

    net = with_space_to_batch(net, dilation_rate, "VALID", op_1)
    ...
    net = with_space_to_batch(net, dilation_rate, "VALID", op_k)

  can be combined into a single `with_space_to_batch` operation as follows:

    def combined_op(converted_input, num_spatial_dims, _):
      result = op_1(converted_input, num_spatial_dims, "VALID")
      ...
      result = op_k(result, num_spatial_dims, "VALID")

    net = with_space_to_batch(net, dilation_rate, "VALID", combined_op)

  This eliminates the overhead of `k-1` calls to `space_to_batch_nd` and
  `batch_to_space_nd`.

  Similarly, a sequence of `with_space_to_batch` operations with identical (not
  uniformly 1) `dilation_rate` parameters, "SAME" padding, and odd filter
  dimensions

    net = with_space_to_batch(net, dilation_rate, "SAME", op_1, filter_shape_1)
    ...
    net = with_space_to_batch(net, dilation_rate, "SAME", op_k, filter_shape_k)

  can be combined into a single `with_space_to_batch` operation as follows:

    def combined_op(converted_input, num_spatial_dims, _):
      result = op_1(converted_input, num_spatial_dims, "SAME")
      ...
      result = op_k(result, num_spatial_dims, "SAME")

    net = with_space_to_batch(net, dilation_rate, "VALID", combined_op)

  Args:
    input: Tensor of rank > max(spatial_dims).
    dilation_rate: int32 Tensor of *known* shape [num_spatial_dims].
    padding: str constant equal to "VALID" or "SAME"
    op: Function that maps (input, num_spatial_dims, padding) -> output
    filter_shape: If padding = "SAME", specifies the shape of the convolution
      kernel/pooling window as an integer Tensor of shape [>=num_spatial_dims].
      If padding = "VALID", filter_shape is ignored and need not be specified.
    spatial_dims: Monotonically increasing sequence of `num_spatial_dims`
      integers (which are >= 1) specifying the spatial dimensions of `input`
      and output.  Defaults to: `range(1, num_spatial_dims+1)`.
    data_format: A string or None.  Specifies whether the channel dimension of
      the `input` and output is the last dimension (default, or if `data_format`
      does not start with "NC"), or the second dimension (if `data_format`
      starts with "NC").  For N=1, the valid values are "NWC" (default) and
      "NCW".  For N=2, the valid values are "NHWC" (default) and "NCHW".
      For N=3, the valid values are "NDHWC" (default) and "NCDHW".

  Returns:
    The output Tensor as described above, dimensions will vary based on the op
    provided.

  Raises:
    ValueError: if `padding` is invalid or the arguments are incompatible.
    ValueError: if `spatial_dims` are invalid.
  r@   rA   c                       fdS )Nc                      |       S Nrs   )rl   _num_spatial_dimsrM   rD   s     r;   <lambda>z7with_space_to_batch.<locals>.build_op.<locals>.<lambda>  s    "S"2G< r=   rs   )r   rD   rM   s   ``r;   build_opz%with_space_to_batch.<locals>.build_op  s	    <<r=   )rC   spatial_dimsrE   N)r	   rH   rI   _WithSpaceToBatch)
r@   dilation_raterD   rM   rC   r   rE   rL   r   new_ops
      `      r;   with_space_to_batchr   <  sV    ^ 

G
4%+= & 
t	r=   c                   ,    e Zd ZdZ	 	 	 	 ddZd Zd Zy)r   a  Helper class for with_space_to_batch.

  Note that this class assumes that shapes of input and filter passed to
  `__call__` are compatible with `input_shape`, `filter_shape`, and
  `spatial_dims` passed to the constructor.

  Arguments
    input_shape: static shape of input. i.e. input.shape.
    dilation_rate: see `with_space_to_batch`.
    padding: see `with_space_to_batch`.
    build_op: Function that maps (num_spatial_dims, paddings) -> (function that
      maps (input, filter) -> output).
    filter_shape: see `with_space_to_batch`.
    spatial_dims: `see with_space_to_batch`.
    data_format: see `with_space_to_batch`.
    num_batch_dims: (Optional).  Number of batch dims in `input_shape`.
  Nc	           	         t        j                  |t        j                  d      }|j                  j
                  dvr%t        d| d|j                  j                         |j                  j                         st        d| d|j                         |j                  j                  d   j                  }	||j                  d
      r|dz   }
n|}
|t        |
|	|
z         }t        |      }t        t        d |D                    }||k7  st!        d |D              rt        d|       ||j                  d
      r|d   }n|d   dz   }	 |j#                  |       t%        j&                  |      }|}|O|}t)        j                   |dk        rt        d|       t)        j*                  |dk(        r ||	|      | _        y	t/        |      \  }}|dk(  rl|t        d| d|       t        j                  |d      }t%        j&                  |      }||}t1        ||	|      | _        n|	| _        || _        d	| _        n|dk(  r,t)        j8                  |	dgt(        j                        | _        ne|dk(  rRt)        j:                  |      j=                  |	dz   dg      }||j                  d
      r|dd	 | _        n|dd | _        nt        d|       || _        || _         || _!        || _"         ||	d      | _#        | jH                  | _        y	# t        $ r t        d| d| d|j                         w xY w)z&Helper class for _with_space_to_batch.r   rA   )Nr+   z>`dilation_rate.shape.rank` must be 1. Received: dilation_rate=rQ   zE`dilation_rate.shape` must be fully defined. Received: dilation_rate=z with shape r   NNCr+   c              3   2   K   | ]  }t        |        y wr   )r2   .0xs     r;   	<genexpr>z-_WithSpaceToBatch.__init__.<locals>.<genexpr>  s     @c!f@s   c              3   &   K   | ]	  }|d k    ywr+   Nrs   r   s     r;   r   z-_WithSpaceToBatch.__init__.<locals>.<genexpr>  s     /L!A/L   zh`spatial_dims` must be a monotonically increasing sequence of positive integers. Received: spatial_dims=rv   z$`input.shape.rank` must be at least z. Received: input.shape=z with rank z:`dilation_rate` must be positive. Received: dilation_rate=SAMEzN`filter_shape` must be specified for `padding='SAME'`. Received: filter_shape=z and padding=rC   VALIDr,   EXPLICITz>`padding` must be one of 'SAME' or 'VALID'. Received: padding=)%r	   rH   r   int32rI   rZ   r5   r\   ry   dimsr6   
startswithranger0   sortedsetanywith_rank_at_leastr   constant_valuenpallcallconvert_padding"_with_space_to_batch_base_paddingsbase_paddingsr   rate_or_const_ratezerosarrayr{   rL   r   r   rE   rM   _with_space_to_batch_call)ra   rL   r   rD   r   rC   r   rE   rb   r   starting_spatial_dimorig_spatial_dimsexpected_input_rank
const_rater   explicit_paddingsconst_filter_shaper   s                     r;   rd   z_WithSpaceToBatch.__init__  s    ))v||/;M  	1(/=3F3F3K3K2LNO O //1(/  !#$ $
 %**//288;#9#9$#?+a/+/+.BBDl\*#@.?@@AL((C/L|/L,L77H6IKL L ;#9#9$#?(,(,q0O$$%89 ++M:J&%	
Q	''1l45 	5 

a	 -w7	!0!9G &		&&2^=	KL 	L **<nMl&55lC		')? 02DF !1"4!	G	88%5q$9288Dd	J	xx 12!1A!5q 9:  
	 [%;%;D%A*12.*1R0 ,,396 7 7 #D$D&D"D'1DG..DIu  O01D0E F##.-{;;K;K:LNO OOs   L (Mc                    d}| j                   }| j                  }|j                  "|j                         }|D cg c]  }||   	 }}|d|v r;t	        j
                  |      }t        j                  |D cg c]  }||   	 c}      }| j                  }	|	6t	        j
                  |      }
t        |
| j                  | j                        }	t	        j                  ||	| j                        \  }}t        | j                  d|      }t        |d|      }t        |d|      }t	        j                  |||      }| j!                  ||      }t	        j"                  |||      }| j$                  }| j$                  j'                  d      rb|j
                  j(                  d   j*                  s?|=|j
                  j                         }|j
                  d   |d<   |j-                  |       |S c c}w c c}w )	z+Call functionality for with_space_to_batch.N)rL   r   block_shaper+   r   )r@   r   paddings)r@   r   cropsr   rv   )rL   r   rZ   r|   r   rI   r   stackr   r   r   r    required_space_to_batch_paddingsr   _with_space_to_batch_adjustspace_to_batch_ndrM   batch_to_space_ndrE   r   r   r6   r~   )ra   rl   rB   input_spatial_shaperL   r   input_shape_listiinput_shape_tensorr   rC   r   r   r   input_convertedresultresult_convertedoutput_shapes                     r;   r   z+_WithSpaceToBatch._with_space_to_batch_callZ  s    ""K$$L$$,,.:FGQ-a0GG"d.A&A$??3/+11*6
7Qa 
79 &&M __V,l8
--t/F/FHm  @@'#&&(OHe
 00B0BA0<>M*8QEH'q,?E11}xAO WW_f-F 22-u> #(8(8(C(CD(I##((+11f6H'--557 ,,r*Q""<0M H 8s   G17G6c                 &    | j                  ||      S r   )r   rk   s      r;   rm   z_WithSpaceToBatch.__call__  s    99S&!!r=   rn   )ro   rp   rq   rr   rd   r   rm   rs   r=   r;   r   r     s'    . ! i/V.`"r=   r   c                     | d| }|dz
  |z  }|dz  }||z
  }t        j                  t        |      D cg c]  }||   ||   g c}      }|S c c}w )z)Helper function to compute base_paddings.Nr+   r,   )r   r   r   )	rC   r   r   filter_spatial_shapepad_extra_shapepad_extra_startpad_extra_endr   r   s	            r;   r   r     sy    
 &&7'78)A-1CC/ $q(/!O3-!''7<=M7NO!M!,-OQ-	 Ps   Ac                    | j                         j                         dd }| j                  j                  }g }t	        j
                  |       }||n| }d}d}	|	t        |      k  r|	}
||	   }|dkD  r1|j                  t        j                  |dz
  |z
  g|z   ||             |	dz   t        |      k  r9||	dz      ||	   dz   k(  r(|	dz  }	|	dz   t        |      k  r||	dz      ||	   dz   k(  r(|j                  ||
|	dz           ||	   }|	dz  }	|	t        |      k  r|t        j                  |      S t        j                  |d      S )a  Returns an `adjusted` version of `orig` based on `spatial_dims`.

  Tensor of the same type as `orig` and with shape
  `[max(spatial_dims), ...]` where:

    adjusted[spatial_dims[i] - 1, ...] = orig[i, ...]

  for 0 <= i < len(spatial_dims), and

    adjusted[j, ...] = fill_value

  for j != spatial_dims[i] - 1 for some i.

  If `orig` is a constant value, then the result will be a constant value.

  Args:
    orig: Tensor of rank > max(spatial_dims).
    fill_value: Numpy scalar (of same data type as `orig) specifying the fill
      value for non-spatial dimensions.
    spatial_dims: See with_space_to_batch.

  Returns:
    `adjusted` tensor.
  r+   Nr   dtype)	get_shaper|   r   as_numpy_dtyper   r   r4   appendr   fullconcatenater   r}   )orig
fill_valuer   	fill_dimsr   parts
const_origconst_or_origprev_spatial_dimr   start_istart_spatial_dims               r;   r   r     s{   2 nn&&(,)
**
#
#%
%))$/* * 6*D-!	CG$Q1 ll
'' 1$'7789D q53|$$A,q/A"551fa q53|$$A,q/A"55	LLwq1u-.#AFA) 	
C* >>%  E1%%r=   c           
         |dg| z  }n+t        |      | k7  rt        d|  d| dt        |             t        j                  |t        j                        }t        j
                  |dk        rt        d|       |dg| z  }n+t        |      | k7  rt        d|  d| dt        |             t        j                  |t        j                        }t        j
                  |dk        rt        d	|       t        j
                  |dkD        r)t        j
                  |dkD        rt        d
| d|       ||fS )al  Helper function for verifying strides and dilation_rate arguments.

  This is used by `convolution` and `pool`.

  Args:
    num_spatial_dims: int
    strides: Optional.  List of N ints >= 1.  Defaults to `[1]*N`.  If any value
      of strides is > 1, then all values of dilation_rate must be 1.
    dilation_rate: Optional.  List of N ints >= 1.  Defaults to `[1]*N`.  If any
      value of dilation_rate is > 1, then all values of strides must be 1.

  Returns:
    Normalized (strides, dilation_rate) as int32 numpy arrays of shape
    [num_spatial_dims].

  Raises:
    ValueError: if the parameters are invalid.
  r+   z`len(dilation_rate)` should be z. Received: dilation_rate=r.   r   zHall values of `dilation_rate` must be positive. Received: dilation_rate=rT   rU   z<all values of `strides` must be positive. Received: strides=zW`strides > 1` not supported in conjunction with `dilation_rate > 1`. Received: strides= and dilation_rate=)r4   r5   r   r   r   r   )r   rF   r   s      r;   _get_strides_and_dilation_rater     s   & C**M
=--
67G6H I00=kM*+- . . ((=9-VVMA
 00=@ A A _c$$G
7|''
01A0B C**1+c'l^M N NHHWBHH-'VVGaK
 **14 5 5 VVGaKRVVMA$56
	$I%8	IJ J 
-	r=   znn.convolutionc	           	      ^    t        d|d|      }t        d|d|      }t        | ||||||      S )a  Computes sums of N-D convolutions (actually cross-correlation).

  This also supports either output striding via the optional `strides` parameter
  or atrous convolution (also known as convolution with holes or dilated
  convolution, based on the French word "trous" meaning holes in English) via
  the optional `dilation_rate` parameter.  Currently, however, output striding
  is not supported for atrous convolutions.

  Specifically, in the case that `data_format` does not start with "NC", given
  a rank (N+2) `input` Tensor of shape

    [num_batches,
     input_spatial_shape[0],
     ...,
     input_spatial_shape[N-1],
     num_input_channels],

  a rank (N+2) `filter` Tensor of shape

    [spatial_filter_shape[0],
     ...,
     spatial_filter_shape[N-1],
     num_input_channels,
     num_output_channels],

  an optional `dilation_rate` tensor of shape N (defaults to `[1]*N`) specifying
  the filter upsampling/input downsampling rate, and an optional list of N
  `strides` (defaults to `[1]*N`), this computes for each N-D spatial output
  position `(x[0], ..., x[N-1])`:

  ```
  output[b, x[0], ..., x[N-1], k] =
      sum_{z[0], ..., z[N-1], q}
          filter[z[0], ..., z[N-1], q, k] *
          padded_input[b,
                       x[0]*strides[0] + dilation_rate[0]*z[0],
                       ...,
                       x[N-1]*strides[N-1] + dilation_rate[N-1]*z[N-1],
                       q]
  ```

  where b is the index into the batch, k is the output channel number, q is the
  input channel number, and z is the N-D spatial offset within the filter. Here,
  `padded_input` is obtained by zero padding the input using an effective
  spatial filter shape of `(spatial_filter_shape-1) * dilation_rate + 1` and
  output striding `strides`.

  In the case that `data_format` does start with `"NC"`, the `input` and output
  (but not the `filter`) are simply transposed as follows:

  ```python
  convolution(input, data_format, **kwargs) =
    tf.transpose(convolution(tf.transpose(input, [0] + range(2,N+2) + [1]),
                             **kwargs),
                 [0, N+1] + range(1, N+1))
  ```

  It is required that 1 <= N <= 3.

  Args:
    input: An (N+2)-D `Tensor` of type `T`, of shape
      `[batch_size] + input_spatial_shape + [in_channels]` if data_format does
      not start with "NC" (default), or
      `[batch_size, in_channels] + input_spatial_shape` if data_format starts
      with "NC".
    filter: An (N+2)-D `Tensor` with the same type as `input` and shape
      `spatial_filter_shape + [in_channels, out_channels]`.
    padding: A string, either `"VALID"` or `"SAME"`. The padding algorithm.
      `"valid"` means no padding. `"same"` results in padding evenly to
      the left/right or up/down of the input such that output has the same
      height/width dimension as the input when the strides are 1. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    strides: Optional.  Sequence of N ints >= 1.  Specifies the output stride.
      Defaults to `[1]*N`.  If any value of strides is > 1, then all values of
      dilation_rate must be 1.
    dilation_rate: Optional.  Sequence of N ints >= 1.  Specifies the filter
      upsampling/input downsampling rate.  In the literature, the same parameter
      is sometimes called `input stride` or `dilation`.  The effective filter
      size used for the convolution will be `spatial_filter_shape +
      (spatial_filter_shape - 1) * (rate - 1)`, obtained by inserting
      (dilation_rate[i]-1) zeros between consecutive elements of the original
      filter in each spatial dimension i.  If any value of dilation_rate is > 1,
      then all values of strides must be 1.
    name: Optional name for the returned tensor.
    data_format: A string or None.  Specifies whether the channel dimension of
      the `input` and output is the last dimension (default, or if `data_format`
      does not start with "NC"), or the second dimension (if `data_format`
      starts with "NC").  For N=1, the valid values are "NWC" (default) and
      "NCW".  For N=2, the valid values are "NHWC" (default) and "NCHW".
      For N=3, the valid values are "NDHWC" (default) and "NCDHW".

  Returns:
    A `Tensor` with the same type as `input` of shape

        `[batch_size] + output_spatial_shape + [out_channels]`

    if data_format is None or does not start with "NC", or

        `[batch_size, out_channels] + output_spatial_shape`

    if data_format starts with "NC",
    where `output_spatial_shape` depends on the value of `padding`.

    If padding == "SAME":
      output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])

    If padding == "VALID":
      output_spatial_shape[i] =
        ceil((input_spatial_shape[i] -
              (spatial_filter_shape[i]-1) * dilation_rate[i])
             / strides[i]).

  Raises:
    ValueError: If input/output depth does not match `filter` shape, if padding
      is other than `"VALID"` or `"SAME"`, or if data_format is invalid.

  rf   rB   r   r   rF   rD   rE   r   r9   )r   convolution_internal)	r@   rB   rD   rF   r   r9   rE   rf   r   s	            r;   convolutionr   	  sJ    D &i(FK&,9o}>-	
 r=   c           	      &    t        | ||||||      S )Nr   )r   r   s          r;   convolution_v2r     s&     

 r=   r   r   rB   rf   Tc	                    t        |t        j                        sNt        j                  |      s9t        j                  dd|| g      5  t        j                  |d      }ddd       t        | t        j                        sNt        j                  |       s9t        j                  dd|| g      5  t        j                  | d      } ddd       |j                  j                  }	| j                  j                  }
|;|	r|	dz
  }n[|
r|
dz
  }nSt        d| j                   d|
 d	|j                   d|	       |	r&|	dz
  |k7  rt        d
|j                   d|	 d|       |
r	|
|z
  dz
  }nd}|dvrt        d| d      ||t        v r||z   }n|}|t        |||d      }d}n t        |||d      }t        d |D              }t        |||d      }t!        j"                         du}|rd}n|r|rd}n|dk(  rd}n
|dk(  rd}nd}t        j                  ||| |g      5 }|r|r6|dk(  rt$        }n|dk(  rt&        }nt(        } || ||||||      cddd       S |dk(  r|dd }|dd }n
|dd }|dd }t+        t-        j.                  | j                        t-        j.                  |j                        ||||||      } || |      cddd       S # 1 sw Y   wxY w# 1 sw Y   xY w# 1 sw Y   yxY w)a  Internal function which performs rank agnostic convolution.

  Args:
    input: See `convolution`.
    filters: See `convolution`.
    strides: See `convolution`.
    padding: See `convolution`.
    data_format: See `convolution`.
    dilations: See `convolution`.
    name: See `convolution`.
    call_from_convolution: See `convolution`.
    num_spatial_dims: (Optional.).  It is a integer describing the
      rank of the spatial dimensions.  For `1-D`, `2-D` and `3-D` convolutions,
      the value of `num_spatial_dims` is `1`, `2`, and `3`, respectively.
      This argument is only required to disambiguate the rank of `batch_shape`
      when `filter_shape.ndims is None` and `len(batch_shape) > 1`.  For
      backwards compatibility, if `num_spatial_dims is None` and
     `filter_shape.ndims is None`, then `len(batch_shape)` is assumed to be
     `1` (i.e., the input is expected to be
     `[batch_size, num_channels] + input_spatial_shape`
     or `[batch_size] + input_spatial_shape + [num_channels]`.

  Returns:
    A tensor of shape and dtype matching that of `input`.

  Raises:
    ValueError: If input and filter both have unknown shapes, or if
      `num_spatial_dims` is provided and incompatible with the value
      estimated from `filters.shape`.
  r   Nrf   rA   r@   r,   {When `num_spatial_dims` is not set, one of `input.shape.rank` or `filters.shape.rank` must be known. Received: input.shape=rQ    and filters.shape=zR`filters.shape.rank - 2` should equal `num_spatial_dims`. Received: filters.shape= and num_spatial_dims=r+   >   r+   r,   rR   zB`num_spatial_dims` must be 1, 2, or 3. Received: num_spatial_dims=.r   Fc              3   &   K   | ]	  }|d k7    ywr   rs   )r   r   s     r;   r   z'convolution_internal.<locals>.<genexpr>  s     4Q!q&4r   rF   r   Conv2DrR   Conv3Dri   rD   rE   r   r9   rv   )rF   r   r9   rE   r   )r/   variables_libVariabler   
is_tf_typer	   rG   rH   
tensor_libTensorrI   r\   r5   _CHANNELS_LAST_FORMATSr<   r   r   enclosing_tpu_context_conv2d_expanded_batchr`   ri   Convolutionr   as_shape)r@   rf   rF   rD   rE   r   r9   call_from_convolutionr   filters_rankinputs_rankrb   r8   is_dilated_convhas_tpu_contextdefault_namerM   s                    r;   r   r     s|   P Wm44
5

 
 
)	.w6F	G ?%%gI>g?
UJ--
.{7M7M8	.w6F	G 9##E8e9 ##,  +%)	$q##(;;-y F"==/<.BC C
 q(,<<
	 y ?,-	/0 0
  #33a7NNY&
	&&6%7q	:; ; K+AA"%55M"Mi)9=)+IOi)9=)+I4)44O'#3]IN'"88:$F/	L3 L1L1LL
~~dL5'*:; $ t o	Q	#q #


!$  $ ( 
!	!"+abM	!B-aO	



,



.
!!+-b wI$  $ A? ?9 9x$  $ s+   	K1K#"1K0A/K0K #K-0K9c                   .    e Zd ZdZ	 	 	 	 	 ddZd Zd Zy)r  a  Helper class for convolution.

  Note that this class assumes that shapes of input and filter passed to
  `__call__` are compatible with `input_shape`, `filter_shape`, and
  `num_spatial_dims` passed to the constructor.

  Arguments
    input_shape: static shape of input. i.e. input.shape.  Its length is
      `batch_shape + input_spatial_shape + [num_channels]` if `data_format`
      does not start with `NC`, or
      `batch_shape + [num_channels] + input_spatial_shape` if `data_format`
      starts with `NC`.
    filter_shape: static shape of the filter. i.e. filter.shape.
    padding: The padding algorithm, must be "SAME" or "VALID".
    strides: see convolution.
    dilation_rate: see convolution.
    name: see convolution.
    data_format: A string or `None`.  Specifies whether the channel dimension of
      the `input` and output is the last dimension (if `data_format` is `None`
      or does not start with `NC`), or the first post-batch dimension (i.e. if
      `data_format` starts with `NC`).
    num_spatial_dims: (Usually optional.)  Python integer, the rank of the
      spatial and channel dimensions.  For `1-D`, `2-D` and `3-D` convolutions,
      the value of `num_spatial_dims` is `1`, `2`, and `3`, respectively.
      This argument is only required to disambiguate the rank of `batch_shape`
      when `filter_shape.ndims is None` and `len(batch_shape) > 1`.  For
      backwards compatibility, if `num_spatial_dims is None` and
      `filter_shape.ndims is None`, then `len(batch_shape)` is assumed to be
      `1` (i.e., the input is expected to be
      `[batch_size, num_channels] + input_spatial_shape`
      or `[batch_size] + input_spatial_shape + [num_channels]`.
  Nc	                    d}	t        j                  |      }t        j                  |      }|j                  A|0|j                  |dz   k7  rt        d| d|j                   d|       |j                  dz
  }|j                  ||j                  |z
  dz
  }	||j                  dz
  }nP|j                  D|j                  |dz   k  rt        d| d|j                   d|       |	|j                  |z
  dz
  }	|+t        d| d|j                   d	| d
|j                         |	d}	|	dk  r1t        d|	 d| d|j                   d| d|j                   d|       ||j                  d      s)t        j                  |||	z         }
t        |	||	z         }n+t        j                  ||	      }
t        |	dz   ||	z   dz         }t        j                  ||      }|
|z  j                  d      st        d| d|
 d| d| d	      t        |||      \  }}|| _
        || _        || _        || _        || _        || _        || _        |	| _        || _        t'        |||| j(                  ||||	      | _        y)z Helper function for convolution.Nr,   zM`filters.shape.rank` must be `num_spatial_dims + 2`. Received: filters.shape=rQ   r   r+   zQ`input.shape.rank` must be >= than `num_spatial_dims + 2`. Received: input.shape=r   z and `filters.shape=z
` of rank z%Batch dims should be >= 1, but found z. Batch dims was estimated as `input.shape.rank - num_spatial_dims - 1` and `num_spatial_dims` was either provided or estimated as `filters.shape.rank - 2`. Received: input.shape=z, filters.shape=z, and num_spatial_dims=r   r   zsThe number of input channels is not divisible by the corresponding number of output filters. Received: input.shape=z with z channels and filters.shape=z output filters.)r   rD   r   rC   r   rE   rb   )r   r  rZ   r5   r\   r   dimension_at_indexr   is_compatible_withr   rL   rC   rE   rF   rD   r9   r   rb   r   r   	_build_opr^   )ra   rL   rC   rD   rF   r   r9   rE   r   rb   input_channels_dimr   
filter_dims                r;   rd   zConvolution.__init__e  sa    N((6L''4K%

&


 01 4
4)N)L4E4E3F G  0134 	4
 (--1$)9)E"((+;;a?n$**Q.				&/!33''2m9[=M=M<N O&&6%79: :
 #(..1AAAEN##.-y9I9I8J K(>L4E4E3FHI I n1.1A B# $/-y9I9I8J K'.	,2C2C1D E./12 2 +"8"8">'::
'.8:>+;n+LMl'::
~'
1
.?!CEl 00?OPJ+??B==HM  <\N K-/0 0 <'=2G] #D$D"DDLDLDI&D(D,D$#!!%'DLr=   c           	          t        | j                  | j                  || j                  | j                  | j
                  | j                        S )N)rC   rD   rE   rF   r9   rb   )rJ   rL   rC   rE   rF   r9   rb   )ra   r   rD   s      r;   r  zConvolution._build_op  sD     &&$$YY**, ,r=   c                     t        j                         Pt        ||| j                  | j                  | j
                  | j                  | j                  d| j                  	      S | j                  ||      S )NF)rF   rD   rE   r   r9   r	  r   )
r   r  r   rF   rD   rE   r   r9   r   r^   rk   s      r;   rm   zConvolution.__call__  sj    ++-9!

,,,,&&&&yy %00	2 	2 \\#v&&r=   NNNNN)ro   rp   rq   rr   rd   r  rm   rs   r=   r;   r  r  C  s*    J ! $b'H,'r=   r  znn.poolc	           	        
 t        d|d|      }t        j                  |d|j                         z  | g      5 t        j                  | d      } t        |      dk  sdkD  rt        d| d	t        |             | j                         j                  d
z          t        ||      \  }}|dk(  r)t        j                  |dkD        rt        d| d|       t        j                  ||kD        rt        d| d|       t        t        t        t        t        t        d|fvrt         d| d      ||j!                  d      s6dgt#        |      z   dgz   dgt#        |      z   dgz   
t%        ddz         n/ddgt#        |      z   ddgt#        |      z   
t%        d
d
z         dk(  rA||dk(  rt'        d      n |dk(  rt'        d      nt        d|       dgz   dg
z   
nt'        |      
fd}	t)        | |||	|      cddd       S # 1 sw Y   yxY w)aG  Performs an N-D pooling operation.

  In the case that `data_format` does not start with "NC", computes for
      0 <= b < batch_size,
      0 <= x[i] < output_spatial_shape[i],
      0 <= c < num_channels:

  ```
  output[b, x[0], ..., x[N-1], c] =
    REDUCE_{z[0], ..., z[N-1]}
      input[b,
            x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0],
            ...
            x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1],
            c],
  ```

  where the reduction function REDUCE depends on the value of `pooling_type`,
  and pad_before is defined based on the value of `padding` as described in
  the "returns" section of `tf.nn.convolution` for details.
  The reduction never includes out-of-bounds positions.

  In the case that `data_format` starts with `"NC"`, the `input` and output are
  simply transposed as follows:

  ```python
  pool(input, data_format, **kwargs) =
    tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]),
                      **kwargs),
                 [0, N+1] + range(1, N+1))
  ```

  Args:
    input: Tensor of rank N+2, of shape
      `[batch_size] + input_spatial_shape + [num_channels]` if data_format does
      not start with "NC" (default), or
      `[batch_size, num_channels] + input_spatial_shape` if data_format starts
      with "NC".  Pooling happens over the spatial dimensions only.
    window_shape: Sequence of N ints >= 1.
    pooling_type: Specifies pooling operation, must be "AVG" or "MAX".
    padding: The padding algorithm, must be "SAME" or "VALID".
      See the "returns" section of `tf.nn.convolution` for details.
    dilation_rate: Optional.  Dilation rate.  List of N ints >= 1.
      Defaults to `[1]*N`.  If any value of dilation_rate is > 1, then all
      values of strides must be 1.
    strides: Optional.  Sequence of N ints >= 1.  Defaults to `[1]*N`.
      If any value of strides is > 1, then all values of dilation_rate must be
      1.
    name: Optional. Name of the op.
    data_format: A string or None.  Specifies whether the channel dimension of
      the `input` and output is the last dimension (default, or if `data_format`
      does not start with "NC"), or the second dimension (if `data_format`
      starts with "NC").  For N=1, the valid values are "NWC" (default) and
      "NCW".  For N=2, the valid values are "NHWC" (default) and "NCHW".
      For N=3, the valid values are "NDHWC" (default) and "NCDHW".
    dilations: Alias for dilation_rate

  Returns:
    Tensor of rank N+2, of shape
      [batch_size] + output_spatial_shape + [num_channels]

    if data_format is None or does not start with "NC", or

      [batch_size, num_channels] + output_spatial_shape

    if data_format starts with "NC",
    where `output_spatial_shape` depends on the value of padding:

    If padding = "SAME":
      output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])

    If padding = "VALID":
      output_spatial_shape[i] =
        ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i])
             / strides[i]).

  Raises:
    ValueError: if arguments are invalid.

  r   r   z%s_poolr@   rA   r+   rR   z?`len(window_shape)` must be 1, 2, or 3. Received: window_shape=r.   r,   r   zZpooling with 'SAME' padding is not implemented for `dilation_rate` > 1. Received: padding=r   zu`strides` > `window_shape` not supported due to inconsistency between CPU and GPU implementations. Received: strides=z and window_shape=))MAXr+   )r  r,   )r  rR   )AVGr+   )r  r,   )r  rR   z-D z pooling is not supported.Nr   r!   r"   )rE   rV   rW   zAdata_format must be either 'NWC' or 'NCW'. Received: data_format=c                     dk(  rt        j                  | d         }  	   | |fd
i}dk(  rt        j                  |d   g      }|S )Nr+   r   r9   )r   expand_dimssqueeze)converted_inputr   converted_paddingr   adjusted_stridesadjusted_window_shapedata_format_kwargsr   op_keypooling_opsrK   r   s       r;   rM   zpool.<locals>.op  s~    	Q	#//0<QA"{6"



	 
    f 
Q	""6LO+<=mr=   )r@   r   rD   rM   r   rC   )r   r	   rG   lowerrH   r4   r5   r   r[   r   r   r   max_pool
max_pool3davg_pool
avg_pool3dr   r0   r   dictr   )r@   window_shapepooling_typerD   r   rF   r9   rE   r   rM   r!  r"  r#  r   r$  r%  rK   r   s             @@@@@@@@r;   poolr.    s   x -9o}>- ~~dI););)=>g S#"'!!%g6E<(!/!3 ''3nKl+,. / / 
OO 01 45;'=2G] &RVVMA$5644;9 =(/+, ,
 
vvg$%DDK9 M*^-. . K ,-F[ c,/I
JL L +"8"8"> cD$66!<tG},s21.23l !ftL'99Q$w-/1.23l1		u 4!f5%!f5 22=@ A 	A c$99//K8  #!!#[S# S# S#s    G0H::Ic           
      (    t        | |||||||      S )aV  Performs an N-D pooling operation.

  In the case that `data_format` does not start with "NC", computes for
      0 <= b < batch_size,
      0 <= x[i] < output_spatial_shape[i],
      0 <= c < num_channels:

  ```
  output[b, x[0], ..., x[N-1], c] =
    REDUCE_{z[0], ..., z[N-1]}
      input[b,
            x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0],
            ...
            x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1],
            c],
  ```

  where the reduction function REDUCE depends on the value of `pooling_type`,
  and pad_before is defined based on the value of `padding` as described in
  the "returns" section of `tf.nn.convolution` for details.
  The reduction never includes out-of-bounds positions.

  In the case that `data_format` starts with `"NC"`, the `input` and output are
  simply transposed as follows:

  ```python
  pool(input, data_format, **kwargs) =
    tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]),
                      **kwargs),
                 [0, N+1] + range(1, N+1))
  ```

  Args:
    input: Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape +
      [num_channels]` if data_format does not start with "NC" (default), or
      `[batch_size, num_channels] + input_spatial_shape` if data_format starts
      with "NC".  Pooling happens over the spatial dimensions only.
    window_shape: Sequence of N ints >= 1.
    pooling_type: Specifies pooling operation, must be "AVG" or "MAX".
    strides: Optional. Sequence of N ints >= 1.  Defaults to `[1]*N`. If any value of
      strides is > 1, then all values of dilation_rate must be 1.
    padding: The padding algorithm, must be "SAME" or "VALID". Defaults to "SAME".
      See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A string or None.  Specifies whether the channel dimension of
      the `input` and output is the last dimension (default, or if `data_format`
      does not start with "NC"), or the second dimension (if `data_format`
      starts with "NC").  For N=1, the valid values are "NWC" (default) and
      "NCW".  For N=2, the valid values are "NHWC" (default) and "NCHW". For
      N=3, the valid values are "NDHWC" (default) and "NCDHW".
    dilations: Optional.  Dilation rate.  List of N ints >= 1. Defaults to
      `[1]*N`.  If any value of dilation_rate is > 1, then all values of strides
      must be 1.
    name: Optional. Name of the op.

  Returns:
    Tensor of rank N+2, of shape
      [batch_size] + output_spatial_shape + [num_channels]

    if data_format is None or does not start with "NC", or

      [batch_size, num_channels] + output_spatial_shape

    if data_format starts with "NC",
    where `output_spatial_shape` depends on the value of padding:

    If padding = "SAME":
      output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])

    If padding = "VALID":
      output_spatial_shape[i] =
        ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i])
             / strides[i]).

  Raises:
    ValueError: if arguments are invalid.
  )r@   r,  r-  rD   r   rF   r9   rE   )r.  )r@   r,  r-  rF   rD   rE   r   r9   s           r;   pool_v2r0    s*    t 

 r=   znn.atrous_conv2dc           	      J    t        | ||t        j                  |d      |      S )a  Atrous convolution (a.k.a. convolution with holes or dilated convolution).

  This function is a simpler wrapper around the more general
  `tf.nn.convolution`, and exists only for backwards compatibility. You can
  use `tf.nn.convolution` to perform 1-D, 2-D, or 3-D atrous convolution.

  Computes a 2-D atrous convolution, also known as convolution with holes or
  dilated convolution, given 4-D `value` and `filters` tensors. If the `rate`
  parameter is equal to one, it performs regular 2-D convolution. If the `rate`
  parameter is greater than one, it performs convolution with holes, sampling
  the input values every `rate` pixels in the `height` and `width` dimensions.
  This is equivalent to convolving the input with a set of upsampled filters,
  produced by inserting `rate - 1` zeros between two consecutive values of the
  filters along the `height` and `width` dimensions, hence the name atrous
  convolution or convolution with holes (the French word trous means holes in
  English).

  More specifically:

  ```
  output[batch, height, width, out_channel] =
      sum_{dheight, dwidth, in_channel} (
          filters[dheight, dwidth, in_channel, out_channel] *
          value[batch, height + rate*dheight, width + rate*dwidth, in_channel]
      )
  ```

  Atrous convolution allows us to explicitly control how densely to compute
  feature responses in fully convolutional networks. Used in conjunction with
  bilinear interpolation, it offers an alternative to `conv2d_transpose` in
  dense prediction tasks such as semantic image segmentation, optical flow
  computation, or depth estimation. It also allows us to effectively enlarge
  the field of view of filters without increasing the number of parameters or
  the amount of computation.

  For a description of atrous convolution and how it can be used for dense
  feature extraction, please see: (Chen et al., 2015). The same operation is
  investigated further in (Yu et al., 2016). Previous works that effectively
  use atrous convolution in different ways are, among others,
  (Sermanet et al., 2014) and (Giusti et al., 2013).
  Atrous convolution is also closely related to the so-called noble identities
  in multi-rate signal processing.

  There are many different ways to implement atrous convolution (see the refs
  above). The implementation here reduces

  ```python
  atrous_conv2d(value, filters, rate, padding=padding)
  ```

  to the following three operations:

  ```python
  paddings = ...
  net = space_to_batch(value, paddings, block_size=rate)
  net = conv2d(net, filters, strides=[1, 1, 1, 1], padding="VALID")
  crops = ...
  net = batch_to_space(net, crops, block_size=rate)
  ```

  Advanced usage. Note the following optimization: A sequence of `atrous_conv2d`
  operations with identical `rate` parameters, 'SAME' `padding`, and filters
  with odd heights/ widths:

  ```python
  net = atrous_conv2d(net, filters1, rate, padding="SAME")
  net = atrous_conv2d(net, filters2, rate, padding="SAME")
  ...
  net = atrous_conv2d(net, filtersK, rate, padding="SAME")
  ```

  can be equivalently performed cheaper in terms of computation and memory as:

  ```python
  pad = ...  # padding so that the input dims are multiples of rate
  net = space_to_batch(net, paddings=pad, block_size=rate)
  net = conv2d(net, filters1, strides=[1, 1, 1, 1], padding="SAME")
  net = conv2d(net, filters2, strides=[1, 1, 1, 1], padding="SAME")
  ...
  net = conv2d(net, filtersK, strides=[1, 1, 1, 1], padding="SAME")
  net = batch_to_space(net, crops=pad, block_size=rate)
  ```

  because a pair of consecutive `space_to_batch` and `batch_to_space` ops with
  the same `block_size` cancel out when their respective `paddings` and `crops`
  inputs are identical.

  Args:
    value: A 4-D `Tensor` of type `float`. It needs to be in the default "NHWC"
      format. Its shape is `[batch, in_height, in_width, in_channels]`.
    filters: A 4-D `Tensor` with the same type as `value` and shape
      `[filter_height, filter_width, in_channels, out_channels]`. `filters`'
      `in_channels` dimension must match that of `value`. Atrous convolution is
      equivalent to standard convolution with upsampled filters with effective
      height `filter_height + (filter_height - 1) * (rate - 1)` and effective
      width `filter_width + (filter_width - 1) * (rate - 1)`, produced by
      inserting `rate - 1` zeros along consecutive elements across the
      `filters`' spatial dimensions.
    rate: A positive int32. The stride with which we sample input values across
      the `height` and `width` dimensions. Equivalently, the rate by which we
      upsample the filter values by inserting zeros across the `height` and
      `width` dimensions. In the literature, the same parameter is sometimes
      called `input stride` or `dilation`.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    name: Optional name for the returned tensor.

  Returns:
    A `Tensor` with the same type as `value`.
    Output shape with `'VALID'` padding is:

        [batch, height - rate * (filter_width - 1),
         width - rate * (filter_height - 1), out_channels].

    Output shape with `'SAME'` padding is:

        [batch, height, width, out_channels].

  Raises:
    ValueError: If input/output depth does not match `filters`' shape, or if
      padding is other than `'VALID'` or `'SAME'`.

  References:
    Multi-Scale Context Aggregation by Dilated Convolutions:
      [Yu et al., 2016](https://arxiv.org/abs/1511.07122)
      ([pdf](https://arxiv.org/pdf/1511.07122.pdf))
    Semantic Image Segmentation with Deep Convolutional Nets and Fully
    Connected CRFs:
      [Chen et al., 2015](http://arxiv.org/abs/1412.7062)
      ([pdf](https://arxiv.org/pdf/1412.7062))
    OverFeat - Integrated Recognition, Localization and Detection using
    Convolutional Networks:
      [Sermanet et al., 2014](https://arxiv.org/abs/1312.6229)
      ([pdf](https://arxiv.org/pdf/1312.6229.pdf))
    Fast Image Scanning with Deep Max-Pooling Convolutional Neural Networks:
      [Giusti et al., 2013]
      (https://ieeexplore.ieee.org/abstract/document/6738831)
      ([pdf](https://arxiv.org/pdf/1302.1700.pdf))
  )r,   )r@   rB   rD   r   r9   )r   r   broadcast_to)r6   rf   raterD   r9   s        r;   atrous_conv2dr4    s,    ^ 
OOD$/
 r=   c                    g }| dk(  rt        d      t        | t        t        f      rt	        |       D ]t  \  }}t        |t        t        f      st        d|  d| dt        |             t        |      dk7  rt        d|  d| dt        |             |j                  |       v t        |       |k7  rt        d| d	|  dt        |              d} | |fS )
a  Converts Python padding to C++ padding for ops which take EXPLICIT padding.

  Args:
    padding: the `padding` argument for a Python op which supports EXPLICIT
      padding.
    expected_length: Expected number of entries in the padding list when
      explicit padding is used.

  Returns:
    (padding, explicit_paddings) pair, which should be passed as attributes to a
    C++ op.

  Raises:
    ValueError: If padding is invalid.
  r   za'EXPLICIT' is not a valid value for `padding`. To use explicit padding, `padding` must be a list.zfWhen `padding` is a list, each element of `padding` must be a list/tuple of size 2. Received: padding=z with element at index z	 of type r,   z	 of size z+When padding is a list, it must be of size z. Received: padding=)r5   r/   r0   r1   	enumeratetyper4   extend)rD   expected_lengthr   r   dim_paddingss        r;   r   r     s-     

 C D D$'$W- -<tUm4 $$+9,CA3i ./1 2 	2 
\	a	 $$+9,CA3i-.0 1 	1 |,- 7|&77H I&iyW@A A G	#	##r=   z	nn.conv1dz7`NCHW` for data_format is deprecated, use `NCW` insteadrW   )	warn_oncerE   z7`NHWC` for data_format is deprecated, use `NWC` insteadr"   c	                    t        j                  d|d|       } t        j                  |d| |g      5 }|
|dk(  s|dk(  rd}d}	d}
n|d	k(  s|d
k(  rd	}d}	d}
nt	        d|       dgt        |d|
d      z   }dgt        |d|
d      z   }t        j                  | |	      } t        j                  |d      }| j                  j                  dv rt        j                  | |||||||      }n7t        | t        j                  t        j                  ||||||      d|      }t        j                  ||	g      cddd       S # 1 sw Y   yxY w)aq  Computes a 1-D convolution of input with rank `>=3` and a `3-D` filter.

  Given an input tensor of shape
    `batch_shape + [in_width, in_channels]`
  if `data_format` is `"NWC"`, or
    `batch_shape + [in_channels, in_width]`
  if `data_format` is `"NCW"`,
  and a filter / kernel tensor of shape
  `[filter_width, in_channels, out_channels]`, this op reshapes
  the arguments to pass them to `conv2d` to perform the equivalent
  convolution operation.

  Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`.
  For example, if `data_format` does not start with "NC", a tensor of shape
    `batch_shape + [in_width, in_channels]`
  is reshaped to
    `batch_shape + [1, in_width, in_channels]`,
  and the filter is reshaped to
    `[1, filter_width, in_channels, out_channels]`.
  The result is then reshaped back to
    `batch_shape + [out_width, out_channels]`
  \(where out_width is a function of the stride and padding as in conv2d\) and
  returned to the caller.

  Args:
    value: A Tensor of rank at least 3. Must be of type `float16`, `float32`, or
      `float64`.
    filters: A Tensor of rank at least 3.  Must have the same type as `value`.
    stride: An int or list of `ints` that has length `1` or `3`.  The number of
      entries by which the filter is moved right at each step.
    padding: 'SAME' or 'VALID'
    use_cudnn_on_gpu: An optional `bool`.  Defaults to `True`.
    data_format: An optional `string` from `"NWC", "NCW"`.  Defaults to `"NWC"`,
      the data is stored in the order of `batch_shape + [in_width,
      in_channels]`.  The `"NCW"` format stores data as `batch_shape +
      [in_channels, in_width]`.
    name: A name for the operation (optional).
    input: Alias for value.
    dilations: An int or list of `ints` that has length `1` or `3` which
      defaults to 1. The dilation factor for each dimension of input. If set to
      k > 1, there will be k-1 skipped cells between each filter element on that
      dimension. Dilations in the batch and depth dimensions must be 1.

  Returns:
    A `Tensor`.  Has the same type as input.

  Raises:
    ValueError: if `data_format` is invalid.
  r@   r6   ri   Nr"   r!   r,   rW   rV   r+   rX   rg   r   r      rR   r,   r+   r   Nuse_cudnn_on_gpurE   r   r9   )rB   rF   rD   rB  rE   r   rR   r   r9   )r   r   r	   rG   r5   r<   r   r  rI   rZ   r   r_   ru   	functoolspartialr  )r6   rf   rg   rD   rB  rE   r9   r@   r   spatial_start_dimr8   rF   r   s                r;   ri   ri     s   N 
0
0%%
P%
~~dHug&67 *:4kV3{e7Kkm		+"6km 00;}> ? ?cM&!]HEEGmIq-MMI!!%):;E##GQ/G{{11  



+!f "



/%! f V&7%89U*: *: *:s   DEEc           
      (    t        | |||d|||      S )a  Computes a 1-D convolution given 3-D input and filter tensors.

  Given an input tensor of shape
    `batch_shape + [in_width, in_channels]`
  if `data_format` is `"NWC"`, or
    `batch_shape + [in_channels, in_width]`
  if `data_format` is `"NCW"`,
  and a filter / kernel tensor of shape
  `[filter_width, in_channels, out_channels]`, this op reshapes
  the arguments to pass them to `conv2d` to perform the equivalent
  convolution operation.

  Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`.
  For example, if `data_format` does not start with `"NC"`, a tensor of shape
    `batch_shape + [in_width, in_channels]`
  is reshaped to
    `batch_shape + [1, in_width, in_channels]`,
  and the filter is reshaped to
    `[1, filter_width, in_channels, out_channels]`.
  The result is then reshaped back to
    `batch_shape + [out_width, out_channels]`
  \(where out_width is a function of the stride and padding as in conv2d\) and
  returned to the caller.

  Args:
    input: A Tensor of rank at least 3. Must be of type `float16`, `float32`, or
      `float64`.
    filters: A Tensor of rank at least 3.  Must have the same type as `input`.
    stride: An int or list of `ints` that has length `1` or `3`.  The number of
      entries by which the filter is moved right at each step.
    padding: 'SAME' or 'VALID'. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: An optional `string` from `"NWC", "NCW"`.  Defaults to `"NWC"`,
      the data is stored in the order of
      `batch_shape + [in_width, in_channels]`.  The `"NCW"` format stores data
      as `batch_shape + [in_channels, in_width]`.
    dilations: An int or list of `ints` that has length `1` or `3` which
      defaults to 1. The dilation factor for each dimension of input. If set to
      k > 1, there will be k-1 skipped cells between each filter element on that
      dimension. Dilations in the batch and depth dimensions must be 1.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`.  Has the same type as input.

  Raises:
    ValueError: if `data_format` is invalid.
  T)rB  rE   r9   r   rh   )r@   rf   rg   rD   rE   r   r9   s          r;   	conv1d_v2rH  3  s*    v 

 r=   znn.conv1d_transposec                 F   t        j                  |d| ||g      5 }||dk(  rd}d}d}	n|dk(  rd}d}d}	nt        d	|       dgt        |d|	d
      z   }dgt        |d|	d      z   }t	        j
                  | |      } t	        j
                  |d      }t        |t        j                        st        |      n|}t	        j                  |d| dg||d gd      }t        j                  ||| |||||      }
t	        j                  |
|      cddd       S # 1 sw Y   yxY w)a  The transpose of `conv1d`.

  This operation is sometimes called "deconvolution" after
  (Zeiler et al., 2010), but is actually the transpose (gradient) of `conv1d`
  rather than an actual deconvolution.

  Args:
    input: A 3-D `Tensor` of type `float` and shape
      `[batch, in_width, in_channels]` for `NWC` data format or
      `[batch, in_channels, in_width]` for `NCW` data format.
    filters: A 3-D `Tensor` with the same type as `input` and shape
      `[filter_width, output_channels, in_channels]`.  `filter`'s
      `in_channels` dimension must match that of `input`.
    output_shape: A 1-D `Tensor`, containing three elements, representing the
      output shape of the deconvolution op.
    strides: An int or list of `ints` that has length `1` or `3`.  The number of
      entries by which the filter is moved right at each step.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A string. `'NWC'` and `'NCW'` are supported.
    dilations: An int or list of `ints` that has length `1` or `3` which
      defaults to 1. The dilation factor for each dimension of input. If set to
      k > 1, there will be k-1 skipped cells between each filter element on that
      dimension. Dilations in the batch and depth dimensions must be 1.
    name: Optional name for the returned tensor.

  Returns:
    A `Tensor` with the same type as `input`.

  Raises:
    ValueError: If input/output depth does not match `filter`'s shape, if
      `output_shape` is not at 3-element vector, if `padding` is other than
      `'VALID'` or `'SAME'`, or if `data_format` is invalid.

  References:
    Deconvolutional Networks:
      [Zeiler et al., 2010]
      (https://ieeexplore.ieee.org/abstract/document/5539957)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
  conv1d_transposeNr!   r"   r+   r,   rV   rW   rX   rg   r   r   input_sizesrB   out_backproprF   rD   rE   r   r9   )r	   rG   r5   r<   r   r  r/   r  r  r0   r}   r   conv2d_backprop_inputr  )r@   rf   r   rF   rD   rE   r   r9   rF  r8   r   s              r;   rJ  rJ  y  ss   j ~~d.g|46 #89=kU2km		km 00;}> ? ? cM'1mXFFGmIq-MMI!!%):;E##GQ/G-7j''.)4%.: ##\2E4E%F%12C2D%E%GHIKL -- F V%67G#8 #8 #8s   C2DD z	nn.conv2dc           
      (    t        | |||d|||      S )a  Computes a 2-D convolution given `input` and 4-D `filters` tensors.

  The `input` tensor may have rank `4` or higher, where shape dimensions `[:-3]`
  are considered batch dimensions (`batch_shape`).

  Given an input tensor of shape
  `batch_shape + [in_height, in_width, in_channels]` and a filter / kernel
  tensor of shape `[filter_height, filter_width, in_channels, out_channels]`,
  this op performs the following:

  1. Flattens the filter to a 2-D matrix with shape
     `[filter_height * filter_width * in_channels, output_channels]`.
  2. Extracts image patches from the input tensor to form a *virtual*
     tensor of shape `[batch, out_height, out_width,
     filter_height * filter_width * in_channels]`.
  3. For each patch, right-multiplies the filter matrix and the image patch
     vector.

  In detail, with the default NHWC format,

      output[b, i, j, k] =
          sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *
                          filter[di, dj, q, k]

  Must have `strides[0] = strides[3] = 1`.  For the most common case of the same
  horizontal and vertical strides, `strides = [1, stride, stride, 1]`.

  Usage Example:

  >>> x_in = np.array([[
  ...   [[2], [1], [2], [0], [1]],
  ...   [[1], [3], [2], [2], [3]],
  ...   [[1], [1], [3], [3], [0]],
  ...   [[2], [2], [0], [1], [1]],
  ...   [[0], [0], [3], [1], [2]], ]])
  >>> kernel_in = np.array([
  ...  [ [[2, 0.1]], [[3, 0.2]] ],
  ...  [ [[0, 0.3]], [[1, 0.4]] ], ])
  >>> x = tf.constant(x_in, dtype=tf.float32)
  >>> kernel = tf.constant(kernel_in, dtype=tf.float32)
  >>> tf.nn.conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID')
  <tf.Tensor: shape=(1, 4, 4, 2), dtype=float32, numpy=..., dtype=float32)>

  Args:
    input: A `Tensor`. Must be one of the following types:
      `half`, `bfloat16`, `float32`, `float64`.
      A Tensor of rank at least 4. The dimension order is interpreted according
      to the value of `data_format`; with the all-but-inner-3 dimensions acting
      as batch dimensions. See below for details.
    filters: A `Tensor`. Must have the same type as `input`.
      A 4-D tensor of shape
      `[filter_height, filter_width, in_channels, out_channels]`
    strides: An int or list of `ints` that has length `1`, `2` or `4`.  The
      stride of the sliding window for each dimension of `input`. If a single
      value is given it is replicated in the `H` and `W` dimension. By default
      the `N` and `C` dimensions are set to 1. The dimension order is determined
      by the value of `data_format`, see below for details.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information. When explicit padding is used and data_format is
      `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],
      [pad_left, pad_right], [0, 0]]`. When explicit padding used and
      data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    data_format: An optional `string` from: `"NHWC", "NCHW"`.
      Defaults to `"NHWC"`.
      Specify the data format of the input and output data. With the
      default format "NHWC", the data is stored in the order of:
          `batch_shape + [height, width, channels]`.
      Alternatively, the format could be "NCHW", the data storage order of:
          `batch_shape + [channels, height, width]`.
    dilations: An int or list of `ints` that has length `1`, `2` or `4`,
      defaults to 1. The dilation factor for each dimension of`input`. If a
      single value is given it is replicated in the `H` and `W` dimension. By
      default the `N` and `C` dimensions are set to 1. If set to k > 1, there
      will be k-1 skipped cells between each filter element on that dimension.
      The dimension order is determined by the value of `data_format`, see above
      for details. Dilations in the batch and depth dimensions if a 4-d tensor
      must be 1.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `input` and the same outer batch shape.
  TrA  )r_   r   s          r;   	conv2d_v2rP    s)    B 
!%'#
 r=   r+   r+   r+   r+   c	                    t        j                  d|d|      }t        |      \  }}	|d}|j                  d      rdnd}
t	        |d|
d      }t	        |d|
d	      }| j
                  }t        |d
d      }|dk(  rt        |      }|dv rt        j                  | |||||	|||	      S t        | t        j                  t        j                  |||||	||      d|      S )a  Computes a 2-D convolution given 4-D `input` and `filter` tensors.

  Given an input tensor of shape `[batch, in_height, in_width, in_channels]`
  and a filter / kernel tensor of shape
  `[filter_height, filter_width, in_channels, out_channels]`, this op
  performs the following:

  1. Flattens the filter to a 2-D matrix with shape
     `[filter_height * filter_width * in_channels, output_channels]`.
  2. Extracts image patches from the input tensor to form a *virtual*
     tensor of shape `[batch, out_height, out_width,
     filter_height * filter_width * in_channels]`.
  3. For each patch, right-multiplies the filter matrix and the image patch
     vector.

  In detail, with the default NHWC format,

      output[b, i, j, k] =
          sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q]
                          * filter[di, dj, q, k]

  Must have `strides[0] = strides[3] = 1`.  For the most common case of the same
  horizontal and vertical strides, `strides = [1, stride, stride, 1]`.

  Args:
    input: A `Tensor`. Must be one of the following types:
      `half`, `bfloat16`, `float32`, `float64`.
      A 4-D tensor. The dimension order is interpreted according to the value
      of `data_format`, see below for details.
    filter: A `Tensor`. Must have the same type as `input`.
      A 4-D tensor of shape
      `[filter_height, filter_width, in_channels, out_channels]`
    strides: An int or list of `ints` that has length `1`, `2` or `4`.  The
      stride of the sliding window for each dimension of `input`. If a single
      value is given it is replicated in the `H` and `W` dimension. By default
      the `N` and `C` dimensions are set to 1. The dimension order is determined
      by the value of `data_format`, see below for details.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. When explicit padding is used and
      data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top,
      pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used
      and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.
    data_format: An optional `string` from: `"NHWC", "NCHW"`.
      Defaults to `"NHWC"`.
      Specify the data format of the input and output data. With the
      default format "NHWC", the data is stored in the order of:
          [batch, height, width, channels].
      Alternatively, the format could be "NCHW", the data storage order of:
          [batch, channels, height, width].
    dilations: An int or list of `ints` that has length `1`, `2` or `4`,
      defaults to 1. The dilation factor for each dimension of`input`. If a
      single value is given it is replicated in the `H` and `W` dimension. By
      default the `N` and `C` dimensions are set to 1. If set to k > 1, there
      will be k-1 skipped cells between each filter element on that dimension.
      The dimension order is determined by the value of `data_format`, see above
      for details. Dilations in the batch and depth dimensions if a 4-d tensor
      must be 1.
    name: A name for the operation (optional).
    filters: Alias for filter.

  Returns:
    A `Tensor`. Has the same type as `input`.
  rf   rB   r"   r   r+   rR   r,   rF   r   rZ   rv   r?  )rB   rF   rD   rB  r   rE   r   r9   )rB   rF   rD   rB  r   rE   r   rC  )r   r   r   r   r<   rI   getattrr4   r   r_   ru   rD  rE  )r@   rB   rF   rD   rB  rE   r   r9   rf   r   r8   rI   rZ   s                r;   r_   r_   ?	  s   \ 11(F,&.w7'K"--d3!-'1mY?'Iq-E)
++% %"
%%
b[JE
## )+	 	 



+-! 
 r=   znn.conv2d_backprop_filterc	                 Z    t        |      \  }}	t        j                  | ||||||	|||
      S )a@	  Computes the gradients of convolution with respect to the filter.

  Args:
    input: A `Tensor`. Must be one of the following types:
      `half`, `bfloat16`, `float32`, `float64`.
      4-D with shape `[batch, in_height, in_width, in_channels]`.
    filter_sizes: A `Tensor` of type `int32`.
      An integer vector representing the tensor shape of `filter`,
      where `filter` is a 4-D
      `[filter_height, filter_width, in_channels, out_channels]` tensor.
    out_backprop: A `Tensor`. Must have the same type as `input`.
      4-D with shape `[batch, out_height, out_width, out_channels]`.
      Gradients w.r.t. the output of the convolution.
    strides: A list of `ints`.
      The stride of the sliding window for each dimension of the input
      of the convolution. Must be in the same order as the dimension specified
      with format.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. When explicit padding is used and
      data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top,
      pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used
      and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.
    data_format: An optional `string` from: `"NHWC", "NCHW"`.
      Defaults to `"NHWC"`.
      Specify the data format of the input and output data. With the
      default format "NHWC", the data is stored in the order of:
          [batch, in_height, in_width, in_channels].
      Alternatively, the format could be "NCHW", the data storage order of:
          [batch, in_channels, in_height, in_width].
    dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.
      1-D tensor of length 4.  The dilation factor for each dimension of
      `input`. If set to k > 1, there will be k-1 skipped cells between each
      filter element on that dimension. The dimension order is determined by
      the value of `data_format`, see above for details. Dilations in the batch
      and depth dimensions must be 1.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `input`.
  )r   r   conv2d_backprop_filter)
r@   filter_sizesrM  rF   rD   rB  rE   r   r9   r   s
             r;   rU  rU  	  s?    n  /w7'		*	*\<';Ki
7 7r=   znn.conv2d_backprop_inputc
                     t        j                  d|	d|      }t        |      \  }}
t        j                  | ||||||
|||
      S )aN	  Computes the gradients of convolution with respect to the input.

  Args:
    input_sizes: A `Tensor` of type `int32`.
      An integer vector representing the shape of `input`,
      where `input` is a 4-D `[batch, height, width, channels]` tensor.
    filter: A `Tensor`. Must be one of the following types:
      `half`, `bfloat16`, `float32`, `float64`.
      4-D with shape
      `[filter_height, filter_width, in_channels, out_channels]`.
    out_backprop: A `Tensor`. Must have the same type as `filter`.
      4-D with shape `[batch, out_height, out_width, out_channels]`.
      Gradients w.r.t. the output of the convolution.
    strides: A list of `ints`.
      The stride of the sliding window for each dimension of the input
      of the convolution. Must be in the same order as the dimension specified
      with format.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. When explicit padding is used and
      data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top,
      pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used
      and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.
    data_format: An optional `string` from: `"NHWC", "NCHW"`.
      Defaults to `"NHWC"`.
      Specify the data format of the input and output data. With the
      default format "NHWC", the data is stored in the order of:
          [batch, in_height, in_width, in_channels].
      Alternatively, the format could be "NCHW", the data storage order of:
          [batch, in_channels, in_height, in_width].
    dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.
      1-D tensor of length 4.  The dilation factor for each dimension of
      `input`. If set to k > 1, there will be k-1 skipped cells between each
      filter element on that dimension. The dimension order is determined by
      the value of `data_format`, see above for details. Dilations in the batch
      and depth dimensions must be 1.
    name: A name for the operation (optional).
    filters: Alias for filter.

  Returns:
    A `Tensor`. Has the same type as `filter`.
  rf   rB   )r   r   r   r   rN  )rL  rB   rM  rF   rD   rB  rE   r   r9   rf   r   s              r;   rN  rN  	  sX    r 11(F,&.w7'		)	)6<';Ki
7 7r=   znn.conv2d_transposec
                     t        d|d|       } t        d|d|      }t        j                  |d| ||g      5 }t        | ||||||	|      cddd       S # 1 sw Y   yxY w)aF	  The transpose of `conv2d`.

  This operation is sometimes called "deconvolution" after
  (Zeiler et al., 2010), but is really the transpose (gradient) of `conv2d`
  rather than an actual deconvolution.

  Args:
    value: A 4-D `Tensor` of type `float` and shape
      `[batch, height, width, in_channels]` for `NHWC` data format or
      `[batch, in_channels, height, width]` for `NCHW` data format.
    filter: A 4-D `Tensor` with the same type as `value` and shape
      `[height, width, output_channels, in_channels]`.  `filter`'s
      `in_channels` dimension must match that of `value`.
    output_shape: A 1-D `Tensor` representing the output shape of the
      deconvolution op.
    strides: An int or list of `ints` that has length `1`, `2` or `4`.  The
      stride of the sliding window for each dimension of `input`. If a single
      value is given it is replicated in the `H` and `W` dimension. By default
      the `N` and `C` dimensions are set to 0. The dimension order is determined
      by the value of `data_format`, see below for details.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
      See the "returns" section of `tf.nn.convolution` for details.
    data_format: A string. 'NHWC' and 'NCHW' are supported.
    name: Optional name for the returned tensor.
    input: Alias for value.
    filters: Alias for filter.
    dilations: An int or list of `ints` that has length `1`, `2` or `4`,
      defaults to 1. The dilation factor for each dimension of`input`. If a
      single value is given it is replicated in the `H` and `W` dimension. By
      default the `N` and `C` dimensions are set to 1. If set to k > 1, there
      will be k-1 skipped cells between each filter element on that dimension.
      The dimension order is determined by the value of `data_format`, see above
      for details. Dilations in the batch and depth dimensions if a 4-d tensor
      must be 1.

  Returns:
    A `Tensor` with the same type as `value`.

  Raises:
    ValueError: If input/output depth does not match `filter`'s shape, or if
      padding is other than `'VALID'` or `'SAME'`.

  References:
    Deconvolutional Networks:
      [Zeiler et al., 2010]
      (https://ieeexplore.ieee.org/abstract/document/5539957)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
  r@   r6   rf   rB   conv2d_transposer   N)r   r	   rG   conv2d_transpose_v2
r6   rB   r   rF   rD   rE   r9   r@   rf   r   s
             r;   rY  rY  7
  sx    | %WeWe
D%%i(FK&
~~d.fl35 
8<
 
 
s   AAc                 ,   t        j                  |d| t        |g      5 }|d}|j                  d      rdnd}t	        |d|d      }t	        |d|d	      }t        |      \  }}	t        j                  ||| |||	|||
	      cddd       S # 1 sw Y   yxY w)a  The transpose of `conv2d`.

  This operation is sometimes called "deconvolution" after
  (Zeiler et al., 2010), but is really the transpose (gradient) of
  `atrous_conv2d` rather than an actual deconvolution.

  Args:
    input: A 4-D `Tensor` of type `float` and shape `[batch, height, width,
      in_channels]` for `NHWC` data format or `[batch, in_channels, height,
      width]` for `NCHW` data format.
    filters: A 4-D `Tensor` with the same type as `input` and shape `[height,
      width, output_channels, in_channels]`.  `filter`'s `in_channels` dimension
      must match that of `input`.
    output_shape: A 1-D `Tensor` representing the output shape of the
      deconvolution op.
    strides: An int or list of `ints` that has length `1`, `2` or `4`.  The
      stride of the sliding window for each dimension of `input`. If a single
      value is given it is replicated in the `H` and `W` dimension. By default
      the `N` and `C` dimensions are set to 0. The dimension order is determined
      by the value of `data_format`, see below for details.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.  When explicit padding is used and data_format is
      `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],
      [pad_left, pad_right], [0, 0]]`. When explicit padding used and
      data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    data_format: A string. 'NHWC' and 'NCHW' are supported.
    dilations: An int or list of `ints` that has length `1`, `2` or `4`,
      defaults to 1. The dilation factor for each dimension of`input`. If a
      single value is given it is replicated in the `H` and `W` dimension. By
      default the `N` and `C` dimensions are set to 1. If set to k > 1, there
      will be k-1 skipped cells between each filter element on that dimension.
      The dimension order is determined by the value of `data_format`, see above
      for details. Dilations in the batch and depth dimensions if a 4-d tensor
      must be 1.
    name: Optional name for the returned tensor.

  Returns:
    A `Tensor` with the same type as `input`.

  Raises:
    ValueError: If input/output depth does not match `filter`'s shape, or if
      padding is other than `'VALID'` or `'SAME'`.

  References:
    Deconvolutional Networks:
      [Zeiler et al., 2010]
      (https://ieeexplore.ieee.org/abstract/document/5539957)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
  rY  Nr"   r   r+   rR   r,   rF   r   )	rL  rB   rM  rF   rD   r   rE   r   r9   )r	   rG   rB   r   r<   r   r   rN  )
r@   rf   r   rF   rD   rE   r   r9   r8   r   s
             r;   rZ  rZ  
  s    B ~~d.fl35 8<k$//5A1MGQyAGiM;GI!0!9G++ +	  s   A!B

Bc                     | j                   j                  }||dk  rt        j                  | ||||||      S t	        | t        j                  t        j                  |||||      d|      S )zEHelper function for `convolution_internal`; handles expanded batches.rS   )rB   rF   rD   rE   r   r9   rB   rF   rD   rE   r   rR   rC  )rI   r\   r   r_   ru   rD  rE  )r@   rf   rF   rD   rE   r   r9   
input_ranks           r;   r  r  
  s     {{*:>   



! 

 
r=   znn.atrous_conv2d_transposec                 *   t        j                  |d| ||g      5 }t        j                  | d      } t        j                  |d      }| j                         j                  d   j                  |j                         d         sVt        d| j                          d| j                         d    d|j                          d	|j                         d    d
	      |dk  rt        d|       |dk(  rt        | ||g d|d      cddd       S t        j                  |d      }|j                         j                  t        j                  dg            st        d|j                                t        |t              rt        |      }t        |t        t        j                  f      ri|j                         j                  d   j                  |d         s:t        d| d|d    d|j                          d|j                         d    d
	      |dk(  r|j                         j                         r|j                         j!                         }nt#        j$                  |      }|d   |d   }	}||dz
  |dz
  z  z   }
|	|	dz
  |dz
  z  z   }|
dz
  }|dz
  }|dz  }||z
  }|dz  }||z
  }n|dk(  r	d}d}d}d}nt        d|       |d   |z   |z   }|d   |z   |z   }|||z  z
  |z  }|||z  z
  |z  }d|gd|gg}t#        j&                  | ||      } ||z  |d   z  ||z   |z  ||z   |z  |d   g}t)        j*                  ||| g ddd      } |||z   g|||z   gg}t#        j,                  | ||      cddd       S # 1 sw Y   yxY w)a  The transpose of `atrous_conv2d`.

  This operation is sometimes called "deconvolution" after
  (Zeiler et al., 2010), but is really the transpose (gradient) of
  `atrous_conv2d` rather than an actual deconvolution.

  Args:
    value: A 4-D `Tensor` of type `float`. It needs to be in the default `NHWC`
      format. Its shape is `[batch, in_height, in_width, in_channels]`.
    filters: A 4-D `Tensor` with the same type as `value` and shape
      `[filter_height, filter_width, out_channels, in_channels]`. `filters`'
      `in_channels` dimension must match that of `value`. Atrous convolution is
      equivalent to standard convolution with upsampled filters with effective
      height `filter_height + (filter_height - 1) * (rate - 1)` and effective
      width `filter_width + (filter_width - 1) * (rate - 1)`, produced by
      inserting `rate - 1` zeros along consecutive elements across the
      `filters`' spatial dimensions.
    output_shape: A 1-D `Tensor` of shape representing the output shape of the
      deconvolution op, of form `[batch, out_height, out_width, out_channels]`.
    rate: A positive int32. The stride with which we sample input values across
      the `height` and `width` dimensions. Equivalently, the rate by which we
      upsample the filter values by inserting zeros across the `height` and
      `width` dimensions. In the literature, the same parameter is sometimes
      called `input stride` or `dilation`.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    name: Optional name for the returned tensor.

  Returns:
    A `Tensor` with the same type as `value`.

  Raises:
    ValueError: If input/output depth does not match `filters`' shape, or if
      padding is other than `'VALID'` or `'SAME'`, or if the `rate` is less
      than one, or if the output_shape is not a tensor with 4 elements.

  References:
    Deconvolutional Networks:
      [Zeiler et al., 2010]
      (https://ieeexplore.ieee.org/abstract/document/5539957)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
  atrous_conv2d_transposer6   rA   rf   rR   zc`value` channel count must be compatible with `filters` input channel count. Received: value.shape=z with channel count r   z with input channel count r   r+   z/`rate` cannot be less than one. Received: rate=rQ  r"   )rF   rD   rE   Nr   r@  z<`output_shape` must have shape (4,). Received: output_shape=r,   zl`output_shape` channel count must be compatible with `filters` output channel count. Received: output_shape=z with output channel count r   r   r   z>`padding` must be either 'VALID' or 'SAME'. Received: padding=)r@   r   
block_size)rL  rB   rM  rF   rD   rE   )r@   r   rb  )r	   rG   rH   r   r   r  r5   rY  r   rz   r/   r1   r0   r   ndarrayry   r|   r   rI   space_to_batchr   rN  batch_to_space)r6   rf   r   r3  rD   r9   output_shape_rC   filter_heightfilter_widthfilter_height_upfilter_width_up
pad_height	pad_widthpad_top
pad_bottompad_left	pad_right	in_heightin_widthpad_bottom_extrapad_right_extraspace_to_batch_padrL  batch_to_space_crops                            r;   ra  ra  
  sn   h ~~d5g|46 nA9=!!%g6E##G)<G??!!!$778I8I8KA8NO227//2C1D E ??,Q/0 1",,.//I #$A	'( ( axHOPPqy


nA nA. )),^LM""$77  !%' 11>1H1H1J0KM N N ,&,'l,rzz 23 %%a(;;LOL<<H> J)!_- .$..011L  "1%&a	)* 	* &					-	-	/((*224 w/$0O\!_\m '-!*;q)II$q(8TAX'FFo#a'j!A%i ag'jahh&i	G	gjhi ,,396 7 7 Q')J6IA)I5H y4//47ho-5O ./!_1EF$$0TCE 	tl1o%	4D(D'M	O	#,l1oK
 ,,E $Z2B%BC$i/&ABD ##.4A[nA nA nAs   C,N	I.N		Nznn.depthwise_conv2d_nativec           
      X    t        |      \  }}t        j                  | |||||||      S )a
  Computes a 2-D depthwise convolution.

  Given an input tensor of shape `[batch, in_height, in_width, in_channels]`
  and a filter / kernel tensor of shape
  `[filter_height, filter_width, in_channels, channel_multiplier]`, containing
  `in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies
  a different filter to each input channel (expanding from 1 channel to
  `channel_multiplier` channels for each), then concatenates the results
  together. Thus, the output has `in_channels * channel_multiplier` channels.

  ```
  for k in 0..in_channels-1
    for q in 0..channel_multiplier-1
      output[b, i, j, k * channel_multiplier + q] =
        sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] *
                          filter[di, dj, k, q]
  ```

  Must have `strides[0] = strides[3] = 1`.  For the most common case of the same
  horizontal and vertices strides, `strides = [1, stride, stride, 1]`.

  Args:
    input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`,
      `float32`, `float64`.
    filter: A `Tensor`. Must have the same type as `input`.
    strides: A list of `ints`. 1-D of length 4.  The stride of the sliding
      window for each dimension of `input`.
    padding: Controls how to pad the image before applying the convolution. Can
      be the string `"SAME"` or `"VALID"` indicating the type of padding
      algorithm to use, or a list indicating the explicit paddings at the start
      and end of each dimension. When explicit padding is used and data_format
      is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],
      [pad_left, pad_right], [0, 0]]`. When explicit padding used and
      data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to
      `"NHWC"`. Specify the data format of the input and output data. With the
      default format "NHWC", the data is stored in the order of: [batch, height,
        width, channels].
      Alternatively, the format could be "NCHW", the data storage order of:
        [batch, channels, height, width].
    dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D
      tensor of length 4.  The dilation factor for each dimension of `input`. If
      set to k > 1, there will be k-1 skipped cells between each filter element
      on that dimension. The dimension order is determined by the value of
      `data_format`, see above for details. Dilations in the batch and depth
      dimensions must be 1.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `input`.
  r   rE   r   r9   )r   r   depthwise_conv2d_native)r@   rB   rF   rD   rE   r   r9   r   s           r;   ry  ry    s@    ~  /w7'		+	+)
 r=   z"nn.depthwise_conv2d_backprop_inputz)nn.depthwise_conv2d_native_backprop_inputc                 Z    t        |      \  }}t        j                  | ||||||||	      S )a	  Computes the gradients of depthwise convolution with respect to the input.

  Args:
    input_sizes: A `Tensor` of type `int32`. An integer vector representing the
      shape of `input`, based on `data_format`.  For example, if `data_format`
      is 'NHWC' then `input` is a 4-D `[batch, height, width, channels]` tensor.
    filter: A `Tensor`. Must be one of the following types: `half`, `bfloat16`,
      `float32`, `float64`. 4-D with shape `[filter_height, filter_width,
      in_channels, depthwise_multiplier]`.
    out_backprop: A `Tensor`. Must have the same type as `filter`. 4-D with
      shape  based on `data_format`. For example, if `data_format` is 'NHWC'
      then out_backprop shape is `[batch, out_height, out_width, out_channels]`.
      Gradients w.r.t. the output of the convolution.
    strides: A list of `ints`. The stride of the sliding window for each
      dimension of the input of the convolution.
    padding: Controls how to pad the image before applying the convolution. Can
      be the string `"SAME"` or `"VALID"` indicating the type of padding
      algorithm to use, or a list indicating the explicit paddings at the start
      and end of each dimension. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information. When explicit padding is used and data_format is
      `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],
      [pad_left, pad_right], [0, 0]]`. When explicit padding used and
      data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to
      `"NHWC"`. Specify the data format of the input and output data. With the
      default format "NHWC", the data is stored in the order of: [batch, height,
        width, channels].
      Alternatively, the format could be "NCHW", the data storage order of:
        [batch, channels, height, width].
    dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D
      tensor of length 4.  The dilation factor for each dimension of `input`. If
      set to k > 1, there will be k-1 skipped cells between each filter element
      on that dimension. The dimension order is determined by the value of
      `data_format`, see above for details. Dilations in the batch and depth
      dimensions must be 1.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `filter`.
  rx  )r   r   &depthwise_conv2d_native_backprop_input)	rL  rB   rM  rF   rD   rE   r   r9   r   s	            r;   r{  r{    sC    v  /w7'		:	:)	
 	r=   z#nn.depthwise_conv2d_backprop_filterz*nn.depthwise_conv2d_native_backprop_filterc                 Z    t        |      \  }}t        j                  | ||||||||	      S )a
  Computes the gradients of depthwise convolution with respect to the filter.

  Args:
    input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`,
      `float32`, `float64`. 4-D with shape based on `data_format`.  For example,
      if `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height,
      in_width, in_channels]` tensor.
    filter_sizes: A `Tensor` of type `int32`. An integer vector representing the
      tensor shape of `filter`, where `filter` is a 4-D `[filter_height,
      filter_width, in_channels, depthwise_multiplier]` tensor.
    out_backprop: A `Tensor`. Must have the same type as `input`. 4-D with shape
      based on `data_format`. For example, if `data_format` is 'NHWC' then
      out_backprop shape is `[batch, out_height, out_width, out_channels]`.
      Gradients w.r.t. the output of the convolution.
    strides: A list of `ints`. The stride of the sliding window for each
      dimension of the input of the convolution.
    padding: Controls how to pad the image before applying the convolution. Can
      be the string `"SAME"` or `"VALID"` indicating the type of padding
      algorithm to use, or a list indicating the explicit paddings at the start
      and end of each dimension. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information. When explicit padding is used and data_format is
      `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],
      [pad_left, pad_right], [0, 0]]`. When explicit padding used and
      data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`.
    data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to
      `"NHWC"`. Specify the data format of the input and output data. With the
      default format "NHWC", the data is stored in the order of: [batch, height,
        width, channels].
      Alternatively, the format could be "NCHW", the data storage order of:
        [batch, channels, height, width].
    dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D
      tensor of length 4.  The dilation factor for each dimension of `input`. If
      set to k > 1, there will be k-1 skipped cells between each filter element
      on that dimension. The dimension order is determined by the value of
      `data_format`, see above for details. Dilations in the batch and depth
      dimensions must be 1.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `input`.
  rx  )r   r   'depthwise_conv2d_native_backprop_filter)	r@   rV  rM  rF   rD   rE   r   r9   r   s	            r;   r}  r}  6  sC    x  /w7'		;	;)	
 	r=   c                     | j                   }t        |dd      }|dk(  rt        |      }|dv rt        j                  | ||||||      S t        | t        j                  t        j                  |||||      d|      S )z7Helper function for `conv3d`; handles expanded batches.rZ   rv   )rS   r@  rR   r,   r+   r   N)rE   r   r9   r^  r@  rC  )rI   rS  r4   r   conv3dru   rD  rE  )	r@   rB   rF   rD   rE   r   r9   rI   rZ   s	            r;   r`   r`     s     ++% %"
%%
b[JE
&&   #	! 
 
r=   z	nn.conv3dr$   c           	      0    |g d}t        | ||||||      S )Nr+   r+   r+   r+   r+   )r`   r   s          r;   	conv3d_v2r    s+     I	w+ )4
1 1r=   r  c           	      T    t        d|d|      }t        j                  | ||||||      S )Nrf   rB   )r   r   r  )r@   rB   rF   rD   rE   r   r9   rf   s           r;   	conv3d_v1r    s8     &i(FK&			VWg{It
E Er=   znn.conv3d_transposec
           
      `    t        d|d|      }t        d|d|       } t        | ||||||	|      S )aA  The transpose of `conv3d`.

  This operation is sometimes called "deconvolution" after
  (Zeiler et al., 2010), but is really the transpose (gradient) of `conv3d`
  rather than an actual deconvolution.

  Args:
    value: A 5-D `Tensor` of type `float` and shape
      `[batch, depth, height, width, in_channels]`.
    filter: A 5-D `Tensor` with the same type as `value` and shape
      `[depth, height, width, output_channels, in_channels]`.  `filter`'s
      `in_channels` dimension must match that of `value`.
    output_shape: A 1-D `Tensor` representing the output shape of the
      deconvolution op.
    strides: A list of ints. The stride of the sliding window for each
      dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
      See the "returns" section of `tf.nn.convolution` for details.
    data_format: A string, either `'NDHWC'` or `'NCDHW`' specifying the layout
      of the input and output tensors. Defaults to `'NDHWC'`.
    name: Optional name for the returned tensor.
    input: Alias of value.
    filters: Alias of filter.
    dilations: An int or list of `ints` that has length `1`, `3` or `5`,
      defaults to 1. The dilation factor for each dimension of`input`. If a
      single value is given it is replicated in the `D`, `H` and `W` dimension.
      By default the `N` and `C` dimensions are set to 1. If set to k > 1, there
      will be k-1 skipped cells between each filter element on that dimension.
      The dimension order is determined by the value of `data_format`, see above
      for details. Dilations in the batch and depth dimensions if a 5-d tensor
      must be 1.

  Returns:
    A `Tensor` with the same type as `value`.

  Raises:
    ValueError: If input/output depth does not match `filter`'s shape, or if
      padding is other than `'VALID'` or `'SAME'`.

  References:
    Deconvolutional Networks:
      [Zeiler et al., 2010]
      (https://ieeexplore.ieee.org/abstract/document/5539957)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
  rf   rB   r@   r6   r   )r   conv3d_transpose_v2r[  s
             r;   conv3d_transposer    sJ    v &i(FK&
$WeWe
D%	
 r=   c                    t        j                  |d| t        |g      5 }|d}|j                  d      rdnd}t	        |d|d      }t	        |d|d	      }t        j                  ||| |||||
      cddd       S # 1 sw Y   yxY w)a  The transpose of `conv3d`.

  This operation is sometimes called "deconvolution" after
  (Zeiler et al., 2010), but is really the transpose (gradient) of `conv3d`
  rather than an actual deconvolution.

  Args:
    input: A 5-D `Tensor` of type `float` and shape `[batch, depth, height,
      width, in_channels]` for `NDHWC` data format or `[batch, in_channels,
      depth, height, width]` for `NCDHW` data format.
    filters: A 5-D `Tensor` with the same type as `input` and shape `[depth,
      height, width, output_channels, in_channels]`.  `filter`'s `in_channels`
      dimension must match that of `input`.
    output_shape: A 1-D `Tensor` representing the output shape of the
      deconvolution op.
    strides: An int or list of `ints` that has length `1`, `3` or `5`.  The
      stride of the sliding window for each dimension of `input`. If a single
      value is given it is replicated in the `D`, `H` and `W` dimension. By
      default the `N` and `C` dimensions are set to 0. The dimension order is
      determined by the value of `data_format`, see below for details.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A string. 'NDHWC' and 'NCDHW' are supported.
    dilations: An int or list of `ints` that has length `1`, `3` or `5`,
      defaults to 1. The dilation factor for each dimension of`input`. If a
      single value is given it is replicated in the `D`, `H` and `W` dimension.
      By default the `N` and `C` dimensions are set to 1. If set to k > 1, there
      will be k-1 skipped cells between each filter element on that dimension.
      The dimension order is determined by the value of `data_format`, see above
      for details. Dilations in the batch and depth dimensions if a 5-d tensor
      must be 1.
    name: Optional name for the returned tensor.

  Returns:
    A `Tensor` with the same type as `input`.

  References:
    Deconvolutional Networks:
      [Zeiler et al., 2010]
      (https://ieeexplore.ieee.org/abstract/document/5539957)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
  r  Nr$   r   r+   r@  rR   rF   r   rK  )r	   rG   rB   r   r<   r   conv3d_backprop_input_v2)	r@   rf   r   rF   rD   rE   r   r9   r8   s	            r;   r  r    s    l ~~d.fl35 8<k$//5A1MGQyAGiM;GI..   s   AA;;Bznn.conv_transposec                    t        j                  |d| t        |g      5 }t        j                  |      r|j
                  d   dz
  }n7t        |t        j                        rt        |      dz
  }nt        d|       d|cxk  rdk  sn t        d| d|dz    d	      t        |dz
     }	 |	| |||||||
      cddd       S # 1 sw Y   yxY w)a
  The transpose of `convolution`.

  This operation is sometimes called "deconvolution" after
  (Zeiler et al., 2010), but is really the transpose (gradient) of `conv3d`
  rather than an actual deconvolution.

  Args:
    input: An N+2 dimensional `Tensor` of shape
      `[batch_size] + input_spatial_shape + [in_channels]` if data_format does
      not start with "NC" (default), or
      `[batch_size, in_channels] + input_spatial_shape` if data_format starts
      with "NC". It must be one of the following types:
      `half`, `bfloat16`, `float32`, `float64`.
    filters: An N+2 dimensional `Tensor` with the same type as `input` and
      shape `spatial_filter_shape + [in_channels, out_channels]`.
    output_shape: A 1-D `Tensor` representing the output shape of the
      deconvolution op.
    strides: An int or list of `ints` that has length `1`, `N` or `N+2`.  The
      stride of the sliding window for each dimension of `input`. If a single
      value is given it is replicated in the spatial dimensions. By default
      the `N` and `C` dimensions are set to 0. The dimension order is determined
      by the value of `data_format`, see below for details.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A string or None.  Specifies whether the channel dimension of
      the `input` and output is the last dimension (default, or if `data_format`
      does not start with "NC"), or the second dimension (if `data_format`
      starts with "NC").  For N=1, the valid values are "NWC" (default) and
      "NCW".  For N=2, the valid values are "NHWC" (default) and "NCHW".
      For N=3, the valid values are "NDHWC" (default) and "NCDHW".
    dilations: An int or list of `ints` that has length `1`, `N` or `N+2`,
      defaults to 1. The dilation factor for each dimension of`input`. If a
      single value is given it is replicated in the spatial dimensions. By
      default the `N` and `C` dimensions are set to 1. If set to k > 1, there
      will be k-1 skipped cells between each filter element on that dimension.
      The dimension order is determined by the value of `data_format`, see above
      for details.
    name: A name for the operation (optional). If not specified "conv_transpose"
      is used.

  Returns:
    A `Tensor` with the same type as `value`.

  References:
    Deconvolutional Networks:
      [Zeiler et al., 2010]
      (https://ieeexplore.ieee.org/abstract/document/5539957)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
  conv_transposer   r,   zL`output_shape` must be a tensor or sized collection. Received: output_shape=r+   rR   zC`output_shape` must be of length 3, 4 or 5. Received: output_shape=r.   r   r   N)r	   rG   rB   r   r  rI   r/   r   r3   r4   r5   CONV_TRANSPOSE_OPS)
r@   rf   r   rF   rD   rE   r   r9   r7   rM   s
             r;   r  r  d  s   z ~~d,fl35 8<l+


Q
!
#a	L/"7"7	8
l
a
a 11=@ A A ;Q;$$0>QUG1FG G 
AaC	 B!  s   BCCznn.bias_addc                    t        j                  |d| |g      5 }|G|j                  d      rd}n3|j                  d      r|j                  d      rd}nt	        d|       t        j                         s9t        j                  | d	
      } t        j                  || j                  d      }t        j                  | |||      cddd       S # 1 sw Y   yxY w)a  Adds `bias` to `value`.

  This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.
  Broadcasting is supported, so `value` may have any number of dimensions.
  Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the
  case where both types are quantized.

  Args:
    value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
      `int16`, `int8`, `complex64`, or `complex128`.
    bias: A 1-D `Tensor` with size matching the channel dimension of `value`.
      Must be the same type as `value` unless `value` is a quantized type,
      in which case a different quantized type may be used.
    data_format: A string. 'N...C' and 'NC...' are supported. If `None` (the
      default) is specified then 'N..C' is assumed.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with the same type as `value`.

  Raises:
    ValueError if data format is unrecognized, if `value` has less than two
    dimensions when `data_format` is 'N..C'/`None` or `value` has less
    then three dimensions when `data_format` is `NC..`, if `bias` does not
    have exactly one dimension (is a vector), or if the size of `bias`
    does not match the size of the channel dimension of `value`.
  BiasAddNr   rW   NCr"   zL`data_format` must be of the form `N...C` or `NC...`. Received: data_format=r@   rA   biasr   r9   )rE   r9   )r	   rG   r   endswithr5   r   executing_eagerlyrH   r   r   bias_add)r6   r  rE   r9   s       r;   r  r    s    < ~~dIt}5 P				%!!#&;+?+?+D ;;F-I J 	J $$&##E8e""4u{{Hdud$OP P Ps   B/CCc                    t        j                  |d| |g      5 }t        j                  | d      } t        j                  || j                  d      }t	        j
                  | ||      cddd       S # 1 sw Y   yxY w)a=  Adds `bias` to `value`.

  This is a deprecated version of bias_add and will soon to be removed.

  This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.
  Broadcasting is supported, so `value` may have any number of dimensions.
  Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the
  case where both types are quantized.

  Args:
    value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
      `int16`, `int8`, `complex64`, or `complex128`.
    bias: A 1-D `Tensor` with size matching the last dimension of `value`.
      Must be the same type as `value` unless `value` is a quantized type,
      in which case a different quantized type may be used.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with the same type as `value`.
  	BiasAddV1r@   rA   r  r  N)r	   rG   rH   r   r   bias_add_v1)r6   r  r9   s      r;   r  r    sk    * ~~dK%7 :4!!%g6E  U[[vFD!!%D9: : :s   AA55A>znn.creluc                     t        j                  |d| g      5 }t        j                  | d      } t        j                  | |  g||      }t        j                  |      cddd       S # 1 sw Y   yxY w)a  Computes Concatenated ReLU.

  Concatenates a ReLU which selects only the positive part of the activation
  with a ReLU which selects only the *negative* part of the activation.
  Note that as a result this non-linearity doubles the depth of the activations.
  Source: [Understanding and Improving Convolutional Neural Networks via
  Concatenated Rectified Linear Units. W. Shang, et
  al.](https://arxiv.org/abs/1603.05201)

  Args:
    features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,
      `int16`, or `int8`.
    name: A name for the operation (optional).
    axis: The axis that the output values are concatenated along. Default is -1.

  Returns:
    A `Tensor` with the same type as `features`.

  References:
    Understanding and Improving Convolutional Neural Networks via Concatenated
    Rectified Linear Units:
      [Shang et al., 2016](http://proceedings.mlr.press/v48/shang16)
      ([pdf](http://proceedings.mlr.press/v48/shang16.pdf))
  CRelufeaturesrA   N)r	   rG   rH   r   r}   r   relu)r  r9   rx   cs       r;   crelur    sf    6 ~~dGhZ0 D$$XJ?H(XI.4@A??1  s   AA**A3c                     t        | ||      S )N)r9   rx   )r  )r  rx   r9   s      r;   crelu_v2r  '  s     
xd	..r=   znn.relu6c                     t        j                  |d| g      5 }t        j                  | d      } t        j                  | |      cddd       S # 1 sw Y   yxY w)a  Computes Rectified Linear 6: `min(max(features, 0), 6)`.

  In comparison with `tf.nn.relu`, relu6 activation functions have shown to
  empirically perform better under low-precision conditions (e.g. fixed point
  inference) by encouraging the model to learn sparse features earlier.
  Source: [Convolutional Deep Belief Networks on CIFAR-10: Krizhevsky et al.,
  2010](http://www.cs.utoronto.ca/~kriz/conv-cifar10-aug2010.pdf).

  For example:

  >>> x = tf.constant([-3.0, -1.0, 0.0, 6.0, 10.0], dtype=tf.float32)
  >>> y = tf.nn.relu6(x)
  >>> y.numpy()
  array([0., 0., 0., 6., 6.], dtype=float32)

  Args:
    features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,
      `int16`, or `int8`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with the same type as `features`.

  References:
    Convolutional Deep Belief Networks on CIFAR-10:
      Krizhevsky et al., 2010
      ([pdf](http://www.cs.utoronto.ca/~kriz/conv-cifar10-aug2010.pdf))
  Relu6r  rA   N)r	   rG   rH   r   relu6)r  r9   s     r;   r  r  .  sP    @ ~~dGhZ0 1D$$XJ?HH401 1 1s   .AAznn.leaky_reluc                    t        j                  |d| |g      5 }t        j                  | d      } | j                  j                  r$t        j                  | t        j                        } t        |t        j                        r|j                         }t        j                  | ||      cddd       S # 1 sw Y   yxY w)aC  Compute the Leaky ReLU activation function.

  Source: [Rectifier Nonlinearities Improve Neural Network Acoustic Models.
  AL Maas, AY Hannun, AY Ng - Proc. ICML, 2013]
  (https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf).

  Args:
    features: A `Tensor` representing preactivation values. Must be one of
      the following types: `float16`, `float32`, `float64`, `int32`, `int64`.
    alpha: Slope of the activation function at x < 0.
    name: A name for the operation (optional).

  Returns:
    The activation value.

  References:
    Rectifier Nonlinearities Improve Neural Network Acoustic Models:
      [Maas et al., 2013]
      (http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.693.1422)
      ([pdf]
      (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.693.1422&rep=rep1&type=pdf))
  	LeakyRelur  rA   )alphar9   N)r	   rG   rH   r   
is_integerr   castr   float32r/   r   rc  itemr   
leaky_relu)r  r  r9   s      r;   r  r  S  s    4 ~~dK(E):; Ct$$XJ?H~~  x8h%$jjle  TBC C Cs   BB77C znn.geluFc                 0   t        j                  |d| g      5  t        j                  | d      } | j                  j                  st        d| j                         |rdt        j                  d| j                        }d| z  dt        j                  d| |t        j                  | d	      z  z   z        z   z  cd
d
d
       S d| z  t        j                  |  t        j                  d| j                        z        z  	 cd
d
d
       S # 1 sw Y   y
xY w)aC  Compute the Gaussian Error Linear Unit (GELU) activation function.

  Gaussian error linear unit (GELU) computes
  `x * P(X <= x)`, where `P(X) ~ N(0, 1)`.
  The (GELU) nonlinearity weights inputs by their value, rather than gates
  inputs by their sign as in ReLU.

  For example:

  >>> x = tf.constant([-3.0, -1.0, 0.0, 1.0, 3.0], dtype=tf.float32)
  >>> y = tf.nn.gelu(x)
  >>> y.numpy()
  array([-0.00404951, -0.15865529,  0.        ,  0.8413447 ,  2.9959507 ],
      dtype=float32)
  >>> y = tf.nn.gelu(x, approximate=True)
  >>> y.numpy()
  array([-0.00363752, -0.15880796,  0.        ,  0.841192  ,  2.9963627 ],
      dtype=float32)

  Args:
    features: A `float Tensor` representing preactivation values.
    approximate: An optional `bool`. Defaults to `False`. Whether to enable
      approximation.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with the same type as `features`.

  Raises:
    ValueError: if `features` is not a floating point `Tensor`.

  References:
    [Gaussian Error Linear Units (GELUs)](https://arxiv.org/abs/1606.08415).
  Gelur  rA   zI`features.dtype` must be a floating point tensor.Received:features.dtype=gHm?g      ?      ?gQ63E?rR   Ng;f?)r	   rG   rH   r   is_floatingr5   r   r  tanhpowerfc)r  approximater9   coeffs       r;   gelur  v  s   L ~~dFXJ/ $$XJ?H>>%%%%-^^$467 7 mmHhnn5e8^
0'%(,,x2K*KKM N NO  MMi(--(:HNNKK  s   B"D=DDc                    t        j                  |       }t        j                  t        j                  |       t	        j
                  |d      gdg      }t        j                  | t        j                  dg|gd            }t        j                         sa| j                         }|O|j                  C|j                         }d}d}|dd D ]  }|d} n||z  } |r||d   g}|j                  |       |S )z>Flattens logits' outer dimensions and keep its last dimension.r+   rv   r   NTF)r   r\   slicerI   r   subtractr{   r}   r   r  r   r   r|   r~   )	logitsr\   last_dim_sizeoutputrI   productproduct_validdr   s	            r;   _flatten_outer_dimsr    s    		$//oof 1 1$ :;aSB-VY%5%5t]6KQ%OP& 
	"	"	$EUZZ3mmoegmSbz !9-

Q,' 
r+&	-r=   c                   	
 ddt        j                  |       } | j                         |dk(  xs |j                  dz
  k(  }|r
 ||       S |}t	        |t
        j                        rt        j                  |      }|dj                   |cxk  rj                  k  sDn t        j                  dddj                    dj                   dj                   d	|       t        j                  |       }t	        |t
        j                        s|d
k  r4||z  }n.t        j                  t        j                  |d
      ||z   |      }t        j                  |       |j                  z  	 | 	t        j                   d            } 	fd
 ||       }t	        |t"              rt#        
fd|D              S  
|      S )a  Helper function for ops that accept and return 2d inputs of same shape.

  It reshapes and transposes the inputs into a 2-D Tensor and then invokes
  the given function. The output would be transposed and reshaped back.
  If the given function returns a tuple of tensors, each of them will be
  transposed and reshaped.

  Args:
    inputs: A non-empty `Tensor`. Must be one of the following types: `half`,
      `float32`, `float64`.
    compute_op: The function to wrap. Must accept the input tensor as its first
      arugment, and a second keyword argument `name`.
    dim: The dimension softmax would be performed on. The default is -1 which
      indicates the last dimension.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same shape as inputs. If compute_op returns multiple
      tensors, each of them have the same shape as the input.
  Raises:
    InvalidArgumentError: if `inputs` is empty or `dim` is beyond the last
      dimension of `inputs`.
  Nc                     t        j                  | t        j                  t        j                  |      |gt        j                  |dz   |      |ggd      |      S )z(Swaps logits's dim_index and last_index.r+   r   rA   r   	transposer}   r   r   )input_tensor	dim_index
last_indexr9   s       r;   
_swap_axisz%_wrap_2d_function.<locals>._swap_axis  s[    NN9%
|NN9q=*5	{
 	  r=   rv   r+   rA   z`dim` must be in the range [z, z) where z9 is the number of dimensions in the input. Received: dim=r   c                 j     | t        j                  d            } | j                         | S )Nr+   rA   )r   r  r~   )r  r  dim_axisr_  r9   rI   s    r;   
fix_outputz%_wrap_2d_function.<locals>.fix_output  s9    (++J:GF UMr=   c              3   .   K   | ]  } |        y wr   rs   )r   r  r  s     r;   r   z$_wrap_2d_function.<locals>.<genexpr>  s     :F#:s   r   )r	   rH   r   rZ   r/   r  r  r   r   r   InvalidArgumentErrorr   r\   wherer   lessr  r1   )inputs
compute_opdimr9   is_last_dimdim_valrZ   outputsr  r  r  r_  rI   s      `    @@@@@r;   _wrap_2d_functionr    s   2   (& 


%7u{{Q 6+f4(('Z&&'((-G%++!F5;;!F

*
*d
&|nBu{{m8;;-  		#$ $ ..
 %	C**	+
Qw	Ulc
//(--Q/uc
BC ~~f%*5;;(fh(9(9*a(HI&  v':':::gr=   z
nn.softmaxzmath.softmaxc                 B    |d}t        | t        j                  ||      S )a  Computes softmax activations.

  Used for multi-class predictions. The sum of all outputs generated by softmax
  is 1.

  This function performs the equivalent of

  ```python
  softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis, keepdims=True)
  ```
  Example usage:

  >>> softmax = tf.nn.softmax([-1, 0., 1.])
  >>> softmax
  <tf.Tensor: shape=(3,), dtype=float32,
  numpy=array([0.09003057, 0.24472848, 0.66524094], dtype=float32)>
  >>> sum(softmax)
  <tf.Tensor: shape=(), dtype=float32, numpy=1.0>

  Args:
    logits: A non-empty `Tensor`. Must be one of the following types: `half`,
      `float32`, `float64`.
    axis: The dimension softmax would be performed on. The default is -1 which
      indicates the last dimension.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type and shape as `logits`.

  Raises:
    InvalidArgumentError: if `logits` is empty or `axis` is beyond the last
      dimension of `logits`.
  rv   )r  r   softmaxr  rx   r9   s      r;   
softmax_v2r  "  s&    H 
\D	6:#5#5tT	BBr=   z#dim is deprecated, use axis insteadr  c                 r    t        j                  d|d|      }|d}t        | t        j                  ||      S )Nrx   r  rv   )r   r   r  r   r  r  rx   r9   r  s       r;   r  r  K  s;     
	/	/eS	I$	\D	6:#5#5tT	BBr=   znn.log_softmaxzmath.log_softmaxc                 r    t        j                  d|d|      }|d}t        | t        j                  ||      S )a  Computes log softmax activations.

  For each batch `i` and class `j` we have

      logsoftmax = logits - log(reduce_sum(exp(logits), axis))

  Args:
    logits: A non-empty `Tensor`. Must be one of the following types: `half`,
      `float32`, `float64`.
    axis: The dimension softmax would be performed on. The default is -1 which
      indicates the last dimension.
    name: A name for the operation (optional).
    dim: Deprecated alias for `axis`.

  Returns:
    A `Tensor`. Has the same type as `logits`. Same shape as `logits`.

  Raises:
    InvalidArgumentError: if `logits` is empty or `axis` is beyond the last
      dimension of `logits`.
  rx   r  rv   )r   r   r  r   log_softmaxr  s       r;   r  r  X  s;    4 
	/	/eS	I$	\D	6:#9#94	FFr=   c                 B    |d}t        | t        j                  ||      S )al  Computes log softmax activations.

  For each batch `i` and class `j` we have

      logsoftmax = logits - log(reduce_sum(exp(logits), axis))

  Args:
    logits: A non-empty `Tensor`. Must be one of the following types: `half`,
      `float32`, `float64`.
    axis: The dimension softmax would be performed on. The default is -1 which
      indicates the last dimension.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `logits`. Same shape as `logits`.

  Raises:
    InvalidArgumentError: if `logits` is empty or `axis` is beyond the last
      dimension of `logits`.
  rv   )r  r   r  r  s      r;   log_softmax_v2r  x  s%    . 
\D	6:#9#94	FFr=   c                 4    ||t        d|  d| d|       y )Nz0Both `labels` and `logits` must be provided for zReceived: labels=z and logits=)r5   )r9   labelsr  s      r;   _ensure_xent_argsr    s9    ^v~
Gv(VHF G G &r=   z$nn.softmax_cross_entropy_with_logitsc                      t        | |||      S )a	  Computes softmax cross entropy between `logits` and `labels`.

  Measures the probability error in discrete classification tasks in which the
  classes are mutually exclusive (each entry is in exactly one class).  For
  example, each CIFAR-10 image is labeled with one and only one label: an image
  can be a dog or a truck, but not both.

  **NOTE:**  While the classes are mutually exclusive, their probabilities
  need not be.  All that is required is that each row of `labels` is
  a valid probability distribution.  If they are not, the computation of the
  gradient will be incorrect.

  If using exclusive `labels` (wherein one and only
  one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.

  Usage:

  >>> logits = [[4.0, 2.0, 1.0], [0.0, 5.0, 1.0]]
  >>> labels = [[1.0, 0.0, 0.0], [0.0, 0.8, 0.2]]
  >>> tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)
  <tf.Tensor: shape=(2,), dtype=float32,
  numpy=array([0.16984604, 0.82474494], dtype=float32)>

  **WARNING:** This op expects unscaled logits, since it performs a `softmax`
  on `logits` internally for efficiency.  Do not call this op with the
  output of `softmax`, as it will produce incorrect results.

  A common use case is to have logits and labels of shape
  `[batch_size, num_classes]`, but higher dimensions are supported, with
  the `axis` argument specifying the class dimension.

  `logits` and `labels` must have the same dtype (either `float16`, `float32`,
  or `float64`).

  Backpropagation will happen into both `logits` and `labels`.  To disallow
  backpropagation into `labels`, pass label tensors through `tf.stop_gradient`
  before feeding it to this function.

  **Note that to avoid confusion, it is required to pass only named arguments to
  this function.**

  Args:
    labels: Each vector along the class dimension should hold a valid
      probability distribution e.g. for the case in which labels are of shape
      `[batch_size, num_classes]`, each row of `labels[i]` must be a valid
      probability distribution.
    logits: Per-label activations, typically a linear output. These activation
      energies are interpreted as unnormalized log probabilities.
    axis: The class dimension. Defaulted to -1 which is the last dimension.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` that contains the softmax cross entropy loss. Its type is the
    same as `logits` and its shape is the same as `labels` except that it does
    not have the last dimension of `labels`.
  r  r  rx   r9   )+softmax_cross_entropy_with_logits_v2_helperr  s       r;   $softmax_cross_entropy_with_logits_v2r    s    v 
5FD
: :r=   z'nn.softmax_cross_entropy_with_logits_v2c           	         t        d|d|      }~|d}t        j                  |d|| g      5 }t        j                  |d      }t        j                  | d      } |j                  t
        j                  k(  xs |j                  t
        j                  k(  }|r$t        j                  |t
        j                        n|}t        j                  | |j                        } t        j                  |      }|j                         }|dk7  rd	 }	 |	|||      } |	| ||      } t        j                  |      }
t        |      }t        |       } t!        j"                         r't%        |      }t        j&                  | |z  d
       }nt)        j*                  || |      \  }}t        j,                  |
dgt        j.                  |d
      g      }t        j0                  ||      }t3        j4                         s2|0|j6                  $|j9                         }||= |j;                  |       |r)t        j                  ||j                        cddd       S |cddd       S # 1 sw Y   yxY w)a  Computes softmax cross entropy between `logits` and `labels`.

  Measures the probability error in discrete classification tasks in which the
  classes are mutually exclusive (each entry is in exactly one class).  For
  example, each CIFAR-10 image is labeled with one and only one label: an image
  can be a dog or a truck, but not both.

  **NOTE:**  While the classes are mutually exclusive, their probabilities
  need not be.  All that is required is that each row of `labels` is
  a valid probability distribution.  If they are not, the computation of the
  gradient will be incorrect.

  If using exclusive `labels` (wherein one and only
  one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.

  **WARNING:** This op expects unscaled logits, since it performs a `softmax`
  on `logits` internally for efficiency.  Do not call this op with the
  output of `softmax`, as it will produce incorrect results.

  A common use case is to have logits and labels of shape
  `[batch_size, num_classes]`, but higher dimensions are supported, with
  the `axis` argument specifying the class dimension.

  `logits` and `labels` must have the same dtype (either `float16`, `float32`,
  or `float64`).

  Backpropagation will happen into both `logits` and `labels`.  To disallow
  backpropagation into `labels`, pass label tensors through `tf.stop_gradient`
  before feeding it to this function.

  **Note that to avoid confusion, it is required to pass only named arguments to
  this function.**

  Args:
    labels: Each vector along the class dimension should hold a valid
      probability distribution e.g. for the case in which labels are of shape
      `[batch_size, num_classes]`, each row of `labels[i]` must be a valid
      probability distribution.
    logits: Unscaled log probabilities.
    axis: The class dimension. Defaulted to -1 which is the last dimension.
    name: A name for the operation (optional).
    dim: Deprecated alias for axis.

  Returns:
    A `Tensor` that contains the softmax cross entropy loss. Its type is the
    same as `logits` and its shape is the same as `labels` except that it does
    not have the last dimension of `labels`.
  rx   r  Nrv   !softmax_cross_entropy_with_logitsr  rA   r  c           
          t        j                  | t        j                  t        j                  |      t        j                  |dz   |      |ggd            S )Nr+   r   r  )r   r  r\   s      r;   _move_dim_to_endzEsoftmax_cross_entropy_with_logits_v2_helper.<locals>._move_dim_to_end'  sR    ""y)y1}d3i[  	r=   r+   rw   r   )r   r	   rG   rH   r   r   float16bfloat16r   r  r  r   r\   r   rI   r  r   is_op_determinism_enabledr  
reduce_sumr   r  r  r  r{   r   r  r   r|   r~   )r  r  rx   r9   r  convert_to_float32precise_logitsr_  rI   r  rL   	log_probscostunused_backpropr   s                  r;   r  r    s6   p 
$FD%	=$		\D
~~d?v&( <+/""69F""69F&I&,,&//*I  $6 ]] ;A  ]]6>#7#78F/JE rz (jInj9f//.1K )8N (F '') 0i!!&9"41==d )JJ
&t-dO ??;$,$5$5j!$D#EGLT<0D $$ 



 6mmoe
+
nnU]]4.u< <x y< < <s   HI!I!!I*z
Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.

See `tf.nn.softmax_cross_entropy_with_logits_v2`.
)dateinstructionsc                     t        d|d|      }t        d| |       t        j                  |d|| g      5 }t	        j
                  | d      } ddd       t        | |||      S # 1 sw Y   xY w)	a  Computes softmax cross entropy between `logits` and `labels`.

  Measures the probability error in discrete classification tasks in which the
  classes are mutually exclusive (each entry is in exactly one class).  For
  example, each CIFAR-10 image is labeled with one and only one label: an image
  can be a dog or a truck, but not both.

  **NOTE:**  While the classes are mutually exclusive, their probabilities
  need not be.  All that is required is that each row of `labels` is
  a valid probability distribution.  If they are not, the computation of the
  gradient will be incorrect.

  If using exclusive `labels` (wherein one and only
  one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.

  **WARNING:** This op expects unscaled logits, since it performs a `softmax`
  on `logits` internally for efficiency.  Do not call this op with the
  output of `softmax`, as it will produce incorrect results.

  A common use case is to have logits and labels of shape
  `[batch_size, num_classes]`, but higher dimensions are supported, with
  the `dim` argument specifying the class dimension.

  Backpropagation will happen only into `logits`.  To calculate a cross entropy
  loss that allows backpropagation into both `logits` and `labels`, see
  `tf.nn.softmax_cross_entropy_with_logits_v2`.

  **Note that to avoid confusion, it is required to pass only named arguments to
  this function.**

  Args:
    labels: Each vector along the class dimension should hold a valid
      probability distribution e.g. for the case in which labels are of shape
      `[batch_size, num_classes]`, each row of `labels[i]` must be a valid
      probability distribution.
    logits: Per-label activations, typically a linear output. These activation
      energies are interpreted as unnormalized log probabilities.
    dim: The class dimension. Defaulted to -1 which is the last dimension.
    name: A name for the operation (optional).
    axis: Alias for dim.

  Returns:
    A `Tensor` that contains the softmax cross entropy loss. Its type is the
    same as `logits` and its shape is the same as `labels` except that it does
    not have the last dimension of `labels`.
  rx   r  r  $softmax_cross_entropy_with_logits_sglabels_stop_gradientrA   Nr  )r   r  r	   rG   r   stop_gradientr  )r  r  r  r9   rx   s        r;   r  r  ]  s    n 	#64<#7H
~~dBv&( J+/$$V2HIFJ 
.F4
9 9	J Js   A$$A-c           	         t        j                         rt        |       }t        j                  t        j                  ||d            }t        j                  t        d      | j                        }t        j                  |t        j                  |            }t        j                  t        j                  |       d   |j                        }t        j                  t        j                  t        j                   |d      t        j"                  ||            ||      }|S t%        j&                  | ||      \  }}|S )Nr+   )
batch_dimsNanr   rv   r   rA   )r   r  r  r   negativer   gatherr   constantfloatr   r2  rI   r  r  
logical_orr  greater_equalr   (sparse_softmax_cross_entropy_with_logits)	r  r  r9   r  r  
nan_tensorcost_all_nansclass_countr   s	            r;   0_sparse_softmax_cross_entropy_with_rank_2_logitsr    s    %%'
 v&IY--iANOD %%eEl&,,GJ**:yt7LMM--	 7 ;V\\JK??MM&!$""6;7	9:GOD 
+ AAT#GD!	+r=   z+nn.sparse_softmax_cross_entropy_with_logitsc                 .   t        d| |       t        j                  |d| |g      5  t        j                  |       } t        j                  |      }t	        j
                  |j                        t        j                  k(  r$t        j                  |t        j                        n|}| j                         }t        j                  |       }|j                         xr! |j                         dd j                         }|j                         j                  ,|j                         j                  dk(  rt!        d| d      |j                         j                  }|j                  q|j                  |j                         j                  dz
  k7  rGt!        d	| d
|j"                   d|j                          d
|j                         j"                         |r5||j                         dd k7  rt!        d| d|j                                |j                         j                  dk(  rct%        || |      }|j                  t        j                  k(  r-t        j                  |t        j                        cddd       S |cddd       S g }|sN|j'                  t)        j*                  t        j                  |       t        j                  |      dd              t        j,                  |      5  t        j                  |      t        j"                  |      dz
     }	t        j.                  |d|	g      }t        j.                  | dg      } t%        || |      }t        j.                  ||      }|j1                  |       |j                  t        j                  k(  r6t        j                  |t        j                        cddd       cddd       S |cddd       cddd       S # 1 sw Y   nxY w	 ddd       y# 1 sw Y   yxY w)a?	  Computes sparse softmax cross entropy between `logits` and `labels`.

  Measures the probability error in discrete classification tasks in which the
  classes are mutually exclusive (each entry is in exactly one class).  For
  example, each CIFAR-10 image is labeled with one and only one label: an image
  can be a dog or a truck, but not both.

  **NOTE:**  For this operation, the probability of a given label is considered
  exclusive.  That is, soft classes are not allowed, and the `labels` vector
  must provide a single specific index for the true class for each row of
  `logits` (each minibatch entry).  For soft softmax classification with
  a probability distribution for each entry, see
  `softmax_cross_entropy_with_logits_v2`.

  **WARNING:** This op expects unscaled logits, since it performs a `softmax`
  on `logits` internally for efficiency.  Do not call this op with the
  output of `softmax`, as it will produce incorrect results.

  A common use case is to have logits of shape
  `[batch_size, num_classes]` and have labels of shape
  `[batch_size]`, but higher dimensions are supported, in which
  case the `dim`-th dimension is assumed to be of size `num_classes`.
  `logits` must have the dtype of `float16`, `float32`, or `float64`, and
  `labels` must have the dtype of `int32` or `int64`.

  **Note that to avoid confusion, it is required to pass only named arguments to
  this function.**

  Args:
    labels: `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of
      `labels` and result) and dtype `int32` or `int64`. Each entry in `labels`
      must be an index in `[0, num_classes)`. Other values will raise an
      exception when this op is run on CPU, and return `NaN` for corresponding
      loss and gradient rows on GPU.
    logits: Per-label activations (typically a linear output) of shape
      `[d_0, d_1, ..., d_{r-1}, num_classes]` and dtype `float16`, `float32`, or
      `float64`. These activation energies are interpreted as unnormalized log
      probabilities.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of the same shape as `labels` and of the same type as `logits`
    with the softmax cross entropy loss.

  Raises:
    ValueError: If logits are scalars (need to have rank >= 1) or if the rank
      of the labels is not equal to the rank of the logits minus one.
  r  #SparseSoftmaxCrossEntropyWithLogitsNrv   r   z-`logits` cannot be a scalar. Received logits=`r+   zO`labels.shape.rank` must equal `logits.shape.rank - 1`. Received: labels.shape=rQ   z and logits.shape=z_`labels.shape` must equal `logits.shape` except for the last dimension. Received: labels.shape=r,   rA   )r  r	   rG   rH   r   as_dtyper   r  r   r  r  r   r   rI   ry   rZ   r5   r\   r  r   r   assert_equalcontrol_dependenciesr{   r~   )
r  r  r9   r  labels_static_shapelabels_shapestatic_shapes_fully_definedr  shape_checksnum_classess
             r;   r  r    s   l >O ~~dAv&( ;""6*F""6*F?E@@(X]]66>>:.4  !**,??6*L,,. 	33B002   +0@0@0B0H0HA0M9&
CE E+!!-!!V%5%5%7%=%=%AA$$7#8	 %%&&89I9I9K8L M%%',,-/0 0
 	$v//1#26688K7L M$..0134 4
 1$=
&t-d		'}}T6>>2G; ;J K; ;R L&

 
 oof%oof%cr*,- 
	!	!,	/ OOF+INN6,BQ,FGk (("k9JKn  ".f=
&t-dt\2d
nn()		'}}T6>>2 _; ;v  _; ;^  _; ; ;s>   IP	PA'P;CO5	P!O5"	P5O>	:PPc                     t        | ||      S )a
  Computes sparse softmax cross entropy between `logits` and `labels`.

  Measures the probability error in discrete classification tasks in which the
  classes are mutually exclusive (each entry is in exactly one class).  For
  example, each CIFAR-10 image is labeled with one and only one label: an image
  can be a dog or a truck, but not both.

  Note:  For this operation, the probability of a given label is considered
  exclusive.  That is, soft classes are not allowed, and the `labels` vector
  must provide a single specific index for the true class for each row of
  `logits` (each minibatch entry).  For soft softmax classification with
  a probability distribution for each entry, see
  `softmax_cross_entropy_with_logits_v2`.

  Warning: This op expects unscaled logits, since it performs a `softmax`
  on `logits` internally for efficiency.  Do not call this op with the
  output of `softmax`, as it will produce incorrect results.

  A common use case is to have logits of shape
  `[batch_size, num_classes]` and have labels of shape
  `[batch_size]`, but higher dimensions are supported, in which
  case the `dim`-th dimension is assumed to be of size `num_classes`.
  `logits` must have the dtype of `float16`, `float32`, or `float64`, and
  `labels` must have the dtype of `int32` or `int64`.

  >>> logits = tf.constant([[2., -5., .5, -.1],
  ...                       [0., 0., 1.9, 1.4],
  ...                       [-100., 100., -100., -100.]])
  >>> labels = tf.constant([0, 3, 1])
  >>> tf.nn.sparse_softmax_cross_entropy_with_logits(
  ...     labels=labels, logits=logits).numpy()
  array([0.29750752, 1.1448325 , 0.        ], dtype=float32)

  To avoid confusion, passing only named arguments to this function is
  recommended.

  Args:
    labels: `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of
      `labels` and result) and dtype `int32` or `int64`. Each entry in `labels`
      must be an index in `[0, num_classes)`. Other values will raise an
      exception when this op is run on CPU, and return `NaN` for corresponding
      loss and gradient rows on GPU.
    logits: Unscaled log probabilities of shape `[d_0, d_1, ..., d_{r-1},
      num_classes]` and dtype `float16`, `float32`, or `float64`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of the same shape as `labels` and of the same type as `logits`
    with the softmax cross entropy loss.

  Raises:
    ValueError: If logits are scalars (need to have rank >= 1) or if the rank
      of the labels is not equal to the rank of the logits minus one.
  r  r  r9   )r  r  s      r;   +sparse_softmax_cross_entropy_with_logits_v2r  7  s    r 
2F
/ /r=   znn.avg_poolznn.avg_pool_v2c                    | j                   t        | j                         dz
  }n,|t        |      dz
  }nt        d| j                    d|       d|cxk  rdk  s!n t        d| j                    d|dz    d      ||dz   }n|j                  d	      rdn|dz   }t	        |||d
      }t	        |||d      }t
        t        j                  t        j                  d}||   }	 |	| |||||      S )a  Performs the avg pooling on the input.

  Each entry in `output` is the mean of the corresponding size `ksize`
  window in `value`.

  Args:
    input:  Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape +
      [num_channels]` if `data_format` does not start with "NC" (default), or
      `[batch_size, num_channels] + input_spatial_shape` if data_format starts
      with "NC". Pooling happens over the spatial dimensions only.
    ksize: An int or list of `ints` that has length `1`, `N` or `N+2`. The size
      of the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `N` or `N+2`. The
      stride of the sliding window for each dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A string. Specifies the channel dimension. For N=1 it can be
      either "NWC" (default) or "NCW", for N=2 it can be either "NHWC" (default)
      or "NCHW" and for N=3 either "NDHWC" (default) or "NCDHW".
    name: Optional name for the operation.

  Returns:
    A `Tensor` of format specified by `data_format`.
    The average pooled output tensor.
  r,   zW`input` must have a static shape or `data_format` must be given. Received: input.shape= and data_format=r+   rR   <`input.shape.rank` must be 3, 4 or 5. Received: input.shape=rQ   r   r   ksizerF   r+   r,   rR   r  rF   rD   rE   r9   )	rI   r4   r5   r   r<   
avg_pool1dr   r)  r*  )
r@   r  rF   rD   rE   r9   r7   r8   avg_pooling_opsrM   s
             r;   avg_pool_v2r  t  s+   : [[EKK1AK1A
	!!& ."m	%& & 
a1
{{m9QUG1	67 7 EM$//5A1q5M
q-
9%'1mY?' 
						/ q"	
 r=   znn.avg_pool2dc           	      .   t        j                  |d| g      5 }t        j                  d|d|       } |d}|j	                  d      rdnd}t        |d	|d
      }t        |d	|d      }t        j                  | |||||      cddd       S # 1 sw Y   yxY w)a  Performs the average pooling on the input.

  Each entry in `output` is the mean of the corresponding size `ksize`
  window in `value`.

  Args:
    value: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type
      `float32`, `float64`, `qint8`, `quint8`, or `qint32`.
    ksize: An int or list of `ints` that has length `1`, `2` or `4`. The size of
      the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `2` or `4`. The
      stride of the sliding window for each dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
      See the "returns" section of `tf.nn.convolution` for details.
    data_format: A string. 'NHWC' and 'NCHW' are supported.
    name: Optional name for the operation.
    input: Alias for value.

  Returns:
    A `Tensor` with the same type as `value`.  The average pooled output tensor.
  AvgPoolr@   r6   Nr"   r   r+   rR   r,   r  rF   r  )r	   rG   r   r   r   r<   r   r)  )r6   r  rF   rD   rE   r9   r@   r8   s           r;   r)  r)    s    2 ~~dIw/ 422(E k$//5A1M%M7;EGQyAG  s   A(BBc           	          t        j                  |d| g      5 }|d}|j                  d      rdnd}t        |d|d      }t        |d|d	      }t	        j
                  | |||||
      cddd       S # 1 sw Y   yxY w)a  Performs the average pooling on the input.

  Each entry in `output` is the mean of the corresponding size `ksize`
  window in `value`.

  Args:
    input: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type
      `float32`, `float64`, `qint8`, `quint8`, or `qint32`.
    ksize: An int or list of `ints` that has length `1`, `2` or `4`. The size of
      the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `2` or `4`. The
      stride of the sliding window for each dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A string. 'NHWC' and 'NCHW' are supported.
    name: Optional name for the operation.

  Returns:
    A `Tensor` with the same type as `value`.  The average pooled output tensor.
  	AvgPool2DNr"   r   r+   rR   r,   r  rF   r  )r	   rG   r   r<   r   r)  r@   r  rF   rD   rE   r9   r8   s          r;   
avg_pool2dr$    s    0 ~~dK%1 Tk$//5A1M%M7;EGQyAG     AA33A<znn.avg_pool1dc           	         t        j                  |d| g      5 }|d}|j                  d      rdnd}dgt        |d|d      z   }dgt        |d|d      z   }|dk(  rdnd}|dk(  rd	nd
}t	        j
                  | |      } t        j                  | |||||      }t	        j                  ||      cddd       S # 1 sw Y   yxY w)a  Performs the average pooling on the input.

  Each entry in `output` is the mean of the corresponding size `ksize`
  window in `value`.

  Note internally this op reshapes and uses the underlying 2d operation.

  Args:
    input: A 3-D `Tensor` of the format specified by `data_format`.
    ksize: An int or list of `ints` that has length `1` or `3`. The size of the
      window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1` or `3`. The stride of
      the sliding window for each dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: An optional string from: "NWC", "NCW". Defaults to "NWC".
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of format specified by `data_format`.
    The max pooled output tensor.
  	AvgPool1DNr!   r   r+   r,   r  rF   r"   rW   r  )	r	   rG   r   r<   r   expand_dims_v2r   r)  r  )	r@   r  rF   rD   rE   r9   r8   expanding_dimr   s	            r;   r  r    s    4 ~~dK%1 4Tk$//5A1MC-q-AAEcM'1mYGGG$-A1M'50&fK$$UM:E  F V]3%4 4 4s   BB99Cznn.avg_pool3dc           	          t        j                  |d| g      5 }|d}|j                  d      rdnd}t        |d|d      }t        |d|d      }t	        j
                  | |||||	      cddd       S # 1 sw Y   yxY w)
a  Performs the average pooling on the input.

  Each entry in `output` is the mean of the corresponding size `ksize`
  window in `value`.

  Args:
    input: A 5-D `Tensor` of shape `[batch, depth, height, width, channels]`
      and type `float32`, `float64`, `qint8`, `quint8`, or `qint32`.
    ksize: An int or list of `ints` that has length `1`, `3` or `5`. The size of
      the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `3` or `5`. The
      stride of the sliding window for each dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A string. 'NDHWC' and 'NCDHW' are supported.
    name: Optional name for the operation.

  Returns:
    A `Tensor` with the same type as `value`.  The average pooled output tensor.
  	AvgPool3DNr$   r   r+   rR   r  rF   r  )r	   rG   r   r<   r   r*  r#  s          r;   r*  r*  <  s    0 ~~dK%1 Tk$//5A1M%M7;EGQyAG    r%  znn.max_poolznn.max_pool_v2c                 v   | j                   t        | j                         dz
  }n,|t        |      dz
  }nt        d| j                    d|       d|cxk  rdk  s!n t        d| j                    d|dz    d      ||dz   }n|j                  d	      rdn|dz   }t	        |t
        t        f      r|d
k(  rt        d|       t        |||d      }t        |||d      }t	        |t
        t        f      r|dk(  rt        d|       t        t        t        j                  d}||   }	 |	| |||||      S )a  Performs max pooling on the input.

  For a given window of `ksize`, takes the maximum value within that window.
  Used for reducing computation and preventing overfitting.

  Consider an example of pooling with 2x2, non-overlapping windows:

  >>> matrix = tf.constant([
  ...     [0, 0, 1, 7],
  ...     [0, 2, 0, 0],
  ...     [5, 2, 0, 0],
  ...     [0, 0, 9, 8],
  ... ])
  >>> reshaped = tf.reshape(matrix, (1, 4, 4, 1))
  >>> tf.nn.max_pool(reshaped, ksize=2, strides=2, padding="SAME")
  <tf.Tensor: shape=(1, 2, 2, 1), dtype=int32, numpy=
  array([[[[2],
           [7]],
          [[5],
           [9]]]], dtype=int32)>

  We can adjust the window size using the `ksize` parameter. For example, if we
  were to expand the window to 3:

  >>> tf.nn.max_pool(reshaped, ksize=3, strides=2, padding="SAME")
  <tf.Tensor: shape=(1, 2, 2, 1), dtype=int32, numpy=
  array([[[[5],
           [7]],
          [[9],
           [9]]]], dtype=int32)>

  We've now picked up two additional large numbers (5 and 9) in two of the
  pooled spots.

  Note that our windows are now overlapping, since we're still moving by 2 units
  on each iteration. This is causing us to see the same 9 repeated twice, since
  it is part of two overlapping windows.

  We can adjust how far we move our window with each iteration using the
  `strides` parameter. Updating this to the same value as our window size
  eliminates the overlap:

  >>> tf.nn.max_pool(reshaped, ksize=3, strides=3, padding="SAME")
  <tf.Tensor: shape=(1, 2, 2, 1), dtype=int32, numpy=
  array([[[[2],
           [7]],
          [[5],
           [9]]]], dtype=int32)>

  Because the window does not neatly fit into our input, padding is added around
  the edges, giving us the same result as when we used a 2x2 window. We can skip
  padding altogether and simply drop the windows that do not fully fit into our
  input by instead passing `"VALID"` to the `padding` argument:

  >>> tf.nn.max_pool(reshaped, ksize=3, strides=3, padding="VALID")
  <tf.Tensor: shape=(1, 1, 1, 1), dtype=int32, numpy=array([[[[5]]]],
   dtype=int32)>

  Now we've grabbed the largest value in the 3x3 window starting from the upper-
  left corner. Since no other windows fit in our input, they are dropped.

  Args:
    input:  Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape +
      [num_channels]` if `data_format` does not start with "NC" (default), or
      `[batch_size, num_channels] + input_spatial_shape` if data_format starts
      with "NC". Pooling happens over the spatial dimensions only.
    ksize: An int or list of `ints` that has length `1`, `N` or `N+2`. The size
      of the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `N` or `N+2`. The
      stride of the sliding window for each dimension of the input tensor.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information. When explicit padding is used and data_format is
      `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],
      [pad_left, pad_right], [0, 0]]`. When explicit padding used and
      data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`. When using explicit
      padding, the size of the paddings cannot be greater than the sliding
      window size.
    data_format: A string. Specifies the channel dimension. For N=1 it can be
      either "NWC" (default) or "NCW", for N=2 it can be either "NHWC" (default)
      or "NCHW" and for N=3 either "NDHWC" (default) or "NCDHW".
    name: Optional name for the operation.

  Returns:
    A `Tensor` of format specified by `data_format`.
    The max pooled output tensor.

  Raises:
    ValueError: If
      - explicit padding is used with an input tensor of rank 5.
      - explicit padding is used with data_format='NCHW_VECT_C'.
  r,   zW`input` must have a static shape or a data format must be given. Received: input.shape=r  r+   rR   r  rQ   r   r   NCHW_VECT_CV`data_format='NCHW_VECT_C'` is not supported with explicit padding. Received: padding=r  rF   zTExplicit padding is not supported with an input tensor of rank 5. Received: padding=r  r  )rI   r4   r5   r   r/   r0   r1   r<   
max_pool1d
max_pool2dr   r(  )
r@   r  rF   rD   rE   r9   r7   r8   max_pooling_opsrM   s
             r;   max_pool_v2r2  f  s   D [[EKK1AK1A
	!!& ."m	%& & 
a1
{{m9QUG1	67 7 EM$//5A1q5M$'K=,H
 <<C9F G G q-
9%'1mY?'4-(Q!V
 <<C9F G G 
				/ q"	
 r=   c           
      \   t        j                  d|d|       } t        j                  |d| g      5 }|d}|j	                  d      rdnd}t        |d	|d
      }t        |d	|d      }t        |t        t        f      r|dk(  rt        d|       t        |      \  }}t        j                  |      r|dk(  s7t        |t        t        t        j                  f      r t        d |D              rt        d|       t        j                   | ||||||      cddd       S # 1 sw Y   yxY w)a	  Performs the max pooling on the input.

  Args:
    value: A 4-D `Tensor` of the format specified by `data_format`.
    ksize: An int or list of `ints` that has length `1`, `2` or `4`.
      The size of the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `2` or `4`.
      The stride of the sliding window for each dimension of the input tensor.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. When explicit padding is used and
      data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top,
      pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used
      and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
      [pad_top, pad_bottom], [pad_left, pad_right]]`. When using explicit
      padding, the size of the paddings cannot be greater than the sliding
      window size.
    data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported.
    name: Optional name for the operation.
    input: Alias for value.

  Returns:
    A `Tensor` of format specified by `data_format`.
    The max pooled output tensor.
  r@   r6   MaxPoolNr"   r   r+   rR   r,   r  rF   r-  r.  r   c              3   &   K   | ]	  }|d k(    yw)r   Nrs   )r   vs     r;   r   zmax_pool.<locals>.<genexpr>&  s     6M!qAv6Mr   z(`ksize` cannot be zero. Received: ksize=r  rF   rD   r   rE   r9   )r   r   r	   rG   r   r<   r/   r0   r1   r5   r   r   isscalarrc  r   r   r'  )	r6   r  rF   rD   rE   r9   r@   r8   r   s	            r;   r'  r'    s5   D 
0
0%%
P%
~~dIw/ 4k$//5A1M%M7;EGQyAG'D%=)k].J >>EYH I I!0!9G	U	
	E5"**-
/366Mu6M3MA%IJJ+!  s   C'D""D+znn.max_pool1dc           
         t        j                  |d| g      5 }t        |t        t        f      r|dk(  rt        d|       |d}|j                  d      rdnd}dgt        |d|d	      z   }dgt        |d|d
      z   }t        |d      \  }}|dk(  rddg|z   }|dk(  rdnd}|dk(  rdnd}t        j                  | |      } t        j                  | ||||||      }	t        j                  |	|      cddd       S # 1 sw Y   yxY w)am  Performs the max pooling on the input.

  Note internally this op reshapes and uses the underlying 2d operation.

  Args:
    input: A 3-D `Tensor` of the format specified by `data_format`.
    ksize: An int or list of `ints` that has length `1` or `3`. The size of the
      window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1` or `3`. The stride of
      the sliding window for each dimension of the input tensor.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information. When explicit padding is used and data_format is
      `"NWC"`, this should be in the form `[[0, 0], [pad_left, pad_right], [0,
      0]]`. When explicit padding used and data_format is `"NCW"`, this should
      be in the form `[[0, 0], [0, 0], [pad_left, pad_right]]`. When using
      explicit padding, the size of the paddings cannot be greater than the
      sliding window size.
    data_format: An optional string from: "NWC", "NCW". Defaults to "NWC".
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of format specified by `data_format`.
    The max pooled output tensor.
  	MaxPool1dr-  r.  Nr!   r   r+   r,   r  rF   rR   r   r   r"   rW   r7  )r	   rG   r/   r0   r1   r5   r   r<   r   r   r(  r   r'  r  )
r@   r  rF   rD   rE   r9   r8   r   r)  r   s
             r;   r/  r/  4  s=   < ~~dK%1 4T'D%=)k].J >>EYH I Ik$//5A1MC-q-AAEcM'1mYGGG!0!!<G*a&#44$-A1M'50&fK$$UM:E  +F V]334 4 4s   CC>>Dznn.max_pool2dc           
      n   t        j                  |d| g      5 }|d}|j                  d      rdnd}t        |d|d      }t        |d|d	      }t	        |t
        t        f      r|d
k(  rt        d|       t        |      \  }}t        j                  | ||||||      cddd       S # 1 sw Y   yxY w)a=  Performs max pooling on 2D spatial data such as images.

  This is a more specific version of `tf.nn.max_pool` where the input tensor
  is 4D, representing 2D spatial data such as images. Using these APIs are
  equivalent

  Downsamples the input images along theirs spatial dimensions (height and
  width) by taking its maximum over an input window defined by `ksize`.
  The window is shifted by `strides` along each dimension.

  For example, for `strides=(2, 2)` and `padding=VALID` windows that extend
  outside of the input are not included in the output:

  >>> x = tf.constant([[1., 2., 3., 4.],
  ...                  [5., 6., 7., 8.],
  ...                  [9., 10., 11., 12.]])
  >>> # Add the `batch` and `channels` dimensions.
  >>> x = x[tf.newaxis, :, :, tf.newaxis]
  >>> result = tf.nn.max_pool2d(x, ksize=(2, 2), strides=(2, 2),
  ...                           padding="VALID")
  >>> result[0, :, :, 0]
  <tf.Tensor: shape=(1, 2), dtype=float32, numpy=
  array([[6., 8.]], dtype=float32)>

  With `padding=SAME`, we get:

  >>> x = tf.constant([[1., 2., 3., 4.],
  ...                  [5., 6., 7., 8.],
  ...                  [9., 10., 11., 12.]])
  >>> x = x[tf.newaxis, :, :, tf.newaxis]
  >>> result = tf.nn.max_pool2d(x, ksize=(2, 2), strides=(2, 2),
  ...                           padding='SAME')
  >>> result[0, :, :, 0]
  <tf.Tensor: shape=(2, 2), dtype=float32, numpy=
  array([[ 6., 8.],
         [10.,12.]], dtype=float32)>

  We can also specify padding explicitly. The following example adds width-1
  padding on all sides (top, bottom, left, right):

  >>> x = tf.constant([[1., 2., 3., 4.],
  ...                  [5., 6., 7., 8.],
  ...                  [9., 10., 11., 12.]])
  >>> x = x[tf.newaxis, :, :, tf.newaxis]
  >>> result = tf.nn.max_pool2d(x, ksize=(2, 2), strides=(2, 2),
  ...                           padding=[[0, 0], [1, 1], [1, 1], [0, 0]])
  >>> result[0, :, :, 0]
  <tf.Tensor: shape=(2, 3), dtype=float32, numpy=
  array([[ 1., 3., 4.],
         [ 9., 11., 12.]], dtype=float32)>

  For more examples and detail, see `tf.nn.max_pool`.

  Args:
    input: A 4-D `Tensor` of the format specified by `data_format`.
    ksize: An int or list of `ints` that has length `1`, `2` or `4`. The size of
      the window for each dimension of the input tensor. If only one integer is
      specified, then we apply the same window for all 4 dims. If two are
      provided then we use those for H, W dimensions and keep N, C dimension
      window size = 1.
    strides: An int or list of `ints` that has length `1`, `2` or `4`. The
      stride of the sliding window for each dimension of the input tensor. If
      only one integer is specified, we apply the same stride to all 4 dims. If
      two are provided we use those for the H, W dimensions and keep N, C of
      stride = 1.
    padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of
      padding algorithm to use, or a list indicating the explicit paddings at
      the start and end of each dimension. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
        for more information. When explicit padding is used and data_format is
        `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],
        [pad_left, pad_right], [0, 0]]`. When explicit padding used and
        data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0],
        [pad_top, pad_bottom], [pad_left, pad_right]]`. When using explicit
        padding, the size of the paddings cannot be greater than the sliding
        window size.
    data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported.
    name: Optional name for the operation.

  Returns:
    A `Tensor` of format specified by `data_format`.
    The max pooled output tensor.

  Raises:
    ValueError: If explicit padding is used with data_format='NCHW_VECT_C'.
  	MaxPool2dNr"   r   r+   rR   r,   r  rF   r-  r.  r7  )r	   rG   r   r<   r/   r0   r1   r5   r   r   r'  )r@   r  rF   rD   rE   r9   r8   r   s           r;   r0  r0  p  s    r ~~dK%1 Tk$//5A1M%M7;EGQyAG'D%=)k].J >>EYH I I!0!9G+  s   BB++B4znn.max_pool3dc           	          t        j                  |d| g      5 }|d}|j                  d      rdnd}t        |d|d      }t        |d|d	      }t	        j
                  | |||||
      cddd       S # 1 sw Y   yxY w)a}  Performs the max pooling on the input.

  Args:
    input: A 5-D `Tensor` of the format specified by `data_format`.
    ksize: An int or list of `ints` that has length `1`, `3` or `5`. The size of
      the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `3` or `5`. The
      stride of the sliding window for each dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC".
      The data format of the input and output data. With the default format
      "NDHWC", the data is stored in the order of: [batch, in_depth, in_height,
        in_width, in_channels]. Alternatively, the format could be "NCDHW", the
      data storage order is: [batch, in_channels, in_depth, in_height,
        in_width].
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of format specified by `data_format`.
    The max pooled output tensor.
  	MaxPool3DNr$   r   r+   r@  rR   r  rF   r  )r	   rG   r   r<   r   r(  r#  s          r;   r(  r(    s    4 ~~dK%1 Tk$//5A1M%M7;EGQyAG    r%  znn.max_pool_with_argmaxc           	          |dk7  rt        d|       t        |ddd      }t        |ddd      }t        j                  | ||||||      S )a8  Performs max pooling on the input and outputs both max values and indices.

  The indices in `argmax` are flattened, so that a maximum value at position
  `[b, y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if
  `include_batch_in_index` is False;
  `((b * height + y) * width + x) * channels + c`
  if `include_batch_in_index` is True.

  The indices returned are always in `[0, height) x [0, width)` before
  flattening, even if padding is involved and the mathematically correct answer
  is outside (either negative or too large).  This is a bug, but fixing it is
  difficult to do in a safe backwards compatible way, especially due to
  flattening.

  Args:
    input: A `Tensor`. Must be one of the following types: `float32`, `float64`,
      `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`,
      `uint32`, `uint64`.
      4-D with shape `[batch, height, width, channels]`.  Input to pool over.
    ksize: An int or list of `ints` that has length `1`, `2` or `4`.
      The size of the window for each dimension of the input tensor.
    strides: An int or list of `ints` that has length `1`, `2` or `4`.
      The stride of the sliding window for each dimension of the
      input tensor.
    padding: A `string` from: `"SAME", "VALID"`.
      The type of padding algorithm to use. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: An optional `string`, must be set to `"NHWC"`. Defaults to
      `"NHWC"`.
      Specify the data format of the input and output data.
    output_dtype: An optional `tf.DType` from: `tf.int32, tf.int64`.
      Defaults to `tf.int64`.
      The dtype of the returned argmax tensor.
    include_batch_in_index: An optional `boolean`. Defaults to `False`.
      Whether to include batch dimension in flattened index of `argmax`.
    name: A name for the operation (optional).

  Returns:
    A tuple of `Tensor` objects (output, argmax).

    output: A `Tensor`. Has the same type as `input`.
    argmax: A `Tensor` of type `output_dtype`.
  r"   r   r,   rR   r  rF   r@   r  rF   rD   Targmaxinclude_batch_in_indexr9   )r5   r<   r   max_pool_with_argmax)r@   r  rF   rD   rE   output_dtyperB  r9   s           r;   max_pool_with_argmax_v2rE    sv    p F
 99DG H H q!W
-%'1a3'		(	(3
 r=   c	           	          |dk7  rt        d|       t        d|d|      }|t        j                  }t	        j
                  | ||||||      S )Nr"   r   rD  rA  r@  )r5   r   r   int64r   rC  )	r@   r  rF   rD   rE   rA  r9   rD  rB  s	            r;   max_pool_with_argmax_v1rH  V  sv     F
 99DG H H 'lIw8'_llG		(	(3
 r=   r   flopsc                 N   t        j                  | |j                  d         }|j                          t        j                  | |j                  d         }|j                          t        j                  | |j                        }|j                          t        |d         }t        |d         }t        |d         }t        |d         }t        j                  |j                         t        j                        }	t        j                  d|	|z  |z  |z  |z  dz        S )z3Calculates the compute resources needed for Conv3D.r   r+   r,   rR   r   rI  r   tensor_shape_from_node_def_namer@   assert_is_fully_definedr9   r2   r   prodr|   rG  r	   OpStats)
graphnoderL   rC   r   filter_timerg  rh  filter_in_depthoutput_counts
             r;   _calc_conv3d_flopsrU  w  s    ::5$**Q-P+%%';;TZZ],&&(;;E499M,&&(LO$+l1o&-\!_%,Q(/--/rxx@,	W|o=K, -/; <>? @ 
B Br=   r   c                 ,   t        j                  | |j                  d         }|j                          t        j                  | |j                  d         }|j                          t        j                  | |j                        }|j                          t        |d         }t        |d         }t        |d         }t        j                  |j                         t        j                        }t        j                  d||z  |z  |z  dz        S )z3Calculates the compute resources needed for Conv2D.r   r+   r,   r   rI  rK  )	rP  rQ  rL   rC   r   rg  rh  rS  rT  s	            r;   _calc_conv_flopsrW    s     ::5$**Q-P+%%';;TZZ],&&(;;E499M,&&(l1o&-\!_%,Q(/--/rxx@,	o%5DqH
K Kr=   DepthwiseConv2dNativec                 
   t        j                  | |j                  d         }|j                          t        j                  | |j                  d         }|j                          t        j                  | |j                        }|j                          t        |d         }t        |d         }t        j                  |j                         t        j                        }t        j                  d||z  |z  dz        S )zBCalculates the compute resources needed for DepthwiseConv2dNative.r   r+   r   rI  r,   rK  rP  rQ  rL   rC   r   rg  rh  rT  s           r;   _calc_depthwise_conv_flopsr[         ::5$**Q-P+%%';;TZZ],&&(;;E499M,&&(l1o&-\!_%,--/rxx@,	W|m;lJQN	PPr=   r  c                     t        j                  | |j                  d         }|j                          t	        j
                  |j                               }t        j                  d|      S )z,Calculates the computing needed for BiasAdd.r   rI  )	r   rL  r@   rM  r   rN  r|   r	   rO  )rP  rQ  rL   input_counts       r;   _calc_bias_add_flopsr_    sR     ::5$**Q-P+%%'++-.+	Wk	**r=   znn.xw_plus_bc                 4   t        j                  |d| ||g      5 }t        j                  | d      } t        j                  |d      }t        j                  |d      }t        j                  | |      }t        |||      cddd       S # 1 sw Y   yxY w)a  Computes matmul(x, weights) + biases.

  Args:
    x: a 2D tensor.  Dimensions typically: batch, in_units
    weights: a 2D tensor.  Dimensions typically: in_units, out_units
    biases: a 1D tensor.  Dimensions: out_units
    name: A name for the operation (optional).  If not specified
      "xw_plus_b" is used.

  Returns:
    A 2-D Tensor computing matmul(x, weights) + biases.
    Dimensions typically: batch, out_units.
  	xw_plus_br   rA   weightsbiasesN)r	   rG   rH   r   matmulr  r   rb  rc  r9   mms        r;   ra  ra    s      ~~dK!Wf)=> +$ac*A##G)<G""69F	G	$BBT*+ + +   A)BBc                 4   t        j                  |d| ||g      5 }t        j                  | d      } t        j                  |d      }t        j                  |d      }t        j                  | |      }t        |||      cddd       S # 1 sw Y   yxY w)a  Computes matmul(x, weights) + biases.

  This is a deprecated version of that will soon be removed.

  Args:
    x: a 2D tensor.  Dimensions typically: batch, in_units
    weights: a 2D tensor.  Dimensions typically: in_units, out_units
    biases: a 1D tensor.  Dimensions: out_units
    name: A name for the operation (optional).  If not specified
      "xw_plus_b_v1" is used.

  Returns:
    A 2-D Tensor computing matmul(x, weights) + biases.
    Dimensions typically: batch, out_units.
  xw_plus_b_v1r   rA   rb  rc  N)r	   rG   rH   r   rd  r  re  s        r;   ri  ri    s      ~~dNQ,@A .Tac*A##G)<G""69F	G	$Br6-. . .rg  c                 r   |t        j                  |       S 	 t        j                  |      }| j                  j                  t        | j                  j                        t        |j                        k(  rg }t        | j                  j                        D ]n  \  }}|j                  |   j                  (|j                  |j                  |j                         G|j                  |j                  |   j                         p t        j                  |      S |S # t        t
        f$ r |cY S w xY wr   )r   rI   r   r  	TypeErrorr5   r   r4   r6  r6   r   rz   )r   noise_shapenoise_shape_new_dimsr   r  s         r;   _get_noise_shapero    s   ??1  ((5L WW\\#aggll"3s<;L;L7M"MHAGGLL) 43			1		#	#	+		0E		"))!,223	4
 ##H--	 Z	  s   D" "D65D6z
nn.dropoutzWPlease use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.	keep_probc                     	 |d|z
  nd}t        j                  d|d|      }|t        d|       t	        | ||||      S # t         $ r t        d|       w xY w)a9  Computes dropout.

  For each element of `x`, with probability `rate`, outputs `0`, and otherwise
  scales up the input by `1 / (1-rate)`. The scaling is such that the expected
  sum is unchanged.

  By default, each element is kept or dropped independently.  If `noise_shape`
  is specified, it must be
  [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
  to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`
  will make independent decisions.  For example, if `shape(x) = [k, l, m, n]`
  and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be
  kept independently and each row and column will be kept or not kept together.

  Args:
    x: A floating point tensor.
    keep_prob: (deprecated) A deprecated alias for `(1-rate)`.
    noise_shape: A 1-D integer `Tensor`, representing the
      shape for randomly generated keep/drop flags.
    seed: A Python integer. Used to create random seeds. See
      `tf.random.set_seed` for behavior.
    name: A name for this operation (optional).
    rate: A scalar `Tensor` with the same type as `x`. The probability that each
      element of `x` is discarded.

  Returns:
    A Tensor of the same shape of `x`.

  Raises:
    ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating
      point tensor.
  Nr  zK`keep_prob` must be a floating point number or Tensor. Received: keep_prob=r3  rp  z(`rate` must be provided. Received: rate=)rl  seedr9   )rk  r5   r   r   
dropout_v2)r   rp  rl  rr  r9   r3  rate_from_keep_probs          r;   dropoutru    s    N9,5,A"y.t
 
	/	/d&
($ 
\
?vF
GG	At4d	KK 
 9
 ,,5;8 9 99s   	A Ac           	      |    t        j                  t        j                        }fd}t	        | |||||d      S )a  Computes dropout: randomly sets elements to zero to prevent overfitting.

  Warning: You should consider using
  `tf.nn.experimental.stateless_dropout` instead of this function. The
  difference between `tf.nn.experimental.stateless_dropout` and this
  function is analogous to the difference between
  `tf.random.stateless_uniform` and `tf.random.uniform`. Please see
  [Random number
  generation](https://www.tensorflow.org/guide/random_numbers) guide
  for a detailed description of the various RNG systems in TF. As the
  guide states, legacy stateful RNG ops like `tf.random.uniform` and
  `tf.nn.dropout` are not deprecated yet but highly discouraged,
  because their states are hard to control.

  Note: The behavior of dropout has changed between TensorFlow 1.x and 2.x.
  When converting 1.x code, please use named arguments to ensure behavior stays
  consistent.

  See also: `tf.keras.layers.Dropout` for a dropout layer.

  [Dropout](https://arxiv.org/abs/1207.0580) is useful for regularizing DNN
  models. Inputs elements are randomly set to zero (and the other elements are
  rescaled). This encourages each node to be independently useful, as it cannot
  rely on the output of other nodes.

  More precisely: With probability `rate` elements of `x` are set to `0`.
  The remaining elements are scaled up by `1.0 / (1 - rate)`, so that the
  expected value is preserved.

  >>> tf.random.set_seed(0)
  >>> x = tf.ones([3,5])
  >>> tf.nn.dropout(x, rate = 0.5, seed = 1).numpy()
  array([[2., 0., 0., 2., 2.],
       [2., 2., 2., 2., 2.],
       [2., 0., 2., 0., 2.]], dtype=float32)

  >>> tf.random.set_seed(0)
  >>> x = tf.ones([3,5])
  >>> tf.nn.dropout(x, rate = 0.8, seed = 1).numpy()
  array([[0., 0., 0., 5., 5.],
       [0., 5., 0., 5., 0.],
       [5., 0., 5., 0., 5.]], dtype=float32)

  >>> tf.nn.dropout(x, rate = 0.0) == x
  <tf.Tensor: shape=(3, 5), dtype=bool, numpy=
    array([[ True,  True,  True,  True,  True],
           [ True,  True,  True,  True,  True],
           [ True,  True,  True,  True,  True]])>


  By default, each element is kept or dropped independently.  If `noise_shape`
  is specified, it must be
  [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
  to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`
  will make independent decisions. This is useful for dropping whole
  channels from an image or sequence. For example:

  >>> tf.random.set_seed(0)
  >>> x = tf.ones([3,10])
  >>> tf.nn.dropout(x, rate = 2/3, noise_shape=[1,10], seed=1).numpy()
  array([[0., 0., 0., 3., 3., 0., 3., 3., 3., 0.],
       [0., 0., 0., 3., 3., 0., 3., 3., 3., 0.],
       [0., 0., 0., 3., 3., 0., 3., 3., 3., 0.]], dtype=float32)

  Args:
    x: A floating point tensor.
    rate: A scalar `Tensor` with the same type as x. The probability
      that each element is dropped. For example, setting rate=0.1 would drop
      10% of input elements.
    noise_shape: A 1-D integer `Tensor`, representing the
      shape for randomly generated keep/drop flags.
    seed: A Python integer. Used to create random seeds. See
      `tf.random.set_seed` for behavior.
    name: A name for this operation (optional).

  Returns:
    A Tensor of the same shape of `x`.

  Raises:
    ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating point
      tensor. `rate=1` is disallowed, because the output would be all zeros,
      which is likely not what was intended.
  rr  c                  0    t        j                          y r   )r
   get_seedrw  s   r;   dummy_rng_stepz"dropout_v2.<locals>.dummy_rng_step  s    r=   ru  r   r3  rl  uniform_samplerrz  r9   r  )rD  rE  r   random_uniform_dropout)r   r3  rl  rr  r9   r|  rz  s      `   r;   rs  rs  6  sA    l %%j&?&?dK/	ADk"1!/d(
* *r=   z!nn.experimental.stateless_dropoutc           	      x    t        j                  t        j                  ||      }d }t	        | |||||d      S )a!  Computes dropout: randomly sets elements to zero to prevent overfitting.

  [Dropout](https://arxiv.org/abs/1207.0580) is useful for regularizing DNN
  models. Inputs elements are randomly set to zero (and the other elements are
  rescaled). This encourages each node to be independently useful, as it cannot
  rely on the output of other nodes.

  More precisely: With probability `rate` elements of `x` are set to `0`.
  The remaining elements are scaled up by `1.0 / (1 - rate)`, so that the
  expected value is preserved.

  >>> x = tf.ones([3,5])
  >>> tf.nn.experimental.stateless_dropout(x, rate=0.5, seed=[1, 0])
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[2., 0., 2., 0., 0.],
         [0., 0., 2., 0., 2.],
         [0., 0., 0., 0., 2.]], dtype=float32)>

  >>> x = tf.ones([3,5])
  >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[1, 0])
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[5., 0., 0., 0., 0.],
         [0., 0., 0., 0., 5.],
         [0., 0., 0., 0., 5.]], dtype=float32)>

  >>> tf.nn.experimental.stateless_dropout(x, rate=0.0, seed=[1, 0]) == x
  <tf.Tensor: shape=(3, 5), dtype=bool, numpy=
  array([[ True,  True,  True,  True,  True],
         [ True,  True,  True,  True,  True],
         [ True,  True,  True,  True,  True]])>


  This function is a stateless version of `tf.nn.dropout`, in the
  sense that no matter how many times you call this function, the same
  `seed` will lead to the same results, and different `seed` will lead
  to different results.

  >>> x = tf.ones([3,5])
  >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[1, 0])
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[5., 0., 0., 0., 0.],
         [0., 0., 0., 0., 5.],
         [0., 0., 0., 0., 5.]], dtype=float32)>
  >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[1, 0])
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[5., 0., 0., 0., 0.],
         [0., 0., 0., 0., 5.],
         [0., 0., 0., 0., 5.]], dtype=float32)>
  >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[2, 0])
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[5., 0., 0., 0., 0.],
         [0., 0., 0., 5., 0.],
         [0., 0., 0., 0., 0.]], dtype=float32)>
  >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[2, 0])
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[5., 0., 0., 0., 0.],
         [0., 0., 0., 5., 0.],
         [0., 0., 0., 0., 0.]], dtype=float32)>

  Compare the above results to those of `tf.nn.dropout` below. The
  second time `tf.nn.dropout` is called with the same seed, it will
  give a different output.

  >>> tf.random.set_seed(0)
  >>> x = tf.ones([3,5])
  >>> tf.nn.dropout(x, rate=0.8, seed=1)
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[0., 0., 0., 5., 5.],
         [0., 5., 0., 5., 0.],
         [5., 0., 5., 0., 5.]], dtype=float32)>
  >>> tf.nn.dropout(x, rate=0.8, seed=1)
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[0., 0., 0., 0., 0.],
         [0., 0., 0., 5., 0.],
         [0., 0., 0., 0., 0.]], dtype=float32)>
  >>> tf.nn.dropout(x, rate=0.8, seed=2)
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[0., 0., 0., 0., 0.],
         [0., 5., 0., 5., 0.],
         [0., 0., 0., 0., 0.]], dtype=float32)>
  >>> tf.nn.dropout(x, rate=0.8, seed=2)
  <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
  array([[0., 0., 0., 0., 0.],
         [5., 0., 5., 0., 5.],
         [0., 5., 0., 0., 5.]], dtype=float32)>

  The difference between this function and `tf.nn.dropout` is
  analogous to the difference between `tf.random.stateless_uniform`
  and `tf.random.uniform`. Please see [Random number
  generation](https://www.tensorflow.org/guide/random_numbers) guide
  for a detailed description of the various RNG systems in TF. As the
  guide states, legacy stateful RNG ops like `tf.random.uniform` and
  `tf.nn.dropout` are not deprecated yet but highly discouraged,
  because their states are hard to control.

  By default, each element is kept or dropped independently.  If `noise_shape`
  is specified, it must be
  [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
  to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`
  will make independent decisions. This is useful for dropping whole
  channels from an image or sequence. For example:

  >>> x = tf.ones([3,10])
  >>> tf.nn.experimental.stateless_dropout(x, rate=2/3, noise_shape=[1,10],
  ...                                      seed=[1, 0])
  <tf.Tensor: shape=(3, 10), dtype=float32, numpy=
  array([[3., 0., 0., 0., 0., 0., 0., 3., 0., 3.],
         [3., 0., 0., 0., 0., 0., 0., 3., 0., 3.],
         [3., 0., 0., 0., 0., 0., 0., 3., 0., 3.]], dtype=float32)>

  Args:
    x: A floating point tensor.
    rate: A scalar `Tensor` with the same type as x. The probability
      that each element is dropped. For example, setting rate=0.1 would drop
      10% of input elements.
    seed: An integer tensor of shape `[2]`. The seed of the random numbers.
    rng_alg: The algorithm used to generate the random numbers
      (default to `"auto_select"`). See the `alg` argument of
      `tf.random.stateless_uniform` for the supported values.
    noise_shape: A 1-D integer `Tensor`, representing the
      shape for randomly generated keep/drop flags.
    name: A name for this operation.

  Returns:
    A Tensor of the same shape and dtype of `x`.

  Raises:
    ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating point
      tensor. `rate=1` is disallowed, because the output would be all zeros,
      which is likely not what was intended.
  )rr  algc                       y r   rs   rs   r=   r;   rz  z)stateless_dropout.<locals>.dummy_rng_step      r=   stateless_dropoutr{  )rD  rE  r   stateless_random_uniformr~  )r   r3  rr  rng_algrl  r9   r|  rz  s           r;   r  r    sF    L %%33$GM/		ADk"1!/d2
4 4r=   znn.experimental.general_dropoutc           	      ,    d }t        | |||||d      S )a	  Computes dropout: randomly sets elements to zero to prevent overfitting.

  Please see `tf.nn.experimental.stateless_dropout` for an overview
  of dropout.

  Unlike `tf.nn.experimental.stateless_dropout`, here you can supply a
  custom sampler function `uniform_sampler` that (given a shape and a
  dtype) generates a random, `Uniform[0, 1)`-distributed tensor (of
  that shape and dtype).  `uniform_sampler` can be
  e.g. `tf.random.stateless_random_uniform` or
  `tf.random.Generator.uniform`.

  For example, if you are using `tf.random.Generator` to generate
  random numbers, you can use this code to do dropouts:

  >>> g = tf.random.Generator.from_seed(7)
  >>> sampler = g.uniform
  >>> x = tf.constant([1.1, 2.2, 3.3, 4.4, 5.5])
  >>> rate = 0.5
  >>> tf.nn.experimental.general_dropout(x, rate, sampler)
  <tf.Tensor: shape=(5,), ..., numpy=array([ 0. ,  4.4,  6.6,  8.8, 11. ], ...)>
  >>> tf.nn.experimental.general_dropout(x, rate, sampler)
  <tf.Tensor: shape=(5,), ..., numpy=array([2.2, 0. , 0. , 8.8, 0. ], ...)>

  It has better performance than using
  `tf.nn.experimental.stateless_dropout` and
  `tf.random.Generator.make_seeds`:

  >>> g = tf.random.Generator.from_seed(7)
  >>> x = tf.constant([1.1, 2.2, 3.3, 4.4, 5.5])
  >>> rate = 0.5
  >>> tf.nn.experimental.stateless_dropout(x, rate, g.make_seeds(1)[:, 0])
  <tf.Tensor: shape=(5,), ..., numpy=array([ 2.2,  4.4,  6.6,  0. , 11. ], ...)>
  >>> tf.nn.experimental.stateless_dropout(x, rate, g.make_seeds(1)[:, 0])
  <tf.Tensor: shape=(5,), ..., numpy=array([2.2, 0. , 6.6, 8.8, 0. ], ...>

  because generating and consuming seeds cost extra
  computation. `tf.nn.experimental.general_dropout` can let you avoid
  them.

  Args:
    x: A floating point tensor.
    rate: A scalar `Tensor` with the same type as x. The probability
      that each element is dropped. For example, setting rate=0.1 would drop
      10% of input elements.
    uniform_sampler: a callable of signature `(shape, dtype) ->
      Tensor[shape, dtype]`, used to generate a tensor of uniformly-distributed
      random numbers in the range `[0, 1)`, of the given shape and dtype.
    noise_shape: A 1-D integer `Tensor`, representing the
      shape for randomly generated keep/drop flags.
    name: A name for this operation.

  Returns:
    A Tensor of the same shape and dtype of `x`.

  Raises:
    ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating point
      tensor. `rate=1` is disallowed, because the output would be all zeros,
      which is likely not what was intended.
  c                       y r   rs   rs   r=   r;   rz  z'general_dropout.<locals>.dummy_rng_stepd  r  r=   general_dropoutr{  )r~  )r   r3  r|  rl  r9   rz  s         r;   r  r  %  s&    ~		ADk"1!/d0
2 2r=   c                    t        j                  ||| g      5 }t        |t        j                        }|r|dk  s|dk\  rt        d|       t        j                  | d      } | j                  }|j                  st        d|       |r|dk(  r |        | cddd       S t        j                         }	t        j                  |      sH|r8d|z
  }
d|
z  }t        j                  ||      }t        j                  | |      }nt        d	|       |j                         j!                  d       |j                  }||k7  r:|j#                  |      st        d
| d|       t        j$                  ||d      }t'        j(                  d|      }t        j*                  | t        j,                  ||            }t/        | |      } |||      }||k\  }t'        j(                  d|      }t1        j2                  |||      }|	s|j5                  | j                                |cddd       S # 1 sw Y   yxY w)a  Shared implementation of the various dropout functions.

  Args:
    x: same as the namesake in `dropout_v2`.
    rate: same as the namesake in `dropout_v2`.
    noise_shape: same as the namesake in `dropout_v2`.
    uniform_sampler: a callable of signature `(shape, dtype) ->
      Tensor`, used to generate a tensor of uniformly-distributed
      random numbers in the range `[0, 1)`, of the given shape and dtype.
    dummy_rng_step: a callable of signature `() -> None`, to make a
      dummy RNG call in the fast path. In the fast path where rate is
      0, we don't need to generate random numbers, but some samplers
      still require you to make an RNG call, to make sure that RNG
      states won't depend on whether the fast path is taken.
    name: same as the namesake in `dropout_v2`.
    default_name: a default name in case `name` is `None`.

  Returns:
    A Tensor of the same shape and dtype of `x`.
  r   r+   zN`rate` must be a scalar tensor or a float in the range [0, 1). Received: rate=r   rA   zS`x.dtype` must be a floating point tensor as `x` will be scaled. Received: x_dtype=Nr   z9`rate` must be a scalar or scalar tensor. Received: rate=zB`x.dtype` must be compatible with `rate.dtype`. Received: x.dtype=z and rate.dtype=r3  )rI   r   )r	   rG   r/   numbersRealr5   rH   r   r  r   r  r   r  r   mulr   assert_has_rankr  r  r   r  real_divsubro  r   where_v2r~   )r   r3  rl  r|  rz  r9   r  is_rate_numberx_dtypeis_executing_eagerlyrp  scaleret
rate_dtype
one_tensorrandom_tensor	keep_maskzero_tensors                     r;   r~  r~  l  s?   , ~~dL1#. 7$gll3N4!8tqy 77;f> ? ?ac*AggG''.i12 2 $!) -7 70 #446!!$'	H	I%%e7;q%(GvNP 	P nn&&q)::j	w	,,W5##*)+;J<IJ J   wV<''9j!!!\%5%5j$%GHc"1k2K $+WEM%I&&q8K


Y[
9C	mmAKKM"o7 7 7s   BH5$FH55H>z
math.top_kznn.top_kr+   c                 6    t        j                  | ||||      S )a  Finds values and indices of the `k` largest entries for the last dimension.

  If the input is a vector (rank=1), finds the `k` largest entries in the vector
  and outputs their values and indices as vectors.  Thus `values[j]` is the
  `j`-th largest entry in `input`, and its index is `indices[j]`.

  >>> result = tf.math.top_k([1, 2, 98, 1, 1, 99, 3, 1, 3, 96, 4, 1],
  ...                         k=3)
  >>> result.values.numpy()
  array([99, 98, 96], dtype=int32)
  >>> result.indices.numpy()
  array([5, 2, 9], dtype=int32)

  For matrices (resp. higher rank input), computes the top `k` entries in each
  row (resp. vector along the last dimension).  Thus,

  >>> input = tf.random.normal(shape=(3,4,5,6))
  >>> k = 2
  >>> values, indices  = tf.math.top_k(input, k=k)
  >>> values.shape.as_list()
  [3, 4, 5, 2]
  >>>
  >>> values.shape == indices.shape == input.shape[:-1] + [k]
  True

  The indices can be used to `gather` from a tensor who's shape matches `input`.

  >>> gathered_values = tf.gather(input, indices, batch_dims=-1)
  >>> assert tf.reduce_all(gathered_values == values)

  If two elements are equal, the lower-index element appears first.

  >>> result = tf.math.top_k([1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0],
  ...                        k=3)
  >>> result.indices.numpy()
  array([0, 1, 3], dtype=int32)
  
  By default, indices are returned as type `int32`, however, this can be changed
  by specifying the `index_type`.
  
  >>> result = tf.math.top_k([1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0],
  ...                        k=3, index_type=tf.int16)
  >>> result.indices.numpy()
  array([0, 1, 3], dtype=int16)

  Args:
    input: 1-D or higher `Tensor` with last dimension at least `k`.
    k: 0-D `Tensor` of type `int16`, `int32` or `int64`.  Number of top element
      to look for along the last dimension (along each row for matrices).
    sorted: If true the resulting `k` elements will be sorted by the values in
      descending order.
    index_type: Optional dtype for output indices.
    name: Optional name for the operation.

  Returns:
    A tuple with two named fields:
    values: The `k` largest elements along each last dimensional slice.
    indices: The indices of `values` within the last dimension of `input`.
  )kr   
index_typer9   )r   top_kv2)r@   r  r   r  r9   s        r;   top_kr    s#    | 
		qJT
 r=   zmath.approx_max_kznn.approx_max_kc           
      <    t        j                  | |||d|||      S )a8  Returns max `k` values and their indices of the input `operand` in an approximate manner.

  See https://arxiv.org/abs/2206.14286 for the algorithm details. This op is
  only optimized on TPU currently.

  Args:
    operand : Array to search for max-k. Must be a floating number type.
    k : Specifies the number of max-k.
    reduction_dimension : Integer dimension along which to search. Default: -1.
    recall_target : Recall target for the approximation.
    reduction_input_size_override : When set to a positive value, it overrides
      the size determined by `operand[reduction_dim]` for evaluating the recall.
      This option is useful when the given `operand` is only a subset of the
      overall computation in SPMD or distributed pipelines, where the true input
      size cannot be deferred by the `operand` shape.
    aggregate_to_topk : When true, aggregates approximate results to top-k. When
      false, returns the approximate results. The number of the approximate
      results is implementation defined and is greater equals to the specified
      `k`.
    name: Optional name for the operation.

  Returns:
    Tuple of two arrays. The arrays are the max `k` values and the
    corresponding indices along the `reduction_dimension` of the input
    `operand`. The arrays' dimensions are the same as the input `operand`
    except for the `reduction_dimension`: when `aggregate_to_topk` is true,
    the reduction dimension is `k`; otherwise, it is greater equals to `k`
    where the size is implementation-defined.

  We encourage users to wrap `approx_max_k` with jit. See the following
  example for maximal inner production search (MIPS):

  >>> import tensorflow as tf
  >>> @tf.function(jit_compile=True)
  ... def mips(qy, db, k=10, recall_target=0.95):
  ...   dists = tf.einsum('ik,jk->ij', qy, db)
  ...   # returns (f32[qy_size, k], i32[qy_size, k])
  ...   return tf.nn.approx_max_k(dists, k=k, recall_target=recall_target)
  >>>
  >>> qy = tf.random.uniform((256,128))
  >>> db = tf.random.uniform((2048,128))
  >>> dot_products, neighbors = mips(qy, db, k=20)
  Tr  reduction_dimensionrecall_targetis_max_kreduction_input_size_overrideaggregate_to_topkr9   r   approx_top_koperandr  r  r  r  r  r9   s          r;   approx_max_kr    s0    h 
	 	 	-!$A)
 r=   zmath.approx_min_kznn.approx_min_kc           
      <    t        j                  | |||d|||      S )a5	  Returns min `k` values and their indices of the input `operand` in an approximate manner.

  See https://arxiv.org/abs/2206.14286 for the algorithm details. This op is
  only optimized on TPU currently.

  Args:
    operand : Array to search for min-k. Must be a floating number type.
    k : Specifies the number of min-k.
    reduction_dimension: Integer dimension along which to search. Default: -1.
    recall_target: Recall target for the approximation.
    reduction_input_size_override : When set to a positive value, it overrides
      the size determined by `operand[reduction_dim]` for evaluating the recall.
      This option is useful when the given `operand` is only a subset of the
      overall computation in SPMD or distributed pipelines, where the true input
      size cannot be deferred by the `operand` shape.
    aggregate_to_topk: When true, aggregates approximate results to top-k. When
      false, returns the approximate results. The number of the approximate
      results is implementation defined and is greater equals to the specified
      `k`.
    name: Optional name for the operation.

  Returns:
    Tuple of two arrays. The arrays are the least `k` values and the
    corresponding indices along the `reduction_dimension` of the input
    `operand`.  The arrays' dimensions are the same as the input `operand`
    except for the `reduction_dimension`: when `aggregate_to_topk` is true,
    the reduction dimension is `k`; otherwise, it is greater equals to `k`
    where the size is implementation-defined.

  We encourage users to wrap `approx_min_k` with jit. See the following example
  for nearest neighbor search over the squared l2 distance:

  >>> import tensorflow as tf
  >>> @tf.function(jit_compile=True)
  ... def l2_ann(qy, db, half_db_norms, k=10, recall_target=0.95):
  ...   dists = half_db_norms - tf.einsum('ik,jk->ij', qy, db)
  ...   return tf.nn.approx_min_k(dists, k=k, recall_target=recall_target)
  >>>
  >>> qy = tf.random.uniform((256,128))
  >>> db = tf.random.uniform((2048,128))
  >>> half_db_norms = tf.norm(db, axis=1) / 2
  >>> dists, neighbors = l2_ann(qy, db, half_db_norms)

  In the example above, we compute `db_norms/2 - dot(qy, db^T)` instead of
  `qy^2 - 2 dot(qy, db^T) + db^2` for performance reason. The former uses less
  arithmetics and produces the same set of neighbors.
  Fr  r  r  s          r;   approx_min_kr  >  s0    p 
	 	 	-!$A)
 r=   c                 4    t        j                  | |||      S )a  Finds values of the `n`-th smallest value for the last dimension.

  Note that n is zero-indexed.

  If the input is a vector (rank-1), finds the entries which is the nth-smallest
  value in the vector and outputs their values as scalar tensor.

  For matrices (resp. higher rank input), computes the entries which is the
  nth-smallest value in each row (resp. vector along the last dimension). Thus,

      values.shape = input.shape[:-1]

  Args:
    input: 1-D or higher `Tensor` with last dimension at least `n+1`.
    n: A `Tensor` of type `int32`.
      0-D. Position of sorted vector to select along the last dimension (along
      each row for matrices). Valid range of n is `[0, input.shape[:-1])`
    reverse: An optional `bool`. Defaults to `False`.
      When set to True, find the nth-largest value in the vector and vice
      versa.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `input`.
    The `n`-th order statistic along each last dimensional slice.
  )reverser9   )r   nth_element)r@   r7   r  r9   s       r;   r  r    s    6 
		q'	EEr=   znn.fractional_max_poolzM`seed2` and `deterministic` args are deprecated.  Use fractional_max_pool_v2.c           
          t        j                         r|r|r|st        d| d| d|       t        j                  | |||||||      S )a   Performs fractional max pooling on the input.

  This is a deprecated version of `fractional_max_pool`.

  Fractional max pooling is slightly different than regular max pooling.  In
  regular max pooling, you downsize an input set by taking the maximum value of
  smaller N x N subsections of the set (often 2x2), and try to reduce the set by
  a factor of N, where N is an integer.  Fractional max pooling, as you might
  expect from the word "fractional", means that the overall reduction ratio N
  does not have to be an integer.

  The sizes of the pooling regions are generated randomly but are fairly
  uniform.  For example, let's look at the height dimension, and the constraints
  on the list of rows that will be pool boundaries.

  First we define the following:

  1.  input_row_length : the number of rows from the input set
  2.  output_row_length : which will be smaller than the input
  3.  alpha = input_row_length / output_row_length : our reduction ratio
  4.  K = floor(alpha)
  5.  row_pooling_sequence : this is the result list of pool boundary rows

  Then, row_pooling_sequence should satisfy:

  1.  a[0] = 0 : the first value of the sequence is 0
  2.  a[end] = input_row_length : the last value of the sequence is the size
  3.  K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size
  4.  length(row_pooling_sequence) = output_row_length+1

  Args:
    value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.
    pooling_ratio: A list of `floats` that has length >= 4.  Pooling ratio for
      each dimension of `value`, currently only supports row and col dimension
      and should be >= 1.0. For example, a valid pooling ratio looks like [1.0,
      1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't
      allow pooling on batch and channels dimensions.  1.44 and 1.73 are pooling
      ratio on height and width dimensions respectively.
    pseudo_random: An optional `bool`.  Defaults to `False`. When set to `True`,
      generates the pooling sequence in a pseudorandom fashion, otherwise, in a
      random fashion. Check (Graham, 2015) for difference between
      pseudorandom and random.
    overlapping: An optional `bool`.  Defaults to `False`.  When set to `True`,
      it means when pooling, the values at the boundary of adjacent pooling
      cells are used by both cells. For example:
      `index  0  1  2  3  4`
      `value  20 5  16 3  7`
      If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used
      twice.  The result would be [20, 16] for fractional max pooling.
    deterministic: An optional `bool`.  Deprecated; use `fractional_max_pool_v2`
      instead.
    seed: An optional `int`.  Defaults to `0`.  If set to be non-zero, the
      random number generator is seeded by the given seed.  Otherwise it is
      seeded by a random seed.
    seed2: An optional `int`.  Deprecated; use `fractional_max_pool_v2` instead.
    name: A name for the operation (optional).

  Returns:
  A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,
  `col_pooling_sequence`).
    output: Output `Tensor` after fractional max pooling.  Has the same type as
      `value`.
    row_pooling_sequence: A `Tensor` of type `int64`.
    col_pooling_sequence: A `Tensor` of type `int64`.

  Raises:
    ValueError: If op determinism is enabled and either the seeds are not set or
      the "deterministic" argument is False.

  References:
    Fractional Max-Pooling:
      [Graham, 2015](https://arxiv.org/abs/1412.6071)
      ([pdf](https://arxiv.org/pdf/1412.6071.pdf))
  ztf.compat.v1.nn.fractional_max_pool requires "seed" and "seed2" to be non-zero and "deterministic" to be true when op determinism is enabled. Please pass in such values, e.g. by passing"seed=1, seed2=1, deterministic=True". Got: seed=z, seed2=z, deterministic=)r   r  r5   r   fractional_max_poolr6   pooling_ratiopseudo_randomoverlappingdeterministicrr  seed2r9   s           r;   r  r    sp    l %%'U1>
< =A6 B'		89 9 
	'	'}m(3]D%(,
. .r=   c           
         t        |t        t        f      r9|d   dk7  s|d   dk7  rt        d|       |D ]  }|dk  s	t        d|        n7t        |t        t
        f      r|dk  rt        d|       t        d|       t        |dd	d
      }|dk(  r@t        j                         rt        d| d      t        j                  | |||ddd|      S t        j                  |      \  }}t        j                  | |||d|||      S )a  Performs fractional max pooling on the input.

  Fractional max pooling is slightly different than regular max pooling.  In
  regular max pooling, you downsize an input set by taking the maximum value of
  smaller N x N subsections of the set (often 2x2), and try to reduce the set by
  a factor of N, where N is an integer.  Fractional max pooling, as you might
  expect from the word "fractional", means that the overall reduction ratio N
  does not have to be an integer.

  The sizes of the pooling regions are generated randomly but are fairly
  uniform.  For example, let's look at the height dimension, and the constraints
  on the list of rows that will be pool boundaries.

  First we define the following:

  1.  input_row_length : the number of rows from the input set
  2.  output_row_length : which will be smaller than the input
  3.  alpha = input_row_length / output_row_length : our reduction ratio
  4.  K = floor(alpha)
  5.  row_pooling_sequence : this is the result list of pool boundary rows

  Then, row_pooling_sequence should satisfy:

  1.  a[0] = 0 : the first value of the sequence is 0
  2.  a[end] = input_row_length : the last value of the sequence is the size
  3.  K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size
  4.  length(row_pooling_sequence) = output_row_length+1

  Args:
    value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.
    pooling_ratio: An int or list of `ints` that has length `1`, `2` or `4`.
      Pooling ratio for each dimension of `value`, currently only supports row
      and col dimension and should be >= 1.0. For example, a valid pooling ratio
      looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements must be 1.0
      because we don't allow pooling on batch and channels dimensions.  1.44 and
      1.73 are pooling ratio on height and width dimensions respectively.
    pseudo_random: An optional `bool`.  Defaults to `False`. When set to `True`,
      generates the pooling sequence in a pseudorandom fashion, otherwise, in a
      random fashion. Check paper (Graham, 2015) for difference between
      pseudorandom and random.
    overlapping: An optional `bool`.  Defaults to `False`.  When set to `True`,
      it means when pooling, the values at the boundary of adjacent pooling
      cells are used by both cells. For example:
      `index  0  1  2  3  4`
      `value  20 5  16 3  7`
      If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used
      twice.  The result would be [20, 16] for fractional max pooling.
    seed: An optional `int`.  Defaults to `0`.  If set to be non-zero, the
      random number generator is seeded by the given seed.  Otherwise it is
      seeded by a random seed.
    name: A name for the operation (optional).

  Returns:
  A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,
  `col_pooling_sequence`).
    output: Output `Tensor` after fractional max pooling.  Has the same type as
      `value`.
    row_pooling_sequence: A `Tensor` of type `int64`.
    col_pooling_sequence: A `Tensor` of type `int64`.

  Raises:
    ValueError: If no seed is specified and op determinism is enabled.

  References:
    Fractional Max-Pooling:
      [Graham, 2015](https://arxiv.org/abs/1412.6071)
      ([pdf](https://arxiv.org/pdf/1412.6071.pdf))
  r   r  rv   z\`pooling_ratio` should have first and last elements with value 1.0. Received: pooling_ratio=zC`pooling_ratio` elements should be >= 1.0. Received: pooling_ratio=z:`pooling_ratio` should be >= 1.0. Received: pooling_ratio=zL`pooling_ratio` should be an int or a list of ints. Received: pooling_ratio=r,   rR   r  zmtf.nn.fractional_max_pool requires a non-zero seed to be passed in when determinism is enabled, but got seed=z;. Please pass in a non-zero seed, e.g. by passing "seed=1".Fr  rr  r  r9   T)r/   r0   r1   r5   r2   r   r<   r   r  r   r  r
   ry  )	r6   r  r  r  rr  r9   elementseed1r  s	            r;   fractional_max_pool_v2r    sz   X u.aC=#4#;%%2O56 6 ! 8	3''4o78 	88
 	=3,/s%%2O56 6 	##0/	34 4  q!_E-	QY'')77;f =567 7 ))%*5U/0F F ''-LE5))%*5T/4EN Nr=   znn.fractional_avg_poolzM`seed2` and `deterministic` args are deprecated.  Use fractional_avg_pool_v2.c           
      <    t        j                  | |||||||      S )a	  Performs fractional average pooling on the input.

  This is a deprecated version of `fractional_avg_pool`.

  Fractional average pooling is similar to Fractional max pooling in the pooling
  region generation step. The only difference is that after pooling regions are
  generated, a mean operation is performed instead of a max operation in each
  pooling region.

  Args:
    value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.
    pooling_ratio: A list of `floats` that has length >= 4.  Pooling ratio for
      each dimension of `value`, currently only supports row and col dimension
      and should be >= 1.0. For example, a valid pooling ratio looks like [1.0,
      1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't
      allow pooling on batch and channels dimensions.  1.44 and 1.73 are pooling
      ratio on height and width dimensions respectively.
    pseudo_random: An optional `bool`.  Defaults to `False`. When set to `True`,
      generates the pooling sequence in a pseudorandom fashion, otherwise, in a
      random fashion. Check paper (Graham, 2015) for difference between
      pseudorandom and random.
    overlapping: An optional `bool`.  Defaults to `False`.  When set to `True`,
      it means when pooling, the values at the boundary of adjacent pooling
      cells are used by both cells. For example:
      `index  0  1  2  3  4`
      `value  20 5  16 3  7`
      If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used
      twice.  The result would be [20, 16] for fractional avg pooling.
    deterministic: An optional `bool`.  Deprecated; use `fractional_avg_pool_v2`
      instead.
    seed: An optional `int`.  Defaults to `0`.  If set to be non-zero, the
      random number generator is seeded by the given seed.  Otherwise it is
      seeded by a random seed.
    seed2: An optional `int`.  Deprecated; use `fractional_avg_pool_v2` instead.
    name: A name for the operation (optional).

  Returns:
  A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,
  `col_pooling_sequence`).
    output: Output `Tensor` after fractional avg pooling.  Has the same type as
      `value`.
    row_pooling_sequence: A `Tensor` of type `int64`.
    col_pooling_sequence: A `Tensor` of type `int64`.

  References:
    Fractional Max-Pooling:
      [Graham, 2015](https://arxiv.org/abs/1412.6071)
      ([pdf](https://arxiv.org/pdf/1412.6071.pdf))
  rA   )r   fractional_avg_poolr  s           r;   r  r  t  s*    z 
	'	'}m(3]D%-1
3 3r=   c           
          |dk(  rt        j                  | |||ddd|      S t        j                  |      \  }}t        j                  | |||d|||      S )a  Performs fractional average pooling on the input.

  Fractional average pooling is similar to Fractional max pooling in the pooling
  region generation step. The only difference is that after pooling regions are
  generated, a mean operation is performed instead of a max operation in each
  pooling region.

  Args:
    value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.
    pooling_ratio: A list of `floats` that has length >= 4.  Pooling ratio for
      each dimension of `value`, currently only supports row and col dimension
      and should be >= 1.0. For example, a valid pooling ratio looks like [1.0,
      1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't
      allow pooling on batch and channels dimensions.  1.44 and 1.73 are pooling
      ratio on height and width dimensions respectively.
    pseudo_random: An optional `bool`.  Defaults to `False`. When set to `True`,
      generates the pooling sequence in a pseudorandom fashion, otherwise, in a
      random fashion. Check paper (Graham, 2015) for difference between
      pseudorandom and random.
    overlapping: An optional `bool`.  Defaults to `False`.  When set to `True`,
      it means when pooling, the values at the boundary of adjacent pooling
      cells are used by both cells. For example:
      `index  0  1  2  3  4`
      `value  20 5  16 3  7`
      If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used
      twice.  The result would be [20, 16] for fractional avg pooling.
    seed: An optional `int`.  Defaults to `0`.  If set to be non-zero, the
      random number generator is seeded by the given seed.  Otherwise it is
      seeded by a random seed.
    name: A name for the operation (optional).

  Returns:
  A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,
  `col_pooling_sequence`).
    output: Output `Tensor` after fractional avg pooling.  Has the same type as
      `value`.
    row_pooling_sequence: A `Tensor` of type `int64`.
    col_pooling_sequence: A `Tensor` of type `int64`.

  References:
    Fractional Max-Pooling:
      [Graham, 2015](https://arxiv.org/abs/1412.6071)
      ([pdf](https://arxiv.org/pdf/1412.6071.pdf))
  r   Fr  T)r   r  r
   ry  )r6   r  r  r  rr  r9   r  r  s           r;   fractional_avg_pool_v2r    sp    h 
QY))%*5U/0F F ''-LE5))%*5T/4EN Nr=   
Dilation2Dc                 
   t        j                  | |j                  d         }|j                          t        j                  | |j                  d         }|j                          t        j                  | |j                        }|j                          t        |d         }t        |d         }t        j                  |j                         t        j                        }t        j                  d||z  |z  dz        S )z7Calculates the compute resources needed for Dilation2D.r   r+   r   rI  r,   rK  rZ  s           r;   _calc_dilation2d_flopsr    r\  r=   znn.erosion2dc                    t        j                  |d| |g      5 }t        j                  t	        j
                  t        j                  |       t        j                  |ddg      ||||            cddd       S # 1 sw Y   yxY w)a  Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors.

  The `value` tensor has shape `[batch, in_height, in_width, depth]` and the
  `kernel` tensor has shape `[kernel_height, kernel_width, depth]`, i.e.,
  each input channel is processed independently of the others with its own
  structuring function. The `output` tensor has shape
  `[batch, out_height, out_width, depth]`. The spatial dimensions of the
  output tensor depend on the `padding` algorithm. We currently only support the
  default "NHWC" `data_format`.

  In detail, the grayscale morphological 2-D erosion is given by:

      output[b, y, x, c] =
         min_{dy, dx} value[b,
                            strides[1] * y - rates[1] * dy,
                            strides[2] * x - rates[2] * dx,
                            c] -
                      kernel[dy, dx, c]

  Duality: The erosion of `value` by the `kernel` is equal to the negation of
  the dilation of `-value` by the reflected `kernel`.

  Args:
    value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`.
    kernel: A `Tensor`. Must have the same type as `value`.
      3-D with shape `[kernel_height, kernel_width, depth]`.
    strides: A list of `ints` that has length `>= 4`.
      1-D of length 4. The stride of the sliding window for each dimension of
      the input tensor. Must be: `[1, stride_height, stride_width, 1]`.
    rates: A list of `ints` that has length `>= 4`.
      1-D of length 4. The input stride for atrous morphological dilation.
      Must be: `[1, rate_height, rate_width, 1]`.
    padding: A `string` from: `"SAME", "VALID"`.
      The type of padding algorithm to use.
    name: A name for the operation (optional). If not specified "erosion2d"
      is used.

  Returns:
    A `Tensor`. Has the same type as `value`.
    4-D with shape `[batch, out_height, out_width, depth]`.
  Raises:
    ValueError: If the `value` depth does not match `kernel`' shape, or if
      padding is other than `'VALID'` or `'SAME'`.
  	erosion2dr   r+   r   N)r	   rG   r   r  r   r   r   
reverse_v2)r6   kernelrF   r   rD   r9   s         r;   r  r    sz    ^ ~~dK%9 	T##E*''A7		 	 	s   AA;;Bc                 4   |dk7  rt        d|       t        j                  |d| |g      5 }t        j                  t        j                  t        j                  |       t        j                  |ddg      ||||            cddd       S # 1 sw Y   yxY w)a  Computes the grayscale erosion of 4-D `value` and 3-D `filters` tensors.

  The `value` tensor has shape `[batch, in_height, in_width, depth]` and the
  `filters` tensor has shape `[filters_height, filters_width, depth]`, i.e.,
  each input channel is processed independently of the others with its own
  structuring function. The `output` tensor has shape
  `[batch, out_height, out_width, depth]`. The spatial dimensions of the
  output tensor depend on the `padding` algorithm. We currently only support the
  default "NHWC" `data_format`.

  In detail, the grayscale morphological 2-D erosion is given by:

      output[b, y, x, c] =
         min_{dy, dx} value[b,
                            strides[1] * y - dilations[1] * dy,
                            strides[2] * x - dilations[2] * dx,
                            c] -
                      filters[dy, dx, c]

  Duality: The erosion of `value` by the `filters` is equal to the negation of
  the dilation of `-value` by the reflected `filters`.

  Args:
    value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`.
    filters: A `Tensor`. Must have the same type as `value`.
      3-D with shape `[filters_height, filters_width, depth]`.
    strides: A list of `ints` that has length `>= 4`.
      1-D of length 4. The stride of the sliding window for each dimension of
      the input tensor. Must be: `[1, stride_height, stride_width, 1]`.
    padding: A `string` from: `"SAME", "VALID"`.
      The type of padding algorithm to use. See
      [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
      for more information.
    data_format: A `string`, only `"NHWC"` is currently supported.
    dilations: A list of `ints` that has length `>= 4`.
      1-D of length 4. The input stride for atrous morphological dilation.
      Must be: `[1, rate_height, rate_width, 1]`.
    name: A name for the operation (optional). If not specified "erosion2d"
      is used.

  Returns:
    A `Tensor`. Has the same type as `value`.
    4-D with shape `[batch, out_height, out_width, depth]`.

  Raises:
    ValueError: If the `value` depth does not match `filters`' shape, or if
      padding is other than `'VALID'` or `'SAME'`.
  r"   r   r  r   r+   r   N)	r5   r	   rG   r   r  r   r   r   r  )r6   rf   rF   rD   rE   r   r9   s          r;   erosion2d_v2r  @  s    r F
 99DG H H ~~dK%)9: 	d##E*''!Q8		 	 	s   ABBzmath.in_top_kznn.in_top_kc                     t        j                  |d      5  t        j                  | |||      cddd       S # 1 sw Y   yxY w)a  Says whether the targets are in the top `K` predictions.

  This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the
  prediction for the target class is finite (not inf, -inf, or nan) and among
  the top `k` predictions among all predictions for example `i`. Note that the
  behavior of `InTopK` differs from the `TopK` op in its handling of ties; if
  multiple classes have the same prediction value and straddle the top-`k`
  boundary, all of those classes are considered to be in the top `k`.

  More formally, let

    \\(predictions_i\\) be the predictions for all classes for example `i`,
    \\(targets_i\\) be the target class for example `i`,
    \\(out_i\\) be the output for example `i`,

  $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$

  Args:
    predictions: A `Tensor` of type `float32`.
      A `batch_size` x `classes` tensor.
    targets: A `Tensor`. Must be one of the following types: `int32`, `int64`.
      A `batch_size` vector of class ids.
    k: An `int`. Number of top elements to look at for computing precision.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of type `bool`. Computed Precision at `k` as a `bool Tensor`.
  in_top_krA   N)r	   rG   r   
in_top_kv2)predictionstargetsr  r9   s       r;   r  r    s?    > ~~dJ' E  gqtDE E Es	   :Ac                     t        || ||      S )a  Outputs whether the targets are in the top `K` predictions.

  This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the
  prediction for the target class is finite (not inf, -inf, or nan) and among
  the top `k` predictions among all predictions for example `i`.
  `predictions` does not have to be normalized.

  Note that the behavior of `InTopK` differs from the `TopK` op in its handling
  of ties; if multiple classes have the same prediction value and straddle the
  top-`k` boundary, all of those classes are considered to be in the top `k`.

  >>> target = tf.constant([0, 1, 3])
  >>> pred = tf.constant([
  ...  [1.2, -0.3, 2.8, 5.2],
  ...  [0.1, 0.0, 0.0, 0.0],
  ...  [0.0, 0.5, 0.3, 0.3]],
  ...  dtype=tf.float32)
  >>> print(tf.math.in_top_k(target, pred, 2))
  tf.Tensor([False  True  True], shape=(3,), dtype=bool)

  Args:
    targets: A `batch_size` vector of class ids. Must be `int32` or `int64`.
    predictions: A `batch_size` x `classes` tensor of type `float32`.
    k: An `int`. The parameter to specify search space.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` with the same shape of `targets` with type of `bool`. Each
      element specifies if the target falls into top-k predictions.
  )r  )r  r  r  r9   s       r;   in_top_k_v2r    s    B 
+w4	00r=   znn.quantized_avg_poolznn.quantized_conv2dznn.quantized_relu_xznn.quantized_max_poolznn.isotonic_regressionc           
         t         j                  t         j                  t         j                  t         j                  t         j                  t         j                  t         j                  t         j                  t         j
                  t         j                  i}t        j                  |       } 	 || j                     dfd	}t        | ||      S # t        $ r t         j                  Y /w xY w)a  Solves isotonic regression problems along the given axis.

  For each vector x, the problem solved is

  $$\argmin_{y_1 >= y_2 >= ... >= y_n} \sum_i (x_i - y_i)^2.$$

  As the solution is component-wise constant, a second tensor is returned that
  encodes the segments. The problems are solved over the given axis.

  Consider the following example, where we solve a batch of two problems. The
  first input is [3, 1, 2], while the second [1, 3, 4] (as the axis is 1).
  >>> x = tf.constant([[3, 1, 2], [1, 3, 4]], dtype=tf.float32)
  >>> y, segments = tf.nn.isotonic_regression(x, axis=1)
  >>> y  # The solution.
  <tf.Tensor: shape=(2, 3), dtype=float32, numpy=
  array([[3.       , 1.5      , 1.5      ],
         [2.6666667, 2.6666667, 2.6666667]], dtype=float32)>

  Note that the first solution has two blocks [2] and [1.5, 1.5]. The second
  solution is constant, and thus has a single segment. These segments are
  exactly what the second returned tensor encodes:

  >>> segments
  <tf.Tensor: shape=(2, 3), dtype=int32, numpy=
  array([[0, 1, 1],
         [0, 0, 0]], dtype=int32)>


  Args:
    inputs: A tensor holding the inputs.
    decreasing: If set to False, the inequalities in the optimizing constrained
      are flipped.
    axis: The axis along which the problems should be solved.

  Returns:
    output: The solutions, same shape as type as the input.
    segments: An int32 tensor, same shape as the input indicating the segments
      that have the same value. Specifically, those positions that have the same
      value correspond to the same segment. These values start at zero, and are
      monotonously increasing for each solution.
  c                     t        j                  t        j                  |      }r ||       S  ||        \  }}| |fS )N)rD  r9   )rD  rE  r   isotonic_regression)matrixr9   iso_fnr  segments
decreasingrD  s        r;   compute_on_matrixz.isotonic_regression.<locals>.compute_on_matrix  sK    &&\NFF^fhWhr=   r   )r   r  halfr  int8int16r	   rH   r   KeyErrorfloat64r  )r  r  rx   type_promotionsr  rD  s    `   @r;   r  r    s    \ nn
..kk
++oo
//kk
..ll
../   (&""6<<0L 
6#4d	;; 
 ">>L"s   1C C0/C0)NNNr   )NNNNNNN)NNNNNN)Nr   NNN)Nr   NNNTNr  )r@  )	NNNNNNNNN)r!   NN)r   r!   NN)r"   NN)
NNNNr   r"   NNNN)r   r"   NN)NN)r$   NN)	NNNr   r$   NNNN)r   r$   NN)r   NNN)Nrv   )rv   N)g?N)FN)NNrv   NN)r"   N)r!   N)r$   N)r"   NNNF)rv   gffffff?rv   TN)FFFr   r   N)FFr   N)Trv   )rr   rD  r  numpyr   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   r   r   r   r	   r
   r   r  r   r   tensorflow.python.opsr   r   r   r   r   r   r   r   r   r   r    tensorflow.python.ops.gen_nn_opstensorflow.python.platformr   tensorflow.python.utilr   r   tensorflow.python.util.compatr   "tensorflow.python.util.deprecationr   r    tensorflow.python.util.tf_exportr   lrnlocal_response_normalization	frozensetr  r<   rN   rJ   ru   add_dispatch_supportr   r   r   r   r   r   r   r   r   r   rewrite_argument_docstringr   r  r.  r0  r4  r   deprecated_arg_valuesri   rH  rJ  rP  r_   rU  rN  rY  rZ  r  ra  deprecated_endpointsry  r{  r}  r`   r  r  r  r  r  r  r  r  r  r  r  register_unary_elementwise_apir  r  r  r  r  r  r  r  r  r  r  r  _XENT_DEPRECATION
deprecatedr  r  r  r  r  r)  r$  r  r*  r2  r'  r/  r0  r(  rG  rE  rH  rC  RegisterStatisticsrU  rW  r[  r_  ra  ri  ro  ru  rs  r  r  r~  r   r  r  r  r  r  r  r  r  r  r  r  r  r  quantized_avg_poolquantized_conv2dquantized_relu_xquantized_max_poolr  elur  selusoftsignrs   r=   r;   <module>r     s  Wr    + . 3 . 3 2 + 3 < 4 3 + 1 + . , * ) , 6 < / 5 . + 9 > I 6  *~~  # $  $V 	:zm m`.b ?r"	 
B*  #B*J  	 
	M  !M #--55  #$	 [  %[|o" o"d"8&v, ^  !	
 	J  "JZ #	 	  $$ @??*K**_k;i  	N b^' ^'B yk	 	p#  p#f 9	
 	`  `F 	R  Rj&$R {m	"""=	
 #""=	 	
f:  f:R ;2	 	A  AH  !	 	V8  "V8r ;2	
 !f  fR {m	 	u  up *+,	 	87  -87v )*+	 	<7  ,<7~ $%&	
	
H  'HV  R(	 	R  )Rj F '(	 "&`A  )`AF +,-	!!!">? 	E @  .EP (3, 
!!!"MN 	= O =@ )4- 
!!!"NO 	> P >N 	%P ;2	
 "
1  
1 {m	 	E  E ;K::x4	 %%--	  $%&	 	
C  'CL  R(	
 !'$+"&!E  )ER   	
 "#!S   Sl =	*P  *PZ:6 zl	  > :"	/  /==  :	((	1  ) 1D ?	((	C  ) C@ 9	((	5  ) 5p6Sl <B/	$C  0$CN |^,-	T#H%PC Q  .C $$ !345	((	T#H%PG Q  ) 6G8 /B7	G  8G4G 1b9	::  :::z 89:	<eD.2v E  ;vr  567	T0AB
		<9 C  8<9~: <=>		v  ?vr 8R@	8/  A8/v =./0	>  1>B }o./	9?"(  0(V ?r"	$  #$N ?	*4  *4Z ?	$  $P =./0	J  1J\ }o	
  8  8x ?	54  54t ?	j  j^ ?	&  &T $,	  	D  -DN ()*	 	   +8 #-"A"A"I"I   '*B +B$ '*K +K$ /9Q :Q 	7++ ,+ ~	+   +,.02 |n	T $M(* BF/L*  
/Ld <B	Z*   Z*z ./	K4  0K4\ ,-	B2  .B2JM` <$	Tfll >  %>B  12	 &(#/1#':  3:z  12	 &(#/1#'>  3>BF< '()	T 1L M ',$)&+!\.M  *\.~ #+	 */', ! $mN  ,mN` '()	T 1L M ',$)&+!;3M  *;3| #+	 */', ! $:N  ,:Nz g.Q /Q ~	6   6r >b!	 D  "DN ./	E  0EB ?Mb1	1  21D =Y#:";<!H!!*"?"?@  99!6 78!H!!*"="=>  99!6 78!H!!*"="=>  =Y#:";<!H!!*"?"?@ 
 #+	F<  ,F<V ( ' '
 7 ' ' '
 8 ' ' '
 8 ' ' '
(;(; <r=   