You need to enable JavaScript to run this app. React Native中TensorFlow.js如何从应用本地存储加载已下载模型
优惠活动
大模型
产品
解决方案
定价
更多

React Native中TensorFlow.js如何从应用本地存储加载已下载模型

从应用沙箱路径加载模型不需要依赖AsyncStorage

完全可以不经过AsyncStorage直接从你提到的DocumentDir本地路径加载模型,所谓的asyncStorageIO是@tensorflow/tfjs-react-native早期适配不完善时的权宜方案,现在使用本质上是走弯路。

为什么不推荐AsyncStorage中转方案

很多开发者接触tfjs-react-native本地加载时会被asyncStorageIO的方案误导,这个方案的核心逻辑是早期版本没有打通和React Native原生文件系统的通路,只能通过KV存储当文件中转,存在三个无法忽视的硬伤:

  • 存储大小限制:AsyncStorage单条存储条目通常有10-20MB的大小上限,常规TensorFlow.js模型权重动辄几十上百MB,根本无法完整存入
  • 性能损耗:大文件需要经过base64序列化才能存入KV存储,读取时还要反序列化,比直接读文件系统的加载速度慢一个量级以上
  • 存储空间浪费:文件本身已经存在DocumentDir下,复制一份序列化内容到AsyncStorage相当于多占一倍的存储,没有任何实际收益

无AsyncStorage的本地加载实现

你已经用react-native-fetch-blob完成了文件下载到沙箱目录的流程,只要给tf传入一个符合IOHandler接口的自定义读取器,就能直接加载本地文件,不需要额外依赖:

  1. 自定义IOHandler只需要实现两个核心能力:读取本地model.json的文本内容解析为模型拓扑结构、读取本地weights.bin的二进制内容转为tf可识别的ArrayBuffer
  2. 参考实现代码如下:
import RNFetchBlob from 'rn-fetch-blob'; // 对应你正在使用的fetch-blob库
import * as tf from '@tensorflow/tfjs';

// 自定义本地文件加载器,传入两个模型文件的绝对本地路径
const createLocalModelLoader = (modelJsonAbsPath: string, weightsBinAbsPath: string) => {
  return {
    async load(): Promise<tf.io.ModelArtifacts> {
      // 读取model.json文本内容
      const modelJsonRaw = await RNFetchBlob.fs.readFile(modelJsonAbsPath, 'utf8');
      const modelConfig = JSON.parse(modelJsonRaw);
      
      // 读取权重二进制内容为ArrayBuffer;老版本fetch-blob不支持该编码时,可先读为base64再用tf内置工具转成ArrayBuffer
      const weightsBuffer = await RNFetchBlob.fs.readFile(weightsBinAbsPath, 'arrayBuffer');
      
      // 组装为tf要求的模型制品结构返回
      return {
        modelTopology: modelConfig.modelTopology,
        weightSpecs: modelConfig.weightsManifest[0].weights,
        weightData: weightsBuffer,
        format: 'graph-model'
      }
    }
  }
}
  1. 文件下载完成后直接调用加载即可,全程不涉及AsyncStorage:
// 从DocumentDir获取模型文件的实际存放路径
const modelRootPath = `${RNFetchBlob.fs.dirs.DocumentDir}/explain_model`;
const modelJsonPath = `${modelRootPath}/model.json`;
const weightsBinPath = `${modelRootPath}/explain-weights.bin`;

// 加载本地模型
const model = await tf.loadGraphModel(createLocalModelLoader(modelJsonPath, weightsBinPath));
console.log('本地模型加载完成');

补充说明

  • 如果你使用的是0.7.0以上版本的@tensorflow/tfjs-react-native,官方已经内置了本地文件系统的IO适配,不需要自己写自定义加载器,直接传带file://前缀的本地绝对路径即可正常加载
  • 如果你的模型权重是多文件分片存储的,只要在load方法里把所有分片按顺序读取、拼接成完整的ArrayBuffer,就可以兼容多分片模型的加载逻辑
  • 如果你确实需要兼容非常老版本的tfjs-react-native、必须用asyncStorageIO的话,只需要把DocumentDir里的两个文件读取为base64字符串,通过AsyncStorage.setItem存入指定key,再传入asyncStorageIO的对应key即可,但该方案的硬伤前面已经提及,没有特殊需求不建议使用。

内容的提问来源于stack exchange,提问作者Nicolas Munera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.14 23:15:04