code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def read_csv(csv_file, class_whitelist=None): """Loads boxes and class labels from a CSV file in the AVA format. CSV file format described at https://research.google.com/ava/download.html. Args: csv_file: A file object. class_whitelist: If provided, boxes corresponding to (integer) class ...
Loads boxes and class labels from a CSV file in the AVA format. CSV file format described at https://research.google.com/ava/download.html. Args: csv_file: A file object. class_whitelist: If provided, boxes corresponding to (integer) class labels not in this set are skipped. Retur...
read_csv
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_utils.py
Apache-2.0
def _import_ground_truth(ground_truth_filename): """Read ground truth file and return the ground truth instances and the activity classes. Args: ground_truth_filename (str): Full path to the ground truth json file. Returns: tuple[list, dict]: (gr...
Read ground truth file and return the ground truth instances and the activity classes. Args: ground_truth_filename (str): Full path to the ground truth json file. Returns: tuple[list, dict]: (ground_truth, activity_index). ground_truth co...
_import_ground_truth
python
open-mmlab/mmaction2
mmaction/evaluation/functional/eval_detection.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py
Apache-2.0
def _import_prediction(self, prediction_filename): """Read prediction file and return the prediction instances. Args: prediction_filename (str): Full path to the prediction json file. Returns: List: List containing the prediction instances (dictionaries). """ ...
Read prediction file and return the prediction instances. Args: prediction_filename (str): Full path to the prediction json file. Returns: List: List containing the prediction instances (dictionaries).
_import_prediction
python
open-mmlab/mmaction2
mmaction/evaluation/functional/eval_detection.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py
Apache-2.0
def wrapper_compute_average_precision(self): """Computes average precision for each class.""" ap = np.zeros((len(self.tiou_thresholds), len(self.activity_index))) # Adaptation to query faster ground_truth_by_label = [] prediction_by_label = [] for i in range(len(self.act...
Computes average precision for each class.
wrapper_compute_average_precision
python
open-mmlab/mmaction2
mmaction/evaluation/functional/eval_detection.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py
Apache-2.0
def evaluate(self): """Evaluates a prediction file. For the detection task we measure the interpolated mean average precision to measure the performance of a method. """ self.ap = self.wrapper_compute_average_precision() self.mAP = self.ap.mean(axis=1) self.aver...
Evaluates a prediction file. For the detection task we measure the interpolated mean average precision to measure the performance of a method.
evaluate
python
open-mmlab/mmaction2
mmaction/evaluation/functional/eval_detection.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py
Apache-2.0
def compute_average_precision_detection(ground_truth, prediction, tiou_thresholds=np.linspace( 0.5, 0.95, 10)): """Compute average precision (detection task) between ground truth and predi...
Compute average precision (detection task) between ground truth and predictions data frames. If multiple predictions occurs for the same predicted segment, only the one with highest score is matches as true positive. This code is greatly inspired by Pascal VOC devkit. Args: ground_truth (list[d...
compute_average_precision_detection
python
open-mmlab/mmaction2
mmaction/evaluation/functional/eval_detection.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/eval_detection.py
Apache-2.0
def overlap2d_voc(b1, b2): """Compute the overlaps between a set of boxes b1 and one box b2.""" xmin = np.maximum(b1[:, 0], b2[:, 0]) ymin = np.maximum(b1[:, 1], b2[:, 1]) xmax = np.minimum(b1[:, 2], b2[:, 2]) ymax = np.minimum(b1[:, 3], b2[:, 3]) width = np.maximum(0, xmax - xmin) height =...
Compute the overlaps between a set of boxes b1 and one box b2.
overlap2d_voc
python
open-mmlab/mmaction2
mmaction/evaluation/functional/multisports_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py
Apache-2.0
def iou2d_voc(b1, b2): """Compute the IoU between a set of boxes b1 and 1 box b2.""" if b1.ndim == 1: b1 = b1[None, :] if b2.ndim == 1: b2 = b2[None, :] assert b2.shape[0] == 1 ov = overlap2d_voc(b1, b2) return ov / (area2d_voc(b1) + area2d_voc(b2) - ov)
Compute the IoU between a set of boxes b1 and 1 box b2.
iou2d_voc
python
open-mmlab/mmaction2
mmaction/evaluation/functional/multisports_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py
Apache-2.0
def iou3d_voc(b1, b2): """Compute the IoU between two tubes with same temporal extent.""" assert b1.shape[0] == b2.shape[0] assert np.all(b1[:, 0] == b2[:, 0]) ov = overlap2d_voc(b1[:, 1:5], b2[:, 1:5]) return np.mean(ov / (area2d_voc(b1[:, 1:5]) + area2d_voc(b2[:, 1:5]) - ov))
Compute the IoU between two tubes with same temporal extent.
iou3d_voc
python
open-mmlab/mmaction2
mmaction/evaluation/functional/multisports_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py
Apache-2.0
def iou3dt_voc(b1, b2, spatialonly=False, temporalonly=False): """Compute the spatio-temporal IoU between two tubes.""" tmin = max(b1[0, 0], b2[0, 0]) tmax = min(b1[-1, 0], b2[-1, 0]) if tmax < tmin: return 0.0 temporal_inter = tmax - tmin temporal_union = max(b1[-1, 0], b2[-1, 0]) - m...
Compute the spatio-temporal IoU between two tubes.
iou3dt_voc
python
open-mmlab/mmaction2
mmaction/evaluation/functional/multisports_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py
Apache-2.0
def nms_tubelets(dets, overlapThresh=0.3, top_k=None): """Compute the NMS for a set of scored tubelets scored tubelets are numpy array with 4K+1 columns, last one being the score return the indices of the tubelets to keep.""" # If there are no detections, return an empty list if len(dets) == 0: ...
Compute the NMS for a set of scored tubelets scored tubelets are numpy array with 4K+1 columns, last one being the score return the indices of the tubelets to keep.
nms_tubelets
python
open-mmlab/mmaction2
mmaction/evaluation/functional/multisports_utils.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/multisports_utils.py
Apache-2.0
def compute_precision_recall(scores, labels, num_gt): """Compute precision and recall. Args: scores: A float numpy array representing detection score labels: A boolean numpy array representing true/false positive labels num_gt: Number of ground truth instances Raises: Value...
Compute precision and recall. Args: scores: A float numpy array representing detection score labels: A boolean numpy array representing true/false positive labels num_gt: Number of ground truth instances Raises: ValueError: if the input is not of the correct format Returns...
compute_precision_recall
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/metrics.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/metrics.py
Apache-2.0
def compute_average_precision(precision, recall): """Compute Average Precision according to the definition in VOCdevkit. Precision is modified to ensure that it does not decrease as recall decrease. Args: precision: A float [N, 1] numpy array of precisions recall: A float [N, 1] numpy ...
Compute Average Precision according to the definition in VOCdevkit. Precision is modified to ensure that it does not decrease as recall decrease. Args: precision: A float [N, 1] numpy array of precisions recall: A float [N, 1] numpy array of recalls Raises: ValueError: if the ...
compute_average_precision
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/metrics.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/metrics.py
Apache-2.0
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. https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf Returns nans if there are no ground truth images for a class. ...
Compute CorLoc according to the definition in the following paper. https://www.robots.ox.ac.uk/~vgg/rg/papers/deselaers-eccv10.pdf Returns nans if there are no ground truth images for a class. Args: num_gt_imgs_per_class: 1D array, representing number of images containing at least one...
compute_cor_loc
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/metrics.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/metrics.py
Apache-2.0
def __init__(self, data): """Constructs box collection. Args: data: a numpy array of shape [N, 4] representing box coordinates Raises: ValueError: if bbox data is not a numpy array ValueError: if invalid dimensions for bbox data """ if not is...
Constructs box collection. Args: data: a numpy array of shape [N, 4] representing box coordinates Raises: ValueError: if bbox data is not a numpy array ValueError: if invalid dimensions for bbox data
__init__
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/np_box_list.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py
Apache-2.0
def add_field(self, field, field_data): """Add data to a specified field. Args: field: a string parameter used to specify a related field to be accessed. field_data: a numpy array of [N, ...] representing the data associated with the field. ...
Add data to a specified field. Args: field: a string parameter used to specify a related field to be accessed. field_data: a numpy array of [N, ...] representing the data associated with the field. Raises: ValueError: if the field is a...
add_field
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/np_box_list.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py
Apache-2.0
def get_field(self, field): """Accesses data associated with the specified field in the box collection. Args: field: a string parameter used to specify a related field to be accessed. Returns: a numpy 1-d array representing data of an associated ...
Accesses data associated with the specified field in the box collection. Args: field: a string parameter used to specify a related field to be accessed. Returns: a numpy 1-d array representing data of an associated field Raises: Valu...
get_field
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/np_box_list.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py
Apache-2.0
def get_coordinates(self): """Get corner coordinates of boxes. Returns: a list of 4 1-d numpy arrays [y_min, x_min, y_max, x_max] """ box_coordinates = self.get() y_min = box_coordinates[:, 0] x_min = box_coordinates[:, 1] y_max = box_coordinates[:, 2...
Get corner coordinates of boxes. Returns: a list of 4 1-d numpy arrays [y_min, x_min, y_max, x_max]
get_coordinates
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/np_box_list.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py
Apache-2.0
def _is_valid_boxes(data): """Check whether data fulfills the format of N*[ymin, xmin, ymax, xmin]. Args: data: a numpy array of shape [N, 4] representing box coordinates Returns: a boolean indicating whether all ymax of boxes are equal or greater th...
Check whether data fulfills the format of N*[ymin, xmin, ymax, xmin]. Args: data: a numpy array of shape [N, 4] representing box coordinates Returns: a boolean indicating whether all ymax of boxes are equal or greater than ymin, and all xmax of boxes are equ...
_is_valid_boxes
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/np_box_list.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_list.py
Apache-2.0
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: ...
Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with s...
ioa
python
open-mmlab/mmaction2
mmaction/evaluation/functional/ava_evaluation/np_box_ops.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/functional/ava_evaluation/np_box_ops.py
Apache-2.0
def process(self, data_batch: Sequence[Tuple[Any, Dict]], data_samples: Sequence[Dict]) -> None: """Process one batch of data samples and data_samples. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been...
Process one batch of data samples and data_samples. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed. Args: data_batch (Sequence[dict]): A batch of data from the dataloader. data_sa...
process
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/acc_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/acc_metric.py
Apache-2.0
def calculate(self, preds: List[np.ndarray], labels: List[Union[int, np.ndarray]]) -> Dict: """Compute the metrics from processed results. Args: preds (list[np.ndarray]): List of the prediction scores. labels (list[int | np.ndarray]): List of the labels. ...
Compute the metrics from processed results. Args: preds (list[np.ndarray]): List of the prediction scores. labels (list[int | np.ndarray]): List of the labels. Returns: dict: The computed metrics. The keys are the names of the metrics, and the values are...
calculate
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/acc_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/acc_metric.py
Apache-2.0
def process(self, data_batch: Sequence[Tuple[Any, dict]], predictions: Sequence[dict]) -> None: """Process one batch of data samples and predictions. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been p...
Process one batch of data samples and predictions. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed. Args: data_batch (Sequence[Tuple[Any, dict]]): A batch of data from the data...
process
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/anet_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py
Apache-2.0
def compute_metrics(self, results: list) -> dict: """Compute the metrics from processed results. If `metric_type` is 'TEM', only dump middle results and do not compute any metrics. Args: results (list): The processed results of each batch. Returns: dict: ...
Compute the metrics from processed results. If `metric_type` is 'TEM', only dump middle results and do not compute any metrics. Args: results (list): The processed results of each batch. Returns: dict: The computed metrics. The keys are the names of the metrics, ...
compute_metrics
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/anet_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py
Apache-2.0
def dump_results(self, results, version='VERSION 1.3'): """Save middle or final results to disk.""" if self.output_format == 'json': result_dict = self.proposals2json(results) output_dict = { 'version': version, 'results': result_dict, ...
Save middle or final results to disk.
dump_results
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/anet_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py
Apache-2.0
def proposals2json(results, show_progress=False): """Convert all proposals to a final dict(json) format. Args: results (list[dict]): All proposals. show_progress (bool): Whether to show the progress bar. Defaults: False. Returns: dict: The fina...
Convert all proposals to a final dict(json) format. Args: results (list[dict]): All proposals. show_progress (bool): Whether to show the progress bar. Defaults: False. Returns: dict: The final result dict. E.g. .. code-block:: Python ...
proposals2json
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/anet_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/anet_metric.py
Apache-2.0
def process(self, data_batch: Sequence[Tuple[Any, dict]], data_samples: Sequence[dict]) -> None: """Process one batch of data samples and predictions. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been ...
Process one batch of data samples and predictions. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed. Args: data_batch (Sequence[Tuple[Any, dict]]): A batch of data from the data...
process
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/ava_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/ava_metric.py
Apache-2.0
def compute_metrics(self, results: list) -> dict: """Compute the metrics from processed results. Args: results (list): The processed results of each batch. Returns: dict: The computed metrics. The keys are the names of the metrics, and the values are correspo...
Compute the metrics from processed results. Args: results (list): The processed results of each batch. Returns: dict: The computed metrics. The keys are the names of the metrics, and the values are corresponding results.
compute_metrics
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/ava_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/ava_metric.py
Apache-2.0
def process(self, data_batch: Optional[Dict], data_samples: Sequence[Dict]) -> None: """Process one batch of data samples and data_samples. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed. ...
Process one batch of data samples and data_samples. The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed. Args: data_batch (dict, optional): A batch of data from the dataloader. data_sa...
process
python
open-mmlab/mmaction2
mmaction/evaluation/metrics/retrieval_metric.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/retrieval_metric.py
Apache-2.0
def _make_stem_layer(self) -> None: """Construct the stem layers consists of a conv+norm+act module and a pooling layer.""" self.conv1 = ConvModule( self.in_channels, 64, kernel_size=7, stride=2, padding=3, bias=False, ...
Construct the stem layers consists of a conv+norm+act module and a pooling layer.
_make_stem_layer
python
open-mmlab/mmaction2
mmaction/models/backbones/c2d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/c2d.py
Apache-2.0
def forward(self, x: torch.Tensor) \ -> Union[torch.Tensor, Tuple[torch.Tensor]]: """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: Union[torch.Tensor or Tuple[torch.Tensor]]: The feature of the ...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: Union[torch.Tensor or Tuple[torch.Tensor]]: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/c2d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/c2d.py
Apache-2.0
def forward(self, x): """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. the size of x is (num_batches, 3, 16, 112, 112). Returns: torch.Tensor: The feature of the input samples extracted by the backbo...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. the size of x is (num_batches, 3, 16, 112, 112). Returns: torch.Tensor: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/c3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/c3d.py
Apache-2.0
def make_divisible(value, divisor, min_value=None, min_ratio=0.9): """Make divisible function. This function rounds the channel number down to the nearest value that can be divisible by the divisor. Args: value (int): The original channel number. divisor (int): The divisor to fully divi...
Make divisible function. This function rounds the channel number down to the nearest value that can be divisible by the divisor. Args: value (int): The original channel number. divisor (int): The divisor to fully divide the channel number. min_value (int, optional): The minimum valu...
make_divisible
python
open-mmlab/mmaction2
mmaction/models/backbones/mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobilenet_v2.py
Apache-2.0
def forward(self, x): """Defines the computation performed at every call. Args: x (Tensor): The input data. Returns: Tensor: The output of the module. """ def _inner_forward(x): if self.use_res_connect: return x + self.conv(x...
Defines the computation performed at every call. Args: x (Tensor): The input data. Returns: Tensor: The output of the module.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobilenet_v2.py
Apache-2.0
def make_layer(self, out_channels, num_blocks, stride, expand_ratio): """Stack InvertedResidual blocks to build a layer for MobileNetV2. Args: out_channels (int): out_channels of block. num_blocks (int): number of blocks. stride (int): stride of the first block. Defa...
Stack InvertedResidual blocks to build a layer for MobileNetV2. Args: out_channels (int): out_channels of block. num_blocks (int): number of blocks. stride (int): stride of the first block. Defaults to 1 expand_ratio (int): Expand the number of channels of the ...
make_layer
python
open-mmlab/mmaction2
mmaction/models/backbones/mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobilenet_v2.py
Apache-2.0
def forward(self, x): """Defines the computation performed at every call. Args: x (Tensor): The input data. Returns: Tensor or Tuple[Tensor]: The feature of the input samples extracted by the backbone. """ x = self.conv1(x) outs = []...
Defines the computation performed at every call. Args: x (Tensor): The input data. Returns: Tensor or Tuple[Tensor]: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobilenet_v2.py
Apache-2.0
def _freeze_stages(self): """Prevent all the parameters from being optimized before ``self.frozen_stages``.""" if self.frozen_stages >= 0: self.conv1.eval() for param in self.conv1.parameters(): param.requires_grad = False for i in range(1, self.fr...
Prevent all the parameters from being optimized before ``self.frozen_stages``.
_freeze_stages
python
open-mmlab/mmaction2
mmaction/models/backbones/mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobilenet_v2.py
Apache-2.0
def train(self, mode=True): """Set the optimization status when training.""" super(MobileNetV2, self).train(mode) self._freeze_stages() if mode and self.norm_eval: for m in self.modules(): if isinstance(m, _BatchNorm): m.eval()
Set the optimization status when training.
train
python
open-mmlab/mmaction2
mmaction/models/backbones/mobilenet_v2.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobilenet_v2.py
Apache-2.0
def make_temporal_shift(self): """Make temporal shift for some layers.""" for m in self.modules(): if isinstance(m, InvertedResidual) and \ len(m.conv) == 3 and m.use_res_connect: m.conv[0] = TemporalShift( m.conv[0], ...
Make temporal shift for some layers.
make_temporal_shift
python
open-mmlab/mmaction2
mmaction/models/backbones/mobilenet_v2_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobilenet_v2_tsm.py
Apache-2.0
def make_temporal_shift(self): """Make temporal shift for some layers. To make reparameterization work, we can only build the shift layer before the 'block', instead of the 'blockres' """ def make_block_temporal(stage, num_segments): """Make temporal shift on some b...
Make temporal shift for some layers. To make reparameterization work, we can only build the shift layer before the 'block', instead of the 'blockres'
make_temporal_shift
python
open-mmlab/mmaction2
mmaction/models/backbones/mobileone_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobileone_tsm.py
Apache-2.0
def make_block_temporal(stage, num_segments): """Make temporal shift on some blocks. Args: stage (nn.Module): Model layers to be shifted. num_segments (int): Number of frame segments. Returns: nn.Module: The shifted blocks. ...
Make temporal shift on some blocks. Args: stage (nn.Module): Model layers to be shifted. num_segments (int): Number of frame segments. Returns: nn.Module: The shifted blocks.
make_block_temporal
python
open-mmlab/mmaction2
mmaction/models/backbones/mobileone_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mobileone_tsm.py
Apache-2.0
def resize_pos_embed(pos_embed: torch.Tensor, src_shape: Tuple[int], dst_shape: Tuple[int], mode: str = 'trilinear', num_extra_tokens: int = 1) -> torch.Tensor: """Resize pos_embed weights. Args: pos_embed (torch.Tensor...
Resize pos_embed weights. Args: pos_embed (torch.Tensor): Position embedding weights with shape [1, L, C]. src_shape (tuple): The resolution of downsampled origin training image, in format (T, H, W). dst_shape (tuple): The resolution of downsampled new training ...
resize_pos_embed
python
open-mmlab/mmaction2
mmaction/models/backbones/mvit.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mvit.py
Apache-2.0
def resize_decomposed_rel_pos(rel_pos: torch.Tensor, q_size: int, k_size: int) -> torch.Tensor: """Get relative positional embeddings according to the relative positions of query and key sizes. Args: rel_pos (Tensor): relative position embeddings (L, C). q_size...
Get relative positional embeddings according to the relative positions of query and key sizes. Args: rel_pos (Tensor): relative position embeddings (L, C). q_size (int): size of query q. k_size (int): size of key k. Returns: Extracted positional embeddings according to rela...
resize_decomposed_rel_pos
python
open-mmlab/mmaction2
mmaction/models/backbones/mvit.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mvit.py
Apache-2.0
def attention_pool(x: torch.Tensor, pool: nn.Module, in_size: Tuple[int], with_cls_token: bool = False, norm: Optional[nn.Module] = None) -> tuple: """Pooling the feature tokens. Args: x (torch.Tensor): The input tensor, should...
Pooling the feature tokens. Args: x (torch.Tensor): The input tensor, should be with shape ``(B, num_heads, L, C)`` or ``(B, L, C)``. pool (nn.Module): The pooling module. in_size (Tuple[int]): The shape of the input feature map. with_cls_token (bool): Whether concatenat...
attention_pool
python
open-mmlab/mmaction2
mmaction/models/backbones/mvit.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/mvit.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The output of the module. """ identity = x out = self.conv1(x) out = s...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The output of the module.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet.py
Apache-2.0
def make_res_layer(block: nn.Module, inplanes: int, planes: int, blocks: int, stride: int = 1, dilation: int = 1, style: str = 'pytorch', conv_cfg: Optional[ConfigType] = None, ...
Build residual layer for ResNet. Args: block: (nn.Module): Residual module to be built. inplanes (int): Number of channels for the input feature in each block. planes (int): Number of channels for the output feature in each block. blocks (int): Number of residual blocks. str...
make_res_layer
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet.py
Apache-2.0
def _load_conv_params(conv: nn.Module, state_dict_tv: OrderedDict, module_name_tv: str, loaded_param_names: List[str]) -> None: """Load the conv parameters of resnet from torchvision. Args: conv (nn.Module): The destination conv module. ...
Load the conv parameters of resnet from torchvision. Args: conv (nn.Module): The destination conv module. state_dict_tv (OrderedDict): The state dict of pretrained torchvision model. module_name_tv (str): The name of corresponding conv module in the ...
_load_conv_params
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet.py
Apache-2.0
def _load_bn_params(bn: nn.Module, state_dict_tv: OrderedDict, module_name_tv: str, loaded_param_names: List[str]) -> None: """Load the bn parameters of resnet from torchvision. Args: bn (nn.Module): The destination bn module. stat...
Load the bn parameters of resnet from torchvision. Args: bn (nn.Module): The destination bn module. state_dict_tv (OrderedDict): The state dict of pretrained torchvision model. module_name_tv (str): The name of corresponding bn module in the t...
_load_bn_params
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet.py
Apache-2.0
def _load_torchvision_checkpoint(self, logger: mmengine.MMLogger = None) -> None: """Initiate the parameters from torchvision pretrained checkpoint.""" state_dict_torchvision = _load_checkpoint( self.pretrained, map_location='cpu') if 'state_dict'...
Initiate the parameters from torchvision pretrained checkpoint.
_load_torchvision_checkpoint
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet.py
Apache-2.0
def forward(self, x): """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The feature of the input samples extracted by the backbone. """ x = self.conv1(x) x = self.maxpoo...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet2plus1d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet2plus1d.py
Apache-2.0
def make_res_layer(block: nn.Module, inplanes: int, planes: int, blocks: int, spatial_stride: Union[int, Sequence[int]] = 1, temporal_stride: Union[int, Sequence[int]] = 1, dilation:...
Build residual layer for ResNet3D. Args: block (nn.Module): Residual module to be built. inplanes (int): Number of channels for the input feature in each block. planes (int): Number of channels for the output feature in each block. ...
make_res_layer
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py
Apache-2.0
def _inflate_conv_params(conv3d: nn.Module, state_dict_2d: OrderedDict, module_name_2d: str, inflated_param_names: List[str]) -> None: """Inflate a conv module from 2d to 3d. Args: conv3d (nn.Module): The destination conv3d module. ...
Inflate a conv module from 2d to 3d. Args: conv3d (nn.Module): The destination conv3d module. state_dict_2d (OrderedDict): The state dict of pretrained 2d model. module_name_2d (str): The name of corresponding conv module in the 2d model. inflated...
_inflate_conv_params
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py
Apache-2.0
def _inflate_bn_params(bn3d: nn.Module, state_dict_2d: OrderedDict, module_name_2d: str, inflated_param_names: List[str]) -> None: """Inflate a norm module from 2d to 3d. Args: bn3d (nn.Module): The destination bn3d module. s...
Inflate a norm module from 2d to 3d. Args: bn3d (nn.Module): The destination bn3d module. state_dict_2d (OrderedDict): The state dict of pretrained 2d model. module_name_2d (str): The name of corresponding bn module in the 2d model. inflated_param...
_inflate_bn_params
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py
Apache-2.0
def _inflate_weights(self, logger: MMLogger) -> None: """Inflate the resnet2d parameters to resnet3d. The differences between resnet3d and resnet2d mainly lie in an extra axis of conv kernel. To utilize the pretrained parameters in 2d model, the weight of conv2d models should be inflate...
Inflate the resnet2d parameters to resnet3d. The differences between resnet3d and resnet2d mainly lie in an extra axis of conv kernel. To utilize the pretrained parameters in 2d model, the weight of conv2d models should be inflated to fit in the shapes of the 3d counterpart. Ar...
_inflate_weights
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py
Apache-2.0
def _init_weights(self, pretrained: Optional[str] = None) -> None: """Initiate the parameters either from existing checkpoint or from scratch. Args: pretrained (str | None): The path of the pretrained weight. Will override the original `pretrained` if set. The arg is...
Initiate the parameters either from existing checkpoint or from scratch. Args: pretrained (str | None): The path of the pretrained weight. Will override the original `pretrained` if set. The arg is added to be compatible with mmdet. Defaults to None.
_init_weights
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py
Apache-2.0
def forward(self, x: torch.Tensor) \ -> Union[torch.Tensor, Tuple[torch.Tensor]]: """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor or tuple[torch.Tensor]: The feature of the input s...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor or tuple[torch.Tensor]: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The feature of the input samples extracted by the residual layer. """ r...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The feature of the input samples extracted by the residual layer.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py
Apache-2.0
def inflate_weights(self, logger: MMLogger) -> None: """Inflate the resnet2d parameters to resnet3d pathway. The differences between resnet3d and resnet2d mainly lie in an extra axis of conv kernel. To utilize the pretrained parameters in 2d model, the weight of conv2d models should be ...
Inflate the resnet2d parameters to resnet3d pathway. The differences between resnet3d and resnet2d mainly lie in an extra axis of conv kernel. To utilize the pretrained parameters in 2d model, the weight of conv2d models should be inflated to fit in the shapes of the 3d counterpart. For...
inflate_weights
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d_slowfast.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d_slowfast.py
Apache-2.0
def _inflate_conv_params(self, conv3d: nn.Module, state_dict_2d: OrderedDict, module_name_2d: str, inflated_param_names: List[str]) -> None: """Inflate a conv module from 2d to 3d. The differences of conv modules betweene 2d and 3d in Pathway ...
Inflate a conv module from 2d to 3d. The differences of conv modules betweene 2d and 3d in Pathway mainly lie in the inplanes due to lateral connections. To fit the shapes of the lateral connection counterpart, it will expand parameters by concatting conv2d parameters and extra zero pad...
_inflate_conv_params
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d_slowfast.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d_slowfast.py
Apache-2.0
def _freeze_stages(self) -> None: """Prevent all the parameters from being optimized before `self.frozen_stages`.""" if self.frozen_stages >= 0: self.conv1.eval() for param in self.conv1.parameters(): param.requires_grad = False for i in range(1, ...
Prevent all the parameters from being optimized before `self.frozen_stages`.
_freeze_stages
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d_slowfast.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d_slowfast.py
Apache-2.0
def build_pathway(cfg: Dict, *args, **kwargs) -> nn.Module: """Build pathway. Args: cfg (dict): cfg should contain: - type (str): identify backbone type. Returns: nn.Module: Created pathway. """ if not (isinstance(cfg, dict) and 'type' in cfg): raise TypeError('...
Build pathway. Args: cfg (dict): cfg should contain: - type (str): identify backbone type. Returns: nn.Module: Created pathway.
build_pathway
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d_slowfast.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d_slowfast.py
Apache-2.0
def forward(self, x: torch.Tensor) -> tuple: """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: tuple[torch.Tensor]: The feature of the input samples extracted by the backbone. """ x_slow ...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: tuple[torch.Tensor]: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet3d_slowfast.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d_slowfast.py
Apache-2.0
def make_res_layer(block: nn.Module, inplanes: int, planes: int, blocks: int, stride: int = 1, dilation: int = 1, factorize: int = 1, norm_cfg: Optional[Config...
Build residual layer for ResNetAudio. Args: block (nn.Module): Residual module to be built. inplanes (int): Number of channels for the input feature in each block. planes (int): Number of channels for the output feature in each block. ...
make_res_layer
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_audio.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_audio.py
Apache-2.0
def _make_stem_layer(self) -> None: """Construct the stem layers consists of a ``conv+norm+act`` module and a pooling layer.""" self.conv1 = ConvModule( self.in_channels, self.base_channels, kernel_size=self.conv1_kernel, stride=self.conv1_stride, ...
Construct the stem layers consists of a ``conv+norm+act`` module and a pooling layer.
_make_stem_layer
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_audio.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_audio.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The feature of the input samples extracted by the backbone. """ x = sel...
Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_audio.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_audio.py
Apache-2.0
def batch_norm(inputs: torch.Tensor, module: nn.modules.batchnorm, training: Optional[bool] = None) -> torch.Tensor: """Applies Batch Normalization for each channel across a batch of data using params from the given batch normalization module. Args: inputs (Tensor): Th...
Applies Batch Normalization for each channel across a batch of data using params from the given batch normalization module. Args: inputs (Tensor): The input data. module (nn.modules.batchnorm): a batch normalization module. Will use params from this batch normalization module to do ...
batch_norm
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_omni.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_omni.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Defines the computation performed at every call. Accept both 3D (BCTHW for videos) and 2D (BCHW for images) tensors. """ if x.ndim == 4: return self.forward_2d(x) # Forward call for 3D tensors. out = sel...
Defines the computation performed at every call. Accept both 3D (BCTHW for videos) and 2D (BCHW for images) tensors.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_omni.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_omni.py
Apache-2.0
def linear_sampler(data, offset): """Differentiable Temporal-wise Frame Sampling, which is essentially a linear interpolation process. It gets the feature map which has been split into several groups and shift them by different offsets according to their groups. Then compute the weighted sum along ...
Differentiable Temporal-wise Frame Sampling, which is essentially a linear interpolation process. It gets the feature map which has been split into several groups and shift them by different offsets according to their groups. Then compute the weighted sum along with the temporal dimension. Args: ...
linear_sampler
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tin.py
Apache-2.0
def make_temporal_interlace(self): """Make temporal interlace for some layers.""" num_segment_list = [self.num_segments] * 4 assert num_segment_list[-1] > 0 n_round = 1 if len(list(self.layer3.children())) >= 23: print(f'=> Using n_round {n_round} to insert temporal ...
Make temporal interlace for some layers.
make_temporal_interlace
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tin.py
Apache-2.0
def make_block_interlace(stage, num_segments, shift_div): """Apply Deformable shift for a ResNet layer module. Args: stage (nn.module): A ResNet layer to be deformed. num_segments (int): Number of frame segments. shift_div (int): Number of divisio...
Apply Deformable shift for a ResNet layer module. Args: stage (nn.module): A ResNet layer to be deformed. num_segments (int): Number of frame segments. shift_div (int): Number of division parts for shift. Returns: nn.Sequential: A...
make_block_interlace
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tin.py
Apache-2.0
def shift(x, num_segments, shift_div=3): """Perform temporal shift operation on the feature. Args: x (torch.Tensor): The input feature to be shifted. num_segments (int): Number of frame segments. shift_div (int): Number of divisions for shift. Default: 3. Re...
Perform temporal shift operation on the feature. Args: x (torch.Tensor): The input feature to be shifted. num_segments (int): Number of frame segments. shift_div (int): Number of divisions for shift. Default: 3. Returns: torch.Tensor: The shifted feature...
shift
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tsm.py
Apache-2.0
def make_block_temporal(stage, num_segments): """Make temporal shift on some blocks. Args: stage (nn.Module): Model layers to be shifted. num_segments (int): Number of frame segments. Returns: nn.Module: The sh...
Make temporal shift on some blocks. Args: stage (nn.Module): Model layers to be shifted. num_segments (int): Number of frame segments. Returns: nn.Module: The shifted blocks.
make_block_temporal
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tsm.py
Apache-2.0
def make_temporal_pool(self): """Make temporal pooling between layer1 and layer2, using a 3D max pooling layer.""" class TemporalPool(nn.Module): """Temporal pool module. Wrap layer2 in ResNet50 with a 3D max pooling layer. Args: net (nn.Mod...
Make temporal pooling between layer1 and layer2, using a 3D max pooling layer.
make_temporal_pool
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tsm.py
Apache-2.0
def make_non_local(self): """Wrap resnet layer into non local wrapper.""" # This part is for ResNet50 for i in range(self.num_stages): non_local_stage = self.non_local_stages[i] if sum(non_local_stage) == 0: continue layer_name = f'layer{i + 1...
Wrap resnet layer into non local wrapper.
make_non_local
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tsm.py
Apache-2.0
def load_original_weights(self, logger): """Load weights from original checkpoint, which required converting keys.""" state_dict_torchvision = _load_checkpoint( self.pretrained, map_location='cpu') if 'state_dict' in state_dict_torchvision: state_dict_torchvision ...
Load weights from original checkpoint, which required converting keys.
load_original_weights
python
open-mmlab/mmaction2
mmaction/models/backbones/resnet_tsm.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tsm.py
Apache-2.0
def forward(self, imgs: torch.Tensor, heatmap_imgs: torch.Tensor) -> tuple: """Defines the computation performed at every call. Args: imgs (torch.Tensor): The input data. heatmap_imgs (torch.Tensor): The input data. Returns: tuple[torch.Tensor]: The feature ...
Defines the computation performed at every call. Args: imgs (torch.Tensor): The input data. heatmap_imgs (torch.Tensor): The input data. Returns: tuple[torch.Tensor]: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/rgbposeconv3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/rgbposeconv3d.py
Apache-2.0
def window_partition(x: torch.Tensor, window_size: Sequence[int]) -> torch.Tensor: """ Args: x (torch.Tensor): The input features of shape :math:`(B, D, H, W, C)`. window_size (Sequence[int]): The window size, :math:`(w_d, w_h, w_w)`. Returns: torch.Tensor: The ...
Args: x (torch.Tensor): The input features of shape :math:`(B, D, H, W, C)`. window_size (Sequence[int]): The window size, :math:`(w_d, w_h, w_w)`. Returns: torch.Tensor: The partitioned windows of shape :math:`(B*num_windows, w_d*w_h*w_w, C)`.
window_partition
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def window_reverse(windows: torch.Tensor, window_size: Sequence[int], B: int, D: int, H: int, W: int) -> torch.Tensor: """ Args: windows (torch.Tensor): Input windows of shape :meth:`(B*num_windows, w_d, w_h, w_w, C)`. window_size (Sequence[int]): The window size, ...
Args: windows (torch.Tensor): Input windows of shape :meth:`(B*num_windows, w_d, w_h, w_w, C)`. window_size (Sequence[int]): The window size, :meth:`(w_d, w_h, w_w)`. B (int): Batch size of feature maps. D (int): Temporal length of feature maps. H (int): Height o...
window_reverse
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def get_window_size( x_size: Sequence[int], window_size: Sequence[int], shift_size: Optional[Sequence[int]] = None ) -> Union[Tuple[int], Tuple[Tuple[int]]]: """Calculate window size and shift size according to the input size. Args: x_size (Sequence[int]): The input size. window_siz...
Calculate window size and shift size according to the input size. Args: x_size (Sequence[int]): The input size. window_size (Sequence[int]): The expected window size. shift_size (Sequence[int], optional): The expected shift size. Defaults to None. Returns: tuple: Th...
get_window_size
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def compute_mask(D: int, H: int, W: int, window_size: Sequence[int], shift_size: Sequence[int], device: Union[str, torch.device]) -> torch.Tensor: """Compute attention mask. Args: D (int): Temporal length of feature maps. H (int): Height of feature maps. ...
Compute attention mask. Args: D (int): Temporal length of feature maps. H (int): Height of feature maps. W (int): Width of feature maps. window_size (Sequence[int]): The window size. shift_size (Sequence[int]): The shift size. device (str or :obj:`torch.device`): The...
compute_mask
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: """Forward function. Args: x (torch.Tensor): Input feature maps of shape :meth:`(B*num_windows, N, C)`. mask (torch.Tensor, optional): (0/-inf...
Forward function. Args: x (torch.Tensor): Input feature maps of shape :meth:`(B*num_windows, N, C)`. mask (torch.Tensor, optional): (0/-inf) mask of shape :meth:`(num_windows, N, N)`. Defaults to None.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def forward(self, x: torch.Tensor, mask_matrix: torch.Tensor) -> torch.Tensor: """ Args: x (torch.Tensor): Input features of shape :math:`(B, D, H, W, C)`. mask_matrix (torch.Tensor): Attention mask for cyclic shift. """ shortcut = x if se...
Args: x (torch.Tensor): Input features of shape :math:`(B, D, H, W, C)`. mask_matrix (torch.Tensor): Attention mask for cyclic shift.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Perform patch merging. Args: x (torch.Tensor): Input feature maps of shape :math:`(B, D, H, W, C)`. Returns: torch.Tensor: The merged feature maps of shape :math:`(B, D, H/2, W/2, 2*C...
Perform patch merging. Args: x (torch.Tensor): Input feature maps of shape :math:`(B, D, H, W, C)`. Returns: torch.Tensor: The merged feature maps of shape :math:`(B, D, H/2, W/2, 2*C)`.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def forward(self, x: torch.Tensor, do_downsample: bool = True) -> torch.Tensor: """Forward function. Args: x (torch.Tensor): Input feature maps of shape :math:`(B, C, D, H, W)`. do_downsample (bool): Whether to downsample the outpu...
Forward function. Args: x (torch.Tensor): Input feature maps of shape :math:`(B, C, D, H, W)`. do_downsample (bool): Whether to downsample the output of the current layer. Defaults to True.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def forward(self, x: torch.Tensor) -> torch.Tensor: """Perform video to patch embedding. Args: x (torch.Tensor): The input videos of shape :math:`(B, C, D, H, W)`. In most cases, C is 3. Returns: torch.Tensor: The video patches of shape :...
Perform video to patch embedding. Args: x (torch.Tensor): The input videos of shape :math:`(B, C, D, H, W)`. In most cases, C is 3. Returns: torch.Tensor: The video patches of shape :math:`(B, embed_dims, Dp, Hp, Wp)`.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def inflate_weights(self, logger: MMLogger) -> None: """Inflate the swin2d parameters to swin3d. The differences between swin3d and swin2d mainly lie in an extra axis. To utilize the pretrained parameters in 2d model, the weight of swin2d models should be inflated to fit in the shapes o...
Inflate the swin2d parameters to swin3d. The differences between swin3d and swin2d mainly lie in an extra axis. To utilize the pretrained parameters in 2d model, the weight of swin2d models should be inflated to fit in the shapes of the 3d counterpart. Args: logger ...
inflate_weights
python
open-mmlab/mmaction2
mmaction/models/backbones/swin.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/swin.py
Apache-2.0
def make_tam_modeling(self): """Replace ResNet-Block with TA-Block.""" def make_tam_block(stage, num_segments, tam_cfg=dict()): blocks = list(stage.children()) for i, block in enumerate(blocks): blocks[i] = TABlock(block, num_segments, deepcopy(tam_cfg)) ...
Replace ResNet-Block with TA-Block.
make_tam_modeling
python
open-mmlab/mmaction2
mmaction/models/backbones/tanet.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/tanet.py
Apache-2.0
def conv_3xnxn(inp: int, oup: int, kernel_size: int = 3, stride: int = 3, groups: int = 1): """3D convolution with kernel size of 3xnxn. Args: inp (int): Dimension of input features. oup (int): Dimension of output features. ker...
3D convolution with kernel size of 3xnxn. Args: inp (int): Dimension of input features. oup (int): Dimension of output features. kernel_size (int): The spatial kernel size (i.e., n). Defaults to 3. stride (int): The spatial stride. Defaults to 3. grou...
conv_3xnxn
python
open-mmlab/mmaction2
mmaction/models/backbones/uniformer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/uniformer.py
Apache-2.0
def conv_1xnxn(inp: int, oup: int, kernel_size: int = 3, stride: int = 3, groups: int = 1): """3D convolution with kernel size of 1xnxn. Args: inp (int): Dimension of input features. oup (int): Dimension of output features. ker...
3D convolution with kernel size of 1xnxn. Args: inp (int): Dimension of input features. oup (int): Dimension of output features. kernel_size (int): The spatial kernel size (i.e., n). Defaults to 3. stride (int): The spatial stride. Defaults to 3. grou...
conv_1xnxn
python
open-mmlab/mmaction2
mmaction/models/backbones/uniformer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/uniformer.py
Apache-2.0
def _load_pretrained(self, pretrained: str = None) -> None: """Load ImageNet-1K pretrained model. The model is pretrained with ImageNet-1K. https://github.com/Sense-X/UniFormer Args: pretrained (str): Model name of ImageNet-1K pretrained model. Defaults to N...
Load ImageNet-1K pretrained model. The model is pretrained with ImageNet-1K. https://github.com/Sense-X/UniFormer Args: pretrained (str): Model name of ImageNet-1K pretrained model. Defaults to None.
_load_pretrained
python
open-mmlab/mmaction2
mmaction/models/backbones/uniformer.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/uniformer.py
Apache-2.0
def _load_pretrained(self, pretrained: str = None) -> None: """Load CLIP pretrained visual encoder. The visual encoder is extracted from CLIP. https://github.com/openai/CLIP Args: pretrained (str): Model name of pretrained CLIP visual encoder. Defaults to No...
Load CLIP pretrained visual encoder. The visual encoder is extracted from CLIP. https://github.com/openai/CLIP Args: pretrained (str): Model name of pretrained CLIP visual encoder. Defaults to None.
_load_pretrained
python
open-mmlab/mmaction2
mmaction/models/backbones/uniformerv2.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/uniformerv2.py
Apache-2.0
def forward(self, x: Tensor) -> Tensor: """Defines the computation performed at every call. Args: x (Tensor): The input data with size of (B, N, C). Returns: Tensor: The output of the attention block, same size as inputs. """ B, N, C = x.shape if...
Defines the computation performed at every call. Args: x (Tensor): The input data with size of (B, N, C). Returns: Tensor: The output of the attention block, same size as inputs.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/vit_mae.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/vit_mae.py
Apache-2.0
def forward(self, x: Tensor) -> Tensor: """Defines the computation performed at every call. Args: x (Tensor): The input data with size of (B, N, C). Returns: Tensor: The output of the transformer block, same size as inputs. """ if hasattr(self, 'gamma_1')...
Defines the computation performed at every call. Args: x (Tensor): The input data with size of (B, N, C). Returns: Tensor: The output of the transformer block, same size as inputs.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/vit_mae.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/vit_mae.py
Apache-2.0
def get_sinusoid_encoding(n_position: int, embed_dims: int) -> Tensor: """Generate sinusoid encoding table. Sinusoid encoding is a kind of relative position encoding method came from `Attention Is All You Need<https://arxiv.org/abs/1706.03762>`_. Args: n_position (int): The length of the input ...
Generate sinusoid encoding table. Sinusoid encoding is a kind of relative position encoding method came from `Attention Is All You Need<https://arxiv.org/abs/1706.03762>`_. Args: n_position (int): The length of the input token. embed_dims (int): The position embedding dimension. Returns...
get_sinusoid_encoding
python
open-mmlab/mmaction2
mmaction/models/backbones/vit_mae.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/vit_mae.py
Apache-2.0
def forward(self, x: Tensor) -> Tensor: """Defines the computation performed at every call. Args: x (Tensor): The input data. Returns: Tensor: The feature of the input samples extracted by the backbone. """ b, _, _, h, w = x.shape ...
Defines the computation performed at every call. Args: x (Tensor): The input data. Returns: Tensor: The feature of the input samples extracted by the backbone.
forward
python
open-mmlab/mmaction2
mmaction/models/backbones/vit_mae.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/vit_mae.py
Apache-2.0
def make_res_layer(self, block, layer_inplanes, inplanes, planes, blocks, spatial_stride=1, se_style='half', se_ratio=None, ...
Build residual layer for ResNet3D. Args: block (nn.Module): Residual module to be built. layer_inplanes (int): Number of channels for the input feature of the res layer. inplanes (int): Number of channels for the input feature in each block, w...
make_res_layer
python
open-mmlab/mmaction2
mmaction/models/backbones/x3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/x3d.py
Apache-2.0
def aggregate_stats(self): """Synchronize running_mean, and running_var to self.bn. Call this before eval, then call model.eval(); When eval, forward function will call self.bn instead of self.split_bn, During this time the running_mean, and running_var of self.bn has been obtained from...
Synchronize running_mean, and running_var to self.bn. Call this before eval, then call model.eval(); When eval, forward function will call self.bn instead of self.split_bn, During this time the running_mean, and running_var of self.bn has been obtained from self.split_bn.
aggregate_stats
python
open-mmlab/mmaction2
mmaction/models/common/sub_batchnorm3d.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/common/sub_batchnorm3d.py
Apache-2.0
def forward(self, data: Union[dict, Tuple[dict]], training: bool = False) -> Union[dict, Tuple[dict]]: """Perform normalization, padding, bgr2rgb conversion and batch augmentation based on ``BaseDataPreprocessor``. Args: data (dict or Tuple[dict]): da...
Perform normalization, padding, bgr2rgb conversion and batch augmentation based on ``BaseDataPreprocessor``. Args: data (dict or Tuple[dict]): data sampled from dataloader. training (bool): Whether to enable training time augmentation. Returns: dict or Tuple...
forward
python
open-mmlab/mmaction2
mmaction/models/data_preprocessors/data_preprocessor.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/data_preprocessors/data_preprocessor.py
Apache-2.0
def forward_onesample(self, data, training: bool = False) -> dict: """Perform normalization, padding, bgr2rgb conversion and batch augmentation on one data sample. Args: data (dict): data sampled from dataloader. training (bool): Whether to enable training time augmentat...
Perform normalization, padding, bgr2rgb conversion and batch augmentation on one data sample. Args: data (dict): data sampled from dataloader. training (bool): Whether to enable training time augmentation. Returns: dict: Data in the same format as the model ...
forward_onesample
python
open-mmlab/mmaction2
mmaction/models/data_preprocessors/data_preprocessor.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/data_preprocessors/data_preprocessor.py
Apache-2.0
def forward(self, data: Dict, training: bool = False) -> Dict: """Preprocesses the data into the model input format. Args: data (dict): Data returned by dataloader. training (bool): Whether to enable training time augmentation. Returns: dict: Data in the sam...
Preprocesses the data into the model input format. Args: data (dict): Data returned by dataloader. training (bool): Whether to enable training time augmentation. Returns: dict: Data in the same format as the model input.
forward
python
open-mmlab/mmaction2
mmaction/models/data_preprocessors/multimodal_data_preprocessor.py
https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/data_preprocessors/multimodal_data_preprocessor.py
Apache-2.0