Download pretrained (C=3076) model checkpoint (~582 MB zipped):
➡️ deCIFer_v1 Checkpoint (.zip)
The zip contains ckpt.pt (≈635 MB uncompressed).
- Setup
- Data Preparation
- Training
- Evaluation Pipeline
- CIF Generation Consistency Experiment
- Artefact Robustness & Experimental Data (TRW-CSP)
- License
We recommend using Python 3.9, as deCIFer was developed and tested with this version. Other versions may work but have not been verified.
- Clone the repository:
git clone https://github.com/XXXX/deCIFer.git
cd deCIFer- Install deCIFer using setup.py. We recommend an isolated environment (e.g., with Conda or venv):
pip install -e .-
Ensure that you have PyTorch installed: Follow the instructions on the official PyTorch website to install the appropriate version for your system: PyTorch Installation Guide. (https://pytorch.org/get-started/locally/)
-
Install other dependencies:
pip install numpy pandas matplotlib seaborn pyYAML tqdm omegaconf h5py pymatgen periodictable scikit-learn notebookBefore training or evaluation, the dataset must be preprocessed into a structured format that deCIFer can use. This includes parsing CIF files, computing XRD patterns, tokenizing CIFs, and serializing the processed data into HDF5 format.
To prepare a dataset, use the prepare_dataset.py script with the desired options. Here is an example:
python bin/prepare_dataset.py --data-dir data/noma/ --name noma-1k --debug-max 1000 --all --raw-from-gzip-
General options:
--data-dir <path>: Path to the directory containing raw CIF and PXRD data.--name <str>: Identifier for the dataset (used to create an organized structure).--debug-max <int>: Limits processing to the firstNsamples (useful for debugging).--raw-from-gzip: If raw CIFs are stored in a.gzarchive, extract them before processing. (This is the case for the NOMA dataset, depeding on how the data is downloaded)
-
Processing steps:
--preprocess: Parses and cleans CIF files.--xrd: Computes diffraction patterns.--tokenize: Tokenizes CIF files for transformer-based models.--serialize: Serializes the processed dataset into HDF5 format.--all: Runs all preprocessing steps in sequence.
-
Processing options:
--num-workers <int>: Number of parallel processes to use (default: all available CPUs - 1).--include-occupancy-structures: Include structures with atomic site occupancies below 1. (False for deCIFer and U-deCIFer)--ignore-data-split: Disable automatic train/val/test splitting and serialize all data intotest.h5.
After running prepare_dataset.py, the processed data will be stored in the following structure:
data/noma-1k/
├── preprocessed/ – Parsed CIF files (cleaned, formatted, tokenized)
├── xrd/ – Computed XRD patterns
├── cif_tokens/ – Tokenized CIF representations
├── serialized/ – Final dataset (train/val/test) stored as HDF5 files
├── metadata.json – Stores some metadataTo train deCIFer from scratch, you need to specify the training configuration and dataset. The model will initialize randomly and train from the beginning.
--config <path>: Path to a YAML configuration file specifying training parameters.
python bin/train.py --config config/train.yamlThis initializes a new model and starts training using the settings specified in train.yaml.
If training was previously interrupted or stopped, you can resume from a saved checkpoint. This allows training to continue from where it left off.
--config <path>: Path to the same YAML configuration file used during training.- Ensure that the
init_fromoption in the YAML file is set to"resume".
The training parameters are stored in a YAML file. Below is an example configuration:
out_dir: "models/deCIFer" # Directory where checkpoints and logs will be saved
dataset: "data/noma/1k/serialized/" # Path to the dataset
init_from: "scratch" # Options: 'scratch' (new training), 'resume' (continue training)
# Model parameters
n_layer: 8
n_head: 8
n_embd: 512
dropout: 0.0
boundary_masking: True
condition: True
# Training parameters
batch_size: 64
gradient_accumulation_steps: 40
max_iters: 50000
learning_rate: 6e-4
weight_decay: 0.1
warmup_iters: 2000
early_stopping_patience: 50
# Evaluation settings
eval_interval: 250
eval_iters_train: 200
eval_iters_val: 200
validate: TrueModify this file as needed to adjust the training settings.
After training starts, the model and logs will be saved in the output directory:
models/deCIFer/
├── ckpt.pt – Latest model checkpoint including model dictionary, loss metrics, etc.During training, logs will be printed to the console, showing:
- Loss values
- Evaluation results on the validation set
- Learning rate adjustments
- Checkpoint saving status
Example output:
iter 1000: loss 0.4123, time 58.2ms
step 1000: train loss 0.4123, val loss 0.4289
saving checkpoint to models/deCIFer/...If validation loss does not improve for a set number of evaluations (early_stopping_patience), training will stop automatically.
python bin/train.py --config config/train.yamlThe script will automatically load the latest checkpoint from the output directory specified in the configuration file and continue training.
The evaluation process consists of two main steps: generating evaluations for model predictions and collecting them into a single file for visualization and analysis.
This step evaluates the model on a test dataset and saves individual .pkl.gz evaluation files. These separate files allow evaluations to be merged across different datasets and enable checkpointing (resuming evaluation later if needed).
--model-ckpt <path>: Path to the trained model checkpoint.--dataset-path <path>: Path to the test dataset in HDF5 format.--dataset-name <str>: Identifier for the dataset.--out-folder <path>: Folder where evaluation files will be stored.
--num-workers <int>: Number of worker processes for parallel evaluation.--debug-max <int>: Maximum number of samples to process (for debugging).--add-composition: Include atomic composition information in the evaluation.--add-spacegroup: Include space group information in the evaluation.--max-new-tokens <int>: Maximum number of tokens to generate for CIF structures.--num-reps <int>: Number of times to generate a CIF for each test sample.--override: Force regeneration of evaluations even if files already exist.--temperature <float>: Sampling temperature for CIF generation.--top-k <int>: Top-k filtering during sampling.--condition: Use XRD conditioning for generation.
Run evaluation on a test dataset and save results:
python bin/evaluate.py \
--model-ckpt deCIFer_model/ckpt.pt \
--dataset-path data/noma/1k/serialized/test.h5 \
--dataset-name noma-1k \
--out-folder eval_files \
--add-composition \
--add-spacegroupEach evaluated structure will be saved as an individual .pkl.gz file in eval_files/eval_files/noma-1k/.
Once all evaluations are generated, they need to be aggregated into a single .pkl.gz file. This file is used for computing metrics and visualizing results.
--eval-folder-path <path>: Path to the directory containing the individual evaluation files.--output-file <path>: Name of the final collected evaluation file.
python bin/collect_evaluations.py --eval-folder-path eval_files/eval_files/noma-1k --output-file eval_files/noma-1k_collected.pkl.gzThis collects all individual .pkl.gz evaluation files and stores the merged results in noma-1k_collected.pkl.gz.
After running the evaluation pipeline, the output structure will be:
eval_files/
├── eval_files/noma-1k/ – Individual evaluation files (`.pkl.gz` per sample)
├── noma-1k_collected.pkl.gz – Merged evaluation resultsEach evaluation file contains:
- Generated CIF file
- PXRD-based metrics
- Validity checks:
- Formula consistency
- Bond length reasonableness
- Space group consistency
- Unit cell parameters
- Root Mean Square Deviation (RMSD) from reference structure
The CIF Generation Consistency Experiment evaluates the reproducibility of generated crystal structures across multiple repetitions. The script takes a dataset of CIFs, generates multiple versions of each, and compares their structural and diffraction consistency.
To perform the experiment, use the following command:
python bin/generation_consistency.py --num_cifs 100 --num_reps 5 --batch_size 16 --qmin 0.0 --qmax 10.0 --qstep 0.01 --fwhm 0.05 --output_folder results/consistency_experiment --model_path deCIFer_model/ckpt.pt --dataset_path data/noma/1k/serialized/test.h5 --add_comp --add_spg--num_cifs <int>: Number of CIFs to process.--num_reps <int>: Number of times to generate each CIF.--output_folder <path>: Directory where results will be saved.--model_path <path>: Path to the pretrained model checkpoint.--dataset_path <path>: Path to the dataset in HDF5 format.
--batch_size <int>: Number of CIFs to generate in parallel (default: 16).--qmin <float>: Minimum Q value for XRD computation (default: 0.0).--qmax <float>: Maximum Q value for XRD computation (default: 10.0).--qstep <float>: Step size for Q values (default: 0.01).--fwhm <float>: Full-width at half-maximum for XRD broadening (default: 0.05).--noise <float>: Optional noise level in XRD computation.--add_comp: Include atomic composition in the conditioning prompt.--add_spg: Include space group information in the conditioning prompt.
After running the experiment, the results will be stored in the following structure:
results/consistency_experiment/
├── CIF_NAME_1/ – Folder containing generated CIFs for the first structure
│ ├── CIF_NAME_1_0.cif – First repetition
│ ├── CIF_NAME_1_1.cif – Second repetition
│ ├── ...
├── CIF_NAME_2/ – Folder containing generated CIFs for the second structure
│ ├── CIF_NAME_2_0.cif
│ ├── CIF_NAME_2_1.cif
│ ├── ...
├── results.pkl – A pickled summary of all resultsEach generated CIF is analyzed for structural and diffraction consistency. The following metrics are computed:
- Residual Weighted Profile (Rwp): Measures the difference between the experimental and generated XRD patterns.
- Root Mean Square Deviation (RMSD): Measures the structural deviation between generated and reference CIFs.
- Crystal System Consistency: Checks if the generated structure belongs to the same crystal system as the reference.
- Space Group Consistency: Compares the space group number of the generated structure with the original.
- Lattice Parameter Deviations:
a,b,c: Unit cell lengths.α,β,γ: Unit cell angles.
This section covers the scripts and notebook used in a follow-up paper that applies deCIFer to real-world synchrotron PXRD data and tests its robustness to common measurement artefacts (noise, peak broadening, Q-shift, multi-phase contributions, etc.).
The experimental PXRD data and precomputed result pickles used in the paper can be downloaded from:
➡️ Experimental data & results (.zip)
The ZIP contains .xy/.xye scan files (two-column or three-column: angle/Q, intensity, optional error) and a pkl-files/ folder of precomputed pickle outputs required by the figure notebook.
bin/ablation.py evaluates deCIFer's robustness by systematically sweeping over PXRD distortion parameters and measuring whether the model can still recover the correct crystal structure. For each parameter value it generates a batch of structures and records R_wp, structure matching (RMSD), peak similarity, and validity.
Supported distortion parameters (passed via params_dict in the config):
| Parameter | Description |
|---|---|
noise |
Gaussian noise added to intensities |
particle_size |
Scherrer broadening crystallite size (Å) |
base_fwhm |
Baseline peak FWHM |
peak_asymmetry |
Asymmetric peak distortion |
eta |
Pseudo-Voigt mixing parameter (0 = Gaussian, 1 = Lorentzian) |
q_shift |
Rigid shift of the Q-axis |
q_post_scale |
Multiplicative scaling of Q after simulation |
q_pre_scale_uniform |
Uniform lattice parameter scaling (scalar) |
q_pre_scale_abc |
Per-axis lattice scaling (3-element list) |
mask_ranges |
List of Q ranges to zero out, e.g. [[3.0, 5.0], [7.0, 10.0]] |
preferred_orientation_range |
[min, max] range for preferred orientation factor |
chebychev_norm_coeffs |
List of Chebyshev background coefficient vectors |
phase_scales |
Multi-phase mixing (triggers a second CIF) |
Configuration — the script is driven by a YAML file. Example configs are provided in configs-TRW-CSP-PXRD/:
dataset_path: data/noma/serialized/test.h5
model_path: deCIFer_model/ckpt.pt
output: results/ablation_cubic_artefacts.pkl
seed: 42
# Dataset filters (all optional)
crystal_system: cubic # triclinic/monoclinic/orthorhombic/tetragonal/trigonal/hexagonal/cubic
target_elements: ["Fe", "O"] # filter by elements present
element_match_mode: exact # "exact" or "contains"
element_count: 2 # optional: binary, ternary, etc.
# Generation settings
batch_size: 10
n_repeats: 10
max_new_tokens: 3076
temperature: 1.0
add_composition: true
add_spacegroup: false
# Parameters to sweep (each key maps to a list of values; each is swept independently)
params_dict:
particle_size: [1, 5, 10, 20, 30, 50, 100]
peak_asymmetry: [0.0, 0.05, 0.1, 0.2, 0.5, 1.0]
q_pre_scale_uniform: [0.9, 0.95, 0.99, 1.0, 1.01, 1.05, 1.1]
# Default PXRD parameters applied on non-swept axes
default_params_dict:
base_fwhm: 0.05Usage:
python bin/ablation.py --config configs-TRW-CSP-PXRD/ablation_config_cluster.yamlResults are saved as a pickle file containing a results dict keyed by parameter name and value. Each entry holds a list of experiment results (generated CIF, reference CIF, R_wp, structure RMSD, peak similarity, validity flags) and the single best result by R_wp.
bin/run_protocol.py is the entry point for the CeO₂ nanoparticle experiment from the paper. It reads synchrotron PXRD scans from a ZIP archive and runs deCIFer under several conditioning protocols (unconstrained, space-group-constrained, composition-constrained, and combinations thereof).
python bin/run_protocol.py \
--model-path deCIFer_model/ckpt.pt \
--zip-path experimental_data.zip \
--n-trials 25 \
--suffix run1Arguments:
--model-path: Path to the trained model checkpoint.--zip-path: Path to the ZIP file containing experimental PXRD scans.--n-trials: Number of generation attempts per protocol (default: 25).--suffix: Suffix appended to the output folder name (default:default).--debug-max: Limit processing to the first N scan files (for quick testing).
Output is written to particles_CeO2_protocol_<suffix>/ as one pickle file per scan × protocol combination.
For custom datasets, use the DeciferPipeline class from bin/experimental_pipeline.py:
from bin.experimental_pipeline import DeciferPipeline
pipeline = DeciferPipeline(
model_path="deCIFer_model/ckpt.pt",
zip_path="experimental_data.zip",
temperature=1.0,
max_new_tokens=3000,
results_output_folder="results/",
)
# Preprocess one scan (background subtraction, Q-conversion, normalization)
pipeline.prepare_target_data(
target_file="scan-4907_mean.xy",
background_file="scan-4903_mean.xy", # optional
wavelength=None, # provide wavelength in Å if data is in 2θ; None if already in Q
q_min_crop=1.5,
q_max_crop=8.0,
)
# Run generation trials with optional constraints
pipeline.run_experiment_protocol(
n_trials=25,
composition="Ce4O8", # optional: fix composition
spacegroup="Fm-3m_sg", # optional: fix space group
crystal_systems=[7], # optional: restrict to cubic (7)
save_to="ceo2_Fm-3m.pkl",
protocol_name="Ce4O8_Fm-3m",
)prepare_target_data handles:
- Conversion from 2θ to Q (if
wavelengthis given). - Scaled background subtraction.
- Min-max normalization and interpolation onto a common Q grid (0–10 Å⁻¹, 1000 points).
run_experiment_protocol saves a pickle containing the generation config, raw and processed experimental signals, and a list of generated CIF strings and parsed structures.
The notebook gen-figures-TRW-CSP-PXRD.ipynb reproduces all figures from the paper. It expects precomputed pickle files in a pkl-files/ directory; these are included in the shared data download above.
jupyter notebook gen-figures-TRW-CSP-PXRD.ipynbThe notebook is organized into sections mirroring the paper:
- Ablation / artefact tests — loads ablation pickle files and plots robustness curves and structure examples.
- Robustness analysis — sweeps over distortion parameters across crystal systems (cubic, hexagonal, trigonal FeO₂ polymorphs).
- Experimental results — visualizes deCIFer predictions against real CeO₂ synchrotron data, including PXRD overlays and unit cell renderings.
deCIFer is released under the MIT License.
