Skip to content

matlab/matlab-agentic-toolkit / skills-catalog/code-generation/matlab-deploy-ai-model

matlab-deploy-ai-model

Verified

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.

references/pytorch-numeric-verification.md

View on GitHub
# Numeric Verification: MATLAB vs PyTorch

Compare inference output between the original PyTorch model (in Python) and the
MATLAB-loaded model to confirm correct loading and numerical equivalence.

## Primary Approach: pyrun (from within MATLAB)

Use `pyrun` to call PyTorch inference directly from MATLAB. This keeps
everything in one session — no external scripts, no file exchange.

**Ask the user for a Python venv path** with `torch` installed (and any other
packages the model needs to run, e.g., `transformers`, `timm`, model-specific
repos). Do not guess a path or install packages without confirmation.

**Critical:** Set `ExecutionMode` to `'OutOfProcess'` before importing torch.
PyTorch's C extensions conflict with MATLAB's bundled libraries in-process and
crash with an `undefined symbol` error. This must be set before Python is
first loaded (i.e., before the first `pyrun` call in the session).

```matlab
% Set ONCE at the start of the session, before any pyrun call
pyenv('Version', '/path/to/venv/bin/python3', 'ExecutionMode', 'OutOfProcess');

% Fixed input — same seed used for both MATLAB and PyTorch
rng(42);
inp = randn(1, 3, 224, 224, 'single');

% MATLAB inference
model = loadPyTorchExportedProgram("model.pt2");
matlabOut = invoke(model, inp);

% PyTorch inference via pyrun
pyrun("import torch; ep = torch.export.load('model.pt2')");
ptOut = pyrun( ...
    ["import numpy as np;" ...
     "t = torch.from_numpy(np.array(x, dtype='float32'));" ...
     "with torch.no_grad():" ...
     "    out = ep.module()(t);" ...
     "out = out[0] if isinstance(out, (tuple,list)) else out;" ...
     "result = out.numpy()"], ...
    "result", x=inp);
ptOut = single(ptOut);

% Compare
testCase = matlab.unittest.TestCase.forInteractiveUse;
testCase.verifyThat(matlabOut, matlab.unittest.constraints.IsEqualTo(ptOut, ...
    'Within', matlab.unittest.constraints.AbsoluteTolerance(single(1e-4))));
```

**Input shape and type must match what the model expects.** Construct the test
input with the correct dimensions (e.g., NCHW for vision models) and dtype
(`single` for float32). Mismatched inputs produce silent wrong results or
runtime errors.

**Note on multi-output models:** If the PyTorch model returns a tuple, the
`pyrun` snippet above extracts `out[0]`. Adjust indexing if your model returns
multiple tensors.

## Tolerance Values

- Absolute tolerance: `1e-4` (single-precision inference, CPU vs CPU)

## When to Use

- After loading a model with `loadPyTorchExportedProgram` for the first time
- Before proceeding to MEX generation (confirm the model loaded correctly)
- When debugging unexpected inference results

----

Copyright 2026 The MathWorks, Inc.

----
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 321kUpdated Claude CodeCodexVerifiedInstall
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: 197kUpdated Claude CodeCodexVerifiedInstall
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: 119kUpdated Claude CodeCodexVerifiedInstall
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: 118kUpdated Claude CodeCodexVerifiedInstall