1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
|
/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
/**
* \file ImpactLoss.h
*
* Implementation of differentiable loss functions used in the IMPACT image registration metric.
* Each loss is implemented as a class inheriting from `Loss`, and can be registered dynamically
* via the `LossFactory` for use at runtime.
*
* Supports both static and Jacobian-based backpropagation modes.
*
* \author V. Boussot, Univ. Rennes, INSERM, LTSI- UMR 1099, F-35000 Rennes, France
* \note This work was funded by the French National Research Agency as part of the VATSop project (ANR-20-CE19-0015).
* \note If you use the Impact anywhere we would appreciate if you cite the following article:\n
* V. Boussot et al., IMPACT: A Generic Semantic Loss for Multimodal Medical Image Registration, arXiv preprint
* arXiv:2503.24121 (2025). https://doi.org/10.48550/arXiv.2503.24121
*
*/
#ifndef _ImpactLoss_h
#define _ImpactLoss_h
#include <torch/torch.h>
#include <cmath>
#include <iostream>
#include "itkTimeProbe.h"
namespace ImpactLoss
{
/**
* \class Loss
* \brief Abstract base class for losses operating on extracted feature maps.
*
* Stores the accumulated loss value and its derivative, and provides methods for updating them.
* Designed to support both:
* - Static mode (with manual update of derivative using precomputed jacobians)
* - Jacobian mode (direct backpropagation of gradients)
*
* Subclasses must implement:
* - updateValue()
* - updateValueAndGetGradientModulator()
*/
class Loss
{
private:
mutable double m_Normalization = 0;
protected:
double m_Value;
torch::Tensor m_Derivative;
bool m_Initialized = false;
int m_NumberOfParameters;
public:
Loss(bool isLossNormalized)
{
if (!isLossNormalized)
{
m_Normalization = 1.0;
}
}
void
setNumberOfParameters(int numberOfParameters)
{
m_NumberOfParameters = numberOfParameters;
}
void
reset()
{
m_Initialized = false;
}
virtual void
initialize(torch::Tensor & output)
{
// Lazy initialization of internal buffers based on output tensor shape and number of parameters
if (!m_Initialized)
{
m_Value = 0;
m_Derivative = torch::zeros({ m_NumberOfParameters }, output.options());
m_Initialized = true;
}
}
virtual void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) = 0;
virtual void
updateValueAndDerivativeInStaticMode(torch::Tensor & fixedOutput,
torch::Tensor & movingOutput,
torch::Tensor & jacobian,
torch::Tensor & nonZeroJacobianIndices)
{
m_Derivative.index_add_(
0,
nonZeroJacobianIndices.flatten(),
(updateValueAndGetGradientModulator(fixedOutput, movingOutput).unsqueeze(-1) * jacobian).sum(1).flatten());
}
virtual torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) = 0;
void
updateDerivativeInJacobianMode(torch::Tensor & jacobian, torch::Tensor & nonZeroJacobianIndices)
{
m_Derivative.index_add_(0, nonZeroJacobianIndices.flatten(), jacobian.flatten());
}
virtual double
GetValue(double N) const
{
if (m_Normalization == 0)
{
m_Normalization = 1 / (m_Value / N);
}
return m_Normalization * m_Value / N;
}
virtual torch::Tensor
GetDerivative(double N) const
{
return m_Normalization * m_Derivative.to(torch::kCPU) / N;
}
virtual ~Loss() = default;
virtual Loss &
operator+=(const Loss & other)
{
if (!m_Initialized && other.m_Initialized)
{
m_Value = other.m_Value;
m_Derivative = other.m_Derivative;
m_Initialized = true;
}
else if (other.m_Initialized)
{
m_Value += other.m_Value;
m_Derivative += other.m_Derivative;
}
return *this;
}
};
/**
* \class LossFactory
* \brief Singleton factory to register and create Loss instances by string name.
*
* Used to instantiate losses dynamically from configuration.
* Example: "L1", "L2", "NCC", etc.
*/
class LossFactory
{
public:
using CreatorFunc = std::function<std::unique_ptr<Loss>()>;
static LossFactory &
Instance()
{
static LossFactory instance;
return instance;
}
void
RegisterLoss(const std::string & name, CreatorFunc creator)
{
factoryMap[name] = creator;
}
std::unique_ptr<Loss>
Create(const std::string & name)
{
auto it = factoryMap.find(name);
if (it != factoryMap.end())
{
return it->second();
}
throw std::runtime_error("Error: Unknown loss function " + name);
}
private:
std::unordered_map<std::string, CreatorFunc> factoryMap;
};
template <typename T>
class RegisterLoss
{
public:
RegisterLoss(const std::string & name)
{
LossFactory::Instance().RegisterLoss(name, []() { return std::make_unique<T>(); });
}
};
/**
* \class L1
* \brief L1 loss over feature vectors: mean absolute difference.
*/
class L1 : public Loss
{
public:
L1()
: Loss(true)
{}
void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
this->m_Value += (fixedOutput - movingOutput).abs().mean(1).sum().item<double>();
}
torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor diffOutput = fixedOutput - movingOutput;
this->m_Value += diffOutput.abs().mean(1).sum().item<double>();
return -torch::sign(diffOutput) / fixedOutput.size(1);
}
};
inline RegisterLoss<L1> L1_reg("L1"); // Register the loss under its string name for factory-based creation
/**
* \class L2
* \brief Mean Squared Error (L2) over feature vectors.
*/
class L2 : public Loss
{
public:
L2()
: Loss(true)
{}
void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
this->m_Value += (fixedOutput - movingOutput).pow(2).mean(1).sum().item<double>();
}
torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor diffOutput = fixedOutput - movingOutput;
this->m_Value += diffOutput.pow(2).mean(1).sum().item<double>();
return -2 * diffOutput / fixedOutput.size(1);
}
};
inline RegisterLoss<L2> MSE_reg("L2"); // Register the loss under its string name for factory-based creation
/**
* \class Dice
* \brief Binary Dice loss (assumes thresholded activations).
*
* Rounds inputs to {0, 1} before computing overlap.
*/
class Dice : public Loss
{
public:
Dice()
: Loss(false)
{}
void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor intersectionSum = (fixedOutput * movingOutput).sum(1); // [N, ...]
torch::Tensor unionSum = (fixedOutput + movingOutput).sum(1); // [N, ...]
// Detect degenerate case: no structure in either output (union == 0)
torch::Tensor isEmpty = (unionSum == 0);
// Make the denominator safe:
// - where unionSum != 0 -> keep unionSum
// - where unionSum == 0 -> replace by 1
// Even though the degenerate positions are overwritten later
// (dice.masked_fill_(isEmpty, 1.0)), we must avoid forming 0/0 here,
// because the division is evaluated eagerly and would otherwise
// create NaNs in intermediate tensors.
torch::Tensor unionSumSafe = unionSum + isEmpty.to(unionSum.scalar_type());
// Standard Dice formulation: 2 * intersection / union
torch::Tensor dice = 2.0 * intersectionSum / unionSumSafe;
// Convention for the degenerate case:
// if both outputs are empty, force Dice = 1 (perfect similarity)
dice.masked_fill_(isEmpty, 1.0);
// Accumulate the loss value
this->m_Value -= dice.sum().item<double>();
}
torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor intersectionSum = (fixedOutput * movingOutput).sum(1); // [N, ...]
torch::Tensor unionSum = (fixedOutput + movingOutput).sum(1); // [N, ...]
// Detect degenerate case: no structure in either output (union == 0)
torch::Tensor isEmpty = (unionSum == 0);
// Make the denominator safe (see updateValue for rationale)
torch::Tensor unionSumSafe = unionSum + isEmpty.to(unionSum.scalar_type());
// Value: standard Dice formulation
torch::Tensor dice = 2.0 * intersectionSum / unionSumSafe;
// Convention for the degenerate case: empty/empty => Dice = 1
dice.masked_fill_(isEmpty, 1.0);
this->m_Value -= dice.sum().item<double>();
// Gradient modulator:
// standard: -2 * (fixedOutput * v - u) / v^2
torch::Tensor grad = -2.0 * (fixedOutput * unionSumSafe.unsqueeze(-1) - intersectionSum.unsqueeze(-1)) /
(unionSumSafe * unionSumSafe).unsqueeze(-1);
// empty/empty => gradient = 0
grad.masked_fill_(isEmpty.unsqueeze(-1), 0.0);
return grad;
}
};
inline RegisterLoss<Dice> Dice_reg("Dice"); // Register the loss under its string name for factory-based creation
/**
* \class L1Cosine
* \brief Combined cosine similarity and exponential L1 loss.
*
* Useful for simultaneously penalizing direction and magnitude.
*/
class L1Cosine : public Loss
{
private:
double m_Lambda;
public:
L1Cosine()
: Loss(false)
{
m_Lambda = 0.1;
}
void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor dotProduct = (fixedOutput * movingOutput).sum(1);
torch::Tensor normFixed = torch::norm(fixedOutput, 2, 1);
torch::Tensor normMoving = torch::norm(movingOutput, 2, 1);
torch::Tensor cosine = dotProduct / (normFixed * normMoving);
torch::Tensor expL1 = torch::exp(-m_Lambda * (fixedOutput - movingOutput).abs());
this->m_Value -= (cosine.unsqueeze(-1) * expL1).mean(1).sum().item<double>();
}
torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor diffOutput = fixedOutput - movingOutput;
torch::Tensor dotProduct = (fixedOutput * movingOutput).sum(1);
torch::Tensor normFixed = torch::norm(fixedOutput, 2, 1);
torch::Tensor normMoving = torch::norm(movingOutput, 2, 1);
torch::Tensor v = (normFixed * normMoving);
torch::Tensor cosine = dotProduct / (v);
torch::Tensor expL1 = torch::exp(-m_Lambda * (fixedOutput - movingOutput).abs());
torch::Tensor dCosine = -(fixedOutput / v.unsqueeze(-1) -
(fixedOutput * movingOutput * movingOutput) / (v * normMoving.pow(2)).unsqueeze(-1));
torch::Tensor dexpL1 = -torch::sign(diffOutput) * expL1 / fixedOutput.size(1);
this->m_Value -= (cosine.unsqueeze(-1) * expL1).mean(1).sum().item<double>();
return dCosine * dexpL1 + cosine.unsqueeze(-1) * dexpL1;
}
};
inline RegisterLoss<L1Cosine> L1CosineReg(
"L1Cosine"); // Register the loss under its string name for factory-based creation
/**
* \class Cosine
* \brief Cosine similarity loss (negative mean cosine between vectors).
*/
class Cosine : public Loss
{
public:
Cosine()
: Loss(false)
{}
void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor dotProduct = (fixedOutput * movingOutput).sum(1);
torch::Tensor normFixed = torch::norm(fixedOutput, 2, 1);
torch::Tensor normMoving = torch::norm(movingOutput, 2, 1);
this->m_Value -= (dotProduct / (normFixed * normMoving)).sum().item<double>();
}
torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
torch::Tensor dotProduct = (fixedOutput * movingOutput).sum(1);
torch::Tensor normFixed = torch::norm(fixedOutput, 2, 1);
torch::Tensor normMoving = torch::norm(movingOutput, 2, 1);
torch::Tensor v = (normFixed * normMoving);
this->m_Value -= (dotProduct / v).sum().item<double>();
return -(fixedOutput / v.unsqueeze(-1) -
(fixedOutput * movingOutput * movingOutput) / (v * normMoving.pow(2)).unsqueeze(-1));
}
};
inline RegisterLoss<Cosine> CosineReg("Cosine"); // Register the loss under its string name for factory-based creation
/**
* \class DotProduct
* \brief Negative dot product loss (simple similarity).
*/
class DotProduct : public Loss
{
public:
DotProduct()
: Loss(false)
{}
void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
this->m_Value -= (fixedOutput * movingOutput).sum(1).sum().item<double>();
}
torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
this->m_Value -= (fixedOutput * movingOutput).sum(1).sum().item<double>();
return -fixedOutput;
}
};
inline RegisterLoss<DotProduct> DotProductReg(
"DotProduct"); // Register the loss under its string name for factory-based creation
/**
* \class NCC
* \brief Normalized Cross Correlation loss over feature vectors.
*
* Computes NCC between fixed and moving features across batches.
* Derivative is accumulated in static mode using full Jacobian tracking.
*/
class NCC : public Loss
{
private:
torch::Tensor m_Sff, m_Smm, m_Sfm, m_Sf, m_Sm;
torch::Tensor m_Sfdm, m_Smdm, m_Sdm;
public:
NCC()
: Loss(false)
{}
void
initialize(torch::Tensor & output) override
{
if (!this->m_Initialized)
{
m_Sff = torch::zeros({ output.size(1) }, output.options());
m_Smm = torch::zeros({ output.size(1) }, output.options());
m_Sfm = torch::zeros({ output.size(1) }, output.options());
m_Sf = torch::zeros({ output.size(1) }, output.options());
m_Sm = torch::zeros({ output.size(1) }, output.options());
m_Initialized = true;
}
}
void
updateValue(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
this->initialize(fixedOutput);
m_Sff += (fixedOutput * fixedOutput).sum(0);
m_Smm += (movingOutput * movingOutput).sum(0);
m_Sfm += (fixedOutput * movingOutput).sum(0);
m_Sf += fixedOutput.sum(0);
m_Sm += movingOutput.sum(0);
}
void
updateValueAndDerivativeInStaticMode(torch::Tensor & fixedOutput,
torch::Tensor & movingOutput,
torch::Tensor & jacobian,
torch::Tensor & nonZeroJacobianIndices) override
{
// Accumulate first-order statistics and weighted Jacobians
// sfdm: sum(fixed * dM), smdm: sum(moving * dM), sdm: sum(dM)
if (!this->m_Initialized)
{
m_Sfdm = torch::zeros({ fixedOutput.size(1), m_NumberOfParameters }, fixedOutput.options());
m_Smdm = torch::zeros({ fixedOutput.size(1), m_NumberOfParameters }, fixedOutput.options());
m_Sdm = torch::zeros({ fixedOutput.size(1), m_NumberOfParameters }, fixedOutput.options());
}
this->updateValue(fixedOutput, movingOutput);
m_Sfdm.index_add_(
1, nonZeroJacobianIndices.flatten(), (fixedOutput.unsqueeze(-1) * jacobian).permute({ 1, 0, 2 }).flatten(1, 2));
m_Smdm.index_add_(
1, nonZeroJacobianIndices.flatten(), (movingOutput.unsqueeze(-1) * jacobian).permute({ 1, 0, 2 }).flatten(1, 2));
m_Sdm.index_add_(1, nonZeroJacobianIndices.flatten(), (jacobian).permute({ 1, 0, 2 }).flatten(1, 2));
}
torch::Tensor
updateValueAndGetGradientModulator(torch::Tensor & fixedOutput, torch::Tensor & movingOutput) override
{
if (!this->m_Initialized)
{
this->m_Derivative = torch::zeros({ this->m_NumberOfParameters }, fixedOutput.options());
}
this->initialize(fixedOutput);
const double N = fixedOutput.size(0);
torch::Tensor sff = (fixedOutput * fixedOutput).sum(0);
torch::Tensor smm = (movingOutput * movingOutput).sum(0);
torch::Tensor sfm = (fixedOutput * movingOutput).sum(0);
torch::Tensor sf = fixedOutput.sum(0);
torch::Tensor sm = movingOutput.sum(0);
m_Sff += sff;
m_Smm += smm;
m_Sfm += sfm;
m_Sf += sf;
m_Sm += sm;
torch::Tensor u = sfm - (sf * sm / N);
torch::Tensor v = torch::sqrt(sff - sf * sf / N) * torch::sqrt(smm - sm * sm / N); // v = a*b
torch::Tensor u_p = fixedOutput - sf.unsqueeze(0) / N;
return -((u_p - u.unsqueeze(0) * (movingOutput - sm.unsqueeze(0) / N) / (smm - sm * sm / N).unsqueeze(0)) /
v.unsqueeze(0)) /
fixedOutput.size(1);
}
double
GetValue(double N) const override
{
// Compute NCC loss from accumulated statistics: mean( -NCC(channel) )
if (N <= 0)
return 0.0;
torch::Tensor u = m_Sfm - (m_Sf * m_Sm / N);
torch::Tensor v = torch::sqrt(m_Sff - m_Sf * m_Sf / N) * torch::sqrt(m_Smm - m_Sm * m_Sm / N);
return -(u / v).mean().item<double>();
}
torch::Tensor
GetDerivative(double N) const override
{
if (this->m_Derivative.defined())
{
return this->m_Derivative.to(torch::kCPU);
}
torch::Tensor u = m_Sfm - (m_Sf * m_Sm / N);
torch::Tensor v = torch::sqrt(m_Sff - m_Sf * m_Sf / N) * torch::sqrt(m_Smm - m_Sm * m_Sm / N);
torch::Tensor u_p = m_Sfdm - m_Sf.unsqueeze(-1) * m_Sdm / N;
return -((u_p -
u.unsqueeze(-1) * (m_Smdm - m_Sm.unsqueeze(-1) * m_Sdm / N) / (m_Smm - m_Sm * m_Sm / N).unsqueeze(-1)) /
v.unsqueeze(-1))
.mean(0)
.to(torch::kCPU);
}
NCC &
operator+=(const Loss & other) override
{
const auto * nccOther = dynamic_cast<const NCC *>(&other);
if (nccOther)
{
m_Sff += nccOther->m_Sff;
m_Smm += nccOther->m_Smm;
m_Sfm += nccOther->m_Sfm;
m_Sf += nccOther->m_Sf;
m_Sm += nccOther->m_Sm;
if (m_Sfdm.defined())
{
m_Sfdm += nccOther->m_Sfdm;
m_Smdm += nccOther->m_Smdm;
m_Sdm += nccOther->m_Sdm;
}
if (m_Derivative.defined())
{
m_Derivative += nccOther->m_Derivative;
}
}
return *this;
}
};
inline RegisterLoss<NCC> NCC_reg("NCC"); // Register the loss under its string name for factory-based creation
} // namespace ImpactLoss
#endif // _ImpactLoss_h
|