Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- Dockerfile +16 -0
- README.md +20 -5
- __pycache__/engine.cpython-310.pyc +0 -0
- __pycache__/predict_us.cpython-310.pyc +0 -0
- app.py +62 -0
- engine.py +117 -0
- model/__init__.py +17 -0
- model/__pycache__/__init__.cpython-310.pyc +0 -0
- model/__pycache__/kronos.cpython-310.pyc +0 -0
- model/__pycache__/module.cpython-310.pyc +0 -0
- model/kronos.py +662 -0
- model/module.py +570 -0
- predict_us.py +50 -0
- requirements.txt +10 -0
- templates/dashboard.html +225 -0
Dockerfile
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# HF Spaces runs as a non-root user (uid 1000); cache HF downloads in a writable dir.
|
| 6 |
+
ENV HF_HOME=/app/.cache/huggingface \
|
| 7 |
+
PYTHONUNBUFFERED=1
|
| 8 |
+
|
| 9 |
+
COPY requirements.txt .
|
| 10 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY . .
|
| 13 |
+
RUN mkdir -p /app/.cache && chmod -R 777 /app/.cache
|
| 14 |
+
|
| 15 |
+
EXPOSE 7860
|
| 16 |
+
CMD ["python", "app.py"]
|
README.md
CHANGED
|
@@ -1,10 +1,25 @@
|
|
| 1 |
---
|
| 2 |
-
title: Kronos
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Kronos US Forecast
|
| 3 |
+
emoji: 📈
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Kronos · US-stock Forecast Dashboard
|
| 12 |
+
|
| 13 |
+
Interactive CPU dashboard for the [Kronos](https://github.com/shiyu-coder/Kronos)
|
| 14 |
+
financial time-series model, applied to US stocks (data via yfinance).
|
| 15 |
+
|
| 16 |
+
Pick a ticker and sampling parameters → the server draws an ensemble of sample
|
| 17 |
+
paths from Kronos-small → the page shows the **median forecast** with a **10–90%
|
| 18 |
+
uncertainty band**, plus accuracy metrics in `backtest` mode.
|
| 19 |
+
|
| 20 |
+
- **Model / prediction**: 100% original Kronos (`model/`, unmodified).
|
| 21 |
+
- **This app**: US data adapter, hold-out accuracy backtest, ensemble median+band,
|
| 22 |
+
metrics, and the interactive UI.
|
| 23 |
+
|
| 24 |
+
⚠️ Runs on CPU — each sample path is ~1–2s, so an ensemble takes tens of seconds.
|
| 25 |
+
The UI shows a spinner and elapsed time. `n_paths` is capped at 30 for hosting.
|
__pycache__/engine.cpython-310.pyc
ADDED
|
Binary file (4.42 kB). View file
|
|
|
__pycache__/predict_us.cpython-310.pyc
ADDED
|
Binary file (2.35 kB). View file
|
|
|
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Hosted US-stock Kronos dashboard for HuggingFace Spaces (Docker SDK).
|
| 3 |
+
|
| 4 |
+
Same Flask app as ../dashboard.py, adapted for hosting:
|
| 5 |
+
* binds 0.0.0.0:7860 (the port HF Spaces expects),
|
| 6 |
+
* pre-loads the model at startup so the first request isn't slow,
|
| 7 |
+
* a lower default n_paths keeps a request comfortably under proxy timeouts.
|
| 8 |
+
"""
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
from flask import Flask, jsonify, render_template, request
|
| 12 |
+
|
| 13 |
+
import engine
|
| 14 |
+
|
| 15 |
+
app = Flask(__name__, template_folder="templates")
|
| 16 |
+
|
| 17 |
+
# Ceiling on ensemble size so a single hosted request can't run for minutes.
|
| 18 |
+
MAX_PATHS = int(os.environ.get("MAX_PATHS", "30"))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@app.route("/")
|
| 22 |
+
def index():
|
| 23 |
+
return render_template("dashboard.html")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@app.route("/api/health")
|
| 27 |
+
def health():
|
| 28 |
+
return jsonify({"ok": True, "model_loaded": engine.is_loaded()})
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@app.route("/api/forecast", methods=["POST"])
|
| 32 |
+
def forecast():
|
| 33 |
+
p = request.get_json(force=True) or {}
|
| 34 |
+
try:
|
| 35 |
+
n_paths = min(int(p.get("n_paths", 20)), MAX_PATHS)
|
| 36 |
+
result = engine.run_ensemble(
|
| 37 |
+
ticker=str(p.get("ticker", "AAPL")).upper().strip(),
|
| 38 |
+
interval=str(p.get("interval", "1d")),
|
| 39 |
+
period=str(p.get("period", "3y")),
|
| 40 |
+
lookback=int(p.get("lookback", 400)),
|
| 41 |
+
pred_len=int(p.get("pred_len", 20)),
|
| 42 |
+
mode=str(p.get("mode", "backtest")),
|
| 43 |
+
n_paths=n_paths,
|
| 44 |
+
T=float(p.get("T", 0.7)),
|
| 45 |
+
top_p=float(p.get("top_p", 0.9)),
|
| 46 |
+
top_k=int(p.get("top_k", 0)),
|
| 47 |
+
seed=int(p.get("seed", 123)),
|
| 48 |
+
)
|
| 49 |
+
return jsonify({"ok": True, "result": result})
|
| 50 |
+
except Exception as exc:
|
| 51 |
+
return jsonify({"ok": False, "error": str(exc)}), 400
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
# Warm the model before serving so the first user request is fast.
|
| 56 |
+
print("[startup] pre-loading Kronos model ...", flush=True)
|
| 57 |
+
try:
|
| 58 |
+
engine.get_predictor()
|
| 59 |
+
print("[startup] model ready.", flush=True)
|
| 60 |
+
except Exception as exc:
|
| 61 |
+
print(f"[startup] model preload failed (will retry on first request): {exc}", flush=True)
|
| 62 |
+
app.run(host="0.0.0.0", port=7860, threaded=True)
|
engine.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Ensemble inference engine for the hosted dashboard.
|
| 3 |
+
Same logic as ../engine.py but with flat imports (Space repo is self-contained).
|
| 4 |
+
"""
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from model import Kronos, KronosTokenizer, KronosPredictor
|
| 10 |
+
from predict_us import fetch_ohlcv, future_timestamps, report_metrics
|
| 11 |
+
|
| 12 |
+
_COLS = ["open", "high", "low", "close", "volume"]
|
| 13 |
+
|
| 14 |
+
_PREDICTOR = None
|
| 15 |
+
_PREDICTOR_KEY = None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_predictor(device: str = "cpu", max_context: int = 512,
|
| 19 |
+
model_id: str = "NeoQuasar/Kronos-small",
|
| 20 |
+
tokenizer_id: str = "NeoQuasar/Kronos-Tokenizer-base"):
|
| 21 |
+
global _PREDICTOR, _PREDICTOR_KEY
|
| 22 |
+
key = (device, max_context, model_id, tokenizer_id)
|
| 23 |
+
if _PREDICTOR is None or _PREDICTOR_KEY != key:
|
| 24 |
+
tokenizer = KronosTokenizer.from_pretrained(tokenizer_id)
|
| 25 |
+
model = Kronos.from_pretrained(model_id)
|
| 26 |
+
tokenizer.eval()
|
| 27 |
+
model.eval()
|
| 28 |
+
_PREDICTOR = KronosPredictor(model, tokenizer, device=device, max_context=max_context)
|
| 29 |
+
_PREDICTOR_KEY = key
|
| 30 |
+
return _PREDICTOR
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def is_loaded() -> bool:
|
| 34 |
+
return _PREDICTOR is not None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def run_ensemble(ticker: str = "AAPL", interval: str = "1d", period: str = "3y",
|
| 38 |
+
lookback: int = 400, pred_len: int = 20, mode: str = "backtest",
|
| 39 |
+
n_paths: int = 20, T: float = 0.7, top_p: float = 0.9, top_k: int = 0,
|
| 40 |
+
seed: int = 123, device: str = "cpu", ctx_tail: int = 120) -> dict:
|
| 41 |
+
import random
|
| 42 |
+
import torch
|
| 43 |
+
|
| 44 |
+
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
|
| 45 |
+
|
| 46 |
+
df = fetch_ohlcv(ticker, interval, period)
|
| 47 |
+
need = lookback + (pred_len if mode == "backtest" else 0)
|
| 48 |
+
if len(df) < need:
|
| 49 |
+
raise ValueError(
|
| 50 |
+
f"Not enough bars for {ticker}: have {len(df)}, need {need}. "
|
| 51 |
+
f"Lower lookback/pred_len or raise period."
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
if mode == "backtest":
|
| 55 |
+
hist = df.iloc[-(lookback + pred_len):-pred_len]
|
| 56 |
+
fut = df.iloc[-pred_len:]
|
| 57 |
+
y_ts = fut["timestamps"].reset_index(drop=True)
|
| 58 |
+
else:
|
| 59 |
+
hist = df.iloc[-lookback:]
|
| 60 |
+
fut = None
|
| 61 |
+
y_ts = future_timestamps(hist["timestamps"].iloc[-1], interval, pred_len)
|
| 62 |
+
|
| 63 |
+
x_df = hist[_COLS].reset_index(drop=True)
|
| 64 |
+
x_ts = hist["timestamps"].reset_index(drop=True)
|
| 65 |
+
|
| 66 |
+
predictor = get_predictor(device=device)
|
| 67 |
+
|
| 68 |
+
t0 = time.time()
|
| 69 |
+
paths = []
|
| 70 |
+
for i in range(n_paths):
|
| 71 |
+
torch.manual_seed(seed + i); np.random.seed(seed + i)
|
| 72 |
+
pred_df = predictor.predict(
|
| 73 |
+
df=x_df, x_timestamp=x_ts, y_timestamp=y_ts, pred_len=pred_len,
|
| 74 |
+
T=T, top_k=top_k, top_p=top_p, sample_count=1, verbose=False,
|
| 75 |
+
)
|
| 76 |
+
paths.append(pred_df["close"].values.astype(float))
|
| 77 |
+
paths = np.stack(paths, axis=0)
|
| 78 |
+
elapsed = time.time() - t0
|
| 79 |
+
|
| 80 |
+
median = np.median(paths, axis=0)
|
| 81 |
+
lo = np.quantile(paths, 0.1, axis=0)
|
| 82 |
+
hi = np.quantile(paths, 0.9, axis=0)
|
| 83 |
+
|
| 84 |
+
def _iso(ts_series):
|
| 85 |
+
return [pd_ts.isoformat() for pd_ts in ts_series]
|
| 86 |
+
|
| 87 |
+
ctx = hist.iloc[-ctx_tail:]
|
| 88 |
+
out = {
|
| 89 |
+
"meta": {
|
| 90 |
+
"ticker": ticker, "interval": interval, "period": period, "mode": mode,
|
| 91 |
+
"lookback": lookback, "pred_len": pred_len, "n_paths": n_paths,
|
| 92 |
+
"T": T, "top_p": top_p, "top_k": top_k, "elapsed": round(elapsed, 1),
|
| 93 |
+
},
|
| 94 |
+
"history": {
|
| 95 |
+
"t": _iso(ctx["timestamps"]),
|
| 96 |
+
"close": [float(v) for v in ctx["close"].values],
|
| 97 |
+
},
|
| 98 |
+
"forecast": {
|
| 99 |
+
"t": _iso(y_ts),
|
| 100 |
+
"median": [float(v) for v in median],
|
| 101 |
+
"lo": [float(v) for v in lo],
|
| 102 |
+
"hi": [float(v) for v in hi],
|
| 103 |
+
"paths": [[float(v) for v in p] for p in paths],
|
| 104 |
+
},
|
| 105 |
+
"truth": None,
|
| 106 |
+
"metrics": None,
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
if mode == "backtest":
|
| 110 |
+
truth = fut["close"].values.astype(float)
|
| 111 |
+
out["truth"] = {"t": _iso(fut["timestamps"]), "close": [float(v) for v in truth]}
|
| 112 |
+
m = report_metrics(truth, median)
|
| 113 |
+
cover = float(np.mean((truth >= lo) & (truth <= hi)) * 100)
|
| 114 |
+
m["coverage%"] = cover
|
| 115 |
+
out["metrics"] = {k: round(v, 3) for k, v in m.items()}
|
| 116 |
+
|
| 117 |
+
return out
|
model/__init__.py
ADDED
|
@@ -0,0 +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 |
+
|
model/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (529 Bytes). View file
|
|
|
model/__pycache__/kronos.cpython-310.pyc
ADDED
|
Binary file (22.8 kB). View file
|
|
|
model/__pycache__/module.cpython-310.pyc
ADDED
|
Binary file (20.1 kB). View file
|
|
|
model/kronos.py
ADDED
|
@@ -0,0 +1,662 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
|
predict_us.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Data + metric helpers for the hosted dashboard (trimmed, no matplotlib/CLI).
|
| 3 |
+
Mirrors the functions of the same name in ../predict_us.py.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def fetch_ohlcv(ticker: str, interval: str, period: str) -> pd.DataFrame:
|
| 10 |
+
"""Download OHLCV via yfinance and normalise to Kronos' expected schema."""
|
| 11 |
+
import yfinance as yf
|
| 12 |
+
|
| 13 |
+
raw = yf.download(ticker, interval=interval, period=period,
|
| 14 |
+
auto_adjust=True, progress=False)
|
| 15 |
+
if raw is None or raw.empty:
|
| 16 |
+
raise RuntimeError(f"No data returned for {ticker} ({interval}, {period}).")
|
| 17 |
+
|
| 18 |
+
if isinstance(raw.columns, pd.MultiIndex):
|
| 19 |
+
raw.columns = raw.columns.get_level_values(0)
|
| 20 |
+
|
| 21 |
+
raw = raw.rename(columns=str.lower)
|
| 22 |
+
df = raw[["open", "high", "low", "close", "volume"]].copy()
|
| 23 |
+
df = df.dropna().reset_index()
|
| 24 |
+
ts_col = "Date" if "Date" in df.columns else "Datetime"
|
| 25 |
+
df = df.rename(columns={ts_col: "timestamps"})
|
| 26 |
+
df["timestamps"] = pd.to_datetime(df["timestamps"]).dt.tz_localize(None)
|
| 27 |
+
return df
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def future_timestamps(last_ts: pd.Timestamp, interval: str, n: int) -> pd.Series:
|
| 31 |
+
"""Generate n future timestamps after last_ts, respecting the bar interval."""
|
| 32 |
+
if interval.endswith("d"):
|
| 33 |
+
idx = pd.bdate_range(start=last_ts, periods=n + 1, freq="C")[1:]
|
| 34 |
+
elif interval.endswith("h"):
|
| 35 |
+
idx = pd.date_range(start=last_ts, periods=n + 1, freq="h")[1:]
|
| 36 |
+
else:
|
| 37 |
+
step = int("".join(c for c in interval if c.isdigit()) or "1")
|
| 38 |
+
idx = pd.date_range(start=last_ts, periods=n + 1, freq=f"{step}min")[1:]
|
| 39 |
+
return pd.Series(idx)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def report_metrics(truth: np.ndarray, pred: np.ndarray) -> dict:
|
| 43 |
+
"""Accuracy metrics on the close price."""
|
| 44 |
+
mae = float(np.mean(np.abs(pred - truth)))
|
| 45 |
+
rmse = float(np.sqrt(np.mean((pred - truth) ** 2)))
|
| 46 |
+
mape = float(np.mean(np.abs((pred - truth) / truth)) * 100)
|
| 47 |
+
dir_truth = np.sign(np.diff(truth))
|
| 48 |
+
dir_pred = np.sign(np.diff(pred))
|
| 49 |
+
da = float(np.mean(dir_truth == dir_pred) * 100) if len(dir_truth) else float("nan")
|
| 50 |
+
return {"MAE": mae, "RMSE": rmse, "MAPE%": mape, "DirAcc%": da}
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch
|
| 3 |
+
numpy
|
| 4 |
+
pandas
|
| 5 |
+
einops==0.8.1
|
| 6 |
+
huggingface_hub==0.33.1
|
| 7 |
+
safetensors==0.6.2
|
| 8 |
+
tqdm==4.67.1
|
| 9 |
+
flask==3.0.3
|
| 10 |
+
yfinance
|
templates/dashboard.html
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Kronos · US Forecast Dashboard</title>
|
| 7 |
+
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
|
| 8 |
+
<style>
|
| 9 |
+
:root{
|
| 10 |
+
--bg:#0d1117; --panel:#161b22; --panel2:#1c2330; --line:#30363d;
|
| 11 |
+
--fg:#e6edf3; --muted:#8b949e; --accent:#e5484d; --blue:#4493f8; --good:#3fb950;
|
| 12 |
+
}
|
| 13 |
+
*{box-sizing:border-box}
|
| 14 |
+
body{margin:0;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
|
| 15 |
+
background:var(--bg);color:var(--fg)}
|
| 16 |
+
header{padding:16px 22px;border-bottom:1px solid var(--line);display:flex;
|
| 17 |
+
align-items:baseline;gap:12px;flex-wrap:wrap}
|
| 18 |
+
header h1{font-size:17px;margin:0;font-weight:650}
|
| 19 |
+
header .sub{color:var(--muted);font-size:12.5px}
|
| 20 |
+
.wrap{display:grid;grid-template-columns:290px 1fr;gap:18px;padding:18px 22px;
|
| 21 |
+
align-items:start}
|
| 22 |
+
@media(max-width:880px){.wrap{grid-template-columns:1fr}}
|
| 23 |
+
.panel{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:16px}
|
| 24 |
+
.panel h2{font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);
|
| 25 |
+
margin:0 0 12px}
|
| 26 |
+
label{display:block;font-size:12px;color:var(--muted);margin:10px 0 4px}
|
| 27 |
+
input,select{width:100%;background:var(--panel2);border:1px solid var(--line);color:var(--fg);
|
| 28 |
+
border-radius:7px;padding:8px 9px;font-size:13px}
|
| 29 |
+
input:focus,select:focus{outline:none;border-color:var(--blue)}
|
| 30 |
+
.row2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
| 31 |
+
button{width:100%;margin-top:16px;background:var(--accent);color:#fff;border:none;
|
| 32 |
+
border-radius:8px;padding:11px;font-size:14px;font-weight:600;cursor:pointer}
|
| 33 |
+
button:disabled{opacity:.55;cursor:not-allowed}
|
| 34 |
+
.chk{display:flex;align-items:center;gap:8px;margin-top:12px;color:var(--muted);font-size:12.5px}
|
| 35 |
+
.chk input{width:auto}
|
| 36 |
+
.metrics{display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:16px}
|
| 37 |
+
@media(max-width:880px){.metrics{grid-template-columns:repeat(2,1fr)}}
|
| 38 |
+
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px}
|
| 39 |
+
.card .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}
|
| 40 |
+
.card .v{font-size:22px;font-weight:680;margin-top:5px}
|
| 41 |
+
.card .u{font-size:12px;color:var(--muted);font-weight:400}
|
| 42 |
+
.chartbox{position:relative;height:460px}
|
| 43 |
+
.status{color:var(--muted);font-size:13px;margin-top:10px;min-height:18px}
|
| 44 |
+
.status.err{color:var(--accent)}
|
| 45 |
+
.spin{display:inline-block;width:13px;height:13px;border:2px solid var(--muted);
|
| 46 |
+
border-top-color:transparent;border-radius:50%;animation:sp .8s linear infinite;
|
| 47 |
+
vertical-align:-2px;margin-right:7px}
|
| 48 |
+
@keyframes sp{to{transform:rotate(360deg)}}
|
| 49 |
+
.empty{color:var(--muted);text-align:center;padding:120px 0;font-size:13px}
|
| 50 |
+
/* info tooltips */
|
| 51 |
+
.info{display:inline-block;width:14px;height:14px;line-height:14px;text-align:center;
|
| 52 |
+
border-radius:50%;background:#30363d;color:#8b949e;font-size:10px;font-weight:700;
|
| 53 |
+
cursor:help;position:relative;margin-left:5px;vertical-align:1px}
|
| 54 |
+
.info:hover{background:var(--blue);color:#fff}
|
| 55 |
+
.info:hover::after{content:attr(data-tip);position:absolute;top:19px;left:0;width:230px;
|
| 56 |
+
background:#0d1117;border:1px solid var(--line);border-radius:7px;padding:9px 11px;
|
| 57 |
+
color:var(--fg);font-size:11.5px;line-height:1.5;font-weight:400;z-index:60;
|
| 58 |
+
box-shadow:0 8px 24px rgba(0,0,0,.55);white-space:normal;text-transform:none;letter-spacing:0}
|
| 59 |
+
.info.il:hover::after{left:auto;right:0} /* right-column fields open leftward */
|
| 60 |
+
</style>
|
| 61 |
+
</head>
|
| 62 |
+
<body>
|
| 63 |
+
<header>
|
| 64 |
+
<h1>Kronos · US Forecast</h1>
|
| 65 |
+
<span class="sub">CPU ensemble · median + 10–90% band · yfinance data</span>
|
| 66 |
+
</header>
|
| 67 |
+
|
| 68 |
+
<div class="wrap">
|
| 69 |
+
<!-- controls -->
|
| 70 |
+
<div class="panel">
|
| 71 |
+
<h2>Parameters</h2>
|
| 72 |
+
<label>Ticker
|
| 73 |
+
<span class="info" data-tip="股票/ETF 代號,任何 yfinance 抓得到的美股皆可,如 AAPL、NVDA、MSFT、SPY、QQQ。自動轉大寫。冷門或剛上市的可能資料不足。"></span></label>
|
| 74 |
+
<input id="ticker" value="AAPL" autocomplete="off">
|
| 75 |
+
<div class="row2">
|
| 76 |
+
<div><label>Interval
|
| 77 |
+
<span class="info" data-tip="K 線週期。1d 日線最穩;1h/5m 的歷史 yfinance 只給最近一小段(5m≈60天),用它們時 Period 要調短,否則抓不到足夠根數會報錯。"></span></label>
|
| 78 |
+
<select id="interval"><option>1d</option><option>1h</option><option>5m</option></select>
|
| 79 |
+
</div>
|
| 80 |
+
<div><label>Period
|
| 81 |
+
<span class="info il" data-tip="往回下載多久的歷史。這是資料範圍,不是餵給模型的長度(那是 Lookback)。只要夠切出 Lookback+Pred len 根即可。別跨太多不同價格量級。"></span></label>
|
| 82 |
+
<select id="period"><option>1y</option><option selected>3y</option><option>5y</option></select>
|
| 83 |
+
</div>
|
| 84 |
+
</div>
|
| 85 |
+
<div class="row2">
|
| 86 |
+
<div><label>Lookback
|
| 87 |
+
<span class="info" data-tip="餵給模型看的歷史根數(model context)。模型上限 512,別超過 ~500;太短看不到趨勢。400 是實測甜蜜點,一般不用動。"></span></label>
|
| 88 |
+
<input id="lookback" type="number" value="400"></div>
|
| 89 |
+
<div><label>Pred len
|
| 90 |
+
<span class="info il" data-tip="要預測未來幾根。越長越不準(不確定性隨步數累積)。短線 5–10,中期 20–30。backtest 模式也用它決定藏起幾根當真值。"></span></label>
|
| 91 |
+
<input id="pred_len" type="number" value="20"></div>
|
| 92 |
+
</div>
|
| 93 |
+
<div class="row2">
|
| 94 |
+
<div><label>Mode
|
| 95 |
+
<span class="info" data-tip="backtest:藏起最後 Pred len 根真值讓模型預測、再對比打分(才有下方指標)。future:用全部最新資料預測真正的未來,無真值、無分數。"></span></label>
|
| 96 |
+
<select id="mode"><option value="backtest">backtest</option><option value="future">future</option></select>
|
| 97 |
+
</div>
|
| 98 |
+
<div><label>Paths
|
| 99 |
+
<span class="info il" data-tip="集成路徑數(此線上版上限 30)。每條是一次獨立抽樣;中位數與 10–90% 區間都由這 N 條算出。越多越穩越慢(CPU 每條 ~1–2s)。集成是把 MAPE 從 8.6% 降到 ~6% 的關鍵。"></span></label>
|
| 100 |
+
<input id="n_paths" type="number" value="20" max="30"></div>
|
| 101 |
+
</div>
|
| 102 |
+
<div class="row2">
|
| 103 |
+
<div><label>Temperature T
|
| 104 |
+
<span class="info" data-tip="抽樣亂度。低(0.5–0.7)保守、路徑集中、方向命中較高;高(1.0+)發散、區間更寬。官方預設 1.0,我們實測 0.7 方向命中最好。"></span></label>
|
| 105 |
+
<input id="T" type="number" step="0.05" value="0.7"></div>
|
| 106 |
+
<div><label>top_p
|
| 107 |
+
<span class="info il" data-tip="Nucleus 抽樣:只從累積機率前 p 的候選裡抽。低(0.8)砍掉長尾極端值、更保守;高(0.95+)允許更極端走勢。官方與我們都用 0.9。"></span></label>
|
| 108 |
+
<input id="top_p" type="number" step="0.05" value="0.9"></div>
|
| 109 |
+
</div>
|
| 110 |
+
<label class="chk"><input type="checkbox" id="showpaths"> show sample paths
|
| 111 |
+
<span class="info" data-tip="只是顯示開關,不影響計算。勾選會把 N 條原始抽樣路徑疊上圖,直觀看發散程度;不勾只留乾淨的中位數 + 區間。"></span></label>
|
| 112 |
+
<button id="run">Run forecast</button>
|
| 113 |
+
<div id="status" class="status"></div>
|
| 114 |
+
</div>
|
| 115 |
+
|
| 116 |
+
<!-- results -->
|
| 117 |
+
<div>
|
| 118 |
+
<div class="metrics" id="metrics" style="display:none">
|
| 119 |
+
<div class="card"><div class="k">MAE <span class="info" data-tip="平均絕對誤差(美元)。越小越好。會隨股價高低而變,不同標的之間別直接比。"></span></div><div class="v" id="m_mae">–</div></div>
|
| 120 |
+
<div class="card"><div class="k">MAPE <span class="info" data-tip="平均百分比誤差。跨標的可比的主要指標,~6% 算不錯。"></span></div><div class="v" id="m_mape">–</div></div>
|
| 121 |
+
<div class="card"><div class="k">Dir Acc <span class="info" data-tip="方向命中率(每步漲跌預測對不對)。50% = 瞎猜,>55% 才算有訊號。"></span></div><div class="v" id="m_dir">–</div></div>
|
| 122 |
+
<div class="card"><div class="k">Band cover <span class="info il" data-tip="真值落在 10–90% 區間內的比例,理想 ~80%。目前偏低 = 模型過度自信,是待辦裡『區間校準』要修的。"></span></div><div class="v" id="m_cov">–</div></div>
|
| 123 |
+
<div class="card"><div class="k">Runtime <span class="info il" data-tip="這次集成在 CPU 上花的秒數,主要由 Paths × Pred len 決定。"></span></div><div class="v" id="m_time">–</div></div>
|
| 124 |
+
</div>
|
| 125 |
+
<div class="panel">
|
| 126 |
+
<div class="chartbox">
|
| 127 |
+
<canvas id="chart" style="display:none"></canvas>
|
| 128 |
+
<div class="empty" id="empty">Set parameters and click <b>Run forecast</b>.<br>
|
| 129 |
+
First run downloads/loads the model (~20–40s), then each path ~1–2s on CPU.</div>
|
| 130 |
+
</div>
|
| 131 |
+
</div>
|
| 132 |
+
</div>
|
| 133 |
+
</div>
|
| 134 |
+
|
| 135 |
+
<script>
|
| 136 |
+
const $ = id => document.getElementById(id);
|
| 137 |
+
let chart = null;
|
| 138 |
+
const fmtDate = s => s.slice(0,10);
|
| 139 |
+
|
| 140 |
+
async function run(){
|
| 141 |
+
const btn = $('run'), st = $('status');
|
| 142 |
+
const body = {
|
| 143 |
+
ticker:$('ticker').value, interval:$('interval').value, period:$('period').value,
|
| 144 |
+
lookback:+$('lookback').value, pred_len:+$('pred_len').value, mode:$('mode').value,
|
| 145 |
+
n_paths:+$('n_paths').value, T:+$('T').value, top_p:+$('top_p').value,
|
| 146 |
+
};
|
| 147 |
+
btn.disabled = true;
|
| 148 |
+
st.className = 'status';
|
| 149 |
+
const t0 = Date.now();
|
| 150 |
+
const tick = setInterval(()=>{ st.innerHTML =
|
| 151 |
+
`<span class="spin"></span>running ${body.n_paths} paths on CPU… ${((Date.now()-t0)/1000).toFixed(0)}s`;
|
| 152 |
+
}, 200);
|
| 153 |
+
try{
|
| 154 |
+
const r = await fetch('/api/forecast', {method:'POST',
|
| 155 |
+
headers:{'Content-Type':'application/json'}, body:JSON.stringify(body)});
|
| 156 |
+
const j = await r.json();
|
| 157 |
+
clearInterval(tick);
|
| 158 |
+
if(!j.ok){ st.className='status err'; st.textContent = 'Error: '+j.error; return; }
|
| 159 |
+
st.textContent = `done in ${j.result.meta.elapsed}s`;
|
| 160 |
+
render(j.result);
|
| 161 |
+
}catch(e){
|
| 162 |
+
clearInterval(tick); st.className='status err'; st.textContent = 'Request failed: '+e;
|
| 163 |
+
}finally{
|
| 164 |
+
btn.disabled = false;
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
function render(res){
|
| 169 |
+
$('empty').style.display='none';
|
| 170 |
+
$('chart').style.display='block';
|
| 171 |
+
const H = res.history, F = res.forecast, Tr = res.truth, M = res.metrics;
|
| 172 |
+
const labels = [...H.t, ...F.t].map(fmtDate);
|
| 173 |
+
const nH = H.t.length, nF = F.t.length;
|
| 174 |
+
const anchor = H.close[nH-1]; // connect history -> forecast
|
| 175 |
+
const pad = n => Array(n).fill(null);
|
| 176 |
+
|
| 177 |
+
// forecast series padded to sit under the forecast portion, anchored to last hist pt
|
| 178 |
+
const fc = arr => { const d = pad(nH-1); d.push(anchor); return d.concat(arr); };
|
| 179 |
+
const histLine = H.close.concat(pad(nF));
|
| 180 |
+
|
| 181 |
+
const ds = [
|
| 182 |
+
{label:'History', data:histLine, borderColor:'#8b949e', borderWidth:1.4,
|
| 183 |
+
pointRadius:0, tension:.15},
|
| 184 |
+
{label:'10–90% band (hi)', data:fc(F.hi), borderColor:'transparent',
|
| 185 |
+
backgroundColor:'rgba(229,72,77,.16)', pointRadius:0, fill:'+1'},
|
| 186 |
+
{label:'10–90% band (lo)', data:fc(F.lo), borderColor:'transparent',
|
| 187 |
+
pointRadius:0, fill:false},
|
| 188 |
+
{label:'Median forecast', data:fc(F.median), borderColor:'#e5484d',
|
| 189 |
+
borderWidth:2.4, pointRadius:0, tension:.15},
|
| 190 |
+
];
|
| 191 |
+
if(Tr){ ds.push({label:'Ground truth', data:fc(Tr.close), borderColor:'#4493f8',
|
| 192 |
+
borderWidth:2.4, pointRadius:0, tension:.15}); }
|
| 193 |
+
if($('showpaths').checked){
|
| 194 |
+
F.paths.forEach(p => ds.push({label:'_path', data:fc(p), borderColor:'rgba(229,72,77,.13)',
|
| 195 |
+
borderWidth:.6, pointRadius:0, tension:.1}));
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
const cfg = {type:'line', data:{labels, datasets:ds}, options:{
|
| 199 |
+
responsive:true, maintainAspectRatio:false, animation:false,
|
| 200 |
+
interaction:{mode:'index', intersect:false},
|
| 201 |
+
plugins:{legend:{labels:{color:'#e6edf3', filter:i=>!i.text.startsWith('_')
|
| 202 |
+
&& !i.text.includes('(lo)')}},
|
| 203 |
+
tooltip:{filter:i=>i.dataset.label!=='_path' && !i.dataset.label.includes('(lo)')}},
|
| 204 |
+
scales:{
|
| 205 |
+
x:{ticks:{color:'#8b949e',maxTicksLimit:12,autoSkip:true},grid:{color:'#21262d'}},
|
| 206 |
+
y:{ticks:{color:'#8b949e'},grid:{color:'#21262d'}},
|
| 207 |
+
}}};
|
| 208 |
+
if(chart) chart.destroy();
|
| 209 |
+
chart = new Chart($('chart'), cfg);
|
| 210 |
+
|
| 211 |
+
// metrics (accuracy cards only exist in backtest; runtime always shown)
|
| 212 |
+
$('metrics').style.display='grid';
|
| 213 |
+
const U = '<span class="u">%</span>';
|
| 214 |
+
$('m_mae').innerHTML = M ? M['MAE'].toFixed(2) : '–';
|
| 215 |
+
$('m_mape').innerHTML = M ? M['MAPE%'].toFixed(2)+U : '–';
|
| 216 |
+
$('m_dir').innerHTML = M ? M['DirAcc%'].toFixed(0)+U : '–';
|
| 217 |
+
$('m_cov').innerHTML = M ? M['coverage%'].toFixed(0)+U : '–';
|
| 218 |
+
$('m_time').innerHTML = res.meta.elapsed+'<span class="u">s</span>';
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
$('run').addEventListener('click', run);
|
| 222 |
+
$('ticker').addEventListener('keydown', e=>{ if(e.key==='Enter') run(); });
|
| 223 |
+
</script>
|
| 224 |
+
</body>
|
| 225 |
+
</html>
|