deeplc 4.4.0__tar.gz → 4.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. {deeplc-4.4.0/deeplc.egg-info → deeplc-4.5.0}/PKG-INFO +1 -1
  2. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/_architecture.py +23 -0
  3. deeplc-4.5.0/deeplc/_factored.py +181 -0
  4. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/_model_ops.py +99 -12
  5. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/calibration/multihead.py +53 -9
  6. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/core.py +17 -2
  7. {deeplc-4.4.0 → deeplc-4.5.0/deeplc.egg-info}/PKG-INFO +1 -1
  8. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc.egg-info/SOURCES.txt +2 -0
  9. {deeplc-4.4.0 → deeplc-4.5.0}/pyproject.toml +1 -1
  10. deeplc-4.5.0/tests/test_factored.py +149 -0
  11. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_model_ops.py +42 -0
  12. {deeplc-4.4.0 → deeplc-4.5.0}/LICENSE +0 -0
  13. {deeplc-4.4.0 → deeplc-4.5.0}/MANIFEST.in +0 -0
  14. {deeplc-4.4.0 → deeplc-4.5.0}/README.md +0 -0
  15. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/__init__.py +0 -0
  16. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/__main__.py +0 -0
  17. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/_batch_features.py +0 -0
  18. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/_features.py +0 -0
  19. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/_reference_selection.py +0 -0
  20. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/calibration/__init__.py +0 -0
  21. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/calibration/simple.py +0 -0
  22. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/data.py +0 -0
  23. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/exceptions.py +0 -0
  24. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/gui.py +0 -0
  25. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/__init__.py +0 -0
  26. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/baseline_performance/__init__.py +0 -0
  27. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv +0 -0
  28. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/examples/__init__.py +0 -0
  29. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/examples/example_psms.tsv.gz +0 -0
  30. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/__init__.py +0 -0
  31. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/config_icon.png +0 -0
  32. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/deeplc_logo.png +0 -0
  33. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/deeplc_logo.svg +0 -0
  34. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/program_icon.png +0 -0
  35. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/models/__init__.py +0 -0
  36. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/models/full_hc_PXD005573_pub_1fd8363d9af9dcad3be7553c39396960.pt +0 -0
  37. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/models/full_hc_PXD005573_pub_8c22d89667368f2f02ad996469ba157e.pt +0 -0
  38. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/models/full_hc_PXD005573_pub_cb975cfdd4105f97efa0b3afffe075cc.pt +0 -0
  39. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/models/multitask_flexcnn_model.pt +0 -0
  40. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/package_data/models/multitask_model.pt +0 -0
  41. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/plot.py +0 -0
  42. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc/report.py +0 -0
  43. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc.egg-info/dependency_links.txt +0 -0
  44. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc.egg-info/entry_points.txt +0 -0
  45. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc.egg-info/requires.txt +0 -0
  46. {deeplc-4.4.0 → deeplc-4.5.0}/deeplc.egg-info/top_level.txt +0 -0
  47. {deeplc-4.4.0 → deeplc-4.5.0}/setup.cfg +0 -0
  48. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_batch_features.py +0 -0
  49. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_calibration.py +0 -0
  50. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_core.py +0 -0
  51. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_deduplication.py +0 -0
  52. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_features.py +0 -0
  53. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_flexcnn.py +0 -0
  54. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_multihead_calibration.py +0 -0
  55. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_reference_selection.py +0 -0
  56. {deeplc-4.4.0 → deeplc-4.5.0}/tests/test_report.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deeplc
3
- Version: 4.4.0
3
+ Version: 4.5.0
4
4
  Summary: DeepLC: Retention time prediction for (modified) peptides using Deep Learning.
5
5
  Author: Ralf Gabriels, Kevin Velghe, Robbe Devreese, Arthur Declercq, Alireza Nameni, Ralf Gabriels, Niels Hulstaert, Sven Degroeve, Lennart Martens
6
6
  Author-email: Robbin Bouwmeester <robbin.bouwmeester@ugent.be>
@@ -938,6 +938,29 @@ class FlexCNNMultitaskModel(nn.Module):
938
938
  del x_atom_sum # the fused trunk reads x_atom directly
939
939
  return self.head(self.encoder(x_atom, x_global, x_one_hot), task_idx)
940
940
 
941
+ def project(
942
+ self,
943
+ x_atom: torch.Tensor,
944
+ x_atom_sum: torch.Tensor,
945
+ x_global: torch.Tensor,
946
+ x_one_hot: torch.Tensor,
947
+ ) -> torch.Tensor:
948
+ """
949
+ Map the trunk into the head's low-rank space, stopping before the per-setup step.
950
+
951
+ ``FactorHead`` finishes with ``projected @ embedding.T * scale + shift``, so this is
952
+ everything the setups share. Keeping it, rather than the ``(batch, n_tasks)`` matrix
953
+ it expands to, is what lets a whole run be held in ``(n_peptides, rank)``.
954
+
955
+ Returns
956
+ -------
957
+ torch.Tensor
958
+ Shape ``(batch, rank)``.
959
+
960
+ """
961
+ del x_atom_sum # the fused trunk reads x_atom directly
962
+ return self.head.proj(self.encoder(x_atom, x_global, x_one_hot))
963
+
941
964
  @property
942
965
  def padding_reach(self) -> int | None:
943
966
  """
@@ -0,0 +1,181 @@
1
+ """A prediction matrix held as its low-rank factors rather than materialised."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ __all__ = ["FactoredPredictionMatrix"]
8
+
9
+
10
+ class FactoredPredictionMatrix:
11
+ """
12
+ A prediction matrix kept as its low-rank factors.
13
+
14
+ Holds the ``(n_peptides, n_tasks)`` output of a
15
+ :class:`~deeplc._architecture.FactorHead` as the factors it is computed from.
16
+
17
+ That head is low rank by construction::
18
+
19
+ pred[:, j] = (proj(trunk).embedding[j]) * scale[j] + shift[j]
20
+
21
+ so the whole matrix is determined by ``proj(trunk)``, which is ``(n_peptides, rank)``,
22
+ together with the head's own parameters. At rank 64 and 6,543 setups that is 102 times
23
+ smaller than the matrix it stands for: 2.6 M peptides need 0.6 GiB of factors instead of
24
+ 63 GiB of predictions.
25
+
26
+ It indexes like the matrix. ``m[rows]``, ``m[:, heads]`` and ``m[rows, head]`` each
27
+ evaluate only what was asked for, so a caller that reads a few thousand rows to choose a
28
+ head and then one column per run never builds the rest. ``np.asarray(m)`` still gives the
29
+ dense matrix for code that genuinely needs it, at its full size.
30
+
31
+ Parameters
32
+ ----------
33
+ projections
34
+ ``proj(trunk)`` for every peptide, shape ``(n_peptides, rank)``.
35
+ embedding
36
+ Per-setup embedding, shape ``(n_tasks, rank)``.
37
+ scale, shift
38
+ Per-setup affine map, shape ``(n_tasks,)``.
39
+
40
+ """
41
+
42
+ #: Marks this as a source a calibration may index instead of a materialised matrix.
43
+ is_head_source = True
44
+
45
+ def __init__(
46
+ self,
47
+ projections: np.ndarray,
48
+ embedding: np.ndarray,
49
+ scale: np.ndarray,
50
+ shift: np.ndarray,
51
+ ) -> None:
52
+ self._projections = np.asarray(projections)
53
+ self._embedding = np.asarray(embedding, dtype=self._projections.dtype)
54
+ self._scale = np.asarray(scale, dtype=self._projections.dtype)
55
+ self._shift = np.asarray(shift, dtype=self._projections.dtype)
56
+ if self._embedding.shape[1] != self._projections.shape[1]:
57
+ raise ValueError(
58
+ f"embedding rank {self._embedding.shape[1]} does not match projection rank "
59
+ f"{self._projections.shape[1]}"
60
+ )
61
+
62
+ @property
63
+ def shape(self) -> tuple[int, int]:
64
+ """Rows and task count, without evaluating anything."""
65
+ return (self._projections.shape[0], self._embedding.shape[0])
66
+
67
+ @property
68
+ def ndim(self) -> int:
69
+ """Always two: this stands in for a matrix."""
70
+ return 2
71
+
72
+ @property
73
+ def dtype(self) -> np.dtype:
74
+ """Element type of the matrix it stands for."""
75
+ return self._projections.dtype
76
+
77
+ @property
78
+ def rank(self) -> int:
79
+ """Width of the factorisation."""
80
+ return self._projections.shape[1]
81
+
82
+ @property
83
+ def nbytes(self) -> int:
84
+ """What the factors occupy."""
85
+ return int(
86
+ self._projections.nbytes
87
+ + self._embedding.nbytes
88
+ + self._scale.nbytes
89
+ + self._shift.nbytes
90
+ )
91
+
92
+ @property
93
+ def dense_nbytes(self) -> int:
94
+ """What the matrix would occupy if it were materialised."""
95
+ rows, columns = self.shape
96
+ return int(rows * columns * self._projections.itemsize)
97
+
98
+ def __len__(self) -> int:
99
+ """Return the number of peptides."""
100
+ return self.shape[0]
101
+
102
+ def _evaluate(self, rows, columns) -> np.ndarray:
103
+ """Compute just the requested block from the factors."""
104
+ projections = self._projections if rows is None else self._projections[rows]
105
+ if projections.ndim == 1:
106
+ projections = projections[None, :]
107
+ if columns is None:
108
+ embedding, scale, shift = self._embedding, self._scale, self._shift
109
+ else:
110
+ embedding = np.atleast_2d(self._embedding[columns])
111
+ scale = np.atleast_1d(self._scale[columns])
112
+ shift = np.atleast_1d(self._shift[columns])
113
+ return (projections @ embedding.T) * scale + shift
114
+
115
+ def _select_rows(self, rows) -> FactoredPredictionMatrix:
116
+ """Narrow to a subset of peptides, still as factors."""
117
+ return FactoredPredictionMatrix(
118
+ self._projections[rows], self._embedding, self._scale, self._shift
119
+ )
120
+
121
+ def __getitem__(self, key):
122
+ """
123
+ Index as the dense matrix would, evaluating only the block that is asked for.
124
+
125
+ Selecting rows alone gives another factored matrix rather than a dense one. That is
126
+ what lets a caller narrow to one run's peptides and still hand the result to a
127
+ calibration, which reads a few dozen of the thousands of heads: nothing in that path
128
+ ever builds the wide matrix. A scalar in either position drops that axis, as numpy
129
+ does, so ``m[rows, head]`` is one dimensional and ``m[i, j]`` is a scalar.
130
+ """
131
+ rows, columns = key if isinstance(key, tuple) else (key, None)
132
+ if isinstance(rows, slice) and rows == slice(None):
133
+ rows = None
134
+ if columns is None and rows is not None and not _is_scalar(rows):
135
+ return self._select_rows(rows)
136
+ row_scalar = _is_scalar(rows)
137
+ column_scalar = columns is not None and _is_scalar(columns)
138
+ block = self._evaluate(rows, columns)
139
+ if row_scalar:
140
+ block = block[0]
141
+ return block[0] if column_scalar else block
142
+ return block[:, 0] if column_scalar else block
143
+
144
+ def __array__(self, dtype=None, copy=None) -> np.ndarray:
145
+ """Return the whole matrix, for callers that really need it, at its full size."""
146
+ dense = self._evaluate(None, None)
147
+ return dense if dtype is None else dense.astype(dtype)
148
+
149
+ def __getattr__(self, name: str):
150
+ """
151
+ Fall back to the dense matrix for anything not answered from the factors.
152
+
153
+ Reductions such as ``.min()`` and ``.mean()`` have no cheap factored form, so code
154
+ that calls them gets the same answer it always did, at the same cost it always had.
155
+ Only indexing, which is the path that matters for a wide matrix, stays lazy.
156
+ """
157
+ if name.startswith("_"):
158
+ raise AttributeError(name)
159
+ return getattr(np.asarray(self), name)
160
+
161
+ def __repr__(self) -> str:
162
+ """Show the shape it stands for and what it actually costs."""
163
+ rows, columns = self.shape
164
+ return (
165
+ f"{type(self).__name__}(shape=({rows}, {columns}), rank={self.rank}, "
166
+ f"{_human(self.nbytes)} held for a {_human(self.dense_nbytes)} matrix)"
167
+ )
168
+
169
+
170
+ def _is_scalar(index) -> bool:
171
+ """Whether an index selects one element rather than a subset."""
172
+ return np.isscalar(index) or (isinstance(index, np.generic) and np.ndim(index) == 0)
173
+
174
+
175
+ def _human(n: int) -> str:
176
+ """Format a byte count in the largest unit that keeps it above one."""
177
+ for unit in ("B", "KiB", "MiB", "GiB"):
178
+ if n < 1024 or unit == "GiB":
179
+ return f"{n:.1f} {unit}" if unit != "B" else f"{n} B"
180
+ n /= 1024
181
+ return f"{n:.1f} GiB"
@@ -19,7 +19,8 @@ from rich.progress import (
19
19
  )
20
20
  from torch.utils.data import DataLoader, Dataset, Subset
21
21
 
22
- from deeplc._architecture import DeepLCModel, FlexCNNMultitaskModel
22
+ from deeplc._architecture import DeepLCModel, FactorHead, FlexCNNMultitaskModel
23
+ from deeplc._factored import FactoredPredictionMatrix
23
24
  from deeplc.data import DeepLCDataset
24
25
 
25
26
  logger = logging.getLogger(__name__)
@@ -242,6 +243,49 @@ def train(
242
243
  return model
243
244
 
244
245
 
246
+ def supports_factored(model: torch.nn.Module) -> bool:
247
+ """
248
+ Whether this model's output can be kept as low-rank factors instead of a matrix.
249
+
250
+ True only for a multitask model that still has its ``FactorHead``. A head fine-tuned
251
+ onto one setup returns that column alone, so there is nothing to factor.
252
+ """
253
+ head = getattr(model, "head", None)
254
+ return (
255
+ hasattr(model, "project")
256
+ and isinstance(head, FactorHead)
257
+ and not getattr(head, "has_new_task", False)
258
+ )
259
+
260
+
261
+ def _output_hint(n_rows: int, columns: int, itemsize: int) -> str:
262
+ """Explain an output that does not fit, and how to make it smaller."""
263
+ return (
264
+ f"Predicting would need an output of {n_rows:,} x {columns:,} values "
265
+ f"({n_rows * columns * itemsize / 2**30:.1f} GiB). A multitask model returns one "
266
+ f"column per LC setup, so ask for the setups you need with "
267
+ f"predict_kwargs={{'task_idx': [...]}}, or predict in smaller groups of peptides."
268
+ )
269
+
270
+
271
+ def _allocate_output(n_rows: int, tail: tuple[int, ...], dtype: torch.dtype) -> torch.Tensor:
272
+ """
273
+ Allocate the whole prediction output up front.
274
+
275
+ Two reasons not to collect batches in a list and concatenate at the end. The
276
+ concatenation needs the result twice over, once in the parts and once in the copy, so
277
+ the peak is double what the caller ends up holding. And it only fails after every
278
+ batch has been predicted, which on a large run means the work is lost. Allocating
279
+ first fails immediately and holds one copy.
280
+ """
281
+ try:
282
+ return torch.empty((n_rows, *tail), dtype=dtype)
283
+ except (RuntimeError, MemoryError) as exc:
284
+ columns = int(np.prod(tail)) if tail else 1
285
+ itemsize = torch.empty(0, dtype=dtype).element_size()
286
+ raise MemoryError(_output_hint(n_rows, columns, itemsize)) from exc
287
+
288
+
245
289
  def predict(
246
290
  model: torch.nn.Module | PathLike | str | None,
247
291
  data: Dataset,
@@ -252,10 +296,17 @@ def predict(
252
296
  show_progress: bool = True,
253
297
  task_idx: Sequence[int] | None = None,
254
298
  length_buckets: bool = True,
255
- ) -> torch.Tensor:
299
+ factored: bool = False,
300
+ ) -> torch.Tensor | FactoredPredictionMatrix:
256
301
  """
257
302
  Predict using the model for the given dataset.
258
303
 
304
+ ``factored`` returns a :class:`~deeplc._factored.FactoredPredictionMatrix` rather than
305
+ the matrix itself, for the multitask models whose head is low rank. It indexes the same
306
+ way but holds ``(n_peptides, rank)`` instead of ``(n_peptides, n_tasks)``, which at rank
307
+ 64 and 6,543 setups is 102 times less memory. Ignored when the model cannot be factored
308
+ or when ``task_idx`` already narrows the output.
309
+
259
310
  ``length_buckets`` runs length-sorted chunks in a window that fits them rather than
260
311
  padding every peptide to the model's full window; see :func:`_length_buckets`. It is
261
312
  exact for models that report a ``padding_reach`` and ignored for those that do not.
@@ -270,6 +321,8 @@ def predict(
270
321
  device = device or ("cuda" if torch.cuda.is_available() else "cpu")
271
322
  model = load_model(model, device)
272
323
 
324
+ as_factors = factored and task_idx is None and supports_factored(model)
325
+
273
326
  buckets = _length_buckets(model, data, batch_size) if length_buckets else None
274
327
  if buckets is None:
275
328
  predictions = _predict_epoch(
@@ -280,8 +333,10 @@ def predict(
280
333
  num_workers=num_workers,
281
334
  show_progress=show_progress,
282
335
  task_idx=task_idx,
336
+ project=as_factors,
283
337
  )
284
- return predictions.cpu().detach()
338
+ result = predictions.cpu().detach()
339
+ return _as_factored(model, result) if as_factors else result
285
340
 
286
341
  out: torch.Tensor | None = None
287
342
  for indices, subset in buckets:
@@ -293,13 +348,26 @@ def predict(
293
348
  num_workers=num_workers,
294
349
  show_progress=show_progress,
295
350
  task_idx=task_idx,
351
+ project=as_factors,
296
352
  ).cpu()
297
353
  if out is None:
298
- out = torch.empty((len(data), part.shape[1]), dtype=part.dtype)
354
+ out = _allocate_output(len(data), tuple(part.shape[1:]), part.dtype)
299
355
  out[indices] = part
300
356
  if out is None:
301
357
  raise ValueError("Dataset is empty — nothing to predict.")
302
- return out.detach()
358
+ out = out.detach()
359
+ return _as_factored(model, out) if as_factors else out
360
+
361
+
362
+ def _as_factored(model: torch.nn.Module, projections: torch.Tensor) -> FactoredPredictionMatrix:
363
+ """Pair the projections with the head parameters that expand them."""
364
+ head = model.head
365
+ return FactoredPredictionMatrix(
366
+ projections.numpy(),
367
+ head.embedding.detach().cpu().numpy(),
368
+ head.scale.detach().cpu().numpy(),
369
+ head.shift.detach().cpu().numpy(),
370
+ )
303
371
 
304
372
 
305
373
  #: Widest spread of peptide lengths allowed inside one prediction chunk. Small enough that
@@ -475,14 +543,18 @@ def _predict_epoch(
475
543
  num_workers: int = 0,
476
544
  show_progress: bool = False,
477
545
  task_idx: Sequence[int] | None = None,
546
+ project: bool = False,
478
547
  ) -> torch.Tensor:
479
- """Predict using the model for one epoch."""
548
+ """Predict using the model for one epoch, or project into the head's rank if asked."""
480
549
  model.eval()
481
550
  selected = None
482
551
  if task_idx is not None and supports_task_subset(model):
483
552
  selected = torch.as_tensor(list(task_idx), dtype=torch.long, device=device)
484
- predictions = []
485
- total = int(np.ceil(len(data) / batch_size)) if hasattr(data, "__len__") else None
553
+ sized = hasattr(data, "__len__")
554
+ total = int(np.ceil(len(data) / batch_size)) if sized else None
555
+ out: torch.Tensor | None = None
556
+ parts: list[torch.Tensor] = []
557
+ filled = 0
486
558
  with torch.no_grad():
487
559
  for features in track(
488
560
  _feature_batches(data, batch_size, num_workers),
@@ -492,11 +564,26 @@ def _predict_epoch(
492
564
  total=total,
493
565
  ):
494
566
  features = [feature_tensor.to(device) for feature_tensor in features]
495
- outputs = model(*features) if selected is None else model(*features, task_idx=selected)
496
- predictions.append(outputs.cpu())
497
- if not predictions:
567
+ if project:
568
+ outputs = model.project(*features)
569
+ else:
570
+ outputs = (
571
+ model(*features) if selected is None else model(*features, task_idx=selected)
572
+ )
573
+ batch = outputs.cpu()
574
+ # The column count is only known once a batch has been through the model, so the
575
+ # output is allocated on the first one and filled from there. A dataset that
576
+ # cannot report its length falls back to collecting the batches.
577
+ if sized:
578
+ if out is None:
579
+ out = _allocate_output(len(data), tuple(batch.shape[1:]), batch.dtype)
580
+ out[filled : filled + len(batch)] = batch
581
+ else:
582
+ parts.append(batch)
583
+ filled += len(batch)
584
+ if filled == 0:
498
585
  raise ValueError("Dataset is empty — nothing to predict.")
499
- return torch.cat(predictions, dim=0)
586
+ return out[:filled] if out is not None else torch.cat(parts, dim=0)
500
587
 
501
588
 
502
589
  def _create_progress(disable: bool = False) -> Progress:
@@ -119,15 +119,22 @@ class _SingleHeadCalibration(MultiHeadCalibration):
119
119
  # The matrix arrives from the model as float32 and is (n, 6,543) wide; promoting it
120
120
  # here doubled a 276 MB reference to 552 MB for no gain, since every head's column is
121
121
  # cast to float32 again for its spline and the ranking accumulates in float64 itself.
122
- source = np.asarray(source)
123
- if source.ndim == 1:
124
- source = source[:, None]
122
+ #
123
+ # A lazy source is left lazy. Ranking already walks the heads in blocks and every step
124
+ # after it reads single columns, so nothing here needs the matrix whole; forcing it
125
+ # would put the reference's full width in memory for no purpose. A reference of every
126
+ # confidently identified PSM in a large search is exactly where that bites.
127
+ source = as_head_matrix(source)
128
+ if not getattr(source, "is_head_source", False):
129
+ source = np.asarray(source)
130
+ if source.ndim == 1:
131
+ source = source[:, None]
125
132
  target = np.asarray(target, dtype=np.float64).ravel()
126
133
  if source.shape[0] != target.shape[0]:
127
134
  raise CalibrationError(
128
135
  f"source has {source.shape[0]} rows and target {target.shape[0]}"
129
136
  )
130
- finite = np.isfinite(target) & np.isfinite(source).all(axis=1)
137
+ finite = np.isfinite(target) & _finite_rows(source)
131
138
  if int(finite.sum()) < 3:
132
139
  raise CalibrationError("Fewer than three reference points with finite values.")
133
140
  source, target = source[finite], target[finite]
@@ -267,15 +274,22 @@ class MultiHeadRidgeCalibration(MultiHeadCalibration):
267
274
  # The matrix arrives from the model as float32 and is (n, 6,543) wide; promoting it
268
275
  # here doubled a 276 MB reference to 552 MB for no gain, since every head's column is
269
276
  # cast to float32 again for its spline and the ranking accumulates in float64 itself.
270
- source = np.asarray(source)
271
- if source.ndim == 1:
272
- source = source[:, None]
277
+ #
278
+ # A lazy source is left lazy. Ranking already walks the heads in blocks and every step
279
+ # after it reads single columns, so nothing here needs the matrix whole; forcing it
280
+ # would put the reference's full width in memory for no purpose. A reference of every
281
+ # confidently identified PSM in a large search is exactly where that bites.
282
+ source = as_head_matrix(source)
283
+ if not getattr(source, "is_head_source", False):
284
+ source = np.asarray(source)
285
+ if source.ndim == 1:
286
+ source = source[:, None]
273
287
  target = np.asarray(target, dtype=np.float64).ravel()
274
288
  if source.shape[0] != target.shape[0]:
275
289
  raise CalibrationError(
276
290
  f"source has {source.shape[0]} rows and target {target.shape[0]}"
277
291
  )
278
- finite = np.isfinite(target) & np.isfinite(source).all(axis=1)
292
+ finite = np.isfinite(target) & _finite_rows(source)
279
293
  if int(finite.sum()) < 3:
280
294
  raise CalibrationError("Fewer than three reference points with finite values.")
281
295
  source, target = source[finite], target[finite]
@@ -424,6 +438,36 @@ def upgrade_calibration(calibration: Calibration | MultiHeadCalibration) -> Mult
424
438
  return MultiHeadSplineCalibration()
425
439
 
426
440
 
441
+ #: Largest block of a lazy source held at once, in bytes. Blocks are sized from the row count
442
+ #: so the peak does not grow with the reference: a reference of a million PSMs reads narrower
443
+ #: blocks than one of a thousand, and both stay near this figure.
444
+ _BLOCK_BYTES = 64 * 2**20
445
+
446
+
447
+ def _head_block(n_rows: int, n_heads: int, itemsize: int = 8) -> int:
448
+ """How many heads to read at once so a block stays near :data:`_BLOCK_BYTES`."""
449
+ if n_rows <= 0:
450
+ return n_heads
451
+ return int(max(1, min(n_heads, _BLOCK_BYTES // max(1, n_rows * itemsize))))
452
+
453
+
454
+ def _finite_rows(source) -> np.ndarray:
455
+ """
456
+ Rows whose every head is finite, without holding more than a block of heads at once.
457
+
458
+ A dense source is checked in one pass as before. A lazy one is walked in the same blocks
459
+ the ranking uses, so the widest thing in memory is a slice rather than the matrix.
460
+ """
461
+ if not getattr(source, "is_head_source", False):
462
+ return np.isfinite(source).all(axis=1)
463
+ n_rows, n_heads = source.shape
464
+ finite = np.ones(n_rows, dtype=bool)
465
+ block = _head_block(n_rows, n_heads, itemsize=4)
466
+ for start in range(0, n_heads, block):
467
+ finite &= np.isfinite(np.asarray(source[:, start : start + block])).all(axis=1)
468
+ return finite
469
+
470
+
427
471
  def _rank_heads_by_correlation(source: np.ndarray, target: np.ndarray) -> np.ndarray:
428
472
  """
429
473
  Head indices by decreasing Pearson correlation with the target, in one pass.
@@ -442,7 +486,7 @@ def _rank_heads_by_correlation(source: np.ndarray, target: np.ndarray) -> np.nda
442
486
  # product per block and the variance follows from the block's own sums. Blocks keep the
443
487
  # accumulation in float64 without ever holding more than a slice of the matrix.
444
488
  correlation = np.empty(n_heads, dtype=np.float64)
445
- block = 512
489
+ block = _head_block(n_rows, n_heads)
446
490
  with np.errstate(invalid="ignore", divide="ignore"):
447
491
  for start in range(0, n_heads, block):
448
492
  chunk = np.asarray(source[:, start : start + block], dtype=np.float64)
@@ -12,6 +12,7 @@ from psm_utils import PSM, Peptidoform, PSMList
12
12
  from torch.utils.data import DataLoader
13
13
 
14
14
  from deeplc import _model_ops
15
+ from deeplc._factored import FactoredPredictionMatrix
15
16
  from deeplc._reference_selection import deduplicate_psms, select_reference_psms
16
17
  from deeplc.calibration import (
17
18
  Calibration,
@@ -76,7 +77,11 @@ def predict(
76
77
  model
77
78
  Trained model or path to model file. If None, the default DeepLC model is used.
78
79
  predict_kwargs
79
- Additional keyword arguments to pass to the prediction function.
80
+ Additional keyword arguments to pass to the prediction function. Pass
81
+ ``{"factored": False}`` to force a dense ``ndarray`` from ``return_matrix=True``.
82
+ The default hands back a
83
+ :class:`~deeplc._factored.FactoredPredictionMatrix`, which holds the head's low-rank
84
+ factors and indexes identically at a fraction of the memory.
80
85
  return_matrix
81
86
  If True, return the full prediction matrix of shape ``(n, n_heads)`` when using a
82
87
  multitask model. If False (default), return a 1D array of shape ``(n,)`` for the
@@ -114,6 +119,15 @@ def predict(
114
119
  ):
115
120
  kwargs["task_idx"] = [_default_task_idx(loaded_model)]
116
121
 
122
+ # The matrix a multitask model returns is its head's low-rank factors expanded out, so the
123
+ # factors are handed back instead. They report the same shape and index the same way, but
124
+ # hold (n_peptides, rank) rather than (n_peptides, n_tasks): at rank 64 and 6,543 setups
125
+ # that is 102 times less, the difference between 0.6 GiB and 63 GiB on a 2.6 M peptide run.
126
+ # Anything the factors cannot answer falls through to the dense matrix, so a caller that
127
+ # reduces over the result rather than slicing it behaves exactly as before.
128
+ if return_matrix and "task_idx" not in kwargs and _model_ops.supports_factored(loaded_model):
129
+ kwargs.setdefault("factored", True)
130
+
117
131
  result = _model_ops.predict(
118
132
  model=loaded_model,
119
133
  data=DeepLCDataset.from_psm_list(
@@ -122,7 +136,8 @@ def predict(
122
136
  **_feature_kwargs_from_spec(feature_spec),
123
137
  ),
124
138
  **kwargs,
125
- ).numpy()
139
+ )
140
+ result = result if isinstance(result, FactoredPredictionMatrix) else result.numpy()
126
141
  if not return_matrix:
127
142
  return result[:, 0 if "task_idx" in kwargs else _default_task_idx(loaded_model)]
128
143
  return result
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deeplc
3
- Version: 4.4.0
3
+ Version: 4.5.0
4
4
  Summary: DeepLC: Retention time prediction for (modified) peptides using Deep Learning.
5
5
  Author: Ralf Gabriels, Kevin Velghe, Robbe Devreese, Arthur Declercq, Alireza Nameni, Ralf Gabriels, Niels Hulstaert, Sven Degroeve, Lennart Martens
6
6
  Author-email: Robbin Bouwmeester <robbin.bouwmeester@ugent.be>
@@ -6,6 +6,7 @@ deeplc/__init__.py
6
6
  deeplc/__main__.py
7
7
  deeplc/_architecture.py
8
8
  deeplc/_batch_features.py
9
+ deeplc/_factored.py
9
10
  deeplc/_features.py
10
11
  deeplc/_model_ops.py
11
12
  deeplc/_reference_selection.py
@@ -44,6 +45,7 @@ tests/test_batch_features.py
44
45
  tests/test_calibration.py
45
46
  tests/test_core.py
46
47
  tests/test_deduplication.py
48
+ tests/test_factored.py
47
49
  tests/test_features.py
48
50
  tests/test_flexcnn.py
49
51
  tests/test_model_ops.py
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "deeplc"
3
- version = "4.4.0"
3
+ version = "4.5.0"
4
4
  description = "DeepLC: Retention time prediction for (modified) peptides using Deep Learning."
5
5
  readme = "README.md"
6
6
  license = { file = "LICENSE" }
@@ -0,0 +1,149 @@
1
+ """The factored prediction matrix must equal the matrix it stands for."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pytest
7
+ import torch
8
+
9
+ from deeplc import _model_ops, core
10
+ from deeplc._architecture import DeepLCModel
11
+ from deeplc._factored import FactoredPredictionMatrix
12
+ from deeplc.core import DEFAULT_MODEL
13
+
14
+ PREDICT_KWARGS = {"device": "cpu", "show_progress": False}
15
+ PEPTIDES = [
16
+ "PEPTIDEK",
17
+ "LVVVGAGGVGK",
18
+ "GPNGPWSVMK",
19
+ "YPLQLAELLK",
20
+ "VVEEAVDLFK",
21
+ "AAELALR",
22
+ "SLIDLLQK",
23
+ "ELVISLIVESK",
24
+ "AAAAAAAAAAK",
25
+ "WWWWK",
26
+ ]
27
+
28
+
29
+ def _matrices():
30
+ """Return the same predictions as factors and as a dense matrix."""
31
+ lazy = core.predict(PEPTIDES, model=None, predict_kwargs=PREDICT_KWARGS, return_matrix=True)
32
+ dense = core.predict(
33
+ PEPTIDES,
34
+ model=None,
35
+ predict_kwargs={**PREDICT_KWARGS, "factored": False},
36
+ return_matrix=True,
37
+ )
38
+ return lazy, dense
39
+
40
+
41
+ requires_bundled_model = pytest.mark.skipif(
42
+ not DEFAULT_MODEL.exists(), reason="multitask model not bundled"
43
+ )
44
+
45
+
46
+ @requires_bundled_model
47
+ def test_factored_is_the_default_and_dense_is_available():
48
+ """A multitask matrix comes back factored; `factored: False` forces the dense one."""
49
+ lazy, dense = _matrices()
50
+ assert isinstance(lazy, FactoredPredictionMatrix)
51
+ assert isinstance(dense, np.ndarray)
52
+ assert lazy.shape == dense.shape
53
+ assert lazy.ndim == dense.ndim == 2
54
+ assert len(lazy) == len(PEPTIDES)
55
+
56
+
57
+ @requires_bundled_model
58
+ @pytest.mark.parametrize(
59
+ "index",
60
+ [
61
+ np.s_[:],
62
+ np.s_[np.array([0, 3, 7])],
63
+ np.s_[2],
64
+ np.s_[:, 2016],
65
+ np.s_[:, [12, 2016, 4000]],
66
+ np.s_[np.array([0, 3, 7]), 2016],
67
+ np.s_[3, 2016],
68
+ ],
69
+ ids=["all", "rows", "one-row", "one-column", "columns", "rows-and-column", "scalar"],
70
+ )
71
+ def test_every_indexing_form_matches_the_dense_matrix(index):
72
+ """Shape and values must agree, so a caller cannot tell which it was handed."""
73
+ lazy, dense = _matrices()
74
+ from_factors = np.asarray(lazy[index])
75
+ from_dense = np.asarray(dense[index])
76
+ assert from_factors.shape == from_dense.shape
77
+ np.testing.assert_allclose(from_factors, from_dense, atol=1e-3)
78
+
79
+
80
+ @requires_bundled_model
81
+ def test_selecting_rows_stays_factored():
82
+ """A run's rows must remain factors, or a calibration would build every head for them."""
83
+ lazy, dense = _matrices()
84
+ rows = np.array([0, 3, 7])
85
+ view = lazy[rows]
86
+ assert isinstance(view, FactoredPredictionMatrix)
87
+ assert view.shape == (len(rows), lazy.shape[1])
88
+ np.testing.assert_allclose(np.asarray(view), dense[rows], atol=1e-3)
89
+
90
+
91
+ @requires_bundled_model
92
+ def test_array_methods_fall_back_to_the_dense_matrix():
93
+ """Reductions have no factored form, so they must still give the same answer."""
94
+ lazy, dense = _matrices()
95
+ assert np.isfinite(lazy).all()
96
+ np.testing.assert_allclose(lazy.min(), dense.min(), atol=1e-3)
97
+ np.testing.assert_allclose(lazy.mean(), dense.mean(), atol=1e-3)
98
+
99
+
100
+ @requires_bundled_model
101
+ def test_asarray_gives_the_dense_matrix():
102
+ """Code that genuinely needs the matrix still gets it."""
103
+ lazy, dense = _matrices()
104
+ np.testing.assert_allclose(np.asarray(lazy), dense, atol=1e-3)
105
+
106
+
107
+ @requires_bundled_model
108
+ def test_factors_are_smaller_than_the_matrix_they_stand_for():
109
+ """The point of the exercise: a run's factors cost a fraction of its predictions."""
110
+ lazy, _ = _matrices()
111
+ # Per peptide, rank floats instead of n_tasks floats.
112
+ per_peptide_factored = lazy.rank * lazy.dtype.itemsize
113
+ per_peptide_dense = lazy.shape[1] * lazy.dtype.itemsize
114
+ assert per_peptide_dense / per_peptide_factored > 100
115
+
116
+
117
+ @requires_bundled_model
118
+ def test_calibration_accepts_it_as_a_head_source():
119
+ """`as_head_matrix` must pass it through rather than densifying it."""
120
+ from deeplc.calibration.multihead import as_head_matrix
121
+
122
+ lazy, _ = _matrices()
123
+ assert lazy.is_head_source is True
124
+ assert as_head_matrix(lazy) is lazy
125
+
126
+
127
+ def test_single_task_models_are_not_factorable():
128
+ """Only a multitask FactorHead has factors to keep."""
129
+ assert _model_ops.supports_factored(DeepLCModel(n_heads=1)) is False
130
+
131
+
132
+ @requires_bundled_model
133
+ def test_a_head_finetuned_onto_one_setup_is_not_factorable():
134
+ """`add_task` makes the head return one column, so there is nothing to factor."""
135
+ model = _model_ops.load_model(DEFAULT_MODEL, device="cpu")
136
+ assert _model_ops.supports_factored(model) is True
137
+ model.head.add_task(torch.zeros(4))
138
+ assert _model_ops.supports_factored(model) is False
139
+
140
+
141
+ def test_rank_mismatch_is_rejected():
142
+ """Factors that cannot multiply are caught at construction, not at indexing."""
143
+ with pytest.raises(ValueError, match="rank"):
144
+ FactoredPredictionMatrix(
145
+ np.zeros((4, 8), dtype=np.float32),
146
+ np.zeros((3, 16), dtype=np.float32),
147
+ np.ones(3, dtype=np.float32),
148
+ np.zeros(3, dtype=np.float32),
149
+ )
@@ -81,3 +81,45 @@ def test_load_multitask_model_without_prior_shim():
81
81
  assert out.ndim == 2
82
82
  assert out.shape[0] == 2
83
83
  assert out.shape[1] > 1 # multiple heads
84
+
85
+
86
+ def test_predict_output_matches_batchwise_concatenation():
87
+ """The preallocated output must equal what concatenating the batches produced."""
88
+ model, dataset = DeepLCModel(n_heads=1), _TinyDeepLCDataset(length=37)
89
+ batched = _model_ops.predict(
90
+ model, dataset, device="cpu", batch_size=8, show_progress=False, length_buckets=False
91
+ )
92
+ single = _model_ops.predict(
93
+ model, dataset, device="cpu", batch_size=1000, show_progress=False, length_buckets=False
94
+ )
95
+ assert batched.shape == single.shape == (37, 1)
96
+ torch.testing.assert_close(batched, single)
97
+
98
+
99
+ def test_allocate_output_reports_the_size_when_it_does_not_fit():
100
+ """An output that cannot be allocated says how large it was and how to shrink it."""
101
+ with pytest.raises(MemoryError, match=r"task_idx"):
102
+ _model_ops._allocate_output(2**40, (6543,), torch.float32)
103
+
104
+
105
+ def test_predict_propagates_the_allocation_failure(monkeypatch):
106
+ """The helper's message reaches the caller of predict() rather than a raw allocator error."""
107
+ def _refuse(*args, **kwargs):
108
+ raise MemoryError(_model_ops._output_hint(2**40, 6543, 4))
109
+
110
+ monkeypatch.setattr(_model_ops, "_allocate_output", _refuse)
111
+ with pytest.raises(MemoryError, match=r"task_idx"):
112
+ _model_ops.predict(
113
+ model=DeepLCModel(n_heads=1),
114
+ data=_TinyDeepLCDataset(length=4),
115
+ device="cpu",
116
+ show_progress=False,
117
+ length_buckets=False,
118
+ )
119
+
120
+
121
+ def test_output_hint_mentions_the_size_in_gigabytes():
122
+ """The hint names the size that failed, so a log line is enough to diagnose it."""
123
+ hint = _model_ops._output_hint(2_587_932, 6543, 4)
124
+ assert "63.1 GiB" in hint
125
+ assert "task_idx" in hint
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes