<?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 Rafael Bischof on Medium]]></title>
        <description><![CDATA[Stories by Rafael Bischof on Medium]]></description>
        <link>https://medium.com/@rabischof?source=rss-913c6c1e6a94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b7vBV3yNgMijwKyMcABf4g.png</url>
            <title>Stories by Rafael Bischof on Medium</title>
            <link>https://medium.com/@rabischof?source=rss-913c6c1e6a94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:59:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rabischof/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[How to combine Pretrained Latent Diffusion Models with Physics-Informed Losses]]></title>
            <link>https://medium.com/data-science-collective/how-to-combine-pretrained-latent-diffusion-models-with-physics-informed-losses-615031c597a9?source=rss-913c6c1e6a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/615031c597a9</guid>
            <dc:creator><![CDATA[Rafael Bischof]]></dc:creator>
            <pubDate>Thu, 21 May 2026 14:06:18 GMT</pubDate>
            <atom:updated>2026-05-24T20:21:42.432Z</atom:updated>
            <content:encoded><![CDATA[<p>If you work on machine learning for physics, you are probably familiar with physics-informed losses. Physics-Informed Neural Networks (PINNs) are trained by minimizing PDE residuals and boundary errors on a set of collocation points and get their supervision directly from the underlying physics rather than simulation data or measurements. These same losses have also been shown to improve neural operators like <a href="https://arxiv.org/abs/1910.03193">DeepONets</a> and <a href="https://arxiv.org/abs/2010.08895">Fourier Neural Operators (FNOs)</a> and are now generally regarded as an effective way to improve the fidelity of neural surrogates and emulators.</p><p>At the same time, generative models have made huge progress, among other things, by splitting the complex generation process into two stages: a VAE handles compression and reconstruction, while a denoising model, such as a U-Net, operates within that compressed latent space. This factorization allows training a larger overall model than an end-to-end pipeline would, due to, for example, VRAM constraints.</p><p>The other big realization of the last few years is that taking massive models, pretraining them on huge, even seemingly unrelated datasets, and fine-tuning them on a downstream task often works much better than building a specialized model from scratch. Scientific ML is no exception to this trend.</p><p>So, to create the ideal model for a new simulation task, the best thing seems to be to combine a large, pretrained latent diffusion model with physics-informed losses, right?</p><p>As it turns out, combining the two is not as straightforward as it seems.</p><h3>Physics and the latent space conflict</h3><p>The main hurdle is that physics losses are explicitly defined in the physical domain. They are completely undefined on an abstract latent vector. Because the latent diffusion model trains and generates entirely in latent space, you cannot just drop a PDE loss directly into the denoising objective.</p><p>The intuitive workaround is to apply the losses to the VAE, since its decoder reconstructs the fields where the physics makes sense. One might naturally try to fine-tune the entire VAE end-to-end using these physics losses before plugging it back into the generative pipeline.</p><p>But end-to-end fine-tuning introduces another major issue: the pretrained diffusion model was trained on the original encoder’s latent space. If you modify the encoder, the latent distribution shifts, and the pretrained prior you wanted to inherit no longer aligns with the data.</p><h3>The solution</h3><p>We ran into this exact tension while developing <a href="https://rbischof.github.io/windinet_web/">WinDiNet</a> [1], a model designed to predict wind flow through urban geometries for pedestrian wind comfort analysis.</p><p>Our backbone was <a href="https://github.com/Lightricks/ltx-video">LTX-Video</a>, a 2-billion-parameter video latent diffusion model. The spatial-temporal priors it absorbed from natural video are incredibly useful for fluid dynamics, so we had no intention of giving them up. Therefore, we structured our data using a pseudo-RGB mapping: the R and G channels encoded the U and V velocities, and the B channel carried the static building geometry.</p><p>The way out of this conflict came down to a simple observation about the asymmetry between the VAE encoder and decoder. The latent distribution the LDM expects is determined solely by the encoder. The decoder just maps those latents back to the physical field. It does not define the latent space structure itself. If you freeze the encoder and fine-tune only the decoder, the distribution of latents remains identical, and the pretraining prior is preserved exactly.</p><p>This setup gives you a clean, two-stage training pipeline:</p><ol><li><strong>Decoder Fine-Tuning:</strong> The encoder is frozen. The decoder is fine-tuned on wind-flow simulations with a standard reconstruction loss, an incompressibility (divergence-free) penalty, and a no-penetration loss at the walls.</li><li><strong>Diffusion Fine-Tuning:</strong> Separately, the latent diffusion model is fine-tuned in latent space on the encoded simulation data using the standard denoising objective.</li></ol><p>Because the encoder never changes, fine-tuning the decoder has no impact on LDM training.</p><h3>Ablation Results</h3><p>The ablation study isolated the impact of each training stage cleanly, measured in Variance-Normalized Root Mean Squared Error (VRMSE):</p><p>Training the pipeline entirely from scratch on simulation data, without any pretraining prior, establishes a baseline error of 0.92 Variance-Normalized Root Mean Squared Error (VRMSE). Introducing the pretrained backbone and fine-tuning only the diffusion model on simulations brings that error down significantly to 0.61. Adapting the VAE decoder on reconstructions before training the LDM reduces the error further to 0.53, as the decoder learns to map latents into a more accurate physical field. Finally, adding the physics losses to that decoder fine-tuning yields our full WinDiNet pipeline with a VRMSE of 0.52.</p><p>While the final step from 0.53 to 0.52 looks modest in absolute numerical error, it represents the transition to actual physical consistency. It eliminates divergence artifacts and ensures the flow cleanly respects solid boundaries. As a surrogate model, this architecture outperformed neural-operator baselines on both forward prediction and gradient-based inverse design, where we successfully leveraged the differentiability of the entire pipeline to optimize building layouts for pedestrian wind comfort.</p><p><strong>Therefore, fine-tuning the decoders of latent diffusion models while keeping their encoders frozen provides a remarkably simple and effective way to enforce physical fidelity without sacrificing the power of large-scale generative priors.</strong></p><p>[1] Perini, J., Bischof, R., Arar, M., Duran, A., Kraus, M. A., Mishra, S., &amp; Bickel, B. (2026). Pretrained Video Models as Differentiable Physics Simulators for Urban Wind Flows. <em>arXiv preprint arXiv:2603.21210</em>. <a href="https://www.google.com/search?q=https://doi.org/10.48550/arXiv.2603.21210">https://doi.org/10.48550/arXiv.2603.21210</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=615031c597a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/how-to-combine-pretrained-latent-diffusion-models-with-physics-informed-losses-615031c597a9">How to combine Pretrained Latent Diffusion Models with Physics-Informed Losses</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards Multi-Physics Neural Operators]]></title>
            <link>https://medium.com/data-science-collective/creating-neural-operators-for-solving-pdes-via-manufactured-solutions-8c2449aff019?source=rss-913c6c1e6a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c2449aff019</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[differential-equations]]></category>
            <category><![CDATA[physics-informed-learning]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Rafael Bischof]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 09:45:24 GMT</pubDate>
            <atom:updated>2025-10-25T19:51:50.103Z</atom:updated>
            <content:encoded><![CDATA[<p>Simulating the physical world is one of the grand challenges of modern science. From forecasting weather and designing next-generation aircraft to modeling how medicines diffuse through the body, our ability to predict reality is governed by a set of mathematical rules called Partial Differential Equations (PDEs). For decades, scientists have relied on powerful but highly specialized solvers to crunch through these equations. While accurate, these solvers are often slow, computationally expensive, and each built to specialize only a narrow range of problems.</p><p>In recent years, a new method using AI has emerged. Specifically, a class of models called “neural operators” promises a faster, more flexible alternative. These models learn the underlying physics of a system from large datasets and can generate near-instantaneous solutions for new PDE instances.</p><p>This article is about <a href="https://arxiv.org/abs/2509.05117"><strong>HyPINO</strong></a>, a new neural operator that introduces architectural and training innovations that allow it to solve various PDEs with different physics, geometries, and boundary conditions without needing expensive simulation datasets for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-W2hPTKQQiPQ9dGFE3X0A.png" /><figcaption>Overview of the full HyPINO pipeline, from generating the data to encoding the PDE with the hypernetwork and predicting weights of the target network. The resulting network can be used for downstream adaptation like iterative refinement or fine-tuning. [Bischof et al. 2025]</figcaption></figure><h3>Train on “manufactured” problems</h3><p>The biggest bottleneck in training a scientific AI model is data. To learn physics, a model needs to see thousands or even millions of examples, which usually means running traditional high-fidelity simulations over and over.</p><p>HyPINO gets around this with the <strong>Method of Manufactured Solutions (MMS)</strong>. Instead of starting with a complex physics problem and spending hours computing the solution, MMS works backward. It begins by inventing a simple, elegant solution in the form of an analytical function. Then, it uses basic calculus to figure out the exact PDE problem that would produce that exact solution. It’s like knowing the answer to a complex math problem is y = sin(x) and then creating the specific differential equation and boundary conditions that lead to that exact result.</p><p>The impact of this is that it allows for generating a virtually infinite, perfectly labeled dataset of (PDE, solution) pairs for training the AI <em>without running a single costly simulation</em>.</p><h3>A true zero-shot, multi-physics solver</h3><p>Most neural operators are specialists. They are trained to solve a very narrow family of problems, such as a single type of equation where only a coefficient changes. HyPINO, by contrast, was built with the vision of creating true multi-physics solvers that can be applied to diverse physical problems.</p><p>Indeed, HyPINO demonstrates a strong zero-shot generalization, which is the ability to accurately solve a wide variety of new, unseen PDE problems without any task-specific fine-tuning. HyPINO can simultaneously handle variations in:</p><ul><li>Different classes of linear, 2D, and second-order equations (elliptic, hyperbolic, and parabolic)</li><li>Varying source terms</li><li>Complex geometries, including those with internal boundaries or holes</li><li>Mixed Dirichlet and Neumann boundary conditions</li></ul><h3>Improve its own answers by treating residuals as new PDEs</h3><p>For most AI models, the prediction process is simple: you give it a problem, it gives you an answer, and the process ends. With HyPINO, however, there is a possibility to let it self-correct its own predictions through a process called <strong>residual-driven iterative refinement</strong>.</p><p>Here’s how it works in a few simple steps:</p><ol><li>First, HyPINO generates an initial solution to a given PDE.</li><li>Next, it checks its own work. It plugs its answer back into the original physics equations to see how “wrong” it is. This error is known as the “residual.”</li><li>The model then treats this residual error as a new, simpler PDE problem to solve. It feeds this new problem back into itself.</li><li>The model generates a new, corrective prediction (a “delta network”) whose sole job is to represent the error. This correction is then added to the first solution to produce a more accurate final answer.</li></ol><p>This refinement process can be repeated multiple times, with each loop making the answer progressively better. The result is a method that can achieve over 100x gain in average L2 loss on some benchmarks without requiring any retraining or backward passes through the hypernetwork.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ce7ex9CeTfXttbgxSAPWGw.png" /><figcaption>Comparison of predictions and errors of HyPINO after zero, three, and 10 refinement rounds<br>across all benchmark PDEs. [Bischof et al. 2025]</figcaption></figure><p>Note that this specific procedure works because of the principle of superposition, meaning it applies directly to the linear problems HyPINO was trained on, but not to nonlinear ones.</p><h3>Use predictions as initializations for downstream fine-tuning</h3><p>When HyPINO generates a solution, its output isn’t just a static grid of numbers. It’s the actual parameters for a complete, smaller neural network (i.e. a Physics-Informed Neural Network (PINN)) that represents the continuous solution to the problem. This means the output is not a static image of a solution, but a compact, differentiable function that can be evaluated at any point in the domain and provides exact, analytical derivatives.</p><p>In particular, this self-contained PINN can be used as a smart initialization for fine-tuning the network on a specific task. The head start that HyPINO provides is significant: randomly initialized PINN requires an average of <strong>1,068 training steps</strong> with the Adam optimizer just to match the initial accuracy of a PINN generated by HyPINO.</p><h3>A path towards real-time world models</h3><p>HyPINO is currently limited to linear problems, where the principle of superposition enables its effective residual-based refinement. However, it can be naturally extended to nonlinear, higher-order, and 3D systems by adapting the MMS sampling process and increasing the modeling capacity of its hypernetwork.</p><p>If these extensions are successful and HyPINO can be applied to complex problems such as fluid dynamics, heat transfer, or structural mechanics, then it could mark a turning point toward <strong>real-time world models</strong> for physics. Scientific simulations would become interactive and end-to-end differentiable. Beyond merely predicting airflow over a wing in near real time, an engineer could define an objective, such as minimizing drag, and the model could automatically work backward, using gradient-based optimization, to propose the ideal wing shape. In doing so, the AI evolves from a passive predictor into an active design partner.</p><h3>Try HyPINO in the web app</h3><p>Want to try HyPINO yourself? The <a href="https://rbischof.github.io/hypino_web/"><strong>HyPINO Web Demo</strong></a> lets you experiment with the model and generate PDE solutions directly in your browser, with no installation or setup required. You can explore preset equations or upload your own coefficients and boundary conditions, then watch as HyPINO predicts and iteratively refines the solution in real time. The interface visualizes each refinement step as the solution evolves. You can also export the results and generated PINN weights to use in your own code for downstream analysis or fine-tuning.</p><h4>Paper</h4><p>Bischof, Rafael, Michal Piovarči, Michael A. Kraus, Siddhartha Mishra, and Bernd Bickel. <a href="https://arxiv.org/abs/2509.05117"><em>HyPINO: Multi-Physics Neural Operators via HyperPINNs and the Method of Manufactured Solutions</em></a><em>.</em> arXiv preprint arXiv:2509.05117, 2025.</p><h4>Codebase</h4><p><a href="https://github.com/rbischof/hypino">https://github.com/rbischof/hypino</a></p><h4>Web-based demo</h4><p><a href="https://rbischof.github.io/hypino_web/">https://rbischof.github.io/hypino_web</a></p><h4>HyPINO model weights</h4><p><a href="https://huggingface.co/rabischof/hypino">https://huggingface.co/rabischof/hypino</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c2449aff019" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/creating-neural-operators-for-solving-pdes-via-manufactured-solutions-8c2449aff019">Towards Multi-Physics Neural Operators</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Ideas for Physics-Informed Neural Networks that failed]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/4-ideas-for-physics-informed-neural-networks-that-failed-ce054270e62a?source=rss-913c6c1e6a94------2"><img src="https://cdn-images-1.medium.com/max/2600/1*VLy4um3-GCs9fx6xPJ1AoQ.jpeg" width="7500"></a></p><p class="medium-feed-snippet">Here is a list of extensions for PINNs that either did not improve their performance, or broke them completely&#x200A;&#x2014;&#x200A;so you do not have to try&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/data-science/4-ideas-for-physics-informed-neural-networks-that-failed-ce054270e62a?source=rss-913c6c1e6a94------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/4-ideas-for-physics-informed-neural-networks-that-failed-ce054270e62a?source=rss-913c6c1e6a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce054270e62a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Rafael Bischof]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 11:02:34 GMT</pubDate>
            <atom:updated>2023-02-24T22:17:52.992Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[10 Useful Hints and Tricks for Improving Physics-Informed Neural Networks (PINNs)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/10-useful-hints-and-tricks-for-improving-pinns-1a5dd7b86001?source=rss-913c6c1e6a94------2"><img src="https://cdn-images-1.medium.com/max/2600/0*CZfS6t-w6irMZ3P7" width="4582"></a></p><p class="medium-feed-snippet">A handful of tricks concerning the sampling, architecture, activation function, loss balancing, optimisers, data normalisation, and more.</p><p class="medium-feed-link"><a href="https://medium.com/data-science/10-useful-hints-and-tricks-for-improving-pinns-1a5dd7b86001?source=rss-913c6c1e6a94------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/10-useful-hints-and-tricks-for-improving-pinns-1a5dd7b86001?source=rss-913c6c1e6a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a5dd7b86001</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Rafael Bischof]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 17:22:30 GMT</pubDate>
            <atom:updated>2023-05-19T13:21:39.230Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[AI-Augmented Designing Process of a Pedestrian Bridge in Switzerland]]></title>
            <link>https://rabischof.medium.com/ai-augmented-designing-of-a-pedestrian-bridge-in-switzerland-1fc22a975ea7?source=rss-913c6c1e6a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fc22a975ea7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[civil-engineering]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rafael Bischof]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 08:10:07 GMT</pubDate>
            <atom:updated>2023-02-09T10:05:51.439Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leveraging AI to enhance designing processes in the AEC Industry: A Case Study of a Pedestrian Bridge in Switzerland</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVIvilCrAlaf5CSRUsPsFQ.jpeg" /><figcaption>Rendering of the point cloud and proposed design of a pedestrian bridge in St. Gallen, Switzerland. <a href="https://mkrausai.github.io/research/01_SciML/01_BH_PedestrianBridge_XAI/">Image by M. Kraus.</a></figcaption></figure><p>The world is facing an unprecedented urbanisation and with it, a growing concern for the environment. The building sector plays a crucial role in this issue, as buildings consume a significant amount of resources. Yet, the current practice of architectural, engineering and construction (AEC) often leads to a disconnect between the conceptual design phase and later phases of the building process.</p><p>The <strong>conceptual design phase</strong> is a critical stage in the building process where important decisions are made that can impact the final structure. During this phase, the problem is defined and distilled into a set of design parameters, such as the type of bridge, material, and number of supports, that control the shape, building materials, and elements of the final structure.</p><p>Once the design parameters are selected, engineers calculate the performance attributes, such as costs, material consumption, and structural utilization, that determine the “goodness” of the design. However, the calculation of these attributes can be time-consuming, especially for complex structures. Moreover, the conventional software used in the design process often lacks feedback on how to modify the design parameters to optimise performance, leaving it up to the experience and intuition of the design team. This leads to a number of problems:</p><ol><li>The design process can be lengthy and iterative, requiring multiple rounds of tweaking and refinement before arriving at a final design with satisfactory performance.</li><li>It can only be sped up by skilled engineers with prior knowledge, which can be hard to find, especially for complex structures and cutting-edge technologies.</li><li>Relying on the experience and intuition of the design team can lead to biased designs and a limited exploration of the design space.</li></ol><p>To address these problems, <a href="https://arxiv.org/abs/2211.16406">researchers from ETH Zürich developed a method</a> that uses Artificial Intelligence (AI) to invert the traditional design process. Instead of starting with design parameters and then assessing the performance attributes, this tool maps from performance attributes to design parameters and allows engineers to select from a range of designs that already meet predefined performance attributes. It saves a considerable amount of time that would otherwise be spent on iterations, time which can now be invested in exploring more designs in a more holistic manner that also takes environmental aspects into account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*SKbgh7S6WValQCXeEM-IhA.png" /><figcaption>Comparison of the timelines in the traditional, iterative approach, and the AI-augmented approach. Image by author.</figcaption></figure><p>The AI-augmented approach requires the computation of considerably more examples and the additional training of a ML-model. However, these computations can be done during down-times, such as overnight or over the weekend. Once the generative ML-model has been set up, it can generate designs in real-time. This streamlines the designing process and allows for the exploration of a much larger variety of designs.</p><p>It is important to note that the predictions made by the AI tool are only approximations. Before making a final decision, engineers still need to run the final design through established CAD software to verify the results.</p><h3>Case study: Pedestrian Bridge in Switzerland</h3><p>In order to assess the effectiveness of this tool, the developers tested it on a <a href="https://espazium.s3.eu-central-1.amazonaws.com/files/2022-01/st-gallen-graben-jurybericht.pdf">real-life case study, a pedestrian bridge</a> built by <a href="https://www.baslerhofmann.ch/home.html">Basler &amp; Hofmann AG</a> in St. Gallen, Switzerland.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*E7rQSZICX_kIZ31MfHF6hw.png" /><figcaption>Project site. The red crosses mark the endpoints of the planned bridge. Image from Woodtli et al. [2].</figcaption></figure><p>The pedestrian bridge will provide a pedestrian crossing from the exit of a parking garage, over a busy street, then through a park, to terminate next to a church.</p><h4>Parametrisation and Dataset generation</h4><p>The chosen parametrisation of the bridge consists of 6 design parameters (denoted <em>features</em> in the following figure) and 37 performance attributes (denoted <em>performances</em>), which include boundary conditions such as whether a bridge clips one of the trees in the park or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRUUx7rS4hdN2tm2yMASdg.png" /><figcaption>Design parameters (features) and performance attributes (performances) in the parametrisation of the pedestiran bridge in St. Gallen. Mapping from features to performances is known as the forward problem, while mapping from performances to features is usually called the inverse problem. Image from Balmer, Kuhn et al. [1].</figcaption></figure><p>With the parametrisation in place, a large set of designs were sampled (18&#39;000 examples), meaning that the design parameters were slightly varied for each bridge, and the corresponding performance attributes computed. The resulting data of pairs of design parameters and performance attributes constituted the dataset for training the ML-model.</p><h4>Machine Learning Model</h4><p>A Conditional Variational AutoEncoder (CVAE) was selected as the machine learning model. It has two main components: an Encoder and a Decoder. The Encoder takes in the design parameters and generates predictions for the performance attributes, as well as a latent vector <em>z</em>, which encodes additional information about the design that is not captured by the performance attributes. The Decoder takes the performance attributes and latent vector as inputs and reconstructs the original design. Note that the information contained in the latent vector <em>z</em> is not designed to be directly understandable by humans and typically lacks a clear interpretation or relationship to the original input data. Its purpose is to capture relevant patterns and relationships in the input data in a way that can be easily manipulated by the model for specific tasks, not to provide a human-readable representation of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*sqcMD3ZsdxHZ5A_MjQK5SA.png" /><figcaption>Illustration of a conditional Variational AutoEncoder, where x denotes the design parameters, y are the performance attributes and z a latent vector containing additional, non-trivial information for humans. X hat and y hat denote the prediction of the ML-model for the design parameters and performance attributes, respectively. Image from Balmer, Kuhn et al. [1].</figcaption></figure><p>One advantage of this CVAE model is its ability to solve both forward and inverse problems simultaneously. The Encoder serves as a surrogate model for the forward problem by predicting performance attributes, while the Decoder solves the inverse problem by mapping from performance attributes to design parameters. After training the model, new designs can be generated by inputting desired performance attributes into the Decoder along with random values for the latent vector, resulting in a variety of different designs that respect, with a certain error-margin, the requested performance attributes.</p><h4>Interpretability of the ML-model</h4><p>Neural networks and CVAEs are amongst the most powerful generative models available to this day. However, the are often referred to as “black box” models.</p><p>A black box model is a type of model where the internal workings are not easily understandable or interpretable. In other words, it is difficult or impossible to understand how the model arrived at its predictions or decisions.</p><p>This lack of interpretability is a disadvantage in certain applications where transparency and interpretability are crucial for safety reasons, such as healthcare and civil engineering. This is why methods for increasing the interpretability of neural networks are a hot topic in the field of AI and several techniques have been proposed, such as the sensitivity analysis.</p><p>In the context of CVAEs, sensitivity analysis is performed by taking derivatives of the output with respect to the input. The derivatives provide information about the rate of change of the output with respect to changes in the input, or, in other words, the derivatives tell us which direction the input should be changed in order to increase or decrease the output. This provides insights into the relationship between features and can help to identify the most important factors that influence the model’s predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8q_XXvT7wCf5sozHZihcg.png" /><figcaption>Sensitivity analysis in the final CVAE model of the performance attribute Costs [CHF] w.r.t. the design variables. Each point in the swarm plot represents a design and its position on the “Sensitivity” axis shows how the Costs react to a change in the input. It can be loosely compared to a correlation value. Figure from Balmer, Kuhn et al. [1]</figcaption></figure><p>This figure shows that the model found a positive correlation between the height and thickness of a girder and the total cost of the bridge. Using the sensitivity plots, engineers can estimate the robustness of the model by determining if the found relations make sense or not. In this particular case, the relation makes sense, as the volume of the girder (determined by its height and thickness) has a large influence on the amount of concrete necessary for building a bridge, which in turn influences the costs.</p><h4>User Interface</h4><p>Finally, the entire toolbox was equipped with an intuitive user interface that allows engineers to quickly generate and evaluate new designs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9up_VK7Vak5lmune7vY6w.png" /><figcaption>Snapshot of the proposed user interface integrated in the commonly used Grasshopper software. Users can modify some performance attributes (orange box, left), interpret the model’s decision making through the sensitivity analysis (pink box, center) and visually inspect a 3D rendering of the selected design (grey box, right). Image from Balmer, Kuhn et al. [1]</figcaption></figure><h3>Conclusion</h3><p>In conclusion, this toolbox has the potential to revolutionise the design process in architecture and civil engineering. Its ability to efficiently estimate design performance and providing instant feedback and proposals to designers make the design process faster and more efficient. Furthermore, the efforts at improving the interpretability through methods like the sensitivity analysis enhance the overall design optimisation process and increase trust in the tool. The user feedback supports the conclusion that this tool has a wide range of potential applications in the AEC industry and research, serving as a valuable aid in conceptual design studies.</p><p>Thank you a lot for reading until the end of this article! You can find more information about the <a href="https://designplusplus.ethz.ch/research/domain-aware-ai-augmented-design-of-bridge-structures--daaadbrid.html">toolbox on the project page of ETH Zürich</a> and about the lead researcher Dr. Michael Kraus on <a href="http://mkrausai.com/">mkrausai.com</a>, or about myself on <a href="http://rabischof.ch/">rabischof.ch</a>.</p><blockquote>[1] Balmer, Vera M., Kuhn, Sophia V., et al. “Design Space Exploration and Explanation via Conditional Variational Autoencoders in Meta-model-based Conceptual Design of Pedestrian Bridges.” <a href="https://arxiv.org/pdf/2211.16406.pdf">arXiv preprint arXiv:2211.16406 (2022)</a>.</blockquote><blockquote>[2] H. Woodtli and C. Svec, “Projektwettbewerb Brücke über den Graben<br>(Passerelle St. Gallen, Unterer Graben 25), Projektwettbewerb für Senn<br>Resources AG,” Mar 2021.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fc22a975ea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixture of Experts for PINNs (MoE-PINNs)]]></title>
            <link>https://medium.com/data-science/mixture-of-experts-for-pinns-moe-pinns-6520adf32438?source=rss-913c6c1e6a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/6520adf32438</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Rafael Bischof]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 17:45:31 GMT</pubDate>
            <atom:updated>2023-02-22T01:39:25.426Z</atom:updated>
            <content:encoded><![CDATA[<h4>Utilising Ensembles to enhance Physics-Informed Neural Networks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oIurVU8hL9GlVNK_" /><figcaption>Photo by <a href="https://unsplash.com/@sovietartefacts?utm_source=medium&amp;utm_medium=referral">Soviet Artefacts</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://www.sciencedirect.com/science/article/pii/S0021999118307125">Physics-Informed Neural Networks (PINNs)</a> [1] have emerged as a popular and promising approach for solving partial differential equations (PDEs). In our latest research, my colleague Michael Kraus and I introduce a new framework called <a href="https://mediatum.ub.tum.de/doc/1688403/uic8b0xn1c845e7rac1or092o.Bischof%20et%20Al.%202022.pdf">Mixture of Experts for Physics-Informed Neural Networks (MoE-PINNs)</a> [2], which shows great potential on PDEs with complex and varied patterns.</p><p>In this post, we will discuss the benefits of MoE-PINNs and how they can be easily implemented to solve a wide range of PDE problems. It is structured the following way:</p><ul><li>Introduction to MoE-PINNs</li><li>Solving Burgers’ PDE using MoE-PINNs</li><li>Reducing Hyperparameter Search with Sparsity Regularisation</li><li>Example of Sparsity Regularisation by solving the Poisson PDE on an L-shaped Domain</li><li>Automated Architecture Search with Differentiable MoE-PINNs</li></ul><p>To help you gain a better understanding of the concepts discussed in this article, we have provided accompanying notebooks that can be run directly on Colab:</p><ul><li><a href="https://drive.google.com/file/d/1JyejLXPS9LQdsNzZE5z-FTd8idRgrP1n/view?usp=sharing">Notebook for MoE-PINNs on Burgers’ equation</a></li><li><a href="https://drive.google.com/file/d/1IRyZvl9OFU8a0PETjdEEppM1BBoda4e8/view?usp=sharing">Notebook for MoE-PINNs on the L-shaped Poisson equation</a></li></ul><p>PINNs use physical laws and automatic differentiation to solve Partial Differential Equations (PDEs) with just a few lines of code. However, they are also highly susceptible to their hyperparameters, such as the activation function or initialisation of the weights. This makes training PINNs particularly difficult and a laborious, iterative process. The depth of the network and the choice of activation function can greatly impact the solution accuracy. For example, deep networks work well for complex PDEs with varying patterns and discontinuities, such as Navier-Stokes equations. Meanwhile, shallow networks may suffice for simple PDEs with simpler patterns, like the Poisson equation on a square domain. The sine activation function, with its property of preserving shape under differentiation, may be ideal for high-order differentiation problems. On the other hand, activation functions like swish or softplus may perform better for problems with sharp discontinuities.</p><p>But what if your problem requires a combination of both? How do we handle a PDE that is smooth and repeating in one part, and highly complex with sharp discontinuities in another? This is where the <strong>Mixture of Experts (MoE)</strong> framework for PINNs comes in. By leveraging multiple networks and a gate to divide the domain, each expert can specialise in solving a distinct part of the problem, allowing for improved accuracy and reduced bias-variance trade-off.</p><p>Dividing the problem into smaller sub-problems has many advantages:</p><ul><li>By using several learners on distinct sub-domains, the complexity of the problem is reduced.</li><li>The gate in MoE-PINNs is a continuous function, resulting in smooth transitions between the domains. Therefore, more complex regions of the domain can be equally divided amongst several learners, whereas simpler regions can be attributed to a single expert.</li><li>The gate can be any type of neural network, from a linear layer to a deep neural network, which allows it to adapt to different types of domains and divide them in an arbitrary way.</li><li>MoE can be easily parallelised, since only the weights lambda need to be shared amongst learners on different devices. In theory, each learner could be placed on a distinct GPU.</li><li>By initialising a large number of PINNs with different architectures, the need for labor-intensive hyperparameter tuning is reduced.</li></ul><h3>MoE-PINN Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*MYdAwQ1MwIofIJ7_juqviw.png" /><figcaption>Mixture of Experts of PINNs. An arbitrary number m of PINNs, possibly with varying architectures and properties, is initialised together with a gating network. All models receive the same input and the gate produces weights that are used for aggregating the results. Figure by author [2].</figcaption></figure><p>Unlike traditional PINNs, which use a single neural network to make predictions, MoE-PINNs employ an ensemble of multiple PINNs that are combined using a gating network.</p><p>Just like all PINNs in the ensemble, the gating network is a fully-connected feed-forward network that takes in the spatial coordinates <strong>x</strong> and <strong>y </strong>(may differ from PDE to PDE). However, unlike the PINNs, its output is an <em>m</em>-dimensional vector of importances, where <em>m</em> is the number of PINNs in the ensemble. The importances are passed through a softmax function to convert them into a probability distribution, ensuring that the sum of all importances equals 1.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F65aFguynvr5MdvqDiHARCf&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F65aFguynvr5MdvqDiHARCf&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="162" frameborder="0" scrolling="no"><a href="https://medium.com/media/128a867bf62cfe200793f59d5179bb31/href">https://medium.com/media/128a867bf62cfe200793f59d5179bb31/href</a></iframe><p>The final prediction of the MoE-PINN is obtained by aggregating the predictions of each PINN in the ensemble, weighted by their respective importances.</p><p>MoE-PINNs can be very concisely built in TensorFlow with just a few lines of code:</p><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Input, Dense, Concatenate<br><br>def build_moe_pinn(pinns:List[tf.keras.Model], n_layers:int, n_nodes:int) -&gt; tf.keras.Model:<br>    x = Input((1,), name=&#39;x&#39;)<br>    y = Input((1,), name=&#39;y&#39;)<br><br>    # create predictions with each PINN in the ensemble<br>    u = Concatenate()([pinn([x, y]) for pinn in pinns])<br>    <br>    # initialise the gating network<br>    gate = tf.keras.models.Sequential(<br>        [Dense(n_nodes, activation=&#39;tanh&#39;) for _ in range(n_layers)] + \<br>        [Dense(len(pinns), activation=&#39;softmax&#39;)],<br>        name=&#39;gate&#39;,<br>    )<br>    <br>    # receive importances from the gating network, multiply with PINN<br>    # predictions and sum up the results<br>    u = tf.reduce_sum(gate([x, y]) * u, axis=1, keepdims=True)<br><br>    return tf.keras.Model([x, y], u, name=&#39;moe_pinn&#39;)</pre><h3>Burgers’ Equation</h3><p>To illustrate the effectiveness of MoE-PINNs, let us have a look at an example. The Burgers’ equation is a PDE used to model phenomenons like shock waves, gas dynamics, or traffic flow. It takes the following form:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoGvAPqyFidR9GFDspo1krQ&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FoGvAPqyFidR9GFDspo1krQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="408" height="203" frameborder="0" scrolling="no"><a href="https://medium.com/media/922ed2e3a3b270a4a8bff7fe170e2215/href">https://medium.com/media/922ed2e3a3b270a4a8bff7fe170e2215/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yibPfUdBUO5RB01XYt-pEA.png" /><figcaption>Visualisation of Burgers’ equation with the above initial and boundary conditions. Image by author.</figcaption></figure><p>Burgers’ PDE presents an intriguing challenge: it transitions from a smooth sine function to a sharp, step-like discontinuity over time. This unique property makes it a perfect benchmark for evaluating the performance of MoE-PINNs.</p><h4>Training MoE-PINNs on Burgers’ equation</h4><p>Let us initialise a MoE-PINN with 5 PINNs as well as a gating network and train it on Burgers’ equation. The experts have the following architectures:</p><ul><li>Expert 1: 2 layers with 64 nodes each and tanh activation</li><li>Expert 2: 2 layers with 64 nodes each and sine activation</li><li>Expert 3: 2 layers with 128 nodes each and tanh activation</li><li>Expert 4: 3 layers with 128 nodes each and tanh activation</li><li>Expert 5: 2 layers with 256 nodes each and swish activation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkgxrqXtwD0maag0_TD-XQ.png" /><figcaption>Prediction and squared error against the ground truth (Spectral Elements Method) on Burgers’ equation using a MoE-PINN with 5 experts. Image by author.</figcaption></figure><p>More interestingly we can now inspect how the experts were distributed over the domain and what their individual predictions look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-03xT2A108mLN9U8AYXCIg.png" /><figcaption>Weights lambda produced by the gating network (top row) for each of the expert (columns) as well as the predictions from each expert (bottom row) for Burgers’ equation. Image by author.</figcaption></figure><p>Observe how the gating network in MoE-PINNs was able to effectively allocate tasks to each expert based on their respective capacity for modelling different parts of the domain. The experts with fewer layers and nodes were assigned to the smoother regions, which are relatively easier to model, i.e. close to the initial conditions. Meanwhile, the more complex experts, i.e. those with deeper and wider architectures, were utilised in the regions with discontinuities, where a more complex model was necessary for accurate representation. This is particularly evident in the case of expert 3, which was solely dedicated to capturing the discontinuity.</p><h3>Sparsity Regularisation for reduced hyperparameter search</h3><p>MoE-PINNs reduce the need for tuning multiple hyperparameters by allowing you to initialise a diverse group of experts. However, one important hyperparameter remains: the number of experts, m. To get the best results, m should be as high as possible while still fitting within memory. But a large number of experts also comes with increased computational costs. To balance these trade-offs, it is important to determine the minimum number of experts needed to divide the physical domain optimally. One way to achieve this is by adding a regularisation term that encourages sparse weights, lambda, produced by the gating network.</p><p>The regularisation loss can be expressed as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FkvGmbm2RVaEfn1d6Ps1qZf&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FkvGmbm2RVaEfn1d6Ps1qZf&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="231" height="183" frameborder="0" scrolling="no"><a href="https://medium.com/media/691fb81e07d581459e828b46293feb75/href">https://medium.com/media/691fb81e07d581459e828b46293feb75/href</a></iframe><p>where B is a batch of collocation points (x, t), and p is a hyperparameter that controls the strength of the regularisation. Values of p below 1 enforce sparsity, while values above 1 result in a more uniform distribution. To encourage sparsity, a good starting point for p is 0.5.</p><p>Finally, to make the training procedure even more efficient, we can use a heuristic to drop experts that the gating network deems unimportant. For example, an expert can be dropped if its average weight in a batch falls below a certain threshold.</p><p>Let us have a look at another example to illustrate this procedure.</p><h3>Poisson PDE on L-shaped Domain</h3><p>The Poisson equation is a common tool for modelling physical processes in engineering and natural sciences. For example, it can be used to solve the elastostatic problem of a rod under a torsion load. For testing the sparsity regularisation, let us examine how well MoE-PINNs perform when solving the Poisson equation on a 2-dimensional L-shaped domain with homogeneous Dirichlet boundary conditions:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8TKNHc2TUC9FVsJEsuvxBA&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F8TKNHc2TUC9FVsJEsuvxBA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="346" height="184" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dd6f3e670775da54a26250e4d0a4d09/href">https://medium.com/media/2dd6f3e670775da54a26250e4d0a4d09/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*os8-4l1xcHMCviakmFiIzg.png" /><figcaption>Visualisation of the Poisson equation on an L-shaped domain defined above solved using Finite Element Method. Image by author [2].</figcaption></figure><p>If an engineer had to subdivide this domain and employ various models, an intuitive choice would be to use a different expert in each of the three quadrants in the L-shaped domain: one in the top left, one in the bottom left, and one in the bottom right corner. It will be interesting to see how the MoE-PINN decides to divide the domain and assign experts.</p><h4>Training sparse MoE-PINNs on the Poisson PDE</h4><p>When initialising an ensemble with four identical experts, the results of the MoE-PINN look the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*H3XtsTNtUOBsWYNfi3MMbQ.png" /><figcaption>Prediction and squared error against the ground truth (FEM solution) on the Poisson equation using a MoE-PINN with 4 experts. Image by author [2].</figcaption></figure><p>But much more importantly, we can now inspect the importances that were attributed to the individual experts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KZ1BbzdzOQgO0tNur8icw.png" /><figcaption>Weights lambda produced by the gating network (top row) for each of the expert (columns) as well as the predictions from each expert (bottom row) for the Poisson equation. Figure by author [2].</figcaption></figure><p>The figure shows that the gating network made the decision, under the influence of the sparsity regularisation, to almost completely drop expert 1 from the ensemble. This resulted in a more efficient and effective division of the domain amongst the remaining PINNs. The network assigned one dominant expert to each of the three quadrants, creating a symmetrical and intuitive distribution.</p><p>It is also worth noting that due to the low average importance of expert 1, if a new training run was to be initiated, this expert could be dropped from the ensemble and the remaining experts could be fine-tuned in a reduced-size, and thus more efficient, ensemble.</p><h3>Differentiable Architecture Search</h3><p>Finally, we want to make use of the introduced concepts to reduce the time needed for tuning hyperparameters. MoE-PINNs allow to initialise an ensemble of diverse experts and let the gating network decide, which experts should be retained and which experts could be discarded under the sparsity regularisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ld1_hs6HI6aP7jIeWhBXw.png" /><figcaption>Importance in ensembles of three experts (left) and four experts (right) with different activation functions on the Poisson equation. Figure by author [2].</figcaption></figure><p>Surprisingly, when analysing the importance of experts in diverse ensembles using different activation functions, the gating network consistently discards networks with tanh activations, despite tanh being a commonly used activation in PINN literature. Conversely, the gating network consistently favours experts with sine activations. This preference suggests that using an ensemble of sine activation networks may enhance PINN performance, which aligns with the principles of signal decomposition using the Fourier Transform, stating that any function can be represented as a combination of sine functions of different frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3vhlFJuOqWUjmOiosOlfw.png" /><figcaption>Importance in ensembles of four experts when varying the depth (left) and the depth (right) of otherwise identical experts on the Poisson equation. Figure by author [2].</figcaption></figure><p>Looking at ensembles with experts of varying depth and width, it appears as if a depth of two or three layers may be the optimal choice for PINNs on the poisson equation, whereas it seems like wider networks are to be preferred over narrow ones.</p><h3>Conclusion</h3><p>In conclusion, MoE-PINNs are a great extension for improving PINNs on PDEs exhibiting varying patterns and for reducing the time needed for tuning hyperparameters by letting the gating network decide on which architectures to utilise from a diverse set of experts.</p><p>If you want to try out MoE-PINNs yourself, have a look at the following notebooks:</p><ul><li><a href="https://drive.google.com/file/d/1JyejLXPS9LQdsNzZE5z-FTd8idRgrP1n/view?usp=sharing">Notebook for MoE-PINNs on Burgers’ equation</a></li><li><a href="https://drive.google.com/file/d/1IRyZvl9OFU8a0PETjdEEppM1BBoda4e8/view?usp=sharing">Notebook for MoE-PINNs on the L-shaped Poisson equation</a></li></ul><p>Thank you a lot for reading until the end of this article! If you found this article helpful and would like to use MoE-PINNs or the notebooks in your own work, please use the following citation:</p><blockquote>R. Bischof and M. A. Kraus, “<a href="https://scholar.google.com/scholar?oi=bibs&amp;cluster=12593425659851579449&amp;btnI=1&amp;hl=en">Mixture-of-Experts-Ensemble Meta-Learning for Physics-Informed Neural Networks</a>”, Proceedings of 33. Forum Bauinformatik, 2022</blockquote><p>You can find more information about my colleague Michael Kraus on <a href="http://mkrausai.com/">mkrausai.com</a> and about myself on <a href="http://rabischof.ch/">rabischof.ch</a>.</p><p>[1] M. Raissi, P. Perdikaris, and G. E. Karniadakis, Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations, Journal of Computational Physics 378 (2019), 686–707.</p><p>[2] R. Bischof and M. A. Kraus, “<a href="https://scholar.google.com/scholar?oi=bibs&amp;cluster=12593425659851579449&amp;btnI=1&amp;hl=en">Mixture-of-Experts-Ensemble Meta-Learning for Physics-Informed Neural Networks</a>”, Proceedings of 33. Forum Bauinformatik, 2022</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6520adf32438" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/mixture-of-experts-for-pinns-moe-pinns-6520adf32438">Mixture of Experts for PINNs (MoE-PINNs)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Physics-Informed Neural Networks through Adaptive Loss Balancing]]></title>
            <link>https://medium.com/data-science/improving-pinns-through-adaptive-loss-balancing-55662759e701?source=rss-913c6c1e6a94------2</link>
            <guid isPermaLink="false">https://medium.com/p/55662759e701</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Rafael Bischof]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 08:33:48 GMT</pubDate>
            <atom:updated>2023-02-23T09:25:24.795Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>How to boost your PINN’s performance with ReLoBRaLo, Learning Rate Annealing and co.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tOr8iV_72KsMq_5o" /><figcaption>Photo by <a href="https://unsplash.com/@davidclode?utm_source=medium&amp;utm_medium=referral">David Clode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we review the basics of PINNs, explore the issue of imbalanced losses, and show how the balancing scheme <a href="https://arxiv.org/abs/2110.09813">ReLoBRaLo (Relative Loss Balancing with Random Lookbacks)</a> [1], proposed by Michael Kraus and myself, can significantly boost the training process. Plus, experience the technique in action with two accompanying notebooks solving real-world PDEs:</p><ul><li><a href="https://colab.research.google.com/drive/1_PmLv8OWh9GZTzqPgFpCXYYBlxGqszOn?usp=sharing"><strong>Notebook for Kirchhoff Plate bending PDE</strong></a></li><li><a href="https://colab.research.google.com/drive/1R6aPThhp1wrQVaydl8pj1G0s4gLiH8Wc?usp=sharing"><strong>Notebook for Helmholtz PDE</strong></a></li></ul><p>If you clicked on this article, it is probably because you already have quite a good understanding of what <a href="https://www.sciencedirect.com/science/article/pii/S0021999118307125">Physics-Informed Neural Networks (PINN)</a> [2] are. Maybe you have found some tutorials online and implemented PINNs on well-known benchmarks like the Burgers or Helmholtz equation. The idea of harnessing the power of neural networks to solve complex partial differential equations (PDEs) is certainly an appealing one. But as many of us have painfully discovered, the reality of working with PINNs can also be quite a frustrating process. If you went ahead and tried applying these tools on a PDE that you encountered in your own research, one that may not yet be well-documented in the literature, then it is very likely that the vanilla PINNs may not have performed as well as you had hoped. Worse, that they even converged more slowly than established approaches like the Finite Elements Method (FEM)!</p><p>Bear with me, I have been there, in fact, basically every time that I tried applying PINNs to a new problem. Despite the progress that has been made in the five years since their proposal, and the decades of <a href="https://www.sciencedirect.com/science/article/pii/002199919090007N">research on using differentiable Neural Networks to solve differential equations</a> [3], there is still no easy, plug-and-play version of PINNs that can be seamlessly transferred to any type of problem.</p><p>You see, PINNs make use of differential equations in their loss function by taking multiple higher-order derivatives of the output with respect to the input. These derivatives are then used to construct the residual and boundary conditions that should be approximated. This means that each partial differential equation fundamentally changes the PINN’s training procedure. Not only may it become necessary to adapt the architecture, such as adding or removing layers and nodes, but other, more intricate hyperparameters may have a crucial impact on the modelling capabilities, many of which are pecularities of PINNs and can not be found in the literature of classical Neural Networks. These may include the choice of activation functions, the sampling procedure on the physical domain, or, very treacherous, the choice of units of measurements in the differential equation.</p><p>While I can unfortunately not give you all the ingredients necessary to make your PINNs work, I can most certainly tell you what the fundamental steps are, without which your endeavour will most likely be fruitless. But before I reveal these crucial tools, allow me to provide some context to better understand my arguments. Let us take a step back and open a parenthesis, if you will. (</p><h3>Benchmark PDEs</h3><p>For the sake of illustration, let us introduce the Helmholtz and Kirchhoff plate bending equations. But before you start feeling overwhelmed, let me assure you that understanding the intricacies of these PDEs is not necessary for following the rest of this article. If you want to skip this section, just know that the Helmholtz PDE is a second-order PDE with zeroth order (Dirichlet) boundary conditions, and the Kirchhoff plate bending equation is a fourth-order PDE with boundary conditions on the zeroth and second-order derivatives.</p><p>This equation is a fourth-order partial differential equation (PDE) that describes the deformation of a plate under load. The unknown function u in the equation represents the vertical displacement (in meters, for example) from the initial state of the plate at a given point (x, y). The load applied on the plate is represented by the function p(x, y). The constant D in the equation encapsulates various properties of the plate such as its thickness, modulus of elasticity, and density.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FgovhtmzonKQ4ek1kjZMtkZ&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FgovhtmzonKQ4ek1kjZMtkZ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="327" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a90df283cecc7eb3a2c736838d7b065/href">https://medium.com/media/5a90df283cecc7eb3a2c736838d7b065/href</a></iframe><p>So, Kirchhoff’s equation states that the fourth-order derivative of the deformation is equal to the load applied on the plate divided by a constant factor. Fairly straightforward, right?</p><p>Of course every experienced PDE-tian knows that a governing equation, as elegant as it may seem, is nothing but a meaningless abstraction without the proper boundary conditions. After all, there are an infinite number of equations that could fulfill it.</p><p>So let us also introduce the boundary conditions:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FiHdwPT4z35WB3Rhgqe8iCq&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FiHdwPT4z35WB3Rhgqe8iCq&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="392" height="160" frameborder="0" scrolling="no"><a href="https://medium.com/media/bee642bfc9f1f266fb27b65793cd0174/href">https://medium.com/media/bee642bfc9f1f266fb27b65793cd0174/href</a></iframe><p>where W and H define the the plate’s width and height, respectively. The first row of the boundary conditions shows the zeroth (Dirichlet) and states that the edges of the plate are not allowed to bend. The second row shows the second-order derivatives, which enforce the moments on the edges to be zero. This can be illustrated with an edge of a plate that is supported below by a beam (hence zero 0th order derivative) and squeezed by another beam by above (resulting in zero moments).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1eljk9JqlP5PvnUX02L0HQ.png" /><figcaption>Example of a Kirchhoff plate and its deformation (in m) under a sine load and W = H = 10 and D = 20.83. Figure by author.</figcaption></figure><h4>The Helmholtz Equation: Modeling Waves in a Medium</h4><p>The Helmholtz equation is a partial differential equation that describes the propagation of waves in a medium. It is a second-order equation and named after the German physicist Hermann von Helmholtz.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fn5Z4aq6i9VL1QnHBrD7uog&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fn5Z4aq6i9VL1QnHBrD7uog&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="396" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/71a537356de77d99a392e48a934d3442/href">https://medium.com/media/71a537356de77d99a392e48a934d3442/href</a></iframe><p>where k is the wave number and u(x, y) the unknown function to be found. For this problem, we will use the zeroth-order Dirichlet boundary conditions on all four edges of the domain:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F29tqi4owScW9tjfa8wopdU&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F29tqi4owScW9tjfa8wopdU&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/efadf352f6027a5290f94c1f41a314aa/href">https://medium.com/media/efadf352f6027a5290f94c1f41a314aa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVa1E7lRj49HErcGZ1cIAw.png" /><figcaption>Example of a Helmholtz wave propagation with zero Dirichlet boundaries. Figure by author.</figcaption></figure><h4>PINN Loss Function</h4><p>If I lost you anywhere during the definition of the Kirchhoff or Helmholtz functions, do not worry. It took me over half a year, and countless explanations from patient civil engineers, before being able to ruminate these formulas to you.</p><p>The real key is understanding how to translate these equations into a loss function that can be used to train our PINN, here for the Helmholtz equation:</p><pre>import tensorflow as tf<br>import tensorflow.experimental.numpy.isclose<br><br>TOL = 1e-5<br><br>def compute_loss(self, x, y, u, dudxx, dudyy, eval=False):<br>    &quot;&quot;&quot;<br>    Computes the physics-informed loss for Helmholtz&#39;s PDE.<br>    <br>    Parameters<br>    ----------<br>    x : tf.Tensor of shape (batch_size, 1)<br>        x coordinate of the points in the current batch<br>    y : tf.Tensor of shape (batch_size, 1)<br>        y coordinate of the points in the current batch<br>    u : tf.Tensor of shape (batch_size, 1)<br>        predictions made by our PINN (dim 0)<br>    dudxx : tf.Tensor of shape (batch_size, 1)<br>        second-order derivative of the predictions w.r.t. x<br>    dudyy : tf.Tensor of shape (batch_size, 1)<br>        second-order derivative of the predictions w.r.t. y<br>    &quot;&quot;&quot;<br>    <br>    # governing equation loss<br>    L_f = (dudxx + dudyy + self.k**2 * u - \<br>          (-np.pi**2 - (4 * np.pi)**2 + self.k**2) * tf.math.sin(np.pi * x) * tf.math.sin(4 * np.pi * y))**2<br><br>    # determine which points are on the boundaries of the domain<br>    # if a point is on either of the boundaries, its value is 1 and 0 otherwise<br>    x_lower = tf.cast(isclose(x, -1, rtol=0., atol=EPS), dtype=tf.float32)<br>    x_upper = tf.cast(isclose(x,  1, rtol=0., atol=EPS), dtype=tf.float32)<br>    y_lower = tf.cast(isclose(y, -1, rtol=0., atol=EPS), dtype=tf.float32)<br>    y_upper = tf.cast(isclose(y,  1, rtol=0., atol=EPS), dtype=tf.float32)<br><br>    # compute 0th order boundary condition loss<br>    L_b = ((x_lower + x_upper + y_lower + y_upper) * u)**2<br><br>    if eval:<br>        L_u = (tf.math.sin(np.pi*x) * tf.math.sin(4*np.pi*y) - u)**2<br>        return L_f, L_b, L_u<br>    <br>    return L_f, L_b</pre><p>You can find the full code in the notebooks implementing ReLoBRaLo for the <a href="https://colab.research.google.com/drive/1R6aPThhp1wrQVaydl8pj1G0s4gLiH8Wc?usp=sharing">Helmholtz</a> and the <a href="https://colab.research.google.com/drive/1_PmLv8OWh9GZTzqPgFpCXYYBlxGqszOn?usp=sharing">Kirchhoff PDEs</a>.</p><h3>Multi-Objective Optimisation</h3><p>As we have already established, the final loss function for our Helmholtz PDE will consist of two, the Kirchhoff PDE of three objectives:</p><ul><li>Helmholtz: the loss for the governing equation L_f and the loss for the 0th order boundary condition L_b0.</li><li>Kirchhoff: in addition to L_f and L_b0, Kirchhoff also has a term for the second-order boundary condition L_b2.</li></ul><p>Therefore, these losses fall into the category of Multi-Objective Optimisation (MOO), as is the case for most applications involving PINNs.</p><p>The way the several objectives are aggregated into a single loss is usually done through linear scalarisation:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FszxS114Mj8N9AcsEcyJ2Tj&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FszxS114Mj8N9AcsEcyJ2Tj&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="348" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/76dc44127a80743e27dd9d1d3f8465c4/href">https://medium.com/media/76dc44127a80743e27dd9d1d3f8465c4/href</a></iframe><p>where the lambdas are scaling factors for controlling each term’s contribution towards the total loss. But why are they necessary?</p><h3>The Issue of imbalanced Gradients</h3><p>After this detour for gathering the necessary context, we can finally close the open parenthesis ) and continue exploring why the units of measurements in the PDE have an influence on the convergence of PINNs. You see, the several objectives in our loss function — L_f, L_b0, and L_b2 — each have different units of measurement. L_b0 for Kirchhoff may be measured in meters, while L_b2 is measured in Nm, and the load on the plate is measured in MN per square meter. This creates a significant disparity in the magnitude of each term, leading to a computation of gradients that heavily favours the terms with the highest magnitude. The same is true for Helmholtz and any other PDE.</p><p>Let us have a look at what this means in our example with the Helmholtz equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4m1v2ooWvJjhXhQ4V_ie3Q.png" /><figcaption>Evolution of the losses when training a PINN on Helmholtz’ equation. L_f is the squared loss on the governing equation, L_b is the squared loss on the boundary conditions and L_u is the square loss of the predictions against the analytical solution. Figure by author.</figcaption></figure><p>Notice how the governing equation loss L_f is several orders of magnitude larger than the losses for the boundary conditions at the beginning of training and, as a consequence, how the value of L_b starts off by actually INCREASING. This discrepancy in magnitude can lead to a PINN that prioritizes L_f over L_b, ultimately converging towards a solution that satisfies the governing equation but neglects the crucial boundary conditions. This effect can be observed in the plot by the fact that the validation loss L_u follows the same pattern as the boundary loss L_b, suggesting that the validation performance is closely related to the performance on the boundaries.</p><p>What about the Kirchhoff PDE?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*W8lRwk26PNLcfxzdN8UWbg.png" /><figcaption>Evolution of the losses when training a PINN on Kirchhoff’s equation. L_f is the squared loss on the governing equation, L_b0 is the squared loss on the Dirichlet boundary conditions, L_b2 on the moments’ boundary conditions, and L_u is the square loss of the predictions against the analytical solution. Figure by author.</figcaption></figure><p>In the case of Kirchhoff, the inverse holds true. Here, the boundary conditions converge much more rapidly, while the governing equation makes little progress. The most likely explanation is that the governing equation involves fourth-order derivatives and is therefore a particularly hard objective to optimise for. This shows that the causes for <strong>imbalanced losses</strong> are not limited to differences in magnitudes between the terms. They range from the choice of activation function to the complexity of the function being approximated by each term.</p><p>I<strong>mbalanced gradients </strong>are by no means limited to the Helmholtz or Kirchhoff PDEs alone. Many studies have <a href="https://arxiv.org/pdf/2001.04536.pdf">documented this issue in various PINN applications</a> [4]. The key takeaway here is that, in order to arrive at accurate solutions, it is essential to strike a balance between all the objectives in the loss function.</p><h3>Adaptive Loss balancing Schemes</h3><p>To mitigate the issue of imbalanced losses and gradients, one can resort to the scaling factors lambda in the linear scalarisation of the Multi-Objective Optimisation introduced earlier. Selecting larger values of lambda for terms with smaller magnitudes or harder objectives can help evening the contributions to the final gradient, and thus make sure that all terms are appropriately approximated. However, doing this by hand is a tedious task, requiring many iterations and thus a lot of resources in terms of time and compute.</p><p>This is why researchers have proposed loss balancing schemes, such as <a href="https://arxiv.org/abs/1711.02257">Gradnorm</a> [5], <a href="https://arxiv.org/abs/1912.12355">SoftAdapt</a> [6] or <a href="https://arxiv.org/pdf/2001.04536.pdf">Learning Rate Annealing</a> [4].</p><h4>Relative Loss Balancing with Random Lookbacks (ReLoBRaLo)</h4><p>In this article, we will focus on a scheme called <a href="https://arxiv.org/abs/2110.09813">Relative Loss Balancing with Random Lookbacks (ReLoBRaLo)</a> [1], which is a combination of the aforementioned methods.</p><p>The goal of ReLoBRaLo is to ensure that each term in the loss function makes the same amount of progress over time, relative to its value at the start of training. For example, if L_f improves by 50% since the beginning of training, we want the other terms to improve at about the same rate and achieve a reduction of 50%. However, if there is a term that consistently improves at a slower rate, ReLoBRaLo incrementally increases the scaling lambda of this term, thus increasing its contribution to the gradient calculation.</p><p>Let us say that we have n loss terms L_i and let us denote the function L_i(t) to be the value of this term at training iteration t. One way that we can measure its progress since the start of training is by dividing the value at the current iteration L_i(t) by the value at the beginning of training, L_i(0):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FqEhqWm5uXASiW3Xe5WFxTn&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FqEhqWm5uXASiW3Xe5WFxTn&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="211" height="158" frameborder="0" scrolling="no"><a href="https://medium.com/media/859837da40105fd3017e16988ee3187f/href">https://medium.com/media/859837da40105fd3017e16988ee3187f/href</a></iframe><p>The greater the progress since the beginning of training was, the smaller the result of this operation will be. Observe how this is exactly what we are looking for: our scheme should attribute high scalings to terms that improved slowly, and small scalings to terms that improved fast — and all of that should happen independent of the absolute values of the terms. Therefore, we can use L_i(t) / L_i(0) for calculating the scalings of the terms in the loss function.</p><p>While this is the key component of ReLoBRaLo, it contains a number of additional extension that have been found to further improve the performance. However, for the sake of readability of this article, I leave it to the interested reader to <a href="https://arxiv.org/abs/2110.09813">have a look at the paper</a> and learn more about the methods used and their motivation.</p><p>But does it work? Well let us have a look at the loss evolution on the Helmholtz PDE, but this time by using ReLoBRsLo for balancing the contributions of the terms to the total loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*IVryC80D6DIhRtSJ_BGeSA.png" /><figcaption>Evolution of the losses when training a PINN on Helmholtz’ equation and using ReLoBRaLo. L_f is the squared loss on the governing equation, L_b is the squared loss on the boundary conditions and L_u is the square loss of the predictions against the analytical solution. Figure by author.</figcaption></figure><p>While the loss for the governing equation L_f does not make as much progress anymore (it converged at around -3.8 in the previous plot), the boundary conditions L_b and in consequence the validation loss L_u receive much more weight. The final validation loss against the analytical solution yields a <strong>65% improvement over the unscaled training run</strong>. Let us have a look at the scaling values that ReLoBRaLo computed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3c-QSA7vgNj0U5UpEDbtvQ.png" /><figcaption>Scaling factors lambda_i obtained through ReLoBRaLo for the governing equation term L_f (blue) and boundary conditions L_b (orange) on the Helmholtz PDE. Figure by author.</figcaption></figure><p>The same goes for Kirchhoff:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qPBQLr4Vd-tDeJm1b-FEUQ.png" /><figcaption>Evolution of the losses when training a PINN on Kirchhoff’s equation and using ReLoBRaLo. L_f is the squared loss on the governing equation, L_b0 is the squared loss on the Dirichlet boundary conditions, L_b2 on the moments’ boundary conditions, and L_u is the square loss of the predictions against the analytical solution. Figure by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bdHm4jluJ-rP6AS6KiREqg.png" /><figcaption>Scaling factors lambda_i obtained through ReLoBRaLo for the governing equation term L_f (blue), Dirichlet boundary conditions L_b0 (orange) and moments’ boundary conditions L_b2 (green) on the Kirchhoff PDE. Figure by author.</figcaption></figure><p>Again, ReLoBRaLo improved the error against the analytical solution by over an order of magnitude. It is also worth noting that this balancing scheme adds almost no computational overhead (cf. the paper). It is this effectiveness and efficiency that earned ReLoBRaLo its way into <a href="https://docs.nvidia.com/deeplearning/modulus/api/modulus.loss.html#modulus.loss.aggregator.Relobralo">Nvidia’s Modulus framework for Physics-Informed Deep Learning</a>.</p><p>But the real question is: can you use ReLoBRaLo in your own projects? The answer is a resounding yes! As it happens, the scheme can be neatly wrapped into a keras loss that can either be added to your keras model through model.compile(), or, in case you defined your own custom training loop, by explicitly calling it at each iteration.</p><p>You can find the full code in the notebooks implementing ReLoBRaLo for the <a href="https://colab.research.google.com/drive/1R6aPThhp1wrQVaydl8pj1G0s4gLiH8Wc?usp=sharing">Helmholtz</a> and the <a href="https://colab.research.google.com/drive/1_PmLv8OWh9GZTzqPgFpCXYYBlxGqszOn?usp=sharing">Kirchhoff PDEs</a>.</p><pre>import tensorflow as tf<br><br>class ReLoBRaLoLoss(tf.keras.losses.Loss):<br>    &quot;&quot;&quot;<br>    Class for the ReLoBRaLo Loss. <br>    This class extends the keras Loss class to have dynamic weighting for each term.<br>    &quot;&quot;&quot;<br>    def __init__(self, pde:HelmholtzPDE, alpha:float=0.999, temperature:float=0.1, rho:float=0.99,<br>                 name=&#39;ReLoBRaLoLoss&#39;, **kwargs):<br>        &quot;&quot;&quot;<br>        Parameters<br>        ----------<br>        pde : PDE<br>            An instance of a PDE class containing the PDE-specific `compute_loss` function.<br>        alpha, optional : float<br>            Controls the exponential weight decay rate. <br>            Value between 0 and 1. The smaller, the more stochasticity.<br>            0 means no historical information is transmitted to the next iteration.<br>            1 means only first calculation is retained. Defaults to 0.999.<br>        temperature, optional : float<br>            Softmax temperature coefficient. Controlls the &quot;sharpness&quot; of the softmax operation. <br>            Defaults to 0.1.<br>        rho, optional : float<br>            Probability of the Bernoulli random variable controlling the frequency of random lookbacks.<br>            Value berween 0 and 1. The smaller, the fewer lookbacks happen.<br>            0 means lambdas are always calculated w.r.t. the initial loss values.<br>            1 means lambdas are always calculated w.r.t. the loss values in the previous training iteration.<br>            Defaults to 0.99.<br>        &quot;&quot;&quot;<br>        super().__init__(name=name, **kwargs)<br>        self.pde = pde<br>        self.alpha = alpha<br>        self.temperature = temperature<br>        self.rho = rho<br>        self.call_count = tf.Variable(0, trainable=False, dtype=tf.int16)<br><br>        self.lambdas = [tf.Variable(1., trainable=False) for _ in range(pde.num_terms)]<br>        self.last_losses = [tf.Variable(1., trainable=False) for _ in range(pde.num_terms)]<br>        self.init_losses = [tf.Variable(1., trainable=False) for _ in range(pde.num_terms)]<br><br>    def call(self, xy, preds):<br>        x, y = xy[:, :1], xy[:, 1:]<br><br>        # obtain the unscaled values for each term <br>        losses = [tf.reduce_mean(loss) for loss in self.pde.compute_loss(x, y, preds)]<br><br>        # in first iteration (self.call_count == 0), drop lambda_hat and use init lambdas, i.e. lambda = 1<br>        #   i.e. alpha = 1 and rho = 1<br>        # in second iteration (self.call_count == 1), drop init lambdas and use only lambda_hat<br>        #   i.e. alpha = 0 and rho = 1<br>        # afterwards, default procedure (see paper)<br>        #   i.e. alpha = self.alpha and rho = Bernoully random variable with p = self.rho<br>        alpha = tf.cond(tf.equal(self.call_count, 0), <br>                lambda: 1., <br>                lambda: tf.cond(tf.equal(self.call_count, 1), <br>                                lambda: 0., <br>                                lambda: self.alpha))<br>        rho = tf.cond(tf.equal(self.call_count, 0), <br>              lambda: 1., <br>              lambda: tf.cond(tf.equal(self.call_count, 1), <br>                              lambda: 1., <br>                              lambda: tf.cast(tf.random.uniform(shape=()) &lt; self.rho, dtype=tf.float32)))<br><br>        # compute new lambdas w.r.t. the losses in the previous iteration<br>        lambdas_hat = [losses[i] / (self.last_losses[i] * self.temperature + EPS) for i in range(len(losses))]<br>        lambdas_hat = tf.nn.softmax(lambdas_hat - tf.reduce_max(lambdas_hat)) * tf.cast(len(losses), dtype=tf.float32)<br><br>        # compute new lambdas w.r.t. the losses in the first iteration<br>        init_lambdas_hat = [losses[i] / (self.init_losses[i] * self.temperature + EPS) for i in range(len(losses))]<br>        init_lambdas_hat = tf.nn.softmax(init_lambdas_hat - tf.reduce_max(init_lambdas_hat)) * tf.cast(len(losses), dtype=tf.float32)<br>        <br>        # use rho for deciding, whether a random lookback should be performed<br>        new_lambdas = [(rho * alpha * self.lambdas[i] + (1 - rho) * alpha * init_lambdas_hat[i] + (1 - alpha) * lambdas_hat[i]) for i in range(len(losses))]<br>        self.lambdas = [var.assign(tf.stop_gradient(lam)) for var, lam in zip(self.lambdas, new_lambdas)]<br><br>        # compute weighted loss<br>        loss = tf.reduce_sum([lam * loss for lam, loss in zip(self.lambdas, losses)])<br><br>        # store current losses in self.last_losses to be accessed in the next iteration<br>        self.last_losses = [var.assign(tf.stop_gradient(loss)) for var, loss in zip(self.last_losses, losses)]<br>        # in first iteration, store losses in self.init_losses to be accessed in next iterations<br>        first_iteration = tf.cast(self.call_count &lt; 1, dtype=tf.float32)<br>        self.init_losses = [var.assign(tf.stop_gradient(loss * first_iteration + var * (1 - first_iteration))) for var, loss in zip(self.init_losses, losses)]<br>        <br>        self.call_count.assign_add(1)<br><br>        return loss</pre><p>Thank you a lot for reading until the end of this article! If you found this article helpful and would like to use ReLoBRaLo or the notebooks in your own work, please use <a href="https://ui.adsabs.harvard.edu/abs/2021arXiv211009813B/exportcitation">this citation</a>. You can find more information about me on <a href="http://rabischof.ch/">rabischof.ch</a> and my colleague on <a href="http://mkrausai.com/">mkrausai.com</a>.</p><p>[1] Rafael Bischof and Michael Kraus. Multi-objective loss balancing for physics-informed deep learning. arXiv preprint arXiv:2110.09813, 2021.</p><p>[2] M. Raissi, P. Perdikaris, and G. E. Karniadakis, Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations, Journal of Computational Physics 378 (2019), 686–707.</p><p>[3] H. Lee and I. S. Kang, Neural algorithm for solving differential equations, J. Comput. Phys. 91 (1990), no. 1, 110–131</p><p>[4] Wang, S., Teng, Y., and Perdikaris, P. Understanding and mitigating gradient pathologies in physics-informed neural networks. arXiv e-prints (Jan. 2020), arXiv:2001.04536.</p><p>[5] Chen, Z., Badrinarayanan, V., Lee, C.-Y., and Rabinovich, A. GradNorm: Gradient Normalization for Adaptive Loss Balancing in Deep Multitask Networks. arXiv e-prints (Nov. 2017), arXiv:1711.02257.</p><p>[6] Heydari, A. A., Thompson, C. A., and Mehmood, A. SoftAdapt: Techniques for Adaptive Loss Weighting of Neural Networks with Multi-Part Loss Functions. arXiv e-prints (Dec. 2019), arXiv:1912.12355.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55662759e701" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/improving-pinns-through-adaptive-loss-balancing-55662759e701">Improving Physics-Informed Neural Networks through Adaptive Loss Balancing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>