Generated banner for Matlab Deploy Embedded AI
Generated logo for Matlab Deploy Embedded AI

Matlab Deploy Embedded AI

MathWorksOfficialCreated by MathWorks

  • Skill
  • Workflow
  • Software development
  • BSD-2-Clause
  • No issues found

From the author

Deploy AI models to embedded hardware using MathWorks tools (MATLAB, Simulink, Embedded Coder). Covers two workflow patterns: (1) MathWorks-native or imported models rebuilt as dlnetwork for lean hardware, (2) direct C/C++ code generation from PyTorch and LiteRT models. Both patterns support all targets (Cortex-M/A/R, x86, GPU). Trigger when: user wants to deploy AI to embedded targets; generate C/CUDA from neural networks; compress AI models for MCU; integrate AI in Simulink for system-level simulation; import PyTorch/ONNX/TensorFlow models for embedded deployment; optimize AI for resource-constrained hardware; or use loadPyTorchExportedProgram, loadLiteRTModel, importNetworkFromPyTorch, importNetworkFromONNX, importNetworkFromTensorFlow, importNetworkFromKeras, dlquantizer, exportNetworkToSimulink, or Embedded Coder with AI models.
— the description by MathWorks

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach for deploying AI models to embedded targets such as Cortex-M, Cortex-A/R, x86, and GPU. It supports two primary deployment patterns: rebuilding models as native dlnetwork objects for optimized hardware deployment, or direct C/C++ code generation from PyTorch and LiteRT models. The skill covers the entire lifecycle, including model import, compression (quantization, pruning, projection), system-level simulation in Simulink, and code generation using MATLAB Coder and Embedded Coder.

What it does

  • Imports and converts external AI models (PyTorch, ONNX, TensorFlow, Keras) into MATLAB-native formats.
  • Optimizes models for resource-constrained hardware via quantization, pruning, and projection.
  • Integrates AI inference into Simulink models for closed-loop system simulation.
  • Generates optimized C/C++ or CUDA code for various embedded hardware targets.
  • Validates numerical equivalence between original models and generated code.
  • Provides a decision framework to select the optimal deployment pattern based on hardware and performance needs.

When to use it

  • When you need to deploy a trained neural network to embedded hardware.
  • When you must compress an AI model to fit within memory or latency constraints of an MCU.
  • When you need to integrate AI inference into a Simulink system model.
  • When you need to generate C/C++ code from PyTorch or LiteRT models for production deployment.
  • When you require verification of numerical accuracy across model transformations.

Advantages

  • Supports a wide range of embedded targets including ARM Cortex and GPU architectures.
  • Enables system-level verification through Simulink integration before hardware deployment.
  • Provides advanced compression techniques to optimize performance on resource-constrained devices.
  • Ensures reproducibility through script-based execution and numerical validation steps.
  • Offers flexible deployment paths for both native MATLAB models and external framework models.

Usage examples

“How do I deploy my trained MATLAB neural network to an ARM Cortex-M processor?”
The agent will initiate the Project Discovery process to confirm the target hardware and model type, then guide you through the Pattern 1 workflow, including potential compression and code generation steps.
“I have a PyTorch model and need to generate C++ code for an x86 target. Which pattern should I use?”
The agent will identify this as a Pattern 2 scenario, confirm the requirements, and walk you through the direct code generation workflow using the PyTorch support package.
“Can you help me quantize my imported ONNX model for an embedded device?”
The agent will guide you through importing the model as a dlnetwork, performing quantization using the dlquantizer, and validating the accuracy before generating the final code.
“I need to verify if my model is compatible with code generation.”
The agent will run the analysis function to check for unsupported layers and provide a report on compatibility for your specific target library.

Install

  1. Download the skill as a ZIP:

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

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

Documentation by MathWorks

Embedded AI for Engineered Systems

Deploy AI models to embedded hardware using MATLAB® and Simulink®. This skill is written specifically for MATLAB R2026a and uses APIs, functions, and workflows introduced in that release. It covers the complete lifecycle: model creation or import, verification, compression, system-level simulation, and code generation for resource-constrained targets.

Requires MATLAB R2026a or newer. Core toolboxes: Deep Learning Toolbox, Statistics and Machine Learning Toolbox, MATLAB Coder, Embedded Coder, Simulink, and Fixed-Point Designer. Workflow-specific support packages are checked during Environment Discovery. The MATLAB and Simulink Agentic Toolkits must be available so the agent can drive a live MATLAB and Simulink session through MCP tools.

When to Use

  • Deploying a trained neural network (MATLAB-native or imported) to embedded hardware

  • Generating C or CUDA code from a deep learning model for ARM Cortex-M/A/R, x86, or GPU targets

  • Deploying imported PyTorch, ONNX, TensorFlow, or LiteRT models to embedded targets (import step handled by /matlab-import-external-ai-model)

  • Compressing AI models (quantization, pruning, projection) to fit resource-constrained hardware

  • Integrating AI inference into a Simulink system model for closed-loop simulation before code generation

  • Using loadPyTorchExportedProgram, importNetworkFromPyTorch, importNetworkFromONNX, importNetworkFromTensorFlow, dlquantizer, exportNetworkToSimulink, or Embedded Coder with AI models

  • Choosing between MathWorks-native code generation and direct PyTorch/LiteRT code generation

When NOT to Use

  • Training a model purely for research with no deployment target — use Deep Learning Toolbox documentation directly

  • Deploying to cloud/server endpoints (no embedded target) — use MATLAB Production Server or MATLAB Compiler SDK

  • Working with classical ML models (decision trees, SVMs, ensembles) that aren't neural networks — use Statistics and Machine Learning Toolbox codegen workflows directly. Note: fitcnet/fitrnet neural network models ARE covered by this skill

  • Generating code for non-AI Simulink models — use standard Embedded Coder workflows

  • Converting between model formats without an embedded deployment goal (e.g., ONNX to MATLAB for desktop inference only)

Workflow Pattern Selection

This skill uses two deployment patterns:

  • Pattern 1 — MATLAB Network Codegen: Import or build a dlnetwork, optionally compress it, then generate C/C++ via MATLAB Coder or export to Simulink. See references/pattern1/workflow.md.

  • Pattern 2 — PyTorch/LiteRT Direct Codegen: Load a PyTorch (.pt2) or LiteRT (.tflite) model directly and generate C/C++ without converting to a dlnetwork. See references/pattern2/workflow.md.

Decision Tree

Primary discriminator for external models: deployment capabilities + hardware class.

Q1: Where does the AI model come from?
 |
 +-- Trained in MATLAB, or requires training in MATLAB -------> Pattern 1
 |
 +-- External framework (PyTorch, TF, ONNX, Keras) --> Q2
      |
      Q2: Does the deployment need any of these?
       |  - Quantization (INT8 via dlquantizer)
       |  - Pruning or projection
       |  - Weight inspection / modification
       |  - exportNetworkToSimulink integration
       |
       +-- YES --> Pattern 1 (import as dlnetwork)
       |
       +-- NO ---> Q3
            |
            Q3: What is the deployment target?
             |
             +-- Cortex-M: Pattern 1
             |     (compression and Simulink verification typically needed)
             |
             +-- x86 / GPU:
             |     +-- PyTorch (.pt2) or LiteRT (.tflite) --> Pattern 2
             |     +-- ONNX, TF, Keras --> Pattern 1 (convert to ONNX recommended)
             |
             +-- Cortex-A/R:
                   +-- Small model --> Pattern 1
                   |     (import as dlnetwork, then codegen)
                   +-- Large model:
                        +-- PyTorch (.pt2) or LiteRT (.tflite) --> Pattern 2
                        +-- ONNX, TF, Keras --> Pattern 1 (convert to ONNX recommended)
Pattern Summary
PatternWhen to UsePrimary Toolchain
1 — MATLAB Network CodegenModel trained in MATLAB, OR external model needing compression/quantization/Simulink export/weight inspection, OR Cortex-M targetsMATLAB Coder™ / Embedded Coder™
2 — PyTorch/LiteRT Direct CodegenExternal PyTorch (.pt2) or LiteRT (.tflite) model on x86/GPU/Cortex-A targets; shorter path to C code without compressionMATLAB Coder™ + PyTorch & LiteRT SPKG

Pattern 2's generated C is portable to any target, but Cortex-M deployments typically require Pattern 1 capabilities (compression, Simulink verification).

Import step (Pattern 1): For PyTorch/ONNX/Keras/TensorFlow model import, use /matlab-import-external-ai-model. This skill takes over after import for the compression, Simulink integration, and code generation phases.

Pattern 1 vs Pattern 2 Capability Comparison
CapabilityPattern 1 (dlnetwork)Pattern 2 (PyTorch/LiteRT direct)
C code generationYesYes
Target: Cortex-M, Cortex-A/R, x86, GPUYesYes
Weight inspection / modificationYesNo
dlquantizer (INT8)YesNo
Projection (compressNetworkUsingProjection)YesNo
PruningYesNo
Simulink integrationYes (exportNetworkToSimulink)Yes (PyTorch SPKG Simulink blocks)
Combined compressionYesNo
Speed to first C codeSlowerFaster

Rule of thumb: Choose Pattern 1 when you need to compress, quantize, inspect weights, or use exportNetworkToSimulink — or when the model is already a dlnetwork, or when targeting Cortex-M. Choose Pattern 2 when the model is already in PyTorch (.pt2) or LiteRT (.tflite) format and you want the shorter path to C code without compression.

Stats/ML models (fitrnet/fitcnet): These follow Pattern 1 but have their own Simulink integration path. Use the RegressionNeuralNetwork Predict block (for fitrnet) or ClassificationNeuralNetwork Predict block (for fitcnet) from the Statistics and Machine Learning Toolbox library — do NOT use exportNetworkToSimulink (which is for dlnetwork only). Configure simulation programmatically with Simulink.SimulationInput.

Common Start: Prerequisites

Regardless of pattern, always begin with these two prerequisite steps before entering the pattern-specific phases (which start at Phase 1):

  1. Environment Discovery (silent): Load references/shared/environment-setup.md

  2. Project Discovery (interactive): Load references/shared/project-discovery.md

Project Discovery determines the workflow pattern via the decision tree above.

Do Not Use (Legacy Functions)

LegacyModern Replacement
trainNetwork / train (for DL)trainnet
DAGNetwork / SeriesNetwork / networkdlnetwork
taylorPrunableNetwork / updateScore / updatePrunablescompressNetworkUsingTaylorPruning (when trainable with trainnet); use taylorPrunableNetwork for custom training loops
csvread / xlsreadreadmatrix / readtable
datenumdatetime

For legacy import functions (importONNXNetwork, importKerasNetwork, etc.), see /matlab-import-external-ai-model which handles all model import workflows.

Global Rules

Advisory vs Execution Mode

Distinguish between two modes based on the user's intent:

  • Advisory ("How should I approach this?", "What workflow?", "Which pattern?"): Answer the routing question directly — state the recommended Pattern, explain why, and outline the high-level steps. Do NOT enter Environment Discovery or start asking prerequisite questions. After giving the recommendation, ask if the user wants to begin execution.

  • Execution ("Deploy my model", "Walk me through", "Write the script"): Enter the full prerequisite flow (Environment Discovery → Project Discovery → step-by-step phases).

ALWAYS
  • Check toolboxes via detect_matlab_toolboxes and support packages via matlabshared.supportpkg.getInstalled before any workflow step

  • If a support package is missing, ask the user to download from Add-On Explorer -- never install on their behalf

  • Guide the user step-by-step -- one phase at a time

  • Use consistent data partitioning (e.g., fixed indices or a stored partition object) for reproducibility

  • Verify numerical equivalence at each transformation step

  • Generate MEX for desktop validation before generating C code for target

  • Use single precision for all inference inputs

  • Script-based execution: For each workflow step done in MATLAB, create a .m script file and execute it with run_matlab_file or evaluate_matlab_code. Do NOT run ad-hoc MATLAB commands without first writing the script file. If a script needs changes, edit the script file and re-run it. This gives users full visibility into what code is being executed and enables reproducibility. IMPORTANT: run_matlab_file sets the working directory to the script's folder. Always use absolute paths (via fullfile) for model files, data, and saved outputs — never rely on pwd or relative paths.

  • Pause after each workflow step: After every workflow step completes, pause and explicitly ask the user for permission to proceed to the next step. The goal is to let the user read/inspect the MATLAB scripts you created, review results, and ask questions before moving on.

  • Deep Network Designer: When a model is trained in MATLAB, imported, or rebuilt as a native dlnetwork, load it in Deep Network Designer (deepNetworkDesigner(net)) so the user can visually inspect the architecture. Announce this action and wait for user acknowledgment before proceeding.

  • Numerical equivalency tests (import workflows): For any import from PyTorch or ONNX:

    1. Run inference on the original model (via bundled Python for PyTorch, or ONNX runtime) to collect ground-truth reference data. Do NOT use the imported MATLAB model as reference — for PyTorch imports in R2026a, custom autogenerated layers may not support code generation and the model may need to be rebuilt natively. (ONNX autogenerated layers have supported code generation since R2025a and may not require a rebuild.)

    2. Run the same inputs through the rebuilt native MATLAB model and compare against ground truth

    3. After compression, report the accuracy delta vs. the uncompressed baseline (MAE, max error, % accuracy drop). Compute these from variables in the current run — never hardcode numeric values into fprintf/disp strings, because re-running the script with different inputs or a different model will then print stale numbers.

    4. Run tests to validate numerical equivalence between: compressed model in MATLAB, compressed model in Simulink, and final generated code

  • Test count proposal: Before running numerical equivalency tests, propose how many tests you plan to run and explain why (considering model complexity, output range, class count, etc.). Wait for user agreement or correction before proceeding.

  • Code generation report: Do NOT open the code generation report automatically — it opens a GUI that is not useful in an agentic workflow. Only open if the user explicitly requests it.

  • Look up function signatures from MATLAB's help or the online reference page, not from this skill. Argument lists, name-value pair (NVP) defaults, and supported-layer enumerations live in MATLAB's help <function> output and on the function's reference page. Use those as the source of truth instead of any inline parameter table in this skill — inline tables go stale across releases and burn context. This skill only flags name-value arguments that materially change the recipe (e.g., ValidationThreshold for accuracy-budgeted pruning). Lookup procedure:

    1. First try help <function> in the live MATLAB session. Fast and reflects the actually-installed release of the toolbox or support package.

    2. If help returns only a stub like "Run doc <function> for more information." — common for support-package functions whose help redirects to the browser doc — fall back to the agent's web browsing of the online reference page at https://www.mathworks.com/help/<product>/ref/<funcname>.html (lower-case function name). Extract every name-value argument with its default value, formatted as a markdown table, quoting defaults verbatim.

    3. If the function is not found at all (which <func> returns "not found") on a system that has the relevant support package installed, the support package is likely on a stale build. Ask the user to update via Add-On Explorer rather than working around the missing function.

  • Compression decision flow: At the start of Phase 5 (Pattern 1), load references/pattern1/compression-decision.md and walk the user through the question flow (hardware + Simulink availability, primary goal, retraining tolerance). Pick the compression and code generation path based on the answers. Compression is not mandatory and the optimal combination of pruning, projection, and quantization depends on the goal — for example, on Cortex-M with a latency-bound LSTM model, the float32 path with CMSIS-DSP outperforms the quantized path because CMSIS-NN provides no INT8 kernel for recurrent layers.

ASK FIRST
  • Before each phase transition: "Is this step relevant to your project?" (some phases may not apply)

  • Before data splitting: "Do you have existing train/val/test splits, or should I partition?" (avoids overwriting user's partitioning)

  • Before model selection: "What problem type (classification/regression/sequence) and any size constraints?" (determines architecture)

  • Before Simulink: "Do you have an existing Simulink model to integrate into?" (determines export vs standalone)

  • Before quantization: "Does your target support floating-point, or is integer-only required?" (determines quantization path)

  • Before code generation: "What is the target hardware?" (determines Coder configuration and CRL)

  • Before compression and code generation (Pattern 1): walk the user through the decision flow in references/pattern1/compression-decision.md — hardware target + Simulink availability, primary goal, retraining tolerance. The answers determine the compression techniques and the code-replacement library to use. Even if the hardware target is already stated, you MUST still ask about the primary deployment goal (flash, SRAM, latency, accuracy) and present the user with the recommended recipe for confirmation before executing any compression step.

NEVER
  • Present the entire workflow at once

  • Skip Environment Discovery or Project Discovery

  • Open, load, or inspect user data before Project Discovery is confirmed

  • Use legacy functions listed in "Do Not Use" section

  • Assume toolbox or support package availability without checking

  • Install support packages on the user's behalf

  • Promise hardware-agnostic performance or "deploy anywhere"

  • Generate DAGNetwork, SeriesNetwork, or network objects

  • Run MATLAB commands directly in the MCP server without creating a script file first

  • Skip numerical equivalency testing when using imported external models

  • Proceed to the next workflow step without explicit user permission

  • Apply compression without first walking the user through the decision flow in compression-decision.md

  • Use the imported model (with custom autogenerated layers) as numerical ground truth — always validate against the original model via bundled Python

  • Pass a [C × T] array with format "CBT" to a sequence model — always reshape to [C × 1 × T] for single-sequence inference

  • Pass a dlnetwork to prepareNetwork — in R2026a the function takes a dlquantizer object (prepareNetwork(quantObj)) and mutates it in place. The legacy net = prepareNetwork(net) form is no longer defined


This skill covers C/C++ code generation for CPU targets (Cortex-M, Cortex-A/R, x86) via MATLAB Coder and Embedded Coder, and GPU targets (CUDA/TensorRT) via Pattern 2's DeepLearningConfig options. The following deployment targets use different toolchains and are NOT covered:

TargetToolchainNotes
FPGA / SoCHDL Coder + Deep Learning HDL ToolboxGenerates HDL (VHDL/Verilog) from dlnetwork
PLCSimulink PLC CoderGenerates Structured Text for PLCs from Simulink models

If the user's target falls into one of these categories, inform them that this skill does not cover that workflow and suggest the relevant toolchain.


MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders.

Copyright 2026 The MathWorks, Inc.

Files

references/pattern1/native-rebuild-preparation.md

Weight Extraction and Native Rebuild Preparation

Extract weights from imported networks and prepare for the native-rebuild path. The imported network provides weights and architecture information for constructing a native dlnetwork suitable for codegen, quantization, and Simulink export.

Import Step

Use the /matlab-import-external-ai-model skill for the import itself (PyTorch, ONNX, TensorFlow/Keras). That skill handles the full import pipeline: preparing the model in Python, choosing import arguments, troubleshooting, and numeric validation against the source framework.

Once you have an imported dlnetwork, return here if the network contains layers that do not support code generation (verify by attempting codegen). ONNX autogenerated layers support codegen since R2025a and may not need a rebuild. PyTorch autogenerated layers may not support codegen in R2026a — rebuild is typically required.

Expanding NetworkLayer Containers

By default, importNetworkFromPyTorch produces nested NetworkLayer containers. NetworkLayer is supported by predict and exportNetworkToSimulink, but you must call expandLayers before code generation — NetworkLayer containers are not supported by the codegen path. Always expand before attempting codegen:

  • Required for code generation (MATLAB Coder / Embedded Coder)

  • Also needed to inspect individual layer properties (LSTM OutputMode, etc.)

  • Also needed to access weights by index from net.Learnables

  • Also needed to compare layer counts between imported and native networks

Without expandLayers, the Learnables table references container layer names (e.g., "SOC_LSTM:lstm") rather than individual layer names, and you cannot see the full architecture via net.Layers.

net = expandLayers(net);

Inspecting Imported Weights

After import, examine the Learnables table to understand the weight structure:

disp(net.Learnables)
% Columns: Layer | Parameter | Value
% Each row is one learnable tensor (weights, biases, etc.)

Example output for a 2-layer LSTM + FC head:

    Layer          Parameter          Value
    ____________   ________________   _________________
    'lstm_1'       'InputWeights'     {256x5 single}
    'lstm_1'       'RecurrentWeights' {256x64 single}
    'lstm_1'       'Bias'             {256x1 single}
    'lstm_2'       'InputWeights'     {256x64 single}
    'lstm_2'       'RecurrentWeights' {256x64 single}
    'lstm_2'       'Bias'             {256x1 single}
    'fc_1'         'Weights'          {64x64 single}
    'fc_1'         'Bias'             {64x1 single}
    'fc_2'         'Weights'          {1x64 single}
    'fc_2'         'Bias'             {1x1 single}

Weight Dimension Conventions

PyTorch and MATLAB use different dimension orderings. You must handle this when transferring.

Fully Connected Layers
FrameworkWeight ShapeConvention
PyTorch[output, input]Row-major
MATLAB[output, input]Same -- usually no transpose needed

When importing from ONNX, FC weights may need transposing:

% ONNX MatMul stores [input, output]; MATLAB FC expects [output, input]
matlabW = onnxW';

Always verify by comparing predict() outputs after transfer.

Convolutional Layers
FrameworkWeight ShapeConvention
PyTorch[out_channels, in_channels, H, W]OIHW
MATLAB[H, W, in_channels, out_channels]HWIO

Transpose needed:

% PyTorch [O,I,H,W] -> MATLAB [H,W,I,O]
matlabWeights = permute(pytorchWeights, [3, 4, 2, 1]);
LSTM Layers

Both PyTorch and MATLAB LSTM layers use the same concatenated gate layout (4*hidden_size rows), so weights usually transfer directly without reshaping. However, verify gate ordering:

FrameworkGate Order
PyTorchi (input), f (forget), g (cell), o (output)
MATLABSame order
Self-Attention (Transformers) -- QKV Splitting

ONNX-exported attention typically stores Q, K, V as a single concatenated matrix:

% ONNX: QKV combined [inputDim, 3*embedDim]
% Split into Q, K, V:
qWeights = combinedWeights(:, 1:embedDim);
kWeights = combinedWeights(:, embedDim+1:2*embedDim);
vWeights = combinedWeights(:, 2*embedDim+1:3*embedDim);

Identifying Custom Layers to Replace

After import, scan for non-standard layers that will need replacement for downstream integration (code generation, Simulink export, quantization):

for i = 1:numel(net.Layers)
    L = net.Layers(i);
    cls = class(L);
    if startsWith(cls, "nnet.onnx.") || startsWith(cls, "nnet.pytorch.") || ...
       startsWith(cls, "nnet.tensorflow.") || contains(cls, "PlaceholderLayer")
        fprintf('CUSTOM: %3d  %-35s [%s]\n', i, L.Name, cls);
    else
        fprintf('  OK:   %3d  %-35s [%s]\n', i, L.Name, cls);
    end
end

Common custom layers by architecture:

ArchitectureCustom Layer Name PatternWhat It DoesNative Replacement
Any with LSTM*_select_*h_n[-1] selectionlstmLayer(..., 'OutputMode', 'last')
Any with argmax*_max_to_*ArgmaxMove to entry-point function
CNN (ShuffleNet, etc.)*_view_view_*Channel shuffleChannelShuffleLayer
CNN*_chunk_*Channel splitChannelSplitLayer
CNN*_mean_*Global avg poolglobalAveragePooling2dLayer + flattenLayer
Transformer*_view_view_*Head reshapeChannelShuffleLayer or native selfAttentionLayer

Weight Transfer Methods

Method A: Learnables Table Matching (General)

Works when layer names in native and imported networks partially match:

importLearn = netImport.Learnables;
for i = 1:height(netNative.Learnables)
    lyr = netNative.Learnables.Layer{i};
    prm = netNative.Learnables.Parameter{i};
    idx = find(contains(importLearn.Layer, lyr) & strcmp(importLearn.Parameter, prm));
    if ~isempty(idx)
        netNative.Learnables.Value{i} = importLearn.Value{idx(1)};
    else
        warning('No match for %s/%s', lyr, prm);
    end
end
Method B: Explicit Index-Based Assignment (When Names Don't Match)
% Extract specific weights by position from imported network
lstm1_IW = netImport.Learnables.Value{1};  % InputWeights
lstm1_RW = netImport.Learnables.Value{2};  % RecurrentWeights
lstm1_B  = netImport.Learnables.Value{3};  % Bias

% Assign directly to native network's Learnables table by index
netNative.Learnables.Value{1} = lstm1_IW;
netNative.Learnables.Value{2} = lstm1_RW;
netNative.Learnables.Value{3} = lstm1_B;

NOTE: There is no public API to set individual learnables by name. Always assign via the net.Learnables.Value{idx} table directly.

Method C: Constructor-Time Weight Assignment

Set weights directly when constructing layers:

fc1 = fullyConnectedLayer(50, 'Name', 'fc1', ...
    'Weights', extractedWeights, 'Bias', extractedBias);

Post-Import Validation (Codegen Compatibility)

After importing any external model, validate for code generation:

% Analyze network architecture
analyzeNetwork(net)

% Check for placeholder, autogenerated, or unsupported layers
numLayers = numel(net.Layers);
isUnsupported = false(numLayers, 1);
for i = 1:numLayers
    layerClass = class(net.Layers(i));
    if contains(layerClass, "PlaceholderLayer") || ...
       contains(layerClass, "nnet.pytorch") || ...
       contains(layerClass, "nnet.tensorflow") || ...
       contains(layerClass, "autogenerated")
        warning("Layer '%s' (%s) may not support code generation.", ...
            net.Layers(i).Name, layerClass);
        isUnsupported(i) = true;
    end
end
unsupportedLayers = find(isUnsupported);

if ~isempty(unsupportedLayers)
    fprintf("Found %d layers that may not support code generation.\n", ...
        numel(unsupportedLayers));
    fprintf("See 'Handling Unsupported Custom Layers' section.\n");
end

% Test inference with sample data
sampleInput = dlarray(randn(1, numFeatures, "single"), "BC");
output = predict(net, sampleInput);

Post-Transfer Verification (Numerical Equivalency Testing)

Always verify the rebuilt network produces identical outputs. This is a critical gate before proceeding to compression.

Validate Against the Original Framework

Compare the rebuilt native network's predictions against the original framework's outputs on a set of test inputs. This end-to-end comparison is the primary validation — it confirms that weights transferred correctly and architecture reconstruction is faithful.

Direct weight comparison (checking individual weight tensors match between imported and native networks) is useful as a debugging tool when end-to-end validation fails, but is not a substitute for output-level verification.

CRITICAL: dlarray Shape Convention for Sequence Models

For sequence models with format "CBT" (Channels x Batch x Time):

  • A single sequence of length T with C features MUST be shaped [C, 1, T]

  • NEVER pass shape [C, T] with format "CBT" — MATLAB will interpret T as the batch dimension and set sequence length to 1, causing MinLength errors or wrong results

% WRONG: [5 x 10] with "CBT" -> C=5, B=10, T=1
testInput = dlarray(seq', "CBT");  % BUG!

% CORRECT: [5 x 1 x 10] with "CBT" -> C=5, B=1, T=10
testInput = dlarray(reshape(seq', [numFeatures, 1, seqLen]), "CBT");
CRITICAL: torch.export Models Have Fixed Dimensions

.pt2 files created with torch.export.export() have fixed input shapes by default. The sequence length is baked into the exported program unless dynamic_shapes was explicitly specified during export. Always check the model's expected dimensions before generating test data:

ep = torch.export.load("model.pt2")
# Check input specs for fixed dimensions
print(ep.graph_signature.input_specs)
Step 1: Propose Test Count

Before running tests, propose to the user how many tests to run and why:

  • Minimum: 50 test inputs for simple models (MLP with few classes)

  • Recommended: 100 test inputs for most models

  • Thorough: 200+ for complex models (transformers, multi-output regression)

Rationale for test count:

  • Cover all output classes (classification) or output range (regression)

  • Include edge cases and boundary inputs

  • Statistical confidence: 100 inputs gives ~95% confidence of catching 3%+ error rates

Present your proposal: "I propose running N numerical equivalency tests because [reason]. Does this work for you, or would you prefer a different number?"

Step 2: Collect Reference Data from Original Model

For PyTorch models, generate reference test vectors using the bundled Python:

% Generate reference data from PyTorch model
% Create a script: generate_reference_vectors.py
% Run via the configured project Python or MATLAB support-package bundled Python.
% See references/shared/environment-setup.md for discovery guidance.

For ONNX models, use the MATLAB ONNX import directly with known test inputs.

Step 3: Run Equivalency Tests
testInput = dlarray(single(randn(inputShape)), formatString);
yImport = predict(netImport, testInput);
yNative = predict(netNative, testInput);

maxErr = max(abs(extractdata(yImport(:)) - extractdata(yNative(:))));
cosine = dot(extractdata(yImport(:)), extractdata(yNative(:))) / ...
    (norm(extractdata(yImport(:))) * norm(extractdata(yNative(:))));

fprintf('Max error: %.2e, Cosine similarity: %.10f\n', maxErr, cosine);
assert(maxErr < 1e-3, 'Weight transfer verification failed');

Run on the agreed number of test inputs (not just one). Numerical equivalence should be < 1e-5 for identical architectures, < 1e-3 when replacement layers change operation order slightly.

Step 4: Report Results

After running all tests, present a summary table:

Numerical Equivalency Report: Original Model vs. MATLAB Rebuilt Model
================================================================
Tests run:            N
Mean Absolute Error:  X.XXe-Y
Max Absolute Error:   X.XXe-Y
Cosine Similarity:    0.XXXXXXXXXX (avg)
Pass/Fail:            PASS (all errors < threshold)
Step 5: Load in Deep Network Designer

After successful verification, load the rebuilt model in Deep Network Designer:

deepNetworkDesigner(netNative)

Announce: "The rebuilt model is now open in Deep Network Designer. Please inspect the architecture and let me know when you're ready to proceed."

Handling Unsupported Custom Layers (ONNX and TensorFlow)

If the imported network contains custom autogenerated layers that are not supported for code generation, rebuild the network natively using dlnetwork and transfer the learned weights.

Step 1: Identify unsupported layers
% List all layers and their classes
for i = 1:numel(net.Layers)
    fprintf("%3d: %-30s %s\n", i, net.Layers(i).Name, class(net.Layers(i)));
end
Step 2: Rebuild the network with native MATLAB layers

Map each imported layer to its native MATLAB equivalent:

% Example: rebuild a simple network natively
layers = [
    featureInputLayer(numFeatures)
    fullyConnectedLayer(64)
    reluLayer
    fullyConnectedLayer(32)
    reluLayer
    fullyConnectedLayer(numClasses)
    softmaxLayer
];

nativeNet = dlnetwork(layers);
Step 3: Extract and transfer weights from the imported network
% Get learnables from the imported network
importedLearnables = net.Learnables;
disp(importedLearnables);

% If the layer structure matches, copy all learnables at once
nativeNet.Learnables = net.Learnables;

% If layer names differ, copy weights layer by layer
% Example: copy weights from imported "dense_1" to native "fc_1"
importedWeights = net.Learnables(net.Learnables.Layer == "dense_1", :);
nativeIdx = find(nativeNet.Learnables.Layer == "fc_1");
nativeNet.Learnables.Value{nativeIdx(1)} = importedWeights.Value{1};  % Weights
nativeNet.Learnables.Value{nativeIdx(2)} = importedWeights.Value{2};  % Bias
Step 4: Validate the rebuilt network
% Compare outputs between imported and native networks
sampleInput = dlarray(randn(1, numFeatures, "single"), "BC");
importedOutput = predict(net, sampleInput);
nativeOutput = predict(nativeNet, sampleInput);

maxDiff = max(abs(extractdata(importedOutput) - extractdata(nativeOutput)), [], "all");
fprintf("Max output difference: %.6e\n", maxDiff);

if maxDiff < 1e-5
    fprintf("Native network matches imported network.\n");
else
    warning("Significant difference detected. Review weight mapping.");
end

Important Notes for Workflow Pattern 1

  • Imported models for lean hardware should be small (< 500 KB target)

  • Large imported models will need compression in Phase 5

  • Verify that the imported network uses layers supported by code generation

  • Run analyzeNetwork to check code generation compatibility

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.

Needs: Needs an MCP server

Security

No issues found by our static scan· No issues found

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/ai-and-statistics/matlab-deploy-embedded-ai · 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-embedded-ai.zip