Repository: WenjieDu/PyPOTS (language: python)

Issue:
Add TCN (Temporal Convolutional Network)
### 1. Model description

TCN should be included in PyPOTS, and could start from the imputation task.

This is also related to #399 proposing to add ModernTCN into PyPOTS.

```bibtex
@article{bai2018tcn,
title={An empirical evaluation of generic convolutional and recurrent networks for sequence modeling},
author={Bai, Shaojie and Kolter, J Zico and Koltun, Vladlen},
journal={arXiv preprint arXiv:1803.01271},
year={2018}
}
```

### 2. Check open-source status

- [X] The model implementation is publicly available

### 3. Provide useful information for the implementation

https://github.com/locuslab/TCN
Add TCN as an imputation model
<!-- 🚨Please create your PR to merge code from your branch to `dev` branch here, rather than `main`. -->

# What does this PR do?

<!--
Congrats! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution 😉.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, I will review your PR shortly. I may suggest changes to make the code even better 🤝.
-->

<!-- Remove if not applicable -->

1. fixing #466;


## Before submitting

<!-- You can remove checks that are not relevant to this PR. -->

- [x] This PR is made to fix a typo or improve the docs (you can dismiss the other checks if this is the case).
- [x] Was this discussed/approved via a GitHub issue? Please add a link to it if that's the case.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have written necessary tests and already run them locally.



Discussion / hints:

Fix patch:
diff --git a/README.md b/README.md
index 80571138..e1dc8028 100644
--- a/README.md
+++ b/README.md
@@ -144,6 +144,7 @@ The paper references and links are all listed at the bottom of this file.
 | Neural Net    | M-RNN[^9]                   |    ✅     |          |          |          |          | `2019 - TBME`      |
 | Neural Net    | BRITS[^3]                   |    ✅     |          |    ✅     |          |          | `2018 - NeurIPS`   |
 | Neural Net    | GRU-D[^4]                   |    ✅     |          |    ✅     |          |          | `2018 - Sci. Rep.` |
+| Neural Net    | TCN🧑‍🔧[^35]               |    ✅     |          |          |          |          | `2018 - arXiv`     |
 | Neural Net    | Transformer🧑‍🔧[^2]        |    ✅     |          |          |          |          | `2017 - NeurIPS`   |
 | Naive         | Lerp                        |    ✅     |          |          |          |          |                    |
 | Naive         | LOCF/NOCB                   |    ✅     |          |          |          |          |                    |
@@ -383,6 +384,7 @@ PyPOTS community is open, transparent, and surely friendly. Let's work together
 [^32]: Kitaev, N., Kaiser, Ł., & Levskaya, A. (2020). [Reformer: The Efficient Transformer](https://openreview.net/forum?id=0EXmFzUn5I). *ICLR 2020*.
 [^33]: Cao, D., Wang, Y., Duan, J., Zhang, C., Zhu, X., Huang, C., Tong, Y., Xu, B., Bai, J., Tong, J., & Zhang, Q. (2020). [Spectral Temporal Graph Neural Network for Multivariate Time-series Forecasting](https://proceedings.neurips.cc/paper/2020/hash/cdf6581cb7aca4b7e19ef136c6e601a5-Abstract.html). *NeurIPS 2020*.
 [^34]: Nie, T., Qin, G., Mei, Y., & Sun, J. (2024). [ImputeFormer: Low Rankness-Induced Transformers for Generalizable Spatiotemporal Imputation](https://arxiv.org/abs/2312.01728). *KDD 2024*.
+[^35]: Bai, S., Kolter, J. Z., & Koltun, V. (2018). [An empirical evaluation of generic convolutional and recurrent networks for sequence modeling](https://arxiv.org/abs/1803.01271). *arXiv 2018*.
 
 <details>
 <summary>🏠 Visits</summary>
diff --git a/README_zh.md b/README_zh.md
index c6a31af4..58aae7d0 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -130,6 +130,7 @@ PyPOTS当前支持多变量POTS数据的插补，预测，分类，聚类以及
 | Neural Net    | M-RNN[^9]                   |    ✅     |          |          |          |          | `2019 - TBME`      |
 | Neural Net    | BRITS[^3]                   |    ✅     |          |    ✅     |          |          | `2018 - NeurIPS`   |
 | Neural Net    | GRU-D[^4]                   |    ✅     |          |    ✅     |          |          | `2018 - Sci. Rep.` |
+| Neural Net    | TCN🧑‍🔧[^35]               |    ✅     |          |          |          |          | `2018 - arXiv`     |
 | Neural Net    | Transformer🧑‍🔧[^2]        |    ✅     |          |          |          |          | `2017 - NeurIPS`   |
 | Naive         | Lerp                        |    ✅     |          |          |          |          |                    |
 | Naive         | LOCF/NOCB                   |    ✅     |          |          |          |          |                    |
@@ -354,6 +355,7 @@ PyPOTS社区是一个开放、透明、友好的社区，让我们共同努力
 [^32]: Kitaev, N., Kaiser, Ł., & Levskaya, A. (2020). [Reformer: The Efficient Transformer](https://openreview.net/forum?id=0EXmFzUn5I). *ICLR 2020*.
 [^33]: Cao, D., Wang, Y., Duan, J., Zhang, C., Zhu, X., Huang, C., Tong, Y., Xu, B., Bai, J., Tong, J., & Zhang, Q. (2020). [Spectral Temporal Graph Neural Network for Multivariate Time-series Forecasting](https://proceedings.neurips.cc/paper/2020/hash/cdf6581cb7aca4b7e19ef136c6e601a5-Abstract.html). *NeurIPS 2020*.
 [^34]: Nie, T., Qin, G., Mei, Y., & Sun, J. (2024). [ImputeFormer: Low Rankness-Induced Transformers for Generalizable Spatiotemporal Imputation](https://arxiv.org/abs/2312.01728). *KDD 2024*.
+[^35]: Bai, S., Kolter, J. Z., & Koltun, V. (2018). [An empirical evaluation of generic convolutional and recurrent networks for sequence modeling](https://arxiv.org/abs/1803.01271). *arXiv 2018*.
 
 
 <details>
diff --git a/docs/index.rst b/docs/index.rst
index 7066994b..b780093e 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -195,6 +195,8 @@ The paper references are all listed at the bottom of this readme file.
 +----------------+-----------------------------------------------------------+------+------+------+------+------+-----------------------+
 | Neural Net     | GRU-D :cite:`che2018GRUD`                                 |      |      |  ✅  |      |      | ``2018 - Sci. Rep.``  |
 +----------------+-----------------------------------------------------------+------+------+------+------+------+-----------------------+
+| Neural Net     | TCN🧑‍🔧 :cite:`bai2018tcn`                               |  ✅  |      |      |      |      | ``2018 - arXiv``      |
++----------------+-----------------------------------------------------------+------+------+------+------+------+-----------------------+
 | Neural Net     | Transformer🧑‍🔧 :cite:`vaswani2017Transformer`           |  ✅  |      |      |      |      | ``2017 - NeurIPS``    |
 +----------------+-----------------------------------------------------------+------+------+------+------+------+-----------------------+
 | Naive          | Lerp (Linear Interpolation)                               |  ✅  |      |      |      |      |                       |
diff --git a/docs/pypots.imputation.rst b/docs/pypots.imputation.rst
index 8f237e0e..d994f96a 100644
--- a/docs/pypots.imputation.rst
+++ b/docs/pypots.imputation.rst
@@ -261,6 +261,15 @@ pypots.imputation.grud
    :show-inheritance:
    :inherited-members:
 
+pypots.imputation.tcn
+------------------------------
+
+.. automodule:: pypots.imputation.tcn
+   :members:
+   :undoc-members:
+   :show-inheritance:
+   :inherited-members:
+
 pypots.imputation.lerp
 -----------------------------
 
diff --git a/docs/references.bib b/docs/references.bib
index 7ef5bdd8..9f66b6a5 100644
--- a/docs/references.bib
+++ b/docs/references.bib
@@ -756,3 +756,10 @@ @article{nie2024imputeformer
 doi = {10.1145/3637528.3671751},
 url = {https://doi.org/10.1145/3637528.3671751},
 }
+
+@article{bai2018tcn,
+title={An empirical evaluation of generic convolutional and recurrent networks for sequence modeling},
+author={Bai, Shaojie and Kolter, J Zico and Koltun, Vladlen},
+journal={arXiv preprint arXiv:1803.01271},
+year={2018}
+}
\ No newline at end of file
diff --git a/pypots/imputation/__init__.py b/pypots/imputation/__init__.py
index b27f9079..7de15dae 100644
--- a/pypots/imputation/__init__.py
+++ b/pypots/imputation/__init__.py
@@ -23,6 +23,7 @@
 from .crossformer import Crossformer
 from .informer import Informer
 from .autoformer import Autoformer
+from .tcn import TCN
 from .reformer import Reformer
 from .dlinear import DLinear
 from .patchtst import PatchTST
@@ -57,6 +58,7 @@
     "DLinear",
     "Informer",
     "Autoformer",
+    "TCN",
     "Reformer",
     "NonstationaryTransformer",
     "Pyraformer",
diff --git a/pypots/imputation/tcn/__init__.py b/pypots/imputation/tcn/__init__.py
new file mode 100644
index 00000000..86e12914
--- /dev/null
+++ b/pypots/imputation/tcn/__init__.py
@@ -0,0 +1,24 @@
+"""
+The package of the partially-observed time-series imputation model TCN.
+
+Refer to the paper
+`Shaojie Bai, J. Zico Kolter, and Vladlen Koltun.
+"An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling".
+arXiv preprint arXiv:1803.01271.
+<https://arxiv.org/pdf/1803.01271>`_
+
+Notes
+-----
+This implementation is inspired by the official one https://github.com/locuslab/TCN
+
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+
+from .model import TCN
+
+__all__ = [
+    "TCN",
+]
diff --git a/pypots/imputation/tcn/core.py b/pypots/imputation/tcn/core.py
new file mode 100644
index 00000000..07be25b6
--- /dev/null
+++ b/pypots/imputation/tcn/core.py
@@ -0,0 +1,81 @@
+"""
+The core wrapper assembles the submodules of TCN imputation model
+and takes over the forward progress of the algorithm.
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+import torch.nn as nn
+
+from ...nn.modules.saits import SaitsLoss, SaitsEmbedding
+from ...nn.modules.tcn import BackboneTCN
+
+
+class _TCN(nn.Module):
+    def __init__(
+        self,
+        n_steps: int,
+        n_features: int,
+        n_levels: int,
+        d_hidden: int,
+        kernel_size: int,
+        dropout: float = 0,
+        ORT_weight: float = 1,
+        MIT_weight: float = 1,
+    ):
+        super().__init__()
+        self.n_steps = n_steps
+        channel_sizes = [d_hidden] * n_levels
+
+        self.saits_embedding = SaitsEmbedding(
+            n_features * 2,
+            n_features,
+            with_pos=False,
+            dropout=dropout,
+        )
+        self.backbone = BackboneTCN(
+            n_features,
+            channel_sizes,
+            kernel_size,
+            dropout,
+        )
+
+        # for the imputation task, the output dim is the same as input dim
+        self.output_projection = nn.Linear(channel_sizes[-1], n_features)
+        self.saits_loss_func = SaitsLoss(ORT_weight, MIT_weight)
+
+    def forward(self, inputs: dict, training: bool = True) -> dict:
+        X, missing_mask = inputs["X"], inputs["missing_mask"]
+
+        # WDU: the original TCN paper isn't proposed for imputation task. Hence the model doesn't take
+        # the missing mask into account, which means, in the process, the model doesn't know which part of
+        # the input data is missing, and this may hurt the model's imputation performance. Therefore, I apply the
+        # SAITS embedding method to project the concatenation of features and masks into a hidden space, as well as
+        # the output layers to project back from the hidden space to the original space.
+        enc_out = self.saits_embedding(X, missing_mask)
+        enc_out = enc_out.permute(0, 2, 1)
+
+        # TCN encoder processing
+        enc_out = self.backbone(enc_out)
+        enc_out = enc_out.permute(0, 2, 1)
+        # project back the original data space
+        reconstruction = self.output_projection(enc_out)
+
+        imputed_data = missing_mask * X + (1 - missing_mask) * reconstruction
+        results = {
+            "imputed_data": imputed_data,
+        }
+
+        # if in training mode, return results with losses
+        if training:
+            X_ori, indicating_mask = inputs["X_ori"], inputs["indicating_mask"]
+            loss, ORT_loss, MIT_loss = self.saits_loss_func(
+                reconstruction, X_ori, missing_mask, indicating_mask
+            )
+            results["ORT_loss"] = ORT_loss
+            results["MIT_loss"] = MIT_loss
+            # `loss` is always the item for backward propagating to update the model
+            results["loss"] = loss
+
+        return results
diff --git a/pypots/imputation/tcn/data.py b/pypots/imputation/tcn/data.py
new file mode 100644
index 00000000..8571cded
--- /dev/null
+++ b/pypots/imputation/tcn/data.py
@@ -0,0 +1,24 @@
+"""
+Dataset class for TCN.
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+from typing import Union
+
+from ..saits.data import DatasetForSAITS
+
+
+class DatasetForTCN(DatasetForSAITS):
+    """Actually TCN uses the same data strategy as SAITS, needs MIT for training."""
+
+    def __init__(
+        self,
+        data: Union[dict, str],
+        return_X_ori: bool,
+        return_y: bool,
+        file_type: str = "hdf5",
+        rate: float = 0.2,
+    ):
+        super().__init__(data, return_X_ori, return_y, file_type, rate)
diff --git a/pypots/imputation/tcn/model.py b/pypots/imputation/tcn/model.py
new file mode 100644
index 00000000..b51cceb9
--- /dev/null
+++ b/pypots/imputation/tcn/model.py
@@ -0,0 +1,306 @@
+"""
+The implementation of TCN for the partially-observed time-series imputation task.
+
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+from typing import Union, Optional
+
+import numpy as np
+import torch
+from torch.utils.data import DataLoader
+
+from .core import _TCN
+from .data import DatasetForTCN
+from ..base import BaseNNImputer
+from ...data.checking import key_in_data_set
+from ...data.dataset import BaseDataset
+from ...optim.adam import Adam
+from ...optim.base import Optimizer
+
+
+class TCN(BaseNNImputer):
+    """The PyTorch implementation of the TCN model.
+    TCN is originally proposed by Bai et al. in :cite:`bai2018tcn`.
+
+    Parameters
+    ----------
+    n_steps :
+        The number of time steps in the time-series data sample.
+
+    n_features :
+        The number of features in the time-series data sample.
+
+    n_levels :
+        The number of levels in the TCN model.
+
+    d_hidden :
+        The hidden dimension for the TCN model.
+
+    kernel_size :
+        The kernel size for the TCN model.
+
+    dropout :
+        The dropout rate for the model.
+
+    ORT_weight :
+        The weight for the ORT loss, the same as SAITS.
+
+    MIT_weight :
+        The weight for the MIT loss, the same as SAITS.
+
+    batch_size :
+        The batch size for training and evaluating the model.
+
+    epochs :
+        The number of epochs for training the model.
+
+    patience :
+        The patience for the early-stopping mechanism. Given a positive integer, the training process will be
+        stopped when the model does not perform better after that number of epochs.
+        Leaving it default as None will disable the early-stopping.
+
+    optimizer :
+        The optimizer for model training.
+        If not given, will use a default Adam optimizer.
+
+    num_workers :
+        The number of subprocesses to use for data loading.
+        `0` means data loading will be in the main process, i.e. there won't be subprocesses.
+
+    device :
+        The device for the model to run on. It can be a string, a :class:`torch.device` object, or a list of them.
+        If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple),
+        then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models.
+        If given a list of devices, e.g. ['cuda:0', 'cuda:1'], or [torch.device('cuda:0'), torch.device('cuda:1')] , the
+        model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices).
+        Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.
+
+    saving_path :
+        The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during
+        training into a tensorboard file). Will not save if not given.
+
+    model_saving_strategy :
+        The strategy to save model checkpoints. It has to be one of [None, "best", "better", "all"].
+        No model will be saved when it is set as None.
+        The "best" strategy will only automatically save the best model after the training finished.
+        The "better" strategy will automatically save the model during training whenever the model performs
+        better than in previous epochs.
+        The "all" strategy will save every model after each epoch training.
+
+    verbose :
+        Whether to print out the training logs during the training process.
+    """
+
+    def __init__(
+        self,
+        n_steps: int,
+        n_features: int,
+        n_levels: int,
+        d_hidden: int,
+        kernel_size: int,
+        dropout: float = 0,
+        ORT_weight: float = 1,
+        MIT_weight: float = 1,
+        batch_size: int = 32,
+        epochs: int = 100,
+        patience: int = None,
+        optimizer: Optional[Optimizer] = Adam(),
+        num_workers: int = 0,
+        device: Optional[Union[str, torch.device, list]] = None,
+        saving_path: str = None,
+        model_saving_strategy: Optional[str] = "best",
+        verbose: bool = True,
+    ):
+        super().__init__(
+            batch_size,
+            epochs,
+            patience,
+            num_workers,
+            device,
+            saving_path,
+            model_saving_strategy,
+            verbose,
+        )
+
+        self.n_steps = n_steps
+        self.n_features = n_features
+        # model hype-parameters
+        self.n_levels = n_levels
+        self.d_hidden = d_hidden
+        self.kernel_size = kernel_size
+        self.dropout = dropout
+        self.ORT_weight = ORT_weight
+        self.MIT_weight = MIT_weight
+
+        # set up the model
+        self.model = _TCN(
+            self.n_steps,
+            self.n_features,
+            self.n_levels,
+            self.d_hidden,
+            self.kernel_size,
+            self.dropout,
+            self.ORT_weight,
+            self.MIT_weight,
+        )
+        self._send_model_to_given_device()
+        self._print_model_size()
+
+        # set up the optimizer
+        self.optimizer = optimizer
+        self.optimizer.init_optimizer(self.model.parameters())
+
+    def _assemble_input_for_training(self, data: list) -> dict:
+        (
+            indices,
+            X,
+            missing_mask,
+            X_ori,
+            indicating_mask,
+        ) = self._send_data_to_given_device(data)
+
+        inputs = {
+            "X": X,
+            "missing_mask": missing_mask,
+            "X_ori": X_ori,
+            "indicating_mask": indicating_mask,
+        }
+
+        return inputs
+
+    def _assemble_input_for_validating(self, data: list) -> dict:
+        return self._assemble_input_for_training(data)
+
+    def _assemble_input_for_testing(self, data: list) -> dict:
+        indices, X, missing_mask = self._send_data_to_given_device(data)
+
+        inputs = {
+            "X": X,
+            "missing_mask": missing_mask,
+        }
+
+        return inputs
+
+    def fit(
+        self,
+        train_set: Union[dict, str],
+        val_set: Optional[Union[dict, str]] = None,
+        file_type: str = "hdf5",
+    ) -> None:
+        # Step 1: wrap the input data with classes Dataset and DataLoader
+        training_set = DatasetForTCN(
+            train_set, return_X_ori=False, return_y=False, file_type=file_type
+        )
+        training_loader = DataLoader(
+            training_set,
+            batch_size=self.batch_size,
+            shuffle=True,
+            num_workers=self.num_workers,
+        )
+        val_loader = None
+        if val_set is not None:
+            if not key_in_data_set("X_ori", val_set):
+                raise ValueError("val_set must contain 'X_ori' for model validation.")
+            val_set = DatasetForTCN(
+                val_set, return_X_ori=True, return_y=False, file_type=file_type
+            )
+            val_loader = DataLoader(
+                val_set,
+                batch_size=self.batch_size,
+                shuffle=False,
+                num_workers=self.num_workers,
+            )
+
+        # Step 2: train the model and freeze it
+        self._train_model(training_loader, val_loader)
+        self.model.load_state_dict(self.best_model_dict)
+        self.model.eval()  # set the model as eval status to freeze it.
+
+        # Step 3: save the model if necessary
+        self._auto_save_model_if_necessary(confirm_saving=True)
+
+    def predict(
+        self,
+        test_set: Union[dict, str],
+        file_type: str = "hdf5",
+    ) -> dict:
+        """Make predictions for the input data with the trained model.
+
+        Parameters
+        ----------
+        test_set : dict or str
+            The dataset for model validating, should be a dictionary including keys as 'X',
+            or a path string locating a data file supported by PyPOTS (e.g. h5 file).
+            If it is a dict, X should be array-like of shape [n_samples, sequence length (n_steps), n_features],
+            which is time-series data for validating, can contain missing values, and y should be array-like of shape
+            [n_samples], which is classification labels of X.
+            If it is a path string, the path should point to a data file, e.g. a h5 file, which contains
+            key-value pairs like a dict, and it has to include keys as 'X' and 'y'.
+
+        file_type :
+            The type of the given file if test_set is a path string.
+
+        Returns
+        -------
+        file_type :
+            The dictionary containing the clustering results and latent variables if necessary.
+
+        """
+        # Step 1: wrap the input data with classes Dataset and DataLoader
+        self.model.eval()  # set the model as eval status to freeze it.
+        test_set = BaseDataset(
+            test_set,
+            return_X_ori=False,
+            return_X_pred=False,
+            return_y=False,
+            file_type=file_type,
+        )
+        test_loader = DataLoader(
+            test_set,
+            batch_size=self.batch_size,
+            shuffle=False,
+            num_workers=self.num_workers,
+        )
+        imputation_collector = []
+
+        # Step 2: process the data with the model
+        with torch.no_grad():
+            for idx, data in enumerate(test_loader):
+                inputs = self._assemble_input_for_testing(data)
+                results = self.model.forward(inputs, training=False)
+                imputation_collector.append(results["imputed_data"])
+
+        # Step 3: output collection and return
+        imputation = torch.cat(imputation_collector).cpu().detach().numpy()
+        result_dict = {
+            "imputation": imputation,
+        }
+        return result_dict
+
+    def impute(
+        self,
+        test_set: Union[dict, str],
+        file_type: str = "hdf5",
+    ) -> np.ndarray:
+        """Impute missing values in the given data with the trained model.
+
+        Parameters
+        ----------
+        test_set :
+            The data samples for testing, should be array-like of shape [n_samples, sequence length (n_steps),
+            n_features], or a path string locating a data file, e.g. h5 file.
+
+        file_type :
+            The type of the given file if X is a path string.
+
+        Returns
+        -------
+        array-like, shape [n_samples, sequence length (n_steps), n_features],
+            Imputed data.
+        """
+
+        result_dict = self.predict(test_set, file_type=file_type)
+        return result_dict["imputation"]
diff --git a/pypots/nn/modules/tcn/__init__.py b/pypots/nn/modules/tcn/__init__.py
new file mode 100644
index 00000000..52c06e3c
--- /dev/null
+++ b/pypots/nn/modules/tcn/__init__.py
@@ -0,0 +1,24 @@
+"""
+The package including the modules of TCN (Temporal Convolutional Network).
+
+Refer to the paper
+`Shaojie Bai, J. Zico Kolter, and Vladlen Koltun.
+"An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling".
+arXiv preprint arXiv:1803.01271.
+<https://arxiv.org/pdf/1803.01271>`_
+
+Notes
+-----
+This implementation is inspired by the official one https://github.com/locuslab/TCN
+
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+
+from .backbone import BackboneTCN
+
+__all__ = [
+    "BackboneTCN",
+]
diff --git a/pypots/nn/modules/tcn/backbone.py b/pypots/nn/modules/tcn/backbone.py
new file mode 100644
index 00000000..2a36223b
--- /dev/null
+++ b/pypots/nn/modules/tcn/backbone.py
@@ -0,0 +1,44 @@
+"""
+
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+
+import torch.nn as nn
+
+from .layers import TemporalBlock
+
+
+class BackboneTCN(nn.Module):
+    def __init__(
+        self,
+        num_inputs,
+        num_channels,
+        kernel_size=2,
+        dropout=0.2,
+    ):
+        super().__init__()
+        layers = []
+        num_levels = len(num_channels)
+        for i in range(num_levels):
+            dilation_size = 2**i
+            in_channels = num_inputs if i == 0 else num_channels[i - 1]
+            out_channels = num_channels[i]
+            layers += [
+                TemporalBlock(
+                    in_channels,
+                    out_channels,
+                    kernel_size,
+                    stride=1,
+                    dilation=dilation_size,
+                    padding=(kernel_size - 1) * dilation_size,
+                    dropout=dropout,
+                )
+            ]
+
+        self.network = nn.Sequential(*layers)
+
+    def forward(self, x):
+        return self.network(x)
diff --git a/pypots/nn/modules/tcn/layers.py b/pypots/nn/modules/tcn/layers.py
new file mode 100644
index 00000000..be640396
--- /dev/null
+++ b/pypots/nn/modules/tcn/layers.py
@@ -0,0 +1,87 @@
+"""
+
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+
+import torch.nn as nn
+from torch.nn.utils import weight_norm
+
+
+class Chomp1d(nn.Module):
+    def __init__(self, chomp_size):
+        super().__init__()
+        self.chomp_size = chomp_size
+
+    def forward(self, x):
+        return x[:, :, : -self.chomp_size].contiguous()
+
+
+class TemporalBlock(nn.Module):
+    def __init__(
+        self,
+        n_inputs,
+        n_outputs,
+        kernel_size,
+        stride,
+        dilation,
+        padding,
+        dropout=0.2,
+    ):
+        super().__init__()
+        self.conv1 = weight_norm(
+            nn.Conv1d(
+                n_inputs,
+                n_outputs,
+                kernel_size,
+                stride=stride,
+                padding=padding,
+                dilation=dilation,
+            )
+        )
+        self.chomp1 = Chomp1d(padding)
+        self.relu1 = nn.ReLU()
+        self.dropout1 = nn.Dropout(dropout)
+
+        self.conv2 = weight_norm(
+            nn.Conv1d(
+                n_outputs,
+                n_outputs,
+                kernel_size,
+                stride=stride,
+                padding=padding,
+                dilation=dilation,
+            )
+        )
+        self.chomp2 = Chomp1d(padding)
+        self.relu2 = nn.ReLU()
+        self.dropout2 = nn.Dropout(dropout)
+
+        self.net = nn.Sequential(
+            self.conv1,
+            self.chomp1,
+            self.relu1,
+            self.dropout1,
+            self.conv2,
+            self.chomp2,
+            self.relu2,
+            self.dropout2,
+        )
+        self.downsample = (
+            nn.Conv1d(n_inputs, n_outputs, 1) if n_inputs != n_outputs else None
+        )
+        self.relu = nn.ReLU()
+        self.init_weights()
+
+    def init_weights(self):
+        self.conv1.weight.data.normal_(0, 0.01)
+        self.conv2.weight.data.normal_(0, 0.01)
+        if self.downsample is not None:
+            self.downsample.weight.data.normal_(0, 0.01)
+
+    def forward(self, x):
+        out = self.net(x)
+        res = x if self.downsample is None else self.downsample(x)
+        return self.relu(out + res)


Test patch:
diff --git a/tests/imputation/tcn.py b/tests/imputation/tcn.py
new file mode 100644
index 00000000..400b66c4
--- /dev/null
+++ b/tests/imputation/tcn.py
@@ -0,0 +1,124 @@
+"""
+Test cases for TCN imputation model.
+"""
+
+# Created by Wenjie Du <wenjay.du@gmail.com>
+# License: BSD-3-Clause
+
+
+import os.path
+import unittest
+
+import numpy as np
+import pytest
+
+from pypots.imputation import TCN
+from pypots.optim import Adam
+from pypots.utils.logging import logger
+from pypots.utils.metrics import calc_mse
+from tests.global_test_config import (
+    DATA,
+    EPOCHS,
+    DEVICE,
+    TRAIN_SET,
+    VAL_SET,
+    TEST_SET,
+    GENERAL_H5_TRAIN_SET_PATH,
+    GENERAL_H5_VAL_SET_PATH,
+    GENERAL_H5_TEST_SET_PATH,
+    RESULT_SAVING_DIR_FOR_IMPUTATION,
+    check_tb_and_model_checkpoints_existence,
+)
+
+
+class TestTCN(unittest.TestCase):
+    logger.info("Running tests for an imputation model TCN...")
+
+    # set the log and model saving path
+    saving_path = os.path.join(RESULT_SAVING_DIR_FOR_IMPUTATION, "TCN")
+    model_save_name = "saved_tcn_model.pypots"
+
+    # initialize an Adam optimizer
+    optimizer = Adam(lr=0.001, weight_decay=1e-5)
+
+    # initialize a TCN model
+    tcn = TCN(
+        DATA["n_steps"],
+        DATA["n_features"],
+        n_levels=2,
+        d_hidden=64,
+        kernel_size=3,
+        dropout=0,
+        epochs=EPOCHS,
+        saving_path=saving_path,
+        optimizer=optimizer,
+        device=DEVICE,
+    )
+
+    @pytest.mark.xdist_group(name="imputation-tcn")
+    def test_0_fit(self):
+        self.tcn.fit(TRAIN_SET, VAL_SET)
+
+    @pytest.mark.xdist_group(name="imputation-tcn")
+    def test_1_impute(self):
+        imputation_results = self.tcn.predict(TEST_SET)
+        assert not np.isnan(
+            imputation_results["imputation"]
+        ).any(), "Output still has missing values after running impute()."
+
+        test_MSE = calc_mse(
+            imputation_results["imputation"],
+            DATA["test_X_ori"],
+            DATA["test_X_indicating_mask"],
+        )
+        logger.info(f"TCN test_MSE: {test_MSE}")
+
+    @pytest.mark.xdist_group(name="imputation-tcn")
+    def test_2_parameters(self):
+        assert hasattr(self.tcn, "model") and self.tcn.model is not None
+
+        assert hasattr(self.tcn, "optimizer") and self.tcn.optimizer is not None
+
+        assert hasattr(self.tcn, "best_loss")
+        self.assertNotEqual(self.tcn.best_loss, float("inf"))
+
+        assert (
+            hasattr(self.tcn, "best_model_dict")
+            and self.tcn.best_model_dict is not None
+        )
+
+    @pytest.mark.xdist_group(name="imputation-tcn")
+    def test_3_saving_path(self):
+        # whether the root saving dir exists, which should be created by save_log_into_tb_file
+        assert os.path.exists(
+            self.saving_path
+        ), f"file {self.saving_path} does not exist"
+
+        # check if the tensorboard file and model checkpoints exist
+        check_tb_and_model_checkpoints_existence(self.tcn)
+
+        # save the trained model into file, and check if the path exists
+        saved_model_path = os.path.join(self.saving_path, self.model_save_name)
+        self.tcn.save(saved_model_path)
+
+        # test loading the saved model, not necessary, but need to test
+        self.tcn.load(saved_model_path)
+
+    @pytest.mark.xdist_group(name="imputation-tcn")
+    def test_4_lazy_loading(self):
+        self.tcn.fit(GENERAL_H5_TRAIN_SET_PATH, GENERAL_H5_VAL_SET_PATH)
+        imputation_results = self.tcn.predict(GENERAL_H5_TEST_SET_PATH)
+        assert not np.isnan(
+            imputation_results["imputation"]
+        ).any(), "Output still has missing values after running impute()."
+
+        test_MSE = calc_mse(
+            imputation_results["imputation"],
+            DATA["test_X_ori"],
+            DATA["test_X_indicating_mask"],
+        )
+        logger.info(f"Lazy-loading TCN test_MSE: {test_MSE}")
+
+
+if __name__ == "__main__":
+    unittest.main()