matlab/matlab-agentic-toolkit / skills-catalog/code-generation/matlab-deploy-ai-model
matlab-deploy-ai-model
VerifiedGenerate 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.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 10.8 KB |
| manifest.yaml | config | 617 B |
| references/codegen-workflow.md | markdown | 4.0 KB |
| references/dnn-codegen-options.md | markdown | 6.9 KB |
| references/export-pytorch-models.md | markdown | 4.6 KB |
| references/litert-numeric-verification.md | markdown | 3.8 KB |
| references/litert-workflow.md | markdown | 14.7 KB |
| references/pytorch-api-reference.md | markdown | 2.6 KB |
| references/pytorch-data-layout.md | markdown | 4.1 KB |
| references/pytorch-export-gotchas.md | markdown | 4.7 KB |
| references/pytorch-export-patterns.md | markdown | 5.2 KB |
| references/pytorch-numeric-verification.md | markdown | 2.6 KB |
| references/pytorch-supported-models.md | markdown | 3.4 KB |
| references/pytorch-workflow.md | markdown | 5.7 KB |
| references/simulink-workflow.md | markdown | 12.7 KB |
| references/tensorflow-to-litert-conversion.md | markdown | 5.8 KB |
references/pytorch-data-layout.md
View on GitHub# Data Layout: NCHW vs HWC
## Core Rule
`PyTorchExportedProgram` preserves PyTorch's native data layout. It does NOT
convert to MATLAB's traditional image convention.
| Framework | Layout | Example (224x224 RGB image) |
|-----------|--------|----------------------------|
| PyTorch | NCHW | `[1, 3, 224, 224]` |
| MATLAB images (`imread`) | HWC | `[224, 224, 3]` |
| `PyTorchExportedProgram` | NCHW (preserved) | `[1, 3, 224, 224]` |
## Determining the Expected Layout
Always check `inputSpecifications` — it reports the exact shape expected:
```matlab
model = loadPyTorchExportedProgram("resnet18.pt2");
inSpecs = model.inputSpecifications;
disp(inSpecs.Size{1}) % e.g., [1 3 224 224] for ResNet
```
## Common Layout Patterns by Model Type
| Model Type | PyTorch Layout | Dimensions |
|-----------|---------------|------------|
| Vision (CNN) | NCHW | `[batch, channels, height, width]` |
| Sequence (RNN/LSTM) | NCL | `[batch, features, sequence_length]` |
| Transformer (NLP) | NLC | `[batch, sequence_length, features]` |
| Audio | NCL | `[batch, channels, samples]` |
## When Permutation Is Needed
If the user's source data is in MATLAB image format (HWC), permute before passing
to `invoke`:
```matlab
img = single(imread("test.png")); % [224, 224, 3] single HWC
input = permute(img, [4 3 1 2]); % HWC -> 1CHW (add batch dim)
% Result: [1, 3, 224, 224] single
output = invoke(model, input);
```
**Note:** Model-specific preprocessing (normalization, resizing, mean subtraction,
etc.) is still required before calling `invoke`. The preprocessing depends on how
the PyTorch model was trained — consult the model's documentation for the expected
input range and transformations.
### Example: ResNet from torchvision
torchvision ImageNet models expect input normalized with ImageNet statistics:
- Mean: `[0.485, 0.456, 0.406]` (RGB)
- Std: `[0.229, 0.224, 0.225]` (RGB)
- Input range: `[0, 1]` before normalization
- Crop size: 224x224
```matlab
img = single(imread("test.png")); % [H, W, 3] uint8 -> single
img = imresize(img, [224 224]); % resize to expected crop size
img = img / 255.0; % scale to [0, 1]
% ImageNet normalization (per-channel)
mean = reshape(single([0.485, 0.456, 0.406]), [1 1 3]);
stddev = reshape(single([0.229, 0.224, 0.225]), [1 1 3]);
img = (img - mean) ./ stddev;
input = permute(img, [4 3 1 2]); % HWC -> 1CHW
output = invoke(model, input);
```
For other models, find the expected preprocessing in the model's documentation.
torchvision models document their transforms at:
https://docs.pytorch.org/vision/stable/models.html
## When Permutation Is NOT Needed
- Data already in NCHW format (e.g., from another PyTorch preprocessing step)
- Random test inputs created directly in the correct shape:
```matlab
input = randn(1, 3, 224, 224, "single");
```
- Sequence data already in NCL format
## Output Layout
Outputs also preserve PyTorch layout. For a classification model:
- PyTorch output: `[1, 1000]` (batch, classes)
- `invoke` output: `[1, 1000]` (same)
No permutation needed for 1D outputs (classification scores, embeddings).
For spatial outputs (segmentation masks, depth maps), the output will be NCHW —
permute back to HWC for display in MATLAB:
```matlab
output = invoke(model, input); % [1, numClasses, H, W] NCHW
mask = permute(output, [3 4 2 1]); % NCHW -> HWC (drop batch)
imshow(mask(:,:,1)); % display first class channel
```
## Common Mistake
Assuming a fixed layout instead of checking `inputSpecifications`:
```matlab
% WRONG — assumes NCHW without checking
input = ones(224, 224, 3, "single");
output = invoke(model, input); % likely shape mismatch
% CORRECT — always check inputSpecifications first
inSpecs = model.inputSpecifications;
disp(inSpecs.Size{1}) % reveals actual expected shape
input = ones(1, 3, 224, 224, "single"); % match what the model expects
output = invoke(model, input);
```
Most standard vision models (ResNet, EfficientNet, etc.) use NCHW, but custom
models may use any layout. Always consult `inputSpecifications`.
----
Copyright 2026 The MathWorks, Inc.
----
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 321k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |