Repository navigation
Security
-
PyTorch bundles are stored as safetensors plus a JSON config.
InferencePipeline.save(andpush_to_hub) on the PyTorch backend wrote the whole
model pickled tomodel.pt, andload/from_pretrainedunpickled it, which runs
any code the file contains: loading a public dlomix PyTorch repo from the Hub ran
code from that repo. A bundle now holdsmodel.safetensors(the weights, tensors
only) andmodel_config.json(the model's class name andget_config()). Loading
rebuilds only the six dlomix PyTorch models (or a class you register with
dlomix.models.register_torch_model), loads the weights strictly onto the CPU, and
unpickles nothing. The six PyTorch models gainget_config/from_config. The
pipeline metadata records"format_version": 2. TensorFlow bundles (model.keras,
loaded in Keras' safe mode) are unchanged. -
Loading a
model.ptbundle requiresallow_pickle=True.InferencePipeline.load
andfrom_pretrainedtakeallow_pickle=False; a bundle saved by dlomix 0.4.0 or
earlier raisesValueErrorunless it is set, and then loads with a warning. Set it
only for bundles you trust. Convert a trusted bundle once:from dlomix.pipelines import InferencePipeline InferencePipeline.load("old_bundle", allow_pickle=True).save("new_bundle")
-
Re-push PyTorch repos on the Hub: load each one as above and call
push_to_hub
again, which replacesmodel.ptwith the new files. Until then, users of dlomix
0.4.1 cannot load them withoutallow_pickle=True.
Dependencies
safetensors>=0.4.3in thetorch/pytorchextras.
Documentation
SECURITY.md: report vulnerabilities privately, through GitHub's private vulnerability
reporting. The docs say to load pipelines only from trusted sources and to pin a Hub
repo'srevision, and explain how to recognise a pre-0.4.1 PyTorch repo.
Behaviour changes
- Dropout is now applied during
fit(TensorFlow/Keras backend). Thecallof
PrositIntensityPredictor,PrositRetentionTimePredictor,ChargeStatePredictor,
RetentionTimePredictorandDetectabilityModeldid not declaretraining, and
Keras 3 passestraining=Trueonly to acallthat declares it, so these models
trained in inference mode: everyDropoutlayer was off, without error or warning.
Training results change for every model trained with a dropout rate above 0
(dropout_rate,latent_dropout_rate); the defaults are above 0. To reproduce
results obtained with 0.3.1 or earlier, set the dropout rates to 0. Inference
(predict,evaluate, saved models) is unchanged. - Training batches are reshuffled every epoch (TensorFlow datasets,
tensor_train_data). With a global seed set (keras.utils.set_random_seed), every
epoch repeated the batch order of the first; now each epoch has a new order, and
the sequence of orders is reproducible from the seed. Results of seeded training
runs change. Every row is still visited once per epoch, and validation and test
data keep the split's row order. enable_tf_dataset_cache=Truenow means "keep the split in memory": the
split's tensor columns are loaded into RAM once and batches are gathered from
there (in a synthetic benchmark, about 15x the rate of reading from disk), for
the train, val and test splits. Before, it called.cache()after shuffling and
batching, which replayed the first epoch's batches in every later epoch. The
splits used must fit in memory; streaming is not supported.initialization_strategy="mean"averages residue embeddings only. The mean
included the rows of the padding token (-) and the unknown token (X), which
carry no residue information. New tokens (and the"best-fit"fallback for tokens
without examples) therefore start from a slightly different embedding than in
0.3.1. Rows and indices of known tokens are unchanged.- Best-fit initialization with several new tokens scores the candidates for a
new token on the spectra in which it is the only new token. Before, it used every
spectrum containing the token, with the other new tokens encoded as the unknown
tokenX, so candidates were scored on damaged inputs. With fewer than
min_examples_for_evalsuch spectra (a newbest_fit_kwargsoption, default 20,
at mostn_examples_for_eval), spectra that also carry other new tokens are added
up ton_examples_for_eval, with the other new tokens encoded as their
unmodified residue (R[UNIMOD:7]asR). Picks can change for datasets with
several new tokens; with one new token they are the same as in 0.3.1. - Best-fit samples its examples: of more than
n_examples_for_evalspectra it
takes a random sample seeded withrandom_seed, instead of the first rows of the
dataset. Passrandom_seedfor a reproducible pick. FineTunePipeline.finetune()keeps the starting model when fine-tuning does not
improve it. It evaluates the validation loss before training and, when no epoch
has a lower one, restores the starting weights (with little data, every epoch can
be worse, andEarlyStopping(restore_best_weights=True)only returns the best
trained epoch). The returned history says which model was kept (kept_model:
"starting"or"trained") and has thestarting_val_loss. This costs one extra
pass over the validation data;keep_starting_model=Falseturns it off.
Added
FineTunePipeline.finetune(trainable="all" | "embedding" | "new_tokens"), also a
constructor argument and YAML key (default"all", as before)."embedding"
trains only the token embedding;"new_tokens"trains only the embedding rows of
the tokens added by the vocabulary expansion, leaving every other weight,
including the known tokens' rows, exactly as it was, so predictions for peptides
without the new tokens do not change. Withfrom_dataset_and_model, name the
tokens withnew_tokens=[...]. In Keras 3,model.trainable = Falsefollowed by
model.embedding.trainable = Trueleaves no trainable weights; the pipeline
freezes the other layers individually and restores their flags after training.
The same is available for custom training loops as
dlomix.models.model_utils.embedding_only_training(model, rows=None).dlomix.reports.evaluate_intensity(model, dataset, split="test"): predicts a
split, post-processes the predictions as Prosit does and adds the spectral angle.
Returns a DataFrame with one row per spectrum, in the order of the split. For
Keras models. Example in the intensity walkthrough notebook.Model.from_dataset(dataset, **kwargs)on every model (both backends) builds the
model with the arguments that must agree with the dataset taken from it; other
arguments, such as the layer sizes, are passed as keyword arguments, and one that
contradicts the dataset raises. Taken from the dataset:
PrositIntensityPredictor:alphabet,seq_length,with_termini, the sequence
column ininput_keys, andmeta_data_keys/use_meta_datafrom its
model_features;PrositRetentionTimePredictor,RetentionTimePredictor,
ChargeStatePredictor:alphabetandseq_length(the encoded width, with the
termini);DeepLCRetentionTimePredictor: the same andsequence_input_key;
DetectabilityModel: the alphabet size and padding token;Ionmob:num_tokens
(andsequence_keyon TensorFlow).dlomix.reports.score_intensity_predictions(predictions, dataset, split="test"):
the scoring ofevaluate_intensityfor predictions made elsewhere (an
InferencePipelineon the raw rows, a PyTorch model, another tool), so their
spectral angles are comparable.evaluate_intensityis now predict, then this.dlomix.data.sequence_tokens,find_new_tokensandextend_alphabet: the tokens
of a ProForma sequence as the datasets encode it, the tokens of new data that an
alphabet (e.g. a pretrained model's) does not have, and the alphabet extended by
them with every known token at its index. Fine-tuning code needed the private
SequenceParsingProcessor._parse_proforma_sequencefor this; the parser is now
the publicdlomix.data.processing.processors.parse_proforma_sequence.FineTunePipeline.from_pretrained(base, data): a ready pipeline from a pretrained
inference bundle (object, path or Hub repo id) and Hugging Face data. The bundle's
preprocessing settings build the dataset, the tokens new to the model are found
and appended to its vocabulary, and their embeddings are initialized by
initialization_strategy;new_tokensandbest_fit_infoare set. It composes
public steps that remain available one by one:find_new_tokens,
extend_alphabet, the dataset class with the new
PeptidePreprocessor.dataset_settings, the new
dlomix.models.adapt_pretrained_model(model, new_alphabet, ...)(the part of
load_and_adapt_pretrained_modelafter loading, for a model in memory) and
from_dataset_and_model. The existing constructor,setup()and
load_and_adapt_pretrained_modelare unchanged.- The feature lookup tables are documented (#103) in
dlomix.data.processing.feature_dicts: what each JSON file holds, and the atom
order[H, C, N, O, P, S]ofatom_count,mod_lossandmod_gain, also
available asdlomix.data.processing.feature_tables.PTM_ATOMSand named in
available_feature_extractors().
Changed
- dlomix builds its TensorFlow datasets itself, from a shuffled row index, instead of
calling Hugging Face'sto_tf_dataset. Tensor names, dtypes and shapes are
unchanged; reading batches from disk (the default) is faster than before. return_fit_inforeturns the whole best-fit search per new token: every
candidate's score (scores), the spectra with the token, left out and searched
(n_with_token,n_left_out,n_searched), which examples were used (examples)
and theinitializationthat applied. A token without examples now has an entry
saying it kept the mean initialization (old_tokenis None) instead of an empty
dict.load_processed_datasetgives the tensors of the active backend (DLOMIX_BACKEND),
whichever backend the dataset was saved on; before, a dataset saved on TensorFlow
keptdataset_type="tf"on PyTorch until overridden by hand. Passdataset_type=
to choose explicitly.- The warning for a preprocessor that does not match the one a pipeline was saved
with names the settings that changed (InferencePipeline.load). Bundles record
these settings from this release on; for older bundles the warning says so. - Release workflow:
pypa/gh-action-pypi-publish1.14.3, which fixes the security
advisory GHSA-5xjx-3w67-w9x9. - Docs: for the PyTorch backend,
torch_dataloader_kwargs={"num_workers": N}loads
batches in parallel.
Deprecated
PrositIntensityPredictor(latent_dropout_rate=...)(both backends): the argument
was documented, stored and serialised, but never used by any layer. It is still
accepted and saved, so existing models and configs load unchanged; a value other
than the default warns, and the argument will be removed in a future release.
Fixed
PrositIntensityPredictordocstrings:regressor_layer_sizeis the width of the
decoder GRU, not of a dense layer;recurrent_layers_sizes[1]is also the width of
the latent vector and of the meta data dense layer.- Building the package no longer warns that
dlomix.data.processing.feature_dicts"would be ignored": the folder of the
feature lookup tables is now a package with its JSON files as package data.