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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags: []
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# Model Card for Model ID
|
| 7 |
+
|
| 8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
## Model Details
|
| 13 |
+
|
| 14 |
+
### Model Description
|
| 15 |
+
|
| 16 |
+
<!-- Provide a longer summary of what this model is. -->
|
| 17 |
+
|
| 18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
| 19 |
+
|
| 20 |
+
- **Developed by:** [More Information Needed]
|
| 21 |
+
- **Funded by [optional]:** [More Information Needed]
|
| 22 |
+
- **Shared by [optional]:** [More Information Needed]
|
| 23 |
+
- **Model type:** [More Information Needed]
|
| 24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
| 25 |
+
- **License:** [More Information Needed]
|
| 26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
| 27 |
+
|
| 28 |
+
### Model Sources [optional]
|
| 29 |
+
|
| 30 |
+
<!-- Provide the basic links for the model. -->
|
| 31 |
+
|
| 32 |
+
- **Repository:** [More Information Needed]
|
| 33 |
+
- **Paper [optional]:** [More Information Needed]
|
| 34 |
+
- **Demo [optional]:** [More Information Needed]
|
| 35 |
+
|
| 36 |
+
## Uses
|
| 37 |
+
|
| 38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
| 39 |
+
|
| 40 |
+
### Direct Use
|
| 41 |
+
|
| 42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
| 43 |
+
|
| 44 |
+
[More Information Needed]
|
| 45 |
+
|
| 46 |
+
### Downstream Use [optional]
|
| 47 |
+
|
| 48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
| 49 |
+
|
| 50 |
+
[More Information Needed]
|
| 51 |
+
|
| 52 |
+
### Out-of-Scope Use
|
| 53 |
+
|
| 54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
| 55 |
+
|
| 56 |
+
[More Information Needed]
|
| 57 |
+
|
| 58 |
+
## Bias, Risks, and Limitations
|
| 59 |
+
|
| 60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
| 61 |
+
|
| 62 |
+
[More Information Needed]
|
| 63 |
+
|
| 64 |
+
### Recommendations
|
| 65 |
+
|
| 66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 67 |
+
|
| 68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 69 |
+
|
| 70 |
+
## How to Get Started with the Model
|
| 71 |
+
|
| 72 |
+
Use the code below to get started with the model.
|
| 73 |
+
|
| 74 |
+
[More Information Needed]
|
| 75 |
+
|
| 76 |
+
## Training Details
|
| 77 |
+
|
| 78 |
+
### Training Data
|
| 79 |
+
|
| 80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
| 81 |
+
|
| 82 |
+
[More Information Needed]
|
| 83 |
+
|
| 84 |
+
### Training Procedure
|
| 85 |
+
|
| 86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 87 |
+
|
| 88 |
+
#### Preprocessing [optional]
|
| 89 |
+
|
| 90 |
+
[More Information Needed]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
#### Training Hyperparameters
|
| 94 |
+
|
| 95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 96 |
+
|
| 97 |
+
#### Speeds, Sizes, Times [optional]
|
| 98 |
+
|
| 99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 100 |
+
|
| 101 |
+
[More Information Needed]
|
| 102 |
+
|
| 103 |
+
## Evaluation
|
| 104 |
+
|
| 105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 106 |
+
|
| 107 |
+
### Testing Data, Factors & Metrics
|
| 108 |
+
|
| 109 |
+
#### Testing Data
|
| 110 |
+
|
| 111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
| 112 |
+
|
| 113 |
+
[More Information Needed]
|
| 114 |
+
|
| 115 |
+
#### Factors
|
| 116 |
+
|
| 117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 118 |
+
|
| 119 |
+
[More Information Needed]
|
| 120 |
+
|
| 121 |
+
#### Metrics
|
| 122 |
+
|
| 123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 124 |
+
|
| 125 |
+
[More Information Needed]
|
| 126 |
+
|
| 127 |
+
### Results
|
| 128 |
+
|
| 129 |
+
[More Information Needed]
|
| 130 |
+
|
| 131 |
+
#### Summary
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
## Model Examination [optional]
|
| 136 |
+
|
| 137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
| 138 |
+
|
| 139 |
+
[More Information Needed]
|
| 140 |
+
|
| 141 |
+
## Environmental Impact
|
| 142 |
+
|
| 143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 144 |
+
|
| 145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
| 146 |
+
|
| 147 |
+
- **Hardware Type:** [More Information Needed]
|
| 148 |
+
- **Hours used:** [More Information Needed]
|
| 149 |
+
- **Cloud Provider:** [More Information Needed]
|
| 150 |
+
- **Compute Region:** [More Information Needed]
|
| 151 |
+
- **Carbon Emitted:** [More Information Needed]
|
| 152 |
+
|
| 153 |
+
## Technical Specifications [optional]
|
| 154 |
+
|
| 155 |
+
### Model Architecture and Objective
|
| 156 |
+
|
| 157 |
+
[More Information Needed]
|
| 158 |
+
|
| 159 |
+
### Compute Infrastructure
|
| 160 |
+
|
| 161 |
+
[More Information Needed]
|
| 162 |
+
|
| 163 |
+
#### Hardware
|
| 164 |
+
|
| 165 |
+
[More Information Needed]
|
| 166 |
+
|
| 167 |
+
#### Software
|
| 168 |
+
|
| 169 |
+
[More Information Needed]
|
| 170 |
+
|
| 171 |
+
## Citation [optional]
|
| 172 |
+
|
| 173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 174 |
+
|
| 175 |
+
**BibTeX:**
|
| 176 |
+
|
| 177 |
+
[More Information Needed]
|
| 178 |
+
|
| 179 |
+
**APA:**
|
| 180 |
+
|
| 181 |
+
[More Information Needed]
|
| 182 |
+
|
| 183 |
+
## Glossary [optional]
|
| 184 |
+
|
| 185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 186 |
+
|
| 187 |
+
[More Information Needed]
|
| 188 |
+
|
| 189 |
+
## More Information [optional]
|
| 190 |
+
|
| 191 |
+
[More Information Needed]
|
| 192 |
+
|
| 193 |
+
## Model Card Authors [optional]
|
| 194 |
+
|
| 195 |
+
[More Information Needed]
|
| 196 |
+
|
| 197 |
+
## Model Card Contact
|
| 198 |
+
|
| 199 |
+
[More Information Needed]
|
config.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"MELPEncoderModel"
|
| 4 |
+
],
|
| 5 |
+
"attn_pooler_heads": 8,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_MELP_Encoder.MELPEncoderConfig",
|
| 8 |
+
"AutoModel": "modeling_MELP_Encoder.MELPEncoderModel"
|
| 9 |
+
},
|
| 10 |
+
"drop": 0.0,
|
| 11 |
+
"embed_dim_caption": 768,
|
| 12 |
+
"model_size": "small",
|
| 13 |
+
"model_type": "melp",
|
| 14 |
+
"n_queries_caption": 128,
|
| 15 |
+
"n_queries_contrast": 14,
|
| 16 |
+
"num_leads": 12,
|
| 17 |
+
"proj": "linear",
|
| 18 |
+
"proj_bias": false,
|
| 19 |
+
"shared_emb_dim": 256,
|
| 20 |
+
"torch_dtype": "bfloat16",
|
| 21 |
+
"transformers_version": "4.48.2",
|
| 22 |
+
"use_attentional_pool_caption": true,
|
| 23 |
+
"use_attentional_pool_contrast": true
|
| 24 |
+
}
|
configuration_MELP_Encoder.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class MELPEncoderConfig(PretrainedConfig):
|
| 5 |
+
model_type = "melp"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
model_size: str = "small", # small by default
|
| 10 |
+
shared_emb_dim: int = 256,
|
| 11 |
+
embed_dim_caption: int = 768,
|
| 12 |
+
use_attentional_pool_contrast: bool = True,
|
| 13 |
+
use_attentional_pool_caption: bool = True,
|
| 14 |
+
n_queries_contrast: int = 14,
|
| 15 |
+
n_queries_caption: int = 128,
|
| 16 |
+
attn_pooler_heads: int = 8,
|
| 17 |
+
proj: str = "linear",
|
| 18 |
+
drop: float = 0.,
|
| 19 |
+
proj_bias: bool = False,
|
| 20 |
+
num_leads: int = 12,
|
| 21 |
+
**kwargs
|
| 22 |
+
):
|
| 23 |
+
self.model_size = model_size
|
| 24 |
+
self.shared_emb_dim = shared_emb_dim
|
| 25 |
+
self.embed_dim_caption = embed_dim_caption
|
| 26 |
+
self.use_attentional_pool_contrast = use_attentional_pool_contrast
|
| 27 |
+
self.use_attentional_pool_caption = use_attentional_pool_caption
|
| 28 |
+
self.n_queries_contrast = n_queries_contrast
|
| 29 |
+
self.n_queries_caption = n_queries_caption
|
| 30 |
+
self.attn_pooler_heads = attn_pooler_heads
|
| 31 |
+
self.proj = proj
|
| 32 |
+
self.drop = drop
|
| 33 |
+
self.proj_bias = proj_bias
|
| 34 |
+
self.num_leads = num_leads
|
| 35 |
+
super().__init__(**kwargs)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ebd02d76e12c9740c32d596f3341fc04f4b6277d2bb7483302b47533dd00f10f
|
| 3 |
+
size 131213666
|
modeling_MELP_Encoder.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from collections import OrderedDict
|
| 6 |
+
from typing import Callable
|
| 7 |
+
from timm.models.layers import Mlp
|
| 8 |
+
from fairseq_signals_backbone.models.wav2vec2.wav2vec2_cmsc import Wav2Vec2CMSCModel, Wav2Vec2CMSCConfig
|
| 9 |
+
from lightning import LightningModule
|
| 10 |
+
from transformers import PreTrainedModel
|
| 11 |
+
from .configuration_MELP_Encoder import MELPEncoderConfig
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class LayerNorm(nn.LayerNorm):
|
| 15 |
+
"""Subclass torch's LayerNorm (with cast back to input dtype)."""
|
| 16 |
+
|
| 17 |
+
def forward(self, x: torch.Tensor):
|
| 18 |
+
orig_type = x.dtype
|
| 19 |
+
x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
|
| 20 |
+
return x.to(orig_type)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class AttentionalPooler(nn.Module):
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
d_model: int,
|
| 27 |
+
context_dim: int,
|
| 28 |
+
n_head: int = 8,
|
| 29 |
+
n_queries: int = 256,
|
| 30 |
+
norm_layer: Callable = LayerNorm,
|
| 31 |
+
):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.query = nn.Parameter(torch.randn(n_queries, d_model))
|
| 34 |
+
self.attn = nn.MultiheadAttention(d_model, n_head, kdim=context_dim, vdim=context_dim, batch_first=True)
|
| 35 |
+
self.ln_q = norm_layer(d_model)
|
| 36 |
+
self.ln_k = norm_layer(context_dim)
|
| 37 |
+
|
| 38 |
+
def forward(self, x: torch.Tensor):
|
| 39 |
+
N = x.shape[0]
|
| 40 |
+
x = self.ln_k(x)
|
| 41 |
+
q = self.ln_q(self.query)
|
| 42 |
+
out = self.attn(q.unsqueeze(0).expand(N, -1, -1), x, x, need_weights=False)[0]
|
| 43 |
+
return out
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def off_diagonal(x):
|
| 47 |
+
# return a flattened view of the off-diagonal elements of a square matrix
|
| 48 |
+
n, m = x.shape
|
| 49 |
+
assert n == m
|
| 50 |
+
return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ECGFMModel(LightningModule):
|
| 54 |
+
def __init__(self,
|
| 55 |
+
model_size: str = "small", # small by default
|
| 56 |
+
shared_emb_dim: int = 256,
|
| 57 |
+
embed_dim_caption: int = 768,
|
| 58 |
+
use_attentional_pool_contrast: bool = False,
|
| 59 |
+
use_attentional_pool_caption: bool = False,
|
| 60 |
+
n_queries_contrast: int = 10,
|
| 61 |
+
n_queries_caption: int = 128,
|
| 62 |
+
attn_pooler_heads: int = 8,
|
| 63 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
| 64 |
+
proj: str = "linear",
|
| 65 |
+
drop: float = 0.,
|
| 66 |
+
proj_bias: bool = False,
|
| 67 |
+
num_leads: int = 12,
|
| 68 |
+
softmax_temperature: float = 0.1,
|
| 69 |
+
lambd: float = 0.0051,
|
| 70 |
+
*args,
|
| 71 |
+
**kwargs):
|
| 72 |
+
|
| 73 |
+
"""" Implementation of ECG-FM model.
|
| 74 |
+
Using the Wave2Vec2 model as the ECG encoder: CNN + Transformer
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.save_hyperparameters()
|
| 79 |
+
self.shared_emb_dim = shared_emb_dim
|
| 80 |
+
self.num_leads = num_leads
|
| 81 |
+
self.temperature = softmax_temperature
|
| 82 |
+
|
| 83 |
+
if model_size == "small":
|
| 84 |
+
self.encoder_embed_dim = 768
|
| 85 |
+
self.encoder_attention_heads = 12
|
| 86 |
+
self.encoder_layers = 8
|
| 87 |
+
self.encoder_ffn_embed_dim = 3072
|
| 88 |
+
elif model_size == "base":
|
| 89 |
+
self.encoder_embed_dim = 768
|
| 90 |
+
self.encoder_attention_heads = 12
|
| 91 |
+
self.encoder_layers = 12
|
| 92 |
+
self.encoder_ffn_embed_dim = 3072
|
| 93 |
+
elif model_size == "large":
|
| 94 |
+
self.encoder_embed_dim = 1024
|
| 95 |
+
self.encoder_attention_heads = 16
|
| 96 |
+
self.encoder_layers = 24
|
| 97 |
+
self.encoder_ffn_embed_dim = 4096
|
| 98 |
+
else:
|
| 99 |
+
raise ValueError(f"Unknown model size: {model_size}")
|
| 100 |
+
print("Using ECG encoder with the following configuration:")
|
| 101 |
+
print(f"encoder_embed_dim: {self.encoder_embed_dim}")
|
| 102 |
+
print(f"encoder_attention_heads: {self.encoder_attention_heads}")
|
| 103 |
+
print(f"encoder_layers: {self.encoder_layers}")
|
| 104 |
+
print(f"encoder_ffn_embed_dim: {self.encoder_ffn_embed_dim}")
|
| 105 |
+
|
| 106 |
+
self.init_ecg_encoder()
|
| 107 |
+
|
| 108 |
+
self.embed_dim_caption = embed_dim_caption
|
| 109 |
+
self.use_attentional_pool_contrast = use_attentional_pool_contrast
|
| 110 |
+
self.use_attentional_pool_caption = use_attentional_pool_caption
|
| 111 |
+
|
| 112 |
+
head_layers = OrderedDict()
|
| 113 |
+
prev_chs = self.ecg_encoder.cfg.encoder_embed_dim
|
| 114 |
+
if use_attentional_pool_contrast:
|
| 115 |
+
scale = prev_chs ** -0.5
|
| 116 |
+
self.attn_pool_contrast = AttentionalPooler(
|
| 117 |
+
d_model=shared_emb_dim,
|
| 118 |
+
context_dim=prev_chs,
|
| 119 |
+
n_head=attn_pooler_heads,
|
| 120 |
+
n_queries=n_queries_contrast)
|
| 121 |
+
self.ln_contrast = norm_layer(shared_emb_dim)
|
| 122 |
+
self.proj_contrast = nn.Parameter(scale * torch.randn(shared_emb_dim, shared_emb_dim))
|
| 123 |
+
else:
|
| 124 |
+
assert proj, 'projection layer needed if not using attentional pooling.'
|
| 125 |
+
# NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used
|
| 126 |
+
if proj == 'linear':
|
| 127 |
+
head_layers['drop'] = nn.Dropout(drop)
|
| 128 |
+
head_layers['proj'] = nn.Linear(prev_chs, shared_emb_dim, bias=proj_bias)
|
| 129 |
+
elif proj == 'mlp':
|
| 130 |
+
head_layers['mlp'] = Mlp(prev_chs, 2 * shared_emb_dim, shared_emb_dim, drop=(drop, 0), bias=(True, proj_bias))
|
| 131 |
+
|
| 132 |
+
self.head = nn.Sequential(head_layers)
|
| 133 |
+
|
| 134 |
+
if use_attentional_pool_caption:
|
| 135 |
+
self.attn_pool_caption = AttentionalPooler(
|
| 136 |
+
d_model=embed_dim_caption, context_dim=prev_chs, n_head=attn_pooler_heads, n_queries=n_queries_caption)
|
| 137 |
+
self.ln_caption = norm_layer(embed_dim_caption)
|
| 138 |
+
|
| 139 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
|
| 140 |
+
|
| 141 |
+
self.bn = nn.BatchNorm1d(768, affine=False)
|
| 142 |
+
self.lambd = lambd
|
| 143 |
+
|
| 144 |
+
def init_ecg_encoder(self):
|
| 145 |
+
# Here we define Wav2Vec2CMSC model as the ECG encoder
|
| 146 |
+
cfg = Wav2Vec2CMSCConfig(
|
| 147 |
+
apply_mask = True,
|
| 148 |
+
mask_prob = 0.65,
|
| 149 |
+
quantize_targets = True,
|
| 150 |
+
final_dim = 256,
|
| 151 |
+
dropout_input = 0.1,
|
| 152 |
+
dropout_features = 0.1,
|
| 153 |
+
feature_grad_mult = 0.1,
|
| 154 |
+
encoder_embed_dim = self.encoder_embed_dim,
|
| 155 |
+
encoder_attention_heads = self.encoder_attention_heads,
|
| 156 |
+
in_d = 12,
|
| 157 |
+
encoder_layers = self.encoder_layers,
|
| 158 |
+
encoder_ffn_embed_dim = self.encoder_ffn_embed_dim
|
| 159 |
+
)
|
| 160 |
+
self.ecg_encoder = Wav2Vec2CMSCModel(cfg)
|
| 161 |
+
|
| 162 |
+
def _global_pool(self, x):
|
| 163 |
+
return torch.mean(x, dim=1)
|
| 164 |
+
|
| 165 |
+
@torch.no_grad()
|
| 166 |
+
# only used for finetune ...
|
| 167 |
+
def ext_ecg_emb(self, ecg, normalize=False):
|
| 168 |
+
assert ecg.dim() == 3, "Input tensor must be 3D"
|
| 169 |
+
|
| 170 |
+
ecg_out = self.ecg_encoder(source=ecg, mask=False, features_only=True)
|
| 171 |
+
features = ecg_out["x"]
|
| 172 |
+
|
| 173 |
+
if self.use_attentional_pool_contrast:
|
| 174 |
+
pooled = self.attn_pool_contrast(features)
|
| 175 |
+
pooled = self.ln_contrast(pooled)
|
| 176 |
+
pooled = torch.mean(pooled, dim=1)
|
| 177 |
+
else:
|
| 178 |
+
pooled = self._global_pool(features)
|
| 179 |
+
|
| 180 |
+
if normalize:
|
| 181 |
+
pooled = F.normalize(pooled, p=2, dim=-1)
|
| 182 |
+
|
| 183 |
+
return pooled
|
| 184 |
+
|
| 185 |
+
def _encode_ecg(self, ecg):
|
| 186 |
+
assert ecg.dim() == 3, "Input tensor must be 3D"
|
| 187 |
+
ecg_out = self.ecg_encoder(source=ecg, mask=False, features_only=True)
|
| 188 |
+
# features = self.ecg_encoder.get_features(net_output=ecg_out, aggregate=False)
|
| 189 |
+
# results after CNN-Transformer
|
| 190 |
+
features = ecg_out["x"]
|
| 191 |
+
|
| 192 |
+
if self.use_attentional_pool_contrast:
|
| 193 |
+
# hierarchical pooling
|
| 194 |
+
pooled = self.attn_pool_contrast(features)
|
| 195 |
+
pooled = self.ln_contrast(pooled)
|
| 196 |
+
pooled = pooled @ self.proj_contrast.unsqueeze(0)
|
| 197 |
+
pooled_beat = pooled.clone()
|
| 198 |
+
pooled = torch.mean(pooled, dim=1)
|
| 199 |
+
else:
|
| 200 |
+
pooled = self._global_pool(features)
|
| 201 |
+
pooled = self.head(features)
|
| 202 |
+
|
| 203 |
+
tokens = None
|
| 204 |
+
if self.use_attentional_pool_caption:
|
| 205 |
+
tokens = self.attn_pool_caption(features)
|
| 206 |
+
tokens = self.ln_caption(tokens)
|
| 207 |
+
else:
|
| 208 |
+
tokens = None
|
| 209 |
+
|
| 210 |
+
return pooled, pooled_beat, tokens
|
| 211 |
+
|
| 212 |
+
def encode_ecg(self, ecg):
|
| 213 |
+
ecg_latent, _, _ = self._encode_ecg(ecg)
|
| 214 |
+
return ecg_latent
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class MELPEncoderModel(PreTrainedModel):
|
| 218 |
+
config_class = MELPEncoderConfig
|
| 219 |
+
|
| 220 |
+
def __init__(self, config: MELPEncoderConfig):
|
| 221 |
+
super().__init__(config)
|
| 222 |
+
|
| 223 |
+
self.ecg_encoder = ECGFMModel(
|
| 224 |
+
model_size=config.model_size,
|
| 225 |
+
shared_emb_dim=config.shared_emb_dim,
|
| 226 |
+
embed_dim_caption=config.embed_dim_caption,
|
| 227 |
+
use_attentional_pool_contrast=config.use_attentional_pool_contrast,
|
| 228 |
+
use_attentional_pool_caption=config.use_attentional_pool_caption,
|
| 229 |
+
n_queries_contrast=config.n_queries_contrast,
|
| 230 |
+
n_queries_caption=config.n_queries_caption,
|
| 231 |
+
attn_pooler_heads=config.attn_pooler_heads,
|
| 232 |
+
proj=config.proj,
|
| 233 |
+
drop=config.drop,
|
| 234 |
+
proj_bias=config.proj_bias,
|
| 235 |
+
num_leads=config.num_leads,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def forward(self, tensor: torch.Tensor) -> torch.Tensor:
|
| 239 |
+
proj_ecg_emb, ecg_beat_emb, ecg_token_emb = self.ecg_encoder._encode_ecg(tensor)
|
| 240 |
+
|
| 241 |
+
return {
|
| 242 |
+
"proj_ecg_emb": proj_ecg_emb,
|
| 243 |
+
"ecg_beat_emb": ecg_beat_emb,
|
| 244 |
+
"ecg_token_emb": ecg_token_emb
|
| 245 |
+
}
|