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 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 corresponding results.
"""
time_now = datetime.now().strftime('%Y%m%d_%H%M%S')
temp_file = f'AVA_{time_now}_result.csv'
results2csv(results, temp_file, self.custom_classes)
eval_results = ava_eval(
temp_file,
self.options[0],
self.label_file,
self.ann_file,
self.exclude_file,
ignore_empty_frames=True,
custom_classes=self.custom_classes)
os.remove(temp_file)
return eval_results | 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, data_samples):
"""Process one batch of data samples.
The processed results should be stored in ``self.results``, which will
be used to computed the metrics when all batches have been processed.
Args:
data_batch: A batch of data from the dataloader.
data_samples (Sequence[dict]): A batch of outputs from the model.
"""
for sample in data_samples:
gt_answer = sample.get('gt_answer')
gt_answer_weight = sample.get('gt_answer_weight')
if isinstance(gt_answer, str):
gt_answer = [gt_answer]
if gt_answer_weight is None:
gt_answer_weight = [1. / (len(gt_answer))] * len(gt_answer)
result = {
'pred_answer': sample.get('pred_answer'),
'gt_answer': gt_answer,
'gt_answer_weight': gt_answer_weight,
}
self.results.append(result) | Process one batch of data samples.
The processed results should be stored in ``self.results``, which will
be used to computed the metrics when all batches have been processed.
Args:
data_batch: A batch of data from the dataloader.
data_samples (Sequence[dict]): A batch of outputs from the model.
| process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def compute_metrics(self, results: List):
"""Compute the metrics from processed results.
Args:
results (dict): 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.
"""
acc = []
for result in results:
pred_answer = self._process_answer(result['pred_answer'])
gt_answer = [
self._process_answer(answer) for answer in result['gt_answer']
]
answer_weight = result['gt_answer_weight']
weight_sum = 0
for i, gt in enumerate(gt_answer):
if gt == pred_answer:
weight_sum += answer_weight[i]
vqa_acc = min(1.0, weight_sum / self.full_score_weight)
acc.append(vqa_acc)
accuracy = sum(acc) / len(acc) * 100
metrics = {'acc': accuracy}
return metrics | Compute the metrics from processed results.
Args:
results (dict): 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/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def process(self, data_batch, data_samples) -> None:
"""transfer tensors in predictions to CPU."""
for sample in data_samples:
question_id = sample['question_id']
pred_answer = sample['pred_answer']
result = {
'question_id': int(question_id),
'answer': pred_answer,
}
self.results.append(result) | transfer tensors in predictions to CPU. | process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def compute_metrics(self, results: List):
"""Dump the result to json file."""
mmengine.dump(results, self.file_path)
logger = MMLogger.get_current_instance()
logger.info(f'Results has been saved to {self.file_path}.')
return {} | Dump the result to json file. | compute_metrics | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def process(self, data_batch, data_samples):
"""Process one batch of data samples.
The processed results should be stored in ``self.results``, which will
be used to computed the metrics when all batches have been processed.
Args:
data_batch: A batch of data from the dataloader.
data_samples (Sequence[dict]): A batch of outputs from the model.
"""
for sample in data_samples:
# gt_labels in datasample is a LabelData
label = sample['gt_label'].item()
result = {
'pred_label': sample.get('pred_label'),
'gt_label': label,
}
self.results.append(result) | Process one batch of data samples.
The processed results should be stored in ``self.results``, which will
be used to computed the metrics when all batches have been processed.
Args:
data_batch: A batch of data from the dataloader.
data_samples (Sequence[dict]): A batch of outputs from the model.
| process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def compute_metrics(self, results: List):
"""Compute the metrics from processed results.
Args:
results (dict): 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.
"""
preds = np.array([x['pred_label'] for x in results])
labels = np.array([x['gt_label'] for x in results])
accuracy = np.sum(preds == labels) / len(preds) * 100
metrics = {'acc': accuracy}
return metrics | Compute the metrics from processed results.
Args:
results (dict): 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/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def process(self, data_batch: Sequence[dict],
data_samples: Sequence[dict]):
"""Process one batch of data and predictions.
The processed results should be stored in ``self.results``, which will
be used to computed the metrics when all batches have been processed.
Args:
data_batch (Sequence[dict]): A batch of data from the dataloader.
predictions (Sequence[dict]): A batch of outputs from the model.
"""
for data_sample in data_samples:
pred_score = data_sample['pred_score'].cpu()
gt_label = format_label(data_sample['gt_label'])
if 'gt_score' in data_sample:
target = data_sample.get('gt_score').clone()
else:
num_classes = pred_score.size()[-1]
target = F.one_hot(gt_label, num_classes)
# Because the retrieval output logit vector will be much larger
# compared to the normal classification, to save resources, the
# evaluation results are computed each batch here and then reduce
# all results at the end.
result = RetrievalRecall.calculate(
pred_score.unsqueeze(0), target.unsqueeze(0), topk=self.topk)
self.results.append(result) | Process one batch of data and predictions.
The processed results should be stored in ``self.results``, which will
be used to computed the metrics when all batches have been processed.
Args:
data_batch (Sequence[dict]): A batch of data from the dataloader.
predictions (Sequence[dict]): A batch of outputs from the model.
| process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def compute_metrics(self, results: List):
"""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.
"""
result_metrics = dict()
for i, k in enumerate(self.topk):
recall_at_k = sum([r[i].item() for r in results]) / len(results)
result_metrics[f'Recall@{k}'] = recall_at_k
return result_metrics | 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/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def calculate(pred: Union[np.ndarray, torch.Tensor],
target: Union[np.ndarray, torch.Tensor],
topk: Union[int, Sequence[int]],
pred_indices: (bool) = False,
target_indices: (bool) = False) -> float:
"""Calculate the average recall.
Args:
pred (torch.Tensor | np.ndarray | Sequence): The prediction
results. A :obj:`torch.Tensor` or :obj:`np.ndarray` with
shape ``(N, M)`` or a sequence of index/onehot
format labels.
target (torch.Tensor | np.ndarray | Sequence): The prediction
results. A :obj:`torch.Tensor` or :obj:`np.ndarray` with
shape ``(N, M)`` or a sequence of index/onehot
format labels.
topk (int, Sequence[int]): Predictions with the k-th highest
scores are considered as positive.
pred_indices (bool): Whether the ``pred`` is a sequence of
category index labels. Defaults to False.
target_indices (bool): Whether the ``target`` is a sequence of
category index labels. Defaults to False.
Returns:
List[float]: the average recalls.
"""
topk = (topk, ) if isinstance(topk, int) else topk
for k in topk:
if k <= 0:
raise ValueError('`topk` must be a ingter larger than 0 '
'or seq of ingter larger than 0.')
max_keep = max(topk)
pred = _format_pred(pred, max_keep, pred_indices)
target = _format_target(target, target_indices)
assert len(pred) == len(target), (
f'Length of `pred`({len(pred)}) and `target` ({len(target)}) '
f'must be the same.')
num_samples = len(pred)
results = []
for k in topk:
recalls = torch.zeros(num_samples)
for i, (sample_pred,
sample_target) in enumerate(zip(pred, target)):
sample_pred = np.array(to_tensor(sample_pred).cpu())
sample_target = np.array(to_tensor(sample_target).cpu())
recalls[i] = int(np.in1d(sample_pred[:k], sample_target).max())
results.append(recalls.mean() * 100)
return results | Calculate the average recall.
Args:
pred (torch.Tensor | np.ndarray | Sequence): The prediction
results. A :obj:`torch.Tensor` or :obj:`np.ndarray` with
shape ``(N, M)`` or a sequence of index/onehot
format labels.
target (torch.Tensor | np.ndarray | Sequence): The prediction
results. A :obj:`torch.Tensor` or :obj:`np.ndarray` with
shape ``(N, M)`` or a sequence of index/onehot
format labels.
topk (int, Sequence[int]): Predictions with the k-th highest
scores are considered as positive.
pred_indices (bool): Whether the ``pred`` is a sequence of
category index labels. Defaults to False.
target_indices (bool): Whether the ``target`` is a sequence of
category index labels. Defaults to False.
Returns:
List[float]: the average recalls.
| calculate | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def _format_pred(label, topk=None, is_indices=False):
"""format various label to List[indices]."""
if is_indices:
assert isinstance(label, Sequence), \
'`pred` must be Sequence of indices when' \
f' `pred_indices` set to True, but get {type(label)}'
for i, sample_pred in enumerate(label):
assert is_seq_of(sample_pred, int) or isinstance(
sample_pred, (np.ndarray, torch.Tensor)), \
'`pred` should be Sequence of indices when `pred_indices`' \
f'set to True. but pred[{i}] is {sample_pred}'
if topk:
label[i] = sample_pred[:min(topk, len(sample_pred))]
return label
if isinstance(label, np.ndarray):
label = torch.from_numpy(label)
elif not isinstance(label, torch.Tensor):
raise TypeError(f'The pred must be type of torch.tensor, '
f'np.ndarray or Sequence but get {type(label)}.')
topk = topk if topk else label.size()[-1]
_, indices = label.topk(topk)
return indices | format various label to List[indices]. | _format_pred | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_metric.py | Apache-2.0 |
def _format_target(label, is_indices=False):
"""format various label to List[indices]."""
if is_indices:
assert isinstance(label, Sequence), \
'`target` must be Sequence of indices when' \
f' `target_indices` set to True, but get {type(label)}'
for i, sample_gt in enumerate(label):
assert is_seq_of(sample_gt, int) or isinstance(
sample_gt, (np.ndarray, torch.Tensor)), \
'`target` should be Sequence of indices when ' \
f'`target_indices` set to True. but target[{i}] is {sample_gt}'
return label
if isinstance(label, np.ndarray):
label = torch.from_numpy(label)
elif isinstance(label, Sequence) and not mmengine.is_str(label):
label = torch.tensor(label)
elif not isinstance(label, torch.Tensor):
raise TypeError(f'The pred must be type of torch.tensor, '
f'np.ndarray or Sequence but get {type(label)}.')
indices = [sample_gt.nonzero().squeeze(-1) for sample_gt in label]
return indices | format various label to List[indices]. | _format_target | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multimodal_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multimodal_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 processed.
Args:
data_batch (Sequence[Tuple[Any, dict]]): A batch of data
from the dataloader.
data_samples (Sequence[dict]): A batch of outputs from
the model.
"""
for pred in data_samples:
video_key = pred['video_id'].split('.mp4')[0]
frm_num = pred['timestamp']
bboxes = pred['pred_instances']['bboxes'].cpu().numpy()
cls_scores = pred['pred_instances']['scores'].cpu().numpy()
det_result = [video_key, frm_num, bboxes, cls_scores]
self.results.append(det_result) | 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 dataloader.
data_samples (Sequence[dict]): A batch of outputs from
the model.
| process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/multisports_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multisports_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 corresponding results.
"""
test_videos = self.annos['test_videos'][0]
resolutions = self.annos['resolution']
detections = []
for result in results:
video_key, frm_num, bboxes, cls_scores = result
for bbox, cls_score in zip(bboxes, cls_scores):
video_idx = test_videos.index(video_key)
pred_label = np.argmax(cls_score)
score = cls_score[pred_label]
h, w = resolutions[video_key]
bbox *= np.array([w, h, w, h])
instance_result = np.array(
[video_idx, frm_num, pred_label, score, *bbox])
detections.append(instance_result)
frm_detections = np.array(detections)
metric_result = dict()
f_map = frameAP(self.annos, frm_detections,
self.metric_options['F_mAP']['thr'], self.verbose)
metric_result.update({'frameAP': round(f_map, 4)})
video_tubes = link_tubes(
self.annos,
frm_detections,
len_thre=self.metric_options['V_mAP']['tube_thr'])
v_map = {}
for thr in self.metric_options['V_mAP']['thr']:
map = videoAP(
self.annos, video_tubes, thr, print_info=self.verbose)
v_map.update({f'v_map@{thr}': round(map, 4)})
metric_result.update(v_map)
if self.metric_options['V_mAP'].get('all'):
all_map = videoAP_all(self.annos, video_tubes)
metric_result.update(all_map)
return metric_result | 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/multisports_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/multisports_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.
Args:
data_batch (dict, optional): A batch of data from the dataloader.
data_samples (Sequence[dict]): A batch of outputs from the model.
"""
data_samples = copy.deepcopy(data_samples)
for data_sample in data_samples:
results = dict()
features = data_sample['features']
video_feature = features['video_feature'].cpu().numpy()
text_feature = features['text_feature'].cpu().numpy()
results['video_feature'] = video_feature
results['text_feature'] = text_feature
self.results.append(results) | 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_samples (Sequence[dict]): A batch of outputs from the model.
| 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 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 corresponding results.
"""
video_features = np.stack([res['video_feature'] for res in results])
text_features = np.stack([res['text_feature'] for res in results])
video_features = video_features / np.linalg.norm(
video_features, axis=-1, keepdims=True)
text_features = text_features / np.linalg.norm(
text_features, axis=-1, keepdims=True)
similarity = text_features @ video_features.T
sx = np.sort(-similarity)
d = np.diag(-similarity)
ind = np.where((sx - d[:, None]) == 0)[1]
metrics = OrderedDict()
for metric in self.metric_list:
if metric == 'R1':
metrics['R1'] = float(np.sum(ind == 0)) * 100 / len(ind)
elif metric == 'R5':
metrics['R5'] = float(np.sum(ind < 5)) * 100 / len(ind)
elif metric == 'R10':
metrics['R10'] = float(np.sum(ind < 10)) * 100 / len(ind)
elif metric == 'MdR':
metrics['MdR'] = np.median(ind) + 1
elif metric == 'MnR':
metrics['MnR'] = np.mean(ind) + 1
return metrics | 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/retrieval_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/retrieval_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 processed.
Args:
data_batch (Sequence[Tuple[Any, dict]]): A batch of data
from the dataloader.
predictions (Sequence[dict]): A batch of outputs from
the model.
"""
for pred in predictions:
self.results.append(pred) | 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 dataloader.
predictions (Sequence[dict]): A batch of outputs from
the model.
| process | python | open-mmlab/mmaction2 | mmaction/evaluation/metrics/video_grounding_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/video_grounding_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 corresponding results.
"""
eval_results = dict()
for topK in self.topK_list:
total = len(results)
correct = 0.0
for result in results:
gt = result['gt']
predictions = result['predictions'][:topK]
for prediction in predictions:
IoU = self.calculate_IoU(gt, prediction)
if IoU > self.threshold:
correct += 1
break
acc = correct / total
eval_results[f'Recall@Top{topK}_IoU={self.threshold}'] = acc
return eval_results | 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/video_grounding_metric.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/evaluation/metrics/video_grounding_metric.py | Apache-2.0 |
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Defines the computation performed at every call."""
N, M, T, V, C = x.size()
x = x.permute(0, 1, 3, 4, 2).contiguous()
if self.data_bn_type == 'MVC':
x = self.data_bn(x.view(N, M * V * C, T))
else:
x = self.data_bn(x.view(N * M, V * C, T))
x = x.view(N, M, V, C, T).permute(0, 1, 3, 4,
2).contiguous().view(N * M, C, T, V)
for i in range(self.num_stages):
x = self.gcn[i](x)
x = x.reshape((N, M) + x.shape[1:])
return x | Defines the computation performed at every call. | forward | python | open-mmlab/mmaction2 | mmaction/models/backbones/aagcn.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/aagcn.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,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg)
self.maxpool3d_1 = nn.MaxPool3d(
kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 0, 0))
self.maxpool3d_2 = nn.MaxPool3d(
kernel_size=(2, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0)) | 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
input samples extracted by the backbone.
"""
batches = x.shape[0]
def _convert_to_2d(x: torch.Tensor) -> torch.Tensor:
"""(N, C, T, H, W) -> (N x T, C, H, W)"""
x = x.permute((0, 2, 1, 3, 4))
x = x.reshape(-1, x.shape[2], x.shape[3], x.shape[4])
return x
def _convert_to_3d(x: torch.Tensor) -> torch.Tensor:
"""(N x T, C, H, W) -> (N, C, T, H, W)"""
x = x.reshape(batches, -1, x.shape[1], x.shape[2], x.shape[3])
x = x.permute((0, 2, 1, 3, 4))
return x
x = _convert_to_2d(x)
x = self.conv1(x)
x = _convert_to_3d(x)
x = self.maxpool3d_1(x)
x = _convert_to_2d(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i == 0:
x = _convert_to_3d(x)
x = self.maxpool3d_2(x)
x = _convert_to_2d(x)
if i in self.out_indices:
x = _convert_to_3d(x)
outs.append(x)
if len(outs) == 1:
return outs[0]
return tuple(outs) | 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 init_weights(self):
"""Initiate the parameters either from existing checkpoint or from
scratch."""
if isinstance(self.pretrained, str):
logger = MMLogger.get_current_instance()
logger.info(f'load model from: {self.pretrained}')
load_checkpoint(self, self.pretrained, strict=False, logger=logger)
elif self.pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv3d):
kaiming_init(m)
elif isinstance(m, nn.Linear):
normal_init(m, std=self.init_std)
elif isinstance(m, _BatchNorm):
constant_init(m, 1)
else:
raise TypeError('pretrained must be a str or None') | Initiate the parameters either from existing checkpoint or from
scratch. | init_weights | 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 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 backbone.
"""
x = self.conv1a(x)
x = self.pool1(x)
x = self.conv2a(x)
x = self.pool2(x)
x = self.conv3a(x)
x = self.conv3b(x)
x = self.pool3(x)
x = self.conv4a(x)
x = self.conv4b(x)
x = self.pool4(x)
x = self.conv5a(x)
x = self.conv5b(x)
x = self.pool5(x)
x = x.flatten(start_dim=1)
x = self.relu(self.fc6(x))
x = self.dropout(x)
x = self.relu(self.fc7(x))
return 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 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 divide the channel number.
min_value (int, optional): The minimum value of the output channel.
Defaults to None, means that the minimum value equal to the
divisor.
min_ratio (float, optional): The minimum ratio of the rounded channel
number to the original channel number. Defaults to 0.9.
Returns:
int: The modified output channel number
"""
if min_value is None:
min_value = divisor
new_value = max(min_value, int(value + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than (1-min_ratio).
if new_value < min_ratio * value:
new_value += divisor
return new_value | 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 value of the output channel.
Defaults to None, means that the minimum value equal to the
divisor.
min_ratio (float, optional): The minimum ratio of the rounded channel
number to the original channel number. Defaults to 0.9.
Returns:
int: The modified output channel number
| 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)
return self.conv(x)
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
return out | 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. Defaults to 1
expand_ratio (int): Expand the number of channels of the
hidden layer in InvertedResidual by this ratio. Defaults to 6.
"""
layers = []
for i in range(num_blocks):
if i >= 1:
stride = 1
layers.append(
InvertedResidual(
self.in_channels,
out_channels,
stride,
expand_ratio=expand_ratio,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg,
with_cp=self.with_cp))
self.in_channels = out_channels
return nn.Sequential(*layers) | 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
hidden layer in InvertedResidual by this ratio. Defaults to 6.
| 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 = []
for i, layer_name in enumerate(self.layers):
layer = getattr(self, layer_name)
x = layer(x)
if i in self.out_indices:
outs.append(x)
if len(outs) == 1:
return outs[0]
return tuple(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.frozen_stages + 1):
layer_name = self.layers[i - 1]
layer = getattr(self, layer_name)
layer.eval()
for param in layer.parameters():
param.requires_grad = False | 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],
num_segments=self.num_segments,
shift_div=self.shift_div,
) | 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 init_weights(self):
"""Initiate the parameters either from existing checkpoint or from
scratch."""
if self.pretrained2d:
logger = MMLogger.get_current_instance()
self.load_original_weights(logger)
else:
if self.pretrained:
self.init_cfg = dict(
type='Pretrained', checkpoint=self.pretrained)
super().init_weights() | Initiate the parameters either from existing checkpoint or from
scratch. | init_weights | 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 blocks.
Args:
stage (nn.Module): Model layers to be shifted.
num_segments (int): Number of frame segments.
Returns:
nn.Module: The shifted blocks.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
blocks[i] = TemporalShift(
b, num_segments=num_segments, shift_div=self.shift_div)
return nn.Sequential(*blocks)
self.stage0 = make_block_temporal(
nn.Sequential(self.stage0), self.num_segments)[0]
for i in range(1, 5):
temporal_stage = make_block_temporal(
getattr(self, f'stage{i}'), self.num_segments)
setattr(self, f'stage{i}', temporal_stage) | 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.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
blocks[i] = TemporalShift(
b, num_segments=num_segments, shift_div=self.shift_div)
return nn.Sequential(*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 init_weights(self):
"""Initiate the parameters either from existing checkpoint or from
scratch."""
if self.pretrained2d:
logger = MMLogger.get_current_instance()
self.load_original_weights(logger)
else:
super().init_weights() | Initiate the parameters either from existing checkpoint or from
scratch. | init_weights | 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): 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
image, in format (T, H, W).
mode (str): Algorithm used for upsampling. Choose one from 'nearest',
'linear', 'bilinear', 'bicubic' and 'trilinear'.
Defaults to 'trilinear'.
num_extra_tokens (int): The number of extra tokens, such as cls_token.
Defaults to 1.
Returns:
torch.Tensor: The resized pos_embed of shape [1, L_new, C]
"""
if src_shape[0] == dst_shape[0] and src_shape[1] == dst_shape[1] \
and src_shape[2] == dst_shape[2]:
return pos_embed
assert pos_embed.ndim == 3, 'shape of pos_embed must be [1, L, C]'
_, L, C = pos_embed.shape
src_t, src_h, src_w = src_shape
assert L == src_t * src_h * src_w + num_extra_tokens, \
f"The length of `pos_embed` ({L}) doesn't match the expected " \
f'shape ({src_t}*{src_h}*{src_w}+{num_extra_tokens}).' \
'Please check the `img_size` argument.'
extra_tokens = pos_embed[:, :num_extra_tokens]
src_weight = pos_embed[:, num_extra_tokens:]
src_weight = src_weight.reshape(1, src_t, src_h, src_w,
C).permute(0, 4, 1, 2, 3)
dst_weight = F.interpolate(
src_weight, size=dst_shape, align_corners=False, mode=mode)
dst_weight = torch.flatten(dst_weight, 2).transpose(1, 2)
return torch.cat((extra_tokens, dst_weight), dim=1) | 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
image, in format (T, H, W).
mode (str): Algorithm used for upsampling. Choose one from 'nearest',
'linear', 'bilinear', 'bicubic' and 'trilinear'.
Defaults to 'trilinear'.
num_extra_tokens (int): The number of extra tokens, such as cls_token.
Defaults to 1.
Returns:
torch.Tensor: The resized pos_embed of shape [1, L_new, C]
| 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 (int): size of query q.
k_size (int): size of key k.
Returns:
Extracted positional embeddings according to relative positions.
"""
max_rel_dist = int(2 * max(q_size, k_size) - 1)
# Interpolate rel pos if needed.
if rel_pos.shape[0] != max_rel_dist:
# Interpolate rel pos.
resized = F.interpolate(
# (L, C) -> (1, C, L)
rel_pos.transpose(0, 1).unsqueeze(0),
size=max_rel_dist,
mode='linear',
)
# (1, C, L) -> (L, C)
resized = resized.squeeze(0).transpose(0, 1)
else:
resized = rel_pos
# Scale the coords with short length if shapes for q and k are different.
q_h_ratio = max(k_size / q_size, 1.0)
k_h_ratio = max(q_size / k_size, 1.0)
q_coords = torch.arange(q_size)[:, None] * q_h_ratio
k_coords = torch.arange(k_size)[None, :] * k_h_ratio
relative_coords = (q_coords - k_coords) + (k_size - 1) * k_h_ratio
return resized[relative_coords.long()] | 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 relative positions.
| 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 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 concatenating class token into video
tokens as transformer input. Defaults to True.
norm (nn.Module, optional): The normalization module.
Defaults to None.
"""
ndim = x.ndim
if ndim == 4:
B, num_heads, L, C = x.shape
elif ndim == 3:
num_heads = 1
B, L, C = x.shape
x = x.unsqueeze(1)
else:
raise RuntimeError(f'Unsupported input dimension {x.shape}')
T, H, W = in_size
assert L == T * H * W + with_cls_token
if with_cls_token:
cls_tok, x = x[:, :, :1, :], x[:, :, 1:, :]
# (B, num_heads, T*H*W, C) -> (B*num_heads, C, T, H, W)
x = x.reshape(B * num_heads, T, H, W, C).permute(0, 4, 1, 2,
3).contiguous()
x = pool(x)
out_size = x.shape[2:]
# (B*num_heads, C, T', H', W') -> (B, num_heads, T'*H'*W', C)
x = x.reshape(B, num_heads, C, -1).transpose(2, 3)
if with_cls_token:
x = torch.cat((cls_tok, x), dim=2)
if norm is not None:
x = norm(x)
if ndim == 3:
x = x.squeeze(1)
return x, out_size | 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 concatenating class token into video
tokens as transformer input. Defaults to True.
norm (nn.Module, optional): The normalization module.
Defaults to None.
| 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 = self.conv2(out)
if self.downsample is not None:
identity = self.downsample(x)
out = out + identity
out = self.relu(out)
return out | 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 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.
"""
def _inner_forward(x):
"""Forward wrapper for utilizing checkpoint."""
identity = x
out = self.conv1(x)
out = self.conv2(out)
out = self.conv3(out)
if self.downsample is not None:
identity = self.downsample(x)
out = out + identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out | 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,
norm_cfg: Optional[ConfigType] = None,
act_cfg: Optional[ConfigType] = None,
with_cp: bool = False) -> nn.Module:
"""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.
stride (int): Stride in the conv layer. Defaults to 1.
dilation (int): Spacing between kernel elements. Defaults to 1.
style (str): ``pytorch`` or ``caffe``. If set to ``pytorch``, the
stride-two layer is the 3x3 conv layer, otherwise the stride-two
layer is the first 1x1 conv layer. Defaults to ``pytorch``.
conv_cfg (Union[dict, ConfigDict], optional): Config for norm layers.
Defaults to None.
norm_cfg (Union[dict, ConfigDict], optional): Config for norm layers.
Defaults to None.
act_cfg (Union[dict, ConfigDict], optional): Config for activate
layers. Defaults to None.
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed. Defaults to False.
Returns:
nn.Module: A residual layer for the given config.
"""
downsample = None
if stride != 1 or inplanes != planes * block.expansion:
downsample = ConvModule(
inplanes,
planes * block.expansion,
kernel_size=1,
stride=stride,
bias=False,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=None)
layers = []
layers.append(
block(
inplanes,
planes,
stride,
dilation,
downsample,
style=style,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg,
with_cp=with_cp))
inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(
block(
inplanes,
planes,
1,
dilation,
style=style,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg,
with_cp=with_cp))
return nn.Sequential(*layers) | 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.
stride (int): Stride in the conv layer. Defaults to 1.
dilation (int): Spacing between kernel elements. Defaults to 1.
style (str): ``pytorch`` or ``caffe``. If set to ``pytorch``, the
stride-two layer is the 3x3 conv layer, otherwise the stride-two
layer is the first 1x1 conv layer. Defaults to ``pytorch``.
conv_cfg (Union[dict, ConfigDict], optional): Config for norm layers.
Defaults to None.
norm_cfg (Union[dict, ConfigDict], optional): Config for norm layers.
Defaults to None.
act_cfg (Union[dict, ConfigDict], optional): Config for activate
layers. Defaults to None.
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed. Defaults to False.
Returns:
nn.Module: A residual layer for the given config.
| 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 _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,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) | 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.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.
state_dict_tv (OrderedDict): The state dict of pretrained
torchvision model.
module_name_tv (str): The name of corresponding conv module in the
torchvision model.
loaded_param_names (list[str]): List of parameters that have been
loaded.
"""
weight_tv_name = module_name_tv + '.weight'
if conv.weight.data.shape == state_dict_tv[weight_tv_name].shape:
conv.weight.data.copy_(state_dict_tv[weight_tv_name])
loaded_param_names.append(weight_tv_name)
if getattr(conv, 'bias') is not None:
bias_tv_name = module_name_tv + '.bias'
if conv.bias.data.shape == state_dict_tv[bias_tv_name].shape:
conv.bias.data.copy_(state_dict_tv[bias_tv_name])
loaded_param_names.append(bias_tv_name) | 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
torchvision model.
loaded_param_names (list[str]): List of parameters that have been
loaded.
| _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.
state_dict_tv (OrderedDict): The state dict of pretrained
torchvision model.
module_name_tv (str): The name of corresponding bn module in the
torchvision model.
loaded_param_names (list[str]): List of parameters that have been
loaded.
"""
for param_name, param in bn.named_parameters():
param_tv_name = f'{module_name_tv}.{param_name}'
param_tv = state_dict_tv[param_tv_name]
if param.data.shape == param_tv.shape:
param.data.copy_(param_tv)
loaded_param_names.append(param_tv_name)
for param_name, param in bn.named_buffers():
param_tv_name = f'{module_name_tv}.{param_name}'
# some buffers like num_batches_tracked may not exist
if param_tv_name in state_dict_tv:
param_tv = state_dict_tv[param_tv_name]
if param.data.shape == param_tv.shape:
param.data.copy_(param_tv)
loaded_param_names.append(param_tv_name) | 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
torchvision model.
loaded_param_names (list[str]): List of parameters that have been
loaded.
| _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' in state_dict_torchvision:
state_dict_torchvision = state_dict_torchvision['state_dict']
loaded_param_names = []
for name, module in self.named_modules():
if isinstance(module, ConvModule):
# we use a ConvModule to wrap conv+bn+relu layers, thus the
# name mapping is needed
if 'downsample' in name:
# layer{X}.{Y}.downsample.conv->layer{X}.{Y}.downsample.0
original_conv_name = name + '.0'
# layer{X}.{Y}.downsample.bn->layer{X}.{Y}.downsample.1
original_bn_name = name + '.1'
else:
# layer{X}.{Y}.conv{n}.conv->layer{X}.{Y}.conv{n}
original_conv_name = name
# layer{X}.{Y}.conv{n}.bn->layer{X}.{Y}.bn{n}
original_bn_name = name.replace('conv', 'bn')
self._load_conv_params(module.conv, state_dict_torchvision,
original_conv_name, loaded_param_names)
self._load_bn_params(module.bn, state_dict_torchvision,
original_bn_name, loaded_param_names)
# check if any parameters in the 2d checkpoint are not loaded
remaining_names = set(
state_dict_torchvision.keys()) - set(loaded_param_names)
if remaining_names:
logger.info(
f'These parameters in pretrained checkpoint are not loaded'
f': {remaining_names}') | 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 init_weights(self) -> None:
"""Initiate the parameters either from existing checkpoint or from
scratch."""
if isinstance(self.pretrained, str):
logger = MMLogger.get_current_instance()
if self.torchvision_pretrain:
# torchvision's
self._load_torchvision_checkpoint(logger)
else:
# ours
if self.pretrained:
self.init_cfg = dict(
type='Pretrained', checkpoint=self.pretrained)
super().init_weights()
elif self.pretrained is None:
super().init_weights()
else:
raise TypeError('pretrained must be a str or None') | Initiate the parameters either from existing checkpoint or from
scratch. | init_weights | 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: 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
input samples extracted by the backbone.
"""
x = self.conv1(x)
x = self.maxpool(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i in self.out_indices:
outs.append(x)
if len(outs) == 1:
return outs[0]
return tuple(outs) | 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/resnet.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet.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.bn.eval()
for m in self.conv1.modules():
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False | Prevent all the parameters from being optimized before
``self.frozen_stages``. | _freeze_stages | 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 train(self, mode: bool = True) -> None:
"""Set the optimization status when training."""
super().train(mode)
self._freeze_stages()
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval()
if mode and self.partial_bn:
self._partial_bn() | Set the optimization status when training. | train | 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 _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.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False | Prevent all the parameters from being optimized before
``self.frozen_stages``. | _freeze_stages | 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 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.maxpool(x)
for layer_name in self.res_layers:
res_layer = getattr(self, layer_name)
# no pool2 in R(2+1)d
x = res_layer(x)
return 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.
| 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 forward(self, x: torch.Tensor) -> torch.Tensor:
"""Defines the computation performed at every call."""
def _inner_forward(x):
"""Forward wrapper for utilizing checkpoint."""
identity = x
out = self.conv1(x)
out = self.conv2(out)
if self.downsample is not None:
identity = self.downsample(x)
out = out + identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
if self.non_local:
out = self.non_local_block(out)
return out | Defines the computation performed at every call. | 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."""
def _inner_forward(x):
"""Forward wrapper for utilizing checkpoint."""
identity = x
out = self.conv1(x)
out = self.conv2(out)
out = self.conv3(out)
if self.downsample is not None:
identity = self.downsample(x)
out = out + identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
if self.non_local:
out = self.non_local_block(out)
return out | Defines the computation performed at every call. | 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 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: int = 1,
style: str = 'pytorch',
inflate: Union[int, Sequence[int]] = 1,
inflate_style: str = '3x1x1',
non_local: Union[int, Sequence[int]] = 0,
non_local_cfg: Dict = dict(),
norm_cfg: Optional[Dict] = None,
act_cfg: Optional[Dict] = None,
conv_cfg: Optional[Dict] = None,
with_cp: bool = False,
**kwargs) -> nn.Module:
"""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.
blocks (int): Number of residual blocks.
spatial_stride (int | Sequence[int]): Spatial strides in
residual and conv layers. Defaults to 1.
temporal_stride (int | Sequence[int]): Temporal strides in
residual and conv layers. Defaults to 1.
dilation (int): Spacing between kernel elements. Defaults to 1.
style (str): 'pytorch' or 'caffe'. If set to 'pytorch', the
stride-two layer is the 3x3 conv layer,otherwise the
stride-two layer is the first 1x1 conv layer.
Defaults to ``'pytorch'``.
inflate (int | Sequence[int]): Determine whether to inflate
for each block. Defaults to 1.
inflate_style (str): ``3x1x1`` or ``3x3x3``. which determines
the kernel sizes and padding strides for conv1 and conv2
in each block. Default: ``'3x1x1'``.
non_local (int | Sequence[int]): Determine whether to apply
non-local module in the corresponding block of each stages.
Defaults to 0.
non_local_cfg (dict): Config for non-local module.
Defaults to ``dict()``.
conv_cfg (dict, optional): Config for conv layers.
Defaults to None.
norm_cfg (dict, optional): Config for norm layers.
Defaults to None.
act_cfg (dict, optional): Config for activate layers.
Defaults to None.
with_cp (bool, optional): Use checkpoint or not. Using checkpoint
will save some memory while slowing down the training speed.
Defaults to False.
Returns:
nn.Module: A residual layer for the given config.
"""
inflate = inflate if not isinstance(inflate, int) \
else (inflate,) * blocks
non_local = non_local if not isinstance(non_local, int) \
else (non_local,) * blocks
assert len(inflate) == blocks and len(non_local) == blocks
downsample = None
if spatial_stride != 1 or inplanes != planes * block.expansion:
downsample = ConvModule(
inplanes,
planes * block.expansion,
kernel_size=1,
stride=(temporal_stride, spatial_stride, spatial_stride),
bias=False,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=None)
layers = []
layers.append(
block(
inplanes,
planes,
spatial_stride=spatial_stride,
temporal_stride=temporal_stride,
dilation=dilation,
downsample=downsample,
style=style,
inflate=(inflate[0] == 1),
inflate_style=inflate_style,
non_local=(non_local[0] == 1),
non_local_cfg=non_local_cfg,
norm_cfg=norm_cfg,
conv_cfg=conv_cfg,
act_cfg=act_cfg,
with_cp=with_cp,
**kwargs))
inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(
block(
inplanes,
planes,
spatial_stride=1,
temporal_stride=1,
dilation=dilation,
style=style,
inflate=(inflate[i] == 1),
inflate_style=inflate_style,
non_local=(non_local[i] == 1),
non_local_cfg=non_local_cfg,
norm_cfg=norm_cfg,
conv_cfg=conv_cfg,
act_cfg=act_cfg,
with_cp=with_cp,
**kwargs))
return Sequential(*layers) | 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.
blocks (int): Number of residual blocks.
spatial_stride (int | Sequence[int]): Spatial strides in
residual and conv layers. Defaults to 1.
temporal_stride (int | Sequence[int]): Temporal strides in
residual and conv layers. Defaults to 1.
dilation (int): Spacing between kernel elements. Defaults to 1.
style (str): 'pytorch' or 'caffe'. If set to 'pytorch', the
stride-two layer is the 3x3 conv layer,otherwise the
stride-two layer is the first 1x1 conv layer.
Defaults to ``'pytorch'``.
inflate (int | Sequence[int]): Determine whether to inflate
for each block. Defaults to 1.
inflate_style (str): ``3x1x1`` or ``3x3x3``. which determines
the kernel sizes and padding strides for conv1 and conv2
in each block. Default: ``'3x1x1'``.
non_local (int | Sequence[int]): Determine whether to apply
non-local module in the corresponding block of each stages.
Defaults to 0.
non_local_cfg (dict): Config for non-local module.
Defaults to ``dict()``.
conv_cfg (dict, optional): Config for conv layers.
Defaults to None.
norm_cfg (dict, optional): Config for norm layers.
Defaults to None.
act_cfg (dict, optional): Config for activate layers.
Defaults to None.
with_cp (bool, optional): Use checkpoint or not. Using checkpoint
will save some memory while slowing down the training speed.
Defaults to False.
Returns:
nn.Module: A residual layer for the given config.
| 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.
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_param_names (list[str]): List of parameters that have been
inflated.
"""
weight_2d_name = module_name_2d + '.weight'
conv2d_weight = state_dict_2d[weight_2d_name]
kernel_t = conv3d.weight.data.shape[2]
new_weight = conv2d_weight.data.unsqueeze(2).expand_as(
conv3d.weight) / kernel_t
conv3d.weight.data.copy_(new_weight)
inflated_param_names.append(weight_2d_name)
if getattr(conv3d, 'bias') is not None:
bias_2d_name = module_name_2d + '.bias'
conv3d.bias.data.copy_(state_dict_2d[bias_2d_name])
inflated_param_names.append(bias_2d_name) | 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_param_names (list[str]): List of parameters that have been
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.
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_names (list[str]): List of parameters that have been
inflated.
"""
for param_name, param in bn3d.named_parameters():
param_2d_name = f'{module_name_2d}.{param_name}'
param_2d = state_dict_2d[param_2d_name]
if param.data.shape != param_2d.shape:
warnings.warn(f'The parameter of {module_name_2d} is not'
'loaded due to incompatible shapes. ')
return
param.data.copy_(param_2d)
inflated_param_names.append(param_2d_name)
for param_name, param in bn3d.named_buffers():
param_2d_name = f'{module_name_2d}.{param_name}'
# some buffers like num_batches_tracked may not exist in old
# checkpoints
if param_2d_name in state_dict_2d:
param_2d = state_dict_2d[param_2d_name]
param.data.copy_(param_2d)
inflated_param_names.append(param_2d_name) | 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_names (list[str]): List of parameters that have been
inflated.
| _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 inflated to fit in the shapes of
the 3d counterpart.
Args:
logger (MMLogger): The logger used to print
debugging information.
"""
state_dict_r2d = _load_checkpoint(self.pretrained, map_location='cpu')
if 'state_dict' in state_dict_r2d:
state_dict_r2d = state_dict_r2d['state_dict']
inflated_param_names = []
for name, module in self.named_modules():
if isinstance(module, ConvModule):
# we use a ConvModule to wrap conv+bn+relu layers, thus the
# name mapping is needed
if 'downsample' in name:
# layer{X}.{Y}.downsample.conv->layer{X}.{Y}.downsample.0
original_conv_name = name + '.0'
# layer{X}.{Y}.downsample.bn->layer{X}.{Y}.downsample.1
original_bn_name = name + '.1'
else:
# layer{X}.{Y}.conv{n}.conv->layer{X}.{Y}.conv{n}
original_conv_name = name
# layer{X}.{Y}.conv{n}.bn->layer{X}.{Y}.bn{n}
original_bn_name = name.replace('conv', 'bn')
if original_conv_name + '.weight' not in state_dict_r2d:
logger.warning(f'Module not exist in the state_dict_r2d'
f': {original_conv_name}')
else:
shape_2d = state_dict_r2d[original_conv_name +
'.weight'].shape
shape_3d = module.conv.weight.data.shape
if shape_2d != shape_3d[:2] + shape_3d[3:]:
logger.warning(f'Weight shape mismatch for '
f': {original_conv_name} : '
f'3d weight shape: {shape_3d}; '
f'2d weight shape: {shape_2d}. ')
else:
self._inflate_conv_params(module.conv, state_dict_r2d,
original_conv_name,
inflated_param_names)
if original_bn_name + '.weight' not in state_dict_r2d:
logger.warning(f'Module not exist in the state_dict_r2d'
f': {original_bn_name}')
else:
self._inflate_bn_params(module.bn, state_dict_r2d,
original_bn_name,
inflated_param_names)
# check if any parameters in the 2d checkpoint are not loaded
remaining_names = set(
state_dict_r2d.keys()) - set(inflated_param_names)
if remaining_names:
logger.info(f'These parameters in the 2d checkpoint are not loaded'
f': {remaining_names}') | 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.
Args:
logger (MMLogger): The logger used to print
debugging information.
| _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 _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_t, self.conv1_stride_s,
self.conv1_stride_s),
padding=tuple([(k - 1) // 2 for k in _triple(self.conv1_kernel)]),
bias=False,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg)
self.maxpool = nn.MaxPool3d(
kernel_size=(1, 3, 3),
stride=(self.pool1_stride_t, self.pool1_stride_s,
self.pool1_stride_s),
padding=(0, 1, 1))
self.pool2 = nn.MaxPool3d(kernel_size=(2, 1, 1), stride=(2, 1, 1)) | 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/resnet3d.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.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, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False | Prevent all the parameters from being optimized before
``self.frozen_stages``. | _freeze_stages | 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 added to
be compatible with mmdet. Defaults to None.
"""
if pretrained:
self.pretrained = pretrained
if isinstance(self.pretrained, str):
logger = MMLogger.get_current_instance()
logger.info(f'load model from: {self.pretrained}')
if self.pretrained2d:
# Inflate 2D model into 3D model.
self.inflate_weights(logger)
else:
# Directly load 3D model.
load_checkpoint(
self, self.pretrained, strict=False, logger=logger)
elif self.pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv3d):
kaiming_init(m)
elif isinstance(m, _BatchNorm):
constant_init(m, 1)
if self.zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck3d):
constant_init(m.conv3.bn, 0)
elif isinstance(m, BasicBlock3d):
constant_init(m.conv2.bn, 0)
else:
raise TypeError('pretrained must be a str or 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 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
samples extracted by the backbone.
"""
x = self.conv1(x)
if self.with_pool1:
x = self.maxpool(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i == 0 and self.with_pool2:
x = self.pool2(x)
if i in self.out_indices:
outs.append(x)
if len(outs) == 1:
return outs[0]
return tuple(outs) | 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 train(self, mode: bool = True) -> None:
"""Set the optimization status when training."""
super().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/resnet3d.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py | Apache-2.0 |
def _freeze_stages(self) -> None:
"""Prevent all the parameters from being optimized before
``self.frozen_stages``."""
if self.all_frozen:
layer = getattr(self, self.layer_name)
layer.eval()
for param in layer.parameters():
param.requires_grad = False | Prevent all the parameters from being optimized before
``self.frozen_stages``. | _freeze_stages | 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.
"""
res_layer = getattr(self, self.layer_name)
out = res_layer(x)
return out | 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 train(self, mode: bool = True) -> None:
"""Set the optimization status when training."""
super().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/resnet3d.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d.py | Apache-2.0 |
def train(self, mode=True):
"""Set the optimization status when training."""
super(ResNet3d, self).train(mode)
self._freeze_stages()
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval()
if self.bn_frozen:
for param in m.parameters():
param.requires_grad = False | Set the optimization status when training. | train | python | open-mmlab/mmaction2 | mmaction/models/backbones/resnet3d_csn.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet3d_csn.py | Apache-2.0 |
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Defines the computation performed at every call."""
# x should be a 5-d tensor
assert len(x.shape) == 5
N, C, T, H, W = x.shape
out_shape = (N, self.out_channels, self.stride[0] * T,
self.stride[1] * H, self.stride[2] * W)
x = self.conv(x, output_size=out_shape)
if self.with_bn:
x = self.bn(x)
if self.with_relu:
x = self.relu(x)
return x | Defines the computation performed at every call. | 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 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 inflated to fit in the shapes of
the 3d counterpart. For pathway the ``lateral_connection`` part should
not be inflated from 2d weights.
Args:
logger (MMLogger): The logger used to print
debugging information.
"""
state_dict_r2d = _load_checkpoint(self.pretrained, map_location='cpu')
if 'state_dict' in state_dict_r2d:
state_dict_r2d = state_dict_r2d['state_dict']
inflated_param_names = []
for name, module in self.named_modules():
if 'lateral' in name:
continue
if isinstance(module, ConvModule):
# we use a ConvModule to wrap conv+bn+relu layers, thus the
# name mapping is needed
if 'downsample' in name:
# layer{X}.{Y}.downsample.conv->layer{X}.{Y}.downsample.0
original_conv_name = name + '.0'
# layer{X}.{Y}.downsample.bn->layer{X}.{Y}.downsample.1
original_bn_name = name + '.1'
else:
# layer{X}.{Y}.conv{n}.conv->layer{X}.{Y}.conv{n}
original_conv_name = name
# layer{X}.{Y}.conv{n}.bn->layer{X}.{Y}.bn{n}
original_bn_name = name.replace('conv', 'bn')
if original_conv_name + '.weight' not in state_dict_r2d:
logger.warning(f'Module not exist in the state_dict_r2d'
f': {original_conv_name}')
else:
self._inflate_conv_params(module.conv, state_dict_r2d,
original_conv_name,
inflated_param_names)
if original_bn_name + '.weight' not in state_dict_r2d:
logger.warning(f'Module not exist in the state_dict_r2d'
f': {original_bn_name}')
else:
self._inflate_bn_params(module.bn, state_dict_r2d,
original_bn_name,
inflated_param_names)
# check if any parameters in the 2d checkpoint are not loaded
remaining_names = set(
state_dict_r2d.keys()) - set(inflated_param_names)
if remaining_names:
logger.info(f'These parameters in the 2d checkpoint are not loaded'
f': {remaining_names}') | 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 pathway the ``lateral_connection`` part should
not be inflated from 2d weights.
Args:
logger (MMLogger): The logger used to print
debugging information.
| 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
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 paddings.
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_param_names (list[str]): List of parameters that have been
inflated.
"""
weight_2d_name = module_name_2d + '.weight'
conv2d_weight = state_dict_2d[weight_2d_name]
old_shape = conv2d_weight.shape
new_shape = conv3d.weight.data.shape
kernel_t = new_shape[2]
if new_shape[1] != old_shape[1]:
if new_shape[1] < old_shape[1]:
warnings.warn(f'The parameter of {module_name_2d} is not'
'loaded due to incompatible shapes. ')
return
# Inplanes may be different due to lateral connections
new_channels = new_shape[1] - old_shape[1]
pad_shape = old_shape
pad_shape = pad_shape[:1] + (new_channels, ) + pad_shape[2:]
# Expand parameters by concat extra channels
conv2d_weight = torch.cat(
(conv2d_weight,
torch.zeros(pad_shape).type_as(conv2d_weight).to(
conv2d_weight.device)),
dim=1)
new_weight = conv2d_weight.data.unsqueeze(2).expand_as(
conv3d.weight) / kernel_t
conv3d.weight.data.copy_(new_weight)
inflated_param_names.append(weight_2d_name)
if getattr(conv3d, 'bias') is not None:
bias_2d_name = module_name_2d + '.bias'
conv3d.bias.data.copy_(state_dict_2d[bias_2d_name])
inflated_param_names.append(bias_2d_name) | 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 paddings.
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_param_names (list[str]): List of parameters that have been
inflated.
| _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, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False
if i != len(self.res_layers) and self.lateral:
# No fusion needed in the final stage
lateral_name = self.lateral_connections[i - 1]
conv_lateral = getattr(self, lateral_name)
conv_lateral.eval()
for param in conv_lateral.parameters():
param.requires_grad = False | 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 init_weights(self, pretrained: Optional[str] = None) -> None:
"""Initiate the parameters either from existing checkpoint or from
scratch."""
if pretrained:
self.pretrained = pretrained
# Override the init_weights of i3d
super().init_weights()
for module_name in self.lateral_connections:
layer = getattr(self, module_name)
for m in layer.modules():
if isinstance(m, (nn.Conv3d, nn.Conv2d)):
kaiming_init(m) | Initiate the parameters either from existing checkpoint or from
scratch. | init_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 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('cfg must be a dict containing the key "type"')
cfg_ = cfg.copy()
pathway_type = cfg_.pop('type')
if pathway_type not in pathway_cfg:
raise KeyError(f'Unrecognized pathway type {pathway_type}')
pathway_cls = pathway_cfg[pathway_type]
pathway = pathway_cls(*args, **kwargs, **cfg_)
return pathway | 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 init_weights(self, pretrained: Optional[str] = None) -> None:
"""Initiate the parameters either from existing checkpoint or from
scratch."""
if pretrained:
self.pretrained = pretrained
if isinstance(self.pretrained, str):
logger = MMLogger.get_current_instance()
msg = f'load model from: {self.pretrained}'
print_log(msg, logger=logger)
# Directly load 3D model.
load_checkpoint(self, self.pretrained, strict=True, logger=logger)
elif self.pretrained is None:
# Init two branch separately.
self.fast_path.init_weights()
self.slow_path.init_weights()
else:
raise TypeError('pretrained must be a str or None') | Initiate the parameters either from existing checkpoint or from
scratch. | init_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 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 = nn.functional.interpolate(
x,
mode='nearest',
scale_factor=(1.0 / self.resample_rate, 1.0, 1.0))
x_slow = self.slow_path.conv1(x_slow)
x_slow = self.slow_path.maxpool(x_slow)
x_fast = nn.functional.interpolate(
x,
mode='nearest',
scale_factor=(1.0 / (self.resample_rate // self.speed_ratio), 1.0,
1.0))
x_fast = self.fast_path.conv1(x_fast)
x_fast = self.fast_path.maxpool(x_fast)
if self.slow_path.lateral:
x_fast_lateral = self.slow_path.conv1_lateral(x_fast)
x_slow = torch.cat((x_slow, x_fast_lateral), dim=1)
for i, layer_name in enumerate(self.slow_path.res_layers):
res_layer = getattr(self.slow_path, layer_name)
x_slow = res_layer(x_slow)
res_layer_fast = getattr(self.fast_path, layer_name)
x_fast = res_layer_fast(x_fast)
if (i != len(self.slow_path.res_layers) - 1
and self.slow_path.lateral):
# No fusion needed in the final stage
lateral_name = self.slow_path.lateral_connections[i]
conv_lateral = getattr(self.slow_path, lateral_name)
x_fast_lateral = conv_lateral(x_fast)
x_slow = torch.cat((x_slow, x_fast_lateral), dim=1)
out = (x_slow, x_fast)
return out | 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 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.
"""
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.conv2(out)
out = self.conv3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out | 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_audio.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_audio.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[ConfigType] = None,
with_cp: bool = False) -> nn.Module:
"""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.
blocks (int): Number of residual blocks.
stride (int): Strides of residual blocks of each stage.
Defaults to 1.
dilation (int): Spacing between kernel elements. Defaults to 1.
factorize (Uninon[int, Sequence[int]]): Determine whether to
factorize for each block. Defaults to 1.
norm_cfg (Union[dict, ConfigDict], optional): Config for norm
layers. Defaults to None.
with_cp (bool): Use checkpoint or not. Using checkpoint will save
some memory while slowing down the training speed.
Defaults to False.
Returns:
nn.Module: A residual layer for the given config.
"""
factorize = factorize if not isinstance(
factorize, int) else (factorize, ) * blocks
assert len(factorize) == blocks
downsample = None
if stride != 1 or inplanes != planes * block.expansion:
downsample = ConvModule(
inplanes,
planes * block.expansion,
kernel_size=1,
stride=stride,
bias=False,
norm_cfg=norm_cfg,
act_cfg=None)
layers = []
layers.append(
block(
inplanes,
planes,
stride,
dilation,
downsample,
factorize=(factorize[0] == 1),
norm_cfg=norm_cfg,
with_cp=with_cp))
inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(
block(
inplanes,
planes,
1,
dilation,
factorize=(factorize[i] == 1),
norm_cfg=norm_cfg,
with_cp=with_cp))
return nn.Sequential(*layers) | 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.
blocks (int): Number of residual blocks.
stride (int): Strides of residual blocks of each stage.
Defaults to 1.
dilation (int): Spacing between kernel elements. Defaults to 1.
factorize (Uninon[int, Sequence[int]]): Determine whether to
factorize for each block. Defaults to 1.
norm_cfg (Union[dict, ConfigDict], optional): Config for norm
layers. Defaults to None.
with_cp (bool): Use checkpoint or not. Using checkpoint will save
some memory while slowing down the training speed.
Defaults to False.
Returns:
nn.Module: A residual layer for the given config.
| 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,
bias=False,
conv_cfg=dict(type='ConvAudio', op='sum'),
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg) | 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 _freeze_stages(self) -> None:
"""Prevent all the parameters from being optimized before
``self.frozen_stages``."""
if self.frozen_stages >= 0:
self.conv1.bn.eval()
for m in [self.conv1.conv, self.conv1.bn]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False | Prevent all the parameters from being optimized before
``self.frozen_stages``. | _freeze_stages | 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 init_weights(self) -> None:
"""Initiate the parameters either from existing checkpoint or from
scratch."""
if isinstance(self.pretrained, str):
logger = MMLogger.get_current_instance()
logger.info(f'load model from: {self.pretrained}')
load_checkpoint(self, self.pretrained, strict=False, logger=logger)
elif self.pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv2d):
kaiming_init(m)
elif isinstance(m, _BatchNorm):
constant_init(m, 1)
if self.zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck2dAudio):
constant_init(m.conv3.bn, 0)
else:
raise TypeError('pretrained must be a str or None') | Initiate the parameters either from existing checkpoint or from
scratch. | init_weights | 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 = self.conv1(x)
for layer_name in self.res_layers:
res_layer = getattr(self, layer_name)
x = res_layer(x)
return 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.
| 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 train(self, mode: bool = True) -> None:
"""Set the optimization status when training."""
super().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/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): The input data.
module (nn.modules.batchnorm): a batch normalization module. Will use
params from this batch normalization module to do the operation.
training (bool, optional): if true, apply the train mode batch
normalization. Defaults to None and will use the training mode of
the module.
"""
if training is None:
training = module.training
return F.batch_norm(
input=inputs,
running_mean=None if training else module.running_mean,
running_var=None if training else module.running_var,
weight=module.weight,
bias=module.bias,
training=training,
momentum=module.momentum,
eps=module.eps) | 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 the operation.
training (bool, optional): if true, apply the train mode batch
normalization. Defaults to None and will use the training mode of
the module.
| 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 = self.conv1(x)
out = self.bn1(out).relu_()
out = self.conv2(out)
out = self.bn2(out).relu_()
out = self.conv3(out)
out = self.bn3(out)
if hasattr(self, 'downsample'):
x = self.downsample(x)
return out.add_(x).relu_() | 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 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.
x = self.conv1(x)
x = self.bn1(x).relu_()
x = self.pool3d(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
return x | 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 with the temporal dimension.
Args:
data (torch.Tensor): Split data for certain group in shape
[N, num_segments, C, H, W].
offset (torch.Tensor): Data offsets for this group data in shape
[N, num_segments].
"""
# [N, num_segments, C, H, W]
n, t, c, h, w = data.shape
# offset0, offset1: [N, num_segments]
offset0 = torch.floor(offset).int()
offset1 = offset0 + 1
# data, data0, data1: [N, num_segments, C, H * W]
data = data.view(n, t, c, h * w).contiguous()
try:
from mmcv.ops import tin_shift
except (ImportError, ModuleNotFoundError):
raise ImportError('Failed to import `tin_shift` from `mmcv.ops`. You '
'will be unable to use TIN. ')
data0 = tin_shift(data, offset0)
data1 = tin_shift(data, offset1)
# weight0, weight1: [N, num_segments]
weight0 = 1 - (offset - offset0.float())
weight1 = 1 - weight0
# weight0, weight1:
# [N, num_segments] -> [N, num_segments, C // num_segments] -> [N, C]
group_size = offset.shape[1]
weight0 = weight0[:, :, None].repeat(1, 1, c // group_size)
weight0 = weight0.view(weight0.size(0), -1)
weight1 = weight1[:, :, None].repeat(1, 1, c // group_size)
weight1 = weight1.view(weight1.size(0), -1)
# weight0, weight1: [N, C] -> [N, 1, C, 1]
weight0 = weight0[:, None, :, None]
weight1 = weight1[:, None, :, None]
# output: [N, num_segments, C, H * W] -> [N, num_segments, C, H, W]
output = weight0 * data0 + weight1 * data1
output = output.view(n, t, c, h, w)
return output | 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:
data (torch.Tensor): Split data for certain group in shape
[N, num_segments, C, H, W].
offset (torch.Tensor): Data offsets for this group data in shape
[N, num_segments].
| 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 forward(self, x):
"""Defines the computation performed at every call.
Args:
x (torch.Tensor): The input data.
Returns:
torch.Tensor: The output of the module.
"""
# input shape: [num_batches * num_segments, C, H, W]
# output x shape: [num_batches * num_segments, C, H, W]
x = self.net1(x)
# [num_batches * num_segments, C, H, W]
x = self.net2(x)
return x | 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_tin.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tin.py | Apache-2.0 |
def init_weights(self):
"""Initiate the parameters either from existing checkpoint or from
scratch."""
# we set the initial bias of the convolution
# layer to 0, and the final initial output will be 1.0
self.conv.bias.data[...] = 0 | Initiate the parameters either from existing checkpoint or from
scratch. | init_weights | 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 forward(self, x):
"""Defines the computation performed at every call.
Args:
x (torch.Tensor): The input data.
Returns:
torch.Tensor: The output of the module.
"""
# calculate weight
# [N, C, T]
n, _, t = x.shape
# [N, groups, T]
x = self.conv(x)
x = x.view(n, self.groups, t)
# [N, T, groups]
x = x.permute(0, 2, 1)
# scale the output to range (0, 2)
x = 2 * self.sigmoid(x)
# [N, T, groups]
return x | 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_tin.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tin.py | Apache-2.0 |
def init_weights(self):
"""Initiate the parameters either from existing checkpoint or from
scratch."""
# The bias of the last fc layer is initialized to
# make the post-sigmoid output start from 1
self.fc2.bias.data[...] = 0.5108 | Initiate the parameters either from existing checkpoint or from
scratch. | init_weights | 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 forward(self, x):
"""Defines the computation performed at every call.
Args:
x (torch.Tensor): The input data.
Returns:
torch.Tensor: The output of the module.
"""
# calculate offset
# [N, C, T]
n, _, t = x.shape
# [N, 1, T]
x = self.conv(x)
# [N, T]
x = x.view(n, t)
# [N, T]
x = self.relu(self.fc1(x))
# [N, groups]
x = self.fc2(x)
# [N, 1, groups]
x = x.view(n, 1, -1)
# to make sure the output is in (-t/2, t/2)
# where t = num_segments = 8
x = 4 * (self.sigmoid(x) - 0.5)
# [N, 1, groups]
return x | 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_tin.py | https://github.com/open-mmlab/mmaction2/blob/master/mmaction/models/backbones/resnet_tin.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 output of the module.
"""
# x: [N, C, H, W],
# where N = num_batches x num_segments, C = shift_div * num_folds
n, c, h, w = x.size()
num_batches = n // self.num_segments
num_folds = c // self.shift_div
# x_out: [num_batches x num_segments, C, H, W]
x_out = torch.zeros((n, c, h, w), device=x.device)
# x_descriptor: [num_batches, num_segments, num_folds, H, W]
x_descriptor = x[:, :num_folds, :, :].view(num_batches,
self.num_segments,
num_folds, h, w)
# x should only obtain information on temporal and channel dimensions
# x_pooled: [num_batches, num_segments, num_folds, W]
x_pooled = torch.mean(x_descriptor, 3)
# x_pooled: [num_batches, num_segments, num_folds]
x_pooled = torch.mean(x_pooled, 3)
# x_pooled: [num_batches, num_folds, num_segments]
x_pooled = x_pooled.permute(0, 2, 1).contiguous()
# Calculate weight and bias, here groups = 2
# x_offset: [num_batches, groups]
x_offset = self.offset_net(x_pooled).view(num_batches, -1)
# x_weight: [num_batches, num_segments, groups]
x_weight = self.weight_net(x_pooled)
# x_offset: [num_batches, 2 * groups]
x_offset = torch.cat([x_offset, -x_offset], 1)
# x_shift: [num_batches, num_segments, num_folds, H, W]
x_shift = linear_sampler(x_descriptor, x_offset)
# x_weight: [num_batches, num_segments, groups, 1]
x_weight = x_weight[:, :, :, None]
# x_weight:
# [num_batches, num_segments, groups * 2, c // self.shift_div // 4]
x_weight = x_weight.repeat(1, 1, 2, num_folds // 2 // 2)
# x_weight:
# [num_batches, num_segments, c // self.shift_div = num_folds]
x_weight = x_weight.view(x_weight.size(0), x_weight.size(1), -1)
# x_weight: [num_batches, num_segments, num_folds, 1, 1]
x_weight = x_weight[:, :, :, None, None]
# x_shift: [num_batches, num_segments, num_folds, H, W]
x_shift = x_shift * x_weight
# x_shift: [num_batches, num_segments, num_folds, H, W]
x_shift = x_shift.contiguous().view(n, num_folds, h, w)
# x_out: [num_batches x num_segments, C, H, W]
x_out[:, :num_folds, :] = x_shift
x_out[:, num_folds:, :] = x[:, num_folds:, :]
return x_out | 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_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 shift.')
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 division parts for shift.
Returns:
nn.Sequential: A Sequential container consisted of
deformed Interlace blocks.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
if i % n_round == 0:
tds = TemporalInterlace(
b.conv1.in_channels,
num_segments=num_segments,
shift_div=shift_div)
blocks[i].conv1.conv = CombineNet(tds,
blocks[i].conv1.conv)
return nn.Sequential(*blocks)
self.layer1 = make_block_interlace(self.layer1, num_segment_list[0],
self.shift_div)
self.layer2 = make_block_interlace(self.layer2, num_segment_list[1],
self.shift_div)
self.layer3 = make_block_interlace(self.layer3, num_segment_list[2],
self.shift_div)
self.layer4 = make_block_interlace(self.layer4, num_segment_list[3],
self.shift_div) | 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 division parts for shift.
Returns:
nn.Sequential: A Sequential container consisted of
deformed Interlace blocks.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
if i % n_round == 0:
tds = TemporalInterlace(
b.conv1.in_channels,
num_segments=num_segments,
shift_div=shift_div)
blocks[i].conv1.conv = CombineNet(tds,
blocks[i].conv1.conv)
return nn.Sequential(*blocks) | 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 Sequential container consisted of
deformed Interlace blocks.
| 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 forward(self, x):
"""Defines the computation performed at every call."""
x = self.block(x)
n, c, h, w = x.size()
x = x.view(n // self.num_segments, self.num_segments, c, h,
w).transpose(1, 2).contiguous()
x = self.non_local_block(x)
x = x.transpose(1, 2).contiguous().view(n, c, h, w)
return x | Defines the computation performed at every call. | forward | 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 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.
Returns:
torch.Tensor: The shifted feature.
"""
# [N, C, H, W]
n, c, h, w = x.size()
# [N // num_segments, num_segments, C, H*W]
# can't use 5 dimensional array on PPL2D backend for caffe
x = x.view(-1, num_segments, c, h * w)
# get shift fold
fold = c // shift_div
# split c channel into three parts:
# left_split, mid_split, right_split
left_split = x[:, :, :fold, :]
mid_split = x[:, :, fold:2 * fold, :]
right_split = x[:, :, 2 * fold:, :]
# can't use torch.zeros(*A.shape) or torch.zeros_like(A)
# because array on caffe inference must be got by computing
# shift left on num_segments channel in `left_split`
zeros = left_split - left_split
blank = zeros[:, :1, :, :]
left_split = left_split[:, 1:, :, :]
left_split = torch.cat((left_split, blank), 1)
# shift right on num_segments channel in `mid_split`
zeros = mid_split - mid_split
blank = zeros[:, :1, :, :]
mid_split = mid_split[:, :-1, :, :]
mid_split = torch.cat((blank, mid_split), 1)
# right_split: no shift
# concatenate
out = torch.cat((left_split, mid_split, right_split), 2)
# [N, C, H, W]
# restore the original dimension
return out.view(n, c, h, w) | 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_temporal_shift(self):
"""Make temporal shift for some layers."""
if self.temporal_pool:
num_segment_list = [
self.num_segments, self.num_segments // 2,
self.num_segments // 2, self.num_segments // 2
]
else:
num_segment_list = [self.num_segments] * 4
if num_segment_list[-1] <= 0:
raise ValueError('num_segment_list[-1] must be positive')
if self.shift_place == 'block':
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.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
blocks[i] = TemporalShift(
b, num_segments=num_segments, shift_div=self.shift_div)
return nn.Sequential(*blocks)
self.layer1 = make_block_temporal(self.layer1, num_segment_list[0])
self.layer2 = make_block_temporal(self.layer2, num_segment_list[1])
self.layer3 = make_block_temporal(self.layer3, num_segment_list[2])
self.layer4 = make_block_temporal(self.layer4, num_segment_list[3])
elif 'blockres' in self.shift_place:
n_round = 1
if len(list(self.layer3.children())) >= 23:
n_round = 2
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.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
if i % n_round == 0:
blocks[i].conv1.conv = TemporalShift(
b.conv1.conv,
num_segments=num_segments,
shift_div=self.shift_div)
return nn.Sequential(*blocks)
self.layer1 = make_block_temporal(self.layer1, num_segment_list[0])
self.layer2 = make_block_temporal(self.layer2, num_segment_list[1])
self.layer3 = make_block_temporal(self.layer3, num_segment_list[2])
self.layer4 = make_block_temporal(self.layer4, num_segment_list[3])
else:
raise NotImplementedError | Make temporal shift for some layers. | make_temporal_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 shifted blocks.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
blocks[i] = TemporalShift(
b, num_segments=num_segments, shift_div=self.shift_div)
return nn.Sequential(*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/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 shifted blocks.
"""
blocks = list(stage.children())
for i, b in enumerate(blocks):
if i % n_round == 0:
blocks[i].conv1.conv = TemporalShift(
b.conv1.conv,
num_segments=num_segments,
shift_div=self.shift_div)
return nn.Sequential(*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/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.Module): Module to make temporal pool.
num_segments (int): Number of frame segments.
"""
def __init__(self, net, num_segments):
super().__init__()
self.net = net
self.num_segments = num_segments
self.max_pool3d = nn.MaxPool3d(
kernel_size=(3, 1, 1), stride=(2, 1, 1), padding=(1, 0, 0))
def forward(self, x):
"""Defines the computation performed at every call."""
# [N, C, H, W]
n, c, h, w = x.size()
# [N // num_segments, C, num_segments, H, W]
x = x.view(n // self.num_segments, self.num_segments, c, h,
w).transpose(1, 2)
# [N // num_segmnets, C, num_segments // 2, H, W]
x = self.max_pool3d(x)
# [N // 2, C, H, W]
x = x.transpose(1, 2).contiguous().view(n // 2, c, h, w)
return self.net(x)
self.layer2 = TemporalPool(self.layer2, self.num_segments) | 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 forward(self, x):
"""Defines the computation performed at every call."""
# [N, C, H, W]
n, c, h, w = x.size()
# [N // num_segments, C, num_segments, H, W]
x = x.view(n // self.num_segments, self.num_segments, c, h,
w).transpose(1, 2)
# [N // num_segmnets, C, num_segments // 2, H, W]
x = self.max_pool3d(x)
# [N // 2, C, H, W]
x = x.transpose(1, 2).contiguous().view(n // 2, c, h, w)
return self.net(x) | Defines the computation performed at every call. | forward | 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}'
res_layer = getattr(self, layer_name)
for idx, non_local in enumerate(non_local_stage):
if non_local:
res_layer[idx] = NL3DWrapper(res_layer[idx],
self.num_segments,
self.non_local_cfg) | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.