gpu_utils.py 3.54 KB
import os

def tf_setup(GPU_MEM_LIMIT : int) -> None:
    
    os.environ['TF_USE_LEGACY_KERAS'] = '1'
    
    if GPU_MEM_LIMIT == 0:
        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
    
    import tensorflow as tf
    from transformers import __version__ as transformers_version
    try:
        import tf_keras as keras
    except:
        import keras
    
    gpus = tf.config.list_physical_devices('GPU')

    # https://www.tensorflow.org/guide/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)
            tf.config.set_logical_device_configuration(
                gpus[0],
                [tf.config.LogicalDeviceConfiguration(memory_limit=GPU_MEM_LIMIT)]
            )
            logical_gpus = tf.config.list_logical_devices('GPU')
            print(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)

    print('DEVICE:      ', tf.test.gpu_device_name())
    print('TENSORFLOW:  ', tf.__version__)
    print('KERAS:       ', keras.__version__)
    print('TRANSFORMERS:', transformers_version)


def pytorch_setup(GPU_MEM_LIMIT: int, device_id : int = 0) -> str:
    
    if GPU_MEM_LIMIT == 0:
        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
        
    os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
    
    import torch
    from transformers import __version__ as transformers_version
    
    device = ''
    
    if GPU_MEM_LIMIT:
    
        # initialize CUDA context immediately to capture baseline driver overhead
        torch.cuda.init() # type: ignore[no-untyped-call]

        # get absolute physical specs of the card (in bytes)
        _device = torch.device(f'cuda:{device_id}')
        free_bytes, total_bytes = torch.cuda.mem_get_info(_device)
        print(f'{total_bytes / 1024**2:.2f}MB total')
        print(f'{free_bytes  / 1024**2:.2f}MB available')
        target_bytes = GPU_MEM_LIMIT * 1024 * 1024

        if target_bytes > free_bytes:
            raise ValueError(f'{GPU_MEM_LIMIT}MB exceeds available GPU capacity ({free_bytes / 1024**2:.2f}MB)')

        # query exact memory currently held by driver/context (non-tensor overhead)
        # total_allocated tracking covers any early tensor allocations if they exist
        overhead_bytes = torch.cuda.memory_reserved(device_id) 
        if overhead_bytes == 0:
            # Fallback approximation if no context memory is reserved yet
            overhead_bytes = 512 * 1024 * 1024 

        # calculate allowable space remaining for the PyTorch caching allocator
        allowable_tensor_bytes = target_bytes - overhead_bytes

        if allowable_tensor_bytes <= 0:
            raise ValueError(f'{overhead_bytes / 1024**2:.2f}MB CUDA overhead exceeds {GPU_MEM_LIMIT}MB limit')

        # convert to physical fraction of the total GPU
        fraction_total = allowable_tensor_bytes / total_bytes
        fraction_free  = allowable_tensor_bytes / free_bytes
        print(f'fraction to be used: {fraction_total:.4f} total, {fraction_free:.4f} free')

        # enforce limit safely
        torch.cuda.set_per_process_memory_fraction(max(0.01, fraction_total), device=device_id)
        
        device = torch.cuda.get_device_name(device=None)
    
    print('\n\nDEVICE:      ', device)
    print('PYTORCH:     ', torch.__version__)
    print('TRANSFORMERS:', transformers_version)
    
    return device