Repository navigation
Fix FEM shape optimization not moving vertices [GH-1832] - #1879
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: Your plan provides up to 12 included reviews per hour; 11 remain after this review. 📝 WalkthroughWalkthroughThe 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. ChangesElastic shape optimization
Estimated code review effort: 1 (Trivial) | ~5 minutes Merge Risk: ⚪ Minimal · up to 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)
✅ Passed checks (4 passed)
Full details: Linked Issues checkExplanation The changes address issue Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Greptile SummaryThe 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.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains. Important Files Changed
Reviews (4): Last reviewed commit: "Fix FEM shape optimization not moving ve..." | Re-trigger Greptile |
|
Great, please rebase with |
2adfd32 to
fa2d195
Compare
|
Rebased onto main, should be ready now. Thanks for the reviews. |
|
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]>
|
Done, squashed to a single commit. |
fa2d195 to
16a0e37
Compare
Description
warp/examples/fem/example_elastic_shape_optimization.pyruns 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, andremesh()never finds an edge worth flipping because the mesh it is handed is the starting mesh.Adam has no
vec2kernel, so the example builds a scalar view of itsvec2position array to hand to the optimizer. It built that view withwp.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.rstand from the shape-optimization tile inREADME.md, so what it demonstrates right now is a loop that does nothing.closes #1832
Changes
warp/examples/fem/example_elastic_shape_optimization.pyview(wp.float32).flatten()instead ofwp.array(..., dtype=wp.float32).flatten(). Both calls are zero-copy._vertex_positions_scalar.grad = ...line.view()already carries the gradient array through as a view of_vertex_positions.grad, andflatten()does the same, so assigning it again is redundant once the parent is a real view.warp/tests/fem/test_fem_examples.pytest_elastic_shape_optimization_moves_vertices, an in-process test that asserts the optimizer parameter aliases the position array and that onestep()moves at least one vertex.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.mdChecklist
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.femautodiff that is not there.The gradient is not zero. Measured on
mainat 608094f, CPU,resolution=8, by instrumentingwp.Tape.backward,Adam.stepandwp.Tape.zero:step()ends withtape.zero(), which clears_vertex_positions.grad. Anyone who reads the gradient afterstep()returns, which is the natural place to look, reads zeros. That is a measurement artifact, not a missing derivative.Shape derivatives through a
Trimesh2Dwork fine on their own. Integrating1.0over the unit square split into two triangles gives an area of 1.0 andd(area)/d(positions)of±0.5per 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
mainat 608094f:With this PR, same script, 120 iterations with the default remesh interval:
Both
--mesh triand--mesh deformedwere 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_indicesin place, and #1804 reports thatTrimesh2Dside 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
mainat 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:
test_elastic_shape_optimization_moves_vertices_cpupasses in 3.6s.AssertionError: 153768448 != 140138112.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: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 awarp-clangbuilt with--sanitize=address, 2 are Windows-only path checks, and one each for missingrmm, missingtorch, and an insufficient-free-memory guard.FEM suite alone,
python -m warp.tests -s autodetect -p 'test_fem*.py', run three ways:Ran 98 tests/OK (skipped=34).Ran 99 tests/OK (skipped=34). The extra test is the new one.Ran 99 tests/OK (skipped=34).Lint and format, at the versions pinned in
.pre-commit-config.yaml:ruff 0.16.5 checkon both changed Python files:All checks passed!ruff 0.16.5 format --check:2 files already formattedtypos 1.50.0on all three changed files: clean.Summary by CodeRabbit
Bug Fixes
Documentation