Source code for towhee.models.layers.temporal_cg_avgpool3d

# Copyright 2022 Zilliz. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Original code from https://github.com/Atze00/MoViNet-pytorch
#
# Modified by Zilliz.

import torch
from torch import Tensor
from towhee.models.utils.causal_module import CausalModule

[docs]class TemporalCGAvgPool3D(CausalModule): """ TemporalCGAvgPool3D """
[docs] def __init__(self,) -> None: super().__init__() self.n_cumulated_values = 0 self.register_forward_hook(self._detach_activation)
[docs] def forward(self, x: Tensor) -> Tensor: input_shape = x.shape device = x.device cumulative_sum = torch.cumsum(x, dim=2) if self.activation is None: self.activation = cumulative_sum[:, :, -1:].clone() else: cumulative_sum += self.activation self.activation = cumulative_sum[:, :, -1:].clone() divisor = (torch.arange(1, input_shape[2]+1, device=device)[None, None, :, None, None] .expand(x.shape)) x = cumulative_sum / (self.n_cumulated_values + divisor) self.n_cumulated_values += input_shape[2] return x
@staticmethod # pylint: disable=W0613 def _detach_activation(module: CausalModule, input_tensor: Tensor, output: Tensor) -> None: module.activation.detach_() def reset_activation(self) -> None: super().reset_activation() self.n_cumulated_values = 0