o
    ॵi<J                     @   s  d Z ddlZddlmZ ejdkrddlZnddlmZ ejdkr%ej	j
ZejZej			dddZej			dd	d
Z								dddZde_							dddZeje_							d ddZeje_							d!ddZeje_							d"ddZeje_							d#ddZeje_edkrejejdddZee ZeeZW d   dS 1 sw   Y  dS dS )$a  Contains definitions for the original form of Residual Networks.
The 'v1' residual networks (ResNets) implemented in this module were proposed
by:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
    Deep Residual Learning for Image Recognition. arXiv:1512.03385
Other variants were introduced in:
[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
    Identity Mappings in Deep Residual Networks. arXiv: 1603.05027
The networks defined in this module utilize the bottleneck building block of
[1] with projection shortcuts only for increasing depths. They employ batch
normalization *after* every weight layer. This is the architecture used by
MSRA in the Imagenet and MSCOCO 2016 competition models ResNet-101 and
ResNet-152. See [2; Fig. 1a] for a comparison between the current 'v1'
architecture and the alternative 'v2' architecture of [2] which uses batch
normalization *before* every weight layer in the so-called full pre-activation
units.
Typical use:
   from tensorflow.contrib.slim.nets import resnet_v1
ResNet-101 for image classification into 1000 classes:
   # inputs has shape [batch, 224, 224, 3]
   with slim.arg_scope(resnet_v1.resnet_arg_scope()):
      net, end_points = resnet_v1.resnet_v1_101(inputs, 1000, is_training=False)
ResNet-101 for semantic segmentation into 21 classes:
   # inputs has shape [batch, 513, 513, 3]
   with slim.arg_scope(resnet_v1.resnet_arg_scope()):
      net, end_points = resnet_v1.resnet_v1_101(inputs,
                                                21,
                                                is_training=False,
                                                global_pool=False,
                                                output_stride=16)
    N   )resnet_utilsz2.0)slimc              	   C   s   t |d| gR}tjj|  dd}||krt| |d}	ntj| |ddg|ddd}	tj	| |d||d	d
}
tj	|
|dd|dd
}
t j
|
|	 }tj||j|W  d   S 1 s]w   Y  dS )  Bottleneck residual unit variant with BN after convolutions.
    This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] for
    its definition. Note that we use here the bottleneck variant which has an
    extra bottleneck layer.
    When putting together two consecutive ResNet blocks that use this unit, one
    should use stride = 2 in the last unit of the first block.
    Args:
      inputs: A tensor of size [batch, height, width, channels].
      depth: The depth of the ResNet unit output.
      depth_bottleneck: The depth of the bottleneck layers.
      stride: The ResNet unit's stride. Determines the amount of downsampling of
        the units output compared to its input.
      rate: An integer, rate for atrous convolution.
      outputs_collections: Collection to add the ResNet unit output.
      scope: Optional variable_scope.
    Returns:
      The ResNet unit's output.
    bottleneck_v1   min_rankshortcutr   Nstrideactivation_fnscope   conv1rater   conv2tfvariable_scoper   utilslast_dimension	get_shaper   	subsampleconv2dconv2d_samennrelucollect_named_outputsoriginal_name_scopeinputsdepthdepth_bottleneckr   r   outputs_collectionsr   scdepth_inr
   residualoutput r*   a/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/pipelines/cv/ocr_utils/resnet18_v1.py
basicblock=   s,   $r,   c              	   C   s   t |d| g`}tjj|  dd}||krt| |d}	ntj| |ddg|ddd}	tj| |ddgddd	}
tj	|
|d
||dd}
tj|
|ddgdddd}
t j
|	|
 }tj||j|W  d   S 1 skw   Y  dS )r   r   r   r   r
   r   Nr   r   r   r   r   r   r   conv3r   r!   r*   r*   r+   
bottleneckn   s:   $r/   Tc
                 C   s  t j|	d| g|d}
|
jd }tjtjttjg|d tjtj	g|d | }|rl|dur=|d dkr9t
d	|d }tj|d
dddd}t |ddgddgddgddgg}tj|ddgddd}tj|d|}t|||}tj|}|d |d< |d |d< |d |d< |d |d< |d |d< ||d< ||fW  d   W  d   W  d   S 1 sw   Y  W d   n1 sw   Y  W d   dS W d   dS 1 sw   Y  dS )a6  Generator for v1 ResNet models.
    This function generates a family of ResNet v1 models. See the resnet_v1_*()
    methods for specific model instantiations, obtained by selecting different
    block instantiations that produce ResNets of various depths.
    Training for image classification on Imagenet is usually done with [224, 224]
    inputs, resulting in [7, 7] feature maps at the output of the last ResNet
    block for the ResNets defined in [1] that have nominal stride equal to 32.
    However, for dense prediction tasks we advise that one uses inputs with
    spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In
    this case the feature maps at the ResNet output will have spatial shape
    [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1]
    and corners exactly aligned with the input image corners, which greatly
    facilitates alignment of the features to the image. Using as input [225, 225]
    images results in [8, 8] feature maps at the output of the last ResNet block.
    For dense prediction tasks, the ResNet needs to run in fully-convolutional
    (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all
    have nominal stride equal to 32 and a good choice in FCN mode is to use
    output_stride=16 in order to increase the density of the computed features at
    small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915.
    Args:
      inputs: A tensor of size [batch, height_in, width_in, channels].
      blocks: A list of length equal to the number of ResNet blocks. Each element
        is a resnet_utils.Block object describing the units in the block.
      num_classes: Number of predicted classes for classification tasks. If None
        we return the features before the logit layer.
      is_training: whether is training or not.
      global_pool: If True, we perform global average pooling before computing the
        logits. Set to True for image classification, False for dense prediction.
      output_stride: If None, then the output will be computed at the nominal
        network stride. If output_stride is not None, it specifies the requested
        ratio of input to output spatial resolution.
      include_root_block: If True, include the initial convolution followed by
        max-pooling, if False excludes it.
      spatial_squeeze: if True, logits is of shape [B, C], if false logits is
          of shape [B, 1, 1, C], where B is batch_size and C is number of classes.
      reuse: whether or not the network and its variables should be reused. To be
        able to reuse 'scope' must be given.
      scope: Optional variable_scope.
    Returns:
      net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
        If global_pool is False, then height_out and width_out are reduced by a
        factor of output_stride compared to the respective height_in and width_in,
        else both height_out and width_out equal one. If num_classes is None, then
        net is the output of the last ResNet block, potentially after global
        average pooling. If num_classes is not None, net contains the pre-softmax
        activations.
      end_points: A dictionary from components of the network to the corresponding
        activation.
    Raises:
      ValueError: If the target output_stride is not valid.
    	resnet_v1)reuse_end_points)r%   )is_trainingNr   r   z.The output_stride needs to be a multiple of 4.@         r   r-   r   r   pool1pool2zresnet_v1_18/block2/unit_2zresnet_v1_18/block3/unit_2zresnet_v1_18/block4/unit_2pool3zresnet_v1_18/block5/unit_2pool4zresnet_v1_18/block6/unit_2pool5pool6)r   r   namer   	arg_scoper   r/   r   stack_blocks_dense
batch_norm
ValueErrorr   pad
max_pool2dr   r   convert_collection_to_dict)r"   blocksnum_classesr3   global_pooloutput_strideinclude_root_blockspatial_squeezer1   r   r&   end_points_collectionnet
end_pointsr*   r*   r+   r0      sX   =

$"r0      resnet_v1_18c           	      C   s   t dtdgdg t dtdgdg t dtdgdg t dtd	gd
g t dtdgdg t dtdgdg t dtdgdg g}t| |||||d|||d
S )zGResNet-18 model of [1]. See resnet_v1() for arg and return description.block1)r4   r4   r   block2)   rR   r   block3)   rT   r6   )rT   rT   r   block4)   rV   r6   )rV   rV   r   block5block6block7TrG   rH   rI   rJ   r1   r   )r   Blockr,   r0   	r"   rF   r3   rG   rH   rJ   r1   r   rE   r*   r*   r+   rO     sD   







resnet_v1_50c           	      C   s   t dtdgd dg t dtdgd dg t d	td
gd dg t dtdgd dg t dtd
gd dg t dtd
gd g}t| |||||d|||d
S )zGResNet-50 model of [1]. See resnet_v1() for arg and return description.rP   rT   r4   r   r6   rT   r4   r6   rQ   rV   rR   r   r   rV   rR   r6   rS      rT   r      rc   rT   r6   rU      rV   r   )rg   rV   r6   rW   rX   TrZ   r   r[   r/   r0   r\   r*   r*   r+   r]   4  s:   
resnet_v1_101c           	      C   sz   t dtdgd dg t dtdgd dg t d	td
gd dg t dtdgd g}t| |||||d|||d
S )zHResNet-101 model of [1]. See resnet_v1() for arg and return description.rP   r^   r6   r_   rQ   r`   r   ra   rS   rb      re   rU   rf   TrZ   rh   r\   r*   r*   r+   ri   Z  .   
	resnet_v1_152c           	      C   z   t dtdgd dg t dtdgd dg t d	td
gd dg t dtdgd g}t| |||||d|||d
S )zHResNet-152 model of [1]. See resnet_v1() for arg and return description.rP   r^   r6   r_   rQ   r`   r5   ra   rS   rb   #   re   rU   rf   r   TrZ   rh   r\   r*   r*   r+   rl   |  rk   resnet_v1_200c           	      C   rm   )zHResNet-200 model of [2]. See resnet_v1() for arg and return description.rP   r^   r6   r_   rQ   r`      ra   rS   rb   rn   re   rU   rf   r   TrZ   rh   r\   r*   r*   r+   ro     rk   __main__)NrN   rN   r   input)shaper=   )r   NN)NTTNTTNN)NTTNTNrO   )NTTNTNr]   )NTTNTNri   )NTTNTNrl   )NTTNTNro   )__doc__
tensorflowr    r   __version__tf_slimr   tensorflow.contribcompatv1resnet_arg_scopeadd_arg_scoper,   r/   r0   default_image_sizerO   r]   ri   rl   ro   __name__placeholderfloat32rr   r>   r&   logitsr*   r*   r*   r+   <module>   s   


08
c
&
#



"