code
stringlengths
17
6.64M
def Ucf101(data_path: str, clip_sampler: ClipSampler, transform: (Callable[([dict[(str, Any)]], dict[(str, Any)])] | None)=None, video_path_prefix: str='', split_id: int=1, split_type: str='train', decode_audio: bool=True, decoder: str='pyav', decoder_args: DictConfig={}) -> LabeledVideoDataset: "A helper functio...
def get_time_difference_indices(indices: NDArray, add_last_indice: bool=False, max_last_indice: int=(- 1)) -> Tuple[(NDArray, NDArray)]: 'Get the indices of frames when time difference is desired. Time difference recquires to have subsequent\n indices to work. This function retrieves lacking indices and avoid ...
def get_video_to_frame_path_fn(fn_type: str='idx', zeros: int=8, incr: int=1) -> Callable: 'Get the function to get video frame paths.\n\n Args:\n fn_type: The function to use. Options are:\n\n * idx: it retrieves a video path frame from video path and the index of the frame.\n\n zeros...
def random_subsample(x: List, num_samples: int=8, time_difference: bool=False) -> Tuple[NDArray]: 'Randomly subsample a list of indices.\n\n Args:\n x: The list to subsample\n num_samples: The number of samples to keep.\n time_difference: If ``True``, retrieve indices to be able to apply t...
def uniform_subsample(x: List, num_samples: int=8, time_difference: bool=False) -> Tuple[NDArray]: 'Unformly subsample a list of indices.\n\n Args:\n x: The list to subsample\n num_samples: The number of samples to keep.\n time_difference: If ``True``, retrieve indices to be able to apply ...
def get_subsample_fn(subsample_type: str='uniform', num_samples: int=8, time_difference: bool=False) -> Callable: "Get the function to subsample video frame indices.\n\n Args:\n subsample_type: The function to use. Options are: ``'uniform'``, ``'random'``.\n num_samples: The number of samples to ...
def remove_suffix(file: Path) -> Path: 'Remove the suffix from a path.\n\n Args:\n file: The path.\n\n Returns:\n The path without the suffix.\n ' return Path(file).with_suffix('')
def get_raw_video_duration(root_folder: str, raw_video: str) -> int: 'Get the video duration from a video extracted in frames folder.\n\n Args:\n root_folder: The root folders of the videos.\n raw_video: The video path.\n\n Returns:\n The video duration.\n ' root_folder = Path(ro...
def get_shard_indices(dataset_size: int, shuffle_shards=True, seed: int=42) -> List[int]: 'Retrieve the indices for the shard.\n\n Args:\n dataset_size: Complete size of the dataset.\n shuffle_shards: Whether to shuffle before sharding.\n seed: Seed for sharding.\n\n Raises:\n No...
class VideoPathHandler(): 'Utility class that handles all deciphering and caching of video paths for encoded and frame videos.' def __init__(self) -> None: self.path_order_cache = {} def video_from_path(self, filepath: str, decode_audio=False, decoder='pyav', num_frames: Optional[int]=None, **kw...
class LinearClassifierEvaluation(pl.LightningModule): 'Linear classifier evaluation for self-supervised learning.\n\n Args:\n trunk: Config to build a trunk.\n classifier: Config to build a classifier.\n optimizer: Config to build an optimizer.\n pretrained_trunk_path: Path to the p...
def compute_moco_loss(q: Tensor, k: Tensor, k_global: Tensor, use_keys: bool, queue: Tensor, temp: float=0.2, rank: int=0) -> Tensor: 'Compute the SCE loss.\n\n Args:\n q: The representations of the queries.\n k: The representations of the keys.\n k_global: The global representations of th...
def compute_mocov3_loss(q: Tensor, k: Tensor, temp: float=1.0, rank: int=0) -> Tensor: 'Compute the MoCov3 loss.\n\n Args:\n q: The representations of the queries.\n k: The global representations of the keys.\n temp: Temperature for softmax.\n rank: Rank of the device for positive l...
def compute_ressl_mask(batch_size: int, num_negatives: int, use_keys: bool=True, rank: int=0, world_size: int=1, device: Any='cpu') -> (Tensor | None): 'Precompute the mask for ReSSL.\n\n Args:\n batch_size: The local batch size.\n num_negatives: The number of negatives besides the non-positive k...
def compute_ressl_loss(q: Tensor, k: Tensor, k_global: Tensor, use_keys: bool, queue: Tensor, mask: (Tensor | None), temp: float=0.1, temp_m: float=0.04, LARGE_NUM: float=1000000000.0) -> Tensor: 'Compute the RESSL loss.\n\n Args:\n q: The representations of the queries.\n k: The representations ...
def compute_sce_mask(batch_size: int, num_negatives: int, use_keys: bool=True, rank: int=0, world_size: int=1, device: Any='cpu') -> Tensor: 'Precompute the mask for SCE.\n\n Args:\n batch_size: The local batch size.\n num_negatives: The number of negatives besides the non-positive key elements.\...
def compute_sce_loss(q: Tensor, k: Tensor, k_global: Tensor, use_keys: bool, queue: Tensor, mask: Tensor, coeff: Tensor, temp: float=0.1, temp_m: float=0.07, LARGE_NUM: float=1000000000.0) -> Tensor: 'Compute the SCE loss.\n\n Args:\n q: The representations of the queries.\n k: The representation...
class DummyModel(EztorchBaseModule, ABC): 'Dummy model to perform test such as profiling dataloading.\n\n Args:\n input_shape: The input shape of the data.\n transform: The configuration of a transform to apply to the data.\n ' def __init__(self, input_shape: int, transform: Optional[Dict...
class EztorchBaseModule(pl.LightningModule): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) def configure_gradient_clipping(self, optimizer: Optimizer, gradient_clip_val: ((int | float) | None)=None, gradient_clip_algorithm: (str | None)=None) -> None: ...
class FinetuningModel(EztorchBaseModule): 'Fine-tuning training.\n\n Args:\n trunk: Config to build a trunk.\n classifier: Config to build a classifier.\n optimizer: Config to build an optimizer for trunk.\n pretrained_trunk_path: Path to the pretrained trunk file.\n trunk_pa...
class LinearHead(Module): 'Build a Linear head with optional dropout and normalization.\n\n Args:\n affine: Use affine in normalization layer.\n bias: Use bias in linear layer. If ``norm_layer``, set to ``False``.\n dropout: Dropout probability, if :math:`0`, no dropout layer.\n dro...
class Linear3DHead(Module): '\n Linear 3D head. This layer performs an optional pooling operation followed by an\n optional dropout, a fully-connected projection, an optional activation layer and a\n global spatiotemporal averaging.\n\n ::\n\n Pool3d\n ...
def create_linear3d_head(*, in_features: int, num_classes: int=400, bn: Union[(str, Callable)]=None, norm: bool=False, pool: Union[(str, Callable)]=AvgPool3d, pool_kernel_size: Tuple[int]=(1, 7, 7), pool_stride: Tuple[int]=(1, 1, 1), pool_padding: Tuple[int]=(0, 0, 0), output_size: Tuple[int]=(1, 1, 1), dropout_rate:...
class MLPHead(Module): 'Build a MLP head with optional dropout and normalization.\n\n Args:\n activation_inplace: Inplace operation for activation layers.\n activation_layer: Activation layer, if str lookup for the module in ``_ACTIVATION_LAYERS`` dictionary.\n affine: If ``True``, use aff...
class VideoResNetHead(Module): '\n ResNet basic head. This layer performs an optional pooling operation followed by an\n optional dropout, a fully-connected projection, an optional activation layer and a\n global spatiotemporal averaging.\n\n ::\n\n Pool3d\n ...
class VideoResNetTemporalHead(Module): 'ResNet basic head for keeping temporal dimension. This layer performs an initial temporal pooling and\n reshape the output.\n\n Args:\n init_std: init std for weights from pytorchvideo.\n ' def __init__(self, init_std: float=0.01) -> None: super...
def create_video_resnet_head(*, in_features: int, num_classes: int=400, pool: Union[(str, Callable)]=AvgPool3d, output_size: Tuple[int]=(1, 1, 1), pool_kernel_size: Tuple[int]=(1, 7, 7), pool_stride: Tuple[int]=(1, 1, 1), pool_padding: Tuple[int]=(0, 0, 0), dropout_rate: float=0.5, activation: Optional[Union[(str, Ca...
def create_video_resnet_temporal_head() -> Module: 'Creates ResNet basic head for keeping temporal dimension.\n\n This layer performs an initial temporal pooling and reshape the output.\n ' return VideoResNetTemporalHead()
class SiameseBaseModel(EztorchBaseModule, ABC): 'Abstract class to represent siamese models.\n\n Subclasses should implement training_step method.\n\n Args:\n trunk: Config to build a trunk.\n optimizer: Config to build optimizers and schedulers.\n projector: Config to build a project.\...
class MoCoModel(ShuffleMomentumQueueBaseModel): 'MoCo model with version 1, 2, 2+, 3 that can be configured.\n\n References:\n - MoCo: https://arxiv.org/abs/1911.05722\n - MoCov2: https://arxiv.org/abs/2003.04297\n - MoCov2+: https://arxiv.org/abs/2011.10566\n - MoCov3: https://arxi...
class MoCov3Model(MomentumSiameseBaseModel): 'MoCov3 that can be configured as in the paper.\n\n References:\n - MoCov3: https://arxiv.org/abs/2104.02057\n\n Args:\n trunk: Config to build a trunk.\n optimizer: Config to build optimizers and schedulers.\n projector: Config to bui...
class MomentumSiameseBaseModel(SiameseBaseModel, ABC): 'Abstract class to represent siamese models with a momentum branch.\n\n Subclasses should implement training_step method.\n\n Args:\n trunk: Config to build a trunk.\n optimizer: Config to build optimizers and schedulers.\n projecto...
class ReSSLModel(ShuffleMomentumQueueBaseModel): 'ReSSL model.\n\n References:\n - ReSSL: https://proceedings.neurips.cc/paper/2021/file/14c4f36143b4b09cbc320d7c95a50ee7-Paper.pdf\n\n Args:\n trunk: Config tu build a trunk.\n optimizer: Config tu build optimizers and schedulers.\n ...
class SCEModel(ShuffleMomentumQueueBaseModel): "SCE model.\n\n References:\n - SCE: https://arxiv.org/pdf/2111.14585.pdf\n\n Args:\n trunk: Config tu build a trunk.\n optimizer: Config tu build optimizers and schedulers.\n projector: Config to build a project.\n predictor:...
class ShuffleMomentumSiameseBaseModel(MomentumSiameseBaseModel, ABC): 'Abstract class to represent siamese models with a momentum branch and possibility to shuffle input elements\n in momentum branch to apply normalization trick from MoCo.\n\n Subclasses should implement training_step method.\n\n Args:\n...
class SimCLRModel(SiameseBaseModel): 'SimCLR model with version 1, 2 that can be configured.\n\n References:\n - SimCLR: https://arxiv.org/abs/2002.05709\n - SimCLRv2: https://arxiv.org/abs/2006.10029\n\n Args:\n trunk: Config tu build a trunk.\n optimizer: Config tu build optimi...
class SoccerNetSpottingModel(EztorchBaseModule): 'Model to perform action spotting.\n\n Args:\n trunk: Config to build a trunk.\n head_class: Config to build a head for classification.\n optimizer: Config to build an optimizer for trunk.\n pretrained_trunk_path: Path to the pretrain...
class SpottingModel(EztorchBaseModule): 'Model to perform spotting.\n\n Args:\n trunk: Config to build a trunk.\n head_class: Config to build a head for classification.\n optimizer: Config to build an optimizer for trunk.\n pretrained_trunk_path: Path to the pretrained trunk file.\n...
class SupervisedModel(EztorchBaseModule): 'Supervised model.\n\n Args:\n model: Config to build a model.\n optimizer: Config to build optimizers and schedulers.\n train_transform: Config to perform transformation on train input.\n val_transform: Config to perform transformation on v...
def create_r2plus1d(*, input_channel: int=3, model_depth: int=50, model_num_class: int=400, dropout_rate: float=0.0, norm: Callable=BatchNorm3d, norm_eps: float=1e-05, norm_momentum: float=0.1, activation: Callable=ReLU, stem_dim_out: int=64, stem_conv_kernel_size: Tuple[int]=(1, 7, 7), stem_conv_stride: Tuple[int]=(...
class LargeR2Plus1dStem(Sequential): 'R(2+1)D stem is different than the default one as it uses separated 3D convolution.' def __init__(self) -> None: super().__init__(Conv3d(3, 83, kernel_size=(1, 7, 7), stride=(1, 2, 2), padding=(0, 3, 3), bias=False), BatchNorm3d(83), ReLU(inplace=True), Conv3d(83...
def create_r2plus1d_18(downsample: bool=True, num_classes: int=101, layers: List[int]=[1, 1, 1, 1], progress: bool=True, pretrained: bool=False, stem: Union[(str, Module)]=LargeR2Plus1dStem, **kwargs) -> Module: 'Build R2+1D_18 from torchvision for video.\n\n Args:\n num_classes: If not :math:`0`, repla...
class SpatioTemporalConv(nn.Module): 'Applies a factored 3D convolution over an input signal composed of several input planes with distinct\n spatial and time axes, by performing a 2D convolution over the spatial axes to an intermediate subspace,\n followed by a 1D convolution over the time axis to produce ...
class SpatioTemporalResBlock(nn.Module): 'Single block for the ResNet network.\n\n Uses SpatioTemporalConv in\n the standard ResNet block layout (conv->batchnorm->ReLU->conv->batchnorm->sum->ReLU)\n Args:\n in_chans: Number of channels in the input tensor.\n out_channels: Number of channels...
class SpatioTemporalResLayer(nn.Module): 'Forms a single layer of the ResNet network, with a number of repeating\n blocks of same output size stacked on top of each other\n Args:\n in_chans: Number of channels in the input tensor.\n out_channels: Number of channels in the output pr...
class R2Plus1DDownSample(nn.Module): 'Forms the overall ResNet feature extractor by initializng 5 layers, with the number of blocks in each layer\n set by layer_sizes, and by performing a global average pool at the end producing a 512-dimensional vector for\n each element in the batch.\n\n Args:\n ...
def create_resnet(name: str, num_classes: int=1000, progress: bool=True, pretrained: bool=False, small_input: bool=False, **kwargs) -> Module: 'Build ResNet from torchvision for image.\n\n Args:\n name: name of the resnet model (such as resnet18).\n num_classes: If not :math:`0`, replace the last...
def create_basic_block(*, dim_in: int, dim_out: int, conv_a_kernel_size: Tuple[int]=(3, 3, 3), conv_a_stride: Tuple[int]=(2, 2, 2), conv_a_padding: Tuple[int]=(1, 1, 1), conv_a: Callable=Conv3d, conv_b_kernel_size: Tuple[int]=(3, 3, 3), conv_b_stride: Tuple[int]=(2, 2, 2), conv_b_padding: Tuple[int]=(1, 1, 1), conv_b...
def create_res_basic_block(*, dim_in: int, dim_out: int, basicblock: Callable, use_shortcut: bool=False, branch_fusion: Callable=_trivial_sum, conv_a_kernel_size: Tuple[int]=(3, 3, 3), conv_a_stride: Tuple[int]=(2, 2, 2), conv_a_padding: Tuple[int]=(1, 1, 1), conv_a: Callable=Conv3d, conv_b_kernel_size: Tuple[int]=(3...
def create_res_basic_stage(*, depth: int, dim_in: int, dim_out: int, basicblock: Callable, conv_a_kernel_size: Union[(Tuple[int], List[Tuple[int]])]=(3, 3, 3), conv_a_stride: Tuple[int]=(2, 2, 2), conv_a_padding: Union[(Tuple[int], List[Tuple[int]])]=(1, 1, 1), conv_a: Callable=Conv3d, conv_b_kernel_size: Tuple[int]=...
def create_resnet3d_basic(*, input_channel: int=3, model_depth: int=50, model_num_class: int=400, dropout_rate: float=0.5, norm: Callable=BatchNorm3d, activation: Callable=ReLU, stem_activation: Optional[Callable]=ReLU, stem_dim_out: int=64, stem_conv_kernel_size: Tuple[int]=(1, 7, 7), stem_conv_stride: Tuple[int]=(1...
class ResBlock(Module): '\n Residual block. Performs a summation between an identity shortcut in branch1 and a\n main block in branch2. When the input and output dimensions are different, a\n convolution followed by a normalization will be performed.\n\n ::\n\n\n ...
class BasicBlock(Module): '\n basicblock block: a sequence of spatiotemporal Convolution, Normalization,\n and Activations repeated in the following order:\n\n ::\n\n\n Conv3d (conv_a)\n ↓\n Norma...
class Swin(nn.Module): 'Swin Transformer\n A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -\n https://arxiv.org/pdf/2103.14030\n Args:\n img_size (int | tuple(int)): Input image size. Default 224\n patch_size (int | tuple(int)): Patc...
def create_swin(img_size: (int | Tuple[(int, int)])=224, patch_size: (int | Tuple[(int, int)])=4, in_chans: int=3, global_pool: str='avg', embed_dim: int=96, depths: Tuple[int]=(2, 2, 6, 2), num_heads: Tuple[int]=(3, 6, 12, 24), window_size: int=7, mlp_ratio: float=4.0, qkv_bias: bool=True, drop_rate: float=0.0, attn...
def create_swin_tiny(*args, **kwargs) -> Swin: return create_swin(*args, patch_size=4, window_size=7, embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), **kwargs)
def create_swin_small(*args, **kwargs) -> Swin: return create_swin(*args, patch_size=4, window_size=7, embed_dim=96, depths=(2, 2, 18, 2), num_heads=(3, 6, 12, 24), **kwargs)
def create_swin_base(*args, **kwargs) -> Swin: return create_swin(*args, patch_size=4, window_size=7, embed_dim=128, depths=(2, 2, 18, 2), num_heads=(4, 8, 16, 32), **kwargs)
@torch.no_grad() def constant_init_(tensor, constant_value=0): nn.init.constant_(tensor, constant_value)
@torch.no_grad() def kaiming_init_(tensor, a=0, mode='fan_out', nonlinearity='relu', distribution='normal'): assert (distribution in ['uniform', 'normal']) if (distribution == 'uniform'): nn.init.kaiming_uniform_(tensor, a=a, mode=mode, nonlinearity=nonlinearity) else: nn.init.kaiming_norm...
class PatchEmbed(nn.Module): 'Images to Patch Embedding.\n\n Args:\n img_size: Size of input image.\n patch_size: Size of one patch.\n tube_size: Size of temporal field of one 3D patch.\n in_chans: Channel num of input features.\n embed_dim: Dimensions of ...
def get_patch_embed(**kwargs) -> nn.Module: if (kwargs['conv_type'] == 'identity'): return nn.Identity() return PatchEmbed(**kwargs)
class VideoHeadModel(Module): 'A general purpose model that handles an encoder and its head.\n\n Args:\n model: A model that precedes the head and is supposed to have initialized weights. Ex: stem + stages.\n head: A network head.\n ' def __init__(self, model: Module, head: Module): ...
def create_video_head_model(model: DictConfig, head: DictConfig): 'Build a video model.\n\n Args:\n model: Config for the model.\n head: Config for the head.\n ' model = hydra.utils.instantiate(model) head = hydra.utils.instantiate(head) video_model = VideoHeadModel(model, head) ...
def create_x3d(*, input_channel: int=3, input_clip_length: int=13, input_crop_size: int=160, model_num_class: int=400, dropout_rate: float=0.5, width_factor: float=2.0, depth_factor: float=2.2, norm: Callable=BatchNorm3d, norm_eps: float=1e-05, norm_momentum: float=0.1, activation: Callable=ReLU, stem_dim_in: int=12,...
def extract_features(model: Module, loader: DataLoader) -> Tuple[(Tensor, Tensor)]: 'Extract features from a model.\n\n Args:\n model: The model to extract features from.\n loader: The dataloader to retrieve features from.\n\n Returns:\n The features and its associated labels.\n ' ...
def group_params_layer_id(model: Module) -> List[Tuple[(int, Tuple[(str, Parameter)])]]: 'Retrive from model the groups of parameters in the different layers.\n\n Args:\n model: The model to retrieve the parameters from.\n\n Returns:\n The list of groups of parameters in the format:\n ...
class GatherLayer(torch.autograd.Function): 'Gather tensor across devices with grad.' @staticmethod def forward(ctx, inp): ctx.save_for_backward(inp) if (dist.is_available() and dist.is_initialized()): output = [torch.zeros_like(inp) for _ in range(dist.get_world_size())] ...
def concat_all_gather_with_backprop(x: Tensor, dim: int=0) -> Tensor: 'Gather tensor across devices with grad.\n\n Args:\n x: Tensor to gather.\n dim: Dimension to concat.\n\n Returns:\n Gathered tensor.\n ' return torch.cat(GatherLayer.apply(x), dim=dim)
@torch.no_grad() def concat_all_gather_without_backprop(x: Tensor, dim: int=0) -> Tensor: 'Gather tensor across devices without grad.\n\n Args:\n x: Tensor to gather.\n dim: Dimension to concat.\n\n Returns:\n Gathered tensor.\n ' if (dist.is_available() and dist.is_initialized()...
@torch.no_grad() def get_world_size() -> int: 'Returns the world size.\n\n Returns:\n The world size.\n ' if (dist.is_available() and dist.is_initialized()): return torch.distributed.get_world_size() return 1
class SplitBatchNorm2D(BatchNorm2d): 'Split batch normalization in several pieces to simulate several devices.\n\n Args:\n num_features: :math:`C` from an expected input of size :math:`(N, C, H, W)`.\n num_splits: Number of devices to simulate.\n ' def __init__(self, num_features: int, nu...
def convert_to_split_batchnorm(module: Module, num_splits: int) -> Module: 'Convert BatchNorm layers to SplitBatchNorm layers in module.\n\n Args:\n module: Module to convert.\n num_splits: Number of splits for the :class:`SplitBatchNorm2D` layers.\n\n Returns:\n The converted module.\n...
class LARS(torch.optim.Optimizer): 'LARS optimizer, no rate scaling or weight decay for parameters <= 1D.\n\n References LARS:\n - https://arxiv.org/pdf/1708.03888.pdf\n\n Args:\n params: Parameters to optimize.\n lr: Learning rate of the optimizer.\n weight_decay: Weight decay t...
def optimizer_factory(name: str, initial_lr: float, model: Module, batch_size: Optional[int]=None, num_steps_per_epoch: Optional[int]=None, layer_decay_lr: (float | None)=None, keys_without_decay: List[str]=[], exclude_wd_norm: bool=False, exclude_wd_bias: bool=False, scaler: Optional[str]=None, params: DictConfig={}...
def optimizer_factory_two_groups(name: str, initial_lr1: float, initial_lr2: float, model1: Module, model2: Module, batch_size: Optional[int]=None, num_steps_per_epoch: Optional[int]=None, exclude_wd_norm: bool=False, exclude_wd_bias: bool=False, scaler: Optional[str]=None, params: DictConfig={}, scheduler: Optional[...
def retrieve_model_params(model: Module, modules_to_filter: Iterable[Module]=[], keys_to_filter: Iterable[str]=[]) -> Tuple[(List[Parameter], List[Parameter])]: 'Retrieve sets of filtered and not filtered parameters from a model.\n\n Args:\n model: Model to retrieve the params from.\n modules_to_...
def filter_learnable_params(parameters: Iterable[Parameter], model: Module) -> List[Parameter]: 'Filter passed parameters to be in learnable parameters list from model. If model do not have\n ``learnable_params`` property defined, return all passed parameters.\n\n Args:\n parameters: Parameters to fi...
def scale_learning_rate(initial_lr: int, scaler: Optional[str]=None, batch_size: Optional[int]=None, multiply_lr: float=1.0) -> int: 'Scale the initial learning rate.\n\n Args:\n initial_lr: Initial learning rate.\n scaler: Scaler rule.\n batch_size: Batch size to scale the learning rate.\...
class LinearWarmupCosineAnnealingLR(_LRScheduler): 'Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr\n and base_lr followed by a cosine annealing schedule between base_lr and eta_min.\n\n Args:\n optimizer: Wrapped optimizer.\n warmup_ep...
def scheduler_factory(optimizer: Optimizer, name: str, params: DictConfig={}, interval: str='epoch', num_steps_per_epoch: Optional[int]=None, scaler: Optional[str]=None, batch_size: Optional[int]=None, multiply_lr: float=1.0) -> Dict[(str, Any)]: "Scheduler factory.\n\n Args:\n optimizer: Optimizer to w...
class ApplyTransformToKey(Module): 'Applies transform to key of dictionary input.\n\n Args:\n key: The dictionary key the transform is applied to.\n transform: The transform that is applied.\n ' def __init__(self, key: str, transform: Module): super().__init__() self._key ...
class ApplyTransformToKeyOnList(Module): "\n Applies transform to key of dictionary input where input is a list\n Args:\n key: the dictionary key the transform is applied to.\n transform: the transform that is applied.\n\n Example::\n >>> transforms.ApplyTransformToKeyOnList(\n ...
class ApplySameTransformToKeyOnList(Module): 'Applies the same transform to key of dictionary input where input is a list.\n\n Args:\n key: the dictionary key the transform is applied to.\n transform: the transform that is applied.\n dim: The dimension to retrieve the various elements of t...
class ApplyTransformInputKeyOnList(ApplyTransformToKeyOnList): 'Apply Transform to the input key.\n\n Args:\n transform: The transform to apply.\n ' def __init__(self, transform: Module): super().__init__('input', transform=transform) def __repr__(self): return f'{self.__cla...
class ApplySameTransformInputKeyOnList(ApplySameTransformToKeyOnList): 'Apply same transform to the input list key.\n\n Args:\n transform: The transform to apply.\n dim: The dimension to retrieve the various elements of the list.\n ' def __init__(self, transform: Module, dim: int=1): ...
class ApplyTransformAudioKeyOnList(ApplyTransformToKeyOnList): 'Apply Transform to the audio key.\n\n Args:\n transform: The transform to apply.\n ' def __init__(self, transform: Module): super().__init__('audio', transform=transform) def __repr__(self): return f'{self.__cla...
class ApplyTransformInputKey(ApplyTransformToKey): 'Apply Transform to the input key.\n\n Args:\n transform: The transform to apply.\n ' def __init__(self, transform: Module): super().__init__('input', transform=transform) def __repr__(self): return f'{self.__class__.__name_...
class ApplyTransformAudioKey(ApplyTransformToKey): 'Apply Transform to the audio key.\n\n Args:\n transform: The transform to apply.\n ' def __init__(self, transform: Module): super().__init__('audio', transform=transform)
class ApplyTransformOnDict(Module): 'Apply Transform to the audio key.\n\n Args:\n transform: The transform to apply.\n ' def __init__(self, transform: Module): super().__init__() self._transform = transform def forward(self, x: Dict[(str, torch.Tensor)]) -> Dict[(str, torch...
class ApplyTransformOnList(Module): 'Apply transform to a list of input.\n\n Args:\n transform: A transform for the list of input.\n list_len: len of the input.\n ' def __init__(self, transform: Module, list_len: int=2) -> None: super().__init__() self.list_len = list_len ...
class ApplyTransformsOnList(Module): 'Apply transform to a list of input.\n\n Args:\n transform: A transform for the list of input.\n list_len: len of the input.\n ' def __init__(self, transforms: List[Module]) -> None: super().__init__() self.list_len = len(transforms) ...
class ApplySameTransformOnList(Module): 'Apply same transform to a list of input by concatenating the inputs and splitting them after.\n\n Args:\n transform: A transform for the list of input.\n list_len: len of the input.\n dim: The dimension to retrieve the various elements of the list.\...
class DictKeepKeys(): 'Keep specified keys in dict.\n\n References:\n - https://github.com/kalyanvasudev/pytorchInput-1/blob/export-D33431232/pytorchInput_trainer/pytorchInput_trainer/datamodule/transforms.py\n\n Args:\n keys: The list of keys to keep.\n ' def __init__(self, keys: List...
class DictKeepInputLabel(DictKeepKeys): "Transform dict to list containing values of only ``'input'`` and ``'label'``." def __init__(self): super().__init__(['input', 'label'])
class DictKeepInputLabelIdx(DictKeepKeys): "Transform dict to list containing values of only ``'input'``, ``'label'``, ``'index'`` and\n ``'aug_index'``." def __init__(self): super().__init__(['input', 'label', 'idx', 'aug_index'])
class DictToListFromKeys(): 'Transform dict to list containing values of only specified keys.\n\n References:\n - https://github.com/kalyanvasudev/pytorchInput-1/blob/export-D33431232/pytorchInput_trainer/pytorchInput_trainer/datamodule/transforms.py\n\n Args:\n keys: The list of keys to keep....
class DictToListInputLabel(DictToListFromKeys): "Transform dict to list containing values of only ``'input'`` and ``'label'``.\n\n Args:\n transform: The transform to apply.\n " def __init__(self): super().__init__(['input', 'label']) def __call__(self, x: Dict[(str, Tensor)]) -> Li...
def div_255(input: Tensor, inplace: bool=True, dtype: dtype=torch.get_default_dtype()) -> Tensor: 'Divide the given tensor x by 255.\n\n Args:\n input: The input tensor.\n inplace: Whether to perform the operation inplace. Performed after dtype conversion.\n dtype: dtype to convert the ten...
class Div255Input(Module): 'Perform Division by 255 on a tensor or list of tensor.' def __init__(self, inplace: bool=True, dtype: dtype=torch.get_default_dtype()) -> None: super().__init__() self.inplace = inplace self.dtype = dtype def forward(self, x: (Tensor | List[Tensor])) -...