Skip to main content

License: MIT PyPI - Python Version PyPI - Version Tests Binder DOI

Documentation · Examples · Changelog

torch-fem

torch-fem is a simple GPU-accelerated differentiable finite element solver for solid mechanics built on PyTorch. Automatic differentiation provides exact sensitivities of simulation results with respect to material parameters, geometry, loads, etc. without hand-derived adjoint formulations. It is aimed at researchers in computational mechanics who need gradients through FEM solvers for tasks such as optimization, inverse problems, and machine-learning-augmented simulation.

Features

  • Elements

    • 1D: Bar1, Bar2
    • 2D: Quad1, Quad2, Tria1, Tria2
    • 3D: Hexa1, Hexa2, Tetra1, Tetra2
    • Shell: Flat-facet Quad1, Tria1
  • Material models

    • Linear elasticity (isotropic, transverse isotropic, orthotropic)
    • Isotropic small strain plasticity
    • Isotropic small strain damage
    • Hyperelasticity (via automatic differentiation of their energy function)
    • Thermal conductivity (isotropic, orthotropic)
    • Custom user material interface
  • Utilities

    • Assembly of several models coupled by kinematic constraints
    • Homogenization of orthotropic elasticity for composites
    • Composite laminates for shells
    • Simple structured meshing
    • I/O to and from other mesh formats via meshio

Installation

You may install torch-fem via pip with

pip install torch-fem

To run the example notebooks, install with the notebook extra (pip install torch-fem[notebook]). For GPU acceleration, install PyTorch with CUDA support - see the installation guide for details.

Minimal example

This is a minimal example of how to use torch-fem to solve a very simple planar cantilever problem.

import torch
from torchfem import Planar
from torchfem.materials import IsotropicElasticityPlaneStress

torch.set_default_dtype(torch.float64)

# Material
material = IsotropicElasticityPlaneStress(E=1000.0, nu=0.3)

# Nodes and elements
nodes = torch.tensor([[0., 0.], [1., 0.], [2., 0.], [0., 1.], [1., 1.], [2., 1.]])
elements = torch.tensor([[0, 1, 4, 3], [1, 2, 5, 4]])

# Create model
cantilever = Planar(nodes, elements, material)

# Load at tip [Node_ID, DOF]
cantilever.forces[5, 1] = -1.0

# Constrained displacement at left end [Node_IDs, DOFs]
cantilever.constraints[[0, 3], :] = True

# Show model
cantilever.plot(node_markers=True, node_labels=True)

This creates a minimal planar FEM model:

minimal
# Solve
u, f, σ, F, α = cantilever.solve()

# Plot displacement magnitude on deformed state
cantilever.plot(u, node_property=torch.norm(u, dim=1))

This solves the model and plots the result:

minimal

If we want to compute gradients through the FEM model, we simply need to define the variables that require gradients. Automatic differentiation is performed through the entire FE solver. Rather than differentiating through individual solver iterations or Newton iterations (this would explode in memory and autograd graph size) though, the implicit function theorem is used to formulate an adjoint backward for solve().

# Enable automatic differentiation
cantilever.thickness.requires_grad = True
u, f, _, _, _ = cantilever.solve(differentiable_parameters=cantilever.thickness)

# Compute sensitivity of compliance w.r.t. element thicknesses
compliance = torch.inner(f.ravel(), u.ravel())
torch.autograd.grad(compliance, cantilever.thickness)[0]

This returns the sensitivity of the compliance with respect to the thickness of each element:

tensor([-0.0208, -0.0053])

Both entries are negative, so adding material anywhere stiffens the structure, but the element at the clamped end is about four times as effective as the one at the tip.

Basic examples

The subdirectory examples/basic contains a couple of Jupyter notebooks demonstrating the use of torch-fem for trusses, planar problems, shells, and solids. You may click on the examples to check out the notebooks online.

Planar plate with a hole plasticity example
Plasticity in a plate with hole: Isotropic linear hardening model for plane-stress or plane-strain.
Finite-strain cantilever example
Finite strain cantilever: Hyperelastic model in Total Lagrangian Formulation.
Shell modal analysis example Implicit gyroid structure example
Modal analysis of a clamped shell: Natural frequencies and mode shapes of a fully clamped flat shell. Implicit gyroid structure: A voxel mesh is carved into a triply periodic minimal surface with a signed distance function.

Optimization examples

The subdirectory examples/optimization demonstrates the use of torch-fem for optimization of structures (e.g. topology optimization, composite orientation optimization). You may click on the examples to check out the notebooks online.

Truss shape optimization example Planar fillet shape optimization example
Shape optimization of a truss: The top nodes are moved and MMA + autograd is used to minimize the compliance. Shape optimization of a fillet: The shape is morphed with shape basis vectors and MMA + autograd is used to minimize the maximum stress.
3D jet engine bracket topology optimization result Combined topology and orientation optimization example
Topology optimization of a jet engine bracket: The optimized part is cut out of the design space at an iso-value of the density. Combined topology and orientation optimization: Compliance is minimized by optimizing fiber orientation and density of an anisotropic material.
Fiber orientation optimization example 3D heat sink topology optimization example
Fiber orientation optimization of a plate with a hole Compliance is minimized by optimizing the fiber orientation of an anisotropic material. Topology optimization of a 3D heat sink: Conductive material is distributed in a cube with a homogeneous heat source to minimize thermal compliance.
Property field recovery example Pressure vessel free size optimization example
Recovery of a property field: A direct optimization and a neural field recover a graded elastic modulus from noisy observations of the displacement. Free size optimization of a pressure vessel: Each element's shell thickness is a design variable and a fixed amount of material is redistributed to minimize compliance.

Performance

torch-fem solves problems with millions of degrees of freedom: a linear elastic hexahedral cube model with 1.5 million DOFs assembles and solves in about four seconds on a consumer GPU (RTX 4090, float64). Detailed CPU and GPU benchmarks for timing and memory are reported in the performance documentation and can be reproduced with the scripts in benchmarks/.

Citing torch-fem

If you use torch-fem in your research, please cite it as follows:

@software{torchfem,
    author = {Meyer, Nils},
    title  = {torch-fem: GPU accelerated differentiable finite elements for solid mechanics with PyTorch},
    doi    = {10.5281/zenodo.20306384},
    url    = {https://github.com/meyer-nils/torch-fem},
}

Contributing

Contributions are welcome! Please check out the contributing guide for the development workflow. Bug reports, feature requests, and usage questions are all welcome in the issue tracker - see the support guide for what to include.

Alternatives

torch-fem focuses on solid mechanics and thermal problems. It provides sensitivities through PyTorch autograd, which makes it easy to drop into optimization loops and ML pipelines. It is the natural choice if you are working in the PyTorch ecosystem. Depending on your needs, one of these Python FEM tools may serve you better:

Library Stars Focus Differentiable Consider it over torch-fem when…
FEniCSx (DOLFINx) stars General PDEs, UFL weak forms, MPI via dolfin-adjoint you need arbitrary weak forms or massively parallel distributed runs
SfePy stars General multiphysics, pure Python — you need a broad range of PDE applications on CPU
JAX-FEM stars Differentiable FEM, JAX / GPU ✅ your stack is built on JAX rather than PyTorch
Firedrake stars General PDEs, UFL weak forms via pyadjoint you want a UFL form language with automated adjoints for multiphysics
scikit-fem stars Lightweight assembly, NumPy/SciPy — you want minimal dependencies and full control over custom forms
FElupe stars Finite-strain solid mechanics partially via tensortrax you work with hyperelastic / finite-strain solids
Nutils stars High-order / immersed methods — you research advanced or immersed discretizations including IGA
PyTorch-FEA stars Biomechanics, PyTorch ✅ you work on soft-tissue / inverse biomechanics

Not sure which to pick? The mosaic differentiable-physics benchmark suite compares several of these solvers on gradient accuracy and forward/adjoint performance under a common interface.

Metadata

Release files for torch-fem 0.12.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for torch-fem 0.12.1
File Size Uploaded
torch_fem-0.12.1.tar.gz 3.1 MB Details

Built distribution (wheel)

Table of built distributions (wheels) for torch-fem 0.12.1
File Interpreter ABI Platform
torch_fem-0.12.1-py3-none-any.whl Python 3 none any Details

Total release size: 6.1 MB

Release files / torch_fem-0.12.1.tar.gz

Download URL torch_fem-0.12.1.tar.gz
Size 3.1 MB
Tags Source
SHA-256 checksum
How to use checksums
471de0e2557241e27b3cc0b5bc9300809cb7eb65aa6ad430179a18e585ceb6af
BLAKE2b-256 checksum
How to use checksums
2c47cc425be87d4bc73bb2f067eaa11708039f9d3cfd52920c93dca5c7eab92c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 22, 2026.

Transparency log

Release files / torch_fem-0.12.1-py3-none-any.whl

Download URL torch_fem-0.12.1-py3-none-any.whl
Size 3.0 MB
Tags Python 3
SHA-256 checksum
How to use checksums
b7336d3465b5ba705a622d10e57f2930b558528749e6d31248a1ae9fd95dbfd2
BLAKE2b-256 checksum
How to use checksums
db1afbc5404f7db9441db85c0cbb84dffd3f8b1eef4b101550cb2ff92f01adf7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 22, 2026.

Transparency log

Release history Release notifications | RSS feed

0.13.1

2 release files

0.13.0

2 release files

This release

0.12.1 This release

2 release files

0.12.0

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.5

2 release files

0.7.4

2 release files

0.7.3

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.3

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.0

2 release files

0.3.8

2 release files

0.3.7

2 release files

0.3.5

2 release files

0.3.4

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.16

2 release files

0.1.14

2 release files

0.1.13

2 release files

0.1.12

2 release files

0.1.11

2 release files

0.1.10

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.0

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page