Skip to content

PERF: Keep the fixed image value of each metric sample - #7223

Open
gdevenyi wants to merge 1 commit into
InsightSoftwareConsortium:mainfrom
gdevenyi:perf-metric-fixed-sample-cache
Open

gdevenyi wants to merge 1 commit into
InsightSoftwareConsortium:mainfrom
gdevenyi:perf-metric-fixed-sample-cache

Conversation

@gdevenyi

@gdevenyi gdevenyi commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

With a sampled point set and a linear fixed transform, image metrics now keep each sample's fixed image value instead of interpolating it on every evaluation. ANTs antsAI runs 14–18% faster. In-place fixed image edits now need Modified().

What changes
  • Each evaluation used to map every sample into the fixed image and interpolate it again. With a fixed transform made only of linear transforms (the default identity included), these results don't change between evaluations. In a callgrind profile of antsAI, the fixed side was about 25% of the instructions.
  • ImageToImageMetricv4 keeps, per sample:
    • a state byte (unknown, valid or invalid);
    • the fixed value;
    • the mapped fixed point, except when the fixed transform is the identity, where the point is mapped again (a copy).
  • The first evaluation fills the samples; each work unit fills the ones it processes. A sample that is not filled is computed as before.
  • Before each evaluation, the threader's BeforeThreadedExecution() has the metric clear the samples when any of these changes:
    • the fixed image, fixed interpolator or fixed mask (pointer or modified time);
    • the sampled point set, or its points container (SetPoint() modifies only the container);
    • the fixed transform, or any transform inside a composite fixed transform (a CompositeTransform keeps its modified time when one of its transforms changes).
  • Initialize() clears them too.
  • The cache is off for any non-linear fixed transform, e.g. a displacement field, which can change in place without a new modified time.
  • Only the base ImageToImageMetricv4GetValueAndDerivativeThreader uses the cache: its sparse loop passes the sample index to ProcessVirtualPoint() through the per-thread data. This covers MeanSquares, Mattes, Demons and the derivative pass of joint histogram MI. Threaders that override ProcessVirtualPoint() (Correlation, ANTS neighborhood correlation) return false from the new UsesFixedSampleCache(), so the metric does not allocate the cache for them; the joint histogram PDF pass has its own loop. These stay unchanged.
  • Results change in one case: an edit of the fixed image or fixed mask image buffer in place, without Modified(), is no longer seen by a metric that was already evaluated. A migration record (20261124_MetricFixedSampleCache.yaml) says so.
  • Memory: 5 bytes per sample for float images with an identity fixed transform, or 29 with a linear one.
Testing

Minimal build (Module_ITKMetricsv4, Module_ITKRegistrationMethodsv4, Module_ITKOptimizersv4, tests on), GCC 15:

  • New itkImageToImageMetricv4FixedSampleCacheGTest.cxx compares, with EXPECT_EQ, a metric that was already evaluated against a new metric:
    • repeated evaluations, including GetValue() before GetValueAndDerivative(), for MeanSquares, Mattes, Demons, Correlation and joint histogram MI, at 1 and 4 work units (derivatives too at 4, except Mattes and Demons, whose multi-work-unit derivatives vary in the last bits on main);
    • with Demons, which reads the fixed gradient at the mapped points: repeated evaluations with an unchanged affine or composite fixed transform, which read the kept mapped points, then after changing that transform, at 1 and 4 work units;
    • after changing the fixed image values, the fixed mask, and the sampled points;
    • with a displacement field fixed transform edited in place;
    • an in-place fixed image edit without Modified(), which keeps the old values, then is seen after Modified().
  • On main's headers, 11 of 12 tests pass; the in-place-edit test fails, as it pins the new behavior.
  • Each broken variant fails its test: no composite walk, no transform time, no fixed image, no mask, or no points container in the key; displacement fields cached; cached value off by 1; the mapped point of another sample; cache never enabled. The off-by-1 variant fails MeanSquares, Mattes, Demons and joint histogram MI, which shows those read the cache.
  • 300 repeated runs of the 12 tests pass.
  • ctest for the three modules: 365/365 pass, including KWStyle.

ANTs on ITK 537ce087, alternating runs on 32 threads unless noted:

main this PR result
antsAI brain-extraction search (64³, Regular 0.2, 243 starts) 6.5 s 5.6 s same transform
same, 1 thread 51.2 s 41.8 s same transform
antsRegistration rigid + affine, Mattes, Regular 0.25 (117×109×103) 1.31 s 1.21 s within main's own run-to-run differences

Peak RSS is unchanged within noise.

AI assistance
  • Tool: Claude Code (claude-opus-5-5)
  • Role: profiled antsAI, designed and wrote the change and the tests, and ran the builds, tests and benchmarks
  • All code was reviewed and tested locally before committing

@github-actions github-actions Bot added type:Infrastructure Infrastructure/ecosystem related changes, such as CMake or buildbots type:Performance Improvement in terms of compilation or execution time type:Testing Ensure that the purpose of a class is met/the results on a wide set of test cases are correct area:Registration Issues affecting the Registration module labels Nov 20, 2026
@gdevenyi

Copy link
Copy Markdown
Contributor Author

@ntustison, could you review this when you have time? It came out of an audit of antsAI: with sampled metrics, about a quarter of the work was re-interpolating the fixed image at the same sample points on every evaluation. antsAI's brain-extraction search is 14% faster on 32 threads (18% on 1), with the same transform.

@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · Fix change tracking for the fixed mask's world transform before merging.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change affects sampled-point evaluations across ITK's metrics-v4 registration workflows.

Fix change tracking for the fixed mask's world transform before merging.

Findings

  1. P1 Moved masks keep old decisions ▶

Summary

The PR keeps fixed image values between sampled metric evaluations when the fixed transform is linear.

  • Sampled-point metrics reuse fixed-image results when their inputs stay unchanged.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Start metric evaluation] --> B{Threader uses cache and fixed transform is linear?}
  B -->|No| C[Evaluate fixed points normally]
  B -->|Yes| D{Tracked inputs changed?}
  D -->|Yes| E[Clear saved samples]
  D -->|No| F[Keep saved samples]
  E --> G[Process each sample]
  F --> G
  G --> H{Sample already saved?}
  H -->|No| I[Map point and save fixed value and validity]
  H -->|Yes| J[Reuse fixed value and validity]
  I --> K[Evaluate moving image and metric]
  J --> K
Loading

Reviews (4) · Last reviewed commit: "PERF: Keep the fixed image value of each..." · Reviewed by Greptile

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @gdevenyi, a clean way to remove the repeated fixed-side interpolation. Three should-fix items are below as line comments: a results change that needs a migration record, Demons using the cache without a test, and Greptile's two findings, which both hold on the code and are not yet answered (the unused allocation also applies to the sparse ANTS neighborhood correlation threader, which has its own ProcessVirtualPoint). The rest are nits.

On the data layout: parallel vectors or a per-sample record

I asked whether one per-sample record would serve better than three vectors that must stay the same length. Reasoned from the code, not measured: separate arrays (as written) are the better layout for the samples.

  • Identity fixed transform (the default): 5 B per sample here, against 8 B for a padded {value, state} record; with a linear transform, 29 B against 32 B.
  • ThreadedIndexedContainerPartitioner gives each work unit a contiguous index range, so each array is read in a straight line, which the prefetcher handles well.
  • After a hit, the moving transform, moving interpolation, gradient, Jacobian, and (for Mattes) the PDF update cost hundreds of nanoseconds per sample; the cache read is a nanosecond or two, so its layout cannot show up in timing.

Optionally, a small private class that owns the three arrays, their resizing and clearing, and an explicit identity flag would keep them in step, and replace m_FixedSamplePoints.empty() as the identity marker.

Checked and sound
  • Invalidation: image origin, spacing, and direction setters, mask spatial objects, MultiTransform edits (walked recursively), SetCenter/SetFixedParameters, a replaced transform (pointer in the key), toggling UseSampledPointSet, and Initialize().
  • The hit path: TransformAndEvaluateFixedPoint() zeroes the value and maps the point before any early return, so nothing uninitialized is stored; the identity hit maps the point exactly as a miss does, so the fixed gradient is unchanged.
  • Threading: each work unit writes its own indices of a uint8_t array, and threads are joined between evaluations.

@hjmjohnson
hjmjohnson marked this pull request as draft November 22, 2026 23:57
@gdevenyi
gdevenyi force-pushed the perf-metric-fixed-sample-cache branch from 9e52158 to 8c6b9e0 Compare November 24, 2026 14:04
@github-actions github-actions Bot added the area:Documentation Issues affecting the Documentation module label Nov 24, 2026
@gdevenyi

Copy link
Copy Markdown
Contributor Author

Force-push 9e521584f4 → 8c6b9e02fb, review fixes only, no rebase. Changes:

  • the cache is not allocated for threaders that override ProcessVirtualPoint();
  • a migration record, plus a test of in-place edits without Modified();
  • Demons is in the typed tests;
  • repeated unchanged evaluations with affine and composite fixed transforms, at 1 and 4 work units;
  • 4-work-unit derivatives for MeanSquares, Correlation and joint histogram MI;
  • the two nits.

All 12 tests pass 300 times in a row, and ctest for the three modules passes 365/365. Every broken variant fails, including two new ones: the mapped point of another sample, and a cache that is never enabled.

I kept the three arrays as they are and did not add the optional class that owns them.

Found while testing, and also on main: with sparse sampling and a displacement field moving transform, BeforeThreadedExecution() points every work unit's Derivatives at the shared m_DerivativeResult. Samples that round to the same voxel in different work units then race on +=. Dense sampling partitions by region, so it does not hit this. I left it alone here; I can open an issue if you want one.

@gdevenyi

Copy link
Copy Markdown
Contributor Author

Opened #7234 for the sparse derivative race, with a standalone reproduction against main.

@gdevenyi
gdevenyi force-pushed the perf-metric-fixed-sample-cache branch from 8c6b9e0 to a48fcd1 Compare November 25, 2026 04:21
@gdevenyi

Copy link
Copy Markdown
Contributor Author

Force-push 8c6b9e02fb → a48fcd117e: removes a local FieldTransformType alias in IsNotUsedWithADisplacementFieldFixedTransform that shadowed the new namespace-level one. Apple clang reported it as -Wshadow, which failed the two ARMBUILD jobs; their tests had all passed (5208/5208 and 5018/5018). No other change.

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough round: every round-1 item checks out at this head, including the migration record, Demons coverage, the SampleIndex initializer, and the repeat-evaluation tests. One should-fix remains, on the Correlation opt-out. Nothing was built or run; reasoned from the code.

Optional nits (no change needed to merge)
  • Migration record: the template's rubric puts a ResultsChange at impact: medium unless details says why few users would notice; either add that sentence or raise it. An actions: line would also help downstream code: "A threader that overrides ProcessVirtualPoint() without calling the superclass should override UsesFixedSampleCache() to return false."
  • Test comments: several // blocks run to two or three lines (test lines 19-21, 115-116, 125, 164-165), and the comment at 238-239 is repeated at 267-268 (Documentation/AI/prose-budget.md).
  • Commit body: lines 1 and 8 are 73 characters (limit 72).

@gdevenyi
gdevenyi force-pushed the perf-metric-fixed-sample-cache branch from a48fcd1 to 6b88a85 Compare November 26, 2026 03:38
@gdevenyi

Copy link
Copy Markdown
Contributor Author

Force-push a48fcd117e → 6b88a853eb, review fixes only, no rebase:

  • the Correlation helper threader opts out of the cache (the should-fix);
  • std::uint8_t with <cstdint>;
  • the migration record says why few users should notice at low impact, and has an actions: line for threaders that override ProcessVirtualPoint();
  • the test comments are cut to one line each, and the repeated one is shortened;
  • the commit body is re-wrapped to 72 columns.

All 12 tests pass 50 runs in a row, the three modules' ctest passes 365/365, and clang -Wall -Wextra -Wshadow is clean on the test.

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified at 6b88a85: the helper threader opts out of the cache, and all three ProcessVirtualPoint() overrides (both Correlation threaders and ANTS neighborhood correlation) now return false from UsesFixedSampleCache(). Max review is clean; requesting Greptile. Two optional nits, no need to block on them:

Optional nits
  • itkImageToImageMetricv4.h:31-32: #include <cstdint> sits between ITK includes, after a blank line, with three "itk*.h" includes still below it. .clang-format has SortIncludes: Never, so pre-commit will not move it. Put the three ITK includes straight after the threader header, then a blank line, then <cstdint>.
  • itkImageToImageMetricv4FixedSampleCacheGTest.cxx: the Demons comment (lines 232 and 260) and "Unchanged: reads the kept mapped points." (241 and 269) each appear twice; dropping the second copies, or moving the Demons note into MakeMetric<DemonsMetricType>, would leave one of each.

@hjmjohnson
hjmjohnson dismissed their stale review November 26, 2026 11:46

Requested changes are addressed at 6b88a85; dismissing my change request.

@hjmjohnson

Copy link
Copy Markdown
Member

@greptileai review

@gdevenyi
gdevenyi marked this pull request as ready for review November 26, 2026 19:30
Copilot AI balanced review requested due to automatic review settings November 26, 2026 19:30

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@hjmjohnson
hjmjohnson self-requested a review November 30, 2026 18:16

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm addressing the greptile issue in a different PR. This will need to stack on top of that, and also be be tested in a forest of ITK tools. I'll start the forest build later today.

@hjmjohnson

Copy link
Copy Markdown
Member

@gdevenyi I force-pushed a plain rebase of this branch onto #7277; your commit is unchanged (git range-diff shows =). #7277 fixes the cause of Greptile's P1 ("Spline changes are ignored"): BSplineInterpolateImageFunction::SetSplineOrder() never called Modified(), so this cache's key could not see the change. This PR now depends on #7277 merging first.

Evidence

A temporary probe (not committed) using this PR's test helpers: a sampled MeanSquares metric with a B-spline fixed interpolator at order 1 is evaluated; then SetSplineOrder(3) and SetInputImage() are called on the interpolator, without Initialize(), and it is evaluated again and compared with a fresh order 3 metric.

You may want to add that check as a regression test here; it is short, and I can paste it.

@github-actions github-actions Bot added area:Core Issues affecting the Core module area:Filtering Issues affecting the Filtering module labels Nov 30, 2026
@gdevenyi
gdevenyi force-pushed the perf-metric-fixed-sample-cache branch from 3ecbb65 to a8c6c32 Compare November 30, 2026 22:19

@gdevenyi gdevenyi left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Force-push 3ecbb65db4 → a8c6c32d1d, on top of your rebase onto #7277. Only my commit changed:

  • Regression test: FollowsTheFixedInterpolatorSplineOrder, your probe as a test (see the thread). Without #7277's Modified() it gets 0.8443 where 0.8831 is expected.
  • Optional nits from your 11-26 review:
    • <cstdint> now comes after the ITK includes in itkImageToImageMetricv4.h;
    • the repeated Demons and "Unchanged" comments in the test now appear once each.
  • Tests: the 13 cache tests pass 10 runs in a row, and the three modules' ctest passes 379/379 (GCC 15).

Thanks for tracing the spline-order problem to its cause.

With a sampled point set, each evaluation of an image metric mapped
every sample into the fixed image and interpolated it again, though with
a linear fixed transform these results do not change between
evaluations. ImageToImageMetricv4 now keeps them per sample, and
recomputes them when the fixed image, interpolator, mask, transform
(including those inside a composite) or sampled points are modified;
in-place buffer edits need Modified(), as the migration record says.
Threaders that override ProcessVirtualPoint() (the Correlation ones,
ANTS neighborhood correlation) do not allocate the cache. antsAI's
brain-extraction search is 14% faster on 32 threads and 18% on 1, with
the same transform.
@hjmjohnson
hjmjohnson force-pushed the perf-metric-fixed-sample-cache branch from a8c6c32 to 68e8ad9 Compare November 30, 2026 22:53
@github-actions github-actions Bot removed area:Core Issues affecting the Core module area:Filtering Issues affecting the Filtering module labels Nov 30, 2026

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified at 68e8ad9 (plain rebase of a8c6c32 onto main, now that #7277 is merged; git range-diff shows =). The spline-order test fails without #7277's fix and passes with it, and both earlier nits are fixed. Max review is clean; nothing is open on the code, so I am dismissing my change request. I will still run the downstream forest build before this merges. Thanks @gdevenyi.

Optional nits, no need to block on them
  • PR body: the test counts are stale ("11 of 12", "300 repeated runs of the 12 tests"); the cache test file now has 8 tests, including FollowsTheFixedInterpolatorSplineOrder.
  • itkImageToImageMetricv4FixedSampleCacheGTest.cxx:418-422 builds a displacement field by hand, repeating MakeFieldTransform() (51-60); and the 1.5x fixed-buffer loop appears twice (287-291, 338-342).
  • SizeType::Filled(20) appears four times in the test (55, 66, 359, 419); one named constant would do.
  • InspectFixedTransform (itkImageToImageMetricv4.h:918) returns "all linear" and writes identity, which the caller must preset to true (.hxx:332); its comment does not mention identity.
  • .hxx uses std::max and the header std::vector without including <algorithm> or <vector>; both arrive transitively today.

@hjmjohnson
hjmjohnson dismissed their stale review December 1, 2026 01:51

Requested changes are addressed (#7277 merged, spline-order test verified); dismissing my change request.

@hjmjohnson

Copy link
Copy Markdown
Member

@greptileai review

FixedSampleCacheKey key;
for (const Object * const object : { static_cast<const Object *>(this->m_FixedImage.GetPointer()),
static_cast<const Object *>(this->m_FixedInterpolator.GetPointer()),
static_cast<const Object *>(this->m_FixedImageMask.GetPointer()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Moved masks keep old decisions

UpdateFixedSampleCache() misses changes to the mask's world transform. After an evaluation, a caller can move the mask through GetModifiableObjectToWorldTransform() and call GetObjectToWorldTransformInverse() to refresh its inverse, as documented. Neither call changes the mask's GetMTime(), so the key still matches. The metric then reuses old mask decisions and returns values and derivatives based on the mask's previous position.

Include the mask transforms' modified times in the key and add a test for this path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:Documentation Issues affecting the Documentation module area:Registration Issues affecting the Registration module type:Infrastructure Infrastructure/ecosystem related changes, such as CMake or buildbots type:Performance Improvement in terms of compilation or execution time type:Testing Ensure that the purpose of a class is met/the results on a wide set of test cases are correct

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants