Florian Leininger commited on
Commit
d5e1ea2
·
1 Parent(s): 6816d10

updating preprocessor, fixing issue with resampling, resulting in wrong objectivevalue

Browse files
Files changed (1) hide show
  1. preprocessor.py +19 -45
preprocessor.py CHANGED
@@ -8,13 +8,13 @@ Implements the outcome preprocessor contract expected by pyRadPlan's
8
  - ``set_dose_grid(grid)`` precomputes dose<->model sampling coordinates for an
9
  arbitrary optimization dose grid.
10
  - ``preprocess(dose, requires_grad=False)`` resamples the dose onto the model
11
- grid under ``torch.no_grad()``; with ``requires_grad`` the model-grid dose
12
- becomes the autograd leaf, so backward only spans the model. Gradient
13
- smoothness is expected from the model architecture (e.g. BlurPool3d), not
14
- from any explicit smoothing.
15
  - ``postprocess(outputs)`` maps the model logit to a probability (sigmoid).
16
- - ``gradient_to_dose_grid()`` applies the preprocessing chain rule to
17
- ``dose_leaf.grad`` and interpolates it linearly onto the dose grid.
18
 
19
  All parameters (grid size/spacing, HU window, dose normalization, mask
20
  collapsing, input ordering) come from the ``model_preprocessing`` section of
@@ -92,7 +92,6 @@ class OutcomeCnnPreprocessor(BasePreprocessor):
92
  self._model_grid: Optional[dict] = None
93
  self._dose_grid: Optional[dict] = None
94
  self._coords_dose_to_model: Optional[torch.Tensor] = None
95
- self._coords_model_to_dose: Optional[torch.Tensor] = None
96
 
97
  # Leaf of the last preprocess(requires_grad=True) call
98
  self._dose_leaf: Optional[torch.Tensor] = None
@@ -148,7 +147,7 @@ class OutcomeCnnPreprocessor(BasePreprocessor):
148
  )
149
 
150
  def set_dose_grid(self, dose_grid) -> None:
151
- """Precompute dose<->model sampling coordinates for an arbitrary dose grid.
152
 
153
  Parameters
154
  ----------
@@ -162,9 +161,6 @@ class OutcomeCnnPreprocessor(BasePreprocessor):
162
  self._coords_dose_to_model = self._compute_sample_coords(
163
  self._dose_grid, self._model_grid
164
  ).to(self.device)
165
- self._coords_model_to_dose = self._compute_sample_coords(
166
- self._model_grid, self._dose_grid
167
- ).to(self.device)
168
  logger.debug(
169
  "Dose grid set: %s @ %s mm", self._dose_grid["size"], self._dose_grid["spacing"]
170
  )
@@ -182,7 +178,7 @@ class OutcomeCnnPreprocessor(BasePreprocessor):
182
  1-D Fortran-order flat dose array or 3-D (X, Y, Z) array on the
183
  dose grid, in any array namespace (numpy, cupy, torch).
184
  requires_grad : bool
185
- When *True* the model-grid dose becomes an autograd leaf,
186
  afterwards accessible as :attr:`dose_leaf`.
187
 
188
  Returns
@@ -194,11 +190,12 @@ class OutcomeCnnPreprocessor(BasePreprocessor):
194
  if self._coords_dose_to_model is None:
195
  raise RuntimeError("Dose grid not set - call set_dose_grid() first.")
196
 
197
- with torch.no_grad():
198
- dose_src = self._dose_to_tensor(inputs)
199
- dose_5d = dose_src.unsqueeze(0).unsqueeze(0) # (1, 1, dZ, dY, dX)
 
200
  dose_model = F.grid_sample(
201
- dose_5d,
202
  self._coords_dose_to_model,
203
  mode="bilinear",
204
  padding_mode="zeros",
@@ -212,10 +209,6 @@ class OutcomeCnnPreprocessor(BasePreprocessor):
212
  if self.dose_config.get("extract", False):
213
  dose_model = dose_model * self._mask_tensor
214
 
215
- if requires_grad:
216
- dose_model = dose_model.detach().requires_grad_(True)
217
- self._dose_leaf = dose_model if requires_grad else None
218
-
219
  return self.assemble(dose_model, self._ct_tensor, self._mask_tensor)
220
 
221
  def assemble(
@@ -240,44 +233,25 @@ class OutcomeCnnPreprocessor(BasePreprocessor):
240
 
241
  @property
242
  def dose_leaf(self) -> "torch.Tensor":
243
- """The model-grid dose leaf of the last ``preprocess(requires_grad=True)``."""
244
  if self._dose_leaf is None:
245
  raise RuntimeError("No dose leaf - call preprocess(..., requires_grad=True) first.")
246
  return self._dose_leaf
247
 
248
  def gradient_to_dose_grid(self) -> "torch.Tensor":
249
- """Map the model-grid gradient back onto the dose grid.
250
-
251
- Applies the chain rule of the preprocessing (extract mask,
252
- normalization) to ``dose_leaf.grad`` and interpolates the result
253
- linearly onto the dose grid.
254
 
255
  Returns
256
  -------
257
  torch.Tensor
258
  Flat (Fortran-order) float32 gradient of length ``prod(dose grid)``.
259
  """
260
- grad_model = self.dose_leaf.grad
261
- if grad_model is None:
262
  raise RuntimeError("dose_leaf has no gradient - run backward() first.")
263
 
264
- with torch.no_grad():
265
- if self.dose_config.get("extract", False):
266
- grad_model = (grad_model * self._mask_tensor).sum(dim=1, keepdim=True)
267
- norm_value = self.dose_config.get("normalization_value")
268
- if norm_value is not None:
269
- grad_model = grad_model / norm_value
270
-
271
- grad_dose = F.grid_sample(
272
- grad_model,
273
- self._coords_model_to_dose,
274
- mode="bilinear",
275
- padding_mode="zeros",
276
- align_corners=True,
277
- ) # (1, 1, dZ, dY, dX)
278
-
279
- # C-order flatten of (Z, Y, X) equals Fortran-order flatten of (X, Y, Z)
280
- return grad_dose[0, 0].contiguous().to(dtype=torch.float32).reshape(-1)
281
 
282
  # ------------------------------------------------------------------
283
  # Introspection (mainly for debugging / tests)
 
8
  - ``set_dose_grid(grid)`` precomputes dose<->model sampling coordinates for an
9
  arbitrary optimization dose grid.
10
  - ``preprocess(dose, requires_grad=False)`` resamples the dose onto the model
11
+ grid; with ``requires_grad`` the dose-grid dose becomes the autograd leaf, so
12
+ backward runs through the resampling and the gradient is its exact adjoint.
13
+ Gradient smoothness is expected from the model architecture (e.g.
14
+ BlurPool3d), not from any explicit smoothing.
15
  - ``postprocess(outputs)`` maps the model logit to a probability (sigmoid).
16
+ - ``gradient_to_dose_grid()`` returns ``dose_leaf.grad`` as a flat dose-grid
17
+ vector.
18
 
19
  All parameters (grid size/spacing, HU window, dose normalization, mask
20
  collapsing, input ordering) come from the ``model_preprocessing`` section of
 
92
  self._model_grid: Optional[dict] = None
93
  self._dose_grid: Optional[dict] = None
94
  self._coords_dose_to_model: Optional[torch.Tensor] = None
 
95
 
96
  # Leaf of the last preprocess(requires_grad=True) call
97
  self._dose_leaf: Optional[torch.Tensor] = None
 
147
  )
148
 
149
  def set_dose_grid(self, dose_grid) -> None:
150
+ """Precompute dose->model sampling coordinates for an arbitrary dose grid.
151
 
152
  Parameters
153
  ----------
 
161
  self._coords_dose_to_model = self._compute_sample_coords(
162
  self._dose_grid, self._model_grid
163
  ).to(self.device)
 
 
 
164
  logger.debug(
165
  "Dose grid set: %s @ %s mm", self._dose_grid["size"], self._dose_grid["spacing"]
166
  )
 
178
  1-D Fortran-order flat dose array or 3-D (X, Y, Z) array on the
179
  dose grid, in any array namespace (numpy, cupy, torch).
180
  requires_grad : bool
181
+ When *True* the dose-grid dose becomes an autograd leaf,
182
  afterwards accessible as :attr:`dose_leaf`.
183
 
184
  Returns
 
190
  if self._coords_dose_to_model is None:
191
  raise RuntimeError("Dose grid not set - call set_dose_grid() first.")
192
 
193
+ dose_src = self._dose_to_tensor(inputs).requires_grad_(requires_grad)
194
+ self._dose_leaf = dose_src if requires_grad else None
195
+
196
+ with torch.set_grad_enabled(requires_grad):
197
  dose_model = F.grid_sample(
198
+ dose_src.unsqueeze(0).unsqueeze(0), # (1, 1, dZ, dY, dX)
199
  self._coords_dose_to_model,
200
  mode="bilinear",
201
  padding_mode="zeros",
 
209
  if self.dose_config.get("extract", False):
210
  dose_model = dose_model * self._mask_tensor
211
 
 
 
 
 
212
  return self.assemble(dose_model, self._ct_tensor, self._mask_tensor)
213
 
214
  def assemble(
 
233
 
234
  @property
235
  def dose_leaf(self) -> "torch.Tensor":
236
+ """The dose-grid dose leaf of the last ``preprocess(requires_grad=True)``, (dZ, dY, dX)."""
237
  if self._dose_leaf is None:
238
  raise RuntimeError("No dose leaf - call preprocess(..., requires_grad=True) first.")
239
  return self._dose_leaf
240
 
241
  def gradient_to_dose_grid(self) -> "torch.Tensor":
242
+ """Return the gradient w.r.t. the dose-grid dose of the last backward.
 
 
 
 
243
 
244
  Returns
245
  -------
246
  torch.Tensor
247
  Flat (Fortran-order) float32 gradient of length ``prod(dose grid)``.
248
  """
249
+ grad = self.dose_leaf.grad
250
+ if grad is None:
251
  raise RuntimeError("dose_leaf has no gradient - run backward() first.")
252
 
253
+ # C-order flatten of (Z, Y, X) equals Fortran-order flatten of (X, Y, Z)
254
+ return grad.detach().to(dtype=torch.float32).reshape(-1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
  # ------------------------------------------------------------------
257
  # Introspection (mainly for debugging / tests)