2021-08-17 19:52:42 +08:00
|
|
|
# Copyright (c) OpenMMLab. All rights reserved.
|
2021-04-16 19:22:41 +08:00
|
|
|
import collections.abc
|
2021-07-08 22:49:05 +08:00
|
|
|
import warnings
|
2021-04-16 19:22:41 +08:00
|
|
|
from itertools import repeat
|
|
|
|
|
2021-07-07 11:55:53 +08:00
|
|
|
import torch
|
2022-08-24 15:59:02 +08:00
|
|
|
from mmengine.utils import digit_version
|
2021-07-07 11:55:53 +08:00
|
|
|
|
|
|
|
|
|
|
|
def is_tracing() -> bool:
|
2022-04-15 20:19:20 +08:00
|
|
|
"""Determine whether the model is called during the tracing of code with
|
|
|
|
``torch.jit.trace``."""
|
2021-12-31 12:55:47 +08:00
|
|
|
if digit_version(torch.__version__) >= digit_version('1.6.0'):
|
2021-07-07 11:55:53 +08:00
|
|
|
on_trace = torch.jit.is_tracing()
|
|
|
|
# In PyTorch 1.6, torch.jit.is_tracing has a bug.
|
|
|
|
# Refers to https://github.com/pytorch/pytorch/issues/42448
|
|
|
|
if isinstance(on_trace, bool):
|
|
|
|
return on_trace
|
|
|
|
else:
|
|
|
|
return torch._C._is_tracing()
|
2021-07-08 22:49:05 +08:00
|
|
|
else:
|
|
|
|
warnings.warn(
|
|
|
|
'torch.jit.is_tracing is only supported after v1.6.0. '
|
|
|
|
'Therefore is_tracing returns False automatically. Please '
|
|
|
|
'set on_trace manually if you are using trace.', UserWarning)
|
|
|
|
return False
|
2021-07-07 11:55:53 +08:00
|
|
|
|
2021-04-16 19:22:41 +08:00
|
|
|
|
|
|
|
# From PyTorch internals
|
|
|
|
def _ntuple(n):
|
2022-04-15 20:19:20 +08:00
|
|
|
"""A `to_tuple` function generator.
|
|
|
|
|
|
|
|
It returns a function, this function will repeat the input to a tuple of
|
|
|
|
length ``n`` if the input is not an Iterable object, otherwise, return the
|
|
|
|
input directly.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
n (int): The number of the target length.
|
|
|
|
"""
|
2021-04-16 19:22:41 +08:00
|
|
|
|
|
|
|
def parse(x):
|
|
|
|
if isinstance(x, collections.abc.Iterable):
|
|
|
|
return x
|
|
|
|
return tuple(repeat(x, n))
|
|
|
|
|
|
|
|
return parse
|
|
|
|
|
|
|
|
|
|
|
|
to_1tuple = _ntuple(1)
|
|
|
|
to_2tuple = _ntuple(2)
|
|
|
|
to_3tuple = _ntuple(3)
|
|
|
|
to_4tuple = _ntuple(4)
|
|
|
|
to_ntuple = _ntuple
|