code stringlengths 17 6.64M |
|---|
def add_weight_decay(weight_decay: float, filter_fn: Optional[FilterFn]=None) -> optax.GradientTransformation:
'Adds a weight decay to the update.\n\n Args:\n weight_decay: weight_decay coeficient.\n filter_fn: an optional filter function.\n\n Returns:\n An (init_fn, update_fn) tuple.\n '
... |
def lars(learning_rate: ScalarOrSchedule, weight_decay: float=0.0, momentum: float=0.9, eta: float=0.001, weight_decay_filter: Optional[FilterFn]=None, lars_adaptation_filter: Optional[FilterFn]=None) -> optax.GradientTransformation:
"Creates lars optimizer with weight decay.\n\n References:\n [You et a... |
def _rename(kwargs, originals, new):
for (o, n) in zip(originals, new):
o = kwargs.pop(o, None)
if (o is not None):
kwargs[n] = o
|
def _erase(kwargs, names):
for u in names:
kwargs.pop(u, None)
|
def create_optax_optim(name, learning_rate=None, momentum=0.9, weight_decay=0, **kwargs):
" Optimizer Factory\n\n Args:\n learning_rate (float): specify learning rate or leave up to scheduler / optim if None\n weight_decay (float): weight decay to apply to all params, not applied if 0\n **... |
def get_like_padding(kernel_size: int, stride: int=1, dilation: int=1, **_) -> int:
padding = (((stride - 1) + (dilation * (kernel_size - 1))) // 2)
return padding
|
def _randomly_negate_tensor(tensor):
'With 50% prob turn the tensor negative.'
should_flip = tf.cast(tf.floor((tf.random.uniform([]) + 0.5)), tf.bool)
final_tensor = tf.cond(should_flip, (lambda : tensor), (lambda : (- tensor)))
return final_tensor
|
def _rotate_level(level):
level = ((level / _MAX_LEVEL) * 30.0)
level = _randomly_negate_tensor(level)
return (level,)
|
def _shrink_level(level):
'Converts level to ratio by which we shrink the image content.'
if (level == 0):
return (1.0,)
level = ((2.0 / (_MAX_LEVEL / level)) + 0.9)
return (level,)
|
def _enhance_level(level):
level = ((level / _MAX_LEVEL) * 0.9)
level = (1.0 + _randomly_negate_tensor(level))
level = tf.clip_by_value(level, 0.0, 3.0)
return (level,)
|
def _shear_level(level):
level = ((level / _MAX_LEVEL) * 0.3)
level = _randomly_negate_tensor(level)
return (level,)
|
def _translate_level(level, translate_const):
level = ((level / _MAX_LEVEL) * float(translate_const))
level = _randomly_negate_tensor(level)
return (level,)
|
def _get_args_fn(hparams):
return {'AutoContrast': (lambda level: ()), 'Equalize': (lambda level: ()), 'Invert': (lambda level: ()), 'Rotate': (lambda level: (_rotate_level(level) + (hparams['fill_value'],))), 'Posterize': (lambda level: (int(((level / _MAX_LEVEL) * 4)),)), 'Solarize': (lambda level: (int(((level... |
class RandAugment():
'Random augment with fixed magnitude.\n FIXME this is a class based impl or RA from fixmatch, it needs some changes before using\n '
def __init__(self, num_layers=2, prob_to_apply=None, magnitude=None, num_levels=10):
'Initialized rand augment.\n Args:\n n... |
def _parse_policy_info(name, prob, level, augmentation_hparams):
'Return the function that corresponds to `name` and update `level` param.'
func = NAME_TO_FUNC[name]
args = _get_args_fn(augmentation_hparams)[name](level)
return (func, prob, args)
|
def _apply_func_with_prob(func, image, args, prob):
'Apply `func` to image w/ `args` as input with probability `prob`.'
assert isinstance(args, tuple)
should_apply_op = tf.cast(tf.floor((tf.random.uniform([], dtype=tf.float32) + prob)), tf.bool)
augmented_image = tf.cond(should_apply_op, (lambda : fun... |
def select_and_apply_random_policy(policies, image):
'Select a random policy from `policies` and apply it to `image`.'
policy_to_select = tf.random.uniform([], maxval=len(policies), dtype=tf.int32)
for (i, policy) in enumerate(policies):
image = tf.cond(tf.equal(i, policy_to_select), (lambda selec... |
def distort_image_with_randaugment(image, num_layers, magnitude, fill_value=(128, 128, 128)):
'Applies the RandAugment policy to `image`.\n\n RandAugment is from the paper https://arxiv.org/abs/1909.13719,\n\n Args:\n image: `Tensor` of shape [height, width, 3] representing an image.\n num_lay... |
class Split(enum.Enum):
'Imagenet dataset split.'
TRAIN = 1
TEST = 2
@property
def num_examples(self):
return {Split.TRAIN: 1281167, Split.TEST: 50000}[self]
|
def _to_tfds_split(split: Split) -> tfds.Split:
'Returns the TFDS split appropriately sharded.'
if (split == Split.TRAIN):
return tfds.Split.TRAIN
else:
assert (split == Split.TEST)
return tfds.Split.VALIDATION
|
def _shard(split: Split, shard_index: int, num_shards: int) -> Tuple[(int, int)]:
'Returns [start, end) for the given shard index.'
assert (shard_index < num_shards)
arange = np.arange(split.num_examples)
shard_range = np.array_split(arange, num_shards)[shard_index]
(start, end) = (shard_range[0],... |
def load(split: Split, is_training: bool, batch_dims: Sequence[int], image_size: int=IMAGE_SIZE, chw: bool=False, dataset_name='imagenet2012:5.0.0', mean: Optional[Tuple[float]]=None, std: Optional[Tuple[float]]=None, interpolation: str='bicubic', tfds_data_dir: Optional[str]=None):
mean = (MEAN_RGB if (mean is N... |
def normalize_image_for_view(image, mean=MEAN_RGB, std=STDDEV_RGB):
'Normalizes dataset image into the format for viewing.'
image *= np.reshape(mean, (3, 1, 1))
image += np.reshape(std, (3, 1, 1))
image = np.transpose(image, (1, 2, 0))
return image.clip(0, 255).round().astype('uint8')
|
def _preprocess_image(image_bytes: tf.Tensor, is_training: bool, image_size: int=IMAGE_SIZE, mean=MEAN_RGB, std=STDDEV_RGB, interpolation=tf.image.ResizeMethod.BICUBIC) -> tf.Tensor:
'Returns processed and resized images.'
if is_training:
image = _decode_and_random_crop(image_bytes, image_size=image_s... |
def _normalize_image(image: tf.Tensor, mean=MEAN_RGB, std=STDDEV_RGB) -> tf.Tensor:
'Normalize the image to zero mean and unit variance.'
image -= tf.constant(mean, shape=[1, 1, 3], dtype=image.dtype)
image /= tf.constant(std, shape=[1, 1, 3], dtype=image.dtype)
return image
|
def _distorted_bounding_box_crop(image_bytes: tf.Tensor, jpeg_shape: tf.Tensor, bbox: tf.Tensor, min_object_covered: float, aspect_ratio_range: Tuple[(float, float)], area_range: Tuple[(float, float)], max_attempts: int) -> tf.Tensor:
'Generates cropped_image using one of the bboxes randomly distorted.'
(bbox... |
def _decode_and_random_crop(image_bytes: tf.Tensor, image_size: int=224) -> tf.Tensor:
'Make a random crop of image.'
jpeg_shape = tf.image.extract_jpeg_shape(image_bytes)
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, jpeg... |
def _decode_and_center_crop(image_bytes: tf.Tensor, image_size: int=224, jpeg_shape: Optional[tf.Tensor]=None) -> tf.Tensor:
'Crops to center of image with padding then scales.'
if (jpeg_shape is None):
jpeg_shape = tf.image.extract_jpeg_shape(image_bytes)
image_height = jpeg_shape[0]
image_wi... |
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):
'Generates cropped_image using one of the bboxes randomly distorted.\n\n See `tf.image.sample_distorted_bounding_box` for more documentation.\n\n Args:\n ... |
def resize(image, image_size, interpolation=tf.image.ResizeMethod.BICUBIC, antialias=True):
return tf.image.resize([image], [image_size, image_size], method=interpolation, antialias=antialias)[0]
|
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, interpolation):
'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)), ar... |
def decode_and_center_crop(image_bytes, image_size, interpolation):
'Crops to center of image with padding then scales image_size.'
shape = tf.io.extract_jpeg_shape(image_bytes)
image_height = shape[0]
image_width = shape[1]
padded_center_crop_size = tf.cast(((image_size / (image_size + CROP_PADDI... |
def normalize_image(image, mean=MEAN_RGB, std=STDDEV_RGB):
image -= tf.constant(mean, shape=[1, 1, 3], dtype=image.dtype)
image /= tf.constant(std, shape=[1, 1, 3], dtype=image.dtype)
return image
|
def preprocess_for_train(image_bytes, dtype=tf.float32, image_size=IMAGE_SIZE, mean=MEAN_RGB, std=STDDEV_RGB, interpolation=tf.image.ResizeMethod.BICUBIC, augment_name=None, randaug_num_layers=None, randaug_magnitude=None):
'Preprocesses the given image for training.\n\n Args:\n image_bytes: `Tensor` repr... |
def preprocess_for_eval(image_bytes, dtype=tf.float32, image_size=IMAGE_SIZE, mean=MEAN_RGB, std=STDDEV_RGB, interpolation=tf.image.ResizeMethod.BICUBIC):
'Preprocesses the given image for evaluation.\n\n Args:\n image_bytes: `Tensor` representing an image binary of arbitrary size.\n dtype: data type... |
def create_split(dataset_builder: tfds.core.DatasetBuilder, batch_size: int, train: bool=True, half_precision: bool=False, image_size: int=IMAGE_SIZE, mean: Optional[Tuple[float]]=None, std: Optional[Tuple[float]]=None, interpolation: str='bicubic', augment_name: Optional[str]=None, randaug_num_layers: Optional[int]=... |
def random_apply(func, p, x):
'Randomly apply function func to x with probability p.'
return tf.cond(tf.less(tf.random.uniform([], minval=0, maxval=1, dtype=tf.float32), tf.cast(p, tf.float32)), (lambda : func(x)), (lambda : x))
|
def random_brightness(image, max_delta, impl='simclrv2'):
'A multiplicative vs additive change of brightness.'
if (impl == 'simclrv2'):
factor = tf.random.uniform([], tf.maximum((1.0 - max_delta), 0), (1.0 + max_delta))
image = (image * factor)
elif (impl == 'simclrv1'):
image = tf... |
def to_grayscale(image, keep_channels=True):
image = tf.image.rgb_to_grayscale(image)
if keep_channels:
image = tf.tile(image, [1, 1, 3])
return image
|
def color_jitter(image, strength, random_order=True, impl='simclrv2'):
"Distorts the color of the image.\n\n Args:\n image: The input image tensor.\n strength: the floating number for the strength of the color augmentation.\n random_order: A bool, specifying whether to randomize the jittering or... |
def color_jitter_nonrand(image, brightness=0, contrast=0, saturation=0, hue=0, impl='simclrv2'):
"Distorts the color of the image (jittering order is fixed).\n\n Args:\n image: The input image tensor.\n brightness: A float, specifying the brightness for color jitter.\n contrast: A float, specify... |
def color_jitter_rand(image, brightness=0, contrast=0, saturation=0, hue=0, impl='simclrv2'):
"Distorts the color of the image (jittering order is random).\n\n Args:\n image: The input image tensor.\n brightness: A float, specifying the brightness for color jitter.\n contrast: A float, specifyin... |
def _compute_crop_shape(image_height, image_width, aspect_ratio, crop_proportion):
'Compute aspect ratio-preserving shape for central crop.\n\n The resulting shape retains `crop_proportion` along one side and a proportion\n less than or equal to `crop_proportion` along the other side.\n\n Args:\n im... |
def center_crop(image, height, width, crop_proportion):
'Crops to center of image and rescales to desired size.\n\n Args:\n image: Image Tensor to crop.\n height: Height of image to be cropped.\n width: Width of image to be cropped.\n crop_proportion: Proportion of image to retain along the... |
def distorted_bounding_box_crop(image, 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 Args:... |
def crop_and_resize(image, height, width):
'Make a random crop and resize it to height `height` and width `width`.\n\n Args:\n image: Tensor representing the image.\n height: Desired image height.\n width: Desired image width.\n\n Returns:\n A `height` x `width` x channels Tensor holding... |
def gaussian_blur(image, kernel_size, sigma, padding='SAME'):
"Blurs the given image with separable convolution.\n\n\n Args:\n image: Tensor of shape [height, width, channels] and dtype float to blur.\n kernel_size: Integer Tensor for the size of the blur kernel. This is should\n be an odd num... |
def random_crop_with_resize(image, height, width, p=1.0):
'Randomly crop and resize an image.\n\n Args:\n image: `Tensor` representing an image of arbitrary size.\n height: Height of output image.\n width: Width of output image.\n p: Probability of applying this transformation.\n\n Retur... |
def random_color_jitter(image, p=1.0, impl='simclrv2'):
def _transform(image):
color_jitter_t = functools.partial(color_jitter, strength=FLAGS.color_jitter_strength, impl=impl)
image = random_apply(color_jitter_t, p=0.8, x=image)
return random_apply(to_grayscale, p=0.2, x=image)
retur... |
def random_blur(image, height, width, p=1.0):
'Randomly blur an image.\n\n Args:\n image: `Tensor` representing an image of arbitrary size.\n height: Height of output image.\n width: Width of output image.\n p: probability of applying this transformation.\n\n Returns:\n A preprocess... |
def batch_random_blur(images_list, height, width, blur_probability=0.5):
'Apply efficient batch data transformations.\n\n Args:\n images_list: a list of image tensors.\n height: the height of image.\n width: the width of image.\n blur_probability: the probaility to apply the blur operator.\... |
def preprocess_for_train(image, height, width, color_distort=True, crop=True, flip=True, impl='simclrv2'):
"Preprocesses the given image for training.\n\n Args:\n image: `Tensor` representing an image of arbitrary size.\n height: Height of output image.\n width: Width of output image.\n col... |
def preprocess_for_eval(image, height, width, crop=True):
'Preprocesses the given image for evaluation.\n\n Args:\n image: `Tensor` representing an image of arbitrary size.\n height: Height of output image.\n width: Width of output image.\n crop: Whether or not to (center) crop the test ima... |
def preprocess_image(image, height, width, is_training=False, color_distort=True, test_crop=True):
'Preprocesses the given image.\n\n Args:\n image: `Tensor` representing an image of arbitrary size.\n height: Height of output image.\n width: Width of output image.\n is_training: `bool` for ... |
def create_conv(features, kernel_size, conv_layer=None, **kwargs):
' Select a convolution implementation based on arguments\n Creates and returns one of Conv, MixedConv, or CondConv (TODO)\n '
conv_layer = (conv2d if (conv_layer is None) else conv_layer)
if isinstance(kernel_size, list):
ass... |
class SqueezeExcite(nn.Module):
num_features: int
block_features: int = None
se_ratio: float = 0.25
divisor: int = 1
reduce_from_block: bool = True
dtype: Dtype = jnp.float32
conv_layer: ModuleDef = conv2d
act_fn: Callable = nn.relu
bound_act_fn: Optional[Callable] = None
gate_... |
class ConvBnAct(nn.Module):
out_features: int
in_features: int = None
kernel_size: int = 3
stride: int = 1
dilation: int = 1
pad_type: str = 'LIKE'
conv_layer: ModuleDef = conv2d
norm_layer: ModuleDef = batchnorm2d
act_fn: Callable = nn.relu
@nn.compact
def __call__(self, ... |
class DepthwiseSeparable(nn.Module):
' DepthwiseSeparable block\n Used for DS convs in MobileNet-V1 and in the place of IR blocks that have no expansion\n (factor of 1.0). This is an alternative to having a IR with an optional first pw conv.\n '
in_features: int
out_features: int
dw_kernel_si... |
class InvertedResidual(nn.Module):
' Inverted residual block w/ optional SE and CondConv routing'
in_features: int
out_features: int
exp_kernel_size: int = 1
dw_kernel_size: int = 3
pw_kernel_size: int = 1
stride: int = 1
dilation: int = 1
pad_type: str = 'LIKE'
noskip: bool = ... |
class EdgeResidual(nn.Module):
' Residual block with expansion convolution followed by pointwise-linear w/ stride'
in_features: int
out_features: int
exp_kernel_size: int = 1
dw_kernel_size: int = 3
pw_kernel_size: int = 1
stride: int = 1
dilation: int = 1
pad_type: str = 'LIKE'
... |
class Head(nn.Module):
' Standard Head from EfficientNet, MixNet, MNasNet, MobileNetV2, etc. '
num_features: int
num_classes: int = 1000
global_pool: str = 'avg'
drop_rate: float = 0.0
dtype: Dtype = jnp.float32
conv_layer: ModuleDef = conv2d
norm_layer: ModuleDef = batchnorm2d
lin... |
class EfficientHead(nn.Module):
' EfficientHead for MobileNetV3. '
num_features: int
num_classes: int = 1000
global_pool: str = 'avg'
drop_rate: float = 0.0
dtype: Dtype = jnp.float32
conv_layer: ModuleDef = conv2d
norm_layer: ModuleDef = None
linear_layer: ModuleDef = linear
a... |
def chan_to_features(kwargs):
in_chs = kwargs.pop('in_chs', None)
if (in_chs is not None):
kwargs['in_features'] = in_chs
out_chs = kwargs.pop('out_chs', None)
if (out_chs is not None):
kwargs['out_features'] = out_chs
return kwargs
|
class BlockFactory():
@staticmethod
def CondConv(stage_idx, block_idx, **block_args):
assert False, 'Not currently impl'
@staticmethod
def InvertedResidual(stage_idx, block_idx, **block_args):
block_args = chan_to_features(block_args)
return InvertedResidual(**block_args, nam... |
class EfficientNet(nn.Module):
' EfficientNet (and other MBConvNets)\n * EfficientNet B0-B8, L2\n * EfficientNet-EdgeTPU\n * EfficientNet-Lite\n * MixNet S, M, L, XL\n * MobileNetV3\n * MobileNetV2\n * MnasNet A1, B1, and small\n * FBNet C\n * Single-Path NAS Pixel1\n ... |
def _filter(state_dict):
' convert state dict keys from pytorch style origins to flax linen '
out = {}
p_blocks = re.compile('blocks\\.(\\d)\\.(\\d)')
p_bn_scale = re.compile('bn(\\w*)\\.weight')
for (k, v) in state_dict.items():
k = p_blocks.sub('blocks_\\1_\\2', k)
k = p_bn_scale... |
def create_model(variant, pretrained=False, rng=None, input_shape=None, dtype=jnp.float32, **kwargs):
model_cfg = get_model_cfg(variant)
model_args = model_cfg['arch_fn'](variant, **model_cfg['arch_cfg'])
model_args.update(kwargs)
se_args = model_args.pop('se_cfg', {})
if ('se_layer' not in model_... |
@struct.dataclass
class EmaState():
decay: float = struct.field(pytree_node=False, default=0.0)
variables: flax.core.FrozenDict[(str, Any)] = None
@staticmethod
def create(decay, variables):
'Initialize ema state'
if (decay == 0.0):
return EmaState()
ema_variables ... |
def load_pretrained(variables, url='', default_cfg=None, filter_fn=None):
if (not url):
assert ((default_cfg is not None) and default_cfg['url'])
url = default_cfg['url']
state_dict = load_state_dict_from_url(url, transpose=True)
(source_params, source_state) = split_state_dict(state_dict)... |
def get_act_fn(name='relu', **kwargs):
name = name.lower()
assert (name in _ACT_FN)
act_fn = _ACT_FN[name]
if kwargs:
act_fn = partial(act_fn, **kwargs)
return act_fn
|
def conv2d(features: int, kernel_size: int, stride: Optional[int]=None, padding: Union[(str, Tuple[(int, int)])]=0, dilation: Optional[int]=None, groups: int=1, bias: bool=False, dtype: Dtype=jnp.float32, precision: Any=None, name: Optional[str]=None, kernel_init: Callable[([PRNGKey, Shape, Dtype], Array)]=default_ke... |
def linear(features: int, bias: bool=True, dtype: Dtype=jnp.float32, name: str=None, kernel_init: Callable[([PRNGKey, Shape, Dtype], Array)]=default_kernel_init, bias_init: Callable[([PRNGKey, Shape, Dtype], Array)]=initializers.zeros):
return nn.Dense(features=features, use_bias=bias, dtype=dtype, name=name, ker... |
def _split_channels(num_feat, num_groups):
split = [(num_feat // num_groups) for _ in range(num_groups)]
split[0] += (num_feat - sum(split))
return split
|
def _to_list(x):
if isinstance(x, int):
return [x]
return x
|
class MixedConv(nn.Module):
' Mixed Grouped Convolution\n Based on MDConv and GroupedConv in MixNet impl:\n https://github.com/tensorflow/tpu/blob/master/models/official/mnasnet/mixnet/custom_layers.py\n '
features: int
kernel_size: Union[(List[int], int)] = 3
dilation: int = 1
stride... |
def _absolute_dims(rank, dims):
return tuple([((rank + dim) if (dim < 0) else dim) for dim in dims])
|
class BatchNorm(nn.Module):
'BatchNorm Module.\n\n NOTE: A BatchNorm layer similar to Flax ver, but with diff of squares for var cal for numerical\n comparisons. Also, removed cross-process reduction in this variation (for now).\n\n Attributes:\n axis: the feature or non-batch axis of the input.\n... |
class FlaxBatchNorm(nn.Module):
' FlaxBatchNorm Module.\n\n NOTE: A copy of the official Flax BN layer, w/ diff of squares variance and cross-process batch stats syncing.\n\n Attributes:\n axis: the feature or non-batch axis of the input.\n momentum: decay rate for the exponential moving avera... |
class L1BatchNorm(nn.Module):
'L1 BatchNorm Module.\n\n Attributes:\n axis: the feature or non-batch axis of the input.\n momentum: decay rate for the exponential moving average of the batch statistics.\n epsilon: a small float added to variance to avoid dividing by zero.\n dtype: t... |
def batchnorm2d(eps=0.001, momentum=0.99, affine=True, dtype: Dtype=jnp.float32, name: Optional[str]=None, variant: str='', bias_init: Callable[([PRNGKey, Shape, Dtype], Array)]=initializers.zeros, weight_init: Callable[([PRNGKey, Shape, Dtype], Array)]=initializers.ones):
layer = BatchNorm
if (variant == 'fl... |
class Dropout(nn.Module):
' Dropout layer.\n Attributes:\n rate: the dropout probability. (_not_ the keep rate!)\n '
rate: float
@nn.compact
def __call__(self, x, training: bool, rng: PRNGKey=None):
'Applies a random dropout mask to the input.\n Args:\n ... |
def drop_path(x: jnp.array, drop_rate: float=0.0, rng=None) -> jnp.array:
"Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\n\n This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,\n the original name is misleading as 'Drop Conne... |
class DropPath(nn.Module):
rate: float = 0.0
@nn.compact
def __call__(self, x, training: bool, rng: PRNGKey=None):
if ((not training) or (self.rate == 0.0)):
return x
if (rng is None):
rng = self.make_rng('dropout')
return drop_path(x, self.rate, rng)
|
def create_conv(in_channels, out_channels, kernel_size, conv_layer=None, **kwargs):
' Select a convolution implementation based on arguments\n Creates and returns one of Conv, MixedConv, or CondConv (TODO)\n '
conv_layer = (Conv2d if (conv_layer is None) else conv_layer)
if isinstance(kernel_size, l... |
class SqueezeExcite(Module):
def __init__(self, in_chs, se_ratio=0.25, block_chs=None, reduce_from_block=True, conv_layer=Conv2d, act_fn=F.relu, bound_act_fn=None, gate_fn=F.sigmoid, divisor=1):
super(SqueezeExcite, self).__init__()
base_features = (block_chs if (block_chs and reduce_from_block) ... |
class ConvBnAct(Module):
def __init__(self, in_chs, out_chs, kernel_size, stride=1, dilation=1, pad_type='LIKE', conv_layer=Conv2d, norm_layer=BatchNorm2d, act_fn=F.relu):
super(ConvBnAct, self).__init__()
self.conv = conv_layer(in_chs, out_chs, kernel_size, stride=stride, dilation=dilation, padd... |
class DepthwiseSeparable(Module):
' DepthwiseSeparable block\n Used for DS convs in MobileNet-V1 and in the place of IR blocks that have no expansion\n (factor of 1.0). This is an alternative to having a IR with an optional first pw conv.\n '
def __init__(self, in_chs, out_chs, dw_kernel_size=3, str... |
class InvertedResidual(Module):
' Inverted residual block w/ optional SE and CondConv routing'
def __init__(self, in_chs, out_chs, dw_kernel_size=3, stride=1, dilation=1, pad_type='LIKE', noskip=False, exp_ratio=1.0, exp_kernel_size=1, pw_kernel_size=1, se_ratio=0.0, conv_layer=Conv2d, norm_layer=BatchNorm2d... |
class EdgeResidual(Module):
' Residual block with expansion convolution followed by pointwise-linear w/ stride'
def __init__(self, in_chs, out_chs, exp_kernel_size=3, exp_ratio=1.0, fake_in_chs=0, stride=1, dilation=1, pad_type='LIKE', noskip=False, pw_kernel_size=1, se_ratio=0.0, conv_layer=Conv2d, norm_lay... |
class EfficientHead(Module):
' EfficientHead from MobileNetV3 '
def __init__(self, in_chs: int, num_features: int, num_classes: int=1000, global_pool: str='avg', act_fn='relu', conv_layer=Conv2d, norm_layer=None):
self.global_pool = global_pool
self.conv_pw = conv_layer(in_chs, num_features, ... |
class Head(Module):
' Standard Head from EfficientNet, MixNet, MNasNet, MobileNetV2, etc. '
def __init__(self, in_chs: int, num_features: int, num_classes: int=1000, global_pool: str='avg', act_fn=F.relu, conv_layer=Conv2d, norm_layer=BatchNorm2d):
self.global_pool = global_pool
self.conv_pw ... |
class BlockFactory():
@staticmethod
def CondConv(stage_idx, block_idx, **block_args):
assert False, 'Not currently impl'
@staticmethod
def InvertedResidual(stage_idx, block_idx, **block_args):
return InvertedResidual(**block_args)
@staticmethod
def DepthwiseSeparable(stage_i... |
class EfficientNet(Module):
' EfficientNet (and other MBConvNets)\n * EfficientNet B0-B8, L2\n * EfficientNet-EdgeTPU\n * EfficientNet-Lite\n * MixNet S, M, L, XL\n * MobileNetV3\n * MobileNetV2\n * MnasNet A1, B1, and small\n * FBNet C\n * Single-Path NAS Pixel1\n ... |
def create_model(variant, pretrained=False, **kwargs):
model_cfg = get_model_cfg(variant)
model_args = model_cfg['arch_fn'](variant, **model_cfg['arch_cfg'])
model_args.update(kwargs)
se_args = model_args.pop('se_cfg', {})
if ('se_layer' not in model_args):
if ('bound_act_fn' in se_args):
... |
def load_pretrained(model, url='', default_cfg=None, filter_fn=None):
if (not url):
assert ((default_cfg is not None) and default_cfg['url'])
url = default_cfg['url']
model_vars = model.vars()
jax_state_dict = load_state_dict_from_url(url=url, transpose=False)
if (filter_fn is not None... |
def get_act_fn(name='relu', **kwargs):
name = name.lower()
assert (name in _ACT_FN)
act_fn = _ACT_FN[name]
if kwargs:
act_fn = partial(act_fn, **kwargs)
return act_fn
|
def drop_path(x: JaxArray, drop_prob: float=0.0, generator=random.DEFAULT_GENERATOR) -> JaxArray:
"Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\n\n This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,\n the original name is m... |
class Conv2d(Module):
'Applies a 2D convolution on a 4D-input batch of shape (N,C,H,W).'
def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[(Tuple[(int, int)], int)], stride: Union[(Tuple[(int, int)], int)]=1, padding: Union[(str, Tuple[(int, int)], int)]=0, dilation: Union[(Tuple[(in... |
class Linear(Module):
'Applies a linear transformation on an input batch.'
def __init__(self, in_features: int, out_features: int, bias: bool=True, weight_init: Callable=xavier_normal, bias_init: Callable=jnp.zeros):
'Creates a Linear module instance.\n\n Args:\n in_features: number... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.