<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Devamuthan Sankar on Medium]]></title>
        <description><![CDATA[Stories by Devamuthan Sankar on Medium]]></description>
        <link>https://medium.com/@devamuthansankar?source=rss-705e25a4f776------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lyrntPPxeEasAGdUQVZE0g.jpeg</url>
            <title>Stories by Devamuthan Sankar on Medium</title>
            <link>https://medium.com/@devamuthansankar?source=rss-705e25a4f776------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:28:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devamuthansankar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Smarter iOS Apps: Implementing Apple Intelligence with Foundation Model Framework]]></title>
            <link>https://medium.com/@devamuthansankar/implementing-apple-intelligence-50aa8ca6c52d?source=rss-705e25a4f776------2</link>
            <guid isPermaLink="false">https://medium.com/p/50aa8ca6c52d</guid>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[apple-intelligence]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Devamuthan Sankar]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 13:36:01 GMT</pubDate>
            <atom:updated>2025-08-29T09:40:27.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ek9BkZQBvVIkN0O" /></figure><p>Generative AI has rapidly transformed the landscape of modern app development, empowering applications with unprecedented intelligence, context-awareness, and responsiveness. Apple’s <strong>Foundation Model Framework</strong> is at the forefront of this shift, enabling developers to seamlessly integrate powerful generative capabilities directly into their iOS applications. Whether your goal is to enhance user personalization, automate content creation, or develop smarter interactive experiences, this practical guide will clearly walk you through the implementation process. Dive in to learn the essentials of managing sessions, handling errors gracefully, crafting effective prompts, and customizing generative models, helping you bring the full power of Apple Intelligence to your apps.</p><h3>Implementing Apple Intelligence in Apps</h3><p>Developers can begin interacting with Apple Intelligence using the <strong>Foundation Model Framework</strong>, which provides APIs to run on-device models and manage conversation sessions. Key components include:</p><p><strong>SystemLanguageModel</strong>:</p><ul><li>The default model available on-device, capable of text generation.</li></ul><p><strong>LanguageModelSession</strong>:</p><ul><li>Supports multi-turn conversations with persistent state.</li><li>Handles only one request at a time (subsequent calls before completion trigger errors).</li><li>Supports system prompts for defining model behaviour.</li><li>Context window limited to 4096 tokens — not ideal for chatbot-scale memory.</li></ul><p><strong>Transcript</strong>:</p><ul><li>Logs all session activity, allowing for replay or analysis of past interactions.</li></ul><p><strong>Prompting:</strong></p><ul><li>Prompt interaction with Apple’s models is handled primarily through two functions: respond and streamRespond.</li><li>The respond function is used for standard interactions, allowing developers to submit prompts and receive generated outputs in a single completion.</li><li>The streamRespond function enables developers to handle generated outputs incrementally, useful for real-time interfaces.</li></ul><pre>import Playgrounds<br>import FoundationModels<br><br>#Playground {<br>    // Default On-Device Language model<br>    let model = SystemLanguageModel.default <br>    // Check for model availability<br>    switch model.availability {<br>    case .available:<br>        print(&quot;Foundation Models are available&quot;)<br>    case .unavailable(.modelNotReady):<br>        print(&quot;Foundation Model not ready&quot;)<br>    case .unavailable(.deviceNotEligible):<br>        print(&quot;Device not eligible&quot;)<br>    case .unavailable(.appleIntelligenceNotEnabled):<br>        print(&quot;Apple Intelligence not enabled&quot;)<br>    case .unavailable(let reason):<br>        print(&quot;Model Unavailable: \(reason)&quot;)<br>    }<br>    <br>    if model.isAvailable {<br>        // Create Language Model session<br>        let modelSession = LanguageModelSession(model: model)<br>      <br>        do {<br>            // Standard usage of session<br>            try await modelSession.respond(to: &quot;Hi Model&quot;)<br>            // Streaming the model response<br>            let stream = try modelSession.streamResponse(to: &quot;Let&#39;s get a little deeper into the world of iOS&quot;)<br>            for try await streamData in stream {<br>                print(streamData)<br>            }<br>        } catch {...}<br>        <br>        // Transcript records all the input prompts and output responses<br>        print(&quot;Session Transcripts: \(modelSession.transcript)&quot;)<br>    }<br>}</pre><p><strong>Error Handling:</strong></p><p>While interacting with Foundation Models, developers should be aware of specific runtime errors and handle them gracefully within their applications:</p><ul><li><strong>GuardRailViolation</strong>: Apple’s built-in guardrails automatically scan content for safety concerns. If potentially unsafe content is detected, the model throws a guardRailViolation error. Developers have limited direct control over this process, but can manage such errors to maintain app stability.</li><li><strong>RateLimited</strong>: Each LanguageModelSession instance can only process one request at a time. If another prompt is sent before the previous request completes, a rateLimited error is triggered. Proper management of request sequencing is essential to avoid this.</li><li><strong>ExceededContextWindowSize</strong>: Every session instance has a fixed context window of 4096 tokens. Attempting to exceed this limit results in an exceededContextWindowSize error. Developers should monitor prompt lengths and session states closely to remain within context limits.</li></ul><pre>import Playgrounds<br>import FoundationModels<br><br>#Playground {<br>    let model = SystemLanguageModel.default<br>    <br>    switch model.availability {<br>      ...<br>    }<br>    <br>    if model.isAvailable {<br>        let modelSession = LanguageModelSession(model: model)<br>        <br>        do {<br>          ...<br>        } catch LanguageModelSession.GenerationError.guardrailViolation {<br>            print(&quot;The content contains some inappropriate language. Please try again with a different request.&quot;)<br>        } catch LanguageModelSession.GenerationError.rateLimited {<br>            print(&quot;A session can handle only one request at a time.&quot;)<br>        } catch LanguageModelSession.GenerationError.exceededContextWindowSize {<br>            print(&quot;Prompt exceeds context window, create a new session.&quot;)<br>        }<br>    }<br>}</pre><p><strong>Tools:</strong></p><ul><li>Foundation Models can invoke <strong>Tools</strong> — specialised actions or external data calls executed at runtime — to extend their capabilities beyond standard text generation.</li><li>These tools allow models to interact dynamically with app-specific logic or gather external information seamlessly within a conversation flow.</li></ul><p><strong>Guided Generation:</strong></p><p>Developers can precisely shape the model’s outputs using guided generation techniques provided by Apple using two Macros:</p><ul><li><strong>@Generable</strong>: Applied to Swift structs and enums to automatically map generated outputs into custom-defined Swift data structures.</li><li><strong>@Guide</strong>: Used to specify detailed instructions at the attribute level, enabling fine-grained control over how specific parts of the generated content should be structured or formatted.</li></ul><pre>import FoundationModels<br><br>@Generable // Structs or Enums has to be defines Generable<br>struct RequirementAnalysisPlan {<br>    // A Generatble structure may or may not contain Guided variables<br>    // Guided variables helps the model provide user intended generated response<br>    @Guide(description: &quot;A concise, engaging, and relevant title for the proposed business idea.&quot;)<br>    var title: String<br>    <br>    @Guide(description: &quot;An in-depth and comprehensive description outlining the purpose, key features, and potential impact of the proposed business idea.&quot;)<br>    var expandedDescription: String<br>    // Nested Generable Structure<br>    @Guide(description: &quot;A structured list of implementation phases detailing essential tasks, responsibilities, and timelines required to successfully deliver the project.&quot;)<br>    var phases: [Phase]<br>    <br>    @Guide(description: &quot;A carefully selected list of five technology recommendations that prioritize cost-efficiency, scalability, ease of maintenance, and alignment with the project&#39;s goals.&quot;)<br>    @Guide(.count(5)) // Limiting the number of response<br>    var techStackRecommendation: [String]<br>    @Guide(description: &quot;Recommended cloud technologies suitable for this project, ensuring services are relevant, compatible, and necessary. Specify &#39;None&#39; if cloud services are not applicable.&quot;)<br>    var cloudTechRecommendation: [String]<br>    @Guide(description: &quot;Overall estimated duration to complete the project, provided in weeks or months, adjusted realistically according to the team size.&quot;)<br>    var estimatedTimeToCompletion: String<br>    @Guide(description: &quot;Total estimated number of personnel needed across the entire lifecycle of the project, adjusted realistically based on team size and project complexity.&quot;)<br>    var totalTeamSizeEstimate: Int<br>}<br>@Generable<br>struct Phase {<br>    @Guide(description: &quot;The clear, descriptive name for this phase of the project, such as &#39;Planning&#39;, &#39;Design&#39;, or &#39;Deployment&#39;.&quot;)<br>    var name: String<br>    <br>    @Guide(description: &quot;Detailed summary of key responsibilities, objectives, and activities to be accomplished during this project phase.&quot;)<br>    var description: String<br>    @Guide(description: &quot;Projected duration required to complete this specific phase, specified in weeks or months.&quot;)<br>    var duration: String<br>    // Nested Generable Structure<br>    @Guide(description: &quot;Detailed tasks required to accomplish this phase.&quot;)<br>    var tasks: [RequirementTask]<br>}<br>@Generable<br>struct RequirementTask {<br>    @Guide(description: &quot;A clear, succinct title describing the main objective of this task.&quot;)<br>    var title: String<br>    <br>    @Guide(description: &quot;An explicit explanation detailing what actions or outcomes this task aims to achieve.&quot;)<br>    var description: String<br>    @Guide(description: &quot;Time estimated to complete this task, clearly specified in hours, days, or weeks.&quot;)<br>    var timeEstimate: String<br>    // Generable Enum used as guided property<br>    @Guide(description: &quot;Professional roles essential to complete this task (e.g., &#39;iOS Developer&#39;, &#39;UI Designer&#39;, &#39;Product Manager&#39;).&quot;)<br>    var roles: [Roles]<br>    @Guide(description: &quot;The specific number of personnel required to efficiently execute and complete this task.&quot;)<br>    var peopleRequired: Int<br>}<br>// Generable Enum<br>@Generable<br>enum Roles: String, CaseIterable {<br>    case iosDeveloper<br>    case productManager<br>    case buisnessAnalyst<br>    case uiDesigner<br>    case qaTester<br>}</pre><p>Usage:</p><pre>// modelSession: Instance of LanguageModelSession<br>func generateRequirement(text: String) async {<br>    guard text != &quot;&quot; else { return }<br>    do {<br>        let prompt: Prompt = .init(&quot;You are a business requirement analyst. Analyze the following idea: \(text)&quot;)<br>        let generation = try await modelSession.respond(<br>                generating: RequirementAnalysisPlan.self // Provide the Generable type<br>            ) { prompt }<br>        // Utilise the generated content<br>    } catch {<br>        // Handle Error<br>    }<br>}</pre><h3>Building Custom Adapters</h3><p>For more advanced use cases, developers can build their own <strong>custom adapters</strong> using Apple’s <strong>Adapter Training Kit</strong>, which supports training in Python.</p><p>The typical workflow includes:</p><ol><li>Downloading and setting up the toolkit</li><li>Preparing and preprocessing custom data</li><li>Training the adapter</li><li>Testing its performance</li><li>Exporting the adapter</li><li>Deploying it using the necessary <strong>entitlements</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBUdW_Ym-64wxGui8mamRw.png" /></figure><h4>Trade-offs and Limitations</h4><p>Despite their flexibility, custom adapters come with constraints:</p><ul><li>A new adapter must be built for each Foundation Model version</li><li>Older adapters become incompatible with newer model updates</li><li>Adapters significantly increase app size, making them impractical for small to mid-size apps</li></ul><p>Using the custom adapter:</p><pre>import Playgrounds<br>import FoundationModels<br><br>#Playground {<br>    // Use the custom built adapter for Language model<br>    let customModel = SystemLanguageModel(adapter: .init(name: &quot;custom-adapter&quot;))<br>    <br>    if model.isAvailable {<br>        // Language session using the custom adapter language model<br>        let customModelSession = LanguageModelSession(model: customModel)<br>        <br>        do {<br>          try await customModelSession.respond(to: &quot;Hi custom model&quot;)<br>          ...<br>        } catch { <br>          //Handle Error <br>        }<br>    }<br>}</pre><h3>Conclusion:</h3><p>Implementing Apple Intelligence with the Foundation Model Framework equips developers with the tools to create intelligent, context-aware apps that redefine user experience standards. By thoughtfully managing sessions, error handling, prompting, guided generation, and custom adapters, developers can effectively harness the power of on-device generative AI. This practical guide provides a solid foundation to experiment, innovate, and unlock new possibilities — positioning your iOS apps at the forefront of Apple’s evolving intelligent ecosystem.</p><h3>References:</h3><ul><li>Foundation Model Framework: <a href="https://developer.apple.com/documentation/FoundationModels">https://developer.apple.com/documentation/FoundationModels</a></li><li>Building Custom Adapters: <a href="https://developer.apple.com/apple-intelligence/foundation-models-adapter/">https://developer.apple.com/apple-intelligence/foundation-models-adapter/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50aa8ca6c52d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apple Intelligence Explained: The Technology Behind Apple’s On-Device Generative AI]]></title>
            <link>https://medium.com/@devamuthansankar/apple-intelligence-explained-081722e917c2?source=rss-705e25a4f776------2</link>
            <guid isPermaLink="false">https://medium.com/p/081722e917c2</guid>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[apple-intelligence]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Devamuthan Sankar]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 10:38:09 GMT</pubDate>
            <atom:updated>2025-07-28T10:38:09.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBpxrDxdYWqY9QJDQn-6ag.png" /></figure><p>Apple’s entry into the generative AI space is more than just another milestone in technology — it’s a deliberate and strategic leap toward privacy-focused, personalized intelligence. In this blog, we’ll explore the underlying technology of <strong>Apple Intelligence</strong>, unveiling the carefully constructed architectures, data strategies, training methodologies, and optimizations that power this revolutionary on-device AI. If you’ve ever wondered how Apple balances powerful generative capabilities with privacy, performance, and personalization, this theoretical exploration is your starting point.</p><h3>What Is Apple Intelligence?</h3><p>Apple Intelligence is a suite of highly capable generative models developed to support a range of everyday user tasks. These models are context-aware, adapting based on what the user is doing in real time.</p><p>At the core are <strong>Foundation Models</strong> that are fine-tuned for user-centric tasks like writing and refining text, summarising and prioritising notifications, generating images, and even performing in-app actions. With up to <strong>3 billion parameters</strong>, the models strike a balance between computational power and on-device efficiency.</p><p>This technology debuted with <strong>iOS 18 </strong>and has remained exclusive to Apple’s own system features. As of now, <strong>iOS 26 beta is publicly available</strong>, providing developers and users an early glimpse into future capabilities . However, full developer access to build and deploy custom experiences using Apple Intelligence is still expected to become broadly available with the <strong>final iOS 26 release</strong>.</p><h3>Foundation Models: On-Device vs. Server-Side</h3><p>Apple’s Foundation Models are available in two deployment configurations:</p><ul><li><strong>On-device models</strong></li><li><strong>Server-based models</strong> accessed securely via Apple’s <strong>Private Cloud Compute</strong></li></ul><p>In this post, we focus on the <strong>on-device models</strong>, which are integral to Apple’s privacy-first vision. These models ensure that sensitive data never leaves the device, while still delivering high-performance AI experiences.</p><h3>Under the Hood: Architecture of Apple’s Foundation Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-HH86xSphIk-IPzpA9erA.png" /></figure><p>To truly understand how Apple Intelligence works, it’s important to look at the architecture powering it. Apple’s Foundation Models are built on a carefully layered structure that balances performance, privacy, and flexibility. This architecture enables seamless deployment across both on-device and private cloud environments, while supporting real-time personalisation and efficient model execution.</p><h3>Data Collection and Preprocessing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joV_RSfYpDzf0Vv-Cg3BIQ.png" /><figcaption>Data Collection</figcaption></figure><p>To train these models, Apple relies on a combination of <strong>licensed data</strong> and <strong>public web content</strong>, the latter gathered using <strong>AppleBot</strong>, Apple’s proprietary web crawler.</p><p>Before training begins, Apple runs a robust preprocessing pipeline that includes:</p><ul><li><strong>Content filtering</strong>: Removing spam, profanity, and low-quality material.</li><li><strong>Privacy filtering</strong>: Ensuring no user data is included, and stripping out sensitive information like credit card numbers or Social Security details from public datasets or any other Personally Identifiable Information (PII).</li></ul><p>This ensures that the training corpus is <strong>clean, high quality, and privacy-safe</strong>.</p><h3>Pre-training with AXLearn</h3><p>Apple trains its Foundation Models using <strong>AXLearn</strong>, a custom training framework built on top of <strong>JAX</strong> and <strong>XLA</strong>:</p><ul><li><strong>JAX</strong>: A high-performance Python library tailored for numerical computing, especially on Tensor Processing Units (TPUs).</li><li><strong>XLA (Accelerated Linear Algebra)</strong>: A machine learning compiler that optimises computational graphs.</li></ul><p>AXLearn allows Apple to scale efficiently across cloud GPUs, TPUs, and on-premise infrastructure — making it ideal for large model training with performance and cost in mind.</p><h3>Post-Training Fine-Tuning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CcFcMvVWm3HqqIxRbZrrQ.png" /><figcaption>Post-Training Fine-Tuning methods</figcaption></figure><p>Once pre-training is complete, Apple applies two key methods to fine-tune its models for higher-quality responses:</p><ul><li><strong>Rejection Sampling with a Teacher Committee</strong>: The model generates multiple outputs, and a committee of heuristic “teacher” models filters out poor responses.</li><li><strong>Reinforcement Learning from Human Feedback (RLHF)</strong>: Human reviewers score model responses, and those scores guide future output quality.</li></ul><p>These methods align model outputs more closely with human expectations and improve overall safety and usefulness.</p><h3>Optimising for On-Device Performance</h3><p>To deliver fast, low-power, and private AI on-device, Apple applies a variety of optimisation techniques:</p><ul><li><strong>Grouped-Query Attention</strong>: A transformer efficiency method that reduces memory usage and speeds up inference.</li><li><strong>Shared Embedding Tables</strong>: Reuses token embeddings for both input and output to save space.</li><li><strong>Low-bit Palletization</strong>: A quantisation technique that compresses model weights to fewer bits, enhancing speed and power efficiency.</li><li><strong>Talaria</strong>: Apple’s custom performance profiler, used to analyse latency and energy usage of model operations.</li><li><strong>Activation and Embedding Quantisation</strong>: Compresses runtime computations and vocabulary embedding tables to improve model efficiency and reduce memory footprint.</li><li><strong>KV Cache Optimisation</strong>: Optimises transformer memory usage by streamlining key-value cache updates, leveraging Apple’s Neural Engine for faster attention calculations.</li></ul><p>Together, these techniques make the on-device models <strong>fast, compact, and battery-conscious</strong>, without sacrificing intelligence.</p><h3>Personalisation with Adapters</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmlr.cdn-apple.com%2Fvideo%2FFig2_Adapters_9f087bc5c5.mp4&amp;type=text%2Fhtml&amp;schema=cdn-apple&amp;display_name=FlowDrive&amp;src=https%3A%2F%2Fmlr.cdn-apple.com%2Fvideo%2FFig2_Adapters_9f087bc5c5.mp4%3Fembed%3Dtrue" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d0eb43da9880630f375486856eaba5/href">https://medium.com/media/b0d0eb43da9880630f375486856eaba5/href</a></iframe><p>To customise the model’s behaviour for individual users, Apple introduces <strong>Adapters</strong> — small neural network modules stacked on top of the base model.</p><p>Rather than altering the base model, Apple fine-tunes only these lightweight adapters. This allows for quick personalisation while maintaining efficiency and protecting the original model’s integrity.</p><h3>Conclusion:</h3><p>Apple Intelligence represents a sophisticated blend of state-of-the-art machine learning engineering and Apple’s longstanding commitment to user privacy and experience. By carefully curating data, innovation in training techniques, and applying cutting-edge optimisation, Apple sets a new standard in on-device AI. As you deepen your understanding of these foundational concepts, you’ll be better prepared to harness Apple Intelligence in practice, building smarter, more responsive applications that respect users’ privacy.</p><h3>References:</h3><ul><li>Foundation Models: <a href="https://machinelearning.apple.com/research/introducing-apple-foundation-models">https://machinelearning.apple.com/research/introducing-apple-foundation-models</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=081722e917c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>