Interpretable Pre-Trained Transformers for Heart Time-Series Data

## Abstract

Abstract Decoder-only transformers are the backbone of the popular generative pre-trained transformer (GPT) series of large language models. In this work, we employ this framework to the analysis of clinical heart time-series data, to create two pre-trained general purpose cardiac models, termed PPG-PT and ECG-PT. We place a special emphasis on making both such pre-trained models fully interpretable. This is achieved firstly through aggregate attention maps which show that, in order to make predictions, the model focuses on similar points in previous cardiac cycles and gradually broadens its attention in deeper layers. Next, we show that tokens with the same value, which occur at different distinct points in the electrocardiography (ECG) and photoplethysmography (PPG) cycle, form separate clusters in high dimensional space. The clusters form according to phase, as the tokens propagate through the transformer blocks. Finally, we highlight that individual attention heads respond to specific physiologically relevent features, such as the dicrotic notch in PPG and the P-wave in ECG. It is also demonstrated that these pre-trained models are straightforward to fine-tune for tasks such as classification of atrial fibrillation (AF), and beat detection in photoplethysmography. For the example of AF, the fine-tuning took 11 minutes of computer time, and achieved the respective leave-one-subject-out AUCs of 0.99 and 0.93 for ECG and PPG within the MIMIC Perform AF dataset. In addition, the fine-tuned beat detector achieved a state-of-the-art F1 score of 98%, as well as uniquely providing a beat confidence level which acts as a signal quality estimator. Importantly, the fine-tuned models for AF screening are also fully explainable, with attention shifting to regions in the context that are strongly indicative of atrial fibrillation.

## 1 Introduction

The generative pretrained transformer (GPT) [] [] is a large language model (LLM) which forms the basis of the chat-GPT models []. It consists of layers of decoder-only transformers [] that are trained to predict the next token (words, sub-words, or characters), using all previous tokens provided to the model as context. The attention mechanism is masked, such that tokens inputted to the model can only communicate with past tokens and thus a context window of length $N$ effectively provides $N$ different training examples, whereby the model tries to predict the same context window shifted by one token into the future. The whole premise of the GPT model is that in order to accurately predict the next token, across a large and diverse array of texts, a model must gain an efficient and general comprehension of these texts. Given that language is a way that we summarise and communicate the world around us, this efficient and general understanding allows the pre-trained model to be fine tuned for a myriad of complex tasks [].

The assertion of this paper is that we can leverage the GPT mechanism, i.e. stacks of decoder-only transformers trained to predict the next token, and develop it for physiological time series. Our hypothesis is that if our models gain an efficient and general understanding of these physiological time series, such as photoplethysmography (PPG) or electrocardiography (ECG), then these large models will be simple to fine-tune for downstream tasks such as the classification of heart conditions. The ECG signal refers to the monitoring of the electrical activity of the heart through external non-invasive electrodes that measure the potential difference across the heart [][]. In this work, we use only single-lead ECG. The photoplethysmography (PPG) signal refers to the non-invasive measurement of blood volume []. The PPG operates by shining light through tissue with an LED, which is absorbed by the blood, and then either measuring the transmitted light or reflected light with a corresponding photo-diode. The PPG is thus able to measure changes in blood volume related to pulse and even breathing []. In PPG, for example, in order to accurately predict the next time point the model must gain knowledge on several underlying phenomena, such as the subtle changes in heart rate and pulse amplitude due to breathing and blood pressure. This leads us to hypothesise that a large model that is good at predicting the next token of PPG will be straightforward to fine-tune for specific PPG related tasks.

As GPT and other large language models are rapidly gaining capability, and thus decision making power, it is of crucial importance that LLMs do not remain black boxes. Indeed, the black box nature of deep learning models is an immediate problem in healthcare, where decisions made by artificial intelligence have the potential to directly impact our health and even our lives. It is therefore critical that models are developed which give clear insights and explanations into why decisions are made. A natural way to interpret the operation of transformer-based LLMs is to take a close examination of the attention weights of the individual transformer blocks. This attention mechanism provides information on which tokens a model looks at in order to make a decision, and thus it is common to use heat maps that visualise this attention as an avenue for interpretability []. Language is complex, and there are often several pathways to achieve the same result. In many instances this makes it difficult to decipher attention, which means that in the context of LLMs attention cannot always be relied upon for explainability []. However, both the PPG and ECG signals are far less complicated than language, and downstream tasks, such as screening for heart conditions, offer more constraints on the possible pathways to achieve a correct diagnosis. It is therefore a core focus of this paper not just to provide generalised transformer models for PPG and ECG related tasks, but to provide models that are fully interpretable so that they may be safely used in a healthcare setting.

To this end, we firstly develop two pre-trained decoder-only time series transformer models for use with heart signals, namely PPG-PT and ECG-PT. The pre-trained models and example code are provided at [https://github.com/harryjdavies/HeartGPT](https://github.com/harryjdavies/HeartGPT). Furthermore, we demonstrate that, through i) aggregate attention of different transformer layers, ii) changes in cosine similarity between core PPG and ECG features in the embedding space upon propagation through transformer layers, and iii) the analysis of the attention weights of individual attention heads in the final transformer block, that both the PPG-PT and ECG-PT models behave exactly as expected for the task of predicting the next time series point in PPG and ECG. Finally, we demonstrate how these models can be fine-tuned to detect atrial fibrillation (AF), a common type of abnormal heart rhythm. The changes in attention from the task of next token prediction to the task of classification of AF can be used to further explain the reason why a model has made a decision. This makes it possible to provide clinicians with both accurate classification and the reasoning behind it, thus allowing for a conjoint operation between a clinician and AI in diagnostics and treatment.

## 2 The Pre-Trained Transformer Models

### 2.1 Tokenisation and Embedding

Both the ECG and PPG signals are periodic, and in most applications we can ignore any mean offset. With this in mind, we can divide each PPG and ECG signal into a range of finite tokens, forming a vocabulary from which each signal can be constructed. To tokenise the PPG signals, they were resampled to 50Hz and each 10 second context window (500 samples) was scaled to between 100 and 0. The resulting signal was then rounded to give integer values, yielding a total vocabulary size of 101 tokens. The 10 second context window was chosen so as to be long enough to preserve low frequency variations in the PPG (such as respiratory variations), but not too long as to run into memory issues when training. For the ECG, the process was similar, apart from resampling to 100Hz and thus using a context window that corresponded to 5 seconds instead of 10 seconds. A higher sampling frequency was required in the ECG tokenisation in order to preserve the high frequency components of the QRS complex. In GPT models, common sequences of token values can be combined during tokenisation, in order to allow for a longer context length for the same number of tokens. This method of tokenisation was not implemented in the PPG-PT and ECG-PT models, as further extending the length of the context window was not necessary.

Upon tokenisation, each token was embedded with a token embedding table and a position embedding table. The dimensions of the token embedding were the vocabulary size times the embedding dimension ($d_{model}$), giving a $d_{model}$ dimensional vector for every possible token in the vocabulary. The dimensions of the position embedding table were the maximum context length times $d_{model}$, giving a $d_{model}$-dimensional vector for every possible position in the context window. In our models, both of these embeddings are learnt as the model trains. In the original transformer paper, the positional embeddings utilised sine and cosine functions of different frequencies []. The token and positional embeddings were added together, which means that the attention mechanism in the subsequent transformer blocks had information on both the specific token and the position of the token in the context.

### 2.2 Multi-Head Masked Self Attention and the Transformer Block

Once tokens have been embedded with a token embedding and positional embedding which are added together, thus allowing the model to use information on both the position of the token in the context window (length $N$) and the value of the token, these are fed to transformer blocks in their high dimensional vector form. In multi-head attention, the embedding space (of size $d_{model}$) is divided into lower dimensional spaces of equal size ($d_{k}$), before the results of attention are concatenated after the attention mechanism to reconstruct the original embedding space size ($d_{model}$) [].

The attention mechanism operates by allowing tokens to communicate with one another and thus update each other’s information. Each attention head transforms tokens into keys ($K$), using a linear layer which compresses the tokens from $d_{model}$ dimensions to $d_{k}$ dimensions. It also separately transforms tokens into queries ($Q$), which again use another linear layer to compress the tokens from $d_{model}$ dimensions to $d_{k}$ dimensions. One can think of queries ($Q$) as each token broadcasting what it is looking for, and keys ($K$) as each token broadcasting what it contains. The dot product is then taken between both the queries and the keys, such that if there is a match between the information a token is looking for in $Q$ and the information a token emits in $K$, there will be a spike in the corresponding attention weights $QK^{T}$. This dot product is next scaled by $\sqrt{d_{k}}$, and the SoftMax of each row is taken (resulting in attention rows that sum to 1). This scaled dot product results in an $N\times N$ matrix of attention weights, which convey how tokens communicate with each other, for all tokens in the context window. In masked self attention, the mechanism used to train GPT models, the upper triangle of this weight matrix is set to zero. This means that tokens can only communicate with themselves or with past tokens in the sequence, and allows for efficient training by allowing for N separate training examples with an input block of N token length. During training of the model, dropout (the random zeroing of weights) is also applied to the weight matrix. The final step to the masked self attention process is to multiply the weight matrix with a value matrix. The value matrix, $V$, is formed from another linear layer that compresses the tokens from $d_{model}$ dimensions to $d_{k}$ dimensions. A combination of all of these steps produces the following attention function []

$$ $\text{Attention}(Q,K,V)=\text{SoftMax}(\frac{QK^{T}}{\sqrt{d_{k}}})V$ (1) $$

As previously mentioned, the results of each head, which are of dimension $d_{k}=d_{model}/\text{(\# Heads)}$, are next concatenated to give the original dimension $d_{model}$. This output from multi-head attention is then added to input to the multi-head attention, forming a residual connection that allows the model to bypass a transformer block if needed. Finally, this new combined output is normalised and passed through a feed-forward network which firstly expands the embedding dimension to $4\times d_{model}$, applies a ReLU activation function, and then compresses the dimension back to $d_{model}$. During training, dropout is also applied to this feed-forward network. The feed-forward network after multi-head attention can be thought of as allowing the model to process the results of self-attention, before these results are fed into another multi-head attention block. The combination of the multi-head attention and this feed-forward network constitute one transformer block. After the final transformer block, the output is passed through a final linear layer, which converts the output from a dimension of $d_{model}$ to the size of the vocabulary. When passed through a SoftMax activation function, this provides the probabilities for all tokens in the vocabulary, at all $N$ points.

### 2.3 Architecture

Our models were developed in PyTorch [] and adapted from a tutorial by Andrej Karpathy [] titled “Let’s build GPT: from scratch, in code, spelled out”. For both the photoplethysmography pre-trained transformer (PPG-PT) and electrocardiography pre-trained transformer (ECG-PT) we used an embedding dimension ($d_{model}$) of 64. The original GPT paper used an embedding dimension of 768 [], but given that PPG and ECG are far less complex than language, 64 was found to be sufficient in our case. We used 8 transformer blocks, each with 8 attention heads, as described in Section 2.2 of this paper and the original transformer paper []. It was found during early training that bigger models performed better, so we trained the largest model possible, with the trade-offs of context length ($N=$ 500 samples) and batch size (64), in order to utilise almost all of the 12GB of RAM on our NVIDIA RTX A2000 GPU. This architecture resulted in 443,493 trainable parameters. In the areas where dropout was applied (the feedforward subsection of the transformer and the attention weight matrix), dropout was set to 0.2.

### 2.4 Pre-Training

Three datasets were used for training the PPG-PT base model: 1) Capnobase “respiratory benchmark” dataset [], which consists of high quality ECG and PPG recorded over 42 subjects for 8 minutes each; 2) BIDMC(^1^11The BIDMC data set is made available under the ODC Attribution license, and is available at https://physionet.org/content/bidmc/1.0.0/) dataset [] which consists of PPG and ECG from 53 subjects for 8 minutes each; 3) the “cuffless blood pressure dataset” [], a subset of MIMIC II [], consisting of 12,000 recordings of PPG signals of varied quality, in a hospital setting. The combination of all of these datasets resulted in over 128 million total tokens for training.

For the training of the ECG-PT base model, we used subsets of the “PhysioNet Computing in Cardiology Challenge 2020” dataset [] [], which consists of tens of thousands of 12-lead ECG recordings, across tens of thousands of patients in a hospital setting. From each of these recordings, we extracted 10-second examples of Lead I ECG. This dataset comprises a diverse range of cardiac abnormalities as well as many healthy subjects, as the dataset was originally constructed for the identification of different heart conditions. Once tokenised, this dataset resulted in over 42 million tokens for training.

For each model, training data was split into 90% training and 10% validation datasets. The data was not shuffled to ensure that validation data primarily consisted of unseen subjects. The PPG-PT model was trained over 500,000 iterations with a batch size of 64, and the ECG-PT model was trained over 560,000 iterations with the same batch size. After every 2,000 iterations, the models were evaluated over a further 200 iterations to measure validation loss. In both cases, the learning rate was set as $3\times 10^{-4}$ within the AdamW optimiser. The training of PPG-PT took just over 5 days on an RTX A2000 12GB GPU, while the training of ECG-PT took almost 6 days. Optimisation loss was measured using cross entropy, by mapping the $N\times 101$ model outputs (logits) where the $101$ represents all possible tokens, to the target tokens which were the next token values for all points in the input. The final validation loss of the PPG-PT model was 1.2, corresponding to roughly a third of prediction being perfect. The final validation loss of the ECG-PT model was 1.8 (1 in 6 predictions are perfect). The higher validation loss for ECG-PT was likely due to the high proportion of abnormal heart rhythms in the training and validation datasets.

### 2.5 Fine-Tuning

#### 2.5.1 Atrial Fibrillation

During the fine-tuning, the final linear layer, which converts the output from $d_{model}$ dimensions to the dimensions of the vocabulary size, was replaced with a linear layer which instead converts the output from $d_{model}$ dimensions to 1 dimension. This new output then was passed through a sigmoid activation function to scale the values between 0 and 1; the final value was then used to classify the signal as either healthy (0) or atrial fibrillation (1). A binary cross entropy loss criterion was then used to map the output value to the true class. This same conversion of the final linear layer of the model could be used for any suitable classification or regression task, by simply scaling the number of output dimensions to be in line with the specific task. During training, just the new linear layer and the final transformer block were trained, whilst all other layers were frozen. In this example, the learning rate was maintained at $3\times 10^{-4}$ within the AdamW optimiser.

To train and evaluate the fine-tuning of the model for classification of atrial fibrillation (AF), the “MIMIC PERform AF” dataset [] was used, which is a subset of MIMIC III dataset []. This dataset contains 20 minutes of continuous PPG and ECG recordings from each of 35 subjects, of whom 19 had AF and 16 did not have AF. These signals, originally recorded at a sample frequency of 125Hz, were band-pass filtered to between 1 and 15Hz and then downsampled to 50Hz in the case of the PPG, and band-pass filtered between 1 and 45Hz and downsampled to 100Hz in the case of the ECG. A window length of 500 samples was maintained, corresponding to 10 seconds of PPG (50Hz) and 5 seconds of ECG (100Hz), and sliding windows were extracted from the data and tokenised with a shift of 50 samples each time, in order to artificially inflate the volume of data for the model training. In both the cases of ECG and PPG, the models were fine-tuned in a leave-one-subject-out fashion by training on 34 subjects and testing on 1, over 1,000 iterations and with a batch size of 128. Each model took 11 minutes to fine tune on an RTX A2000 GPU, which is a fraction of the over 5 days that it took to train each of the base models.

#### 2.5.2 PPG Beat Detection

As was the case with fine-tuning to detect atrial fibrillation, the final linear layer was again replaced with a linear layer which converted the output from $d_{model}$ dimensions to 1 dimension. However, instead of using just the final value in the context as was the case with AF, all values from the context were used. This 1-dimensional array was passed through a Sigmoid activation function, to map to values of 0 (no peak) or 1 (peak) for all tokens in the context. Only the new linear layer and the final transformer layer were trained. The learning rate was again maintained at $3\times 10^{-4}$ within the AdamW optimiser, with a binary cross entropy loss function. The model was fine-tuned over 5000 iterations, with a batch size of 128.

To train and evaluate the fine-tuning of the model for beat detection, the “MIMIC PERform” training and test datasets were used []. Both datasets consist of real-world clinical PPG and ECG recordings at a sample frequency of 125Hz from 200 subjects, for 10 minutes per subject. The training dataset was used to train and validate, and the unseen test dataset was then used to evaluate performance of the trained model. The PPG signals were band-pass filtered between 1 and 30 Hz to remove low frequency variations, and ECG between 4 and 60Hz to isolate the higher frequency QRS complex and remove P and T waves. Labels for peaks were determined by using the inbuilt MATLAB findpeaks function on the filtered reference ECG data. Peaks, and the points immediately neighbouring the peaks, were labelled as 1. All other points were labeled as zero. This signal was then aligned with the filtered PPG signal to the point of maximal cross correlation, to ensure peak labels that mapped to the PPG peaks. Both the reference signal and the PPG signal were resampled to 50Hz, and the PPG signal was then tokenised as per previous examples. In the reference signal, the difference in the time between each peak should be minimal. When the standard deviation of this difference was greater than 0.3 seconds, a sign that the reference signal was of poor quality, the subject was excluded from the training data.

When testing, the criterion outlined by Chartlon et al. [] was followed to allow for comparability of results. Poor quality labels were excluded from the test set by removing reference segments which had no beats for 2 seconds or more. Input segments with constant values for more than 0.2 seconds, an indication of clipping and thus data loss, were also excluded from analysis. Output peaks were determined by applying findpeaks to the output of the model, with a minimum height of 0.015, a maximum peak width of 0.4 seconds, and a minimum distance between peaks of 0.28 seconds (corresponding to a heart rate of 214 beats per minute). If a predicted beat was within 0.15 seconds of a reference beat, it was deemed to be correct. Results were then analysed in terms of the median F1 score (%) across test subjects.

It should be noted that the fine-tuned model produces continuous values between 0 and 1, for each position in the context, which are a measure of its confidence that a beat is present. In our analysis, we also investigated the utility of using these beat confidence values as a measure of signal quality.

### 2.6 Cross Entropy Loss and Next Token Prediction vs Mean Squared Error

Conventionally, time series transformer models produce a continuous output values for each token prediction and are thus trained with a mean squared error (MSE) loss function [] or a combination of likelihood and MSE []. However, unlike many time series prediction tasks, we were able to leverage the highly periodic nature of the PPG and ECG signals to create models with a well-defined small vocabulary. This allowed us to train the model exclusively with a cross-entropy loss function, in a similar fashion to a conventional large language model. It should be noted that we did also experiment with continuous output values and mean squared error as a loss function, but these results were less able to capture long range trends and importantly lacked interpretability in the attention weights. A full investigation into this finding is beyond the scope of this work.

Through training for next token prediction in combination with cross entropy loss, for each part of the context window, we force tokens to update in a way which is still relevant to that specific token. For example, tokens around peaks update to become more “peak-like” as they propagate through the transformer blocks, and the same principle is the case for all other positions in each cardiac cycle. In that sense, the final layer of attention operates on a ECG or PPG signal where each token is rich in period-specific information, and attention can thus be fine-tuned in a way that is more easily interpretable to a clinician.

Figure: Figure 1: Generation error (in terms of absolute error) for both the PPG-PT and ECG-PT base models for a duration of half the length of the context window, evaluated over 40 unseen subjects from the bed-based balistocardiography dataset. The examples demonstrate that whilst the models were able to accurately capture features of the context, such as pulse shape and the dicrotic notch in the case of PPG, and all sections of the P-QRS-T for the ECG, large errors can come from slight temporal misalignment. (a) Two examples of model generations for PPG-PT, with context in black, ground truth in blue and model prediction in red. Both examples provide the maximum error of the prediction, with a large error occurring in the first, and a more typical error occurring in the second example. (b) The median prediction error (red solid line) and interquartile range (red shaded area) for PPG-PT across all windows. (c) Two examples of model generations for ECG-PT, with context in black, ground truth in blue and model prediction in red. Both examples provide the maximum absolute error of the prediction, with two examples of large errors due to slight misalignments in prediction. (d) The median prediction error (red solid line) and interquartile range (red shaded area) for ECG-PT across all windows.
Refer to caption: x1.png

## 3 Generative Model Evaluation

In training, for all points in the context window the model outputs logits to which a SoftMax function can be applied, giving a predicted probability distribution of the next token over all possible tokens. For the generation of future tokens, the final probability distribution is taken, representing the possible token values for the next token. The multinomial function in PyTorch is then used to sample this distribution and generate a predicted next token. Each new predicted token can then be appended to the previous context, and the last 500 tokens in this new context are then used to predict the next token. This process can be repeated until a maximum number of generated tokens has been reached. Another way to examine the predictive capabilities of each model would be to predict the next token as the one with the highest probability, instead of sampling from a distribution. The problem with this second approach is that sometimes in low frequency periods, such as a trough in PPG or a period between P-QRS-T regions in the ECG, taking just the token with maximum likelihood could allow the model to become stuck in predicting the sample token value over and over again. Because of this issue, the first approach of sampling from a probability distribution was chosen to evaluate the models.

For the evaluation of generative capabilities of each model, the pre-processed subset of the Bed-based ballistocardiography dataset [] [] was used. This dataset consists of simultaneously recorded PPG and ECG from 40 subjects, sampled at 1kHz. In the preprocessed subset, the PPG was low-pass filtered with a cut off of 10Hz and the ECG was band-pass filtered between 1 and 40Hz. As with the previous datasets, we resampled the PPG to 50Hz, and the ECG to 100Hz, before converting the signals to tokens. The 750-sample windows were extracted and split into 500 samples to form the context and 250 samples to test the prediction accuracy of the model. For each predicted token, we calculated the absolute distance between the predicted token and the true token. We were then able to calculate the median and inter-quartile range of absolute prediction error against the prediction horizon for both the PPG-PT and ECG-PT models. In Figure 1(a,c), example generation waveforms and maximum absolute errors are highlighted for both the PPG-PT and ECG-PT models. Observe that the errors stem not from a failure to predict the morphology of the PPG or ECG, but from slight temporal misalignment between the prediction and the ground truth, as is common with periodic physiological signals []. The median absolute distance between the prediction and ground truth in PPG-PT starts at 1 token and grows to 21 tokens across the 5 second (250 samples) prediction horizon, as shown in Figure 1(b). For ECG-PT, the median error starts at 1 token and grows to 3 tokens across the 2.5 second (250 samples) prediction horizon, as shown in Figure 1(d). It should be noted that we expect the errors to be significantly higher in the PPG-PT model when compared with the ECG-PT model, as due to the comparatively broader shape of the peaks in the PPG waveform, errors in temporal misalignment increase the prediction error across the whole waveform. This is in contrast to ECG where the vast majority of the signal is flat, and thus slight temporal misalignment is mainly penalised around the QRS complex and the T wave.

Whilst these prediction errors show us that the introduced models are good at extrapolating PPG and ECG waveforms into the future, this can never be perfect given that there may be changes in heart rate, respiration, and even arrhythmia events that are impossible to predict from the context. The important result here is the ability of the models to generalise to unseen distinct morphologies of PPG and ECG as context. It is clear that the PPG-PT condenses knowledge of peak width and the shape of the dicrotic notch (the sub-peak) in the PPG examples and is thus able to generate PPG with the same properties. This is even more obvious in the case of ECG, where both examples have very different P, Q, R, S and T wave morphologies, and ECG-PT was able to replicate this well. This is the first indicator that the PPG-PT and ECG-PT models pay attention to the relevent features of both signals.

## 4 Interpretability of the Pre-Trained Models

Figure: Figure 2: Aggregate attention across all attention heads for the attention row corresponding to the prediction point, per transformer layer shown (the first and last layers), for both the PPG-PT and ECG-PT models. The attention maps demonstrate that in order to predict the next token, the models first look at all tokens in the immediate cycle to gain an understanding of where a token falls within that cycle. When this understanding has been established, models then look at the all similar points occuring in other cycles in the context window. For both models, attention in the first transformer layer is shown on top and the last transformer layer beneath, with context (black line) and the prediction point (blue circle) corresponding to overlaid transformer attention (red transparent bars), with transparency scaled based on the attention weights shown below (red solid line). (a) The PPG-PT aggregate attention, for the prediction of a peak in the given previously unseen photoplethysmography context. (b) The ECG-PT aggregate attention, for the prediction of a peak in the given previously unseen electrocardiography context.
Refer to caption: x2.png

### 4.1 Interpretability of aggregate model attention

As is the case with GPT models [], our pre-trained transformer models (PPG-PT and ECG-PT) are trained to predict the next token at each point, by using the attention mechanism to collate knowledge from previous tokens. It is then natural to ask ourselves: given the task of predicting the next token in a periodic signal, which tokens would one look at in order to make that prediction? The obvious answer to this question is to look at tokens which are at the same point in the previous cycles as the token that we want to predict. For example, if the current token to predict was a peak, it would be logical to look at all previous peaks, with an emphasis on peaks of similar height and width, in order to make an accurate prediction. However, the information we start with is just the position of a token in the context window and the value of a token. Given that the fundamental frequency changes between contexts and that different points in the same cycle can have the same value, we cannot rely on the initial position and value information alone to find similar points in the same cycle. In order to understand the point at which a token lies in a cycle, it is therefore necessary to first look at the context of surrounding tokens. Once this relationship between a token and its local cycle is understood, attention can broaden to look at all cycles.

**Table 1: The average look-back distance for the attention, in seconds, for all the different layers (1 to 8) in the PPG-PT and ECG-PT models.**
|  | Mean Layer Attention Distance for Different Models (in seconds) |  |
| --- | --- | --- |
| Transformer Layer | PPG-PT | ECG-PT |
| 1 | $0.43\pm 0.07$ | $0.33\pm 0.11$ |
| 2 | $0.55\pm 0.33$ | $0.99\pm 0.26$ |
| 3 | $1.04\pm 0.29$ | $1.17\pm 0.29$ |
| 4 | $0.92\pm 0.37$ | $1.11\pm 0.10$ |
| 5 | $0.65\pm 0.37$ | $0.58\pm 0.11$ |
| 6 | $0.92\pm 0.55$ | $0.51\pm 0.22$ |
| 7 | $2.62\pm 0.47$ | $1.79\pm 0.26$ |
| 8 | $2.31\pm 0.42$ | $1.88\pm 0.23$ |

This mechanism of broadening attention is indeed found in both of our PPG-PT and ECG-PT models. The last row in the attention weight matrix corresponds to the final token in the context. To examine the attention span of the model, we calculated the central point of attention for this final row of attention in each attention head in each transformer block, across all context windows in the generative test set. In Table 1 it is shown that for PPG-PT, the mean central point of attention is 0.43 seconds in the first transformer block, and thus the focus is within the immediate cycle. By the last transformer block, this central point of attention has broadened to 2.31 seconds, indicating that the PPG-PT model was updating the current token based on the tokens in previous cycles of PPG. The same effect is seen in ECG-PT, with a broadening of attention from 0.33 seconds in the first block to 1.88 seconds in the last block.

The next step to interpreting the aggregate attention of the model is to examine the attention weights of different transformer blocks for specific context examples. In Figure 2 (a) we examine the summed attention weights in PPG-PT from the row associated with predicting the peak point highlighted with a blue circle. As expected, in order to predict the peak point the first transformer block focuses on the immediate points before the peak point in order to learn how the point integrates to the local PPG cycle. This also is true of the attention matrix rows in the first transformer block that are associated with all previous tokens in the context. Importantly, observe that in the final transformer block, in order to predict the peak point the network focuses its attention on all previous peaks in the context. This is also true of the ECG-PT model, as demonstrated in Figure 2 (b).

### 4.2 Vector similarities between points of interest

Figure: Figure 3: Plots showing the cosine similarity of points in rising slopes (blue circles, blue solid lines) and falling slopes (red circles, red solid lines) with similar input values, upon propagation through the transformer layers of the model. In each case, a single point on a rising slope is chosen as a comparison point, represented by a black cross on the context (black solid line), and a black dotted line with a cosine similarity of 1 in the cosine similarity plot. The point of propagation through the model is highlighted with grey transparent blocks labeled with the corresponding transformer layer (from 1 to 8). In both examples, rising slope points and falling slope points are shuffled in embedding space upon input to the first model layer, and gradually divide into two clusters as they propagate through the model. (a) The cosine similarity in embedding space of rising slopes and falling slopes in a photoplethysmography signal, upon propagation through the PPG-PT model. (b) The cosine similarity in embedding space of rising slopes and falling slopes in the T-wave of an electrocardiography signal, upon propagation through the ECG-PT model.
Refer to caption: x3.png

In the previous section, we have demonstrated that the pre-trained transformer models naturally focus on similar points in previous cycles of PPG or ECG when predicting the next token. This strongly indicates that the models are able to distinguish different points in the cycle of PPG and ECG waveforms. In this section, we aim to solidify this finding by examining how the cosine similarity of embedded tokens with the same value, which occur at different distinct points in the PPG and ECG cycle, change upon propagation through the model. To this end, we chose tokens at similar points on rising slopes and falling slopes on the PPG signal, and on the T-wave of the ECG signal. The similarity of these tokens was calculated with respect to the final rising slope in each context window. If the models are effective at distinguishing different points in the cycle, we would expect rising slopes to cluster with each other in vector space, and falling slopes to form a separate cluster in vector space. An analogous experiment in a large language model would be to look at the vector similarity of homonyms (words that have the same spelling but can have multiple different meanings), and examine how the vector similarity changes based on specific context in a sentence. For example, we would expect the token “bat” to form separate clusters in vector space upon propagation through an LLM based on if it contextually refers to a club to hit a cricket ball or it refers to the flying mammal.

It is highlighted in Figure 3 that, upon input to the pre-trained models, falling slopes and rising slopes of the PPG and ECG are shuffled in vector space. This is because the inputs to the models have the same token embedding that has not yet been updated based on the context of previous tokens. Notably, as these tokens propagate through the models, rising slopes increase in vector similarity and cluster below a cosine similarity of 1 (identical vector) and falling slopes form their own independent cluster. This further demonstrates that these large pre-trained models can clearly identify the relationship between different points in cycle of both PPG and ECG.

Figure: Figure 4: Attention maps of the attention weights of individual attention heads of the last layer of both the PPG-PT and ECG-PT models. Averaged attention maps are generated by averaging the final layer of the attention weight matrix over the prediction of the next 500 tokens beyond the initial context window. The model context is plotted in black, with attention weights plotted in red, pink, and blue for different attention heads. Peaks in attention are highlighted in the same colour with circles, and overlaid on the context with bars. (a) Mapping of the averaged attention weights in the final layer attention heads of the PPG-PT model for an example photoplethysmography context. Observe that the 3rd attention head (red) looks primarily for peaks in PPG, the 4th attention head (pink) looks primarily for troughs in PPG, and the 6th (blue) looks for the dicrotic notch. (b) Mapping of the averaged attention weights in the final layer attention heads of the ECG-PT model for an example electrocardiography context. The 1st attention head (red) looks for R peaks in the ECG, the 5th attention head (pink) looks primarily for P waves, and the 7th attention head (blue) looks primarily for the Q portion of the QRS complex of ECG.
Refer to caption: x4.png

### 4.3 Attention Maps of Individual Attention Heads

Now that we know that the base pre-trained PPG-PT and ECG-PT models look at similar points in previous cycles in order to predict the next token, and that the models have knowledge of the context of different points within a PPG and ECG cycle, the final step is to examine if the individual attention heads look for specific high level features in the PPG and ECG signals. To investigate this, we examined example contexts from the generative evaluation dataset which contained the common features of each signal. For example, a PPG context which has well-defined peaks, troughs, and a dicrotic notch, and an ECG context which has a well defined P-wave and QRS complex.

For each model, upon inputting the context, we looked at the final row in the attention weights of each head in the last transformer block, corresponding to the weights associated with predicting the next token. Upon saving these weights, we inputted a new context corresponding to the original shifted by 1 sample into the future. We then saved these weights and added the final N-1 weights to the last N-1 original weights. We repeated this shift and add operation for a further N-2 times, and divided each of the N weights element-wise by the number of additions made to them. This gave us an average map of attention to the context for the next 500 token predictions, for each self-attention head in the final transformer block. We then used the findpeaks function in MATLAB, with a minimum peak distance of 15 tokens and a minimum peak height of 0.5 of the maximum attention weight in the window, to highlight the local maximas in attention.

Figure 4 highlights that individual attention heads do indeed pay attention to important features in the signal of interest. In particular, PPG-PT has an attention head that looks for peaks, another that looks for troughs and another which looks for the dicrotic notch. In addition, we found that ECG-PT has a head which looks for the Q portion of the QRS, another which looks for R-peaks and another that looks for P waves. Therefore, on top of an ability to distinguish all separate points in a PPG and ECG cycle, the pre-trained models presented in this paper also pay specific attention to some of the most physiological relevent features.

## 5 Fine-Tuning Results

Figure: Figure 5: Changes in final layer attention weights of the base PPG-PT and ECG-PT models when fine-tuned to classifying atrial fibrillation. The model input context is shown in black, with attention overlaid with red bars of varying transparency based on the change in attention weights. The full difference in attention weights is shown below each plot in red. (a) Example fine-tuned PPG-PT test results, with examples of pulses occurring later than expected and earlier than expected, and the corresponding spikes in attention weights. (b) Example fine-tuned ECG-PT test results, again showing beats occurring later or earlier than expected with the aforementioned spikes in attention.
Refer to caption: x5.png

### 5.1 Change in Attention when Screening For Atrial Fibrillation

Through pre-training we have obtained models which have focus on the important features of PPG and ECG, and generalise well to unseen morphologies. However, rather like in LLMs, predicting the next token of PPG and ECG lacks utility. To make full use of these pre-trained models, we fine tune the models to classify atrial fibrillation (AF), as outlined in Section 2.4.2. Atrial fibrillation is the most common arrhythmia, characterised by an irregular heart rate which can manifest itself in rapid increases in heart rate and periods where it slows down dramatically []. The fine-tuned AF-PPG-PT model achieved a leave-one-subject-out area under the curve (AUC) of 0.93 when cross validated across all test subjects, and 0.96 when two subjects with poor signal to noise ratio were excluded. The fine-tuned AF-ECG-PT model achieved an AUC of 0.99 when cross validated across all test subjects. It is worth reiterating that these results were achieved with 11 minutes of fine-tuning computer time, corresponding to roughly 0.2% of the total time it took to train the base models.

The key result of fine-tuning is not just the accuracy, but the interpretability of the results. To ascertain why a model made a classification, we simply aggregated the final row of SoftMaxed attention weights across all heads in the final transformer layer for the base model and compared with the fine-tuned model. Any increases in attention weights therefore indicate that the model deems the corresponding tokens valuable for classification of AF. In Figure 5(a) two representative attention maps are displayed for the classification of a PPG context as AF. Observe in both cases that the model increases attention on periods where beats occur later than expected on earlier than expected, which is the obvious characteristic of AF. This is even clearer in the fine-tuned ECG attention, given that peaks in ECG are more precisely localised in time. In Figure 5(b), an example is highlighted where a beat is expected to occur based on the previous beat timing, but it does not and thus the model attention spikes. A second example is also highlighted, where based on the previous beat timing a beat occurs much earlier than expected, and model attention therefore spikes exactly at this point. These interpretable maps of shifts in attention, demonstrating the reason why the model has made the classification, can easily be provided along with with the probability of AF.

### 5.2 Beat Detection and Signal Quality Estimation in PPG

Figure: Figure 6: Example results of fine-tuning PPG-PT for beat detection. The input context PPG signal is plotted in black, predicted beats are highlighted with red crosses and ECG derived beats (ground truth) are designated with blue circles. The beat confidence is overlaid as vertical lines, with green indicating high confidence, orange indicating medium, and red indicating low. Both an example of high signal quality (top) and an example of low signal quality (bottom) are shown.
Refer to caption: x6.png

Evaluation of the fine-tuned PPG-PT model for beat detection on the “MIMIC perform testing dataset” yielded a median F1 score of 98.04% across subjects, which is comparable to the F1 scores of qppg [] (96.9%) and MSPTD [] (97.5%) as found by Charlton et al. []. It was found during training that whilst the model was able to accurately distinguish beats in examples with high signal quality after just 50 to 100 iterations, training it for longer was necessary to detect beats in examples with visibly poor signal quality. In addition to predicting the location of beats, our fine-tuned PPG-PT model also provides a continuous value between 0 and 1 at each location. This can be thought of as a “quasi-confidence estimate” in the prediction that a beat is indeed present at that location. Given that test dataset is clinical data, and thus the majority of the data is high quality, values in the bottom 10% of confidence were labelled as low confidence, values between 10% and 25% were labelled as medium confidence, and values in the top 75% were labelled as high confidence.

Observe in Figure 6 that in both the cases of high signal quality and low signal quality, our fine-tuned beat detector was able to correctly identify all PPG beats, within 150ms of the ECG derived ground truth beats. Importantly, the confidence estimates also aligned with signal quality, with lower confidence in areas of poor signal quality. The confidence estimates also carry over to the previous AF dataset. Beat detection was applied independently to “MIMIC Perform AF” and it was found that two subjects with the lowest classification accuracy, and visibly poor PPG signal quality, also had the lowest mean beat confidence. Conversely, the subject with the highest mean classification accuracy had the highest signal quality, as determined by the beat confidence.

It should be emphasised that the PPG-PT model was pretrained on finger-based clinical data, and thus has also been fine-tuned on clinical data. Wearable sensor data, such as from the wrist [] or the ear [] have different morphology to that of the finger. It is likely that further training would be necessary for these models to be transferable to wearable PPG data.

## 6 Conclusion

This work has conclusively demonstrated that GPT-like models, trained to predict the next token in periodic physiological time series, are fully interpretable in their operation. This has been illustrated through aggregate attention maps which are natural for the task of predicting the next token and through the clustering of different PPG and ECG features in vector space. This has been further shown through individual attention heads that correspond strongly to specific features such as the dicrotic notch in PPG or the P-wave in ECG. Moreover, we have shown that this interpretability is carried forward when fine-tuning for the classification of atrial fibrillation, where attention shifts to regions in the input context that most indicate the presence of the arrhythmia. This work represents a step forward in the explainability of large transformer networks when applied to healthcare settings.

## Peer Reviews

confidence: 3
contribution: 3
initial_rating: 5
presentation: 3
questions: 1: You have considered very clean datasets and samples; seeing the behavior across different noisy scenarios would be highly important. Since we could achieve very high performance on high-quality data with an F1 score of 0.96 with DeepBeat (Torres-Soto et al., 2020).

2: Attention maps as an interpretability tool have been successfully explored (Zhao et al., 2023). It needs to be clarified that you did something new methodologically; it seems more of an application. For example, you have details on using the `findpeaks` function in Matlab, but it is poorly structured overall. It would be great if you would summarize the methodology as a pseudocode and suggest choices.

- Zhao, Haiyan, et al. "Explainability for Large Language Models: A Survey." arXiv preprint arXiv:2309.01029 (2023).
- Torres-Soto, Jessica, and Euan A. Ashley. "Multi-task deep learning for cardiac rhythm detection in wearable devices." NPJ digital medicine 3.1 (2020): 116.
soundness: 3
strengths: - Interpretability analysis on physiological time series
- The model was tested on two types of physiological time series: PPG and single-lead ECG.
summary: This paper introduces two interpretable pre-trained transformer models (PPG-PT and ECG-PT) adapted from the GPT framework for analyzing heart time-series data from PPG and ECG signals.  The authors demonstrate that these models develop interpretable attention patterns corresponding to physiologically meaningful cardiac cycle features.
weaknesses: 1. The model's novelty is questionable, as the PPG-GPT has previously been explored across multiple tasks (Chen et al., 2024). It will be helpful to specify how the current work differs from it.
2. The manuscript does not compare models on different PPG or ECG tasks compared to previous PPG-GPT (Chen et al., 2024). The comparison with one baseline per PPG and ECG is mentioned only in the appendix. Importantly, the models are compared on performance using different setups.
3. The experiments have not been performed across multiple runs, so the variability (std or IQR) of the performance is not clear. Consider 5-fold or 5 seeds.
4. Consider additional metrics, for example, sensitivity, specificity, false-positive rate, false-negative rate, and F1 score for AF.
5. The majority of the paper focuses on interpretability. However, it is difficult for the machine-learning community to validate clinical utility claims that require experience in reading ECG or PPG. Have you collaborated with clinical experts to validate the interpretability claims? Could you provide more evidence that the examples you have shown guarantee the presence of AF?

- Chen, Zhaoliang, et al. "Adapting a Generative Pretrained Transformer Achieves SOTA Performance in Assessing Diverse Physiological Functions Using Only Photoplethysmography Signals: A GPT-PPG Approach." AAAI 2024 Spring Symposium on Clinical Foundation Models. 2024.

---

confidence: 5
contribution: 3
initial_rating: 6
presentation: 2
questions: See the "Weaknesses" section.
soundness: 3
strengths: 1. To the best of my knowledge, this is the first work that applies generative pre-training to representation learning for heart time-series data, where previously contrastive learning methods were the most popular (also inherited from other domains like voice recognition). This is a novel and interesting idea.

2. The attention mechanism analysis is very detailed and provides a clear understanding of the learned representations, and how the transformer layers work on the heart time-series data.
summary: This manuscript presents a novel approach to representation learning for heart time-series data (typically PPG and ECG in this work) using generative pre-trained transformers (GPTs). The idea comes from the NLP domain where GPTs have shown remarkable capabilities in learning representations from text data, and the fact that the (pre-)training process for GPTs is very simple, only next-token prediction, also motivated this work, as claimed by the authors. The authors conducted a very detailed attention mechanism analysis to interpret the learned representations of the pre-trained GPTs.
weaknesses: 1. The datasets used in the experiments are not comprehensive enough. The authors used the CinC2020 dataset, which is superseded by the CinC2021 dataset. The latter dataset is more comprehensive and contains more data. Moreover, there are other larger datasets available, such as the CODE-15% dataset (https://zenodo.org/records/4916206), etc.

2. The authors did not compare their method in their numerical experiments with other representation learning methods, such as contrastive learning-based methods (for example CLOCS (https://proceedings.mlr.press/v139/kiyasseh21a/kiyasseh21a.pdf)), to show the effectiveness of their method.

3. Not enough downstream tasks are conducted to evaluate the learned representations (or the pre-trained GPTs).

---

confidence: 4
contribution: 3
initial_rating: 8
presentation: 4
questions: - 10 second segments were extracted from recordings from where tokens were generated, are these tokens represent whole segment data or beats were isolated to form tokens?

- The prediction or generation of tokens from GPT models is unclear. Experiment says a single token is generated for a given context length, then it needs to be clearly mentioned how the generation process continued to generate to produce, say Figure 1, of 15 second PPG or ECG data which was compared against the original signal?
soundness: 3
strengths: - Related GPT based interpretation studies for ECG and PPG exists in literature, but the experimentation carried out in this study is rigour and systematic in revealing the explanations for firstly, the generation of next token and finally, extend the idea for a downstream classification task.

- The idea of decoding attention head for explanations are common in the CV and NLP domain, but extending it to physiological time-series can be seen a contribution.

- Data split follows a subject-wise separation to avoid data leak in training and testing.
summary: The paper aims to use generative pre-trained transformer (GPT) framework to predict next token for ECG and PPG signals with a focus in interpreting the decision-making of these large language models. This was done through observing the behavior of the attention heads in different transformer layers and aggregating them. The experiments reveal that the next token generation looks cycles in the nearest past more than that of the farthest past in the context. Qualitative interpretation reveals the ECG and PPG GPT models look into important signal components. These GPT models were fine tuned for a downstream task of atrial fibrillation classification with interpretation highlighting irregular occurrence of a beat w.r.t. the previous beat which is interesting. Overall, the problem formulation is logical, methods are well designed and explained, and the discussion clearly articulates the explainability the GPT models can offer.
weaknesses: Major:
- The explainability method of GPT models was shown to focus on previous cycles meaning that it can observe a beat w.r.t the previous one which is why the downstream task interprets well where distance between two consecutive beat is important criteria. However, this might not be the case for other common tasks such as sleep staging where the input in 30 second ECG or PPG signal and separating sleep stages such as wake, light sleep, deep sleep and REM sleep manifests from HR variability. Another experimentation for a downstream task would be interesting to see if the proposed explainability idea fits well to provide clinical domain specific interpretation, given the fact that GPT models were found to be useful in these downstream tasks.

- Few related GPT interpretability studies were referenced. More references should be included to have a broad picture based on GPT interpretablity. For example, 
a. Creswell, A., Shanahan, M., & Higgins, I. (2022). Selection-inference: Exploiting large language models for interpretable logical reasoning. arXiv preprint arXiv:2205.09712.
b. Ben Melech Stan, G., Aflalo, E., Rohekar, R. Y., Bhiwandiwalla, A., Tseng, S. Y., Olson, M. L., ... & Lal, V. (2024). LVLM-Intrepret: an interpretability tool for large vision-language models. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 8182-8187).

Minor:
- Figure 3 captions needs to be corrected a-d.

Meta-review: Summary: Although this paper received positive reviews and one borderline review but I do not believe it to be above the bar for acceptance at ICLR. This paper builds two transformer based models, one for ECGs and another for PPGs (signals used for non-invasive). These are trained via next token prediction. The work goes on to interpret what the model has learned by looking at the attention weights onto the space of inputs. They find that peak predictions are most sensitive to prior peaks, the cosine similarities of patterns such as rising and falling slopes are shared across time and that for each modality, various attention heads latch on to different parts of the signal and studying how the model's insights change when fine tuning to predict atrial fibrilation. Overall, this reads as a well written report that builds two transformers and does a study on how to interpret the model's predictions on two data modalities relevant for healthcare. My concern is not with the choice of topic, which I do think is interesting, but rather with the claims of the paper, the organization, the lack of engagement with other work in the literature on interpretability and finally the lack of clarity on what a practitioner in ML and healthcare should do with these results.

Limitations: First, it is unclear what the core technical contributions from the perspective of learning. If there are no new technical contributions, this should be stated up-front and the manuscript should instead highlight the exploratory nature of the work on a problem of interest. Given the simple methods (training transformers, using simple methods for interpreting attention weights) used here, if the contribution of this work is that transformers capture clinically relevant signals, then this should be verified via a panel of clinicians to demonstrate that using this form of interpretability improves trust and/or utility. Second, there is a large body of in deep learning at the intersection of ML and healthcare for cardiology that this work does not do much to engage with in terms of how similar the models are and this, in turn, hurts the generalizability of the findings. Finally, there is a large literature around the interpretability of transformer based models the relationship to which has not been well articulated or compared to (e.g. https://arxiv.org/abs/2005.00928, https://arxiv.org/abs/1908.07442, https://arxiv.org/abs/2406.00426,https://arxiv.org/abs/2212.14776). Is this the only method for interpretability of such models, a good one, or even the best one? I think its important to contend with these topics for this work to have value for a learning focused venue like ICLR.

Decision: Reject