{ "cells": [ { "cell_type": "markdown", "id": "3902fdc0", "metadata": {}, "source": [ "# Modeling Magnetohydrodynamics with Physics Informed Neural Operators" ] }, { "cell_type": "markdown", "id": "982a76df", "metadata": {}, "source": [ "In this notebook, we will study the application of physics informed data-driven modeling to the incompressible magnetohydrodynamics (MHD) equations representing an incompressible fluid in the presence of a magnetic field $\\mathbf{B}$. Our model will be built using a Tensor Factorized Fourier Neural Operator (tFNO), and trained in conjunction with the PDEs representing our system. The model is physics-informed during training by encoding known information about the physical system into the loss functions, enabling generalization of the resulting model to a variety of settings in the solution space. Specifically, the PDEs and initial conditions are used as soft constraints learned by the neural network as its trains. Models covering different data regimes governed by the Reynolds number are trained using transfer learning to showcase how our model may be applied to both laminar and turbulent flows. The AI-accelerated surrogate model is compared to classical simulations to compare its throughput and accuracy.\n", "\n", "Note that while the majority of the code needed to run this example is provided in the notebook, the lower barrier to entry for training and evaluating models will be to run the scripts in the source directory, and the material referenced here should be used as a base for learning the underlying components leading to model training and evaluation. " ] }, { "cell_type": "markdown", "id": "19f35947", "metadata": {}, "source": [ "#### Learning Outcomes\n", "* How to apply physics constraints to neural networks\n", "* Learn how the Tensor Factorized Fourier Neural Operator can be applied to physics based problems\n", "* Learn how to define PDEs with PhysicsNeMo\n", "* Train PINOs with PhysicsNeMo Core\n", "* Learn how data driven modeling can help build computationally efficient surrogates for physics problems" ] }, { "cell_type": "markdown", "id": "03be824a", "metadata": {}, "source": [ "## Pre-Requisites\n", "This workshop is derived primarily from the informative paper [Magnetohydrodynamics with physics informed neural operators\n", "](https://iopscience.iop.org/article/10.1088/2632-2153/ace30a)[1]. Reading the paper will provide both context and an overview of what will be presented in this workshop. Additionally, the paper serves as a great reference if more details are needed on any specific section. It is encouraged to read through the paper before continuing.\n", "\n", "[1] Rosofsky, S. G., & Huerta, E. A. (2023). Magnetohydrodynamics with physics informed neural operators. Machine Learning: Science and Technology, 4(3), 035002." ] }, { "cell_type": "markdown", "id": "e5a666a2", "metadata": {}, "source": [ "## Problem Overview\n", "\n", "To examine the properties of PINOs with multiple complex equations, we examined the ability of the networks to reproduce the incompressible magnetohydrodynamics (MHD) equations representing an incompressible fluid in the presence of a magnetic field $\\mathbf{B}$. These equations are present in several astrophysical phenomena, including black hole accretion and binary neutron star mergers. Additionally, MDH has applications to nuclear power engineering, and plasma modeling. \n", "\n", "These equations for incompressible MHD are given by:\n", "\n", "$$\\begin{align*}\n", "\\partial_t \\mathbf{u}+\\mathbf{u} \\cdot \\nabla \\mathbf{u} &=\n", "-\\nabla \\left( p+\\frac{B^2}{2} \\right)/\\rho_0 +\\mathbf{B}\n", "\\cdot \\nabla \\mathbf{B}+\\nu \\nabla^2 \\mathbf{u}, \\\\\n", "\\partial_t \\mathbf{B}+\\mathbf{u} \\cdot \\nabla \\mathbf{B} &=\n", "\\mathbf{B} \\cdot \\nabla \\mathbf{u}+\\eta \\nabla^2 \\mathbf{B}, \\\\\n", "\\nabla \\cdot \\mathbf{u} &= 0, \\\\\n", "\\nabla \\cdot \\mathbf{B} &= 0,\n", "\\end{align*}$$\n", " \n", "where $\\mathbf{u}$ is the velocity field, $p$ is the pressure, $B^2$ is the magnitude of the magnetic field, $\\rho_0=1$ is the density of the fluid, $\\nu$ is the kinetic viscosity, and $\\eta$ is the magnetic resistivity. We have two equations for evolution and two constraint equations.\n", "\n", "\n", "For the magnetic field divergence equation, we can either include it in the loss function or instead evolve the magnetic vector potential $\\mathbf{A}$. This quantity is defined such that\n", "\n", "$$\\begin{align*}\n", "\\mathbf{B} = \\nabla \\times \\mathbf{A},\n", "\\end{align*}$$\n", "\n", "which ensures that the divergence of $\\mathbf{B}$ is zero. By evolving magnetic vector potential $\\mathbf{A}$ instead of the magnetic field $\\mathbf{B}$, we have a new evolution equation for the vector potential $\\mathbf{A}$. This equation is given by \n", "\n", "$$\\begin{align*}\n", "\\partial_t \\mathbf{A} + \\mathbf{u} \\cdot \\nabla \\mathbf{A}=\\eta \\nabla^2 \\mathbf{A}.\n", "\\end{align*}$$\n", "\n", "In practice, using the magnetic vector potential representation leads to better model performance. " ] }, { "cell_type": "markdown", "id": "5331b9b9", "metadata": {}, "source": [ "## Data Creation\n", "Note that in this HuggingFace Space, the data are available at `/data/mhd_data`. There are:\n", "1000 samples for Re=100, 100 samples for Re=250 and 100 samples for Re=1,000.\n", "\n", "To train our model, a representative dataset is first created that gives enough coverage of the solution space to train a surrogate model to make predictions on new data points. To obtain interesting results without additional computational difficulty, we will solve the equations in 2D with periodic boundary conditions. This results in solving a total of 3 evolution PDEs at each time step. Two for the velocity evolution, and one for the magnetic vector potential. \n", "\n", "The solution space to this problem can be obtained numerically by solving the PDEs from above with a numerical solver such as `dedalus`. To generate this data, `dedalus` is used to simulate a 2D periodic incompressible MHD flow with a passive tracer field for visualization. The initial flow is in the $x$-direction and depends only on $z$. The problem is non-dimensionalized using the shear-layer spacing and velocity jump, so the resulting viscosity and tracer diffusivity are related to the Reynolds and\n", "Schmidt numbers as:\n", "\n", "$$\\begin{align}\n", "\\nu &= \\frac{1}{\\text{Re}} \\\\\n", "\\eta &= \\frac{1}{\\text{Re}_M} \\\\\n", "D &= \\frac{\\nu}{\\text{Sc}}\n", "\\end{align}$$\n", "\n", "The initial data field for running the simulation is produced using the Gaussian Random Field method in which the radial basis function kernel (RBF) is transformed into Fourier space to obey the desired periodic boundary conditions. Finally, two initial data fields the vorticity potential and magnetic potential are used to guarantee initial velocity and magnetic fields are divergence free. \n", "\n", "The dataset is produced by running 1,000 simulations with different initial conditions, and evolving the system for 1,000 time steps. The time step used is $\\Delta t=0.001s$, however output data is saved at an interval of $t=0.01$ for a total time of $1$ second, resulting in 101 samples per simulation. \n", "\n", "Scripts to generate the dataset are in the `generate_mhd_data` folder. Make sure to source this environment with `source activate env` to make use of the environment. To generate the dataset, run the command: \n", "```bash\n", "python dedalus_mhd_parallel.py\n", "```\n", "Note that depending on system resources, this process may take up to a few hours to complete. Once data generation is finished, we can exit the env with `conda deactivate`. " ] }, { "cell_type": "markdown", "id": "69a099f7", "metadata": {}, "source": [ "## Defining our Constraints - Setting up the PDE\n", "\n", "Constraints are used to define the objectives for training our model. They house a set of nodes from which a computational graph is build for execution as well as the loss function. [PhysicsNeMo Sim](https://docs.nvidia.com/deeplearning/physicsnemo/physicsnemo-sym/index.html) provides utilities tailored for physics-informed machine learning, and uses abstracted APIs that allow users to think and model the problem from the lens of equations, constraints, etc. In this example, we will only leverage the physics-informed utilities to see how we can add physics to an existing data-driven model with ease while still maintaining the flexibility to define our own training loop and other details. The types of constraints used will be problem dependent. For this example, we can define the following constraints: \n", "\n", "**Data Loss**: Obtain simulation data and compare it to the PINO output.\n", "\n", "**PDE Loss**: Use the known PDEs of the system to describe violations of the time evolution of our system\n", "\n", "**Constraint Loss**: This loss describes constraints from the PDE. Specifically, the velocity divergence free condition and magnetic divergence free condition.\n", "\n", "**Initial Condition Loss**: Input field compared to the output at $t=0$\n", "\n", "**Boundary Condition Loss**: Difference in boundary terms. In our case, we have a periodic boundary constraint.\n", "\n", "\n", "\n", "To begin setting up our constraints, we can start by defining the MHD equations using the `PDE` class from `physicsnemo.sym.eq.pde`. The process of converting our PDEs into a form that is compatible with `PhysicsNeMo` involves defining a class to hold our equations, called `MHD_PDE`, and including each term of the equations. Each variable of the equations is set up as a `Sympy` `Function`, which is then used to create an attribute of our `MHD_PDE` class that holds the final `equations`.\n", "\n", "Because we have elected to solve the equations in two dimensions, we only have the input variables $x$, $y$, $t$ and and the Laplacian operator. \n", "\n", "In PhysicsNeMo, it is preferable to represent our equations by isolating our target terms on the left, and moving the rest of the equation to the right-hand-side. To do this, various components of each equation are compartmentalized, and the final set of equations is composed from these parts.\n", "\n", "```python\n", "from physicsnemo.sym.eq.pde import PDE\n", "from sympy import Symbol, Function, Number\n", "\n", "\n", "class MHD_PDE(PDE):\n", " \"\"\"MHD PDEs using PhysicsNeMo Sym\"\"\"\n", "\n", " name = \"MHD_PDE\"\n", "\n", " def __init__(self, nu=1e-4, eta=1e-4, rho0=1.0):\n", "\n", " # x, y, time\n", " x, y, t, lap = Symbol(\"x\"), Symbol(\"y\"), Symbol(\"t\"), Symbol(\"lap\")\n", "\n", " # make input variables\n", " input_variables = {\"x\": x, \"y\": y, \"t\": t, \"lap\": lap}\n", "\n", " # make functions\n", " u = Function(\"u\")(*input_variables)\n", " v = Function(\"v\")(*input_variables)\n", " Bx = Function(\"Bx\")(*input_variables)\n", " By = Function(\"By\")(*input_variables)\n", " A = Function(\"A\")(*input_variables)\n", " # pressure\n", " ptot = Function(\"ptot\")(*input_variables)\n", "\n", " u_rhs = Function(\"u_rhs\")(*input_variables)\n", " v_rhs = Function(\"v_rhs\")(*input_variables)\n", " Bx_rhs = Function(\"Bx_rhs\")(*input_variables)\n", " By_rhs = Function(\"By_rhs\")(*input_variables)\n", " A_rhs = Function(\"A_rhs\")(*input_variables)\n", "\n", " # initialize constants\n", " nu = Number(nu)\n", " eta = Number(eta)\n", " rho0 = Number(rho0)\n", "\n", " # set equations\n", " self.equations = {}\n", "\n", " # u · ∇u\n", " self.equations[\"vel_grad_u\"] = u * u.diff(x) + v * u.diff(y)\n", " self.equations[\"vel_grad_v\"] = u * v.diff(x) + v * v.diff(y)\n", " # B · ∇u\n", " self.equations[\"B_grad_u\"] = Bx * u.diff(x) + v * Bx.diff(y)\n", " self.equations[\"B_grad_v\"] = Bx * v.diff(x) + By * v.diff(y)\n", " # u · ∇B\n", " self.equations[\"vel_grad_Bx\"] = u * Bx.diff(x) + v * Bx.diff(y)\n", " self.equations[\"vel_grad_By\"] = u * By.diff(x) + v * By.diff(y)\n", " # B · ∇B\n", " self.equations[\"B_grad_Bx\"] = Bx * Bx.diff(x) + By * Bx.diff(y)\n", " self.equations[\"B_grad_By\"] = Bx * By.diff(x) + By * By.diff(y)\n", " # ∇ × (u × B) = u(∇ · B) - B(∇ · u) + B · ∇u − u · ∇B\n", " self.equations[\"uBy_x\"] = u * By.diff(x) + By * u.diff(x)\n", " self.equations[\"uBy_y\"] = u * By.diff(y) + By * u.diff(y)\n", " self.equations[\"vBx_x\"] = v * Bx.diff(x) + Bx * v.diff(x)\n", " self.equations[\"vBx_y\"] = v * Bx.diff(y) + Bx * v.diff(y)\n", " # ∇ · B \n", " self.equations[\"div_B\"] = Bx.diff(x) + By.diff(y)\n", " # ∇ · u \n", " self.equations[\"div_vel\"] = u.diff(x) + v.diff(y)\n", "\n", " # RHS of MHD equations\n", " # = u · ∇u - p/rho + B · ∇B + ν * ∇^2(u)\n", " self.equations[\"u_rhs\"] = (\n", " -self.equations[\"vel_grad_u\"]\n", " - ptot.diff(x) / rho0\n", " + self.equations[\"B_grad_Bx\"] / rho0\n", " + nu * u.diff(lap)\n", " )\n", " self.equations[\"v_rhs\"] = (\n", " -self.equations[\"vel_grad_v\"]\n", " - ptot.diff(y) / rho0\n", " + self.equations[\"B_grad_By\"] / rho0\n", " + nu * v.diff(lap)\n", " )\n", " # Uses identity above\n", " # = ∇ × (u × B) + η * ∇^2(B)\n", " self.equations[\"Bx_rhs\"] = (\n", " self.equations[\"uBy_y\"] - self.equations[\"vBx_y\"] + eta * Bx.diff(lap)\n", " )\n", " self.equations[\"By_rhs\"] = -(\n", " self.equations[\"uBy_x\"] - self.equations[\"vBx_x\"]\n", " ) + eta * By.diff(lap)\n", "\n", " # Final equations move all terms to RHS\n", " # Node 18, 19, 20, 21\n", " self.equations[\"Du\"] = u.diff(t) - u_rhs\n", " self.equations[\"Dv\"] = v.diff(t) - v_rhs\n", " self.equations[\"DBx\"] = Bx.diff(t) - Bx_rhs\n", " self.equations[\"DBy\"] = By.diff(t) - By_rhs\n", "\n", " # Vec potential equations\n", " # Node 22, 23, 24\n", " self.equations[\"vel_grad_A\"] = u * A.diff(x) + v * A.diff(y)\n", " self.equations[\"A_rhs\"] = -self.equations[\"vel_grad_A\"] + eta * A.diff(lap)\n", " self.equations[\"DA\"] = A.diff(t) - A_rhs\n", "```\n", "\n", "Our model's output can then be used to compute the loss between prediction and true values, and for computing loss based on initial conditions, PDEs, and simulation data.\n" ] }, { "cell_type": "markdown", "id": "677d49b4", "metadata": { "vscode": { "languageId": "plaintext" } }, "source": [ "## Defining our Constraints - Loss Functions \n", "\n", "Now that we have defined our PDE, we can define all of the constraints that make up the loss function for our problem. The loss functions are defined inside of a class called `LossMHD_PhysicsNeMo`, which can use a weighted sum of individual losses for training. Additionally, all of the fixed and constant parameters needed are added to the class definition.\n", "\n", "```python\n", "import torch\n", "import torch.nn.functional as F\n", "from physicsnemo.models.layers.spectral_layers import fourier_derivatives\n", "\n", "from .losses import (LpLoss, fourier_derivatives_lap, fourier_derivatives_ptot,\n", " fourier_derivatives_vec_pot)\n", "from .mhd_pde import MHD_PDE\n", "\n", "\n", "class LossMHDVecPot_PhysicsNeMo(object):\n", " \"Calculate loss for MHD equations with vector potential, using physicsnemo derivatives\"\n", "\n", " def __init__(\n", " self,\n", " nu=1e-4,\n", " eta=1e-4,\n", " rho0=1.0,\n", " data_weight=1.0,\n", " ic_weight=1.0,\n", " pde_weight=1.0,\n", " constraint_weight=1.0,\n", " use_data_loss=True,\n", " use_ic_loss=True,\n", " use_pde_loss=True,\n", " use_constraint_loss=True,\n", " u_weight=1.0,\n", " v_weight=1.0,\n", " A_weight=1.0,\n", " Du_weight=1.0,\n", " Dv_weight=1.0,\n", " DA_weight=1.0,\n", " div_B_weight=1.0,\n", " div_vel_weight=1.0,\n", " Lx=1.0,\n", " Ly=1.0,\n", " tend=1.0,\n", " use_weighted_mean=False,\n", " **kwargs,\n", " ): # add **kwargs so that we ignore unexpected kwargs when passing a config dict):\n", "\n", " self.nu = nu\n", " self.eta = eta\n", " self.rho0 = rho0\n", " self.data_weight = data_weight\n", " self.ic_weight = ic_weight\n", " self.pde_weight = pde_weight\n", " self.constraint_weight = constraint_weight\n", " self.use_data_loss = use_data_loss\n", " self.use_ic_loss = use_ic_loss\n", " self.use_pde_loss = use_pde_loss\n", " self.use_constraint_loss = use_constraint_loss\n", " self.u_weight = u_weight\n", " self.v_weight = v_weight\n", " self.Du_weight = Du_weight\n", " self.Dv_weight = Dv_weight\n", " self.div_B_weight = div_B_weight\n", " self.div_vel_weight = div_vel_weight\n", " self.Lx = Lx\n", " self.Ly = Ly\n", " self.tend = tend\n", " self.use_weighted_mean = use_weighted_mean\n", " self.A_weight = A_weight\n", " self.DA_weight = DA_weight\n", " # Define 2D MHD PDEs\n", " self.mhd_pde_eq = MHD_PDE(self.nu, self.eta, self.rho0)\n", " self.mhd_pde_node = self.mhd_pde_eq.make_nodes()\n", "\n", " if not self.use_data_loss:\n", " self.data_weight = 0\n", " if not self.use_ic_loss:\n", " self.ic_weight = 0\n", " if not self.use_pde_loss:\n", " self.pde_weight = 0\n", " if not self.use_constraint_loss:\n", " self.constraint_weight = 0\n", "\n", " def __call__(self, pred, true, inputs, return_loss_dict=False):\n", " loss, loss_dict = self.compute_losses(pred, true, inputs)\n", " return loss, loss_dict\n", "\n", " def compute_losses(self, pred, true, inputs):\n", " \"Compute weighted loss and dictionary\"\n", " pred = pred.reshape(true.shape)\n", " u = pred[..., 0]\n", " v = pred[..., 1]\n", " A = pred[..., 2]\n", "\n", " loss_dict = {}\n", "\n", " # Data\n", " if self.use_data_loss:\n", " loss_data, loss_u, loss_v, loss_A = self.data_loss(\n", " pred, true, return_all_losses=True\n", " )\n", " loss_dict[\"loss_data\"] = loss_data\n", " loss_dict[\"loss_u\"] = loss_u\n", " loss_dict[\"loss_v\"] = loss_v\n", " loss_dict[\"loss_A\"] = loss_A\n", " else:\n", " loss_data = 0\n", " # IC\n", " if self.use_ic_loss:\n", " loss_ic, loss_u_ic, loss_v_ic, loss_A_ic = self.ic_loss(\n", " pred, inputs, return_all_losses=True\n", " )\n", " loss_dict[\"loss_ic\"] = loss_ic\n", " loss_dict[\"loss_u_ic\"] = loss_u_ic\n", " loss_dict[\"loss_v_ic\"] = loss_v_ic\n", " loss_dict[\"loss_A_ic\"] = loss_A_ic\n", " else:\n", " loss_ic = 0\n", "\n", " # PDE\n", " if self.use_pde_loss:\n", " Du, Dv, DA = self.mhd_pde(u, v, A)\n", " loss_pde, loss_Du, loss_Dv, loss_DA = self.mhd_pde_loss(\n", " Du, Dv, DA, return_all_losses=True\n", " )\n", " loss_dict[\"loss_pde\"] = loss_pde\n", " loss_dict[\"loss_Du\"] = loss_Du\n", " loss_dict[\"loss_Dv\"] = loss_Dv\n", " loss_dict[\"loss_DA\"] = loss_DA\n", " else:\n", " loss_pde = 0\n", "\n", " # Constraints\n", " if self.use_constraint_loss:\n", " div_vel, div_B = self.mhd_constraint(u, v, A)\n", " loss_constraint, loss_div_vel, loss_div_B = self.mhd_constraint_loss(\n", " div_vel, div_B, return_all_losses=True\n", " )\n", " loss_dict[\"loss_constraint\"] = loss_constraint\n", " loss_dict[\"loss_div_vel\"] = loss_div_vel\n", " loss_dict[\"loss_div_B\"] = loss_div_B\n", " else:\n", " loss_constraint = 0\n", "\n", " if self.use_weighted_mean:\n", " weight_sum = (\n", " self.data_weight\n", " + self.ic_weight\n", " + self.pde_weight\n", " + self.constraint_weight\n", " )\n", " else:\n", " weight_sum = 1.0\n", "\n", " loss = (\n", " self.data_weight * loss_data\n", " + self.ic_weight * loss_ic\n", " + self.pde_weight * loss_pde\n", " + self.constraint_weight * loss_constraint\n", " ) / weight_sum\n", " loss_dict[\"loss\"] = loss\n", " return loss, loss_dict\n", "\n", "```\n", "\n", "The MDH equations that we defined before are initialized for use within the following loss functions. " ] }, { "cell_type": "markdown", "id": "c6c1a66a", "metadata": {}, "source": [ "### Data Loss\n", "The data loss is used to compare simulation data to the output of our model. The velocity in $x$ and $y$, as well as magnetic vector potential $\\mathbf{A}$ is directly compared to the ground truth data through the `Lp-Loss`, and the relative mean squared error is returned. \n", "\n", "\n", "```python\n", "def data_loss(self, pred, true, return_all_losses=False):\n", " \"Compute data loss\"\n", " lploss = LpLoss(size_average=True)\n", " u_pred = pred[..., 0]\n", " v_pred = pred[..., 1]\n", " A_pred = pred[..., 2]\n", "\n", " u_true = true[..., 0]\n", " v_true = true[..., 1]\n", " A_true = true[..., 2]\n", "\n", " loss_u = lploss(u_pred, u_true)\n", " loss_v = lploss(v_pred, v_true)\n", " loss_A = lploss(A_pred, A_true)\n", "\n", " if self.use_weighted_mean:\n", " weight_sum = self.u_weight + self.v_weight + self.A_weight\n", " else:\n", " weight_sum = 1.0\n", "\n", " loss_data = (\n", " self.u_weight * loss_u + self.v_weight * loss_v + self.A_weight * loss_A\n", " ) / weight_sum\n", "\n", " if return_all_losses:\n", " return loss_data, loss_u, loss_v, loss_A\n", " else:\n", " return loss_data\n", "```" ] }, { "cell_type": "markdown", "id": "fe2f1f44", "metadata": {}, "source": [ "## PDE Loss\n", "The PDE loss describes violations of the time evolution of the PDEs and the PINO outputs. In order to make this comparison, the spatial and temporal derivatives of the output fields need to be computed. To do so, Fourier differentiation is used to calculate the spacial derivatives, and second order finite differencing is used for temporal derivatives. The output fields are the velocity in the $x$ direction ($u$), the velocity in the $y$ direction ($v$), and the magnetic vector potential ($\\mathbf{A}$). The PDE loss is then defined as the MSE loss between zero and the PDE, after putting all the terms on the same side of the equation.\n", "\n", "Specifically, this loss covers the following equations: \n", "$$\\begin{align*}\n", "\\partial_t \\mathbf{u}+\\mathbf{u} \\cdot \\nabla \\mathbf{u} &=\n", "-\\nabla \\left( p+\\frac{B^2}{2} \\right)/\\rho_0 +\\mathbf{B}\n", "\\cdot \\nabla \\mathbf{B}+\\nu \\nabla^2 \\mathbf{u}, \\\\\n", "\n", "\\partial_t \\mathbf{A} + \\mathbf{u} \\cdot \\nabla \\mathbf{A} &=\\eta \\nabla^2 \\mathbf{A}\n", "\\end{align*}$$\n", "\n", "```python\n", "def mhd_pde(self, u, v, A, p=None):\n", " \"Compute PDEs for MHD using vector potential\"\n", " nt = u.size(1)\n", " nx = u.size(2)\n", " ny = u.size(3)\n", " dt = self.tend / (nt - 1)\n", "\n", " # compute fourier derivatives\n", " f_du, _ = fourier_derivatives(u, [self.Lx, self.Ly])\n", " f_dv, _ = fourier_derivatives(v, [self.Lx, self.Ly])\n", " f_dBx, f_dBy, f_dA, f_dB, B2_h = fourier_derivatives_vec_pot(\n", " A, [self.Lx, self.Ly]\n", " )\n", "\n", " u_x = f_du[:, 0:nt, :nx, :ny]\n", " u_y = f_du[:, nt : 2 * nt, :nx, :ny]\n", " v_x = f_dv[:, 0:nt, :nx, :ny]\n", " v_y = f_dv[:, nt : 2 * nt, :nx, :ny]\n", " A_x = f_dA[:, 0:nt, :nx, :ny]\n", " A_y = f_dA[:, nt : 2 * nt, :nx, :ny]\n", "\n", " Bx = f_dB[:, 0:nt, :nx, :ny]\n", " By = f_dB[:, nt : 2 * nt, :nx, :ny]\n", " Bx_x = f_dBx[:, 0:nt, :nx, :ny]\n", " Bx_y = f_dBx[:, nt : 2 * nt, :nx, :ny]\n", " By_x = f_dBy[:, 0:nt, :nx, :ny]\n", " By_y = f_dBy[:, nt : 2 * nt, :nx, :ny]\n", "\n", " u_lap = fourier_derivatives_lap(u, [self.Lx, self.Ly])\n", " v_lap = fourier_derivatives_lap(v, [self.Lx, self.Ly])\n", " A_lap = fourier_derivatives_lap(A, [self.Lx, self.Ly])\n", "\n", " # note that for pressure, the zero mode (the mean) cannot be zero for invertability so it is set to 1\n", " div_vel_grad_vel = u_x**2 + 2 * u_y * v_x + v_y**2\n", " div_B_grad_B = Bx_x**2 + 2 * Bx_y * By_x + By_y**2\n", " f_dptot = fourier_derivatives_ptot(\n", " p, div_vel_grad_vel, div_B_grad_B, B2_h, self.rho0, [self.Lx, self.Ly]\n", " )\n", " ptot_x = f_dptot[:, 0:nt, :nx, :ny]\n", " ptot_y = f_dptot[:, nt : 2 * nt, :nx, :ny]\n", "\n", " # Plug inputs into dictionary\n", " all_inputs = {\n", " \"u\": u,\n", " \"u__x\": u_x,\n", " \"u__y\": u_y,\n", " \"v\": v,\n", " \"v__x\": v_x,\n", " \"v__y\": v_y,\n", " \"Bx\": Bx,\n", " \"Bx__x\": Bx_x,\n", " \"Bx__y\": Bx_y,\n", " \"By\": By,\n", " \"By__x\": By_x,\n", " \"By__y\": By_y,\n", " \"A__x\": A_x,\n", " \"A__y\": A_y,\n", " \"ptot__x\": ptot_x,\n", " \"ptot__y\": ptot_y,\n", " \"u__lap\": u_lap,\n", " \"v__lap\": v_lap,\n", " \"A__lap\": A_lap,\n", " }\n", "\n", " # Substitute values into PDE equations\n", " u_rhs = self.mhd_pde_node[14].evaluate(all_inputs)[\"u_rhs\"]\n", " v_rhs = self.mhd_pde_node[15].evaluate(all_inputs)[\"v_rhs\"]\n", " A_rhs = self.mhd_pde_node[23].evaluate(all_inputs)[\"A_rhs\"]\n", "\n", " u_t = self.Du_t(u, dt)\n", " v_t = self.Du_t(v, dt)\n", " A_t = self.Du_t(A, dt)\n", "\n", " # Find difference\n", " Du = self.mhd_pde_node[18].evaluate({\"u__t\": u_t, \"u_rhs\": u_rhs[:, 1:-1]})[\n", " \"Du\"\n", " ]\n", " Dv = self.mhd_pde_node[19].evaluate({\"v__t\": v_t, \"v_rhs\": v_rhs[:, 1:-1]})[\n", " \"Dv\"\n", " ]\n", " DA = self.mhd_pde_node[24].evaluate({\"A__t\": A_t, \"A_rhs\": A_rhs[:, 1:-1]})[\n", " \"DA\"\n", " ]\n", "\n", " return Du, Dv, DA\n", "\n", "\n", "def mhd_pde_loss(self, Du, Dv, DA, return_all_losses=None):\n", " \"Compute PDE loss\"\n", " Du_val = torch.zeros_like(Du)\n", " Dv_val = torch.zeros_like(Dv)\n", " DA_val = torch.zeros_like(DA)\n", "\n", " loss_Du = F.mse_loss(Du, Du_val)\n", " loss_Dv = F.mse_loss(Dv, Dv_val)\n", " loss_DA = F.mse_loss(DA, DA_val)\n", "\n", " if self.use_weighted_mean:\n", " weight_sum = self.Du_weight + self.Dv_weight + self.DA_weight\n", " else:\n", " weight_sum = 1.0\n", "\n", " loss_pde = (\n", " self.Du_weight * loss_Du\n", " + self.Dv_weight * loss_Dv\n", " + self.DA_weight * loss_DA\n", " ) / weight_sum\n", "\n", " if return_all_losses:\n", " return loss_pde, loss_Du, loss_Dv, loss_DA\n", " else:\n", " return loss_pde\n", "```" ] }, { "cell_type": "markdown", "id": "cd40c1ed", "metadata": {}, "source": [ "## Constraint Loss\n", "The constraint illustrates the deviations of the velocity divergence free condition and the magnetic divergence free condition. These conditions are implemented similarly to the PDE loss, but without time derivative terms. The constraint loss is then the MSE between each of the constraint equations and zero. \n", "\n", "Specifically, the equations used for constraint loss are:\n", "$$\\begin{align*}\n", "\\nabla \\cdot \\mathbf{u} &= 0, \\\\\n", "\\nabla \\cdot \\mathbf{B} &= 0\n", "\\end{align*}$$\n", "\n", "\n", "```python\n", "def mhd_constraint(self, u, v, A):\n", " \"Compute constraints\"\n", " nt = u.size(1)\n", " nx = u.size(2)\n", " ny = u.size(3)\n", "\n", " f_du, _ = fourier_derivatives(u, [self.Lx, self.Ly])\n", " f_dv, _ = fourier_derivatives(v, [self.Lx, self.Ly])\n", " f_dBx, f_dBy, _, _, _ = fourier_derivatives_vec_pot(A, [self.Lx, self.Ly])\n", "\n", " u_x = f_du[:, 0:nt, :nx, :ny]\n", " v_y = f_dv[:, nt : 2 * nt, :nx, :ny]\n", " Bx_x = f_dBx[:, 0:nt, :nx, :ny]\n", " By_y = f_dBy[:, nt : 2 * nt, :nx, :ny]\n", "\n", " div_B = self.mhd_pde_node[12].evaluate({\"Bx__x\": Bx_x, \"By__y\": By_y})[\"div_B\"]\n", " div_vel = self.mhd_pde_node[13].evaluate({\"u__x\": u_x, \"v__y\": v_y})[\"div_vel\"]\n", "\n", " return div_vel, div_B\n", "\n", "def mhd_constraint_loss(self, div_vel, div_B, return_all_losses=False):\n", " \"Compute constraint loss\"\n", " div_vel_val = torch.zeros_like(div_vel)\n", " div_B_val = torch.zeros_like(div_B)\n", "\n", " loss_div_vel = F.mse_loss(div_vel, div_vel_val)\n", " loss_div_B = F.mse_loss(div_B, div_B_val)\n", "\n", " if self.use_weighted_mean:\n", " weight_sum = self.div_vel_weight + self.div_B_weight\n", " else:\n", " weight_sum = 1.0\n", "\n", " loss_constraint = (\n", " self.div_vel_weight * loss_div_vel + self.div_B_weight * loss_div_B\n", " ) / weight_sum\n", "\n", " if return_all_losses:\n", " return loss_constraint, loss_div_vel, loss_div_B\n", " else:\n", " return loss_constraint\n", "```\n" ] }, { "cell_type": "markdown", "id": "627ae018", "metadata": {}, "source": [ "## Initial Condition Loss\n", "The initial condition loss encourages the model to associate the input field with the output field specifically at $t=0$. This constraint can usually be achieved with data loss, however this approach emphasized the importance of correct initial condition prediction, and enables training in the absence of data. Training without data and the significance of the initial condition term stem from the PDE loss term. \n", "\n", "```python\n", "def ic_loss(self, pred, input, return_all_losses=False):\n", " \"Compute initial condition loss\"\n", " lploss = LpLoss(size_average=True)\n", " ic_pred = pred[:, 0]\n", " ic_true = input[:, 0, ..., 3:]\n", " u_ic_pred = ic_pred[..., 0]\n", " v_ic_pred = ic_pred[..., 1]\n", " A_ic_pred = ic_pred[..., 2]\n", "\n", " u_ic_true = ic_true[..., 0]\n", " v_ic_true = ic_true[..., 1]\n", " A_ic_true = ic_true[..., 2]\n", "\n", " loss_u_ic = lploss(u_ic_pred, u_ic_true)\n", " loss_v_ic = lploss(v_ic_pred, v_ic_true)\n", " loss_A_ic = lploss(A_ic_pred, A_ic_true)\n", "\n", " if self.use_weighted_mean:\n", " weight_sum = self.u_weight + self.v_weight + self.A_weight\n", " else:\n", " weight_sum = 1.0\n", "\n", " loss_ic = (\n", " self.u_weight * loss_u_ic\n", " + self.v_weight * loss_v_ic\n", " + self.A_weight * loss_A_ic\n", " ) / weight_sum\n", "\n", " if return_all_losses:\n", " return loss_ic, loss_u_ic, loss_v_ic, loss_A_ic\n", " else:\n", " return loss_ic\n", "```\n", "\n", "Similar to the initial condition loss, boundary condition loss can be used to describe violations of the boundary terms. In this specific case, the tFNO architecture ensures that the periodic boundary conditions are satisfied, thus the term is not used in this example. " ] }, { "cell_type": "markdown", "id": "58809a2f", "metadata": {}, "source": [ "In theory, training can be done by correctly predicting the initial conditions, boundary conditions and correctly evolving the PDE forward in time. In practice, having data helps the model converge more quickly. However, an incorrect initial condition results in the PDE evolving the wrong state forward in time, which is why it is emphasized as its own term. The initial condition loss is calculated by taking the input fields and computing the relative MSE with output fields at $t=0$. \n" ] }, { "cell_type": "markdown", "id": "f14c9c48", "metadata": {}, "source": [ "## Dataset and Dataloaders\n", "To use the data we have generated, we need to define a dataset and a dataloader that can ingest the files and parse them based on the relevant content. \n", "\n", "```python\n", "import glob\n", "import os\n", "\n", "import h5py\n", "from torch.utils import data\n", "\n", "\n", "class Dedalus2DDataset(data.Dataset):\n", " \"Dataset for MHD 2D Dataset\"\n", "\n", " def __init__(\n", " self,\n", " data_path,\n", " output_names=\"output-\",\n", " field_names=[\"magnetic field\", \"velocity\"],\n", " num_train=None,\n", " num_test=None,\n", " num=None,\n", " use_train=True,\n", " ):\n", " self.data_path = data_path\n", " output_names = \"output-\" + \"?\"*len(str(len(os.listdir(data_path))))\n", " self.output_names = output_names\n", " raw_path = os.path.join(data_path, output_names, \"*.h5\")\n", " files_raw = sorted(glob.glob(raw_path))\n", " self.files_raw = files_raw\n", " self.num_files_raw = num_files_raw = len(files_raw)\n", " self.field_names = field_names\n", " self.use_train = use_train\n", "\n", " # Handle num parameter: -1 means use full dataset, otherwise limit to specified number\n", " if num is not None and num > 0:\n", " num_files_raw = min(num, num_files_raw)\n", " files_raw = files_raw[:num_files_raw]\n", " self.files_raw = files_raw\n", " self.num_files_raw = num_files_raw\n", "\n", " # Handle percentage-based splits\n", " if num_train is not None and num_train <= 1.0:\n", " # num_train is a percentage\n", " num_train = int(num_train * num_files_raw)\n", " elif num_train is None or num_train > num_files_raw:\n", " num_train = num_files_raw\n", "\n", " if num_test is not None and num_test <= 1.0:\n", " # num_test is a percentage\n", " num_test = int(num_test * num_files_raw)\n", " elif num_test is None or num_test > (num_files_raw - num_train):\n", " num_test = num_files_raw - num_train\n", "\n", " self.num_train = num_train\n", " self.train_files = self.files_raw[:num_train]\n", " self.num_test = num_test\n", " self.test_end = test_end = num_train + num_test\n", " self.test_files = self.files_raw[num_train:test_end]\n", " \n", " if (self.use_train) or (self.test_files is None):\n", " files = self.train_files\n", " else:\n", " files = self.test_files\n", " self.files = files\n", " self.num_files = num_files = len(files)\n", "\n", " def __len__(self):\n", " length = len(self.files)\n", " return length\n", "\n", " def __getitem__(self, index):\n", " \"Gets item for dataloader\"\n", " file = self.files[index]\n", "\n", " field_names = self.field_names\n", " fields = {}\n", " coords = []\n", " with h5py.File(file, mode=\"r\") as h5file:\n", " data_file = h5file[\"tasks\"]\n", " keys = list(data_file.keys())\n", " if field_names is None:\n", " field_names = keys\n", " for field_name in field_names:\n", " if field_name in data_file:\n", " field = data_file[field_name][:]\n", " fields[field_name] = field\n", " else:\n", " print(f\"field name {field_name} not found\")\n", " dataset = fields\n", " return dataset\n", "\n", " def get_coords(self, index):\n", " \"Gets coordinates of t, x, y for dataloader\"\n", " file = self.files[index]\n", " with h5py.File(file, mode=\"r\") as h5file:\n", " data_file = h5file[\"tasks\"]\n", " keys = list(data_file.keys())\n", " dims = data_file[keys[0]].dims\n", "\n", " ndims = len(dims)\n", " t = dims[0][\"sim_time\"][:]\n", " x = dims[ndims - 2][0][:]\n", " y = dims[ndims - 1][0][:]\n", " return t, x, y\n", "```\n", "\n", "And the dataloader which is sampled from during training.\n", "\n", "```python\n", "class MHDDataloaderVecPot(Dataset):\n", " \"Dataloader for MHD Dataset with vector potential\"\n", "\n", " def __init__(\n", " self, dataset: Dedalus2DDataset, sub_x=1, sub_t=1, ind_x=None, ind_t=None\n", " ):\n", " self.dataset = dataset\n", " self.sub_x = sub_x\n", " self.sub_t = sub_t\n", " self.ind_x = ind_x\n", " self.ind_t = ind_t\n", " t, x, y = dataset.get_coords(0)\n", " self.x = x[:ind_x:sub_x]\n", " self.y = y[:ind_x:sub_x]\n", " self.t = t[:ind_t:sub_t]\n", " self.nx = len(self.x)\n", " self.ny = len(self.y)\n", " self.nt = len(self.t)\n", " self.num = num = len(self.dataset)\n", " self.x_slice = slice(0, self.ind_x, self.sub_x)\n", " self.t_slice = slice(0, self.ind_t, self.sub_t)\n", "\n", " def __len__(self):\n", " length = len(self.dataset)\n", " return length\n", "\n", " def __getitem__(self, index):\n", " \"Gets input of dataloader, including data, t, x, and y\"\n", " fields = self.dataset[index]\n", "\n", " # Data includes velocity and vector potential\n", " velocity = fields[\"velocity\"]\n", " vector_potential = fields[\"vector potential\"]\n", "\n", " u = torch.from_numpy(\n", " velocity[\n", " : self.ind_t : self.sub_t,\n", " 0,\n", " : self.ind_x : self.sub_x,\n", " : self.ind_x : self.sub_x,\n", " ]\n", " )\n", " v = torch.from_numpy(\n", " velocity[\n", " : self.ind_t : self.sub_t,\n", " 1,\n", " : self.ind_x : self.sub_x,\n", " : self.ind_x : self.sub_x,\n", " ]\n", " )\n", " A = torch.from_numpy(\n", " vector_potential[\n", " : self.ind_t : self.sub_t,\n", " : self.ind_x : self.sub_x,\n", " : self.ind_x : self.sub_x,\n", " ]\n", " )\n", "\n", " # shape is now (self.nt, self.nx, self.ny, nfields)\n", " data = torch.stack([u, v, A], dim=-1)\n", " data0 = data[0].reshape(1, self.nx, self.ny, -1).repeat(self.nt, 1, 1, 1)\n", "\n", " grid_t = (\n", " torch.from_numpy(self.t)\n", " .reshape(self.nt, 1, 1, 1)\n", " .repeat(1, self.nx, self.ny, 1)\n", " )\n", " grid_x = (\n", " torch.from_numpy(self.x)\n", " .reshape(1, self.nx, 1, 1)\n", " .repeat(self.nt, 1, self.ny, 1)\n", " )\n", " grid_y = (\n", " torch.from_numpy(self.y)\n", " .reshape(1, 1, self.ny, 1)\n", " .repeat(self.nt, self.nx, 1, 1)\n", " )\n", "\n", " inputs = torch.cat([grid_t, grid_x, grid_y, data0], dim=-1)\n", " outputs = data\n", "\n", " return inputs, outputs\n", " \n", " def create_dataloader(\n", " self,\n", " batch_size=1,\n", " shuffle=False,\n", " num_workers=0,\n", " pin_memory=False,\n", " distributed=False,\n", " ):\n", " \"Creates dataloader and sampler based on whether distributed training is on\"\n", " if distributed:\n", " sampler = torch.utils.data.DistributedSampler(self)\n", " dataloader = DataLoader(\n", " self,\n", " batch_size=batch_size,\n", " shuffle=False,\n", " sampler=sampler,\n", " num_workers=num_workers,\n", " pin_memory=pin_memory,\n", " )\n", " else:\n", " sampler = None\n", " dataloader = DataLoader(\n", " self,\n", " batch_size=batch_size,\n", " shuffle=shuffle,\n", " num_workers=num_workers,\n", " pin_memory=pin_memory,\n", " )\n", "\n", " return dataloader, sampler\n", "```" ] }, { "cell_type": "markdown", "id": "bf33d763", "metadata": {}, "source": [ "## Model Architecture\n", "
\n", "
\n", " \n", "
Model architecture overview.
\n", "
\n", "
\n", "\n", "\n", "\n", "Our PINO model is composed of Tensor Factorized Neural Operators as the core component. Input fields are fed in as the input, which are composed of $u$, $v$, and $A$ initial conditions. The data is first lifted into a higher dimension representation by the neural network, P1. The data then enters the Fourier layers ($F_1$,...,$F_n$). Each Fourier layer consists of a sequence of non-logical integral operators, and nonlinear activation functions. $T_1$ represents a linear transform that employs CP decomposed tensors as weights, and $T_2$ represents a local linear transform. $\\sigma$ is the activation function, and $\\mathcal{F}$, $\\mathcal{F}^{-1}$ represent the Fourier transfrom and inverse Fourier transform respectively. At the end, $P_2$ projects back down into the input space, producing the output shown on the right which describe the\n", "time evolution of the system. \n" ] }, { "cell_type": "markdown", "id": "5dacfbfb", "metadata": {}, "source": [ "## Training our Model\n", "\n", "PhysicsNeMo has two distinct styles, namely Core and Sym. PhysicsNeMo Sym is a framework providing pythonic APIs, algorithms and utilities to be used with PhysicsNeMo Core, while PhysicsNeMo Core interoperates with PyTorch directly. Working with PhysicsNeMo Core looks and feels more like a PyTorch workflow with some key utils like models, utils, and datapipes imported directly from `physicsnemo` itself. While some components of this workflow so far have borrowed from PhysicsNeMo Sym (`MHD_PDE`), the training workflow for this problem will be build primarily using the Core style. This will provide more flexibility over our training loop, and allow for further customizations to our workflow. The training script follows the standard flow of training models using pytorch. \n" ] }, { "cell_type": "markdown", "id": "3339921a", "metadata": {}, "source": [ "## Hydra Config\n", "\n", "Training in PhysicsNeMo is facilitated by Hydra configs, which allow us to set and manager parameters from a single file, updating parameters for components such as our model, datasets, optimizer, logger, loss function, and dataloaders. The first step in getting set up for training is defining this yaml file and loading the config.\n", "\n", "\n", "```yaml \n", "## Training options\n", "# Reynolds number parameter\n", "reynolds_number: 100\n", "\n", "load_ckpt: False\n", "output_dir: './checkpoints/MHDVecPot_TFNO/MHDVecPot_TFNO_PINO_Re${reynolds_number}/figures/'\n", "\n", "###################\n", "## Model options\n", "model_params:\n", " layers: 8\n", " modes: 8\n", " num_fno_layers: 4\n", " fc_dim: 128\n", " decoder_layers: 1\n", " in_dim: 6 # 3 + in_fields\n", " out_dim: 3\n", " dimension: 3\n", " activation: 'gelu'\n", " pad_x: 5\n", " pad_y: 0\n", " pad_z: 0\n", " input_norm: [1.0, 1.0, 1.0, 1.0, 1.0, 0.00025]\n", " output_norm: [1.0, 1.0, 0.00025]\n", "\n", " #TensorLy arguments\n", " rank: 0.5\n", " factorization: 'cp'\n", " fixed_rank_modes: null\n", " decomposition_kwargs: {}\n", "\n", "###################\n", "## Dataset options\n", "dataset_params:\n", " data_dir: '/Datasets/mhd_data/simulation_outputs_Re${reynolds_number}'\n", " field_names: ['velocity', 'vector potential']\n", " output_names: 'output-????'\n", " dataset_type: 'mhd'\n", " name: 'MHDVecPot_TFNO_Re${reynolds_number}'\n", " num: -1 # -1 means use full dataset, otherwise specify total number\n", " num_train: 0.8 # percentage of dataset for training\n", " num_test: 0.2 # percentage of dataset for testing\n", " sub_x: 1\n", " sub_t: 1\n", " ind_x: null\n", " ind_t: null\n", " nin: 3\n", " nout: 3\n", " fields: ['u', 'v', 'A']\n", "\n", "###################\n", "## Dataloader options\n", "train_loader_params:\n", " batch_size: 1\n", " shuffle: True\n", " num_workers: 4\n", " pin_memory: True\n", "\n", "val_loader_params:\n", " batch_size: 1\n", " shuffle: False\n", " num_workers: 4\n", " pin_memory: True\n", "\n", "test_loader_params:\n", " batch_size: 1\n", " shuffle: False\n", " num_workers: 4\n", " pin_memory: True\n", "\n", "###################\n", "## Loss options\n", "loss_params:\n", " nu: 0.004\n", " eta: 0.004\n", " rho0: 1.0\n", "\n", " data_weight: 5.0\n", " ic_weight: 1.0\n", " pde_weight: 1.0\n", " constraint_weight: 10.0\n", "\n", " use_data_loss: True\n", " use_ic_loss: True\n", " use_pde_loss: True\n", " use_constraint_loss: True\n", "\n", " u_weight: 1.0\n", " v_weight: 1.0\n", " A_weight: 1.0\n", "\n", " Du_weight: 1.0\n", " Dv_weight: 1.0\n", " DA_weight: 1_000_000\n", "\n", " div_B_weight: 1.0\n", " div_vel_weight: 1.0\n", "\n", " Lx: 1.0\n", " Ly: 1.0\n", " tend: 1.0\n", "\n", " use_weighted_mean: False\n", "\n", "###################\n", "## Optimizer options\n", "optimizer_params:\n", " betas: [0.9, 0.999]\n", " lr: 5.0e-4\n", " milestones: [20, 40, 60, 80, 100]\n", " gamma: 0.5\n", "\n", "\n", "###################\n", "## Train params\n", "train_params:\n", " epochs: 100\n", " ckpt_freq: 10\n", " ckpt_path: 'checkpoints/MHDVecPot_TFNO/MHDVecPot_TFNO_PINO_Re${reynolds_number}/'\n", "\n", "###################\n", "## log params\n", "log_params:\n", " log_dir: 'logs'\n", " log_project: 'MHD_PINO'\n", " log_group: 'MHDVecPot_TFNO_Re${reynolds_number}'\n", " log_num_plots: 1\n", " log_plot_freq: 5\n", " log_plot_types: ['ic', 'pred', 'true', 'error']\n", "\n", "test:\n", " batchsize: 1\n", " ckpt_path: 'checkpoints/MHDVecPot_TFNO/MHDVecPot_TFNO_PINO_Re${reynolds_number}/'\n", "\n", "```" ] }, { "cell_type": "markdown", "id": "c9c370fa", "metadata": {}, "source": [ "## Training Setup\n", "\n", "We begin with importing the required modules, capturing our hydra config, and initializing some utilities to facilitate the model training. Most of this initial setup is \n", "\n", "```python\n", "import os\n", "\n", "import hydra\n", "from omegaconf import ListConfig, OmegaConf\n", "import torch\n", "from omegaconf import DictConfig\n", "from physicsnemo.distributed import DistributedManager\n", "from physicsnemo.launch.logging import LaunchLogger, PythonLogger\n", "from physicsnemo.launch.utils import load_checkpoint, save_checkpoint\n", "from physicsnemo.sym.hydra import to_absolute_path\n", "from torch.nn.parallel import DistributedDataParallel\n", "from torch.optim import AdamW\n", "\n", "from dataloaders import Dedalus2DDataset, MHDDataloaderVecPot\n", "from losses import LossMHDVecPot_PhysicsNeMo\n", "from tfno import TFNO\n", "from utils.plot_utils import plot_predictions_mhd, plot_predictions_mhd_plotly\n", "\n", "dtype = torch.float\n", "torch.set_default_dtype(dtype)\n", "\n", "\n", "@hydra.main(\n", " version_base=\"1.3\", config_path=\"config\", config_name=\"train_mhd_vec_pot_tfno.yaml\"\n", ")\n", "def main(cfg: DictConfig) -> None:\n", " DistributedManager.initialize() # Only call this once in the entire script!\n", " dist = DistributedManager() # call if required elsewhere\n", " cfg = OmegaConf.to_container(cfg, resolve=True)\n", "\n", " # initialize monitoring\n", " log = PythonLogger(name=\"mhd_pino\")\n", " log.file_logging()\n", "\n", " log_params = cfg[\"log_params\"]\n", "\n", " # Load config file parameters\n", " model_params = cfg[\"model_params\"]\n", " dataset_params = cfg[\"dataset_params\"]\n", " train_loader_params = cfg[\"train_loader_params\"]\n", " val_loader_params = cfg[\"val_loader_params\"]\n", " loss_params = cfg[\"loss_params\"]\n", " optimizer_params = cfg[\"optimizer_params\"]\n", " train_params = cfg[\"train_params\"]\n", "\n", " load_ckpt = cfg[\"load_ckpt\"]\n", " output_dir = cfg[\"output_dir\"]\n", "\n", " output_dir = to_absolute_path(output_dir)\n", " os.makedirs(output_dir, exist_ok=True)\n", "\n", " data_dir = dataset_params[\"data_dir\"]\n", " ckpt_path = train_params[\"ckpt_path\"]\n", "```\n" ] }, { "cell_type": "markdown", "id": "bacc38c7", "metadata": {}, "source": [ "## Datasets and Dataloaders\n", "\n", "Datasets and dataloaders are initialized using parameters from the hydra config.\n", "\n", "```python\n", "# Construct dataloaders\n", "dataset_train = Dedalus2DDataset(\n", " dataset_params[\"data_dir\"],\n", " output_names=dataset_params[\"output_names\"],\n", " field_names=dataset_params[\"field_names\"],\n", " num_train=dataset_params[\"num_train\"],\n", " num_test=dataset_params[\"num_test\"],\n", " num=dataset_params[\"num\"],\n", " use_train=True,\n", ")\n", "dataset_val = Dedalus2DDataset(\n", " data_dir,\n", " output_names=dataset_params[\"output_names\"],\n", " field_names=dataset_params[\"field_names\"],\n", " num_train=dataset_params[\"num_train\"],\n", " num_test=dataset_params[\"num_test\"],\n", " num=dataset_params[\"num\"],\n", " use_train=False,\n", ")\n", "\n", "mhd_dataloader_train = MHDDataloaderVecPot(\n", " dataset_train,\n", " sub_x=dataset_params[\"sub_x\"],\n", " sub_t=dataset_params[\"sub_t\"],\n", " ind_x=dataset_params[\"ind_x\"],\n", " ind_t=dataset_params[\"ind_t\"],\n", ")\n", "mhd_dataloader_val = MHDDataloaderVecPot(\n", " dataset_val,\n", " sub_x=dataset_params[\"sub_x\"],\n", " sub_t=dataset_params[\"sub_t\"],\n", " ind_x=dataset_params[\"ind_x\"],\n", " ind_t=dataset_params[\"ind_t\"],\n", ")\n", "\n", "dataloader_train, sampler_train = mhd_dataloader_train.create_dataloader(\n", " batch_size=train_loader_params[\"batch_size\"],\n", " shuffle=train_loader_params[\"shuffle\"],\n", " num_workers=train_loader_params[\"num_workers\"],\n", " pin_memory=train_loader_params[\"pin_memory\"],\n", " distributed=dist.distributed,\n", ")\n", "dataloader_val, sampler_val = mhd_dataloader_val.create_dataloader(\n", " batch_size=val_loader_params[\"batch_size\"],\n", " shuffle=val_loader_params[\"shuffle\"],\n", " num_workers=val_loader_params[\"num_workers\"],\n", " pin_memory=val_loader_params[\"pin_memory\"],\n", " distributed=dist.distributed,\n", ")\n", "```" ] }, { "cell_type": "markdown", "id": "4826da07", "metadata": {}, "source": [ "## Model Construction\n", "For a relatively simple model such as `FNO`, we can directly use an architecture pre-defined by PhysicsNeMo. Hyper-parameters are set directly from the hydra config, and makes it straight forward to configure hyper parameter optimization if necessary. For a more complex model such as `tFNO`, we can leverage a combination of PhysicsNeMo primitives and third party packages to build a model in pytorch. \n", "\n", "```python\n", "# Define the model\n", "model = TFNO(\n", " in_channels=model_params[\"in_dim\"],\n", " out_channels=model_params[\"out_dim\"],\n", " decoder_layers=model_params[\"decoder_layers\"],\n", " decoder_layer_size=model_params[\"fc_dim\"],\n", " dimension=model_params[\"dimension\"],\n", " latent_channels=model_params[\"layers\"],\n", " num_fno_layers=model_params[\"num_fno_layers\"],\n", " num_fno_modes=model_params[\"modes\"],\n", " padding=[model_params[\"pad_z\"], model_params[\"pad_y\"], model_params[\"pad_x\"]],\n", " rank=model_params[\"rank\"],\n", " factorization=model_params[\"factorization\"],\n", " fixed_rank_modes=model_params[\"fixed_rank_modes\"],\n", " decomposition_kwargs=model_params[\"decomposition_kwargs\"],\n", ").to(dist.device)\n", "# Set up DistributedDataParallel if using more than a single process.\n", "# The `distributed` property of DistributedManager can be used to\n", "# check this.\n", "if dist.distributed:\n", " ddps = torch.cuda.Stream()\n", " with torch.cuda.stream(ddps):\n", " model = DistributedDataParallel(\n", " model,\n", " device_ids=[dist.local_rank], # Set the device_id to be\n", " # the local rank of this process on\n", " # this node\n", " output_device=dist.device,\n", " broadcast_buffers=dist.broadcast_buffers,\n", " find_unused_parameters=dist.find_unused_parameters,\n", " )\n", " torch.cuda.current_stream().wait_stream(ddps)\n", "\n", "```" ] }, { "cell_type": "markdown", "id": "99604fbc", "metadata": {}, "source": [ "## Optimizer, Scheduler, Loss Functions and Check-pointing\n", "\n", "\n", "```python\n", "# Construct optimizer and scheduler\n", "optimizer = AdamW(\n", " model.parameters(),\n", " betas=optimizer_params[\"betas\"],\n", " lr=optimizer_params[\"lr\"],\n", " weight_decay=0.1,\n", ")\n", "\n", "scheduler = torch.optim.lr_scheduler.MultiStepLR(\n", " optimizer,\n", " milestones=optimizer_params[\"milestones\"],\n", " gamma=optimizer_params[\"gamma\"],\n", ")\n", "\n", "# Construct Loss class\n", "mhd_loss = LossMHDVecPot_PhysicsNeMo(**loss_params)\n", "\n", "# Load model from checkpoint (if exists)\n", "loaded_epoch = 0\n", "if load_ckpt:\n", " loaded_epoch = load_checkpoint(\n", " ckpt_path, model, optimizer, scheduler, device=dist.device\n", " )\n", "```\n" ] }, { "cell_type": "markdown", "id": "a775b128", "metadata": {}, "source": [ "## Training Loop\n", "Finally, the main training loop iterates through the dataset for our defined number of epochs, saving checkpoints and visualizations of our training along the way.\n", "\n", "```python\n", "# Training Loop\n", "epochs = train_params[\"epochs\"]\n", "ckpt_freq = train_params[\"ckpt_freq\"]\n", "names = dataset_params[\"fields\"]\n", "input_norm = torch.tensor(model_params[\"input_norm\"]).to(dist.device)\n", "output_norm = torch.tensor(model_params[\"output_norm\"]).to(dist.device)\n", "for epoch in range(max(1, loaded_epoch + 1), epochs + 1):\n", " with LaunchLogger(\n", " \"train\",\n", " epoch=epoch,\n", " num_mini_batch=len(dataloader_train),\n", " epoch_alert_freq=1,\n", " ) as log:\n", " if dist.distributed:\n", " sampler_train.set_epoch(epoch)\n", "\n", " # Train Loop\n", " model.train()\n", "\n", " for i, (inputs, outputs) in enumerate(dataloader_train):\n", " inputs = inputs.type(torch.FloatTensor).to(dist.device)\n", " outputs = outputs.type(torch.FloatTensor).to(dist.device)\n", " # Zero Gradients\n", " optimizer.zero_grad()\n", " # Compute Predictions\n", " pred = (\n", " model((inputs / input_norm).permute(0, 4, 1, 2, 3)).permute(\n", " 0, 2, 3, 4, 1\n", " )\n", " * output_norm\n", " )\n", " # Compute Loss\n", " loss, loss_dict = mhd_loss(pred, outputs, inputs, return_loss_dict=True)\n", " # Compute Gradients for Back Propagation\n", " loss.backward()\n", " # Update Weights\n", " optimizer.step()\n", "\n", " log.log_minibatch(loss_dict)\n", "\n", " log.log_epoch({\"Learning Rate\": optimizer.param_groups[0][\"lr\"]})\n", " scheduler.step()\n", "\n", " with LaunchLogger(\"valid\", epoch=epoch) as log:\n", " # Val loop\n", " model.eval()\n", " plot_count = 0\n", " with torch.no_grad():\n", " for i, (inputs, outputs) in enumerate(dataloader_val):\n", " inputs = inputs.type(dtype).to(dist.device)\n", " outputs = outputs.type(dtype).to(dist.device)\n", "\n", " # Compute Predictions\n", " pred = (\n", " model((inputs / input_norm).permute(0, 4, 1, 2, 3)).permute(\n", " 0, 2, 3, 4, 1\n", " )\n", " * output_norm\n", " )\n", " # Compute Loss\n", " loss, loss_dict = mhd_loss(\n", " pred, outputs, inputs, return_loss_dict=True\n", " )\n", "\n", " log.log_minibatch(loss_dict)\n", "\n", " # Get prediction plots to log\n", " # Do for number of batches specified in the config file\n", " if (i < log_params[\"log_num_plots\"]) and (\n", " epoch % log_params[\"log_plot_freq\"] == 0\n", " ):\n", " # Add all predictions in batch\n", " for j, _ in enumerate(pred):\n", " # Make plots for each field\n", " for index, name in enumerate(names):\n", " # Generate figure\n", " _ = plot_predictions_mhd_plotly(\n", " pred[j].cpu(),\n", " outputs[j].cpu(),\n", " inputs[j].cpu(),\n", " index=index,\n", " name=name,\n", " )\n", " plot_count += 1\n", "\n", " # Get prediction plots and save images locally\n", " if (i < 2) and (epoch % log_params[\"log_plot_freq\"] == 0):\n", " # Add all predictions in batch\n", " for j, _ in enumerate(pred):\n", " # Generate figure\n", " plot_predictions_mhd(\n", " pred[j].cpu(),\n", " outputs[j].cpu(),\n", " inputs[j].cpu(),\n", " names=names,\n", " save_path=os.path.join(\n", " output_dir,\n", " \"MHD_physicsnemo\" + \"_\" + str(dist.rank),\n", " ),\n", " save_suffix=i,\n", " )\n", "\n", " if epoch % ckpt_freq == 0 and dist.rank == 0:\n", " save_checkpoint(ckpt_path, model, optimizer, scheduler, epoch=epoch)\n", "\n", "```" ] }, { "cell_type": "markdown", "id": "ca49a425", "metadata": {}, "source": [ "## Running the Training Script\n", "\n", "The full set of python code to start training is available in the folder `./mhd`. Configs, data generation, dataloaders, loss functions, model architectures, and training scripts are all available here. If utilizing the scripts outside of this HuggingFace Space, you can launch training with:\n", "\n", "```bash\n", "torchrun --standalone --nnodes=1 --nproc_per_node=1 train_mhd_vec_pot_tfno.py\n", "```\n", "\n", "With the default set of parameters, the model will take up around 5.2GB of GPU memory, and a full training run up to 100 epochs will take around 1.5 hours." ] }, { "cell_type": "markdown", "id": "39c969ce", "metadata": {}, "source": [ "## End-to-End Training\n", "\n", "All of the code that was detailed above is available to explore in the \"./mhd\" folder. There are also two scripts that execute the end-to-end workflow for training and evaluation. " ] }, { "cell_type": "code", "execution_count": null, "id": "6013cf5d-8232-45bf-8e79-1757bb29d3fe", "metadata": {}, "outputs": [], "source": [ "!python mhd/train_mhd_vec_pot_tfno.py" ] }, { "cell_type": "markdown", "id": "daf003ec", "metadata": {}, "source": [ "## Transfer Learning to New Reynolds Number\n", "In practice, our system may not follow smooth, laminar flows described with low Reynolds numbers. In MHD systems, much of the magnetic field energy is stored at high wave numbers, which occur at smaller scales. Models must then be able to characterize high frequency features in order to successfully reproduce the trajectories of the system. These turbulent flows at higher Reynolds number are simulated, which will in turn produce higher frequency features that a model trained on smooth flows may not be able to resolve with good accuracy. To this end, transfer learning can be used to take a base model and adapt it to the new data domain by using a pre-trained checkpoint as the starting point of a new iteration of model training. \n", "\n", "To run transfer learning, we need a dataset of points from our new domain. For example, our default model is trained on data using $Re=100$, so we can use the model checkpoint from this domain to start off transferlerning to a new dataset with $Re=250$. In the Hydra config, we can update the following parameters:\n", "\n", "```yaml\n", "load_ckpt: True\n", "output_dir: \"/path/to/new/output_dir\"\n", "\n", "dataset_params:\n", " data_dir: \"/path/to/new/dataset\"\n", " name: 'Dataset Name'\n", "\n", "train_params:\n", " ckpt_path: \"/path/to/starting_checkpoint\"\n", "```\n", "\n", "
\n", "
\n", " \n", "
Predictions with a large Reynolds Number.
\n", "
\n", "
" ] }, { "cell_type": "markdown", "id": "93c7d926", "metadata": {}, "source": [ "## Evaluation\n", "When solving the MHD equations with `dedalus`, the average time per simulation is about 37 seconds. On the other hand, our physics informed model has an average inference time of 0.15 seconds, a 246x speedup. This comes at the cost of decreased accuracy in our solution, as it is an approximation to the system equations. Furthermore, our models performance will vary, depending on the Reynolds number. \n", "\n", "Evaluation can be run a few different ways. If there are many systems to evaluate, we can load them into a dataloader and do batch processing. In this example, we will use a standalone script, which is a stripped down version of the training script that will run our model with a single sample. \n", "\n", "To run evaluation we can use the following command, which pulls in a config that points to a specific pre-trained checkpoint and dataset. The config is found in `eval_mhd_vec_pot_tfno.yaml`\n", "\n", "\n", "```bash\n", "torchrun --standalone --nnodes=1 --nproc_per_node=1 evaluate_mhd_vec_pot_tfno.py\n", "```\n", "\n", "In evaluations, our model is able to accurately simulate flows at $Re<250$. Specifically, for $Re=100$, our surrogate model has less than 4% error at $t=1$ for all fields. At $Re=250$, the velocity field and vector potential potential are accurately described, with MSEs <7% and <10%, respectively. At higher Reynolds numbers, our model starts to break down. An example for $Re=100$ is shown below, as well as some plots showing $MSE$ vs $Re$.\n", "\n", "
\n", "
\n", " \n", "
Predictions with a low Reynolds Number.
\n", "
\n", "
\n", "
\n", "
\n", " \n", "
Error vs. Reynolds Number.
\n", "
\n", "
" ] }, { "cell_type": "markdown", "id": "9fec5e93", "metadata": {}, "source": [ "## End-to-End Evaluation\n", "To run evaluation, use the following script:" ] }, { "cell_type": "code", "execution_count": null, "id": "b44a1bfd", "metadata": {}, "outputs": [], "source": [ "!python mhd/evaluate_mhd_vec_pot_tfno.py" ] }, { "cell_type": "markdown", "id": "26acf9de", "metadata": {}, "source": [ "## Shortcomings and areas for improvement\n", "\n", "Physics informed machine learning shows promising results when applied to certain regions of parameter space as governed by the Reynolds number. While models such as tFNOs are able to accurately capture and simulate systems, they do not always perform well when the underlying physics begin to shift into regions of high frequency features. A tradeoff is present in accuracy and throughput, where these AI surrogate models accelerate simulations over 200x, however they remain accuracy for only the low Reynolds number parameter space. To this end, applying physics informed ML to the MHD equations shows both promise and room for improvement. For example, increased model size, additional physical loss functions from energy spectra, and higher resolution datasets may be a few areas in which the development and application of these models may be improved. In conclusion, the efficacy of physics informed machine learning has been shown to the modeling of magnetohydrodynamics, and researchers, scientists, and engineers are encouraged to build on this foundation to enhance these techniques further. " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }