weirdo 2.1.2__tar.gz → 2.1.4__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 (64) hide show
  1. {weirdo-2.1.2/weirdo.egg-info → weirdo-2.1.4}/PKG-INFO +54 -23
  2. {weirdo-2.1.2 → weirdo-2.1.4}/README.md +46 -0
  3. weirdo-2.1.4/pyproject.toml +61 -0
  4. {weirdo-2.1.2 → weirdo-2.1.4}/requirements.txt +2 -2
  5. weirdo-2.1.4/scripts/train_modal_long_run.py +282 -0
  6. weirdo-2.1.4/test/test_cli_logic.py +94 -0
  7. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_mlp_scorers.py +232 -0
  8. weirdo-2.1.4/test/test_model_downloads.py +96 -0
  9. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_swissprot_reference.py +22 -0
  10. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/__init__.py +7 -1
  11. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/api.py +28 -0
  12. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/cli.py +104 -0
  13. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/model_manager.py +162 -1
  14. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/base.py +1 -1
  15. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/config.py +1 -1
  16. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/mlp.py +634 -59
  17. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/reference.py +1 -1
  18. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/similarity.py +1 -1
  19. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/swissprot.py +4 -0
  20. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/trainable.py +1 -3
  21. {weirdo-2.1.2 → weirdo-2.1.4/weirdo.egg-info}/PKG-INFO +54 -23
  22. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo.egg-info/SOURCES.txt +3 -1
  23. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo.egg-info/requires.txt +3 -3
  24. weirdo-2.1.4/weirdo.egg-info/top_level.txt +5 -0
  25. weirdo-2.1.2/setup.py +0 -100
  26. weirdo-2.1.2/test/test_cli_logic.py +0 -40
  27. weirdo-2.1.2/weirdo.egg-info/top_level.txt +0 -1
  28. {weirdo-2.1.2 → weirdo-2.1.4}/LICENSE +0 -0
  29. {weirdo-2.1.2 → weirdo-2.1.4}/MANIFEST.in +0 -0
  30. {weirdo-2.1.2 → weirdo-2.1.4}/setup.cfg +0 -0
  31. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_amino_acids.py +0 -0
  32. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_blosum.py +0 -0
  33. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_data_manager.py +0 -0
  34. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_hamming.py +0 -0
  35. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_logic_consistency.py +0 -0
  36. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_ngram.py +0 -0
  37. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_pmbec.py +0 -0
  38. {weirdo-2.1.2 → weirdo-2.1.4}/test/test_scorers.py +0 -0
  39. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/amino_acid.py +0 -0
  40. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/amino_acid_alphabet.py +0 -0
  41. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/amino_acid_properties.py +0 -0
  42. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/blosum.py +0 -0
  43. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/chou_fasman.py +0 -0
  44. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/common.py +0 -0
  45. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/data_manager.py +0 -0
  46. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/distances.py +0 -0
  47. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/BLOSUM30 +0 -0
  48. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/BLOSUM50 +0 -0
  49. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/BLOSUM62 +0 -0
  50. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/__init__.py +0 -0
  51. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/amino_acid_properties.txt +0 -0
  52. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/helix_vs_coil.txt +0 -0
  53. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/helix_vs_strand.txt +0 -0
  54. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/pmbec.mat +0 -0
  55. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/matrices/strand_vs_coil.txt +0 -0
  56. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/peptide_vectorizer.py +0 -0
  57. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/pmbec.py +0 -0
  58. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/reduced_alphabet.py +0 -0
  59. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/residue_contact_energies.py +0 -0
  60. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/__init__.py +0 -0
  61. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/scorers/registry.py +0 -0
  62. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo/static_data.py +0 -0
  63. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo.egg-info/dependency_links.txt +0 -0
  64. {weirdo-2.1.2 → weirdo-2.1.4}/weirdo.egg-info/entry_points.txt +0 -0
@@ -1,31 +1,27 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: weirdo
3
- Version: 2.1.2
3
+ Version: 2.1.4
4
4
  Summary: Metrics of immunological foreignness for candidate T-cell epitopes
5
- Home-page: https://github.com/pirl-unc/weirdo
6
- Author: Alex Rubinsteyn
7
- Author-email: alex.rubinsteyn@unc.edu
8
- License: Apache-2.0
5
+ Author-email: Alex Rubinsteyn <alex.rubinsteyn@unc.edu>
6
+ Project-URL: Homepage, https://github.com/pirl-unc/weirdo
7
+ Project-URL: Bug Tracker, https://github.com/pirl-unc/weirdo/issues
9
8
  Classifier: Development Status :: 4 - Beta
10
9
  Classifier: Environment :: Console
11
10
  Classifier: Operating System :: OS Independent
12
11
  Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
13
  Classifier: Programming Language :: Python :: 3
14
- Classifier: Programming Language :: Python :: 3.9
15
- Classifier: Programming Language :: Python :: 3.10
16
- Classifier: Programming Language :: Python :: 3.11
17
- Classifier: Programming Language :: Python :: 3.12
18
14
  Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
19
15
  Requires-Python: >=3.9
20
16
  Description-Content-Type: text/markdown
21
17
  License-File: LICENSE
22
- Requires-Dist: numpy<2.0.0,>=1.20.0
23
- Requires-Dist: pandas<3.0.0,>=1.3.0
18
+ Requires-Dist: numpy<3.0.0,>=2.0.0
19
+ Requires-Dist: pandas>=1.3.0
24
20
  Requires-Dist: scikit-learn<2.0.0,>=1.0.0
25
21
  Provides-Extra: dev
26
22
  Requires-Dist: pytest>=7.0.0; extra == "dev"
27
23
  Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
28
- Requires-Dist: pylint>=2.0.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.4.0; extra == "dev"
29
25
  Requires-Dist: sphinx>=5.0.0; extra == "dev"
30
26
  Requires-Dist: sphinx-rtd-theme>=1.0.0; extra == "dev"
31
27
  Requires-Dist: sphinx-autodoc-typehints>=1.0.0; extra == "dev"
@@ -34,18 +30,7 @@ Provides-Extra: docs
34
30
  Requires-Dist: sphinx>=5.0.0; extra == "docs"
35
31
  Requires-Dist: sphinx-rtd-theme>=1.0.0; extra == "docs"
36
32
  Requires-Dist: sphinx-autodoc-typehints>=1.0.0; extra == "docs"
37
- Dynamic: author
38
- Dynamic: author-email
39
- Dynamic: classifier
40
- Dynamic: description
41
- Dynamic: description-content-type
42
- Dynamic: home-page
43
- Dynamic: license
44
33
  Dynamic: license-file
45
- Dynamic: provides-extra
46
- Dynamic: requires-dist
47
- Dynamic: requires-python
48
- Dynamic: summary
49
34
 
50
35
  [![Tests](https://github.com/pirl-unc/weirdo/actions/workflows/tests.yml/badge.svg)](https://github.com/pirl-unc/weirdo/actions/workflows/tests.yml)
51
36
  [![Documentation](https://github.com/pirl-unc/weirdo/actions/workflows/docs.yml/badge.svg)](https://github.com/pirl-unc/weirdo/actions/workflows/docs.yml)
@@ -258,11 +243,57 @@ weirdo data list # Show data status
258
243
  weirdo models list # List trained models
259
244
  weirdo models train --data train.csv --name my-model
260
245
  weirdo models info my-model # Show model details
246
+ weirdo models available # List built-in downloadable pretrained models
247
+ weirdo models download NAME # Download pretrained weights by name
248
+ weirdo models download --url https://.../model.tar.gz --save-as my-model
261
249
 
262
250
  # Scoring
263
251
  weirdo score --model my-model MTMDKSEL SIINFEKL
264
252
  ```
265
253
 
254
+ ## Long-Run Training on Modal
255
+
256
+ Use `scripts/train_modal_long_run.py` to run long remote training and export
257
+ weights as a `.tar.gz` archive:
258
+
259
+ ```bash
260
+ # One-time setup: seed full SwissProt CSV into Modal data volume
261
+ modal volume put weirdo-data-cache data/swissprot-8mers.csv downloads/swissprot-8mers.csv --force
262
+ ```
263
+
264
+ ```bash
265
+ modal run scripts/train_modal_long_run.py \
266
+ --model-name swissprot-mlp-modal \
267
+ --epochs 1000 \
268
+ --max-samples 2000000 \
269
+ --output-archive ./swissprot-mlp-modal.tar.gz
270
+ ```
271
+
272
+ The script:
273
+ - trains `MLPScorer` remotely
274
+ - saves model files to a Modal volume
275
+ - packages weights into `MODEL_NAME.tar.gz`
276
+ - can return archive bytes to your local machine (`--output-archive`)
277
+ - reads SwissProt from `--swissprot-path` (default: `/root/.weirdo/downloads/swissprot-8mers.csv`)
278
+ - treats `--max-samples 0` (default) as "use all available rows"
279
+
280
+ ## Distributing Model Weights
281
+
282
+ Recommended flow:
283
+
284
+ 1. Train and export `MODEL_NAME.tar.gz` (Modal script above).
285
+ 2. Upload archive to a GitHub Release asset (or other HTTPS hosting).
286
+ 3. Download after install via CLI:
287
+
288
+ ```bash
289
+ # Direct URL (no code change needed)
290
+ weirdo models download --url https://github.com/ORG/REPO/releases/download/vX.Y.Z/MODEL_NAME.tar.gz --save-as MODEL_NAME
291
+ ```
292
+
293
+ If you want named built-in downloads (`weirdo models download MODEL_NAME`),
294
+ add an entry to `PRETRAINED_MODELS` in `weirdo/model_manager.py` and release a
295
+ new package version.
296
+
266
297
  ## Architecture
267
298
 
268
299
  ```
@@ -209,11 +209,57 @@ weirdo data list # Show data status
209
209
  weirdo models list # List trained models
210
210
  weirdo models train --data train.csv --name my-model
211
211
  weirdo models info my-model # Show model details
212
+ weirdo models available # List built-in downloadable pretrained models
213
+ weirdo models download NAME # Download pretrained weights by name
214
+ weirdo models download --url https://.../model.tar.gz --save-as my-model
212
215
 
213
216
  # Scoring
214
217
  weirdo score --model my-model MTMDKSEL SIINFEKL
215
218
  ```
216
219
 
220
+ ## Long-Run Training on Modal
221
+
222
+ Use `scripts/train_modal_long_run.py` to run long remote training and export
223
+ weights as a `.tar.gz` archive:
224
+
225
+ ```bash
226
+ # One-time setup: seed full SwissProt CSV into Modal data volume
227
+ modal volume put weirdo-data-cache data/swissprot-8mers.csv downloads/swissprot-8mers.csv --force
228
+ ```
229
+
230
+ ```bash
231
+ modal run scripts/train_modal_long_run.py \
232
+ --model-name swissprot-mlp-modal \
233
+ --epochs 1000 \
234
+ --max-samples 2000000 \
235
+ --output-archive ./swissprot-mlp-modal.tar.gz
236
+ ```
237
+
238
+ The script:
239
+ - trains `MLPScorer` remotely
240
+ - saves model files to a Modal volume
241
+ - packages weights into `MODEL_NAME.tar.gz`
242
+ - can return archive bytes to your local machine (`--output-archive`)
243
+ - reads SwissProt from `--swissprot-path` (default: `/root/.weirdo/downloads/swissprot-8mers.csv`)
244
+ - treats `--max-samples 0` (default) as "use all available rows"
245
+
246
+ ## Distributing Model Weights
247
+
248
+ Recommended flow:
249
+
250
+ 1. Train and export `MODEL_NAME.tar.gz` (Modal script above).
251
+ 2. Upload archive to a GitHub Release asset (or other HTTPS hosting).
252
+ 3. Download after install via CLI:
253
+
254
+ ```bash
255
+ # Direct URL (no code change needed)
256
+ weirdo models download --url https://github.com/ORG/REPO/releases/download/vX.Y.Z/MODEL_NAME.tar.gz --save-as MODEL_NAME
257
+ ```
258
+
259
+ If you want named built-in downloads (`weirdo models download MODEL_NAME`),
260
+ add an entry to `PRETRAINED_MODELS` in `weirdo/model_manager.py` and release a
261
+ new package version.
262
+
217
263
  ## Architecture
218
264
 
219
265
  ```
@@ -0,0 +1,61 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "weirdo"
7
+ requires-python = ">=3.9"
8
+ authors = [{name="Alex Rubinsteyn", email="alex.rubinsteyn@unc.edu"}]
9
+ description = "Metrics of immunological foreignness for candidate T-cell epitopes"
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Environment :: Console",
13
+ "Operating System :: OS Independent",
14
+ "Intended Audience :: Science/Research",
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
18
+ ]
19
+ readme = "README.md"
20
+ dynamic = ["version", "dependencies"]
21
+
22
+ [tool.setuptools.dynamic]
23
+ version = {attr = "weirdo.__version__"}
24
+ dependencies = {file = ["requirements.txt"]}
25
+
26
+ [tool.setuptools.packages.find]
27
+ exclude = ["test", "test.*", "examples"]
28
+
29
+ [tool.setuptools.package-data]
30
+ weirdo = ["logging.conf", "matrices/*"]
31
+
32
+ [project.urls]
33
+ "Homepage" = "https://github.com/pirl-unc/weirdo"
34
+ "Bug Tracker" = "https://github.com/pirl-unc/weirdo/issues"
35
+
36
+ [project.scripts]
37
+ weirdo = "weirdo.cli:run"
38
+
39
+ [project.optional-dependencies]
40
+ dev = [
41
+ "pytest>=7.0.0",
42
+ "pytest-cov>=4.0.0",
43
+ "ruff>=0.4.0",
44
+ "sphinx>=5.0.0",
45
+ "sphinx-rtd-theme>=1.0.0",
46
+ "sphinx-autodoc-typehints>=1.0.0",
47
+ "tqdm>=4.0.0",
48
+ ]
49
+ docs = [
50
+ "sphinx>=5.0.0",
51
+ "sphinx-rtd-theme>=1.0.0",
52
+ "sphinx-autodoc-typehints>=1.0.0",
53
+ ]
54
+
55
+ [tool.ruff.lint]
56
+ select = ["E", "F"]
57
+ ignore = ["F821", "E501", "F841", "E731", "E741"]
58
+
59
+ [tool.ruff.lint.per-file-ignores]
60
+ "__init__.py" = ["F401"]
61
+ "test/*" = ["F401"]
@@ -1,4 +1,4 @@
1
1
  # Core dependencies
2
- numpy>=1.20.0,<2.0.0
3
- pandas>=1.3.0,<3.0.0
2
+ numpy>=2.0.0,<3.0.0
3
+ pandas>=1.3.0
4
4
  scikit-learn>=1.0.0,<2.0.0
@@ -0,0 +1,282 @@
1
+ #!/usr/bin/env python3
2
+ """Train WEIRDO for a long run on Modal and export learned weights.
3
+
4
+ This script trains `MLPScorer` remotely, saves the model directory to a Modal
5
+ volume, and packages it as a `.tar.gz` artifact that can be distributed.
6
+
7
+ Examples
8
+ --------
9
+ Seed full SwissProt data once into the Modal data volume:
10
+ modal volume put weirdo-data-cache data/swissprot-8mers.csv downloads/swissprot-8mers.csv --force
11
+
12
+ Run long training remotely:
13
+ modal run scripts/train_modal_long_run.py --model-name swissprot-mlp-modal --epochs 1000
14
+
15
+ Download resulting weights to a local file:
16
+ modal run scripts/train_modal_long_run.py --model-name swissprot-mlp-modal --output-archive ./swissprot-mlp-modal.tar.gz
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import subprocess
24
+ import modal
25
+
26
+
27
+ APP_NAME = "weirdo-train-long-run"
28
+ ARTIFACTS_VOLUME_NAME = "weirdo-model-artifacts"
29
+ DATA_CACHE_VOLUME_NAME = "weirdo-data-cache"
30
+
31
+ def _resolve_weirdo_git_ref() -> str:
32
+ """Resolve WEIRDO git ref for Modal image build."""
33
+ explicit_ref = os.getenv("WEIRDO_GIT_REF", "").strip()
34
+ if explicit_ref:
35
+ return explicit_ref
36
+ try:
37
+ return subprocess.check_output(
38
+ ["git", "rev-parse", "HEAD"],
39
+ text=True,
40
+ ).strip()
41
+ except Exception:
42
+ # Fallback for environments without git metadata.
43
+ return "main"
44
+
45
+
46
+ WEIRDO_GIT_REF = _resolve_weirdo_git_ref()
47
+
48
+ DEFAULT_TARGET_CATEGORIES = (
49
+ "archaea,bacteria,fungi,human,invertebrates,mammals,plants,rodents,vertebrates,viruses"
50
+ )
51
+ DEFAULT_SWISSPROT_PATH = "/root/.weirdo/downloads/swissprot-8mers.csv"
52
+
53
+
54
+ def _build_image() -> modal.Image:
55
+ return (
56
+ modal.Image.debian_slim(python_version="3.12")
57
+ .apt_install("git")
58
+ .run_commands("python -m pip install --upgrade pip")
59
+ .run_commands(
60
+ "git clone https://github.com/pirl-unc/weirdo.git /root/weirdo "
61
+ f"&& cd /root/weirdo && git checkout {WEIRDO_GIT_REF}"
62
+ )
63
+ .workdir("/root/weirdo")
64
+ .run_commands("python -m pip install .")
65
+ )
66
+
67
+
68
+ image = _build_image()
69
+ app = modal.App(APP_NAME, image=image)
70
+
71
+ artifacts_volume = modal.Volume.from_name(ARTIFACTS_VOLUME_NAME, create_if_missing=True)
72
+ data_cache_volume = modal.Volume.from_name(DATA_CACHE_VOLUME_NAME, create_if_missing=True)
73
+
74
+
75
+ @app.function(
76
+ cpu=16,
77
+ memory=65536,
78
+ timeout=12 * 60 * 60,
79
+ volumes={
80
+ "/artifacts": artifacts_volume,
81
+ "/root/.weirdo": data_cache_volume,
82
+ },
83
+ )
84
+ def train_remote(
85
+ model_name: str,
86
+ max_samples: int = 0,
87
+ epochs: int = 500,
88
+ learning_rate: float = 1e-3,
89
+ batch_size: int = 2048,
90
+ progress_every_samples: int = 500000,
91
+ total_rows_hint: int = 0,
92
+ scaler_max_rows: int = 0,
93
+ train_max_rows_per_epoch: int = 0,
94
+ epoch_shuffle: bool = True,
95
+ epoch_shuffle_max_skip_rows: int = 0,
96
+ shuffle_in_batch: bool = True,
97
+ parallel_workers: int = 1,
98
+ parallel_chunksize: int = 256,
99
+ hidden_layers_csv: str = "256,128,64",
100
+ target_categories_csv: str = DEFAULT_TARGET_CATEGORIES,
101
+ swissprot_path: str = DEFAULT_SWISSPROT_PATH,
102
+ seed: int = 42,
103
+ ) -> dict[str, object]:
104
+ """Train model remotely and persist model + archive in volume.
105
+
106
+ Use ``max_samples=0`` to train on all available rows.
107
+ """
108
+ from pathlib import Path
109
+ import tarfile
110
+
111
+ from weirdo.model_manager import ModelManager
112
+ from weirdo.scorers import MLPScorer, SwissProtReference
113
+
114
+ target_categories = [x.strip() for x in target_categories_csv.split(",") if x.strip()]
115
+ hidden_layers = tuple(int(x.strip()) for x in hidden_layers_csv.split(",") if x.strip())
116
+
117
+ data_path = Path(swissprot_path)
118
+ if not data_path.exists():
119
+ raise FileNotFoundError(
120
+ "SwissProt CSV not found in Modal volume at "
121
+ f"{data_path}. Seed it once with:\n"
122
+ " modal volume put weirdo-data-cache data/swissprot-8mers.csv "
123
+ "downloads/swissprot-8mers.csv --force"
124
+ )
125
+
126
+ scorer = MLPScorer(
127
+ k=8,
128
+ hidden_layer_sizes=hidden_layers,
129
+ random_state=seed,
130
+ )
131
+ if max_samples <= 0:
132
+ # Stream all rows from CSV to keep memory bounded for full SwissProt runs.
133
+ ref = SwissProtReference(
134
+ data_path=str(data_path),
135
+ auto_download=False,
136
+ lazy=True,
137
+ ).load()
138
+
139
+ def row_iterator_factory():
140
+ for kmer, cats in ref.iter_kmers_with_categories():
141
+ yield kmer, [1.0 if cats.get(cat, False) else 0.0 for cat in target_categories]
142
+
143
+ scorer.train_streaming(
144
+ row_iterator_factory=row_iterator_factory,
145
+ target_categories=target_categories,
146
+ epochs=epochs,
147
+ learning_rate=learning_rate,
148
+ batch_size=batch_size,
149
+ progress_every_samples=progress_every_samples,
150
+ total_rows_hint=(None if total_rows_hint <= 0 else total_rows_hint),
151
+ scaler_max_rows=scaler_max_rows,
152
+ train_max_rows_per_epoch=train_max_rows_per_epoch,
153
+ epoch_shuffle=epoch_shuffle,
154
+ epoch_shuffle_max_skip_rows=epoch_shuffle_max_skip_rows,
155
+ shuffle_in_batch=shuffle_in_batch,
156
+ parallel_workers=parallel_workers,
157
+ parallel_chunksize=parallel_chunksize,
158
+ verbose=True,
159
+ )
160
+ else:
161
+ ref = SwissProtReference(
162
+ data_path=str(data_path),
163
+ auto_download=False,
164
+ lazy=True,
165
+ ).load()
166
+ peptides, labels = ref.get_training_data(
167
+ target_categories=target_categories,
168
+ multi_label=True,
169
+ max_samples=max_samples,
170
+ shuffle=True,
171
+ seed=seed,
172
+ )
173
+ scorer.train(
174
+ peptides=peptides,
175
+ labels=labels,
176
+ target_categories=target_categories,
177
+ epochs=epochs,
178
+ learning_rate=learning_rate,
179
+ batch_size=batch_size,
180
+ verbose=True,
181
+ )
182
+
183
+ manager = ModelManager(model_dir=Path("/artifacts/models"))
184
+ saved_model_dir = manager.save(scorer, name=model_name, overwrite=True)
185
+
186
+ archive_path = Path("/artifacts") / f"{model_name}.tar.gz"
187
+ with tarfile.open(archive_path, "w:gz") as tar:
188
+ tar.add(saved_model_dir, arcname=model_name)
189
+
190
+ metadata = {
191
+ "model_name": model_name,
192
+ "saved_model_dir": str(saved_model_dir),
193
+ "archive_path": str(archive_path),
194
+ "swissprot_path": str(data_path),
195
+ "n_train": scorer._metadata.get("n_train"),
196
+ "scaler_rows": scorer._metadata.get("scaler_rows"),
197
+ "n_epochs": scorer._metadata.get("n_epochs"),
198
+ "final_train_loss": scorer._metadata.get("final_train_loss"),
199
+ "final_val_loss": scorer._metadata.get("final_val_loss"),
200
+ "epoch_rows": scorer._metadata.get("epoch_rows"),
201
+ "epoch_skip_rows": scorer._metadata.get("epoch_skip_rows"),
202
+ "training_history": scorer.training_history,
203
+ }
204
+ with open(Path("/artifacts") / f"{model_name}.json", "w") as f:
205
+ json.dump(metadata, f, indent=2)
206
+
207
+ # Ensure files are visible to other functions in the same app run.
208
+ artifacts_volume.commit()
209
+
210
+ return metadata
211
+
212
+
213
+ @app.function(
214
+ timeout=30 * 60,
215
+ volumes={"/artifacts": artifacts_volume},
216
+ )
217
+ def read_archive_bytes(model_name: str) -> bytes:
218
+ """Read archived model bytes from volume."""
219
+ from pathlib import Path
220
+
221
+ # Pull latest writes from other containers before reading.
222
+ artifacts_volume.reload()
223
+
224
+ archive_path = Path("/artifacts") / f"{model_name}.tar.gz"
225
+ if not archive_path.exists():
226
+ raise FileNotFoundError(f"Archive not found: {archive_path}")
227
+ return archive_path.read_bytes()
228
+
229
+
230
+ @app.local_entrypoint()
231
+ def main(
232
+ model_name: str = "swissprot-mlp-modal",
233
+ max_samples: int = 0,
234
+ epochs: int = 500,
235
+ learning_rate: float = 1e-3,
236
+ batch_size: int = 2048,
237
+ progress_every_samples: int = 500000,
238
+ total_rows_hint: int = 0,
239
+ scaler_max_rows: int = 0,
240
+ train_max_rows_per_epoch: int = 0,
241
+ epoch_shuffle: bool = True,
242
+ epoch_shuffle_max_skip_rows: int = 0,
243
+ shuffle_in_batch: bool = True,
244
+ parallel_workers: int = 1,
245
+ parallel_chunksize: int = 256,
246
+ hidden_layers: str = "256,128,64",
247
+ target_categories: str = DEFAULT_TARGET_CATEGORIES,
248
+ swissprot_path: str = DEFAULT_SWISSPROT_PATH,
249
+ seed: int = 42,
250
+ output_archive: str = "",
251
+ ):
252
+ """Run remote training and optionally pull model weights locally."""
253
+ result = train_remote.remote(
254
+ model_name=model_name,
255
+ max_samples=max_samples,
256
+ epochs=epochs,
257
+ learning_rate=learning_rate,
258
+ batch_size=batch_size,
259
+ progress_every_samples=progress_every_samples,
260
+ total_rows_hint=total_rows_hint,
261
+ scaler_max_rows=scaler_max_rows,
262
+ train_max_rows_per_epoch=train_max_rows_per_epoch,
263
+ epoch_shuffle=epoch_shuffle,
264
+ epoch_shuffle_max_skip_rows=epoch_shuffle_max_skip_rows,
265
+ shuffle_in_batch=shuffle_in_batch,
266
+ parallel_workers=parallel_workers,
267
+ parallel_chunksize=parallel_chunksize,
268
+ hidden_layers_csv=hidden_layers,
269
+ target_categories_csv=target_categories,
270
+ swissprot_path=swissprot_path,
271
+ seed=seed,
272
+ )
273
+ print(json.dumps(result, indent=2))
274
+
275
+ if output_archive:
276
+ from pathlib import Path
277
+
278
+ model_bytes = read_archive_bytes.remote(model_name=model_name)
279
+ output_path = Path(output_archive)
280
+ output_path.parent.mkdir(parents=True, exist_ok=True)
281
+ output_path.write_bytes(model_bytes)
282
+ print(f"Wrote model archive to: {output_path}")
@@ -0,0 +1,94 @@
1
+ import pytest
2
+
3
+ from weirdo.cli import create_parser, run
4
+ from weirdo.reduced_alphabet import alphabets
5
+
6
+
7
+ def test_score_command_requires_model_argument():
8
+ parser = create_parser()
9
+ with pytest.raises(SystemExit):
10
+ parser.parse_args(["score", "MTMDKSEL"])
11
+
12
+
13
+ def test_translate_fasta_file(tmp_path, capsys):
14
+ fasta = tmp_path / "input.fasta"
15
+ fasta.write_text(">seq1\nACD\nEF\n>seq2\nWXYZ\n")
16
+
17
+ code = run(["translate", "--input-fasta", str(fasta), "-a", "hp2"])
18
+ assert code == 0
19
+
20
+ out_lines = capsys.readouterr().out.strip().splitlines()
21
+ alphabet = alphabets["hp2"]
22
+ expected_seq1 = "".join(alphabet.get(aa, aa) for aa in "ACDEF")
23
+ expected_seq2 = "".join(alphabet.get(aa, aa) for aa in "WXYZ")
24
+
25
+ assert out_lines == [">seq1", expected_seq1, ">seq2", expected_seq2]
26
+
27
+
28
+ def test_translate_fasta_requires_header(tmp_path, capsys):
29
+ fasta = tmp_path / "bad.fasta"
30
+ fasta.write_text("ACDEFG\n")
31
+
32
+ code = run(["translate", "--input-fasta", str(fasta), "-a", "hp2"])
33
+ assert code == 1
34
+ assert "must contain at least one header line" in capsys.readouterr().out
35
+
36
+
37
+ def test_data_clear_rejects_conflicting_flags(capsys):
38
+ code = run(["data", "clear", "--downloads", "--all", "-y"])
39
+ assert code == 1
40
+ assert "Choose either --downloads or --all" in capsys.readouterr().out
41
+
42
+
43
+ def test_models_available_when_no_registry(capsys, monkeypatch):
44
+ monkeypatch.setattr("weirdo.model_manager.list_pretrained_models", lambda: [])
45
+ code = run(["models", "available"])
46
+ assert code == 0
47
+ assert "No built-in pretrained models are configured." in capsys.readouterr().out
48
+
49
+
50
+ def test_models_download_requires_name_without_url(capsys):
51
+ code = run(["models", "download"])
52
+ assert code == 1
53
+ assert "Provide a pretrained model name" in capsys.readouterr().out
54
+
55
+
56
+ def test_models_download_url_requires_name(capsys):
57
+ code = run(["models", "download", "--url", "https://example.com/model.tar.gz"])
58
+ assert code == 1
59
+ assert "provide a model name" in capsys.readouterr().out.lower()
60
+
61
+
62
+ def test_models_download_custom_url(monkeypatch, capsys):
63
+ called = {}
64
+
65
+ def fake_download_model_from_url(name, url, overwrite=False, expected_sha256=None):
66
+ called["name"] = name
67
+ called["url"] = url
68
+ called["overwrite"] = overwrite
69
+ called["expected_sha256"] = expected_sha256
70
+ return f"/tmp/{name}"
71
+
72
+ monkeypatch.setattr("weirdo.model_manager.download_model_from_url", fake_download_model_from_url)
73
+
74
+ code = run(
75
+ [
76
+ "models",
77
+ "download",
78
+ "--url",
79
+ "https://example.com/model.tar.gz",
80
+ "--save-as",
81
+ "my-model",
82
+ "--sha256",
83
+ "abc123",
84
+ "--force",
85
+ ]
86
+ )
87
+ assert code == 0
88
+ assert called == {
89
+ "name": "my-model",
90
+ "url": "https://example.com/model.tar.gz",
91
+ "overwrite": True,
92
+ "expected_sha256": "abc123",
93
+ }
94
+ assert "Downloaded model 'my-model'" in capsys.readouterr().out