NVML Injection allows you to mock the return values of NVML calls for testing purposes. There are two ways to provide mocked values:
- YAML Configuration: Loading values from an NVML injection YAML file (e.g., via
run_with_injection_nvml_using_specific_sku). - Manual Injection: Using the
dcgmInjectNvmlDevice API.
Priority Rule: Manual injection via dcgmInjectNvmlDevice has higher priority than values loaded from a YAML file. If both are present, the manually injected value is used.
Key Implementation Rules
- Target Naming: When specifying the injection target, do not include the
Get prefix. For example, to mock nvmlDeviceGetFanSpeed, use the target name FanSpeed. This allows the same injection to affect both getters and setters (e.g., nvmlDeviceSetFanSpeed). - Device Handles: Since the Python injection code cannot directly provide a device handle, pass the
gpuId. The dcgmInjectNvmlDevice function will automatically translate the gpuId into the appropriate device handle. - Overriding: Calling
dcgmInjectNvmlDevice multiple times on the same API will override previous values. To test multiple fields, perform individual injections.
# Example of mocking nvmlDeviceGetNvLinkErrorCounter
def mock_nvlink_error_counter(handle, gpuId, linkId, counterType, nvmlRet, value):
# 1. Define the return value (injectedRet)
injectedRet = nvml_injection.c_injectNvmlRet_t()
injectedRet.nvmlRet = nvmlRet
injectedRet.values[0].type = nvml_injection_structs.c_injectionArgType_t.INJECTION_ULONG_LONG
injectedRet.values[0].value.ULongLong = value
injectedRet.valueCount = 1
# 2. Define extra keys (parameters) for the function
extraKeysType = nvml_injection_structs.c_injectNvmlVal_t * 2
extraKeys = extraKeysType()
extraKeys[0].type = nvml_injection_structs.c_injectionArgType_t.INJECTION_UINT
extraKeys[0].value.UInt = linkId
extraKeys[1].type = nvml_injection_structs.c_injectionArgType_t.INJECTION_NVLINKERRORCOUNTER
extraKeys[1].value.NvLinkErrorCounter = counterType
# 3. Execute injection
ret = dcgm_agent_internal.dcgmInjectNvmlDevice(handle, gpuId, "NvLinkErrorCounter", extraKeys, 2, injectedRet)
assert (ret == dcgm_structs.DCGM_ST_OK)