faster-diffbloch 0.2.0__py3-none-macosx_14_0_arm64.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.
@@ -0,0 +1,14 @@
1
+ """faster-diffBloch: Metal GPU and CPU acceleration for diffBloch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .backend import enable, disable, matrix_exp, matrix_exp_backward, faster_propagate
6
+
7
+ __version__ = "0.1.7"
8
+ __all__ = [
9
+ "enable",
10
+ "disable",
11
+ "matrix_exp",
12
+ "matrix_exp_backward",
13
+ "faster_propagate",
14
+ ]
@@ -0,0 +1,263 @@
1
+ """Flow and Metal acceleration backend for diffBloch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import warnings
7
+ from typing import Literal
8
+ import numpy as np
9
+ import torch
10
+
11
+ from .builder import (
12
+ build_and_load_library,
13
+ has_metal_support,
14
+ is_apple_silicon,
15
+ is_linux,
16
+ is_macos,
17
+ is_windows,
18
+ )
19
+
20
+ _LIB: ctypes.CDLL | None = None
21
+ _CURRENT_DEVICE: Literal["cpu", "gpu"] = "gpu"
22
+
23
+ # What enable() replaced, keyed by (module name, attribute), so disable() can
24
+ # put it back. A sentinel marks an attribute that did not exist before.
25
+ _MISSING = object()
26
+ _ORIGINALS: dict[tuple[str, str], object] = {}
27
+
28
+
29
+ def get_library() -> ctypes.CDLL | None:
30
+ global _LIB
31
+ if _LIB is None:
32
+ _LIB = build_and_load_library()
33
+ return _LIB
34
+
35
+
36
+ def matrix_exp(a: np.ndarray, device: str = "gpu") -> np.ndarray:
37
+ lib = get_library()
38
+ if lib is None:
39
+ # Fallback to PyTorch ATen
40
+ t = torch.from_numpy(a)
41
+ return torch.matrix_exp(t).numpy()
42
+
43
+ a_c = np.ascontiguousarray(a, dtype=np.complex64)
44
+ out = np.empty_like(a_c)
45
+ n = a_c.shape[-1]
46
+ batch = int(a_c.size // (n * n))
47
+ ptr_in = a_c.ctypes.data_as(ctypes.c_void_p)
48
+ ptr_out = out.ctypes.data_as(ctypes.c_void_p)
49
+
50
+ if device == "gpu" and is_macos():
51
+ fn = getattr(lib, "bridge_matrix_exp_gpu_ptr_c64_i32_i32_ptr_c64", None)
52
+ if fn:
53
+ fn.argtypes = [ctypes.c_void_p, ctypes.c_int32, ctypes.c_int32, ctypes.c_void_p]
54
+ fn.restype = ctypes.c_int32
55
+ if fn(ptr_in, n, batch, ptr_out) == 0:
56
+ return out
57
+
58
+ fn = getattr(lib, "bridge_matrix_exp_ptr_c64_i32_i32_ptr_c64", None)
59
+ if fn:
60
+ fn.argtypes = [ctypes.c_void_p, ctypes.c_int32, ctypes.c_int32, ctypes.c_void_p]
61
+ fn.restype = None
62
+ fn(ptr_in, n, batch, ptr_out)
63
+ return out
64
+
65
+ return torch.matrix_exp(torch.from_numpy(a)).numpy()
66
+
67
+
68
+ def matrix_exp_backward(a: np.ndarray, ebar: np.ndarray, dense: bool = False, device: str = "gpu") -> np.ndarray:
69
+ lib = get_library()
70
+ if lib is None:
71
+ # Custom autograd.Function backward methods run with grad mode disabled.
72
+ # Re-enable it for the correctness fallback.
73
+ with torch.enable_grad():
74
+ tA = torch.from_numpy(a).requires_grad_(True)
75
+ tE = torch.matrix_exp(tA)
76
+ tE.backward(torch.from_numpy(ebar))
77
+ return tA.grad.numpy()
78
+
79
+ a_c = np.ascontiguousarray(a, dtype=np.complex64)
80
+ ebar_c = np.ascontiguousarray(ebar, dtype=np.complex64)
81
+ out = np.empty_like(a_c)
82
+ n = a_c.shape[-1]
83
+ batch = int(a_c.size // (n * n))
84
+ dense_val = 1 if dense else 0
85
+
86
+ ptr_a = a_c.ctypes.data_as(ctypes.c_void_p)
87
+ ptr_ebar = ebar_c.ctypes.data_as(ctypes.c_void_p)
88
+ ptr_out = out.ctypes.data_as(ctypes.c_void_p)
89
+
90
+ if device == "gpu" and is_macos():
91
+ fn = getattr(lib, "bridge_matrix_exp_backward_gpu_ptr_c64_ptr_c64_i32_i32_i32_ptr_c64", None)
92
+ if fn:
93
+ fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int32, ctypes.c_int32, ctypes.c_int32, ctypes.c_void_p]
94
+ fn.restype = ctypes.c_int32
95
+ if fn(ptr_a, ptr_ebar, n, batch, dense_val, ptr_out) == 0:
96
+ return out
97
+
98
+ fn = getattr(lib, "bridge_matrix_exp_backward_ptr_c64_ptr_c64_i32_i32_i32_ptr_c64", None)
99
+ if fn:
100
+ fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int32, ctypes.c_int32, ctypes.c_int32, ctypes.c_void_p]
101
+ fn.restype = None
102
+ fn(ptr_a, ptr_ebar, n, batch, dense_val, ptr_out)
103
+ return out
104
+
105
+ tA = torch.from_numpy(a).requires_grad_(True)
106
+ tE = torch.matrix_exp(tA)
107
+ tE.backward(torch.from_numpy(ebar))
108
+ return tA.grad.numpy()
109
+
110
+
111
+ class FasterMatrixExp(torch.autograd.Function):
112
+ @staticmethod
113
+ def forward(ctx, m: torch.Tensor) -> torch.Tensor:
114
+ source = m.detach().resolve_conj().contiguous()
115
+ exp_np = matrix_exp(source.cpu().numpy(), device=_CURRENT_DEVICE)
116
+ ctx.save_for_backward(source)
117
+ return torch.from_numpy(exp_np).to(device=m.device)
118
+
119
+ @staticmethod
120
+ @torch.autograd.function.once_differentiable
121
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
122
+ (source,) = ctx.saved_tensors
123
+ cotangent = grad_output.resolve_conj().contiguous().to(torch.complex64)
124
+ pullback_np = matrix_exp_backward(source.cpu().numpy(), cotangent.cpu().numpy(), dense=False, device=_CURRENT_DEVICE)
125
+ return torch.from_numpy(pullback_np).to(device=grad_output.device)
126
+
127
+
128
+ def faster_propagate_matrix_exp(system, thicknesses, *, max_batch=None):
129
+ from diffBloch.core.solver import _complex_operator
130
+ a = _complex_operator(system.a).to(torch.complex64)
131
+ psi0 = system.psi0.to(dtype=a.dtype, device=a.device)
132
+ scalars = (1j * torch.pi * thicknesses / system.k_n).to(a.dtype)
133
+ if max_batch is None:
134
+ transfer = FasterMatrixExp.apply(a.unsqueeze(-3) * scalars[:, None, None])
135
+ return (transfer @ psi0.unsqueeze(-1)).squeeze(-1)
136
+ n = a.shape[-1]
137
+ a_flat = a.reshape(-1, n, n)
138
+ n_batch, n_thick = a_flat.shape[0], scalars.shape[0]
139
+ total = n_batch * n_thick
140
+ amplitudes = []
141
+ for start in range(0, total, max_batch):
142
+ flat = torch.arange(start, min(total, start + max_batch), device=a.device)
143
+ block = a_flat[flat // n_thick] * scalars[flat % n_thick][:, None, None]
144
+ amplitudes.append((FasterMatrixExp.apply(block) @ psi0.unsqueeze(-1)).squeeze(-1))
145
+ return torch.cat(amplitudes, dim=0).reshape(*a.shape[:-2], n_thick, n)
146
+
147
+
148
+ def faster_propagate(system, thicknesses, *, method="matrix_exp", max_batch=None):
149
+ from diffBloch.core.solver import _propagate_bloch_eigen
150
+ if max_batch is not None and max_batch < 1:
151
+ raise ValueError(f"max_batch must be a positive integer or None, got {max_batch}")
152
+ t = torch.as_tensor(thicknesses, dtype=torch.float32, device=system.a.device)
153
+ if t.ndim == 0:
154
+ t = t.reshape(1)
155
+ if t.ndim != 1:
156
+ raise ValueError("thicknesses must be a scalar or 1-D sequence")
157
+ if method == "matrix_exp":
158
+ return faster_propagate_matrix_exp(system, t, max_batch=max_batch)
159
+ if method == "bloch_eigen":
160
+ return _propagate_bloch_eigen(system, t)
161
+ raise ValueError(f"method must be 'matrix_exp' or 'bloch_eigen', got {method!r}")
162
+
163
+
164
+ def enable(device: Literal["cpu", "gpu"] = "gpu") -> None:
165
+ """Inject faster-diffbloch acceleration into diffBloch runtime with platform checking."""
166
+ global _CURRENT_DEVICE
167
+
168
+ if device == "gpu":
169
+ if not is_macos():
170
+ warnings.warn(
171
+ "Metal GPU acceleration is available on macOS only. "
172
+ "Automatically selecting device='cpu' on this platform.",
173
+ UserWarning,
174
+ stacklevel=2,
175
+ )
176
+ device = "cpu"
177
+ elif not is_apple_silicon():
178
+ warnings.warn(
179
+ "Metal GPU acceleration is optimized for Apple Silicon unified memory. "
180
+ "Running on Intel macOS.",
181
+ UserWarning,
182
+ stacklevel=2,
183
+ )
184
+
185
+ _CURRENT_DEVICE = device
186
+ import importlib
187
+ try:
188
+ solver = importlib.import_module("diffBloch.core.solver")
189
+ _remember(solver, "_propagate_matrix_exp")
190
+ _remember(solver, "propagate")
191
+ solver._propagate_matrix_exp = faster_propagate_matrix_exp
192
+ solver.propagate = faster_propagate
193
+ for mod_name in ("diffBloch.core", "diffBloch.engine.forward"):
194
+ try:
195
+ mod = importlib.import_module(mod_name)
196
+ _remember(mod, "propagate")
197
+ setattr(mod, "propagate", faster_propagate)
198
+ except Exception:
199
+ pass
200
+ except ImportError:
201
+ pass
202
+
203
+ # Structure factors are the larger cost below roughly 163 beams, where the
204
+ # matrix exponential is small. Both call sites import the name at module
205
+ # scope, so each module's own attribute has to be replaced.
206
+ try:
207
+ from .scattering import faster_structure_factors, remember_original
208
+
209
+ scattering = importlib.import_module("diffBloch.core.scattering")
210
+ remember_original(scattering.structure_factors)
211
+ for mod_name in (
212
+ "diffBloch.core.scattering",
213
+ "diffBloch.core",
214
+ "diffBloch.engine.forward",
215
+ "diffBloch.preprocess.experiment",
216
+ ):
217
+ try:
218
+ mod = importlib.import_module(mod_name)
219
+ if hasattr(mod, "structure_factors"):
220
+ _remember(mod, "structure_factors")
221
+ setattr(mod, "structure_factors", faster_structure_factors)
222
+ except Exception:
223
+ pass
224
+ except ImportError:
225
+ pass
226
+
227
+
228
+ def _remember(module, name: str) -> None:
229
+ """Record a module attribute the first time it is replaced.
230
+
231
+ Only the first value is kept, so calling enable() twice does not record
232
+ the accelerated function as the thing to restore.
233
+ """
234
+ key = (module.__name__, name)
235
+ if key not in _ORIGINALS:
236
+ _ORIGINALS[key] = getattr(module, name, _MISSING)
237
+
238
+
239
+ def disable() -> None:
240
+ """Put diffBloch's own functions back.
241
+
242
+ Undoes what enable() replaced, so a later call runs stock diffBloch.
243
+ Calling this without a preceding enable() does nothing.
244
+ """
245
+ import importlib
246
+
247
+ for (mod_name, attr), original in list(_ORIGINALS.items()):
248
+ try:
249
+ module = importlib.import_module(mod_name)
250
+ except ImportError:
251
+ continue
252
+ if original is _MISSING:
253
+ if hasattr(module, attr):
254
+ delattr(module, attr)
255
+ else:
256
+ setattr(module, attr, original)
257
+ _ORIGINALS.clear()
258
+ try:
259
+ from .scattering import forget_original
260
+
261
+ forget_original()
262
+ except ImportError:
263
+ pass
@@ -0,0 +1,122 @@
1
+ """Native runtime builder, platform guards, and loader for faster-diffbloch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import os
7
+ import platform
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import warnings
12
+ from pathlib import Path
13
+
14
+ NATIVE_DIR = Path(__file__).resolve().parent / "native"
15
+ BUILD_DIR = Path.home() / ".cache" / "faster_diffbloch"
16
+
17
+
18
+ def is_macos() -> bool:
19
+ return sys.platform == "darwin"
20
+
21
+
22
+ def is_apple_silicon() -> bool:
23
+ return is_macos() and platform.machine() in ("arm64", "aarch64")
24
+
25
+
26
+ def is_linux() -> bool:
27
+ return sys.platform.startswith("linux")
28
+
29
+
30
+ def is_windows() -> bool:
31
+ return sys.platform.startswith("win") or sys.platform == "cygwin"
32
+
33
+
34
+ def has_metal_support() -> bool:
35
+ if not is_macos():
36
+ return False
37
+ # Check if xcrun and metal compiler are available
38
+ return shutil.which("xcrun") is not None
39
+
40
+
41
+ def get_c_compiler() -> str | None:
42
+ for cc in ("clang", "gcc", "cc"):
43
+ if shutil.which(cc) is not None:
44
+ return cc
45
+ return None
46
+
47
+
48
+ def build_and_load_library() -> ctypes.CDLL | None:
49
+ """Build or load the cached native acceleration library with platform guards."""
50
+ if is_windows():
51
+ warnings.warn(
52
+ "faster-diffbloch native acceleration is not currently supported on Windows. "
53
+ "Falling back to standard PyTorch execution.",
54
+ RuntimeWarning,
55
+ stacklevel=2,
56
+ )
57
+ return None
58
+
59
+ compiler = get_c_compiler()
60
+ if compiler is None:
61
+ warnings.warn(
62
+ "No C compiler (clang/gcc) found. "
63
+ "Install clang or build-essential to enable faster-diffbloch acceleration. "
64
+ "Falling back to standard PyTorch execution.",
65
+ RuntimeWarning,
66
+ stacklevel=2,
67
+ )
68
+ return None
69
+
70
+ BUILD_DIR.mkdir(parents=True, exist_ok=True)
71
+ lib_name = "libfaster_diffbloch.dylib" if is_macos() else "libfaster_diffbloch.so"
72
+ lib_path = BUILD_DIR / lib_name
73
+
74
+ sources = [
75
+ NATIVE_DIR / "bridge_lib.c",
76
+ NATIVE_DIR / "batch_cgemm.c",
77
+ NATIVE_DIR / "native_scattering.c",
78
+ ]
79
+
80
+ if is_macos():
81
+ sources.append(NATIVE_DIR / "metal_batch_cgemm.m")
82
+ if has_metal_support():
83
+ metal_src = NATIVE_DIR / "batch_cgemm.metal"
84
+ metallib_path = BUILD_DIR / "batch_cgemm.metallib"
85
+ if metal_src.exists() and (not metallib_path.exists() or metallib_path.stat().st_mtime < metal_src.stat().st_mtime):
86
+ try:
87
+ subprocess.run(
88
+ ["xcrun", "-sdk", "macosx", "metal", "-O3", "-c", str(metal_src), "-o", str(BUILD_DIR / "batch_cgemm.air")],
89
+ check=True, capture_output=True,
90
+ )
91
+ subprocess.run(
92
+ ["xcrun", "-sdk", "macosx", "metallib", str(BUILD_DIR / "batch_cgemm.air"), "-o", str(metallib_path)],
93
+ check=True, capture_output=True,
94
+ )
95
+ except Exception as exc:
96
+ warnings.warn(f"Metal shader precompilation skipped: {exc}", RuntimeWarning, stacklevel=2)
97
+
98
+ stale = not lib_path.exists() or any(lib_path.stat().st_mtime < s.stat().st_mtime for s in sources if s.exists())
99
+ if stale:
100
+ frameworks = ["-framework", "Accelerate", "-framework", "Metal", "-framework", "Foundation"] if is_macos() else ["-lblas"]
101
+ cmd = [
102
+ compiler, "-std=c11", "-O3", "-fPIC", "-shared",
103
+ "-D_DEFAULT_SOURCE", "-Wno-unused-function", "-Wno-unused-variable",
104
+ f"-I{NATIVE_DIR}",
105
+ *[str(s) for s in sources if s.exists()],
106
+ *frameworks, "-lm", "-o", str(lib_path),
107
+ ]
108
+ res = subprocess.run(cmd, capture_output=True, text=True)
109
+ if res.returncode != 0:
110
+ warnings.warn(
111
+ f"Failed to build faster-diffbloch native library with {compiler}:\n{res.stderr}\n"
112
+ "Falling back to standard PyTorch execution.",
113
+ RuntimeWarning,
114
+ stacklevel=2,
115
+ )
116
+ return None
117
+
118
+ try:
119
+ return ctypes.CDLL(str(lib_path))
120
+ except Exception as exc:
121
+ warnings.warn(f"Could not load faster-diffbloch library: {exc}", RuntimeWarning, stacklevel=2)
122
+ return None
@@ -0,0 +1,57 @@
1
+ """CLI wrapper enabling faster-diffbloch before running diffbloch commands.
2
+
3
+ faster-diffbloch <diffbloch command ...> Metal GPU acceleration, then diffBloch
4
+ faster-diffbloch refine --exact <experiment> diffBloch's refinement run in Flow,
5
+ bit for bit with `diffbloch refine`
6
+
7
+ --exact needs the macOS arm64 wheel, which ships the prebuilt Flow binary.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import sys
13
+
14
+ # The versions --exact was checked against, bit for bit, on an M4 Max under macOS 26.
15
+ EXACT_TORCH = "2.14."
16
+ EXACT_DIFFBLOCH = ("https://github.com/Differentiable-Electron-Crystallography/diffBloch",
17
+ "1291356")
18
+
19
+
20
+ def _exact(argv: list[str]) -> int:
21
+ try:
22
+ from .exact.cli import main as exact_main
23
+ from .exact.toolchain import bundled_backends
24
+ except ImportError as err:
25
+ print(f"faster-diffbloch: --exact is not in this install ({err}).\n"
26
+ "It ships in the macOS arm64 wheel only.", file=sys.stderr)
27
+ return 1
28
+ if not bundled_backends():
29
+ print("faster-diffbloch: --exact needs the macOS arm64 wheel, which ships the Flow binary.",
30
+ file=sys.stderr)
31
+ return 1
32
+ import torch
33
+ if not torch.__version__.startswith(EXACT_TORCH):
34
+ print(f"faster-diffbloch: warning: --exact matches diffBloch bit for bit under torch "
35
+ f"{EXACT_TORCH}x; this is torch {torch.__version__}, so the last bits may differ.",
36
+ file=sys.stderr)
37
+ return exact_main(argv)
38
+
39
+
40
+ def main() -> None:
41
+ argv = sys.argv[1:]
42
+ if argv[:1] == ["refine"] and "--exact" in argv:
43
+ # Exact mode runs diffBloch untouched apart from its optimizer loop: no acceleration.
44
+ sys.exit(_exact([a for a in argv if a != "--exact"]))
45
+ # Enable Metal GPU acceleration by default
46
+ from .backend import enable
47
+ enable(device="gpu")
48
+ try:
49
+ from diffBloch.app.cli import main as diffbloch_main
50
+ diffbloch_main()
51
+ except ImportError:
52
+ print("Error: diffbloch is not installed. Install diffbloch or run 'pip install diffbloch'.", file=sys.stderr)
53
+ sys.exit(1)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
File without changes
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
Binary file
@@ -0,0 +1,204 @@
1
+ """diffBloch's refinement loop, run by diffFlow.
2
+
3
+ `flow_refinement` has run_refinement_model's signature and contract. diffBloch's app calls it
4
+ in place of its own loop; it exports the problem, runs flow/experiment.flow, and reports
5
+ every step through diffBloch's own logger with diffBloch's own event types, so the console,
6
+ the reports and the written structure are diffBloch's code end to end. Only the arithmetic of
7
+ the objective, its gradient and the optimizer step is Flow's.
8
+
9
+ Flow streams, after each step's objective and before its update: the loss, every rotation's
10
+ wR2, R(obs) and loss term, the parameters behind the step and their gradient. The loop it
11
+ mirrors reports a step's structure drift after that step's update, so a step's event is
12
+ emitted once the next step's parameters (or the final ones) have arrived.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import dataclasses
18
+ import math
19
+ import os
20
+ import subprocess
21
+ import tempfile
22
+ import time
23
+ from pathlib import Path
24
+ from types import MappingProxyType
25
+
26
+ import numpy as np
27
+ import torch
28
+
29
+ from diffBloch.engine import forward as fwd
30
+ from diffBloch.engine.refine import (
31
+ ObjectiveComponent,
32
+ ObjectiveValue,
33
+ _component_measurements,
34
+ _resolve_trainable,
35
+ _to_trainable_params,
36
+ )
37
+ from diffBloch.observability import (
38
+ ObjectiveManifest,
39
+ ObjectiveTerm,
40
+ RefinementCompleted,
41
+ RefinementOrientationStep,
42
+ RefinementStarted,
43
+ RefinementStep,
44
+ )
45
+ from diffBloch.observability import NULL_LOGGER
46
+
47
+ from . import export as exporter
48
+ from .toolchain import experiment_binary
49
+
50
+ NN_KEYS = exporter.NN_KEYS
51
+
52
+
53
+ def _params_from_leaves(model, leaves: np.ndarray, nn_key: str):
54
+ """A RefinementModel whose trainable fields are `leaves` ([positions | uij_raw | net])."""
55
+ initial = model.structure.initial
56
+ n_asu = int(initial.asu_positions.shape[0])
57
+ pos = torch.from_numpy(leaves[: n_asu * 3].copy()).reshape(n_asu, 3)
58
+ uij = torch.from_numpy(leaves[n_asu * 3: n_asu * 12].copy()).reshape(n_asu, 3, 3)
59
+ at = n_asu * 12
60
+ net = {}
61
+ for key in NN_KEYS:
62
+ shape = model.component_params[nn_key][key].shape
63
+ n = int(np.prod(shape))
64
+ net[key] = torch.from_numpy(leaves[at:at + n].copy()).reshape(shape)
65
+ at += n
66
+ structure = dataclasses.replace(model.structure,
67
+ initial=dataclasses.replace(initial, asu_positions=pos, uij_raw=uij))
68
+ return dataclasses.replace(model, structure=structure,
69
+ component_params=MappingProxyType({nn_key: MappingProxyType(net)}))
70
+
71
+
72
+ def flow_refinement(engine, model, problem, *, trainable, steps, optimizer="adam", lr=1e-3,
73
+ logger=NULL_LOGGER, verbose=False, profile=False, selection_engine=None,
74
+ device="cpu", backend="mlir"):
75
+ if steps < 1:
76
+ raise ValueError("steps must be >= 1")
77
+ if selection_engine is not None:
78
+ raise SystemExit("diffflow: a validation split (refinement.split.train_test) is not supported yet")
79
+ (nn,) = model.components
80
+ work = Path(tempfile.mkdtemp(prefix="diffflow-"))
81
+ # DIFFFLOW_REUSE_EXPERIMENT names an experiment.bin already exported from this same run
82
+ # directory; the export is skipped. A CsPbBr3 or borane export is about 1 GB and costs memory.
83
+ reuse = os.environ.get("DIFFFLOW_REUSE_EXPERIMENT")
84
+ if reuse:
85
+ experiment = Path(reuse)
86
+ if not experiment.is_file():
87
+ raise SystemExit(f"diffflow: DIFFFLOW_REUSE_EXPERIMENT={reuse} does not exist")
88
+ else:
89
+ experiment = work / "experiment.bin"
90
+ exporter.export(engine, model, problem,
91
+ dict(trainable=trainable, steps=steps, optimizer=optimizer, lr=lr), experiment)
92
+
93
+ manifest = ObjectiveManifest(
94
+ penalties=tuple(ObjectiveTerm(name=p.name, weight=p.weight) for p in problem.penalties),
95
+ constraints=tuple(c.name for c in model.structure.constraints),
96
+ components=tuple(c.key for c in model.components),
97
+ )
98
+ logger.report(manifest)
99
+ logger.report(RefinementStarted(total_steps=steps))
100
+ with torch.no_grad():
101
+ reference_state = engine.physical_state(model.structure.initial)
102
+
103
+ n_orient = len(engine.orientations)
104
+ n_leaves = sum(int(np.prod(t.shape)) for t in (model.structure.initial.asu_positions,
105
+ model.structure.initial.uij_raw)) \
106
+ + sum(int(np.prod(model.component_params[nn.key][k].shape)) for k in NN_KEYS)
107
+ block = 1 + 3 * n_orient + 2 * n_leaves
108
+
109
+ stream = work / "stream.bin"
110
+ out = work / "result.bin"
111
+ env = dict(os.environ, DIFFFLOW_EXPERIMENT=str(experiment), DIFFFLOW_OUT=str(out),
112
+ DIFFFLOW_STREAM=str(stream), DIFFFLOW_STEPS=str(steps))
113
+ if device == "gpu":
114
+ env["DIFFFLOW_DEVICE"] = "gpu"
115
+ stream.write_bytes(b"") # exists before Flow reopens it, so the reader can open it now
116
+ proc = subprocess.Popen([str(experiment_binary(backend))], env=env,
117
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
118
+
119
+ losses: list[float] = []
120
+ history: list[RefinementStep] = []
121
+ best_loss, best_step, best_model = math.inf, 0, None
122
+ pending = None # (step, loss, wr2s, robss, terms, model snapshot) awaiting its post-update params
123
+
124
+ def emit(step, loss, wr2s, robss, terms, snapshot, after):
125
+ nonlocal best_loss, best_step, best_model
126
+ finite_wr2 = [v for v in wr2s if math.isfinite(v)]
127
+ finite_robs = [v for v in robss if math.isfinite(v)]
128
+ total = torch.tensor(loss, dtype=torch.float64)
129
+ objective = ObjectiveValue({"diffraction": ObjectiveComponent(raw=total)})
130
+ position_rmsd, ueq_rmsd = fwd._structure_drift(engine, reference_state, after.structure.initial)
131
+ event = RefinementStep(
132
+ iteration=step,
133
+ loss=loss,
134
+ wr2=sum(finite_wr2) / len(finite_wr2) if finite_wr2 else float("nan"),
135
+ r_obs=sum(finite_robs) / len(finite_robs) if finite_robs else float("nan"),
136
+ diff_loss=loss,
137
+ objective_total=loss,
138
+ components=_component_measurements(objective),
139
+ n_rotations=n_orient,
140
+ n_wr2_evaluated=len(finite_wr2),
141
+ n_r_obs_evaluated=len(finite_robs),
142
+ val_wr2=None, val_r_obs=None, val_n_rotations=None,
143
+ val_n_wr2_evaluated=None, val_n_r_obs_evaluated=None,
144
+ position_rmsd=position_rmsd,
145
+ ueq_rmsd=ueq_rmsd,
146
+ )
147
+ history.append(event)
148
+ logger.report(event)
149
+ if verbose:
150
+ for r, o in enumerate(engine.orientations):
151
+ logger.report(RefinementOrientationStep(
152
+ iteration=step, rotation_index=int(o.pattern.rotation_index),
153
+ wr2=wr2s[r], r_obs=robss[r], diff_loss=terms[r]))
154
+ if loss < best_loss:
155
+ best_loss, best_step, best_model = loss, step, snapshot
156
+
157
+ fh = open(stream, "rb")
158
+ step = 0
159
+ while step < steps:
160
+ line = proc.stdout.readline()
161
+ if not line:
162
+ if proc.poll() is not None:
163
+ break
164
+ continue
165
+ if not line.lstrip().startswith("step"):
166
+ continue
167
+ raw = b""
168
+ while len(raw) < block * 8:
169
+ chunk = fh.read(block * 8 - len(raw))
170
+ if not chunk:
171
+ time.sleep(0.001)
172
+ continue
173
+ raw += chunk
174
+ v = np.frombuffer(raw, "<f8")
175
+ loss = float(v[0])
176
+ wr2s, robss, terms = (v[1:1 + n_orient].tolist(), v[1 + n_orient:1 + 2 * n_orient].tolist(),
177
+ v[1 + 2 * n_orient:1 + 3 * n_orient].tolist())
178
+ leaves = v[1 + 3 * n_orient:1 + 3 * n_orient + n_leaves]
179
+ snapshot = _params_from_leaves(model, leaves, nn.key)
180
+ losses.append(loss)
181
+ if pending is not None:
182
+ emit(*pending, after=snapshot)
183
+ pending = (step, loss, wr2s, robss, terms, snapshot)
184
+ step += 1
185
+ rc = proc.wait()
186
+ if rc != 0 or step != steps:
187
+ raise SystemExit(f"diffflow: the Flow refinement stopped (exit {rc}):\n{proc.stderr.read()}")
188
+ fh.close()
189
+ # result.bin: 8 x i32 header, then f64 losses[steps], grad0[n_leaves], final[n_leaves], ...
190
+ body = np.frombuffer(out.read_bytes()[32:], "<f8")
191
+ final_model = _params_from_leaves(model, body[steps + n_leaves: steps + 2 * n_leaves], nn.key)
192
+ emit(*pending, after=final_model)
193
+
194
+ _, n_matched, n_strong, n_weak, n_unmatched = engine.refinement_metrics(best_model)
195
+ reflection_counts = MappingProxyType({
196
+ "matched": n_matched, "matched_i_gt_3sigma": n_strong,
197
+ "matched_i_le_3sigma": n_weak, "unmatched_observed": n_unmatched,
198
+ })
199
+ logger.report(RefinementCompleted(n_steps=steps, best_step=best_step, best_loss=best_loss,
200
+ selection="training", reflection_counts=reflection_counts))
201
+ return fwd.ModelRefinementResult(
202
+ model=final_model, losses=torch.tensor(losses, dtype=torch.float64), best_model=best_model,
203
+ best_step=best_step, selection_losses=None, history=tuple(history),
204
+ reflection_counts=reflection_counts, objective_manifest=manifest)