FluidNet re-written with ATen tensor lib

Overview

fluidnet_cxx: Accelerating Fluid Simulation with Convolutional Neural Networks. A PyTorch/ATen Implementation.

This repository is based on the paper, Accelerating Eulerian Fluid Simulation With Convolutional Networks by Jonathan Tompson, Kristofer Schlachter, Pablo Sprechmann, Ken Perlin on the accelation of fluid simulations by embedding a neural network in an existing solver for pressure prediction, replacing an expensive pressure projection linked to a Poisson equation on the pressure, which is usually solved with iterative methods (PCG or Jacobi methods). We implemented our code with PyTorch, effectively replacing all the original Torch/Lua and C++/CUDA implementation of the inviscid, incompressible fluid solver (based on the open-source fluid simulator Mantaflow, aimed at the Computer Graphics community). Find the original FluidNet repository here.

We have retaken the original FluidNet NN architecture and added different features, such as replacing upsampling with deconvolution layers, or directly replacing the complete architecture with a deeper MultiScale net which showed more accurate results at the expense of inference speed.

This work allows to compare both the code perfomace when run in a single GPU unit and the accuracy of this data-driven method in comparison with tradional mehtods (Jacobi) or other fluid simulation methods like Lattice Boltzmann Methods.

Results

Simulations of a buoyancy-driven plume flow are performed with different methods for the Poisson equation resolution. An inlet is placed at the bottom of the domain, where a lighter fluid (with density rho0) is injected with velocity v0 into a quiescent heavier fluid. Results show that some work is still needed to predict a correct plume growth rate, due probably to a poor modelling of buoyant forces by the trained model.

Alt text

Resolution with ConvNet | Jacobi Method 28 iter | Jacobi Method 100 iter

Growth Rate of the plume's head for Ri=0.14

Functionalities:

  • NOTE: For the moment, only 2D simulations and training are supported. 3D needs still some work.
  • Full eulerian (incompressible and inviscid) fluid simulator:
    • Momentum equation resolution using a splitting algorithm:
      • Advection of velocity + External forces
      • Enforcing of non-divergence of velocity constraint through Poisson equation resolution, resulting in a pressure gradient that corrects the velocity from the previous step. Step replaced by a fully convolutional Neural Network with divergence of velocity as input and pressure as output.
    • Unconditional Stable MacCormack discretization of velocity advection algorithm.
    • Jacobi method implementation for comparison.
  • Dataset:
    • Generation with FluidNet own Mantaflow sript.
    • Random insertion of objects and velocity emitters, as well as gravity forces.
    • Pre-processed into PyTorch objects
  • Pre-trained models:
  • Training:
    • Several options for loss function:
      • MSE of pressure
      • "Physical" loss: MSE of velocity divergence (unsupervised)
      • MSE of velocity divergence after several timesteps.
    • Short term divergence loss: 8 hours training
    • Short+Long term divergence loss: ~2 days
  • Inference. Two test cases:
    • Buoyant plume.
    • Rayleigh Taylor instability.
    • Launch your simulation with the available pre-trained model.
    • Comparison with Jacobi method resolution + LBM with open-sourced C++ library Palabos
  • Results visualization:
    • Matplotlib
    • Paraview post-processing tool (VTK files)

Models

Requirements

  • Python 3.X
  • C++11
  • Pytorch 0.4 (Including ATen Tensor library, exposing PyTorch library in C++)
  • FluidNet own Mantaflow implementation
  • PyVTK (pip install)
  • (Optional) Paraview
  • (Optional) OpenCV2

ATen allows to write generic code that works on both devices. More information in ATen repo. It can be called from PyTorch, using its new extension-cpp.

Installation

To install this repo:

  1. Clone this repo:
https://github.com/jolibrain/fluidnet_cxx.git
  1. Install Pytorch 0.4: Pytorch 0.4 NOTE: Training is done in GPUs

  2. Install cpp extensions for fluid solver: C++ scripts have been written using PyTorch's backend C++ library ATen. These scripts are used for the advection part of the solver. Follow these instructions from main directory:

cd pytorch/lib/fluid/cpp
python3 setup.py install # if you want to install it on local user, use --user

Training

Dataset We use the same 2D dataset as the original FluidNet Section 1: Generating the data - Generating training data (generated with MantaFlow) for training our ConvNet.

Running the training To train the model, go to pytorch folder:

cd pytorch

The dataset file structure should be located in <dataDir> folder with the following structure:

.
└── dataDir
    └── dataset
        ├── te
        └── tr

Precise the location of the dataset in pytorch/config.yaml writing the folder location at dataDir (use absolute paths). Precise also dataset (name of the dataset), and output folder modelDirwhere the trained model and loss logs will be stored and the model name modelFilename.

Run the training :

python3 fluid_net_train.py

For a given dataset, a pre-processing operation must be performed to save it as PyTorch objects, easily loaded when training. This is done automatically if no preprocessing log is detected. This process can take some time but it is necessary only once per dataset.

Training can be stopped using Ctrl+C and then resumed by running:

python3 fluid_net_train.py --resume

You can also monitor the loss during training by running in /pytorch

python3 plot_loss.py <modelDir> #For total training and validation losses
#or
python3 plot_5loss.py <modelDir> #For each of the losses (e.g: L1(div) and L2(div))

It is also possible to load the saved model and print its output fields and compare it to targets (Pressure, Velocity, Divergence and Errors):

python3 print_output.py <modelDir> <modelFilename>
#example:
python3 print_output.py data/model_pLoss_L2 convModel

Training options

You can set the following options for training from the terminal command line:

  • -h : displays help message
  • --trainingConf : YAML config file for training. Default = config.yaml.
  • --modelDir : Output folder location for trained model. When resuming, reads from this location.
  • --modelFilename : Model name.
  • --dataDir : Dataset location.
  • --resume : Resumes training from checkpoint in modelDir
  • --bsz : Batch size for training.
  • --maxEpochs : Maximum number training epochs.
  • --noShuffle : Remove dataset shuffle when training.
  • --lr : Learning rate.
  • --numWorkers : Number of parallel workers for dataset loading.
  • --outMode : Training debug options. Prints or shows validation dataset. save = saves plots to disk show = shows plots in window during training none = do nothing

The rest of the training parameters are set in the trainingConf file, by default config.yaml.

Parameters in the YAML config file are copied into a python dictionary and saved as two separated dictionaries in modelDir, one conf dictionary for parameters related to training (batch size, maximum number of epochs) and one mconf dictionary for parameters related to the model (inputs, losses, scaling options etc)

Test

Run the buoyant plume test case by running:

cd pytorch
python3 plume.py --modelDir <modelDir> --modelFilename <modelFilename> --outputFolder <outputFolder>

with:

  • <modelDir> : folder with trained model.
  • <modelFilename> : Trained model name.
  • <outputFolder> : Folder for saving simulation results.

You can also stop the simulation (Ctrl+C) and restart it afterwards:

python3 plume.py --restartSim

Test options

  • -h : displays help message
  • --simConf : YAML config file for simulation. Default = plumeConfig.yaml.
  • --trainingConf : YAML config file for training. Default = config.yaml.
  • --modelDir : Trained model location.
  • --modelFilename : Model name.
  • --outputFolder : Location of output results.
  • --restartSim : Restart simulation from checkpoint in <outputFolder>.

Check plumeConfig.yaml to see how the configuation file for the simulation is organized.

Modifying the NN architecture

If you want to try your own architecture, you only have to follow these simple rules:

  • Write your model in a separate script and save it inside pytorch/lib.
  • Open model.py and import your own script as a module. Go to class FluidNet here.
  • Ideally, as with the Multi-Scale Net example, you should just have to precise the number of channels from the input, and add your net forward pass as in the multicale example here

Extending the cpp code:

The cpp code, written with ATen library, can be compiled, tested and run on its own. You will need OpenCV2 to visualize output of the pressure and velocity fields, as matplotlib is unfortunately not available in cpp!

Test

First, generate the test data from FluidNet Section 3. Limitations of the current system - Unit Testing and write the location of your folder in:

solver_cpp/test/test_fluid.cpp
#define DATA <path_to_data>

Run the following commands:

cd solver_cpp/
mkdir build_test
cd build_test
cmake .. -DFLUID_TEST=ON # Default is OFF
./test/fluidnet_sim

This will test every routine of the solver (advection, divergence calculation, velocity update, adding of gravity and buoyancy, linear system resolution with Jacobi method). These tests are taken from FluidNet and compare outputs of Manta to ours, except for advection when there is no Manta equivalent. In that case, we compare to the original FluidNet advection.

Run

cd solver_cpp/
mkdir build
cd build
cmake .. -DFLUID_TEST=OFF # Default is OFF
./simulate/fluidnet_sim

Output images will be written in build folder, and can be converted into gif using ImageMagick.

NOTE: For the moment, only 2D simulations and training are supported, as bugs are still found for the 3D advection.

Comments
  • Cpp extensions do not work

    Cpp extensions do not work

    At execution, in the function Advect Scalar, called from advection.py input arguments behave as Variable type (grad is computed) whereas intermediate objects in the function are just Tensor type.

    at::Tensor advectScalar
    (
      float dt, T src, T U, T flags,
      const std::string method_str,
      int bnd,
      const bool sample_outside_fluid,
      const float maccormack_strength
    ) {
      // Size checking done in python side
      int bsz = flags.size(0);
      int d = flags.size(2);
      int h = flags.size(3);
      int w = flags.size(4);
    
      bool is3D = (U.size(1) == 3);
    
      src.set_requires_grad(false);
      U.set_requires_grad(false);
      flags.set_requires_grad(false);
    
      T s_dst = zeros_like(src);
    
      T fwd = zeros_like(src);
      T bwd = zeros_like(src);
      T fwd_pos = zeros_like(U);
      T bwd_pos = zeros_like(U);
    
      std::cout << "Is variable?" << std::endl;
      std::cout << src.is_variable() << std::endl;
      // returns 1, should be 0
      std::cout << U.is_variable() << std::endl;
      // returns 1, should be 0
      std::cout << flags.is_variable() << std::endl;
      // returns 1, should be 0
    
    

    All should be of Tensor type as no backpropagation is required in the advection part.

    opened by AAlguacil 2
  • Plume.py with pre-trained model And config.yaml file.

    Plume.py with pre-trained model And config.yaml file.

    Hi,

    I tried to run plume simulation with pre-trained model. and I figured out I need config file for pre-trained model.

    So, can you add config file for pre-trained model? Or can I just use default trainConfig.yaml for pre-trained model?

    Thank you for reading.

    opened by ChungHyup 0
  • Namespace change ATen

    Namespace change ATen

    namespace at:: in cpp-extension will change in PyTorch v1.0 to namespace torch:: (Cpp API). This will have to be changed when updating to newer version

    opened by AAlguacil 0
  • Enhanced readme

    Enhanced readme

    • Added some gifs (plume sim, done in VTK) and growth rate graph (showing there is still some improvements in buoyancy forces modelling).
    • Added a pretrained model (MultiScale Net with Long and Short Term Loss training). This allows to launch simulations (plume, Rayleigh Taylor) directly without training from scratch a model.
    • Added some comments and documentation in functions related to fluid simulator (pytorch/lib/fluid)
    opened by AAlguacil 0
  • Update 21/08

    Update 21/08

    -Change inference configuration: different test cases (cylinder, plume, Rayleigh Taylor instability) -At inference, two options for output: real time or save as vtk format for postprocessing with Paraview. -Introduction of viscosity as an additional step prior to velocity advection. -Bug correction of bcs and velocity Update

    opened by AAlguacil 0
Owner
JoliBrain
Pretty AI for solving real world problems
JoliBrain
Simulating Sycamore quantum circuits classically using tensor network algorithm.

Simulating the Sycamore quantum supremacy circuit This repo contains data we have obtained in simulating the Sycamore quantum supremacy circuits with

Feng Pan 46 Nov 17, 2022
Spectral Tensor Train Parameterization of Deep Learning Layers

Spectral Tensor Train Parameterization of Deep Learning Layers This repository is the official implementation of our AISTATS 2021 paper titled "Spectr

Anton Obukhov 12 Oct 23, 2022
TuckER: Tensor Factorization for Knowledge Graph Completion

TuckER: Tensor Factorization for Knowledge Graph Completion This codebase contains PyTorch implementation of the paper: TuckER: Tensor Factorization f

Ivana Balazevic 296 Dec 6, 2022
Pretty Tensor - Fluent Neural Networks in TensorFlow

Pretty Tensor provides a high level builder API for TensorFlow. It provides thin wrappers on Tensors so that you can easily build multi-layer neural networks.

Google 1.2k Dec 29, 2022
A torch.Tensor-like DataFrame library supporting multiple execution runtimes and Arrow as a common memory format

TorchArrow (Warning: Unstable Prototype) This is a prototype library currently under heavy development. It does not currently have stable releases, an

Facebook Research 536 Jan 6, 2023
Gradient-free global optimization algorithm for multidimensional functions based on the low rank tensor train format

ttopt Description Gradient-free global optimization algorithm for multidimensional functions based on the low rank tensor train (TT) format and maximu

null 5 May 23, 2022
(Py)TOD: Tensor-based Outlier Detection, A General GPU-Accelerated Framework

(Py)TOD: Tensor-based Outlier Detection, A General GPU-Accelerated Framework Background: Outlier detection (OD) is a key data mining task for identify

Yue Zhao 127 Jan 5, 2023
Code to reproduce the results in the paper "Tensor Component Analysis for Interpreting the Latent Space of GANs".

Tensor Component Analysis for Interpreting the Latent Space of GANs [ paper | project page ] Code to reproduce the results in the paper "Tensor Compon

James Oldfield 4 Jun 17, 2022
PyTorch framework, for reproducing experiments from the paper Implicit Regularization in Hierarchical Tensor Factorization and Deep Convolutional Neural Networks

Implicit Regularization in Hierarchical Tensor Factorization and Deep Convolutional Neural Networks. Code, based on the PyTorch framework, for reprodu

Asaf 3 Dec 27, 2022
Self-Correcting Quantum Many-Body Control using Reinforcement Learning with Tensor Networks

Self-Correcting Quantum Many-Body Control using Reinforcement Learning with Tensor Networks This repository contains the code and data for the corresp

Friederike Metz 7 Apr 23, 2022
mbrl-lib is a toolbox for facilitating development of Model-Based Reinforcement Learning algorithms.

mbrl-lib is a toolbox for facilitating development of Model-Based Reinforcement Learning algorithms. It provides easily interchangeable modeling and planning components, and a set of utility functions that allow writing model-based RL algorithms with only a few lines of code.

Facebook Research 724 Jan 4, 2023
OpenDILab RL Kubernetes Custom Resource and Operator Lib

DI Orchestrator DI Orchestrator is designed to manage DI (Decision Intelligence) jobs using Kubernetes Custom Resource and Operator. Prerequisites A w

OpenDILab 205 Dec 29, 2022
Jittor Medical Segmentation Lib -- The assignment of Pattern Recognition course (2021 Spring) in Tsinghua University

THU模式识别2021春 -- Jittor 医学图像分割 模型列表 本仓库收录了课程作业中同学们采用jittor框架实现的如下模型: UNet SegNet DeepLab V2 DANet EANet HarDNet及其改动HarDNet_alter PSPNet OCNet OCRNet DL

null 48 Dec 26, 2022
Python lib to talk to pylontech lithium batteries (US2000, US3000, ...) using RS485

python-pylontech Python lib to talk to pylontech lithium batteries (US2000, US3000, ...) using RS485 What is this lib ? This lib is meant to talk to P

Frank 26 Dec 28, 2022
A mini lib that implements several useful functions binding to PyTorch in C++.

Torch-gather A mini library that implements several useful functions binding to PyTorch in C++. What does gather do? Why do we need it? When dealing w

maxwellzh 8 Sep 7, 2022
Compare outputs between layers written in Tensorflow and layers written in Pytorch

Compare outputs of Wasserstein GANs between TensorFlow vs Pytorch This is our testing module for the implementation of improved WGAN in Pytorch Prereq

Hung Nguyen 72 Dec 20, 2022
Home repository for the Regularized Greedy Forest (RGF) library. It includes original implementation from the paper and multithreaded one written in C++, along with various language-specific wrappers.

Regularized Greedy Forest Regularized Greedy Forest (RGF) is a tree ensemble machine learning method described in this paper. RGF can deliver better r

RGF-team 364 Dec 28, 2022
🎯 A comprehensive gradient-free optimization framework written in Python

Solid is a Python framework for gradient-free optimization. It contains basic versions of many of the most common optimization algorithms that do not

Devin Soni 565 Dec 26, 2022
Minimal deep learning library written from scratch in Python, using NumPy/CuPy.

SmallPebble Project status: experimental, unstable. SmallPebble is a minimal/toy automatic differentiation/deep learning library written from scratch

Sidney Radcliffe 92 Dec 30, 2022