Repository navigation
Conversation
|
@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. |
[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
|
hjmjohnson
left a comment
There was a problem hiding this comment.
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. ThreadedIndexedContainerPartitionergives 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,
MultiTransformedits (walked recursively),SetCenter/SetFixedParameters, a replaced transform (pointer in the key), togglingUseSampledPointSet, andInitialize(). - 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_tarray, and threads are joined between evaluations.
9e52158 to
8c6b9e0
Compare
|
Force-push
All 12 tests pass 300 times in a row, and I kept the three arrays as they are and did not add the optional class that owns them. Found while testing, and also on |
|
Opened #7234 for the sparse derivative race, with a standalone reproduction against |
8c6b9e0 to
a48fcd1
Compare
|
Force-push |
hjmjohnson
left a comment
There was a problem hiding this comment.
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: mediumunlessdetailssays why few users would notice; either add that sentence or raise it. Anactions:line would also help downstream code: "A threader that overridesProcessVirtualPoint()without calling the superclass should overrideUsesFixedSampleCache()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).
a48fcd1 to
6b88a85
Compare
|
Force-push
All 12 tests pass 50 runs in a row, the three modules' |
hjmjohnson
left a comment
There was a problem hiding this comment.
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-formathasSortIncludes: 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 intoMakeMetric<DemonsMetricType>, would leave one of each.
Requested changes are addressed at 6b88a85; dismissing my change request.
|
@greptileai review |
hjmjohnson
left a comment
There was a problem hiding this comment.
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.
6b88a85 to
3ecbb65
Compare
|
@gdevenyi I force-pushed a plain rebase of this branch onto #7277; your commit is unchanged ( EvidenceA 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
You may want to add that check as a regression test here; it is short, and I can paste it. |
3ecbb65 to
a8c6c32
Compare
gdevenyi
left a comment
There was a problem hiding this comment.
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'sModified()it gets 0.8443 where 0.8831 is expected. - Optional nits from your 11-26 review:
<cstdint>now comes after the ITK includes initkImageToImageMetricv4.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'
ctestpasses 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.
a8c6c32 to
68e8ad9
Compare
hjmjohnson
left a comment
There was a problem hiding this comment.
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-422builds a displacement field by hand, repeatingMakeFieldTransform()(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 writesidentity, which the caller must preset to true (.hxx:332); its comment does not mentionidentity..hxxusesstd::maxand the headerstd::vectorwithout including<algorithm>or<vector>; both arrive transitively today.
Requested changes are addressed (#7277 merged, spline-order test verified); dismissing my change request.
|
@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()), |
There was a problem hiding this comment.
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.
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
antsAIruns 14–18% faster. In-place fixed image edits now needModified().What changes
antsAI, the fixed side was about 25% of the instructions.ImageToImageMetricv4keeps, per sample:BeforeThreadedExecution()has the metric clear the samples when any of these changes:SetPoint()modifies only the container);CompositeTransformkeeps its modified time when one of its transforms changes).Initialize()clears them too.ImageToImageMetricv4GetValueAndDerivativeThreaderuses the cache: its sparse loop passes the sample index toProcessVirtualPoint()through the per-thread data. This covers MeanSquares, Mattes, Demons and the derivative pass of joint histogram MI. Threaders that overrideProcessVirtualPoint()(Correlation, ANTS neighborhood correlation) return false from the newUsesFixedSampleCache(), so the metric does not allocate the cache for them; the joint histogram PDF pass has its own loop. These stay unchanged.Modified(), is no longer seen by a metric that was already evaluated. A migration record (20261124_MetricFixedSampleCache.yaml) says so.Testing
Minimal build (
Module_ITKMetricsv4,Module_ITKRegistrationMethodsv4,Module_ITKOptimizersv4, tests on), GCC 15:itkImageToImageMetricv4FixedSampleCacheGTest.cxxcompares, withEXPECT_EQ, a metric that was already evaluated against a new metric:GetValue()beforeGetValueAndDerivative(), 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 onmain);Modified(), which keeps the old values, then is seen afterModified().main's headers, 11 of 12 tests pass; the in-place-edit test fails, as it pins the new behavior.ctestfor the three modules: 365/365 pass, including KWStyle.ANTs on ITK
537ce087, alternating runs on 32 threads unless noted:mainantsAIbrain-extraction search (64³, Regular 0.2, 243 starts)antsRegistrationrigid + affine, Mattes, Regular 0.25 (117×109×103)main's own run-to-run differencesPeak RSS is unchanged within noise.
AI assistance