code
stringlengths
17
6.64M
class Fnode(nn.Module): ' A simple wrapper used in place of nn.Sequential for torchscript typing\n Handles input type List[Tensor] -> output type Tensor\n ' def __init__(self, combine: nn.Module, after_combine: nn.Module): super(Fnode, self).__init__() self.combine = combine sel...
class BiFpnLayer(nn.Module): def __init__(self, feature_info, feat_sizes, fpn_config, fpn_channels, num_levels=5, pad_type='', downsample=None, upsample=None, norm_layer=nn.BatchNorm2d, act_layer=_ACT_LAYER, apply_resample_bn=False, pre_act=True, separable_conv=True, redundant_bias=False): super(BiFpnLay...
class BiFpn(nn.Module): def __init__(self, config, feature_info): super(BiFpn, self).__init__() self.num_levels = config.num_levels norm_layer = (config.norm_layer or nn.BatchNorm2d) if config.norm_kwargs: norm_layer = partial(norm_layer, **config.norm_kwargs) ...
class HeadNet(nn.Module): def __init__(self, config, num_outputs): super(HeadNet, self).__init__() self.num_levels = config.num_levels self.bn_level_first = getattr(config, 'head_bn_level_first', False) norm_layer = (config.norm_layer or nn.BatchNorm2d) if config.norm_kwar...
def _init_weight(m, n=''): ' Weight initialization as per Tensorflow official implementations.\n ' def _fan_in_out(w, groups=1): dimensions = w.dim() if (dimensions < 2): raise ValueError('Fan in and fan out can not be computed for tensor with fewer than 2 dimensions') ...
def _init_weight_alt(m, n=''): ' Weight initialization alternative, based on EfficientNet bacbkone init w/ class bias addition\n NOTE: this will likely be removed after some experimentation\n ' if isinstance(m, nn.Conv2d): fan_out = ((m.kernel_size[0] * m.kernel_size[1]) * m.out_channels) ...
def get_feature_info(backbone): if isinstance(backbone.feature_info, Callable): feature_info = [dict(num_chs=f['num_chs'], reduction=f['reduction']) for (i, f) in enumerate(backbone.feature_info())] else: feature_info = backbone.feature_info.get_dicts(keys=['num_chs', 'reduction']) return ...
class EfficientDet(nn.Module): def __init__(self, config, pretrained_backbone=True, alternate_init=False): super(EfficientDet, self).__init__() self.config = config set_config_readonly(self.config) self.backbone = create_model(config.backbone_name, features_only=True, out_indices=...
def create_category_index(categories): "Creates dictionary of COCO compatible categories keyed by category id.\n Args:\n categories: a list of dicts, each of which has the following keys:\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) stri...
class DetectionEvaluator(metaclass=ABCMeta): 'Interface for object detection evalution classes.\n Example usage of the Evaluator:\n ------------------------------\n evaluator = DetectionEvaluator(categories)\n # Detections and groundtruth for image 1.\n evaluator.add_single_gt_image_info(...)\n ...
class ObjectDetectionEvaluator(DetectionEvaluator): 'A class to evaluation detections.' def __init__(self, categories, matching_iou_threshold=0.5, recall_lower_bound=0.0, recall_upper_bound=1.0, evaluate_corlocs=False, evaluate_precision_recall=False, metric_prefix=None, use_weighted_mean_ap=False, evaluate_...
class PascalDetectionEvaluator(ObjectDetectionEvaluator): 'A class to evaluation detections using PASCAL metrics.' def __init__(self, categories, matching_iou_threshold=0.5): super(PascalDetectionEvaluator, self).__init__(categories, matching_iou_threshold=matching_iou_threshold, evaluate_corlocs=Fal...
class WeightedPascalDetectionEvaluator(ObjectDetectionEvaluator): 'A class to evaluation detections using weighted PASCAL metrics.\n Weighted PASCAL metrics computes the mean average precision as the average\n precision given the scores and tp_fp_labels of all classes. In comparison,\n PASCAL metrics com...
class PrecisionAtRecallDetectionEvaluator(ObjectDetectionEvaluator): 'A class to evaluation detections using precision@recall metrics.' def __init__(self, categories, matching_iou_threshold=0.5, recall_lower_bound=0.0, recall_upper_bound=1.0): super(PrecisionAtRecallDetectionEvaluator, self).__init__...
class OpenImagesDetectionEvaluator(ObjectDetectionEvaluator): 'A class to evaluation detections using Open Images V2 metrics.\n Open Images V2 introduce group_of type of bounding boxes and this metric\n handles those boxes appropriately.\n ' def __init__(self, categories, matching_iou_threshold=...
class OpenImagesChallengeEvaluator(OpenImagesDetectionEvaluator): 'A class implements Open Images Challenge metrics.\n Both Detection and Instance Segmentation evaluation metrics are implemented.\n Open Images Challenge Detection metric has two major changes in comparison\n with Open Images V2 dete...
class InputDataFields(object): 'Names for the input tensors.\n Holds the standard data field names to use for identifying input tensors. This\n should be used by the decoder to identify keys for the returned tensor_dict\n containing input tensors. And it should be used by the model to identify the\n t...
class DetectionResultFields(object): 'Naming conventions for storing the output of the detector.\n Attributes:\n source_id: source of the original image.\n key: unique key corresponding to image.\n detection_boxes: coordinates of the detection boxes in the image.\n detection_scores:...
class BoxListFields(object): 'Naming conventions for BoxLists.\n Attributes:\n boxes: bounding box coordinates.\n classes: classes per bounding box.\n scores: scores per bounding box.\n weights: sample weights per bounding box.\n objectness: objectness score per bounding box....
def compute_precision_recall(scores, labels, num_gt): 'Compute precision and recall.\n Args:\n scores: A float numpy array representing detection score\n labels: A float numpy array representing weighted true/false positive labels\n num_gt: Number of ground truth instances\n Raises:\n ...
def compute_average_precision(precision, recall): 'Compute Average Precision according to the definition in VOCdevkit.\n Precision is modified to ensure that it does not decrease as recall\n decrease.\n Args:\n precision: A float [N, 1] numpy array of precisions\n recall: A float [N, 1] num...
def compute_cor_loc(num_gt_imgs_per_class, num_images_correctly_detected_per_class): 'Compute CorLoc according to the definition in the following paper.\n https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf\n Returns nans if there are no ground truth images for a class.\n Args:\n num_g...
def compute_median_rank_at_k(tp_fp_list, k): 'Computes MedianRank@k, where k is the top-scoring labels.\n Args:\n tp_fp_list: a list of numpy arrays; each numpy array corresponds to the all\n detection on a single image, where the detections are sorted by score in\n descending orde...
def compute_recall_at_k(tp_fp_list, num_gt, k): 'Computes Recall@k, MedianRank@k, where k is the top-scoring labels.\n Args:\n tp_fp_list: a list of numpy arrays; each numpy array corresponds to the all\n detection on a single image, where the detections are sorted by score in\n de...
class ObjectDetectionEvaluation(): 'Internal implementation of Pascal object detection metrics.' def __init__(self, num_gt_classes, matching_iou_threshold=0.5, nms_iou_threshold=1.0, nms_max_output_boxes=10000, recall_lower_bound=0.0, recall_upper_bound=1.0, use_weighted_mean_ap=False, label_id_offset=0, gro...
def create_model(model_name, bench_task='', num_classes=None, pretrained=False, checkpoint_path='', checkpoint_ema=False, **kwargs): config = get_efficientdet_config(model_name) return create_model_from_config(config, bench_task=bench_task, num_classes=num_classes, pretrained=pretrained, checkpoint_path=check...
def create_model_from_config(config, bench_task='', num_classes=None, pretrained=False, checkpoint_path='', checkpoint_ema=False, **kwargs): pretrained_backbone = kwargs.pop('pretrained_backbone', True) if (pretrained or checkpoint_path): pretrained_backbone = False overrides = ('redundant_bias', ...
def load_pretrained(model, url, filter_fn=None, strict=True): if (not url): logging.warning('Pretrained model URL is empty, using random initialization. Did you intend to use a `tf_` variant of the model?') return state_dict = load_state_dict_from_url(url, progress=False, map_location='cpu') ...
def focal_loss_legacy(logits, targets, alpha: float, gamma: float, normalizer): "Compute the focal loss between `logits` and the golden `target` values.\n\n 'Legacy focal loss matches the loss used in the official Tensorflow impl for initial\n model releases and some time after that. It eventually transitio...
def new_focal_loss(logits, targets, alpha: float, gamma: float, normalizer, label_smoothing: float=0.01): "Compute the focal loss between `logits` and the golden `target` values.\n\n 'New' is not the best descriptor, but this focal loss impl matches recent versions of\n the official Tensorflow impl of Effic...
def huber_loss(input, target, delta: float=1.0, weights: Optional[torch.Tensor]=None, size_average: bool=True): '\n ' err = (input - target) abs_err = err.abs() quadratic = torch.clamp(abs_err, max=delta) linear = (abs_err - quadratic) loss = ((0.5 * quadratic.pow(2)) + (delta * linear)) ...
def smooth_l1_loss(input, target, beta: float=(1.0 / 9), weights: Optional[torch.Tensor]=None, size_average: bool=True): '\n very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter\n ' if (beta < 1e-05): loss = torch.abs((input - target)) else: err = torch....
def _box_loss(box_outputs, box_targets, num_positives, delta: float=0.1): 'Computes box regression loss.' normalizer = (num_positives * 4.0) mask = (box_targets != 0.0) box_loss = huber_loss(box_outputs, box_targets, weights=mask, delta=delta, size_average=False) return (box_loss / normalizer)
def one_hot(x, num_classes: int): x_non_neg = (x >= 0).unsqueeze((- 1)) onehot = torch.zeros((x.shape + (num_classes,)), device=x.device, dtype=torch.float32) return (onehot.scatter((- 1), (x.unsqueeze((- 1)) * x_non_neg), 1) * x_non_neg)
def loss_fn(cls_outputs: List[torch.Tensor], box_outputs: List[torch.Tensor], cls_targets: List[torch.Tensor], box_targets: List[torch.Tensor], num_positives: torch.Tensor, num_classes: int, alpha: float, gamma: float, delta: float, box_loss_weight: float, label_smoothing: float=0.0, legacy_focal: bool=False) -> Tupl...
class DetectionLoss(nn.Module): __constants__ = ['num_classes'] def __init__(self, config): super(DetectionLoss, self).__init__() self.config = config self.num_classes = config.num_classes self.alpha = config.alpha self.gamma = config.gamma self.delta = config....
def one_hot_bool(x, num_classes: int): onehot = torch.zeros(x.size(0), num_classes, device=x.device, dtype=torch.bool) return onehot.scatter_(1, x.unsqueeze(1), 1)
@torch.jit.script class ArgMaxMatcher(object): 'Matcher based on highest value.\n\n This class computes matches from a similarity matrix. Each column is matched\n to a single row.\n\n To support object detection target assignment this class enables setting both\n matched_threshold (upper threshold) an...
class FasterRcnnBoxCoder(object): 'Faster RCNN box coder.' def __init__(self, scale_factors: Optional[List[float]]=None, eps: float=EPS): 'Constructor for FasterRcnnBoxCoder.\n\n Args:\n scale_factors: List of 4 positive scalars to scale ty, tx, th and tw.\n If set to...
def batch_decode(encoded_boxes, box_coder: FasterRcnnBoxCoder, anchors: BoxList): 'Decode a batch of encoded boxes.\n\n This op takes a batch of encoded bounding boxes and transforms\n them to a batch of bounding boxes specified by their corners in\n the order of [y_min, x_min, y_max, x_max].\n\n Args...
@torch.jit.script class BoxList(object): 'Box collection.' data: Dict[(str, torch.Tensor)] def __init__(self, boxes): 'Constructs box collection.\n\n Args:\n boxes: a tensor of shape [N, 4] representing box corners\n\n Raises:\n ValueError: if invalid dimension...
@torch.jit.script class Match(object): 'Class to store results from the matcher.\n\n This class is used to store the results from the matcher. It provides\n convenient methods to query the matching results.\n ' def __init__(self, match_results: torch.Tensor): 'Constructs a Match object.\n\n ...
def area(boxlist: BoxList): 'Computes area of boxes.\n\n Args:\n boxlist: BoxList holding N boxes\n\n Returns:\n a tensor with shape [N] representing box areas.\n ' (y_min, x_min, y_max, x_max) = boxlist.boxes().chunk(4, dim=1) out = ((y_max - y_min).squeeze(1) * (x_max - x_min).squ...
def intersection(boxlist1: BoxList, boxlist2: BoxList): 'Compute pairwise intersection areas between boxes.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n\n Returns:\n a tensor with shape [N, M] representing pairwise intersections\n ' (y_min1,...
def iou(boxlist1: BoxList, boxlist2: BoxList): 'Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n\n Returns:\n a tensor with shape [N, M] representing pairwise iou scores.\n ' int...
@torch.jit.script class IouSimilarity(object): 'Class to compute similarity based on Intersection over Union (IOU) metric.\n\n This class computes pairwise similarity between two BoxLists based on IOU.\n ' def __init__(self): pass def compare(self, boxlist1: BoxList, boxlist2: BoxList): ...
class TargetAssigner(object): 'Target assigner to compute classification and regression targets.' def __init__(self, similarity_calc: IouSimilarity, matcher: ArgMaxMatcher, box_coder: FasterRcnnBoxCoder, negative_class_weight: float=1.0, unmatched_cls_target: Optional[float]=None, keypoints_field_name: str=K...
def _parse_args(): (args_config, remaining) = config_parser.parse_known_args() if args_config.config: with open(args_config.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg) args = parser.parse_args(remaining) args_text = yaml.safe_dump(args.__dict__...
def get_clip_parameters(model, exclude_head=False): if exclude_head: return [p for (n, p) in model.named_parameters() if ('predict' not in n)] else: return model.parameters()
def main(): utils.setup_default_logging() (args, args_text) = _parse_args() args.pretrained_backbone = (not args.no_pretrained_backbone) args.prefetcher = (not args.no_prefetcher) args.distributed = False if ('WORLD_SIZE' in os.environ): args.distributed = (int(os.environ['WORLD_SIZE']...
def create_datasets_and_loaders(args, model_config, transform_train_fn=None, transform_eval_fn=None, collate_fn=None): ' Setup datasets, transforms, loaders, evaluator.\n\n Args:\n args: Command line args / config for training\n model_config: Model specific configuration dict / struct\n tr...
def train_epoch(epoch, model, loader, optimizer, args, lr_scheduler=None, saver=None, output_dir='', amp_autocast=suppress, loss_scaler=None, model_ema=None): batch_time_m = utils.AverageMeter() data_time_m = utils.AverageMeter() losses_m = utils.AverageMeter() model.train() clip_params = get_clip...
def validate(model, loader, args, evaluator=None, log_suffix=''): batch_time_m = utils.AverageMeter() losses_m = utils.AverageMeter() model.eval() end = time.time() last_idx = (len(loader) - 1) with torch.no_grad(): for (batch_idx, (input, target)) in enumerate(loader): las...
def add_bool_arg(parser, name, default=False, help=''): dest_name = name.replace('-', '_') group = parser.add_mutually_exclusive_group(required=False) group.add_argument(('--' + name), dest=dest_name, action='store_true', help=help) group.add_argument(('--no-' + name), dest=dest_name, action='store_fa...
def validate(args): setup_default_logging() if args.amp: if has_native_amp: args.native_amp = True elif has_apex: args.apex_amp = True assert ((not args.apex_amp) or (not args.native_amp)), 'Only one AMP mode should be set.' args.pretrained = (args.pretrained or...
def main(): args = parser.parse_args() validate(args)
def main(): args = parser.parse_args() args.gpu_id = 0 if args.c2_prefix: args.c2_init = (args.c2_prefix + '.init.pb') args.c2_predict = (args.c2_prefix + '.predict.pb') model = model_helper.ModelHelper(name='le_net', init_params=False) init_net_proto = caffe2_pb2.NetDef() with...
def natural_key(string_): 'See http://www.codinghorror.com/blog/archives/001018.html' return [(int(s) if s.isdigit() else s) for s in re.split('(\\d+)', string_.lower())]
def find_images_and_targets(folder, types=IMG_EXTENSIONS, class_to_idx=None, leaf_name_only=True, sort=True): if (class_to_idx is None): class_to_idx = dict() build_class_idx = True else: build_class_idx = False labels = [] filenames = [] for (root, subdirs, files) in os.wa...
class Dataset(data.Dataset): def __init__(self, root, transform=None, load_bytes=False): (imgs, _, _) = find_images_and_targets(root) if (len(imgs) == 0): raise RuntimeError(((('Found 0 images in subfolders of: ' + root) + '\nSupported image extensions are: ') + ','.join(IMG_EXTENSION...
def fast_collate(batch): targets = torch.tensor([b[1] for b in batch], dtype=torch.int64) batch_size = len(targets) tensor = torch.zeros((batch_size, *batch[0][0].shape), dtype=torch.uint8) for i in range(batch_size): tensor[i] += torch.from_numpy(batch[i][0]) return (tensor, targets)
class PrefetchLoader(): def __init__(self, loader, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): self.loader = loader self.mean = torch.tensor([(x * 255) for x in mean]).cuda().view(1, 3, 1, 1) self.std = torch.tensor([(x * 255) for x in std]).cuda().view(1, 3, 1, 1) def __i...
def create_loader(dataset, input_size, batch_size, is_training=False, use_prefetcher=True, interpolation='bilinear', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, num_workers=1, crop_pct=None, tensorflow_preprocessing=False): if isinstance(input_size, tuple): img_size = input_size[(- 2):] else...
def distorted_bounding_box_crop(image_bytes, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None): 'Generates cropped_image using one of the bboxes randomly distorted.\n\n See `tf.image.sample_distorted_bounding_box` for more documentation.\n\n ...
def _at_least_x_are_equal(a, b, x): 'At least `x` of `a` and `b` `Tensors` are equal.' match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
def _decode_and_random_crop(image_bytes, image_size, resize_method): 'Make a random crop of image_size.' bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) image = distorted_bounding_box_crop(image_bytes, bbox, min_object_covered=0.1, aspect_ratio_range=((3.0 / 4), (4.0 / 3.0)), a...
def _decode_and_center_crop(image_bytes, image_size, resize_method): 'Crops to center of image with padding then scales image_size.' shape = tf.image.extract_jpeg_shape(image_bytes) image_height = shape[0] image_width = shape[1] padded_center_crop_size = tf.cast(((image_size / (image_size + CROP_P...
def _flip(image): 'Random horizontal image flip.' image = tf.image.random_flip_left_right(image) return image
def preprocess_for_train(image_bytes, use_bfloat16, image_size=IMAGE_SIZE, interpolation='bicubic'): 'Preprocesses the given image for evaluation.\n\n Args:\n image_bytes: `Tensor` representing an image binary of arbitrary size.\n use_bfloat16: `bool` for whether to use bfloat16.\n image_size: i...
def preprocess_for_eval(image_bytes, use_bfloat16, image_size=IMAGE_SIZE, interpolation='bicubic'): 'Preprocesses the given image for evaluation.\n\n Args:\n image_bytes: `Tensor` representing an image binary of arbitrary size.\n use_bfloat16: `bool` for whether to use bfloat16.\n image_size: im...
def preprocess_image(image_bytes, is_training=False, use_bfloat16=False, image_size=IMAGE_SIZE, interpolation='bicubic'): 'Preprocesses the given image.\n\n Args:\n image_bytes: `Tensor` representing an image binary of arbitrary size.\n is_training: `bool` for whether the preprocessing is for trainin...
class TfPreprocessTransform(): def __init__(self, is_training=False, size=224, interpolation='bicubic'): self.is_training = is_training self.size = (size[0] if isinstance(size, tuple) else size) self.interpolation = interpolation self._image_bytes = None self.process_image...
def resolve_data_config(model, args, default_cfg={}, verbose=True): new_config = {} default_cfg = default_cfg if ((not default_cfg) and (model is not None) and hasattr(model, 'default_cfg')): default_cfg = model.default_cfg in_chans = 3 input_size = (in_chans, 224, 224) if (args.img_si...
class ToNumpy(): def __call__(self, pil_img): np_img = np.array(pil_img, dtype=np.uint8) if (np_img.ndim < 3): np_img = np.expand_dims(np_img, axis=(- 1)) np_img = np.rollaxis(np_img, 2) return np_img
class ToTensor(): def __init__(self, dtype=torch.float32): self.dtype = dtype def __call__(self, pil_img): np_img = np.array(pil_img, dtype=np.uint8) if (np_img.ndim < 3): np_img = np.expand_dims(np_img, axis=(- 1)) np_img = np.rollaxis(np_img, 2) return t...
def _pil_interp(method): if (method == 'bicubic'): return Image.BICUBIC elif (method == 'lanczos'): return Image.LANCZOS elif (method == 'hamming'): return Image.HAMMING else: return Image.BILINEAR
def transforms_imagenet_eval(img_size=224, crop_pct=None, interpolation='bilinear', use_prefetcher=False, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD): crop_pct = (crop_pct or DEFAULT_CROP_PCT) if isinstance(img_size, tuple): assert (len(img_size) == 2) if (img_size[(- 1)] == img_size...
def add_override_act_fn(name, fn): global _OVERRIDE_FN _OVERRIDE_FN[name] = fn
def update_override_act_fn(overrides): assert isinstance(overrides, dict) global _OVERRIDE_FN _OVERRIDE_FN.update(overrides)
def clear_override_act_fn(): global _OVERRIDE_FN _OVERRIDE_FN = dict()
def add_override_act_layer(name, fn): _OVERRIDE_LAYER[name] = fn
def update_override_act_layer(overrides): assert isinstance(overrides, dict) global _OVERRIDE_LAYER _OVERRIDE_LAYER.update(overrides)
def clear_override_act_layer(): global _OVERRIDE_LAYER _OVERRIDE_LAYER = dict()
def get_act_fn(name='relu'): ' Activation Function Factory\n Fetching activation fns by name with this function allows export or torch script friendly\n functions to be returned dynamically based on current config.\n ' if (name in _OVERRIDE_FN): return _OVERRIDE_FN[name] use_me = (not (co...
def get_act_layer(name='relu'): ' Activation Layer Factory\n Fetching activation layers by name with this function allows export or torch script friendly\n functions to be returned dynamically based on current config.\n ' if (name in _OVERRIDE_LAYER): return _OVERRIDE_LAYER[name] use_me =...
def swish(x, inplace: bool=False): 'Swish - Described originally as SiLU (https://arxiv.org/abs/1702.03118v3)\n and also as Swish (https://arxiv.org/abs/1710.05941).\n\n TODO Rename to SiLU with addition to PyTorch\n ' return (x.mul_(x.sigmoid()) if inplace else x.mul(x.sigmoid()))
class Swish(nn.Module): def __init__(self, inplace: bool=False): super(Swish, self).__init__() self.inplace = inplace def forward(self, x): return swish(x, self.inplace)
def mish(x, inplace: bool=False): 'Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681\n ' return x.mul(F.softplus(x).tanh())
class Mish(nn.Module): def __init__(self, inplace: bool=False): super(Mish, self).__init__() self.inplace = inplace def forward(self, x): return mish(x, self.inplace)
def sigmoid(x, inplace: bool=False): return (x.sigmoid_() if inplace else x.sigmoid())
class Sigmoid(nn.Module): def __init__(self, inplace: bool=False): super(Sigmoid, self).__init__() self.inplace = inplace def forward(self, x): return (x.sigmoid_() if self.inplace else x.sigmoid())
def tanh(x, inplace: bool=False): return (x.tanh_() if inplace else x.tanh())
class Tanh(nn.Module): def __init__(self, inplace: bool=False): super(Tanh, self).__init__() self.inplace = inplace def forward(self, x): return (x.tanh_() if self.inplace else x.tanh())
def hard_swish(x, inplace: bool=False): inner = F.relu6((x + 3.0)).div_(6.0) return (x.mul_(inner) if inplace else x.mul(inner))
class HardSwish(nn.Module): def __init__(self, inplace: bool=False): super(HardSwish, self).__init__() self.inplace = inplace def forward(self, x): return hard_swish(x, self.inplace)
def hard_sigmoid(x, inplace: bool=False): if inplace: return x.add_(3.0).clamp_(0.0, 6.0).div_(6.0) else: return (F.relu6((x + 3.0)) / 6.0)
class HardSigmoid(nn.Module): def __init__(self, inplace: bool=False): super(HardSigmoid, self).__init__() self.inplace = inplace def forward(self, x): return hard_sigmoid(x, self.inplace)
@torch.jit.script def swish_jit(x, inplace: bool=False): 'Swish - Described originally as SiLU (https://arxiv.org/abs/1702.03118v3)\n and also as Swish (https://arxiv.org/abs/1710.05941).\n\n TODO Rename to SiLU with addition to PyTorch\n ' return x.mul(x.sigmoid())
@torch.jit.script def mish_jit(x, _inplace: bool=False): 'Mish: A Self Regularized Non-Monotonic Neural Activation Function - https://arxiv.org/abs/1908.08681\n ' return x.mul(F.softplus(x).tanh())
class SwishJit(nn.Module): def __init__(self, inplace: bool=False): super(SwishJit, self).__init__() def forward(self, x): return swish_jit(x)