# 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 nn, Tensor
[docs]class TfAvgPool3D(nn.Module):
"""
TfAvgPool3D
"""
[docs] def __init__(self) -> None:
super().__init__()
self.avgf = nn.AvgPool3d((1, 3, 3), stride=(1, 2, 2))
[docs] def forward(self, x: Tensor) -> Tensor:
if x.shape[-1] != x.shape[-2]:
raise RuntimeError('only same shape for h and w ' +
'are supported by avg with tf_like')
if x.shape[-1] != x.shape[-2]:
raise RuntimeError('only same shape for h and w ' +
'are supported by avg with tf_like')
f1 = x.shape[-1] % 2 != 0
if f1:
padding_pad = (0, 0, 0, 0)
else:
padding_pad = (0, 1, 0, 1)
x = torch.nn.functional.pad(x, padding_pad)
if f1:
x = torch.nn.functional.avg_pool3d(x,
(1, 3, 3),
stride=(1, 2, 2),
count_include_pad=False,
padding=(0, 1, 1))
else:
x = self.avgf(x)
x[..., -1] = x[..., -1] * 9/6
x[..., -1, :] = x[..., -1, :] * 9/6
return x