File size: 4,254 Bytes
3621f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""
PatchTST Implementation for Financial Time Series Prediction.

Based on: "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers" (ICLR 2023)
Paper: https://arxiv.org/abs/2211.14730

Key innovations of PatchTST:
1. Patching: Split time series into patches (like ViT for images)
2. Channel Independence: Each feature processed independently
3. Efficiency: Much faster than vanilla Transformer
"""

import torch
import torch.nn as nn
import math


class PatchEmbedding(nn.Module):
    """Convert time series to patches and embed them."""
    
    def __init__(self, patch_len=16, stride=8, d_model=128, in_channels=5):
        super().__init__()
        self.patch_len = patch_len
        self.stride = stride
        
        # Linear projection for each patch
        self.proj = nn.Linear(patch_len * in_channels, d_model)
    
    def forward(self, x):
        """
        Args:
            x: [B, seq_len, in_channels]
        Returns:
            patches: [B, num_patches, d_model]
        """
        B, L, C = x.shape
        
        # Extract patches with stride
        num_patches = (L - self.patch_len) // self.stride + 1
        patches = []
        
        for i in range(num_patches):
            start = i * self.stride
            end = start + self.patch_len
            patch = x[:, start:end, :]  # [B, patch_len, C]
            patch = patch.reshape(B, -1)  # [B, patch_len*C]
            patches.append(patch)
        
        patches = torch.stack(patches, dim=1)  # [B, num_patches, patch_len*C]
        patches = self.proj(patches)  # [B, num_patches, d_model]
        
        return patches


class PatchTST(nn.Module):
    """
    PatchTST model for time series forecasting.
    
    Architecture:
    1. Patch Embedding: Split series into patches
    2. Positional Encoding
    3. Transformer Encoder
    4. Flatten and Project to output
    """
    
    def __init__(
        self,
        seq_len=96,
        pred_len=20,
        in_channels=5,
        d_model=128,
        nhead=8,
        num_layers=3,
        dim_feedforward=256,
        dropout=0.1,
        patch_len=16,
        stride=8
    ):
        super().__init__()
        
        self.seq_len = seq_len
        self.pred_len = pred_len
        self.in_channels = in_channels
        self.d_model = d_model
        
        # Patch embedding
        self.patch_embed = PatchEmbedding(patch_len, stride, d_model, in_channels)
        
        # Calculate number of patches
        self.num_patches = (seq_len - patch_len) // stride + 1
        
        # Positional encoding (learnable)
        self.pos_embed = nn.Parameter(torch.randn(1, self.num_patches, d_model) * 0.02)
        
        # Transformer encoder
        encoder_layer = nn.TransformerEncoderLayer(
            d_model=d_model,
            nhead=nhead,
            dim_feedforward=dim_feedforward,
            dropout=dropout,
            batch_first=True
        )
        self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
        
        # Output projection
        self.head = nn.Sequential(
            nn.Flatten(),
            nn.Linear(self.num_patches * d_model, 256),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(256, pred_len * in_channels)
        )
    
    def forward(self, x):
        """
        Args:
            x: [B, seq_len, in_channels]
        Returns:
            pred: [B, pred_len, in_channels]
        """
        B = x.size(0)
        
        # Patch embedding
        x = self.patch_embed(x)  # [B, num_patches, d_model]
        
        # Add positional encoding
        x = x + self.pos_embed
        
        # Transformer encoding
        x = self.transformer(x)  # [B, num_patches, d_model]
        
        # Project to output
        out = self.head(x)  # [B, pred_len * in_channels]
        out = out.reshape(B, self.pred_len, self.in_channels)
        
        return out


if __name__ == "__main__":
    # Test
    model = PatchTST(seq_len=96, pred_len=20, in_channels=5)
    x = torch.randn(4, 96, 5)
    out = model(x)
    print(f"Input: {x.shape}")
    print(f"Output: {out.shape}")
    print(f"Parameters: {sum(p.numel() for p in model.parameters()) / 1e6:.2f}M")