xianqiu commited on
Commit
57be171
·
1 Parent(s): 881b36e

Deploy Kronos BTC Prediction API

Browse files

- FastAPI server with /predict and /signal endpoints
- Kronos model (iter5, 62.4% win rate, 3.25 Sharpe ratio)
- Python client SDK
- Docker configuration for HuggingFace Spaces

DEPLOYMENT.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HuggingFace Space 部署指南
2
+
3
+ 本指南介绍如何将 Kronos BTC 预测 API 部署到 HuggingFace Spaces。
4
+
5
+ ## 准备工作
6
+
7
+ ### 1. 创建 HuggingFace 账户
8
+
9
+ 如果还没有账户,请访问 https://huggingface.co/join 注册。
10
+
11
+ ### 2. 安装 HuggingFace CLI
12
+
13
+ ```bash
14
+ pip install huggingface_hub
15
+ huggingface-cli login
16
+ ```
17
+
18
+ ## 方法一:通过 Git 部署 (推荐)
19
+
20
+ ### 1. 创建新 Space
21
+
22
+ 访问 https://huggingface.co/new-space 创建新 Space:
23
+
24
+ - **Space name**: `kronos-btc-predictor` (或任意名称)
25
+ - **License**: MIT
26
+ - **SDK**: Docker
27
+ - **Hardware**: CPU basic (免费)
28
+
29
+ ### 2. 克隆 Space 仓库
30
+
31
+ ```bash
32
+ git clone https://huggingface.co/spaces/YOUR_USERNAME/kronos-btc-predictor
33
+ cd kronos-btc-predictor
34
+ ```
35
+
36
+ ### 3. 复制文件
37
+
38
+ ```bash
39
+ # 复制所有文件到 Space 仓库
40
+ cp -r /path/to/hf_space/* .
41
+
42
+ # 文件结构应该是:
43
+ # ├── app.py
44
+ # ├── requirements.txt
45
+ # ├── README.md
46
+ # ├── client.py
47
+ # ├── Dockerfile # 需要创建
48
+ # ├── model/
49
+ # │ ├── __init__.py
50
+ # │ ├── kronos.py
51
+ # │ └── module.py
52
+ # └── models/
53
+ # ├── tokenizer/
54
+ # │ ├── config.json
55
+ # │ └── model.safetensors
56
+ # └── predictor/
57
+ # ├── config.json
58
+ # └── model.safetensors
59
+ ```
60
+
61
+ ### 4. 创建 Dockerfile
62
+
63
+ ```dockerfile
64
+ FROM python:3.10-slim
65
+
66
+ WORKDIR /app
67
+
68
+ # 安装依赖
69
+ COPY requirements.txt .
70
+ RUN pip install --no-cache-dir -r requirements.txt
71
+
72
+ # 复制应用代码
73
+ COPY . .
74
+
75
+ # 暴露端口
76
+ EXPOSE 7860
77
+
78
+ # 启动服务
79
+ CMD ["python", "app.py"]
80
+ ```
81
+
82
+ ### 5. 推送到 HuggingFace
83
+
84
+ ```bash
85
+ git add .
86
+ git commit -m "Initial deployment"
87
+ git push
88
+ ```
89
+
90
+ ### 6. 等待构建
91
+
92
+ Space 会自动构建和部署。你可以在 Space 页面查看构建日志。
93
+
94
+ 构建完成后,API 将在以下地址可用:
95
+ ```
96
+ https://YOUR_USERNAME-kronos-btc-predictor.hf.space
97
+ ```
98
+
99
+ ## 方法二:通过 Web 界面上传
100
+
101
+ ### 1. 创建 Space
102
+
103
+ 访问 https://huggingface.co/new-space:
104
+ - SDK: Docker
105
+ - Hardware: CPU basic
106
+
107
+ ### 2. 上传文件
108
+
109
+ 在 Space 页面点击 "Files" 标签,然后 "Add file" -> "Upload files":
110
+
111
+ 逐个上传以下文件:
112
+ - `app.py`
113
+ - `requirements.txt`
114
+ - `Dockerfile`
115
+ - `model/__init__.py`
116
+ - `model/kronos.py`
117
+ - `model/module.py`
118
+ - `models/tokenizer/config.json`
119
+ - `models/tokenizer/model.safetensors`
120
+ - `models/predictor/config.json`
121
+ - `models/predictor/model.safetensors`
122
+
123
+ ## 验证部署
124
+
125
+ ### 1. 健康检查
126
+
127
+ ```bash
128
+ curl https://YOUR_USERNAME-kronos-btc-predictor.hf.space/health
129
+ ```
130
+
131
+ 预期响应:
132
+ ```json
133
+ {
134
+ "status": "healthy",
135
+ "model_loaded": true,
136
+ "model_version": "iter5 (converged)",
137
+ "device": "cpu"
138
+ }
139
+ ```
140
+
141
+ ### 2. API 文档
142
+
143
+ 访问 Swagger UI:
144
+ ```
145
+ https://YOUR_USERNAME-kronos-btc-predictor.hf.space/docs
146
+ ```
147
+
148
+ ### 3. 测试预测
149
+
150
+ ```python
151
+ from client import KronosClient
152
+
153
+ client = KronosClient("https://YOUR_USERNAME-kronos-btc-predictor.hf.space")
154
+ health = client.health()
155
+ print(f"Status: {health.status}")
156
+ ```
157
+
158
+ ## 配置自定义域名
159
+
160
+ 1. 在 Space 设置中找到 "Custom domain"
161
+ 2. 输入你的域名 (如 `api.yourdomain.com`)
162
+ 3. 配置 DNS CNAME 记录指向 HuggingFace
163
+
164
+ ## 注意事项
165
+
166
+ ### 免费版限制
167
+
168
+ - **CPU**: 2 vCPU
169
+ - **内存**: 16GB RAM
170
+ - **存储**: 50GB
171
+ - **请求**: 无硬性限制,但有速率控制
172
+ - **冷启动**: 不活动时会休眠,首次请求需等待约 30-60 秒
173
+
174
+ ### 性能优化
175
+
176
+ 1. **减少 n_paths**: 使用 10-20 个路径而不是 30-100
177
+ 2. **减少 pred_len**: 使用 12-24 而不是 72
178
+ 3. **预热**: 定期发送健康检查请求防止休眠
179
+
180
+ ### 安全建议
181
+
182
+ 1. 不要在代码中硬编码 API 密钥
183
+ 2. 使用 HuggingFace Secrets 存储敏感信息
184
+ 3. 考虑添加请求速率限制
185
+
186
+ ## 升级到 Pro
187
+
188
+ 如果需要更好的性能,可以升级到 HuggingFace Pro:
189
+
190
+ - **CPU upgrade**: 更快的 CPU
191
+ - **GPU**: T4 GPU (付费)
192
+ - **永不休眠**: 始终保持运行
193
+
194
+ 访问 https://huggingface.co/pricing 了解详情。
195
+
196
+ ## 故障排除
197
+
198
+ ### 构建失败
199
+
200
+ 1. 检查 `requirements.txt` 中的版本兼容性
201
+ 2. 确保所有文件都已上传
202
+ 3. 查看构建日志中的错误信息
203
+
204
+ ### 模型加载失败
205
+
206
+ 1. 确认 `models/` 目录结构正确
207
+ 2. 检查 `config.json` 和 `model.safetensors` 文件
208
+
209
+ ### 请求超时
210
+
211
+ 1. 减少 `n_paths` 和 `pred_len` 参数
212
+ 2. 检查输入数据大小
213
+ 3. 考虑升级到更好的硬件
214
+
215
+ ## 联系支持
216
+
217
+ 如有问题,请在项目仓库提交 Issue。
Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kronos BTC Prediction API - Docker Image
2
+ # Optimized for HuggingFace Spaces
3
+
4
+ FROM python:3.10-slim
5
+
6
+ # Set working directory
7
+ WORKDIR /app
8
+
9
+ # Install system dependencies
10
+ RUN apt-get update && apt-get install -y --no-install-recommends \
11
+ build-essential \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Copy requirements first for better caching
15
+ COPY requirements.txt .
16
+
17
+ # Install Python dependencies
18
+ RUN pip install --no-cache-dir -r requirements.txt
19
+
20
+ # Copy application code
21
+ COPY . .
22
+
23
+ # Create non-root user for security
24
+ RUN useradd -m -u 1000 user
25
+ USER user
26
+
27
+ # Set environment variables
28
+ ENV HOME=/home/user \
29
+ PATH=/home/user/.local/bin:$PATH \
30
+ PYTHONUNBUFFERED=1
31
+
32
+ # Expose port (HuggingFace Spaces uses 7860)
33
+ EXPOSE 7860
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
37
+ CMD python -c "import httpx; httpx.get('http://localhost:7860/health', timeout=5)" || exit 1
38
+
39
+ # Start the application
40
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,12 +1,50 @@
1
  ---
2
- title: Tslm
3
- emoji: 🦀
4
- colorFrom: indigo
5
- colorTo: yellow
6
  sdk: docker
7
  pinned: false
8
- license: apache-2.0
9
- short_description: time series language modle
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: TSLM - Time Series Language Model
3
+ emoji: 📈
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: docker
7
  pinned: false
8
+ license: mit
9
+ short_description: BTC price prediction API based on Kronos model
10
  ---
11
 
12
+ # Kronos BTC Prediction API
13
+
14
+ 基于 Kronos 时序预测模型的 BTC 价格预测 API 服务。
15
+
16
+ ## 模型信息
17
+
18
+ | 指标 | 值 |
19
+ |------|-----|
20
+ | 迭代版本 | iter5 (收敛) |
21
+ | 胜率 | 62.4% |
22
+ | 夏普比率 | 3.25 |
23
+ | 盈亏比 | 1.47 |
24
+ | 模型大小 | ~32MB |
25
+
26
+ ## API 端点
27
+
28
+ - `GET /health` - 健康检查
29
+ - `POST /predict` - 价格预测
30
+ - `POST /signal` - 交易信号
31
+
32
+ ## 快速开始
33
+
34
+ ```python
35
+ from client import KronosClient
36
+
37
+ client = KronosClient("https://xianqiu-tslm.hf.space")
38
+
39
+ # 价格预测
40
+ prediction = client.predict(ohlcv_data, pred_len=24)
41
+ print(f"上涨概率: {prediction.upside_probability:.1%}")
42
+
43
+ # 交易信号
44
+ signal = client.get_signal(ohlcv_data)
45
+ print(f"信号: {signal.signal}")
46
+ ```
47
+
48
+ ## API 文档
49
+
50
+ 访问 `/docs` 查看完整的 Swagger API 文档。
app.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Kronos BTC Prediction API - HuggingFace Space
3
+ 基于 Kronos 模型的 BTC 价格预测 API 服务
4
+
5
+ 模型信息:
6
+ - 迭代版本: iter5 (收敛)
7
+ - 胜率: 62.4%
8
+ - 夏普比率: 3.25
9
+ - 盈亏比: 1.47
10
+
11
+ API 端点:
12
+ - GET /health - 健康检查
13
+ - POST /predict - 预测 BTC 价格走势
14
+ - POST /signal - 生成交易信号
15
+ """
16
+
17
+ import os
18
+ import logging
19
+ from datetime import datetime, timedelta
20
+ from typing import List, Optional
21
+ from enum import Enum
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+ import torch
26
+ from fastapi import FastAPI, HTTPException
27
+ from fastapi.middleware.cors import CORSMiddleware
28
+ from pydantic import BaseModel, Field
29
+
30
+ from model import KronosTokenizer, Kronos, calc_time_stamps
31
+
32
+ # 配置日志
33
+ logging.basicConfig(level=logging.INFO)
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # 创建 FastAPI 应用
37
+ app = FastAPI(
38
+ title="Kronos BTC Prediction API",
39
+ description="基于 Kronos 时序预测模型的 BTC 价格预测服务",
40
+ version="1.0.0",
41
+ docs_url="/docs",
42
+ redoc_url="/redoc"
43
+ )
44
+
45
+ # CORS 配置
46
+ app.add_middleware(
47
+ CORSMiddleware,
48
+ allow_origins=["*"],
49
+ allow_credentials=True,
50
+ allow_methods=["*"],
51
+ allow_headers=["*"],
52
+ )
53
+
54
+
55
+ # ==================== 数据模型 ====================
56
+
57
+ class OHLCVData(BaseModel):
58
+ """OHLCV K线数据"""
59
+ timestamp: str = Field(..., description="时间戳 (ISO格式或毫秒)")
60
+ open: float = Field(..., description="开盘价")
61
+ high: float = Field(..., description="最高价")
62
+ low: float = Field(..., description="最低价")
63
+ close: float = Field(..., description="收盘价")
64
+ volume: float = Field(0.0, description="成交量")
65
+ amount: Optional[float] = Field(None, description="成交额 (可选)")
66
+
67
+
68
+ class PredictRequest(BaseModel):
69
+ """预测请求"""
70
+ data: List[OHLCVData] = Field(..., description="历史 OHLCV 数据 (至少 100 条)")
71
+ pred_len: int = Field(24, ge=1, le=72, description="预测长度 (小时)")
72
+ n_paths: int = Field(30, ge=10, le=100, description="Monte Carlo 路径数")
73
+ temperature: float = Field(1.0, ge=0.1, le=2.0, description="采样温度")
74
+ top_p: float = Field(0.9, ge=0.5, le=1.0, description="Top-p 采样")
75
+
76
+
77
+ class PredictResponse(BaseModel):
78
+ """预测响应"""
79
+ current_price: float
80
+ mean_forecast: float
81
+ min_forecast: float
82
+ max_forecast: float
83
+ upside_probability: float
84
+ expected_return: float
85
+ volatility_amplification: float
86
+ confidence: float
87
+ forecast_prices: List[float]
88
+ timestamp: str
89
+
90
+
91
+ class SignalType(str, Enum):
92
+ """交易信号类型"""
93
+ STRONG_BUY = "STRONG_BUY"
94
+ BUY = "BUY"
95
+ HOLD = "HOLD"
96
+ SELL = "SELL"
97
+ STRONG_SELL = "STRONG_SELL"
98
+
99
+
100
+ class SignalRequest(BaseModel):
101
+ """交易信号请求"""
102
+ data: List[OHLCVData] = Field(..., description="历史 OHLCV 数据")
103
+ buy_threshold: float = Field(0.58, ge=0.5, le=0.9, description="买入阈值")
104
+ sell_threshold: float = Field(0.42, ge=0.1, le=0.5, description="卖出阈值")
105
+ stop_loss: float = Field(0.03, ge=0.01, le=0.1, description="止损比例")
106
+ take_profit: float = Field(0.08, ge=0.02, le=0.2, description="止盈比例")
107
+ n_paths: int = Field(30, ge=10, le=100, description="Monte Carlo 路径数")
108
+
109
+
110
+ class SignalResponse(BaseModel):
111
+ """交易信号响应"""
112
+ signal: SignalType
113
+ confidence: float
114
+ current_price: float
115
+ target_price: float
116
+ stop_loss_price: float
117
+ take_profit_price: float
118
+ upside_probability: float
119
+ expected_return: float
120
+ suggested_position_size: float
121
+ reason: str
122
+ timestamp: str
123
+
124
+
125
+ class HealthResponse(BaseModel):
126
+ """健康检查响应"""
127
+ model_config = {"protected_namespaces": ()}
128
+
129
+ status: str
130
+ model_loaded: bool
131
+ model_version: str
132
+ device: str
133
+ timestamp: str
134
+
135
+
136
+ # ==================== 模型加载 ====================
137
+
138
+ class KronosPredictor:
139
+ """Kronos 预测器"""
140
+
141
+ def __init__(self):
142
+ self.tokenizer = None
143
+ self.model = None
144
+ self.device = "cpu" # HuggingFace Space 免费版只有 CPU
145
+ self.max_context = 2048
146
+ self.clip = 5.0
147
+ self.loaded = False
148
+
149
+ def load_models(self):
150
+ """加载模型"""
151
+ if self.loaded:
152
+ return
153
+
154
+ logger.info("Loading Kronos models...")
155
+
156
+ # 模型路径
157
+ tokenizer_path = os.path.join(os.path.dirname(__file__), "models", "tokenizer")
158
+ predictor_path = os.path.join(os.path.dirname(__file__), "models", "predictor")
159
+
160
+ # 加载 tokenizer
161
+ logger.info(f"Loading tokenizer from {tokenizer_path}")
162
+ self.tokenizer = KronosTokenizer.from_pretrained(tokenizer_path)
163
+ self.tokenizer.to(self.device)
164
+ self.tokenizer.eval()
165
+
166
+ # 加载 predictor
167
+ logger.info(f"Loading predictor from {predictor_path}")
168
+ self.model = Kronos.from_pretrained(predictor_path)
169
+ self.model.to(self.device)
170
+ self.model.eval()
171
+
172
+ self.loaded = True
173
+ logger.info("Models loaded successfully!")
174
+
175
+ def _sample_from_logits(self, logits, T, top_p):
176
+ """从 logits 采样"""
177
+ logits = logits / T
178
+
179
+ if top_p < 1.0:
180
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
181
+ cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
182
+ sorted_indices_to_remove = cumulative_probs > top_p
183
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
184
+ sorted_indices_to_remove[..., 0] = 0
185
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
186
+ logits[indices_to_remove] = float('-inf')
187
+
188
+ probs = torch.softmax(logits, dim=-1)
189
+ return torch.multinomial(probs, num_samples=1)
190
+
191
+ @torch.no_grad()
192
+ def predict(self, df: pd.DataFrame, pred_len: int = 24, n_paths: int = 30,
193
+ T: float = 1.0, top_p: float = 0.9) -> dict:
194
+ """
195
+ 执行预测
196
+
197
+ Args:
198
+ df: OHLCV DataFrame
199
+ pred_len: 预测长度
200
+ n_paths: Monte Carlo 路径数
201
+ T: 温度
202
+ top_p: Top-p 采样
203
+
204
+ Returns:
205
+ 预测结果字典
206
+ """
207
+ if not self.loaded:
208
+ self.load_models()
209
+
210
+ df = df.copy()
211
+
212
+ # 确保有 amount 列
213
+ if 'amount' not in df.columns:
214
+ df['amount'] = df['volume'] * df['close']
215
+
216
+ # 时间戳处理
217
+ x_timestamp = pd.Series(df['timestamp'])
218
+ last_time = df['timestamp'].iloc[-1]
219
+ y_timestamp = pd.Series(pd.date_range(
220
+ start=last_time + timedelta(hours=1),
221
+ periods=pred_len,
222
+ freq='1h'
223
+ ))
224
+
225
+ x_time_df = calc_time_stamps(x_timestamp)
226
+ y_time_df = calc_time_stamps(y_timestamp)
227
+
228
+ # 特征
229
+ price_cols = ['open', 'high', 'low', 'close']
230
+ x = df[price_cols + ['volume', 'amount']].values.astype(np.float32)
231
+ x_stamp = x_time_df.values.astype(np.float32)
232
+ y_stamp = y_time_df.values.astype(np.float32)
233
+
234
+ # 归一化
235
+ x_mean = np.mean(x, axis=0)
236
+ x_std = np.std(x, axis=0)
237
+ x_norm = (x - x_mean) / (x_std + 1e-5)
238
+ x_norm = np.clip(x_norm, -self.clip, self.clip)
239
+
240
+ # 添加 batch 维度
241
+ x_norm = x_norm[np.newaxis, :]
242
+ x_stamp = x_stamp[np.newaxis, :]
243
+ y_stamp = y_stamp[np.newaxis, :]
244
+
245
+ # 转换为 tensor
246
+ x_tensor = torch.from_numpy(x_norm).to(self.device)
247
+ x_stamp_tensor = torch.from_numpy(x_stamp).to(self.device)
248
+ y_stamp_tensor = torch.from_numpy(y_stamp).to(self.device)
249
+
250
+ # Monte Carlo 采样
251
+ all_paths = self._generate_mc_paths(
252
+ x_tensor, x_stamp_tensor, y_stamp_tensor,
253
+ pred_len, T, top_p, n_paths
254
+ )
255
+
256
+ # 反归一化
257
+ all_paths = all_paths[0] # (n_paths, pred_len, 6)
258
+ all_paths = all_paths * (x_std + 1e-5) + x_mean
259
+
260
+ # 计算指标
261
+ current_price = float(df['close'].iloc[-1])
262
+ close_paths = all_paths[:, :, 3] # close price
263
+
264
+ final_prices = close_paths[:, -1]
265
+ mean_forecast = float(np.mean(final_prices))
266
+ upside_prob = float(np.mean(final_prices > current_price))
267
+
268
+ # 波动率放大
269
+ hist_returns = df['close'].pct_change().dropna().values[-24:]
270
+ hist_vol = np.std(hist_returns) if len(hist_returns) > 0 else 0.01
271
+
272
+ pred_vols = []
273
+ for path in close_paths:
274
+ returns = np.diff(path) / path[:-1]
275
+ pred_vols.append(np.std(returns))
276
+ vol_amp = float(np.mean(np.array(pred_vols) > hist_vol))
277
+
278
+ # 置信度
279
+ confidence = 1.0 - np.std(final_prices) / (np.mean(final_prices) + 1e-8)
280
+ confidence = float(max(0.0, min(1.0, confidence)))
281
+
282
+ # 预期收益
283
+ expected_return = (mean_forecast - current_price) / current_price
284
+
285
+ # 平均预测路径
286
+ mean_path = np.mean(close_paths, axis=0).tolist()
287
+
288
+ return {
289
+ "current_price": current_price,
290
+ "mean_forecast": mean_forecast,
291
+ "min_forecast": float(np.min(final_prices)),
292
+ "max_forecast": float(np.max(final_prices)),
293
+ "upside_probability": upside_prob,
294
+ "expected_return": float(expected_return),
295
+ "volatility_amplification": vol_amp,
296
+ "confidence": confidence,
297
+ "forecast_prices": mean_path,
298
+ "timestamp": datetime.utcnow().isoformat()
299
+ }
300
+
301
+ def _generate_mc_paths(self, x, x_stamp, y_stamp, pred_len, T, top_p, n_paths):
302
+ """生成 Monte Carlo 路径"""
303
+ x = torch.clip(x, -self.clip, self.clip)
304
+
305
+ # 扩展为多个路径
306
+ x = x.unsqueeze(1).repeat(1, n_paths, 1, 1).reshape(-1, x.size(1), x.size(2))
307
+ x_stamp = x_stamp.unsqueeze(1).repeat(1, n_paths, 1, 1).reshape(-1, x_stamp.size(1), x_stamp.size(2))
308
+ y_stamp = y_stamp.unsqueeze(1).repeat(1, n_paths, 1, 1).reshape(-1, y_stamp.size(1), y_stamp.size(2))
309
+
310
+ # 编码
311
+ x_token = self.tokenizer.encode(x, half=True)
312
+
313
+ initial_seq_len = x.size(1)
314
+ batch_size = x_token[0].size(0)
315
+ total_seq_len = initial_seq_len + pred_len
316
+ full_stamp = torch.cat([x_stamp, y_stamp], dim=1)
317
+
318
+ generated_pre = x_token[0].new_empty(batch_size, pred_len)
319
+ generated_post = x_token[1].new_empty(batch_size, pred_len)
320
+
321
+ pre_buffer = x_token[0].new_zeros(batch_size, self.max_context)
322
+ post_buffer = x_token[1].new_zeros(batch_size, self.max_context)
323
+ buffer_len = min(initial_seq_len, self.max_context)
324
+
325
+ if buffer_len > 0:
326
+ start_idx = max(0, initial_seq_len - self.max_context)
327
+ pre_buffer[:, :buffer_len] = x_token[0][:, start_idx:start_idx + buffer_len]
328
+ post_buffer[:, :buffer_len] = x_token[1][:, start_idx:start_idx + buffer_len]
329
+
330
+ # 自回归生成
331
+ for i in range(pred_len):
332
+ current_seq_len = initial_seq_len + i
333
+ window_len = min(current_seq_len, self.max_context)
334
+
335
+ if current_seq_len <= self.max_context:
336
+ input_tokens = [pre_buffer[:, :window_len], post_buffer[:, :window_len]]
337
+ else:
338
+ input_tokens = [pre_buffer, post_buffer]
339
+
340
+ context_end = current_seq_len
341
+ context_start = max(0, context_end - self.max_context)
342
+ current_stamp = full_stamp[:, context_start:context_end, :].contiguous()
343
+
344
+ s1_logits, context = self.model.decode_s1(input_tokens[0], input_tokens[1], current_stamp)
345
+ s1_logits = s1_logits[:, -1, :]
346
+ sample_pre = self._sample_from_logits(s1_logits, T, top_p)
347
+
348
+ s2_logits = self.model.decode_s2(context, sample_pre)
349
+ s2_logits = s2_logits[:, -1, :]
350
+ sample_post = self._sample_from_logits(s2_logits, T, top_p)
351
+
352
+ generated_pre[:, i] = sample_pre.squeeze(-1)
353
+ generated_post[:, i] = sample_post.squeeze(-1)
354
+
355
+ if current_seq_len < self.max_context:
356
+ pre_buffer[:, current_seq_len] = sample_pre.squeeze(-1)
357
+ post_buffer[:, current_seq_len] = sample_post.squeeze(-1)
358
+ else:
359
+ pre_buffer = torch.roll(pre_buffer, shifts=-1, dims=1)
360
+ post_buffer = torch.roll(post_buffer, shifts=-1, dims=1)
361
+ pre_buffer[:, -1] = sample_pre.squeeze(-1)
362
+ post_buffer[:, -1] = sample_post.squeeze(-1)
363
+
364
+ # 解码
365
+ full_pre = torch.cat([x_token[0], generated_pre], dim=1)
366
+ full_post = torch.cat([x_token[1], generated_post], dim=1)
367
+
368
+ context_start = max(0, total_seq_len - self.max_context)
369
+ input_tokens = [
370
+ full_pre[:, context_start:total_seq_len].contiguous(),
371
+ full_post[:, context_start:total_seq_len].contiguous()
372
+ ]
373
+ z = self.tokenizer.decode(input_tokens, half=True)
374
+
375
+ # 重塑
376
+ z = z.reshape(-1, n_paths, z.size(1), z.size(2))
377
+ preds = z.cpu().numpy()
378
+
379
+ return preds[:, :, -pred_len:, :]
380
+
381
+ def generate_signal(self, df: pd.DataFrame, buy_threshold: float = 0.58,
382
+ sell_threshold: float = 0.42, stop_loss: float = 0.03,
383
+ take_profit: float = 0.08, n_paths: int = 30) -> dict:
384
+ """
385
+ 生成交易信号
386
+ """
387
+ # 获取预测
388
+ pred = self.predict(df, pred_len=24, n_paths=n_paths)
389
+
390
+ current_price = pred["current_price"]
391
+ upside_prob = pred["upside_probability"]
392
+ confidence = pred["confidence"]
393
+ vol_amp = pred["volatility_amplification"]
394
+
395
+ # 生成信号
396
+ if confidence < 0.3:
397
+ signal = SignalType.HOLD
398
+ reason = f"Low confidence ({confidence:.2f})"
399
+ elif upside_prob > 0.7 and vol_amp < 0.5:
400
+ signal = SignalType.STRONG_BUY
401
+ reason = f"Strong upside ({upside_prob:.1%}) with low volatility"
402
+ elif upside_prob > buy_threshold:
403
+ signal = SignalType.BUY
404
+ reason = f"Upside probability {upside_prob:.1%} > {buy_threshold:.0%}"
405
+ elif upside_prob < 0.3 and vol_amp < 0.5:
406
+ signal = SignalType.STRONG_SELL
407
+ reason = f"Strong downside ({1-upside_prob:.1%}) with low volatility"
408
+ elif upside_prob < sell_threshold:
409
+ signal = SignalType.SELL
410
+ reason = f"Upside probability {upside_prob:.1%} < {sell_threshold:.0%}"
411
+ else:
412
+ signal = SignalType.HOLD
413
+ reason = f"Neutral zone (upside: {upside_prob:.1%})"
414
+
415
+ # 计算价格目标
416
+ if signal in [SignalType.BUY, SignalType.STRONG_BUY]:
417
+ target_price = pred["mean_forecast"]
418
+ stop_loss_price = current_price * (1 - stop_loss)
419
+ take_profit_price = current_price * (1 + take_profit)
420
+ elif signal in [SignalType.SELL, SignalType.STRONG_SELL]:
421
+ target_price = pred["mean_forecast"]
422
+ stop_loss_price = current_price * (1 + stop_loss)
423
+ take_profit_price = current_price * (1 - take_profit)
424
+ else:
425
+ target_price = current_price
426
+ stop_loss_price = current_price
427
+ take_profit_price = current_price
428
+
429
+ # 动态仓位 (Kelly Criterion 简化版)
430
+ if signal != SignalType.HOLD:
431
+ win_prob = upside_prob if upside_prob > 0.5 else (1 - upside_prob)
432
+ odds = take_profit / stop_loss
433
+ kelly = (win_prob * odds - (1 - win_prob)) / odds
434
+ kelly = kelly * 0.5 # 半 Kelly
435
+ direction_strength = abs(upside_prob - 0.5) * 2
436
+ position_size = 0.1 * (1 + direction_strength) * confidence
437
+ position_size = max(0.02, min(0.3, position_size))
438
+ if kelly > 0:
439
+ position_size = min(position_size, kelly)
440
+ else:
441
+ position_size = 0.02
442
+ else:
443
+ position_size = 0.0
444
+
445
+ return {
446
+ "signal": signal,
447
+ "confidence": confidence,
448
+ "current_price": current_price,
449
+ "target_price": target_price,
450
+ "stop_loss_price": stop_loss_price,
451
+ "take_profit_price": take_profit_price,
452
+ "upside_probability": upside_prob,
453
+ "expected_return": pred["expected_return"],
454
+ "suggested_position_size": position_size,
455
+ "reason": reason,
456
+ "timestamp": datetime.utcnow().isoformat()
457
+ }
458
+
459
+
460
+ # 全局预测器实例
461
+ predictor = KronosPredictor()
462
+
463
+
464
+ # ==================== API 端点 ====================
465
+
466
+ @app.on_event("startup")
467
+ async def startup_event():
468
+ """启动时加载模型"""
469
+ logger.info("Starting Kronos BTC Prediction API...")
470
+ try:
471
+ predictor.load_models()
472
+ except Exception as e:
473
+ logger.error(f"Failed to load models: {e}")
474
+
475
+
476
+ @app.get("/", response_model=HealthResponse)
477
+ async def root():
478
+ """根路径 - 返回健康状态"""
479
+ return await health_check()
480
+
481
+
482
+ @app.get("/health", response_model=HealthResponse)
483
+ async def health_check():
484
+ """健康检查"""
485
+ return HealthResponse(
486
+ status="healthy" if predictor.loaded else "loading",
487
+ model_loaded=predictor.loaded,
488
+ model_version="iter5 (converged)",
489
+ device=predictor.device,
490
+ timestamp=datetime.utcnow().isoformat()
491
+ )
492
+
493
+
494
+ @app.post("/predict", response_model=PredictResponse)
495
+ async def predict(request: PredictRequest):
496
+ """
497
+ 预测 BTC 价格走势
498
+
499
+ 输入至少 100 条历史 OHLCV 数据,返回未来价格预测。
500
+ """
501
+ if not predictor.loaded:
502
+ raise HTTPException(status_code=503, detail="Model not loaded yet")
503
+
504
+ if len(request.data) < 100:
505
+ raise HTTPException(status_code=400, detail="At least 100 data points required")
506
+
507
+ try:
508
+ # 转换数据
509
+ records = []
510
+ for d in request.data:
511
+ try:
512
+ # 处理时间戳
513
+ if d.timestamp.isdigit():
514
+ ts = pd.Timestamp(int(d.timestamp), unit='ms')
515
+ else:
516
+ ts = pd.Timestamp(d.timestamp)
517
+
518
+ records.append({
519
+ 'timestamp': ts,
520
+ 'open': d.open,
521
+ 'high': d.high,
522
+ 'low': d.low,
523
+ 'close': d.close,
524
+ 'volume': d.volume,
525
+ 'amount': d.amount if d.amount else d.volume * d.close
526
+ })
527
+ except Exception as e:
528
+ raise HTTPException(status_code=400, detail=f"Invalid data format: {e}")
529
+
530
+ df = pd.DataFrame(records)
531
+ df = df.sort_values('timestamp').reset_index(drop=True)
532
+
533
+ # 执行预测
534
+ result = predictor.predict(
535
+ df,
536
+ pred_len=request.pred_len,
537
+ n_paths=request.n_paths,
538
+ T=request.temperature,
539
+ top_p=request.top_p
540
+ )
541
+
542
+ return PredictResponse(**result)
543
+
544
+ except Exception as e:
545
+ logger.error(f"Prediction error: {e}")
546
+ raise HTTPException(status_code=500, detail=str(e))
547
+
548
+
549
+ @app.post("/signal", response_model=SignalResponse)
550
+ async def get_signal(request: SignalRequest):
551
+ """
552
+ 生成交易信号
553
+
554
+ 基于历史数据和策略参数,生成买入/卖出/持有信号。
555
+ """
556
+ if not predictor.loaded:
557
+ raise HTTPException(status_code=503, detail="Model not loaded yet")
558
+
559
+ if len(request.data) < 100:
560
+ raise HTTPException(status_code=400, detail="At least 100 data points required")
561
+
562
+ try:
563
+ # 转换数据
564
+ records = []
565
+ for d in request.data:
566
+ try:
567
+ if d.timestamp.isdigit():
568
+ ts = pd.Timestamp(int(d.timestamp), unit='ms')
569
+ else:
570
+ ts = pd.Timestamp(d.timestamp)
571
+
572
+ records.append({
573
+ 'timestamp': ts,
574
+ 'open': d.open,
575
+ 'high': d.high,
576
+ 'low': d.low,
577
+ 'close': d.close,
578
+ 'volume': d.volume,
579
+ 'amount': d.amount if d.amount else d.volume * d.close
580
+ })
581
+ except Exception as e:
582
+ raise HTTPException(status_code=400, detail=f"Invalid data format: {e}")
583
+
584
+ df = pd.DataFrame(records)
585
+ df = df.sort_values('timestamp').reset_index(drop=True)
586
+
587
+ # 生成信号
588
+ result = predictor.generate_signal(
589
+ df,
590
+ buy_threshold=request.buy_threshold,
591
+ sell_threshold=request.sell_threshold,
592
+ stop_loss=request.stop_loss,
593
+ take_profit=request.take_profit,
594
+ n_paths=request.n_paths
595
+ )
596
+
597
+ return SignalResponse(**result)
598
+
599
+ except Exception as e:
600
+ logger.error(f"Signal generation error: {e}")
601
+ raise HTTPException(status_code=500, detail=str(e))
602
+
603
+
604
+ # HuggingFace Spaces 入口
605
+ if __name__ == "__main__":
606
+ import uvicorn
607
+ uvicorn.run(app, host="0.0.0.0", port=7860)
client.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Kronos BTC Prediction API Client SDK
3
+
4
+ 用于连接 Kronos BTC 预测 API 的 Python 客户端。
5
+
6
+ 使用示例:
7
+ from client import KronosClient
8
+
9
+ client = KronosClient("https://your-space.hf.space")
10
+
11
+ # 健康检查
12
+ health = client.health()
13
+
14
+ # 价格预测
15
+ prediction = client.predict(ohlcv_data, pred_len=24)
16
+
17
+ # 交易信号
18
+ signal = client.get_signal(ohlcv_data)
19
+ """
20
+
21
+ import time
22
+ from datetime import datetime
23
+ from typing import List, Dict, Any, Optional, Union
24
+ from dataclasses import dataclass
25
+ from enum import Enum
26
+
27
+ import httpx
28
+ import pandas as pd
29
+
30
+
31
+ class SignalType(str, Enum):
32
+ """交易信号类型"""
33
+ STRONG_BUY = "STRONG_BUY"
34
+ BUY = "BUY"
35
+ HOLD = "HOLD"
36
+ SELL = "SELL"
37
+ STRONG_SELL = "STRONG_SELL"
38
+
39
+
40
+ @dataclass
41
+ class OHLCVData:
42
+ """OHLCV K线数据"""
43
+ timestamp: str
44
+ open: float
45
+ high: float
46
+ low: float
47
+ close: float
48
+ volume: float
49
+ amount: Optional[float] = None
50
+
51
+ def to_dict(self) -> Dict[str, Any]:
52
+ return {
53
+ "timestamp": self.timestamp,
54
+ "open": self.open,
55
+ "high": self.high,
56
+ "low": self.low,
57
+ "close": self.close,
58
+ "volume": self.volume,
59
+ "amount": self.amount
60
+ }
61
+
62
+
63
+ @dataclass
64
+ class PredictResult:
65
+ """预测结果"""
66
+ current_price: float
67
+ mean_forecast: float
68
+ min_forecast: float
69
+ max_forecast: float
70
+ upside_probability: float
71
+ expected_return: float
72
+ volatility_amplification: float
73
+ confidence: float
74
+ forecast_prices: List[float]
75
+ timestamp: str
76
+
77
+ @classmethod
78
+ def from_dict(cls, data: Dict[str, Any]) -> "PredictResult":
79
+ return cls(**data)
80
+
81
+ def __repr__(self) -> str:
82
+ return (
83
+ f"PredictResult(\n"
84
+ f" current_price={self.current_price:.2f},\n"
85
+ f" mean_forecast={self.mean_forecast:.2f},\n"
86
+ f" upside_probability={self.upside_probability:.1%},\n"
87
+ f" expected_return={self.expected_return:.2%},\n"
88
+ f" confidence={self.confidence:.1%}\n"
89
+ f")"
90
+ )
91
+
92
+
93
+ @dataclass
94
+ class SignalResult:
95
+ """交易信号结果"""
96
+ signal: SignalType
97
+ confidence: float
98
+ current_price: float
99
+ target_price: float
100
+ stop_loss_price: float
101
+ take_profit_price: float
102
+ upside_probability: float
103
+ expected_return: float
104
+ suggested_position_size: float
105
+ reason: str
106
+ timestamp: str
107
+
108
+ @classmethod
109
+ def from_dict(cls, data: Dict[str, Any]) -> "SignalResult":
110
+ data["signal"] = SignalType(data["signal"])
111
+ return cls(**data)
112
+
113
+ def __repr__(self) -> str:
114
+ return (
115
+ f"SignalResult(\n"
116
+ f" signal={self.signal.value},\n"
117
+ f" confidence={self.confidence:.1%},\n"
118
+ f" current_price={self.current_price:.2f},\n"
119
+ f" target_price={self.target_price:.2f},\n"
120
+ f" stop_loss={self.stop_loss_price:.2f},\n"
121
+ f" take_profit={self.take_profit_price:.2f},\n"
122
+ f" position_size={self.suggested_position_size:.1%},\n"
123
+ f" reason='{self.reason}'\n"
124
+ f")"
125
+ )
126
+
127
+
128
+ @dataclass
129
+ class HealthResult:
130
+ """健康检查结果"""
131
+ status: str
132
+ model_loaded: bool
133
+ model_version: str
134
+ device: str
135
+ timestamp: str
136
+
137
+ @classmethod
138
+ def from_dict(cls, data: Dict[str, Any]) -> "HealthResult":
139
+ return cls(**data)
140
+
141
+
142
+ class KronosClientError(Exception):
143
+ """Kronos 客户端错误"""
144
+ pass
145
+
146
+
147
+ class KronosClient:
148
+ """
149
+ Kronos BTC 预测 API 客户端
150
+
151
+ Args:
152
+ base_url: API 服务地址 (如 "https://your-space.hf.space")
153
+ timeout: 请求超时时间 (秒)
154
+ max_retries: 最大重试次数
155
+
156
+ Examples:
157
+ >>> client = KronosClient("https://your-space.hf.space")
158
+ >>> health = client.health()
159
+ >>> print(f"Status: {health.status}")
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ base_url: str,
165
+ timeout: float = 60.0,
166
+ max_retries: int = 3
167
+ ):
168
+ self.base_url = base_url.rstrip("/")
169
+ self.timeout = timeout
170
+ self.max_retries = max_retries
171
+ self._client = httpx.Client(timeout=timeout)
172
+
173
+ def __enter__(self):
174
+ return self
175
+
176
+ def __exit__(self, *args):
177
+ self.close()
178
+
179
+ def close(self):
180
+ """关闭客户端"""
181
+ self._client.close()
182
+
183
+ def _request(
184
+ self,
185
+ method: str,
186
+ endpoint: str,
187
+ json: Optional[Dict] = None,
188
+ retry_count: int = 0
189
+ ) -> Dict[str, Any]:
190
+ """发送 HTTP 请求"""
191
+ url = f"{self.base_url}{endpoint}"
192
+
193
+ try:
194
+ response = self._client.request(method, url, json=json)
195
+
196
+ if response.status_code == 503:
197
+ # 模型未加载,等待重试
198
+ if retry_count < self.max_retries:
199
+ time.sleep(5)
200
+ return self._request(method, endpoint, json, retry_count + 1)
201
+ raise KronosClientError("Model not loaded after retries")
202
+
203
+ response.raise_for_status()
204
+ return response.json()
205
+
206
+ except httpx.ConnectError as e:
207
+ raise KronosClientError(f"Connection failed: {e}")
208
+ except httpx.TimeoutException as e:
209
+ raise KronosClientError(f"Request timeout: {e}")
210
+ except httpx.HTTPStatusError as e:
211
+ raise KronosClientError(f"HTTP error {e.response.status_code}: {e.response.text}")
212
+
213
+ def health(self) -> HealthResult:
214
+ """
215
+ 健康检查
216
+
217
+ Returns:
218
+ HealthResult: 健康状态
219
+ """
220
+ data = self._request("GET", "/health")
221
+ return HealthResult.from_dict(data)
222
+
223
+ def predict(
224
+ self,
225
+ data: Union[List[Dict], List[OHLCVData], pd.DataFrame],
226
+ pred_len: int = 24,
227
+ n_paths: int = 30,
228
+ temperature: float = 1.0,
229
+ top_p: float = 0.9
230
+ ) -> PredictResult:
231
+ """
232
+ 预测 BTC 价格走势
233
+
234
+ Args:
235
+ data: OHLCV 数据 (至少 100 条)
236
+ - List[Dict]: 字典列表
237
+ - List[OHLCVData]: OHLCVData 对象列表
238
+ - pd.DataFrame: DataFrame (需包含 timestamp, open, high, low, close, volume 列)
239
+ pred_len: 预测长度 (1-72 小时)
240
+ n_paths: Monte Carlo 路径数 (10-100)
241
+ temperature: 采样温度 (0.1-2.0)
242
+ top_p: Top-p 采样 (0.5-1.0)
243
+
244
+ Returns:
245
+ PredictResult: 预测结果
246
+
247
+ Examples:
248
+ >>> result = client.predict(df, pred_len=24)
249
+ >>> print(f"上涨概率: {result.upside_probability:.1%}")
250
+ """
251
+ ohlcv_list = self._convert_data(data)
252
+
253
+ if len(ohlcv_list) < 100:
254
+ raise KronosClientError(f"At least 100 data points required, got {len(ohlcv_list)}")
255
+
256
+ request_data = {
257
+ "data": ohlcv_list,
258
+ "pred_len": pred_len,
259
+ "n_paths": n_paths,
260
+ "temperature": temperature,
261
+ "top_p": top_p
262
+ }
263
+
264
+ response = self._request("POST", "/predict", json=request_data)
265
+ return PredictResult.from_dict(response)
266
+
267
+ def get_signal(
268
+ self,
269
+ data: Union[List[Dict], List[OHLCVData], pd.DataFrame],
270
+ buy_threshold: float = 0.58,
271
+ sell_threshold: float = 0.42,
272
+ stop_loss: float = 0.03,
273
+ take_profit: float = 0.08,
274
+ n_paths: int = 30
275
+ ) -> SignalResult:
276
+ """
277
+ 获取交易信号
278
+
279
+ Args:
280
+ data: OHLCV 数据 (至少 100 条)
281
+ buy_threshold: 买入阈值 (0.5-0.9)
282
+ sell_threshold: 卖出阈值 (0.1-0.5)
283
+ stop_loss: 止损比例 (0.01-0.1)
284
+ take_profit: 止盈比例 (0.02-0.2)
285
+ n_paths: Monte Carlo 路径数 (10-100)
286
+
287
+ Returns:
288
+ SignalResult: 交易信号
289
+
290
+ Examples:
291
+ >>> signal = client.get_signal(df)
292
+ >>> if signal.signal == SignalType.BUY:
293
+ ... print(f"买入! 目标价: {signal.target_price:.2f}")
294
+ """
295
+ ohlcv_list = self._convert_data(data)
296
+
297
+ if len(ohlcv_list) < 100:
298
+ raise KronosClientError(f"At least 100 data points required, got {len(ohlcv_list)}")
299
+
300
+ request_data = {
301
+ "data": ohlcv_list,
302
+ "buy_threshold": buy_threshold,
303
+ "sell_threshold": sell_threshold,
304
+ "stop_loss": stop_loss,
305
+ "take_profit": take_profit,
306
+ "n_paths": n_paths
307
+ }
308
+
309
+ response = self._request("POST", "/signal", json=request_data)
310
+ return SignalResult.from_dict(response)
311
+
312
+ def _convert_data(
313
+ self,
314
+ data: Union[List[Dict], List[OHLCVData], pd.DataFrame]
315
+ ) -> List[Dict[str, Any]]:
316
+ """转换数据格式"""
317
+ if isinstance(data, pd.DataFrame):
318
+ return self._dataframe_to_list(data)
319
+ elif isinstance(data, list):
320
+ if len(data) == 0:
321
+ return []
322
+ if isinstance(data[0], OHLCVData):
323
+ return [d.to_dict() for d in data]
324
+ elif isinstance(data[0], dict):
325
+ return data
326
+
327
+ raise KronosClientError(f"Unsupported data type: {type(data)}")
328
+
329
+ def _dataframe_to_list(self, df: pd.DataFrame) -> List[Dict[str, Any]]:
330
+ """将 DataFrame 转换为列表"""
331
+ required_cols = ["open", "high", "low", "close", "volume"]
332
+ for col in required_cols:
333
+ if col not in df.columns:
334
+ raise KronosClientError(f"Missing required column: {col}")
335
+
336
+ result = []
337
+ for _, row in df.iterrows():
338
+ # 处理时间戳
339
+ if "timestamp" in df.columns:
340
+ ts = row["timestamp"]
341
+ if isinstance(ts, pd.Timestamp):
342
+ ts = ts.isoformat()
343
+ elif isinstance(ts, datetime):
344
+ ts = ts.isoformat()
345
+ else:
346
+ ts = str(ts)
347
+ else:
348
+ ts = datetime.utcnow().isoformat()
349
+
350
+ result.append({
351
+ "timestamp": ts,
352
+ "open": float(row["open"]),
353
+ "high": float(row["high"]),
354
+ "low": float(row["low"]),
355
+ "close": float(row["close"]),
356
+ "volume": float(row["volume"]),
357
+ "amount": float(row["amount"]) if "amount" in df.columns else None
358
+ })
359
+
360
+ return result
361
+
362
+
363
+ class AsyncKronosClient:
364
+ """
365
+ 异步 Kronos BTC 预测 API 客户端
366
+
367
+ 用于异步场景 (如 asyncio 应用)。
368
+
369
+ Examples:
370
+ >>> async with AsyncKronosClient("https://your-space.hf.space") as client:
371
+ ... health = await client.health()
372
+ ... prediction = await client.predict(df)
373
+ """
374
+
375
+ def __init__(
376
+ self,
377
+ base_url: str,
378
+ timeout: float = 60.0,
379
+ max_retries: int = 3
380
+ ):
381
+ self.base_url = base_url.rstrip("/")
382
+ self.timeout = timeout
383
+ self.max_retries = max_retries
384
+ self._client: Optional[httpx.AsyncClient] = None
385
+
386
+ async def __aenter__(self):
387
+ self._client = httpx.AsyncClient(timeout=self.timeout)
388
+ return self
389
+
390
+ async def __aexit__(self, *args):
391
+ await self.close()
392
+
393
+ async def close(self):
394
+ """关闭客户端"""
395
+ if self._client:
396
+ await self._client.aclose()
397
+ self._client = None
398
+
399
+ async def _request(
400
+ self,
401
+ method: str,
402
+ endpoint: str,
403
+ json: Optional[Dict] = None,
404
+ retry_count: int = 0
405
+ ) -> Dict[str, Any]:
406
+ """发送 HTTP 请求"""
407
+ if not self._client:
408
+ raise KronosClientError("Client not initialized. Use 'async with' context.")
409
+
410
+ url = f"{self.base_url}{endpoint}"
411
+
412
+ try:
413
+ response = await self._client.request(method, url, json=json)
414
+
415
+ if response.status_code == 503:
416
+ if retry_count < self.max_retries:
417
+ import asyncio
418
+ await asyncio.sleep(5)
419
+ return await self._request(method, endpoint, json, retry_count + 1)
420
+ raise KronosClientError("Model not loaded after retries")
421
+
422
+ response.raise_for_status()
423
+ return response.json()
424
+
425
+ except httpx.ConnectError as e:
426
+ raise KronosClientError(f"Connection failed: {e}")
427
+ except httpx.TimeoutException as e:
428
+ raise KronosClientError(f"Request timeout: {e}")
429
+ except httpx.HTTPStatusError as e:
430
+ raise KronosClientError(f"HTTP error {e.response.status_code}: {e.response.text}")
431
+
432
+ async def health(self) -> HealthResult:
433
+ """健康检查"""
434
+ data = await self._request("GET", "/health")
435
+ return HealthResult.from_dict(data)
436
+
437
+ async def predict(
438
+ self,
439
+ data: Union[List[Dict], List[OHLCVData], pd.DataFrame],
440
+ pred_len: int = 24,
441
+ n_paths: int = 30,
442
+ temperature: float = 1.0,
443
+ top_p: float = 0.9
444
+ ) -> PredictResult:
445
+ """预测 BTC 价格走势"""
446
+ ohlcv_list = self._convert_data(data)
447
+
448
+ if len(ohlcv_list) < 100:
449
+ raise KronosClientError(f"At least 100 data points required")
450
+
451
+ request_data = {
452
+ "data": ohlcv_list,
453
+ "pred_len": pred_len,
454
+ "n_paths": n_paths,
455
+ "temperature": temperature,
456
+ "top_p": top_p
457
+ }
458
+
459
+ response = await self._request("POST", "/predict", json=request_data)
460
+ return PredictResult.from_dict(response)
461
+
462
+ async def get_signal(
463
+ self,
464
+ data: Union[List[Dict], List[OHLCVData], pd.DataFrame],
465
+ buy_threshold: float = 0.58,
466
+ sell_threshold: float = 0.42,
467
+ stop_loss: float = 0.03,
468
+ take_profit: float = 0.08,
469
+ n_paths: int = 30
470
+ ) -> SignalResult:
471
+ """获取交易信号"""
472
+ ohlcv_list = self._convert_data(data)
473
+
474
+ if len(ohlcv_list) < 100:
475
+ raise KronosClientError(f"At least 100 data points required")
476
+
477
+ request_data = {
478
+ "data": ohlcv_list,
479
+ "buy_threshold": buy_threshold,
480
+ "sell_threshold": sell_threshold,
481
+ "stop_loss": stop_loss,
482
+ "take_profit": take_profit,
483
+ "n_paths": n_paths
484
+ }
485
+
486
+ response = await self._request("POST", "/signal", json=request_data)
487
+ return SignalResult.from_dict(response)
488
+
489
+ def _convert_data(
490
+ self,
491
+ data: Union[List[Dict], List[OHLCVData], pd.DataFrame]
492
+ ) -> List[Dict[str, Any]]:
493
+ """转换数据格式"""
494
+ if isinstance(data, pd.DataFrame):
495
+ return self._dataframe_to_list(data)
496
+ elif isinstance(data, list):
497
+ if len(data) == 0:
498
+ return []
499
+ if isinstance(data[0], OHLCVData):
500
+ return [d.to_dict() for d in data]
501
+ elif isinstance(data[0], dict):
502
+ return data
503
+
504
+ raise KronosClientError(f"Unsupported data type: {type(data)}")
505
+
506
+ def _dataframe_to_list(self, df: pd.DataFrame) -> List[Dict[str, Any]]:
507
+ """将 DataFrame 转换为列表"""
508
+ required_cols = ["open", "high", "low", "close", "volume"]
509
+ for col in required_cols:
510
+ if col not in df.columns:
511
+ raise KronosClientError(f"Missing required column: {col}")
512
+
513
+ result = []
514
+ for _, row in df.iterrows():
515
+ if "timestamp" in df.columns:
516
+ ts = row["timestamp"]
517
+ if isinstance(ts, pd.Timestamp):
518
+ ts = ts.isoformat()
519
+ elif isinstance(ts, datetime):
520
+ ts = ts.isoformat()
521
+ else:
522
+ ts = str(ts)
523
+ else:
524
+ ts = datetime.utcnow().isoformat()
525
+
526
+ result.append({
527
+ "timestamp": ts,
528
+ "open": float(row["open"]),
529
+ "high": float(row["high"]),
530
+ "low": float(row["low"]),
531
+ "close": float(row["close"]),
532
+ "volume": float(row["volume"]),
533
+ "amount": float(row["amount"]) if "amount" in df.columns else None
534
+ })
535
+
536
+ return result
537
+
538
+
539
+ # ==================== 使用示例 ====================
540
+
541
+ if __name__ == "__main__":
542
+ import asyncio
543
+
544
+ # 示例数据 (实际使用时替换为真实数据)
545
+ def create_sample_data() -> pd.DataFrame:
546
+ """创建示例数据"""
547
+ import numpy as np
548
+
549
+ np.random.seed(42)
550
+ n = 120
551
+
552
+ dates = pd.date_range(start="2024-01-01", periods=n, freq="1h")
553
+ base_price = 42000
554
+
555
+ prices = [base_price]
556
+ for i in range(1, n):
557
+ change = np.random.randn() * 100
558
+ prices.append(prices[-1] + change)
559
+
560
+ df = pd.DataFrame({
561
+ "timestamp": dates,
562
+ "open": prices,
563
+ "high": [p + np.random.rand() * 50 for p in prices],
564
+ "low": [p - np.random.rand() * 50 for p in prices],
565
+ "close": [p + np.random.randn() * 20 for p in prices],
566
+ "volume": np.random.rand(n) * 1000 + 100
567
+ })
568
+
569
+ return df
570
+
571
+ # 同步示例
572
+ def sync_example():
573
+ print("=== 同步客户端示例 ===")
574
+
575
+ # 创建客户端
576
+ client = KronosClient("http://localhost:7860")
577
+
578
+ try:
579
+ # 健康检查
580
+ health = client.health()
581
+ print(f"Status: {health.status}")
582
+ print(f"Model loaded: {health.model_loaded}")
583
+
584
+ # 创建示例数据
585
+ df = create_sample_data()
586
+ print(f"\n数据点数: {len(df)}")
587
+
588
+ # 预测
589
+ prediction = client.predict(df, pred_len=24)
590
+ print(f"\n预测结果:")
591
+ print(prediction)
592
+
593
+ # 交易信号
594
+ signal = client.get_signal(df)
595
+ print(f"\n交易信号:")
596
+ print(signal)
597
+
598
+ except KronosClientError as e:
599
+ print(f"Error: {e}")
600
+ finally:
601
+ client.close()
602
+
603
+ # 异步示例
604
+ async def async_example():
605
+ print("\n=== 异步客户端示例 ===")
606
+
607
+ async with AsyncKronosClient("http://localhost:7860") as client:
608
+ try:
609
+ # 健康检查
610
+ health = await client.health()
611
+ print(f"Status: {health.status}")
612
+
613
+ # 创建示例数据
614
+ df = create_sample_data()
615
+
616
+ # 并发预测和信号
617
+ prediction, signal = await asyncio.gather(
618
+ client.predict(df),
619
+ client.get_signal(df)
620
+ )
621
+
622
+ print(f"\n预测结果:")
623
+ print(prediction)
624
+ print(f"\n交易信号:")
625
+ print(signal)
626
+
627
+ except KronosClientError as e:
628
+ print(f"Error: {e}")
629
+
630
+ # 运行示例
631
+ print("Kronos Client SDK 示例\n")
632
+ print("注意: 请确保 API 服务已启动 (python app.py)\n")
633
+
634
+ # 仅打印帮助信息,不实际运行
635
+ print("同步使用:")
636
+ print(" client = KronosClient('http://localhost:7860')")
637
+ print(" prediction = client.predict(df)")
638
+ print(" signal = client.get_signal(df)")
639
+ print()
640
+ print("异步使用:")
641
+ print(" async with AsyncKronosClient('http://localhost:7860') as client:")
642
+ print(" prediction = await client.predict(df)")
643
+ print(" signal = await client.get_signal(df)")
model/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .kronos import KronosTokenizer, Kronos, calc_time_stamps
2
+
3
+ __all__ = ['KronosTokenizer', 'Kronos', 'calc_time_stamps']
model/kronos.py ADDED
@@ -0,0 +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.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 = top_k(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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
models/predictor/README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - model_hub_mixin
4
+ - pytorch_model_hub_mixin
5
+ ---
6
+
7
+ This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration:
8
+ - Code: [More Information Needed]
9
+ - Paper: [More Information Needed]
10
+ - Docs: [More Information Needed]
models/predictor/config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attn_dropout_p": 0.0,
3
+ "d_model": 256,
4
+ "ff_dim": 512,
5
+ "ffn_dropout_p": 0.2,
6
+ "learn_te": true,
7
+ "n_heads": 4,
8
+ "n_layers": 4,
9
+ "resid_dropout_p": 0.2,
10
+ "s1_bits": 10,
11
+ "s2_bits": 10,
12
+ "token_dropout_p": 0.0
13
+ }
models/predictor/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fb3d6ca23cb183f692e232ba427c801f1b706d862ae3226241c9a6ba86796fc
3
+ size 16440776
models/tokenizer/README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - model_hub_mixin
4
+ - pytorch_model_hub_mixin
5
+ ---
6
+
7
+ This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration:
8
+ - Code: [More Information Needed]
9
+ - Paper: [More Information Needed]
10
+ - Docs: [More Information Needed]
models/tokenizer/config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attn_dropout_p": 0.0,
3
+ "beta": 0.05,
4
+ "d_in": 6,
5
+ "d_model": 256,
6
+ "ff_dim": 512,
7
+ "ffn_dropout_p": 0.0,
8
+ "gamma": 1.1,
9
+ "gamma0": 1.0,
10
+ "group_size": 5,
11
+ "n_dec_layers": 4,
12
+ "n_enc_layers": 4,
13
+ "n_heads": 4,
14
+ "resid_dropout_p": 0.0,
15
+ "s1_bits": 10,
16
+ "s2_bits": 10,
17
+ "zeta": 0.05
18
+ }
models/tokenizer/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f559eb686c32b87b12b63bdadcdf069e53690f05c31b4c3bd810ba3176229f6a
3
+ size 15842376
requirements.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kronos BTC Prediction API - Dependencies
2
+ # Optimized for HuggingFace Spaces (CPU)
3
+
4
+ # Core
5
+ fastapi==0.104.1
6
+ uvicorn[standard]==0.24.0
7
+ pydantic==2.5.2
8
+
9
+ # ML/DL
10
+ torch==2.1.0
11
+ numpy>=1.24.0,<2.0.0
12
+ pandas>=2.0.0
13
+
14
+ # Model loading
15
+ safetensors>=0.4.0
16
+ huggingface-hub>=0.19.0
17
+
18
+ # HTTP client (for client SDK)
19
+ httpx>=0.25.0
20
+ aiohttp>=3.9.0
21
+
22
+ # Utilities
23
+ python-dateutil>=2.8.0