# Agent brief: Treat Core AI as the program that runs the model

- **Lesson id:** 03-core-ai-runtime
- **Goal:** Explain `AIModel`, `InferenceFunction`, `NDArray`, specialization, and cache as the host around the compiled clothing graph.
- **Prerequisites:** Complete 01 and 02; know `clothing.aimodel` from the original course.
- **Inputs:** `clothing.aimodel`, function `main`, input `image`, output `logits`, fixed tensor contract.
- **Outputs/artifacts:** Contract diagram and clearly labelled Swift shape pseudocode.
- **Concrete steps:**
  1. Start from the model file and show `main`, `image [1,1,28,28]`, and `logits [1,10]`.
  2. Describe `AIModel` loading, `InferenceFunction` invocation, and `NDArray` data.
  3. Mark exact Swift calls as names that can change with the SDK version and defer to Xcode docs.
  4. Show prepare or specialise once, then reuse on every image.
  5. Link the original Xcode lesson and SwiftUI lesson.
- **Constraints:** Preserve float32 NCHW and 0 to 1 pixels; no fake signatures; no CUDA, Mermaid, quizzes, or em dashes.
- **Acceptance checks:** Asset names and shapes are explicit, preparation is separated from inference, pseudocode is labelled, and the Agent brief link is on the human page.
- **Human lesson:** [03-core-ai-runtime.html](03-core-ai-runtime.html)

## Environment setup

Use Xcode 27 on macOS. Create an iOS or macOS SwiftUI App target, add the exported `.aimodel` to the target's model/resources build phase, add the **Core AI** framework under Frameworks, Libraries, and Embedded Content, and install the **Metal Toolchain** in Xcode Settings > Components. Confirm the installed toolchain with:

```bash
xcode-select --install
xcodebuild -version
```

Build the bundled model once before adding UI. Core AI and `NDArray` names can change with the SDK version, so check the exact names in the installed Xcode docs.

## Key concepts

- `AIModel` loads the file. `InferenceFunction` is `main`. `NDArray` carries typed shaped data.
- The contract is `clothing.aimodel` to `main` to `image` `[1, 1, 28, 28]` to `logits` `[1, 10]`.
- Load and prepare once at app start. Every image reuses the prepared function.
- Softmax and label mapping are display work after `logits`.

## Takeaways

- A picker callback should build a tensor and call an already prepared function.
- Exact Swift names can change with the SDK. The shape contract does not.
- The runtime must turn array descriptions into buffers with the right type and layout.
