I'm looking to adapt the transformer machine learning model arch to my sequence to seqeunce stock modelling problem. My input data is typical stock information "close", "open", "volume", diffrent moving averages etc. In the typical GPT transformer arch a pytorch nn embedding layer is used as the data from the tokeniser will be a sparse one hot encoded vector for the token, whereas in my usecase the timestep or token has a non sparse representation of the various features of the stock at that point.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
You're absolutely right in observing that the typical GPT-style Transformer model expects discrete tokens (like words), which are mapped through an nn.Embedding layer into a dense vector space. However, your use case involves continuous-valued financial time-series features (e.g., close, open, volume, moving averages, etc.), which are already dense vectors per time step.
This is actually more aligned with architectures like the Transformer used for time series forecasting, such as models like Informer, Autoformer, or even vanilla encoder-decoder Transformers adapted to continuous input domains.
✅ Problem Summary
Your data: Continuous feature vectors per time step (e.g., [close, open, volume, MA_10, MA_50])
Goal: Use a Transformer-based architecture for sequence-to-sequence modeling of stock data
Challenge: Unlike NLP, you don't have discrete tokens → no need for token embeddings via nn.Embedding
🛠️ Solution Overview
Since each time step already has a dense representation, you should skip the embedding layer and instead directly project your feature vector (of size F) into the model's hidden dimension (d_model) using a linear layer:
python
self.input_proj = nn.Linear(F, d_model)
Then feed this projection into the Transformer (either encoder-only or encoder-decoder) as usual.
🔁 Full Adaptation Strategy
Here’s how you can adapt a standard Transformer model (PyTorch's nn.Transformer) for your sequence-to-sequence stock prediction task:
1. Input Representation
Each input sample will be a tensor of shape:
code
(batch_size, seq_len, num_features)
Example: (64, 30, 8) → 64 samples, 30 days lookback, 8 features per day.
Use a linear projection to get it into d_model dimensions:
python
class StockTransformer(nn.Module):
def __init__(self, num_features, d_model=512, nhead=8, num_encoder_layers=3,
num_decoder_layers=3, dim_feedforward=2048, dropout=0.1):
super().__init__()
self.input_proj = nn.Linear(num_features, d_model)
self.transformer = nn.Transformer(
d_model=d_model,
nhead=nhead,
num_encoder_layers=num_encoder_layers,
num_decoder_layers=num_decoder_layers,
dim_feedforward=dim_feedforward,
dropout=dropout,
batch_first=True # Important for time series
)
# Output head: map decoder output to prediction (e.g., next price or returns)
self.output_proj = nn.Linear(d_model, 1) # Predicting 1 value (e.g., next close)
2. Positional Encoding
Since Transformers don’t inherently understand order, you need to add positional encodings.
You can either:
Use learnable positional embeddings
Or use fixed sinusoidal positional encodings
Here's a simple version of learnable positional embeddings:
python
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=500):
super().__init__()
self.pe = nn.Parameter(torch.zeros(1, max_len, d_model))
def forward(self, x):
return x + self.pe[:, :x.size(1)]