# Copyright (c) 2023, NVIDIA CORPORATION.
# 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.

from typing import Union, List, Tuple

import torch


def maybe_size(tensor: torch.Tensor, dim: int = -1):
    return tensor.size(dim) if tensor is not None else 0


def maybe_empty_like(input: torch.Tensor, create_tensor: bool = True):
    # intended for usages where a gradient is only initialized
    # if we have the corresponding ctx.needs_input_grads
    return torch.empty_like(input) if create_tensor else None


def maybe_empty(
    size: Union[List[int], Tuple[int], torch.Size],
    device: torch.device,
    dtype: torch.dtype,
    create_tensor: bool = True,
):
    # intended for usages where a gradient is only initialized
    # if we have the corresponding ctx.needs_input_grads
    return torch.empty(size, device=device, dtype=dtype) if create_tensor else None
