File size: 3,385 Bytes
674c639
cc044ba
 
 
674c639
 
 
 
 
 
 
 
 
 
 
 
 
cc044ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
674c639
 
 
 
 
cc044ba
 
674c639
 
cc044ba
674c639
 
cc044ba
674c639
 
 
 
 
 
 
 
 
 
 
cc044ba
 
 
 
674c639
 
cc044ba
674c639
 
 
 
 
 
 
cc044ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import os
import shutil
import subprocess
import numpy

stderrFileDescriptor = os.dup(2)
nullFileDescriptor = os.open(os.devnull, os.O_WRONLY)

os.dup2(nullFileDescriptor, 2)

import onnxruntime

os.dup2(stderrFileDescriptor, 2)

os.close(nullFileDescriptor)
os.close(stderrFileDescriptor)

onnxruntime.set_default_logger_severity(3)

def memoryFree(isGpu):
    if isGpu:
        return int(subprocess.run(["nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits"], capture_output=True).stdout.decode().split("\n")[0]) * 1024 * 1024

    with open("/proc/meminfo", encoding="utf-8") as file:
        return int([line for line in file if line.startswith("MemAvailable")][0].split()[1]) * 1024

def memoryLimitBuild():
    resultObject = {"gpu": 0, "cpu": int(memoryFree(False) * levelMemory)}

    onnxruntime.create_and_register_allocator(onnxruntime.OrtMemoryInfo("Cpu", onnxruntime.OrtAllocatorType.ORT_ARENA_ALLOCATOR, 0, onnxruntime.OrtMemType.DEFAULT), onnxruntime.OrtArenaCfg({"max_mem": resultObject["cpu"], "arena_extend_strategy": 1}))

    if "CUDAExecutionProvider" in onnxruntime.get_available_providers() and shutil.which("nvidia-smi") != None:
        resultObject["gpu"] = int(memoryFree(True) * levelMemory)

        onnxruntime.create_and_register_allocator_v2("CUDAExecutionProvider", onnxruntime.OrtMemoryInfo("Cuda", onnxruntime.OrtAllocatorType.ORT_ARENA_ALLOCATOR, 0, onnxruntime.OrtMemType.DEFAULT), {}, onnxruntime.OrtArenaCfg({"max_mem": resultObject["gpu"], "arena_extend_strategy": 1}))

    return resultObject

def onnxSessionBuild(pathModel):
    option = onnxruntime.SessionOptions()

    option.log_severity_level = 3

    option.add_session_config_entry("session.use_env_allocators", "1")

    option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL

    option.intra_op_num_threads = len(os.sched_getaffinity(0))
    option.inter_op_num_threads = 1

    option.enable_cpu_mem_arena = False
    option.enable_mem_pattern = True
    option.enable_mem_reuse = True

    option.execution_mode = onnxruntime.ExecutionMode.ORT_SEQUENTIAL

    providerPreferredList = [
        "CUDAExecutionProvider",
        "OpenVINOExecutionProvider",
        "CPUExecutionProvider"
    ]

    providerOptionObject = {
        "CUDAExecutionProvider": {"arena_extend_strategy": "kSameAsRequested", "cudnn_conv_algo_search": "HEURISTIC"}
    }

    providerAvailableList = onnxruntime.get_available_providers()

    providerList = [(provider, providerOptionObject[provider] if provider in providerOptionObject else {}) for provider in providerPreferredList if provider in providerAvailableList]

    inference = onnxruntime.InferenceSession(pathModel, sess_options=option, providers=providerList)

    print(f"Provider available: {providerAvailableList}")
    print(f"Provider active: {inference.get_providers()}\n")

    return inference

def onnxMemoryRelease(onnxSession):
    if memoryLimitObject["gpu"] == 0:
        return

    runOption = onnxruntime.RunOptions()

    runOption.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0")

    inputNode = onnxSession.get_inputs()[0]

    onnxSession.run(None, {inputNode.name: numpy.zeros([size if isinstance(size, int) else 1 for size in inputNode.shape], dtype=numpy.float32)}, runOption)

# Custom
levelMemory = 0.8

memoryLimitObject = memoryLimitBuild()