Repository navigation
Conversation
a51f009 to
5a11c16
Compare
|
@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 |
hjmjohnson
left a comment
There was a problem hiding this comment.
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
- RTK:
- BRAINSTools:
itkReflectiveCorrelationCenterToImageMetric.h:159,165(v4, both methods)itkMixtureStatisticCostFunction.h:99itkFastMarchingCostFunction.h:113
- elastix:
itkSingleValuedPointSetToPointSetMetric.h:138itkScaledSingleValuedCostFunction.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, useconst auto. Where vnl does take it, convert explicitly at that one boundary. categories: ApiRemoveddescribes a changed signature rather than a removal. The schema has no "changed" value, so keep it unless another reviewer objects.Array::GetNumberOfElements()andParametricImageSource/ShapeSignedDistanceFunction::GetNumberOfParameters()still returnunsigned int. This is out of scope, but worth a follow-up issue, since #6949 lists the first as a residual.
| 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`. |
There was a problem hiding this comment.
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:
| 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`. |
There was a problem hiding this comment.
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.
| end. ITK 6.0 first rejected such counts with an exception; the metric now | ||
| reports the full count, so such registrations can run. |
There was a problem hiding this comment.
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:
| 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. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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
Not affected: SimpleITK (full build passes), Slicer, and ITK's Python wrapping (builds with this PR). ANTs' legacy Risk analysis: counts below 2^32For counts that fit in 32 bits, the change is a pure widening:
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:
The copy-initialization warning is Above 2^32: one behavior to guardOn
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 Suggested additions to the migration record
Evidence and method
|
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.
5a11c16 to
00e2040
Compare
gdevenyi
left a comment
There was a problem hiding this comment.
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
decltypeform. - 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, viaMath::CastWithRangeCheck<unsigned int>. A newVnlOptimizersRejectParameterCountsAbove32Bitschecks three of them; it fails with the LBFGS v4 check removed. - Other optimizer sites: the rest of the v3/v4
const unsigned intcount locals are nowconst auto, including Exhaustive, RegularStep, QuaternionRigid and Versor, which your list did not name. - Histogram metrics: the nit is done.
- Not changed:
categories: ApiRemovedstays, as you suggested. I leftArray::GetNumberOfElements()and theParametricImageSource/ShapeSignedDistanceFunctioncounts for a follow-up issue.
The minimal build's ctest passes 879/879.
| 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`. |
There was a problem hiding this comment.
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.
| end. ITK 6.0 first rejected such counts with an exception; the metric now | ||
| reports the full count, so such registrations can run. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| << NumericTraits<NumberOfParametersType>::max()); | ||
| } | ||
| return static_cast<NumberOfParametersType>(numberOfParameters); | ||
| return this->m_MovingTransform->GetNumberOfParameters(); |
There was a problem hiding this comment.
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.
|
[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
|
| if (!m_ScalesInitialized) | ||
| { | ||
| const unsigned int numberOfParameters = m_CostFunction->GetNumberOfParameters(); | ||
| const auto numberOfParameters = m_CostFunction->GetNumberOfParameters(); |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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
| // 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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🟡 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
Check dimensions before narrowing in legacy optimizers · New Widen AdvanceOneStep loop counters to match the expanded dimension · New Widen all remaining AdvanceOneStep counters · New Widen StepAlongGradient loop counter · New Reject oversized dimensions before configuring Powell v4 · New Check cost-function size before replacing the configured function · New Check metric size before assigning m_Metric · New Validate metric size before replacing the configured metric · New
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()); |


Make
CostFunctionTemplateand the v4 metric parameter counts 64-bit (IdentifierType, as inTransformBase), so SyN can register dense fields with more than 2^32 − 1 parameters instead of throwing (#6991). Closes #6949.Change
CostFunctionTemplategainsNumberOfParametersType = IdentifierType, andGetNumberOfParameters()returns it.ObjectToObjectMetricBaseTemplate::NumberOfParametersTypeis nowIdentifierType. 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 whereIdentifierTypeis 32 bits.TwoImageToOneImageMetric,ShapePriorMAPCostFunctionBase,CumulativeGaussianCostFunction,SingleImageCostFunction,MRIBiasEnergyFunction) and 58 test overrides now returnNumberOfParametersType.ImageVectorOptimizerParametersHelperkeeps its voxel count asSizeValueType.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>throwsitk::RangeErrorfor a count above 2^32 − 1. That keeps the clean exceptionmainhas today instead of a silent truncation.CompareHistogramImageToImageMetricandKullbackLeiblerCompareHistogramImageToImageMetricimportNumberOfParametersTypewith their other base types.20261119_CostFunctionParameterCountIs64Bit.yaml: overrides that returnunsigned intno longer compile. The record gives the fix, the shadowing-alias case, adecltypeform 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-32was compared before and after the change. The new warnings are all in code that cannot see a dense field's count:The SyN and time-varying B-spline derivative copies index with 64-bit counters; the warnings there are for the per-dimension
itk::Vectorindex.Testing
ctest: 879/879 pass.VnlOptimizersRejectParameterCountsAbove32Bits(new) expectsRangeErrorfromSetMetric()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.Downstream
Every override of
GetNumberOfParameters()orGetNumberOfLocalParameters()that returnsunsigned intstops compiling (different return type than the function it overrides). @hjmjohnson's forest build of 5a11c16 confirmed these sites; with them fixed, the builds complete:rtkProjectionsDecompositionNegativeLogLikelihood.hitktubeContrastCostFunction.h,itktubeSpatialObjectToImageMetric.h,itktubePointBasedSpatialObjectToImageMetric.h,itktubeRadiusExtractor3.hxx, a test, and an exampleitkBlockMatchingOptimizingInterpolationDisplacementCalculator.h(dependent base:typename Superclass::NumberOfParametersType)Utilities/itkN3MRIBiasFieldCorrectionImageFilter.hand.hxx. The fix is COMP: Take the N3 cost function parameter count type from ITK ANTsX/ANTs#2080 (draft), which uses thedecltypeform so ANTs still builds against ITK 5.4. antsRegistration (SyN, CC) crashes on ~1 to 2.6 G-voxel 3D images (segfault / munmap_chunk(): invalid pointer) ANTsX/ANTs#2033 is the report that led to ObjectToObjectMetricBase NumberOfParametersType is unsigned int: heap overflow in SyN for dense fields > 2^32 parameters #6949.itkReflectiveCorrelationCenterToImageMetric.h(both methods),itkMixtureStatisticCostFunction.h,itkFastMarchingCostFunction.hitkSingleValuedPointSetToPointSetMetric.h,itkScaledSingleValuedCostFunction.h(also a localNumberOfParametersType = unsigned intalias, which must go)vtkPlusProbeCalibrationOptimizerAlgo.cxx) and MITK (mitkSVModelFitCostFunction,mitkMVModelFitCostFunction). Also, from source search only: CaPTk (two copies of the ANTs N3 header) and Nornir (itkImageMosaicVarianceMetric.h).AI assistance