Generated banner for Matlab Deploy AI Model
Generated logo for Matlab Deploy AI Model

Matlab Deploy AI Model

MathWorksOfficialCreated by MathWorks

  • Skill
  • Tool integration
  • Software development
  • BSD-2-Clause
  • Low risk

From the author

Generate C/C++ or CUDA code from an AI model (PyTorch, LiteRT) using MATLAB Coder or GPU Coder. Use when the user wants to integrate an AI model into an application with code generation as the end goal — generating MEX, CUDA MEX, static library, dynamic library, or executable — or using the model in Simulink for simulation and code generation. Covers PyTorch ExportedProgram (.pt2) via loadPyTorchExportedProgram and LiteRT (.tflite) via loadLiteRTModel (R2026a+). Keywords: PyTorch, torch, .pt2, ExportedProgram, loadPyTorchExportedProgram, invoke, codegen, MEX, CUDA, GPU, C, C++, deploy, AI model, deep learning model, LiteRT, TFLite, TensorFlow Lite, Simulink, slbuild, PyTorch ExportedProgram block, MATLAB Function block, dlosslib, loadLiteRTModel.
— the description by MathWorks

From the skill’s files

Taken from the skill’s own files (its description, section headings and stated usage). Not an AutoGineer summary, and not written by the author as one.

Generate C/C++ or CUDA code from an AI model (PyTorch, LiteRT) using MATLAB Coder or GPU Coder. Use when the user wants to integrate an AI model into an application with code generation as the end goal — generating MEX, CUDA MEX, static library, dynamic library, or executable — or using the model in Simulink for simulation and code generation. Covers PyTorch ExportedProgram (.pt2) via loadPyTorchExportedProgram and LiteRT (.tflite) via loadLiteRTModel (R2026a+). Keywords: PyTorch, torch, .pt2, ExportedProgram, loadPyTorchExportedProgram, invoke, codegen, MEX, CUDA, GPU, C, C++, deploy, AI model, deep learning model, LiteRT, TFLite, TensorFlow Lite, Simulink, slbuild, PyTorch ExportedProgram block, MATLAB Function block, dlosslib, loadLiteRTModel. Generate deployable C/C++ or CUDA code from an AI model using MATLAB Coder or GPU Coder. The workflow follows a common pattern regardless of…

What it does

  • When to Use
  • When NOT to Use
  • Supported Frameworks
  • Generic Workflow
  • Key Functions
  • Conventions

When to use it

  • Use when the user wants to integrate an AI model into an application with code generation as the end goal — generating MEX, CUDA MEX, static library, dynamic library, or executable — or using the…
  • User wants to generate C/C++/CUDA code from an AI model (PyTorch, LiteRT)
  • User has a model file (.pt2, .tflite) and wants to load it into MATLAB
  • User wants MEX acceleration for an AI model
  • User wants to generate CUDA code or GPU-accelerated MEX from an AI model
  • User wants to deploy an AI model to hardware

Advantages

The skill’s files do not state this.

Usage examples

The skill’s files do not state this.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/matlab/matlab-deploy-ai-model/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip matlab-deploy-ai-model.zip -d .agents/skills

Documentation by MathWorks

Generate C/C++/CUDA Code from an AI Model

Generate deployable C/C++ or CUDA code from an AI model using MATLAB Coder or GPU Coder. The workflow follows a common pattern regardless of model framework: load, inspect, write entry-point, generate MEX, verify, then generate production code.

When to Use

  • User wants to generate C/C++/CUDA code from an AI model (PyTorch, LiteRT)

  • User has a model file (.pt2, .tflite) and wants to load it into MATLAB

  • User wants MEX acceleration for an AI model

  • User wants to generate CUDA code or GPU-accelerated MEX from an AI model

  • User wants to deploy an AI model to hardware

  • User wants to use a PyTorch or LiteRT model in Simulink (simulation or code generation)

  • User wants to verify AI model numerics between the source framework and MATLAB

When NOT to Use

  • General MATLAB Coder usage (codegen syntax, config tuning, writing codegen-ready code)

  • Editable dlnetwork for Deep Learning Toolbox workflows (quantization, compression, transfer learning) — use importNetworkFromPyTorch (PyTorch), importNetworkFromTensorFlow (SavedModel), or importNetworkFromKeras (.keras/.h5) which return a dlnetwork. For deployment of an editable dlnetwork with model compression (INT8 quantization via dlquantizer, pruning, projection) or exportNetworkToSimulink workflows — use matlab-deploy-embedded-ai (Pattern 1).

  • Training or fine-tuning — this skill is for inference code generation only

Supported Frameworks

FrameworkModel formatLoad functionStatus
PyTorch.pt2loadPyTorchExportedProgramSupported (R2026a+)
LiteRT / TFLite.tfliteloadLiteRTModelSupported (R2026a+)

For PyTorch-specific details (API routing, entry-point pattern, export workflow, data layout, common mistakes): see references/pytorch-workflow.md.

For LiteRT-specific details (API routing, entry-point pattern, variable-size inputs, Simulink integration, conventions): see references/litert-workflow.md. For converting TensorFlow/Keras/.h5 to .tflite: see references/tensorflow-to-litert-conversion.md.

Generic Workflow

The code generation workflow follows the same steps for any framework:

1. Load and Inspect

Load the model and check its input/output specifications to determine expected shapes and types.

2. Write Entry-Point Function

Create a codegen-compatible entry-point function that:

  • Loads the model from a file path

  • Runs inference on an input

  • Returns the output

The model file path must be wrapped with coder.Constant so it's known at compile time.

3. Verify Numerics

Compare MATLAB inference output against the source framework to confirm correct loading. Use the same input data in both environments and compare with tolerance.

4. Generate MEX (First!)

Always generate MEX before lib/exe to verify on the host machine:

CPU MEX:

cfg = coder.config("mex");
codegen -config cfg -args {coder.Constant("model_file"), input} entryPoint

CUDA MEX (GPU acceleration):

cfg = coder.gpuConfig("mex");
codegen -config cfg -args {coder.Constant("model_file"), input} entryPoint

For CPU MEX SIMD acceleration (SIMDAcceleration = 'Full' for AVX2 on Intel/AMD), see the matlab-generate-code skill. For the DNN- inference-specific MEX AVX2 ceiling, see references/dnn-codegen-options.md.

5. Verify MEX Output

Compare MEX output against MATLAB reference using matlab.unittest with tolerance:

refOut = entryPoint("model_file", input);
mexOut = entryPoint_mex("model_file", input);
testCase = matlab.unittest.TestCase.forInteractiveUse;
testCase.verifyThat(mexOut, matlab.unittest.constraints.IsEqualTo(refOut, ...
    'Within', matlab.unittest.constraints.AbsoluteTolerance(single(1e-5))));
6. Generate Library/Executable

Once MEX is verified, generate production code:

cfgLib = coder.config("lib");
cfgLib.TargetLang = "C++";  % set to "C++" for C++ output; default is "C"
codegen -config cfgLib -args {coder.Constant("model_file"), input} entryPoint

For DLL: coder.config("dll"). For executable: coder.config("exe").

CUDA variants: Replace coder.config with coder.gpuConfig.

Performance tuning:

  • Generic knobs (SIMD instruction sets, reduction-loop vectorization, multithreaded loops): see the matlab-generate-code skill.

  • MATLAB Coder ↔ Simulink Coder property naming duality and slbuild set_param patterns: see the matlab-deploy-embedded-code skill.

  • DNN-inference-specific knobs (DLTargetLibrary / DeepLearningConfig to disable third-party DL libraries, LargeConstantGeneration to serialize weights to data files): see references/dnn-codegen-options.md.

For Simulink integration, use the dedicated PyTorch ExportedProgram block from dlosslib — set ModelFilePath to the .pt2 file and it auto-detects input/output shapes. No entry-point function or coder.Constant needed.

Pre/post-processing can be done with Simulink blocks around the dedicated block. If you need everything in a single block, use a MATLAB Function block with loadPyTorchExportedProgram + invoke (same pattern as the entry-point, but the model path is a string literal — no coder.Constant).

Both paths support slbuild code generation (requires fixed-step solver + ERT or GRT target). See references/simulink-workflow.md for full details.

8. Deploy to Hardware (Optional — requires Embedded Coder)

For embedded deployment, use the same entry-point function with an Embedded Coder configuration. See the matlab-deploy-embedded-code skill for ERT config, hardware settings, PIL/SIL verification, and target-specific options. Ask the user to install the skill if it is not installed

Key Functions

FunctionPurposePackageSince
coder.ConstantMake argument a compile-time constantMATLAB CoderR2011a
coder.gpuConfigCreate GPU (CUDA) code generation configGPU CoderR2017b
codegenGenerate codeMATLAB CoderR2011a
loadPyTorchExportedProgramLoad .pt2 into MATLABMATLAB Coder Support Package for PyTorch and LiteRT ModelsR2026a
loadLiteRTModelLoad .tflite into MATLABMATLAB Coder Support Package for PyTorch and LiteRT ModelsR2026a

Conventions

  • Always check the model's input specifications for correct input shape and type

  • Always generate MEX first, verify, then proceed to lib/exe

  • Always use coder.Constant for the model file path argument

  • Input data is typically single-precision (check model input specs to confirm)

  • Do NOT use importNetworkFromPyTorch, importNetworkFromTensorFlow, or importNetworkFromKeras in this skill — they return a dlnetwork on a different path. If the user needs a dlnetwork for quantization, projection, pruning, or exportNetworkToSimulink before code generation, route to matlab-deploy-embedded-ai instead

References

  • references/pytorch-workflow.md — Full PyTorch-specific workflow: API routing, entry-point pattern, export guidance, common mistakes, and conventions. Consult for any PyTorch/.pt2 model code generation task. Links to deeper PyTorch references (API signatures, data layout, numeric verification, supported models).

  • references/export-pytorch-models.md — Exporting an eager-mode PyTorch model to .pt2 with torch.export (upstream of loading). Consult when the user has a PyTorch model but no .pt2 file yet, or hits torch.export SerializeError / kwarg-mismatch errors. Links to pytorch-export-patterns.md (per-source templates) and pytorch-export-gotchas.md (torch 2.11 serialization fixes).

  • references/simulink-workflow.md — Simulink integration: dedicated PyTorch ExportedProgram block (Path A) vs MATLAB Function block (Path B), block mask parameters, code generation config, and key differences from command-line codegen.

  • references/litert-workflow.md — Full LiteRT-specific workflow: API routing (loadLiteRTModel → inputSpecifications → invoke), entry-point pattern, variable-size input handling, Simulink integration, and conventions. Consult for any LiteRT/.tflite model code generation task.

  • references/tensorflow-to-litert-conversion.md — Converting TensorFlow SavedModel/Keras/.h5 to .tflite via the Python tf.lite.TFLiteConverter API. Consult when the user has a TensorFlow model but no .tflite file yet.

  • references/litert-numeric-verification.md — Verifying MEX numerics against MATLAB reference for LiteRT models (tolerance guidance, common mismatches).

  • references/codegen-workflow.md — Shared code generation steps for both PyTorch and LiteRT: MEX generation, MEX verification, library/executable targets, coder.Constant usage, and coder.DeepLearningConfig notes.

  • references/dnn-codegen-options.md — DNN-INFERENCE-SPECIFIC codegen options: DLTargetLibrary / DeepLearningConfig('none') for the plain-C DL path, LargeConstantGeneration for serializing large DNN weights to data files, and MEX SIMD ceiling in a DNN-inference context. Read this when the generic file's knobs need DNN-specific framing (e.g., "the MEX SIMD cap matters because inference is the target").

See Also

  • matlab-generate-code — Generic MATLAB Coder tuning (SIMD instruction sets, OpenMP multi-threading, reduction-loop vectorization). Consult for performance options not specific to DNN inference.

  • matlab-deploy-embedded-ai — dlnetwork-based codegen with model compression (quantization, pruning, projection) and exportNetworkToSimulink workflows (Pattern 1). Use it when the source is an editable dlnetwork in MATLAB rather than a .pt2 / .tflite file.

  • matlab-optimize-gpu-codegen — CUDA-target codegen tuning (coder.gpuConfig, kernel fusion, memory-hierarchy options) when the deployment target is an NVIDIA GPU rather than CPU or embedded hardware.


Copyright 2026 The MathWorks, Inc.


Files

references/dnn-codegen-options.md

DNN-Specific Codegen Options

Options that only apply to deep-learning inference codegen. For generic codegen tuning (SIMD instruction sets, OpenMP multi-threading, MEX SIMD, OptimizeReductions, the MATLAB Coder ↔ Simulink Coder naming duality), see the matlab-generate-code skill.

When to read this file: you're generating code from a .pt2 or .tflite model and want to (a) route around third-party DL libraries, (b) serialize weights to data files, or (c) understand DNN-inference specifics of SIMDAcceleration on MEX.

1. Deep learning target library — different name per API

To use the plain-C codegen path (no third-party DL library backends like cuDNN, MKL-DNN), disable the DL library backend:

% MATLAB Coder
cfg.DeepLearningConfig = coder.DeepLearningConfig("none");

% Simulink Coder — set BOTH. SimDLTargetLibrary controls simulation
% (normal-mode / sim()); DLTargetLibrary controls slbuild-time code
% generation. They are independent parameters — setting one does NOT set
% the other, so setting only DLTargetLibrary leaves simulation still
% routing inference through the DL library.
set_param(modelName, "SimDLTargetLibrary", "none");   % simulation
set_param(modelName, "DLTargetLibrary",    "none");   % code generation

Setting a target library routes inference through the library at runtime and bypasses InstructionSetExtensions, OpenMP, and LargeConstantGeneration — those parameters only affect generated source code, not library calls. For plain-C DNN inference on host CPU or embedded targets, "none" is the correct choice; the perf knobs from the matlab-generate-code skill (SIMD, OpenMP, OptimizeReductions) then take effect on the generated inference code.

2. Large DNN constants (weights) — LargeConstantGeneration (R2024a+)

Model weight constants can either be embedded directly in generated source ("KeepInSourceFiles") or written to binary data files that the generated code loads at run time ("WriteOnlyDNNConstantsToDataFiles", for constants above LargeConstantThreshold, default 131072 bytes). Embedding blows up compile time and binary size for larger models but has no filesystem dependency; the data-files path is smaller and faster to compile but requires the deployment target to have a filesystem.

Since R2024a, defaults vary by codegen path — only ert.tlc defaults to the inline path:

PathDefault
MATLAB Coder coder.config("lib") (ecoder or not)"WriteOnlyDNNConstantsToDataFiles"
Simulink grt.tlc"WriteOnlyDNNConstantsToDataFiles"
Simulink ert.tlc"KeepInSourceFiles" — must flip to "WriteOnlyDNNConstantsToDataFiles" for the data-files path

Same property name on both APIs. Requires MATLAB R2024a or later — the property does not exist in earlier releases.

% MATLAB Coder (requires R2024a+)
cfg.LargeConstantGeneration = "WriteOnlyDNNConstantsToDataFiles";
% cfg.LargeConstantThreshold = 131072;   % optional (bytes)

% Simulink Coder (requires R2024a+)
set_param(modelName, "MATLABDynamicMemAlloc", "on");
set_param(modelName, "LargeConstantGeneration", "WriteOnlyDNNConstantsToDataFiles");

The generated loader needs dynamic memory allocation at runtime. Defaults vary by codegen path:

PathPropertyDefault
MATLAB Coder coder.config("lib") (ecoder or not)EnableDynamicMemoryAllocation (boolean)true
Simulink grt.tlcMATLABDynamicMemAlloc ("on"/"off")"on"
Simulink ert.tlcMATLABDynamicMemAlloc ("on"/"off")"off" — must flip to "on"

ert.tlc (Embedded Coder) is the one where the flip is genuinely required — a fresh model that switches to ert.tlc gets MATLABDynamicMemAlloc = "off". On the MATLAB Coder side use cfg.EnableDynamicMemoryAllocation, NOT cfg.MATLABDynamicMemAlloc (that's the Simulink set_param name and throws an unrecognized-property error on coder.EmbeddedCodeConfig).

Notes:

  • Applies only to code that does NOT depend on third-party deep learning libraries (the loadPyTorchExportedProgram / loadLiteRTModel codegen path qualifies).

  • Non-DNN constants are always inlined in source, regardless of size.

  • The binary data files land in the code generation folder. If you relocate them at deploy time, set the CODER_DATA_PATH environment variable to the new location before running the generated code.

  • The deployment target must have a filesystem so the generated code can read the data files at runtime — not suitable for bare-metal MCU targets. For bare-metal, use "KeepInSourceFiles" (already the default on ert.tlc; must be set explicitly on MATLAB Coder and grt.tlc) (see matlab-deploy-embedded-code).

3. MEX SIMD ceiling (DNN-inference context)

Generic SIMDAcceleration values are documented in the matlab-generate-code skill. The DNN-inference-specific note:

MEX SIMD is capped at AVX2 via "Full" — there is no AVX512 option for MEX, even on AVX512-capable hosts. For AI model MEX inference where the user wants maximum SIMD throughput, "Full" is the ceiling. If a user needs AVX512 for their DNN inference, ask whether generating a library (coder.config("lib")) instead of a MEX is acceptable — MEX and lib serve different purposes (host-side iteration vs. deployable artifact), so don't switch on their behalf.

DNN-Inference Quick Recipe

Plain-C DNN inference with maximum vectorization + multi-threading (Intel/AMD host, Embedded Coder available):

Simulink:

set_param(modelName, "SystemTargetFile", "ert.tlc");
set_param(modelName, "ProdHWDeviceType", "Intel->x86-64 (Windows64)");
% set_param(modelName, "ProdHWDeviceType", "Intel->x86-64 (Linux 64)");  % Linux host
set_param(modelName, "InstructionSetExtensions", "AVX512F");            % see generic ref for SIMD ladder
set_param(modelName, "OptimizeReductions", "on");
set_param(modelName, "MultiThreadedLoops", "on");
set_param(modelName, "DLTargetLibrary", "none");                        % plain-C path
% For large models, serialize weights to data files:
set_param(modelName, "MATLABDynamicMemAlloc", "on");
set_param(modelName, "LargeConstantGeneration", "WriteOnlyDNNConstantsToDataFiles");

MATLAB Coder:

cfg = coder.config("lib", "ecoder", true);
cfg.HardwareImplementation.ProdHWDeviceType = "Intel->x86-64 (Windows64)";
% cfg.HardwareImplementation.ProdHWDeviceType = "Intel->x86-64 (Linux 64)";  % Linux host
cfg.InstructionSetExtensions = "AVX512F";
cfg.OptimizeReductions = "on";
cfg.EnableOpenMP = true;
cfg.DeepLearningConfig = coder.DeepLearningConfig("none");              % plain-C path
% EnableDynamicMemoryAllocation is true by default on ecoder configs.
cfg.LargeConstantGeneration = "WriteOnlyDNNConstantsToDataFiles";

For target-hardware-specific config (device selection, EnableDynamicMemoryAllocation, StackUsageMax, CodeReplacementLibrary catalog, PIL/SIL, hardware boards, target-connection), see the matlab-deploy-embedded-code skill.


Copyright 2026 The MathWorks, Inc.


Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
MathWorks
Publisher
MathWorks (Official)
Source
matlab/matlab-agentic-toolkit · skills-catalog/code-generation/matlab-deploy-ai-model · commit 2a7f215
Licence
BSD 2-Clause License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-deploy-ai-model.zip