openharmony 鸿蒙 js-apis-mindSporeLite

2025-06-12 浏览 (1)

@ohos.ai.mindSporeLite (On-device AI Framework)

MindSpore Lite is a lightweight and high-performance on-device AI engine that provides standard model inference and training APIs and built-in universal high-performance operator libraries. It supports Neural Network Runtime Kit for a higher inference efficiency, empowering intelligent applications in all scenarios.

This topic describes the model inference and training capabilities supported by the MindSpore Lite AI engine.

NOTE

  • The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. Unless otherwise stated, the MindSpore model is used in the sample code.

  • The APIs of this module can be used only in the stage model.

Modules to Import

import { mindSporeLite } from '@kit.MindSporeLiteKit';

mindSporeLite.loadModelFromFile

loadModelFromFile(model: string, callback: Callback<Model>): void

Loads the input model from the full path for model inference. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelstringYesComplete path of the input model.
callbackCallback<Model>YesCallback used to return the result, which is a Model object.

Example

let modelFile : string = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(modelFile, (mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

mindSporeLite.loadModelFromFile

loadModelFromFile(model: string, context: Context, callback: Callback<Model>): void

Loads the input model from the full path for model inference. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelstringYesComplete path of the input model.
contextContextYesConfiguration information of the running environment.
callbackCallback<Model>YesCallback used to return the result, which is a Model object.

Example

let context: mindSporeLite.Context = {};
context.target = ['cpu'];
let modelFile : string = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(modelFile, context, (mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

mindSporeLite.loadModelFromFile

loadModelFromFile(model: string, context?: Context): Promise<Model>

Loads the input model from the full path for model inference. This API uses a promise to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelstringYesComplete path of the input model.
contextContextNoConfiguration information of the running environment. By default, CpuDevice is used for initialization.

Return value

TypeDescription
Promise<Model>Promise used to return the result, which is a Model object.

Example

let modelFile = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

mindSporeLite.loadModelFromBuffer

loadModelFromBuffer(model: ArrayBuffer, callback: Callback<Model>): void

Loads the input model from the memory for inference. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelArrayBufferYesMemory that contains the input model.
callbackCallback<Model>YesCallback used to return the result, which is a Model object.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let modelFile = 'xxx.ms';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => {
  let modelBuffer = buffer.buffer;
  mindSporeLite.loadModelFromBuffer(modelBuffer, (mindSporeLiteModel: mindSporeLite.Model) => {
    let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
    console.info('MS_LITE_LOG: ' + modelInputs[0].name);
  })
})

mindSporeLite.loadModelFromBuffer

loadModelFromBuffer(model: ArrayBuffer, context: Context, callback: Callback<Model>): void

Loads the input model from the memory for inference. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelArrayBufferYesMemory that contains the input model.
contextContextYesConfiguration information of the running environment.
callbackCallback<Model>YesCallback used to return the result, which is a Model object.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let modelFile = 'xxx.ms';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => {
  let modelBuffer = buffer.buffer;
  let context: mindSporeLite.Context = {};
  context.target = ['cpu'];
  mindSporeLite.loadModelFromBuffer(modelBuffer, context, (mindSporeLiteModel: mindSporeLite.Model) => {
    let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
    console.info('MS_LITE_LOG: ' + modelInputs[0].name);
  })
})

mindSporeLite.loadModelFromBuffer

loadModelFromBuffer(model: ArrayBuffer, context?: Context): Promise<Model>

Loads the input model from the memory for inference. This API uses a promise to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelArrayBufferYesMemory that contains the input model.
contextContextNoConfiguration information of the running environment. By default, CpuDevice is used for initialization.

Return value

TypeDescription
Promise<Model>Promise used to return the result, which is a Model object.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let modelFile = 'xxx.ms';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => {
  let modelBuffer = buffer.buffer;
  mindSporeLite.loadModelFromBuffer(modelBuffer).then((mindSporeLiteModel: mindSporeLite.Model) => {
    let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
    console.info('MS_LITE_LOG: ' + modelInputs[0].name);
  })
})

mindSporeLite.loadModelFromFd

loadModelFromFd(model: number, callback: Callback<Model>): void

Loads the input model based on the specified file descriptor for inference. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelnumberYesFile descriptor of the input model.
callbackCallback<Model>YesCallback used to return the result, which is a Model object.

Example

import { fileIo } from '@kit.CoreFileKit';
let modelFile = '/path/to/xxx.ms';
let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY);
mindSporeLite.loadModelFromFd(file.fd, (mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

mindSporeLite.loadModelFromFd

loadModelFromFd(model: number, context: Context, callback: Callback<Model>): void

Loads the input model based on the specified file descriptor for inference. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelnumberYesFile descriptor of the input model.
contextContextYesConfiguration information of the running environment.
callbackCallback<Model>YesCallback used to return the result, which is a Model object.

Example

import { fileIo } from '@kit.CoreFileKit';
let modelFile = '/path/to/xxx.ms';
let context : mindSporeLite.Context = {};
context.target = ['cpu'];
let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY);
mindSporeLite.loadModelFromFd(file.fd, context, (mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

mindSporeLite.loadModelFromFd

loadModelFromFd(model: number, context?: Context): Promise<Model>

Loads the input model based on the specified file descriptor for inference. This API uses a promise to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelnumberYesFile descriptor of the input model.
contextContextNoConfiguration information of the running environment. By default, CpuDevice is used for initialization.

Return value

TypeDescription
Promise<Model>Promise used to return the result, which is a Model object.

Example

import { fileIo } from '@kit.CoreFileKit';
let modelFile = '/path/to/xxx.ms';
let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY);
mindSporeLite.loadModelFromFd(file.fd).then((mindSporeLiteModel: mindSporeLite.Model) => {
  let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

mindSporeLite.loadTrainModelFromFile12+

loadTrainModelFromFile(model: string, trainCfg?: TrainCfg, context?: Context): Promise<Model>

Loads the training model file based on the specified path. This API uses a promise to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelstringYesComplete path of the input model.
trainCfgTrainCfgNoModel training configuration. The default value is an array of the default values of attributes in TrainCfg.
contextContextNoConfiguration information of the running environment. By default, CpuDevice is used for initialization.

Return value

TypeDescription
Promise<Model>Promise used to return the result, which is a Model object.

Example

let modelFile = '/path/to/xxx.ms';
mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

mindSporeLite.loadTrainModelFromBuffer12+

loadTrainModelFromBuffer(model: ArrayBuffer, trainCfg?: TrainCfg, context?: Context): Promise<Model>

Loads a training model from the memory buffer. This API uses a promise to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelArrayBufferYesMemory accommodating the training model.
trainCfgTrainCfgNoModel training configuration. The default value is an array of the default values of attributes in TrainCfg.
contextContextNoConfiguration information of the running environment. By default, CpuDevice is used for initialization.

Return value

TypeDescription
Promise<Model>Promise used to return the result, which is a Model object.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let modelFile = 'xxx.ms';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => {
  let modelBuffer = buffer.buffer;
  mindSporeLite.loadTrainModelFromBuffer(modelBuffer).then((mindSporeLiteModel: mindSporeLite.Model) => {
    console.info("MSLITE trainMode: ", mindSporeLiteModel.trainMode);
  })
})

mindSporeLite.loadTrainModelFromFd12+

loadTrainModelFromFd(model: number, trainCfg?: TrainCfg, context?: Context): Promise<Model>

Loads the training model file from the file descriptor. This API uses a promise to return the result.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelnumberYesFile descriptor of the training model.
trainCfgTrainCfgNoModel training configuration. The default value is an array of the default values of attributes in TrainCfg.
contextContextNoConfiguration information of the running environment. By default, CpuDevice is used for initialization.

Return value

TypeDescription
Promise<Model>Promise used to return the result, which is a Model object.

Example

import { fileIo } from '@kit.CoreFileKit';
let modelFile = '/path/to/xxx.ms';
let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY);
mindSporeLite.loadTrainModelFromFd(file.fd).then((mindSporeLiteModel: mindSporeLite.Model) => {
  console.info("MSLITE trainMode: ", mindSporeLiteModel.trainMode);
});

mindSporeLite.getAllNNRTDeviceDescriptions12+

getAllNNRTDeviceDescriptions() : NNRTDeviceDescription[]

Obtains all device descriptions in NNRt.

System capability: SystemCapability.AI.MindSporeLite

Return value

TypeDescription
NNRTDeviceDescription[]NNRt device description array.

Example

let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions();
if (allDevices == null) {
  console.error('MS_LITE_LOG: getAllNNRTDeviceDescriptions is NULL.');
}

Context

Defines the configuration information of the running environment.

Attributes

System capability: SystemCapability.AI.MindSporeLite

NameTypeRead OnlyOptionalDescription
targetstring[]NoYesTarget backend. The value can be cpu or nnrt. The default value is cpu.
cpuCpuDeviceNoYesCPU backend device option. Set this parameter set only when target is set to cpu. The default value is an array of the default values of attributes in CpuDevice.
nnrtNNRTDeviceNoYesNNRt backend device option. Set this parameter set only when target is set to nnrt. The default value is an array of the default values of attributes in NNRTDevice.

Example

let context: mindSporeLite.Context = {};
context.target = ['cpu','nnrt'];

CpuDevice

Defines the CPU backend device option.

Attributes

System capability: SystemCapability.AI.MindSporeLite

NameTypeRead OnlyOptionalDescription
threadNumnumberNoYesNumber of runtime threads. The default value is 2.
threadAffinityModeThreadAffinityModeNoYesAffinity mode for binding runtime threads to CPU cores. The default value is mindSporeLite.ThreadAffinityMode.NO_AFFINITIES.
threadAffinityCoreListnumber[]NoYesList of CPU cores bound to runtime threads. Set this parameter only when threadAffinityMode is set. If threadAffinityMode is set to mindSporeLite.ThreadAffinityMode.NO_AFFINITIES, this parameter is empty. The number in the list indicates the SN of the CPU core. The default value is [].
precisionModestringNoYesWhether to enable the Float16 inference mode. The value preferred_fp16 means to enable half-precision inference and the default value enforce_fp32 means to disable half-precision inference. Other settings are not supported.

Float16 inference mode: a mode that uses half-precision inference. Float16 uses 16 bits to represent a number and therefore it is also called half-precision.

Example

let context: mindSporeLite.Context = {};
context.cpu = {};
context.target = ['cpu'];
context.cpu.threadNum = 2;
context.cpu.threadAffinityMode = 0;
context.cpu.precisionMode = 'preferred_fp16';
context.cpu.threadAffinityCoreList = [0, 1, 2];

ThreadAffinityMode

Specifies the affinity mode for binding runtime threads to CPU cores.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
NO_AFFINITIES0No affinities.
BIG_CORES_FIRST1Big cores first.
LITTLE_CORES_FIRST2Medium cores first.

NNRTDevice

Represents an NNRt device. Neural Network Runtime (NNRt) is a bridge that connects the upper-layer AI inference framework to the bottom-layer acceleration chip to implement cross-chip inference and computing of AI models. An NNRt backend can be configured for MindSpore Lite.

Attributes

System capability: SystemCapability.AI.MindSporeLite

NameTypeRead OnlyOptionalDescription
deviceID12+bigintNoYesNNRt device ID. The default value is 0.
performanceMode12+PerformanceModeNoYesNNRt device performance mode. The default value is PERFORMANCE_NONE.
priority12+PriorityNoYesNNRt inference task priority. The default value is PRIORITY_MEDIUM.
extensions12+Extension[]NoYesExtended NNRt device configuration. This parameter is left empty by default.

PerformanceMode12+

Enumerates NNRt device performance modes.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
PERFORMANCE_NONE0No special settings.
PERFORMANCE_LOW1Low power consumption.
PERFORMANCE_MEDIUM2Power consumption and performance balancing.
PERFORMANCE_HIGH3High performance.
PERFORMANCE_EXTREME4Ultimate performance.

Priority12+

Enumerates NNRt inference task priorities.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
PRIORITY_NONE0No priority preference.
PRIORITY_LOW1Low priority.
PRIORITY_MEDIUM2Medium priority.
PRIORITY_HIGH3High priority.

Extension12+

Defines the extended NNRt device configuration.

Attributes

System capability: SystemCapability.AI.MindSporeLite

NameTypeRead OnlyOptionalDescription
name12+stringNoNoConfiguration name.
value12+ArrayBufferNoNoMemory accommodating the extended configuration.

NNRTDeviceDescription12+

Defines NNRt device information, including the device ID and device name.

System capability: SystemCapability.AI.MindSporeLite

deviceID

deviceID() : bigint

Obtains the NNRt device ID.

System capability: SystemCapability.AI.MindSporeLite

Return value

TypeDescription
bigintNNRt device ID.

Example

let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions();
if (allDevices == null) {
  console.error('getAllNNRTDeviceDescriptions is NULL.');
}
let context: mindSporeLite.Context = {};
context.target = ["nnrt"];
context.nnrt = {};
for (let i: number = 0; i < allDevices.length; i++) {
  console.info(allDevices[i].deviceID().toString());
}

deviceType

deviceType() : NNRTDeviceType

Obtains the device model.

System capability: SystemCapability.AI.MindSporeLite

Return value

TypeDescription
NNRTDeviceTypeNNRt device type.

Example

let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions();
if (allDevices == null) {
  console.error('getAllNNRTDeviceDescriptions is NULL.');
}
let context: mindSporeLite.Context = {};
context.target = ["nnrt"];
context.nnrt = {};
for (let i: number = 0; i < allDevices.length; i++) {
  console.info(allDevices[i].deviceType().toString());
}

deviceName

deviceName() : string

Obtains the NNRt device name.

System capability: SystemCapability.AI.MindSporeLite

Return value

TypeDescription
stringNNRt device name.

Example

let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions();
if (allDevices == null) {
  console.error('getAllNNRTDeviceDescriptions is NULL.');
}
let context: mindSporeLite.Context = {};
context.target = ["nnrt"];
context.nnrt = {};
for (let i: number = 0; i < allDevices.length; i++) {
  console.info(allDevices[i].deviceName().toString());
}

NNRTDeviceType12+

Enumerates NNRt device types.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
NNRTDEVICE_OTHERS0Others (any device type except the following three types).
NNRTDEVICE_CPU1CPU.
NNRTDEVICE_GPU2GPU.
NNRTDEVICE_ACCELERATOR3Specific acceleration device.

TrainCfg12+

Defines the configuration for on-device training.

Attributes

System capability: SystemCapability.AI.MindSporeLite

NameTypeRead OnlyOptionalDescription
lossName12+string[]NoYesList of loss functions. The default value is ["loss_fct", "_loss_fn", "SigmoidCrossEntropy"].
optimizationLevel12+OptimizationLevelNoYesNetwork optimization level for on-device training. The default value is O0.

Example

let cfg: mindSporeLite.TrainCfg = {};
cfg.lossName = ["loss_fct", "_loss_fn", "SigmoidCrossEntropy"];
cfg.optimizationLevel = mindSporeLite.OptimizationLevel.O0;

OptimizationLevel12+

Enumerates network optimization levels for on-device training.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
O00No optimization level.
O22Converts the precision type of the network to float16 and keeps the precision type of the batch normalization layer and loss function as float32.
O33Converts the precision type of the network (including the batch normalization layer) to float16.
AUTO4Selects an optimization level based on the device.

QuantizationType12+

Enumerates quantization types.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
NO_QUANT0No quantification.
WEIGHT_QUANT1Weight quantization.
FULL_QUANT2Full quantization.

Model

Represents a Model instance, with properties and APIs defined.

In the following sample code, you first need to use loadModelFromFile(), loadModelFromBuffer(), or loadModelFromFd() to obtain a Model instance before calling related APIs.

Attributes

System capability: SystemCapability.AI.MindSporeLite

NameTypeRead OnlyOptionalDescription
learningRate12+numberNoYesLearning rate of a training model. The default value is read from the loaded model.
trainMode12+booleanNoYesTraining mode. The value true indicates the training mode, and the value false indicates the non-training mode. The default value is true for a training model and false for an inference model.

getInputs

getInputs(): MSTensor[]

Obtains the model input for inference.

System capability: SystemCapability.AI.MindSporeLite

Return value

TypeDescription
MSTensor[]MSTensor object.

Example

let modelFile = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
})

predict

predict(inputs: MSTensor[], callback: Callback<MSTensor[]>): void

Executes the inference model. This API uses an asynchronous callback to return the result. Ensure that the model object is not reclaimed when being invoked.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
inputsMSTensor[]YesList of input models.
callbackCallback<MSTensor[]>YesCallback used to return the result, which is a list of MSTensor objects.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let inputName = 'input_data.bin';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => {
  let inputBuffer = buffer.buffer;
  let modelFile : string = '/path/to/xxx.ms';
  let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile);
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();

  modelInputs[0].setData(inputBuffer);
  mindSporeLiteModel.predict(modelInputs, (mindSporeLiteTensor : mindSporeLite.MSTensor[]) => {
    let output = new Float32Array(mindSporeLiteTensor[0].getData());
    for (let i = 0; i < output.length; i++) {
      console.info('MS_LITE_LOG: ' + output[i].toString());
    }
  })
})

predict

predict(inputs: MSTensor[]): Promise<MSTensor[]>

Executes model inference. This API uses a promise to return the result. Ensure that the model object is not reclaimed when being invoked.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
inputsMSTensor[]YesList of input models.

Return value

TypeDescription
Promise<MSTensor[]>Promise used to return the result, List of MSTensor objects.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let inputName = 'input_data.bin';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => {
  let inputBuffer = buffer.buffer;
  let modelFile = '/path/to/xxx.ms';
  let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile);
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  modelInputs[0].setData(inputBuffer);
  mindSporeLiteModel.predict(modelInputs).then((mindSporeLiteTensor : mindSporeLite.MSTensor[]) => {
    let output = new Float32Array(mindSporeLiteTensor[0].getData());
    for (let i = 0; i < output.length; i++) {
      console.info(output[i].toString());
    }
  })
})

resize

resize(inputs: MSTensor[], dims: Array<Array<number>>): boolean

Resets the tensor size.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
inputsMSTensor[]YesList of input models.
dimsArray<Array<number>>YesTarget tensor size.

Return value

TypeDescription
booleanResult indicating whether the setting is successful. The value true indicates that the tensor size is successfully reset, and the value false indicates the opposite.

Example

let modelFile = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  let new_dim = new Array([1,32,32,1]);
  mindSporeLiteModel.resize(modelInputs, new_dim);
})

runStep12+

runStep(inputs: MSTensor[]): boolean

Defines a single-step training model. This API is used only for on-device training.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
inputsMSTensor[]YesList of input models.

Return value

TypeDescription
booleanResult indicating whether the operation is successful. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

let modelFile = '/path/to/xxx.ms';
mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel: mindSporeLite.Model) => {
  mindSporeLiteModel.trainMode = true;
  const modelInputs = mindSporeLiteModel.getInputs();
  let ret = mindSporeLiteModel.runStep(modelInputs);
  if (ret == false) {
    console.error('MS_LITE_LOG: runStep failed.')
  }
})

getWeights12+

getWeights(): MSTensor[]

Obtains all weight tensors of a model. This API is used only for on-device training.

System capability: SystemCapability.AI.MindSporeLite

Return value

TypeDescription
MSTensor[]Weight tensor of the training model.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let modelFile = 'xxx.ms';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((modelBuffer : Uint8Array) => {
  mindSporeLite.loadTrainModelFromBuffer(modelBuffer.buffer.slice(0)).then((mindSporeLiteModel: mindSporeLite.Model) => {
    mindSporeLiteModel.trainMode = true;
    const weights = mindSporeLiteModel.getWeights();
    for (let i = 0; i < weights.length; i++) {
      let printStr = weights[i].name + ", ";
      printStr += weights[i].shape + ", ";
      printStr += weights[i].dtype + ", ";
      printStr += weights[i].dataSize + ", ";
      printStr += weights[i].getData();
      console.info("MS_LITE weights: ", printStr);
    }
  })
})

updateWeights12+

updateWeights(weights: MSTensor[]): boolean

Weight of the updated model, which is used only for on-device training.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
weightsMSTensor[]YesList of weight tensors.

Return value

TypeDescription
booleanResult indicating whether the operation is successful. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let modelFile = 'xxx.ms';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((modelBuffer : Uint8Array) => {
  mindSporeLite.loadTrainModelFromBuffer(modelBuffer.buffer.slice(0)).then((mindSporeLiteModel: mindSporeLite.Model) => {
    mindSporeLiteModel.trainMode = true;
    const weights = mindSporeLiteModel.getWeights();
    let ret = mindSporeLiteModel.updateWeights(weights);
    if (ret == false) {
      console.error('MS_LITE_LOG: updateWeights failed.')
    }
  })
})

setupVirtualBatch12+

setupVirtualBatch(virtualBatchMultiplier: number, lr: number, momentum: number): boolean

Sets the virtual batch for training. This API is used only for on-device training.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
virtualBatchMultipliernumberYesVirtual batch multiplier. If the value is less than 1, the virtual batch is disabled.
lrnumberYesLearning rate.
momentumnumberYesMomentum.

Return value

TypeDescription
booleanResult indicating whether the operation is successful. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let modelFile = 'xxx.ms';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((modelBuffer : Uint8Array) => {
  mindSporeLite.loadTrainModelFromBuffer(modelBuffer.buffer.slice(0)).then((mindSporeLiteModel: mindSporeLite.Model) => {
    mindSporeLiteModel.trainMode = true;
    let ret = mindSporeLiteModel.setupVirtualBatch(2,-1,-1);
    if (ret == false) {
      console.error('MS_LITE setupVirtualBatch failed.')
    }
  })
})

exportModel12+

exportModel(modelFile: string, quantizationType?: QuantizationType, exportInferenceOnly?: boolean, outputTensorName?: string[]): boolean

Exports a training model. This API is used only for on-device training.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
modelFilestringYesFile path of the training models.
quantizationTypeQuantizationTypeNoQuantization type. The default value is NO_QUANT.
exportInferenceOnlybooleanNoWhether to export inference models only. The value true means to export only inference models, and the value false means to export both training and inference models. The default value is true.
outputTensorNamestring[]NoName of the output tensor of the exported training model. The default value is an empty string array, which indicates full export.

Return value

TypeDescription
booleanResult indicating whether the operation is successful. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

let modelFile = '/path/to/xxx.ms';
let newPath = '/newpath/to';
mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel: mindSporeLite.Model) => {
  mindSporeLiteModel.trainMode = true;
  let ret = mindSporeLiteModel.exportModel(newPath + "/new_model.ms", mindSporeLite.QuantizationType.NO_QUANT, true);
  if (ret == false) {
    console.error('MS_LITE exportModel failed.')
  }
})

exportWeightsCollaborateWithMicro12+

exportWeightsCollaborateWithMicro(weightFile: string, isInference?: boolean, enableFp16?: boolean, changeableWeightsName?: string[]): boolean

Exports model weights for micro inference. This API is available only for on-device training.

Micro inference is a ultra-lightweight micro AI deployment solution provided by MindSpore Lite to deploy hardware backends for Micro Controller Units (MCUs). This solution directly converts models into lightweight code in offline mode, eliminating the need for online model parsing and graph compilation.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
weightFilestringYesPath of the weight file.
isInferencebooleanNoWhether to export weights from the inference model. The value true means to export weights from the inference model. The default value is true. Currently, only true is supported.
enableFp16booleanNoWhether to store floating-point weights in float16 format. The value true means to store floating-point weights in float16 format, and the value false means the opposite. The default value is false.
changeableWeightsNamestring[]NoName of the variable weight. The default value is an empty string array.

Return value

TypeDescription
booleanResult indicating whether the operation is successful. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

let modelFile = '/path/to/xxx.ms';
let microWeight = '/path/to/xxx.bin';
mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel: mindSporeLite.Model) => {
  let ret = mindSporeLiteModel.exportWeightsCollaborateWithMicro(microWeight);
  if (ret == false) {
    console.error('MSLITE exportWeightsCollaborateWithMicro failed.')
  }
})

MSTensor

Represents an MSTensor instance, with properties and APIs defined. It is a special data structure similar to arrays and matrices. It is the basic data structure used in MindSpore Lite network operations.

In the following sample code, you first need to use getInputs() to obtain an MSTensor instance before calling related APIs.

Attributes

System capability: SystemCapability.AI.MindSporeLite

NameTypeRead OnlyOptionalDescription
namestringNoNoTensor name.
shapenumber[]NoNoTensor dimension array.
elementNumnumberNoNoLength of the tensor dimension array.
dataSizenumberNoNoLength of tensor data.
dtypeDataTypeNoNoTensor data type.
formatFormatNoNoTensor data format.

Example

let modelFile = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => {
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  console.info(modelInputs[0].name);
  console.info(modelInputs[0].shape.toString());
  console.info(modelInputs[0].elementNum.toString());
  console.info(modelInputs[0].dtype.toString());
  console.info(modelInputs[0].format.toString());
  console.info(modelInputs[0].dataSize.toString());
})

getData

getData(): ArrayBuffer

Obtains tensor data.

System capability: SystemCapability.AI.MindSporeLite

Return value

TypeDescription
ArrayBufferPointer to the tensor data.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let inputName = 'input_data.bin';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => {
  let inputBuffer = buffer.buffer;
  let modelFile = '/path/to/xxx.ms';
  let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile);
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  modelInputs[0].setData(inputBuffer);
  mindSporeLiteModel.predict(modelInputs).then((mindSporeLiteTensor : mindSporeLite.MSTensor[]) => {
    let output = new Float32Array(mindSporeLiteTensor[0].getData());
    for (let i = 0; i < output.length; i++) {
      console.info(output[i].toString());
    }
  })
})

setData

setData(inputArray: ArrayBuffer): void

Sets the tensor data.

System capability: SystemCapability.AI.MindSporeLite

Parameters

NameTypeMandatoryDescription
inputArrayArrayBufferYesInput data buffer of the tensor.

Example

import { mindSporeLite } from '@kit.MindSporeLiteKit';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

let inputName = 'input_data.bin';
let globalContext = new UIContext().getHostContext() as common.UIAbilityContext;
globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => {
  let inputBuffer = buffer.buffer;
  let modelFile = '/path/to/xxx.ms';
  let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile);
  let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs();
  modelInputs[0].setData(inputBuffer);
})

DataType

Tensor data type.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
TYPE_UNKNOWN0Unknown type.
NUMBER_TYPE_INT832Int8 type.
NUMBER_TYPE_INT1633Int16 type.
NUMBER_TYPE_INT3234Int32 type.
NUMBER_TYPE_INT6435Int64 type.
NUMBER_TYPE_UINT837UInt8 type.
NUMBER_TYPE_UINT1638UInt16 type.
NUMBER_TYPE_UINT3239UInt32 type.
NUMBER_TYPE_UINT6440UInt64 type.
NUMBER_TYPE_FLOAT1642Float16 type.
NUMBER_TYPE_FLOAT3243Float32 type.
NUMBER_TYPE_FLOAT6444Float64 type.

Format

Enumerates tensor data formats.

System capability: SystemCapability.AI.MindSporeLite

NameValueDescription
DEFAULT_FORMAT-1Unknown data format.
NCHW0NCHW format.
NHWC1NHWC format.
NHWC42NHWC4 format.
HWKC3HWKC format.
HWCK4HWCK format.
KCHW5KCHW format.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙MindSpore Lite Kit

harmony 鸿蒙MindSpore

harmony 鸿蒙OH_AI_CallBackParam

harmony 鸿蒙OH_AI_ShapeInfo

harmony 鸿蒙OH_AI_TensorHandleArray

harmony 鸿蒙context.h

harmony 鸿蒙data_type.h

harmony 鸿蒙format.h

harmony 鸿蒙model.h

harmony 鸿蒙status.h

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/kFZ03u