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.2.0.tar.gz (502.0 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.2.0-py3-none-any.whl (19.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ms2deepscore_onnx_converter-0.2.0.tar.gz
  • Upload date:
  • Size: 502.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.24 {"installer":{"name":"uv","version":"0.11.24","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.2.0.tar.gz
Algorithm Hash digest
SHA256 06cd8a508dedd62f66e205072103e58dd96f4775acd27b60856a1e8f5ad8ba7c
MD5 8aa64c408362b7f62c385712b920db98
BLAKE2b-256 ce39ea1694428c6604e1786ceb393b1e8db3658fa84aa9ec463da35a1da3cfd8

See more details on using hashes here.

File details

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

File metadata

  • Download URL: ms2deepscore_onnx_converter-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 19.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.24 {"installer":{"name":"uv","version":"0.11.24","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.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4ffb462b7a26f6a5e5a8ca615575b218713aaeabb64e2915fbe397e91463ce50
MD5 9a1f78c24659d8a968157311dc43b3d0
BLAKE2b-256 4e3944f5039c457b599dfab17d2d3fbd89a4bf25250968984f602825350654ed

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