<?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 Flavio Hafner on Medium]]></title>
        <description><![CDATA[Stories by Flavio Hafner on Medium]]></description>
        <link>https://medium.com/@f-hafner?source=rss-348aad3349b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gcCxWf33tibqvNv1kaMnbQ.jpeg</url>
            <title>Stories by Flavio Hafner on Medium</title>
            <link>https://medium.com/@f-hafner?source=rss-348aad3349b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:43:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@f-hafner/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[Empirically evaluating privacy in machine learning III: functional & gaussian differential privacy]]></title>
            <link>https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-iii-functional-gaussian-differential-privacy-ccef13153e12?source=rss-348aad3349b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccef13153e12</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[privacy]]></category>
            <dc:creator><![CDATA[Flavio Hafner]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 09:02:16 GMT</pubDate>
            <atom:updated>2025-06-17T13:09:53.661Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Using statistics to think like a hacker, so we can avoid them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*SGiWBRlbFJWfVtbvqXSGqQ.png" /><figcaption>The Greek letter lambda, symbol of functional programming.</figcaption></figure><p>This post is the third in a series on differential privacy and machine learning (see here episodes <a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-i-introduction-de5fe808d186?source=user_profile_page---------2-------------348aad3349b0----------------------">I</a> and <a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-ii-hypothesis-testing-647806e2985c?source=user_profile_page---------0-------------348aad3349b0----------------------">II</a>). It takes a big step towards understanding how to assess privacy properties of machine learning algorithms: It introduces functional and gaussian differential privacy as defined by <a href="https://academic.oup.com/jrsssb/article/84/1/3/7056089">Dong et al. (2022)</a>. This definition helps reasoning about differential privacy in some contexts, and in particular it has been useful for recent work in auditing machine learning algorithms with differential privacy.</p><p>When reading this post, the reader should be familiar with <a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-ii-hypothesis-testing-647806e2985c?source=user_profile_page---------0-------------348aad3349b0----------------------">the previous post</a> in this series. That post showed that differential privacy constrains the success of an attacker in inferring whether a particular record was included in a differentially private data release.</p><h3>Functional Differential Privacy</h3><h4>Trade-off functions</h4><p>So far, we have derived the boundary for the best possible performance of any adversary in the original case of (epsilon,delta) differential privacy. It turns out this function is an instance of what Dong et al. (2022) define as a <em>trade-off function.</em></p><p>Remember that a differentially private mechanism M induces two different distributions of data under the two competing hypotheses H0 and H1. A trade-off function T(P,Q)(alpha) defines the difficulty in distinguishing the two distributions: it is defined over any two probability distributions P and Q, and tells us the lowest achievable type-II error rate beta (= False Negative Rate FNR) an adversary can achieve with a type-I error rate (= False Positive Rate FPR) of at most alpha. The higher this function, the higher the lowest achievable type-II error rate for any alpha, thus the harder it is to distinguish the two distributions P and Q.</p><p>As a concrete example, a trade-off function TP(P,Q)(0.05)=0.1 tells us that distinguishing P from Q with a type-I error of at most 0.05 cannot have a type-II error of less than 0.1.</p><p>A trade-off function has the following mathematical properties:</p><ul><li>It takes inputs alpha that range from 0 to 1.</li><li>It has domain beta that range from 0 to 1.</li><li>It is convex, continuous, non-increasing.</li><li>For all alpha, beta lies on or below the line 1-alpha. The dotted line in figure 2 of <a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-ii-hypothesis-testing-647806e2985c?source=user_profile_page---------0-------------348aad3349b0----------------------">the previous blog post</a> represents the line 1-alpha , indicating that the distributions P and Q are indistinguishable.</li></ul><h4>Functional Differential Privacy</h4><p>Instead with parameters (epsilon, delta), it is now possible to define differential privacy in terms of a function — and is thus called functional differential privacy.</p><p>According to the definition, a mechanism M is f-differentially private if it creates, for all neighboring databases db0 and db1, a trade-off function over M(db0) and M(db1) that is bounded by the trade-off function f.</p><p>The definition is best illustrated with this figure from Dong et al (2022):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ju4yFPyue43V1mYT7FmwWA.png" /><figcaption>Figure 1: Functional differential privacy. The solid line is a trade-off function for `f` differential privacy. Only the dashed line above the solid line satisfies f-differential privacy. Source: Dong et al (2022).</figcaption></figure><p>The figure has the same x- and y-axes as the figures in the previous blog post: On the x-axis is the false positive rate, or type I error; on the y-axis is the false negative rate, or type II error.</p><p>The solid line is the trade-off function f. The other lines represent trade-off functions from differentially private mechanisms. Among them, only the dashed line that never crosses the solid line is f-DP; the other lines do not always lie above the line defined by f, and thus do not satisfy f-differential privacy. For reference, the kinked line could have come from an (epsilon, delta) -differentially private mechanism we discussed in the previous post.</p><h4>Analyzing composition</h4><p>A first advantage of functional differential privacy is that it makes it easier to analyze properties such as composition. Composition handles the question of how sequentially querying a dataset with a private mechanism impacts the overall privacy of the original dataset, after all queries are applied. As an example, take an analyst that sequentially queries a private dataset: they query the data with a private mechanism, explore the result, and query the data in a way that depends on the result of the first query. The question arises: how does this sequential and adaptive querying of the data degrade overall privacy? If the person is adversarial, they may try to refine the queries step by step until they found the answer to their question.</p><p>A key result in Dong et al (2022) is that the n-fold composition of mechanisms that are f_i differentially private is f* -differentially private. The precise level of privacy f* depends on the privacy of each individual mechanism f_i, and details can be found in section 3 of the paper. Importantly, this privacy bound is <em>tight</em>: f* is the most precise bound possible, informally meaning that we cannot move the function f* further away from the x-y origin without making the f* function crossing the trade-off function of the composed mechanism.</p><p>This contrasts with (epsilon,delta) differential privacy, where composition cannot be bounded as tightly.</p><h3>Gaussian differential privacy</h3><p>A special case of f-differential privacy is Gaussian differential privacy. In this definition, the trade-off function is defined over two unit-variance normal distributions — one with mean 0, the other with mean mu. In other words, under H0, the private mechanism generates a standard normal distribution, and under H1, it generates a normal distribution with mean mu and variance 1. This is shown in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGnAcrj1so-lPK6E4Ijzkg.jpeg" /><figcaption>Figure 2: Two normal distributions. Under H0, X is generated with mean 0 and standard deviation 1. Under H1, X is generated with mean mu and standard deviation 1.</figcaption></figure><p>While this definition makes assumptions about the functional form of the distribution, it is very useful:</p><ol><li>It summarizes the adversary’s trade-off between false positives and false negatives with a single parameter, mu. This makes it easy to describe and interpret privacy guarantees.</li><li>It characterizes the <a href="https://en.wikipedia.org/wiki/Additive_noise_differential_privacy_mechanisms">Gaussian mechanism</a>, one commonly used differentially private mechanism.</li><li>As shown by Dong et al (2022), Gaussian differential privacy is the asymptotic limit when f-differentially private mechanisms are applied repeatedly on the same dataset. This is useful for analyzing complex algorithms that consist of multiple, adaptive and individually private steps.</li></ol><h4>Relation to machine learning with differential privacy</h4><p>It is this last result that has made Gaussian differential privacy an important tool for analyzing differentially private machine learning.</p><p>While we discuss it in detail in a future blog post, a commonly-used algorithm in deep learning is Differentially Private Stochastic Gradient Descent (DP-SGD). It is a method for sequentially updating parameters in a complex neural network: Instead of directly updating parameters with the gradients in each batch, noise is added and the contribution of individual samples in the batch is constrained. This avoids that any individual sample contributes too much to the parameter update, and can be shown to satisfy differential privacy.</p><p>Since each parameter update is differentially private, one can view the trained model that results after many iterations as an algorithm that composes multiple differentially-private queries on the training data. Therefore, one can use Gaussian differential privacy to derive tight privacy bounds of the DP-SGD algorithm, which was not possible before.</p><h4>Trade-off function for Gaussian differential privacy</h4><p>Building on the previous figure, the following figure illustrates the trade-off between false positives and false negatives under Gaussian differential privacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JgZxuEKucTyK3OsANlKlQ.jpeg" /><figcaption><em>Figure 3: The likelihood-ratio test with normal distributions. If `X` is higher than t, H0 is rejected in favor of H1, and vice-versa. The blue and green areas show the false positive and false negative rates, respectively.</em></figcaption></figure><p>The red line indicates a decision threshold. In particular, when conducting a hypothesis test, the <a href="https://en.wikipedia.org/wiki/Neyman%E2%80%93Pearson_lemma">Neyman-Pearson lemma</a> says that the best test statistic is the likelihood ratio test: Given a sample X, the likelihood ratio test compares the likelihood that the sample was generated under H1 vs H0. From the figure above, we see that because the likelihood ratio of H1 vs H0 is increasing in X, the null hypothesis is rejected if X is above some threshold t, indicated in red.</p><p>Given the decision threshold, we can derive the False Positive and the False Negative rates:</p><ol><li>The False Positive Rate is defined for cases when H0 is falsely rejected. This happens if X&gt;t but X was generated under H0. This probability is shown by the blue area.</li><li>The False Negative Rate is defined for cases when H0 is falsely not rejected. This happens if X&lt;t but X was generated under H1. This probability is shown by the green area.</li></ol><p>Now that we have an analytical expression for both FPR and FNR, we can derive the trade-off function — the FNR as a function of the FPR and mu: We rearrange the equation for the FPR for t and then plug in t to the equation for FNR. This yields the following trade-off function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Cx779nSJ59dV3AJOgOAI8g.png" /></figure><p>Again, an illustration makes this easier to understand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_vJxECcFYmgaY2zS-9qiw.jpeg" /><figcaption>Figure 4: The trade-off function for Gaussian differential privacy. Phi is the standard normal distribution. alpha is the false positive rate. beta is the false negative rate. a lower mu means more privacy.</figcaption></figure><p>First, for a given false positive rate alpha, the false negative rate is at least as large as the the green area. In line with the definition of a trade-off function, lowering the false positive rate makes the red area smaller, and pulls the boundary of the green area to the right, thus increasing the false negative rate.</p><p>Second, a lower mu is associated with more privacy: as mu decreases, it pulls the boundaries either the false positive or false negative rate (or both) closer to the center, thereby making it harder to distinguish between the distributions generated by H0 and H1.</p><p>Dong et al (2022) also illustrate the trade-off function for some values of mu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*TUzmb0rxyJZuZiK7oJJkeg.png" /><figcaption>Figure 5: Example trade-off functions for different values of mu. Source: Dong et al (2022).</figcaption></figure><p>Here, for instance G_{0.5} is the trade-off function for Gaussian differential privacy with mu=0.5 . Reasonable privacy is given for mu=0.5, whereas for mu=6 the trade-off function almost coincides with the x- and y-axis, thus giving virtually no privacy.</p><h4>Connections between definitions of privacy</h4><p>Another insight from Dong et al (2022) is that one can convert between(epsilon, delta) -differential privacy and f-differential privacy, and thus also Gaussian differential privacy. This is useful for two reasons. First, it means existing results from (epsilon, delta)-differential privacy apply also to the definitions here. Second, for certain analyses, it is more convenient to work with one definition than the other, but results derived from one hold for the other. For instance, one can analyze composition more easily with f-differential privacy, but analyze the privacy properties of mechanisms with data sub-sampling (discussed in the paper) more easily with (epsilon,delta)-differential privacy.</p><h3>Conclusion</h3><p>We saw that the hypothesis testing interpretation gives rise to new notions of privacy such as f- and Gaussian differential privacy, which are more handy to work with for certain analyses of privacy.</p><p>We now have the foundations to understand privacy testing in machine learning. Both the hypothesis testing interpretation and Gaussian differential privacy have been useful to empirically check the privacy-preserving properties of machine learning algorithms. This will be covered in a future article.</p><blockquote>Thanks to Kody Moodley, Erik Tjong Kim Sang and Lourens Veen for commenting on and discussing an earlier draft.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccef13153e12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-iii-functional-gaussian-differential-privacy-ccef13153e12">Empirically evaluating privacy in machine learning III: functional &amp; gaussian differential privacy</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empirically evaluating privacy in machine learning II: Hypothesis testing]]></title>
            <link>https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-ii-hypothesis-testing-647806e2985c?source=rss-348aad3349b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/647806e2985c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Flavio Hafner]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 07:31:18 GMT</pubDate>
            <atom:updated>2025-06-17T13:04:23.058Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Using statistics to think like a hacker, so we can avoid them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJd_jaiCV8qyAqdTBk6X3w.jpeg" /><figcaption>Image from page 182 of “Elements of statistics” (1954). Licensed under creative commons.</figcaption></figure><p>This post is the second in a series on evaluating privacy in machine learning models (see first episode <a href="https://blog.esciencecenter.nl/empirically-evaluating-privacy-in-machine-learning-i-introduction-de5fe808d186">here</a>). It explains the hypothesis testing interpretation of differential privacy by showing how differential privacy constrains the success of any attacker in finding out about the underlying data.</p><p>The post assumes readers are familiar with differential privacy and some concepts in statistics and machine learning. In addition, it keeps concepts such as an “input database” and a “data release” abstract. If you are unfamiliar with either of these terms, you can have a look at the <a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-i-introduction-de5fe808d186">previous post</a>. It introduces differential privacy and has a specific example for an input database and a data release.</p><h3>Differential privacy through the lens of hypothesis testing</h3><p>The <a href="https://blog.esciencecenter.nl/empirically-evaluating-privacy-in-machine-learning-i-introduction-de5fe808d186">first blog post</a> of this series showed that differential privacy has adversarial thinking built-in: Leaking sensitive information may allow a malevolent actor to use the information to the disadvantage of a person in the database. In a differentially private mechanism, the more noise is added, the less any adversary can learn about any particular record in the database.</p><h4>Adversarial inference as a hypothesis test</h4><p>This intuition was formalized by <a href="https://arxiv.org/abs/0811.2501">Wasserman &amp; Zou (2009)</a>. Imagine an adversary has access to a differentially private data release Y from a tabular database db. And suppose the adversary wants to find out if a particular person i was part of the database db. Define the neighboring databases db0 and db1, where i is only in db1 but not in db0 .</p><p>Then, the adversary faces the following hypothesis testing problem:</p><ul><li>H0: Y was drawn from db0, so that i was not in the input data for Y.</li><li>H1: Y was drawn from db1, so that i was in the input data for Y.</li></ul><p>When seeing the data, the adversary needs to make an inference about the true state of db , having seen only Y.</p><p>There are four possible scenarios.</p><ul><li>The adversary correctly predicts that Y was based on db0. This is a true negative.</li><li>The adversary correctly predicts that Y was based on db1. This is a true positive.</li><li>The adversary predicts that Y was based on db0, but in truth it was based on db1. This is a false negative.</li><li>The adversary predicts that Y was based on db1, but in truth it was based on db0. This is a false positive.</li></ul><h4>Deriving the ROC curve</h4><p>How does the adversary make their inference? They need a decision rule that takes the observed data Y and returns an output that is db0 or db1.</p><p>In a future blog post, we will be more specific on what such a rule can look like and how one can derive it. For now, we assume the adversary has the following decision rule: First, they have a trained logistic regression model that takes Y as input and returns a score. Second, the adversary decides on a threshold: if the score is above the threshold, the decision rule returns db1, and db0 otherwise.</p><p>In other words, the adversary rejects H0 in favor of H1 if the score is above the threshold. Then, lowering the threshold means rejecting H0 more often, and so:</p><ul><li>The adversary is more likely to detect cases when Y is based on db1. This means a higher true positive rate, which is good for the adversary.</li><li>But the adversary is also more likely to predict that Y is based on db1 when in truth it is based on db0. This means a higher false positive rate, which is bad for the adversary.</li></ul><p>We can visualize this trade-off with the <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">Receiver Operating Characteristic curve</a>, or ROC curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08MYRyhmLsGFGdn8uDp4bA.jpeg" /><figcaption>Figure 1: The blue line is an ROC curve. The distinguishing between H0 and H1 becomes easier as the True Positive Rate increases and the False Positive Rate decreases, thus moving North-West n the figure.</figcaption></figure><p>In the figure above, the blue line defines the trade-off between the False Positive Rate FPR and the True Positive Rate TPR for a given prediction model. Lowering the FPR comes at the cost of a lower TPR, and vice-versa.</p><p>Moreover, the red arrow indicates the direction in which it becomes easier to distinguish between H0 and H1, meaning a lower FPR and a higher TPR: An ideal decision rule gives an FPR of 0 and a TPR of 1. On the other hand, the dotted line indicates the performance of a decision rule that randomly rejects or does not reject H0.</p><p>The ROC curve is a standard tool in machine learning for binary classification — and from here it is only a few steps to visualizing how differential privacy restricts the amount of information an adversary can learn from a data release.</p><h4>Flipping the ROC curve</h4><p>To start, let’s flip the y-axis in the above figure, and recognize that 1-TPR is the False Negative Rate FNR. Thus, we have a curve in the FPR-FNR space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYyNiVYeLyAWXut4IhSpPA.jpeg" /><figcaption>Figure 2: The blue line is an ROC’ curve, which is the ROC curve with a flipped y-axis. The hypothesis test gets easier as we move South-West.</figcaption></figure><p>This figure shows the same information as the previous figure. Importantly, the hypothesis test is easier the closer the blue ROC curve follows the two axes— in other words, the more convex the curve is.</p><h4>Differential<strong> privacy puts constraints on the best possible ROC curve</strong></h4><p>Next, <a href="https://arxiv.org/abs/1311.0776">Kairouz et al (2015)</a> show that if an algorithm satisfies (epsilon, delta) differential privacy, then the adversary’s success in the hypothesis testing problem is bounded by a function of epsilon and delta. Specifically, this bound can be drawn in the FPR-FNR space as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEDoRYwIJDvAoQ8uK16dMA.jpeg" /><figcaption>Figure 3: The performance boundaries of a hypothesis test for two differentially private mechanisms: The blue is from a mechanism that is (epsilon1, delta) differentially private. The red is from a mechanism that is (epsilon2, delta) differentially private. The latter allows for a more convex ROC’ curve of the adversary, and therefore provides less privacy than the first mechanism.</figcaption></figure><p>First, the blue line indicates the best possible performance any adversary can achieve in the hypothesis testing problem when the data satisfy (epsilon1, delta) differential privacy. This means the ROC&#39; curve from the previous figure, cannot cross the blue line — for <em>any</em> adversarial decision rule. As before, the dotted line shows the performance of a decision rule that is completely random.</p><p>Second, the figure illustrates that the parameter delta defines the intercepts of the line on both the FPR and FNR axes. Intuitively, delta defines an area where the adversary’s trade-off is not bounded — for instance, they can lower the FNR without increasing the FPR.</p><p>Lastly, the figure illustrates how epsilon defines the slope of the constraint. Consider two mechanisms with equal delta , but varying epsilonparameters — denoted epsilon1 and epsilon2 with epsilon1 &lt; epsilon2 . Then, we see that the constraint for epsilon2 is closer to the origin of the diagram — showing that a higher epsilon means lower privacy and an easier business for an adversary to make inferences about the underlying data.</p><h3>What do we learn?</h3><p>Starting from the ROC curve in machine learning, we saw how differential privacy restricts the success of an adversary trying to infer whether a certain record was part of a differentially private data release.</p><p>In the next post, we will see how these insights lead to the notions of functional and Gaussian differential privacy, which are more handy to work with for certain analyses of privacy.</p><blockquote>Thanks to Kody Moodley, Erik Tjong Kim Sang and Lourens Veen for commenting on and discussing an earlier draft.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=647806e2985c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-ii-hypothesis-testing-647806e2985c">Empirically evaluating privacy in machine learning II: Hypothesis testing</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking LLM fine-tuning on different HPC systems]]></title>
            <link>https://medium.com/escience-center/benchmarking-llm-fine-tuning-on-different-hpc-systems-0ed7efcac646?source=rss-348aad3349b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ed7efcac646</guid>
            <category><![CDATA[social-data]]></category>
            <category><![CDATA[high-performace-computing]]></category>
            <category><![CDATA[secure-computing]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[benchmarking]]></category>
            <dc:creator><![CDATA[Flavio Hafner]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 12:28:05 GMT</pubDate>
            <atom:updated>2025-05-06T07:39:55.460Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Authors: Flavio Hafner (Netherlands eScience center), Mattie Niznik (Princeton Research Computing), Malte Lüken (Netherlands eScience center), Alessandra Maranca (Princeton University), Matthew Salganik (Princeton University).</blockquote><p>We have developed a benchmark that compares the compute performance of fine-tuning LLMs on multiple high-performance computing (HPC) systems, including systems designed for working with sensitive data. In this blog post, we introduce the benchmark, describe the lessons learned developing it and make it <a href="https://github.com/odissei-benchmarks/torchtune-gpu-benchmark">open-source</a> so that it can be used and improved by others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qy5gQe3QGRqi2Fzq" /><figcaption>Photo by <a href="https://unsplash.com/@nanadua11?utm_source=medium&amp;utm_medium=referral">Nana Dua</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Our use case</h4><p>Our team researches how Large Language Models (LLMs) can be leveraged to predict social outcomes with large-scale social and survey data. We use the ODISSEI Secure Supercomputer (<a href="https://servicedesk.surf.nl/wiki/spaces/WIKI/pages/17826074/ODISSEI+Secure+Supercomputer">OSSC</a>), which <a href="https://www.surf.nl/">SURF</a> operates in the Netherlands. The OSSC is a virtual private cluster running on the hardware of Snellius, the Dutch national supercomputer. The OSSC makes it possible to use GPU and CPU nodes to analyze sensitive data from Statistics Netherlands. This makes the OSSC one among very few systems globally that bring the power of national computing clusters to large-scale social data.</p><p><a href="https://arxiv.org/pdf/2103.14679">Previous performance benchmarks for OSSC</a> were entirely focused on CPUs, and the performance of OSSC for GPU-intensive tasks, such as fine-tuning LLMs, was unknown.</p><p>Our benchmarking compares the performance of the OSSC to two different systems: 1) its parent system, <a href="https://www.surf.nl/en/services/snellius-the-national-supercomputer">Snellius</a>, which is not connected to sensitive data and 2) <a href="https://researchcomputing.princeton.edu/systems/della">Della</a>, an HPC system similar to Snellius, which is operated by Princeton University.</p><h4>Beyond our use case</h4><p>Our benchmark, <a href="https://github.com/odissei-benchmarks/torchtune-gpu-benchmark">openly available on GitHub</a>, is also a starting point for the exploration of fine-tuning performance in other cases. For instance, one can compare the training performance within and across HPC systems:</p><ul><li>Within a system, one may have to choose between different GPU models, and the cost and benefits of using one versus the other may vary depending on the task.</li><li>Across systems, training performance does not only depend on the raw performance of GPUs–the number of floating point operations per second–, but also on factors such as the file system, how the computing hardware (processing cores and nodes) is connected through wires, and the exact version of GPU models used — as we will show.</li></ul><h3>The performance benchmark</h3><h4>The specification</h4><p>We decided that our benchmark should satisfy the following requirements:</p><ul><li>It is easy to run in many different computing environments.</li><li>It tracks multiple measures of speed, such as tokens per second and wall time.</li><li>It tracks anything useful to understand possible differences between the environments (GPU usage, CPU usage).</li><li>It is fast to run.</li><li>It is easy to improve over time: as our research evolves, we may need to re-assess the performance for new use cases.</li><li>It is easy to understand and replicate.</li></ul><p>Our compute conditions are the following:</p><ul><li>Environment: Della, Snellius, OSSC.</li><li>GPUs: A100 (40/80GB VRAM), H100 (80/96GB VRAM).</li><li>Single-node training, with GPUs per node: 1, 2, 4.</li><li>As many CPUs as are necessary to keep the GPUs busy.</li></ul><h4>The implementation</h4><p>We found that <a href="https://pytorch.org/torchtune/stable/index.html">torchtune</a> fits our requirements best. We fine-tune the <a href="https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct">Llama-3.2–1B-Instruct</a> model on the <a href="https://huggingface.co/datasets/yahma/alpaca-cleaned">alpaca-cleaned</a> dataset. Our main hyperparameters are:</p><ul><li>A context length of 2048 on a packed dataset</li><li>Low-Rank Adaptation (LoRA) for the attention layers as well as the output layers. We use a rank of 64, alpha of 128 and 0 dropout.</li><li>A batch size of 6, which was the maximum we could fit into our least capable GPUs (A100)</li></ul><h3>What we found</h3><h4>Performance differences</h4><p>The figure below shows the results from our benchmarking runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*02FthXTB_LRdiwOH" /><figcaption>Tokens per second per GPU on a single node (higher is better). The colors refer to different systems (Della, Snellius, OSSC); the panels refer to different numbers of GPUs.</figcaption></figure><p>In our experience, there was little variation in throughput across different runs on the same system, so we did not average over multiple runs.</p><p>Our four key findings are:</p><ul><li>Della was about 15% faster than the Dutch systems, independent of the number and models of GPUs.</li><li>The OSSC performed on par with Snellius.</li><li>For our use case, H100s were between 1.7x and 2x faster than A100s.</li><li>Throughput scales nearly linearly with the number of GPUs: The communication overhead from multiple GPUs was about 6–8% for going from 1 to 2 GPUs and 2% or less for going from 2 to 4 GPUs.</li></ul><p>Many of these results made sense to us. Because Della and Snellius are broadly similar systems, we were surprised by the performance gap between the two. Thus, we decided to <a href="https://github.com/odissei-benchmarks/torchtune-gpu-benchmark/issues/10">investigate</a> further.</p><p>First, we ruled out that the gap stems from differences in software. The precise way to install dependencies differs between Della and Snellius: Our environments use anaconda on Della and a Python virtual environment with pip on Snellius. We confirmed that the two environments use the same package versions.</p><p>Second, we ruled out that the gap stems from differences in the file system. In particular, for high-performance machine learning, data I/O is often a bottleneck, and it can be reduced by using a fast file system. However, our experiments on Snellius showed no difference in speed between the <a href="https://servicedesk.surf.nl/wiki/display/WIKI/Snellius+filesystems">various file systems</a> available.</p><p>We then found that subtle hardware differences probably explain the gap — differences in memory clock speed of the GPUs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*aX4l-25vcCoCS9on" /><figcaption>Memory clock speed for GPUs on the two systems (higher is better).</figcaption></figure><p>For the A100s, the Snellius/OSSC GPUs have 40GB VRAM, while the Della GPUs have 80GB VRAM. The 80GB variant also comes with a higher memory clock speed than the 40GB variant, leading to the difference in fine-tuning speed on A100s between Della and Snellius.</p><p>For the H100s, the difference is in the version of the cards, and specifically their memory: Della has cards with the faster HBM3 memory, while Snellius/OSSC has cards with HBM2e memory. This means that the calculations during model training have a memory speed bottleneck on Snellius/OSSC compared to Della.</p><h4>Lessons learned from bringing LLMs into secure computing environments</h4><p>Running this test and bringing the Llama model into a secure environment created additional challenges.</p><p>First, by default, torchtune downloads the specified dataset from the internet without the user noticing. But because the OSSC is cut off from the internet, we had to use the Alpaca dataset locally and adjust the code accordingly before deployment.</p><p>Second, to import the model weights to the secure computing environment, we had to ensure that the contents of the files were not a security risk. Thus, we followed current best practices: First, we manually scanned the files with the virus scanner <a href="https://docs.clamav.net/manual/Usage/Scanning.html">ClamScan</a>, similar to what Hugging Face does automatically for models hosted there. Second, we imported the model weights in <a href="https://huggingface.co/docs/safetensors/en/index">safetensors</a> format, which is safer than the pickle format and prevents arbitrary code execution.</p><h3>Conclusion</h3><p>We introduce a benchmark for comparing throughput for LLM fine-tuning on different HPC systems. We found hardware-driven performance differences between two standard HPC systems. We also provide the first performance comparison of the OSSC compared to its parent system, Snellius. Lastly, our benchmark suggests little cost of scaling fine-tuning to multiple GPUs on a single node.</p><p>The code for our benchmark is publicly available: <a href="https://github.com/odissei-benchmarks/torchtune-gpu-benchmark">https://github.com/odissei-benchmarks/torchtune-gpu-benchmark</a></p><blockquote>Thanks to Patrick Bos for feedback on a draft.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ed7efcac646" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/benchmarking-llm-fine-tuning-on-different-hpc-systems-0ed7efcac646">Benchmarking LLM fine-tuning on different HPC systems</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empirically evaluating privacy in machine learning I: Introduction]]></title>
            <link>https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-i-introduction-de5fe808d186?source=rss-348aad3349b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/de5fe808d186</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Flavio Hafner]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 15:25:01 GMT</pubDate>
            <atom:updated>2025-06-27T12:22:16.606Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Research in the social and health sciences often relies on accessing data sourced from statistical agencies or healthcare organizations. Such data sets contain sensitive information, which requires restrictions on who can access the data. This can slow down not only scientific progress — if data were completely open, more researchers could investigate them — , but also the translation of progress to applications — for instance, machine learning models trained on medical data cannot easily be shared and re-used for personalized treatments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uqv0HK733K6-T1iN" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Differential privacy is one technology that aims to solve this problem. Intuitively, it is a method that adds calibrated noise to the data, and so prevents a malevolent actor from learning sensitive attributes about any person in the underlying data. But because statistical noise makes statistical inference harder, there is an inherent trade-off between statistical utility and privacy — making differential privacy challenging to deploy in practice (<a href="https://arxiv.org/abs/2406.12103">Cummings &amp; Sarathy, 2023</a>).</p><p>In addition, using differential privacy in machine learning has its own challenges. First, often it’s impossible to have reasonable privacy and utility at the same time. Second, differential privacy for machine learning makes strong assumptions about the capabilities of the malevolent actor. Third, implementing it in software is not straightforward, and there is evidence of bugs (<a href="https://arxiv.org/abs/2304.06929">Cummings et al, 2023</a>; <a href="https://arxiv.org/abs/2302.07956">Nasr et al, 2023</a>; <a href="https://arxiv.org/abs/2303.00654">Ponomareva et al, 2023</a>).</p><p>For this reason, empirically evaluating the privacy of machine learning models has become an important field of research. Privacy testing probes whether a trained machine learning model leaks sensitive information. It can be an important indicator for model developers and owners of sensitive data whether the privacy-preserving training mechanism can be trusted.</p><h4>The plan for this series of blog posts</h4><p>Despite this, most resources in this topic are in research articles. The goal of this series of blog posts is to make the topic more accessible. We will build knowledge from the ground up:</p><ol><li>The first blog posts introduces differential privacy, and gives some economic intuition. It is aimed at readers unfamiliar with differential privacy.</li><li>The <a href="https://blog.esciencecenter.nl/empirically-evaluating-privacy-in-machine-learning-ii-hypothesis-testing-647806e2985c">second</a> post explains how differential privacy can be interpreted from a perspective of statistical hypothesis testing. It is aimed at readers familiar with differential privacy and some concepts from statistics and machine learning.</li><li>The <a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-iii-functional-gaussian-differential-privacy-ccef13153e12">third</a> post discusses how the hypothesis testing perspective has been used to reformulate differential privacy with functional differential privacy and Gaussian differential privacy. It is aimed at readers interested in understanding privacy testing of machine learning.</li><li>The fourth blog post discusses some recent papers that audit machine learning models and make use of Gaussian differential privacy. It is aimed at an audience similar to the third post.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A9wF6BkPw9h4YKbl" /><figcaption>Photo by <a href="https://unsplash.com/@tobiastu?utm_source=medium&amp;utm_medium=referral">Tobias Tullius</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>A short introduction with an example</h3><p>This section builds on <a href="https://www.cis.upenn.edu/~aaroth/Papers/privacybook.pdf">Dwork &amp; Roth (2013)</a>.</p><h4>Randomized response</h4><p>Imagine a researcher wants to know the fraction of people that engage in a behavior that is illegal or socially not accepted — for instance, if they have income that they do not declare to the tax agency. The researcher runs a survey and asks people whether they have such income. Denote this behavior by the variable <em>X</em>, and let’s say it can take values 0 or 1, where 1 indicates the person earns undeclared income, and 0 indicates the person does not.</p><p>How can the researcher ensure that people are willing to share this sensitive information with them? To solve this problem, social scientists have developed a method called <em>randomized response</em>, which gives survey participants the following instructions:</p><ul><li>Flip a coin privately</li><li>If it comes up heads, answer truthfully</li><li>If it comes up tails, flip again. If the second flip is heads, answer with “1”, if the second flip is tails, answer with “0”.</li></ul><p>This approach strikes a balance between privacy and statistical utility. First, privacy comes from plausible deniability — anyone can always plausibly claim not to engage in behavior <em>X, </em>independently of the answer they have given. Second, statistical accuracy comes from understanding how the noise was generated: because we know the response mechanism, we can infer the mean of <em>X</em> in the population.</p><p>In addition, in a more general setting, one could replace the first coin flip with a draw from a continuous random variable that takes values between 0 and 1, and instruct people to respond truthfully if the random variable is above some threshold p. Varying p amounts to varying the amount of noise we introduce to the response. On one hand, if p=0 , we have perfect accuracy but no privacy. If p=1 , we have perfect privacy but no accuracy.</p><h4>Formal definition of differential privacy</h4><p>Define db as a tabular database where each row corresponds to the data of one person. We call db0 and db1 neighboring databases when they differ by one record: they hold the exact same information, except for one person called Anne. For instance, it can be that Anne is not present in database db0 but in db1, or that some column in Anne’s row is altered in db1 but not db0 .</p><p>Now, consider an algorithm M that takes db as input and creates some output. The algorithm is randomized because its outcome is not deterministic, but drawn from some distribution: The distribution of outcomes of the algorithm when fed with db is denoted M(db).</p><p>Such an algorithm is called (epsilon,0) <strong>-differentially private</strong> if the distribution of M(db0) and the distribution M(db1) are not too different from each other — formally, if the log odds of observing any outcome from M(db0) vs M(db1) are not larger than epsilon. The 0 in the (epsilon,0) expression is a second parameter called delta, which denotes the probability that this guarantee fails. It is typically a very small number that decreases in the size of the database db.</p><h4>Differential Privacy of randomized response</h4><p>This is an abstract definition, but we now show that randomized response satisfies differential privacy. To do so, we assume that the database db only consists of one person — one row — , and one variable — the answer to the survey. We will relax this assumption later.</p><p>Let y_i = M(x_i)=1 denoting that person i with attribute x_i answers 1 to the survey. Note that we only observe y_i and x_i is kept private. The randomized mechanism M is the protocol that instructs people to flip coins and respond accordingly; M generates a Bernoulli distribution of outcomes over neighboring databases with the following probabilities.</p><p>We can construct neighboring databases by varying person i‘s sensitive attribute x_i: One input database has x_i=1, and the other has x_i=0 . Running randomized response, what are the probabilities of y_i=1 given values for x ? If x_i=1, the person answers “1” with probability 0.75; if x_i=0 , the person answers “1” with probability 0.25. In other words, for personi , the odds ratio for randomized response returning y_i=1 when having x_i=1 as opposed to having x_i=0 is P[y_i=1|x_i=1]/P[y_i=1|x_i=0]=(3/4)/(1/4)=3 . We can do a similar analysis for the outcome y_i=0 . Therefore, randomized response satisfies (ln(3),0) differential privacy.</p><h4>Economic intuition</h4><p>What does differential privacy promise? Let’s continue with the example of undeclared income. Suppose the researcher publishes the finding that 50% of people have some undeclared income. In response, the tax agency improves their enforcement, finds the people that do not declare income, and fines them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rzj7J2OOvfB30SSn" /><figcaption>Photo by <a href="https://unsplash.com/@nypl?utm_source=medium&amp;utm_medium=referral">The New York Public Library</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Pick one person, Bob, who is a tax dodger and who participated in the original survey of the researcher. Because of better enforcement, he gets caught by the tax office and needs to pay a fine. Does differential privacy guarantee that Bob is not being penalized for his behavior?</p><p>No. Recall that differential privacy guarantees a similar distribution of outcomes under two neighboring databases. Releasing the survey result does impact Bob’s utility, but it does so independently of whether Bob is in the data or not: Even if Bob did not participate in the original survey, the tax office would have learned that many people do not declare their income, and started stronger enforcement, possibly leading to Bob being caught and fined.</p><p>In other words, Bob’s expected utility is similar in the two scenarios considered, and <em>no differential harm</em> is caused to Bob from releasing the survey results. This highlights a crucial aspect of differential privacy: <strong>what matters is the difference in outcomes from being in the database and from not being in the database</strong>. Differential privacy makes no guarantees about the <em>level</em> of utility of records in the database. And in consequence, “Statistical Inference is Not a Privacy Violation” (<a href="https://differentialprivacy.org/inference-is-not-a-privacy-violation/">Bun et. al., 2021</a>).</p><h3>The limits of this example</h3><p>Above, we made the simplifying assumption that a database consists only of one row and one column. In real life, databases have multiple rows and columns. That’s why it is common to define neighboring databases by taking two databases that vary exactly by one row, but are otherwise identical.</p><p>But working with this definition, applying randomized response to the sensitive attribute x_i is not enough anymore to guarantee the privacy of each person in the survey. For instance, if for each person, the researcher published the randomized response y_i along with some of their true identifying information — for instance their address and age — , it would be possible for the tax office to prosecute people with y_i=1, since they are more likely to have x_i=1.</p><p>Instead, the researcher needs to collect the real answers of all participants, decide which statistic to use for publishing the results, and apply a respective algorithm that satisfies differential privacy. But this then also requires that the survey participants trust the researcher that they will not use the sensitive data against them.</p><h4>Differential privacy’s model of computation</h4><p>These questions bring us to two important assumptions behind the theory of differential privacy. The first assumption is that there is a <strong>trusted curator</strong> of the data — in our case the researcher that holds the individual survey responses are trusted to not leak the individual responses to the tax office.</p><p>The second assumption is that only results to <strong>queries</strong> are released — in our case, a relevant statistic of the survey such as “the fraction of people that have undeclared income”.</p><p>Another important aspect of differential privacy is that multiple queries of the same data weaken privacy, even if each query itself satisfies differential privacy. For instance, suppose the researcher allowed the tax office to get multiple differentially private queries of the original data. Then, the tax office could gradually refine their queries and potentially identify a certain person that does not pay their taxes.</p><p>This problem is known as <strong>composition</strong>, and differential privacy provides mathematical tools to study how exactly privacy degrades with composition. We will touch on it again in the context of differentially private machine learning.</p><h3>Conclusion</h3><p>We used an example from social science research to illustrate how differential privacy can strike a trade-off between utility and privacy. The example helped illustrate the assumptions that are important for privacy guarantees. In the <a href="https://blog.esciencecenter.nl/empirically-evaluating-privacy-in-machine-learning-ii-hypothesis-testing-647806e2985c">next</a> blog post, we will look at the hypothesis testing interpretation of differential privacy.</p><blockquote>Thanks to Kody Moodley, Erik Tjong Kim Sang and Lourens Veen for commenting on and discussing an earlier draft.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de5fe808d186" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/empirically-evaluating-privacy-in-machine-learning-i-introduction-de5fe808d186">Empirically evaluating privacy in machine learning I: Introduction</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to manage your IP address in Python]]></title>
            <link>https://medium.com/escience-center/how-to-manage-your-ip-address-in-python-75a2c9eda648?source=rss-348aad3349b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/75a2c9eda648</guid>
            <category><![CDATA[research-software]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Flavio Hafner]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 09:55:48 GMT</pubDate>
            <atom:updated>2024-02-27T09:55:48.590Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This post is the first of a series of blog posts arising from a collaboration between the eScience Center and the ODISSEI Social Data Science Team. You can find this text also at <a href="https://odissei-soda.nl/tutorials/">https://odissei-soda.nl/tutorials/</a>.</blockquote><p>Research often relies on accessing novel data, for instance by collecting them from the internet through web scraping. If you have ever tried this, you may have run into your IP address being blocked by the website you scrape. Websites do this with a good reason — to protect themselves against malicious acts, such as <a href="https://en.wikipedia.org/wiki/Denial-of-service_attack">denial-of-service attacks</a> or large-scale scraping by parties with ill intent. This makes sense from the websites’ perspective, but prevents you from answering your research question.</p><p>But this problem can be solved. In this tutorial, we show how you as a researcher can use IP rotation to circumvent certain scraping protections with the sirup package, which works on Linux operating systems.</p><p>Before we jump into it, it is important to highlight that web scraping and IP rotation need to respect the law and should only be a last resort. For instance, before you scrape data from a website, you should ask the data owner whether they are willing to make them available to you through a data sharing agreement. If you nevertheless decide to scrape the data, you should get approval from the ethical review board at your university. Moreover, do only scrape data that are publicly available on the web and do not send excessive number of requests to the website in a given time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rCeQ_vF1vWGlWYGv" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For rotating the IP address, we will use a VPN service. <a href="https://azure.microsoft.com/en-us/resources/cloud-computing-dictionary/what-is-vpn#:~:text=A%20VPN%2C%20which%20stands%20for,and%20firewalls%20on%20the%20internet.">Here</a> you can read more about what a VPN service is—in short, the service has a bunch of remote servers, and connecting your computer to one of these servers changes your IP address.</p><h3>What you need</h3><h3>1. OpenVPN</h3><p><a href="https://en.wikipedia.org/wiki/OpenVPN">OpenVPN</a> is a system that allows you to create secure VPN connections. You can install it by following <a href="https://community.openvpn.net/openvpn/wiki/OpenvpnSoftwareRepos">these instructions</a>.</p><h3>2. Root access to your computer</h3><p>Because internet connections are an important security concern, OpenVPN requires root access — this is the equivalent to administrator rights on a Windows computer. If you have root access, you can for instance run the following command on your terminal:</p><pre>sudo ls -lh # will ask you for your root password</pre><h3>Installing and setting up sirup</h3><p>You can install sirup as follows:</p><pre>python -m pip install sirup</pre><p>To use the package and change your IP address, you need an account with a VPN service provider that offers OpenVPN configuration files for your account. At the time of writing, for instance ProtonVPN and Surfshark offer this option — note that these services are not for free. We will use ProtonVPN in this tutorial.</p><p>After creating an account, you need to download two sets of files.</p><p>First, you download credentials that identify your Proton account when using OpenVPN. On the ProtonVPN website, click on “Account” and then you see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*x-ck8J9O6s-JLY-X" /></figure><p>Copy and paste the username and the password into a txt file that looks like this:</p><pre>username<br>password</pre><p>Then, save the file as “proton_credentials.txt”. Remember where it is stored — we will need it later.</p><blockquote><strong>A first warning on security. </strong>Storing account credentials like this makes it easy for you to use the sirup package. But it also increases the risk that unauthorized persons get a hold on these credentials. Thus, be careful to store the credentials in a safe place on your laptop and to not share them with anyone.</blockquote><p>Second, to use OpenVPN we need configuration files, whose names end with .ovpn. The files allow OpenVPN to connect to a server from the VPN service provider. In ProtonVPN, go to the &quot;Download&quot; section of your account. Select the options as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5D877Odmx0Jr5DKr" /></figure><p>And download the configuration file(s) you want to use. Store the downloaded files on your computer, and remember the location.</p><p>Now you are ready!</p><h3>Using sirup</h3><p>We start by defining the path to the proton_credentials.txt file. When you execute the code below, you will be asked to enter the root password, which is necessary to make the connection.</p><pre>import getpass<br>auth_file = &quot;proton_credentials.txt&quot;<br>pwd = getpass.getpass(&quot;Please enter your root password:&quot;)</pre><blockquote><strong>A second warning on security.</strong> The code above stores your root password during the Python session without encrypting it. This is OK to do on your laptop — if someone gets access to your Python session, your security has already been compromised — but not recommended on a shared computer such as a cluster or a cloud service.</blockquote><h4>Changing the IP address with sirup</h4><p>Now you can use the VPNConnector to change our IP address. We will use the &quot;my_config_file.ovpn&quot; configuration file.</p><pre>from sirup.VPNConnector import VPNConnector<br>config_file = &quot;my_config_file.ovpn&quot;</pre><p>The code below first connects to the server associated with &quot;my_config_file.ovpn&quot; and then disconnects.</p><pre>connector = VPNConnector(auth_file, config_file)<br><br># Let&#39;s see the current IP address when no VPN tunnel is active<br>print(connector.base_ip) <br><br>connector.connect(pwd=pwd)<br><br># Now the IP address should differ<br>print(connector.current_ip)<br><br>connector.disconnect(pwd=pwd)<br><br># Now current_ip should be the same as base_ip above<br>print(connector.current_ip)</pre><h4>Rotating the IP address with sirup</h4><p>Instead of connecting to a single server, you can also rotate across many different servers — which means you rotate your IP address across a set of potential addresses. Doing so is useful for larger scraping jobs because it will spread your requests across more servers.</p><p>To do this, you need to download multiple configuration files as described above. Store all of the .ovpn configuration files together in a separate directory. Let&#39;s say you store them in the &quot;/path/to/config/files/&quot; directory. You need to define this path in your Python script:</p><pre>config_path = &quot;/path/to/config/files/&quot;</pre><p>The following code connects to two different servers before disconnecting again:</p><pre>from sirup.IPRotator import IPRotator<br><br>rotator = IPRotator(auth_file=my_auth_file, config_location=config_path, seed=seed) # this will ask for the root password<br><br>print(rotator.connector.base_ip) <br><br>rotator.connect()<br>print(rotator.connector.current_ip) <br><br>rotator.rotate()<br>print(rotator.connector.current_ip) <br><br>rotator.disconnect()<br><br>print(rotator.connector.current_ip)</pre><h3>Conclusion</h3><p>This tutorial has walked you through the steps to manage your IP address in Python, using the sirup package. We hope it makes your scraping workflows easier!</p><blockquote>sirup is an open-source package developed by the Netherlands eScience Center. If you use the tool, you can cite <a href="https://zenodo.org/records/10261949">this zenodo repository</a> with the DOI: <a href="https://doi.org/10.5281/zenodo.10261949">https://doi.org/10.5281/zenodo.10261949</a>.</blockquote><blockquote>The source code of the package is <a href="https://github.com/ivory-tower-private-power/sirup?tab=readme-ov-file">here</a>, where you can contribute to it, build on it and submit issues.</blockquote><p>Thanks to Patrick Bos, Peter Kalverla, Kody Moodley and Carlos Gonzalez Poses for comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75a2c9eda648" width="1" height="1" alt=""><hr><p><a href="https://medium.com/escience-center/how-to-manage-your-ip-address-in-python-75a2c9eda648">How to manage your IP address in Python</a> was originally published in <a href="https://medium.com/escience-center">Netherlands eScience Center</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>