Sample Code

Principles

Load the model generated according to Building a Model and prepare for model execution.

If the shape of the input data is uncertain, you cannot call aclmdlQuerySize to query the memory size. As a result, you cannot manage the memory during model loading. Therefore, you need to call aclmdlLoadFromFile or aclmdlLoadFromMem to allow the system to manage the memory.

After the model is loaded successfully, the ID of the model is returned, which will be used in Running a Model.

Sample Code

You can view the complete code in Sample Overview.

Following the API calls, add exception handling branches and specify log printing of error and information levels. The following is a code snippet of key steps only, which is not ready to be built or run.

//1. Initialize variables.
//The two dots (..) indicate a path relative to the directory of the executable file.
//For example, if the executable file is stored in the out directory, the two dots (..) point to the parent directory of the out directory.
const char* omModelPath = "../model/resnet50.om"
// ......

//2. Obtain the weight memory size and workspace size required for model execution.
aclError ret = aclmdlQuerySize(omModelPath, &modelMemSize_, &modelWeightSize_);

//3. Allocate workspace on the device for model execution.
ret = aclrtMalloc(&modelMemPtr_, modelMemSize_, ACL_MEM_MALLOC_HUGE_FIRST);

//4. Allocate weight memory on the device for model execution.
ret = aclrtMalloc(&modelWeightPtr_, modelWeightSize_, ACL_MEM_MALLOC_HUGE_FIRST);

//5. Load your offline model adapted to the Ascend AI Processor. The memory (including the weight memory and workspace) is managed by the user.
//The model is successfully loaded, and the model ID is returned.
ret = aclmdlLoadFromFileWithMem(modelPath, &modelId_, modelMemPtr_, modelMemSize_, modelWeightPtr_, modelWeightSize_);

// ......