# -*- coding:utf-8 -*-

import tensorflow as tf

from hypernets.utils import logging
logger = logging.get_logger(__name__)

def set_memory_growth():
    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
        try:
            # Currently, memory growth needs to be the same across GPUs
            for gpu in gpus:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            logger.info(f'{len(gpus)}, "Physical GPUs,", {len(logical_gpus)}, "Logical GPUs"')
        except RuntimeError as e:
            # Memory growth must be set before GPUs have been initialized
            print(e)


def set_memory_limit(limit):
    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
        try:
            for gpu in gpus:
                tf.config.experimental.set_virtual_device_configuration(
                    gpu,
                    [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=limit)])
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            logger.info(f'{len(gpus)}, "Physical GPUs,", {len(logical_gpus)}, "Logical GPUs"')
        except RuntimeError as e:
            # Memory growth must be set before GPUs have been initialized
            print(e)
