# Core AI Fast First Token and the Right Compute Unit: Lesson 02. Specialize before the user waits

Lesson id: `core-ai-fast-first-token/02-specialize-before-the-user-waits`
Human lesson: https://edgefde.dev/courses/core-ai-fast-first-token/02-specialize-before-the-user-waits.html

## Goal

Make sure specialization happens before the first user request, from the cache or ahead-of-time compiled files.

## Prerequisites

- Lesson 01 timings
- Metal Toolchain for coreai-build

## Inputs

- `MyModel.aimodel`
- Hosting for compiled assets

## Outputs and artifacts

- `ModelPreparer` with cache check
- `prepareAfterDownload` using `AIModel.specialize`
- `compiled/MyModel..aimodelc` files
- `loadCompiled` runtime picker

## Steps

1. Add the cache check with `AIModelCache.default.model(for:options:)` and show Preparing only on nil.
2. Call `AIModel.specialize(contentsOf:options:cachePolicy: .persistent)` after the model download or when the feature turns on.
3. Use the same `SpecializationOptions` for specialize and load.
4. Run `xcrun coreai-build compile MyModel.aimodel --platform iOS --min-deployment-version 27.0 --output compiled/`.
5. Host the `.aimodelc` files. At runtime build the name with `AIModel.deviceArchitectureName` and download only that file.
6. Load the compiled file if present, else the portable `.aimodel`.
7. Re-measure cold and warm launch with lesson 01 timers.

## Constraints

- Do not claim ahead-of-time compilation removes on-device specialization.
- Do not invent multi-Neural-Engine behavior; measure it.

## Acceptance checks

- Second launch is a cache hit.
- Cold launch with a matching .aimodelc is faster than with the portable model on the same device.

## Key concepts

- `AIModelCache.default.model(for:options:)` tells you if a specialization is cached and never specializes.
- `AIModel.specialize(...)` specializes without inference. Run it after download or on feature enable.
- The cache key is the model URL plus SpecializationOptions. OS updates and storage pressure can remove entries.
- `coreai-build compile` makes one `.aimodelc` per architecture. Pick it with `AIModel.deviceArchitectureName`.

## Takeaways

- Show a Preparing state only on a cache miss.
- Specialize before the user presses Send, with the same options you load with.
- Ship per-architecture .aimodelc files for Apple Intelligence devices and keep the portable model as a fallback.
