rewirebench 0.6.0__py3-none-any.whl

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 (76) hide show
  1. rewirebench/__init__.py +26 -0
  2. rewirebench/adapters/__init__.py +0 -0
  3. rewirebench/adapters/baselines.py +114 -0
  4. rewirebench/adapters/esm.py +97 -0
  5. rewirebench/adapters/esm_embeddings.py +79 -0
  6. rewirebench/adapters/evcouplings_independent.py +575 -0
  7. rewirebench/adapters/fimo_motifs.py +286 -0
  8. rewirebench/adapters/mfass.py +201 -0
  9. rewirebench/adapters/sequence.py +60 -0
  10. rewirebench/backends/__init__.py +57 -0
  11. rewirebench/backends/base.py +188 -0
  12. rewirebench/backends/local.py +59 -0
  13. rewirebench/backends/runpod.py +256 -0
  14. rewirebench/backends/spark.py +361 -0
  15. rewirebench/baselines.py +304 -0
  16. rewirebench/cleanup.py +77 -0
  17. rewirebench/cli.py +428 -0
  18. rewirebench/mcp_server.py +736 -0
  19. rewirebench/metrics.py +141 -0
  20. rewirebench/models.py +294 -0
  21. rewirebench/protocols/__init__.py +0 -0
  22. rewirebench/protocols/dart_eval.py +292 -0
  23. rewirebench/protocols/flip2.py +264 -0
  24. rewirebench/protocols/genomic_benchmarks.py +241 -0
  25. rewirebench/protocols/mfass.py +230 -0
  26. rewirebench/protocols/mrnabench.py +239 -0
  27. rewirebench/protocols/proteingym.py +250 -0
  28. rewirebench/protocols/tdc_admet.py +237 -0
  29. rewirebench/provenance.py +49 -0
  30. rewirebench/receipts.py +1385 -0
  31. rewirebench/recipes.py +932 -0
  32. rewirebench/resources/dart_eval/demo.json +66 -0
  33. rewirebench/resources/dart_eval/sources.json +105 -0
  34. rewirebench/resources/dart_eval/statistical-reference.json +126 -0
  35. rewirebench/resources/dart_eval/uniform-background.txt +6 -0
  36. rewirebench/resources/dart_eval/upstream-evaluator-reference.json +50 -0
  37. rewirebench/resources/dart_eval/validation-receipt.json +40 -0
  38. rewirebench/resources/flip2/amylase-README.upstream.md +8 -0
  39. rewirebench/resources/flip2/example_adapter.py +32 -0
  40. rewirebench/resources/flip2/hydro-README.upstream.md +9 -0
  41. rewirebench/resources/flip2/ired-README.upstream.md +10 -0
  42. rewirebench/resources/flip2/nucb-README.upstream.md +9 -0
  43. rewirebench/resources/flip2/pdz3-README.upstream.md +8 -0
  44. rewirebench/resources/flip2/rhomax-README.upstream.md +9 -0
  45. rewirebench/resources/flip2/sources.json +406 -0
  46. rewirebench/resources/flip2/trpb-README.upstream.md +10 -0
  47. rewirebench/resources/flip2/validation-2026-09-20.json +335 -0
  48. rewirebench/resources/mfass/README.md +27 -0
  49. rewirebench/resources/mfass/split-v2.tsv +27734 -0
  50. rewirebench/resources/mfass/validation-2026-09-17.json +54 -0
  51. rewirebench/resources/models/esm2-embeddings.json +36 -0
  52. rewirebench/resources/mrnabench/sources.json +66 -0
  53. rewirebench/resources/mrnabench/validation-receipt.json +122 -0
  54. rewirebench/resources/proteingym/DMS_substitutions.csv +218 -0
  55. rewirebench/resources/proteingym/EVcouplings-LICENSE.upstream +24 -0
  56. rewirebench/resources/proteingym/LICENSE.upstream +21 -0
  57. rewirebench/resources/proteingym/esm-smoke-receipt.json +27 -0
  58. rewirebench/resources/proteingym/sources.json +97 -0
  59. rewirebench/resources/proteingym/upstream_esm_compute_fitness.py +549 -0
  60. rewirebench/resources/proteingym/upstream_performance.py +406 -0
  61. rewirebench/resources/recipes/flip2/flip2-synthetic-smoke.yaml +86 -0
  62. rewirebench/resources/recipes/mfass/mfass-v2-kmer-baseline.yaml +109 -0
  63. rewirebench/resources/recipes/recipe.schema.json +1108 -0
  64. rewirebench/resources/sequence-submission-contract.json +337 -0
  65. rewirebench/resources/sequence-submission-fixtures.json +6435 -0
  66. rewirebench/results.py +122 -0
  67. rewirebench/sdk.py +603 -0
  68. rewirebench/sequence_submission.py +83 -0
  69. rewirebench/splits.py +160 -0
  70. rewirebench/submission.py +416 -0
  71. rewirebench/submission_queue.py +258 -0
  72. rewirebench-0.6.0.dist-info/METADATA +28 -0
  73. rewirebench-0.6.0.dist-info/RECORD +76 -0
  74. rewirebench-0.6.0.dist-info/WHEEL +4 -0
  75. rewirebench-0.6.0.dist-info/entry_points.txt +2 -0
  76. rewirebench-0.6.0.dist-info/licenses/LICENSE +21 -0
@@ -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)}