daeeeee commited on
Commit
98a87e4
·
1 Parent(s): fa05c89

Initial local commit matching Space

Browse files
Files changed (8) hide show
  1. .gitattributes +0 -35
  2. .gitignore +3 -3
  3. README.md +32 -32
  4. app.py +117 -117
  5. model/__init__.py +17 -17
  6. model/kronos.py +662 -662
  7. model/module.py +570 -570
  8. requirements.txt +8 -8
.gitattributes DELETED
@@ -1,35 +0,0 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore CHANGED
@@ -1,4 +1,4 @@
1
- __pycache__/
2
- *.pyc
3
- .venv/
4
  .env
 
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
  .env
README.md CHANGED
@@ -1,32 +1,32 @@
1
- ---
2
- title: kronos-dashboard
3
- app_file: app.py
4
- sdk: gradio
5
- sdk_version: 6.14.0
6
- ---
7
- \---
8
-
9
- title: Kronos Forecast Dashboard
10
-
11
- emoji: 📈
12
-
13
- colorFrom: blue
14
-
15
- colorTo: indigo
16
-
17
- sdk: gradio
18
-
19
- sdk\_version: 4.44.1
20
-
21
- app\_file: app.py
22
-
23
- pinned: false
24
-
25
- \---
26
-
27
-
28
-
29
- \# Kronos Forecast Dashboard
30
-
31
- Zero-shot OHLCV forecasting with Kronos + FMP data.
32
-
 
1
+ ---
2
+ title: kronos-dashboard
3
+ app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 6.14.0
6
+ ---
7
+ \---
8
+
9
+ title: Kronos Forecast Dashboard
10
+
11
+ emoji: 📈
12
+
13
+ colorFrom: blue
14
+
15
+ colorTo: indigo
16
+
17
+ sdk: gradio
18
+
19
+ sdk\_version: 4.44.1
20
+
21
+ app\_file: app.py
22
+
23
+ pinned: false
24
+
25
+ \---
26
+
27
+
28
+
29
+ \# Kronos Forecast Dashboard
30
+
31
+ Zero-shot OHLCV forecasting with Kronos + FMP data.
32
+
app.py CHANGED
@@ -1,118 +1,118 @@
1
- import os, requests
2
- import numpy as np
3
- import pandas as pd
4
- import torch
5
- import gradio as gr
6
- import plotly.graph_objects as go
7
- from plotly.subplots import make_subplots
8
-
9
- from model import Kronos, KronosTokenizer, KronosPredictor
10
-
11
- # ----- Load model once at startup -----
12
- print("Loading Kronos-small on CPU...")
13
- tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
14
- model = Kronos.from_pretrained("NeoQuasar/Kronos-small")
15
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
16
- predictor = KronosPredictor(model, tokenizer, device=device, max_context=512)
17
- print(f"Model loaded on {device}")
18
-
19
- FMP_KEY = os.getenv("FMP_API_KEY")
20
-
21
- # ----- Data fetch -----
22
- def fetch_fmp(symbol: str, interval: str, n_bars: int) -> pd.DataFrame:
23
- url = (f"https://financialmodelingprep.com/api/v3/historical-chart/"
24
- f"{interval}/{symbol}?apikey={FMP_KEY}")
25
- r = requests.get(url, timeout=30); r.raise_for_status()
26
- df = pd.DataFrame(r.json()).rename(columns={"date": "timestamps"})
27
- if df.empty:
28
- raise gr.Error(f"No data from FMP for {symbol} at {interval}")
29
- df["timestamps"] = pd.to_datetime(df["timestamps"])
30
- df = df.sort_values("timestamps").reset_index(drop=True)
31
- df["amount"] = df["close"] * df["volume"]
32
- df = df[["timestamps","open","high","low","close","volume","amount"]]
33
- return df.tail(n_bars).reset_index(drop=True)
34
-
35
- # ----- Forecast + chart -----
36
- def run_forecast(symbol, interval, lookback, pred_len, sample_count, temperature, top_p):
37
- lookback, pred_len, sample_count = int(lookback), int(pred_len), int(sample_count)
38
- if lookback + pred_len > 512:
39
- raise gr.Error(f"lookback + pred_len must be ≤ 512 (got {lookback+pred_len})")
40
-
41
- df = fetch_fmp(symbol.upper(), interval, lookback + 10)
42
- df = df.tail(lookback).reset_index(drop=True)
43
-
44
- # Build future timestamps
45
- step = df["timestamps"].diff().median()
46
- y_timestamp = pd.Series([df["timestamps"].iloc[-1] + step*(i+1) for i in range(pred_len)])
47
-
48
- x_df = df[["open","high","low","close","volume","amount"]]
49
- x_timestamp = df["timestamps"]
50
-
51
- pred_df = predictor.predict(
52
- df=x_df, x_timestamp=x_timestamp, y_timestamp=y_timestamp,
53
- pred_len=pred_len, T=temperature, top_p=top_p,
54
- sample_count=sample_count, verbose=False,
55
- )
56
- pred_df.index = y_timestamp
57
-
58
- # Plotly candlestick + forecast
59
- fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
60
- row_heights=[0.75, 0.25], vertical_spacing=0.03,
61
- subplot_titles=(f"{symbol.upper()} {interval} — Kronos Forecast", "Volume"))
62
- fig.add_trace(go.Candlestick(x=df["timestamps"], open=df["open"], high=df["high"],
63
- low=df["low"], close=df["close"], name="History"), row=1, col=1)
64
- fig.add_trace(go.Candlestick(x=pred_df.index, open=pred_df["open"], high=pred_df["high"],
65
- low=pred_df["low"], close=pred_df["close"],
66
- name="Forecast",
67
- increasing_line_color="#00CED1",
68
- decreasing_line_color="#FF69B4"), row=1, col=1)
69
- fig.add_trace(go.Bar(x=df["timestamps"], y=df["volume"], name="Vol", marker_color="#888"), row=2, col=1)
70
- fig.add_trace(go.Bar(x=pred_df.index, y=pred_df["volume"], name="Vol (fcst)", marker_color="#00CED1"), row=2, col=1)
71
- fig.update_layout(height=700, template="plotly_dark", xaxis_rangeslider_visible=False,
72
- showlegend=True, margin=dict(l=20, r=20, t=50, b=20))
73
-
74
- summary = pd.DataFrame({
75
- "Metric": ["Last close", "Forecast close", "Expected change %", "Forecast high", "Forecast low"],
76
- "Value": [
77
- f"{df['close'].iloc[-1]:.2f}",
78
- f"{pred_df['close'].iloc[-1]:.2f}",
79
- f"{(pred_df['close'].iloc[-1]/df['close'].iloc[-1]-1)*100:+.2f}%",
80
- f"{pred_df['high'].max():.2f}",
81
- f"{pred_df['low'].min():.2f}",
82
- ]
83
- })
84
- return fig, summary, pred_df.reset_index().rename(columns={"index":"timestamps"})
85
-
86
- # ----- UI -----
87
- with gr.Blocks(title="Kronos Forecast Dashboard") as demo:
88
- gr.Markdown("# 📈 Kronos Financial Forecast Dashboard\nZero-shot OHLCV forecasting powered by [Kronos](https://github.com/shiyu-coder/Kronos) + FMP market data.")
89
- with gr.Row():
90
- with gr.Column(scale=1):
91
- symbol = gr.Textbox("SPY", label="Symbol (e.g. SPY, AAPL, BTCUSD, EURUSD)")
92
- interval = gr.Dropdown(["1min","5min","15min","30min","1hour","4hour"], value="5min", label="Interval")
93
- lookback = gr.Slider(100, 400, 392, step=1, label="Lookback bars")
94
- pred_len = gr.Slider(12, 120, 120, step=1, label="Forecast bars")
95
- sample_count = gr.Slider(1, 30, 5, step=1, label="Monte Carlo samples")
96
- temperature = gr.Slider(0.1, 2.0, 1.0, step=0.1, label="Temperature (T)")
97
- top_p = gr.Slider(0.1, 1.0, 0.9, step=0.05, label="Top-p")
98
- run_btn = gr.Button("🚀 Forecast", variant="primary")
99
- with gr.Column(scale=3):
100
- chart_out = gr.Plot(label="Forecast Chart")
101
- summary_out = gr.Dataframe(label="Summary", interactive=False)
102
- pred_out = gr.Dataframe(label="Forecasted Bars", interactive=False)
103
- run_btn.click(run_forecast,
104
- inputs=[symbol, interval, lookback, pred_len, sample_count, temperature, top_p],
105
- outputs=[chart_out, summary_out, pred_out])
106
-
107
- import os
108
-
109
- if __name__ == "__main__":
110
- # Hugging Face Spaces sets SPACE_ID env var
111
- on_hf = os.getenv("SPACE_ID") is not None
112
- demo.launch(
113
- server_name="0.0.0.0" if on_hf else "127.0.0.1",
114
- server_port=7860,
115
- share=False,
116
- inbrowser=not on_hf,
117
- theme=gr.themes.Soft(),
118
  )
 
1
+ import os, requests
2
+ import numpy as np
3
+ import pandas as pd
4
+ import torch
5
+ import gradio as gr
6
+ import plotly.graph_objects as go
7
+ from plotly.subplots import make_subplots
8
+
9
+ from model import Kronos, KronosTokenizer, KronosPredictor
10
+
11
+ # ----- Load model once at startup -----
12
+ print("Loading Kronos-small on CPU...")
13
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
14
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-small")
15
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
16
+ predictor = KronosPredictor(model, tokenizer, device=device, max_context=512)
17
+ print(f"Model loaded on {device}")
18
+
19
+ FMP_KEY = os.getenv("FMP_API_KEY")
20
+
21
+ # ----- Data fetch -----
22
+ def fetch_fmp(symbol: str, interval: str, n_bars: int) -> pd.DataFrame:
23
+ url = (f"https://financialmodelingprep.com/api/v3/historical-chart/"
24
+ f"{interval}/{symbol}?apikey={FMP_KEY}")
25
+ r = requests.get(url, timeout=30); r.raise_for_status()
26
+ df = pd.DataFrame(r.json()).rename(columns={"date": "timestamps"})
27
+ if df.empty:
28
+ raise gr.Error(f"No data from FMP for {symbol} at {interval}")
29
+ df["timestamps"] = pd.to_datetime(df["timestamps"])
30
+ df = df.sort_values("timestamps").reset_index(drop=True)
31
+ df["amount"] = df["close"] * df["volume"]
32
+ df = df[["timestamps","open","high","low","close","volume","amount"]]
33
+ return df.tail(n_bars).reset_index(drop=True)
34
+
35
+ # ----- Forecast + chart -----
36
+ def run_forecast(symbol, interval, lookback, pred_len, sample_count, temperature, top_p):
37
+ lookback, pred_len, sample_count = int(lookback), int(pred_len), int(sample_count)
38
+ if lookback + pred_len > 512:
39
+ raise gr.Error(f"lookback + pred_len must be ≤ 512 (got {lookback+pred_len})")
40
+
41
+ df = fetch_fmp(symbol.upper(), interval, lookback + 10)
42
+ df = df.tail(lookback).reset_index(drop=True)
43
+
44
+ # Build future timestamps
45
+ step = df["timestamps"].diff().median()
46
+ y_timestamp = pd.Series([df["timestamps"].iloc[-1] + step*(i+1) for i in range(pred_len)])
47
+
48
+ x_df = df[["open","high","low","close","volume","amount"]]
49
+ x_timestamp = df["timestamps"]
50
+
51
+ pred_df = predictor.predict(
52
+ df=x_df, x_timestamp=x_timestamp, y_timestamp=y_timestamp,
53
+ pred_len=pred_len, T=temperature, top_p=top_p,
54
+ sample_count=sample_count, verbose=False,
55
+ )
56
+ pred_df.index = y_timestamp
57
+
58
+ # Plotly candlestick + forecast
59
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
60
+ row_heights=[0.75, 0.25], vertical_spacing=0.03,
61
+ subplot_titles=(f"{symbol.upper()} {interval} — Kronos Forecast", "Volume"))
62
+ fig.add_trace(go.Candlestick(x=df["timestamps"], open=df["open"], high=df["high"],
63
+ low=df["low"], close=df["close"], name="History"), row=1, col=1)
64
+ fig.add_trace(go.Candlestick(x=pred_df.index, open=pred_df["open"], high=pred_df["high"],
65
+ low=pred_df["low"], close=pred_df["close"],
66
+ name="Forecast",
67
+ increasing_line_color="#00CED1",
68
+ decreasing_line_color="#FF69B4"), row=1, col=1)
69
+ fig.add_trace(go.Bar(x=df["timestamps"], y=df["volume"], name="Vol", marker_color="#888"), row=2, col=1)
70
+ fig.add_trace(go.Bar(x=pred_df.index, y=pred_df["volume"], name="Vol (fcst)", marker_color="#00CED1"), row=2, col=1)
71
+ fig.update_layout(height=700, template="plotly_dark", xaxis_rangeslider_visible=False,
72
+ showlegend=True, margin=dict(l=20, r=20, t=50, b=20))
73
+
74
+ summary = pd.DataFrame({
75
+ "Metric": ["Last close", "Forecast close", "Expected change %", "Forecast high", "Forecast low"],
76
+ "Value": [
77
+ f"{df['close'].iloc[-1]:.2f}",
78
+ f"{pred_df['close'].iloc[-1]:.2f}",
79
+ f"{(pred_df['close'].iloc[-1]/df['close'].iloc[-1]-1)*100:+.2f}%",
80
+ f"{pred_df['high'].max():.2f}",
81
+ f"{pred_df['low'].min():.2f}",
82
+ ]
83
+ })
84
+ return fig, summary, pred_df.reset_index().rename(columns={"index":"timestamps"})
85
+
86
+ # ----- UI -----
87
+ with gr.Blocks(title="Kronos Forecast Dashboard") as demo:
88
+ gr.Markdown("# 📈 Kronos Financial Forecast Dashboard\nZero-shot OHLCV forecasting powered by [Kronos](https://github.com/shiyu-coder/Kronos) + FMP market data.")
89
+ with gr.Row():
90
+ with gr.Column(scale=1):
91
+ symbol = gr.Textbox("SPY", label="Symbol (e.g. SPY, AAPL, BTCUSD, EURUSD)")
92
+ interval = gr.Dropdown(["1min","5min","15min","30min","1hour","4hour"], value="5min", label="Interval")
93
+ lookback = gr.Slider(100, 400, 392, step=1, label="Lookback bars")
94
+ pred_len = gr.Slider(12, 120, 120, step=1, label="Forecast bars")
95
+ sample_count = gr.Slider(1, 30, 5, step=1, label="Monte Carlo samples")
96
+ temperature = gr.Slider(0.1, 2.0, 1.0, step=0.1, label="Temperature (T)")
97
+ top_p = gr.Slider(0.1, 1.0, 0.9, step=0.05, label="Top-p")
98
+ run_btn = gr.Button("🚀 Forecast", variant="primary")
99
+ with gr.Column(scale=3):
100
+ chart_out = gr.Plot(label="Forecast Chart")
101
+ summary_out = gr.Dataframe(label="Summary", interactive=False)
102
+ pred_out = gr.Dataframe(label="Forecasted Bars", interactive=False)
103
+ run_btn.click(run_forecast,
104
+ inputs=[symbol, interval, lookback, pred_len, sample_count, temperature, top_p],
105
+ outputs=[chart_out, summary_out, pred_out])
106
+
107
+ import os
108
+
109
+ if __name__ == "__main__":
110
+ # Hugging Face Spaces sets SPACE_ID env var
111
+ on_hf = os.getenv("SPACE_ID") is not None
112
+ demo.launch(
113
+ server_name="0.0.0.0" if on_hf else "127.0.0.1",
114
+ server_port=7860,
115
+ share=False,
116
+ inbrowser=not on_hf,
117
+ theme=gr.themes.Soft(),
118
  )
model/__init__.py CHANGED
@@ -1,17 +1,17 @@
1
- from .kronos import KronosTokenizer, Kronos, KronosPredictor
2
-
3
- model_dict = {
4
- 'kronos_tokenizer': KronosTokenizer,
5
- 'kronos': Kronos,
6
- 'kronos_predictor': KronosPredictor
7
- }
8
-
9
-
10
- def get_model_class(model_name):
11
- if model_name in model_dict:
12
- return model_dict[model_name]
13
- else:
14
- print(f"Model {model_name} not found in model_dict")
15
- raise NotImplementedError
16
-
17
-
 
1
+ from .kronos import KronosTokenizer, Kronos, KronosPredictor
2
+
3
+ model_dict = {
4
+ 'kronos_tokenizer': KronosTokenizer,
5
+ 'kronos': Kronos,
6
+ 'kronos_predictor': KronosPredictor
7
+ }
8
+
9
+
10
+ def get_model_class(model_name):
11
+ if model_name in model_dict:
12
+ return model_dict[model_name]
13
+ else:
14
+ print(f"Model {model_name} not found in model_dict")
15
+ raise NotImplementedError
16
+
17
+
model/kronos.py CHANGED
@@ -1,662 +1,662 @@
1
- import numpy as np
2
- import pandas as pd
3
- import torch
4
- from huggingface_hub import PyTorchModelHubMixin
5
- import sys
6
-
7
- from tqdm import trange
8
-
9
- sys.path.append("../")
10
- from model.module import *
11
-
12
-
13
- class KronosTokenizer(nn.Module, PyTorchModelHubMixin):
14
- """
15
- KronosTokenizer module for tokenizing input data using a hybrid quantization approach.
16
-
17
- This tokenizer utilizes a combination of encoder and decoder Transformer blocks
18
- along with the Binary Spherical Quantization (BSQuantizer) to compress and decompress input data.
19
-
20
- Args:
21
- d_in (int): Input dimension.
22
- d_model (int): Model dimension.
23
- n_heads (int): Number of attention heads.
24
- ff_dim (int): Feed-forward dimension.
25
- n_enc_layers (int): Number of encoder layers.
26
- n_dec_layers (int): Number of decoder layers.
27
- ffn_dropout_p (float): Dropout probability for feed-forward networks.
28
- attn_dropout_p (float): Dropout probability for attention mechanisms.
29
- resid_dropout_p (float): Dropout probability for residual connections.
30
- s1_bits (int): Number of bits for the pre token in BSQuantizer.
31
- s2_bits (int): Number of bits for the post token in BSQuantizer.
32
- beta (float): Beta parameter for BSQuantizer.
33
- gamma0 (float): Gamma0 parameter for BSQuantizer.
34
- gamma (float): Gamma parameter for BSQuantizer.
35
- zeta (float): Zeta parameter for BSQuantizer.
36
- group_size (int): Group size parameter for BSQuantizer.
37
-
38
- """
39
-
40
- def __init__(self, d_in, d_model, n_heads, ff_dim, n_enc_layers, n_dec_layers, ffn_dropout_p, attn_dropout_p, resid_dropout_p, s1_bits, s2_bits, beta, gamma0, gamma, zeta, group_size):
41
-
42
- super().__init__()
43
- self.d_in = d_in
44
- self.d_model = d_model
45
- self.n_heads = n_heads
46
- self.ff_dim = ff_dim
47
- self.enc_layers = n_enc_layers
48
- self.dec_layers = n_dec_layers
49
- self.ffn_dropout_p = ffn_dropout_p
50
- self.attn_dropout_p = attn_dropout_p
51
- self.resid_dropout_p = resid_dropout_p
52
-
53
- self.s1_bits = s1_bits
54
- self.s2_bits = s2_bits
55
- self.codebook_dim = s1_bits + s2_bits # Total dimension of the codebook after quantization
56
- self.embed = nn.Linear(self.d_in, self.d_model)
57
- self.head = nn.Linear(self.d_model, self.d_in)
58
-
59
- # Encoder Transformer Blocks
60
- self.encoder = nn.ModuleList([
61
- TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
62
- for _ in range(self.enc_layers - 1)
63
- ])
64
- # Decoder Transformer Blocks
65
- self.decoder = nn.ModuleList([
66
- TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
67
- for _ in range(self.dec_layers - 1)
68
- ])
69
- self.quant_embed = nn.Linear(in_features=self.d_model, out_features=self.codebook_dim) # Linear layer before quantization
70
- self.post_quant_embed_pre = nn.Linear(in_features=self.s1_bits, out_features=self.d_model) # Linear layer after quantization (pre part - s1 bits)
71
- self.post_quant_embed = nn.Linear(in_features=self.codebook_dim, out_features=self.d_model) # Linear layer after quantization (full codebook)
72
- self.tokenizer = BSQuantizer(self.s1_bits, self.s2_bits, beta, gamma0, gamma, zeta, group_size) # BSQuantizer module
73
-
74
- def forward(self, x):
75
- """
76
- Forward pass of the KronosTokenizer.
77
-
78
- Args:
79
- x (torch.Tensor): Input tensor of shape (batch_size, seq_len, d_in).
80
-
81
- Returns:
82
- tuple: A tuple containing:
83
- - tuple: (z_pre, z) - Reconstructed outputs from decoder with s1_bits and full codebook respectively,
84
- both of shape (batch_size, seq_len, d_in).
85
- - torch.Tensor: bsq_loss - Loss from the BSQuantizer.
86
- - torch.Tensor: quantized - Quantized representation from BSQuantizer.
87
- - torch.Tensor: z_indices - Indices from the BSQuantizer.
88
- """
89
- z = self.embed(x)
90
-
91
- for layer in self.encoder:
92
- z = layer(z)
93
-
94
- z = self.quant_embed(z) # (B, T, codebook)
95
-
96
- bsq_loss, quantized, z_indices = self.tokenizer(z)
97
-
98
- quantized_pre = quantized[:, :, :self.s1_bits] # Extract the first part of quantized representation (s1_bits)
99
- z_pre = self.post_quant_embed_pre(quantized_pre)
100
-
101
- z = self.post_quant_embed(quantized)
102
-
103
- # Decoder layers (for pre part - s1 bits)
104
- for layer in self.decoder:
105
- z_pre = layer(z_pre)
106
- z_pre = self.head(z_pre)
107
-
108
- # Decoder layers (for full codebook)
109
- for layer in self.decoder:
110
- z = layer(z)
111
- z = self.head(z)
112
-
113
- return (z_pre, z), bsq_loss, quantized, z_indices
114
-
115
- def indices_to_bits(self, x, half=False):
116
- """
117
- Converts indices to bit representations and scales them.
118
-
119
- Args:
120
- x (torch.Tensor): Indices tensor.
121
- half (bool, optional): Whether to process only half of the codebook dimension. Defaults to False.
122
-
123
- Returns:
124
- torch.Tensor: Bit representation tensor.
125
- """
126
- if half:
127
- x1 = x[0] # Assuming x is a tuple of indices if half is True
128
- x2 = x[1]
129
- mask = 2 ** torch.arange(self.codebook_dim//2, device=x1.device, dtype=torch.long) # Create a mask for bit extraction
130
- x1 = (x1.unsqueeze(-1) & mask) != 0 # Extract bits for the first half
131
- x2 = (x2.unsqueeze(-1) & mask) != 0 # Extract bits for the second half
132
- x = torch.cat([x1, x2], dim=-1) # Concatenate the bit representations
133
- else:
134
- mask = 2 ** torch.arange(self.codebook_dim, device=x.device, dtype=torch.long) # Create a mask for bit extraction
135
- x = (x.unsqueeze(-1) & mask) != 0 # Extract bits
136
-
137
- x = x.float() * 2 - 1 # Convert boolean to bipolar (-1, 1)
138
- q_scale = 1. / (self.codebook_dim ** 0.5) # Scaling factor
139
- x = x * q_scale
140
- return x
141
-
142
- def encode(self, x, half=False):
143
- """
144
- Encodes the input data into quantized indices.
145
-
146
- Args:
147
- x (torch.Tensor): Input tensor of shape (batch_size, seq_len, d_in).
148
- half (bool, optional): Whether to use half quantization in BSQuantizer. Defaults to False.
149
-
150
- Returns:
151
- torch.Tensor: Quantized indices from BSQuantizer.
152
- """
153
- z = self.embed(x)
154
- for layer in self.encoder:
155
- z = layer(z)
156
- z = self.quant_embed(z)
157
-
158
- bsq_loss, quantized, z_indices = self.tokenizer(z, half=half, collect_metrics=False)
159
- return z_indices
160
-
161
- def decode(self, x, half=False):
162
- """
163
- Decodes quantized indices back to the input data space.
164
-
165
- Args:
166
- x (torch.Tensor): Quantized indices tensor.
167
- half (bool, optional): Whether the indices were generated with half quantization. Defaults to False.
168
-
169
- Returns:
170
- torch.Tensor: Reconstructed output tensor of shape (batch_size, seq_len, d_in).
171
- """
172
- quantized = self.indices_to_bits(x, half)
173
- z = self.post_quant_embed(quantized)
174
- for layer in self.decoder:
175
- z = layer(z)
176
- z = self.head(z)
177
- return z
178
-
179
-
180
- class Kronos(nn.Module, PyTorchModelHubMixin):
181
- """
182
- Kronos Model.
183
-
184
- Args:
185
- s1_bits (int): Number of bits for pre tokens.
186
- s2_bits (int): Number of bits for post tokens.
187
- n_layers (int): Number of Transformer blocks.
188
- d_model (int): Dimension of the model's embeddings and hidden states.
189
- n_heads (int): Number of attention heads in the MultiheadAttention layers.
190
- ff_dim (int): Dimension of the feedforward network in the Transformer blocks.
191
- ffn_dropout_p (float): Dropout probability for the feedforward network.
192
- attn_dropout_p (float): Dropout probability for the attention layers.
193
- resid_dropout_p (float): Dropout probability for residual connections.
194
- token_dropout_p (float): Dropout probability for token embeddings.
195
- learn_te (bool): Whether to use learnable temporal embeddings.
196
- """
197
-
198
- def __init__(self, s1_bits, s2_bits, n_layers, d_model, n_heads, ff_dim, ffn_dropout_p, attn_dropout_p, resid_dropout_p, token_dropout_p, learn_te):
199
- super().__init__()
200
- self.s1_bits = s1_bits
201
- self.s2_bits = s2_bits
202
- self.n_layers = n_layers
203
- self.d_model = d_model
204
- self.n_heads = n_heads
205
- self.learn_te = learn_te
206
- self.ff_dim = ff_dim
207
- self.ffn_dropout_p = ffn_dropout_p
208
- self.attn_dropout_p = attn_dropout_p
209
- self.resid_dropout_p = resid_dropout_p
210
- self.token_dropout_p = token_dropout_p
211
-
212
- self.s1_vocab_size = 2 ** self.s1_bits
213
- self.token_drop = nn.Dropout(self.token_dropout_p)
214
- self.embedding = HierarchicalEmbedding(self.s1_bits, self.s2_bits, self.d_model)
215
- self.time_emb = TemporalEmbedding(self.d_model, self.learn_te)
216
- self.transformer = nn.ModuleList([
217
- TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
218
- for _ in range(self.n_layers)
219
- ])
220
- self.norm = RMSNorm(self.d_model)
221
- self.dep_layer = DependencyAwareLayer(self.d_model)
222
- self.head = DualHead(self.s1_bits, self.s2_bits, self.d_model)
223
- self.apply(self._init_weights)
224
-
225
- def _init_weights(self, module):
226
-
227
- if isinstance(module, nn.Linear):
228
- nn.init.xavier_normal_(module.weight)
229
- if module.bias is not None:
230
- nn.init.zeros_(module.bias)
231
- elif isinstance(module, nn.Embedding):
232
- nn.init.normal_(module.weight, mean=0, std=self.embedding.d_model ** -0.5)
233
- elif isinstance(module, nn.LayerNorm):
234
- nn.init.ones_(module.weight)
235
- nn.init.zeros_(module.bias)
236
- elif isinstance(module, RMSNorm):
237
- nn.init.ones_(module.weight)
238
-
239
- def forward(self, s1_ids, s2_ids, stamp=None, padding_mask=None, use_teacher_forcing=False, s1_targets=None):
240
- """
241
- Args:
242
- s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
243
- s2_ids (torch.Tensor): Input tensor of s2 token IDs. Shape: [batch_size, seq_len]
244
- stamp (torch.Tensor, optional): Temporal stamp tensor. Shape: [batch_size, seq_len]. Defaults to None.
245
- padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
246
- use_teacher_forcing (bool, optional): Whether to use teacher forcing for s1 decoding. Defaults to False.
247
- s1_targets (torch.Tensor, optional): Target s1 token IDs for teacher forcing. Shape: [batch_size, seq_len]. Defaults to None.
248
-
249
- Returns:
250
- Tuple[torch.Tensor, torch.Tensor]:
251
- - s1 logits: Logits for s1 token predictions. Shape: [batch_size, seq_len, s1_vocab_size]
252
- - s2_logits: Logits for s2 token predictions, conditioned on s1. Shape: [batch_size, seq_len, s2_vocab_size]
253
- """
254
- x = self.embedding([s1_ids, s2_ids])
255
- if stamp is not None:
256
- time_embedding = self.time_emb(stamp)
257
- x = x + time_embedding
258
- x = self.token_drop(x)
259
-
260
- for layer in self.transformer:
261
- x = layer(x, key_padding_mask=padding_mask)
262
-
263
- x = self.norm(x)
264
-
265
- s1_logits = self.head(x)
266
-
267
- if use_teacher_forcing:
268
- sibling_embed = self.embedding.emb_s1(s1_targets)
269
- else:
270
- s1_probs = F.softmax(s1_logits.detach(), dim=-1)
271
- sample_s1_ids = torch.multinomial(s1_probs.view(-1, self.s1_vocab_size), 1).view(s1_ids.shape)
272
- sibling_embed = self.embedding.emb_s1(sample_s1_ids)
273
-
274
- x2 = self.dep_layer(x, sibling_embed, key_padding_mask=padding_mask) # Dependency Aware Layer: Condition on s1 embeddings
275
- s2_logits = self.head.cond_forward(x2)
276
- return s1_logits, s2_logits
277
-
278
- def decode_s1(self, s1_ids, s2_ids, stamp=None, padding_mask=None):
279
- """
280
- Decodes only the s1 tokens.
281
-
282
- This method performs a forward pass to predict only s1 tokens. It returns the s1 logits
283
- and the context representation from the Transformer, which can be used for subsequent s2 decoding.
284
-
285
- Args:
286
- s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
287
- s2_ids (torch.Tensor): Input tensor of s2 token IDs. Shape: [batch_size, seq_len]
288
- stamp (torch.Tensor, optional): Temporal stamp tensor. Shape: [batch_size, seq_len]. Defaults to None.
289
- padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
290
-
291
- Returns:
292
- Tuple[torch.Tensor, torch.Tensor]:
293
- - s1 logits: Logits for s1 token predictions. Shape: [batch_size, seq_len, s1_vocab_size]
294
- - context: Context representation from the Transformer. Shape: [batch_size, seq_len, d_model]
295
- """
296
- x = self.embedding([s1_ids, s2_ids])
297
- if stamp is not None:
298
- time_embedding = self.time_emb(stamp)
299
- x = x + time_embedding
300
- x = self.token_drop(x)
301
-
302
- for layer in self.transformer:
303
- x = layer(x, key_padding_mask=padding_mask)
304
-
305
- x = self.norm(x)
306
-
307
- s1_logits = self.head(x)
308
- return s1_logits, x
309
-
310
- def decode_s2(self, context, s1_ids, padding_mask=None):
311
- """
312
- Decodes the s2 tokens, conditioned on the context and s1 tokens.
313
-
314
- This method decodes s2 tokens based on a pre-computed context representation (typically from `decode_s1`)
315
- and the s1 token IDs. It uses the dependency-aware layer and the conditional s2 head to predict s2 tokens.
316
-
317
- Args:
318
- context (torch.Tensor): Context representation from the transformer (output of decode_s1).
319
- Shape: [batch_size, seq_len, d_model]
320
- s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
321
- padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
322
-
323
- Returns:
324
- torch.Tensor: s2 logits. Shape: [batch_size, seq_len, s2_vocab_size]
325
- """
326
- sibling_embed = self.embedding.emb_s1(s1_ids)
327
- x2 = self.dep_layer(context, sibling_embed, key_padding_mask=padding_mask)
328
- return self.head.cond_forward(x2)
329
-
330
-
331
- def top_k_top_p_filtering(
332
- logits,
333
- top_k: int = 0,
334
- top_p: float = 1.0,
335
- filter_value: float = -float("Inf"),
336
- min_tokens_to_keep: int = 1,
337
- ):
338
- """Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
339
- Args:
340
- logits: logits distribution shape (batch size, vocabulary size)
341
- if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
342
- if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
343
- Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
344
- Make sure we keep at least min_tokens_to_keep per batch example in the output
345
- From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
346
- """
347
- if top_k > 0:
348
- top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check
349
- # Remove all tokens with a probability less than the last token of the top-k
350
- indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
351
- logits[indices_to_remove] = filter_value
352
- return logits
353
-
354
- if top_p < 1.0:
355
- sorted_logits, sorted_indices = torch.sort(logits, descending=True)
356
- cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
357
-
358
- # Remove tokens with cumulative probability above the threshold (token with 0 are kept)
359
- sorted_indices_to_remove = cumulative_probs > top_p
360
- if min_tokens_to_keep > 1:
361
- # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
362
- sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
363
- # Shift the indices to the right to keep also the first token above the threshold
364
- sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
365
- sorted_indices_to_remove[..., 0] = 0
366
-
367
- # scatter sorted tensors to original indexing
368
- indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
369
- logits[indices_to_remove] = filter_value
370
- return logits
371
-
372
-
373
- def sample_from_logits(logits, temperature=1.0, top_k=None, top_p=None, sample_logits=True):
374
- logits = logits / temperature
375
- if top_k is not None or top_p is not None:
376
- if top_k > 0 or top_p < 1.0:
377
- logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
378
-
379
- probs = F.softmax(logits, dim=-1)
380
-
381
- if not sample_logits:
382
- _, x = torch.topk(probs, k=1, dim=-1)
383
- else:
384
- x = torch.multinomial(probs, num_samples=1)
385
-
386
- return x
387
-
388
-
389
- def auto_regressive_inference(tokenizer, model, x, x_stamp, y_stamp, max_context, pred_len, clip=5, T=1.0, top_k=0, top_p=0.99, sample_count=5, verbose=False):
390
- with torch.no_grad():
391
- x = torch.clip(x, -clip, clip)
392
-
393
- device = x.device
394
- x = x.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, x.size(1), x.size(2)).to(device)
395
- x_stamp = x_stamp.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, x_stamp.size(1), x_stamp.size(2)).to(device)
396
- y_stamp = y_stamp.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, y_stamp.size(1), y_stamp.size(2)).to(device)
397
-
398
- x_token = tokenizer.encode(x, half=True)
399
-
400
- initial_seq_len = x.size(1)
401
- batch_size = x_token[0].size(0)
402
- total_seq_len = initial_seq_len + pred_len
403
- full_stamp = torch.cat([x_stamp, y_stamp], dim=1)
404
-
405
- generated_pre = x_token[0].new_empty(batch_size, pred_len)
406
- generated_post = x_token[1].new_empty(batch_size, pred_len)
407
-
408
- pre_buffer = x_token[0].new_zeros(batch_size, max_context)
409
- post_buffer = x_token[1].new_zeros(batch_size, max_context)
410
- buffer_len = min(initial_seq_len, max_context)
411
- if buffer_len > 0:
412
- start_idx = max(0, initial_seq_len - max_context)
413
- pre_buffer[:, :buffer_len] = x_token[0][:, start_idx:start_idx + buffer_len]
414
- post_buffer[:, :buffer_len] = x_token[1][:, start_idx:start_idx + buffer_len]
415
-
416
- if verbose:
417
- ran = trange
418
- else:
419
- ran = range
420
- for i in ran(pred_len):
421
- current_seq_len = initial_seq_len + i
422
- window_len = min(current_seq_len, max_context)
423
-
424
- if current_seq_len <= max_context:
425
- input_tokens = [
426
- pre_buffer[:, :window_len],
427
- post_buffer[:, :window_len]
428
- ]
429
- else:
430
- input_tokens = [pre_buffer, post_buffer]
431
-
432
- context_end = current_seq_len
433
- context_start = max(0, context_end - max_context)
434
- current_stamp = full_stamp[:, context_start:context_end, :].contiguous()
435
-
436
- s1_logits, context = model.decode_s1(input_tokens[0], input_tokens[1], current_stamp)
437
- s1_logits = s1_logits[:, -1, :]
438
- sample_pre = sample_from_logits(s1_logits, temperature=T, top_k=top_k, top_p=top_p, sample_logits=True)
439
-
440
- s2_logits = model.decode_s2(context, sample_pre)
441
- s2_logits = s2_logits[:, -1, :]
442
- sample_post = sample_from_logits(s2_logits, temperature=T, top_k=top_k, top_p=top_p, sample_logits=True)
443
-
444
- generated_pre[:, i] = sample_pre.squeeze(-1)
445
- generated_post[:, i] = sample_post.squeeze(-1)
446
-
447
- if current_seq_len < max_context:
448
- pre_buffer[:, current_seq_len] = sample_pre.squeeze(-1)
449
- post_buffer[:, current_seq_len] = sample_post.squeeze(-1)
450
- else:
451
- pre_buffer.copy_(torch.roll(pre_buffer, shifts=-1, dims=1))
452
- post_buffer.copy_(torch.roll(post_buffer, shifts=-1, dims=1))
453
- pre_buffer[:, -1] = sample_pre.squeeze(-1)
454
- post_buffer[:, -1] = sample_post.squeeze(-1)
455
-
456
- full_pre = torch.cat([x_token[0], generated_pre], dim=1)
457
- full_post = torch.cat([x_token[1], generated_post], dim=1)
458
-
459
- context_start = max(0, total_seq_len - max_context)
460
- input_tokens = [
461
- full_pre[:, context_start:total_seq_len].contiguous(),
462
- full_post[:, context_start:total_seq_len].contiguous()
463
- ]
464
- z = tokenizer.decode(input_tokens, half=True)
465
- z = z.reshape(-1, sample_count, z.size(1), z.size(2))
466
- preds = z.cpu().numpy()
467
- preds = np.mean(preds, axis=1)
468
-
469
- return preds
470
-
471
-
472
- def calc_time_stamps(x_timestamp):
473
- time_df = pd.DataFrame()
474
- time_df['minute'] = x_timestamp.dt.minute
475
- time_df['hour'] = x_timestamp.dt.hour
476
- time_df['weekday'] = x_timestamp.dt.weekday
477
- time_df['day'] = x_timestamp.dt.day
478
- time_df['month'] = x_timestamp.dt.month
479
- return time_df
480
-
481
-
482
- class KronosPredictor:
483
-
484
- def __init__(self, model, tokenizer, device=None, max_context=512, clip=5):
485
- self.tokenizer = tokenizer
486
- self.model = model
487
- self.max_context = max_context
488
- self.clip = clip
489
- self.price_cols = ['open', 'high', 'low', 'close']
490
- self.vol_col = 'volume'
491
- self.amt_vol = 'amount'
492
- self.time_cols = ['minute', 'hour', 'weekday', 'day', 'month']
493
-
494
- # Auto-detect device if not specified
495
- if device is None:
496
- if torch.cuda.is_available():
497
- device = "cuda:0"
498
- elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
499
- device = "mps"
500
- else:
501
- device = "cpu"
502
-
503
- self.device = device
504
-
505
- self.tokenizer = self.tokenizer.to(self.device)
506
- self.model = self.model.to(self.device)
507
-
508
- def generate(self, x, x_stamp, y_stamp, pred_len, T, top_k, top_p, sample_count, verbose):
509
-
510
- x_tensor = torch.from_numpy(np.array(x).astype(np.float32)).to(self.device)
511
- x_stamp_tensor = torch.from_numpy(np.array(x_stamp).astype(np.float32)).to(self.device)
512
- y_stamp_tensor = torch.from_numpy(np.array(y_stamp).astype(np.float32)).to(self.device)
513
-
514
- preds = auto_regressive_inference(self.tokenizer, self.model, x_tensor, x_stamp_tensor, y_stamp_tensor, self.max_context, pred_len,
515
- self.clip, T, top_k, top_p, sample_count, verbose)
516
- preds = preds[:, -pred_len:, :]
517
- return preds
518
-
519
- def predict(self, df, x_timestamp, y_timestamp, pred_len, T=1.0, top_k=0, top_p=0.9, sample_count=1, verbose=True):
520
-
521
- if not isinstance(df, pd.DataFrame):
522
- raise ValueError("Input must be a pandas DataFrame.")
523
-
524
- if not all(col in df.columns for col in self.price_cols):
525
- raise ValueError(f"Price columns {self.price_cols} not found in DataFrame.")
526
-
527
- df = df.copy()
528
- if self.vol_col not in df.columns:
529
- df[self.vol_col] = 0.0 # Fill missing volume with zeros
530
- df[self.amt_vol] = 0.0 # Fill missing amount with zeros
531
- if self.amt_vol not in df.columns and self.vol_col in df.columns:
532
- df[self.amt_vol] = df[self.vol_col] * df[self.price_cols].mean(axis=1)
533
-
534
- if df[self.price_cols + [self.vol_col, self.amt_vol]].isnull().values.any():
535
- raise ValueError("Input DataFrame contains NaN values in price or volume columns.")
536
-
537
- x_time_df = calc_time_stamps(x_timestamp)
538
- y_time_df = calc_time_stamps(y_timestamp)
539
-
540
- x = df[self.price_cols + [self.vol_col, self.amt_vol]].values.astype(np.float32)
541
- x_stamp = x_time_df.values.astype(np.float32)
542
- y_stamp = y_time_df.values.astype(np.float32)
543
-
544
- x_mean, x_std = np.mean(x, axis=0), np.std(x, axis=0)
545
-
546
- x = (x - x_mean) / (x_std + 1e-5)
547
- x = np.clip(x, -self.clip, self.clip)
548
-
549
- x = x[np.newaxis, :]
550
- x_stamp = x_stamp[np.newaxis, :]
551
- y_stamp = y_stamp[np.newaxis, :]
552
-
553
- preds = self.generate(x, x_stamp, y_stamp, pred_len, T, top_k, top_p, sample_count, verbose)
554
-
555
- preds = preds.squeeze(0)
556
- preds = preds * (x_std + 1e-5) + x_mean
557
-
558
- pred_df = pd.DataFrame(preds, columns=self.price_cols + [self.vol_col, self.amt_vol], index=y_timestamp)
559
- return pred_df
560
-
561
-
562
- def predict_batch(self, df_list, x_timestamp_list, y_timestamp_list, pred_len, T=1.0, top_k=0, top_p=0.9, sample_count=1, verbose=True):
563
- """
564
- Perform parallel (batch) prediction on multiple time series. All series must have the same historical length and prediction length (pred_len).
565
-
566
- Args:
567
- df_list (List[pd.DataFrame]): List of input DataFrames, each containing price columns and optional volume/amount columns.
568
- x_timestamp_list (List[pd.DatetimeIndex or Series]): List of timestamps corresponding to historical data, length should match the number of rows in each DataFrame.
569
- y_timestamp_list (List[pd.DatetimeIndex or Series]): List of future prediction timestamps, length should equal pred_len.
570
- pred_len (int): Number of prediction steps.
571
- T (float): Sampling temperature.
572
- top_k (int): Top-k filtering threshold.
573
- top_p (float): Top-p (nucleus sampling) threshold.
574
- sample_count (int): Number of parallel samples per series, automatically averaged internally.
575
- verbose (bool): Whether to display autoregressive progress.
576
-
577
- Returns:
578
- List[pd.DataFrame]: List of prediction results in the same order as input, each DataFrame contains
579
- `open, high, low, close, volume, amount` columns, indexed by corresponding `y_timestamp`.
580
- """
581
- # Basic validation
582
- if not isinstance(df_list, (list, tuple)) or not isinstance(x_timestamp_list, (list, tuple)) or not isinstance(y_timestamp_list, (list, tuple)):
583
- raise ValueError("df_list, x_timestamp_list, y_timestamp_list must be list or tuple types.")
584
- if not (len(df_list) == len(x_timestamp_list) == len(y_timestamp_list)):
585
- raise ValueError("df_list, x_timestamp_list, y_timestamp_list must have consistent lengths.")
586
-
587
- num_series = len(df_list)
588
-
589
- x_list = []
590
- x_stamp_list = []
591
- y_stamp_list = []
592
- means = []
593
- stds = []
594
- seq_lens = []
595
- y_lens = []
596
-
597
- for i in range(num_series):
598
- df = df_list[i]
599
- if not isinstance(df, pd.DataFrame):
600
- raise ValueError(f"Input at index {i} is not a pandas DataFrame.")
601
- if not all(col in df.columns for col in self.price_cols):
602
- raise ValueError(f"DataFrame at index {i} is missing price columns {self.price_cols}.")
603
-
604
- df = df.copy()
605
- if self.vol_col not in df.columns:
606
- df[self.vol_col] = 0.0
607
- df[self.amt_vol] = 0.0
608
- if self.amt_vol not in df.columns and self.vol_col in df.columns:
609
- df[self.amt_vol] = df[self.vol_col] * df[self.price_cols].mean(axis=1)
610
-
611
- if df[self.price_cols + [self.vol_col, self.amt_vol]].isnull().values.any():
612
- raise ValueError(f"DataFrame at index {i} contains NaN values in price or volume columns.")
613
-
614
- x_timestamp = x_timestamp_list[i]
615
- y_timestamp = y_timestamp_list[i]
616
-
617
- x_time_df = calc_time_stamps(x_timestamp)
618
- y_time_df = calc_time_stamps(y_timestamp)
619
-
620
- x = df[self.price_cols + [self.vol_col, self.amt_vol]].values.astype(np.float32)
621
- x_stamp = x_time_df.values.astype(np.float32)
622
- y_stamp = y_time_df.values.astype(np.float32)
623
-
624
- if x.shape[0] != x_stamp.shape[0]:
625
- raise ValueError(f"Inconsistent lengths at index {i}: x has {x.shape[0]} vs x_stamp has {x_stamp.shape[0]}.")
626
- if y_stamp.shape[0] != pred_len:
627
- raise ValueError(f"y_timestamp length at index {i} should equal pred_len={pred_len}, got {y_stamp.shape[0]}.")
628
-
629
- x_mean, x_std = np.mean(x, axis=0), np.std(x, axis=0)
630
- x_norm = (x - x_mean) / (x_std + 1e-5)
631
- x_norm = np.clip(x_norm, -self.clip, self.clip)
632
-
633
- x_list.append(x_norm)
634
- x_stamp_list.append(x_stamp)
635
- y_stamp_list.append(y_stamp)
636
- means.append(x_mean)
637
- stds.append(x_std)
638
-
639
- seq_lens.append(x_norm.shape[0])
640
- y_lens.append(y_stamp.shape[0])
641
-
642
- # Require all series to have consistent historical and prediction lengths for batch processing
643
- if len(set(seq_lens)) != 1:
644
- raise ValueError(f"Parallel prediction requires all series to have consistent historical lengths, got: {seq_lens}")
645
- if len(set(y_lens)) != 1:
646
- raise ValueError(f"Parallel prediction requires all series to have consistent prediction lengths, got: {y_lens}")
647
-
648
- x_batch = np.stack(x_list, axis=0).astype(np.float32) # (B, seq_len, feat)
649
- x_stamp_batch = np.stack(x_stamp_list, axis=0).astype(np.float32) # (B, seq_len, time_feat)
650
- y_stamp_batch = np.stack(y_stamp_list, axis=0).astype(np.float32) # (B, pred_len, time_feat)
651
-
652
- preds = self.generate(x_batch, x_stamp_batch, y_stamp_batch, pred_len, T, top_k, top_p, sample_count, verbose)
653
- # preds: (B, pred_len, feat)
654
-
655
- pred_dfs = []
656
- for i in range(num_series):
657
- preds_i = preds[i] * (stds[i] + 1e-5) + means[i]
658
- pred_df = pd.DataFrame(preds_i, columns=self.price_cols + [self.vol_col, self.amt_vol], index=y_timestamp_list[i])
659
- pred_dfs.append(pred_df)
660
-
661
- return pred_dfs
662
-
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ from huggingface_hub import PyTorchModelHubMixin
5
+ import sys
6
+
7
+ from tqdm import trange
8
+
9
+ sys.path.append("../")
10
+ from model.module import *
11
+
12
+
13
+ class KronosTokenizer(nn.Module, PyTorchModelHubMixin):
14
+ """
15
+ KronosTokenizer module for tokenizing input data using a hybrid quantization approach.
16
+
17
+ This tokenizer utilizes a combination of encoder and decoder Transformer blocks
18
+ along with the Binary Spherical Quantization (BSQuantizer) to compress and decompress input data.
19
+
20
+ Args:
21
+ d_in (int): Input dimension.
22
+ d_model (int): Model dimension.
23
+ n_heads (int): Number of attention heads.
24
+ ff_dim (int): Feed-forward dimension.
25
+ n_enc_layers (int): Number of encoder layers.
26
+ n_dec_layers (int): Number of decoder layers.
27
+ ffn_dropout_p (float): Dropout probability for feed-forward networks.
28
+ attn_dropout_p (float): Dropout probability for attention mechanisms.
29
+ resid_dropout_p (float): Dropout probability for residual connections.
30
+ s1_bits (int): Number of bits for the pre token in BSQuantizer.
31
+ s2_bits (int): Number of bits for the post token in BSQuantizer.
32
+ beta (float): Beta parameter for BSQuantizer.
33
+ gamma0 (float): Gamma0 parameter for BSQuantizer.
34
+ gamma (float): Gamma parameter for BSQuantizer.
35
+ zeta (float): Zeta parameter for BSQuantizer.
36
+ group_size (int): Group size parameter for BSQuantizer.
37
+
38
+ """
39
+
40
+ def __init__(self, d_in, d_model, n_heads, ff_dim, n_enc_layers, n_dec_layers, ffn_dropout_p, attn_dropout_p, resid_dropout_p, s1_bits, s2_bits, beta, gamma0, gamma, zeta, group_size):
41
+
42
+ super().__init__()
43
+ self.d_in = d_in
44
+ self.d_model = d_model
45
+ self.n_heads = n_heads
46
+ self.ff_dim = ff_dim
47
+ self.enc_layers = n_enc_layers
48
+ self.dec_layers = n_dec_layers
49
+ self.ffn_dropout_p = ffn_dropout_p
50
+ self.attn_dropout_p = attn_dropout_p
51
+ self.resid_dropout_p = resid_dropout_p
52
+
53
+ self.s1_bits = s1_bits
54
+ self.s2_bits = s2_bits
55
+ self.codebook_dim = s1_bits + s2_bits # Total dimension of the codebook after quantization
56
+ self.embed = nn.Linear(self.d_in, self.d_model)
57
+ self.head = nn.Linear(self.d_model, self.d_in)
58
+
59
+ # Encoder Transformer Blocks
60
+ self.encoder = nn.ModuleList([
61
+ TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
62
+ for _ in range(self.enc_layers - 1)
63
+ ])
64
+ # Decoder Transformer Blocks
65
+ self.decoder = nn.ModuleList([
66
+ TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
67
+ for _ in range(self.dec_layers - 1)
68
+ ])
69
+ self.quant_embed = nn.Linear(in_features=self.d_model, out_features=self.codebook_dim) # Linear layer before quantization
70
+ self.post_quant_embed_pre = nn.Linear(in_features=self.s1_bits, out_features=self.d_model) # Linear layer after quantization (pre part - s1 bits)
71
+ self.post_quant_embed = nn.Linear(in_features=self.codebook_dim, out_features=self.d_model) # Linear layer after quantization (full codebook)
72
+ self.tokenizer = BSQuantizer(self.s1_bits, self.s2_bits, beta, gamma0, gamma, zeta, group_size) # BSQuantizer module
73
+
74
+ def forward(self, x):
75
+ """
76
+ Forward pass of the KronosTokenizer.
77
+
78
+ Args:
79
+ x (torch.Tensor): Input tensor of shape (batch_size, seq_len, d_in).
80
+
81
+ Returns:
82
+ tuple: A tuple containing:
83
+ - tuple: (z_pre, z) - Reconstructed outputs from decoder with s1_bits and full codebook respectively,
84
+ both of shape (batch_size, seq_len, d_in).
85
+ - torch.Tensor: bsq_loss - Loss from the BSQuantizer.
86
+ - torch.Tensor: quantized - Quantized representation from BSQuantizer.
87
+ - torch.Tensor: z_indices - Indices from the BSQuantizer.
88
+ """
89
+ z = self.embed(x)
90
+
91
+ for layer in self.encoder:
92
+ z = layer(z)
93
+
94
+ z = self.quant_embed(z) # (B, T, codebook)
95
+
96
+ bsq_loss, quantized, z_indices = self.tokenizer(z)
97
+
98
+ quantized_pre = quantized[:, :, :self.s1_bits] # Extract the first part of quantized representation (s1_bits)
99
+ z_pre = self.post_quant_embed_pre(quantized_pre)
100
+
101
+ z = self.post_quant_embed(quantized)
102
+
103
+ # Decoder layers (for pre part - s1 bits)
104
+ for layer in self.decoder:
105
+ z_pre = layer(z_pre)
106
+ z_pre = self.head(z_pre)
107
+
108
+ # Decoder layers (for full codebook)
109
+ for layer in self.decoder:
110
+ z = layer(z)
111
+ z = self.head(z)
112
+
113
+ return (z_pre, z), bsq_loss, quantized, z_indices
114
+
115
+ def indices_to_bits(self, x, half=False):
116
+ """
117
+ Converts indices to bit representations and scales them.
118
+
119
+ Args:
120
+ x (torch.Tensor): Indices tensor.
121
+ half (bool, optional): Whether to process only half of the codebook dimension. Defaults to False.
122
+
123
+ Returns:
124
+ torch.Tensor: Bit representation tensor.
125
+ """
126
+ if half:
127
+ x1 = x[0] # Assuming x is a tuple of indices if half is True
128
+ x2 = x[1]
129
+ mask = 2 ** torch.arange(self.codebook_dim//2, device=x1.device, dtype=torch.long) # Create a mask for bit extraction
130
+ x1 = (x1.unsqueeze(-1) & mask) != 0 # Extract bits for the first half
131
+ x2 = (x2.unsqueeze(-1) & mask) != 0 # Extract bits for the second half
132
+ x = torch.cat([x1, x2], dim=-1) # Concatenate the bit representations
133
+ else:
134
+ mask = 2 ** torch.arange(self.codebook_dim, device=x.device, dtype=torch.long) # Create a mask for bit extraction
135
+ x = (x.unsqueeze(-1) & mask) != 0 # Extract bits
136
+
137
+ x = x.float() * 2 - 1 # Convert boolean to bipolar (-1, 1)
138
+ q_scale = 1. / (self.codebook_dim ** 0.5) # Scaling factor
139
+ x = x * q_scale
140
+ return x
141
+
142
+ def encode(self, x, half=False):
143
+ """
144
+ Encodes the input data into quantized indices.
145
+
146
+ Args:
147
+ x (torch.Tensor): Input tensor of shape (batch_size, seq_len, d_in).
148
+ half (bool, optional): Whether to use half quantization in BSQuantizer. Defaults to False.
149
+
150
+ Returns:
151
+ torch.Tensor: Quantized indices from BSQuantizer.
152
+ """
153
+ z = self.embed(x)
154
+ for layer in self.encoder:
155
+ z = layer(z)
156
+ z = self.quant_embed(z)
157
+
158
+ bsq_loss, quantized, z_indices = self.tokenizer(z, half=half, collect_metrics=False)
159
+ return z_indices
160
+
161
+ def decode(self, x, half=False):
162
+ """
163
+ Decodes quantized indices back to the input data space.
164
+
165
+ Args:
166
+ x (torch.Tensor): Quantized indices tensor.
167
+ half (bool, optional): Whether the indices were generated with half quantization. Defaults to False.
168
+
169
+ Returns:
170
+ torch.Tensor: Reconstructed output tensor of shape (batch_size, seq_len, d_in).
171
+ """
172
+ quantized = self.indices_to_bits(x, half)
173
+ z = self.post_quant_embed(quantized)
174
+ for layer in self.decoder:
175
+ z = layer(z)
176
+ z = self.head(z)
177
+ return z
178
+
179
+
180
+ class Kronos(nn.Module, PyTorchModelHubMixin):
181
+ """
182
+ Kronos Model.
183
+
184
+ Args:
185
+ s1_bits (int): Number of bits for pre tokens.
186
+ s2_bits (int): Number of bits for post tokens.
187
+ n_layers (int): Number of Transformer blocks.
188
+ d_model (int): Dimension of the model's embeddings and hidden states.
189
+ n_heads (int): Number of attention heads in the MultiheadAttention layers.
190
+ ff_dim (int): Dimension of the feedforward network in the Transformer blocks.
191
+ ffn_dropout_p (float): Dropout probability for the feedforward network.
192
+ attn_dropout_p (float): Dropout probability for the attention layers.
193
+ resid_dropout_p (float): Dropout probability for residual connections.
194
+ token_dropout_p (float): Dropout probability for token embeddings.
195
+ learn_te (bool): Whether to use learnable temporal embeddings.
196
+ """
197
+
198
+ def __init__(self, s1_bits, s2_bits, n_layers, d_model, n_heads, ff_dim, ffn_dropout_p, attn_dropout_p, resid_dropout_p, token_dropout_p, learn_te):
199
+ super().__init__()
200
+ self.s1_bits = s1_bits
201
+ self.s2_bits = s2_bits
202
+ self.n_layers = n_layers
203
+ self.d_model = d_model
204
+ self.n_heads = n_heads
205
+ self.learn_te = learn_te
206
+ self.ff_dim = ff_dim
207
+ self.ffn_dropout_p = ffn_dropout_p
208
+ self.attn_dropout_p = attn_dropout_p
209
+ self.resid_dropout_p = resid_dropout_p
210
+ self.token_dropout_p = token_dropout_p
211
+
212
+ self.s1_vocab_size = 2 ** self.s1_bits
213
+ self.token_drop = nn.Dropout(self.token_dropout_p)
214
+ self.embedding = HierarchicalEmbedding(self.s1_bits, self.s2_bits, self.d_model)
215
+ self.time_emb = TemporalEmbedding(self.d_model, self.learn_te)
216
+ self.transformer = nn.ModuleList([
217
+ TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
218
+ for _ in range(self.n_layers)
219
+ ])
220
+ self.norm = RMSNorm(self.d_model)
221
+ self.dep_layer = DependencyAwareLayer(self.d_model)
222
+ self.head = DualHead(self.s1_bits, self.s2_bits, self.d_model)
223
+ self.apply(self._init_weights)
224
+
225
+ def _init_weights(self, module):
226
+
227
+ if isinstance(module, nn.Linear):
228
+ nn.init.xavier_normal_(module.weight)
229
+ if module.bias is not None:
230
+ nn.init.zeros_(module.bias)
231
+ elif isinstance(module, nn.Embedding):
232
+ nn.init.normal_(module.weight, mean=0, std=self.embedding.d_model ** -0.5)
233
+ elif isinstance(module, nn.LayerNorm):
234
+ nn.init.ones_(module.weight)
235
+ nn.init.zeros_(module.bias)
236
+ elif isinstance(module, RMSNorm):
237
+ nn.init.ones_(module.weight)
238
+
239
+ def forward(self, s1_ids, s2_ids, stamp=None, padding_mask=None, use_teacher_forcing=False, s1_targets=None):
240
+ """
241
+ Args:
242
+ s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
243
+ s2_ids (torch.Tensor): Input tensor of s2 token IDs. Shape: [batch_size, seq_len]
244
+ stamp (torch.Tensor, optional): Temporal stamp tensor. Shape: [batch_size, seq_len]. Defaults to None.
245
+ padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
246
+ use_teacher_forcing (bool, optional): Whether to use teacher forcing for s1 decoding. Defaults to False.
247
+ s1_targets (torch.Tensor, optional): Target s1 token IDs for teacher forcing. Shape: [batch_size, seq_len]. Defaults to None.
248
+
249
+ Returns:
250
+ Tuple[torch.Tensor, torch.Tensor]:
251
+ - s1 logits: Logits for s1 token predictions. Shape: [batch_size, seq_len, s1_vocab_size]
252
+ - s2_logits: Logits for s2 token predictions, conditioned on s1. Shape: [batch_size, seq_len, s2_vocab_size]
253
+ """
254
+ x = self.embedding([s1_ids, s2_ids])
255
+ if stamp is not None:
256
+ time_embedding = self.time_emb(stamp)
257
+ x = x + time_embedding
258
+ x = self.token_drop(x)
259
+
260
+ for layer in self.transformer:
261
+ x = layer(x, key_padding_mask=padding_mask)
262
+
263
+ x = self.norm(x)
264
+
265
+ s1_logits = self.head(x)
266
+
267
+ if use_teacher_forcing:
268
+ sibling_embed = self.embedding.emb_s1(s1_targets)
269
+ else:
270
+ s1_probs = F.softmax(s1_logits.detach(), dim=-1)
271
+ sample_s1_ids = torch.multinomial(s1_probs.view(-1, self.s1_vocab_size), 1).view(s1_ids.shape)
272
+ sibling_embed = self.embedding.emb_s1(sample_s1_ids)
273
+
274
+ x2 = self.dep_layer(x, sibling_embed, key_padding_mask=padding_mask) # Dependency Aware Layer: Condition on s1 embeddings
275
+ s2_logits = self.head.cond_forward(x2)
276
+ return s1_logits, s2_logits
277
+
278
+ def decode_s1(self, s1_ids, s2_ids, stamp=None, padding_mask=None):
279
+ """
280
+ Decodes only the s1 tokens.
281
+
282
+ This method performs a forward pass to predict only s1 tokens. It returns the s1 logits
283
+ and the context representation from the Transformer, which can be used for subsequent s2 decoding.
284
+
285
+ Args:
286
+ s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
287
+ s2_ids (torch.Tensor): Input tensor of s2 token IDs. Shape: [batch_size, seq_len]
288
+ stamp (torch.Tensor, optional): Temporal stamp tensor. Shape: [batch_size, seq_len]. Defaults to None.
289
+ padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
290
+
291
+ Returns:
292
+ Tuple[torch.Tensor, torch.Tensor]:
293
+ - s1 logits: Logits for s1 token predictions. Shape: [batch_size, seq_len, s1_vocab_size]
294
+ - context: Context representation from the Transformer. Shape: [batch_size, seq_len, d_model]
295
+ """
296
+ x = self.embedding([s1_ids, s2_ids])
297
+ if stamp is not None:
298
+ time_embedding = self.time_emb(stamp)
299
+ x = x + time_embedding
300
+ x = self.token_drop(x)
301
+
302
+ for layer in self.transformer:
303
+ x = layer(x, key_padding_mask=padding_mask)
304
+
305
+ x = self.norm(x)
306
+
307
+ s1_logits = self.head(x)
308
+ return s1_logits, x
309
+
310
+ def decode_s2(self, context, s1_ids, padding_mask=None):
311
+ """
312
+ Decodes the s2 tokens, conditioned on the context and s1 tokens.
313
+
314
+ This method decodes s2 tokens based on a pre-computed context representation (typically from `decode_s1`)
315
+ and the s1 token IDs. It uses the dependency-aware layer and the conditional s2 head to predict s2 tokens.
316
+
317
+ Args:
318
+ context (torch.Tensor): Context representation from the transformer (output of decode_s1).
319
+ Shape: [batch_size, seq_len, d_model]
320
+ s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
321
+ padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
322
+
323
+ Returns:
324
+ torch.Tensor: s2 logits. Shape: [batch_size, seq_len, s2_vocab_size]
325
+ """
326
+ sibling_embed = self.embedding.emb_s1(s1_ids)
327
+ x2 = self.dep_layer(context, sibling_embed, key_padding_mask=padding_mask)
328
+ return self.head.cond_forward(x2)
329
+
330
+
331
+ def top_k_top_p_filtering(
332
+ logits,
333
+ top_k: int = 0,
334
+ top_p: float = 1.0,
335
+ filter_value: float = -float("Inf"),
336
+ min_tokens_to_keep: int = 1,
337
+ ):
338
+ """Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
339
+ Args:
340
+ logits: logits distribution shape (batch size, vocabulary size)
341
+ if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
342
+ if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
343
+ Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
344
+ Make sure we keep at least min_tokens_to_keep per batch example in the output
345
+ From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
346
+ """
347
+ if top_k > 0:
348
+ top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check
349
+ # Remove all tokens with a probability less than the last token of the top-k
350
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
351
+ logits[indices_to_remove] = filter_value
352
+ return logits
353
+
354
+ if top_p < 1.0:
355
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
356
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
357
+
358
+ # Remove tokens with cumulative probability above the threshold (token with 0 are kept)
359
+ sorted_indices_to_remove = cumulative_probs > top_p
360
+ if min_tokens_to_keep > 1:
361
+ # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
362
+ sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
363
+ # Shift the indices to the right to keep also the first token above the threshold
364
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
365
+ sorted_indices_to_remove[..., 0] = 0
366
+
367
+ # scatter sorted tensors to original indexing
368
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
369
+ logits[indices_to_remove] = filter_value
370
+ return logits
371
+
372
+
373
+ def sample_from_logits(logits, temperature=1.0, top_k=None, top_p=None, sample_logits=True):
374
+ logits = logits / temperature
375
+ if top_k is not None or top_p is not None:
376
+ if top_k > 0 or top_p < 1.0:
377
+ logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
378
+
379
+ probs = F.softmax(logits, dim=-1)
380
+
381
+ if not sample_logits:
382
+ _, x = torch.topk(probs, k=1, dim=-1)
383
+ else:
384
+ x = torch.multinomial(probs, num_samples=1)
385
+
386
+ return x
387
+
388
+
389
+ def auto_regressive_inference(tokenizer, model, x, x_stamp, y_stamp, max_context, pred_len, clip=5, T=1.0, top_k=0, top_p=0.99, sample_count=5, verbose=False):
390
+ with torch.no_grad():
391
+ x = torch.clip(x, -clip, clip)
392
+
393
+ device = x.device
394
+ x = x.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, x.size(1), x.size(2)).to(device)
395
+ x_stamp = x_stamp.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, x_stamp.size(1), x_stamp.size(2)).to(device)
396
+ y_stamp = y_stamp.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, y_stamp.size(1), y_stamp.size(2)).to(device)
397
+
398
+ x_token = tokenizer.encode(x, half=True)
399
+
400
+ initial_seq_len = x.size(1)
401
+ batch_size = x_token[0].size(0)
402
+ total_seq_len = initial_seq_len + pred_len
403
+ full_stamp = torch.cat([x_stamp, y_stamp], dim=1)
404
+
405
+ generated_pre = x_token[0].new_empty(batch_size, pred_len)
406
+ generated_post = x_token[1].new_empty(batch_size, pred_len)
407
+
408
+ pre_buffer = x_token[0].new_zeros(batch_size, max_context)
409
+ post_buffer = x_token[1].new_zeros(batch_size, max_context)
410
+ buffer_len = min(initial_seq_len, max_context)
411
+ if buffer_len > 0:
412
+ start_idx = max(0, initial_seq_len - max_context)
413
+ pre_buffer[:, :buffer_len] = x_token[0][:, start_idx:start_idx + buffer_len]
414
+ post_buffer[:, :buffer_len] = x_token[1][:, start_idx:start_idx + buffer_len]
415
+
416
+ if verbose:
417
+ ran = trange
418
+ else:
419
+ ran = range
420
+ for i in ran(pred_len):
421
+ current_seq_len = initial_seq_len + i
422
+ window_len = min(current_seq_len, max_context)
423
+
424
+ if current_seq_len <= max_context:
425
+ input_tokens = [
426
+ pre_buffer[:, :window_len],
427
+ post_buffer[:, :window_len]
428
+ ]
429
+ else:
430
+ input_tokens = [pre_buffer, post_buffer]
431
+
432
+ context_end = current_seq_len
433
+ context_start = max(0, context_end - max_context)
434
+ current_stamp = full_stamp[:, context_start:context_end, :].contiguous()
435
+
436
+ s1_logits, context = model.decode_s1(input_tokens[0], input_tokens[1], current_stamp)
437
+ s1_logits = s1_logits[:, -1, :]
438
+ sample_pre = sample_from_logits(s1_logits, temperature=T, top_k=top_k, top_p=top_p, sample_logits=True)
439
+
440
+ s2_logits = model.decode_s2(context, sample_pre)
441
+ s2_logits = s2_logits[:, -1, :]
442
+ sample_post = sample_from_logits(s2_logits, temperature=T, top_k=top_k, top_p=top_p, sample_logits=True)
443
+
444
+ generated_pre[:, i] = sample_pre.squeeze(-1)
445
+ generated_post[:, i] = sample_post.squeeze(-1)
446
+
447
+ if current_seq_len < max_context:
448
+ pre_buffer[:, current_seq_len] = sample_pre.squeeze(-1)
449
+ post_buffer[:, current_seq_len] = sample_post.squeeze(-1)
450
+ else:
451
+ pre_buffer.copy_(torch.roll(pre_buffer, shifts=-1, dims=1))
452
+ post_buffer.copy_(torch.roll(post_buffer, shifts=-1, dims=1))
453
+ pre_buffer[:, -1] = sample_pre.squeeze(-1)
454
+ post_buffer[:, -1] = sample_post.squeeze(-1)
455
+
456
+ full_pre = torch.cat([x_token[0], generated_pre], dim=1)
457
+ full_post = torch.cat([x_token[1], generated_post], dim=1)
458
+
459
+ context_start = max(0, total_seq_len - max_context)
460
+ input_tokens = [
461
+ full_pre[:, context_start:total_seq_len].contiguous(),
462
+ full_post[:, context_start:total_seq_len].contiguous()
463
+ ]
464
+ z = tokenizer.decode(input_tokens, half=True)
465
+ z = z.reshape(-1, sample_count, z.size(1), z.size(2))
466
+ preds = z.cpu().numpy()
467
+ preds = np.mean(preds, axis=1)
468
+
469
+ return preds
470
+
471
+
472
+ def calc_time_stamps(x_timestamp):
473
+ time_df = pd.DataFrame()
474
+ time_df['minute'] = x_timestamp.dt.minute
475
+ time_df['hour'] = x_timestamp.dt.hour
476
+ time_df['weekday'] = x_timestamp.dt.weekday
477
+ time_df['day'] = x_timestamp.dt.day
478
+ time_df['month'] = x_timestamp.dt.month
479
+ return time_df
480
+
481
+
482
+ class KronosPredictor:
483
+
484
+ def __init__(self, model, tokenizer, device=None, max_context=512, clip=5):
485
+ self.tokenizer = tokenizer
486
+ self.model = model
487
+ self.max_context = max_context
488
+ self.clip = clip
489
+ self.price_cols = ['open', 'high', 'low', 'close']
490
+ self.vol_col = 'volume'
491
+ self.amt_vol = 'amount'
492
+ self.time_cols = ['minute', 'hour', 'weekday', 'day', 'month']
493
+
494
+ # Auto-detect device if not specified
495
+ if device is None:
496
+ if torch.cuda.is_available():
497
+ device = "cuda:0"
498
+ elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
499
+ device = "mps"
500
+ else:
501
+ device = "cpu"
502
+
503
+ self.device = device
504
+
505
+ self.tokenizer = self.tokenizer.to(self.device)
506
+ self.model = self.model.to(self.device)
507
+
508
+ def generate(self, x, x_stamp, y_stamp, pred_len, T, top_k, top_p, sample_count, verbose):
509
+
510
+ x_tensor = torch.from_numpy(np.array(x).astype(np.float32)).to(self.device)
511
+ x_stamp_tensor = torch.from_numpy(np.array(x_stamp).astype(np.float32)).to(self.device)
512
+ y_stamp_tensor = torch.from_numpy(np.array(y_stamp).astype(np.float32)).to(self.device)
513
+
514
+ preds = auto_regressive_inference(self.tokenizer, self.model, x_tensor, x_stamp_tensor, y_stamp_tensor, self.max_context, pred_len,
515
+ self.clip, T, top_k, top_p, sample_count, verbose)
516
+ preds = preds[:, -pred_len:, :]
517
+ return preds
518
+
519
+ def predict(self, df, x_timestamp, y_timestamp, pred_len, T=1.0, top_k=0, top_p=0.9, sample_count=1, verbose=True):
520
+
521
+ if not isinstance(df, pd.DataFrame):
522
+ raise ValueError("Input must be a pandas DataFrame.")
523
+
524
+ if not all(col in df.columns for col in self.price_cols):
525
+ raise ValueError(f"Price columns {self.price_cols} not found in DataFrame.")
526
+
527
+ df = df.copy()
528
+ if self.vol_col not in df.columns:
529
+ df[self.vol_col] = 0.0 # Fill missing volume with zeros
530
+ df[self.amt_vol] = 0.0 # Fill missing amount with zeros
531
+ if self.amt_vol not in df.columns and self.vol_col in df.columns:
532
+ df[self.amt_vol] = df[self.vol_col] * df[self.price_cols].mean(axis=1)
533
+
534
+ if df[self.price_cols + [self.vol_col, self.amt_vol]].isnull().values.any():
535
+ raise ValueError("Input DataFrame contains NaN values in price or volume columns.")
536
+
537
+ x_time_df = calc_time_stamps(x_timestamp)
538
+ y_time_df = calc_time_stamps(y_timestamp)
539
+
540
+ x = df[self.price_cols + [self.vol_col, self.amt_vol]].values.astype(np.float32)
541
+ x_stamp = x_time_df.values.astype(np.float32)
542
+ y_stamp = y_time_df.values.astype(np.float32)
543
+
544
+ x_mean, x_std = np.mean(x, axis=0), np.std(x, axis=0)
545
+
546
+ x = (x - x_mean) / (x_std + 1e-5)
547
+ x = np.clip(x, -self.clip, self.clip)
548
+
549
+ x = x[np.newaxis, :]
550
+ x_stamp = x_stamp[np.newaxis, :]
551
+ y_stamp = y_stamp[np.newaxis, :]
552
+
553
+ preds = self.generate(x, x_stamp, y_stamp, pred_len, T, top_k, top_p, sample_count, verbose)
554
+
555
+ preds = preds.squeeze(0)
556
+ preds = preds * (x_std + 1e-5) + x_mean
557
+
558
+ pred_df = pd.DataFrame(preds, columns=self.price_cols + [self.vol_col, self.amt_vol], index=y_timestamp)
559
+ return pred_df
560
+
561
+
562
+ def predict_batch(self, df_list, x_timestamp_list, y_timestamp_list, pred_len, T=1.0, top_k=0, top_p=0.9, sample_count=1, verbose=True):
563
+ """
564
+ Perform parallel (batch) prediction on multiple time series. All series must have the same historical length and prediction length (pred_len).
565
+
566
+ Args:
567
+ df_list (List[pd.DataFrame]): List of input DataFrames, each containing price columns and optional volume/amount columns.
568
+ x_timestamp_list (List[pd.DatetimeIndex or Series]): List of timestamps corresponding to historical data, length should match the number of rows in each DataFrame.
569
+ y_timestamp_list (List[pd.DatetimeIndex or Series]): List of future prediction timestamps, length should equal pred_len.
570
+ pred_len (int): Number of prediction steps.
571
+ T (float): Sampling temperature.
572
+ top_k (int): Top-k filtering threshold.
573
+ top_p (float): Top-p (nucleus sampling) threshold.
574
+ sample_count (int): Number of parallel samples per series, automatically averaged internally.
575
+ verbose (bool): Whether to display autoregressive progress.
576
+
577
+ Returns:
578
+ List[pd.DataFrame]: List of prediction results in the same order as input, each DataFrame contains
579
+ `open, high, low, close, volume, amount` columns, indexed by corresponding `y_timestamp`.
580
+ """
581
+ # Basic validation
582
+ if not isinstance(df_list, (list, tuple)) or not isinstance(x_timestamp_list, (list, tuple)) or not isinstance(y_timestamp_list, (list, tuple)):
583
+ raise ValueError("df_list, x_timestamp_list, y_timestamp_list must be list or tuple types.")
584
+ if not (len(df_list) == len(x_timestamp_list) == len(y_timestamp_list)):
585
+ raise ValueError("df_list, x_timestamp_list, y_timestamp_list must have consistent lengths.")
586
+
587
+ num_series = len(df_list)
588
+
589
+ x_list = []
590
+ x_stamp_list = []
591
+ y_stamp_list = []
592
+ means = []
593
+ stds = []
594
+ seq_lens = []
595
+ y_lens = []
596
+
597
+ for i in range(num_series):
598
+ df = df_list[i]
599
+ if not isinstance(df, pd.DataFrame):
600
+ raise ValueError(f"Input at index {i} is not a pandas DataFrame.")
601
+ if not all(col in df.columns for col in self.price_cols):
602
+ raise ValueError(f"DataFrame at index {i} is missing price columns {self.price_cols}.")
603
+
604
+ df = df.copy()
605
+ if self.vol_col not in df.columns:
606
+ df[self.vol_col] = 0.0
607
+ df[self.amt_vol] = 0.0
608
+ if self.amt_vol not in df.columns and self.vol_col in df.columns:
609
+ df[self.amt_vol] = df[self.vol_col] * df[self.price_cols].mean(axis=1)
610
+
611
+ if df[self.price_cols + [self.vol_col, self.amt_vol]].isnull().values.any():
612
+ raise ValueError(f"DataFrame at index {i} contains NaN values in price or volume columns.")
613
+
614
+ x_timestamp = x_timestamp_list[i]
615
+ y_timestamp = y_timestamp_list[i]
616
+
617
+ x_time_df = calc_time_stamps(x_timestamp)
618
+ y_time_df = calc_time_stamps(y_timestamp)
619
+
620
+ x = df[self.price_cols + [self.vol_col, self.amt_vol]].values.astype(np.float32)
621
+ x_stamp = x_time_df.values.astype(np.float32)
622
+ y_stamp = y_time_df.values.astype(np.float32)
623
+
624
+ if x.shape[0] != x_stamp.shape[0]:
625
+ raise ValueError(f"Inconsistent lengths at index {i}: x has {x.shape[0]} vs x_stamp has {x_stamp.shape[0]}.")
626
+ if y_stamp.shape[0] != pred_len:
627
+ raise ValueError(f"y_timestamp length at index {i} should equal pred_len={pred_len}, got {y_stamp.shape[0]}.")
628
+
629
+ x_mean, x_std = np.mean(x, axis=0), np.std(x, axis=0)
630
+ x_norm = (x - x_mean) / (x_std + 1e-5)
631
+ x_norm = np.clip(x_norm, -self.clip, self.clip)
632
+
633
+ x_list.append(x_norm)
634
+ x_stamp_list.append(x_stamp)
635
+ y_stamp_list.append(y_stamp)
636
+ means.append(x_mean)
637
+ stds.append(x_std)
638
+
639
+ seq_lens.append(x_norm.shape[0])
640
+ y_lens.append(y_stamp.shape[0])
641
+
642
+ # Require all series to have consistent historical and prediction lengths for batch processing
643
+ if len(set(seq_lens)) != 1:
644
+ raise ValueError(f"Parallel prediction requires all series to have consistent historical lengths, got: {seq_lens}")
645
+ if len(set(y_lens)) != 1:
646
+ raise ValueError(f"Parallel prediction requires all series to have consistent prediction lengths, got: {y_lens}")
647
+
648
+ x_batch = np.stack(x_list, axis=0).astype(np.float32) # (B, seq_len, feat)
649
+ x_stamp_batch = np.stack(x_stamp_list, axis=0).astype(np.float32) # (B, seq_len, time_feat)
650
+ y_stamp_batch = np.stack(y_stamp_list, axis=0).astype(np.float32) # (B, pred_len, time_feat)
651
+
652
+ preds = self.generate(x_batch, x_stamp_batch, y_stamp_batch, pred_len, T, top_k, top_p, sample_count, verbose)
653
+ # preds: (B, pred_len, feat)
654
+
655
+ pred_dfs = []
656
+ for i in range(num_series):
657
+ preds_i = preds[i] * (stds[i] + 1e-5) + means[i]
658
+ pred_df = pd.DataFrame(preds_i, columns=self.price_cols + [self.vol_col, self.amt_vol], index=y_timestamp_list[i])
659
+ pred_dfs.append(pred_df)
660
+
661
+ return pred_dfs
662
+
model/module.py CHANGED
@@ -1,570 +1,570 @@
1
- import math
2
-
3
- from einops import rearrange, reduce
4
- import torch
5
- import torch.nn as nn
6
- from torch.autograd import Function
7
- import torch.nn.functional as F
8
-
9
-
10
- class DifferentiableEntropyFunction(Function):
11
- @staticmethod
12
- def forward(ctx, zq, basis, K, eps):
13
- zb = (zq + 1) / 2
14
- zi = ((zb * basis).sum(-1)).to(torch.int64)
15
- cnt = torch.scatter_reduce(torch.zeros(2 ** K, device=zq.device, dtype=zq.dtype),
16
- 0,
17
- zi.flatten(),
18
- torch.ones_like(zi.flatten()).to(zq.dtype),
19
- 'sum')
20
- prob = (cnt + eps) / (cnt + eps).sum()
21
- H = -(prob * torch.log(prob)).sum()
22
- ctx.save_for_backward(zq, zi, prob)
23
- ctx.K = K
24
- return H
25
-
26
- @staticmethod
27
- def backward(ctx, grad_output):
28
- zq, zi, prob = ctx.saved_tensors
29
- grad_array = -grad_output * (torch.log(prob) + 1) / zi.numel() / ctx.K
30
- reord_grad = grad_array[zi.flatten()].reshape(zi.shape)
31
- grad_input = reord_grad.unsqueeze(-1) * zq
32
- return grad_input, None, None, None, None
33
-
34
-
35
- def codebook_entropy(zq, basis, K, eps=1e-4):
36
- return DifferentiableEntropyFunction.apply(zq, basis, K, eps)
37
-
38
-
39
- class BinarySphericalQuantizer(nn.Module):
40
- def __init__(self, embed_dim, beta, gamma0, gamma, zeta,
41
- input_format='bchw',
42
- soft_entropy=True, group_size=9,
43
- persample_entropy_compute='analytical',
44
- cb_entropy_compute='group',
45
- l2_norm=True,
46
- inv_temperature=1):
47
- """
48
- Paper link: https://arxiv.org/pdf/2406.07548.pdf
49
- Here we use the official implementation of the BinarySphericalQuantizer.
50
- """
51
- super().__init__()
52
- self.embed_dim = embed_dim
53
- self.beta = beta # loss weight for commit loss
54
- self.gamma0 = gamma0 # loss weight for entropy penalty
55
- self.gamma = gamma # loss weight for entropy penalty
56
- self.zeta = zeta # loss weight for entire entropy penalty
57
- self.input_format = input_format
58
- assert self.embed_dim % group_size == 0, "embed_dim must be divisible by group_size"
59
- self.num_groups = self.embed_dim // group_size
60
- self.group_size = group_size
61
- assert persample_entropy_compute in ['group', 'analytical'], "persample_entropy_compute must be either 'group' or 'analytical'"
62
- assert cb_entropy_compute in ['group', 'nce'], "cb_entropy_compute must be either 'group' or 'nce'"
63
- self.persample_entropy_compute = persample_entropy_compute
64
- self.cb_entropy_compute = cb_entropy_compute
65
- self.l2_norm = l2_norm
66
- self.inv_temperature = inv_temperature
67
-
68
- self.register_buffer('basis', 2 ** torch.arange(embed_dim - 1, -1, -1))
69
- self.register_buffer('group_basis', 2 ** torch.arange(group_size - 1, -1, -1))
70
-
71
- self.num_dimensions = 2 ** embed_dim
72
- self.bits_per_index = embed_dim
73
-
74
- # we only need to keep the codebook portion up to the group size
75
- # because we approximate the H loss with this subcode
76
- group_codes = torch.arange(2 ** self.group_size)
77
- group_codebook = self.indexes_to_codes(group_codes).float()[:, -group_size:]
78
- self.register_buffer('group_codebook', group_codebook, persistent=False)
79
-
80
- self.soft_entropy = soft_entropy # soft_entropy: Sec 3.2 of https://arxiv.org/pdf/1911.05894.pdf
81
-
82
- def quantize(self, z):
83
- assert z.shape[-1] == self.embed_dim, f"Expected {self.embed_dim} dimensions, got {z.shape[-1]}"
84
-
85
- zhat = torch.where(z > 0,
86
- torch.tensor(1, dtype=z.dtype, device=z.device),
87
- torch.tensor(-1, dtype=z.dtype, device=z.device))
88
- return z + (zhat - z).detach()
89
-
90
- def forward(self, z, collect_metrics=True):
91
- # if self.input_format == 'bchw':
92
- # z = rearrange(z, 'b c h w -> b h w c')
93
- zq = self.quantize(z)
94
-
95
- q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
96
-
97
- zq = zq * q_scale
98
-
99
- if not collect_metrics:
100
- return zq, zq.new_zeros(()), {}
101
-
102
- indices = self.codes_to_indexes(zq.detach())
103
- group_indices = self.codes_to_group_indexes(zq.detach())
104
- if not self.training:
105
- used_codes = torch.unique(indices, return_counts=False)
106
- else:
107
- used_codes = None
108
-
109
- if self.soft_entropy:
110
- persample_entropy, cb_entropy, avg_prob = self.soft_entropy_loss(z)
111
- entropy_penalty = self.gamma0 * persample_entropy - self.gamma * cb_entropy
112
- else:
113
- zb_by_sample = ((zq + 1) / 2).reshape(z.shape[0], -1, z.shape[-1]).to(torch.float32)
114
- persample_entropy = self.get_hard_per_sample_entropy(zb_by_sample)
115
- cb_entropy = codebook_entropy(zq, self.basis, self.embed_dim)
116
- entropy_penalty = self.gamma0 * persample_entropy - self.gamma * cb_entropy
117
-
118
- # commit loss
119
- commit_loss = self.beta * torch.mean(((zq.detach() - z) ** 2).sum(dim=-1))
120
-
121
- # if self.input_format == 'bchw':
122
- # zq = rearrange(zq, 'b h w c -> b c h w')
123
-
124
- return (
125
- zq,
126
- commit_loss + self.zeta * entropy_penalty / self.inv_temperature,
127
- {"H": cb_entropy, "used_codes": used_codes, "indices": indices, "group_indices": group_indices,
128
- "avg_prob": avg_prob}
129
- )
130
-
131
- def soft_entropy_loss(self, z):
132
- # if we divide the code in subgroups of size group_size, the codebook will be of size 2 ** group_size
133
- # the sub-code is the last group_size bits of the full code
134
- group_code_book = self.group_codebook / (self.embed_dim ** 0.5 if self.l2_norm else 1)
135
- divided_z = rearrange(z, '... (g c) -> ... g c', c=self.group_size)
136
-
137
- # we calculate the distance between the divided_z and the codebook for each subgroup
138
- distance = - 2 * torch.einsum('... g c, d c ->... g d', divided_z, group_code_book)
139
- prob = (-distance * self.inv_temperature).softmax(dim=-1)
140
- if self.persample_entropy_compute == 'analytical':
141
- if self.l2_norm:
142
- p = torch.sigmoid(-4 * z / (self.embed_dim ** 0.5) * self.inv_temperature)
143
- else:
144
- p = torch.sigmoid(-4 * z * self.inv_temperature)
145
- prob = torch.stack([p, 1 - p], dim=-1)
146
- per_sample_entropy = self.get_entropy(prob, dim=-1, normalize=False).sum(dim=-1).mean()
147
- else:
148
- per_sample_entropy = self.get_entropy(prob, dim=-1, normalize=False).sum(dim=-1).mean()
149
-
150
- # macro average of the probability of each subgroup
151
- avg_prob = reduce(prob, '... g d ->g d', 'mean')
152
- codebook_entropy = self.get_entropy(avg_prob, dim=-1, normalize=False)
153
-
154
- # the approximation of the entropy is the sum of the entropy of each subgroup
155
- return per_sample_entropy, codebook_entropy.sum(), avg_prob
156
-
157
- def get_hard_per_sample_entropy(self, zb_by_sample):
158
- probs_per_dim = zb_by_sample.sum(1) / zb_by_sample.shape[1]
159
- persample_entropy = - probs_per_dim * torch.log(probs_per_dim + 1e-8) - (1 - probs_per_dim) * torch.log(1 - probs_per_dim + 1e-8)
160
- persample_entropy = persample_entropy.sum(-1)
161
- return persample_entropy.mean()
162
-
163
- def codes_to_indexes(self, zhat):
164
- """Converts a `code` to an index in the codebook.
165
- Args:
166
- zhat: A tensor of shape (B, ..., C) containing the codes. must be in {-1, 1}
167
- """
168
- assert zhat.shape[-1] == self.embed_dim, f"Expected {self.embed_dim} dimensions, got {zhat.shape[-1]}"
169
- return ((zhat + 1) / 2 * self.basis).sum(axis=-1).to(torch.int64)
170
-
171
- def codes_to_group_indexes(self, zhat):
172
- """Converts a `code` to a list of indexes (in groups) in the codebook.
173
- Args:
174
- zhat: A tensor of shape (B, ..., C) containing the codes. must be in {-1, 1}
175
- """
176
- zhat_in_group = rearrange(zhat, 'b ... (g c) -> b ... g c', c=self.group_size)
177
- return ((zhat_in_group + 1) / 2 * self.group_basis).sum(axis=-1).to(torch.int64)
178
-
179
- def indexes_to_codes(self, indices):
180
- """Inverse of `indexes_to_codes`."""
181
- indices = indices.unsqueeze(-1)
182
- codes_non_centered = torch.remainder(
183
- torch.floor_divide(indices, self.basis), 2
184
- )
185
- return codes_non_centered * 2 - 1
186
-
187
- def group_indexes_to_codes(self, group_indices):
188
- """Inverse of `group_indexes_to_codes`."""
189
- group_indices = group_indices.unsqueeze(-1)
190
- codes_non_centered = torch.remainder(
191
- torch.floor_divide(group_indices, self.group_basis), 2
192
- )
193
- codes_non_centered = rearrange(codes_non_centered, 'b ... g c -> b ... (g c)')
194
- return codes_non_centered * 2 - 1
195
-
196
- def get_entropy(self, count, dim=-1, eps=1e-4, normalize=True):
197
- if normalize:
198
- probs = (count + eps) / (count + eps).sum(dim=dim, keepdim=True)
199
- else:
200
- probs = count
201
- H = -(probs * torch.log(probs + 1e-8)).sum(dim=dim)
202
- return H
203
-
204
- def get_group_codebook_entry(self, group_indices):
205
- z_q = self.group_indexes_to_codes(group_indices)
206
- q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
207
- z_q = z_q * q_scale
208
- if self.input_format == 'bchw':
209
- h, w = int(z_q.shape[1] ** 0.5)
210
- assert h * w == z_q.shape[1], 'Invalid sequence length'
211
- z_q = rearrange(z_q, 'b (h w) c -> b c h w', h=h)
212
- return z_q
213
-
214
- def get_codebook_entry(self, indices):
215
- z_q = self.indexes_to_codes(indices)
216
- q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
217
- z_q = z_q * q_scale
218
- if self.input_format == 'bchw':
219
- h, w = int(z_q.shape[1] ** 0.5)
220
- assert h * w == z_q.shape[1], 'Invalid sequence length'
221
- z_q = rearrange(z_q, 'b (h w) c -> b c h w', h=h)
222
- return z_q
223
-
224
-
225
- class BSQuantizer(nn.Module):
226
-
227
- def __init__(self, s1_bits, s2_bits, beta, gamma0, gamma, zeta, group_size):
228
- super().__init__()
229
- self.codebook_dim = s1_bits + s2_bits
230
- self.s1_bits = s1_bits
231
- self.s2_bits = s2_bits
232
- self.bsq = BinarySphericalQuantizer(self.codebook_dim, beta, gamma0, gamma, zeta, group_size=group_size)
233
-
234
- def bits_to_indices(self, bits):
235
- bits = (bits >= 0).to(torch.long)
236
- indices = 2 ** torch.arange(
237
- 0,
238
- bits.shape[-1],
239
- 1,
240
- dtype=torch.long,
241
- device=bits.device,
242
- )
243
- return (bits * indices).sum(-1)
244
-
245
- def forward(self, z, half=False, collect_metrics=True):
246
- z = F.normalize(z, dim=-1)
247
- quantized, bsq_loss, metrics = self.bsq(z, collect_metrics=collect_metrics)
248
- if half:
249
- q_pre = quantized[:, :, :self.s1_bits]
250
- q_post = quantized[:, :, self.s1_bits:]
251
- z_indices = [self.bits_to_indices(q_pre), self.bits_to_indices(q_post)]
252
- else:
253
- z_indices = self.bits_to_indices(quantized)
254
- return bsq_loss, quantized, z_indices
255
-
256
-
257
- class RMSNorm(torch.nn.Module):
258
- def __init__(self, dim: int, eps: float = 1e-5):
259
- super().__init__()
260
- self.eps = eps
261
- self.weight = nn.Parameter(torch.ones(dim))
262
-
263
- def _norm(self, x):
264
- return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
265
-
266
- def forward(self, x):
267
- output = self._norm(x.float()).type_as(x)
268
- return output * self.weight
269
-
270
-
271
- class FeedForward(nn.Module):
272
- def __init__(self, d_model, ff_dim, ffn_dropout_p=0.0):
273
- super().__init__()
274
-
275
- self.w1 = nn.Linear(d_model, ff_dim, bias=False)
276
- self.w3 = nn.Linear(d_model, ff_dim, bias=False)
277
- self.w2 = nn.Linear(ff_dim, d_model, bias=False)
278
- self.ffn_dropout = nn.Dropout(ffn_dropout_p)
279
-
280
- def forward(self, x):
281
- return self.ffn_dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
282
-
283
-
284
- class RotaryPositionalEmbedding(nn.Module):
285
- def __init__(self, dim):
286
- super().__init__()
287
- inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
288
- self.register_buffer("inv_freq", inv_freq)
289
- self.seq_len_cached = None
290
- self.cos_cached = None
291
- self.sin_cached = None
292
-
293
- def _update_cos_sin_cache(self, x, seq_len):
294
- if seq_len != self.seq_len_cached:
295
- self.seq_len_cached = seq_len
296
- t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
297
- freqs = torch.einsum('i,j->ij', t, self.inv_freq)
298
- emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
299
- self.cos_cached = emb.cos()[None, None, :, :]
300
- self.sin_cached = emb.sin()[None, None, :, :]
301
- return self.cos_cached, self.sin_cached
302
-
303
- def forward(self, q, k):
304
- cos, sin = self._update_cos_sin_cache(q, q.shape[-2])
305
- return (
306
- (q * cos) + (self._rotate_half(q) * sin),
307
- (k * cos) + (self._rotate_half(k) * sin),
308
- )
309
-
310
- def _rotate_half(self, x):
311
- x1, x2 = x.chunk(2, dim=-1)
312
- return torch.cat((-x2, x1), dim=-1)
313
-
314
-
315
- class MultiHeadAttentionWithRoPE(nn.Module):
316
- def __init__(self, d_model, n_heads, attn_dropout_p=0.0, resid_dropout_p=0.0):
317
- super().__init__()
318
- self.d_model = d_model
319
- self.n_heads = n_heads
320
- self.head_dim = d_model // n_heads
321
-
322
- self.q_proj = nn.Linear(d_model, d_model)
323
- self.k_proj = nn.Linear(d_model, d_model)
324
- self.v_proj = nn.Linear(d_model, d_model)
325
- self.out_proj = nn.Linear(d_model, d_model)
326
- self.rotary = RotaryPositionalEmbedding(self.head_dim)
327
- self.attn_dropout_p = attn_dropout_p
328
- self.resid_dropout = nn.Dropout(resid_dropout_p)
329
-
330
- def forward(self, x, key_padding_mask=None):
331
- batch_size, seq_len, _ = x.shape
332
-
333
- q = self.q_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
334
- k = self.k_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
335
- v = self.v_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
336
-
337
- q, k = self.rotary(q, k)
338
-
339
- if key_padding_mask is not None:
340
- attn_mask = key_padding_mask.unsqueeze(1).unsqueeze(2) # [batch, 1, 1, seq_len]
341
- attn_mask = attn_mask.expand(-1, self.n_heads, seq_len, -1) # [batch, n_heads, q_len, k_len]
342
- else:
343
- attn_mask = None
344
-
345
- attn_output = F.scaled_dot_product_attention(
346
- q, k, v,
347
- attn_mask=attn_mask,
348
- dropout_p=self.attn_dropout_p if self.training else 0.0,
349
- is_causal=True
350
- )
351
-
352
- attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
353
- return self.resid_dropout(self.out_proj(attn_output))
354
-
355
-
356
- class MultiHeadCrossAttentionWithRoPE(nn.Module):
357
- def __init__(self, d_model, n_heads, attn_dropout_p=0.0, resid_dropout=0.0):
358
- super().__init__()
359
- self.d_model = d_model
360
- self.n_heads = n_heads
361
- self.head_dim = d_model // n_heads
362
-
363
- self.q_proj = nn.Linear(d_model, d_model)
364
- self.k_proj = nn.Linear(d_model, d_model)
365
- self.v_proj = nn.Linear(d_model, d_model)
366
- self.out_proj = nn.Linear(d_model, d_model)
367
- self.rotary = RotaryPositionalEmbedding(self.head_dim)
368
- self.attn_dropout_p = attn_dropout_p
369
- self.resid_dropout = nn.Dropout(resid_dropout)
370
-
371
- def forward(self, query, key, value, key_padding_mask=None):
372
- batch_size, q_len, _ = query.shape
373
- _, seq_len, _ = key.shape
374
-
375
- q = self.q_proj(query).view(batch_size, q_len, self.n_heads, self.head_dim).transpose(1, 2)
376
- k = self.k_proj(key).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
377
- v = self.v_proj(value).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
378
-
379
- q, k = self.rotary(q, k)
380
-
381
- if key_padding_mask is not None:
382
- attn_mask = key_padding_mask.unsqueeze(1).unsqueeze(2)
383
- attn_mask = attn_mask.expand(-1, self.n_heads, q_len, -1)
384
- else:
385
- attn_mask = None
386
-
387
- is_causal_flag = self.training
388
-
389
- attn_output = F.scaled_dot_product_attention(
390
- q, k, v,
391
- attn_mask=attn_mask,
392
- dropout_p=self.attn_dropout_p if self.training else 0.0,
393
- is_causal=is_causal_flag
394
- )
395
-
396
- attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, q_len, self.d_model)
397
- return self.resid_dropout(self.out_proj(attn_output))
398
-
399
-
400
- class HierarchicalEmbedding(nn.Module):
401
- def __init__(self, s1_bits, s2_bits, d_model=256):
402
- super().__init__()
403
- self.s1_bits = s1_bits
404
- self.s2_bits = s2_bits
405
-
406
- vocab_s1 = 2 ** s1_bits
407
- vocab_s2 = 2 ** s2_bits
408
-
409
- self.emb_s1 = nn.Embedding(vocab_s1, d_model)
410
- self.emb_s2 = nn.Embedding(vocab_s2, d_model)
411
- self.d_model = d_model
412
- self.fusion_proj = nn.Linear(d_model * 2, d_model)
413
-
414
- nn.init.normal_(self.emb_s1.weight, mean=0, std=d_model ** -0.5)
415
- nn.init.normal_(self.emb_s2.weight, mean=0, std=d_model ** -0.5)
416
-
417
- def split_token(self, token_ids: torch.Tensor, s2_bits: int):
418
- """Inputs:
419
- token_ids (torch.Tensor): Composite token IDs of shape [batch_size, seq_len] or [N], each in range [0, 2^(s1_bits + s2_bits) - 1].
420
- s2_bits (int): Number of low bits used for the fine token (s2).
421
- """
422
- assert isinstance(s2_bits, int) and s2_bits > 0, "s2_bits must be a positive integer"
423
-
424
- t = token_ids.long()
425
- mask = (1 << s2_bits) - 1
426
- s2_ids = t & mask # extract low bits
427
- s1_ids = t >> s2_bits # extract high bits
428
- return s1_ids, s2_ids
429
-
430
- def forward(self, token_ids):
431
- """Inputs:
432
- token_ids:
433
- - tuple or list: (s1_ids, s2_ids), each of shape [batch_size, seq_len], or
434
- - torch.Tensor: composite token IDs of shape [batch_size, seq_len], which will be split into (s1_ids, s2_ids) internally.
435
- Output: [batch_size, seq_len, d_model]
436
- """
437
- if isinstance(token_ids, tuple) or isinstance(token_ids, list):
438
- s1_ids, s2_ids = token_ids
439
- else:
440
- s1_ids, s2_ids = self.split_token(token_ids, self.s2_bits)
441
- s1_emb = self.emb_s1(s1_ids) * math.sqrt(self.d_model)
442
- s2_emb = self.emb_s2(s2_ids) * math.sqrt(self.d_model)
443
- return self.fusion_proj(torch.cat([s1_emb, s2_emb], dim=-1))
444
-
445
-
446
- class DependencyAwareLayer(nn.Module):
447
- def __init__(self, d_model, n_heads=4, attn_dropout_p=0.0, resid_dropout=0.0):
448
- super().__init__()
449
- self.cross_attn = MultiHeadCrossAttentionWithRoPE(d_model, n_heads, attn_dropout_p, resid_dropout)
450
- self.norm = RMSNorm(d_model)
451
-
452
- def forward(self, hidden_states, sibling_embed, key_padding_mask=None):
453
- """hidden_states: [batch, seq_len, d_model]
454
- sibling_embed: Embedding from another subtoken
455
- """
456
- attn_out = self.cross_attn(
457
- query=sibling_embed,
458
- key=hidden_states,
459
- value=hidden_states,
460
- key_padding_mask=key_padding_mask
461
- )
462
- return self.norm(hidden_states + attn_out)
463
-
464
-
465
- class TransformerBlock(nn.Module):
466
- def __init__(self, d_model, n_heads, ff_dim=1024, ffn_dropout_p=0.0, attn_dropout_p=0.0, resid_dropout_p=0.0):
467
- super().__init__()
468
- self.norm1 = RMSNorm(d_model)
469
- self.self_attn = MultiHeadAttentionWithRoPE(d_model, n_heads, attn_dropout_p, resid_dropout_p)
470
- self.norm2 = RMSNorm(d_model)
471
- self.ffn = FeedForward(d_model, ff_dim, ffn_dropout_p)
472
-
473
- def forward(self, x, key_padding_mask=None):
474
- residual = x
475
- x = self.norm1(x)
476
- attn_out = self.self_attn(x, key_padding_mask=key_padding_mask)
477
- x = residual + attn_out
478
-
479
- residual = x
480
- x = self.norm2(x)
481
- ffn_out = self.ffn(x)
482
- x = residual + ffn_out
483
- return x
484
-
485
-
486
- class DualHead(nn.Module):
487
- def __init__(self, s1_bits, s2_bits, d_model):
488
- super().__init__()
489
- self.vocab_s1 = 2 ** s1_bits
490
- self.vocab_s2 = 2 ** s2_bits
491
- self.proj_s1 = nn.Linear(d_model, self.vocab_s1)
492
- self.proj_s2 = nn.Linear(d_model, self.vocab_s2)
493
-
494
- def compute_loss(self, s1_logits, s2_logits, s1_targets, s2_targets, padding_mask=None):
495
- if padding_mask is not None:
496
- valid_mask = (padding_mask == 0)
497
- s1_logits = s1_logits[valid_mask]
498
- s2_logits = s2_logits[valid_mask]
499
- s1_targets = s1_targets[valid_mask]
500
- s2_targets = s2_targets[valid_mask]
501
- ce_s1 = F.cross_entropy(s1_logits, s1_targets)
502
- ce_s2 = F.cross_entropy(s2_logits, s2_targets)
503
- else:
504
- ce_s1 = F.cross_entropy(s1_logits.reshape(-1, self.vocab_s1), s1_targets.reshape(-1))
505
- ce_s2 = F.cross_entropy(s2_logits.reshape(-1, self.vocab_s2), s2_targets.reshape(-1))
506
- ce_loss = (ce_s1 + ce_s2) / 2
507
- return ce_loss, ce_s1, ce_s2
508
-
509
- def forward(self, x):
510
- return self.proj_s1(x)
511
-
512
- def cond_forward(self, x2):
513
- return self.proj_s2(x2)
514
-
515
-
516
- class FixedEmbedding(nn.Module):
517
- def __init__(self, c_in, d_model):
518
- super(FixedEmbedding, self).__init__()
519
-
520
- w = torch.zeros(c_in, d_model).float()
521
- w.require_grad = False
522
-
523
- position = torch.arange(0, c_in).float().unsqueeze(1)
524
- div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()
525
-
526
- w[:, 0::2] = torch.sin(position * div_term)
527
- w[:, 1::2] = torch.cos(position * div_term)
528
-
529
- self.emb = nn.Embedding(c_in, d_model)
530
- self.emb.weight = nn.Parameter(w, requires_grad=False)
531
-
532
- def forward(self, x):
533
- return self.emb(x).detach()
534
-
535
-
536
- class TemporalEmbedding(nn.Module):
537
- def __init__(self, d_model, learn_pe):
538
- super(TemporalEmbedding, self).__init__()
539
-
540
- minute_size = 60
541
- hour_size = 24
542
- weekday_size = 7
543
- day_size = 32
544
- month_size = 13
545
-
546
- Embed = FixedEmbedding if not learn_pe else nn.Embedding
547
- self.minute_embed = Embed(minute_size, d_model)
548
- self.hour_embed = Embed(hour_size, d_model)
549
- self.weekday_embed = Embed(weekday_size, d_model)
550
- self.day_embed = Embed(day_size, d_model)
551
- self.month_embed = Embed(month_size, d_model)
552
-
553
- def forward(self, x):
554
- x = x.long()
555
-
556
- minute_x = self.minute_embed(x[:, :, 0])
557
- hour_x = self.hour_embed(x[:, :, 1])
558
- weekday_x = self.weekday_embed(x[:, :, 2])
559
- day_x = self.day_embed(x[:, :, 3])
560
- month_x = self.month_embed(x[:, :, 4])
561
-
562
- return hour_x + weekday_x + day_x + month_x + minute_x
563
-
564
-
565
-
566
-
567
-
568
-
569
-
570
-
 
1
+ import math
2
+
3
+ from einops import rearrange, reduce
4
+ import torch
5
+ import torch.nn as nn
6
+ from torch.autograd import Function
7
+ import torch.nn.functional as F
8
+
9
+
10
+ class DifferentiableEntropyFunction(Function):
11
+ @staticmethod
12
+ def forward(ctx, zq, basis, K, eps):
13
+ zb = (zq + 1) / 2
14
+ zi = ((zb * basis).sum(-1)).to(torch.int64)
15
+ cnt = torch.scatter_reduce(torch.zeros(2 ** K, device=zq.device, dtype=zq.dtype),
16
+ 0,
17
+ zi.flatten(),
18
+ torch.ones_like(zi.flatten()).to(zq.dtype),
19
+ 'sum')
20
+ prob = (cnt + eps) / (cnt + eps).sum()
21
+ H = -(prob * torch.log(prob)).sum()
22
+ ctx.save_for_backward(zq, zi, prob)
23
+ ctx.K = K
24
+ return H
25
+
26
+ @staticmethod
27
+ def backward(ctx, grad_output):
28
+ zq, zi, prob = ctx.saved_tensors
29
+ grad_array = -grad_output * (torch.log(prob) + 1) / zi.numel() / ctx.K
30
+ reord_grad = grad_array[zi.flatten()].reshape(zi.shape)
31
+ grad_input = reord_grad.unsqueeze(-1) * zq
32
+ return grad_input, None, None, None, None
33
+
34
+
35
+ def codebook_entropy(zq, basis, K, eps=1e-4):
36
+ return DifferentiableEntropyFunction.apply(zq, basis, K, eps)
37
+
38
+
39
+ class BinarySphericalQuantizer(nn.Module):
40
+ def __init__(self, embed_dim, beta, gamma0, gamma, zeta,
41
+ input_format='bchw',
42
+ soft_entropy=True, group_size=9,
43
+ persample_entropy_compute='analytical',
44
+ cb_entropy_compute='group',
45
+ l2_norm=True,
46
+ inv_temperature=1):
47
+ """
48
+ Paper link: https://arxiv.org/pdf/2406.07548.pdf
49
+ Here we use the official implementation of the BinarySphericalQuantizer.
50
+ """
51
+ super().__init__()
52
+ self.embed_dim = embed_dim
53
+ self.beta = beta # loss weight for commit loss
54
+ self.gamma0 = gamma0 # loss weight for entropy penalty
55
+ self.gamma = gamma # loss weight for entropy penalty
56
+ self.zeta = zeta # loss weight for entire entropy penalty
57
+ self.input_format = input_format
58
+ assert self.embed_dim % group_size == 0, "embed_dim must be divisible by group_size"
59
+ self.num_groups = self.embed_dim // group_size
60
+ self.group_size = group_size
61
+ assert persample_entropy_compute in ['group', 'analytical'], "persample_entropy_compute must be either 'group' or 'analytical'"
62
+ assert cb_entropy_compute in ['group', 'nce'], "cb_entropy_compute must be either 'group' or 'nce'"
63
+ self.persample_entropy_compute = persample_entropy_compute
64
+ self.cb_entropy_compute = cb_entropy_compute
65
+ self.l2_norm = l2_norm
66
+ self.inv_temperature = inv_temperature
67
+
68
+ self.register_buffer('basis', 2 ** torch.arange(embed_dim - 1, -1, -1))
69
+ self.register_buffer('group_basis', 2 ** torch.arange(group_size - 1, -1, -1))
70
+
71
+ self.num_dimensions = 2 ** embed_dim
72
+ self.bits_per_index = embed_dim
73
+
74
+ # we only need to keep the codebook portion up to the group size
75
+ # because we approximate the H loss with this subcode
76
+ group_codes = torch.arange(2 ** self.group_size)
77
+ group_codebook = self.indexes_to_codes(group_codes).float()[:, -group_size:]
78
+ self.register_buffer('group_codebook', group_codebook, persistent=False)
79
+
80
+ self.soft_entropy = soft_entropy # soft_entropy: Sec 3.2 of https://arxiv.org/pdf/1911.05894.pdf
81
+
82
+ def quantize(self, z):
83
+ assert z.shape[-1] == self.embed_dim, f"Expected {self.embed_dim} dimensions, got {z.shape[-1]}"
84
+
85
+ zhat = torch.where(z > 0,
86
+ torch.tensor(1, dtype=z.dtype, device=z.device),
87
+ torch.tensor(-1, dtype=z.dtype, device=z.device))
88
+ return z + (zhat - z).detach()
89
+
90
+ def forward(self, z, collect_metrics=True):
91
+ # if self.input_format == 'bchw':
92
+ # z = rearrange(z, 'b c h w -> b h w c')
93
+ zq = self.quantize(z)
94
+
95
+ q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
96
+
97
+ zq = zq * q_scale
98
+
99
+ if not collect_metrics:
100
+ return zq, zq.new_zeros(()), {}
101
+
102
+ indices = self.codes_to_indexes(zq.detach())
103
+ group_indices = self.codes_to_group_indexes(zq.detach())
104
+ if not self.training:
105
+ used_codes = torch.unique(indices, return_counts=False)
106
+ else:
107
+ used_codes = None
108
+
109
+ if self.soft_entropy:
110
+ persample_entropy, cb_entropy, avg_prob = self.soft_entropy_loss(z)
111
+ entropy_penalty = self.gamma0 * persample_entropy - self.gamma * cb_entropy
112
+ else:
113
+ zb_by_sample = ((zq + 1) / 2).reshape(z.shape[0], -1, z.shape[-1]).to(torch.float32)
114
+ persample_entropy = self.get_hard_per_sample_entropy(zb_by_sample)
115
+ cb_entropy = codebook_entropy(zq, self.basis, self.embed_dim)
116
+ entropy_penalty = self.gamma0 * persample_entropy - self.gamma * cb_entropy
117
+
118
+ # commit loss
119
+ commit_loss = self.beta * torch.mean(((zq.detach() - z) ** 2).sum(dim=-1))
120
+
121
+ # if self.input_format == 'bchw':
122
+ # zq = rearrange(zq, 'b h w c -> b c h w')
123
+
124
+ return (
125
+ zq,
126
+ commit_loss + self.zeta * entropy_penalty / self.inv_temperature,
127
+ {"H": cb_entropy, "used_codes": used_codes, "indices": indices, "group_indices": group_indices,
128
+ "avg_prob": avg_prob}
129
+ )
130
+
131
+ def soft_entropy_loss(self, z):
132
+ # if we divide the code in subgroups of size group_size, the codebook will be of size 2 ** group_size
133
+ # the sub-code is the last group_size bits of the full code
134
+ group_code_book = self.group_codebook / (self.embed_dim ** 0.5 if self.l2_norm else 1)
135
+ divided_z = rearrange(z, '... (g c) -> ... g c', c=self.group_size)
136
+
137
+ # we calculate the distance between the divided_z and the codebook for each subgroup
138
+ distance = - 2 * torch.einsum('... g c, d c ->... g d', divided_z, group_code_book)
139
+ prob = (-distance * self.inv_temperature).softmax(dim=-1)
140
+ if self.persample_entropy_compute == 'analytical':
141
+ if self.l2_norm:
142
+ p = torch.sigmoid(-4 * z / (self.embed_dim ** 0.5) * self.inv_temperature)
143
+ else:
144
+ p = torch.sigmoid(-4 * z * self.inv_temperature)
145
+ prob = torch.stack([p, 1 - p], dim=-1)
146
+ per_sample_entropy = self.get_entropy(prob, dim=-1, normalize=False).sum(dim=-1).mean()
147
+ else:
148
+ per_sample_entropy = self.get_entropy(prob, dim=-1, normalize=False).sum(dim=-1).mean()
149
+
150
+ # macro average of the probability of each subgroup
151
+ avg_prob = reduce(prob, '... g d ->g d', 'mean')
152
+ codebook_entropy = self.get_entropy(avg_prob, dim=-1, normalize=False)
153
+
154
+ # the approximation of the entropy is the sum of the entropy of each subgroup
155
+ return per_sample_entropy, codebook_entropy.sum(), avg_prob
156
+
157
+ def get_hard_per_sample_entropy(self, zb_by_sample):
158
+ probs_per_dim = zb_by_sample.sum(1) / zb_by_sample.shape[1]
159
+ persample_entropy = - probs_per_dim * torch.log(probs_per_dim + 1e-8) - (1 - probs_per_dim) * torch.log(1 - probs_per_dim + 1e-8)
160
+ persample_entropy = persample_entropy.sum(-1)
161
+ return persample_entropy.mean()
162
+
163
+ def codes_to_indexes(self, zhat):
164
+ """Converts a `code` to an index in the codebook.
165
+ Args:
166
+ zhat: A tensor of shape (B, ..., C) containing the codes. must be in {-1, 1}
167
+ """
168
+ assert zhat.shape[-1] == self.embed_dim, f"Expected {self.embed_dim} dimensions, got {zhat.shape[-1]}"
169
+ return ((zhat + 1) / 2 * self.basis).sum(axis=-1).to(torch.int64)
170
+
171
+ def codes_to_group_indexes(self, zhat):
172
+ """Converts a `code` to a list of indexes (in groups) in the codebook.
173
+ Args:
174
+ zhat: A tensor of shape (B, ..., C) containing the codes. must be in {-1, 1}
175
+ """
176
+ zhat_in_group = rearrange(zhat, 'b ... (g c) -> b ... g c', c=self.group_size)
177
+ return ((zhat_in_group + 1) / 2 * self.group_basis).sum(axis=-1).to(torch.int64)
178
+
179
+ def indexes_to_codes(self, indices):
180
+ """Inverse of `indexes_to_codes`."""
181
+ indices = indices.unsqueeze(-1)
182
+ codes_non_centered = torch.remainder(
183
+ torch.floor_divide(indices, self.basis), 2
184
+ )
185
+ return codes_non_centered * 2 - 1
186
+
187
+ def group_indexes_to_codes(self, group_indices):
188
+ """Inverse of `group_indexes_to_codes`."""
189
+ group_indices = group_indices.unsqueeze(-1)
190
+ codes_non_centered = torch.remainder(
191
+ torch.floor_divide(group_indices, self.group_basis), 2
192
+ )
193
+ codes_non_centered = rearrange(codes_non_centered, 'b ... g c -> b ... (g c)')
194
+ return codes_non_centered * 2 - 1
195
+
196
+ def get_entropy(self, count, dim=-1, eps=1e-4, normalize=True):
197
+ if normalize:
198
+ probs = (count + eps) / (count + eps).sum(dim=dim, keepdim=True)
199
+ else:
200
+ probs = count
201
+ H = -(probs * torch.log(probs + 1e-8)).sum(dim=dim)
202
+ return H
203
+
204
+ def get_group_codebook_entry(self, group_indices):
205
+ z_q = self.group_indexes_to_codes(group_indices)
206
+ q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
207
+ z_q = z_q * q_scale
208
+ if self.input_format == 'bchw':
209
+ h, w = int(z_q.shape[1] ** 0.5)
210
+ assert h * w == z_q.shape[1], 'Invalid sequence length'
211
+ z_q = rearrange(z_q, 'b (h w) c -> b c h w', h=h)
212
+ return z_q
213
+
214
+ def get_codebook_entry(self, indices):
215
+ z_q = self.indexes_to_codes(indices)
216
+ q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
217
+ z_q = z_q * q_scale
218
+ if self.input_format == 'bchw':
219
+ h, w = int(z_q.shape[1] ** 0.5)
220
+ assert h * w == z_q.shape[1], 'Invalid sequence length'
221
+ z_q = rearrange(z_q, 'b (h w) c -> b c h w', h=h)
222
+ return z_q
223
+
224
+
225
+ class BSQuantizer(nn.Module):
226
+
227
+ def __init__(self, s1_bits, s2_bits, beta, gamma0, gamma, zeta, group_size):
228
+ super().__init__()
229
+ self.codebook_dim = s1_bits + s2_bits
230
+ self.s1_bits = s1_bits
231
+ self.s2_bits = s2_bits
232
+ self.bsq = BinarySphericalQuantizer(self.codebook_dim, beta, gamma0, gamma, zeta, group_size=group_size)
233
+
234
+ def bits_to_indices(self, bits):
235
+ bits = (bits >= 0).to(torch.long)
236
+ indices = 2 ** torch.arange(
237
+ 0,
238
+ bits.shape[-1],
239
+ 1,
240
+ dtype=torch.long,
241
+ device=bits.device,
242
+ )
243
+ return (bits * indices).sum(-1)
244
+
245
+ def forward(self, z, half=False, collect_metrics=True):
246
+ z = F.normalize(z, dim=-1)
247
+ quantized, bsq_loss, metrics = self.bsq(z, collect_metrics=collect_metrics)
248
+ if half:
249
+ q_pre = quantized[:, :, :self.s1_bits]
250
+ q_post = quantized[:, :, self.s1_bits:]
251
+ z_indices = [self.bits_to_indices(q_pre), self.bits_to_indices(q_post)]
252
+ else:
253
+ z_indices = self.bits_to_indices(quantized)
254
+ return bsq_loss, quantized, z_indices
255
+
256
+
257
+ class RMSNorm(torch.nn.Module):
258
+ def __init__(self, dim: int, eps: float = 1e-5):
259
+ super().__init__()
260
+ self.eps = eps
261
+ self.weight = nn.Parameter(torch.ones(dim))
262
+
263
+ def _norm(self, x):
264
+ return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
265
+
266
+ def forward(self, x):
267
+ output = self._norm(x.float()).type_as(x)
268
+ return output * self.weight
269
+
270
+
271
+ class FeedForward(nn.Module):
272
+ def __init__(self, d_model, ff_dim, ffn_dropout_p=0.0):
273
+ super().__init__()
274
+
275
+ self.w1 = nn.Linear(d_model, ff_dim, bias=False)
276
+ self.w3 = nn.Linear(d_model, ff_dim, bias=False)
277
+ self.w2 = nn.Linear(ff_dim, d_model, bias=False)
278
+ self.ffn_dropout = nn.Dropout(ffn_dropout_p)
279
+
280
+ def forward(self, x):
281
+ return self.ffn_dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
282
+
283
+
284
+ class RotaryPositionalEmbedding(nn.Module):
285
+ def __init__(self, dim):
286
+ super().__init__()
287
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
288
+ self.register_buffer("inv_freq", inv_freq)
289
+ self.seq_len_cached = None
290
+ self.cos_cached = None
291
+ self.sin_cached = None
292
+
293
+ def _update_cos_sin_cache(self, x, seq_len):
294
+ if seq_len != self.seq_len_cached:
295
+ self.seq_len_cached = seq_len
296
+ t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
297
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
298
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
299
+ self.cos_cached = emb.cos()[None, None, :, :]
300
+ self.sin_cached = emb.sin()[None, None, :, :]
301
+ return self.cos_cached, self.sin_cached
302
+
303
+ def forward(self, q, k):
304
+ cos, sin = self._update_cos_sin_cache(q, q.shape[-2])
305
+ return (
306
+ (q * cos) + (self._rotate_half(q) * sin),
307
+ (k * cos) + (self._rotate_half(k) * sin),
308
+ )
309
+
310
+ def _rotate_half(self, x):
311
+ x1, x2 = x.chunk(2, dim=-1)
312
+ return torch.cat((-x2, x1), dim=-1)
313
+
314
+
315
+ class MultiHeadAttentionWithRoPE(nn.Module):
316
+ def __init__(self, d_model, n_heads, attn_dropout_p=0.0, resid_dropout_p=0.0):
317
+ super().__init__()
318
+ self.d_model = d_model
319
+ self.n_heads = n_heads
320
+ self.head_dim = d_model // n_heads
321
+
322
+ self.q_proj = nn.Linear(d_model, d_model)
323
+ self.k_proj = nn.Linear(d_model, d_model)
324
+ self.v_proj = nn.Linear(d_model, d_model)
325
+ self.out_proj = nn.Linear(d_model, d_model)
326
+ self.rotary = RotaryPositionalEmbedding(self.head_dim)
327
+ self.attn_dropout_p = attn_dropout_p
328
+ self.resid_dropout = nn.Dropout(resid_dropout_p)
329
+
330
+ def forward(self, x, key_padding_mask=None):
331
+ batch_size, seq_len, _ = x.shape
332
+
333
+ q = self.q_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
334
+ k = self.k_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
335
+ v = self.v_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
336
+
337
+ q, k = self.rotary(q, k)
338
+
339
+ if key_padding_mask is not None:
340
+ attn_mask = key_padding_mask.unsqueeze(1).unsqueeze(2) # [batch, 1, 1, seq_len]
341
+ attn_mask = attn_mask.expand(-1, self.n_heads, seq_len, -1) # [batch, n_heads, q_len, k_len]
342
+ else:
343
+ attn_mask = None
344
+
345
+ attn_output = F.scaled_dot_product_attention(
346
+ q, k, v,
347
+ attn_mask=attn_mask,
348
+ dropout_p=self.attn_dropout_p if self.training else 0.0,
349
+ is_causal=True
350
+ )
351
+
352
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
353
+ return self.resid_dropout(self.out_proj(attn_output))
354
+
355
+
356
+ class MultiHeadCrossAttentionWithRoPE(nn.Module):
357
+ def __init__(self, d_model, n_heads, attn_dropout_p=0.0, resid_dropout=0.0):
358
+ super().__init__()
359
+ self.d_model = d_model
360
+ self.n_heads = n_heads
361
+ self.head_dim = d_model // n_heads
362
+
363
+ self.q_proj = nn.Linear(d_model, d_model)
364
+ self.k_proj = nn.Linear(d_model, d_model)
365
+ self.v_proj = nn.Linear(d_model, d_model)
366
+ self.out_proj = nn.Linear(d_model, d_model)
367
+ self.rotary = RotaryPositionalEmbedding(self.head_dim)
368
+ self.attn_dropout_p = attn_dropout_p
369
+ self.resid_dropout = nn.Dropout(resid_dropout)
370
+
371
+ def forward(self, query, key, value, key_padding_mask=None):
372
+ batch_size, q_len, _ = query.shape
373
+ _, seq_len, _ = key.shape
374
+
375
+ q = self.q_proj(query).view(batch_size, q_len, self.n_heads, self.head_dim).transpose(1, 2)
376
+ k = self.k_proj(key).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
377
+ v = self.v_proj(value).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
378
+
379
+ q, k = self.rotary(q, k)
380
+
381
+ if key_padding_mask is not None:
382
+ attn_mask = key_padding_mask.unsqueeze(1).unsqueeze(2)
383
+ attn_mask = attn_mask.expand(-1, self.n_heads, q_len, -1)
384
+ else:
385
+ attn_mask = None
386
+
387
+ is_causal_flag = self.training
388
+
389
+ attn_output = F.scaled_dot_product_attention(
390
+ q, k, v,
391
+ attn_mask=attn_mask,
392
+ dropout_p=self.attn_dropout_p if self.training else 0.0,
393
+ is_causal=is_causal_flag
394
+ )
395
+
396
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, q_len, self.d_model)
397
+ return self.resid_dropout(self.out_proj(attn_output))
398
+
399
+
400
+ class HierarchicalEmbedding(nn.Module):
401
+ def __init__(self, s1_bits, s2_bits, d_model=256):
402
+ super().__init__()
403
+ self.s1_bits = s1_bits
404
+ self.s2_bits = s2_bits
405
+
406
+ vocab_s1 = 2 ** s1_bits
407
+ vocab_s2 = 2 ** s2_bits
408
+
409
+ self.emb_s1 = nn.Embedding(vocab_s1, d_model)
410
+ self.emb_s2 = nn.Embedding(vocab_s2, d_model)
411
+ self.d_model = d_model
412
+ self.fusion_proj = nn.Linear(d_model * 2, d_model)
413
+
414
+ nn.init.normal_(self.emb_s1.weight, mean=0, std=d_model ** -0.5)
415
+ nn.init.normal_(self.emb_s2.weight, mean=0, std=d_model ** -0.5)
416
+
417
+ def split_token(self, token_ids: torch.Tensor, s2_bits: int):
418
+ """Inputs:
419
+ token_ids (torch.Tensor): Composite token IDs of shape [batch_size, seq_len] or [N], each in range [0, 2^(s1_bits + s2_bits) - 1].
420
+ s2_bits (int): Number of low bits used for the fine token (s2).
421
+ """
422
+ assert isinstance(s2_bits, int) and s2_bits > 0, "s2_bits must be a positive integer"
423
+
424
+ t = token_ids.long()
425
+ mask = (1 << s2_bits) - 1
426
+ s2_ids = t & mask # extract low bits
427
+ s1_ids = t >> s2_bits # extract high bits
428
+ return s1_ids, s2_ids
429
+
430
+ def forward(self, token_ids):
431
+ """Inputs:
432
+ token_ids:
433
+ - tuple or list: (s1_ids, s2_ids), each of shape [batch_size, seq_len], or
434
+ - torch.Tensor: composite token IDs of shape [batch_size, seq_len], which will be split into (s1_ids, s2_ids) internally.
435
+ Output: [batch_size, seq_len, d_model]
436
+ """
437
+ if isinstance(token_ids, tuple) or isinstance(token_ids, list):
438
+ s1_ids, s2_ids = token_ids
439
+ else:
440
+ s1_ids, s2_ids = self.split_token(token_ids, self.s2_bits)
441
+ s1_emb = self.emb_s1(s1_ids) * math.sqrt(self.d_model)
442
+ s2_emb = self.emb_s2(s2_ids) * math.sqrt(self.d_model)
443
+ return self.fusion_proj(torch.cat([s1_emb, s2_emb], dim=-1))
444
+
445
+
446
+ class DependencyAwareLayer(nn.Module):
447
+ def __init__(self, d_model, n_heads=4, attn_dropout_p=0.0, resid_dropout=0.0):
448
+ super().__init__()
449
+ self.cross_attn = MultiHeadCrossAttentionWithRoPE(d_model, n_heads, attn_dropout_p, resid_dropout)
450
+ self.norm = RMSNorm(d_model)
451
+
452
+ def forward(self, hidden_states, sibling_embed, key_padding_mask=None):
453
+ """hidden_states: [batch, seq_len, d_model]
454
+ sibling_embed: Embedding from another subtoken
455
+ """
456
+ attn_out = self.cross_attn(
457
+ query=sibling_embed,
458
+ key=hidden_states,
459
+ value=hidden_states,
460
+ key_padding_mask=key_padding_mask
461
+ )
462
+ return self.norm(hidden_states + attn_out)
463
+
464
+
465
+ class TransformerBlock(nn.Module):
466
+ def __init__(self, d_model, n_heads, ff_dim=1024, ffn_dropout_p=0.0, attn_dropout_p=0.0, resid_dropout_p=0.0):
467
+ super().__init__()
468
+ self.norm1 = RMSNorm(d_model)
469
+ self.self_attn = MultiHeadAttentionWithRoPE(d_model, n_heads, attn_dropout_p, resid_dropout_p)
470
+ self.norm2 = RMSNorm(d_model)
471
+ self.ffn = FeedForward(d_model, ff_dim, ffn_dropout_p)
472
+
473
+ def forward(self, x, key_padding_mask=None):
474
+ residual = x
475
+ x = self.norm1(x)
476
+ attn_out = self.self_attn(x, key_padding_mask=key_padding_mask)
477
+ x = residual + attn_out
478
+
479
+ residual = x
480
+ x = self.norm2(x)
481
+ ffn_out = self.ffn(x)
482
+ x = residual + ffn_out
483
+ return x
484
+
485
+
486
+ class DualHead(nn.Module):
487
+ def __init__(self, s1_bits, s2_bits, d_model):
488
+ super().__init__()
489
+ self.vocab_s1 = 2 ** s1_bits
490
+ self.vocab_s2 = 2 ** s2_bits
491
+ self.proj_s1 = nn.Linear(d_model, self.vocab_s1)
492
+ self.proj_s2 = nn.Linear(d_model, self.vocab_s2)
493
+
494
+ def compute_loss(self, s1_logits, s2_logits, s1_targets, s2_targets, padding_mask=None):
495
+ if padding_mask is not None:
496
+ valid_mask = (padding_mask == 0)
497
+ s1_logits = s1_logits[valid_mask]
498
+ s2_logits = s2_logits[valid_mask]
499
+ s1_targets = s1_targets[valid_mask]
500
+ s2_targets = s2_targets[valid_mask]
501
+ ce_s1 = F.cross_entropy(s1_logits, s1_targets)
502
+ ce_s2 = F.cross_entropy(s2_logits, s2_targets)
503
+ else:
504
+ ce_s1 = F.cross_entropy(s1_logits.reshape(-1, self.vocab_s1), s1_targets.reshape(-1))
505
+ ce_s2 = F.cross_entropy(s2_logits.reshape(-1, self.vocab_s2), s2_targets.reshape(-1))
506
+ ce_loss = (ce_s1 + ce_s2) / 2
507
+ return ce_loss, ce_s1, ce_s2
508
+
509
+ def forward(self, x):
510
+ return self.proj_s1(x)
511
+
512
+ def cond_forward(self, x2):
513
+ return self.proj_s2(x2)
514
+
515
+
516
+ class FixedEmbedding(nn.Module):
517
+ def __init__(self, c_in, d_model):
518
+ super(FixedEmbedding, self).__init__()
519
+
520
+ w = torch.zeros(c_in, d_model).float()
521
+ w.require_grad = False
522
+
523
+ position = torch.arange(0, c_in).float().unsqueeze(1)
524
+ div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()
525
+
526
+ w[:, 0::2] = torch.sin(position * div_term)
527
+ w[:, 1::2] = torch.cos(position * div_term)
528
+
529
+ self.emb = nn.Embedding(c_in, d_model)
530
+ self.emb.weight = nn.Parameter(w, requires_grad=False)
531
+
532
+ def forward(self, x):
533
+ return self.emb(x).detach()
534
+
535
+
536
+ class TemporalEmbedding(nn.Module):
537
+ def __init__(self, d_model, learn_pe):
538
+ super(TemporalEmbedding, self).__init__()
539
+
540
+ minute_size = 60
541
+ hour_size = 24
542
+ weekday_size = 7
543
+ day_size = 32
544
+ month_size = 13
545
+
546
+ Embed = FixedEmbedding if not learn_pe else nn.Embedding
547
+ self.minute_embed = Embed(minute_size, d_model)
548
+ self.hour_embed = Embed(hour_size, d_model)
549
+ self.weekday_embed = Embed(weekday_size, d_model)
550
+ self.day_embed = Embed(day_size, d_model)
551
+ self.month_embed = Embed(month_size, d_model)
552
+
553
+ def forward(self, x):
554
+ x = x.long()
555
+
556
+ minute_x = self.minute_embed(x[:, :, 0])
557
+ hour_x = self.hour_embed(x[:, :, 1])
558
+ weekday_x = self.weekday_embed(x[:, :, 2])
559
+ day_x = self.day_embed(x[:, :, 3])
560
+ month_x = self.month_embed(x[:, :, 4])
561
+
562
+ return hour_x + weekday_x + day_x + month_x + minute_x
563
+
564
+
565
+
566
+
567
+
568
+
569
+
570
+
requirements.txt CHANGED
@@ -1,9 +1,9 @@
1
- torch>=2.0.0
2
- numpy
3
- pandas
4
- einops==0.8.1
5
- huggingface_hub>=0.33
6
- safetensors>=0.4.3
7
- gradio>=5.0
8
- plotly>=5.22
9
  requests
 
1
+ torch>=2.0.0
2
+ numpy
3
+ pandas
4
+ einops==0.8.1
5
+ huggingface_hub>=0.33
6
+ safetensors>=0.4.3
7
+ gradio>=5.0
8
+ plotly>=5.22
9
  requests