# Copyright 2024 The HuggingFace Team. 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.
"""
MindSpore utilities: Utilities related to MindSpore
"""

from typing import List, Optional, Tuple, Union

import numpy as np

import mindspore as ms
from mindspore import ops

from . import logging

logger = logging.get_logger(__name__)  # pylint: disable=invalid-name


def randn(
    size: Union[Tuple, List], generator: Optional["np.random.Generator"] = None, dtype: Optional["ms.Type"] = None
):
    if generator is None:
        generator = np.random.default_rng()

    return ms.tensor(generator.standard_normal(size), dtype=dtype)


def randn_tensor(
    shape: Union[Tuple, List],
    generator: Optional[Union[List["np.random.Generator"], "np.random.Generator"]] = None,
    dtype: Optional["ms.Type"] = None,
):
    """A helper function to create random tensors with the desired `dtype`. When
    passing a list of generators, you can seed each batch size individually.
    """
    batch_size = shape[0]

    # make sure generator list of length 1 is treated like a non-list
    if isinstance(generator, list) and len(generator) == 1:
        generator = generator[0]

    if isinstance(generator, list):
        shape = (1,) + shape[1:]
        latents = [randn(shape, generator=generator[i], dtype=dtype) for i in range(batch_size)]
        latents = ops.cat(latents, axis=0)
    else:
        latents = randn(shape, generator=generator, dtype=dtype)

    return latents
