<?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 Alessia Lin on Medium]]></title>
        <description><![CDATA[Stories by Alessia Lin on Medium]]></description>
        <link>https://medium.com/@alessia.lin?source=rss-71ccfe3cb2e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uN8lUXWB-hqRu1IVRXJiTw.jpeg</url>
            <title>Stories by Alessia Lin on Medium</title>
            <link>https://medium.com/@alessia.lin?source=rss-71ccfe3cb2e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:58:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alessia.lin/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[Optimizing function calling with Small Language Models: Data quality, quantity, and practical…]]></title>
            <link>https://medium.com/data-science-at-microsoft/optimizing-function-calling-with-small-language-models-data-quality-quantity-and-practical-353be49b7a00?source=rss-71ccfe3cb2e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/353be49b7a00</guid>
            <category><![CDATA[small-language-model]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alessia Lin]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 07:16:35 GMT</pubDate>
            <atom:updated>2025-07-29T07:16:35.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing function calling with Small Language Models: Data quality, quantity, and practical strategies</h3><p>Language models are reshaping how we approach coding and automation, with function calling emerging as one of their most powerful capabilities. However, leveraging Large Language Model (LLM) APIs typically requires verbose prompts that include detailed function configurations. This can be both costly and impractical, especially in scenarios where consistent cloud connectivity is not guaranteed.</p><p>This article builds on our <a href="https://pub.towardsai.net/from-first-principles-building-function-calling-by-fine-tuning-nanogpt-4f3ad55a2d0d">previous discussion</a>, where we turned <strong>function calling into a generation task </strong>rather than a schema-parsing one. Therefore, you don’t always need the full prompt at inference time — your Small Language Model (SLM) can learn function behavior directly from training data with comparable results to the LLM. The catch? That training data must be of high quality.</p><p><em>But what exactly does “</em><strong><em>good</em></strong><em>” </em><strong><em>data</em></strong><em> look like? And how good is </em><strong><em>good enough</em></strong><em>?</em></p><h3>Methodology</h3><p>For function calling to work effectively, your training data needs to cover the parameter space of your functions adequately.</p><p>Today, it’s common to have functions and arguments stored in machine-readable format, like JSON. What’s often missing, though, is the <strong>natural language command</strong>: the user’s actual intent expressed in plain language.</p><p>To bridge this gap, we turned to <strong>synthetic data generation</strong>. We generated structured pairs of function calls and their corresponding natural language queries, carefully designed to mimic real-world usage. This process involves defining function configuration details, sampling function calls, and utilizing GPT-4o to generate commands for these function calls. Each data point captures the heart of the interaction: a user-like query paired with a function call that follows precise syntactic and semantic rules.</p><p>The training data generation is as follows:</p><p><strong>1) Generate function call</strong></p><pre>{<br>&quot;name&quot;: &quot;set_temperature&quot;, <br>&quot;arguments&quot;: &quot;{&#39;temperature&#39;: 22, &#39;unit&#39;: &#39;celsius&#39;}&quot;<br>}</pre><p><strong>2) Use LLM to come up with natural sounding user command</strong></p><pre>{<br>  &quot;user&quot;: &quot; Set the temperature to 22 degrees Celsius&quot;<br>}</pre><p><strong>3) Generate actual training data</strong></p><pre>{<br>  &quot;system&quot;: &quot;&lt;|im_start|&gt;system\nYou are a helpful assistant. You have to either provide a way to answer user&#39;s request or answer user&#39;s query.\n&lt;|im_end|&gt;\n&quot;,<br><br>  &quot;user&quot;: &quot;&lt;|im_start|&gt;user\nSet the temperature to 22 degrees Celsius.&lt;|im_end|&gt;\n&quot;,<br><br>  &quot;assistant&quot;: &quot;&lt;|im_start|&gt;assistant\n&lt;functioncall&gt; {\&quot;name\&quot;: \&quot;set_temperature\&quot;, \&quot;arguments\&quot;: \&quot;{&#39;temperature&#39;: 22, &#39;unit&#39;: &#39;celsius&#39;}\&quot;} &lt;|im_end|&gt;&lt;|endoftext|&gt;&quot;<br>}</pre><p>Another advantage of synthetic data lies in its <em>flexibility</em>.</p><p>By designing these datasets ourselves, we can inject linguistic diversity, simulate complex parameter combinations, and even tackle edge cases head-on. Although real-world datasets are often considered the gold standard for their authenticity, such natural command-to-function-call datasets are scarce.</p><h3>Synthetic data</h3><p>When fine-tuning SLMs for function calling, data is not merely a supporting actor: it’s the lead. The effectiveness of a model relies on how well its fine-tuning data represents the task’s nuances. Unlike generic text generation tasks, function calling demands precise handling of input-output relationships — from mapping parameters to syntactic correctness.</p><h3>Complete versus incomplete user commands</h3><p>For this reason, we want to have a comprehensive data curation strategy. To do so, we have generated both complete and incomplete user commands. <strong>Complete queries</strong> are defined as clearly formulated commands such as:</p><p><em>“Set the fan speed to low for the entire car”</em></p><p><strong>Incomplete queries</strong>, in contrast, include instances where, for example, the user stops talking mid-sentence, or if the command does not include all the required information to generate a complete function:</p><p><em>“Change the temperature”</em></p><p><em>“Can you change the speed of my windshield wipers?”</em></p><h3>Complex functions versus simple functions</h3><p>Another way we have diversified our dataset is by creating functions that vary in complexity, from very simple to highly complex. This is aimed at reflecting a realistic use case and evaluating how each model handles increasing difficulty.</p><p>Complexity is defined by the diversity in how user commands can be expressed, possible combinations of function arguments, and the variety of ways the same instruction can be phrased in natural language.</p><p><strong>Very complex function:</strong></p><pre>{<br>  &quot;name&quot;: &quot;set_temperature&quot;,<br>  &quot;description&quot;: &quot;Set the temperature in a specified zone of the car.&quot;,<br>  &quot;parameters&quot;: {<br>      &quot;type&quot;: &quot;object&quot;,<br>      &quot;properties&quot;: {<br>          &quot;area&quot;: {<br>              &quot;type&quot;: &quot;array[string]&quot;,<br>              &quot;enum&quot;: [&quot;driver&quot;,&quot;front-passenger&quot;,&quot;rear-right&quot;,&quot;rear-left&quot;],<br>              &quot;description&quot;: &quot;The zone where the temperature will be adjusted.&quot;,<br>              &quot;default&quot;: &quot;all&quot;<br>          },<br>          &quot;temperature&quot;: {<br>              &quot;type&quot;: &quot;number&quot;,<br>              &quot;description&quot;: &quot;The target temperature for the specified zone in degrees Celsius.&quot;,<br>              &quot;lower_bound&quot;: 1,<br>              &quot;upper_bound&quot;: 80<br>          },<br>          &quot;unit&quot;: {<br>              &quot;type&quot;: &quot;string&quot;,<br>              &quot;description&quot;: &quot;The unit of the temperature value.&quot;,<br>              &quot;enum&quot;: [&quot;Celsius&quot;, &quot;Fahrenheit&quot;],<br>              &quot;default&quot;: &quot;Celsius&quot;<br>          }<br>      },<br>      &quot;required&quot;: [&quot;temperature&quot;],<br>      &quot;optional&quot;: [&quot;area&quot;,&quot;unit&quot;]<br>}</pre><p><strong>Very simple function:</strong></p><pre>{<br>  &quot;name&quot;: &quot;start_engine&quot;,<br>  &quot;description&quot;: &quot;Start the car&#39;s engine remotely.&quot;,<br>  &quot;parameters&quot;: {<br>      &quot;type&quot;: &quot;object&quot;,<br>      &quot;properties&quot;: {<br>          &quot;method&quot;: {<br>              &quot;type&quot;: &quot;string&quot;,<br>              &quot;description&quot;: &quot;The method to start the engine (e.g., &#39;remote&#39;, &#39;keyless&#39;, &#39;keyed&#39;).&quot;,<br>              &quot;default&quot;: &quot;keyless&quot;,<br>              &quot;enum&quot;: [&quot;remote&quot;, &quot;keyless&quot;, &quot;keyed&quot;]<br>          }<br>      },<br>      &quot;optional&quot;: [<br>          &quot;method&quot;<br>      ],<br>      &quot;required&quot;: []<br>    }</pre><h3>Getting “good” data</h3><p>Despite these efforts, gaps in synthetic data quality remain. Here are five aspects to consider when fine-tuning SLMs.</p><h4>1. The Impact of parameter and data variations</h4><p>In our first experiment, we explored how parameter variations affect the model’s ability to generalize. By creating datasets with a range of parameter combinations (varying in temperature degrees, functionalities, values, and so on) we observed that:</p><ul><li>Models fine-tuned on <strong>highly variable data</strong> consistently outperformed those trained on static or homogeneous datasets.</li><li>Very complex functions require<strong> more training instances</strong> than simple ones for proper execution by the SLM.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LeFLEi2FzRU2YoJo6zKnxQ.png" /></figure><ul><li>When additional (unnecessary) information is provided in user commands, the SLM may <strong>hallucinate</strong>.</li></ul><p><strong>Example</strong></p><p>Query:<em> “Today’s weather is really nice and I want to go to the mall, but it is a bit too hot in here. Can you lower the temperature for me to 15 degrees?”</em></p><p>Expected output:</p><pre>&lt;|im_start|&gt;assistant&lt;functioncall&gt; {“name”: “set_temperature”, “arguments”: “{‘temperature’: 15, ‘area’: [‘driver’]}”} &lt;|im_end|&gt;&lt;|endoftext|&gt;</pre><p>With proportionally distributed 70K train data (on GPT-2) and proportionally distributed 36K:</p><pre>&lt;|im_start|&gt;assistant&lt;functioncall&gt; {“name”: “set_temperature”, “arguments”: “{‘temperature’: 15, ‘area’: [‘rear-left’, ‘rear-right’, ‘front-passenger’, ‘rear-left’]}”} &lt;|im_end|&gt;&lt;|endoftext|&gt;</pre><p>As you can see, it failed to generate the correct function and added an extra rear-left parameter. With less data (e.g., 3.7K), the SLM cannot produce a suitable response to the query at all.</p><h4>2. Linguistic diversity in prompts</h4><p>Another key experiment focused on testing how the models react to the linguistic diversity in natural language instructions. We fine-tuned models on datasets with prompts ranging from formal and technical language to conversational and colloquial phrasing.</p><p>Results showed that <strong>models exposed to linguistically diverse prompts demonstrated superior robustness, maintaining accuracy even when faced with unconventional phrasing</strong>.</p><h4>3. Edge cases</h4><p>Edge cases are the Achilles’ heel of many fine-tuned models.</p><p>To address this, we constructed a dataset specifically designed to simulate these, such as missing arguments and ambiguous instructions. Not surprisingly, the model fine-tuned on only complete commands struggled to flag it as an incomplete instruction and hallucinated (in the example below, the temperature&#39;s action argument).</p><p><em>Query: “Change temperature”</em></p><p>Model response:</p><pre>&lt;|im_start|&gt;assistant&lt;functioncall&gt; {&quot;name&quot;: &quot;adjust_temperature&quot;, &quot;arguments&quot;: &quot;{action:’increase’}&quot;} &lt;|im_end|&gt;&lt;|endoftext|&gt;</pre><p>On the other hand, once we introduce the incomplete commands in the training set as well, the fine-tuned model is able to detect these instances.</p><p>Model response:</p><pre>&lt;|im_start|&gt;assistant&lt;functioncall&gt; {&quot;name&quot;: &quot;possibly_incomplete_adjust_temperature&quot;, &quot;arguments&quot;: &quot;{&#39;action&#39;: &#39;&#39;}&quot;} &lt;|im_end|&gt;&lt;|endoftext|&gt;</pre><p>This experiment highlights how <strong>proactively introducing even the most basic edge cases into fine-tuning data can safeguard a model’s reliability in unpredictable real-world contexts</strong>. Therefore, it is necessary to include all of these in the training data such that our fine-tuned SLM will be able to capture all possible scenarios.</p><p><strong><em>Performance overview</em></strong></p><p>Having established the necessary baseline conditions and parameters, we now compare the performance of <a href="https://huggingface.co/openai-community/gpt2">GPT-2</a> and comparable models ( <a href="https://huggingface.co/distilbert/distilgpt2">DistilGPT2</a> and <a href="https://huggingface.co/EleutherAI/gpt-neo-125m?utm_source=chatgpt.com">GPT-Neo 125m</a>).</p><p>Accuracy is defined strictly: only outputs with fully correct function calls (both function names and parameters) are considered successful.</p><p><strong>Correct function call:</strong></p><pre>{<br>  \&quot;name\&quot;: \&quot;adjust_fan_speed\&quot;, <br>  \&quot;arguments\&quot;: \&quot;{&#39;speed&#39;: &#39;decrease&#39;}\&quot;<br>}</pre><p><strong>Incorrect predictions:</strong></p><pre>{<br>  \&quot;name\&quot;: \&quot;set_fan_speed\&quot;, // Failed the function name is incorrect<br>  \&quot;arguments\&quot;: \&quot;{&#39;speed&#39;: &#39;decrease&#39;}\&quot;<br>}<br><br>{<br>  \&quot;name\&quot;: \&quot;adjust_fan_speed\&quot;, <br>  \&quot;arguments\&quot;: \&quot;{&#39;speed&#39;: ‘increase’}\&quot; // Failed: wrong argument <br>}<br><br>{<br>  \&quot;name\&quot;: \&quot;adjust_fan_speed\&quot;, <br>  \&quot;arguments\&quot;: \&quot;{&#39;speed&#39;: 5}\&quot; //Failed: hallucinated the value 5<br>}</pre><h4>4. Data quality</h4><p>First, we compare how the quality of the data affects performance by comparing two fine-tuned GPT-2 models with identical hyperparameters. Thus, the only variable is how well maintained the training data is: both use the same sample size (25K), but one dataset is cleaner than the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*gaptB80oDbJFDt4MFt_csw.png" /><figcaption>Comparison of accuracy for the model fine-tuned on cleaner data (gpt2_better_data) compared to benchmark GPT-2. Both are fine-tuned on 20K training data.</figcaption></figure><p>When comparing the performance of the two fine-tuned SLMs, a pattern emerges: the model trained on cleaner data (gpt2_better_data) generally delivers superior results, particularly for complex functions. In contrast, the model trained on noisier data performs adequately for simpler functions but struggles as task complexity increases. This highlights the importance of curating high-quality datasets to maximize the capabilities of small language models.</p><p>For small language models applied to function calling, high-quality data is more valuable than large amounts of (noisy) data. With limited capacity, such as in the case with small language models like GPT-2, these models learn better from clear, relevant examples than from large, inconsistent datasets.</p><blockquote>We have discussed data quality, but how does <strong>data quantity</strong> influence model performance?</blockquote><h4>5. Data quantity</h4><p>Another series of experiments involved exploring how much fine-tuning of data is needed before performance levels off.</p><p>While accuracy improved with additional quantities of data at first, the benefits eventually plateaued.</p><p><strong>Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*0wanMzNh8bmznvuS42kIFg.png" /><figcaption>Comparison of the accuracy of the 3 fine-tuned SLMs across different sample sizes</figcaption></figure><p>Additionally, we’ve observed that beyond a certain point, adding more data may decrease the model’s performance. The exact reason for this phenomenon is unclear, but the introduction of noise may be a contributing factor.</p><p>Moreover, prediction error (dotted line) — which includes instances where the model was not able to produce the correct function call structure at all — decreases very fast after a certain threshold. On the other hand, we notice that across all three models, the best size for training data is around 60K. Performance in more complex functions such as set_temperature, adjust_fan_speed, and set_fan_speed is worse off compared to simpler functions, most likely indicating that the underlying synthetic data quality should be further improved. The higher the complexity, the noisier the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*7QDnPU2b3XRDVBBAQq6iww.png" /><figcaption>Heatmap comparison of accuracy metrics across the three fine-tuned SLMs (on 60K training data)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*epyXoPt6U1uFr9aRx8LR9Q.png" /><figcaption>Breakdown of error distribution across functions for GPT-2 fine-tuned on 60K training data</figcaption></figure><h3>Conclusion</h3><p>The experiments demonstrate that Small Language Models can indeed be fine-tuned for function-calling tasks, effectively replacing Large Language Model calls with complex prompts. However, a comprehensive training set is essential for the successful implementation of an SLM. This dataset can be generated by leveraging LLM models to create user commands.</p><p>The success of fine-tuning hinges on data that is thorough, diverse, and purposefully designed. In practical applications, these insights lead to actionable strategies:</p><ul><li>Curating training datasets that reflect user diversity</li><li>Simulating real-world parameter variations</li><li>Incorporating potential failure modes</li></ul><p>By employing such data strategies, even modestly sized SLMs can compete with their larger counterparts in function-calling tasks, thereby achieving an optimal balance between efficiency and accuracy.</p><p><em>Alessia Lin is on </em><a href="https://www.linkedin.com/in/alessialin/"><em>LinkedIn</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=353be49b7a00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-at-microsoft/optimizing-function-calling-with-small-language-models-data-quality-quantity-and-practical-353be49b7a00">Optimizing function calling with Small Language Models: Data quality, quantity, and practical…</a> was originally published in <a href="https://medium.com/data-science-at-microsoft">Data Science + AI at Microsoft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling model training with PyTorch Distributed Data Parallel (DDP) on Azure Machine Learning]]></title>
            <link>https://medium.com/data-science-at-microsoft/scaling-model-training-with-pytorch-distributed-data-parallel-ddp-on-azure-machine-learning-d512a932ca13?source=rss-71ccfe3cb2e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d512a932ca13</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[ddp]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[distributeddataparallel]]></category>
            <category><![CDATA[azure-machine-learning]]></category>
            <dc:creator><![CDATA[Alessia Lin]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 07:16:53 GMT</pubDate>
            <atom:updated>2025-06-03T13:39:59.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpuMMJJJpj6JZfFQX6bE6Q.png" /><figcaption>Full Distributed Data Parallel (DDP) process</figcaption></figure><p>As Machine Learning models grow increasingly complex and datasets expand in size, training times can become a significant bottleneck.</p><p>Picture yourself training a model designed to detect objects from thousands of images.</p><p>Using traditional methods might take days or even weeks, slowing down your research. PyTorch Distributed Data Parallel (DDP) solves this problem by allowing your model to learn simultaneously across multiple GPUs or machines, significantly reducing training time. Pairing DDP with Azure Machine Learning (Azure ML or AML) gives you the power of cloud scalability, seamless job management, and straightforward monitoring, enabling faster results and more productive workflows.</p><p>While distributed training generally refers to splitting the workload across multiple devices, another related approach called Model Parallel Training splits the model itself across devices due to size constraints.</p><p>However, this article specifically focuses on Distributed Data Parallel, highlighting its ease of use, scalability, and practical implementation.</p><h3><strong>Understanding PyTorch Distributed Data Parallel</strong></h3><p>Unlike traditional methods that run on a single GPU, Distributed Data Parallel synchronizes <strong>gradients </strong>across multiple devices, ensuring that your model remains consistent and your training process stays fast and efficient.</p><p>It’s important not to confuse DDP with another PyTorch method called <a href="https://pytorch.org/tutorials/intermediate/ddp_tutorial.html#comparison-between-dataparallel-and-distributeddataparallel">DataParallel</a>, which is a simpler parallelism method that works on a single node by replicating the model across available GPUs. DataParallel can be less efficient due to higher communication overhead and limited scalability.</p><h3><strong>Prerequisites to have in place before beginning</strong></h3><p>Before implementing DDP on Azure Machine Learning, ensure that you have the following in place:</p><ul><li>An Azure subscription</li><li>An AML Workspace</li><li>GPU quota</li><li>The <a href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">azure-cli</a> installed</li></ul><h3><strong>Environment</strong></h3><p>Compared to local runs using single GPUs or single processes, Azure ML introduces additional considerations like distributed environment initialization, synchronized checkpoints handling, and ensuring reproducibility across distributed nodes.</p><p>Being mindful of these aspects helps to achieve smooth execution and maximized performance on Azure ML.</p><p>With this in mind, the next sections explore how to go about setting things up for success.</p><h4><strong>Preparing for DDP</strong></h4><p>Setting up your model for DDP is fairly straightforward.</p><p>Because each node can have multiple GPUs, it’s necessary to ensure that each process is assigned the correct one. To do this, start by initializing communication between the devices using <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group">torch.distributed.init_process_group().</a></p><pre>torch.distributed.init_process_group(backend=&quot;nccl&quot;, init_method=&quot;env://&quot;)</pre><ul><li>nccl handles the communication between GPUs and is the preferred backend for GPU-based training.</li><li>env:// tells PyTorch to read connection set up details (e.g., rank, world size, and master address) from environment variables, instead of hardcoding them.</li></ul><p>Now that we’ve introduced these connection set up variables, what do they mean?</p><h4><strong>Environment variables</strong></h4><p>To answer that question, first consider that in DDP, there are some important components:</p><ul><li>master_addr, IP of the master node (at rank 0) for communication between processes.</li><li>master_port, port on the master node (rank 0) for coordination.</li><li>world_size, total number of processes across all nodes.</li><li>rank, the unique ID of the current processes (ranging from 0 to world_size–1).</li><li>local_rank, ID of processes across each node.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*lMorzhV9uydh1z2aL8TTAQ.png" /><figcaption>Summary table of environment variables required for DDP</figcaption></figure><p>While running <strong>locally</strong>, it is necessary to specify these variables:</p><pre>def local_run(rank: int, world_size: int, backend: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Setup the distributed environment.<br><br>    Args:<br>        rank (int): The rank of the current process in the distributed setup.<br>        world_size (int): Total number of processes (GPUs across all nodes).<br>        backend (str): Backend to use for distributed training<br>    &quot;&quot;&quot;<br>    os.environ[&quot;MASTER_ADDR&quot;] = &quot;localhost&quot;<br>    os.environ[&quot;MASTER_PORT&quot;] = &quot;12345&quot;<br>    os.environ[&quot;WORLD_SIZE&quot;] = str(world_size)<br>    os.environ[&quot;RANK&quot;] = str(rank)<br><br>    train(rank, world_size, backend)</pre><p>Azure Machine Learning reads them directly from the environment:</p><pre>rank = int(torch.distributed.get_rank())<br>local_rank = int(os.environ[“LOCAL_RANK”])<br>world_size = int(os.environ[”WORLD_SIZE”])</pre><h3><strong>Training</strong></h3><h4><strong>Prepare your model for DDP</strong></h4><p>Adapting your PyTorch script to DDP not only involves initializing the distributed training environment and handling GPU assignments correctly, but also adjusting data loaders.</p><p>Dealing with large datasets being trained requires an appropriate solution in dividing the dataset to be parallelized. <a href="https://pytorch.org/docs/stable/data.html?highlight=distributedsampler#torch.utils.data.distributed.DistributedSampler">DistributedSampler</a> allows balanced data distribution, so that each GPU works on a unique portion of the data. This ensures efficient training and balanced workloads across GPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*I-1ADck5VQjtRYMz0WXD5A.png" /><figcaption>Example of of how DataSampler works with a GPU cluster (2 nodes, each with 2 GPUs)</figcaption></figure><pre>from torch.utils.data import DataLoader, DistributedSampler<br><br>sampler = DistributedSampler(dataset, num_replicas=world_size, rank=rank)<br>dataloader = DataLoader(dataset, batch_size=64, sampler=sampler)</pre><ul><li>DataLoader combines the dataset and a sampler, and iterates over the given dataset.</li><li>Each batch size processes world_size*batch_size samples (e.g., if batch_size= 64, the effective batch size is 64 *world_size, or 128 when using 2 GPUs).</li></ul><p>Make sure to change this assignment between epochs. Calling methods like set_epoch on DistributedSampler at the beginning of each epoch reshuffles the training data so that each epoch gets a different set of samples.</p><pre># Training loop<br>for epoch in range(epochs):<br>    sampler.set_epoch(epoch)<br>    ddp_model.train()<br>    for batch_idx, (data, target) in enumerate(dataloader):<br>        data, target = data.to(device), target.to(device)<br>        optimizer.zero_grad()<br>        output = ddp_model(data)<br>        loss = criterion(output, target)<br>        loss.backward()<br>        optimizer.step()<br><br>        if batch_idx % 100 == 0 and rank == 0:<br>            print(f&quot;Epoch {epoch}, Batch {batch_idx}, Loss: {loss.item()}&quot;)</pre><h4><strong>Initializing the model with DDP</strong></h4><p>To initialize training, assign each data sample to the corresponding GPU:</p><pre>device = torch.device(&quot;cuda&quot;, local_rank)<br><br>model = model.to(device)</pre><h4><strong>Saving models and checkpoints</strong></h4><p>A key concept in DDP is understanding when and where to save certain processes and assets. Not all processes need to be run across all GPUs.</p><ul><li>local_rank= 0 is the main process for nodes. For instance, only one process downloads the training data, while the other local ranks only load the training data.</li><li>rank= 0 is the main process for the entire job. When running test set evaluation or saving checkpoints and models, we want to save them on one common process for the entire job — usually rank 0.</li></ul><p><strong>Saving in DDP</strong></p><pre># Save the model<br>if rank == 0:<br>    model_dir = &quot;./outputs&quot;<br>    os.makedirs(model_dir, exist_ok=True)<br>    model_path = os.path.join(model_dir, &quot;mnist_cnn.pt&quot;)<br><br>    # Save the underlying model (not the DDP wrapper)<br>    torch.save(model.state_dict(), model_path)<br>    print(f&quot;Model saved to {model_path}&quot;)</pre><p>To avoid saving conflicts when running in parallel, make sure to add <a href="https://docs.pytorch.org/docs/stable/distributed.html#python-breakpoint">torch.distributed.barrier()</a>. This ensures that it waits for all processes to finish running before continuing with the next lines of code.</p><p><strong>Loading checkpoints in DDP (before wrapping with DDP)</strong></p><p>When loading checkpoints, on the other hand, we want to load them across all processes.</p><p>This works because all processes start from the same parameters and gradients are synchronized in backward passes, so optimizers should keep setting parameters to the same values.</p><pre>if os.path.exists(checkpoint_path):<br>  checkpoint = torch.load(checkpoint_path, map_location=f”cuda:{local_rank}”)<br>  model.load_state_dict(checkpoint)</pre><ul><li>PyTorch will copy weights to correct devices via map_location</li></ul><p>And now, at last, your model is ready for DDP and for you to run it. You have two options, running it locally or on Azure ML.</p><h3><strong>Running DDP locally</strong></h3><p>When running locally, you have two <strong>mutually exclusive </strong>options.</p><p>1) <strong>torch.multiprocessing.spawn</strong> (<strong>mp.spawn</strong>):</p><ul><li>Set the arguments manually</li><li>Take advantage of in-code process spawning</li><li>The result is generally quicker for local testing, but less recommended</li></ul><pre># Local execution<br>world_size = (<br>    torch.cuda.device_count() if torch.cuda.is_available() else 2<br>)<br>backend = &quot;nccl&quot; if torch.cuda.is_available() else &quot;gloo&quot;<br><br>print(<br>    f&quot;Running locally with {world_size} processes using {backend}&quot;<br>)<br><br># Spawn processes for distributed training<br>mp.spawn(<br>    local_run,<br>    args=(world_size, backend),<br>    nprocs=world_size,<br>    join=True<br>)</pre><p>2) <a href="https://pytorch.org/docs/stable/elastic/run.html#launcher-api"><strong>torchrun</strong></a>:</p><ul><li>Built-in multi-node support</li><li>Automatic environment variables set up (e.g., rank, local_rank and so on)</li><li>Callable and works directly with torch.distributed.init_process_group()</li><li>Launching through CLI</li></ul><pre>torchrun --nnodes=NUM_NODES --nproc_per_node=GPU_PER_NODE train.py</pre><p>As you may notice, running locally requires you to manually assign variables. Azure ML, on the other hand, simplifies this process.</p><h3><strong>Azure Machine Learning</strong></h3><p>You can create and configure GPU-enabled clusters through Azure ML Studio or Azure CLI. Define your training environment using Docker images or Python environments and manage jobs easily with clear YAML configuration files, ensuring reproducibility and ease of use.</p><h4><strong>Environment setup</strong></h4><p>To run jobs in AML, two options exist: using the Python SDK or submitting jobs through YAML scripts. This article focuses on the latter.</p><p>Example YAML script:</p><pre>$schema: https://azuremlschemas.azureedge.net/latest/commandJob.schema.json<br>type: command<br><br># Name of the job<br>experiment_name: ddp-mnist-experiment<br>description: Train a PyTorch model on MNIST using Distributed Data Parallel (DDP)<br><br># Compute target<br>compute: azureml:gpu-cluster  # Replace with your compute target name<br><br># Environment definition<br>environment: azureml:ml-gpu-tuning  # Replace with your environment name<br><br># Distributed training configuration<br>distribution:<br>  type: pytorch<br>  # Number of processes per node for DDP<br>  process_count_per_instance: 1<br><br>resources:<br>  # Number of nodes for multi-node training<br>  instance_count: 2  <br><br># Command to run the training script<br>command: &gt;+<br>  python train.py<br><br># Code<br>code: .<br><br># Outputs<br>outputs:<br>  model:<br>    mode: upload<br>    type: uri_folder</pre><ul><li>command, different from running locally, on AML the command stays python (instead of torchrun). This is because as long as we specify pytorch in the distribution type, AML gets the number of processes and GPUs to spin on from the YAML, thus removing the hassle of dealing with command line arguments.</li><li>instance_count corresponds to the number of nodes</li><li>process_count_per_instance is the number of GPUs each node has</li></ul><h4><strong>Submitting DDP jobs to Azure ML</strong></h4><p>You are now ready to submit the job!</p><p>To do so, remember to authenticate first with:</p><pre>az login</pre><p>Then run:</p><pre>az ml job create -f job.yaml --workspace-name “WORKSPACE_NAME” --resource-group “RESOURCE_GROUP”</pre><p>Once the job has been submitted, AML finds the available compute, the processes across the nodes, and sets the environment variables needed for DDP.</p><p>Check on AML that your job has been successfully submitted and see for yourself the DDP processes being undertaken!</p><h3><strong>Best practices and tips</strong></h3><p>To achieve optimal results, consider the following tips:</p><ul><li>Carefully configure your resources (GPUs per node, node counts, and so on).</li><li>Ensure reproducibility by setting fixed random seeds in each main process per GPU. However, make sure that each<strong> </strong>data loading<strong> </strong>worker<strong> </strong>receives a unique seed, so that operations like data augmentation<strong> </strong>retain their intended randomness.</li><li>Optimize your performance with NCCL as a backend communication method.</li><li>Make some considerations on costs, keeping them under control while maximizing training performance.</li><li>When saving checkpoints during a multi-node DDP job in Azure ML, it is safer to first save them to a temporary local or isolated path (like <em>tmp/</em>), and then move or copy them to the shared <em>outputs/ </em>folder at the end of the job. This avoids cross-process timing issues, where one rank tries to read a checkpoint file before another rank has finished writing or syncing it across the network, leading to FileNotFoundError or partial reads.</li></ul><h3><strong>Conclusion</strong></h3><p>By combining PyTorch Distributed Data Parallel with Azure Machine Learning, data scientists and researchers can revolutionize model training, making it scalable, efficient, and manageable. This powerful integration accelerates innovation and paves the way for faster breakthroughs in Machine Learning and Artificial Intelligence.</p><p>An example of the entire DDP code can be found here: <a href="https://github.com/alessialin/ddp-example">alessialin/ddp-example: An example of DDP with PyTorch</a></p><p><em>Alessia Lin is on </em><a href="https://www.linkedin.com/in/alessialin/"><em>LinkedIn</em></a>.</p><h3><strong>Additional resources</strong></h3><p>PyTorch DDP documentation:</p><ul><li><a href="https://pytorch.org/tutorials/intermediate/ddp_tutorial.html#save-and-load-checkpoints">Getting Started with Distributed Data Parallel — PyTorch Tutorials 2.6.0+cu124 documentation</a></li><li><a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-a-general-checkpoint-for-inference-and-or-resuming-training">Saving and Loading Models — PyTorch Tutorials 2.6.0+cu124 documentation</a></li></ul><p>Azure ML documentation and examples:</p><ul><li><a href="https://learn.microsoft.com/en-us/azure/machine-learning/how-to-train-distributed-gpu?view=azureml-api-2">Distributed GPU training guide (SDK v2) — Azure Machine Learning | Microsoft Learn</a></li></ul><p>For a more efficient solution that handles the complexities of DDP, consider checking out:</p><ul><li><a href="https://pytorch-accelerated.readthedocs.io/en/latest/">Welcome to pytorch-accelerated’s documentation! — pytorch-accelerated 0.1.3 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d512a932ca13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-at-microsoft/scaling-model-training-with-pytorch-distributed-data-parallel-ddp-on-azure-machine-learning-d512a932ca13">Scaling model training with PyTorch Distributed Data Parallel (DDP) on Azure Machine Learning</a> was originally published in <a href="https://medium.com/data-science-at-microsoft">Data Science + AI at Microsoft</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>