Skip to content

Fix FEM shape optimization not moving vertices [GH-1832] - #1879

Merged
shi-eric merged 1 commit into
NVIDIA:mainfrom
HuzaifaAbdulRehman:huzaifaabdulrehman/fem-shape-optimization-position-view
Sep 2, 2026
Merged

shi-eric merged 1 commit into
NVIDIA:mainfrom
HuzaifaAbdulRehman:huzaifaabdulrehman/fem-shape-optimization-position-view

Conversation

@HuzaifaAbdulRehman

@HuzaifaAbdulRehman HuzaifaAbdulRehman commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

warp/examples/fem/example_elastic_shape_optimization.py runs its whole optimization loop without ever moving a vertex. The loss is bit-identical on every iteration, the arch shape the example advertises never forms, and remesh() never finds an edge worth flipping because the mesh it is handed is the starting mesh.

Adam has no vec2 kernel, so the example builds a scalar view of its vec2 position array to hand to the optimizer. It built that view with wp.array(other_array, dtype=...), which copies. So the optimizer read a gradient buffer that nothing writes to, and wrote its updates into positions that nothing reads.

This is the example a reader lands on from docs/domain_modules/fem.rst and from the shape-optimization tile in README.md, so what it demonstrates right now is a loop that does nothing.

closes #1832

Changes

warp/examples/fem/example_elastic_shape_optimization.py

  • Build the optimizer's scalar parameter with view(wp.float32).flatten() instead of wp.array(..., dtype=wp.float32).flatten(). Both calls are zero-copy.
  • Drop the separate _vertex_positions_scalar.grad = ... line. view() already carries the gradient array through as a view of _vertex_positions.grad, and flatten() does the same, so assigning it again is redundant once the parent is a real view.

warp/tests/fem/test_fem_examples.py

  • Add test_elastic_shape_optimization_moves_vertices, an in-process test that asserts the optimizer parameter aliases the position array and that one step() moves at least one vertex.
  • Register it on get_test_devices(mode="basic") so it runs on CPU as well as CUDA, and adjust the module docstring, which said all example tests were CUDA-only.

changelog/1832.fixed.md

  • New fragment.

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.
  • I added a changelog fragment if this change affects users.

Correcting the issue

The issue reports two independent defects. The first is right. The second is not, and it is worth saying so, because a reader who believes it will go looking for a bug in warp.fem autodiff that is not there.

  1. The position gradient is zero. After tape.backward(loss), the gradient with respect to the positions array is identically zero in this setup, so even an in-place update would currently be a no-op.

The gradient is not zero. Measured on main at 608094f, CPU, resolution=8, by instrumenting wp.Tape.backward, Adam.step and wp.Tape.zero:

A  max|positions.grad| right after tape.backward   : 0.13600475
B  max|positions.grad| after projector+symmetrize  : 0.07234181
C  max|grad| Adam actually receives                : 0.00000000   <-- fed from the copy
D  max|param change| Adam applied to its buffer    : 0.00000000
F  max|positions.grad| before tape.zero()          : 0.07234181
G  max|positions.grad| after  tape.zero()          : 0.00000000   <-- what a caller sees post-step

step() ends with tape.zero(), which clears _vertex_positions.grad. Anyone who reads the gradient after step() returns, which is the natural place to look, reads zeros. That is a measurement artifact, not a missing derivative.

Shape derivatives through a Trimesh2D work fine on their own. Integrating 1.0 over the unit square split into two triangles gives an area of 1.0 and d(area)/d(positions) of ±0.5 per vertex, which is correct.

So there is one defect here, not two, and the aliasing fix is sufficient. That also matches the issue's own observation that the two behaviours reproduce identically with and without the fix for #1804.

Bug fix

Before this PR, with main at 608094f:

import numpy as np
import warp as wp
from warp.examples.fem.example_elastic_shape_optimization import Example

with wp.ScopedDevice("cpu"):
    example = Example(quiet=True, degree=1, resolution=25, mesh="tri", lr=1.0e-3)
    start = example._vertex_positions.numpy().copy()
    for i in range(5):
        loss = example.step()
        moved = np.abs(example._vertex_positions.numpy() - start).max()
        print(f"iter {i}: loss={loss:.12f}  max|dx|={moved:.3e}")
iter 0: loss=0.118115417659  max|dx|=0.000e+00
iter 1: loss=0.118115417659  max|dx|=0.000e+00
iter 2: loss=0.118115417659  max|dx|=0.000e+00
iter 3: loss=0.118115417659  max|dx|=0.000e+00
iter 4: loss=0.118115417659  max|dx|=0.000e+00

With this PR, same script, 120 iterations with the default remesh interval:

iter   0: loss=0.1181149557  max|dx|=1.000047e-03
iter  20: loss=0.0981881991  max|dx|=2.216834e-02
iter  40: loss=0.0896228105  max|dx|=4.048952e-02
iter  60: loss=0.0869978070  max|dx|=4.689008e-02
iter  80: loss=0.0853810534  max|dx|=4.902768e-02
iter 119: loss=0.0837662965  max|dx|=5.207330e-02

Both --mesh tri and --mesh deformed were broken, and both now produce identical trajectories, which is what you would expect given the two parametrizations describe the same positions.

Behavioural difference

The example now does real work where it previously did none, so it is slower per iteration and its output changes. Nothing else in the repository imports this module, and no test asserts on its numbers, so the blast radius is the example itself and its own test.

One thing I did not change. remesh() starts flipping edges once the vertices move, which is the behaviour it was written for but has apparently never had. Edge flips mutate _tri_vertex_indices in place, and #1804 reports that Trimesh2D side topology goes stale afterwards. That is a separate bug with its own open issue, and this PR neither fixes nor worsens it. It is now reachable through the default settings, where before the frozen mesh hid it.

Validation summary

Verified on Linux (WSL2, Ubuntu 26.04) against a CPU-only build of main at 608094f, python build_lib.py --no-cuda. I have no NVIDIA GPU, so nothing here was executed on CUDA. The new test is registered for CUDA devices too and I could not run that variant.

Red/green on the new test:

  • With the fix, test_elastic_shape_optimization_moves_vertices_cpu passes in 3.6s.
  • With the test kept and the one-line source change stashed, it fails on the first assertion: AssertionError: 153768448 != 140138112.
  • With the two pointer assertions also removed, so only the behavioural assertion remains, it still fails: AssertionError: np.float32(0.0) not greater than 0.0. Each half of the test catches the bug on its own.

Full default suite on this branch, python -m warp.tests:

Ran 3683 tests in 572.387s
OK (skipped=523)

Of the 523 skips, 505 are CUDA or multi-device tests that this machine has no hardware for. The other 18 are environment gaps rather than device gaps: 10 skip on JAX version too old, 3 want a warp-clang built with --sanitize=address, 2 are Windows-only path checks, and one each for missing rmm, missing torch, and an insufficient-free-memory guard.

FEM suite alone, python -m warp.tests -s autodetect -p 'test_fem*.py', run three ways:

  • Pristine checkout, warm kernel cache: Ran 98 tests / OK (skipped=34).
  • This branch, warm kernel cache: Ran 99 tests / OK (skipped=34). The extra test is the new one.
  • This branch, cold kernel cache: Ran 99 tests / OK (skipped=34).

Lint and format, at the versions pinned in .pre-commit-config.yaml:

  • ruff 0.16.5 check on both changed Python files: All checks passed!
  • ruff 0.16.5 format --check: 2 files already formatted
  • typos 1.50.0 on all three changed files: clean.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed CPU-based vertex movement during elastic shape optimization.
    • Vertex positions and gradients now remain linked correctly, allowing Adam updates to change the shape and reduce the loss.
  • Documentation

    • Added a changelog entry describing the CPU optimization fix.

@copy-pr-bot

copy-pr-bot Bot commented Aug 30, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Enterprise

Run ID: d863d9e2-9869-4cad-abac-1d2babb075f6

📥 Commits

Reviewing files that changed from the base of the PR and between 03900ce and 2adfd32.

📒 Files selected for processing (2)
  • changelog/1832.fixed.md
  • warp/examples/fem/example_elastic_shape_optimization.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • changelog/1832.fixed.md
  • warp/examples/fem/example_elastic_shape_optimization.py

Included review availability: Your plan provides up to 12 included reviews per hour; 11 remain after this review.


📝 Walkthrough

Walkthrough

The FEM elastic shape optimization example now gives Adam a zero-copy flattened view of vertex positions. The changelog documents that detached position and gradient copies prevented CPU vertex movement.

Changes

Elastic shape optimization

Layer / File(s) Summary
Shared vertex-position storage
warp/examples/fem/example_elastic_shape_optimization.py, changelog/1832.fixed.md
The optimizer now uses a zero-copy flattened float32 view of _vertex_positions. The changelog records the detached-copy issue.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Merge Risk: ⚪ Minimal · up to 2adfd

This localized fix makes the shape-optimization example update its vertex positions and adds regression coverage; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the FEM shape optimization bug and the vertex movement fix.
Linked Issues check ✅ Passed The changes address issue #1832 by replacing the copying scalar conversion with a zero-copy view and flatten operation, allowing Adam to update the actual vertex positions. The changelog also document…
Out of Scope Changes check ✅ Passed The changes are limited to the FEM example and its related changelog entry. They directly support the linked issue and stated pull request objectives.
Full details: Linked Issues check

Explanation

The changes address issue #1832 by replacing the copying scalar conversion with a zero-copy view and flatten operation, allowing Adam to update the actual vertex positions. The changelog also documents the fix and the gradient observation clarification.

Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR fixes the FEM elastic shape-optimization example by giving Adam a zero-copy flattened view of the vertex positions whose gradient remains linked to the original array.

  • Replaces detached scalar copies with a chained view() and flatten().
  • Removes the now-redundant explicit gradient assignment.
  • Adds a changelog fragment describing the correction.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
warp/examples/fem/example_elastic_shape_optimization.py Uses an aliased scalar parameter and gradient view so Adam updates the underlying vertex positions.
changelog/1832.fixed.md Records the user-visible correction to the shape-optimization example.

Reviews (4): Last reviewed commit: "Fix FEM shape optimization not moving ve..." | Re-trigger Greptile

Comment thread changelog/1832.fixed.md Resolved
Comment thread warp/tests/fem/test_fem_examples.py Resolved
@shi-eric

shi-eric commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Great, please rebase with main so we can get this merged.

@HuzaifaAbdulRehman
HuzaifaAbdulRehman force-pushed the huzaifaabdulrehman/fem-shape-optimization-position-view branch from 2adfd32 to fa2d195 Compare September 2, 2026 18:08
@HuzaifaAbdulRehman

Copy link
Copy Markdown
Contributor Author

Rebased onto main, should be ready now. Thanks for the reviews.

@shi-eric

shi-eric commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Sorry, I forgot to ask: Can you also squash down to a single commit?

The example gives Adam a scalar view of its vec2 positions, since Adam
has no vec2 kernel. wp.array(a, dtype=...) copies on CPU rather than
aliasing, so Adam updated a detached buffer and the mesh never moved.
Build the view with view().flatten() instead: it is zero-copy and
carries the gradient array along, so the separate .grad line is gone.

Signed-off-by: Huzaifa Abdul Rehman <[email protected]>
@HuzaifaAbdulRehman

Copy link
Copy Markdown
Contributor Author

Done, squashed to a single commit.

@HuzaifaAbdulRehman
HuzaifaAbdulRehman force-pushed the huzaifaabdulrehman/fem-shape-optimization-position-view branch from fa2d195 to 16a0e37 Compare September 2, 2026 18:19
@shi-eric
shi-eric merged commit 16a0e37 into NVIDIA:main Sep 2, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FEM elastic shape optimization example never moves its vertices (optimizer updates a copy; position gradient is zero)

2 participants