Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

coreml-optimizer

БесплатноБез исполняемых скриптовНе проверен

Optimize CoreML models for iOS and macOS deployment. Covers quantization, palettization, pruning, Neural Engine targeting, compute unit selection, and…

ckorhonenот ckorhonen★ 35 звёзд на GitHub8 установок в других каталогах

Об этом скилле

CoreML Optimizer

Expert guidance for optimizing machine learning models for Apple's CoreML framework on iOS and macOS devices.

When to Use This Skill

Use this skill when:

  • Converting PyTorch/TensorFlow models to CoreML format
  • Optimizing CoreML model size and inference latency
  • Targeting the Neural Engine for maximum performance
  • Debugging slow model inference or compute unit issues
  • Applying quantization, palettization, or pruning
  • Profiling model performance with Instruments
  • Troubleshooting accuracy degradation after compression

Speed Optimization Checklist

The critical path to fast CoreML inference:

1. Verify Compute Unit Configuration

Many "slow" models are accidentally CPU-bound. Configure via MLModelConfiguration.computeUnits:

Option Description
.all Uses all available compute units including Neural Engine (default, recommended)
.cpuAndNeuralEngine CPU + Neural Engine, excludes GPU
.cpuAndGPU CPU + GPU, excludes Neural Engine
.cpuOnly Forces CPU-only execution (for debugging/consistency)

In Swift:

let config = MLModelConfiguration()
config.computeUnits = .all  // .cpuAndNeuralEngine, .cpuAndGPU, .cpuOnly
let model = try MLModel(contentsOf: modelURL, configuration: config)

Benchmark each configuration - if .all isn't faster than .cpuAndGPU, your model may not be hitting the Neural Engine.

2. Apply Weight Compression with coremltools

CoreML execution commonly uses float16 where possible. Use coremltools.optimize for further compression:

import coremltools as ct
import coremltools.optimize as cto

# 8-bit quantization (2-4x speedup for memory-bound models)
config = cto.coreml.OptimizationConfig(
    global_config=cto.coreml.OpLinearQuantizerConfig(
        mode="linear_symmetric",
        dtype="int8",
        granularity="per_channel"
    )
)

model = ct.models.MLModel("Model.mlpackage")
quantized = cto.coreml.linear_quantize_weights(model, config=config)
quantized.save("Model_int8.mlpackage")

3. Consider 4-bit Quantization

Recent coremltools releases support 4-bit quantization for even more aggressive compression:

config = cto.coreml.OptimizationConfig(
    global_config=cto.coreml.OpLinearQuantizerConfig(
        mode="linear_symmetric",
        dtype="int4",
        granularity="per_block"
    )
)

4. Profile the FULL Pipeline

Pre/post-processing (image resize, tokenization, NMS, etc.) is often the real bottleneck. Profile the entire pipeline, not just prediction().

// Profile everything
let startTotal = CFAbsoluteTimeGetCurrent()

// Preprocessing
let startPreprocess = CFAbsoluteTimeGetCurrent()
let input = preprocessImage(image)
let preprocessTime = CFAbsoluteTimeGetCurrent() - startPreprocess

// Inference
let startInference = CFAbsoluteTimeGetCurrent()
let output = try model.prediction(from: input)
let inferenceTime = CFAbsoluteTimeGetCurrent() - startInference

// Postprocessing
let startPostprocess = CFAbsoluteTimeGetCurrent()
let result = postprocess(output)
let postprocessTime = CFAbsoluteTimeGetCurrent() - startPostprocess

let totalTime = CFAbsoluteTimeGetCurrent() - startTotal

print("Preprocess: \(preprocessTime * 1000)ms")
print("Inference: \(inferenceTime * 1000)ms")
print("Postprocess: \(postprocessTime * 1000)ms")
print("Total: \(totalTime * 1000)ms")

Hardware Recommendations (iOS 18 / macOS 15)

Technique Best Hardware Use Case
Weight palettization (1-8 bit) Neural Engine Runtime memory + latency gains
W8A8 quantization Neural Engine (A17 Pro, M4) Compute-bound models
INT4 per-block quantization GPU (Mac) Large models on Mac
Pruning (sparse weights) Neural Engine, CPU Memory-bound models

Core Compression Techniques

Quantization

Reduces precision from float16/32 to int8/int4:

import coremltools.optimize as cto

# Data-free 8-bit quantization (fastest, works well for most models)
config = cto.coreml.OptimizationConfig(
    global_config=cto.coreml.OpLinearQuantizerConfig(
        mode="linear_symmetric",
        dtype="int8",
        granularity="per_channel",
        weight_threshold=512  # Only quantize layers with >512 params
    )
)

quantized = cto.coreml.linear_quantize_weights(model, config=config)

Expected results:

  • INT8: ~75% size reduction, 2-3x speedup
  • INT4: ~87.5% size reduction, 3-4x speedup

Palettization

Clusters weights into a small lookup table:

config = cto.coreml.OptimizationConfig(
    global_config=cto.coreml.OpPalettizerConfig(
        mode="kmeans",  # or "uniform"
        nbits=4,        # 16 unique values
        granularity="per_channel"
    )
)

palettized = cto.coreml.palettize_weights(model, config=config)

When to use: Models sensitive to quantization often tolerate palettization better.

Pruning

Zeros out unimportant weights:

``

Полный SKILL.md на GitHub

Установить coreml-optimizer в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/compression-techniques.mdreferences/neural-engine-guide.mdreferences/profiling-tools.md

FAQ

Что делает скилл coreml-optimizer?

Optimize CoreML models for iOS and macOS deployment. Covers quantization, palettization, pruning, Neural Engine targeting, compute unit selection, and performance profiling. Use when converting ML models to CoreML, optimizing model size/latency, debugging Neural Engine issues, or benchmarking on-device inference.

Как установить скилл coreml-optimizer?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл coreml-optimizer запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить coreml-optimizer с