1# @ohos.ai.mindSporeLite (端侧AI框架) 2 3<!--Kit: MindSpore Lite Kit--> 4<!--Subsystem: AI--> 5<!--Owner: @zhuguodong8--> 6<!--Designer: @zhuguodong8; @jjfeing--> 7<!--Tester: @principal87--> 8<!--Adviser: @ge-yafang--> 9 10MindSpore Lite是一个轻量化、高性能的端侧AI引擎,提供了标准的模型推理和训练接口,内置通用硬件高性能算子库,支持Neural Network Runtime Kit使能AI专用芯片加速推理,助力打造全场景智能应用。 11 12本模块主要介绍MindSpore Lite AI引擎支持模型端侧推理/训练的相关能力。 13 14> **说明:** 15> 16> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。示例代码使用模型均为MindSpore端侧模型。 17> 18> - 本模块接口仅可在Stage模型下使用。 19 20## 导入模块 21 22```ts 23import { mindSporeLite } from '@kit.MindSporeLiteKit'; 24``` 25 26## mindSporeLite.loadModelFromFile 27 28loadModelFromFile(model: string, callback: Callback<Model>): void 29 30从完整路径加载输入模型用于推理。使用callback异步回调。 31 32**系统能力:** SystemCapability.AI.MindSporeLite 33 34**参数:** 35 36| 参数名 | 类型 | 必填 | 说明 | 37| -------- | ------------------------- | ---- | ------------------------------------------------ | 38| model | string | 是 | 模型的完整输入路径。字符串长度限制跟随文件系统。 | 39| callback | Callback<[Model](#model)> | 是 | 回调函数。返回模型对象。 | 40 41**示例:** 42 43```ts 44let modelFile : string = '/path/to/xxx.ms'; 45mindSporeLite.loadModelFromFile(modelFile, (mindSporeLiteModel : mindSporeLite.Model) => { 46 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 47 if (modelInputs == null) { 48 console.error('MS_LITE_ERR: getInputs failed.') 49 } else { 50 console.info(modelInputs[0].name); 51 } 52}) 53``` 54## mindSporeLite.loadModelFromFile 55 56loadModelFromFile(model: string, context: Context, callback: Callback<Model>): void 57 58从完整路径加载输入模型用于推理。使用callback异步回调。 59 60**系统能力:** SystemCapability.AI.MindSporeLite 61 62**参数:** 63 64| 参数名 | 类型 | 必填 | 说明 | 65| -------- | ----------------------------------- | ---- | ---------------------- | 66| model | string | 是 | 模型的完整输入路径。字符串长度限制跟随文件系统。 | 67| context | [Context](#context) | 是 | 运行环境的配置信息。 | 68| callback | Callback<[Model](#model)> | 是 | 回调函数。返回模型对象。 | 69 70**示例:** 71 72```ts 73let context: mindSporeLite.Context = {}; 74context.target = ['cpu']; 75let modelFile : string = '/path/to/xxx.ms'; 76mindSporeLite.loadModelFromFile(modelFile, context, (mindSporeLiteModel : mindSporeLite.Model) => { 77 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 78 if (modelInputs == null) { 79 console.error('MS_LITE_ERR: getInputs failed.') 80 } else { 81 console.info(modelInputs[0].name); 82 } 83}) 84``` 85## mindSporeLite.loadModelFromFile 86 87loadModelFromFile(model: string, context?: Context): Promise<Model> 88 89从完整路径加载输入模型用于推理。使用Promise异步函数。 90 91**系统能力:** SystemCapability.AI.MindSporeLite 92 93**参数:** 94 95| 参数名 | 类型 | 必填 | 说明 | 96| ------- | ------------------- | ---- | ------------------------------------------------ | 97| model | string | 是 | 模型的完整输入路径。字符串长度限制跟随文件系统。 | 98| context | [Context](#context) | 否 | 运行环境的配置信息。默认使用CpuDevice初始化。 | 99 100**返回值:** 101 102| 类型 | 说明 | 103| ------------------------- | ---------------------------- | 104| Promise<[Model](#model)> | Promise对象。返回Model对象。 | 105 106**示例:** 107 108```ts 109let modelFile = '/path/to/xxx.ms'; 110mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => { 111 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 112 if (modelInputs == null) { 113 console.error('MS_LITE_ERR: getInputs failed.') 114 } else { 115 console.info(modelInputs[0].name); 116 } 117}) 118``` 119## mindSporeLite.loadModelFromBuffer 120 121loadModelFromBuffer(model: ArrayBuffer, callback: Callback<Model>): void 122 123从内存加载输入模型用于推理。使用callback异步回调。 124 125**系统能力:** SystemCapability.AI.MindSporeLite 126 127**参数:** 128 129| 参数名 | 类型 | 必填 | 说明 | 130| -------- | ------------------------- | ---- | ------------------------ | 131| model | ArrayBuffer | 是 | 包含模型的内存。 | 132| callback | Callback<[Model](#model)> | 是 | 回调函数。返回模型对象。 | 133 134**示例:** 135 136```ts 137import { common } from '@kit.AbilityKit'; 138import { UIContext } from '@kit.ArkUI'; 139import { BusinessError } from '@kit.BasicServicesKit'; 140 141let modelFile = 'xxx.ms'; 142let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 143globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => { 144 let modelBuffer = buffer.buffer; 145 mindSporeLite.loadModelFromBuffer(modelBuffer, (mindSporeLiteModel: mindSporeLite.Model) => { 146 let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 147 console.info('MS_LITE_LOG: ' + modelInputs[0].name); 148 }) 149}).catch((error: BusinessError) => { 150 console.error("getRawFileContent promise error is " + error); 151}); 152``` 153## mindSporeLite.loadModelFromBuffer 154 155loadModelFromBuffer(model: ArrayBuffer, context: Context, callback: Callback<Model>): void 156 157从内存加载输入模型用于推理。使用callback异步回调。 158 159**系统能力:** SystemCapability.AI.MindSporeLite 160 161**参数:** 162 163| 参数名 | 类型 | 必填 | 说明 | 164| -------- | ----------------------------------- | ---- | ---------------------- | 165| model | ArrayBuffer | 是 | 包含模型的内存。 | 166| context | [Context](#context) | 是 | 运行环境的配置信息。 | 167| callback | Callback<[Model](#model)> | 是 | 回调函数。返回模型对象。 | 168 169**示例:** 170 171```ts 172import { common } from '@kit.AbilityKit'; 173import { UIContext } from '@kit.ArkUI'; 174import { BusinessError } from '@kit.BasicServicesKit'; 175 176let modelFile = 'xxx.ms'; 177let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 178globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => { 179 let modelBuffer = buffer.buffer; 180 let context: mindSporeLite.Context = {}; 181 context.target = ['cpu']; 182 mindSporeLite.loadModelFromBuffer(modelBuffer, context, (mindSporeLiteModel: mindSporeLite.Model) => { 183 let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 184 console.info('MS_LITE_LOG: ' + modelInputs[0].name); 185 }) 186}).catch((error: BusinessError) => { 187 console.error("getRawFileContent promise error is " + error); 188}); 189``` 190## mindSporeLite.loadModelFromBuffer 191 192loadModelFromBuffer(model: ArrayBuffer, context?: Context): Promise<Model> 193 194从内存加载输入模型用于推理。使用Promise异步函数。 195 196**系统能力:** SystemCapability.AI.MindSporeLite 197 198**参数:** 199 200| 参数名 | 类型 | 必填 | 说明 | 201| ------- | ------------------- | ---- | --------------------------------------------- | 202| model | ArrayBuffer | 是 | 包含模型的内存。 | 203| context | [Context](#context) | 否 | 运行环境的配置信息。默认使用CpuDevice初始化。 | 204 205**返回值:** 206 207| 类型 | 说明 | 208| ------------------------------- | ---------------------------- | 209| Promise<[Model](#model)> | Promise对象。返回Model对象。 | 210 211**示例:** 212 213```ts 214import { common } from '@kit.AbilityKit'; 215import { UIContext } from '@kit.ArkUI'; 216import { BusinessError } from '@kit.BasicServicesKit'; 217 218let modelFile = 'xxx.ms'; 219let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 220globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => { 221 let modelBuffer = buffer.buffer; 222 mindSporeLite.loadModelFromBuffer(modelBuffer).then((mindSporeLiteModel: mindSporeLite.Model) => { 223 let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 224 console.info('MS_LITE_LOG: ' + modelInputs[0].name); 225 }) 226}).catch((error: BusinessError) => { 227 console.error("getRawFileContent promise error is " + error); 228}); 229``` 230## mindSporeLite.loadModelFromFd 231 232loadModelFromFd(model: number, callback: Callback<Model>): void 233 234从文件描述符加载输入模型用于推理。使用callback异步回调。 235 236**系统能力:** SystemCapability.AI.MindSporeLite 237 238**参数:** 239 240| 参数名 | 类型 | 必填 | 说明 | 241| -------- | ----------------------------------- | ---- | ---------------------- | 242| model | number | 是 | 模型的文件描述符。跟随文件系统返回fd值传入。 | 243| callback | Callback<[Model](#model)> | 是 | 回调函数。返回模型对象。 | 244 245**示例:** 246 247```ts 248import { fileIo } from '@kit.CoreFileKit'; 249let modelFile = '/path/to/xxx.ms'; 250let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY); 251mindSporeLite.loadModelFromFd(file.fd, (mindSporeLiteModel : mindSporeLite.Model) => { 252 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 253 if (modelInputs == null) { 254 console.error('MS_LITE_ERR: getInputs failed.') 255 } else { 256 console.info(modelInputs[0].name); 257 } 258}) 259``` 260## mindSporeLite.loadModelFromFd 261 262loadModelFromFd(model: number, context: Context, callback: Callback<Model>): void 263 264从文件描述符加载输入模型用于推理。使用callback异步回调。 265 266**系统能力:** SystemCapability.AI.MindSporeLite 267 268**参数:** 269 270| 参数名 | 类型 | 必填 | 说明 | 271| -------- | ----------------------------------- | ---- | ---------------------- | 272| model | number | 是 | 模型的文件描述符。跟随文件系统返回fd值传入。 | 273| context | [Context](#context) | 是 | 运行环境的配置信息。 | 274| callback | Callback<[Model](#model)> | 是 | 回调函数。返回模型对象。 | 275 276**示例:** 277 278```ts 279import { fileIo } from '@kit.CoreFileKit'; 280let modelFile = '/path/to/xxx.ms'; 281let context : mindSporeLite.Context = {}; 282context.target = ['cpu']; 283let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY); 284mindSporeLite.loadModelFromFd(file.fd, context, (mindSporeLiteModel : mindSporeLite.Model) => { 285 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 286 if (modelInputs == null) { 287 console.error('MS_LITE_ERR: getInputs failed.') 288 } else { 289 console.info(modelInputs[0].name); 290 } 291}) 292``` 293## mindSporeLite.loadModelFromFd 294 295loadModelFromFd(model: number, context?: Context): Promise<Model> 296 297从文件描述符加载输入模型用于推理。使用Promise异步函数。 298 299**系统能力:** SystemCapability.AI.MindSporeLite 300 301**参数:** 302 303| 参数名 | 类型 | 必填 | 说明 | 304| ------- | ------------------- | ---- | --------------------------------------------- | 305| model | number | 是 | 模型的文件描述符。跟随文件系统返回fd值传入。 | 306| context | [Context](#context) | 否 | 运行环境的配置信息。默认使用CpuDevice初始化。 | 307 308**返回值:** 309 310| 类型 | 说明 | 311| ------------------------- | ---------------------------- | 312| Promise<[Model](#model)> | Promise对象。返回Model对象。 | 313 314**示例:** 315 316```ts 317import { fileIo } from '@kit.CoreFileKit'; 318let modelFile = '/path/to/xxx.ms'; 319let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY); 320mindSporeLite.loadModelFromFd(file.fd).then((mindSporeLiteModel: mindSporeLite.Model) => { 321 let modelInputs: mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 322 if (modelInputs == null) { 323 console.error('MS_LITE_ERR: getInputs failed.') 324 } else { 325 console.info(modelInputs[0].name); 326 } 327}) 328``` 329 330## mindSporeLite.loadTrainModelFromFile<sup>12+</sup> 331 332loadTrainModelFromFile(model: string, trainCfg?: TrainCfg, context?: Context): Promise<Model> 333 334根据路径加载训练模型文件。使用Promise异步回调。 335 336**系统能力:** SystemCapability.AI.MindSporeLite 337 338**参数:** 339 340| 参数名 | 类型 | 必填 | 说明 | 341| -------- | ----------------------- | ---- | ------------------------------------------------ | 342| model | string | 是 | 模型的完整输入路径。字符串长度限制跟随文件系统。 | 343| trainCfg | [TrainCfg](#traincfg12) | 否 | 模型训练配置。默认值为TrainCfg各属性默认值。 | 344| context | [Context](#context) | 否 | 运行环境的配置信息。默认使用CpuDevice初始化。 | 345 346**返回值:** 347 348| 类型 | 说明 | 349| ------------------------ | -------------------- | 350| Promise<[Model](#model)> | Promise对象。返回Model对象。 | 351 352**示例:** 353 354```ts 355let modelFile = '/path/to/xxx.ms'; 356mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => { 357 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 358 if (modelInputs == null) { 359 console.error('MS_LITE_ERR: getInputs failed.') 360 } else { 361 console.info(modelInputs[0].name); 362 } 363}) 364``` 365 366## mindSporeLite.loadTrainModelFromBuffer<sup>12+</sup> 367 368loadTrainModelFromBuffer(model: ArrayBuffer, trainCfg?: TrainCfg, context?: Context): Promise<Model> 369 370从内存缓冲区加载训练模型。使用Promise异步回调。 371 372**系统能力:** SystemCapability.AI.MindSporeLite 373 374**参数:** 375 376| 参数名 | 类型 | 必填 | 说明 | 377| -------- | ----------------------- | ---- | --------------------------------------------- | 378| model | ArrayBuffer | 是 | 包含训练模型的内存。 | 379| trainCfg | [TrainCfg](#traincfg12) | 否 | 模型训练配置。默认值为TrainCfg各属性默认值。 | 380| context | [Context](#context) | 否 | 运行环境的配置信息。默认使用CpuDevice初始化。 | 381 382**返回值:** 383 384| 类型 | 说明 | 385| ------------------------ | -------------------- | 386| Promise<[Model](#model)> | Promise对象。返回Model对象。 | 387 388**示例:** 389 390```ts 391import { common } from '@kit.AbilityKit'; 392import { UIContext } from '@kit.ArkUI'; 393import { BusinessError } from '@kit.BasicServicesKit'; 394 395let modelFile = 'xxx.ms'; 396let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 397globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((buffer: Uint8Array) => { 398 let modelBuffer = buffer.buffer; 399 mindSporeLite.loadTrainModelFromBuffer(modelBuffer).then((mindSporeLiteModel: mindSporeLite.Model) => { 400 console.info("MSLITE trainMode: ", mindSporeLiteModel.trainMode); 401 }) 402}).catch((error: BusinessError) => { 403 console.error("getRawFileContent promise error is " + error); 404}); 405``` 406 407## mindSporeLite.loadTrainModelFromFd<sup>12+</sup> 408 409loadTrainModelFromFd(model: number, trainCfg?: TrainCfg, context?: Context): Promise<Model> 410 411从文件描述符加载训练模型文件。使用Promise异步回调。 412 413**系统能力:** SystemCapability.AI.MindSporeLite 414 415**参数:** 416 417| 参数名 | 类型 | 必填 | 说明 | 418| -------- | ----------------------- | ---- | ------------------------------------------------ | 419| model | number | 是 | 训练模型的文件描述符。跟随文件系统返回fd值传入。 | 420| trainCfg | [TrainCfg](#traincfg12) | 否 | 模型训练配置。默认值为TrainCfg各属性默认值。 | 421| context | [Context](#context) | 否 | 运行环境的配置信息。默认使用CpuDevice初始化。 | 422 423**返回值:** 424 425| 类型 | 说明 | 426| ------------------------ | ---------------------------- | 427| Promise<[Model](#model)> | Promise对象。返回Model对象。 | 428 429**示例:** 430 431```ts 432import { fileIo } from '@kit.CoreFileKit'; 433let modelFile = '/path/to/xxx.ms'; 434let file = fileIo.openSync(modelFile, fileIo.OpenMode.READ_ONLY); 435mindSporeLite.loadTrainModelFromFd(file.fd).then((mindSporeLiteModel: mindSporeLite.Model) => { 436 console.info("MSLITE trainMode: ", mindSporeLiteModel.trainMode); 437}); 438``` 439 440## mindSporeLite.getAllNNRTDeviceDescriptions<sup>12+</sup> 441 442getAllNNRTDeviceDescriptions() : NNRTDeviceDescription[] 443 444获取NNRt中的所有设备描述。 445 446**系统能力:** SystemCapability.AI.MindSporeLite 447 448**返回值:** 449 450| 类型 | 说明 | 451| --------------------------------------------------- | ---------------------- | 452| [NNRTDeviceDescription](#nnrtdevicedescription12)[] | NNRt设备描述信息数组。 | 453 454**示例:** 455 456```ts 457let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions(); 458if (allDevices == null) { 459 console.error('MS_LITE_LOG: getAllNNRTDeviceDescriptions is NULL.'); 460} 461``` 462 463## Context 464 465定义运行环境的配置信息。 466 467### 属性 468 469**系统能力:** SystemCapability.AI.MindSporeLite 470 471 472| 名称 | 类型 | 只读 | 可选 | 说明 | 473| ------ | ------------------------- | ---- | ---- | ------------------------------------------------------------ | 474| target | string[] | 否 | 是 | 配置目标后端。可选'cpu','nnrt',默认'cpu'。 | 475| cpu | [CpuDevice](#cpudevice) | 否 | 是 | CPU后端设备选项。只有当target包含'cpu'时,才能设置此属性。默认值为CpuDevice各属性默认值。 | 476| nnrt | [NNRTDevice](#nnrtdevice) | 否 | 是 | NNRt后端设备选项。只有当target包含'nnrt'时,才能设置此属性。默认值为NNRTDevice各属性默认值。 | 477 478**示例:** 479 480```ts 481let context: mindSporeLite.Context = {}; 482context.target = ['cpu','nnrt']; 483``` 484 485## CpuDevice 486 487CPU后端设备选项。 488 489### 属性 490 491**系统能力:** SystemCapability.AI.MindSporeLite 492 493| 名称 | 类型 | 只读 | 可选 | 说明 | 494| ---------------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------------------------ | 495| threadNum | number | 否 | 是 | 设置运行时的线程数,默认值:2。 | 496| threadAffinityMode | [ThreadAffinityMode](#threadaffinitymode) | 否 | 是 | 设置运行时的CPU绑核策略模式,默认值为不绑核:mindSporeLite.ThreadAffinityMode.NO_AFFINITIES。 | 497| threadAffinityCoreList | number[] | 否 | 是 | 设置运行时的CPU绑核列表,设置绑核策略模式后使能,当绑核策略模式为mindSporeLite.ThreadAffinityMode.NO_AFFINITIES时,绑核列表为空。列表中的数字代表核的序号。默认值:[]。 | 498| precisionMode | string | 否 | 是 | 设置是否使能**Float16推理模式**,设置为'preferred_fp16'代表使能半精度推理,其余设置情况均为不支持,默认设置'enforce_fp32'表示不使能半精度推理。 | 499 500**Float16推理模式**: Float16又称半精度,它使用16比特表示一个数。Float16推理模式表示推理的时候用半精度进行推理。 501 502**示例:** 503 504```ts 505let context: mindSporeLite.Context = {}; 506context.cpu = {}; 507context.target = ['cpu']; 508context.cpu.threadNum = 2; 509context.cpu.threadAffinityMode = 0; 510context.cpu.precisionMode = 'preferred_fp16'; 511context.cpu.threadAffinityCoreList = [0, 1, 2]; 512``` 513 514## ThreadAffinityMode 515 516设置运行时的CPU绑核策略模式,有效值为0-2,0为默认不绑核,1为绑大核,2为绑中核。 517 518**系统能力:** SystemCapability.AI.MindSporeLite 519 520| 名称 | 值 | 说明 | 521| ------------------ | ---- | ------------ | 522| NO_AFFINITIES | 0 | 不绑核。 | 523| BIG_CORES_FIRST | 1 | 绑大核优先。 | 524| LITTLE_CORES_FIRST | 2 | 绑中核优先。 | 525 526## NNRTDevice 527 528Neural Network Runtime表示神经网络运行时,简称NNRt。作为中间桥梁,连通上层 AI 推理框架和底层加速芯片,实现 AI 模型的跨芯片推理计算。MindSpore Lite 可配置NNRt后端。 529 530### 属性 531 532**系统能力:** SystemCapability.AI.MindSporeLite 533 534| 名称 | 类型 | 只读 | 可选 | 说明 | 535| ----------------------------- | ----------------------------------- | ---- | ------------------------ | ------------------------ | 536| deviceID<sup>12+</sup> | bigint | 否 | 是 | NNRt设备ID。默认值为0。 | 537| performanceMode<sup>12+</sup> | [PerformanceMode](#performancemode12) | 否 | 是 | NNRt设备的工作性能模式。默认值为PERFORMANCE_NONE。 | 538| priority<sup>12+</sup> | [Priority](#priority12) | 否 | 是 | NNRt推理任务优先级。默认值为PRIORITY_MEDIUM。 | 539| extensions<sup>12+</sup> | [Extension](#extension12)[] | 否 | 是 | NNRt设备的扩展配置。默认为空。 | 540 541## PerformanceMode<sup>12+</sup> 542 543NNRt设备的工作性能模式枚举。 544 545**系统能力:** SystemCapability.AI.MindSporeLite 546 547| 名称 | 值 | 说明 | 548| ------------------- | ---- | ------------------- | 549| PERFORMANCE_NONE | 0 | 无特殊设置。 | 550| PERFORMANCE_LOW | 1 | 低功耗模式。 | 551| PERFORMANCE_MEDIUM | 2 | 功耗-性能均衡模式。 | 552| PERFORMANCE_HIGH | 3 | 高性能模式。 | 553| PERFORMANCE_EXTREME | 4 | 极致性能模式。 | 554 555## Priority<sup>12+</sup> 556 557NNRt推理任务优先级枚举。 558 559**系统能力:** SystemCapability.AI.MindSporeLite 560 561| 名称 | 值 | 说明 | 562| --------------- | ---- | -------------- | 563| PRIORITY_NONE | 0 | 无优先级偏好。 | 564| PRIORITY_LOW | 1 | 低优先级任务。 | 565| PRIORITY_MEDIUM | 2 | 中优先级任务。 | 566| PRIORITY_HIGH | 3 | 高优先级任务。 | 567 568## Extension<sup>12+</sup> 569 570定义NNRt设备的扩展信息。 571 572### 属性 573 574**系统能力:** SystemCapability.AI.MindSporeLite 575 576| 名称 | 类型 | 只读 | 可选 | 说明 | 577| ------------------- | ----------- | ---- | ---- | ---------------- | 578| name<sup>12+</sup> | string | 否 | 否 | 扩展名称。 | 579| value<sup>12+</sup> | ArrayBuffer | 否 | 否 | 包含扩展的内存。 | 580 581## NNRTDeviceDescription<sup>12+</sup> 582 583NNRt设备信息描述,包含设备ID,设备名称等信息。 584 585**系统能力:** SystemCapability.AI.MindSporeLite 586 587### deviceID<sup>12+</sup> 588 589deviceID() : bigint 590 591获取NNRt设备ID。 592 593**系统能力:** SystemCapability.AI.MindSporeLite 594 595**返回值:** 596 597| 类型 | 说明 | 598| ------ | ------------ | 599| bigint | NNRt设备ID。 | 600 601**示例:** 602 603```ts 604let context: mindSporeLite.Context = {}; 605context.target = ["nnrt"]; 606context.nnrt = {}; 607let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions(); 608if (allDevices == null) { 609 console.error('getAllNNRTDeviceDescriptions is NULL.'); 610} else { 611 for (let i: number = 0; i < allDevices.length; i++) { 612 console.info(allDevices[i].deviceID().toString()); 613 } 614} 615``` 616 617### deviceType<sup>12+</sup> 618 619deviceType() : NNRTDeviceType 620 621获取NNRt设备类型。 622 623**系统能力:** SystemCapability.AI.MindSporeLite 624 625**返回值:** 626 627| 类型 | 说明 | 628| ----------------------------------- | -------------- | 629| [NNRTDeviceType](#nnrtdevicetype12) | NNRt设备类型。 | 630 631**示例:** 632 633```ts 634let context: mindSporeLite.Context = {}; 635context.target = ["nnrt"]; 636context.nnrt = {}; 637let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions(); 638if (allDevices == null) { 639 console.error('getAllNNRTDeviceDescriptions is NULL.'); 640} else { 641 for (let i: number = 0; i < allDevices.length; i++) { 642 console.info(allDevices[i].deviceType().toString()); 643 } 644} 645``` 646 647### deviceName<sup>12+</sup> 648 649deviceName() : string 650 651获取NNRt设备名称。 652 653**系统能力:** SystemCapability.AI.MindSporeLite 654 655**返回值:** 656 657| 类型 | 说明 | 658| ------ | -------------- | 659| string | NNRt设备名称。 | 660 661**示例:** 662 663```ts 664let context: mindSporeLite.Context = {}; 665context.target = ["nnrt"]; 666context.nnrt = {}; 667let allDevices = mindSporeLite.getAllNNRTDeviceDescriptions(); 668if (allDevices == null) { 669 console.error('getAllNNRTDeviceDescriptions is NULL.'); 670} else { 671 for (let i: number = 0; i < allDevices.length; i++) { 672 console.info(allDevices[i].deviceName().toString()); 673 } 674} 675``` 676 677## NNRTDeviceType<sup>12+</sup> 678 679NNRt设备类型枚举。 680 681**系统能力:** SystemCapability.AI.MindSporeLite 682 683| 名称 | 值 | 说明 | 684| ---------------------- | ---- | ----------------------------------- | 685| NNRTDEVICE_OTHERS | 0 | 设备类型不属于以下3种,则属于其它。 | 686| NNRTDEVICE_CPU | 1 | CPU设备。 | 687| NNRTDEVICE_GPU | 2 | GPU设备。 | 688| NNRTDEVICE_ACCELERATOR | 3 | 特定的加速设备。 | 689 690## TrainCfg<sup>12+</sup> 691 692端侧训练相关参数的配置文件。 693 694### 属性 695 696**系统能力:** SystemCapability.AI.MindSporeLite 697 698| 名称 | 类型 | 只读 | 可选 | 说明 | 699| ------------------------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------------------------ | 700| lossName<sup>12+</sup> | string[] | 否 | 是 | 损失函数的名称列表。默认值为["loss_fct", "_loss_fn", "SigmoidCrossEntropy"]。 | 701| optimizationLevel<sup>12+</sup> | [OptimizationLevel](#optimizationlevel12) | 否 | 是 | 端侧训练的网络优化等级。默认值为O0。 | 702 703**示例:** 704 705```ts 706let cfg: mindSporeLite.TrainCfg = {}; 707cfg.lossName = ["loss_fct", "_loss_fn", "SigmoidCrossEntropy"]; 708cfg.optimizationLevel = mindSporeLite.OptimizationLevel.O0; 709``` 710 711## OptimizationLevel<sup>12+</sup> 712 713端侧训练的网络优化等级枚举。 714 715**系统能力:** SystemCapability.AI.MindSporeLite 716 717| 名称 | 值 | 说明 | 718| ---- | ---- | ---------------------------------------------------------- | 719| O0 | 0 | 无优化等级。 | 720| O2 | 2 | 将网络转换为float16,保持批量归一化层和损失函数为float32。 | 721| O3 | 3 | 将网络转换为float16,包括批量归一化层。 | 722| AUTO | 4 | 根据设备选择优化等级。 | 723 724 725## QuantizationType<sup>12+</sup> 726 727量化类型信息,有效值为0-2。 728 729**系统能力:** SystemCapability.AI.MindSporeLite 730 731| 名称 | 值 | 说明 | 732| ------------ | ---- | ---------- | 733| NO_QUANT | 0 | 不做量化。 | 734| WEIGHT_QUANT | 1 | 权重量化。 | 735| FULL_QUANT | 2 | 全量化。 | 736 737## Model 738 739模型实例。描述Model对象的属性和方法。 740 741下例API示例中都需先使用[loadModelFromFile()](#mindsporeliteloadmodelfromfile)、[loadModelFromBuffer()](#mindsporeliteloadmodelfrombuffer)、[loadModelFromFd()](#mindsporeliteloadmodelfromfd)中的任一方法获取到Model实例,再通过此实例调用对应方法。 742 743### 属性 744 745**系统能力:** SystemCapability.AI.MindSporeLite 746 747| 名称 | 类型 | 只读 | 可选 | 说明 | 748| -------------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | 749| learningRate<sup>12+</sup> | number | 否 | 是 | 训练模型的学习率。默认值从加载的模型中读取。 | 750| trainMode<sup>12+</sup> | boolean | 否 | 是 | 模型是否为训练模式。true表示训练模式,false表示非训练模式。如果是训练模型,trainMode默认是true;如果是推理模型,trainMode默认是false。 | 751 752### getInputs 753 754getInputs(): MSTensor[] 755 756获取模型的输入用于推理。 757 758**系统能力:** SystemCapability.AI.MindSporeLite 759 760**返回值:** 761 762| 类型 | 说明 | 763| ----------------------- | ------------------ | 764| [MSTensor](#mstensor)[] | 返回MSTensor对象。 | 765 766**示例:** 767 768```ts 769let modelFile = '/path/to/xxx.ms'; 770mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => { 771 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 772 if (modelInputs == null) { 773 console.error('MS_LITE_ERR: getInputs failed.') 774 } else { 775 console.info(modelInputs[0].name); 776 } 777}) 778``` 779### predict 780 781predict(inputs: MSTensor[], callback: Callback<MSTensor[]>): void 782 783执行推理模型。使用callback异步回调。需要确保调用时模型对象不被资源回收。 784 785**系统能力:** SystemCapability.AI.MindSporeLite 786 787**参数:** 788 789| 参数名 | 类型 | 必填 | 说明 | 790| ------ | ----------------------- | ---- | -------------------------- | 791| inputs | [MSTensor](#mstensor)[] | 是 | 模型的输入列表。MSTensor对象。 | 792| callback | Callback<[MSTensor](#mstensor)[]> | 是 | 回调函数。返回MSTensor对象。 | 793 794**示例:** 795 796```ts 797import { common } from '@kit.AbilityKit'; 798import { UIContext } from '@kit.ArkUI'; 799import { BusinessError } from '@kit.BasicServicesKit'; 800 801let inputName = 'input_data.bin'; 802let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 803globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => { 804 let inputBuffer = buffer.buffer; 805 let modelFile : string = '/path/to/xxx.ms'; 806 let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile); 807 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 808 809 modelInputs[0].setData(inputBuffer); 810 mindSporeLiteModel.predict(modelInputs, (mindSporeLiteTensor : mindSporeLite.MSTensor[]) => { 811 let output = new Float32Array(mindSporeLiteTensor[0].getData()); 812 for (let i = 0; i < output.length; i++) { 813 console.info('MS_LITE_LOG: ' + output[i].toString()); 814 } 815 }) 816}).catch((error: BusinessError) => { 817 console.error("getRawFileContent promise error is " + error); 818}); 819``` 820### predict 821 822predict(inputs: MSTensor[]): Promise<MSTensor[]> 823 824执行推理模型,返回推理结果。使用Promise异步回调。需要确保调用时模型对象不被资源回收。 825 826**系统能力:** SystemCapability.AI.MindSporeLite 827 828**参数:** 829 830| 参数名 | 类型 | 必填 | 说明 | 831| ------ | ----------------------- | ---- | ------------------------------ | 832| inputs | [MSTensor](#mstensor)[] | 是 | 模型的输入列表。MSTensor对象。 | 833 834**返回值:** 835 836| 类型 | 说明 | 837| ----------------------- | ---------------------- | 838| Promise<[MSTensor](#mstensor)[]> | Promise对象。返回MSTensor对象列表。 | 839 840**示例:** 841 842```ts 843import { common } from '@kit.AbilityKit'; 844import { UIContext } from '@kit.ArkUI'; 845import { BusinessError } from '@kit.BasicServicesKit'; 846 847let inputName = 'input_data.bin'; 848let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 849globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => { 850 let inputBuffer = buffer.buffer; 851 let modelFile = '/path/to/xxx.ms'; 852 let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile); 853 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 854 modelInputs[0].setData(inputBuffer); 855 mindSporeLiteModel.predict(modelInputs).then((mindSporeLiteTensor : mindSporeLite.MSTensor[]) => { 856 let output = new Float32Array(mindSporeLiteTensor[0].getData()); 857 for (let i = 0; i < output.length; i++) { 858 console.info(output[i].toString()); 859 } 860 }) 861}).catch((error: BusinessError) => { 862 console.error("getRawFileContent promise error is " + error); 863}); 864``` 865 866### resize 867 868resize(inputs: MSTensor[], dims: Array<Array<number>>): boolean 869 870重新设置张量大小。 871 872**系统能力:** SystemCapability.AI.MindSporeLite 873 874**参数:** 875 876| 参数名 | 类型 | 必填 | 说明 | 877| ------ | --------------------- | ---- | ----------------------------- | 878| inputs | [MSTensor](#mstensor)[] | 是 | 模型的输入列表。 | 879| dims | Array<Array<number>> | 是 | 需要修改的目标张量大小。 | 880 881**返回值:** 882 883| 类型 | 说明 | 884| ------- | ------------------------------------------------------------ | 885| boolean | 返回是否设置成功的结果。true表示重新设置张量大小成功;false表示重新设置张量大小失败。 | 886 887**示例:** 888 889```ts 890let modelFile = '/path/to/xxx.ms'; 891mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => { 892 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 893 let new_dim = new Array([1,32,32,1]); 894 mindSporeLiteModel.resize(modelInputs, new_dim); 895}) 896``` 897 898### runStep<sup>12+</sup> 899 900runStep(inputs: MSTensor[]): boolean 901 902单步训练模型,仅用于端侧训练。 903 904**系统能力:** SystemCapability.AI.MindSporeLite 905 906**参数:** 907 908| 参数名 | 类型 | 必填 | 说明 | 909| ------ | ----------------------- | --- | -------- | 910| inputs | [MSTensor](#mstensor)[] | 是 | 模型的输入列表。 | 911 912**返回值:** 913 914| 类型 | 说明 | 915| ------- | ------------------------------------------------------------ | 916| boolean | 返回单步训练模型是否成功的结果。true表示单步训练模型成功,false表示单步训练模型失败。 | 917 918**示例:** 919 920```ts 921let modelFile = '/path/to/xxx.ms'; 922mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel: mindSporeLite.Model) => { 923 mindSporeLiteModel.trainMode = true; 924 const modelInputs = mindSporeLiteModel.getInputs(); 925 let ret = mindSporeLiteModel.runStep(modelInputs); 926 if (ret == false) { 927 console.error('MS_LITE_LOG: runStep failed.') 928 } 929}) 930``` 931 932### getWeights<sup>12+</sup> 933 934getWeights(): MSTensor[] 935 936获取模型的所有权重,仅用于端侧训练。 937 938**系统能力:** SystemCapability.AI.MindSporeLite 939 940**返回值:** 941 942| 类型 | 说明 | 943| ----------------------- | ---------- | 944| [MSTensor](#mstensor)[] | 返回模型的权重张量。 | 945 946**示例:** 947 948```ts 949import { common } from '@kit.AbilityKit'; 950import { UIContext } from '@kit.ArkUI'; 951import { BusinessError } from '@kit.BasicServicesKit'; 952 953let modelFile = 'xxx.ms'; 954let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 955globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((modelBuffer : Uint8Array) => { 956 mindSporeLite.loadTrainModelFromBuffer(modelBuffer.buffer.slice(0)).then((mindSporeLiteModel: mindSporeLite.Model) => { 957 mindSporeLiteModel.trainMode = true; 958 const weights = mindSporeLiteModel.getWeights(); 959 for (let i = 0; i < weights.length; i++) { 960 let printStr = weights[i].name + ", "; 961 printStr += weights[i].shape + ", "; 962 printStr += weights[i].dtype + ", "; 963 printStr += weights[i].dataSize + ", "; 964 printStr += weights[i].getData(); 965 console.info("MS_LITE weights: ", printStr); 966 } 967 }) 968}).catch((error: BusinessError) => { 969 console.error("getRawFileContent promise error is " + error); 970}); 971``` 972 973### updateWeights<sup>12+</sup> 974 975updateWeights(weights: MSTensor[]): boolean 976 977更新模型的权重,仅用于端侧训练。 978 979**系统能力:** SystemCapability.AI.MindSporeLite 980 981**参数:** 982 983| 参数名 | 类型 | 必填 | 说明 | 984| ------- | ----------------------- | ---- | -------------- | 985| weights | [MSTensor](#mstensor)[] | 是 | 权重张量列表。 | 986 987**返回值:** 988 989| 类型 | 说明 | 990| ------- | ------------------------------------------------------------ | 991| boolean | 返回是否更新权重成功的结果。true表示更新权重成功,false表示更新权重失败。 | 992 993**示例:** 994 995```ts 996import { common } from '@kit.AbilityKit'; 997import { UIContext } from '@kit.ArkUI'; 998import { BusinessError } from '@kit.BasicServicesKit'; 999 1000let modelFile = 'xxx.ms'; 1001let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 1002globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((modelBuffer : Uint8Array) => { 1003 mindSporeLite.loadTrainModelFromBuffer(modelBuffer.buffer.slice(0)).then((mindSporeLiteModel: mindSporeLite.Model) => { 1004 mindSporeLiteModel.trainMode = true; 1005 const weights = mindSporeLiteModel.getWeights(); 1006 let ret = mindSporeLiteModel.updateWeights(weights); 1007 if (ret == false) { 1008 console.error('MS_LITE_LOG: updateWeights failed.') 1009 } 1010 }) 1011}).catch((error: BusinessError) => { 1012 console.error("getRawFileContent promise error is " + error); 1013}); 1014``` 1015 1016### setupVirtualBatch<sup>12+</sup> 1017 1018setupVirtualBatch(virtualBatchMultiplier: number, lr: number, momentum: number): boolean 1019 1020设置虚拟批次用于训练,仅用于端侧训练。 1021 1022**系统能力:** SystemCapability.AI.MindSporeLite 1023 1024**参数:** 1025 1026| 参数名 | 类型 | 必填 | 说明 | 1027| ---------------------- | ------ | ---- | ---------------------------------------------------- | 1028| virtualBatchMultiplier | number | 是 | 虚拟批次乘法器,当设置值小于1时,表示禁用虚拟batch。 | 1029| lr | number | 是 | 学习率。 | 1030| momentum | number | 是 | 动量。 | 1031 1032**返回值:** 1033 1034| 类型 | 说明 | 1035| ------- | ------------------------------------------------------------ | 1036| boolean | 返回是否设置虚拟批次成功的结果。true表示设置虚拟批次成功,false表示设置虚拟批次失败。 | 1037 1038**示例:** 1039 1040```ts 1041import { common } from '@kit.AbilityKit'; 1042import { UIContext } from '@kit.ArkUI'; 1043import { BusinessError } from '@kit.BasicServicesKit'; 1044 1045let modelFile = 'xxx.ms'; 1046let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 1047globalContext.getApplicationContext().resourceManager.getRawFileContent(modelFile).then((modelBuffer : Uint8Array) => { 1048 mindSporeLite.loadTrainModelFromBuffer(modelBuffer.buffer.slice(0)).then((mindSporeLiteModel: mindSporeLite.Model) => { 1049 mindSporeLiteModel.trainMode = true; 1050 let ret = mindSporeLiteModel.setupVirtualBatch(2,-1,-1); 1051 if (ret == false) { 1052 console.error('MS_LITE setupVirtualBatch failed.') 1053 } 1054 }) 1055}).catch((error: BusinessError) => { 1056 console.error("getRawFileContent promise error is " + error); 1057}); 1058``` 1059 1060### exportModel<sup>12+</sup> 1061 1062exportModel(modelFile: string, quantizationType?: QuantizationType, exportInferenceOnly?: boolean, outputTensorName?: string[]): boolean 1063 1064导出训练模型,仅用于端侧训练。 1065 1066**系统能力:** SystemCapability.AI.MindSporeLite 1067 1068**参数:** 1069 1070| 参数名 | 类型 | 必填 | 说明 | 1071| ------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 1072| modelFile | string | 是 | 导出模型的文件路径。字符串长度限制跟随文件系统。 | 1073| quantizationType | [QuantizationType](#quantizationtype12) | 否 | 量化类型,默认为NO_QUANT。 | 1074| exportInferenceOnly | boolean | 否 | 是否只导出推理模型。true表示只导出推理模型,false表示导出训练和推理两个模型。默认为true。 | 1075| outputTensorName | string[] | 否 | 设置导出模型的输出张量的名称。默认为空字符串数组,表示全量导出。 | 1076 1077**返回值:** 1078 1079| 类型 | 说明 | 1080| ------- | ------------------------------------------------------------ | 1081| boolean | 返回是否导出训练模型成功的结果。true表示导出训练模型成功,false表示导出训练模型失败。 | 1082 1083**示例:** 1084 1085```ts 1086let modelFile = '/path/to/xxx.ms'; 1087let newPath = '/newpath/to'; 1088mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel: mindSporeLite.Model) => { 1089 mindSporeLiteModel.trainMode = true; 1090 let ret = mindSporeLiteModel.exportModel(newPath + "/new_model.ms", mindSporeLite.QuantizationType.NO_QUANT, true); 1091 if (ret == false) { 1092 console.error('MS_LITE exportModel failed.') 1093 } 1094}) 1095``` 1096 1097 1098### exportWeightsCollaborateWithMicro<sup>12+</sup> 1099 1100exportWeightsCollaborateWithMicro(weightFile: string, isInference?: boolean, enableFp16?: boolean, changeableWeightsName?: string[]): boolean 1101 1102导出供**micro推理**使用的模型权重,仅用于端侧训练。 1103 1104**micro推理**:MindSpore Lite针对MCUs(MicroControllerUnits)部署硬件后端,提供了一种超轻量Micro AI部署解决方案,离线阶段直接将模型生成轻量化代码,不再需要在线解析模型和图编译。 1105 1106**系统能力:** SystemCapability.AI.MindSporeLite 1107 1108**参数:** 1109 1110| 参数名 | 类型 | 必填 | 说明 | 1111| --------------------- | -------- | ---- | ------------------------------------------------------------ | 1112| weightFile | string | 是 | 权重文件路径。字符串长度限制跟随文件系统。 | 1113| isInference | boolean | 否 | 是否从推理模型中导出权重。true表示从推理模型中导出权重,目前只支持true,默认为true。 | 1114| enableFp16 | boolean | 否 | 浮点权重是否以float16格式保存。true表示以float16格式保存,false表示不以float16格式保存。默认为false。 | 1115| changeableWeightsName | string[] | 否 | 设置可变权重的名称。默认为空字符串数组。 | 1116 1117**返回值:** 1118 1119| 类型 | 说明 | 1120| ------- | ------------------------------------------------------------ | 1121| boolean | 返回是否导出供micro推理使用的模型权重成功的结果。true表示导出供micro推理使用的模型权重成功,false表示导出供micro推理使用的模型权重失败。 | 1122 1123**示例:** 1124 1125```ts 1126let modelFile = '/path/to/xxx.ms'; 1127let microWeight = '/path/to/xxx.bin'; 1128mindSporeLite.loadTrainModelFromFile(modelFile).then((mindSporeLiteModel: mindSporeLite.Model) => { 1129 let ret = mindSporeLiteModel.exportWeightsCollaborateWithMicro(microWeight); 1130 if (ret == false) { 1131 console.error('MSLITE exportWeightsCollaborateWithMicro failed.') 1132 } 1133}) 1134``` 1135 1136## MSTensor 1137 1138模型张量实例。描述MSTensor对象的属性和方法。它与数组和矩阵非常相似,是MindSpore Lite网络运算中的基本数据结构。 1139 1140下例API示例中都需先使用[getInputs()](#getinputs)获取到MSTensor实例,再通过此实例调用对应方法。 1141 1142### 属性 1143 1144**系统能力:** SystemCapability.AI.MindSporeLite 1145 1146| 名称 | 类型 | 只读 | 可选 | 说明 | 1147| ---------- | --------------------- | ---- | ---- | ---------------------- | 1148| name | string | 否 | 否 | 张量的名称。 | 1149| shape | number[] | 否 | 否 | 张量的维度数组。 | 1150| elementNum | number | 否 | 否 | 张量的维度数组的长度。 | 1151| dataSize | number | 否 | 否 | 张量的数据的长度。 | 1152| dtype | [DataType](#datatype) | 否 | 否 | 张量的数据类型。 | 1153| format | [Format](#format) | 否 | 否 | 张量的数据排布方式。 | 1154 1155**示例:** 1156 1157```ts 1158let modelFile = '/path/to/xxx.ms'; 1159mindSporeLite.loadModelFromFile(modelFile).then((mindSporeLiteModel : mindSporeLite.Model) => { 1160 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 1161 console.info(modelInputs[0].name); 1162 console.info(modelInputs[0].shape.toString()); 1163 console.info(modelInputs[0].elementNum.toString()); 1164 console.info(modelInputs[0].dtype.toString()); 1165 console.info(modelInputs[0].format.toString()); 1166 console.info(modelInputs[0].dataSize.toString()); 1167}) 1168``` 1169 1170### getData 1171 1172getData(): ArrayBuffer 1173 1174获取张量的数据。 1175 1176**系统能力:** SystemCapability.AI.MindSporeLite 1177 1178**返回值:** 1179 1180| 类型 | 说明 | 1181| ----------- | -------------------- | 1182| ArrayBuffer | 返回张量的数据指针。 | 1183 1184**示例:** 1185 1186```ts 1187import { common } from '@kit.AbilityKit'; 1188import { UIContext } from '@kit.ArkUI'; 1189import { BusinessError } from '@kit.BasicServicesKit'; 1190 1191let inputName = 'input_data.bin'; 1192let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 1193globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => { 1194 let inputBuffer = buffer.buffer; 1195 let modelFile = '/path/to/xxx.ms'; 1196 let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile); 1197 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 1198 modelInputs[0].setData(inputBuffer); 1199 mindSporeLiteModel.predict(modelInputs).then((mindSporeLiteTensor : mindSporeLite.MSTensor[]) => { 1200 let output = new Float32Array(mindSporeLiteTensor[0].getData()); 1201 for (let i = 0; i < output.length; i++) { 1202 console.info(output[i].toString()); 1203 } 1204 }) 1205}).catch((error: BusinessError) => { 1206 console.error("getRawFileContent promise error is " + error); 1207}); 1208``` 1209 1210### setData 1211 1212setData(inputArray: ArrayBuffer): void 1213 1214设置张量的数据。 1215 1216**系统能力:** SystemCapability.AI.MindSporeLite 1217 1218**参数:** 1219 1220| 参数名 | 类型 | 必填 | 说明 | 1221| ---------- | ----------- | ---- | ---------------------- | 1222| inputArray | ArrayBuffer | 是 | 张量的输入数据缓冲区。 | 1223 1224**示例:** 1225 1226```ts 1227import { common } from '@kit.AbilityKit'; 1228import { UIContext } from '@kit.ArkUI'; 1229import { BusinessError } from '@kit.BasicServicesKit'; 1230 1231let inputName = 'input_data.bin'; 1232let globalContext = new UIContext().getHostContext() as common.UIAbilityContext; 1233globalContext.getApplicationContext().resourceManager.getRawFileContent(inputName).then(async (buffer : Uint8Array) => { 1234 let inputBuffer = buffer.buffer; 1235 let modelFile = '/path/to/xxx.ms'; 1236 let mindSporeLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile); 1237 let modelInputs : mindSporeLite.MSTensor[] = mindSporeLiteModel.getInputs(); 1238 modelInputs[0].setData(inputBuffer); 1239}).catch((error: BusinessError) => { 1240 console.error("getRawFileContent promise error is " + error); 1241}); 1242``` 1243 1244## DataType 1245 1246张量的数据类型。 1247 1248**系统能力:** SystemCapability.AI.MindSporeLite 1249 1250| 名称 | 值 | 说明 | 1251| ------------------- | ---- | ------------------- | 1252| TYPE_UNKNOWN | 0 | 未知类型。 | 1253| NUMBER_TYPE_INT8 | 32 | 保持Int8的类型。 | 1254| NUMBER_TYPE_INT16 | 33 | 保持Int16的类型。 | 1255| NUMBER_TYPE_INT32 | 34 | 保持Int32的类型。 | 1256| NUMBER_TYPE_INT64 | 35 | 保持Int64的类型。 | 1257| NUMBER_TYPE_UINT8 | 37 | 保持UInt8的类型。 | 1258| NUMBER_TYPE_UINT16 | 38 | 保持UInt16的类型。 | 1259| NUMBER_TYPE_UINT32 | 39 | 保持UInt32的类型。 | 1260| NUMBER_TYPE_UINT64 | 40 | 保持UInt64的类型。 | 1261| NUMBER_TYPE_FLOAT16 | 42 | 保持Float16的类型。 | 1262| NUMBER_TYPE_FLOAT32 | 43 | 保持Float32的类型。 | 1263| NUMBER_TYPE_FLOAT64 | 44 | 保持Float64的类型。 | 1264 1265## Format 1266 1267张量的数据排布方式。 1268 1269**系统能力:** SystemCapability.AI.MindSporeLite 1270 1271| 名称 | 值 | 说明 | 1272| -------------- | ---- | --------------------- | 1273| DEFAULT_FORMAT | -1 | 未知数据排布方式。 | 1274| NCHW | 0 | 数据排布方式为NCHW。 | 1275| NHWC | 1 | 数据排布方式为NHWC。 | 1276| NHWC4 | 2 | 数据排布方式为NHWC4。 | 1277| HWKC | 3 | 数据排布方式为HWKC。 | 1278| HWCK | 4 | 数据排布方式为HWCK。 | 1279| KCHW | 5 | 数据排布方式为KCHW。 | 1280