프론트에서 모델 적용을 해야하는 프로젝트가 있어 ONNX 사용 방법을 작성해 보았다.
ONNX(Open Neural Network Exchange)는 2017년에 Microsoft, Facebook, Amazon 등의 주요 회사들이 협력하여 개발한 여러 다른 딥러닝 프레임워크 간에 모델을 공유하고 호환성을 제공하기 위한 개방형 딥러닝 형식입니다.
ONNX는 다양한 딥러닝 프레임워크 간에 모델을 공유하고 호환성을 제공하기 위해 만들어졌습니다. Tensor Flow, PyTorch, Caffe 등 다양한 딥러닝 프레임워크에서 학습한 모델을 다른 프레임워크에서 추론하는 데 사용할 수 있게 해 줍니다
install
👉🏻 yarn add onnxruntime-webimport
import * as ort from 'onnxruntime-web';
webpack 설정 추가
//devServer 설정
headers: {
// to enable SharedArrayBuffer and ONNX multithreading
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'credentialless',
},
//plugins 설정
new CopyPlugin({
patterns: [{
from: '../node_modules/onnxruntime-web/dist/*.wasm',
to: '[name][ext]',
}],
})
initialize
import onnxPath from 'assets/models/dev.onnx';
const MODEL_DIR = '/models/dev.onnx';
public initModel = async () => {
try {
const model = await ort.InferenceSession.create(onnxPath);
} catch (e) {
console.error(e);
}
};
🚫 webpack 설정
import 문을 사용하여 로드
import onnxPath from 'assets/models/dev.onnx';
webpack에 onnx file을 번들링 할 수 있도록 module 추가
{
test: /\.(onnx|pb|pth)$/i,
type: 'asset/resource',
},