Skip to main content

A CLI tool to convert ms2deepscore PyTorch models to ONNX

Project description

ms2deepscore pytorch 2 onnx converter

This library/cli tool aims at converting ms2deepscore models from pytorch to onnx.

Usage with uvx

uvx ms2deepscore-onnx-converter https://zenodo.org/records/17826815 -o onnx_model_dir
# or
uvx ms2deepscore-onnx-converter YOUR_MS2DEEPSCORE_MODEL.pt

Installation

uv add ms2deepscore-onnx-converter
# or using pip:
pip install ms2deepscore-onnx-converter

Usage

The tool can either convert a local ms2deepscore model or download one from zenodo and convert it to onnx.

# Using the CLI:
ms2ds_onnx https://zenodo.org/records/17826815 -o onnx_model_dir
ms2ds_onnx ms2deepscore_model.pt -o onnx_model_dir

# or within your python script:
from ms2ds_converter import convert_to_onnx

convert_to_onnx("ms2deepscore_model.pt", "onnx_model_dir")

Inference using onnx runtime

After converting a ms2deepscore model to pytorch you can use the ONNX Runtime for inference. You'll need to install onnxruntime separately.

import json

import numpy as np
import onnxruntime as ort
from matchms import Spectrum
from matchms.importing import load_spectra
from ms2deepscore import SettingsMS2Deepscore
from ms2deepscore.tensorize_spectra import tensorize_spectra

def compute_embeddings_onnx(
    onnx_session: ort.InferenceSession,
    spectra: list[Spectrum],
    settings: SettingsMS2Deepscore,
) -> np.ndarray:
    # We use ms2deepscore to create tensors from spectra and convert them to np arrays.
    X_binned_torch, X_metadata_torch = tensorize_spectra(spectra, settings)
    X_binned = X_binned_torch.numpy().astype(np.float32)
    X_metadata = X_metadata_torch.numpy().astype(np.float32)

    # Build the input data, depending on additional metadata in model, e.g. ["input_peaks", "input_metadata"] or just ["input_peaks"].
    input_names = [inp.name for inp in onnx_session.get_inputs()]
    output_name = onnx_session.get_outputs()[0].name

    input_feed = {input_names[0]: X_binned}

    if len(input_names) > 1 and X_metadata.shape[1] > 0:
        input_feed[input_names[1]] = X_metadata

    # inference step.
    embeddings = onnx_session.run([output_name], input_feed)[0]

    return embeddings


def main():
    # load some spectra with matchms and maybe do some filtering...
    spectra = list(load_spectra("spectra.mgf"))

    # Load exported SettingsMS2Deepscore.
    with open(
        "onnx_model_dir/ms2deepscore_model_settings.json", "r", encoding="utf-8"
    ) as file:
        settings_dict = json.load(file)

    # Remove spectrum_file_path from settings for inference, since it will fail validation.
    settings_dict["spectrum_file_path"] = None
    settings = SettingsMS2Deepscore(**settings_dict)

    # Load ONNX Model and compute embeddings, will use either GPU or CPU as fallback.
    ort_session = ort.InferenceSession(
        "onnx_model_dir/ms2deepscore_model.onnx",
        providers=["CUDAExecutionProvider", "CPUExecutionProvider"]
    )
    embeddings = compute_embeddings_onnx(ort_session, spectra, settings)

    # Use your embeddings in some way...
    np.save("embeddings_onnx.npy", embeddings)


if __name__ == "__main__":
    main()

License

GNU GPLv3. See License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ms2deepscore_onnx_converter-0.1.1.tar.gz (501.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ms2deepscore_onnx_converter-0.1.1-py3-none-any.whl (19.4 kB view details)

Uploaded Python 3

File details

Details for the file ms2deepscore_onnx_converter-0.1.1.tar.gz.

File metadata

  • Download URL: ms2deepscore_onnx_converter-0.1.1.tar.gz
  • Upload date:
  • Size: 501.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for ms2deepscore_onnx_converter-0.1.1.tar.gz
Algorithm Hash digest
SHA256 607d0bdb808883e3b2089d19d3c380e8f9cecef777088109ea04eaee7a412aed
MD5 accb13bdee76782c642bdcd71f6f1b73
BLAKE2b-256 6465493cdc144fb20cc26862db346e3a876ba078bfb6d7e82a066106226c5772

See more details on using hashes here.

File details

Details for the file ms2deepscore_onnx_converter-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: ms2deepscore_onnx_converter-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for ms2deepscore_onnx_converter-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 573ae910894598e3be7c3c484b7339eafe99e23e55163bc3b9c909ea385af15b
MD5 07ffd4675e09092208f291733fcc42bf
BLAKE2b-256 e75e4da93ab68c7978858da35bc0d92154d43edac18707d83d9b126f5a1b7e0b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page