C.W.K.
Stream
Lesson 03 of 06 · published

MLX Swift — Python 이 답이 아닐 때

~14 min · swift, mlx-swift, ios-app

Level 0Curious
0 XP0/51 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Python 이 잘못된 도구일 때

MLX Quest 의 대부분이 Python 가정 — 대부분 ML 작업이 Python 에서 일어나니까. 근데 Python 이 옵션 아닌 배포 타겟 있어 — App Store 애플리케이션, iOS / macOS 앱 binary 안에 출하해야 하는 무엇이든, Swift 의 더 빡빡한 Apple 의 앱 framework 통합 필요한 시나리오. 그런 케이스에 mlx-swift 가 Swift API 표면 가진 같은 MLX framework.

Mental model 이 매우 적은 surprise 로 Python MLX 에서 carry over. Array 가 typed; lazy evaluation 이 기본; function transform 존재. Syntax 가 Swift-shape (Swift 의 let, type inference, value 의 method), 근데 개념적 API 가 평행.

MLX Swift 가 주는 것

  • Hood 아래 같은 MLX kernel — 성능이 같은 하드웨어의 Python MLX 와 비슷.
  • 앱-출하 path — iOS / macOS 앱 안에 MLX 박고 App Store 통해 출하 가능. Python 은 이거 못 함.
  • 빡빡한 Apple framework 통합 — SwiftUI, Combine, 그리고 Apple 의 앱 stack 의 나머지와 직접 interop.
  • 더 작은 배포 표면 — Python 인터프리터 없음, pip 의존성 없음, 출하할 virtual env 없음.

포기하는 것

  • 라이브러리 ecosystem — 대부분 ML 라이브러리 (Hugging Face transformers, 모든 convenience 가진 mlx-lm) 가 Python-first. mlx-swift 가 core 덮지만 full breadth 아님.
  • Iteration 속도 — Swift 의 edit-compile-run loop 가 Python 의 REPL 보다 느려. Python 에서 iterate; Swift 에서 ship.
  • 커뮤니티 크기 — Python MLX 가 더 많은 사용자, 더 많은 StackOverflow 답, 더 많은 예제 코드.

권장 워크플로

  1. Python MLX 에서 학습과 iterate. 실험 단계에 mlx-lm 또는 mlx-vlm 사용.
  2. 결과 변환 / fuse. LoRA fine-tune 했으면 배포 가능 모델로 fuse (Track 4 lesson 5).
  3. mlx-swift 통해 embed. Step 2 에서 생산한 같은 모델 디렉토리 로드; 파일 형식 동일.
  4. 앱 출하. 거기서 표준 iOS / macOS 배포.

이게 정확히 Ollama-on-Mac 이 사용하는 path. 배포 edge 의 언어가 Swift 라고 MLX path 가 안 변해.

Code

MLX Swift — 같은 array 연산, Swift syntax·swift
// Add mlx-swift via Swift Package Manager:
//   https://github.com/ml-explore/mlx-swift
import MLX

// Create arrays — same shape as Python MLX
let a = MLXArray([1.0, 2.0, 3.0, 4.0])
let b = MLXArray([5.0, 6.0, 7.0, 8.0])

// Operations — also same shape
let c = a + b
print(c)   // array([6, 8, 10, 12], dtype=float32)

// Lazy by default; eval to materialize
let d = a * b
d.eval()
print(d)   // array([5, 12, 21, 32], dtype=float32)

// Default device is GPU on Apple Silicon — no .to(device) ritual
print(MLX.defaultDevice())
SwiftUI 앱에 박기 (스케치)·swift
// SwiftUI view that runs MLX inference on a button tap.
import SwiftUI
import MLX
import MLXLLM   // mlx-swift's LLM extension package

struct ContentView: View {
    @State private var prompt: String = "Capital of France?"
    @State private var output: String = ""

    var body: some View {
        VStack {
            TextField("Prompt", text: $prompt)
            Button("Generate") {
                Task {
                    // Load model once at app start in production code.
                    let model = try await loadModel(...)
                    output = try await model.generate(prompt: prompt, maxTokens: 50)
                }
            }
            Text(output)
        }
    }
}

// In production, load the model once at app startup, not per tap.

External links

Exercise

Xcode 깔려 있으면 minimal Swift Package 또는 iOS / macOS 앱 만들고 Swift Package Manager 통해 mlx-swift 추가. 기본 array 연산 돌려 (이 레슨의 matmul 또는 add). Build 시간 vs Python iteration loop 알아채. 자기 사용 케이스에 Swift 의 배포 이야기가 iteration 비용 가치 있는지 두 문장.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.