diffct 2.5.2__py3-none-any.whl → 2.5.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffct/__init__.py +21 -1
- diffct/_solver_state.py +378 -62
- diffct/analytical.py +21 -2
- diffct/backends.py +16 -5
- diffct/clinical.py +291 -0
- diffct/distribution.py +1 -1
- diffct/kernels/geometry_vjp.py +7 -5
- diffct/kernels/parallel_beam.py +4 -4
- diffct/mayo.py +292 -0
- diffct/operators.py +59 -30
- diffct/pipeline.py +190 -31
- diffct/solvers.py +211 -120
- diffct/utils.py +299 -22
- diffct-2.5.3.dist-info/METADATA +217 -0
- {diffct-2.5.2.dist-info → diffct-2.5.3.dist-info}/RECORD +18 -16
- diffct-2.5.2.dist-info/METADATA +0 -282
- {diffct-2.5.2.dist-info → diffct-2.5.3.dist-info}/WHEEL +0 -0
- {diffct-2.5.2.dist-info → diffct-2.5.3.dist-info}/licenses/LICENSE +0 -0
- {diffct-2.5.2.dist-info → diffct-2.5.3.dist-info}/licenses/NOTICE +0 -0
diffct/__init__.py
CHANGED
|
@@ -15,6 +15,11 @@ from .projectors import (
|
|
|
15
15
|
)
|
|
16
16
|
|
|
17
17
|
from .operators import Projector
|
|
18
|
+
from .clinical import (ClinicalScan, ClinicalScanProbe, ClinicalGeometry, read_dicom_ct_pd,
|
|
19
|
+
probe_dicom_ct_pd, clinical_geometry)
|
|
20
|
+
from .mayo import (CTImageSeries, Mayo2020Case, MayoChallenge2016Case, attenuation_to_hu,
|
|
21
|
+
hu_to_attenuation, discover_mayo_2020_cases, discover_mayo_challenge_2016_cases,
|
|
22
|
+
load_mayo_case, read_dicom_ct_images)
|
|
18
23
|
from .storage import TensorStore, NpyStore
|
|
19
24
|
from .surfaces import ParameterizedSurface
|
|
20
25
|
from .reconstruction import (
|
|
@@ -64,10 +69,25 @@ try:
|
|
|
64
69
|
except ImportError:
|
|
65
70
|
pass
|
|
66
71
|
|
|
67
|
-
__version__ = '2.5.
|
|
72
|
+
__version__ = '2.5.3'
|
|
68
73
|
|
|
69
74
|
__all__ = [
|
|
70
75
|
'Projector',
|
|
76
|
+
'ClinicalScan',
|
|
77
|
+
'ClinicalScanProbe',
|
|
78
|
+
'ClinicalGeometry',
|
|
79
|
+
'read_dicom_ct_pd',
|
|
80
|
+
'probe_dicom_ct_pd',
|
|
81
|
+
'clinical_geometry',
|
|
82
|
+
'CTImageSeries',
|
|
83
|
+
'Mayo2020Case',
|
|
84
|
+
'MayoChallenge2016Case',
|
|
85
|
+
'attenuation_to_hu',
|
|
86
|
+
'hu_to_attenuation',
|
|
87
|
+
'discover_mayo_2020_cases',
|
|
88
|
+
'discover_mayo_challenge_2016_cases',
|
|
89
|
+
'load_mayo_case',
|
|
90
|
+
'read_dicom_ct_images',
|
|
71
91
|
'TensorStore',
|
|
72
92
|
'NpyStore',
|
|
73
93
|
'ParameterizedSurface',
|
diffct/_solver_state.py
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
"""Bounded solver state, owned reductions and complete checkpoint publication."""
|
|
2
2
|
|
|
3
|
+
from contextlib import contextmanager, suppress
|
|
4
|
+
from enum import Enum
|
|
3
5
|
import hashlib
|
|
4
6
|
import json
|
|
5
7
|
import math
|
|
6
8
|
import numbers
|
|
9
|
+
import os
|
|
7
10
|
from pathlib import Path
|
|
11
|
+
import shutil
|
|
8
12
|
|
|
9
13
|
import torch
|
|
10
14
|
import torch.distributed as dist
|
|
@@ -44,6 +48,25 @@ def agreement(operator, error=None, token=None, *, cache_key=None):
|
|
|
44
48
|
mismatch=mismatch)
|
|
45
49
|
|
|
46
50
|
|
|
51
|
+
@contextmanager
|
|
52
|
+
def solver_io_phase(operator):
|
|
53
|
+
"""Agree local solver I/O failures across ranks before the next collective."""
|
|
54
|
+
world = getattr(operator, "world_size", 1)
|
|
55
|
+
if world == 1:
|
|
56
|
+
yield
|
|
57
|
+
return
|
|
58
|
+
error = None
|
|
59
|
+
try:
|
|
60
|
+
yield
|
|
61
|
+
except Exception as caught:
|
|
62
|
+
error = caught
|
|
63
|
+
partition = getattr(operator, "_partition", None)
|
|
64
|
+
if partition is not None:
|
|
65
|
+
partition.preflight(error)
|
|
66
|
+
else:
|
|
67
|
+
preflight(error, process_group=operator.process_group, world_size=world)
|
|
68
|
+
|
|
69
|
+
|
|
47
70
|
def owns_values(operator, kind):
|
|
48
71
|
"""Select one copy of each physical ray or voxel for scalar reductions."""
|
|
49
72
|
partition = getattr(operator, "partition", "views")
|
|
@@ -70,42 +93,58 @@ def scalar_sum(operator, value, kind, *, return_tensor=False):
|
|
|
70
93
|
return float(value)
|
|
71
94
|
|
|
72
95
|
|
|
73
|
-
def
|
|
96
|
+
def _accumulate_scaled_block(peak, total, block):
|
|
97
|
+
if not block.numel():
|
|
98
|
+
return peak, total
|
|
99
|
+
block_peak = block.detach().abs().amax()
|
|
100
|
+
safe = torch.where(block_peak > 0, block_peak, torch.ones_like(block_peak))
|
|
101
|
+
combined = torch.maximum(peak, block_peak)
|
|
102
|
+
guard = torch.where(combined > 0, combined, torch.ones_like(combined))
|
|
103
|
+
updated = (total * (peak / guard).square()
|
|
104
|
+
+ (block.detach() / safe).square().sum() * (block_peak / guard).square())
|
|
105
|
+
return combined, updated
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _scaled_squared_norm(store, elements, device):
|
|
109
|
+
# FP32 devices (MPS): squares of large measurements overflow and tiny
|
|
110
|
+
# geometries underflow, so every block is rescaled by its peak and the
|
|
111
|
+
# running sum follows the largest peak seen. All block math stays on the
|
|
112
|
+
# device; the two closing scalar reads fit the per-iteration reduction
|
|
113
|
+
# budget, and their product leaves FP32 before it can overflow.
|
|
114
|
+
peak = torch.zeros((), device=device, dtype=torch.float32)
|
|
115
|
+
total = torch.zeros((), device=device, dtype=torch.float32)
|
|
116
|
+
for selected in _fragments(tuple(store.shape), elements):
|
|
117
|
+
peak, total = _accumulate_scaled_block(peak, total, store.read(selected))
|
|
118
|
+
return peak.item() ** 2 * total.item()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _local_squared_norm(operator, value, kind, elements=1048576):
|
|
74
122
|
store = TensorStore(value) if isinstance(value, torch.Tensor) else value
|
|
75
123
|
# Scale every block by its own peak before squaring and track the
|
|
76
124
|
# running maximum on the device: unscaled FP32 squares overflow for
|
|
77
125
|
# large measurements and underflow for tiny geometries.
|
|
78
126
|
device = getattr(store, "device", torch.device("cpu"))
|
|
79
127
|
if _work_dtype(device) == torch.float64:
|
|
80
|
-
|
|
128
|
+
local = torch.zeros((), dtype=torch.float64, device=device)
|
|
81
129
|
if owns_values(operator, kind):
|
|
82
130
|
for selected in _fragments(tuple(store.shape), elements):
|
|
83
131
|
# Clone even an FP64 view: norms must never alter caller measurements.
|
|
84
132
|
block = store.read(selected).to(dtype=torch.float64).clone()
|
|
85
133
|
# Preserve the block reductions and their sequential FP64 order.
|
|
86
|
-
|
|
87
|
-
return
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
block_peak = block.detach().abs().amax()
|
|
101
|
-
safe = torch.where(block_peak > 0, block_peak, torch.ones_like(block_peak))
|
|
102
|
-
combined = torch.maximum(peak, block_peak)
|
|
103
|
-
guard = torch.where(combined > 0, combined, torch.ones_like(combined))
|
|
104
|
-
total = (total * (peak / guard).square()
|
|
105
|
-
+ (block.detach() / safe).square().sum() * (block_peak / guard).square())
|
|
106
|
-
peak = combined
|
|
107
|
-
return scalar_sum(operator, peak.item() ** 2 * total.item(), kind,
|
|
108
|
-
return_tensor=return_tensor)
|
|
134
|
+
local.add_(block.square_().sum().to(device=local.device))
|
|
135
|
+
return local
|
|
136
|
+
return _scaled_squared_norm(store, elements, device) if owns_values(operator, kind) else 0.0
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def squared_norm(operator, value, kind, elements=1048576, *, return_tensor=False, before=None):
|
|
140
|
+
if isinstance(value, torch.Tensor) and before is None:
|
|
141
|
+
local = _local_squared_norm(operator, value, kind, elements)
|
|
142
|
+
else:
|
|
143
|
+
with solver_io_phase(operator):
|
|
144
|
+
if before is not None:
|
|
145
|
+
before()
|
|
146
|
+
local = _local_squared_norm(operator, value, kind, elements)
|
|
147
|
+
return scalar_sum(operator, local, kind, return_tensor=return_tensor)
|
|
109
148
|
|
|
110
149
|
|
|
111
150
|
def copy_blocks(source, target, elements):
|
|
@@ -138,6 +177,82 @@ def fingerprint(value, elements):
|
|
|
138
177
|
return digest.hexdigest()
|
|
139
178
|
|
|
140
179
|
|
|
180
|
+
# Prime modulus: 16-bit word products and reduced block sums fit int64.
|
|
181
|
+
_MODULUS = 2 ** 31 - 1
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _logical_positions(shape, selected, device):
|
|
185
|
+
position = torch.zeros(tuple(part.stop - part.start for part in selected),
|
|
186
|
+
dtype=torch.int64, device=device)
|
|
187
|
+
for axis, part in enumerate(selected):
|
|
188
|
+
index = torch.arange(part.start, part.stop, dtype=torch.int64, device=device)
|
|
189
|
+
index.mul_(math.prod(shape[axis + 1:]))
|
|
190
|
+
position.add_(index.view([-1 if other == axis else 1 for other in range(len(shape))]))
|
|
191
|
+
del index
|
|
192
|
+
return position.reshape(-1)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _block_syndromes(block, position, size):
|
|
196
|
+
integer = {1: torch.int8, 2: torch.int16, 4: torch.int32, 8: torch.int64}[block.element_size()]
|
|
197
|
+
flat = torch.empty(block.numel(), dtype=block.dtype, device=block.device)
|
|
198
|
+
flat.copy_(block.reshape(-1))
|
|
199
|
+
bits = flat.view(integer).to(dtype=torch.int64)
|
|
200
|
+
del flat
|
|
201
|
+
for shift in range(0, block.element_size() * 8, 16):
|
|
202
|
+
word = (bits >> shift).bitwise_and_(65535)
|
|
203
|
+
yield word.sum().remainder_(_MODULUS)
|
|
204
|
+
divisor = 1
|
|
205
|
+
while divisor <= size:
|
|
206
|
+
digit = position.div(divisor, rounding_mode="floor").remainder_(_MODULUS)
|
|
207
|
+
yield digit.mul_(word).remainder_(_MODULUS).sum().remainder_(_MODULUS)
|
|
208
|
+
del digit
|
|
209
|
+
divisor *= _MODULUS
|
|
210
|
+
del word
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _checksum_block_elements(shape, dtype, elements):
|
|
214
|
+
size, digits = math.prod(shape), 1
|
|
215
|
+
while size >= _MODULUS:
|
|
216
|
+
size //= _MODULUS
|
|
217
|
+
digits += 1
|
|
218
|
+
lanes = max(1, torch.empty((), dtype=dtype).element_size() // 2)
|
|
219
|
+
# Count all buffers conservatively as int64 slots: five block buffers plus
|
|
220
|
+
# before/old/new scalar syndromes and reduction scratch. Tiny budgets need
|
|
221
|
+
# an unavoidable constant workspace even with one-element blocks.
|
|
222
|
+
scalars = 3 * lanes * (1 + digits) + 4
|
|
223
|
+
return max(1, (elements - scalars) // 5)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _checksum(value, elements):
|
|
227
|
+
"""Separate distance-three codes for each 16-bit lane of logical elements.
|
|
228
|
+
|
|
229
|
+
Each lane has at most two changed words when at most two elements change.
|
|
230
|
+
Its sum and position-weighted sum cannot both cancel modulo the prime.
|
|
231
|
+
Position digits distinguish even iterates larger than the modulus. Only
|
|
232
|
+
scalar syndromes survive a block; no iterate snapshot or host copy is kept.
|
|
233
|
+
"""
|
|
234
|
+
store = TensorStore(value.detach()) if isinstance(value, torch.Tensor) else value
|
|
235
|
+
shape, total = tuple(store.shape), ()
|
|
236
|
+
for selected in _fragments(shape, _checksum_block_elements(shape, store.dtype, elements)):
|
|
237
|
+
block = store.read(selected).detach()
|
|
238
|
+
position = _logical_positions(shape, selected, block.device)
|
|
239
|
+
sums = _block_syndromes(block, position, math.prod(shape))
|
|
240
|
+
total = tuple((old + new).remainder_(_MODULUS) for old, new in zip(total, sums)) if total else tuple(sums)
|
|
241
|
+
del block, position, sums
|
|
242
|
+
return total
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _checksum_changed(before, after):
|
|
246
|
+
changed = False
|
|
247
|
+
for old, new in zip(before, after):
|
|
248
|
+
changed = (old != new) | changed
|
|
249
|
+
return bool(changed)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _layout(value):
|
|
253
|
+
return getattr(value, "device", None), value.dtype, tuple(value.shape)
|
|
254
|
+
|
|
255
|
+
|
|
141
256
|
def _effective_surface(operator, frames, elements):
|
|
142
257
|
"""Hash the actual physical pixel rays, without materializing a volume."""
|
|
143
258
|
surface = getattr(operator, "detector_surface", None)
|
|
@@ -282,43 +397,242 @@ def load_checkpoint(operator, directory, expected, iterations, elements, names):
|
|
|
282
397
|
return saved, states
|
|
283
398
|
|
|
284
399
|
|
|
285
|
-
|
|
286
|
-
|
|
400
|
+
class _CheckpointPhase(str, Enum):
|
|
401
|
+
INIT = "init"
|
|
402
|
+
STAGING = "staging"
|
|
403
|
+
STAGE_AGREE = "stage_agree"
|
|
404
|
+
PUBLISHING = "publishing"
|
|
405
|
+
PUBLISH_AGREE = "publish_agree"
|
|
406
|
+
COMMITTED = "committed"
|
|
407
|
+
CLEANUP = "cleanup"
|
|
408
|
+
ABORTED = "aborted"
|
|
409
|
+
|
|
410
|
+
def __str__(self):
|
|
411
|
+
return self.value
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
_CHECKPOINT_TRANSITIONS = {
|
|
415
|
+
_CheckpointPhase.INIT: (_CheckpointPhase.STAGING,),
|
|
416
|
+
_CheckpointPhase.STAGING: (_CheckpointPhase.STAGE_AGREE,),
|
|
417
|
+
_CheckpointPhase.STAGE_AGREE: (_CheckpointPhase.PUBLISHING, _CheckpointPhase.CLEANUP),
|
|
418
|
+
_CheckpointPhase.PUBLISHING: (_CheckpointPhase.PUBLISH_AGREE,),
|
|
419
|
+
_CheckpointPhase.PUBLISH_AGREE: (_CheckpointPhase.COMMITTED, _CheckpointPhase.CLEANUP),
|
|
420
|
+
_CheckpointPhase.CLEANUP: (_CheckpointPhase.ABORTED,),
|
|
421
|
+
_CheckpointPhase.COMMITTED: (),
|
|
422
|
+
_CheckpointPhase.ABORTED: (),
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _close_npy_store(store):
|
|
427
|
+
array = getattr(store, "_array", None)
|
|
428
|
+
if array is None:
|
|
429
|
+
return
|
|
430
|
+
mmap = getattr(array, "_mmap", None)
|
|
431
|
+
if mmap is not None:
|
|
432
|
+
mmap.close()
|
|
433
|
+
store._array = None
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _mkdir_tracked(step, created=None):
|
|
437
|
+
"""Create missing directories up to ``step``, recording only newly created paths."""
|
|
438
|
+
if created is None:
|
|
439
|
+
created = []
|
|
440
|
+
missing = []
|
|
441
|
+
current = step
|
|
442
|
+
depth = 0
|
|
443
|
+
while current != current.parent and not current.exists():
|
|
444
|
+
missing.append((depth, current))
|
|
445
|
+
current = current.parent
|
|
446
|
+
depth += 1
|
|
447
|
+
for level, path in reversed(missing):
|
|
448
|
+
try:
|
|
449
|
+
path.mkdir()
|
|
450
|
+
except FileExistsError:
|
|
451
|
+
if not path.is_dir():
|
|
452
|
+
raise
|
|
453
|
+
else:
|
|
454
|
+
created.append((level, path))
|
|
455
|
+
return created
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _cleanup_parent_dirs(created_dirs, world, group, *, local_cleanup_failed=False):
|
|
459
|
+
"""Remove attempt-created empty parent directories bottom-up using rmdir only."""
|
|
460
|
+
levels = max((depth + 1 for depth, _ in created_dirs), default=0)
|
|
461
|
+
any_cleanup_failed = bool(local_cleanup_failed)
|
|
462
|
+
if world > 1:
|
|
463
|
+
levels, failed = control_status(
|
|
464
|
+
(levels, int(any_cleanup_failed)), process_group=group, world_size=world,
|
|
465
|
+
)
|
|
466
|
+
any_cleanup_failed = bool(failed)
|
|
467
|
+
by_depth = dict(created_dirs)
|
|
468
|
+
for depth in range(levels):
|
|
469
|
+
if depth in by_depth:
|
|
470
|
+
with suppress(OSError):
|
|
471
|
+
by_depth[depth].rmdir()
|
|
472
|
+
if world > 1:
|
|
473
|
+
control_status((0,), process_group=group, world_size=world)
|
|
474
|
+
return any_cleanup_failed
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _format_cleanup_error(caught):
|
|
478
|
+
detail = str(caught)
|
|
479
|
+
if (isinstance(caught, OSError) and caught.errno is None
|
|
480
|
+
and caught.strerror is None and caught.args):
|
|
481
|
+
message = str(caught.args[0])
|
|
482
|
+
if message and message not in detail:
|
|
483
|
+
detail = f"{message} ({detail})"
|
|
484
|
+
return f"{type(caught).__name__}: {detail}"
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _cleanup_rank_dir(rank_dir, rank):
|
|
287
488
|
try:
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
# failed write, and ranks cannot roll back together.
|
|
294
|
-
raise ValueError(f"checkpoint {rank} already exists; use a new checkpoint_directory "
|
|
295
|
-
"or pass resume= to continue from it")
|
|
296
|
-
rank.mkdir()
|
|
297
|
-
for name, source in states.items():
|
|
298
|
-
source = TensorStore(source.detach()) if isinstance(source, torch.Tensor) else source
|
|
299
|
-
target = NpyStore.create(rank / f"{name}.npy", source.shape, dtype=source.dtype)
|
|
300
|
-
copy_blocks(source, target, elements)
|
|
301
|
-
target.flush()
|
|
302
|
-
manifest[name] = dict(shape=list(source.shape), dtype=str(source.dtype), fingerprint=fingerprint(target, elements))
|
|
303
|
-
except (OSError, ValueError, TypeError) as caught:
|
|
304
|
-
error = caught
|
|
305
|
-
# All owned states on every rank are written and flushed before any rank
|
|
306
|
-
# atomically publishes the metadata marking a completed iteration.
|
|
307
|
-
agreement(operator, error, (iteration, history))
|
|
308
|
-
error = None
|
|
489
|
+
shutil.rmtree(rank_dir)
|
|
490
|
+
except FileNotFoundError:
|
|
491
|
+
pass
|
|
492
|
+
except Exception as caught:
|
|
493
|
+
return rank, str(rank_dir), _format_cleanup_error(caught)
|
|
309
494
|
try:
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
with temporary.open("x", encoding="utf-8") as file:
|
|
314
|
-
json.dump(document, file)
|
|
315
|
-
file.flush()
|
|
316
|
-
temporary.replace(rank / "metadata.json")
|
|
495
|
+
os.lstat(rank_dir)
|
|
496
|
+
except FileNotFoundError:
|
|
497
|
+
return None
|
|
317
498
|
except Exception as caught:
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
499
|
+
return rank, str(rank_dir), _format_cleanup_error(caught)
|
|
500
|
+
return rank, str(rank_dir), "rank directory still exists after cleanup"
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
class _CheckpointAttempt:
|
|
504
|
+
"""Explicit lifecycle state machine for one collective checkpoint save."""
|
|
505
|
+
|
|
506
|
+
def __init__(self, operator=None, directory=None, iteration=None):
|
|
507
|
+
self.phase = _CheckpointPhase.INIT
|
|
508
|
+
self.operator = operator
|
|
509
|
+
self.directory = directory
|
|
510
|
+
self.iteration = iteration
|
|
511
|
+
self.created_dirs = []
|
|
512
|
+
self.rank_dir = None
|
|
513
|
+
self.created_rank = False
|
|
514
|
+
self.manifest = {}
|
|
515
|
+
|
|
516
|
+
def transition(self, target):
|
|
517
|
+
try:
|
|
518
|
+
target_phase = _CheckpointPhase(target)
|
|
519
|
+
except ValueError as error:
|
|
520
|
+
raise RuntimeError(
|
|
521
|
+
f"illegal checkpoint phase {target!r} from {self.phase.value!r}"
|
|
522
|
+
) from error
|
|
523
|
+
if target_phase not in _CHECKPOINT_TRANSITIONS[self.phase]:
|
|
524
|
+
raise RuntimeError(
|
|
525
|
+
f"illegal checkpoint transition from {self.phase.value!r} to {target_phase.value!r}"
|
|
526
|
+
)
|
|
527
|
+
self.phase = target_phase
|
|
528
|
+
return self.phase
|
|
529
|
+
|
|
530
|
+
def stage(self, states, elements):
|
|
531
|
+
self.transition(_CheckpointPhase.STAGING)
|
|
532
|
+
try:
|
|
533
|
+
step = Path(self.directory).resolve() / f"step-{self.iteration:06d}"
|
|
534
|
+
_mkdir_tracked(step, self.created_dirs)
|
|
535
|
+
rank = step / f"rank-{getattr(self.operator, 'rank', 0):05d}"
|
|
536
|
+
self.rank_dir = rank
|
|
537
|
+
if rank.exists() or rank.is_symlink():
|
|
538
|
+
# Replacing a published step in place could destroy it on a
|
|
539
|
+
# failed write, and ranks cannot roll back together.
|
|
540
|
+
raise ValueError(f"checkpoint {rank} already exists; use a new checkpoint_directory "
|
|
541
|
+
"or pass resume= to continue from it")
|
|
542
|
+
rank.mkdir()
|
|
543
|
+
self.created_rank = True
|
|
544
|
+
for name, source in states.items():
|
|
545
|
+
source = TensorStore(source.detach()) if isinstance(source, torch.Tensor) else source
|
|
546
|
+
target = NpyStore.create(rank / f"{name}.npy", source.shape, dtype=source.dtype)
|
|
547
|
+
try:
|
|
548
|
+
copy_blocks(source, target, elements)
|
|
549
|
+
target.flush()
|
|
550
|
+
digest = fingerprint(target, elements)
|
|
551
|
+
finally:
|
|
552
|
+
_close_npy_store(target)
|
|
553
|
+
self.manifest[name] = dict(shape=list(source.shape), dtype=str(source.dtype), fingerprint=digest)
|
|
554
|
+
except Exception as caught:
|
|
555
|
+
return caught
|
|
556
|
+
return None
|
|
557
|
+
|
|
558
|
+
def _abort(self, agreed_error):
|
|
559
|
+
cleanup_report = self.cleanup()
|
|
560
|
+
if cleanup_report is not None:
|
|
561
|
+
raise RuntimeError(
|
|
562
|
+
f"{agreed_error}; checkpoint cleanup failed, leftover checkpoint path(s): {cleanup_report}"
|
|
563
|
+
) from agreed_error
|
|
564
|
+
|
|
565
|
+
def agree_stage(self, error, history):
|
|
566
|
+
# All owned states on every rank are written and flushed before any rank
|
|
567
|
+
# atomically publishes the metadata marking a completed iteration.
|
|
568
|
+
self.transition(_CheckpointPhase.STAGE_AGREE)
|
|
569
|
+
try:
|
|
570
|
+
agreement(self.operator, error, (self.iteration, history))
|
|
571
|
+
except Exception as agreed_error:
|
|
572
|
+
self._abort(agreed_error)
|
|
573
|
+
raise
|
|
574
|
+
|
|
575
|
+
def publish(self, metadata, history, measurement_norm, scalars):
|
|
576
|
+
self.transition(_CheckpointPhase.PUBLISHING)
|
|
577
|
+
try:
|
|
578
|
+
document = dict(metadata, iteration=self.iteration, residual_history=history,
|
|
579
|
+
measurement_norm=measurement_norm, states=self.manifest, **scalars)
|
|
580
|
+
temporary = self.rank_dir / "metadata.tmp"
|
|
581
|
+
with temporary.open("x", encoding="utf-8") as file:
|
|
582
|
+
json.dump(document, file)
|
|
583
|
+
file.flush()
|
|
584
|
+
temporary.replace(self.rank_dir / "metadata.json")
|
|
585
|
+
except Exception as caught:
|
|
586
|
+
return caught
|
|
587
|
+
return None
|
|
588
|
+
|
|
589
|
+
def agree_publish(self, error):
|
|
590
|
+
# A failed metadata write/rename must stop every rank before another
|
|
591
|
+
# projection or callback can enter a numerical collective.
|
|
592
|
+
self.transition(_CheckpointPhase.PUBLISH_AGREE)
|
|
593
|
+
try:
|
|
594
|
+
agreement(self.operator, error, self.iteration)
|
|
595
|
+
except Exception as agreed_error:
|
|
596
|
+
self._abort(agreed_error)
|
|
597
|
+
raise
|
|
598
|
+
self.commit()
|
|
599
|
+
|
|
600
|
+
def commit(self):
|
|
601
|
+
self.transition(_CheckpointPhase.COMMITTED)
|
|
602
|
+
|
|
603
|
+
def cleanup(self):
|
|
604
|
+
self.transition(_CheckpointPhase.CLEANUP)
|
|
605
|
+
rank = getattr(self.operator, "rank", 0)
|
|
606
|
+
world = getattr(self.operator, "world_size", 1)
|
|
607
|
+
group = getattr(self.operator, "process_group", None)
|
|
608
|
+
local_failure = (
|
|
609
|
+
_cleanup_rank_dir(self.rank_dir, rank)
|
|
610
|
+
if self.created_rank and self.rank_dir is not None else None
|
|
611
|
+
)
|
|
612
|
+
any_failed = _cleanup_parent_dirs(
|
|
613
|
+
self.created_dirs, world, group, local_cleanup_failed=local_failure is not None,
|
|
614
|
+
)
|
|
615
|
+
self.transition(_CheckpointPhase.ABORTED)
|
|
616
|
+
if not any_failed:
|
|
617
|
+
return None
|
|
618
|
+
if world == 1:
|
|
619
|
+
failures = [local_failure]
|
|
620
|
+
else:
|
|
621
|
+
failures = [None] * world
|
|
622
|
+
dist.all_gather_object(failures, local_failure, group=group)
|
|
623
|
+
return "; ".join(
|
|
624
|
+
f"rank {failed_rank} ({path}): {detail}"
|
|
625
|
+
for entry in failures if entry is not None
|
|
626
|
+
for failed_rank, path, detail in (entry,)
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def save_checkpoint(operator, directory, states, metadata, iteration, history, measurement_norm, elements, **scalars):
|
|
631
|
+
attempt = _CheckpointAttempt(operator, directory, iteration)
|
|
632
|
+
stage_error = attempt.stage(states, elements)
|
|
633
|
+
attempt.agree_stage(stage_error, history)
|
|
634
|
+
publish_error = attempt.publish(metadata, history, measurement_norm, scalars)
|
|
635
|
+
attempt.agree_publish(publish_error)
|
|
322
636
|
|
|
323
637
|
|
|
324
638
|
def callbacks_enabled(operator, callback):
|
|
@@ -333,10 +647,12 @@ def callback_stop(operator, callback, iteration, residual, volume, *, readonly=F
|
|
|
333
647
|
error, stop = None, False
|
|
334
648
|
try:
|
|
335
649
|
if callback is not None:
|
|
336
|
-
|
|
650
|
+
if readonly:
|
|
651
|
+
layout, before = _layout(volume), _checksum(volume, block_elements)
|
|
337
652
|
stop = callback(iteration, residual, volume) is False
|
|
338
|
-
|
|
339
|
-
|
|
653
|
+
# Layout is host metadata; the storage comparison reads back one flag.
|
|
654
|
+
if readonly and (_layout(volume) != layout or (
|
|
655
|
+
_checksum_changed(before, _checksum(volume, block_elements)))):
|
|
340
656
|
raise ValueError("CGLS callback iterate is read-only")
|
|
341
657
|
except Exception as caught:
|
|
342
658
|
error = caught
|
diffct/analytical.py
CHANGED
|
@@ -107,7 +107,13 @@ def angular_integration_weights(angles, redundant_full_scan=True):
|
|
|
107
107
|
handles their redundancy at the sinogram-filtering stage. Leave
|
|
108
108
|
``redundant_full_scan=True`` for automatic fan/cone scan classification.
|
|
109
109
|
Setting it to ``False`` explicitly disables the full-turn ``1/2`` factor.
|
|
110
|
-
|
|
110
|
+
|
|
111
|
+
Angles are in radians and weights are returned in input order. For a
|
|
112
|
+
short scan wrapped modulo ``2*pi``, the gap outside the acquisition must
|
|
113
|
+
be clearly more than twice every other gap. If the sorted range looks
|
|
114
|
+
like a full turn, that isolated gap marks the scan boundary instead.
|
|
115
|
+
A full turn with a similarly large missing sector is ambiguous from
|
|
116
|
+
angles alone. Pass continuous (unwrapped) angles to ``parker_weights``.
|
|
111
117
|
FP16 and BF16 angles are promoted to FP32; FP64 angles retain their precision.
|
|
112
118
|
"""
|
|
113
119
|
if angles.dtype not in (torch.float32, torch.float64):
|
|
@@ -133,6 +139,19 @@ def angular_integration_weights(angles, redundant_full_scan=True):
|
|
|
133
139
|
span = angles_sorted[-1] - angles_sorted[0]
|
|
134
140
|
period = _angular_scan_period(span, median_step)
|
|
135
141
|
|
|
142
|
+
if period == 2.0 * math.pi and n > 2:
|
|
143
|
+
turn = angles.new_tensor(period)
|
|
144
|
+
closure = turn - span
|
|
145
|
+
gaps, indices = diffs.topk(2)
|
|
146
|
+
other_gap = torch.maximum(gaps[1], closure)
|
|
147
|
+
# Keep endpoint-included turns and turns with a single missing view periodic.
|
|
148
|
+
if (closure > 0) & (gaps[0] > 2.0 * other_gap + 1e-4):
|
|
149
|
+
cut = int(indices[0].item())
|
|
150
|
+
diffs = torch.cat((diffs[cut + 1:], closure[None], diffs[:cut]))
|
|
151
|
+
sort_idx = sort_idx.roll(-cut - 1)
|
|
152
|
+
span = turn - gaps[0]
|
|
153
|
+
period = _angular_scan_period(span, torch.median(diffs))
|
|
154
|
+
|
|
136
155
|
w = torch.zeros(n, device=device, dtype=angles.dtype)
|
|
137
156
|
if period is not None:
|
|
138
157
|
closure = torch.clamp(angles.new_tensor(period) - span, min=0.0)
|
|
@@ -231,7 +250,7 @@ def parker_weights(angles, num_detectors, detector_spacing, sdd, detector_offset
|
|
|
231
250
|
span = angles_sorted[-1] - angles_sorted[0]
|
|
232
251
|
median_step = torch.median(angles_sorted[1:] - angles_sorted[:-1])
|
|
233
252
|
# Full-scan detection depends on acquired angles, not detector fan width.
|
|
234
|
-
# Use
|
|
253
|
+
# Use the same periodic-scan tolerance as angular quadrature.
|
|
235
254
|
if _angular_scan_period(span, median_step) == 2.0 * math.pi:
|
|
236
255
|
# Already a full scan — no Parker needed.
|
|
237
256
|
return torch.ones((n_ang, num_detectors), device=device, dtype=angles.dtype)
|
diffct/backends.py
CHANGED
|
@@ -12,7 +12,7 @@ import torch.distributed as dist
|
|
|
12
12
|
from torch.autograd import forward_ad
|
|
13
13
|
|
|
14
14
|
from .chunking import _memory_lower_bounds
|
|
15
|
-
from .utils import
|
|
15
|
+
from .utils import _active_execution_record, _execution_backward, _work_dtype
|
|
16
16
|
from .distribution import control_status
|
|
17
17
|
from .streaming import _store_phase, _store_rounds
|
|
18
18
|
from .surfaces import ParameterizedSurface
|
|
@@ -222,10 +222,11 @@ class _PortableApply(torch.autograd.Function):
|
|
|
222
222
|
ctx.reference, ctx.is_project = reference, is_project
|
|
223
223
|
ctx.reduce_cotangent = reduce_cotangent
|
|
224
224
|
ctx.dtype = tensor.dtype
|
|
225
|
-
ctx.
|
|
225
|
+
ctx.execution = _active_execution_record()
|
|
226
226
|
ctx.geometry_grad = _PortableApply._geometry_grad_needed(reference.owner, ctx.needs_input_grad[6:])
|
|
227
227
|
ctx.save_for_backward(tensor if ctx.geometry_grad else None, *geometry)
|
|
228
228
|
ctx.save_for_forward(tensor, *geometry)
|
|
229
|
+
ctx.cotangent_metadata = output.shape, output.dtype, output.device
|
|
229
230
|
ctx.set_materialize_grads(False)
|
|
230
231
|
|
|
231
232
|
@staticmethod
|
|
@@ -255,14 +256,17 @@ class _PortableApply(torch.autograd.Function):
|
|
|
255
256
|
|
|
256
257
|
@staticmethod
|
|
257
258
|
def backward(ctx, cotangent):
|
|
258
|
-
# Autograd can run this on a device thread; report
|
|
259
|
-
with
|
|
259
|
+
# Autograd can run this on a device thread; report into the forward's execution record.
|
|
260
|
+
with _execution_backward(ctx.execution):
|
|
260
261
|
return _PortableApply._backward(ctx, cotangent)
|
|
261
262
|
|
|
262
263
|
@staticmethod
|
|
263
264
|
def _backward(ctx, cotangent):
|
|
264
265
|
tensor, *geometry = ctx.saved_tensors
|
|
265
266
|
owner = ctx.reference.owner
|
|
267
|
+
if cotangent is None:
|
|
268
|
+
shape, dtype, device = ctx.cotangent_metadata
|
|
269
|
+
cotangent = torch.zeros(shape, dtype=dtype, device=device)
|
|
266
270
|
gradient = None
|
|
267
271
|
# The adjoint is this Function again, so data second derivatives work.
|
|
268
272
|
# Distributed ranks always run it to keep its collectives in lockstep.
|
|
@@ -1129,7 +1133,8 @@ class ReferenceProjector:
|
|
|
1129
1133
|
|
|
1130
1134
|
def _geometry_grad(self, tensor, cotangent, is_project, reduce_cotangent, geometry):
|
|
1131
1135
|
owner = self.owner
|
|
1132
|
-
|
|
1136
|
+
owner.last_execution_stats = None
|
|
1137
|
+
started = time.perf_counter()
|
|
1133
1138
|
failure = _NumericalFailure(owner.world_size > 1)
|
|
1134
1139
|
# Output replicas contribute one cotangent SUM before local ray math.
|
|
1135
1140
|
output_shape = owner.projection_shape if is_project else owner.volume_shape
|
|
@@ -1146,6 +1151,8 @@ class ReferenceProjector:
|
|
|
1146
1151
|
else:
|
|
1147
1152
|
budget = tuple(None if limit is None else limit // _GEOMETRY_WORK_FACTOR for limit in budget)
|
|
1148
1153
|
plan = self._work_chunks(batch_elements, budget)
|
|
1154
|
+
stats = self._stats(is_project, plan)
|
|
1155
|
+
stats["operation"] = "geometry_vjp"
|
|
1149
1156
|
# One cotangent-sized buffer is outside the work budget. Clone before
|
|
1150
1157
|
# reshaping so a strided cotangent cannot create a second full copy.
|
|
1151
1158
|
# Replicated sums replace disjoint batches or tiles in that same buffer.
|
|
@@ -1241,6 +1248,7 @@ class ReferenceProjector:
|
|
|
1241
1248
|
weights_flat, -1, self._transfer(rays, weights_flat.device),
|
|
1242
1249
|
), device, stats)
|
|
1243
1250
|
accumulate(((selected * lengths).sum(-1) * weights).sum(), leaves, gradients)
|
|
1251
|
+
stats["ray_tile_pairs"] += 1
|
|
1244
1252
|
|
|
1245
1253
|
failure.attempt(pairs)
|
|
1246
1254
|
else:
|
|
@@ -1265,6 +1273,7 @@ class ReferenceProjector:
|
|
|
1265
1273
|
weights = torch.index_select(weights, -1, indices.flatten()).reshape(
|
|
1266
1274
|
*part, *indices.shape)
|
|
1267
1275
|
accumulate((local[..., None] * lengths * weights).sum(), rays, ray_gradients)
|
|
1276
|
+
stats["ray_tile_pairs"] += 1
|
|
1268
1277
|
accumulate((origins * ray_gradients[0]).sum() + (directions * ray_gradients[1]).sum(),
|
|
1269
1278
|
leaves, gradients)
|
|
1270
1279
|
|
|
@@ -1282,6 +1291,8 @@ class ReferenceProjector:
|
|
|
1282
1291
|
result.append(failure.attempt(lambda: torch.cat(pieces).reshape_as(value) if pieces
|
|
1283
1292
|
else torch.zeros_like(value)))
|
|
1284
1293
|
owner._partition.settle(failure.error)
|
|
1294
|
+
stats["elapsed_seconds"] = time.perf_counter() - started
|
|
1295
|
+
owner.last_execution_stats = stats
|
|
1285
1296
|
return tuple(result)
|
|
1286
1297
|
|
|
1287
1298
|
def into(self, source, sink, is_project):
|