Coverage for corgi/models.py: 94.57%
221 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
1"""Neural network models for classifying DNA sequences."""
3from typing import Callable, Optional
4import math
5import numpy as np
6import torch
7import torch.nn as nn
8import torch.nn.functional as F
9from torch import Tensor
10from polytorch import split_tensor, total_size
12from rich.console import Console
14console = Console()
17class PositionalEncoding(nn.Module):
18 """
19 Adapted from https://pytorch.org/tutorials/beginner/transformer_tutorial.html
20 """
22 def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
23 """Creates the sinusoidal positional encodings.
25 Args:
26 d_model (int): The size of the embeddings.
27 dropout (float): The dropout probability.
28 max_len (int): The maximum sequence length.
29 """
30 super().__init__()
31 self.dropout = nn.Dropout(p=dropout)
33 position = torch.arange(max_len).unsqueeze(1)
34 div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
35 pe = torch.zeros(max_len, 1, d_model)
36 pe[:, 0, 0::2] = torch.sin(position * div_term)
37 pe[:, 0, 1::2] = torch.cos(position * div_term)
38 self.register_buffer('pe', pe)
40 def forward(self, x: Tensor) -> Tensor:
41 """
42 Arguments:
43 x: Tensor, shape ``[seq_len, batch_size, embedding_dim]``
44 """
45 x = x + self.pe[: x.size(0)]
46 return self.dropout(x)
49def conv3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv1d:
50 """convolution of width 3 with padding"""
51 return nn.Conv1d(
52 in_planes,
53 out_planes,
54 kernel_size=3,
55 stride=stride,
56 padding=dilation,
57 groups=groups,
58 bias=False,
59 dilation=dilation,
60 )
63class ResidualBlock1D(nn.Module):
64 """Adapted from https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py"""
66 def __init__(
67 self,
68 inplanes: int,
69 planes: int,
70 stride: int = 1,
71 downsample: Optional[nn.Module] = None,
72 norm_layer: Optional[Callable[..., nn.Module]] = None,
73 ) -> None:
74 """Creates the layers of the block.
76 Args:
77 inplanes (int): The number of input channels.
78 planes (int): The number of output channels.
79 stride (int): The stride of the first convolution. If not 1, then the identity is downsampled to match.
80 downsample (nn.Module | None): A module to downsample the identity.
81 norm_layer: The normalization layer class. Defaults to BatchNorm1d.
82 """
83 super().__init__()
84 if norm_layer is None:
85 norm_layer = nn.BatchNorm1d
87 if stride != 1:
88 downsample = nn.Sequential(
89 nn.Conv1d(inplanes, planes, kernel_size=1, stride=stride, bias=False),
90 norm_layer(planes),
91 )
93 # Both self.conv1 and self.downsample layers downsample the input when stride != 1
94 self.conv1 = conv3(inplanes, planes, stride)
95 self.bn1 = norm_layer(planes)
96 self.relu = nn.ReLU(inplace=True)
97 self.conv2 = conv3(planes, planes)
98 self.bn2 = norm_layer(planes)
99 self.downsample = downsample
100 self.stride = stride
102 def forward(self, x: Tensor) -> Tensor:
103 """Applies two convolutions and adds the (possibly downsampled) input."""
104 identity = x
106 out = self.conv1(x)
107 out = self.bn1(out)
108 out = self.relu(out)
110 out = self.conv2(out)
111 out = self.bn2(out)
113 if self.downsample is not None:
114 identity = self.downsample(x)
116 out += identity
117 out = self.relu(out)
119 return out
122class ConvRecurrantClassifier(nn.Module):
123 """A CNN followed by an optional bidirectional LSTM which classifies a sequence into a number of classes.
125 The input is a tensor of nucleotide indices (N, A, C, G, T) of shape (batch, sequence length).
126 """
128 def __init__(
129 self,
130 num_classes,
131 embedding_dim: int = 8,
132 filters: int = 256,
133 cnn_layers: int = 6,
134 kernel_size_cnn: int = 9,
135 lstm_dims: int = 256,
136 final_layer_dims: int = 0, # If this is zero then it isn't used.
137 dropout: float = 0.5,
138 kernel_size_maxpool: int = 2,
139 residual_blocks: bool = False,
140 final_bias: bool = True,
141 multi_kernel_sizes: bool = True,
142 ):
143 """Creates the layers of the classifier.
145 Args:
146 num_classes (int): The number of output classes.
147 embedding_dim (int): The size of the nucleotide embeddings.
148 filters (int): The number of filters in each convolution.
149 cnn_layers (int): The number of convolutions when `multi_kernel_sizes` is True.
150 kernel_size_cnn (int): The kernel size of the convolution when `multi_kernel_sizes` is False.
151 lstm_dims (int): The hidden size of the LSTM. If zero, then no LSTM is used.
152 final_layer_dims (int): The size of an extra linear layer before the output. If zero, it is not used.
153 dropout (float): The dropout probability.
154 kernel_size_maxpool (int): The size of the max pooling.
155 residual_blocks (bool): Whether to use residual blocks instead of a single convolution.
156 final_bias (bool): Whether the output layer has a bias.
157 multi_kernel_sizes (bool): Whether to use parallel convolutions with increasing kernel sizes.
158 """
159 super().__init__()
161 num_embeddings = 5 # i.e. the size of the vocab which is N, A, C, G, T
163 self.num_classes = num_classes
164 self.num_embeddings = num_embeddings
166 ########################
167 ## Embedding
168 ########################
169 self.embedding_dim = embedding_dim
170 self.embed = nn.Embedding(
171 num_embeddings=num_embeddings,
172 embedding_dim=embedding_dim,
173 )
174 self.dropout = nn.Dropout(dropout)
176 ########################
177 ## Convolutional Layer
178 ########################
180 self.multi_kernel_sizes = multi_kernel_sizes
181 if multi_kernel_sizes:
182 kernel_size = 5
183 convolutions = []
184 for _ in range(cnn_layers):
185 convolutions.append(
186 nn.Conv1d(in_channels=embedding_dim, out_channels=filters, kernel_size=kernel_size, padding='same')
187 )
188 kernel_size += 2
190 self.convolutions = nn.ModuleList(convolutions)
191 self.pool = nn.MaxPool1d(kernel_size=kernel_size_maxpool)
192 current_dims = filters * cnn_layers
193 else:
194 self.filters = filters
195 self.residual_blocks = residual_blocks
196 self.intermediate_filters = 128
197 if residual_blocks:
198 self.cnn_layers = nn.Sequential(
199 ResidualBlock1D(embedding_dim, embedding_dim),
200 ResidualBlock1D(embedding_dim, self.intermediate_filters, 2),
201 ResidualBlock1D(self.intermediate_filters, self.intermediate_filters),
202 ResidualBlock1D(self.intermediate_filters, filters, 2),
203 ResidualBlock1D(filters, filters),
204 )
205 else:
206 self.kernel_size_cnn = kernel_size_cnn
207 self.cnn_layers = nn.Sequential(
208 nn.Conv1d(in_channels=embedding_dim, out_channels=filters, kernel_size=kernel_size_cnn),
209 nn.MaxPool1d(kernel_size=kernel_size_maxpool),
210 )
211 current_dims = filters
213 ########################
214 ## Recurrent Layer
215 ########################
216 self.lstm_dims = lstm_dims
217 if lstm_dims:
218 self.bi_lstm = nn.LSTM(
219 input_size=current_dims, # Is this dimension? - this should receive output from maxpool
220 hidden_size=lstm_dims,
221 bidirectional=True,
222 bias=True,
223 batch_first=True,
224 dropout=dropout,
225 )
226 current_dims = lstm_dims * 2
228 if final_layer_dims:
229 self.fc1 = nn.Linear(
230 in_features=current_dims,
231 out_features=final_layer_dims,
232 )
233 current_dims = final_layer_dims
235 #################################
236 ## Linear Layer(s) to Predictions
237 #################################
238 self.final_layer_dims = final_layer_dims
239 self.logits = nn.Linear(
240 in_features=current_dims,
241 out_features=self.num_classes,
242 bias=final_bias,
243 )
245 def forward(self, x):
246 ########################
247 ## Embedding
248 ########################
249 # Cast as pytorch tensor
250 # x = Tensor(x)
252 # Convert to int because it may be simply a byte
253 """Returns the logits for a batch of sequences.
255 Args:
256 x (Tensor): Nucleotide indices of shape (batch, sequence length).
258 Returns:
259 Tensor: Logits of shape (batch, num_classes).
260 """
261 x = x.int()
262 x = self.embed(x)
264 ########################
265 ## Convolutional Layer
266 ########################
267 # Transpose seq_len with embedding dims to suit convention of pytorch CNNs (batch_size, input_size, seq_len)
268 x = x.transpose(1, 2)
270 if self.multi_kernel_sizes:
271 conv_results = [conv(x) for conv in self.convolutions]
272 x = torch.cat(conv_results, dim=-2)
274 x = self.pool(x)
275 else:
276 x = self.cnn_layers(x)
278 # Current shape: batch, filters, seq_len
279 # With batch_first=True, LSTM expects shape: batch, seq, feature
280 x = x.transpose(2, 1)
282 ########################
283 ## Recurrent Layer
284 ########################
286 # BiLSTM
287 if self.lstm_dims:
288 output, (h_n, c_n) = self.bi_lstm(x)
289 # h_n of shape (num_layers * num_directions, batch, hidden_size)
290 # We are using a single layer with 2 directions so the two output vectors are
291 # [0,:,:] and [1,:,:]
292 # [0,:,:] -> considers the first index from the first dimension
293 x = torch.cat((h_n[0, :, :], h_n[1, :, :]), dim=-1)
294 else:
295 # if there is no recurrent layer then simply sum over sequence dimension
296 x = torch.sum(x, dim=1)
298 #################################
299 ## Linear Layer(s) to Predictions
300 #################################
301 # Ignore if the final_layer_dims is empty
302 if self.final_layer_dims:
303 x = F.relu(self.fc1(x))
304 # Get logits. The cross-entropy loss optimisation function just takes in the logits and automatically does a softmax
305 out = self.logits(x)
307 return out
310class ConvClassifier(nn.Module):
311 """A convolutional classifier with an optional transformer encoder or bidirectional LSTM.
313 The output is split according to `output_types` (e.g. for hierarchical classification).
314 """
316 def __init__(
317 self,
318 embedding_dim=8,
319 cnn_layers=6,
320 output_types=None,
321 cnn_dims_start=64,
322 kernel_size_maxpool=2,
323 return_embeddings: bool = False,
324 num_embeddings=5, # i.e. the size of the vocab which is N, A, C, G, T
325 kernel_size=3,
326 factor=2,
327 padding="same",
328 padding_mode="zeros",
329 dropout=0.5,
330 final_bias=True,
331 lstm_dims: int = 0,
332 penultimate_dims: int = 1028,
333 include_length: bool = False,
334 length_scaling: float = 3_000.0,
335 transformer_heads: int = 8,
336 transformer_layers: int = 6,
337 ):
338 """Creates the layers of the classifier.
340 Args:
341 embedding_dim (int): The size of the nucleotide embeddings.
342 cnn_layers (int): The number of convolutional layers.
343 output_types: The output data types, which determine the size and splitting of the output.
344 cnn_dims_start (int): The number of filters in the first convolution.
345 kernel_size_maxpool (int): The size of the max pooling after each convolution.
346 return_embeddings (bool): Whether the forward pass also returns the penultimate layer's activations.
347 num_embeddings (int): The vocabulary size (N, A, C, G, T).
348 kernel_size (int): The kernel size of the convolutions.
349 factor (float): The factor by which the number of filters grows with each layer.
350 padding (str): The padding of the convolutions.
351 padding_mode (str): The padding mode of the convolutions.
352 dropout (float): The dropout probability.
353 final_bias (bool): Whether the output layer has a bias.
354 lstm_dims (int): The hidden size of the LSTM. If zero, then the sequence is averaged instead.
355 penultimate_dims (int): The size of the penultimate linear layer.
356 include_length (bool): Whether to give the (scaled) sequence length as an extra feature.
357 length_scaling (float): The divisor used to scale the sequence length.
358 transformer_heads (int): The number of attention heads in the transformer.
359 transformer_layers (int): The number of transformer layers. If zero, then no transformer is used.
360 """
361 super().__init__()
363 self.embedding_dim = embedding_dim
364 self.cnn_layers = cnn_layers
365 self.output_types = output_types
366 self.kernel_size_maxpool = kernel_size_maxpool
367 self.return_embeddings = return_embeddings
369 self.num_embeddings = num_embeddings
370 self.kernel_size = kernel_size
371 self.factor = factor
372 self.dropout = dropout
373 self.include_length = include_length
374 self.length_scaling = length_scaling
375 self.transformer_layers = transformer_layers
376 self.transformer_heads = transformer_heads
378 self.embedding = nn.Embedding(
379 num_embeddings=num_embeddings,
380 embedding_dim=embedding_dim,
381 )
383 in_channels = embedding_dim
384 out_channels = cnn_dims_start
385 conv_layers = []
386 for layer_index in range(cnn_layers):
387 conv_layers += [
388 nn.Conv1d(
389 in_channels=in_channels,
390 out_channels=out_channels,
391 kernel_size=kernel_size,
392 padding=padding,
393 padding_mode=padding_mode,
394 ),
395 nn.ReLU(),
396 nn.Dropout(dropout),
397 nn.MaxPool1d(kernel_size_maxpool),
398 # nn.Conv1d(
399 # in_channels=out_channels,
400 # out_channels=out_channels,
401 # kernel_size=kernel_size,
402 # stride=kernel_size_maxpool,
403 # ),
404 ]
405 in_channels = out_channels
406 out_channels = int(out_channels * factor)
408 self.conv = nn.Sequential(*conv_layers)
410 if self.transformer_layers:
411 self.positional_encoding = PositionalEncoding(d_model=in_channels)
412 encoder_layer = nn.TransformerEncoderLayer(
413 d_model=in_channels, nhead=self.transformer_heads, batch_first=True
414 )
415 self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=self.transformer_layers)
416 else:
417 self.transformer_encoder = None
419 self.lstm_dims = lstm_dims
420 if lstm_dims:
421 self.bi_lstm = nn.LSTM(
422 input_size=in_channels, # Is this dimension? - this should receive output from maxpool
423 hidden_size=lstm_dims,
424 bidirectional=True,
425 bias=True,
426 batch_first=True,
427 dropout=dropout,
428 )
429 current_dims = lstm_dims * 2
430 else:
431 current_dims = in_channels
433 # self.average_pool = nn.AdaptiveAvgPool1d(1)
435 current_dims += int(include_length)
436 self.penultimate = nn.Linear(in_features=current_dims, out_features=penultimate_dims, bias=True)
437 self.final = nn.Linear(
438 in_features=penultimate_dims, out_features=total_size(self.output_types), bias=final_bias
439 )
441 def forward(self, x):
442 # Convert to int because it may be simply a byte
443 """Returns the predictions for a batch of sequences.
445 Args:
446 x (Tensor): Nucleotide indices of shape (batch, sequence length).
448 Returns:
449 The predictions split by output type. If `return_embeddings` is set, then the penultimate layer's
450 activations are also returned.
451 """
452 x = x.int()
453 length = x.shape[-1]
454 x = self.embedding(x)
456 # Transpose seq_len with embedding dims to suit convention of pytorch CNNs (batch_size, input_size, seq_len)
457 x = x.transpose(1, 2)
458 x = self.conv(x)
460 if hasattr(self, 'transformer_encoder') and self.transformer_encoder:
461 x = x.transpose(2, 1)
462 x = self.positional_encoding(x)
463 x = self.transformer_encoder(x)
464 x = x.transpose(1, 2)
466 if self.lstm_dims:
467 x = x.transpose(2, 1)
468 output, (h_n, c_n) = self.bi_lstm(x)
469 # h_n of shape (num_layers * num_directions, batch, hidden_size)
470 # We are using a single layer with 2 directions so the two output vectors are
471 # [0,:,:] and [1,:,:]
472 # [0,:,:] -> considers the first index from the first dimension
473 x = torch.cat((h_n[0, :, :], h_n[1, :, :]), dim=-1)
474 # elif hasattr(x, 'average_pool'):
475 # x = self.average_pool(x)
476 # x = torch.flatten(x, 1)
477 else:
478 x = torch.mean(x, axis=-1)
479 # x = torch.sum(x, axis=-1)
481 if getattr(self, 'include_length', False):
482 length_tensor = torch.full((x.shape[0], 1), length / self.length_scaling, device=x.device)
483 x = torch.cat([x, length_tensor], dim=1)
485 penultimate_result = self.penultimate(x)
486 predictions = self.final(F.relu(penultimate_result))
488 split_predictions = split_tensor(predictions, self.output_types, feature_axis=1)
490 if getattr(self, "return_embeddings", False):
491 return split_predictions, penultimate_result
493 return split_predictions
495 def output_types_match(self, output_types) -> bool:
496 """Returns whether the final layer of this model is already suitable for the given output types.
498 This is the case when the number of outputs is the same and each output type is equivalent to the
499 corresponding current one. Hierarchical outputs are equivalent if their classification trees have
500 the same nodes (by name and ancestry) in the same order, because the final layer's weights are
501 specific to each node.
503 Args:
504 output_types: The output types to compare to the current output types.
505 """
506 current = self.output_types
507 if current is None or output_types is None:
508 return False
510 if len(current) != len(output_types) or total_size(current) != total_size(output_types):
511 return False
513 if self.final.out_features != total_size(output_types):
514 return False
516 return all(
517 type(old) is type(new) and _output_type_signature(old) == _output_type_signature(new)
518 for old, new in zip(current, output_types)
519 )
521 def replace_output_types(self, output_types, final_bias: bool = None) -> None:
522 """Replaces the final layer so that the model has outputs for new output types.
524 Args:
525 output_types: The new output types.
526 final_bias (bool | None): Whether the new final layer has a bias. If None, then it matches the current layer.
527 """
528 device = next(self.parameters()).device
529 self.output_types = output_types
530 penultimate_dims = self.penultimate.out_features
531 if final_bias is None:
532 final_bias = self.final.bias is not None
534 self.final = nn.Linear(
535 in_features=penultimate_dims, out_features=total_size(self.output_types), bias=final_bias, device=device
536 )
539def _output_type_signature(output_type):
540 """Returns a value which is equal for output types that are equivalent.
542 For types with a classification tree (a `root`), this is the path of names to each node in the tree
543 in pre-order. Otherwise it is the output type itself.
544 """
545 root = getattr(output_type, "root", None)
546 if root is None:
547 return output_type
548 return tuple(tuple(str(n.name) for n in (node, *node.ancestors)) for node in root.pre_order_iter())
551class SequentialDebug(nn.Sequential):
552 """A sequential module which prints the shapes and multiply-accumulate operations of each layer."""
554 def forward(self, input):
555 """Runs each module, printing its shape and the cumulative MACs. Requires `thop`."""
556 macs_cummulative = 0
557 from thop import profile
559 console.print(f"Input shape {input.shape}")
560 for module in self:
561 console.print(f"Module: {module} ({type(module)})")
562 macs, _ = profile(module, inputs=(input,))
563 macs_cummulative += int(macs)
564 console.print(f"MACs: {int(macs)} (cummulative {macs_cummulative})")
566 input = module(input)
567 console.print(f"Output shape: {input.shape}")
569 return input
572class ConvProcessor(nn.Sequential):
573 """A stack of convolution, ReLU, dropout and max pooling layers which increase the number of channels."""
575 def __init__(
576 self,
577 in_channels=8,
578 cnn_layers=6,
579 cnn_dims_start=64,
580 kernel_size_maxpool=2,
581 kernel_size=3,
582 factor=2,
583 dropout=0.5,
584 padding="same",
585 padding_mode="zeros",
586 ):
587 """Creates the layers.
589 Args:
590 in_channels (int): The number of input channels.
591 cnn_layers (int): The number of convolutional layers.
592 cnn_dims_start (int): The number of filters in the first convolution.
593 kernel_size_maxpool (int): The size of the max pooling after each convolution.
594 kernel_size (int): The kernel size of the convolutions.
595 factor (float): The factor by which the number of filters grows with each layer.
596 dropout (float): The dropout probability.
597 padding (str): The padding of the convolutions.
598 padding_mode (str): The padding mode of the convolutions.
599 """
600 out_channels = cnn_dims_start
601 conv_layers = []
602 for layer_index in range(cnn_layers):
603 conv_layers += [
604 nn.Conv1d(
605 in_channels=in_channels,
606 out_channels=out_channels,
607 kernel_size=kernel_size,
608 padding=padding,
609 padding_mode=padding_mode,
610 ),
611 nn.ReLU(),
612 nn.Dropout(dropout),
613 nn.MaxPool1d(kernel_size_maxpool),
614 # nn.Conv1d(
615 # in_channels=out_channels,
616 # out_channels=out_channels,
617 # kernel_size=kernel_size,
618 # stride=kernel_size_maxpool,
619 # ),
620 ]
621 in_channels = out_channels
622 out_channels = int(out_channels * factor)
624 super().__init__(*conv_layers)
627def calc_cnn_dims_start(
628 macc,
629 seq_len: int,
630 embedding_dim: int,
631 cnn_layers: int,
632 kernel_size: int,
633 factor: float,
634 penultimate_dims: int,
635 num_classes: int,
636):
637 r"""
638 Solving equation M = s k e c + \sum_{l=1}^{L-1} \frac{s}{2^{l} } k c^2 f^{2l-1} + c f^{L-1} p + p o
639 for c.
641 Args:
642 macc_per_base (int): the number of multiply-accumulate operations per base pair in the sequence.
643 embedding_dim (int): The size of the embedding.
644 cnn_layers (int): The number of CNN layers.
645 kernel_size (int): The size of the kernel in the CNN
646 factor (float): The multiplying factor for the CNN output layers.
647 """
648 b = kernel_size * embedding_dim * seq_len + factor ** (cnn_layers - 1) * penultimate_dims
649 c = penultimate_dims * num_classes - macc
651 if cnn_layers == 1:
652 cnn_dims_start = -c / b
653 else:
654 a = 0.0
655 for layer_index in range(1, cnn_layers):
656 a += seq_len * kernel_size * (0.5**layer_index) * (factor ** (2 * layer_index - 1))
658 cnn_dims_start = (-b + np.sqrt(b**2 - 4 * a * c)) / (2 * a)
660 return int(cnn_dims_start + 0.5)