Philip Fradkin commited on
Commit
8481452
·
1 Parent(s): c767554

feat: add orthrus logo

Browse files
README.md CHANGED
@@ -7,7 +7,12 @@ metrics:
7
  - pearsonr
8
  ---
9
 
 
10
  ## Model Overview
 
 
 
 
11
  Orthrus is a mature RNA model for RNA property prediction. It uses a mamba encoder backbone, a variant of state-space models specifically designed for long-sequence data, such as RNA.
12
 
13
  Two versions of Orthrus are available:
@@ -22,6 +27,12 @@ The mamba architecture is an extension of the S4 (structured state-space) model
22
  - _Variable Context Filtering:_ RNA sequences often contain functionally relevant motifs separated by variable spacing. The mamba model is capable of selectively focusing on these important elements
23
  - _Selective Context Compression:_ Genomic sequences often have uneven information density, with critical regulatory elements scattered across regions of varying importance. The mamba model selectively compresses less informative regions while preserving the context of key functional areas
24
 
 
 
 
 
 
 
25
  ## Using Orthrus
26
 
27
  Orthrus was trained on full RNA sequences, making its usage different from models like DNABERT or Enformer, which focus on arbitrary DNA segments.
@@ -29,6 +40,39 @@ Orthrus was instead trained on full mature RNA sequences so if you pass an incom
29
 
30
  To generate embeddings using Orthrus for spliced mature RNA sequences, follow the steps below:
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  ### Generating Embeddings
33
 
34
  #### 4-Track Model
 
7
  - pearsonr
8
  ---
9
 
10
+
11
  ## Model Overview
12
+
13
+ <div style="display: flex; align-items: flex-start;">
14
+ <div style="flex: 1;">
15
+
16
  Orthrus is a mature RNA model for RNA property prediction. It uses a mamba encoder backbone, a variant of state-space models specifically designed for long-sequence data, such as RNA.
17
 
18
  Two versions of Orthrus are available:
 
27
  - _Variable Context Filtering:_ RNA sequences often contain functionally relevant motifs separated by variable spacing. The mamba model is capable of selectively focusing on these important elements
28
  - _Selective Context Compression:_ Genomic sequences often have uneven information density, with critical regulatory elements scattered across regions of varying importance. The mamba model selectively compresses less informative regions while preserving the context of key functional areas
29
 
30
+ </div>
31
+ <div style="flex: 1; margin-left: 20px;">
32
+ <img src="images/orthrus_cleaned_up.png" alt="Orthrus Model Overview" style="max-width: 34%; height: auto;">
33
+ </div>
34
+ </div>
35
+
36
  ## Using Orthrus
37
 
38
  Orthrus was trained on full RNA sequences, making its usage different from models like DNABERT or Enformer, which focus on arbitrary DNA segments.
 
40
 
41
  To generate embeddings using Orthrus for spliced mature RNA sequences, follow the steps below:
42
 
43
+ ### Create and Set Up the Environment
44
+
45
+ We recommend using Mamba (a faster alternative to Conda) for environment creation, but Conda works as well. Follow these steps to set up your environment:
46
+
47
+ 1. Install Mamba or Conda if you haven't already.
48
+
49
+ 2. Create and activate the environment:
50
+ ```bash
51
+ # Create the environment from the provided YAML file
52
+ mamba env create -f env.yml
53
+ # Activate the environment
54
+ conda activate orthrus
55
+ ```
56
+
57
+ 3. Install additional dependencies:
58
+ ```bash
59
+ # Install necessary dependencies for the Mamba model (not the environment manager)
60
+ pip install causal_conv1d==1.1.1
61
+ pip install mamba-ssm==1.2.0.post1 --no-cache-dir
62
+ ```
63
+
64
+ 4. Set up GenomeKit:
65
+ ```bash
66
+ # Download the GenomeKit setup script
67
+ wget -O starter_build.sh https://raw.githubusercontent.com/deepgenomics/GenomeKit/main/starter/build.sh
68
+ # Make the script executable
69
+ chmod +x starter_build.sh
70
+ # Run the script to download genomes and annotations
71
+ ./starter_build.sh
72
+ ```
73
+
74
+ Now you're ready to use Orthrus for generating embeddings!
75
+
76
  ### Generating Embeddings
77
 
78
  #### 4-Track Model
env.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: orthrus
2
+ channels:
3
+ - pytorch
4
+ - conda-forge
5
+ - defaults
6
+ - nvidia
7
+ dependencies:
8
+ - python=3.10
9
+ - numpy
10
+ - pandas
11
+ - pip
12
+ - jupyter
13
+ - notebook
14
+ - tqdm
15
+ - pytorch=2.2
16
+ - pytorch-cuda
17
+ - cuda-toolkit=12.1
18
+ - genomekit>=6.0.0
images/orthrus_cleaned_up.png ADDED
notebooks/colab_prototye.ipynb ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "## GenomeKit foundations\n",
8
+ "\n",
9
+ "We're going to be using an awesome library called GenomeKit to extract DNA sequences and build 4/6 track representations of mRNA transcripts, which will be used as input for Orthrus. GenomeKit makes it easy to work with genomic data, such as sequences and annotations, by providing tools to access and manipulate reference genomes and variants efficiently. It's built by the awesome folks at Deep Genomics\n",
10
+ "\n",
11
+ "For more details, you can refer to the [GenomeKit documentation](https://deepgenomics.github.io/GenomeKit/api.html).\n"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": 10,
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "import genome_kit as gk\n",
21
+ "from genome_kit import Genome, Interval\n",
22
+ "import numpy as np"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": 11,
28
+ "metadata": {},
29
+ "outputs": [
30
+ {
31
+ "data": {
32
+ "text/plain": [
33
+ "'CTCTTATGCTCGGGTGATCC'"
34
+ ]
35
+ },
36
+ "execution_count": 11,
37
+ "metadata": {},
38
+ "output_type": "execute_result"
39
+ }
40
+ ],
41
+ "source": [
42
+ "genome = Genome(\"gencode.v29\")\n",
43
+ "interval = Interval(\"chr7\", \"+\", 117120016, 117120036, genome)\n",
44
+ "genome.dna(interval)"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 12,
50
+ "metadata": {},
51
+ "outputs": [
52
+ {
53
+ "name": "stdout",
54
+ "output_type": "stream",
55
+ "text": [
56
+ "5447\n"
57
+ ]
58
+ }
59
+ ],
60
+ "source": [
61
+ "genes = [x for x in genome.genes if x.name == 'PKP1']\n",
62
+ "transcripts = genes[0].transcripts\n",
63
+ "t = [t for t in transcripts if t.id == 'ENST00000263946.7'][0]\n",
64
+ "print(sum([len(x) for x in t.exons]))"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "execution_count": 13,
70
+ "metadata": {},
71
+ "outputs": [],
72
+ "source": [
73
+ "def find_transcript(genome, transcript_id):\n",
74
+ " \"\"\"Find a transcript in a genome by transcript ID.\n",
75
+ " \n",
76
+ " Args:\n",
77
+ " genome (object): The genome object containing a list of transcripts.\n",
78
+ " transcript_id (str): The ID of the transcript to find.\n",
79
+ " \n",
80
+ " Returns:\n",
81
+ " object: The transcript object, if found.\n",
82
+ " \n",
83
+ " Raises:\n",
84
+ " ValueError: If no transcript with the given ID is found.\n",
85
+ " \n",
86
+ " Example:\n",
87
+ " >>> # Create sample transcripts and a genome\n",
88
+ " >>> transcript1 = 'ENST00000263946'\n",
89
+ " >>> genome = Genome(\"gencode.v29\")\n",
90
+ " >>> result = find_transcript(genome, 'ENST00000335137')\n",
91
+ " >>> print(result.id)\n",
92
+ " <Transcript ENST00000263946.7 of PKP1>\n",
93
+ " >>> # If transcript ID is not found\n",
94
+ " >>> find_transcript(genome, 'ENST00000000000')\n",
95
+ " ValueError: Transcript with ID ENST00000000000 not found.\n",
96
+ " \"\"\"\n",
97
+ " transcripts = [x for x in genome.transcripts if x.id.split('.')[0] == transcript_id]\n",
98
+ " if not transcripts:\n",
99
+ " raise ValueError(f\"Transcript with ID {transcript_id} not found.\")\n",
100
+ " \n",
101
+ " return transcripts[0]\n",
102
+ "\n",
103
+ "def find_transcript_by_gene_name(genome, gene_name):\n",
104
+ " \"\"\"Find all transcripts in a genome by gene name.\n",
105
+ " \n",
106
+ " Args:\n",
107
+ " genome (object): The genome object containing a list of transcripts.\n",
108
+ " gene_name (str): The name of the gene whose transcripts are to be found.\n",
109
+ " \n",
110
+ " Returns:\n",
111
+ " list: A list of transcript objects corresponding to the given gene name.\n",
112
+ " \n",
113
+ " Raises:\n",
114
+ " ValueError: If no transcripts for the given gene name are found.\n",
115
+ " \n",
116
+ " Example:\n",
117
+ " >>> # Find transcripts by gene name\n",
118
+ " >>> transcripts = find_transcript_by_gene_name(genome, 'PKP1')\n",
119
+ " >>> print(transcripts)\n",
120
+ " [<Transcript ENST00000367324.7 of PKP1>,\n",
121
+ " <Transcript ENST00000263946.7 of PKP1>,\n",
122
+ " <Transcript ENST00000352845.3 of PKP1>,\n",
123
+ " <Transcript ENST00000475988.1 of PKP1>,\n",
124
+ " <Transcript ENST00000477817.1 of PKP1>] \n",
125
+ " >>> # If gene name is not found\n",
126
+ " >>> find_transcript_by_gene_name(genome, 'XYZ')\n",
127
+ " ValueError: No transcripts found for gene name XYZ.\n",
128
+ " \"\"\"\n",
129
+ " genes = [x for x in genome.genes if x.name == gene_name]\n",
130
+ " if not genes:\n",
131
+ " raise ValueError(f\"No genes found for gene name {gene_name}.\")\n",
132
+ " if len(genes) > 1:\n",
133
+ " print(f\"Warning: More than one gene found for gene name {gene_name}.\")\n",
134
+ " print('Concatenating transcripts from all genes.')\n",
135
+ " \n",
136
+ " transcripts = []\n",
137
+ " for gene in genes:\n",
138
+ " transcripts += gene.transcripts\n",
139
+ " return transcripts\n",
140
+ "\n",
141
+ "def create_cds_track(t):\n",
142
+ " \"\"\"Create a track of the coding sequence of a transcript.\n",
143
+ " Use the exons of the transcript to create a track where the first position of the codon is one.\n",
144
+ " \n",
145
+ " Args:\n",
146
+ " t (gk.Transcript): The transcript object.\n",
147
+ " \"\"\"\n",
148
+ " cds_intervals = t.cdss\n",
149
+ " utr3_intervals = t.utr3s\n",
150
+ " utr5_intervals = t.utr5s\n",
151
+ " \n",
152
+ " len_utr3 = sum([len(x) for x in utr3_intervals])\n",
153
+ " len_utr5 = sum([len(x) for x in utr5_intervals])\n",
154
+ " len_cds = sum([len(x) for x in cds_intervals])\n",
155
+ " \n",
156
+ " # create a track where first position of the codon is one\n",
157
+ " cds_track = np.zeros(len_cds, dtype=int)\n",
158
+ " # set every third position to 1\n",
159
+ " cds_track[0::3] = 1\n",
160
+ " # concat with zeros of utr3 and utr5\n",
161
+ " cds_track = np.concatenate([np.zeros(len_utr5, dtype=int), cds_track, np.zeros(len_utr3, dtype=int)])\n",
162
+ " return cds_track\n",
163
+ "\n",
164
+ "def create_splice_track(t):\n",
165
+ " \"\"\"Create a track of the splice sites of a transcript.\n",
166
+ " The track is a 1D array where the positions of the splice sites are 1.\n",
167
+ "\n",
168
+ " Args:\n",
169
+ " t (gk.Transcript): The transcript object.\n",
170
+ " \"\"\"\n",
171
+ " len_utr3 = sum([len(x) for x in t.utr3s])\n",
172
+ " len_utr5 = sum([len(x) for x in t.utr5s])\n",
173
+ " len_cds = sum([len(x) for x in t.cdss])\n",
174
+ " \n",
175
+ " len_mrna = len_utr3 + len_utr5 + len_cds\n",
176
+ " splicing_track = np.zeros(len_mrna, dtype=int)\n",
177
+ " cumulative_len = 0\n",
178
+ " for exon in t.exons:\n",
179
+ " cumulative_len += len(exon)\n",
180
+ " splicing_track[cumulative_len - 1:cumulative_len] = 1\n",
181
+ " \n",
182
+ " return splicing_track\n",
183
+ "\n",
184
+ "# convert to one hot\n",
185
+ "def seq_to_oh(seq):\n",
186
+ " oh = np.zeros((len(seq), 4), dtype=int)\n",
187
+ " for i, base in enumerate(seq):\n",
188
+ " if base == 'A':\n",
189
+ " oh[i, 0] = 1\n",
190
+ " elif base == 'C':\n",
191
+ " oh[i, 1] = 1\n",
192
+ " elif base == 'G':\n",
193
+ " oh[i, 2] = 1\n",
194
+ " elif base == 'T':\n",
195
+ " oh[i, 3] = 1\n",
196
+ " return oh\n",
197
+ "\n",
198
+ "def create_one_hot_encoding(t):\n",
199
+ " \"\"\"Create a track of the sequence of a transcript.\n",
200
+ " The track is a 2D array where the rows are the positions\n",
201
+ " and the columns are the one-hot encoding of the bases.\n",
202
+ "\n",
203
+ " Args\n",
204
+ " t (gk.Transcript): The transcript object.\n",
205
+ " \"\"\"\n",
206
+ " seq = \"\".join([genome.dna(exon) for exon in t.exons])\n",
207
+ " oh = seq_to_oh(seq)\n",
208
+ " return oh\n",
209
+ "\n",
210
+ "def create_six_track_encoding(t, channels_last=False):\n",
211
+ " \"\"\"Create a track of the sequence of a transcript.\n",
212
+ " The track is a 2D array where the rows are the positions\n",
213
+ " and the columns are the one-hot encoding of the bases.\n",
214
+ " Concatenate the one-hot encoding with the cds track and the splice track.\n",
215
+ "\n",
216
+ " Args\n",
217
+ " t (gk.Transcript): The transcript object.\n",
218
+ " \"\"\"\n",
219
+ " oh = create_one_hot_encoding(t)\n",
220
+ " cds_track = create_cds_track(t)\n",
221
+ " splice_track = create_splice_track(t)\n",
222
+ " six_track = np.concatenate([oh, cds_track[:, None], splice_track[:, None]], axis=1)\n",
223
+ " if not channels_last:\n",
224
+ " six_track = six_track.T\n",
225
+ " return six_track"
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "execution_count": 14,
231
+ "metadata": {},
232
+ "outputs": [],
233
+ "source": [
234
+ "import math\n",
235
+ "from functools import partial\n",
236
+ "import os\n",
237
+ "import json\n",
238
+ "import torch\n",
239
+ "import torch.nn as nn\n",
240
+ "\n",
241
+ "from mamba_ssm.modules.mamba_simple import Mamba, Block\n",
242
+ "from huggingface_hub import PyTorchModelHubMixin\n",
243
+ "\n",
244
+ "def create_block(\n",
245
+ " d_model,\n",
246
+ " ssm_cfg=None,\n",
247
+ " norm_epsilon=1e-5,\n",
248
+ " residual_in_fp32=False,\n",
249
+ " fused_add_norm=False,\n",
250
+ " layer_idx=None,\n",
251
+ " device=None,\n",
252
+ " dtype=None,\n",
253
+ "):\n",
254
+ " if ssm_cfg is None:\n",
255
+ " ssm_cfg = {}\n",
256
+ " factory_kwargs = {\"device\": device, \"dtype\": dtype}\n",
257
+ " mix_cls = partial(Mamba, layer_idx=layer_idx, **ssm_cfg, **factory_kwargs)\n",
258
+ " norm_cls = partial(nn.LayerNorm, eps=norm_epsilon, **factory_kwargs)\n",
259
+ " block = Block(\n",
260
+ " d_model,\n",
261
+ " mix_cls,\n",
262
+ " norm_cls=norm_cls,\n",
263
+ " fused_add_norm=fused_add_norm,\n",
264
+ " residual_in_fp32=residual_in_fp32,\n",
265
+ " )\n",
266
+ " block.layer_idx = layer_idx\n",
267
+ " return block\n",
268
+ "\n",
269
+ "\n",
270
+ "class MixerModel(\n",
271
+ " nn.Module,\n",
272
+ " PyTorchModelHubMixin,\n",
273
+ "):\n",
274
+ "\n",
275
+ " def __init__(\n",
276
+ " self,\n",
277
+ " d_model: int,\n",
278
+ " n_layer: int,\n",
279
+ " input_dim: int,\n",
280
+ " ssm_cfg=None,\n",
281
+ " norm_epsilon: float = 1e-5,\n",
282
+ " rms_norm: bool = False,\n",
283
+ " initializer_cfg=None,\n",
284
+ " fused_add_norm=False,\n",
285
+ " residual_in_fp32=False,\n",
286
+ " device=None,\n",
287
+ " dtype=None,\n",
288
+ " ) -> None:\n",
289
+ " factory_kwargs = {\"device\": device, \"dtype\": dtype}\n",
290
+ " super().__init__()\n",
291
+ " self.residual_in_fp32 = residual_in_fp32\n",
292
+ "\n",
293
+ " self.embedding = nn.Linear(input_dim, d_model, **factory_kwargs)\n",
294
+ "\n",
295
+ " self.layers = nn.ModuleList(\n",
296
+ " [\n",
297
+ " create_block(\n",
298
+ " d_model,\n",
299
+ " ssm_cfg=ssm_cfg,\n",
300
+ " norm_epsilon=norm_epsilon,\n",
301
+ " residual_in_fp32=residual_in_fp32,\n",
302
+ " fused_add_norm=fused_add_norm,\n",
303
+ " layer_idx=i,\n",
304
+ " **factory_kwargs,\n",
305
+ " )\n",
306
+ " for i in range(n_layer)\n",
307
+ " ]\n",
308
+ " )\n",
309
+ "\n",
310
+ " self.norm_f = nn.LayerNorm(d_model, eps=norm_epsilon, **factory_kwargs)\n",
311
+ "\n",
312
+ " self.apply(\n",
313
+ " partial(\n",
314
+ " _init_weights,\n",
315
+ " n_layer=n_layer,\n",
316
+ " **(initializer_cfg if initializer_cfg is not None else {}),\n",
317
+ " )\n",
318
+ " )\n",
319
+ "\n",
320
+ " def forward(self, x, inference_params=None, channel_last=False):\n",
321
+ " if not channel_last:\n",
322
+ " x = x.transpose(1, 2)\n",
323
+ "\n",
324
+ " hidden_states = self.embedding(x)\n",
325
+ " residual = None\n",
326
+ " for layer in self.layers:\n",
327
+ " hidden_states, residual = layer(\n",
328
+ " hidden_states, residual, inference_params=inference_params\n",
329
+ " )\n",
330
+ "\n",
331
+ " residual = (hidden_states + residual) if residual is not None else hidden_states\n",
332
+ " hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))\n",
333
+ "\n",
334
+ " hidden_states = hidden_states\n",
335
+ "\n",
336
+ " return hidden_states\n",
337
+ "\n",
338
+ " def representation(\n",
339
+ " self,\n",
340
+ " x: torch.Tensor,\n",
341
+ " lengths: torch.Tensor,\n",
342
+ " channel_last: bool = False,\n",
343
+ " ) -> torch.Tensor:\n",
344
+ " \"\"\"Get global representation of input data.\n",
345
+ "\n",
346
+ " Args:\n",
347
+ " x: Data to embed. Has shape (B x C x L) if not channel_last.\n",
348
+ " lengths: Unpadded length of each data input.\n",
349
+ " channel_last: Expects input of shape (B x L x C).\n",
350
+ "\n",
351
+ " Returns:\n",
352
+ " Global representation vector of shape (B x H).\n",
353
+ " \"\"\"\n",
354
+ " out = self.forward(x, channel_last=channel_last)\n",
355
+ "\n",
356
+ " mean_tensor = mean_unpadded(out, lengths)\n",
357
+ " return mean_tensor\n",
358
+ "\n",
359
+ "\n",
360
+ "def mean_unpadded(x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:\n",
361
+ " \"\"\"Take mean of tensor across second dimension without padding.\n",
362
+ "\n",
363
+ " Args:\n",
364
+ " x: Tensor to take unpadded mean. Has shape (B x L x H).\n",
365
+ " lengths: Tensor of unpadded lengths. Has shape (B)\n",
366
+ "\n",
367
+ " Returns:\n",
368
+ " Mean tensor of shape (B x H).\n",
369
+ " \"\"\"\n",
370
+ " mask = torch.arange(x.size(1), device=x.device)[None, :] < lengths[:, None]\n",
371
+ " masked_tensor = x * mask.unsqueeze(-1)\n",
372
+ " sum_tensor = masked_tensor.sum(dim=1)\n",
373
+ " mean_tensor = sum_tensor / lengths.unsqueeze(-1).float()\n",
374
+ "\n",
375
+ " return mean_tensor\n",
376
+ "\n",
377
+ "\n",
378
+ "def _init_weights(\n",
379
+ " module,\n",
380
+ " n_layer,\n",
381
+ " initializer_range=0.02, # Now only used for embedding layer.\n",
382
+ " rescale_prenorm_residual=True,\n",
383
+ " n_residuals_per_layer=1, # Change to 2 if we have MLP\n",
384
+ "):\n",
385
+ " if isinstance(module, nn.Linear):\n",
386
+ " if module.bias is not None:\n",
387
+ " if not getattr(module.bias, \"_no_reinit\", False):\n",
388
+ " nn.init.zeros_(module.bias)\n",
389
+ " elif isinstance(module, nn.Embedding):\n",
390
+ " nn.init.normal_(module.weight, std=initializer_range)\n",
391
+ "\n",
392
+ " if rescale_prenorm_residual:\n",
393
+ " for name, p in module.named_parameters():\n",
394
+ " if name in [\"out_proj.weight\", \"fc2.weight\"]:\n",
395
+ " nn.init.kaiming_uniform_(p, a=math.sqrt(5))\n",
396
+ " with torch.no_grad():\n",
397
+ " p /= math.sqrt(n_residuals_per_layer * n_layer)\n",
398
+ "\n",
399
+ "def load_model(run_path: str, checkpoint_name: str) -> nn.Module:\n",
400
+ " \"\"\"Load trained model located at specified path.\n",
401
+ "\n",
402
+ " Args:\n",
403
+ " run_path: Path where run data is located.\n",
404
+ " checkpoint_name: Name of model checkpoint to load.\n",
405
+ "\n",
406
+ " Returns:\n",
407
+ " Model with loaded weights.\n",
408
+ " \"\"\"\n",
409
+ " model_config_path = os.path.join(run_path, \"model_config.json\")\n",
410
+ " data_config_path = os.path.join(run_path, \"data_config.json\")\n",
411
+ "\n",
412
+ " with open(model_config_path, \"r\") as f:\n",
413
+ " model_params = json.load(f)\n",
414
+ "\n",
415
+ " # TODO: Temp backwards compatibility\n",
416
+ " if \"n_tracks\" not in model_params:\n",
417
+ " with open(data_config_path, \"r\") as f:\n",
418
+ " data_params = json.load(f)\n",
419
+ " n_tracks = data_params[\"n_tracks\"]\n",
420
+ " else:\n",
421
+ " n_tracks = model_params[\"n_tracks\"]\n",
422
+ "\n",
423
+ " model_path = os.path.join(run_path, checkpoint_name)\n",
424
+ "\n",
425
+ " model = MixerModel(\n",
426
+ " d_model=model_params[\"ssm_model_dim\"],\n",
427
+ " n_layer=model_params[\"ssm_n_layers\"],\n",
428
+ " input_dim=n_tracks\n",
429
+ " )\n",
430
+ " checkpoint = torch.load(model_path, map_location=torch.device('cpu'))\n",
431
+ "\n",
432
+ " state_dict = {}\n",
433
+ " for k, v in checkpoint[\"state_dict\"].items():\n",
434
+ " if k.startswith(\"model\"):\n",
435
+ " state_dict[k.lstrip(\"model\")[1:]] = v\n",
436
+ "\n",
437
+ " model.load_state_dict(state_dict)\n",
438
+ " return model\n"
439
+ ]
440
+ },
441
+ {
442
+ "cell_type": "code",
443
+ "execution_count": 5,
444
+ "metadata": {},
445
+ "outputs": [
446
+ {
447
+ "name": "stdout",
448
+ "output_type": "stream",
449
+ "text": [
450
+ "MixerModel(\n",
451
+ " (embedding): Linear(in_features=6, out_features=512, bias=True)\n",
452
+ " (layers): ModuleList(\n",
453
+ " (0-5): 6 x Block(\n",
454
+ " (mixer): Mamba(\n",
455
+ " (in_proj): Linear(in_features=512, out_features=2048, bias=False)\n",
456
+ " (conv1d): Conv1d(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024)\n",
457
+ " (act): SiLU()\n",
458
+ " (x_proj): Linear(in_features=1024, out_features=64, bias=False)\n",
459
+ " (dt_proj): Linear(in_features=32, out_features=1024, bias=True)\n",
460
+ " (out_proj): Linear(in_features=1024, out_features=512, bias=False)\n",
461
+ " )\n",
462
+ " (norm): LayerNorm((512,), eps=1e-05, elementwise_affine=True)\n",
463
+ " )\n",
464
+ " )\n",
465
+ " (norm_f): LayerNorm((512,), eps=1e-05, elementwise_affine=True)\n",
466
+ ")\n"
467
+ ]
468
+ }
469
+ ],
470
+ "source": [
471
+ "run_name=\"ssm_6_512_lr0.001_wd5e-05_mask0.15_seed0_splice_all_basic_eutheria_gene-dict\"\n",
472
+ "checkpoint=\"epoch=22-step=20000.ckpt\"\n",
473
+ "model_repository=\"/scratch/hdd001/home/phil/msk_backup/runs/\"\n",
474
+ "model = load_model(f\"{model_repository}{run_name}\", checkpoint_name=checkpoint)\n",
475
+ "model = model.to(torch.device('cuda'))\n",
476
+ "print(model)"
477
+ ]
478
+ },
479
+ {
480
+ "cell_type": "code",
481
+ "execution_count": null,
482
+ "metadata": {},
483
+ "outputs": [],
484
+ "source": []
485
+ },
486
+ {
487
+ "cell_type": "code",
488
+ "execution_count": 30,
489
+ "metadata": {},
490
+ "outputs": [
491
+ {
492
+ "name": "stdout",
493
+ "output_type": "stream",
494
+ "text": [
495
+ "[<Transcript ENST00000380152.7 of BRCA2>, <Transcript ENST00000544455.5 of BRCA2>, <Transcript ENST00000530893.6 of BRCA2>, <Transcript ENST00000614259.1 of BRCA2>, <Transcript ENST00000528762.1 of BRCA2>, <Transcript ENST00000470094.1 of BRCA2>, <Transcript ENST00000533776.1 of BRCA2>]\n",
496
+ "[11986, 10984, 2011, 7950, 495, 842, 523]\n",
497
+ "torch.Size([1, 6, 11986])\n",
498
+ "torch.Size([1, 512])\n"
499
+ ]
500
+ }
501
+ ],
502
+ "source": [
503
+ "transcripts = find_transcript_by_gene_name(genome, 'BRCA2')\n",
504
+ "print(transcripts)\n",
505
+ "print([sum(len(e) for e in t.exons) for t in transcripts])\n",
506
+ "t = transcripts[0]\n",
507
+ "sixt = create_six_track_encoding(t)\n",
508
+ "sixt = torch.tensor(sixt, dtype=torch.float32)\n",
509
+ "sixt = sixt.unsqueeze(0)\n",
510
+ "print(sixt.shape)\n",
511
+ "sixt = sixt.to(device='cuda')\n",
512
+ "lengths = torch.tensor([sixt.shape[2]]).to(device='cuda')\n",
513
+ "embedding = model.representation(sixt, lengths)\n",
514
+ "print(embedding.shape)"
515
+ ]
516
+ },
517
+ {
518
+ "cell_type": "code",
519
+ "execution_count": 41,
520
+ "metadata": {},
521
+ "outputs": [
522
+ {
523
+ "name": "stdout",
524
+ "output_type": "stream",
525
+ "text": [
526
+ "MixerModel(\n",
527
+ " (embedding): Linear(in_features=4, out_features=256, bias=True)\n",
528
+ " (layers): ModuleList(\n",
529
+ " (0-2): 3 x Block(\n",
530
+ " (mixer): Mamba(\n",
531
+ " (in_proj): Linear(in_features=256, out_features=1024, bias=False)\n",
532
+ " (conv1d): Conv1d(512, 512, kernel_size=(4,), stride=(1,), padding=(3,), groups=512)\n",
533
+ " (act): SiLU()\n",
534
+ " (x_proj): Linear(in_features=512, out_features=48, bias=False)\n",
535
+ " (dt_proj): Linear(in_features=16, out_features=512, bias=True)\n",
536
+ " (out_proj): Linear(in_features=512, out_features=256, bias=False)\n",
537
+ " )\n",
538
+ " (norm): LayerNorm((256,), eps=1e-05, elementwise_affine=True)\n",
539
+ " )\n",
540
+ " )\n",
541
+ " (norm_f): LayerNorm((256,), eps=1e-05, elementwise_affine=True)\n",
542
+ ")\n"
543
+ ]
544
+ }
545
+ ],
546
+ "source": [
547
+ "run_name=\"ssm_4t_3_256_lr0.001_wd1e-05_mask0.15_splice_two_none\"\n",
548
+ "checkpoint=\"epoch=83-step=14000.ckpt\"\n",
549
+ "model_repository=\"/scratch/hdd001/home/phil/msk_backup/grid_runs/\"\n",
550
+ "model = load_model(f\"{model_repository}{run_name}\", checkpoint_name=checkpoint)\n",
551
+ "model = model.to(torch.device('cuda'))\n",
552
+ "print(model)"
553
+ ]
554
+ },
555
+ {
556
+ "cell_type": "code",
557
+ "execution_count": 43,
558
+ "metadata": {},
559
+ "outputs": [
560
+ {
561
+ "name": "stdout",
562
+ "output_type": "stream",
563
+ "text": [
564
+ "torch.Size([1, 4, 495])\n"
565
+ ]
566
+ },
567
+ {
568
+ "data": {
569
+ "text/plain": [
570
+ "torch.Size([1, 256])"
571
+ ]
572
+ },
573
+ "execution_count": 43,
574
+ "metadata": {},
575
+ "output_type": "execute_result"
576
+ }
577
+ ],
578
+ "source": [
579
+ "seq = \"\".join([genome.dna(exon) for exon in transcripts[4].exons])\n",
580
+ "one_hot = seq_to_oh(seq)\n",
581
+ "one_hot = one_hot.T\n",
582
+ "torch_one_hot = torch.tensor(one_hot, dtype=torch.float32)\n",
583
+ "torch_one_hot = torch_one_hot.unsqueeze(0)\n",
584
+ "print(torch_one_hot.shape)\n",
585
+ "torch_one_hot = torch_one_hot.to(device='cuda')\n",
586
+ "lengths = torch.tensor([torch_one_hot.shape[2]]).to(device='cuda')\n",
587
+ "model.representation(torch_one_hot, lengths).shape"
588
+ ]
589
+ },
590
+ {
591
+ "cell_type": "code",
592
+ "execution_count": null,
593
+ "metadata": {},
594
+ "outputs": [],
595
+ "source": []
596
+ }
597
+ ],
598
+ "metadata": {
599
+ "kernelspec": {
600
+ "display_name": "torch_rna",
601
+ "language": "python",
602
+ "name": "python3"
603
+ },
604
+ "language_info": {
605
+ "codemirror_mode": {
606
+ "name": "ipython",
607
+ "version": 3
608
+ },
609
+ "file_extension": ".py",
610
+ "mimetype": "text/x-python",
611
+ "name": "python",
612
+ "nbconvert_exporter": "python",
613
+ "pygments_lexer": "ipython3",
614
+ "version": "3.10.13"
615
+ }
616
+ },
617
+ "nbformat": 4,
618
+ "nbformat_minor": 2
619
+ }
src/model.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from functools import partial
3
+ import os
4
+ import json
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from mamba_ssm.modules.mamba_simple import Mamba, Block
9
+ from huggingface_hub import PyTorchModelHubMixin
10
+
11
+ def create_block(
12
+ d_model,
13
+ ssm_cfg=None,
14
+ norm_epsilon=1e-5,
15
+ residual_in_fp32=False,
16
+ fused_add_norm=False,
17
+ layer_idx=None,
18
+ device=None,
19
+ dtype=None,
20
+ ):
21
+ if ssm_cfg is None:
22
+ ssm_cfg = {}
23
+ factory_kwargs = {"device": device, "dtype": dtype}
24
+ mix_cls = partial(Mamba, layer_idx=layer_idx, **ssm_cfg, **factory_kwargs)
25
+ norm_cls = partial(nn.LayerNorm, eps=norm_epsilon, **factory_kwargs)
26
+ block = Block(
27
+ d_model,
28
+ mix_cls,
29
+ norm_cls=norm_cls,
30
+ fused_add_norm=fused_add_norm,
31
+ residual_in_fp32=residual_in_fp32,
32
+ )
33
+ block.layer_idx = layer_idx
34
+ return block
35
+
36
+
37
+ class MixerModel(
38
+ nn.Module,
39
+ PyTorchModelHubMixin,
40
+ ):
41
+
42
+ def __init__(
43
+ self,
44
+ d_model: int,
45
+ n_layer: int,
46
+ input_dim: int,
47
+ ssm_cfg=None,
48
+ norm_epsilon: float = 1e-5,
49
+ rms_norm: bool = False,
50
+ initializer_cfg=None,
51
+ fused_add_norm=False,
52
+ residual_in_fp32=False,
53
+ device=None,
54
+ dtype=None,
55
+ ) -> None:
56
+ factory_kwargs = {"device": device, "dtype": dtype}
57
+ super().__init__()
58
+ self.residual_in_fp32 = residual_in_fp32
59
+
60
+ self.embedding = nn.Linear(input_dim, d_model, **factory_kwargs)
61
+
62
+ self.layers = nn.ModuleList(
63
+ [
64
+ create_block(
65
+ d_model,
66
+ ssm_cfg=ssm_cfg,
67
+ norm_epsilon=norm_epsilon,
68
+ residual_in_fp32=residual_in_fp32,
69
+ fused_add_norm=fused_add_norm,
70
+ layer_idx=i,
71
+ **factory_kwargs,
72
+ )
73
+ for i in range(n_layer)
74
+ ]
75
+ )
76
+
77
+ self.norm_f = nn.LayerNorm(d_model, eps=norm_epsilon, **factory_kwargs)
78
+
79
+ self.apply(
80
+ partial(
81
+ _init_weights,
82
+ n_layer=n_layer,
83
+ **(initializer_cfg if initializer_cfg is not None else {}),
84
+ )
85
+ )
86
+
87
+ def forward(self, x, inference_params=None, channel_last=False):
88
+ if not channel_last:
89
+ x = x.transpose(1, 2)
90
+
91
+ hidden_states = self.embedding(x)
92
+ residual = None
93
+ for layer in self.layers:
94
+ hidden_states, residual = layer(
95
+ hidden_states, residual, inference_params=inference_params
96
+ )
97
+
98
+ residual = (hidden_states + residual) if residual is not None else hidden_states
99
+ hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
100
+
101
+ hidden_states = hidden_states
102
+
103
+ return hidden_states
104
+
105
+ def representation(
106
+ self,
107
+ x: torch.Tensor,
108
+ lengths: torch.Tensor,
109
+ channel_last: bool = False,
110
+ ) -> torch.Tensor:
111
+ """Get global representation of input data.
112
+
113
+ Args:
114
+ x: Data to embed. Has shape (B x C x L) if not channel_last.
115
+ lengths: Unpadded length of each data input.
116
+ channel_last: Expects input of shape (B x L x C).
117
+
118
+ Returns:
119
+ Global representation vector of shape (B x H).
120
+ """
121
+ out = self.forward(x, channel_last=channel_last)
122
+
123
+ mean_tensor = mean_unpadded(out, lengths)
124
+ return mean_tensor
125
+
126
+
127
+ def mean_unpadded(x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
128
+ """Take mean of tensor across second dimension without padding.
129
+
130
+ Args:
131
+ x: Tensor to take unpadded mean. Has shape (B x L x H).
132
+ lengths: Tensor of unpadded lengths. Has shape (B)
133
+
134
+ Returns:
135
+ Mean tensor of shape (B x H).
136
+ """
137
+ mask = torch.arange(x.size(1), device=x.device)[None, :] < lengths[:, None]
138
+ masked_tensor = x * mask.unsqueeze(-1)
139
+ sum_tensor = masked_tensor.sum(dim=1)
140
+ mean_tensor = sum_tensor / lengths.unsqueeze(-1).float()
141
+
142
+ return mean_tensor
143
+
144
+
145
+ def _init_weights(
146
+ module,
147
+ n_layer,
148
+ initializer_range=0.02, # Now only used for embedding layer.
149
+ rescale_prenorm_residual=True,
150
+ n_residuals_per_layer=1, # Change to 2 if we have MLP
151
+ ):
152
+ if isinstance(module, nn.Linear):
153
+ if module.bias is not None:
154
+ if not getattr(module.bias, "_no_reinit", False):
155
+ nn.init.zeros_(module.bias)
156
+ elif isinstance(module, nn.Embedding):
157
+ nn.init.normal_(module.weight, std=initializer_range)
158
+
159
+ if rescale_prenorm_residual:
160
+ for name, p in module.named_parameters():
161
+ if name in ["out_proj.weight", "fc2.weight"]:
162
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
163
+ with torch.no_grad():
164
+ p /= math.sqrt(n_residuals_per_layer * n_layer)
165
+
166
+ def load_model(run_path: str, checkpoint_name: str) -> nn.Module:
167
+ """Load trained model located at specified path.
168
+
169
+ Args:
170
+ run_path: Path where run data is located.
171
+ checkpoint_name: Name of model checkpoint to load.
172
+
173
+ Returns:
174
+ Model with loaded weights.
175
+ """
176
+ model_config_path = os.path.join(run_path, "model_config.json")
177
+ data_config_path = os.path.join(run_path, "data_config.json")
178
+
179
+ with open(model_config_path, "r") as f:
180
+ model_params = json.load(f)
181
+
182
+ # TODO: Temp backwards compatibility
183
+ if "n_tracks" not in model_params:
184
+ with open(data_config_path, "r") as f:
185
+ data_params = json.load(f)
186
+ n_tracks = data_params["n_tracks"]
187
+ else:
188
+ n_tracks = model_params["n_tracks"]
189
+
190
+ model_path = os.path.join(run_path, checkpoint_name)
191
+
192
+ model = MixerModel(
193
+ d_model=model_params["ssm_model_dim"],
194
+ n_layer=model_params["ssm_n_layers"],
195
+ input_dim=n_tracks
196
+ )
197
+ checkpoint = torch.load(model_path, map_location=torch.device('cpu'))
198
+
199
+ state_dict = {}
200
+ for k, v in checkpoint["state_dict"].items():
201
+ if k.startswith("model"):
202
+ state_dict[k.lstrip("model")[1:]] = v
203
+
204
+ model.load_state_dict(state_dict)
205
+ return model