[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6C29YMVJ69AY6GH9RPJHPDN":3,"skill-same:01M6C29YMVJ69AY6GH9RPJHPDN":129},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":55,"commitSha":56,"skillDirectory":57,"forksCount":58,"repositoryHtmlUrl":59,"repositoryHomepageUrl":60,"ownerHtmlUrl":61,"ownerBlogUrl":62,"ownerDescription":63,"updatedAt":64,"install":65,"resources":78},"01M6C29YMVJ69AY6GH9RPJHPDN","swift-mlx-lm",null,"MLX Swift LM - Run LLMs and VLMs on Apple Silicon using MLX. Covers local inference, streaming, wired memory coordination, tool calling, LoRA fine-tuning, embeddings, and model porting.","jtrefon\u002Fcompass","jtrefon","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F5500074?v=4","01M6C29JGV8F2SZSGM2D4EF4HK","Jacek Trefon","01M6C29JNAZPME93JJVBGVPFD1",3,"MIT","https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"swift mlx lm","mlx","mlx lm","swift","Fine-Tuning","coordination","model","tool","apple silicon","tuning","LoRA","embeddings","streaming","run","training","support","memory","inference","llms","2026-11-10 10:12:30",false,"---\nname: swift-mlx-lm\ndescription: MLX Swift LM - Run LLMs and VLMs on Apple Silicon using MLX. Covers local inference, streaming, wired memory coordination, tool calling, LoRA fine-tuning, embeddings, and model porting.\ntriggers:\n  - mlx\n  - mlx-swift\n  - mlx-lm\n  - apple silicon llm\n  - local llm swift\n  - vision language model swift\n  - lora training swift\n  - wired memory\n  - wiredmemory\n  - wired memory ticket\n  - model porting\n  - add model support\n---\n\n# mlx-swift-lm Skill\n\n## 1. Overview & Triggers\n\nmlx-swift-lm is a Swift package for running Large Language Models (LLMs) and Vision-Language Models (VLMs) on Apple Silicon using MLX. It supports local inference, streaming generation, wired-memory coordination, tool calling, LoRA\u002FDoRA fine-tuning, and embeddings.\n\n### When to Use This Skill\n- Running LLM\u002FVLM inference on macOS\u002FiOS with Apple Silicon\n- Streaming text generation from local models\n- Coordinating concurrent inference with wired-memory policies and tickets\n- Tool calling \u002F function calling with models\n- LoRA adapter training and fine-tuning\n- Text embeddings for RAG\u002Fsemantic search\n- Porting model architectures from Python MLX-LM to Swift\n\n### Architecture Overview\n```\nMLXLMCommon     - Core infra (ModelContainer, ChatSession, Evaluate, KVCache, wired memory helpers)\nMLXLLM          - Text-only LLM support (Llama, Qwen, Gemma, Phi, DeepSeek, etc.)\nMLXVLM          - Vision-Language Models (Qwen-VL, PaliGemma, Gemma3, etc.)\nMLXEmbedders    - Embedding models and pooling utilities\n```\n\n## 2. Key File Reference\n\n| Purpose | File Path |\n|---------|-----------|\n| Thread-safe model wrapper | `Libraries\u002FMLXLMCommon\u002FModelContainer.swift` |\n| Simplified chat API | `Libraries\u002FMLXLMCommon\u002FChatSession.swift` |\n| Generation & streaming APIs | `Libraries\u002FMLXLMCommon\u002FEvaluate.swift` |\n| KV cache types | `Libraries\u002FMLXLMCommon\u002FKVCache.swift` |\n| Wired-memory policies | `Libraries\u002FMLXLMCommon\u002FWiredMemoryPolicies.swift` |\n| Wired-memory measurement helpers | `Libraries\u002FMLXLMCommon\u002FWiredMemoryUtils.swift` |\n| Model configuration | `Libraries\u002FMLXLMCommon\u002FModelConfiguration.swift` |\n| Chat message types | `Libraries\u002FMLXLMCommon\u002FChat.swift` |\n| Tool call processing | `Libraries\u002FMLXLMCommon\u002FTool\u002FToolCallFormat.swift` |\n| Concurrency utilities | `Libraries\u002FMLXLMCommon\u002FUtilities\u002FSerialAccessContainer.swift` |\n| LLM factory & registry | `Libraries\u002FMLXLLM\u002FLLMModelFactory.swift` |\n| VLM factory & registry | `Libraries\u002FMLXVLM\u002FVLMModelFactory.swift` |\n| LoRA configuration | `Libraries\u002FMLXLMCommon\u002FAdapters\u002FLoRA\u002FLoRAContainer.swift` |\n| LoRA training | `Libraries\u002FMLXLLM\u002FLoraTrain.swift` |\n\n## 3. Quick Start\n\n### LLM Chat (Simplest API)\n\n```swift\nimport MLXLLM\nimport MLXLMCommon\nimport MLXLMHuggingFace  \u002F\u002F from swift-huggingface-mlx\nimport MLXLMTokenizers   \u002F\u002F from swift-tokenizers-mlx\n\nlet modelContainer = try await LLMModelFactory.shared.loadContainer(\n    from: HubClient.default,\n    using: TokenizersLoader(),\n    configuration: .init(id: \"mlx-community\u002FQwen3-4B-4bit\")\n)\n\nlet session = ChatSession(modelContainer)\n\nlet response = try await session.respond(to: \"What is Swift?\")\nprint(response)\n\nfor try await chunk in session.streamResponse(to: \"Explain structured concurrency\") {\n    print(chunk, terminator: \"\")\n}\n```\n\n### VLM with Image\n\n```swift\nimport MLXVLM\nimport MLXLMCommon\nimport MLXLMHuggingFace  \u002F\u002F from swift-huggingface-mlx\nimport MLXLMTokenizers   \u002F\u002F from swift-tokenizers-mlx\n\nlet modelContainer = try await VLMModelFactory.shared.loadContainer(\n    from: HubClient.default,\n    using: TokenizersLoader(),\n    configuration: .init(id: \"mlx-community\u002FQwen2-VL-2B-Instruct-4bit\")\n)\n\nlet session = ChatSession(modelContainer)\nlet image = UserInput.Image.url(imageURL)\n\nlet response = try await session.respond(\n    to: \"Describe this image\",\n    image: image,\n    video: nil\n)\n```\n\n### Embeddings\n\n```swift\nimport MLXEmbedders\nimport MLXEmbeddersHuggingFace  \u002F\u002F from swift-huggingface-mlx\nimport MLXLMTokenizers          \u002F\u002F from swift-tokenizers-mlx\n\nlet container = try await loadModelContainer(\n    from: HubClient.default,\n    using: TokenizersLoader(),\n    configuration: ModelConfiguration(id: \"mlx-community\u002Fbge-small-en-v1.5-mlx\")\n)\n\nlet embeddings = await container.perform { model, tokenizer, pooler in\n    let tokens = tokenizer.encode(text: \"Hello world\")\n    let input = MLXArray(tokens).expandedDimensions(axis: 0)\n    let output = model(input)\n    let pooled = pooler(output, normalize: true)\n    eval(pooled)\n    return pooled\n}\n```\n\n## 4. Primary Workflow: LLM Inference\n\n### ChatSession API (Recommended)\n\n`ChatSession` manages conversation history and KV cache automatically:\n\n```swift\nlet session = ChatSession(\n    modelContainer,\n    instructions: \"You are a helpful assistant\",\n    generateParameters: GenerateParameters(maxTokens: 500, temperature: 0.7)\n)\n\nlet r1 = try await session.respond(to: \"What is 2+2?\")\nlet r2 = try await session.respond(to: \"And if you multiply that by 3?\")\n\nawait session.clear()\n```\n\n### Streaming with `ModelContainer.generate(...)`\n\nFor lower-level control, prepare `UserInput` and generate directly:\n\n```swift\nlet userInput = UserInput(prompt: \"Hello\")\nlet lmInput = try await modelContainer.prepare(input: userInput)\n\nlet stream = try await modelContainer.generate(\n    input: lmInput,\n    parameters: GenerateParameters()\n)\n\nfor await generation in stream {\n    switch generation {\n    case .chunk(let text):\n        print(text, terminator: \"\")\n    case .toolCall(let call):\n        print(\"Tool call: \\(call.function.name)\")\n    case .info(let info):\n        print(\"\\nStop reason: \\(info.stopReason)\")\n        print(\"\\(info.tokensPerSecond) tok\u002Fs\")\n    }\n}\n```\n\n### Generation API Surface (Evaluate.swift)\n\nUse these depending on your control needs:\n\n- `generate(input:..., context:..., wiredMemoryTicket:) -> AsyncStream\u003CGeneration>`: decoded text + tool calls.\n- `generateTask(..., wiredMemoryTicket:) -> (AsyncStream\u003CGeneration>, Task\u003CVoid, Never>)`: same output, plus task handle for deterministic cleanup when consumers stop early.\n- `generateTokens(..., wiredMemoryTicket:) -> AsyncStream\u003CTokenGeneration>`: raw token IDs.\n- `generateTokensTask(..., wiredMemoryTicket:) -> (AsyncStream\u003CTokenGeneration>, Task\u003CVoid, Never>)`: raw tokens + task handle.\n- `GenerateStopReason`: `.stop`, `.length`, `.cancelled` in final `.info`.\n\nSee [references\u002Fgeneration.md](references\u002Fgeneration.md) for full patterns.\n\n### Tool Calling\n\n```swift\nstruct WeatherInput: Codable { let location: String }\nstruct WeatherOutput: Codable { let temperature: Double; let conditions: String }\n\nlet weatherTool = Tool\u003CWeatherInput, WeatherOutput>(\n    name: \"get_weather\",\n    description: \"Get current weather\",\n    parameters: [.required(\"location\", type: .string, description: \"City name\")]\n) { _ in\n    WeatherOutput(temperature: 22.0, conditions: \"Sunny\")\n}\n\nlet userInput = UserInput(\n    prompt: .text(\"What's the weather in Tokyo?\"),\n    tools: [weatherTool.schema]\n)\n\nlet lmInput = try await modelContainer.prepare(input: userInput)\nlet stream = try await modelContainer.generate(input: lmInput, parameters: GenerateParameters())\n\nfor await generation in stream {\n    switch generation {\n    case .chunk(let text):\n        print(text, terminator: \"\")\n    case .toolCall(let call):\n        let result = try await call.execute(with: weatherTool)\n        print(\"\\nWeather: \\(result.conditions)\")\n    case .info:\n        break\n    }\n}\n```\n\nSee [references\u002Ftool-calling.md](references\u002Ftool-calling.md) for multi-turn tool loops.\n\n### GenerateParameters\n\n```swift\nlet params = GenerateParameters(\n    maxTokens: 1000,            \u002F\u002F nil = unlimited\n    maxKVSize: 4096,            \u002F\u002F Sliding window (RotatingKVCache)\n    kvBits: 4,                  \u002F\u002F Quantized cache (4 or 8)\n    kvGroupSize: 64,            \u002F\u002F Quantization group size\n    quantizedKVStart: 0,        \u002F\u002F Token index to start KV quantization\n    temperature: 0.7,           \u002F\u002F 0 = greedy \u002F argmax\n    topP: 0.9,                  \u002F\u002F Nucleus sampling\n    repetitionPenalty: 1.1,     \u002F\u002F Penalize repeats\n    repetitionContextSize: 20,  \u002F\u002F Penalty window\n    prefillStepSize: 512        \u002F\u002F Prompt prefill chunk size\n)\n```\n\n### Wired Memory (Optional)\n\nUse policy tickets to coordinate concurrent inference memory:\n\n```swift\nlet policy = WiredSumPolicy()\nlet ticket = policy.ticket(size: estimatedBytes, kind: .active)\n\nlet userInput = UserInput(prompt: \"Summarize this text\")\nlet lmInput = try await modelContainer.prepare(input: userInput)\n\nlet stream = try await modelContainer.generate(\n    input: lmInput,\n    parameters: GenerateParameters(),\n    wiredMemoryTicket: ticket\n)\n\nfor await generation in stream {\n    if case .chunk(let text) = generation {\n        print(text, terminator: \"\")\n    }\n}\n```\n\nFor policy selection, reservations, and measurement-based budgeting, see [references\u002Fwired-memory.md](references\u002Fwired-memory.md).\n\n### Prompt Caching \u002F History Re-hydration\n\n```swift\nlet history: [Chat.Message] = [\n    .system(\"You are helpful\"),\n    .user(\"Hello\"),\n    .assistant(\"Hi there!\")\n]\n\nlet session = ChatSession(modelContainer, history: history)\n```\n\n## 5. Secondary Workflow: VLM Inference\n\n### Image Input Types\n\n```swift\nlet imageFromURL = UserInput.Image.url(fileURL)\nlet imageFromCI = UserInput.Image.ciImage(ciImage)\nlet imageFromArray = UserInput.Image.array(mlxArray)\n```\n\n### Video Input\n\n```swift\nlet videoFromURL = UserInput.Video.url(videoURL)\nlet videoFromAsset = UserInput.Video.avAsset(avAsset)\nlet videoFromFrames = UserInput.Video.frames(videoFrames)\n\nlet response = try await session.respond(to: \"What happens in this video?\", video: videoFromURL)\n```\n\n### Multiple Images\n\n```swift\nlet images: [UserInput.Image] = [.url(url1), .url(url2)]\nlet response = try await session.respond(to: \"Compare these two images\", images: images, videos: [])\n```\n\n### VLM-Specific Processing\n\n```swift\nlet session = ChatSession(\n    modelContainer,\n    processing: UserInput.Processing(resize: CGSize(width: 512, height: 512))\n)\n```\n\n## 6. Best Practices\n\n### DO\n\n```swift\n\u002F\u002F DO: Prefer ChatSession for multi-turn chat UX\nlet session = ChatSession(modelContainer)\n\n\u002F\u002F DO: Prepare UserInput before container-level generation\nlet userInput = UserInput(prompt: \"Hello\")\nlet lmInput = try await modelContainer.prepare(input: userInput)\n\n\u002F\u002F DO: Use task-handle variants for early-stop scenarios\nlet (stream, task) = generateTask(\n    promptTokenCount: lmInput.text.tokens.size,\n    modelConfiguration: context.configuration,\n    tokenizer: context.tokenizer,\n    iterator: iterator\n)\nfor await item in stream {\n    if shouldStop { break }\n}\nawait task.value\n\n\u002F\u002F DO: Use wired tickets when coordinating concurrent workloads\nlet ticket = WiredSumPolicy().ticket(size: estimatedBytes)\nlet _ = try await modelContainer.generate(input: lmInput, parameters: params, wiredMemoryTicket: ticket)\n```\n\n### DON'T\n\n```swift\n\u002F\u002F DON'T: Skip prepare(input:) before container-level generation.\n\u002F\u002F ModelContainer.generate expects LMInput, not UserInput.\n\n\u002F\u002F DON'T: Share MLXArray across tasks (not Sendable)\nlet array = MLXArray(...)\nTask { _ = array.sum() } \u002F\u002F wrong\n\n\u002F\u002F DON'T: Ignore task completion after early-break on low-level streams\nfor await item in stream {\n    if shouldStop { break }\n}\n\u002F\u002F await task.value is required for deterministic cleanup\n```\n\n### Thread Safety\n\n- `ModelContainer` is `Sendable` and thread-safe.\n- `ChatSession` is not thread-safe; use one session per task\u002Fflow.\n- `MLXArray` is not `Sendable`; keep it inside one isolation domain or use `SendableBox` transfer patterns.\n\n### Memory Management\n\n```swift\nlet slidingWindow = GenerateParameters(maxKVSize: 4096)\nlet quantizedKV = GenerateParameters(kvBits: 4, kvGroupSize: 64)\nawait session.clear()\n```\n\n## 7. Reference Links\n\n| Reference | When to Use |\n|-----------|-------------|\n| [references\u002Fmodel-container.md](references\u002Fmodel-container.md) | Loading models, ModelContainer API, ModelConfiguration |\n| [references\u002Fgeneration.md](references\u002Fgeneration.md) | `generate`, `generateTask`, raw token streaming APIs |\n| [references\u002Fwired-memory.md](references\u002Fwired-memory.md) | Wired tickets, policies, budgeting, reservations |\n| [references\u002Fkv-cache.md](references\u002Fkv-cache.md) | Cache types, memory optimization, cache serialization |\n| [references\u002Fconcurrency.md](references\u002Fconcurrency.md) | Thread safety, SerialAccessContainer, async patterns |\n| [references\u002Ftool-calling.md](references\u002Ftool-calling.md) | Function calling, tool formats, ToolCallProcessor |\n| [references\u002Ftokenizer-chat.md](references\u002Ftokenizer-chat.md) | Tokenizer, Chat.Message, EOS tokens |\n| [references\u002Fsupported-models.md](references\u002Fsupported-models.md) | Model families, registries, model-specific config |\n| [references\u002Flora-adapters.md](references\u002Flora-adapters.md) | LoRA\u002FDoRA\u002FQLoRA, loading adapters |\n| [references\u002Ftraining.md](references\u002Ftraining.md) | LoRATrain API, fine-tuning |\n| [references\u002Fembeddings.md](references\u002Fembeddings.md) | EmbeddingModel, pooling, use cases |\n| [references\u002Fmodel-porting.md](references\u002Fmodel-porting.md) | Porting models from Python MLX-LM to Swift |\n\n## 8. Deprecated Patterns Summary\n\n| If you see... | Use instead... |\n|---------------|----------------|\n| `generate(... didGenerate:)` callback | AsyncStream-based generation APIs |\n| `perform { model, tokenizer in }` | `perform { context in }` |\n| `TokenIterator(prompt: MLXArray)` | `TokenIterator(input: LMInput)` |\n| `ModelRegistry` typealias | `LLMRegistry` or `VLMRegistry` |\n| `createAttentionMask(h:cache:[KVCache]?)` | `createAttentionMask(h:cache:KVCache?)` |\n\n## 9. Automatic vs Manual Configuration\n\n### Automatic Behaviors\n\n| Feature | Details |\n|---------|---------|\n| EOS token loading | Loaded from `config.json` |\n| EOS override | `generation_config.json` > `config.json` > defaults |\n| EOS merging | All sources merged at generation time |\n| EOS detection | Stops generation when EOS encountered |\n| Chat template application | Applied by tokenizer \u002F processor path |\n| Tool call format detection | Inferred from `model_type` in `config.json` |\n| Cache type selection | Driven by `GenerateParameters` (`maxKVSize`, `kvBits`) |\n| Tokenizer loading | Loaded automatically from model assets |\n| Model weight loading | Downloaded and loaded from Hugging Face\u002Flocal directory |\n\n### Optional Configuration\n\n| Feature | When to Configure |\n|---------|-------------------|\n| `extraEOSTokens` | Model has unlisted stop tokens |\n| `toolCallFormat` | Override auto-detected tool parser format |\n| `maxKVSize` | Enable sliding window cache |\n| `kvBits`, `kvGroupSize`, `quantizedKVStart` | Enable and tune KV quantization |\n| `prefillStepSize` | Tune prompt prefill chunking\u002Fperf tradeoff |\n| `wiredMemoryTicket` | Coordinate policy-based wired-memory limits |\n","# mlx-swift-lm Skill\n\n## 1. Overview & Triggers\n\nmlx-swift-lm is a Swift package for running Large Language Models (LLMs) and Vision-Language Models (VLMs) on Apple Silicon using MLX. It supports local inference, streaming generation, wired-memory coordination, tool calling, LoRA\u002FDoRA fine-tuning, and embeddings.\n\n### When to Use This Skill\n- Running LLM\u002FVLM inference on macOS\u002FiOS with Apple Silicon\n- Streaming text generation from local models\n- Coordinating concurrent inference with wired-memory policies and tickets\n- Tool calling \u002F function calling with models\n- LoRA adapter training and fine-tuning\n- Text embeddings for RAG\u002Fsemantic search\n- Porting model architectures from Python MLX-LM to Swift\n\n### Architecture Overview\n```\nMLXLMCommon     - Core infra (ModelContainer, ChatSession, Evaluate, KVCache, wired memory helpers)\nMLXLLM          - Text-only LLM support (Llama, Qwen, Gemma, Phi, DeepSeek, etc.)\nMLXVLM          - Vision-Language Models (Qwen-VL, PaliGemma, Gemma3, etc.)\nMLXEmbedders    - Embedding models and pooling utilities\n```\n\n## 2. Key File Reference\n\n| Purpose | File Path |\n|---------|-----------|\n| Thread-safe model wrapper | `Libraries\u002FMLXLMCommon\u002FModelContainer.swift` |\n| Simplified chat API | `Libraries\u002FMLXLMCommon\u002FChatSession.swift` |\n| Generation & streaming APIs | `Libraries\u002FMLXLMCommon\u002FEvaluate.swift` |\n| KV cache types | `Libraries\u002FMLXLMCommon\u002FKVCache.swift` |\n| Wired-memory policies | `Libraries\u002FMLXLMCommon\u002FWiredMemoryPolicies.swift` |\n| Wired-memory measurement helpers | `Libraries\u002FMLXLMCommon\u002FWiredMemoryUtils.swift` |\n| Model configuration | `Libraries\u002FMLXLMCommon\u002FModelConfiguration.swift` |\n| Chat message types | `Libraries\u002FMLXLMCommon\u002FChat.swift` |\n| Tool call processing | `Libraries\u002FMLXLMCommon\u002FTool\u002FToolCallFormat.swift` |\n| Concurrency utilities | `Libraries\u002FMLXLMCommon\u002FUtilities\u002FSerialAccessContainer.swift` |\n| LLM factory & registry | `Libraries\u002FMLXLLM\u002FLLMModelFactory.swift` |\n| VLM factory & registry | `Libraries\u002FMLXVLM\u002FVLMModelFactory.swift` |\n| LoRA configuration | `Libraries\u002FMLXLMCommon\u002FAdapters\u002FLoRA\u002FLoRAContainer.swift` |\n| LoRA training | `Libraries\u002FMLXLLM\u002FLoraTrain.swift` |\n\n## 3. Quick Start\n\n### LLM Chat (Simplest API)\n\n```swift\nimport MLXLLM\nimport MLXLMCommon\nimport MLXLMHuggingFace  \u002F\u002F from swift-huggingface-mlx\nimport MLXLMTokenizers   \u002F\u002F from swift-tokenizers-mlx\n\nlet modelContainer = try await LLMModelFactory.shared.loadContainer(\n    from: HubClient.default,\n    using: TokenizersLoader(),\n    configuration: .init(id: \"mlx-community\u002FQwen3-4B-4bit\")\n)\n\nlet session = ChatSession(modelContainer)\n\nlet response = try await session.respond(to: \"What is Swift?\")\nprint(response)\n\nfor try await chunk in session.streamResponse(to: \"Explain structured concurrency\") {\n    print(chunk, terminator: \"\")\n}\n```\n\n### VLM with Image\n\n```swift\nimport MLXVLM\nimport MLXLMCommon\nimport MLXLMHuggingFace  \u002F\u002F from swift-huggingface-mlx\nimport MLXLMTokenizers   \u002F\u002F from swift-tokenizers-mlx\n\nlet modelContainer = try await VLMModelFactory.shared.loadContainer(\n    from: HubClient.default,\n    using: TokenizersLoader(),\n    configuration: .init(id: \"mlx-community\u002FQwen2-VL-2B-Instruct-4bit\")\n)\n\nlet session = ChatSession(modelContainer)\nlet image = UserInput.Image.url(imageURL)\n\nlet response = try await session.respond(\n    to: \"Describe this image\",\n    image: image,\n    video: nil\n)\n```\n\n### Embeddings\n\n```swift\nimport MLXEmbedders\nimport MLXEmbeddersHuggingFace  \u002F\u002F from swift-huggingface-mlx\nimport MLXLMTokenizers          \u002F\u002F from swift-tokenizers-mlx\n\nlet container = try await loadModelContainer(\n    from: HubClient.default,\n    using: TokenizersLoader(),\n    configuration: ModelConfiguration(id: \"mlx-community\u002Fbge-small-en-v1.5-mlx\")\n)\n\nlet embeddings = await container.perform { model, tokenizer, pooler in\n    let tokens = tokenizer.encode(text: \"Hello world\")\n    let input = MLXArray(tokens).expandedDimensions(axis: 0)\n    let output = model(input)\n    let pooled = pooler(output, normalize: true)\n    eval(pooled)\n    return pooled\n}\n```\n\n## 4. Primary Workflow: LLM Inference\n\n### ChatSession API (Recommended)\n\n`ChatSession` manages conversation history and KV cache automatically:\n\n```swift\nlet session = ChatSession(\n    modelContainer,\n    instructions: \"You are a helpful assistant\",\n    generateParameters: GenerateParameters(maxTokens: 500, temperature: 0.7)\n)\n\nlet r1 = try await session.respond(to: \"What is 2+2?\")\nlet r2 = try await session.respond(to: \"And if you multiply that by 3?\")\n\nawait session.clear()\n```\n\n### Streaming with `ModelContainer.generate(...)`\n\nFor lower-level control, prepare `UserInput` and generate directly:\n\n```swift\nlet userInput = UserInput(prompt: \"Hello\")\nlet lmInput = try await modelContainer.prepare(input: userInput)\n\nlet stream = try await modelContainer.generate(\n    input: lmInput,\n    parameters: GenerateParameters()\n)\n\nfor await generation in stream {\n    switch generation {\n    case .chunk(let text):\n        print(text, terminator: \"\")\n    case .toolCall(let call):\n        print(\"Tool call: \\(call.function.name)\")\n    case .info(let info):\n        print(\"\\nStop reason: \\(info.stopReason)\")\n        print(\"\\(info.tokensPerSecond) tok\u002Fs\")\n    }\n}\n```\n\n### Generation API Surface (Evaluate.swift)\n\nUse these depending on your control needs:\n\n- `generate(input:..., context:..., wiredMemoryTicket:) -> AsyncStream\u003CGeneration>`: decoded text + tool calls.\n- `generateTask(..., wiredMemoryTicket:) -> (AsyncStream\u003CGeneration>, Task\u003CVoid, Never>)`: same output, plus task handle for deterministic cleanup when consumers stop early.\n- `generateTokens(..., wiredMemoryTicket:) -> AsyncStream\u003CTokenGeneration>`: raw token IDs.\n- `generateTokensTask(..., wiredMemoryTicket:) -> (AsyncStream\u003CTokenGeneration>, Task\u003CVoid, Never>)`: raw tokens + task handle.\n- `GenerateStopReason`: `.stop`, `.length`, `.cancelled` in final `.info`.\n\nSee [references\u002Fgeneration.md](references\u002Fgeneration.md) for full patterns.\n\n### Tool Calling\n\n```swift\nstruct WeatherInput: Codable { let location: String }\nstruct WeatherOutput: Codable { let temperature: Double; let conditions: String }\n\nlet weatherTool = Tool\u003CWeatherInput, WeatherOutput>(\n    name: \"get_weather\",\n    description: \"Get current weather\",\n    parameters: [.required(\"location\", type: .string, description: \"City name\")]\n) { _ in\n    WeatherOutput(temperature: 22.0, conditions: \"Sunny\")\n}\n\nlet userInput = UserInput(\n    prompt: .text(\"What's the weather in Tokyo?\"),\n    tools: [weatherTool.schema]\n)\n\nlet lmInput = try await modelContainer.prepare(input: userInput)\nlet stream = try await modelContainer.generate(input: lmInput, parameters: GenerateParameters())\n\nfor await generation in stream {\n    switch generation {\n    case .chunk(let text):\n        print(text, terminator: \"\")\n    case .toolCall(let call):\n        let result = try await call.execute(with: weatherTool)\n        print(\"\\nWeather: \\(result.conditions)\")\n    case .info:\n        break\n    }\n}\n```\n\nSee [references\u002Ftool-calling.md](references\u002Ftool-calling.md) for multi-turn tool loops.\n\n### GenerateParameters\n\n```swift\nlet params = GenerateParameters(\n    maxTokens: 1000,            \u002F\u002F nil = unlimited\n    maxKVSize: 4096,            \u002F\u002F Sliding window (RotatingKVCache)\n    kvBits: 4,                  \u002F\u002F Quantized cache (4 or 8)\n    kvGroupSize: 64,            \u002F\u002F Quantization group size\n    quantizedKVStart: 0,        \u002F\u002F Token index to start KV quantization\n    temperature: 0.7,           \u002F\u002F 0 = greedy \u002F argmax\n    topP: 0.9,                  \u002F\u002F Nucleus sampling\n    repetitionPenalty: 1.1,     \u002F\u002F Penalize repeats\n    repetitionContextSize: 20,  \u002F\u002F Penalty window\n    prefillStepSize: 512        \u002F\u002F Prompt prefill chunk size\n)\n```\n\n### Wired Memory (Optional)\n\nUse policy tickets to coordinate concurrent inference memory:\n\n```swift\nlet policy = WiredSumPolicy()\nlet ticket = policy.ticket(size: estimatedBytes, kind: .active)\n\nlet userInput = UserInput(prompt: \"Summarize this text\")\nlet lmInput = try await modelContainer.prepare(input: userInput)\n\nlet stream = try await modelContainer.generate(\n    input: lmInput,\n    parameters: GenerateParameters(),\n    wiredMemoryTicket: ticket\n)\n\nfor await generation in stream {\n    if case .chunk(let text) = generation {\n        print(text, terminator: \"\")\n    }\n}\n```\n\nFor policy selection, reservations, and measurement-based budgeting, see [references\u002Fwired-memory.md](references\u002Fwired-memory.md).\n\n### Prompt Caching \u002F History Re-hydration\n\n```swift\nlet history: [Chat.Message] = [\n    .system(\"You are helpful\"),\n    .user(\"Hello\"),\n    .assistant(\"Hi there!\")\n]\n\nlet session = ChatSession(modelContainer, history: history)\n```\n\n## 5. Secondary Workflow: VLM Inference\n\n### Image Input Types\n\n```swift\nlet imageFromURL = UserInput.Image.url(fileURL)\nlet imageFromCI = UserInput.Image.ciImage(ciImage)\nlet imageFromArray = UserInput.Image.array(mlxArray)\n```\n\n### Video Input\n\n```swift\nlet videoFromURL = UserInput.Video.url(videoURL)\nlet videoFromAsset = UserInput.Video.avAsset(avAsset)\nlet videoFromFrames = UserInput.Video.frames(videoFrames)\n\nlet response = try await session.respond(to: \"What happens in this video?\", video: videoFromURL)\n```\n\n### Multiple Images\n\n```swift\nlet images: [UserInput.Image] = [.url(url1), .url(url2)]\nlet response = try await session.respond(to: \"Compare these two images\", images: images, videos: [])\n```\n\n### VLM-Specific Processing\n\n```swift\nlet session = ChatSession(\n    modelContainer,\n    processing: UserInput.Processing(resize: CGSize(width: 512, height: 512))\n)\n```\n\n## 6. Best Practices\n\n### DO\n\n```swift\n\u002F\u002F DO: Prefer ChatSession for multi-turn chat UX\nlet session = ChatSession(modelContainer)\n\n\u002F\u002F DO: Prepare UserInput before container-level generation\nlet userInput = UserInput(prompt: \"Hello\")\nlet lmInput = try await modelContainer.prepare(input: userInput)\n\n\u002F\u002F DO: Use task-handle variants for early-stop scenarios\nlet (stream, task) = generateTask(\n    promptTokenCount: lmInput.text.tokens.size,\n    modelConfiguration: context.configuration,\n    tokenizer: context.tokenizer,\n    iterator: iterator\n)\nfor await item in stream {\n    if shouldStop { break }\n}\nawait task.value\n\n\u002F\u002F DO: Use wired tickets when coordinating concurrent workloads\nlet ticket = WiredSumPolicy().ticket(size: estimatedBytes)\nlet _ = try await modelContainer.generate(input: lmInput, parameters: params, wiredMemoryTicket: ticket)\n```\n\n### DON'T\n\n```swift\n\u002F\u002F DON'T: Skip prepare(input:) before container-level generation.\n\u002F\u002F ModelContainer.generate expects LMInput, not UserInput.\n\n\u002F\u002F DON'T: Share MLXArray across tasks (not Sendable)\nlet array = MLXArray(...)\nTask { _ = array.sum() } \u002F\u002F wrong\n\n\u002F\u002F DON'T: Ignore task completion after early-break on low-level streams\nfor await item in stream {\n    if shouldStop { break }\n}\n\u002F\u002F await task.value is required for deterministic cleanup\n```\n\n### Thread Safety\n\n- `ModelContainer` is `Sendable` and thread-safe.\n- `ChatSession` is not thread-safe; use one session per task\u002Fflow.\n- `MLXArray` is not `Sendable`; keep it inside one isolation domain or use `SendableBox` transfer patterns.\n\n### Memory Management\n\n```swift\nlet slidingWindow = GenerateParameters(maxKVSize: 4096)\nlet quantizedKV = GenerateParameters(kvBits: 4, kvGroupSize: 64)\nawait session.clear()\n```\n\n## 7. Reference Links\n\n| Reference | When to Use |\n|-----------|-------------|\n| [references\u002Fmodel-container.md](references\u002Fmodel-container.md) | Loading models, ModelContainer API, ModelConfiguration |\n| [references\u002Fgeneration.md](references\u002Fgeneration.md) | `generate`, `generateTask`, raw token streaming APIs |\n| [references\u002Fwired-memory.md](references\u002Fwired-memory.md) | Wired tickets, policies, budgeting, reservations |\n| [references\u002Fkv-cache.md](references\u002Fkv-cache.md) | Cache types, memory optimization, cache serialization |\n| [references\u002Fconcurrency.md](references\u002Fconcurrency.md) | Thread safety, SerialAccessContainer, async patterns |\n| [references\u002Ftool-calling.md](references\u002Ftool-calling.md) | Function calling, tool formats, ToolCallProcessor |\n| [references\u002Ftokenizer-chat.md](references\u002Ftokenizer-chat.md) | Tokenizer, Chat.Message, EOS tokens |\n| [references\u002Fsupported-models.md](references\u002Fsupported-models.md) | Model families, registries, model-specific config |\n| [references\u002Flora-adapters.md](references\u002Flora-adapters.md) | LoRA\u002FDoRA\u002FQLoRA, loading adapters |\n| [references\u002Ftraining.md](references\u002Ftraining.md) | LoRATrain API, fine-tuning |\n| [references\u002Fembeddings.md](references\u002Fembeddings.md) | EmbeddingModel, pooling, use cases |\n| [references\u002Fmodel-porting.md](references\u002Fmodel-porting.md) | Porting models from Python MLX-LM to Swift |\n\n## 8. Deprecated Patterns Summary\n\n| If you see... | Use instead... |\n|---------------|----------------|\n| `generate(... didGenerate:)` callback | AsyncStream-based generation APIs |\n| `perform { model, tokenizer in }` | `perform { context in }` |\n| `TokenIterator(prompt: MLXArray)` | `TokenIterator(input: LMInput)` |\n| `ModelRegistry` typealias | `LLMRegistry` or `VLMRegistry` |\n| `createAttentionMask(h:cache:[KVCache]?)` | `createAttentionMask(h:cache:KVCache?)` |\n\n## 9. Automatic vs Manual Configuration\n\n### Automatic Behaviors\n\n| Feature | Details |\n|---------|---------|\n| EOS token loading | Loaded from `config.json` |\n| EOS override | `generation_config.json` > `config.json` > defaults |\n| EOS merging | All sources merged at generation time |\n| EOS detection | Stops generation when EOS encountered |\n| Chat template application | Applied by tokenizer \u002F processor path |\n| Tool call format detection | Inferred from `model_type` in `config.json` |\n| Cache type selection | Driven by `GenerateParameters` (`maxKVSize`, `kvBits`) |\n| Tokenizer loading | Loaded automatically from model assets |\n| Model weight loading | Downloaded and loaded from Hugging Face\u002Flocal directory |\n\n### Optional Configuration\n\n| Feature | When to Configure |\n|---------|-------------------|\n| `extraEOSTokens` | Model has unlisted stop tokens |\n| `toolCallFormat` | Override auto-detected tool parser format |\n| `maxKVSize` | Enable sliding window cache |\n| `kvBits`, `kvGroupSize`, `quantizedKVStart` | Enable and tune KV quantization |\n| `prefillStepSize` | Tune prompt prefill chunking\u002Fperf tradeoff |\n| `wiredMemoryTicket` | Coordinate policy-based wired-memory limits |\n",{"name":5,"triggers":43,"description":7},[20,44,45,46,47,48,49,50,51,52,53,54],"mlx-swift","mlx-lm","apple silicon llm","local llm swift","vision language model swift","lora training swift","wired memory","wiredmemory","wired memory ticket","model porting","add model support","main","cf1422d1df5cf1df987d1f299d74e0128a3c2b0b","Vendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm",0,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass","https:\u002F\u002Fjtrefon.github.io\u002Fcompass\u002F","https:\u002F\u002Fgithub.com\u002Fjtrefon","https:\u002F\u002Fwww.trefon.com","Visionary leader, technology enthusiast, innovator and disruptor. ","2026-11-14 08:47:15",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add jtrefon\u002Fcompass --skill swift-mlx-lm",{"tool":71,"command":72},"bunx","bunx skills add jtrefon\u002Fcompass --skill swift-mlx-lm",{"tool":74,"command":75},"pnpm","pnpm dlx skills add jtrefon\u002Fcompass --skill swift-mlx-lm","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002FSKILL.md",true,[79,85,89,93,97,101,105,109,113,117,121,125],{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Fconcurrency.md","REFERENCE","参考文档",8546,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fconcurrency.md",{"path":86,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":87,"sourceHtmlUrl":88},"references\u002Fembeddings.md",8160,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fembeddings.md",{"path":90,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":91,"sourceHtmlUrl":92},"references\u002Fgeneration.md",3949,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fgeneration.md",{"path":94,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":95,"sourceHtmlUrl":96},"references\u002Fkv-cache.md",7266,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fkv-cache.md",{"path":98,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":99,"sourceHtmlUrl":100},"references\u002Flora-adapters.md",7820,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Flora-adapters.md",{"path":102,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":103,"sourceHtmlUrl":104},"references\u002Fmodel-container.md",8957,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fmodel-container.md",{"path":106,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":107,"sourceHtmlUrl":108},"references\u002Fmodel-porting.md",13700,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fmodel-porting.md",{"path":110,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":111,"sourceHtmlUrl":112},"references\u002Fsupported-models.md",7399,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fsupported-models.md",{"path":114,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":115,"sourceHtmlUrl":116},"references\u002Ftokenizer-chat.md",7570,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Ftokenizer-chat.md",{"path":118,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":119,"sourceHtmlUrl":120},"references\u002Ftool-calling.md",9099,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Ftool-calling.md",{"path":122,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":123,"sourceHtmlUrl":124},"references\u002Ftraining.md",9165,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Ftraining.md",{"path":126,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":127,"sourceHtmlUrl":128},"references\u002Fwired-memory.md",3757,"https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002FVendor\u002Fmlx-swift-lm\u002Fskills\u002Fmlx-swift-lm\u002Freferences\u002Fwired-memory.md",[130,142,153],{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":38},"01M6C29VZXCDYSM59W486YE7FK","codacy-fix-issues","Find and fix issues in your project using Codacy local analysis","https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002F.devin\u002Fskills\u002Fcodacy-fix-issues\u002FSKILL.md",[],[137,138,139,140,141],"codacy fix issues","fix","issues","find","analysis",{"skillNo":143,"name":144,"nameZh":6,"description":145,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":146,"categories":147,"keywords":148,"publishedAt":38},"01M6C29S7890889XGRX52Q7XN5","codacy-check-coverage","Check code coverage of your project using Codacy","https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002F.devin\u002Fskills\u002Fcodacy-check-coverage\u002FSKILL.md",[],[149,150,151,152],"codacy check coverage","coverage","check","code",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":38},"01M6C29NJJZFPTCZDCJ3Y1ZKNA","deepcode-cardinal-rules","Cardinal rules for the Compass project. Use when writing, reviewing, or architecting code to avoid common LLM coding mistakes. Covers harness-vs-app separation, dead code detection, and build-first discipline.","https:\u002F\u002Fgithub.com\u002Fjtrefon\u002Fcompass\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdeepcode-cardinal-rules\u002FSKILL.md",[],[160,161,162,163,164,165,166,167,168,169,170,152],"Rules","deepcode cardinal rules","discipline","writing","use","common","coding","dead code","first","detection","harness"]