Skip to content

BUG: Make cost function and metric parameter counts 64-bit - #7216

Open
gdevenyi wants to merge 1 commit into
InsightSoftwareConsortium:mainfrom
gdevenyi:bug-metric-parameter-count-64bit
Open

gdevenyi wants to merge 1 commit into
InsightSoftwareConsortium:mainfrom
gdevenyi:bug-metric-parameter-count-64bit

Conversation

@gdevenyi

@gdevenyi gdevenyi commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Make CostFunctionTemplate and the v4 metric parameter counts 64-bit (IdentifierType, as in TransformBase), so SyN can register dense fields with more than 2^32 − 1 parameters instead of throwing (#6991). Closes #6949.

Change
  • CostFunctionTemplate gains NumberOfParametersType = IdentifierType, and GetNumberOfParameters() returns it.
  • ObjectToObjectMetricBaseTemplate::NumberOfParametersType is now IdentifierType. The metric threaders, the multi-metric and the optimizers already store counts in this type, so the dense-field path carries the full count.
  • ObjectToObjectMetric::GetNumberOfParameters() returns the transform's count directly. The BUG: Reject transform parameter counts that exceed the metric limit #6991 guard can no longer fire, so it is removed. Its GTest now checks that a count of 2^32 + 3 is reported unchanged, and skips where IdentifierType is 32 bits.
  • The 11 v3 overrides in ITK (Registration/Common metrics, TwoImageToOneImageMetric, ShapePriorMAPCostFunctionBase, CumulativeGaussianCostFunction, SingleImageCostFunction, MRIBiasEnergyFunction) and 58 test overrides now return NumberOfParametersType.
  • ImageVectorOptimizerParametersHelper keeps its voxel count as SizeValueType.
  • The v3 and v4 optimizers keep the count as auto. Where it sizes a vnl object (unsigned int): LBFGS, LBFGSB, Amoeba v4, conjugate gradient, Levenberg-Marquardt, and both one-plus-one evolutionary optimizers. There, Math::CastWithRangeCheck<unsigned int> throws itk::RangeError for a count above 2^32 − 1. That keeps the clean exception main has today instead of a silent truncation.
  • CompareHistogramImageToImageMetric and KullbackLeiblerCompareHistogramImageToImageMetric import NumberOfParametersType with their other base types.
  • Migration record 20261119_CostFunctionParameterCountIs64Bit.yaml: overrides that return unsigned int no longer compile. The record gives the fix, the shadowing-alias case, a decltype form for code that also builds against 5.4, the caller patterns that break or warn, and search hints.
Truncation audit

A clang build of Optimizersv4, Metricsv4 and RegistrationMethodsv4 with tests and -Wshorten-64-to-32 was compared before and after the change. The new warnings are all in code that cannot see a dense field's count:

  • Local-parameter sizes used to build 32-bit vnl Jacobian matrices, in the CC, JHMI, Mattes, PointSet and threader-base code.
  • The vnl-based optimizers (Amoeba, LBFGS, LBFGSB, Powell, OnePlusOne), which only handle global transforms and use 32-bit dimensions internally. Since the second review round, the ones listed under Change range-check the count where they size vnl objects.

The SyN and time-varying B-spline derivative copies index with 64-bit counters; the warnings there are for the per-dimension itk::Vector index.

Testing
  • GCC 15, Release. A build with every module that defines or tests a cost function (Optimizers, Optimizersv4, Metricsv4, RegistrationMethodsv4, RegistrationCommon, TwoProjectionRegistration, LevelSets, MinimalPathExtraction, BiasCorrection, Deconvolution, Statistics) builds with no errors, and ctest: 879/879 pass.
  • VnlOptimizersRejectParameterCountsAbove32Bits (new) expects RangeError from SetMetric() of LBFGS v4, LBFGSB v4 and Amoeba v4 for a count of 2^32 + 3, and no exception for 17. It fails if the LBFGS v4 range check is removed.
  • A real failing case needs about 2 billion voxels, so it was not run here. The GTest uses a transform that only reports a large count.
  • Real data: the reporter of antsRegistration (SyN, CC) crashes on ~1 to 2.6 G-voxel 3D images (segfault / munmap_chunk(): invalid pointer) ANTsX/ANTs#2033 built ITK 5.4.5 with the same widening and ran their 12 µm template round (852 × 1182 × 1965 template, 5.9 billion parameters). It ran without problems: 48 of 50 registrations had completed when they reported, and the other 2 were in the full-resolution stage (comment).
Downstream

Every override of GetNumberOfParameters() or GetNumberOfLocalParameters() that returns unsigned int stops compiling (different return type than the function it overrides). @hjmjohnson's forest build of 5a11c16 confirmed these sites; with them fixed, the builds complete:

AI assistance
  • Tool: Claude Code (claude-opus-5-5)
  • Role: wrote the change, the GTest update and the migration record, ran the clang truncation audit, and ran the local build and tests
  • All code was reviewed and tested locally before committing

@gdevenyi
gdevenyi force-pushed the bug-metric-parameter-count-64bit branch from a51f009 to 5a11c16 Compare November 19, 2026 18:31
@github-actions github-actions Bot added type:Bug Inconsistencies or issues which will cause an incorrect result under some or all circumstances type:Testing Ensure that the purpose of a class is met/the results on a wide set of test cases are correct area:Core Issues affecting the Core module area:Filtering Issues affecting the Filtering module area:Registration Issues affecting the Registration module area:Segmentation Issues affecting the Segmentation module area:Numerics Issues affecting the Numerics module area:Documentation Issues affecting the Documentation module labels Nov 19, 2026
@gdevenyi

Copy link
Copy Markdown
Contributor Author

@ntustison, could you review this? It lets SyN register images above about 1.43 billion voxels (3-D), the case in ANTsX/ANTs#2033. ANTs needs a one-line change in itkN3MRIBiasFieldCorrectionImageFilter.h when this merges.

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

The widening itself is right, and the GTest fails without it. Because it is an API break, it needs its downstream cost listed and a migration path before merge. Two should-fix items: the downstream list, and the shadowing-alias case in the migration record (line comment).

should-fix: the Downstream section lists only ANTs. At current tips, these overrides also stop compiling:

  • ITK-org remote modules, so the nightly remote-module builds break:
    • RTK: rtkProjectionsDecompositionNegativeLogLikelihood.h:138
    • TubeTK: itktubeSpatialObjectToImageMetric.h:162
    • Ultrasound: itkBlockMatchingOptimizingInterpolationDisplacementCalculator.h:157
    • two cost functions in ITKSphinxExamples
  • BRAINSTools:
    • itkReflectiveCorrelationCenterToImageMetric.h:159,165 (v4, both methods)
    • itkMixtureStatisticCostFunction.h:99
    • itkFastMarchingCostFunction.h:113
  • elastix:
    • itkSingleValuedPointSetToPointSetMetric.h:138
    • itkScaledSingleValuedCostFunction.h

Please list these in the PR, and open companion issues or PRs for the ITK-org remote modules before this merges, so their nightlies do not go red. SimpleITK, Slicer, and the Python wrapping are not affected: none of them overrides these methods.

Nits (optional)
  • v3/v4 vnl optimizer sites still store the count in unsigned int, so each is now an implicit 64-to-32 narrowing (possible MSVC C4244). The Windows pixi build does not report warnings to CDash. Sites: itkSingle/MultipleValuedNonLinearOptimizer.cxx:46, itkGradientDescentOptimizer.cxx:141, itkLevenbergMarquardtOptimizer.cxx:42, itkSPSAOptimizer.cxx:102, itkIterateNeighborhoodOptimizer.cxx:122, itkConjugateGradientOptimizer.cxx:50, itkLBFGSBOptimizer.cxx:259,291, itkLBFGSOptimizer.cxx:176, itkAmoebaOptimizerv4.cxx:79, itkLBFGSBOptimizerv4.cxx:191, itkLBFGSOptimizerv4Base.cxx:118, itkOnePlusOneEvolutionaryOptimizerv4.hxx:90. Where no 32-bit vnl API takes the count, use const auto. Where vnl does take it, convert explicitly at that one boundary.
  • categories: ApiRemoved describes a changed signature rather than a removal. The schema has no "changed" value, so keep it unless another reviewer objects.
  • Array::GetNumberOfElements() and ParametricImageSource / ShapeSignedDistanceFunction::GetNumberOfParameters() still return unsigned int. This is out of scope, but worth a follow-up issue, since #6949 lists the first as a residual.

Comment on lines +22 to +28
actions:
- Return `NumberOfParametersType` from overrides of `GetNumberOfParameters()`
in classes derived from `SingleValuedCostFunction` or
`MultipleValuedCostFunction`, and from overrides of
`GetNumberOfParameters()` and `GetNumberOfLocalParameters()` in v4 metrics.
In a class template whose base depends on a template parameter, write
`typename Superclass::NumberOfParametersType`.

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.

should-fix. elastix's ScaledSingleValuedCostFunction declares using NumberOfParametersType = unsigned int; // temp, copied from itk::CostFunction, so following this action as written still fails to compile there. Please cover the shadowing alias:

Suggested change
actions:
- Return `NumberOfParametersType` from overrides of `GetNumberOfParameters()`
in classes derived from `SingleValuedCostFunction` or
`MultipleValuedCostFunction`, and from overrides of
`GetNumberOfParameters()` and `GetNumberOfLocalParameters()` in v4 metrics.
In a class template whose base depends on a template parameter, write
`typename Superclass::NumberOfParametersType`.
- Return `NumberOfParametersType` from overrides of `GetNumberOfParameters()`
in classes derived from `SingleValuedCostFunction` or
`MultipleValuedCostFunction`, and from overrides of
`GetNumberOfParameters()` and `GetNumberOfLocalParameters()` in v4 metrics.
In a class template whose base depends on a template parameter, write
`typename Superclass::NumberOfParametersType`.
- Delete any local `NumberOfParametersType` alias that redefines it as
`unsigned int`.

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.

Applied in 00e2040, as suggested. The actions also add: the decltype form for code that must still build against 5.4; storing the count as NumberOfParametersType or auto in callers. The details list the caller patterns that break (brace initialization, std::min/std::max, overloads on unsigned int and int) and the warnings (C4244, -Wshorten-64-to-32, -Wconversion). The hints are your two git grep forms plus one for shadowing aliases. Your second form finds the ANTs N3 override.

Comment on lines +14 to +15
end. ITK 6.0 first rejected such counts with an exception; the metric now
reports the full count, so such registrations can run.

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.

nit. The #6991 guard (cc15831) is in no release tag. The latest is v6.0b02, and git tag --contains is empty. So if this lands before 6.0, no release ever threw. A record should stand on its own for readers of the 6.0 guide:

Suggested change
end. ITK 6.0 first rejected such counts with an exception; the metric now
reports the full count, so such registrations can run.
end. Earlier versions truncated the count; the metric now reports the full
count, so such registrations can run.

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.

Applied in 00e2040. The paragraph also says that the vnl-based optimizers now throw itk::RangeError above 2^32 - 1.

/** @ITKEndGrouping */
/** Return the number of parameters required by the Transform */
[[nodiscard]] unsigned int
[[nodiscard]] typename Superclass::NumberOfParametersType

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.

nit. This class, and itkKullbackLeiblerCompareHistogramImageToImageMetric.h:117, already import base types in a "Types transferred from the base class" block. Adding using NumberOfParametersType = typename Superclass::NumberOfParametersType; there and returning NumberOfParametersType would match the other nine overrides.

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.

Done in 00e2040, for both histogram metrics: using typename Superclass::NumberOfParametersType; in the "Types transferred from the base class" block, and the overrides return NumberOfParametersType.

@hjmjohnson

Copy link
Copy Markdown
Member

A forest build of this PR (5a11c16) confirms every downstream break listed in my review and adds two more consumers, PlusLib and MITK. Every break is a compile error at an override; with those overrides fixed locally, ANTs, elastix, Ultrasound, and SphinxExamples build completely, BRAINSTools fails only on its own two overrides, and RTK and TubeTK hit no further count-related errors. For counts below 2^32 the change only widens the type and changes no values.

Merge danger: one-way door for downstream source (each override must change, in about 11 projects, four of them ITK-org remote modules). The ABI break is the expected one for 6.0.

All breakage locations (forest-confirmed unless marked)

Every site fails with virtual function 'GetNumberOfParameters' has a different return type ('unsigned int') than the function it overrides.

  • ANTs: Utilities/itkN3MRIBiasFieldCorrectionImageFilter.h:118 (and its definition in the .hxx)
  • BRAINSTools:
    • BRAINSConstellationDetector/src/itkReflectiveCorrelationCenterToImageMetric.h:160 (GetNumberOfLocalParameters), :166 (GetNumberOfParameters)
    • BRAINSMush/itkMixtureStatisticCostFunction.h:100 (module off in the forest; same pattern)
    • GTRACT/Common/itkFastMarchingCostFunction.h:114 (module off in the forest; same pattern)
  • elastix:
    • Common/CostFunctions/itkScaledSingleValuedCostFunction.h:62: a local using NumberOfParametersType = unsigned int; makes the override at :88 fail; definition at .cxx:161
    • Common/CostFunctions/itkSingleValuedPointSetToPointSetMetric.h:139
  • RTK: include/rtkProjectionsDecompositionNegativeLogLikelihood.h:140
  • TubeTK:
    • src/Filtering/itktubeContrastCostFunction.h:84 (definition .hxx:54)
    • src/Registration/itktubeSpatialObjectToImageMetric.h:163 (definition .hxx:126)
    • src/Registration/itktubePointBasedSpatialObjectToImageMetric.h:176
    • src/Segmentation/itktubeRadiusExtractor3.hxx:127
    • test/Numerics/itktubeSingleValuedCostFunctionImageSourceTest.cxx:65
    • examples/Applications/DeblendTomosynthesisSlicesUsingPrior/DeblendTomosynthesisSlicesUsingPrior.cxx:69,272
  • Ultrasound: include/itkBlockMatchingOptimizingInterpolationDisplacementCalculator.h:158 (dependent base: needs typename Superclass::NumberOfParametersType)
  • ITKSphinxExamples:
    • src/Numerics/Optimizers/AmoebaOptimizer/ExampleCostFunction.h:28
    • src/Numerics/Optimizers/LevenbergMarquardtOptimization/itkExampleCostFunction.h:30
  • PlusLib (not built in the forest; same pattern reproduced by a compile probe): src/PlusCalibration/vtkProbeCalibrationAlgo/vtkPlusProbeCalibrationOptimizerAlgo.cxx:148, which declares the method without override and still fails
  • MITK (not built in the forest; pattern reproduced by a compile probe):
    • Modules/ModelFit/include/mitkSVModelFitCostFunction.h:73 and src/Functors/mitkSVModelFitCostFunction.cpp:55
    • Modules/ModelFit/include/mitkMVModelFitCostFunction.h:79 and src/Functors/mitkMVModelFitCostFunction.cpp:60

Not affected: SimpleITK (full build passes), Slicer, and ITK's Python wrapping (builds with this PR). ANTs' legacy itkJensenHavrdaCharvatTsallis*PointSetMetric.h return unsigned int, but nothing includes them. Outside the forest, CaPTk's two copies of the ANTs N3 header and Nornir's itkImageMosaicVarianceMetric.h have the same override.

Risk analysis: counts below 2^32

For counts that fit in 32 bits, the change is a pure widening:

  • Every count is returned unchanged; unsigned int to IdentifierType is value-preserving on all platforms (32-bit platforms see no change).
  • No virtual function takes the count as an argument, so no override can turn into a silent hiding overload. ComputeParameterOffsetFromVirtual{Index,Point} take it by const &, so unsigned int arguments still bind.
  • With the overrides fixed, the forest found no other compile errors and no behavior change.

What changes is only the type that callers see. A compile probe against this PR shows four caller patterns that behave differently; the forest has no instance of the three that fail:

Caller pattern Before After
unsigned int n = f->GetNumberOfParameters(); OK warning (see below)
unsigned int n{ f->GetNumberOfParameters() }; OK error: narrowing
std::max(f->GetNumberOfParameters(), 3u) OK error: no matching max
g(f->GetNumberOfParameters()) with g(unsigned int) and g(int) OK error: ambiguous

The copy-initialization warning is -Wshorten-64-to-32 in clang and -Wconversion in GCC, both off by default. Microsoft documents C4244 for a 64-bit to 32-bit integer conversion at level 3, which is on by default; I could not build on Windows to confirm. The forest source has 87 such unsigned int receivers (69 in elastix), though some read a transform's count, which is already 64-bit. MITK builds its modules with -Werror and /WX by default, so where that warning is enabled these become errors.

Above 2^32: one behavior to guard

On main, a metric whose transform reports more than 2^32 - 1 parameters throws (#6991). With this PR, the v4 gradient-descent path carries the full count, as intended, but the vnl-based optimizers still store it in unsigned int with no check, so they now truncate without telling anyone:

  • itkLBFGSOptimizerv4Base.cxx:118, itkLBFGSBOptimizerv4.cxx:191, itkAmoebaOptimizerv4.cxx:79, itkOnePlusOneEvolutionaryOptimizerv4.hxx:90
  • v3: itkSingleValuedNonLinearOptimizer.cxx:46, itkGradientDescentOptimizer.cxx:141, and the other sites in the review's nits

These optimizers cannot run on a dense field of that size, but an explicit check at the vnl boundary would keep the clean exception that main has today.

Suggested additions to the migration record
  1. ITK 5.4 compatibility. NumberOfParametersType is new on CostFunctionTemplate: on ITK 5.4 (and on main before this PR) it does not exist, so the record's main action fails for projects that also build against 5.4 (ANTs, BRAINSTools, elastix). Promote the decltype hint into the actions. The forest's ANTs fix uses that form and builds:

    using NumberOfParametersType =
      decltype(std::declval<const SingleValuedCostFunction &>().GetNumberOfParameters());
  2. Shadowing alias (elastix): delete any local NumberOfParametersType defined as unsigned int (the line comment in my review).

  3. Search hint. The current hint only finds the split-line form. It misses same-line declarations (MITK, PlusLib), virtual or inline prefixes (TubeTK), and definitions outside the class (elastix .cxx, MITK .cpp, TubeTK .hxx). Two hints cover all the forest cases:

    git grep -nE 'unsigned( int)?[[:space:]]+([[:alnum:]_:<>, ]+::)?GetNumberOf(Local)?Parameters[[:space:]]*\('
    git grep -n -B1 -E '^[[:space:]]*([[:alnum:]_]+(<[^>]*>)?::)?GetNumberOf(Local)?Parameters[[:space:]]*\(' | grep -E 'unsigned( int)?[[:space:]]*$'
    
  4. Callers. Brace-initialization into unsigned int, std::min or std::max with an unsigned int, and calls to functions overloaded on unsigned int and int no longer compile. Store the count as NumberOfParametersType (or auto), or convert explicitly where a 32-bit API needs it.

  5. Warnings. Assigning the count to unsigned int warns on MSVC by default (C4244) and under clang -Wshorten-64-to-32 or GCC -Wconversion; projects that treat warnings as errors need the same fix as item 4.

Evidence and method
  • Forest build_forest-itk-pr7216, ITK at 5a11c16 (with Python wrapping), seeded from the itk-main baseline forest; macOS arm64, conda clang. Consumer SHAs: ANTs fefdac4d, BRAINSTools 5f36f008, elastix 9c3fd890f, RTK ba990770, TubeTK e3b07ade, Ultrasound 5e450cb, ITKSphinxExamples 32bf48ae, SimpleITK at its forest branch.
  • Round 1: each consumer built, then ninja -k 0 to collect every error. Only the override errors above relate to this PR.
  • Round 2: the overrides fixed locally (ANTs with the decltype form, the rest with NumberOfParametersType or typename Superclass::NumberOfParametersType), then ninja -k 0 again. ANTs, elastix, Ultrasound, and SphinxExamples build completely. RTK and TubeTK still fail, but only on errors that the baseline forest also shows (a macOS linker architecture error, and TubeTK's vnl_svd, ImageRegionIteratorWithIndex, and GetKernelMedialness errors, which come from its April checkout).
  • Compile probe: eight caller and override patterns compiled with -fsyntax-only -Wshorten-64-to-32 against main and against this PR.
  • BRAINSTools was built against the locally fixed ANTs; its only errors are the two ReflectiveCorrelation overrides. BRAINSMush and GTRACT are off in this forest (USE_BRAINSMush=OFF, USE_GTRACT=OFF).
  • Not tested: Windows/MSVC, MITK, PlusLib (Slicer lane), and Plastimatch (fails on older ITK API before reaching this code).

The v4 metrics returned the transform's 64-bit parameter count through
an unsigned int, so a dense displacement field with more than 2^32 - 1
parameters (about 1.43 billion voxels in 3-D) could not be registered;
the guard from InsightSoftwareConsortium#6991 throws there. CostFunctionTemplate and
ObjectToObjectMetricBaseTemplate now use IdentifierType, as
TransformBase does, and overrides return NumberOfParametersType. The
guard can no longer fire and is removed. The optimizers keep the count
in its own type, except at vnl objects sized with unsigned int, where a
larger count throws RangeError. ImageVectorOptimizerParametersHelper
also keeps its voxel count as SizeValueType.

Closes InsightSoftwareConsortium#6949.
@gdevenyi
gdevenyi force-pushed the bug-metric-parameter-count-64bit branch from 5a11c16 to 00e2040 Compare November 26, 2026 19:32

@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 5a11c16ca4 → 00e204008a, review fixes only, no rebase. Thanks for the forest build.

  • Downstream list (should-fix): the PR body's Downstream section now lists every site from your review and forest comment, by project. Companion issues or PRs for the four ITK-org remote modules (RTK, TubeTK, Ultrasound, ITKSphinxExamples) are still to do, and will be done before this merges. ANTs already has ANTsX/ANTs#2080, which uses the decltype form.
  • Migration record (should-fix): the shadowing-alias action, plus your other suggested additions (see the line reply).
  • Above 2^32: at the vnl boundary, LBFGS, LBFGSB, Amoeba v4, conjugate gradient, Levenberg-Marquardt and both one-plus-one evolutionary optimizers now throw itk::RangeError, via Math::CastWithRangeCheck<unsigned int>. A new VnlOptimizersRejectParameterCountsAbove32Bits checks three of them; it fails with the LBFGS v4 check removed.
  • Other optimizer sites: the rest of the v3/v4 const unsigned int count locals are now const auto, including Exhaustive, RegularStep, QuaternionRigid and Versor, which your list did not name.
  • Histogram metrics: the nit is done.
  • Not changed: categories: ApiRemoved stays, as you suggested. I left Array::GetNumberOfElements() and the ParametricImageSource/ShapeSignedDistanceFunction counts for a follow-up issue.

The minimal build's ctest passes 879/879.

Comment on lines +22 to +28
actions:
- Return `NumberOfParametersType` from overrides of `GetNumberOfParameters()`
in classes derived from `SingleValuedCostFunction` or
`MultipleValuedCostFunction`, and from overrides of
`GetNumberOfParameters()` and `GetNumberOfLocalParameters()` in v4 metrics.
In a class template whose base depends on a template parameter, write
`typename Superclass::NumberOfParametersType`.

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.

Applied in 00e2040, as suggested. The actions also add: the decltype form for code that must still build against 5.4; storing the count as NumberOfParametersType or auto in callers. The details list the caller patterns that break (brace initialization, std::min/std::max, overloads on unsigned int and int) and the warnings (C4244, -Wshorten-64-to-32, -Wconversion). The hints are your two git grep forms plus one for shadowing aliases. Your second form finds the ANTs N3 override.

Comment on lines +14 to +15
end. ITK 6.0 first rejected such counts with an exception; the metric now
reports the full count, so such registrations can run.

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.

Applied in 00e2040. The paragraph also says that the vnl-based optimizers now throw itk::RangeError above 2^32 - 1.

/** @ITKEndGrouping */
/** Return the number of parameters required by the Transform */
[[nodiscard]] unsigned int
[[nodiscard]] typename Superclass::NumberOfParametersType

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.

Done in 00e2040, for both histogram metrics: using typename Superclass::NumberOfParametersType; in the "Types transferred from the base class" block, and the overrides return NumberOfParametersType.

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

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.

<< NumericTraits<NumberOfParametersType>::max());
}
return static_cast<NumberOfParametersType>(numberOfParameters);
return this->m_MovingTransform->GetNumberOfParameters();

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.

P2 security Powell v4 truncates 64-bit count

Powell v4 truncates 64-bit count. The guard removed here was the only thing that stopped counts above 2^32 - 1 from reaching consumers that still narrow the value. PowellOptimizerv4::StartOptimization is one of them: itkPowellOptimizerv4.hxx:395 passes the count to SetSpaceDimension(unsigned int), which wraps silently. This PR added Math::CastWithRangeCheck<unsigned int> to LBFGS, LBFGSB and Amoeba v4 for exactly this reason, but Powell v4 was missed, and before this PR it got a clean exception instead.

What can go wrong: with a metric whose moving transform has a parameter count that is a multiple of 2^32 (for example exactly 2^32 parameters from a 2-D dense field of 2^31 pixels, or a 3-D field sized to hit the multiple), m_SpaceDimension becomes 0 and xit[0] = 1 writes past an empty vnl_vector, whose operator[] does no range checking — a crash or heap corruption. Other huge counts make the optimizer run in the wrong dimension and fail later inside the transform's size check with a confusing error. Range-check in PowellOptimizerv4 the way the other vnl optimizers now do.

@greptile-apps

greptile-apps Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

security Security Review

This PR does not appear safe to merge because a registration with more than 2^32 transform parameters now spins forever in the v3 gradient-descent optimizers' 32-bit loop counters, and Powell v4 silently truncates the count.

What was checked
  • The v4 metric threaders, SyN and the multi-metric all size derivative buffers with the full 64-bit count, so the original ObjectToObjectMetricBase NumberOfParametersType is unsigned int: heap overflow in SyN for dense fields > 2^32 parameters #6949 overflow stays fixed.
  • The vnl-based optimizers this PR touches (LBFGS, LBFGSB, Amoeba v4, plus LBFGS, conjugate gradient, Levenberg-Marquardt and one-plus-one v3) now throw RangeError instead of truncating.
  • Parameter and derivative buffers (itk::Array / vnl_vector) size with 64-bit size_t, so buffers sized from the full count are correct.
  • v3 optimizers cannot receive v4 metrics (separate class hierarchies), so no new mixing path opened up.
  • Two consumers of the widened count were missed: the v3 gradient-descent loops hang above 2^32 and PowellOptimizerv4 still truncates, both reported.

Findings

  • P1 32-bit loop counters hang optimizers
  • P2 Powell v4 truncates 64-bit count ▶

@greptile-apps

greptile-apps Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

  • P1 security 32-bit loop counters hang optimizers — Modules/Numerics/Optimizers/src/itkGradientDescentOptimizer.cxx:163

    32-bit loop counters hang optimizers. This PR makes GetNumberOfParameters() return a 64-bit count, and GradientDescentOptimizer::AdvanceOneStep now stores it in auto spaceDimension, but its step loops still count with unsigned int j (lines 157 and 163). When the cost function reports more than 2^32 - 1 parameters, j wraps at 2^32 while j < spaceDimension stays true forever, so the optimizer never finishes even one step and the process spins at 100% CPU.

    Example: an app reads a big image, builds a DisplacementFieldTransform over roughly 1.43 billion voxels or more (the PR itself cites a 5.9-billion-parameter field), and runs a v3 registration with itk::ImageToImageMetric. The first AdvanceOneStep hangs. Before this PR the v3 metric returned the truncated 32-bit count, so these loops always ended. The scales check on the way in passes, because SingleValuedNonLinearOptimizer::SetCostFunction (also changed here) sizes the default scales with the same 64-bit count.

    The same pattern is in itkRegularStepGradientDescentBaseOptimizer.cxx:143 (three loops, plus line 64 in StartOptimization) and itkRegularStepGradientDescentOptimizer.cxx:34, which also covers VersorTransformOptimizer and VersorRigid3DTransformOptimizer through inheritance. Loop with the count's own type, or range-check like the vnl optimizers now do.

@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5 · Fix the legacy loop overflow and Powell's unchecked count conversion before merging.RetriggerView in GreptileConfidence Score: 3/5 Tier: plus

[Medium impact] The PR changes parameter-count handling across ITK's cost-function, registration-metric, and optimizer APIs.

Fix the legacy loop overflow and Powell's unchecked count conversion before merging.

Findings

  1. P1 Large costs hang during setup ▶
  2. P1 Powell crashes on large counts ▶
  3. P2 Rejected counts allocate huge arrays ▶

Summary

The PR makes cost-function and v4 metric parameter counts use IdentifierType.

  • Registration metrics now report full-width transform parameter counts.
  • Optimizers keep large counts or reject them before 32-bit sizing.

gdevenyi explicitly disclosed the downstream override compilation break and supplied migration guidance.

Review checks were source-based; no builds or runtime tests were run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  T[Transform parameter count] --> M[Metric returns IdentifierType]
  M --> D[Dense derivative uses full count]
  M --> V[Checked optimizer conversion]
  V --> E[RangeError for oversized counts]
  M --> P[Powell converts to unsigned int]
  P --> Z[Count can become zero]
  Z --> W[Write into empty vector]
  C[Legacy cost returns IdentifierType] --> S[Full-size default scales]
  S --> L[32-bit scale-loop index wraps]
Loading

Reviews (1) · Last reviewed commit: "BUG: Make cost function and metric param..." · Reviewed by Greptile

if (!m_ScalesInitialized)
{
const unsigned int numberOfParameters = m_CostFunction->GetNumberOfParameters();
const auto numberOfParameters = m_CostFunction->GetNumberOfParameters();

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 Large costs hang during setup

For a cost with more than UINT_MAX parameters, default SetCostFunction() now creates full-size scales and calls Optimizer::SetScales(). That function still uses unsigned int i against the full array size. The index wraps, so setup never finishes.

The newly widened bounds in GradientDescentOptimizer and RegularStepGradientDescentBaseOptimizer have the same problem. Widen the matching indices throughout, or reject unsupported counts before creating the arrays.

Knowledge Base Used: Numerical optimization and statistics

<< NumericTraits<NumberOfParametersType>::max());
}
return static_cast<NumberOfParametersType>(numberOfParameters);
return this->m_MovingTransform->GetNumberOfParameters();

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 Powell crashes on large counts

Removing this guard exposes an unchecked conversion in PowellOptimizerv4::StartOptimization(). It passes the full count to SetSpaceDimension(unsigned int). A count of 2^32, possible for a large 2-D displacement field, becomes zero. Powell then creates an empty xit and writes xit[0] = 1, causing an assertion failure or an invalid write instead of the previous exception.

Add a checked conversion in Powell before accepting these counts.

Knowledge Base Used: Registration framework

Comment on lines +90 to +91
// vnl sizes are unsigned int; throws RangeError for a larger count instead of truncating it.
const auto spaceDimension = Math::CastWithRangeCheck<unsigned int>(this->m_Metric->GetNumberOfParameters());

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.

P2 Rejected counts allocate huge arrays

The new range check runs after Superclass::StartOptimization(). For a global transform, the superclass first creates and fills scales using GetNumberOfLocalParameters(), which equals the full parameter count. A count above UINT_MAX therefore attempts a scales allocation of more than 32 GiB before reaching the intended RangeError.

Move the checked conversion before the superclass call to avoid exhausting memory for a problem the optimizer will reject anyway.

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.

🟡 Changes recommended

Unresolved counter wraparound and unchecked narrowing can hang or misconfigure large-parameter optimizers, while range-check exceptions can leave optimizer state inconsistent.

8 open issues

Review effort: Balanced

* this cost function.
* This method MUST be overloaded by derived classes. */
virtual unsigned int
virtual NumberOfParametersType
}

const unsigned int spaceDimension = m_CostFunction->GetNumberOfParameters();
const auto spaceDimension = m_CostFunction->GetNumberOfParameters();
itkDebugMacro("AdvanceOneStep");

const unsigned int spaceDimension = m_CostFunction->GetNumberOfParameters();
const auto spaceDimension = m_CostFunction->GetNumberOfParameters();
itkDebugMacro("factor = " << factor << " transformedGradient= " << transformedGradient);

const unsigned int spaceDimension = m_CostFunction->GetNumberOfParameters();
const auto spaceDimension = m_CostFunction->GetNumberOfParameters();
<< NumericTraits<NumberOfParametersType>::max());
}
return static_cast<NumberOfParametersType>(numberOfParameters);
return this->m_MovingTransform->GetNumberOfParameters();

const unsigned int numberOfParameters = costFunction->GetNumberOfParameters();
// vnl sizes are unsigned int; throws RangeError for a larger count instead of truncating it.
const auto numberOfParameters = Math::CastWithRangeCheck<unsigned int>(costFunction->GetNumberOfParameters());
// if cost function is nullptr this will throw an exception when the pointer is dereferenced
const unsigned int numberOfParameters = metric->GetNumberOfParameters();
// vnl sizes are unsigned int; throws RangeError for a larger count instead of truncating it.
const auto numberOfParameters = Math::CastWithRangeCheck<unsigned int>(metric->GetNumberOfParameters());
// assign to vnl cost-function adaptor
const unsigned int numberOfParameters = metric->GetNumberOfParameters();
// vnl sizes are unsigned int; throws RangeError for a larger count instead of truncating it.
const auto numberOfParameters = Math::CastWithRangeCheck<unsigned int>(metric->GetNumberOfParameters());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:Core Issues affecting the Core module area:Documentation Issues affecting the Documentation module area:Filtering Issues affecting the Filtering module area:Numerics Issues affecting the Numerics module area:Registration Issues affecting the Registration module area:Segmentation Issues affecting the Segmentation module type:Bug Inconsistencies or issues which will cause an incorrect result under some or all circumstances 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.

ObjectToObjectMetricBase NumberOfParametersType is unsigned int: heap overflow in SyN for dense fields > 2^32 parameters

3 participants