Skip to content

AutoSerialize: safe loading by default, quantEM version in saved files, reconstructions without pickle - #319

Merged
arthurmccray merged 5 commits into
electronmicroscopy:devfrom
cophus:autoser
Nov 18, 2026
Merged

arthurmccray merged 5 commits into
electronmicroscopy:devfrom
cophus:autoser

Conversation

@cophus

@cophus cophus commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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) or dill.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's allow_pickle and torch's weights_only. If a file holds pickled values, load raises one error that lists all of them, before any of them runs. Ptychography, PtychoLite and Tomography.from_file pass allow_pickle through.
  • Ptychography and tomography reconstructions load without pickle. Models, optimizers, schedulers and settings dataclasses are stored as Zarr groups of their state:
    • models: their attributes, rebuilt the way pickle rebuilds them;
    • optimizers: state_dict() and settings, rebuilt with the constructor and load_state_dict(). This also fixes LBFGS, which could not step after unpickling;
    • schedulers: state_dict(), rebuilt with load_state_dict().
  • Classes and functions that models keep as attributes, such as the CNN's nn.BatchNorm2d and torch.cat, are stored by name.
  • A value held in several places, such as a parameter of a model and its optimizer, is stored once and stays shared. A loaded optimizer now updates the loaded model, and a loaded scheduler drives the loaded optimizer. Before, each attribute was pickled separately and these links were lost.
  • NumPy random generators keep their state. Before, it was written but not read back, so the batch order changed after loading.
  • Without 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.
  • Saved files record quantem_version, which print_file shows.
  • 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.
  • A saved tensorboard writer creates its log folder when it next logs, not when it loads. Loading used to create it at the path stored in the file, and failed on a computer where that path could not be made.
  • serialize.py now has one writer and one reader (1682 to 1205 lines). This fixes:
    • dill values in lists and dicts loaded as raw bytes;
    • optimizers, Atoms and random generators in lists and dicts raised errors;
    • 0-d arrays loaded as uninitialized memory;
    • an nn.Sequential with more than ten layers loaded its layers out of order (dicts now keep their key order and int keys);
    • loaded objects carried stray _autoserialize_skip_* attributes;
    • loading evaluated every property of the object.
  • Torch dtypes, torch generators (with their state), EventStack and FourierProbe are stored without pickle.
  • Models, so that they save without pickle:
    • the K-Planes default density_activation is the function shifted_softplus instead of a lambda;
    • the module that get_activation_function builds around a function, CallableWrapper, is defined at module level.
  • Ptychography: save without the raw data (the default) keeps the learned scan positions and descan shifts with the optimizer and scheduler learning them, and from_file restores them on the reloaded dataset. They 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.
  • Tomography:
    • Tomography.save skips the data loaders and samplers, which from_file rebuilds, and the pretraining data. It used to skip only dataloader, so a run with a validation split pickled val_dataloader. ObjectINR.pretrain without a dataset says so if none is loaded.
    • The dataset's .to(), which from_file calls, 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

  • This version reads files written by earlier versions. Their models are pickled, so they need allow_pickle=True.
  • Earlier versions cannot read files from this version that contain models, optimizers, dataclasses, classes or functions, torch generators or dill fallbacks.
  • _post_load is 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_pickle also checks that a file naming a module that is not imported is refused without importing it. test_torch_nn_module_roundtrip saves 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_state checks 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_positions does the same for ptychography scan positions after the default save. test_dummy_save_load_and_skip checks that an overwrite that fails keeps the old save, and test_tensorboard_writer_creates_its_folder_when_it_logs that 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:

  • ptychography: pixelated, DIP, INR and K-Planes objects; pixelated, parametric and DIP probes; Adam, AdamW and SGD with all five schedulers; learned scan positions, also with the default save, which reloads the dataset from its file; PtychoLite and PtychoLiteDIP with a tensorboard log, and PtychoLite also with the default save and its log folder deleted before loading;
  • tomography: INR, K-Planes TILTED, INR pretrained on a SIRT volume, TomographyLiteINR with learned pose, and SIRT.

The one difference left is a tomography run with a validation split: from_file rebuilds 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 with allow_pickle=True, save again with nothing pickled, and load without pickle with all tensors equal.

🤖 Generated with Claude Code

cophus and others added 2 commits November 12, 2026 09:43
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>
@cophus
cophus requested a review from arthurmccray November 13, 2026 02:19
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 arthurmccray left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

cophus and others added 2 commits November 17, 2026 17:55
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>
@cophus

cophus commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, good catch. Fixed in 9aacbaa as you suggested: without allow_pickle, a class's module is imported only if it's in quantEM or torch or already imported, both where the class is rebuilt and in the skip check. The refusal says to import the module first. The safe-load test now edits a file to name a module that isn't imported and checks it's refused without being imported.

While looking for similar gaps I fixed three older bugs, which are also on dev, in 048570f:

  • A failed save(mode="o") no longer deletes the previous file.
  • from_file after the default save (save_raw_data=False) keeps the learned scan positions and the optimizer and scheduler for them.
  • A saved tensorboard writer no longer creates its log folder on load, so files from another computer load.

The second one changes Ptychography.save and from_file, so it's worth a look before you approve.

@arthurmccray arthurmccray left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm!

@arthurmccray
arthurmccray merged commit 5e04899 into electronmicroscopy:dev Nov 18, 2026
4 checks passed
arthurmccray added a commit to arthurmccray/quantem that referenced this pull request Nov 25, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants