Skip to main content
Yanked

This release has been yanked by its maintainers, and will be ignored by installers, except when explicitly specified.
Consider using release 0.2.4 instead.
Reason given by maintainers: pytorch imcompatibility

TorchSX

A PyTorch-based scaling and merging library for serial crystallography (SX)

Python 3.10+ PyTorch TorchRef CUDA License: MIT

In serial crystallography every reflection is seen once per crystal, with an unknown partiality, incident intensity and crystal volume. Established programs scale each crystal with a few parameters and average. TorchSX instead works from a generative model of every observation. The signal that reached the detector aperture of observation j of reflection h is

S_j = K_j · I_h · exp(ε_j)

where I_h is the reflection's true intensity, a latent variable with a Wilson prior; K_j is a scale predicted for this observation; and ε_j is a random multiplicative scatter, with E[exp(ε_j)] = 1, whose distribution is also predicted for this observation (a mixture of two-width Gaussians in log space). The detector then records Poisson counts of S_j on top of the background. One neural network per dataset predicts K_j and the scatter distribution from the observation's geometry, its crystal's metadata and the crystal's other observations. Merging is a posterior integral rather than an average: each merged amplitude and its uncertainty are moments of the posterior of I_h given all its observations. The network is trained on random batches of crystals sized to a given multiplicity, maximising the marginal likelihood of their observations with I_h integrated out.

TorchSX starts from integrated CrystFEL .stream files and writes merged MTZs. We are working on integration with dials and integration of Probixi.

TorchSX is under active development, if you find something behaving unexpectedly please create an issue on GitHub.

Refinement and difference maps in this repo were done with TorchRef. TorchSX output should be compatible with any classical refinement or map calculation program.

Install

pip install torchsx

Python ≥ 3.10. This brings TorchRef 0.7, torch, triton, gemmi and torchsx-native, the compiled .stream reader for your platform. TorchSX is intended to be run on a GPU; its core algorithms are Triton kernels, and we have not investigated CPU runtime or even functionality. GPU memory should not exceed 10 GB. It scales with the redundancy requested for training (default 100) and the number of unique HKLs, not with the amount of data. Host RAM does not scale with the amount of data either: the streams are prepared block by block into an on-disk store of 56 bytes per observation, and training and merging read it one batch at a time, with the next batch read while the current one is computed.

From a checkout, build the native package first (needs Rust, see native/README.md): pip install ./native, then pip install -e ..

Usage

torchsx.train indexed.stream --spacegroup 'P 63' --dmin 2.0 -o run/

This trains the network (400 updates by default) and merges the data with it. run/ then contains:

run/
├── merged.mtz              merged amplitudes from all crystals
├── merged_half1.mtz        the same from one half of the crystals
├── merged_half2.mtz        ... and from the other half
├── merged.metrics.json     in-run precision: CC1/2 and R_split between the two halves
├── best.pt                 the network at the lowest validation loss; it made the merges
├── last.pt                 the network at the end of training
├── prepared/               the prepared observations on disk, reused by later runs on the same input
├── run.json                the resolved settings
├── training_summary.json   updates, best step, run time; time and GPU memory by phase
└── metrics.jsonl           training log: one line per update and per validation

Each MTZ holds:

Column MTZ type Content
H, K, L H Miller index; Friedel mates merged
F-obs F posterior mean of the amplitude |F|
SIGF-obs Q posterior standard deviation of the amplitude
R-free-flags I refinement free set: 0 = free (5 %), 1 = work

There are no intensity columns. F-obs is already the posterior estimate of the amplitude, so it must not go through French–Wilson again; refinement programs use it as it is. With --no-merge-friedel the mates stay apart and the files carry F-obs(+), SIGF-obs(+), F-obs(-) and SIGF-obs(-). --free-from earlier.mtz takes the free set from an existing file.

The two halves split the crystals, not the training: both are merged with the same network, so the CC1/2 and R_split in merged.metrics.json measure the in-run precision, not the agreement of independent merges. For independent halves, as in the comparison below, train two runs on disjoint sets of patterns.

Light and dark

torchsx.train --split dark=dark.stream --split light=light.stream \
  --spacegroup 'P 63' --dmin 2.0 -o run/

One network is trained on both states, and each state is merged on its own: merged_dark.mtz and merged_light.mtz, each with its two halves. A single stream with a CrystFEL custom-split file works too (--split-file).

How it works, by analogy

Every crystal is a witness that saw each reflection once, under its own conditions: how much of the reflection the Ewald sphere caught, how bright the pulse was, how big the crystal was (partiality, incident intensity and crystal volume, none of them known per observation). Established programs correct each witness with a few parameters per crystal and then average the testimonies (per-crystal scale and B factor, then a weighted mean).

TorchSX instead learns, from the whole data set, how reliable each kind of testimony is. One network reads every observation together with the other spots on the same image and predicts two things: how bright this observation should be, and how far from that it may plausibly fall (a scale factor K and a scatter distribution, a mixture of two-width Gaussians in log space, for every observation).

Merging then does not average. It asks which true intensities are consistent with all the testimonies given their predicted reliabilities, and reports the centre of that range as the merged value and its width as the uncertainty (the posterior of each reflection's intensity under the product of per-observation likelihoods and a Wilson prior.).

The network is trained the way a weather forecaster is scored: rewarded for confidence where the data agree with it, penalised for confidence where they do not, so the predicted scatter stays honest (maximising the marginal likelihood, with each reflection's true intensity integrated out).

Compared with Partialator

On the bacteriorhodopsin (bR) data of Weinert et al.1:

bR R-free against dark patterns per merge, TorchSX and Partialator

Rfree of models refined from one starting model against each dark merge, on the reflections common to both programs at each size, as a function of the number of dark patterns per merge. Points, mean of two independent merges; bars, their range. Initial models were refined against a larger merge with the respective method. Refinement used TorchRef with one protocol for all merges.

bR light-minus-dark difference maps from two independent halves, TorchSX and Partialator

Light-minus-dark difference maps from two independent merges of disjoint patterns (7,800 per state each), phased with the dark model. Shown: the end of helix E, the EF loop and helix F of the dark model (grey) and of the open state 6RPH1 (orange). The number under each program is the correlation of its two maps over helix F.

Other commands

  • torchsx.merge run/best.pt more.stream -o merged.mtz merges new or additional data with a trained network.
  • torchsx.merge-stats A/merged.mtz B/merged.mtz -o stats/ compares merges: completeness, CC1/2, R_split and, for light/dark pairs, the information in ΔF (docs/merge_stats.md). torchsx.merge-stats run/ finds the merges of each state in a run directory and writes run/merge_stats/.
  • torchsx.observation-stats indexed.stream --spacegroup 'P 63' -o figures/ plots the raw observations: intensity distributions, skewness, examples (docs/stats.md).

All options, gain and measurement settings, caching and reproducibility are in the command-line reference.

In Python, torchsx.SFXStream.read('indexed.stream', spacegroup='P 63') reads a stream with its geometry and measurement settings.

References

  1. Weinert, T. et al. Proton uptake mechanism in bacteriorhodopsin captured by serial synchrotron crystallography. Science 365, 61–65 (2019). doi:10.1126/science.aaw8634
  2. Seidel, H.-P., Standfuss, J. & Weinert, T. TorchRef: an open-source PyTorch framework for crystallographic refinement. J. Appl. Cryst., accepted (2026).

License

MIT. See LICENSE.

Metadata

Release files for torchsx 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for torchsx 0.2.1
File Size Uploaded Provenance Actions
torchsx-0.2.1.tar.gz 402.6 kB With provenance Details for torchsx-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for torchsx 0.2.1
File Interpreter ABI Platform Actions
torchsx-0.2.1-py3-none-any.whl Python 3 none any Details for torchsx-0.2.1-py3-none-any.whl

Total release size: 707.9 kB

Release files / torchsx-0.2.1.tar.gz

Download URL torchsx-0.2.1.tar.gz
Size 402.6 kB
Tags Source
SHA-256 checksum
How to use checksums
260e6de8994b5e29416d405c97e126aca327fa385f18ee1e8e88d8a6a6a83189
BLAKE2b-256 checksum
How to use checksums
dcf1ce84b3fe4d45b5f5c75bf598157379bea6f8ac9093ded1139180e32e024f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Release files / torchsx-0.2.1-py3-none-any.whl

Download URL torchsx-0.2.1-py3-none-any.whl
Size 305.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f5e01d45e41f5d8862e916750cad25a63e7682faad27bb04867e2928b48f3a33
BLAKE2b-256 checksum
How to use checksums
3f63694fb719904803e4df383b4cb41e8cde97ef1eb33a8e84a5830ff5f6e01b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Security for torchsx 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for torchsx-0.2.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page