Repository navigation
AutoSerialize: safe loading by default, quantEM version in saved files, reconstructions without pickle - #319
Conversation
Rewrite serialize.py around one writer and one reader. Loading was written out four times (object attributes, lists/tuples, sets, dicts) and the copies had drifted: dill fallbacks inside containers loaded as raw bytes, optimizers, ase Atoms and RNGs inside containers raised, and nested objects in containers ignored skips. The module drops from 1682 to ~990 lines and the private helpers no longer live on every AutoSerialize subclass. load() no longer unpickles by default. Torch modules, optimizers, schedulers and dill fallbacks load only with allow_pickle=True; without it, load raises one error listing every pickled value, and nothing from them runs. Tensors load through torch's weights_only reader. The class named in a file must be an AutoSerialize class. Ptychography, PtychoLite and Tomography.from_file take allow_pickle and forward it. To keep everyday objects pickle-free, torch dtypes are stored as strings, torch generators as their device, seed and state, and EventStack and FourierProbe are AutoSerialize. Dill fallbacks are now marked by a "_dill" group; older files' gzip-in-uint8 payloads are still recognized. Saved files record the quantem version in the root "_autoserialize" metadata, shown by print_file. Also fixes: 0-d arrays loaded as uninitialized memory; loaded objects carried _autoserialize_skip_* attributes; loading walked dir(obj) and evaluated properties. CrystalMap's after-load hook is renamed from __attrs_post_init__ to _post_load, the one hook load calls; attrs-class support (unused in quantem) is dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Torch modules, optimizers and schedulers, and dataclasses, are stored as groups of their state instead of pickles, so ptychography and tomography reconstructions load with allow_pickle=False. - Modules: their __dict__ without internals left at their defaults, restored with nn.Module.__setstate__. - Optimizers: defaults, state_dict and parameters, restored with the constructor and load_state_dict (this also fixes LBFGS, which pickling left unable to step). - Schedulers: state_dict and optimizer, restored with load_state_dict. - A tensor or object held in several places, such as a parameter of a model and its optimizer, is written once and referenced elsewhere, so a loaded optimizer updates the loaded model. - Dicts keep their key order and int keys, so nn.Sequential layers load in order. - Without allow_pickle, modules, optimizers, schedulers and dataclasses defined outside quantem and torch are refused, like pickles. Older files still load; their pickled modules still need allow_pickle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Saving a reconstruction mid-run, loading it without pickle and continuing now matches the run that was never saved, bit for bit, for every ptychography and tomography model checked. - Classes and functions that models keep as attributes, such as the CNN's nn.BatchNorm2d and torch.cat, are stored by name instead of pickled, so DIP reconstructions load without pickle. Without allow_pickle, only names from quantem and torch are imported. - Only importable classes are stored as groups; a class defined in a function falls back to dill instead of writing a file that cannot load. - NumPy generators keep their state, so the batch order continues. - K-Planes' default density_activation is a module-level function and CallableWrapper is defined at module level, so both save without pickle. - Tomography.save skips data loaders, samplers and the pretraining data; a validation split used to pickle val_dataloader. - The tomography datasets' .to() moves the pose parameters in place, so the pose optimizer keeps its state after from_file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
arthurmccray
left a comment
There was a problem hiding this comment.
Overall looks good to me! I tested all the tutorials and everything still seems to work, so no issues on that front with regards to maintaining optimizer states or things.
One thing claude raised when I had it go through the changes was:
The PR says nothing in a refused file runs, but that isn't quite true. In serialize.py:621, _Reader._class imports the module named in the file before it checks whether that module is trusted. _stored_class does the same for skip types. I edited a saved file to name a .py file in the working directory, and its top-level code ran before the load raised. An attacker can only name modules that are already importable, and a notebook's own folder counts, so the risk is low. The fix is to check the trust list before importing, as _global already does.
def _class(self, group: zarr.Group) -> Any:
metadata = group.attrs["_autoserialize"]
module_name = metadata["class_module"]
if not (
self.allow_pickle
or module_name.partition(".")[0] in _TRUSTED_PACKAGES
or module_name in sys.modules # already imported, so importing it runs nothing new
):
return self._refuse(
group.path,
f"{module_name}.{metadata['class_name']}; import its module first or use allow_pickle=True",
)
cls = _import_class(metadata)
... # existing checks unchanged_stored_class would need the same guard: return object when the module is untrusted and not yet imported, and _class then refuses that group. With this change, user AutoSerialize classes still load once their module is imported. Classes defined in a notebook are in main, so they still load too.
For a test, tests/datastructures/test_autoserialize.py could edit a saved file's class_module to point at a module on sys.path. It would then assert that load raises and that the module is not in sys.modules.
Up to you on if you think that's worth addressing, but once you decide I'll approve and we can merge.
Without allow_pickle, the reader imported the module that a file names for a class before checking whether it is trusted, so a safe load could run the top-level code of any importable module, such as a .py file next to a notebook. It now imports only modules from quantem and torch, or modules already imported; the skip check does the same. An AutoSerialize class from another package loads once its module is imported, and classes defined in a notebook still load. Raised in Arthur's review of PR 319. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ve, and loggers lazy - save(mode="o") writes next to the target and replaces it only once the new file is complete. It used to delete the old file first, so a save that failed, for example on a value that cannot be pickled, lost the previous one. - Ptychography.save without the raw data also stores the dataset's learn flags and the optimizer and scheduler learning the scan positions and descan shifts, and from_file restores them with the learned values. The learned values used to be restored only when a dataset was passed to from_file, so a reloaded dataset started over from its initial positions, and the optimizer for them was lost. - A saved tensorboard SummaryWriter loads closed and creates its log folder and event file when it next logs. Loading used to create them at the path stored in the file, and failed on a computer where that path could not be made. - A class refused because its module is not imported says to import it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks, good catch. Fixed in 9aacbaa as you suggested: without While looking for similar gaps I fixed three older bugs, which are also on dev, in 048570f:
The second one changes |
Conflict: visualization_utils.py scalebar label rounding, kept the diffractive_imaging version. upstream/dev commits after f39b826 (AutoSerialize rewrite, PR electronmicroscopy#319) are held back. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
What problem this PR addresses
Loading a quantEM file could run code stored in the file. Torch modules, optimizers and schedulers were pickled, any other value without a Zarr form fell back to dill, and loading unpickled them with
torch.load(weights_only=False)ordill.loads. Files also did not record which quantEM version wrote them, and the load code was duplicated in four places that had drifted apart.What changed
load(path, *, allow_pickle=False)is safe by default, like numpy'sallow_pickleand torch'sweights_only. If a file holds pickled values,loadraises one error that lists all of them, before any of them runs.Ptychography,PtychoLiteandTomography.from_filepassallow_picklethrough.state_dict()and settings, rebuilt with the constructor andload_state_dict(). This also fixes LBFGS, which could not step after unpickling;state_dict(), rebuilt withload_state_dict().nn.BatchNorm2dandtorch.cat, are stored by name.allow_pickle, a file can only rebuild AutoSerialize classes, or models, optimizers, schedulers, dataclasses, classes and functions defined in quantEM or torch. Loading imports only modules from quantEM and torch, or modules already imported, so it never runs the code of a module the file names. An AutoSerialize class from another package loads once its module is imported.quantem_version, whichprint_fileshows.save(mode="o")writes next to the target and replaces it only once the new file is complete. It used to delete the old file first, so a save that failed lost the previous one.serialize.pynow has one writer and one reader (1682 to 1205 lines). This fixes:Atomsand random generators in lists and dicts raised errors;nn.Sequentialwith more than ten layers loaded its layers out of order (dicts now keep their key order and int keys);_autoserialize_skip_*attributes;EventStackandFourierProbeare stored without pickle.density_activationis the functionshifted_softplusinstead of a lambda;get_activation_functionbuilds around a function,CallableWrapper, is defined at module level.savewithout the raw data (the default) keeps the learned scan positions and descan shifts with the optimizer and scheduler learning them, andfrom_filerestores them on the reloaded dataset. They used to be restored only when a dataset was passed tofrom_file, so a reloaded dataset started over from its initial positions and the optimizer for them was lost.Tomography.saveskips the data loaders and samplers, whichfrom_filerebuilds, and the pretraining data. It used to skip onlydataloader, so a run with a validation split pickledval_dataloader.ObjectINR.pretrainwithout a dataset says so if none is loaded..to(), whichfrom_filecalls, moves the pose parameters in place instead of replacing them. Replacing them dropped the pose optimizer's state, and on a GPU it would also reset the learned pose to its initial values.Compatibility
allow_pickle=True._post_loadis the only after-load hook.CrystalMap.__attrs_post_init__is renamed to it, and support for attrs classes is removed; no quantEM class used it.Tests
The full suite passes with the slow tests (1090 passed; the 13 skipped need a GPU or several GPUs). The ML save/load tests no longer pass
allow_pickle.test_values_that_can_run_code_load_only_with_allow_picklealso checks that a file naming a module that is not imported is refused without importing it.test_torch_nn_module_roundtripsaves a model mid-training with its Adam optimizer, scheduler and random generator, loads it without pickle, and checks that it trains on identically to the original.test_save_load_keeps_pose_and_optimizer_statechecks that a tomography reconstruction with a validation split loads without pickle with its learned pose and the optimizer state for it.test_default_save_keeps_learned_positionsdoes the same for ptychography scan positions after the default save.test_dummy_save_load_and_skipchecks that an overwrite that fails keeps the old save, andtest_tensorboard_writer_creates_its_folder_when_it_logsthat loading a writer creates nothing.Outside the suite, each reconstruction below was saved mid-run, loaded without pickle and continued. On one thread with deterministic algorithms, every tensor, optimizer state and random state matched right after loading, and the continued run matched a run that was never saved, bit for bit:
PtychoLiteandPtychoLiteDIPwith a tensorboard log, andPtychoLitealso with the default save and its log folder deleted before loading;TomographyLiteINRwith learned pose, and SIRT.The one difference left is a tomography run with a validation split:
from_filerebuilds the loaders and draws a new split, as it did before this PR. A ptychography reconstruction saved on the CPU and loaded onto MPS keeps its parameters and Adam state on MPS. Two BTO DIP reconstructions saved with an earlier version load withallow_pickle=True, save again with nothing pickled, and load without pickle with all tensors equal.🤖 Generated with Claude Code