-
Notifications
You must be signed in to change notification settings - Fork 164
evo2 SAE eval (1/2): label producers — imported by #1636 #1630
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
polinabinder1
wants to merge
15
commits into
pbinder/sae-interp-primitives
Choose a base branch
from
pbinder/evo2-eval-harness
base: pbinder/sae-interp-primitives
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
c27f744
evo2 SAE eval: feature-probing harness + label producers
polinabinder1 b0c2330
evo2 probe: generic annotated-dataset domain-eval (F1 + AUROC vs any …
polinabinder1 e520186
evo2 probe: trim demo command + superseded proxy labelers
polinabinder1 e7d5a05
evo2 eval: use Biopython for the genetic code in labelers (drop hand-…
polinabinder1 1d2e56f
evo2 eval: drop bioframe dep — investigation showed no real reduction
polinabinder1 efbbf11
evo2 probe: add end-to-end usage examples + factor shared subcommand …
polinabinder1 316f8d3
evo2 probe: factor the shared window-encode loop (euk-f1 + domain-eval)
polinabinder1 721760e
evo2 eval: add single-base labelers (base_A/C/G/T)
polinabinder1 7910657
Merge remote-tracking branch 'origin/pbinder/sae-interp-primitives' i…
polinabinder1 dfcd851
evo2 probe: add 'annotate' — persist per-feature best concept to the …
polinabinder1 d3636f4
evo2 eval: reconcile engine import to evo2_sae (was evo2_sae_infer)
polinabinder1 fe6bb14
evo2 eval: split harness out -> label producers only
polinabinder1 e57d174
evo2 eval: condense annot_tracks parsers
polinabinder1 0c76d38
evo2 eval: table-drive consensus motifs + add labeler CPU tests
polinabinder1 f794c31
fix(eval-labels): CodeRabbit review — splice_donor consensus + multi-…
polinabinder1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
146 changes: 146 additions & 0 deletions
146
bionemo-recipes/interpretability/sparse_autoencoders/recipes/evo2/scripts/annot_tracks.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: LicenseRef-Apache2 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| r"""Generic interval-track loader for the "user-supplied annotated dataset" eval. | ||
|
|
||
| The user hands in an annotated dataset: a FASTA of sequences + one or more annotation | ||
| tracks (BED or GFF) naming intervals — RefSeq genes/exons, Rfam ncRNA, JASPAR TFBS, | ||
| ENCODE cCREs, etc. Each interval is one annotation **instance**. This module tiles the | ||
| sequences into windows and produces, per concept, a per-token boolean mask + per-token | ||
| **global** instance IDs (stable across the windows an interval spans) — exactly the | ||
| inputs `sae.eval.probing.domain_f1` (recall-per-instance) and `auroc_all` (per-feature) | ||
| consume. No model here; the SAE-encode step lives in the probe CLI (`probe.py domain-eval`). | ||
|
|
||
| This is the generic sibling of `euk_windows.py` (which decomposes RefSeq gene models into | ||
| exon/intron/cds). Both feed the same shared scorers. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import gzip | ||
| from collections import defaultdict | ||
|
|
||
|
|
||
| def _open(path): | ||
| """Open a path for text reading, transparently handling ``.gz``.""" | ||
| return (gzip.open if str(path).endswith(".gz") else open)(path, "rt") | ||
|
|
||
|
|
||
| def read_fasta_dict(path: str) -> dict[str, str]: | ||
| """Read a (multi-record) FASTA into ``{seq_id: sequence}`` (``.gz`` transparent). | ||
|
|
||
| ``seq_id`` is the first whitespace token of the header — matches the chrom/seqid of BED/GFF. | ||
| """ | ||
| seqs: dict[str, str] = {} | ||
| name, parts = None, [] | ||
| with _open(path) as fh: | ||
| for line in fh: | ||
| line = line.rstrip() | ||
| if line.startswith(">"): | ||
| if name is not None: | ||
| seqs[name] = "".join(parts) | ||
| tok = line[1:].split() | ||
| name, parts = (tok[0] if tok else f"seq_{len(seqs)}"), [] | ||
| elif line: | ||
| parts.append(line) | ||
| if name is not None: | ||
| seqs[name] = "".join(parts) | ||
| return seqs | ||
|
|
||
|
|
||
| def _intervals(path, fmt, feature_type=None): | ||
| """Yield (seqid, start0, end0) from BED (0-based) or GFF/GTF (1-based -> 0-based half-open). | ||
|
|
||
| GFF rows are optionally filtered to a single column-3 ``feature_type`` (e.g. ``exon``). | ||
| """ | ||
| chrom_i, start_i, end_i, off = (0, 1, 2, 0) if fmt == "bed" else (0, 3, 4, 1) | ||
| with _open(path) as fh: | ||
| for line in fh: | ||
| if not line.strip() or line[0] == "#" or line.startswith(("track", "browser")): | ||
| continue | ||
| f = line.split("\t") | ||
| if len(f) <= end_i or (feature_type and fmt != "bed" and f[2] != feature_type): | ||
| continue | ||
| yield f[chrom_i], int(f[start_i]) - off, int(f[end_i]) | ||
|
|
||
|
|
||
| def load_track(path, feature_type=None, fmt=None): | ||
| """Load one annotation track into ``{seqid: [(start0, end0), ...]}`` (0-based half-open, sorted). | ||
|
|
||
| ``fmt`` (``bed``/``gff``) is inferred from the extension; ``feature_type`` filters GFF column 3. | ||
| Every interval is one annotation instance. | ||
| """ | ||
| fmt = fmt or ("gff" if str(path).replace(".gz", "").endswith((".gff", ".gff3", ".gtf")) else "bed") | ||
| by_seq = defaultdict(list) | ||
| for chrom, s, e in _intervals(path, fmt, feature_type): | ||
| if e > s: | ||
| by_seq[chrom].append((s, e)) | ||
| return {k: sorted(v) for k, v in by_seq.items()} | ||
|
|
||
|
|
||
| def label_windows(seqs, tracks, seq_len=1024, stride=None, max_tokens=None, min_n_frac=0.5): | ||
| """Tile sequences into windows, labeling each position per concept (mask + global instance id). | ||
|
|
||
| Args: | ||
| seqs: ``{seqid: dna_str}``. | ||
| tracks: ``{concept: {seqid: [(start0, end0), ...]}}`` (e.g. from `load_track`). | ||
| seq_len: window length in bp. | ||
| stride: step between windows (defaults to non-overlapping = seq_len). | ||
| max_tokens: stop once this many positions are emitted (None = all). | ||
| min_n_frac: skip windows whose ``N`` fraction exceeds this. | ||
|
|
||
| Returns: | ||
| (windows, stats). Each window is ``{"dna": str, "labels": {concept: bool[L]}, | ||
| "instances": {concept: int32[L]}}``. Each interval gets one global id, stable across | ||
| the windows it spans, so `domain_f1`'s recall-per-instance counts a split interval once. | ||
| """ | ||
| import numpy as np | ||
|
|
||
| stride = stride or seq_len | ||
| concepts = list(tracks.keys()) | ||
| # assign a global instance id to every interval, per concept | ||
| concept_iv: dict[str, dict[str, list[tuple[int, int, int]]]] = {} | ||
| n_inst: dict[str, int] = {} | ||
| for concept in concepts: | ||
| gid = 0 | ||
| cc: dict[str, list[tuple[int, int, int]]] = {} | ||
| for seqid, ivs in tracks[concept].items(): | ||
| cc[seqid] = [(s, e, (gid := gid + 1) - 1) for (s, e) in ivs] | ||
| concept_iv[concept] = cc | ||
| n_inst[concept] = gid | ||
|
|
||
| windows, tot = [], 0 | ||
| for seqid, dna in seqs.items(): | ||
| dna = dna.upper() | ||
| N = len(dna) | ||
| for w0 in range(0, max(1, N - seq_len + 1), stride): | ||
| w1 = min(N, w0 + seq_len) | ||
| sub = dna[w0:w1] | ||
| L = w1 - w0 | ||
| if L < 60 or sub.count("N") > min_n_frac * L: | ||
| continue | ||
| labels = {c: np.zeros(L, bool) for c in concepts} | ||
| inst = {c: np.full(L, -1, np.int32) for c in concepts} | ||
| for c in concepts: | ||
| for s, e, gid in concept_iv[c].get(seqid, []): | ||
| if e <= w0 or s >= w1: | ||
| continue | ||
| labels[c][max(s, w0) - w0 : min(e, w1) - w0] = True | ||
| inst[c][max(s, w0) - w0 : min(e, w1) - w0] = gid | ||
| windows.append({"dna": sub, "labels": labels, "instances": inst}) | ||
| tot += L | ||
| if max_tokens and tot >= max_tokens: | ||
| return windows, {"tokens": tot, "n_inst": n_inst, "concepts": concepts} | ||
| return windows, {"tokens": tot, "n_inst": n_inst, "concepts": concepts} | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.