rewirebench 0.6.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.
- rewirebench-0.6.0/.gitignore +19 -0
- rewirebench-0.6.0/LICENSE +21 -0
- rewirebench-0.6.0/PKG-INFO +28 -0
- rewirebench-0.6.0/hatch_build.py +26 -0
- rewirebench-0.6.0/pyproject.toml +27 -0
- rewirebench-0.6.0/src/rewirebench/__init__.py +26 -0
- rewirebench-0.6.0/src/rewirebench/adapters/__init__.py +0 -0
- rewirebench-0.6.0/src/rewirebench/adapters/baselines.py +114 -0
- rewirebench-0.6.0/src/rewirebench/adapters/esm.py +97 -0
- rewirebench-0.6.0/src/rewirebench/adapters/esm_embeddings.py +79 -0
- rewirebench-0.6.0/src/rewirebench/adapters/evcouplings_independent.py +575 -0
- rewirebench-0.6.0/src/rewirebench/adapters/fimo_motifs.py +286 -0
- rewirebench-0.6.0/src/rewirebench/adapters/mfass.py +201 -0
- rewirebench-0.6.0/src/rewirebench/adapters/sequence.py +60 -0
- rewirebench-0.6.0/src/rewirebench/backends/__init__.py +57 -0
- rewirebench-0.6.0/src/rewirebench/backends/base.py +188 -0
- rewirebench-0.6.0/src/rewirebench/backends/local.py +59 -0
- rewirebench-0.6.0/src/rewirebench/backends/runpod.py +256 -0
- rewirebench-0.6.0/src/rewirebench/backends/spark.py +361 -0
- rewirebench-0.6.0/src/rewirebench/baselines.py +304 -0
- rewirebench-0.6.0/src/rewirebench/cleanup.py +77 -0
- rewirebench-0.6.0/src/rewirebench/cli.py +428 -0
- rewirebench-0.6.0/src/rewirebench/mcp_server.py +736 -0
- rewirebench-0.6.0/src/rewirebench/metrics.py +141 -0
- rewirebench-0.6.0/src/rewirebench/models.py +294 -0
- rewirebench-0.6.0/src/rewirebench/protocols/__init__.py +0 -0
- rewirebench-0.6.0/src/rewirebench/protocols/dart_eval.py +292 -0
- rewirebench-0.6.0/src/rewirebench/protocols/flip2.py +264 -0
- rewirebench-0.6.0/src/rewirebench/protocols/genomic_benchmarks.py +241 -0
- rewirebench-0.6.0/src/rewirebench/protocols/mfass.py +230 -0
- rewirebench-0.6.0/src/rewirebench/protocols/mrnabench.py +239 -0
- rewirebench-0.6.0/src/rewirebench/protocols/proteingym.py +250 -0
- rewirebench-0.6.0/src/rewirebench/protocols/tdc_admet.py +237 -0
- rewirebench-0.6.0/src/rewirebench/provenance.py +49 -0
- rewirebench-0.6.0/src/rewirebench/receipts.py +1385 -0
- rewirebench-0.6.0/src/rewirebench/recipes.py +932 -0
- rewirebench-0.6.0/src/rewirebench/resources/dart_eval/demo.json +66 -0
- rewirebench-0.6.0/src/rewirebench/resources/dart_eval/sources.json +105 -0
- rewirebench-0.6.0/src/rewirebench/resources/dart_eval/statistical-reference.json +126 -0
- rewirebench-0.6.0/src/rewirebench/resources/dart_eval/uniform-background.txt +6 -0
- rewirebench-0.6.0/src/rewirebench/resources/dart_eval/upstream-evaluator-reference.json +50 -0
- rewirebench-0.6.0/src/rewirebench/resources/dart_eval/validation-receipt.json +40 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/amylase-README.upstream.md +8 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/example_adapter.py +32 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/hydro-README.upstream.md +9 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/ired-README.upstream.md +10 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/nucb-README.upstream.md +9 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/pdz3-README.upstream.md +8 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/rhomax-README.upstream.md +9 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/sources.json +406 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/trpb-README.upstream.md +10 -0
- rewirebench-0.6.0/src/rewirebench/resources/flip2/validation-2026-09-20.json +335 -0
- rewirebench-0.6.0/src/rewirebench/resources/mfass/README.md +27 -0
- rewirebench-0.6.0/src/rewirebench/resources/mfass/split-v2.tsv +27734 -0
- rewirebench-0.6.0/src/rewirebench/resources/mfass/validation-2026-09-17.json +54 -0
- rewirebench-0.6.0/src/rewirebench/resources/models/esm2-embeddings.json +36 -0
- rewirebench-0.6.0/src/rewirebench/resources/mrnabench/sources.json +66 -0
- rewirebench-0.6.0/src/rewirebench/resources/mrnabench/validation-receipt.json +122 -0
- rewirebench-0.6.0/src/rewirebench/resources/proteingym/DMS_substitutions.csv +218 -0
- rewirebench-0.6.0/src/rewirebench/resources/proteingym/EVcouplings-LICENSE.upstream +24 -0
- rewirebench-0.6.0/src/rewirebench/resources/proteingym/LICENSE.upstream +21 -0
- rewirebench-0.6.0/src/rewirebench/resources/proteingym/esm-smoke-receipt.json +27 -0
- rewirebench-0.6.0/src/rewirebench/resources/proteingym/sources.json +97 -0
- rewirebench-0.6.0/src/rewirebench/resources/proteingym/upstream_esm_compute_fitness.py +549 -0
- rewirebench-0.6.0/src/rewirebench/resources/proteingym/upstream_performance.py +406 -0
- rewirebench-0.6.0/src/rewirebench/resources/recipes/flip2/flip2-synthetic-smoke.yaml +86 -0
- rewirebench-0.6.0/src/rewirebench/resources/recipes/mfass/mfass-v2-kmer-baseline.yaml +109 -0
- rewirebench-0.6.0/src/rewirebench/resources/recipes/recipe.schema.json +1108 -0
- rewirebench-0.6.0/src/rewirebench/resources/sequence-submission-contract.json +337 -0
- rewirebench-0.6.0/src/rewirebench/resources/sequence-submission-fixtures.json +6435 -0
- rewirebench-0.6.0/src/rewirebench/results.py +122 -0
- rewirebench-0.6.0/src/rewirebench/sdk.py +603 -0
- rewirebench-0.6.0/src/rewirebench/sequence_submission.py +83 -0
- rewirebench-0.6.0/src/rewirebench/splits.py +160 -0
- rewirebench-0.6.0/src/rewirebench/submission.py +416 -0
- rewirebench-0.6.0/src/rewirebench/submission_queue.py +258 -0
- rewirebench-0.6.0/tests/conftest.py +13 -0
- rewirebench-0.6.0/tests/fixtures/dart_motif/fimo-build-receipt.json +42 -0
- rewirebench-0.6.0/tests/fixtures/dart_motif/fimo-receipt.json +4967 -0
- rewirebench-0.6.0/tests/fixtures/dart_motif/make_fixture.py +63 -0
- rewirebench-0.6.0/tests/fixtures/dart_motif/sequences.json +14 -0
- rewirebench-0.6.0/tests/fixtures/dart_motif/synthetic.meme +45 -0
- rewirebench-0.6.0/tests/fixtures/proteingym_independent/amfr-20aa.model +0 -0
- rewirebench-0.6.0/tests/fixtures/proteingym_independent/argr-precision-loss.model +0 -0
- rewirebench-0.6.0/tests/fixtures/proteingym_independent/fixture.json +52 -0
- rewirebench-0.6.0/tests/fixtures/proteingym_independent/kcnh2-gapped.model +0 -0
- rewirebench-0.6.0/tests/fixtures/proteingym_independent/make_fixture.py +128 -0
- rewirebench-0.6.0/tests/fixtures/proteingym_independent/upstream-receipt.json +366 -0
- rewirebench-0.6.0/tests/recipe_fixtures.py +71 -0
- rewirebench-0.6.0/tests/test_backends.py +626 -0
- rewirebench-0.6.0/tests/test_baselines.py +276 -0
- rewirebench-0.6.0/tests/test_cleanup.py +132 -0
- rewirebench-0.6.0/tests/test_esm_embeddings.py +46 -0
- rewirebench-0.6.0/tests/test_evcouplings_independent.py +584 -0
- rewirebench-0.6.0/tests/test_fimo_motifs.py +361 -0
- rewirebench-0.6.0/tests/test_house_rules.py +96 -0
- rewirebench-0.6.0/tests/test_mcp_server.py +727 -0
- rewirebench-0.6.0/tests/test_models.py +323 -0
- rewirebench-0.6.0/tests/test_receipts.py +1172 -0
- rewirebench-0.6.0/tests/test_recipes.py +787 -0
- rewirebench-0.6.0/tests/test_sdk.py +212 -0
- rewirebench-0.6.0/tests/test_sdk_dart_eval.py +156 -0
- rewirebench-0.6.0/tests/test_sdk_flip2.py +153 -0
- rewirebench-0.6.0/tests/test_sdk_genomic_benchmarks.py +219 -0
- rewirebench-0.6.0/tests/test_sdk_mrnabench.py +99 -0
- rewirebench-0.6.0/tests/test_sdk_proteingym.py +284 -0
- rewirebench-0.6.0/tests/test_sdk_tdc_admet.py +183 -0
- rewirebench-0.6.0/tests/test_sequence_interfaces.py +104 -0
- rewirebench-0.6.0/tests/test_sequence_submission.py +92 -0
- rewirebench-0.6.0/tests/test_submission.py +372 -0
- rewirebench-0.6.0/tests/test_submission_queue.py +326 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
.venv/
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.pyc
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.ruff_cache/
|
|
6
|
+
|
|
7
|
+
# Downloaded and regenerated benchmark data. Never committed.
|
|
8
|
+
benchmarks/*/data/
|
|
9
|
+
|
|
10
|
+
# Local SDK validation and wheel artifacts; never private model inputs.
|
|
11
|
+
workbench/
|
|
12
|
+
dist/
|
|
13
|
+
*.egg-info/
|
|
14
|
+
.nextflow/
|
|
15
|
+
.nextflow.log*
|
|
16
|
+
work/
|
|
17
|
+
|
|
18
|
+
# Dependencies of the scheduled agents (scripts/agents).
|
|
19
|
+
node_modules/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tim Richardson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: rewirebench
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: Shared machinery for rewire.it benchmarks: grouping, splits, metrics, result schema
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Requires-Dist: numpy>=1.26
|
|
9
|
+
Requires-Dist: pydantic<3,>=2.7
|
|
10
|
+
Requires-Dist: pyyaml<7,>=6
|
|
11
|
+
Requires-Dist: scikit-learn>=1.4
|
|
12
|
+
Requires-Dist: scipy>=1.11
|
|
13
|
+
Provides-Extra: dnabert2
|
|
14
|
+
Requires-Dist: einops==0.6.1; extra == 'dnabert2'
|
|
15
|
+
Requires-Dist: numpy==1.26.4; extra == 'dnabert2'
|
|
16
|
+
Requires-Dist: safetensors==0.7.0; extra == 'dnabert2'
|
|
17
|
+
Requires-Dist: torch==2.2.2; extra == 'dnabert2'
|
|
18
|
+
Requires-Dist: transformers==4.29.2; extra == 'dnabert2'
|
|
19
|
+
Provides-Extra: esm
|
|
20
|
+
Requires-Dist: fair-esm==2.0.0; extra == 'esm'
|
|
21
|
+
Requires-Dist: numpy==1.26.4; extra == 'esm'
|
|
22
|
+
Requires-Dist: torch==2.2.2; extra == 'esm'
|
|
23
|
+
Provides-Extra: mcp
|
|
24
|
+
Requires-Dist: mcp<2,>=1.12; extra == 'mcp'
|
|
25
|
+
Provides-Extra: sequence
|
|
26
|
+
Requires-Dist: h5py<4,>=3.10; extra == 'sequence'
|
|
27
|
+
Requires-Dist: pandas<3,>=2; extra == 'sequence'
|
|
28
|
+
Requires-Dist: pyarrow<24,>=17; extra == 'sequence'
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Bundle top-level recipes/ into sdist and wheel builds without breaking sdist-to-wheel."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RecipesBuildHook(BuildHookInterface):
|
|
11
|
+
def initialize(self, version: str, build_data: dict[str, Any]) -> None:
|
|
12
|
+
if version == "editable":
|
|
13
|
+
return
|
|
14
|
+
root = Path(self.root)
|
|
15
|
+
embedded = root / "src" / "rewirebench" / "resources" / "recipes"
|
|
16
|
+
if embedded.is_dir():
|
|
17
|
+
return
|
|
18
|
+
repo_recipes = (root / ".." / ".." / "recipes").resolve()
|
|
19
|
+
if not (repo_recipes / "recipe.schema.json").is_file():
|
|
20
|
+
raise FileNotFoundError(f"Expected recipes directory at {repo_recipes}")
|
|
21
|
+
target = (
|
|
22
|
+
"src/rewirebench/resources/recipes"
|
|
23
|
+
if self.target_name == "sdist"
|
|
24
|
+
else "rewirebench/resources/recipes"
|
|
25
|
+
)
|
|
26
|
+
build_data.setdefault("force_include", {})[str(repo_recipes)] = target
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "rewirebench"
|
|
3
|
+
version = "0.6.0"
|
|
4
|
+
description = "Shared machinery for rewire.it benchmarks: grouping, splits, metrics, result schema"
|
|
5
|
+
requires-python = ">=3.11"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
dependencies = ["numpy>=1.26", "scikit-learn>=1.4", "scipy>=1.11", "pydantic>=2.7,<3", "pyyaml>=6,<7"]
|
|
9
|
+
|
|
10
|
+
[build-system]
|
|
11
|
+
requires = ["hatchling"]
|
|
12
|
+
build-backend = "hatchling.build"
|
|
13
|
+
|
|
14
|
+
[tool.hatch.build.targets.wheel]
|
|
15
|
+
packages = ["src/rewirebench"]
|
|
16
|
+
|
|
17
|
+
[tool.hatch.build.hooks.custom]
|
|
18
|
+
path = "hatch_build.py"
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
rewirebench = "rewirebench.cli:main"
|
|
22
|
+
|
|
23
|
+
[project.optional-dependencies]
|
|
24
|
+
sequence = ["pandas>=2,<3", "pyarrow>=17,<24", "h5py>=3.10,<4"]
|
|
25
|
+
dnabert2 = ["torch==2.2.2", "transformers==4.29.2", "einops==0.6.1", "safetensors==0.7.0", "numpy==1.26.4"]
|
|
26
|
+
esm = ["fair-esm==2.0.0", "torch==2.2.2", "numpy==1.26.4"]
|
|
27
|
+
mcp = ["mcp>=1.12,<2"]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Shared machinery for rewire.it benchmarks.
|
|
2
|
+
|
|
3
|
+
The house rules in the repository README are enforced here rather than described:
|
|
4
|
+
`splits` refuses a grouping that does not match the stated claim, `metrics` refuses
|
|
5
|
+
an interval that too few independent groups can support, and `results` refuses a
|
|
6
|
+
result that omits coverage, timing or the group count.
|
|
7
|
+
"""
|
|
8
|
+
from rewirebench.splits import connected_components, naive_key_count, assign_groups
|
|
9
|
+
from rewirebench.metrics import precision_at_n, recall_at_n, point_metrics, paired_group_bootstrap
|
|
10
|
+
from rewirebench.results import BenchmarkResult, write_result
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"connected_components", "naive_key_count", "assign_groups",
|
|
14
|
+
"precision_at_n", "recall_at_n", "point_metrics", "paired_group_bootstrap",
|
|
15
|
+
"BenchmarkResult", "write_result",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
# Local execution and explicit reviewed contribution workflow.
|
|
19
|
+
from rewirebench.sdk import prepare, run, evaluate, export, describe, read_embeddings
|
|
20
|
+
from rewirebench.submission import submit
|
|
21
|
+
__all__ += ["prepare", "run", "evaluate", "export", "submit", "describe", "read_embeddings"]
|
|
22
|
+
|
|
23
|
+
from rewirebench.baselines import describe_baselines, run_baselines
|
|
24
|
+
from rewirebench.submission_queue import enqueue_submission, drain_submissions, submission_status
|
|
25
|
+
__all__ += ["describe_baselines", "run_baselines", "enqueue_submission", "drain_submissions",
|
|
26
|
+
"submission_status"]
|
|
File without changes
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Small local reference methods; no weights, downloads or evaluation labels.
|
|
2
|
+
|
|
3
|
+
These are Rewire controls, not claims to reproduce a paper's baseline. The SDK
|
|
4
|
+
owns train/test access and supplies only permitted training labels to ``fit``.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TrainingPrior:
|
|
12
|
+
"""Binary training prevalence or multiclass training majority (ties: lowest class)."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, *, multiclass=False):
|
|
15
|
+
self.multiclass = multiclass
|
|
16
|
+
|
|
17
|
+
def fit(self, inputs, targets):
|
|
18
|
+
if not targets or len(inputs) != len(targets):
|
|
19
|
+
raise ValueError("Nonempty aligned training data required")
|
|
20
|
+
labels = np.asarray(targets)
|
|
21
|
+
if not np.isfinite(labels).all() or not np.equal(labels, labels.astype(int)).all():
|
|
22
|
+
raise ValueError("Classification labels must be finite integers")
|
|
23
|
+
if self.multiclass:
|
|
24
|
+
classes, counts = np.unique(labels, return_counts=True)
|
|
25
|
+
self.value = float(classes[np.argmax(counts)])
|
|
26
|
+
else:
|
|
27
|
+
if not set(labels).issubset({0, 1}):
|
|
28
|
+
raise ValueError("Binary labels required")
|
|
29
|
+
self.value = float(labels.mean())
|
|
30
|
+
|
|
31
|
+
def predict(self, inputs):
|
|
32
|
+
if not hasattr(self, "value"):
|
|
33
|
+
raise ValueError("TrainingPrior requires fitting")
|
|
34
|
+
return {row["id"]: self.value for row in inputs}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class StringNgramReference:
|
|
38
|
+
"""Train-only character 1–3-gram counts with a fixed regularised linear head.
|
|
39
|
+
|
|
40
|
+
DNA and SMILES text are accepted through distinct input fields. SMILES counts
|
|
41
|
+
are a representation-dependent string reference, not chemical descriptors or
|
|
42
|
+
an invariant molecular fingerprint. No canonicalisation or chemistry toolkit
|
|
43
|
+
is silently applied. Inputs are uppercased only for DNA, never for SMILES.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, *, field="sequence", classification=True, multiclass=False):
|
|
47
|
+
if field not in {"sequence", "smiles"}:
|
|
48
|
+
raise ValueError("Unsupported reference input field")
|
|
49
|
+
self.field = field
|
|
50
|
+
self.classification = classification
|
|
51
|
+
self.multiclass = multiclass
|
|
52
|
+
|
|
53
|
+
def _strings(self, inputs):
|
|
54
|
+
values = [row[self.field] for row in inputs]
|
|
55
|
+
if any(not isinstance(v, str) or not v for v in values):
|
|
56
|
+
raise ValueError("Nonempty string inputs required")
|
|
57
|
+
return [v.upper() for v in values] if self.field == "sequence" else values
|
|
58
|
+
|
|
59
|
+
def fit(self, inputs, targets):
|
|
60
|
+
from sklearn.feature_extraction.text import CountVectorizer
|
|
61
|
+
from sklearn.linear_model import LogisticRegression, Ridge
|
|
62
|
+
from sklearn.preprocessing import Normalizer
|
|
63
|
+
|
|
64
|
+
if not targets or len(inputs) != len(targets):
|
|
65
|
+
raise ValueError("Nonempty aligned training data required")
|
|
66
|
+
self.vectorizer = CountVectorizer(analyzer="char", ngram_range=(1, 3), lowercase=False)
|
|
67
|
+
self.normalizer = Normalizer(norm="l2")
|
|
68
|
+
features = self.normalizer.fit_transform(self.vectorizer.fit_transform(self._strings(inputs)))
|
|
69
|
+
if self.classification:
|
|
70
|
+
labels = np.asarray(targets)
|
|
71
|
+
if len(set(targets)) < 2 or not np.equal(labels, labels.astype(int)).all():
|
|
72
|
+
raise ValueError("Classification fitting requires at least two integer classes")
|
|
73
|
+
self.head = LogisticRegression(C=1.0, solver="lbfgs", max_iter=2000, random_state=0)
|
|
74
|
+
else:
|
|
75
|
+
self.head = Ridge(alpha=1.0, solver="lsqr", tol=1e-8, max_iter=10000)
|
|
76
|
+
self.head.fit(features, targets)
|
|
77
|
+
|
|
78
|
+
def predict(self, inputs):
|
|
79
|
+
if not hasattr(self, "head"):
|
|
80
|
+
raise ValueError("StringNgramReference requires fitting")
|
|
81
|
+
features = self.normalizer.transform(self.vectorizer.transform(self._strings(inputs)))
|
|
82
|
+
if self.classification and not self.multiclass:
|
|
83
|
+
if list(self.head.classes_) != [0, 1]:
|
|
84
|
+
raise ValueError("Binary classification requires labels 0 and 1")
|
|
85
|
+
values = self.head.predict_proba(features)[:, 1]
|
|
86
|
+
else:
|
|
87
|
+
values = self.head.predict(features)
|
|
88
|
+
return {r["id"]: float(v) for r, v in zip(inputs, values, strict=True)}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class PairedComposition:
|
|
92
|
+
"""Untrained composition with the existing MFASS fixed train-only probe.
|
|
93
|
+
|
|
94
|
+
Constant vectors test the probe without sequence information; because that
|
|
95
|
+
probe uses balanced class weights, this is NOT training prevalence.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, *, constant=False):
|
|
99
|
+
self.constant = constant
|
|
100
|
+
|
|
101
|
+
def embed(self, inputs):
|
|
102
|
+
from rewirebench.adapters.sequence import SequenceComposition
|
|
103
|
+
|
|
104
|
+
if self.constant:
|
|
105
|
+
return {row["id"]: {"reference": [0.0], "mutant": [0.0]} for row in inputs}
|
|
106
|
+
encoder = SequenceComposition("ACGT")
|
|
107
|
+
reference = encoder.embed([
|
|
108
|
+
{"id": r["id"], "sequence": r["reference_sequence"]} for r in inputs
|
|
109
|
+
])
|
|
110
|
+
mutant = encoder.embed([
|
|
111
|
+
{"id": r["id"], "sequence": r["mutant_sequence"]} for r in inputs
|
|
112
|
+
])
|
|
113
|
+
return {r["id"]: {"reference": reference[r["id"]], "mutant": mutant[r["id"]]}
|
|
114
|
+
for r in inputs}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Offline ESM-2 8M masked-marginal example, not a published ProteinGym row.
|
|
2
|
+
|
|
3
|
+
At each mutated position mask the wild-type residue, compute log P(mutant)
|
|
4
|
+
minus log P(wild type), and sum across substitutions. No labels are accepted.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import importlib.metadata
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from rewirebench.protocols.proteingym import AMINO_ACIDS, _substitutions
|
|
14
|
+
|
|
15
|
+
MODEL_NAME = "esm2_t6_8M_UR50D"
|
|
16
|
+
CHECKPOINT_SHA256 = "46f002a9870c9bdecd0ea887acb1f9a38a6b561e8f8bf8a6990b679b9d31b928"
|
|
17
|
+
CHECKPOINT_URL = "https://dl.fbaipublicfiles.com/fair-esm/models/esm2_t6_8M_UR50D.pt"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ESM2Adapter:
|
|
21
|
+
"""Local pinned checkpoint only. Construct once, then call predict in batches.
|
|
22
|
+
|
|
23
|
+
Sequences exceeding 1022 residues receive an explicit unscored reason.
|
|
24
|
+
No silent cropping or equivalence to upstream windowing protocols is implied.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
capability = "scalar"
|
|
28
|
+
|
|
29
|
+
def __init__(self, checkpoint: str | Path, *, device: str = "cpu"):
|
|
30
|
+
path = Path(checkpoint)
|
|
31
|
+
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
32
|
+
if digest != CHECKPOINT_SHA256:
|
|
33
|
+
raise ValueError("Checkpoint does not match the pinned ESM-2 8M weights")
|
|
34
|
+
try:
|
|
35
|
+
import esm
|
|
36
|
+
import torch
|
|
37
|
+
except ImportError as exc:
|
|
38
|
+
raise ImportError("Install rewirebench[esm] before using the ESM example") from exc
|
|
39
|
+
if importlib.metadata.version("fair-esm") != "2.0.0":
|
|
40
|
+
raise ValueError("This adapter is reviewed for fair-esm==2.0.0")
|
|
41
|
+
# The verified official checkpoint includes Python configuration objects.
|
|
42
|
+
# No hub call: core loading avoids remote contact-regression downloads.
|
|
43
|
+
model_data = torch.load(path, map_location="cpu", weights_only=False)
|
|
44
|
+
self.model, self.alphabet = esm.pretrained.load_model_and_alphabet_core(
|
|
45
|
+
MODEL_NAME, model_data, regression_data=None,
|
|
46
|
+
)
|
|
47
|
+
self.model.eval().to(device)
|
|
48
|
+
self.device = device
|
|
49
|
+
self.torch = torch
|
|
50
|
+
self.converter = self.alphabet.get_batch_converter()
|
|
51
|
+
self._cache: dict[tuple[str, int], object] = {}
|
|
52
|
+
self.provenance = {
|
|
53
|
+
"model": MODEL_NAME, "checkpoint_sha256": digest,
|
|
54
|
+
"checkpoint_url": CHECKPOINT_URL, "fair_esm_version": "2.0.0",
|
|
55
|
+
"implementation_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
|
56
|
+
"strategy": "masked_marginals_wild_type_context_sum_log_odds",
|
|
57
|
+
"maximum_sequence_length": 1022, "device": device,
|
|
58
|
+
"training_overlap": "unreported; UniRef50 pretraining may overlap benchmark proteins",
|
|
59
|
+
"published_result_reproduction": False,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
def predict(self, inputs: list[dict]) -> dict[str, Any]:
|
|
63
|
+
results = {}
|
|
64
|
+
for record in inputs:
|
|
65
|
+
if not {"id", "wild_type_sequence", "mutant"}.issubset(record):
|
|
66
|
+
raise ValueError("ESM inputs require id, wild_type_sequence and mutant")
|
|
67
|
+
if set(record) - {"id", "assay_id", "wild_type_sequence", "mutant", "mutated_sequence"}:
|
|
68
|
+
raise ValueError("Unexpected input fields; labels must not reach model adapters")
|
|
69
|
+
identifier, sequence = record["id"], record["wild_type_sequence"]
|
|
70
|
+
if identifier in results:
|
|
71
|
+
raise ValueError("Duplicate input ID")
|
|
72
|
+
if (not isinstance(sequence, str) or not sequence
|
|
73
|
+
or set(sequence) - (AMINO_ACIDS | set("XBZUO"))):
|
|
74
|
+
raise ValueError("ESM inputs require a nonempty valid amino-acid sequence")
|
|
75
|
+
mutations = _substitutions(record["mutant"], sequence)
|
|
76
|
+
if len(sequence) > 1022:
|
|
77
|
+
results[identifier] = {
|
|
78
|
+
"score": None,
|
|
79
|
+
"reason": "ESM example supports at most 1022 residues; windowed inference not implemented",
|
|
80
|
+
}
|
|
81
|
+
continue
|
|
82
|
+
score = 0.0
|
|
83
|
+
for index, wild_type, mutant in mutations:
|
|
84
|
+
cache_key = (sequence, index)
|
|
85
|
+
if cache_key not in self._cache:
|
|
86
|
+
_, _, tokens = self.converter([("protein", sequence)])
|
|
87
|
+
tokens[0, index + 1] = self.alphabet.mask_idx
|
|
88
|
+
with self.torch.inference_mode():
|
|
89
|
+
logits = self.model(tokens.to(self.device))["logits"]
|
|
90
|
+
self._cache[cache_key] = self.torch.log_softmax(
|
|
91
|
+
logits[0, index + 1], dim=-1,
|
|
92
|
+
).cpu()
|
|
93
|
+
probabilities = self._cache[cache_key]
|
|
94
|
+
score += float(probabilities[self.alphabet.get_idx(mutant)]
|
|
95
|
+
- probabilities[self.alphabet.get_idx(wild_type)])
|
|
96
|
+
results[identifier] = score
|
|
97
|
+
return results
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Frozen ESM-2 8M/35M mean-pooled representations for protocol-owned probes.
|
|
2
|
+
|
|
3
|
+
Pooling follows the official ESM representation example: final-layer residue
|
|
4
|
+
representations, excluding BOS/EOS and padding. No labels enter the encoder.
|
|
5
|
+
This is a new evaluated pipeline, not reproduction of a published model score.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import importlib.metadata
|
|
11
|
+
import json
|
|
12
|
+
from importlib.resources import files
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from types import SimpleNamespace
|
|
15
|
+
|
|
16
|
+
from rewirebench.adapters.esm import ESM2Adapter
|
|
17
|
+
from rewirebench.protocols.proteingym import AMINO_ACIDS
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ESM2Embeddings:
|
|
21
|
+
def __init__(self, checkpoint, *, device="cpu", model_name="esm2_t6_8M_UR50D"):
|
|
22
|
+
manifest = json.loads(files("rewirebench").joinpath(
|
|
23
|
+
"resources/models/esm2-embeddings.json").read_text())
|
|
24
|
+
if model_name not in manifest["models"]:
|
|
25
|
+
raise ValueError("Unsupported ESM-2 embedding checkpoint identity")
|
|
26
|
+
specification = manifest["models"][model_name]
|
|
27
|
+
path = Path(checkpoint)
|
|
28
|
+
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
29
|
+
if digest != specification["checkpoint_sha256"]:
|
|
30
|
+
raise ValueError("Checkpoint does not match the pinned ESM-2 embedding weights")
|
|
31
|
+
if model_name == "esm2_t6_8M_UR50D":
|
|
32
|
+
self.encoder = ESM2Adapter(path, device=device)
|
|
33
|
+
else:
|
|
34
|
+
import esm
|
|
35
|
+
import torch
|
|
36
|
+
|
|
37
|
+
if importlib.metadata.version("fair-esm") != "2.0.0":
|
|
38
|
+
raise ValueError("This adapter requires fair-esm==2.0.0")
|
|
39
|
+
# Verify bytes before loading the official pickle-based checkpoint.
|
|
40
|
+
data = torch.load(path, map_location="cpu", weights_only=False)
|
|
41
|
+
model, alphabet = esm.pretrained.load_model_and_alphabet_core(
|
|
42
|
+
model_name, data, regression_data=None)
|
|
43
|
+
model.eval().to(device)
|
|
44
|
+
self.encoder = SimpleNamespace(model=model, alphabet=alphabet,
|
|
45
|
+
converter=alphabet.get_batch_converter(), torch=torch, device=device)
|
|
46
|
+
self.layer = specification["layer"]
|
|
47
|
+
self.provenance = {
|
|
48
|
+
"model": model_name, "checkpoint_sha256": digest,
|
|
49
|
+
"checkpoint_url": specification["checkpoint_url"],
|
|
50
|
+
"fair_esm_version": "2.0.0", "device": device,
|
|
51
|
+
"maximum_sequence_length": 1022,
|
|
52
|
+
"training_overlap": "unreported; UniRef50 pretraining may overlap benchmark proteins",
|
|
53
|
+
"implementation_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
|
54
|
+
"strategy": "frozen_final_layer_residue_mean_excluding_special_tokens",
|
|
55
|
+
"representation_layer": self.layer,
|
|
56
|
+
"reference": "https://github.com/facebookresearch/esm/blob/" + manifest["upstream_revision"] + "/README.md#usage",
|
|
57
|
+
"published_result_reproduction": False,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
def embed(self, inputs):
|
|
61
|
+
ids = [row.get("id") for row in inputs]
|
|
62
|
+
if len(ids) != len(set(ids)) or any(not isinstance(x, str) or not x for x in ids):
|
|
63
|
+
raise ValueError("Embedding inputs require unique nonempty IDs")
|
|
64
|
+
for row in inputs:
|
|
65
|
+
if set(row) != {"id", "sequence"}:
|
|
66
|
+
raise ValueError("ESM embedding inputs allow only id and sequence, never labels")
|
|
67
|
+
sequence = row["sequence"]
|
|
68
|
+
if (not isinstance(sequence, str) or not 1 <= len(sequence) <= 1022
|
|
69
|
+
or set(sequence) - (AMINO_ACIDS | set("XBZUO"))):
|
|
70
|
+
raise ValueError("ESM embeddings require 1..1022 valid amino-acid residues; no cropping")
|
|
71
|
+
if not inputs:
|
|
72
|
+
return {}
|
|
73
|
+
encoder = self.encoder
|
|
74
|
+
_, _, tokens = encoder.converter([(row["id"], row["sequence"]) for row in inputs])
|
|
75
|
+
with encoder.torch.inference_mode():
|
|
76
|
+
vectors = encoder.model(tokens.to(encoder.device), repr_layers=[self.layer],
|
|
77
|
+
return_contacts=False)["representations"][self.layer]
|
|
78
|
+
return {row["id"]: vectors[i, 1:len(row["sequence"]) + 1].mean(0).cpu().tolist()
|
|
79
|
+
for i, row in enumerate(inputs)}
|