0Pricing
Deep Learning Academy · Урок

Экспортируйте в ONNX

Запускайте модель в разных средах выполнения

«Экспортируйте в ONNX» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

One Model, Many Runtimes

Sometimes your model must run somewhere PyTorch is not installed. ONNX is a shared format that lets one model run across many engines. 🌐

What ONNX Stands For

ONNX means Open Neural Network Exchange. It is a vendor-neutral file format that describes your model as a graph of standard operations.

Why Teams Love ONNX

With ONNX you train in PyTorch but deploy on ONNX Runtime, mobile, or the browser, without rewriting the model for each platform.

Export in One Call

You export by giving PyTorch the model and a sample input. The exporter traces the run and writes a portable graph to disk.

import torch
torch.onnx.export(model, sample_input, 'model.onnx')

The Dummy Input Shapes the Graph

That sample tensor must match your real input shape and dtype, because the exporter records the operations the data triggers.

sample_input = torch.randn(1, 3, 224, 224)

Name Your Inputs and Outputs

Give clear input and output names so the serving code can bind data by name instead of guessing positions.

torch.onnx.export(model, x, 'm.onnx',
  input_names=['image'], output_names=['logits'])

Allow Flexible Batch Sizes

By default the batch size is fixed. Mark it as a dynamic axis so the exported model accepts any number of inputs at once.

dynamic_axes={'image': {0: 'batch'}}

Always Check Your Export

Load the file with the onnx library and run the built-in checker to confirm the graph is valid before you ship it. ✅

import onnx
onnx.checker.check_model(onnx.load('model.onnx'))

Run It with ONNX Runtime

ONNX Runtime is a fast engine that executes the exported model on CPU or GPU, often quicker than plain Python inference.

import onnxruntime as ort
session = ort.InferenceSession('model.onnx')

Confirm the Numbers Match

Run the same input through PyTorch and ONNX Runtime and compare outputs. They should match closely, proving the export is faithful.

Mind the Opset Version

Each export targets an opset version, the set of supported operations. Pick a version your target runtime understands to avoid errors.

torch.onnx.export(model, x, 'm.onnx', opset_version=17)

Quick Check

You want a fixed batch to instead accept any size. What do you set?

Recap: Portable Across Runtimes

You exported a PyTorch model to ONNX with a sample input, named axes, validated it, and ran it on ONNX Runtime anywhere. 🎉

Часто задаваемые вопросы

Урок «Экспортируйте в ONNX» бесплатный?

Да — полный текст урока «Экспортируйте в ONNX» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.

Чему я научусь в уроке «Экспортируйте в ONNX»?

Запускайте модель в разных средах выполнения Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Deep Learning Academy?

Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Экспортируйте в ONNX»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Deep Learning Academy?

Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. TorchScript и torch.compile
  2. Экспортируйте в ONNX
  3. Квантизация для компактных и быстрых моделей
  4. Обслуживайте модель с FastAPI
← Назад к Deep Learning Academy