<?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 François Ponchon on Medium]]></title>
        <description><![CDATA[Stories by François Ponchon on Medium]]></description>
        <link>https://medium.com/@franoisponchon?source=rss-1ef0d35b1011------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FGJ_tNmFNRq5l20zxiE4mw@2x.jpeg</url>
            <title>Stories by François Ponchon on Medium</title>
            <link>https://medium.com/@franoisponchon?source=rss-1ef0d35b1011------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:29:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@franoisponchon/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[Pytorch DDP — Debugging in VSCode]]></title>
            <link>https://medium.com/@franoisponchon/pytorch-ddp-debugging-in-vscode-4fb162eba07e?source=rss-1ef0d35b1011------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb162eba07e</guid>
            <category><![CDATA[distributed]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[accelerate]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[François Ponchon]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 08:20:02 GMT</pubDate>
            <atom:updated>2024-01-26T06:50:55.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pytorch DDP — Debugging in VSCode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfB7eBM8K2pF_a3d8MrNAg.png" /><figcaption>Pytorch DDP — Debugging with Vscode</figcaption></figure><h3>Introduction</h3><p>Now Artificial intelligence training rely more and more on distributed computing.<br>The ability to debug distributed code has become a way point in the life of an MLEngineer / Datascientist.</p><p>Distributed Data Parallel (DDP), allows to run a job on multiple devices. It can be GPUs or CPUs. Most of the time, shared clusters are not available for debugging, then we need to use a less powerfull machine in order to do this debugging.</p><p>In this article, we’ll see how to use gloo backend in order to debug a distributed code on a single GPU laptop even CPU only laptop.</p><p>I will not cover the details of DDP implementation, if you want more information about that, you can follow this great article.</p><p>In this article, i’ll focus on debugging and use <em>accelerate </em>library from huggingface.</p><p><a href="https://medium.com/codex/a-comprehensive-tutorial-to-pytorch-distributeddataparallel-1f4b42bb1b51">A Comprehensive Tutorial to Pytorch DistributedDataParallel</a></p><h3>VSCode Debug Configuration</h3><p>Vscode is an IDE that is use by a large community, often in the top 5 of IDEs used for python developpment.</p><p>In vscode, when it comes to debugging, you can use a configuration file in order to define your entrypoint. In order to generate it, you just need to go in the debug tab and click on <em>create launch.json</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*0MU0UZjiYREZkvY0haabig.png" /><figcaption>create a launch.json from vscode.</figcaption></figure><p>Let’s start by an example :</p><pre>{<br>    // Use IntelliSense to learn about possible attributes.<br>    // Hover to view descriptions of existing attributes.<br>    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;Python: Current File&quot;,<br>            &quot;type&quot;: &quot;python&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            // ${file} will be replaced by the current opened file<br>            // It can be a problem when you want to run code from a file<br>            // and debug a dependancy.<br>            &quot;program&quot;: &quot;${file}&quot;,<br>            &quot;console&quot;: &quot;integratedTerminal&quot;,<br>            &quot;justMyCode&quot;: false<br>        },<br><br>        {<br>            &quot;name&quot;: &quot;Example: Classification Training&quot;,<br>            &quot;type&quot;: &quot;python&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            // In this example, we run everytime the same file<br>            &quot;program&quot;: &quot;examples/train_classification.py&quot;,<br>            &quot;console&quot;: &quot;integratedTerminal&quot;,<br>            &quot;justMyCode&quot;: false,<br><br>        }<br>   ]<br>}</pre><p>With this kind of configuration file, you can now debug whatever piece of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NkrJQjzGBVYf2LodOC4UQ.png" /><figcaption>Example of degugging with a breakpoint in classificationtrainer.py run from a caller script train_classification.py</figcaption></figure><p>If we take a look on the configuration, we see that we under the hood the command is :</p><pre>cd {workspace_dir} ; /usr/bin/env {env_path}/bin/python \<br>{vscode_dir}/debugpy/launcher 52843 -- examples/train_classification.py </pre><p>vscode ask python to launch a debugpy server listening on port 52843 to listen the process that we want to debug.</p><p>The issue when you use distributed code is that you no longer run it with traditionnal python command, for example :</p><pre># Not distributed<br>python example/train_classification.py<br><br># Distributed (no longer use python).<br>torchrun --nproc_per_node=2 example/train_classification_multicpu.py<br># Equivalent to : <br>python -m torch.distributed.launch --use_env --nproc_per_node=2 example/train_classification_multicpu.py</pre><p>But wait, on my computer i have only one GPU, then how can i debug a code that should be distributed on multiple gpus ?</p><h3>Accelerate Library (Huggingface)</h3><p>First of all, i setup my code with <em>accelerate</em>. Because it is not the purpose of current article, i will not detail it but you can find documentation there :</p><p><a href="https://huggingface.co/docs/accelerate/index">Accelerate</a></p><p>Just note that accelerate script can be run with traditionnal DDP commands.</p><pre># Accelerate command<br>accelerate launch --num_processes 2 example/train_classification.py<br># Almost Equivalent<br>torchrun --nproc_per_node=2 example/train_classification_multicpu.py</pre><p>Personnally i never use accelerate launch because i run my job in AzureML and it uses pytorch native way to run jobs.</p><p>Because we don’t have multiple GPU on our computer, we will make 2 slights changes in our code…</p><h4>Gloo Backend / CPU Distributed Training</h4><p>The first one, at the beggining of the code, we’ll force pytorch to use <em>gloo </em>backend. gloo allows us to avoid nccl. Another advantage is that gloo can be run on windows when nccl (to my knowledge) is only available on linux.</p><pre>import accelerate<br>import torch.distributed as dist<br><br># Because torch is initialized before accelerate, <br># accelerate will take in account this configuration<br># source : <br># https://github.com/huggingface/accelerate/issues/141<br>dist.init_process_group(backend=&#39;gloo&#39;)<br>ws = dist.get_world_size()</pre><p>Finally, because we don’t have multiple gpu on our computer, we’ll distribute our job over multiple cpus.</p><pre># Use accelerator on cpu<br>accelerator = Accelerator(cpu=True)</pre><p>Because we use accelerate, it’s the two only operation you have to do.</p><h3>What kind of bugs ?</h3><p>One may wonder why it’s worth talking about debugging multi-gpu code. Let’s imagine an example.</p><blockquote>I want to extend accelerate with more logging capabilities in order to automatically reduce metrics accross nodes (by taking the mean) and aggregate metrics over the epoch.</blockquote><p>In order to do that, i may want to do such things :</p><pre>class Accelerator(accelerate.Accelerator):<br>    # Dictionnary that accumulate metrics/losses over batches...<br>    _accumulated_dict: Dict[str, Dict[str, List[float]]] = {}<br>    <br>    def log_accumulate(<br>        self,<br>        value_dict: Dict[str, torch.Tensor],<br>        global_step: int,<br>        dist_fx: str = &quot;none&quot;,<br>        accumulate_fx: str = &quot;none&quot;,<br>        prefix: str = &quot;&quot;,<br>        log_batch: bool = True,<br>        dst_trackers: Union[str, List[str]] = &quot;all&quot;,<br>    ):<br>        &quot;&quot;&quot;_summary_<br><br>        Args:<br>            value_dict (Dict[str,torch.Tensor]): _description_<br>            global_step (int): _description_<br>            dist_fx (str, optional): _description_. Defaults to &#39;mean&#39;.<br>            accumulate_fx (str, optional): _description_. Defaults to &#39;none&#39;.<br>            prefix (str, optional): _description_. Defaults to &#39;&#39;.<br>            log_batch (bool, optional): _description_. Defaults to True.<br>            dst_trackers (str,List[str]): Restrict to a subset of trackers...<br>        &quot;&quot;&quot;<br>        assert dist_fx in [&quot;mean&quot;, &quot;sum&quot;, &quot;none&quot;]<br>        assert accumulate_fx in [&quot;mean&quot;, &quot;sum&quot;, &quot;none&quot;]<br>        for key, value in value_dict.items():<br>            # First, we apply distributed reduction...<br>            if dist_fx != &quot;none&quot; and isinstance(value, torch.Tensor):<br>                value = self.reduce(value, dist_fx)<br>            # Then, we accumulate if necessary...<br><br>            if accumulate_fx != &quot;none&quot;:<br>                # We create a key_accumulation in order to accumulate the value...<br>                acc_key = f&quot;{prefix}{key}_{accumulate_fx}&quot;<br>                if acc_key in self._accumulated_dict:<br>                    self._accumulated_dict[acc_key]: List[float]<br>                    self._accumulated_dict[acc_key].append(float(value_dict[key]))<br>                else:<br>                    self._accumulated_dict[acc_key] = [float(value_dict[key])]<br>            # We log...<br>            if log_batch:<br>                self.log(<br>                    {f&quot;{prefix}{k}&quot;: v for k, v in value_dict.items()},<br>                    global_step,<br>                    dst_trackers,<br>                )<br><br><br><br>    @on_main_process<br>    def get_accumulate(self, key: str):<br>        # Get accumulated loss values in the end of an epoch for example<br><br>    @on_main_process<br>    def log_compute(self, global_step: int, reset: bool = True):<br>        output_dict = {}<br>        for acc_key in self._accumulated_dict.keys():<br>            acc_value = self.get_accumulate(acc_key)<br>            output_dict[acc_key] = float(acc_value)  # we cast as float for mlflow<br>        self.log(output_dict, global_step=global_step)<br>        # We reset if necessary the dictionnary.<br>        if reset:<br>            self._accumulated_dict = {}<br><br></pre><p>This allows us to compute automatically the aggregated values accross different nodes and durring epochs, what is very convenient to use and reduce the training code.</p><p>But let’s imagine, at the first implementation, we add this :</p><pre>class Accelerator(accelerate.Accelerator):<br>    # Dictionnary that accumulate metrics/losses over batches...<br>    _accumulated_dict: Dict[str, Dict[str, List[float]]] = {}<br>    <br>    @on_main_process  # Decorator to force this function to be run only on the first process<br>    def log_accumulate(<br>        self,<br>        value_dict: Dict[str, torch.Tensor],<br>        global_step: int,<br>        dist_fx: str = &quot;none&quot;,<br>        accumulate_fx: str = &quot;none&quot;,<br>        prefix: str = &quot;&quot;,<br>        log_batch: bool = True,<br>        dst_trackers: Union[str, List[str]] = &quot;all&quot;,<br>    ):</pre><p>For a begginer, it can be an easy to do error, but if we implement it this way, the distributed job will hang because the first process will wait the second one at this line, that requires a synchronisation :</p><pre>`value = self.reduce(value, dist_fx)</pre><p>And debugging such a things when your machine is not multigpu can give you headaches !</p><h3>Debug in vscode</h3><p>In order to debug it, we’ll have to modify a little the configuration :</p><pre>{<br>    // Use IntelliSense to learn about possible attributes.<br>    // Hover to view descriptions of existing attributes.<br>    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>         ...,<br>        {<br>            &quot;name&quot;: &quot;Example: Classification Training&quot;,<br>            &quot;type&quot;: &quot;python&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            // In this example, we run everytime the same file<br>            &quot;program&quot;: &quot;examples/train_classification.py&quot;,<br>            &quot;console&quot;: &quot;integratedTerminal&quot;,<br>            &quot;justMyCode&quot;: false,<br><br>        },<br>        {<br>            &quot;name&quot;: &quot;Example: Classification - MultiCPU&quot;,<br>            &quot;type&quot;: &quot;python&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            // we launch a module...<br>            &quot;module&quot;:&quot;torch.distributed.launch&quot;,<br>            // with args...<br>            &quot;args&quot;:[&quot;--use_env&quot;,&quot;--nproc_per_node=2&quot;,&quot;example/train_classification_multicpu.py&quot;],<br>            &quot;console&quot;: &quot;integratedTerminal&quot;,<br>            &quot;justMyCode&quot;: false<br>        },<br>   ]<br>}</pre><p>When running this way, we see that everything appears in double in our terminal :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VeIbqpRhqa-XkNCgOJSQQg.png" /><figcaption>Every line in double in the terminal</figcaption></figure><p>If we put a breakpoint, we’ll see that vscode will stop us 2 times, one in each process !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQGe3O5qD-82mcPvF4p26g.png" /><figcaption>Breakpoint in Local Rank 0 (Main Process)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wFpJN4pE56fMkXFanGfdQ.png" /><figcaption>Breakpoint in Local Rank 1</figcaption></figure><p>This way you are able to run your code step by step and identify the issue !</p><h3>Conclusion</h3><p>In this post, we saw how to debug a distributed job with vscode.<br>As you can see, we use <em>torch.distributed.launch</em> module in order to run our code, but it will be deprecated in future. Let me know if you know any alternative that use <em>torchrun </em>instead !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*14f9E7cgDNSRkGEe8qPJ4A.png" /><figcaption>torch.distributed.launch deprecated message</figcaption></figure><p>Thanks for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb162eba07e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SimCLR — STL10 Implementation]]></title>
            <link>https://medium.com/@franoisponchon/simclr-stl10-implementation-423dbebb4a0f?source=rss-1ef0d35b1011------2</link>
            <guid isPermaLink="false">https://medium.com/p/423dbebb4a0f</guid>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[self-supervised-learning]]></category>
            <category><![CDATA[stl10]]></category>
            <category><![CDATA[simclr]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[François Ponchon]]></dc:creator>
            <pubDate>Fri, 07 Jan 2022 16:16:19 GMT</pubDate>
            <atom:updated>2022-01-08T17:09:21.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>SimCLR — STL10 PyTorch Implementation</h3><h3>Introduction</h3><p>In the large field of computer vision, DeepLearning gave us many opportunities to enhance algorithms performances.<br>Althought, this approach suffer from different weaknesses :<br>1) We need large Datasets<br>2) We need to label a large amount of data</p><p>Let’s now focus on training dataset : sometime, the label and context are directly given by the user who take a picture. For example on instagram, people tag images, what’s really helps DataScientists to analyse such images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*3LJQALMRr3wesyI75JduAw.png" /><figcaption>Cats results on Instagram</figcaption></figure><p>If we deal with more specific needs, like in the industry, we’ll probably not found images on instagram. we’ll have to build our own dataset and gather labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*YmraAbfFAOQbPHmj.png" /><figcaption>gargour.com — Bottles Classification</figcaption></figure><p>This labelling task can be very time consuming for people who do this, so we’ll want to reduce this to be as small as possible.</p><p>For many use cases (not all) gathering data is not as complicate as labelling it. So we’are in a situation where we have a huge amount of data, and a relatively small amount that is labelled in our training set.</p><h3>STL10 Dataset</h3><p>The purpose of STL10 dataset, is exactly to study such problem and it is why we’ll use it for this example !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*z_S8YsEJBCye4Mfd-N8N7w.png" /></figure><p>STL10 contains 500 training images per classe, 800 test images per classe and 100 000 unlabelled images.</p><p><a href="https://cs.stanford.edu/~acoates/stl10/">https://cs.stanford.edu/~acoates/stl10/</a></p><p>We have 10 classes representing vehicules,animals etc… what can be a great playground for our problem.<br><strong>But how to use unlabelled image ?</strong></p><h3>Self-Supervised / SimCLR</h3><p>When we don’t have label, we need to create a “pretext task” in order to train a model’s backbone that we’ll next finetune on a supervised pipeline.</p><p>This way, the backbone is already aware about features inside images when we start to train the final model.</p><p><strong>But what is a pretext task ?</strong></p><p>Pretext task is a task created by augmentation on the data.<br>For example, you can :<br>- Rotate the original image and train the model to predict the rotation<br>- Convert the image ToGrayscale and Colorize it</p><p>Another option is to use <strong>SimCLR (Constrastive LeaRning) </strong><a href="https://arxiv.org/pdf/2002.05709.pdf">https://arxiv.org/pdf/2002.05709.pdf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*8zNDQpeScrzDG2Xi1QHRGg.png" /></figure><p>The idea behind SimCLR is that images that are from the same class should have <strong>almost </strong>the same features.<br>Why Almost ? Because we have a transformation between the original image and the final image.<br>If we do a rotation, a left “black/white” border can become a top “black/white” border.</p><p>In order to deal with it, we’ll train a projector in order to project the <strong>feature space h </strong>in a <strong>comparison space z</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*RD-PUY4VfqwqYbpg2VnQ5A.png" /><figcaption>Pair Generation — SimCLR</figcaption></figure><p>To sum up, during the training process, we have batches of <strong>size k</strong>.<br>With augmented images, we have <strong>2k</strong> images.<br>We want :<br>Maximize sim(z_i,z_j) for j=i+k<br>Minimize sim(z_i,z_j) else</p><p>With sim = cosine similarity.</p><p>In order to do this min(max) process, we’ll minimize the ratio.<br>To get more ressources, you can have a look to articles [1] and [2] that are very interesting.</p><h3>The code</h3><p>The first thing to implement is the dataset :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14118b4abbbb9291dce0bd8018fe4152/href">https://medium.com/media/14118b4abbbb9291dce0bd8018fe4152/href</a></iframe><p>In this dataset, we have two set of transformations, one is applyed to generate x1 image, the second x2 image.<br>You also notice that we use labelled examples for validation : It is important if we want to plot the representation space with tensorboard (you’ll see bellow).</p><p>Then we’ll code the loss :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f321b093b231005064727c36872e017a/href">https://medium.com/media/f321b093b231005064727c36872e017a/href</a></iframe><p>Then the model :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1adb38f95239f7dbeb1a89e7642f460/href">https://medium.com/media/f1adb38f95239f7dbeb1a89e7642f460/href</a></iframe><p>To train this model we’ll create a model trainer :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ab9da3ca6e97027f5571d4eee1a310/href">https://medium.com/media/97ab9da3ca6e97027f5571d4eee1a310/href</a></iframe><p>Finally, we’ll start the training with the train_CLR.py script :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18409674871f4a01424b0b6f4c3aa4d0/href">https://medium.com/media/18409674871f4a01424b0b6f4c3aa4d0/href</a></iframe><p>The full repository is available <a href="https://github.com/FrsECM/exp-simclr_medium">here</a>.</p><h3>Results</h3><p>After model training, we can plot the representation space with tensorboard :<br>In this space, we colorize items by label and we can select items that are close in the latent space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1CfdmE_n8E-BWFrLe5d9w.png" /></figure><p>Bellow an animation of the process :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qjdDhu8829RpZ8WuvT8sg.gif" /></figure><p>Next step :</p><ul><li>Finetune the generated model for a classification task</li></ul><h3>Bibliography</h3><p>[0] SimCLR Paper : <a href="https://arxiv.org/pdf/2002.05709.pdf">https://arxiv.org/pdf/2002.05709.pdf</a><br>[1] <a href="https://medium.com/analytics-vidhya/understanding-simclr-a-simple-framework-for-contrastive-learning-of-visual-representations-d544a9003f3c">https://medium.com/analytics-vidhya/understanding-simclr-a-simple-framework-for-contrastive-learning-of-visual-representations-d544a9003f3c</a><br>[2] <a href="https://medium.com/the-owl/simclr-in-pytorch-5f290cb11dd7">https://medium.com/the-owl/simclr-in-pytorch-5f290cb11dd7</a><br>[3] STL10 Dataset — <a href="https://cs.stanford.edu/~acoates/stl10/">https://cs.stanford.edu/~acoates/stl10/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=423dbebb4a0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Colab & CFD (Navier Stokes)]]></title>
            <link>https://medium.com/@franoisponchon/google-colab-cfd-navier-stokes-879d9a9723fe?source=rss-1ef0d35b1011------2</link>
            <guid isPermaLink="false">https://medium.com/p/879d9a9723fe</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finite-element-analysis]]></category>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[cfd]]></category>
            <category><![CDATA[navier-stoke]]></category>
            <dc:creator><![CDATA[François Ponchon]]></dc:creator>
            <pubDate>Sat, 30 May 2020 19:04:10 GMT</pubDate>
            <atom:updated>2020-05-31T08:23:12.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*-nZJGddZ5-9QAJ-u9bTEKw.png" /><figcaption>My old building</figcaption></figure><p>Last month, in my country, we had very windy weather, like a storm.<br>Locked in my flat, due to COVID-19, i wondered about how fast was the wind nearby, and how buildings will react.</p><p>I decided to search for a tool in order to simulate the wind flow in 2 dimension : my building has a very simple shape then it seems easy to do. But i didn’t find any suitable tool because of lack of time and experience on this subject.</p><p><strong>Important :</strong></p><p>As i’am not a physician, i don’t have strong basis on CFD. Maybe what i did is not rigourous from a physical point of view. If you point any error, i would appreciate your comment in order to edit my code to fit better with reality !</p><h3>Navier-Stokes</h3><p>I remembered my 10 years ago courses about Navier Stokes equations, and i decided to find ressources to do it myself with python.</p><p>During my research, i’ve find a very interesting online CFD course from Boston University.<br><a href="https://www.youtube.com/playlist?list=PL30F4C5ABCE62CB61">https://www.youtube.com/playlist?list=PL30F4C5ABCE62CB61</a><br>This course was the basis for my work, especially 11th to 13th lessons !</p><h3>Building / Calculation Shape</h3><p>The first think i had to do, is to draw my building’s and buildings arround shapes… To do so, i’ve created a 2D Matrix, containing zeros where stands buildings, ones elsewhere. But i don’t want a 1m grid for the calculation, then i’ve decided to use a resolution parameter, that do the conversion between real shape and calculation shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*-pXDEoi4EgcWUKRDAa195Q.png" /><figcaption>Calculation map, axis are in pixels : different than “meters” coordinates.</figcaption></figure><h3>Initial conditions</h3><p>For my problem, i don’t know much initial condition for different physical parameters such as pressure etc, in the environment. My problem is also limited in space, then boundaries will have an impact on the result.<br>As initial conditions, i decided to create 2 matrix :<br>- One for windspeed (Vx,Vy)<br>- One for pressure (P)<br>I decided to initiate the wind speed with a V0 value on x axis where there is no building.<br>I decided to initiate the Pressure to a P0 value everywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*7_QGZvIpT9KxpsLIZvzX-g.png" /><figcaption>Initial conditions : Wind = V0 on X axis</figcaption></figure><h3>Equations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*kSIrXHNeuRfC6OX7FUW8EQ.png" /><figcaption>1st : Navier-Stoke 2nd : Fluid Incompressibility</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*SZ7ooa2vVsR6Hfx5nkk-ig.png" /></figure><p>In order to solve my problem, i had to write all equations. Firstly on a white dashboard, then in my google colab notebook.<br>I started from 2 equations. Then we can use a simplification term and project our equations</p><p>We can then use finite element in order to be able to compute with python code. To do so, we do a discretization based on Taylor development on space and time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Thjsal8i3NuqNXNVRQw5tQ.png" /><figcaption>The 2 Equations projected and discretized Vx, and Vy Equation</figcaption></figure><p>The problem is that we only have 2 equations for 3 unknowns parameters (Vx, Vy, P). In order to generate the 3rd equation, we’ll discretize the first equation only on time, take the divergence and use the 2nd equation to simplify and generate a new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*kTWn96NAmmpbMcBeH5wvDg.png" /><figcaption>The way we generate pressure equation</figcaption></figure><p>What we did, is to create a relation between our 3 unknown values and their values at the step before.<br>We then just need to iterate step by step to converge to a solution.</p><h3>The result</h3><p>As a result, we plot the speed field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*jxDllI1utzjF5B7I5Ts5hA.png" /><figcaption>We plot the result with a streamplot</figcaption></figure><p>You can find all code in google colab :</p><p><a href="https://colab.research.google.com/drive/1Gxe7ahZgis0__ubzvG8bODebQ6K3-DIO?usp=sharing">Google Colaboratory</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=879d9a9723fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pytorch, Google Colaboratory and UNet]]></title>
            <link>https://medium.com/@franoisponchon/pytorch-google-colaboratory-and-unet-aeda832a6f89?source=rss-1ef0d35b1011------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeda832a6f89</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[step-by-step]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[François Ponchon]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 19:59:01 GMT</pubDate>
            <atom:updated>2020-03-30T19:59:01.732Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, i’ll try to explain you how i trained my first UNet neural network on a TrayFood Dataset via Google Colab and PyTorch.</p><p><a href="https://www.kaggle.com/thezaza102/tray-food-segmentation">https://www.kaggle.com/thezaza102/tray-food-segmentation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkNY3s5TLwSgdrWLWzdwAA.png" /><figcaption>What we’ll be able to do with this Algorithm</figcaption></figure><h3><strong>The Beggining…</strong></h3><p>When i started to work on DeepLearning, i had an ultrabook without any GPU, it quickly became hard to continue…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_eOPVvaibV_YbtKC2zR7w.jpeg" /><figcaption>Asus Ultrabook —What a powerfull workstation !</figcaption></figure><h3>Google Colab</h3><p>After several months, i wanted to train from scratch a UNet on my own data. It was impossible for me to train it on my local machine !<br>Then i discovered <a href="https://colab.research.google.com/">Google Colaboratory</a> as a training plateform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*efKnPAhLU3ec7JwtXU8k4Q.png" /><figcaption>Google Colab and Google Drive interaction</figcaption></figure><p>The first very interesting thing with Google Colab, is that we can virtualy connect it to the Google Drive storage.</p><p>In this case, i use data from kaggle. I can do another way, but i also have some other datasets with my labelled data, it is possible to sync it from my computer to my drive, in order to compute it in Google Colaboratory.</p><p>To connect to my drive, i just need 2 lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*btd_gRk_NXRz0x3OlDMvww.png" /><figcaption>Connect GoogleDrive to Google Colaboratory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zItzely1KbzY-WRIalO0ig.png" /><figcaption>Prompt where to paste your GoogleDrive token</figcaption></figure><p>We can access to the storage with python code like on your local machine, simply with the python os library.<br>In my case, i’ll store everything inside the folder “Tray_Food_Dataset”.</p><blockquote><strong><em>import </em></strong><em>os<br>PROJECT_PATH=”/content/drive/My Drive/Tray_Food_Dataset/”</em></blockquote><h3>How to use libraries ?</h3><p>In order to do the inference locally, it can be interesting to share code through Google Drive, between Google Colaboratory and your local machine.</p><p>In order to get it, the first things to do is to use GoogleDrive Desktop application to sync a local folder to Google Drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*O5YnUBRgGQoKdoSUPVJFDg.png" /><figcaption>Screenshot on GoogleDrive Desktop Application — WIndows 10</figcaption></figure><p>In order to use libraries on Google Colaboratory, we can use <strong>importlib.machinery</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*K1qsqX65dgs61JtD4UcjgQ.png" /><figcaption>How to import libraries on Google Colaboratory</figcaption></figure><p>This way, we can code on local machine and re-use classes on Google Colaboratory Notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*KVrJkzBeuj1oXtY9QQDxCA.png" /><figcaption>Local Directory containing Source Code</figcaption></figure><h3><strong>The Dataset</strong></h3><p>Now let’s talk about the code itself.</p><p>The first thing we should code is the dataset. The way it works in Pytorch is quite simple. We just inherit from <strong>torch.utils.data Dataset </strong>class.</p><p>In our case, we have 4 folders :<br>- XTrain =&gt; Containing “.jpg” Training 1241 original images<br>- yTrain =&gt; Containing “.png” Training class masks<br>- XTest =&gt; Containing “.jpg” Test 6 original images<br>- yTest =&gt; Containing “.png” Test class masks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOsoHVyEc8dYbRsj2VfxaQ.png" /><figcaption>Example of images — Training Data and Labels</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*lcHavpbxIax2jpexpOwOVA.png" /><figcaption>Dataset Constructor — Index Train and Test Data in two lists</figcaption></figure><p>In Pytorch Dataset, it is necessary to override two methods, <strong><em>__len__(self)</em></strong> and <strong><em>__getitem__(self,idx)</em></strong></p><p>The first method is the ability to return the number of elements in the dataset.<br>The second one is to get the i <em>th </em>element from the Dataset.</p><p>Note that we’ll separate Training and Test dataset. We’ll just use Training method to switch the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*NyxVfMnCfEZ98TFMeKnKHA.png" /><figcaption>Methods overrided in order to complete the Dataset</figcaption></figure><p>In order to check that everything work, we can create a Dataset instance, get an element and display it.<br>The problem is that we have already transformed image to PyTorch instance in the <strong>__getitem__ </strong>function, then we’ll have to build a displaying function in order to display it with matplotlib. We’ll also use this function in order to colorize classes, for that, i stored conversion table in a csv file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*UIAVuE9fzcpSUt4RyNA8EQ.png" /><figcaption>Displaying functions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*Lp30yJGZzl5sQjfuwzehxA.png" /><figcaption>Create a Dataset Instance and Display Images</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3Xc2PMASH7j8h_QGg-_mQ.png" /><figcaption>25th Element from the Dataset</figcaption></figure><p><strong>The Network : UNet</strong></p><p>UNet paper (2015) can be found there : <br><a href="https://arxiv.org/pdf/1505.04597.pdf">https://arxiv.org/pdf/1505.04597.pdf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*sEYWbyWJ17HtiC2LGyHNuQ.png" /><figcaption>Unet Original structure</figcaption></figure><p>In this paper, they propose a network which uses a 512x512px image as input. The name of the network comes from the U shape structure of convolutions / deconvolutions.</p><p>An interesting thing is that the output has a 388x388px shape. For our implementation, it is a problem, because we want to do the segmentation on the whole image.In order to avoid it, we will play with padding for getting an output size identical to the input shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*OTFGlX0nZHM4ucHL4v12uA.png" /><figcaption>The way to use padding in order to manage the output size</figcaption></figure><p>We see on the original network structure, that the shape is reduced from the first to the second layer. Without padding, the shape is reduced little by little because the convolution loses one pixel on each side. In order to avoid it, we’ll use a padding value of 1.<br>It will allow us to get an output image with the same size of the input.</p><p>To build our network, we’ll create 2 standard blocks : One for convolution and one for deconvolution.</p><p>In Pytorch, each block inherits from <strong><em>nn.Module</em></strong>. it must implement <strong><em>__init__</em></strong> (constructor) and <strong><em>forward </em></strong>methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*oG0WhhbFCxbgYCann2kztg.png" /><figcaption>Standards blocks we’ll reuse inside the network declaration</figcaption></figure><p>Theses blocks can be assembled in the future network declaration. We’ll first declare them in the network constructor.</p><p>The same way, we’ll declare our network, and reuse our blocks :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*tsNVrp26LBZaXdld9wZuUw.png" /><figcaption>UNet Implementation — The depth of output is the class count</figcaption></figure><p>Now our network is declared, we’ll build our training loop and loss.</p><p><strong>Training Loop</strong></p><p><em>Loss</em></p><p>Firstly we have to define the Loss function we’ll use. In our case, we’ll have 43 different classes.</p><p>We’ll use CrossEntropyLoss because our problem is to estimate for each pixel what is the distribution between classes.<br>This loss allows us to compare the distribution we’ve obtained through the network to the expected distribution.<br>Let’s imagine we have two classes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*BYy4OUSg8LR1Ir27rDMJbg.png" /><figcaption>The Loss will compare the reference (left) to prediction (right)</figcaption></figure><p>For each pixel, we’ll have the two values, P(class=0) and P(class=1). And the expected class</p><p>The CrossEntropyLoss is already implemented in Pytorch, it works like that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*SutoNoogmwDhnoRLtkW65A.png" /><figcaption>PyTorch documentation</figcaption></figure><p>As an input, it expects one matrix and one vector…<br>The matrix will be the output image from our network (flattened) as N Pixels, and C is the number of class (each pixels have C values).<br>The Target will be the label (flattened) as N Pixels, each pixels contains a number representing the class index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqmcISXOkpUsI0L8BGnw7A.png" /><figcaption>What will compute the CrossEntropyLoss</figcaption></figure><p>We can simulate it easily with an Excel Worksheet :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*qCTd6ct0dl1Gn0HeztRu9Q.png" /><figcaption>Value increase when we have a distribution far from the expected distribution</figcaption></figure><p><em>Optimizer</em></p><p>The optimizer is the way we’ll compute the gradient descent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*kaFEIaYissQEwSUhYtSfQQ.png" /><figcaption>SGD Gradient Descent</figcaption></figure><p>In order to explain it, i advise this very interesting article : <a href="https://ruder.io/optimizing-gradient-descent/index.html">https://ruder.io/optimizing-gradient-descent/index.html</a></p><p><em>Loop</em></p><p>In order to build our training loop, we’ll first create instances of our objects :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*7fJh6M5ORu9raMcfs66TEQ.png" /><figcaption>Instances of model, optimizer and criterion (loss)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*2ij4C40uVgnEtPCuGai86A.png" /><figcaption>Prepare the training Loop</figcaption></figure><p>We’ll then first implement the training loop :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7fmgqTMO4fbrlY85QqSDQ.png" /><figcaption>Training Loop — Phase “Train”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnaomSfIdbfS57GYI5r7-A.png" /><figcaption>Training Loop — Phase “Validation”</figcaption></figure><p>Note that :<br>- We randomise indices in each epoch. In our case, we don’t have much data then it is important to use everything. (I won’t talk about augmentation in this story).<br>- We reshape the prediction before we use the Loss function as explained before.<br>- We can compute indicators we want during the process<br>- Network weights are saved every epochs</p><p><strong>Test</strong></p><p>Once it’s done, we’ll reuse the best network we trained and use it on our small test dataset :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*q9tggj_xsOAAQs6x9f9VaA.png" /><figcaption>Test Environnement Loading</figcaption></figure><p>We used the method <strong>DsT.Training(False)</strong> in order to use test images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*I0abbIfa0EG9WZmhQjI-sA.png" /><figcaption>Test on the 4th image of the Test Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*cPwyGmMuyuWX65WVzzmLoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*Le6KVpzc2Om588eKl8Cw5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*tWalj-JdnRoeppjhO6NdJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2twVaBkZlzI6-jApJsSbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avK9YH0JRmOLdVvOk4kKGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tJ1L4cyV7bxxbGl_YA3BQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULy_yipyRgoYeAh8Qod0zQ.png" /></figure><p>The result on the test dataset is not perfect, but not so bad with few data like that. It would be interesting to try data augmentation with horizontal and vertical flip for example and of course to get a bigger dataset than this one.</p><p>I hope this post helped to understand how to work with google colab, Pytorch and UNet network.</p><p>Thanks for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeda832a6f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>