Skip to content

ENH: Add GetFullNumberOfParameters() as an additive alternative to #7216 - #7248

Draft
hjmjohnson wants to merge 2 commits into
InsightSoftwareConsortium:mainfrom
hjmjohnson:metric-full-number-of-parameters
Draft

hjmjohnson wants to merge 2 commits into
InsightSoftwareConsortium:mainfrom
hjmjohnson:metric-full-number-of-parameters

Conversation

@hjmjohnson

@hjmjohnson hjmjohnson commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

An additive alternative to #7216 that lets SyN register dense fields above 2^32 - 1 parameters (#6949, ANTsX/ANTs#2033) without changing GetNumberOfParameters(). A new virtual, GetFullNumberOfParameters(), returns IdentifierType; ITK's dense-field code uses it, and every existing override and caller compiles unchanged.

Merge danger: two-way door. The public API change is additive; the ABI changes (one new vtable slot), as expected for 6.0. Blast radius: none found downstream (see Evidence).

Feedback wanted: the method name, whether the v3 range check (second commit) belongs here, and whether GetNumberOfParameters() should later be deprecated under ITK_FUTURE_LEGACY_REMOVE.

Shape of the change
// ObjectToObjectMetricBaseTemplate
using NumberOfParametersType = unsigned int;          // unchanged
using FullNumberOfParametersType = IdentifierType;    // new
NumberOfParametersType GetNumberOfParameters() const override = 0;  // unchanged
virtual FullNumberOfParametersType GetFullNumberOfParameters() const  // new
{ return this->GetNumberOfParameters(); }

// ObjectToObjectMetric
GetFullNumberOfParameters()  -> m_MovingTransform->GetNumberOfParameters()
GetNumberOfParameters()      -> GetFullNumberOfParameters(), throws above 2^32 - 1 (#6991)

Callers moved to the new method (all inside ITK):

  Metricsv4: ImageToImageMetricv4 derivative sizing, the GetValueAndDerivative
             threader base and threaders (cached count, loops), Correlation and
             Mattes threaders, ObjectToObjectMultiMetricv4, PointSetToPointSetMetricWithIndexv4
  Optimizersv4: ConjugateGradientLineSearch, QuasiNewton, RegularStepGradientDescent
  unchanged: Amoeba, LBFGS, LBFGSB, OnePlusOne, Powell (vnl, 32-bit)
             -> keep calling GetNumberOfParameters() and throw on oversized counts

The gradient-descent optimizers and SyN already size everything from the metric's derivative, so they need no change.

The second commit makes the v3 metrics in Registration/Common convert the transform's count with Math::CastWithRangeCheck<unsigned int>, so a count above 2^32 - 1 throws itk::RangeError instead of truncating. It is separable.

Why not change the return type, or template it?
  • BUG: Make cost function and metric parameter counts 64-bit #7216 widens the return type. A forest build of BUG: Make cost function and metric parameter counts 64-bit #7216 showed overrides break in ANTs, BRAINSTools, elastix, RTK, TubeTK, Ultrasound, and ITKSphinxExamples, with PlusLib and MITK breaking by the same pattern; ITK 5.4 has no NumberOfParametersType on cost functions, so dual-version code needs a decltype workaround. All but one of those overrides are v3 cost functions, which the dense-field path never uses.
  • A template GetNumberOfParameters<T = unsigned int>() cannot be virtual. A non-virtual template over a virtual hook breaks every existing override, and an override written without override (PlusLib, Nornir) compiles and silently stops being called.
Evidence
  • New GTests in itkObjectToObjectMetricGTest.cxx, all passing:
    • ReportsFullParameterCountBeyond32Bits: a transform reporting 2^32 + 3 parameters; GetFullNumberOfParameters() returns it and GetNumberOfParameters() throws.
    • FullParameterCountDefaultsToLegacyOverride: a metric written like BRAINSTools' ReflectiveCorrelationCenterToImageMetric, overriding only unsigned int GetNumberOfParameters(), reports the same count through the new method.
    • The existing BUG: Reject transform parameter counts that exceed the metric limit #6991 tests still pass.
  • macOS arm64, conda clang, Release: ctest -L for ITKOptimizers, ITKOptimizersv4, ITKMetricsv4, ITKRegistrationMethodsv4, and ITKRegistrationCommon: 223 passed, 0 failed (22 not run for a missing itkTestDriver, then run separately: the 44 ITKv3 registration example tests pass).
  • pre-commit run --all-files passes.
  • Downstream, unmodified consumer sources built against this branch with ninja -k 0:
    • Build completely: ANTs (fefdac4d), BRAINSTools (5f36f008), elastix (9c3fd890f), ITKSphinxExamples (32bf48ae), SimpleITK.
    • RTK (ba990770), TubeTK (e3b07ade), Ultrasound (5e450cb): no errors related to this change. Their remaining errors are a macOS SDK linker error, Python.h not found in the wrapping build (a testbed configuration problem), and TubeTK API errors that predate this change.
    • With BUG: Make cost function and metric parameter counts 64-bit #7216, every one of these eight failed on a GetNumberOfParameters() override.
  • Not tested: Windows/MSVC, Python wrapping of the new method, and a real registration above 2^32 parameters (needs about 2 billion voxels).
AI assistance

Claude Code (claude-opus-5-5) designed the additive API, implemented it, wrote the tests, and ran the downstream forest builds, under review by the author.

@github-actions github-actions Bot added 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 area:Numerics Issues affecting the Numerics module area:Documentation Issues affecting the Documentation module labels Nov 26, 2026
@hjmjohnson

Copy link
Copy Markdown
Member Author

@gdevenyi Please review this alternative

@gdevenyi gdevenyi left a comment

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.

Thanks for this. I prefer this design to my #7216. It fixes the dense-field case (#6949, ANTsX/ANTs#2033) without breaking the ~11 downstream projects that your forest build found. Once this merges I will close #7216, and ANTsX/ANTs#2080, which this makes unnecessary.

I checked it at 90db8c9 and found no correctness problems.

  • Call sites: nothing in Metricsv4 or RegistrationMethodsv4 still calls the 32-bit GetNumberOfParameters(). In Optimizersv4, only Amoeba, LBFGS, LBFGSB, OnePlusOne and Powell still use it, which is intended: they size vnl objects with unsigned int, so they should keep throwing.
  • Silent narrowing: none found. Every count that now holds the full value goes into FullNumberOfParametersType or SizeValueType, including the threader base's cached count and globalDerivativeSize.
  • ANTs: no ANTs code calls the metric-level count. Its only GetNumberOfParameters() calls are on command-line option functions or transforms. So with this PR, ANTs SyN needs no ANTs change for counts above 2^32 - 1.
  • Linux/GCC: I built a minimal tree with GCC 15, Release (Optimizers, Optimizersv4, Metricsv4, RegistrationMethodsv4, RegistrationCommon, tests on). It has no new warnings, and ctest passes 474/474, including both new GTests. That adds Linux/GCC to your macOS/clang run.

On your questions:

  1. Name: GetFullNumberOfParameters() is fine with me. Whatever the name, the doc comment could say that this is the count ITK uses internally, and that GetNumberOfParameters() is the 32-bit view of it, which throws when the count does not fit.
  2. The v3 range-check commit: it is independent and correct. Keeping it here is fine. If you would rather keep this PR about the new method, a separate PR would also be fine; I have no preference.
  3. Deprecating GetNumberOfParameters(): I would not, at least not now. The v3 cost functions and the vnl optimizers really are 32-bit, and deprecation would bring back the downstream churn this design avoids.

One behavior worth a sentence in the migration record. ObjectToObjectMetric::GetFullNumberOfParameters() returns the moving transform's count, and ITK's v4 code now asks it for the count. A class derived from ObjectToObjectMetric that overrides only GetNumberOfParameters() to report something else is therefore no longer what the threaders and optimizers see. No class in ITK does this, and I know of none downstream. The default in ObjectToObjectMetricBase covers the BRAINSTools-style metrics that derive from the base directly, as your FullParameterCountDefaultsToLegacyOverride shows.

Review assisted by Claude Code (claude-opus-5-5); the call-site audit, ANTs search, build and tests above were run locally.

@dzenanz dzenanz 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.

As this new GetFullNumberOfParameters is rarely required, I am in favor of retaining both getters indefinitely.

@hjmjohnson
hjmjohnson marked this pull request as ready for review November 27, 2026 18:35
@hjmjohnson hjmjohnson changed the title WIP: ENH: Add GetFullNumberOfParameters() as an additive alternative to #7216 ENH: Add GetFullNumberOfParameters() as an additive alternative to #7216 Nov 27, 2026
@greptile-apps

greptile-apps Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

security Security Review

This PR does not appear safe to merge because a transform with more than 2^32 parameters that is not a displacement field now crashes the process with a divide-by-zero in QuasiNewton or an out-of-bounds read in the metric threaders, where it previously got a clean catchable exception.

What was checked
  • The displacement-field path this PR targets sizes every buffer from the same 64-bit count, so dense fields above 2^32 parameters stay consistent.
  • The new 64-bit counts only reach containers sized by 64-bit size_t (itk::Array / vnl_vector, std::vector), so no total-count truncation is left.
  • The v3 metrics in Registration/Common now throw itk::RangeError on oversized transform counts instead of silently truncating them.
  • The vnl-based optimizers (Amoeba, LBFGS, Powell, OnePlusOne) still fail closed through GetNumberOfParameters() for oversized counts.
  • The multi-metric requires every sub-metric to share one transform, so the derivatives it combines are sized by the same count.

Findings

  • P1 Huge transform count divides by zero ▶
  • P1 Threader reads past derivative buffer ▶

@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5 · Fix the shortened reductions and the wrapped local-count path before merging.RetriggerView in GreptileConfidence Score: 3/5 Tier: plus

[Medium impact] The changes affect bounded ITK registration workflows.

Fix the shortened reductions and the wrapped local-count path before merging.

Findings

  1. P1 Large gradients lose most entries ▶
  2. P1 Large transforms overrun derivative buffers ▶
  3. P2 V3 count checks lack tests ▶
  4. P2 Huge transform count divides by zero ▶
  5. P2 Threader reads past derivative buffer ▶

Summary

Adds GetFullNumberOfParameters() and routes v4 derivative sizes and loops through it.

  • V4 registration carries parameter counts beyond the 32-bit limit.
  • V3 metrics reject transform counts that do not fit their return type.

Intentional or acknowledged limits:

  • hjmjohnson explicitly accepts the added virtual-table slot for ITK 6.0.
  • hjmjohnson intentionally leaves the listed VNL-based optimizers on the legacy getter.
  • hjmjohnson states that Python wrapping and a real registration above the old count limit were not tested.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  T["Moving transform count"] --> F["ObjectToObjectMetric.GetFullNumberOfParameters()"]
  F --> D["V4 derivative sizes and loops"]
  F --> C{"Fits unsigned int?"}
  C -->|Yes| L["GetNumberOfParameters() returns count"]
  C -->|No| E["GetNumberOfParameters() throws"]
Loading

Reviews (1) · Last reviewed commit: "BUG: Throw when a v3 metric's parameter ..." · Reviewed by Greptile

@hjmjohnson
hjmjohnson force-pushed the metric-full-number-of-parameters branch from 90db8c9 to 3227ff8 Compare November 29, 2026 19:22
@github-actions github-actions Bot added type:Infrastructure Infrastructure/ecosystem related changes, such as CMake or buildbots type:Enhancement Improvement of existing methods or implementation labels Nov 29, 2026

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Force-push 90db8c9 → 3227ff8: review fixes only, no rebase.

@gdevenyi, thanks for the review and the GCC run. Both of your suggestions are in 88b9ed7: the GetFullNumberOfParameters() doc comment now calls it the count ITK uses internally and GetNumberOfParameters() its 32-bit view that throws, and the migration record notes that an ObjectToObjectMetric subclass overriding only GetNumberOfParameters() no longer changes the count the threaders and optimizers see.

@hjmjohnson

Copy link
Copy Markdown
Member Author

Converting to draft. The underlying problem, vnl reductions that take an unsigned length and silently truncate long vectors, is being investigated and fixed across ITK in #7262, which now also changes the conjugate-gradient and quasi-Newton lines this PR edits. This PR will be rebased onto that work and staged for review after #7262 is addressed.

@hjmjohnson
hjmjohnson marked this pull request as draft November 30, 2026 13:09
hjmjohnson and others added 2 commits November 30, 2026 13:25
GetNumberOfParameters() returns unsigned int, so a dense displacement
field with more than 2^32 - 1 parameters cannot be registered (InsightSoftwareConsortium#6949).
Add a virtual GetFullNumberOfParameters() returning IdentifierType and
use it where the v4 metrics, threaders, multi-metric, and v4 optimizers
size derivatives. GetNumberOfParameters() and GetNumberOfLocalParameters()
keep their signatures and throw on oversized counts, so existing
overrides compile unchanged. Reductions over the derivative use
std::inner_product with std::multiplies, matching vnl bit for bit
without vnl's unsigned length.

Alternative to InsightSoftwareConsortium#7216, which changed the existing return type.

Co-Authored-By: Gabriel A. Devenyi <gdevenyi@gmail.com>
The v3 metrics in Registration/Common returned the transform's 64-bit
parameter count through an unsigned int, silently truncating counts
above 2^32 - 1. Convert with Math::CastWithRangeCheck so such counts
throw itk::RangeError, matching the v4 metrics' overflow exception.
@hjmjohnson
hjmjohnson force-pushed the metric-full-number-of-parameters branch from 88cac33 to deafb9a Compare November 30, 2026 19:26
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:Numerics Issues affecting the Numerics module area:Registration Issues affecting the Registration module type:Enhancement Improvement of existing methods or implementation type:Infrastructure Infrastructure/ecosystem related changes, such as CMake or buildbots 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