You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.2 KiB
71 lines
2.2 KiB
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. |
|
# |
|
# Licensed under the Apache License, Version 2.0 (the "License"); |
|
# you may not use this file except in compliance with the License. |
|
# You may obtain a copy of the License at |
|
# |
|
# http://www.apache.org/licenses/LICENSE-2.0 |
|
# |
|
# Unless required by applicable law or agreed to in writing, software |
|
# distributed under the License is distributed on an "AS IS" BASIS, |
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
# See the License for the specific language governing permissions and |
|
# limitations under the License.. |
|
|
|
from itertools import repeat |
|
import collections.abc |
|
|
|
import paddle |
|
import paddle.nn as nn |
|
""" |
|
Droppath, reimplement from https://github.com/yueatsprograms/Stochastic_Depth |
|
""" |
|
|
|
|
|
class DropPath(nn.Layer): |
|
"""DropPath class""" |
|
|
|
def __init__(self, drop_prob=None): |
|
super().__init__() |
|
self.drop_prob = drop_prob |
|
|
|
def drop_path(self, inputs): |
|
"""drop path op |
|
Args: |
|
input: tensor with arbitrary shape |
|
drop_prob: float number of drop path probability, default: 0.0 |
|
training: bool, if current mode is training, default: False |
|
Returns: |
|
output: output tensor after drop path |
|
""" |
|
# If prob is 0 or is in eval mode, return original input. |
|
if self.drop_prob == 0. or not self.training: |
|
return inputs |
|
keep_prob = 1 - self.drop_prob |
|
keep_prob = paddle.to_tensor(keep_prob, dtype='float32') |
|
shape = (inputs.shape[0], ) + (1, ) * (inputs.ndim - 1 |
|
) # shape=(N, 1, 1, 1) |
|
random_tensor = keep_prob + paddle.rand(shape, dtype=inputs.dtype) |
|
random_tensor = random_tensor.floor() # mask |
|
# Make division to keep output expectation same. |
|
output = inputs.divide(keep_prob) * random_tensor |
|
return output |
|
|
|
def forward(self, inputs): |
|
return self.drop_path(inputs) |
|
|
|
|
|
def _ntuple(n): |
|
def parse(x): |
|
if isinstance(x, collections.abc.Iterable): |
|
return x |
|
return tuple(repeat(x, n)) |
|
|
|
return parse |
|
|
|
|
|
to_1tuple = _ntuple(1) |
|
to_2tuple = _ntuple(2) |
|
to_3tuple = _ntuple(3) |
|
to_4tuple = _ntuple(4) |
|
to_ntuple = _ntuple
|
|
|