本文へ移動
cccskills
無料GitHub で公開日本語紹介

swift-mlx

Apple Silicon向けの機械学習フレームワークMLXをSwiftで使い、配列計算やニューラルネットワークの構築、勾配計算、モデル学習、Metalカーネルの実装とメモリ調整を進めるためのスキルです。

原文原文の説明を見る

MLX Swift - High-performance ML framework for Apple Silicon with lazy evaluation, automatic differentiation, and unified memory

kellyvv/PhoneClawスター 1,284(GitHub 1,284 + cccskills 0)

実行スコア 未検証

インストール方法を見る

こんなときに便利

  • MLX配列を作成・操作したいとき
  • Swiftでニューラルネットワークを構築したいとき
  • 勾配計算でモデルを学習したいとき
  • Metalカーネルを実装したいとき
  • 並行処理のメモリを調整したいとき

日本語での紹介

できること

Apple Silicon向けの機械学習フレームワークMLX Swiftを使った配列計算やモデル開発を案内します。NumPyに似た配列の作成・変形・演算に加え、遅延評価によって計算を必要なタイミングで実行する方法を扱います。

MLXNNのレイヤーでニューラルネットワークを組み立て、MLXOptimizersの最適化手法と自動微分による勾配計算を使って学習を進められます。処理のコンパイルによる高速化、MLXFastを使ったMetalカーネルの作成、複数の処理が使うメモリの調整も対象です。配列やモデルの基本から、並行処理時の注意点まで参照できます。

こんなときに便利

Apple Silicon上でSwiftによる機械学習処理を作りたい開発者に向いています。配列演算からニューラルネットワークの構築、学習、性能調整へと進むときに、関連するAPIや実装パターンを確認できます。

使い方の例

  • 「MLX Swiftで配列の形状を変える方法を教えて」
  • 「Swiftでニューラルネットワークの学習ループを作って」
  • 「独自のMetalカーネルをMLXから使う方法を説明して」

注意点

Apple Silicon向けのMLX Swift環境が前提です。MLXArrayはタスク間で共有せず、並行処理ではアクターなどで状態を管理する必要があります。

この紹介文は、公開されている SKILL.md をもとに AI(OpenAI Codex)が作成しました。正確な仕様は下の原文を確認してください。

含まれるファイル(11)

  • SKILL.md11.0 KB
  • references/arrays.md6.3 KB
  • references/concurrency.md7.4 KB
  • references/custom-kernels.md7.7 KB
  • references/custom-layers.md7.0 KB
  • references/deprecated.md7.8 KB
  • references/neural-networks.md8.8 KB
  • references/operations.md7.0 KB
  • references/optimizers.md6.9 KB
  • references/transforms.md6.1 KB
  • references/wired-memory.md3.5 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

MLX Swift Framework

MLX Swift is Apple's high-performance machine learning framework designed specifically for Apple Silicon. It provides NumPy-like array operations with lazy evaluation, automatic differentiation, and unified CPU/GPU memory.

When to Use This Skill

  • Array operations on Apple Silicon (MLXArray)
  • Building neural networks (MLXNN)
  • Training models with automatic differentiation
  • Custom Metal kernels via MLXFast
  • Performance optimization with JIT compilation

Architecture Overview

MLXOptimizers (Adam, AdamW, SGD, etc.)
       ↓
MLXNN (Layers, Modules, Losses)
       ↓
MLX (Arrays, Ops, Transforms, FFT, Linalg, Random)
       ↓
Cmlx (C/C++ bindings, Metal GPU)

Key File Reference

PurposeFile Path
Core arraySource/MLX/MLXArray.swift
OperationsSource/MLX/Ops.swift
TransformsSource/MLX/Transforms.swift
Factory methodsSource/MLX/Factory.swift
Neural layersSource/MLXNN/*.swift
OptimizersSource/MLXOptimizers/Optimizers.swift
Fast opsSource/MLX/MLXFast.swift
Custom kernelsSource/MLX/MLXFastKernel.swift
Wired memory coordinatorSource/MLX/WiredMemory.swift
GPU working-set helperSource/MLX/GPU+Metal.swift

Quick Start

Basic Array Creation

import MLX

// Create arrays
let a = MLXArray([1, 2, 3, 4])
let b = MLXArray(0 ..< 12, [3, 4])  // Shape [3, 4]
let c = MLXArray.zeros([2, 3])
let d = MLXArray.ones([4, 4], dtype: .float32)

// Random arrays (use MLXRandom namespace or free functions)
let uniform = MLXRandom.uniform(0.0 ..< 1.0, [3, 3])
let normal = MLXRandom.normal([100])

Array Properties

let array = MLXArray(0 ..< 12, [3, 4])
array.shape    // [3, 4]
array.ndim     // 2
array.size     // 12
array.dtype    // .int64
array.count    // 3 (first dimension)

Basic Operations

let a = MLXArray([1.0, 2.0, 3.0])
let b = MLXArray([4.0, 5.0, 6.0])

// Arithmetic (lazy - not computed until eval)
let sum = a + b
let product = a * b
let matmul = a.matmul(b.T)

// Force evaluation
eval(sum, product)
// or
sum.eval()

Building a Neural Network

import MLX
import MLXNN

class MLP: Module, UnaryLayer {
    @ModuleInfo var fc1: Linear
    @ModuleInfo var fc2: Linear

    init(inputDim: Int, hiddenDim: Int, outputDim: Int) {
        self.fc1 = Linear(inputDim, hiddenDim)
        self.fc2 = Linear(hiddenDim, outputDim)
        super.init()
    }

    func callAsFunction(_ x: MLXArray) -> MLXArray {
        var x = fc1(x)
        x = relu(x)
        return fc2(x)
    }
}

let model = MLP(inputDim: 784, hiddenDim: 256, outputDim: 10)
eval(model)  // Initialize parameters

Training Loop

import MLXOptimizers

let model = MLP(inputDim: 784, hiddenDim: 256, outputDim: 10)
let optimizer = Adam(learningRate: 0.001)

func loss(model: MLP, x: MLXArray, y: MLXArray) -> MLXArray {
    let logits = model(x)
    return crossEntropy(logits: logits, targets: y, reduction: .mean)
}

// Compute loss and gradients - valueAndGrad returns a function
let lossAndGrad = valueAndGrad(model: model, loss)
let (lossValue, grads) = lossAndGrad(model, x, y)

// Update model
optimizer.update(model: model, gradients: grads)
eval(model, optimizer)

Primary Workflow: Array Operations

See arrays.md for detailed array creation and indexing.

Creation Functions

// Zeros and ones
MLXArray.zeros([3, 4])
MLXArray.ones([2, 2], dtype: .float16)

// Ranges
arange(0, 10, 2)           // [0, 2, 4, 6, 8]
linspace(0.0, 1.0, 5)      // [0.0, 0.25, 0.5, 0.75, 1.0]

// Identity and diagonal
MLXArray.identity(3)
diagonal(array, offset: 0)

// Full
MLXArray.full([2, 3], values: 7.0)

Indexing

let a = MLXArray(0 ..< 12, [3, 4])

// Single element
a[0, 1]

// Slicing
a[0...]           // All rows
a[..<2]           // First 2 rows
a[1..., 2...]     // From row 1, column 2 onwards

// Advanced indexing
a[.ellipsis, 0]       // First column of all dimensions
a[.newAxis, .ellipsis]  // Add dimension at front

Shape Manipulation

let a = MLXArray(0 ..< 12, [3, 4])

a.reshaped([4, 3])
a.reshaped(-1, 6)     // Infer first dimension
a.T                    // Transpose
a.transposed(1, 0)     // Explicit transpose
a.squeezed()           // Remove size-1 dimensions
a.expandedDimensions(axis: 0)

Secondary Workflow: Neural Networks

See neural-networks.md for complete layer reference.

Built-in Layers

// Linear layers
Linear(inputDim, outputDim, bias: true)
Bilinear(in1, in2, out)

// Convolutions
Conv1d(inputChannels, outputChannels, kernelSize: 3)
Conv2d(inputChannels, outputChannels, kernelSize: 3, stride: 1, padding: 1)

// Normalization
LayerNorm(dimensions)
RMSNorm(dimensions)
BatchNorm(featureCount)
GroupNorm(groupCount, dimensions)

// Attention
MultiHeadAttention(dimensions: 512, numHeads: 8)

// Recurrent
RNN(inputSize, hiddenSize)
LSTM(inputSize, hiddenSize)
GRU(inputSize, hiddenSize)

// Regularization
Dropout(p: 0.1)

Module Property Wrappers

class MyLayer: Module {
    @ModuleInfo var layer: Linear           // Tracked module
    @ModuleInfo(key: "w") var weights: Linear  // Custom key

    let constant: MLXArray  // NOT tracked (no wrapper)
}

Loss Functions

crossEntropy(logits: logits, targets: targets, reduction: .mean)
binaryCrossEntropy(logits: logits, targets: targets)
l1Loss(predictions: predictions, targets: targets, reduction: .mean)
mseLoss(predictions: predictions, targets: targets, reduction: .mean)
smoothL1Loss(predictions: predictions, targets: targets, beta: 1.0)
klDivLoss(inputs: inputs, targets: targets, reduction: .mean)

Tertiary Workflow: Training

See transforms.md for automatic differentiation details.

Gradient Computation

// Simple gradient
let gradFn = grad { x in
    sum(x * x)
}
let g = gradFn(MLXArray([1.0, 2.0, 3.0]))

// Value and gradient together
let (value, gradient) = valueAndGrad { x in
    sum(x * x)
}(MLXArray([1.0, 2.0, 3.0]))

// Model gradients - valueAndGrad returns a function, call it to get results
let lossAndGradFn = valueAndGrad(model: model) { model in
    model(input)
}
let (loss, grads) = lossAndGradFn(model)

Optimizers

See optimizers.md for all optimizers.

// Common optimizers
let sgd = SGD(learningRate: 0.01, momentum: 0.9)
let adam = Adam(learningRate: 0.001, betas: (0.9, 0.999))
let adamw = AdamW(learningRate: 0.001, weightDecay: 0.01)

// Training step
optimizer.update(model: model, gradients: grads)
eval(model, optimizer)

Compilation for Performance

// Compile a pure array function for faster execution
let compiledOp = compile { (a: MLXArray, b: MLXArray) -> MLXArray in
    let x = a + b
    return sum(x * x)
}

// Use compiled version
let output = compiledOp(arrayA, arrayB)

// Note: compile() works best with pure MLXArray functions.
// For models, call model methods directly (they can use internal compilation).

Quaternary Workflow: Wired Memory Coordination

See wired-memory.md for full policy, hysteresis, and admission guidance.

import MLX

let policy = WiredSumPolicy()

// Reservation: participates in admission but does not keep the wired limit high while idle.
let weightsTicket = policy.ticket(size: weightsBytes, kind: .reservation)
_ = await weightsTicket.start()

// Active work: raises limit while inference runs.
let inferenceTicket = policy.ticket(size: kvCacheBytes, kind: .active)
try await inferenceTicket.withWiredLimit {
    // run model inference
}

_ = await weightsTicket.end()

Best Practices

DO

  • Use lazy evaluation: MLX arrays are computed lazily. Call eval() strategically to control memory and compute.
  • Batch eval calls: eval(a, b, c) is more efficient than separate calls.
  • Use @ModuleInfo for all module properties to enable quantization and updates.
  • Use actors for concurrent code: Encapsulate MLX state within actors for thread safety.
  • Use namespaced functions: MLXRandom.uniform(), FFT.fft(), Linalg.inv().
  • Use ticket-based wired memory coordination: Prefer WiredMemoryTicket.withWiredLimit and WiredMemoryManager.shared.

DON'T

  • Don't share MLXArrays across tasks: MLXArray is NOT Sendable by design.
  • Don't use deprecated module imports: Use import MLX not import MLXRandom.
  • Don't forget to eval(): Unevaluated arrays can accumulate large compute graphs.
  • Don't mutate arrays directly: Use operations that return new arrays.
  • Don't call deprecated wired-limit APIs: Avoid GPU.withWiredLimit(...) and Memory.withWiredLimit(...).

Deprecated Patterns

If you see...Use instead...
import MLXRandomimport MLX then MLXRandom.uniform() or free function uniform()
import MLXFFTimport MLX then FFT.fft()
import MLXLinalgimport MLX then Linalg.inv()
GPU.activeMemoryMemory.activeMemory
GPU.withWiredLimit(...)WiredMemoryTicket(...).withWiredLimit { ... } via WiredMemoryManager
Memory.withWiredLimit(...)WiredMemoryTicket(...).withWiredLimit { ... }
repeat(_:count:)repeated(_:count:)
addmm()addMM()
LogSoftMaxLogSoftmax
SoftMaxSoftmax

See deprecated.md for the complete migration guide.

Swift Concurrency Notes

MLX has specific concurrency behavior:

  • MLXArray is NOT Sendable: This is intentional. Arrays contain references to compute graphs.
  • evalLock protects eval/stream creation: The global lock serializes evaluation and stream operations.
  • Lazy operations are NOT thread-safe: Don't share arrays across tasks without proper synchronization.
  • Use actors to encapsulate MLX state: Create and use MLXArrays within the same actor.
  • Use wired-memory tickets for concurrent inference: Coordinate active/reservation budgets through the shared manager.

See concurrency.md for thread safety details.

Reference Documentation

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

コメント

ログインなしで書き込めます。使ってみた感想、質問、動かなかった環境などを気軽にどうぞ。

まだコメントはありません。最初のコメントを書いてみませんか。

送信するとすぐに公開されます。メールアドレスや電話番号などの個人情報は書かないでください。URL は 2 つまでです。

0 / 1000 文字

このフォームは reCAPTCHA で保護されており、Google のプライバシーポリシーと利用規約が適用されます。

同じリポジトリのスキル

Calendar

無料概要あり

予定の作成や日程の確認を行い、予定の件数や空き時間をもとに、今日や今週の忙しさ、会議を入れられる時間帯を整理するスキルです。

  • 会議や約束を登録したいとき
  • 今日や明日の予定を確認したいとき
  • 今週の忙しさを把握したいとき
kellyvv/PhoneClaw1,2842026年8月6日 更新

Clipboard

無料概要あり

システムのクリップボードからテキストを読み取り、頼まれた文章をコピーできます。内容の確認や、別の場所へ貼り付ける準備に使えます。

  • コピーした内容を確認したいとき
  • 文章をクリップボードへ移したいとき
  • 貼り付ける前に内容を読みたいとき
kellyvv/PhoneClaw1,2842026年8月6日 更新

Contacts

無料概要あり

連絡先を検索して電話番号やメールアドレスを確認し、新規登録や情報の更新、削除も行えます。名前や番号を手がかりに、連絡先をまとめて管理できます。

  • 連絡先の電話番号を調べたいとき
  • 新しい連絡先を保存したいとき
  • 登録済みの情報を更新したいとき
kellyvv/PhoneClaw1,2842026年8月6日 更新

Health

無料概要あり

HealthKitの歩数や運動、睡眠、心拍、体重を読み取り、端末内で日次の確認や期間を指定した健康データの要約を行います。

  • 今日や昨日の歩数を確認したいとき
  • 睡眠や心拍の記録を振り返りたいとき
  • 週単位・月単位の健康状況を知りたいとき
kellyvv/PhoneClaw1,2842026年8月6日 更新

Reminders

無料概要あり

指定した内容と時刻でリマインダーを作成します。いつ何を知らせるかを確認してから登録するため、日時を含む予定や用事を忘れないようにできます。

  • 用事を指定時刻に思い出したいとき
  • 買い物の予定を登録したいとき
  • 締め切り前の作業を忘れたくないとき
kellyvv/PhoneClaw1,2842026年8月6日 更新

swift-mlx-lm

無料概要あり

Apple Silicon上でMLXを使い、Swiftから言語モデルや画像対応モデルを動かす方法を扱います。ストリーミング生成、ツール呼び出し、LoRAによる追加学習、埋め込み生成やモデル移植も支援します。

  • SwiftアプリでローカルLLMを動かしたいとき
  • モデルの応答を逐次表示したいとき
  • 画像や動画をモデルに入力したいとき
kellyvv/PhoneClaw1,2842026年8月6日 更新

kellyvv のスキルをすべて見る

このスキルの問題を報告する