기술 가이드

ONNX 및 모델 상호 운용성

ONNX (Open Neural Network Exchange) is an open file format and operator standard for machine learning models, announced by Facebook and Microsoft in September 2017 and now governed by the Linux Foundation.

이 가이드를 들어보세요AI 내레이션 · ~8 min

이 페이지에서9분 읽기
  1. 개요
  2. 주요 시사점
  3. 심층 분석
  4. Exporting and checking a small PyTorch model
  5. 실제 구현
  6. ONNX와 모델 상호 운용성의 미래
  7. 실천에 옮기기
  8. 출처 및 추가 자료
  9. 계속 탐색하세요
  10. 자주 묻는 질문

개요

It lets a model trained in one framework, such as PyTorch, be saved as a portable computation graph and run by a different engine on servers, phones, browsers or specialized chips.

주요 시사점

  1. ONNX is an open format that stores a trained model as a graph of standardized operators plus its weights, so different engines can run it.
  2. Facebook and Microsoft announced ONNX in September 2017, and it became a Linux Foundation AI graduate project in November 2019.
  3. Every ONNX model declares versioned operator sets, and any change to an operator's behavior must ship as a new operator version.
  4. ONNX Runtime splits a model across hardware execution providers such as CUDA, TensorRT, DirectML, OpenVINO and QNN, with CPU as the fallback.
  5. Models larger than the 2 GB Protocol Buffers limit store their weights in external data files next to the graph.

심층 분석

ONNX, the Open Neural Network Exchange, is a shared language for describing trained machine learning models. A model in ONNX form is a computation graph: a list of operations, such as matrix multiplication, convolution or softmax, connected by the tensors (multi-dimensional arrays of numbers) that flow between them, together with the learned weights. Because the graph uses a standard set of operators with precisely defined behavior, any software that implements those operators can run the model, regardless of which framework trained it. This separation of training from deployment is what model interoperability means in practice.

The format is defined by the ONNX intermediate representation (IR) specification and stored as a Protocol Buffers file, a compact binary encoding developed by Google. The top-level object is a model, which records the IR version, the operator sets it relies on, metadata such as the producing tool, and the graph. The graph holds nodes, each naming an operator type, its inputs, its outputs and fixed attributes such as a convolution's kernel size. Initializers store constant tensors, usually the weights. Inputs and outputs are declared with a data type and shape, and a dimension can be a symbolic name such as batch_size instead of a fixed number. The specification requires nodes to be listed in topological order, so every value is produced before it is used, with no cycles, and every output name must be unique within a graph.

Versioning is the part of ONNX that makes long-term compatibility possible. Operators are grouped into operator sets, or opsets, identified by a domain and an integer version. The default domain covers neural network operators, and ONNX-ML adds operators for classical, non-neural machine learning algorithms. Every model must declare the opsets it uses. Under the versioning rules, any change to an operator's inputs, outputs, attributes, supported types or meaning is a breaking change that must appear as a new operator version in a new opset. A runtime that supports opset 17 therefore knows exactly what every operator in an opset 17 model does. The ONNX versioning table runs from ONNX 1.0, with IR version 3 and opset 1, to ONNX 1.23.0, with IR version 14 and opset 28.

ONNX began inside Facebook's PyTorch team under the name Toffee and was renamed and announced jointly by Facebook and Microsoft in September 2017. IBM, Huawei, Intel, AMD, Arm and Qualcomm later announced support, and in October 2017 Microsoft said it would bring its Cognitive Toolkit and Project Brainwave into the effort. On November 14, 2019, the format became a graduate project of the Linux Foundation's LF AI Foundation, which TechCrunch described as a step toward vendor-neutral governance, with more than 30 companies contributing code. The license moved from MIT to Apache 2.0. Only the format joined the foundation; ONNX Runtime, the inference engine Microsoft had open-sourced about a year earlier, stayed a separate Microsoft-led project.

In a typical workflow, a developer trains a model in PyTorch and calls torch.onnx.export. Since PyTorch 2.9, the default exporter is built on torch.export, which traces the model ahead of time into a graph of basic operations, removes most Python control flow and records shape constraints. The developer marks which dimensions may vary, such as batch size or text length, chooses an opset, and can ask the exporter to verify the result with ONNX Runtime. The resulting .onnx file is then loaded by a runtime. ONNX Runtime splits the graph among execution providers, plug-ins for specific hardware: each provider in a priority list claims the nodes it can run, and the default CPU provider runs whatever is left. Higher-level tools wrap this process; Hugging Face Optimum can export a Transformers model in one command, validate the outputs against the original, and split encoder-decoder models into separate files so the encoder runs once while the decoder loops.

ONNX is not the only way to move models around. Framework-native formats, such as PyTorch's saved programs, keep every framework feature but tie deployment to that framework's runtime. Vendor formats, such as compiled TensorRT engines, are faster on one family of hardware but are not portable. ONNX sits between them: broadly supported, with a stable specification, but limited to what its operators can express. Weight-only formats, which store tensors but not the computation graph, solve a different problem: sharing parameters for use in a framework that already knows the architecture.

The limits are real. Not every framework operation has an ONNX equivalent, so custom layers may need custom operators that only some runtimes support. Dynamic behavior is hard to capture: PyTorch's documentation notes that loops are not exported directly and points to explicit control-flow operators instead. If dynamic dimensions are not declared, the exporter freezes the example input's shapes, so a text model may only accept one length. Protocol Buffers files are limited to 2 GB, so larger models store their weights as external data files beside the graph. Optimizations can reduce portability: Optimum warns that some ONNX Runtime-specific graph optimizations produce files that OpenVINO or TensorRT cannot run. Small numerical differences between runtimes are normal, which is why exporters compare outputs within a tolerance instead of expecting exact matches.

In practice ONNX costs nothing to use: the format, the onnx Python package and ONNX Runtime are open source. The real costs are engineering time to make a model export cleanly, testing on each target runtime, and keeping the opset version aligned with what the deployment engine supports. ONNX Runtime offers APIs for Python, C#, JavaScript, Java and C++, among others, and runs on Linux, Windows, macOS, iOS, Android and in web browsers.

04실제 사례

Exporting and checking a small PyTorch model

  1. Build or load a small PyTorch image classifier and put it in evaluation mode.

  2. Call torch.onnx.export with an example input of shape 1 by 3 by 224 by 224, and declare the batch dimension as dynamic using dynamic_shapes.

  3. Open the saved file with the onnx Python package and run its checker to confirm the graph is valid.

  4. Load the file in ONNX Runtime with the provider list CUDAExecutionProvider then CPUExecutionProvider.

  5. Feed the same random input with a batch of 4 to both PyTorch and ONNX Runtime.

  6. Compare outputs element by element and confirm the largest absolute difference is below a small tolerance such as 0.0001.

그것이 보여주는 것

The learner has a portable .onnx file that accepts any batch size and produces the same predictions as the PyTorch model within a numerical tolerance. If the batch of 4 fails, the dynamic dimension was not declared, which is the most common export mistake.

실제 구현

Microsoft products: the ONNX Runtime website says the engine powers AI features in Windows, Office, Azure Cognitive Services and Bing, running models that were exported to the ONNX format.

Hugging Face models: the command optimum-cli export onnx --model gpt2 gpt2_onnx/ exports a Transformers model, then checks that the ONNX outputs match the original within a tolerance such as 0.0001.

Hardware portability: one ONNX file can run on Nvidia GPUs through the CUDA or TensorRT execution providers, on Windows GPUs through DirectML, on Intel hardware through OpenVINO, or on Qualcomm chips through QNN.

In-browser and mobile inference: ONNX Runtime Web runs exported models inside a web browser, and ONNX Runtime Mobile targets Android and iOS apps, so no Python installation is needed on the device.

Framework handoff: Hugging Face's documentation gives the example of exporting a model trained in PyTorch to ONNX and then importing it into Nvidia TensorRT or Intel OpenVINO for optimized serving.

ONNX와 모델 상호 운용성의 미래

The ONNX specification keeps expanding to cover newer workloads. The IR documentation records multi-device configuration support added in IR version 11, and the type list now includes 8-bit, 6-bit, 4-bit and 2-bit numeric formats used for compressed models, reflecting the shift toward running quantized language models on local hardware. The versioning table shows opset 28 shipping with ONNX 1.23.0. On the tooling side, PyTorch moved its default exporter to the torch.export-based path in version 2.9, deprecated older options such as dynamic_axes for that path, and removed the fallback to the older exporter in version 2.11. That transition aims to make exports more faithful to the original program, but models that rely on Python-level control flow still need rewriting with explicit control-flow operators. Open questions include how well a static graph format can represent large generative models whose inference involves caches, variable-length loops and sampling, which tools such as onnxruntime-genai and Optimum handle partly outside the graph, and how to keep hardware-specific optimizations from fragmenting a format whose value depends on portability. The number of execution providers listed by ONNX Runtime, spanning CPUs, GPUs, NPUs and browsers, suggests that hardware vendors still treat ONNX as a common entry point, though support levels vary and several providers are marked as previews.

실천에 옮기기

왜 중요한가요?

  • 비용 및 예산. 아키텍처 결정은 수년 동안 성능과 운영 비용을 결정합니다.
  • 더 명확한 결정들. 기술 교육은 팀이 최신 스택뿐만 아니라 올바른 스택을 선택하는 데 도움이 됩니다.
  • 품질 관리. 더 나은 엔지니어링 선택은 생산 시 신뢰성 사고를 줄입니다.

조심하세요

  • 하나의 벤치마크를 최적화하면 더 광범위한 시스템 약점을 숨길 수 있습니다.
  • 인프라 및 유지 관리 비용은 종종 과소평가됩니다.
  • 시스템이 더욱 복잡해짐에 따라 보안 및 관찰 가능성의 격차가 커질 수 있습니다.

다음 단계

  1. 구현하기 전에 지연 시간, 품질, 비용 목표를 정의하세요.
  2. 현실적인 로드 및 데이터 조건에서 벤치마킹합니다.
  3. 오류, 드리프트 및 사용자 영향에 대한 계측기 모니터링.
  4. 확장하기 전에 롤백 및 사고 대응 경로를 준비하세요.

출처 및 추가 자료

  1. ONNX project, GitHubOpen Neural Network Exchange Intermediate Representation (ONNX IR) Specification
  2. ONNX project, GitHubONNX Versioning
  3. TechCrunchThe ONNX format becomes the newest Linux Foundation project
  4. ONNX Runtime documentationONNX Runtime Execution Providers
  5. MicrosoftONNX Runtime
  6. PyTorch documentationtorch.onnx
  7. Hugging FaceExport a model to ONNX with optimum.exporters.onnx
  8. WikipediaOpen Neural Network Exchange

계속 탐색하세요

무료 뉴스레터

일일 AI 브리핑 받기

매주 평일 아침마다 3개의 검증된 AI 스토리를 일반 영어로 작성합니다. 무료이며, 광고 없음.

매주 평일마다 한 번 이메일을 받습니다. 한 번 클릭으로 구독 해지. 주소를 판매하거나 공유하지 않습니다.

자신을 테스트해 보세요

Take the ONNX and Model Interoperability quiz

모든 답변에 즉각적인 피드백과, 과정을 통과하면 검증 가능한 ID가 있는 공유 가능한 인증서를 제공합니다.

퀴즈 시작

무료 AI 교육을 지원합니다. AI Understanding는 501(c)(3) 비영리 단체입니다 — 광고 없음, 유료 장벽 없음, 영원히. 기부하기

자주 묻는 질문

What is ONNX and Model Interoperability?

ONNX (Open Neural Network Exchange) is an open file format and operator standard for machine learning models, announced by Facebook and Microsoft in September 2017 and now governed by the Linux Foundation. It lets a model trained in one framework, such as PyTorch, be saved as a portable computation graph and run by a different engine on servers, phones, browsers or specialized chips.

ONNX는 주로 어떤 핵심 문제를 해결합니까?

ONNX는 공유 형식을 정의하므로 한 프레임워크에서 훈련된 모델을 다시 작성하지 않고도 다른 환경에 배포할 수 있습니다.

ONNX 파일은 모델을 어떻게 표현합니까?

ONNX 모델은 노드가 텐서로 연결된 표준화된 연산자(예: Conv, MatMul, Relu)인 계산 그래프입니다.

What does the acronym ONNX stand for?

ONNX is short for Open Neural Network Exchange, the open format and ecosystem for representing machine-learning models.

ONNX Runtime에서 '실행 공급자'란 무엇입니까?

실행 공급자는 ONNX Runtime이 각 연산자가 가장 잘 지원하는 연산자를 실행하는 데 사용하는 플러그형 백엔드(CPU, CUDA, TensorRT 등)입니다.

ONNX 모델의 'opset'(연산자 집합) 버전은 무엇을 정의합니까?

opset 버전은 모델이 의존하는 연산자의 표준화된 집합과 버전을 지정하여 호환 가능한 런타임이 이를 올바르게 해석하도록 합니다.