xchroma 0.1.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.
- xatac/__init__.py +3 -0
- xatac/config.json +29 -0
- xatac/data.py +119 -0
- xatac/io.py +59 -0
- xatac/loss.py +106 -0
- xatac/model.py +123 -0
- xatac/predict.py +111 -0
- xatac/sites.py +135 -0
- xatac/train.py +256 -0
- xatac/windows.py +97 -0
- xbench/__init__.py +1 -0
- xbench/metrics/__init__.py +27 -0
- xbench/metrics/_pollard.py +46 -0
- xbench/metrics/contact_directionality.py +23 -0
- xbench/metrics/distance_enrichment.py +23 -0
- xbench/metrics/eigenvector.py +35 -0
- xbench/metrics/fine_structure.py +21 -0
- xbench/metrics/insulation.py +28 -0
- xbench/metrics/loop_strength.py +67 -0
- xbench/metrics/mse.py +10 -0
- xbench/metrics/pearson.py +16 -0
- xbench/metrics/scc.py +10 -0
- xbench/metrics/spearman.py +10 -0
- xbench/metrics/ssim.py +15 -0
- xbench/metrics/vendor/pollard/NOTICE.md +10 -0
- xbench/metrics/vendor/pollard/hicrep.py +84 -0
- xbench/metrics/vendor/pollard/scoring.py +732 -0
- xchroma/__init__.py +14 -0
- xchroma/__main__.py +4 -0
- xchroma/cli.py +37 -0
- xchroma-0.1.0.dist-info/METADATA +100 -0
- xchroma-0.1.0.dist-info/RECORD +49 -0
- xchroma-0.1.0.dist-info/WHEEL +5 -0
- xchroma-0.1.0.dist-info/entry_points.txt +2 -0
- xchroma-0.1.0.dist-info/licenses/LICENSE +21 -0
- xchroma-0.1.0.dist-info/licenses/xbench/metrics/vendor/pollard/NOTICE.md +10 -0
- xchroma-0.1.0.dist-info/licenses/xtrain/licenses/Selene.txt +32 -0
- xchroma-0.1.0.dist-info/top_level.txt +4 -0
- xtrain/checkpoints/current_model.json +115 -0
- xtrain/checkpoints/verify.py +75 -0
- xtrain/data.py +207 -0
- xtrain/inputs.py +254 -0
- xtrain/licenses/Selene.txt +32 -0
- xtrain/model.py +280 -0
- xtrain/predict.py +153 -0
- xtrain/preprocess/atac/bigwig_to_memmap.py +74 -0
- xtrain/preprocess/atac/scatac_pipeline.sh +75 -0
- xtrain/train.py +243 -0
- xtrain/x_utils.py +298 -0
xatac/__init__.py
ADDED
xatac/config.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"model": {
|
|
3
|
+
"seq_len": 1048576,
|
|
4
|
+
"width": 512,
|
|
5
|
+
"n_dilated": 13,
|
|
6
|
+
"dilation_cycles": 1,
|
|
7
|
+
"pool_factors": [5, 5, 5, 1, 1, 1],
|
|
8
|
+
"up_factors": [5, 5, 5],
|
|
9
|
+
"up_channels": [128, 64, 32],
|
|
10
|
+
"grad_checkpoint": true
|
|
11
|
+
},
|
|
12
|
+
"batch_size": 8,
|
|
13
|
+
"max_steps": 50000,
|
|
14
|
+
"lr": 0.0002,
|
|
15
|
+
"min_lr": 0.00002,
|
|
16
|
+
"warmup": 250,
|
|
17
|
+
"weight_decay": 0.01,
|
|
18
|
+
"grad_clip": 1.0,
|
|
19
|
+
"shift_bp": 1000,
|
|
20
|
+
"reverse_complement_probability": 0.5,
|
|
21
|
+
"seed": 42,
|
|
22
|
+
"val_seed": 42,
|
|
23
|
+
"val_windows": 20,
|
|
24
|
+
"validate_every": 500,
|
|
25
|
+
"save_every": 100,
|
|
26
|
+
"loader_workers": 4,
|
|
27
|
+
"threads": 4,
|
|
28
|
+
"precision": "bf16"
|
|
29
|
+
}
|
xatac/data.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Compact site-label records and deterministic paired shift/RC augmentation."""
|
|
2
|
+
from functools import lru_cache
|
|
3
|
+
import hashlib
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path, PurePosixPath
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from .io import DNA_LUT, decode_bf16, fingerprint, sha256
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def read_dataset(root):
|
|
15
|
+
root = Path(root).resolve()
|
|
16
|
+
meta_path = root / "dataset.json"
|
|
17
|
+
if not meta_path.exists():
|
|
18
|
+
meta_path = root / "READY.json" # Original experimental-target record caches.
|
|
19
|
+
metadata = json.loads(meta_path.read_text())
|
|
20
|
+
if metadata.get("status") != "PASS" or metadata.get("fixture", False):
|
|
21
|
+
raise ValueError("Dataset is incomplete or marked as a fixture")
|
|
22
|
+
known_sites = (metadata.get("signal") == "tn5_insertion_sites"
|
|
23
|
+
or metadata.get("data_source") == "official_experimental_ATAC_TFRecords"
|
|
24
|
+
or "ChromBPNet insertion counts" in metadata.get("label_source", ""))
|
|
25
|
+
if not known_sites:
|
|
26
|
+
raise ValueError("Dataset metadata does not identify insertion-site ATAC labels")
|
|
27
|
+
if not np.isfinite(metadata["track_mean"]) or metadata["track_mean"] <= 0:
|
|
28
|
+
raise ValueError("Dataset requires a positive nonzero-base track mean")
|
|
29
|
+
records_path = root / "records.json"
|
|
30
|
+
records_hash = sha256(records_path)
|
|
31
|
+
if records_hash != metadata["records_sha256"]:
|
|
32
|
+
raise ValueError("Dataset record manifest changed")
|
|
33
|
+
rows = json.loads(records_path.read_text())
|
|
34
|
+
for row in rows:
|
|
35
|
+
path = PurePosixPath(row["path"])
|
|
36
|
+
if path.is_absolute() or ".." in path.parts:
|
|
37
|
+
raise ValueError(f"Invalid record path: {path}")
|
|
38
|
+
if row["subset"] not in {"TRAIN", "VALID", "TEST"}:
|
|
39
|
+
raise ValueError("Unknown data split")
|
|
40
|
+
length, target_length = row["length"], row["target_length"]
|
|
41
|
+
if not 0 < target_length <= length or (length - target_length) % 2:
|
|
42
|
+
raise ValueError("Targets must be centered within the DNA context")
|
|
43
|
+
if row["target_offset"] != (length - target_length) // 2:
|
|
44
|
+
raise ValueError("Incorrect target offset")
|
|
45
|
+
dataset_id = fingerprint({"metadata": metadata, "records_sha256": records_hash})
|
|
46
|
+
return metadata, rows, dataset_id
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@lru_cache(maxsize=48)
|
|
50
|
+
def read_record(path, expected_bytes=None, expected_sha256=None):
|
|
51
|
+
payload = Path(path).read_bytes()
|
|
52
|
+
if expected_bytes is not None and len(payload) != expected_bytes:
|
|
53
|
+
raise ValueError(f"Truncated or replaced record: {path}")
|
|
54
|
+
if expected_sha256 is not None and hashlib.sha256(payload).hexdigest() != expected_sha256:
|
|
55
|
+
raise ValueError(f"Record content changed: {path}")
|
|
56
|
+
with np.load(io.BytesIO(payload), allow_pickle=False) as record:
|
|
57
|
+
code, bits = record["sequence_code"], record["atac_bf16"]
|
|
58
|
+
if code.dtype != np.uint8 or code.ndim != 1 or (code > 4).any():
|
|
59
|
+
raise ValueError("DNA encoding must be A=0,C=1,G=2,T=3,unknown=4")
|
|
60
|
+
if bits.dtype != np.uint16 or bits.ndim != 1:
|
|
61
|
+
raise ValueError("ATAC must be a one-dimensional bfloat16 bit array")
|
|
62
|
+
return code, bits
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def example(root, row, seq_len, shift=0, reverse=False):
|
|
66
|
+
code, bits = read_record(str(Path(root) / row["path"]), row.get("bytes"), row.get("sha256"))
|
|
67
|
+
if len(code) != row["length"] or len(bits) != row["target_length"]:
|
|
68
|
+
raise ValueError("Record dimensions differ from manifest")
|
|
69
|
+
crop = (len(code) - seq_len) // 2 + shift
|
|
70
|
+
end = crop + seq_len
|
|
71
|
+
if crop < 0 or end > len(code):
|
|
72
|
+
raise ValueError("Requested shift exceeds the stored DNA flanks")
|
|
73
|
+
offset = row["target_offset"]
|
|
74
|
+
left, right = max(crop, offset), min(end, offset + len(bits))
|
|
75
|
+
if left >= right:
|
|
76
|
+
raise ValueError("Crop does not intersect observed targets")
|
|
77
|
+
dna = DNA_LUT[code[crop:end]].copy()
|
|
78
|
+
counts = decode_bf16(bits[left - offset:right - offset])[:, None]
|
|
79
|
+
target_slice = (left - crop, right - crop)
|
|
80
|
+
if not np.isfinite(counts).all() or (counts < 0).any():
|
|
81
|
+
raise ValueError("Invalid ATAC target values")
|
|
82
|
+
if reverse:
|
|
83
|
+
dna, counts = dna[::-1, ::-1].copy(), counts[::-1].copy()
|
|
84
|
+
target_slice = (seq_len - target_slice[1], seq_len - target_slice[0])
|
|
85
|
+
return dna, counts, target_slice
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class TrainingBatches(torch.utils.data.Dataset):
|
|
89
|
+
"""One optimizer step per item; sample order survives resume and worker changes."""
|
|
90
|
+
def __init__(self, root, rows, config, first_step, last_step):
|
|
91
|
+
self.root, self.rows, self.config = str(root), rows, config
|
|
92
|
+
self.first_step, self.last_step = first_step, last_step
|
|
93
|
+
n, shift = config["model"]["seq_len"], config["shift_bp"]
|
|
94
|
+
if not rows or any(row["subset"] != "TRAIN" for row in rows):
|
|
95
|
+
raise ValueError("Training requires TRAIN records")
|
|
96
|
+
for row in rows:
|
|
97
|
+
if row["target_length"] < n + 2 * shift:
|
|
98
|
+
raise ValueError("TRAIN labels lack sufficient flanks for the requested shift")
|
|
99
|
+
|
|
100
|
+
def __len__(self):
|
|
101
|
+
return max(0, self.last_step - self.first_step + 1)
|
|
102
|
+
|
|
103
|
+
def __getitem__(self, index):
|
|
104
|
+
step = self.first_step + index
|
|
105
|
+
c = self.config
|
|
106
|
+
rng = np.random.default_rng(np.random.SeedSequence([c["seed"], step]))
|
|
107
|
+
dna, counts, indices, shifts, reverses = [], [], [], [], []
|
|
108
|
+
for _ in range(c["batch_size"]):
|
|
109
|
+
ri = int(rng.integers(len(self.rows)))
|
|
110
|
+
shift = int(rng.integers(-c["shift_bp"], c["shift_bp"] + 1))
|
|
111
|
+
reverse = rng.random() < c["reverse_complement_probability"]
|
|
112
|
+
x, y, observed = example(self.root, self.rows[ri], c["model"]["seq_len"], shift, reverse)
|
|
113
|
+
if observed != (0, c["model"]["seq_len"]):
|
|
114
|
+
raise ValueError("TRAIN crop is not fully supervised")
|
|
115
|
+
dna.append(x); counts.append(y)
|
|
116
|
+
indices.append(ri); shifts.append(shift); reverses.append(reverse)
|
|
117
|
+
return dict(step=step, x=torch.from_numpy(np.stack(dna)),
|
|
118
|
+
raw=torch.from_numpy(np.stack(counts)), indices=indices,
|
|
119
|
+
shifts=shifts, reverses=reverses)
|
xatac/io.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Sequence encoding, checksums and atomic output writes."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def sha256(path):
|
|
10
|
+
digest = hashlib.sha256()
|
|
11
|
+
with open(path, "rb") as stream:
|
|
12
|
+
for block in iter(lambda: stream.read(4 << 20), b""):
|
|
13
|
+
digest.update(block)
|
|
14
|
+
return digest.hexdigest()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def fingerprint(value):
|
|
18
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def write_json(path, value):
|
|
22
|
+
path = Path(path)
|
|
23
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
tmp = path.with_name(path.name + ".partial")
|
|
25
|
+
tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
|
|
26
|
+
tmp.replace(path)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def write_npz(path, **arrays):
|
|
30
|
+
path = Path(path)
|
|
31
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
tmp = path.with_name(path.name + ".partial")
|
|
33
|
+
with tmp.open("wb") as stream:
|
|
34
|
+
np.savez_compressed(stream, **arrays)
|
|
35
|
+
tmp.replace(path)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def encode_dna(sequence):
|
|
39
|
+
table = np.full(256, 4, np.uint8)
|
|
40
|
+
for i, base in enumerate(b"ACGT"):
|
|
41
|
+
table[base] = i
|
|
42
|
+
return table[np.frombuffer(sequence.upper().encode(), np.uint8)]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
DNA_LUT = np.vstack((np.eye(4, dtype=np.float32), np.zeros((1, 4), np.float32)))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def encode_bf16(values):
|
|
49
|
+
values = np.asarray(values, dtype=np.float32)
|
|
50
|
+
if not np.isfinite(values).all() or (values < 0).any():
|
|
51
|
+
raise ValueError("Site labels must be finite and nonnegative")
|
|
52
|
+
bits = values.view(np.uint32)
|
|
53
|
+
return ((bits + np.uint32(0x7FFF) + ((bits >> 16) & 1)) >> 16).astype(np.uint16)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def decode_bf16(bits):
|
|
57
|
+
if bits.dtype != np.uint16:
|
|
58
|
+
raise ValueError("Expected uint16 bfloat16 bit patterns")
|
|
59
|
+
return (bits.astype(np.uint32) << 16).view(np.float32)
|
xatac/loss.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Accessibility scaling and mean-reduced count/profile losses.
|
|
2
|
+
|
|
3
|
+
Tensors use batch, sequence, track order.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
from torch import Tensor
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def targets_scaling(counts: Tensor, track_mean: Tensor) -> Tensor:
|
|
13
|
+
"""Normalize counts and smoothly compress normalized values above ten."""
|
|
14
|
+
normalized = counts.float() / track_mean
|
|
15
|
+
# Clamping only the inactive curved branch avoids sqrt'(0) in backprop.
|
|
16
|
+
curved = 2 * torch.sqrt(10 * normalized.clamp_min(10)) - 10
|
|
17
|
+
return torch.where(normalized <= 10, normalized, curved)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def predictions_scaling(values: Tensor, track_mean: Tensor) -> Tensor:
|
|
21
|
+
"""Invert the target transform and restore the count scale."""
|
|
22
|
+
values = values.float()
|
|
23
|
+
normalized = torch.where(values <= 10, values, (values + 10).square() / 40)
|
|
24
|
+
return normalized * track_mean
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def pool128(counts: Tensor) -> Tensor:
|
|
28
|
+
"""Sum successive, non-overlapping groups of 128 sequence positions."""
|
|
29
|
+
if counts.ndim != 3 or counts.shape[1] % 128:
|
|
30
|
+
raise ValueError("counts must have shape (batch, length, tracks), with length divisible by 128")
|
|
31
|
+
batch, length, tracks = counts.shape
|
|
32
|
+
return counts.reshape(batch, length // 128, 128, tracks).sum(dim=2)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def multinomial_loss(
|
|
36
|
+
prediction: Tensor, target: Tensor, segment_length: int
|
|
37
|
+
) -> tuple[Tensor, Tensor, Tensor]:
|
|
38
|
+
"""Return combined, mass, and profile losses for contiguous segments.
|
|
39
|
+
|
|
40
|
+
The mass term is a Poisson deviance without its factor of two, divided by
|
|
41
|
+
segment length. The profile term is the average negative target-weighted
|
|
42
|
+
log probability. Both inputs enter the calculation as float32 tensors;
|
|
43
|
+
target values below zero are treated as zero.
|
|
44
|
+
"""
|
|
45
|
+
if prediction.ndim != 3 or prediction.shape != target.shape:
|
|
46
|
+
raise ValueError("prediction and target must share shape (batch, length, tracks)")
|
|
47
|
+
if not isinstance(segment_length, int) or segment_length <= 0:
|
|
48
|
+
raise ValueError("segment_length must be a positive integer")
|
|
49
|
+
batch, length, tracks = prediction.shape
|
|
50
|
+
if length == 0 or length % segment_length:
|
|
51
|
+
raise ValueError("sequence length must be nonzero and divisible by segment_length")
|
|
52
|
+
|
|
53
|
+
shape = (batch, length // segment_length, segment_length, tracks)
|
|
54
|
+
predicted = prediction.float().reshape(shape)
|
|
55
|
+
observed = target.float().clamp_min(0).reshape(shape)
|
|
56
|
+
predicted_mass = predicted.sum(dim=2, keepdim=True)
|
|
57
|
+
observed_mass = observed.sum(dim=2, keepdim=True)
|
|
58
|
+
epsilon = 1e-7
|
|
59
|
+
|
|
60
|
+
total = (
|
|
61
|
+
predicted_mass
|
|
62
|
+
- observed_mass * torch.log(predicted_mass + epsilon)
|
|
63
|
+
- (observed_mass - observed_mass * torch.log(observed_mass + epsilon))
|
|
64
|
+
).mean() / segment_length
|
|
65
|
+
positional = -(observed * torch.log(predicted / (predicted_mass + epsilon) + epsilon)).mean()
|
|
66
|
+
return total + 5 * positional, total, positional
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def atac_loss(
|
|
70
|
+
predictions: Sequence[Tensor],
|
|
71
|
+
counts: Tensor,
|
|
72
|
+
track_mean: Tensor,
|
|
73
|
+
target_slice: tuple[int, int] | None = None,
|
|
74
|
+
) -> tuple[Tensor, dict[str, Tensor]]:
|
|
75
|
+
"""Combine full-resolution and 128-base accessibility losses.
|
|
76
|
+
|
|
77
|
+
``counts`` contains the cropped target. ``target_slice`` identifies that
|
|
78
|
+
crop within both prediction tensors in full-resolution coordinates. Each
|
|
79
|
+
resolution uses eight sequence segments over the cropped interval.
|
|
80
|
+
"""
|
|
81
|
+
if len(predictions) != 2:
|
|
82
|
+
raise ValueError("predictions must contain full-resolution and 128-base tensors")
|
|
83
|
+
if counts.ndim != 3 or any(value.ndim != 3 for value in predictions):
|
|
84
|
+
raise ValueError("counts and predictions must have shape (batch, length, tracks)")
|
|
85
|
+
left, right = (0, predictions[0].shape[1]) if target_slice is None else target_slice
|
|
86
|
+
if not isinstance(left, int) or not isinstance(right, int):
|
|
87
|
+
raise ValueError("target_slice endpoints must be integer base coordinates")
|
|
88
|
+
length = right - left
|
|
89
|
+
if left < 0 or right > predictions[0].shape[1] or length <= 0:
|
|
90
|
+
raise ValueError("target_slice must identify a nonempty interval within the predictions")
|
|
91
|
+
if left % 128 or right % 128 or length % 1024:
|
|
92
|
+
raise ValueError("slice endpoints must be divisible by 128 and cropped length by 1024")
|
|
93
|
+
if counts.shape[1] != length:
|
|
94
|
+
raise ValueError("counts length must equal the selected prediction interval")
|
|
95
|
+
|
|
96
|
+
selected = (predictions[0][:, left:right], predictions[1][:, left // 128:right // 128])
|
|
97
|
+
targets = (targets_scaling(counts, track_mean), targets_scaling(pool128(counts), track_mean * 128))
|
|
98
|
+
result: dict[str, Tensor] = {}
|
|
99
|
+
losses = []
|
|
100
|
+
for resolution, predicted, observed in zip((1, 128), selected, targets):
|
|
101
|
+
loss, total, positional = multinomial_loss(predicted, observed, length // 8 // resolution)
|
|
102
|
+
result[f"loss_{resolution}bp"] = loss
|
|
103
|
+
result[f"total_{resolution}bp"] = total
|
|
104
|
+
result[f"positional_{resolution}bp"] = positional
|
|
105
|
+
losses.append(loss)
|
|
106
|
+
return losses[0] + losses[1], result
|
xatac/model.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Convolutional DNA→ATAC model, with the original 125-bp trunk and 1-bp decoder."""
|
|
2
|
+
import math
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn
|
|
6
|
+
from torch.nn import functional as F
|
|
7
|
+
from torch.utils.checkpoint import checkpoint
|
|
8
|
+
|
|
9
|
+
from .loss import pool128, predictions_scaling, targets_scaling
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def group_norm(channels, groups=8):
|
|
13
|
+
groups = next(g for g in (groups, 4, 2, 1) if channels % g == 0)
|
|
14
|
+
return nn.GroupNorm(groups, channels)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DilatedBlock(nn.Module):
|
|
18
|
+
def __init__(self, channels, dilation):
|
|
19
|
+
super().__init__()
|
|
20
|
+
self.net = nn.Sequential(
|
|
21
|
+
group_norm(channels), nn.GELU(),
|
|
22
|
+
nn.Conv1d(channels, channels, 3, padding=dilation, dilation=dilation),
|
|
23
|
+
group_norm(channels), nn.GELU(), nn.Conv1d(channels, channels, 1))
|
|
24
|
+
|
|
25
|
+
def forward(self, x):
|
|
26
|
+
return x + self.net(x)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConvNet(nn.Module):
|
|
30
|
+
def __init__(self, width, n_dilated, dilation_cycles, pool_factors, up_factors, up_channels):
|
|
31
|
+
super().__init__()
|
|
32
|
+
if len(pool_factors) != 6 or len(up_factors) != len(up_channels):
|
|
33
|
+
raise ValueError("Six encoder stages and matching decoder factors/channels are required")
|
|
34
|
+
if any(v < 1 for v in (*pool_factors, *up_factors, *up_channels)):
|
|
35
|
+
raise ValueError("Pooling factors and channel counts must be positive")
|
|
36
|
+
self.trunk_bin = math.prod(pool_factors)
|
|
37
|
+
if self.trunk_bin != math.prod(up_factors):
|
|
38
|
+
raise ValueError("Decoder must return the trunk to 1-bp resolution")
|
|
39
|
+
self.pool_factors, self.up_factors = tuple(pool_factors), tuple(up_factors)
|
|
40
|
+
self.lconv1 = nn.Sequential(
|
|
41
|
+
group_norm(4, 1), nn.GELU(), nn.Conv1d(4, 64, 9, padding=4),
|
|
42
|
+
group_norm(64), nn.GELU(), nn.Conv1d(64, 64, 9, padding=4))
|
|
43
|
+
self.stages = nn.ModuleList()
|
|
44
|
+
channels, resolution, skips = 64, 1, {1: 64}
|
|
45
|
+
for out, factor in zip((96, width, width, width, width, width), pool_factors):
|
|
46
|
+
self.stages.append(nn.Sequential(
|
|
47
|
+
nn.MaxPool1d(factor, factor) if factor > 1 else nn.Identity(),
|
|
48
|
+
group_norm(channels), nn.GELU(), nn.Conv1d(channels, out, 9, padding=4),
|
|
49
|
+
group_norm(out), nn.GELU(), nn.Conv1d(out, out, 9, padding=4)))
|
|
50
|
+
resolution *= factor
|
|
51
|
+
channels, skips[resolution] = out, out
|
|
52
|
+
self.dil_tower = nn.ModuleList(
|
|
53
|
+
DilatedBlock(width, 2 ** i) for _ in range(dilation_cycles) for i in range(n_dilated))
|
|
54
|
+
self.upres, self.up_skip, self.up_post = nn.ModuleList(), nn.ModuleList(), nn.ModuleList()
|
|
55
|
+
for factor, out in zip(up_factors, up_channels):
|
|
56
|
+
resolution //= factor
|
|
57
|
+
if resolution not in skips:
|
|
58
|
+
raise ValueError(f"No encoder skip at {resolution} bp")
|
|
59
|
+
self.upres.append(nn.Sequential(group_norm(channels), nn.GELU(),
|
|
60
|
+
nn.Conv1d(channels, out, 9, padding=4)))
|
|
61
|
+
self.up_skip.append(nn.Sequential(group_norm(skips[resolution]), nn.GELU(),
|
|
62
|
+
nn.Conv1d(skips[resolution], out, 1)))
|
|
63
|
+
self.up_post.append(nn.Sequential(group_norm(out), nn.GELU(),
|
|
64
|
+
nn.Conv1d(out, out, 9, padding=4)))
|
|
65
|
+
channels = out
|
|
66
|
+
self.residual_scale = nn.Parameter(torch.full((len(up_factors),), 0.9))
|
|
67
|
+
self.head_ag = nn.Sequential(group_norm(channels), nn.GELU(), nn.Conv1d(channels, channels, 1),
|
|
68
|
+
nn.GELU(), nn.Conv1d(channels, 1, 1))
|
|
69
|
+
self.ag_scale = nn.Parameter(torch.zeros(1))
|
|
70
|
+
|
|
71
|
+
def forward(self, x, use_checkpoint=False):
|
|
72
|
+
def run(block, values):
|
|
73
|
+
if use_checkpoint and self.training and torch.is_grad_enabled():
|
|
74
|
+
return checkpoint(block, values, use_reentrant=False, preserve_rng_state=True)
|
|
75
|
+
return block(values)
|
|
76
|
+
|
|
77
|
+
x = run(self.lconv1, x)
|
|
78
|
+
skips, resolution = {1: x}, 1
|
|
79
|
+
for stage, factor in zip(self.stages, self.pool_factors):
|
|
80
|
+
x = run(stage, x)
|
|
81
|
+
resolution *= factor
|
|
82
|
+
skips[resolution] = x
|
|
83
|
+
for block in self.dil_tower:
|
|
84
|
+
x = run(block, x)
|
|
85
|
+
for i, (factor, up, skip, post) in enumerate(zip(
|
|
86
|
+
self.up_factors, self.upres, self.up_skip, self.up_post)):
|
|
87
|
+
resolution //= factor
|
|
88
|
+
y = run(up, x).repeat_interleave(factor, dim=2) * self.residual_scale[i]
|
|
89
|
+
y = y + run(skip, skips[resolution])
|
|
90
|
+
x = y + run(post, y)
|
|
91
|
+
return F.softplus(run(self.head_ag, x)) * F.softplus(self.ag_scale).view(1, -1, 1)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class DNA2ATAC(nn.Module):
|
|
95
|
+
"""One cell per model; input (B, L, 4), scaled outputs (B, L, 1) and (B, L/128, 1)."""
|
|
96
|
+
def __init__(self, seq_len=1048576, width=512, n_dilated=13, dilation_cycles=1,
|
|
97
|
+
pool_factors=(5, 5, 5, 1, 1, 1), up_factors=(5, 5, 5),
|
|
98
|
+
up_channels=(128, 64, 32), grad_checkpoint=True, track_mean=0.37652507):
|
|
99
|
+
super().__init__()
|
|
100
|
+
if seq_len < 1024 or seq_len % 1024 or not math.isfinite(track_mean) or track_mean <= 0:
|
|
101
|
+
raise ValueError("seq_len must be a positive multiple of 1024; track_mean must be positive")
|
|
102
|
+
self.seq_len, self.track_mean, self.grad_checkpoint = seq_len, track_mean, grad_checkpoint
|
|
103
|
+
self.cnn = ConvNet(width, n_dilated, dilation_cycles, pool_factors, up_factors, up_channels)
|
|
104
|
+
self.right_pad = (-seq_len) % self.cnn.trunk_bin
|
|
105
|
+
|
|
106
|
+
def forward(self, dna):
|
|
107
|
+
if dna.ndim != 3 or dna.shape[1:] != (self.seq_len, 4):
|
|
108
|
+
raise ValueError(f"Expected (batch, {self.seq_len}, 4), got {tuple(dna.shape)}")
|
|
109
|
+
x = F.pad(dna.transpose(1, 2), (0, self.right_pad))
|
|
110
|
+
p1 = self.cnn(x, self.grad_checkpoint)[..., :self.seq_len].transpose(1, 2)
|
|
111
|
+
p128 = targets_scaling(pool128(predictions_scaling(p1, self.track_mean)), self.track_mean * 128)
|
|
112
|
+
return p1, p128
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def load_weights(model, state):
|
|
116
|
+
"""Strict loading, allowing only the unused legacy head that had no forward path."""
|
|
117
|
+
legacy = {"cnn.head.0.weight", "cnn.head.0.bias", "cnn.head.2.weight", "cnn.head.2.bias",
|
|
118
|
+
"cnn.head.4.weight", "cnn.head.4.bias"}
|
|
119
|
+
found = legacy & state.keys()
|
|
120
|
+
if found and found != legacy:
|
|
121
|
+
raise ValueError("Incomplete legacy unused-head state")
|
|
122
|
+
model.load_state_dict({k: v for k, v in state.items() if k not in legacy}, strict=True)
|
|
123
|
+
return sorted(found)
|
xatac/predict.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Predict a genomic interval with one checkpoint or a mean of per-base signals."""
|
|
2
|
+
import argparse
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pysam
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
from .io import DNA_LUT, encode_dna, sha256, write_json, write_npz
|
|
10
|
+
from .loss import predictions_scaling
|
|
11
|
+
from .model import DNA2ATAC, load_weights
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _resolve_scale(xchroma_scale, xchrom_scale):
|
|
15
|
+
if xchroma_scale is not None and xchrom_scale is not None and xchroma_scale != xchrom_scale:
|
|
16
|
+
raise ValueError("Conflicting values for --xchroma-scale and its legacy alias")
|
|
17
|
+
return xchroma_scale if xchroma_scale is not None else xchrom_scale
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def predict(checkpoints, fasta, chrom, start, end, output, device_name="cuda",
|
|
21
|
+
assembly=None, xchroma_scale=None, gp99=None, *, xchrom_scale=None):
|
|
22
|
+
xchroma_scale = _resolve_scale(xchroma_scale, xchrom_scale)
|
|
23
|
+
if start < 0 or end <= start:
|
|
24
|
+
raise ValueError("Use a nonempty 0-based half-open interval")
|
|
25
|
+
output = Path(output)
|
|
26
|
+
if output.exists() or Path(str(output) + ".json").exists():
|
|
27
|
+
raise FileExistsError(output)
|
|
28
|
+
if (xchroma_scale is None) != (gp99 is None):
|
|
29
|
+
raise ValueError("Provide both a fixed training-derived XChroma scale and gp99, or neither")
|
|
30
|
+
if xchroma_scale is not None and (not np.isfinite([xchroma_scale, gp99]).all() or min(xchroma_scale, gp99) <= 0):
|
|
31
|
+
raise ValueError("Input conversion parameters must be finite and positive")
|
|
32
|
+
device = torch.device(device_name)
|
|
33
|
+
torch.backends.cuda.matmul.allow_tf32 = False
|
|
34
|
+
torch.backends.cudnn.allow_tf32 = False
|
|
35
|
+
total, members, context = None, [], None
|
|
36
|
+
with pysam.FastaFile(str(fasta)) as fa:
|
|
37
|
+
for path in checkpoints:
|
|
38
|
+
state = torch.load(path, map_location="cpu", weights_only=False)
|
|
39
|
+
config = dict(state["config"]["model"])
|
|
40
|
+
config["grad_checkpoint"] = False
|
|
41
|
+
model = DNA2ATAC(**config)
|
|
42
|
+
discarded = load_weights(model, state["model"])
|
|
43
|
+
model = model.eval().to(device)
|
|
44
|
+
seq_len = model.seq_len
|
|
45
|
+
if end - start > seq_len:
|
|
46
|
+
raise ValueError("Requested interval exceeds native model context; no implicit tiling")
|
|
47
|
+
left = start - (seq_len - (end - start)) // 2
|
|
48
|
+
right = left + seq_len
|
|
49
|
+
if left < 0 or chrom not in fa.references or right > fa.get_reference_length(chrom):
|
|
50
|
+
raise ValueError("Full model context extends beyond the reference")
|
|
51
|
+
current = dict(chrom=chrom, start=left, end=right, display_offset=start - left)
|
|
52
|
+
if context is not None and current != context:
|
|
53
|
+
raise ValueError("Ensemble members must share the same native DNA context")
|
|
54
|
+
context = current
|
|
55
|
+
code = encode_dna(fa.fetch(chrom, left, right))
|
|
56
|
+
with torch.inference_mode():
|
|
57
|
+
native, _ = model(torch.from_numpy(DNA_LUT[code][None]).to(device))
|
|
58
|
+
counts = predictions_scaling(native[0, :, 0], model.track_mean).cpu().numpy()
|
|
59
|
+
if not np.isfinite(counts).all() or (counts < 0).any():
|
|
60
|
+
raise FloatingPointError(f"Invalid inverse-scaled prediction from {path}")
|
|
61
|
+
signal = counts[start - left:end - left].astype(np.float64)
|
|
62
|
+
total = signal if total is None else total + signal
|
|
63
|
+
members.append(dict(path=str(Path(path)), sha256=sha256(path), step=state.get("step"),
|
|
64
|
+
model_config=config, legacy_unused_head_keys_discarded=discarded))
|
|
65
|
+
del model, state, native, counts
|
|
66
|
+
if not members:
|
|
67
|
+
raise ValueError("At least one checkpoint is required")
|
|
68
|
+
signal = (total / len(members)).astype(np.float32)
|
|
69
|
+
arrays = dict(signal=signal, valid=np.isfinite(signal), start=np.int64(start), end=np.int64(end))
|
|
70
|
+
if xchroma_scale is not None:
|
|
71
|
+
arrays["xchroma_input"] = (np.log1p(signal.astype(np.float64) * xchroma_scale) / gp99).astype(np.float32)
|
|
72
|
+
write_npz(output, **arrays)
|
|
73
|
+
write_json(Path(str(output) + ".json"), dict(
|
|
74
|
+
status="PASS", assembly=assembly, chrom=chrom, start=start, end=end,
|
|
75
|
+
coordinate_convention="0-based half-open", resolution_bp=1, context=context,
|
|
76
|
+
units="insertion-site target signal after inverse model scaling",
|
|
77
|
+
ensemble="Arithmetic mean of inverse-scaled per-base signals, not weights or scaled head values",
|
|
78
|
+
precision="FP32 forward, FP64 ensemble accumulation, TF32 off", members=members,
|
|
79
|
+
fasta=str(fasta), fasta_sha256=sha256(fasta), output_sha256=sha256(output),
|
|
80
|
+
xchroma_conversion=None if xchroma_scale is None else dict(
|
|
81
|
+
formula="log1p(signal * fixed_training_scale) / gp99", fixed_training_scale=xchroma_scale,
|
|
82
|
+
gp99=gp99, signal_definition="Scaled predicted sites; not measured fragment coverage")))
|
|
83
|
+
return signal
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def main(argv=None):
|
|
87
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
88
|
+
parser.add_argument("--checkpoint", nargs="+", type=Path, required=True)
|
|
89
|
+
parser.add_argument("--fasta", type=Path, required=True)
|
|
90
|
+
parser.add_argument("--assembly", required=True)
|
|
91
|
+
parser.add_argument("--chrom", required=True)
|
|
92
|
+
parser.add_argument("--start", type=int, required=True)
|
|
93
|
+
parser.add_argument("--end", type=int, required=True)
|
|
94
|
+
parser.add_argument("--output", type=Path, required=True)
|
|
95
|
+
parser.add_argument("--device", choices=("cuda", "cpu"), default="cuda")
|
|
96
|
+
parser.add_argument("--threads", type=int, default=4)
|
|
97
|
+
parser.add_argument("--xchroma-scale", type=float)
|
|
98
|
+
parser.add_argument("--xchrom-scale", type=float, help=argparse.SUPPRESS)
|
|
99
|
+
parser.add_argument("--gp99", type=float)
|
|
100
|
+
args = parser.parse_args(argv)
|
|
101
|
+
try:
|
|
102
|
+
scale = _resolve_scale(args.xchroma_scale, args.xchrom_scale)
|
|
103
|
+
except ValueError as exc:
|
|
104
|
+
parser.error(str(exc))
|
|
105
|
+
torch.set_num_threads(args.threads)
|
|
106
|
+
predict(args.checkpoint, args.fasta, args.chrom, args.start, args.end, args.output,
|
|
107
|
+
args.device, args.assembly, scale, args.gp99)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
main()
|