Spaces:
Running
Running
Commit
·
64cd325
1
Parent(s):
e31fc80
Deploy Kronos API service
Browse files- API.md +197 -0
- Dockerfile +38 -0
- README.md +57 -12
- __pycache__/app.cpython-312.pyc +0 -0
- app.py +251 -0
- docker-compose.yml +20 -0
- model/__init__.py +16 -0
- model/__pycache__/__init__.cpython-312.pyc +0 -0
- model/__pycache__/kronos.cpython-312.pyc +0 -0
- model/__pycache__/module.cpython-312.pyc +0 -0
- model/kronos.py +622 -0
- model/module.py +574 -0
- payload.json +1 -0
- requirements.txt +6 -0
- test_data.json +17 -0
API.md
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kronos API 文档
|
| 2 |
+
|
| 3 |
+
本文档提供有关 Kronos 预测服务的 API 端点的详细信息。
|
| 4 |
+
|
| 5 |
+
## 基础 URL
|
| 6 |
+
|
| 7 |
+
基础 URL 将取决于您的部署环境。
|
| 8 |
+
- **本地 Docker**: `http://localhost:7860`
|
| 9 |
+
- **Hugging Face Spaces**: `https://<your-space-name>.hf.space`
|
| 10 |
+
|
| 11 |
+
## 身份验证
|
| 12 |
+
|
| 13 |
+
所有端点(`/api/model-status` 除外)都受到保护,需要 API 密钥。密钥必须在请求的 `Authorization` 头中提供。
|
| 14 |
+
|
| 15 |
+
- **Header**: `Authorization: Bearer <YOUR_API_KEY>`
|
| 16 |
+
|
| 17 |
+
未能提供有效密钥将导致 `401 Unauthorized` 错误。
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## 端点
|
| 22 |
+
|
| 23 |
+
### 1. 获取可用模型列表
|
| 24 |
+
|
| 25 |
+
获取服务端所有可用模型的详细信息。
|
| 26 |
+
|
| 27 |
+
- **URL**: `/api/available-models`
|
| 28 |
+
- **方法**: `GET`
|
| 29 |
+
- **身份验证**: 不需要。
|
| 30 |
+
|
| 31 |
+
**成功响应 (200 OK)**
|
| 32 |
+
```json
|
| 33 |
+
{
|
| 34 |
+
"kronos-mini": {
|
| 35 |
+
"name": "Kronos-mini",
|
| 36 |
+
"model_id": "NeoQuasar/Kronos-mini",
|
| 37 |
+
"tokenizer_id": "NeoQuasar/Kronos-Tokenizer-2k",
|
| 38 |
+
"context_length": 2048,
|
| 39 |
+
"params": "4.1M",
|
| 40 |
+
"description": "Lightweight model, suitable for fast prediction"
|
| 41 |
+
},
|
| 42 |
+
"kronos-small": {
|
| 43 |
+
"name": "Kronos-small",
|
| 44 |
+
"model_id": "NeoQuasar/Kronos-small",
|
| 45 |
+
"tokenizer_id": "NeoQuasar/Kronos-Tokenizer-base",
|
| 46 |
+
"context_length": 512,
|
| 47 |
+
"params": "24.7M",
|
| 48 |
+
"description": "Small model, balanced performance and speed"
|
| 49 |
+
},
|
| 50 |
+
"kronos-base": {
|
| 51 |
+
"name": "Kronos-base",
|
| 52 |
+
"model_id": "NeoQuasar/Kronos-base",
|
| 53 |
+
"tokenizer_id": "NeoQuasar/Kronos-Tokenizer-base",
|
| 54 |
+
"context_length": 512,
|
| 55 |
+
"params": "102.3M",
|
| 56 |
+
"description": "Base model, provides better prediction quality"
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
### 2. 获取当前模型状态
|
| 62 |
+
|
| 63 |
+
检查当前是否有模型被加载到内存中,并返回其详细信息。
|
| 64 |
+
|
| 65 |
+
- **URL**: `/api/model-status`
|
| 66 |
+
- **方法**: `GET`
|
| 67 |
+
- **身份验证**: 不需要。
|
| 68 |
+
|
| 69 |
+
**成功响应 (200 OK)**
|
| 70 |
+
```json
|
| 71 |
+
{
|
| 72 |
+
"status": "loaded",
|
| 73 |
+
"model_key": "kronos-base",
|
| 74 |
+
"model_info": {
|
| 75 |
+
"name": "Kronos-base",
|
| 76 |
+
"model_id": "NeoQuasar/Kronos-base",
|
| 77 |
+
"tokenizer_id": "NeoQuasar/Kronos-Tokenizer-base",
|
| 78 |
+
"context_length": 512,
|
| 79 |
+
"params": "102.3M",
|
| 80 |
+
"description": "Base model, provides better prediction quality"
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
**模型未加载响应 (200 OK)**
|
| 86 |
+
```json
|
| 87 |
+
{
|
| 88 |
+
"status": "not_loaded"
|
| 89 |
+
}
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
### 3. 加载模型
|
| 93 |
+
|
| 94 |
+
手动将一个指定的模型加载到内存中。
|
| 95 |
+
|
| 96 |
+
- **URL**: `/api/load-model`
|
| 97 |
+
- **方法**: `POST`
|
| 98 |
+
- **身份验证**: 需要。
|
| 99 |
+
|
| 100 |
+
**请求体 (Request Body)**
|
| 101 |
+
```json
|
| 102 |
+
{
|
| 103 |
+
"model_key": "kronos-base",
|
| 104 |
+
"force_reload": false
|
| 105 |
+
}
|
| 106 |
+
```
|
| 107 |
+
- `model_key` (可选): 模型的键名。默认为 `kronos-base`。**该值必须是 `/api/available-models` 端点返回的键之一** (例如, `"kronos-mini"`)。
|
| 108 |
+
- `force_reload` (可选): 如果为 `true`,即使请求的模型已在内存中,也会强制重新加载。默认为 `false`。
|
| 109 |
+
|
| 110 |
+
**成功响应 (200 OK)**
|
| 111 |
+
```json
|
| 112 |
+
{
|
| 113 |
+
"status": "Model 'Kronos-base' loaded successfully.",
|
| 114 |
+
"model_info": {
|
| 115 |
+
"name": "Kronos-base",
|
| 116 |
+
"model_id": "NeoQuasar/Kronos-base",
|
| 117 |
+
"tokenizer_id": "NeoQuasar/Kronos-Tokenizer-base",
|
| 118 |
+
"context_length": 512,
|
| 119 |
+
"params": "102.3M",
|
| 120 |
+
"description": "Base model, provides better prediction quality"
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
**错误响应 (400 Bad Request)**
|
| 126 |
+
如果提供了无效的 `model_key`。
|
| 127 |
+
```json
|
| 128 |
+
{
|
| 129 |
+
"error": "Invalid model_key. Please choose from the allowed models.",
|
| 130 |
+
"allowed_models": [
|
| 131 |
+
"kronos-mini",
|
| 132 |
+
"kronos-small",
|
| 133 |
+
"kronos-base"
|
| 134 |
+
]
|
| 135 |
+
}
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
### 4. 获取预测结果
|
| 139 |
+
|
| 140 |
+
提交 K 线数据并接收预测结果。
|
| 141 |
+
|
| 142 |
+
- **URL**: `/api/predict_from_data`
|
| 143 |
+
- **方法**: `POST`
|
| 144 |
+
- **身份验证**: 需要。
|
| 145 |
+
|
| 146 |
+
**请求体 (Request Body)**
|
| 147 |
+
```json
|
| 148 |
+
{
|
| 149 |
+
"k_lines": [
|
| 150 |
+
[1711324800000, "18.545", "19.514", "18.385", "19.395", "2080487", ...],
|
| 151 |
+
[1711411200000, "19.397", "20.759", "19.356", "20.032", "3020519", ...],
|
| 152 |
+
[1711497600000, "20.030", "20.211", "19.011", "19.303", "2351359", ...]
|
| 153 |
+
],
|
| 154 |
+
"prediction_params": {
|
| 155 |
+
"pred_len": 120
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
```
|
| 159 |
+
- `k_lines` (必需): 代表 K 线数据的数组的数组。格式应与币安 API 标准响应匹配(时间戳, 开盘价, 最高价, 最低价, 收盘价, 成交量, ...)。模型仅使用前 6 列。
|
| 160 |
+
- `prediction_params` (可选): 用于预测参数的字典。
|
| 161 |
+
- `pred_len` (可选): 要预测的未来时间步数。默认为 `120`。
|
| 162 |
+
|
| 163 |
+
**成功响应 (200 OK)**
|
| 164 |
+
```json
|
| 165 |
+
{
|
| 166 |
+
"success": true,
|
| 167 |
+
"prediction_params": {
|
| 168 |
+
"pred_len": 120
|
| 169 |
+
},
|
| 170 |
+
"prediction_results": [
|
| 171 |
+
{
|
| 172 |
+
"timestamp": "2024-07-01T00:00:00",
|
| 173 |
+
"open": 150.1,
|
| 174 |
+
"high": 152.3,
|
| 175 |
+
"low": 149.8,
|
| 176 |
+
"close": 151.5,
|
| 177 |
+
"volume": 100000.0
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"timestamp": "2024-07-01T01:00:00",
|
| 181 |
+
"open": 151.5,
|
| 182 |
+
"high": 153.0,
|
| 183 |
+
"low": 151.0,
|
| 184 |
+
"close": 152.8,
|
| 185 |
+
"volume": 120000.0
|
| 186 |
+
}
|
| 187 |
+
]
|
| 188 |
+
}
|
| 189 |
+
```
|
| 190 |
+
*(注意: `prediction_results` 是一个示例;实际值会有所不同。)*
|
| 191 |
+
|
| 192 |
+
**错误响应 (400 Bad Request)**
|
| 193 |
+
如果模型尚未加载。
|
| 194 |
+
```json
|
| 195 |
+
{
|
| 196 |
+
"error": "模型未加载。请先调用 /api/load-model。"
|
| 197 |
+
}
|
Dockerfile
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stage 1: Build stage with dependencies
|
| 2 |
+
FROM python:3.10-slim as builder
|
| 3 |
+
|
| 4 |
+
WORKDIR /app
|
| 5 |
+
|
| 6 |
+
# Install build dependencies
|
| 7 |
+
RUN pip install --upgrade pip
|
| 8 |
+
|
| 9 |
+
# Copy requirements first to leverage Docker cache
|
| 10 |
+
COPY requirements.txt .
|
| 11 |
+
|
| 12 |
+
# Install python dependencies
|
| 13 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
+
|
| 15 |
+
# ---
|
| 16 |
+
|
| 17 |
+
# Stage 2: Final stage
|
| 18 |
+
FROM python:3.10-slim
|
| 19 |
+
|
| 20 |
+
WORKDIR /app
|
| 21 |
+
|
| 22 |
+
# Create a non-root user
|
| 23 |
+
RUN useradd --create-home appuser
|
| 24 |
+
USER appuser
|
| 25 |
+
|
| 26 |
+
# Copy installed dependencies from builder stage
|
| 27 |
+
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
|
| 28 |
+
COPY --from=builder /usr/local/bin /usr/local/bin
|
| 29 |
+
|
| 30 |
+
# Copy the application code and model files
|
| 31 |
+
# Note: The Docker build context should be the parent directory of 'kronos-api-service'
|
| 32 |
+
COPY --chown=appuser:appuser ./kronos-api-service/ .
|
| 33 |
+
|
| 34 |
+
# Expose the port the app runs on
|
| 35 |
+
EXPOSE 7860
|
| 36 |
+
|
| 37 |
+
# Set the default command to run the app with Gunicorn
|
| 38 |
+
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "2", "app:app"]
|
README.md
CHANGED
|
@@ -1,12 +1,57 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kronos API 服务
|
| 2 |
+
|
| 3 |
+
本项目为 Kronos 金融预测模型提供了一个独立的、容器化的 API 服务。它经过优化,可部署在 Hugging Face Spaces 或任何其他支持 Docker 的云环境中。
|
| 4 |
+
|
| 5 |
+
## 功能特性
|
| 6 |
+
|
| 7 |
+
- **纯 API 服务**: 无前端界面,专注于性能和集成。
|
| 8 |
+
- **灵活的数据输入**: 通过 API 直接接受标准的 K 线数据格式(数组的数组)。
|
| 9 |
+
- **安全**: API 端点受持有者令牌(Bearer Token)认证保护。
|
| 10 |
+
- **容器化**: 使用 Docker 轻松部署和扩展。
|
| 11 |
+
|
| 12 |
+
## 开始使用
|
| 13 |
+
|
| 14 |
+
### 1. 本地开发与测试
|
| 15 |
+
|
| 16 |
+
您可以使用 Docker Compose 在本地运行此服务。
|
| 17 |
+
|
| 18 |
+
**先决条件**:
|
| 19 |
+
- 已安装 Docker 和 Docker Compose。
|
| 20 |
+
|
| 21 |
+
**步骤**:
|
| 22 |
+
1. 进入 `kronos-api-service` 目录:
|
| 23 |
+
```bash
|
| 24 |
+
cd kronos-api-service
|
| 25 |
+
```
|
| 26 |
+
2. 启动服务:
|
| 27 |
+
```bash
|
| 28 |
+
docker-compose up --build
|
| 29 |
+
```
|
| 30 |
+
服务将在 `http://localhost:7860` 上可用。用于本地测试的 API 密钥在 `docker-compose.yml` 文件中定义(默认为 `my-secret-local-key`)。
|
| 31 |
+
|
| 32 |
+
### 2. 部署到 Hugging Face Spaces
|
| 33 |
+
|
| 34 |
+
该服务旨在轻松部署到 Hugging Face Space。
|
| 35 |
+
|
| 36 |
+
**步骤**:
|
| 37 |
+
1. 在 Hugging Face 上创建一个新的 **Docker Space**。
|
| 38 |
+
2. 在您的 Space 设置中,进入 **Secrets** 并添加一个新的密钥:
|
| 39 |
+
- **名称**: `KRONOS_API_KEY`
|
| 40 |
+
- **值**: `your_super_secret_api_key` (请替换为您自己的强密钥)
|
| 41 |
+
3. 将 `kronos-api-service` 目录下的**所有内容**推送到您的 Space Git 仓库的根目录。您的 Space 仓库结构应如下所示:
|
| 42 |
+
```
|
| 43 |
+
.
|
| 44 |
+
├── app.py
|
| 45 |
+
├── Dockerfile
|
| 46 |
+
├── requirements.txt
|
| 47 |
+
├── model/
|
| 48 |
+
│ ├── __init__.py
|
| 49 |
+
│ ├── kronos.py
|
| 50 |
+
│ └── module.py
|
| 51 |
+
└── ... (此项目中的所有其他文件)
|
| 52 |
+
```
|
| 53 |
+
4. Hugging Face Spaces 将自动从您的 `Dockerfile` 构建镜像并启动服务。您的 API 将在 Space 提供的 URL 上线。
|
| 54 |
+
|
| 55 |
+
## API 使用方法
|
| 56 |
+
|
| 57 |
+
有关端点、请求/响应格式和示例的详细信息,请参阅详细的 **`API.md`** 文档。
|
__pycache__/app.cpython-312.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
app.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 8 |
+
from huggingface_hub import hf_hub_download
|
| 9 |
+
|
| 10 |
+
# Configure logging
|
| 11 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 12 |
+
|
| 13 |
+
# Add parent directory to sys.path to allow imports from 'model'
|
| 14 |
+
try:
|
| 15 |
+
from model.kronos import Kronos, KronosTokenizer, KronosPredictor
|
| 16 |
+
except ImportError as e:
|
| 17 |
+
logging.error(f"Could not import from model.kronos: {e}")
|
| 18 |
+
sys.exit(1)
|
| 19 |
+
|
| 20 |
+
# --- Globals ---
|
| 21 |
+
app = Flask(__name__)
|
| 22 |
+
predictor = None
|
| 23 |
+
model_name_global = "kronos-base" # Use key now
|
| 24 |
+
API_KEY = os.environ.get("KRONOS_API_KEY")
|
| 25 |
+
AVAILABLE_MODELS = {
|
| 26 |
+
'kronos-mini': {
|
| 27 |
+
'name': 'Kronos-mini',
|
| 28 |
+
'model_id': 'NeoQuasar/Kronos-mini',
|
| 29 |
+
'tokenizer_id': 'NeoQuasar/Kronos-Tokenizer-2k',
|
| 30 |
+
'context_length': 2048,
|
| 31 |
+
'params': '4.1M',
|
| 32 |
+
'description': 'Lightweight model, suitable for fast prediction'
|
| 33 |
+
},
|
| 34 |
+
'kronos-small': {
|
| 35 |
+
'name': 'Kronos-small',
|
| 36 |
+
'model_id': 'NeoQuasar/Kronos-small',
|
| 37 |
+
'tokenizer_id': 'NeoQuasar/Kronos-Tokenizer-base',
|
| 38 |
+
'context_length': 512,
|
| 39 |
+
'params': '24.7M',
|
| 40 |
+
'description': 'Small model, balanced performance and speed'
|
| 41 |
+
},
|
| 42 |
+
'kronos-base': {
|
| 43 |
+
'name': 'Kronos-base',
|
| 44 |
+
'model_id': 'NeoQuasar/Kronos-base',
|
| 45 |
+
'tokenizer_id': 'NeoQuasar/Kronos-Tokenizer-base',
|
| 46 |
+
'context_length': 512,
|
| 47 |
+
'params': '102.3M',
|
| 48 |
+
'description': 'Base model, provides better prediction quality'
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
# --- Helper Functions ---
|
| 53 |
+
|
| 54 |
+
def download_model_from_hf(model_name, local_dir="."):
|
| 55 |
+
"""Downloads a model from Hugging Face Hub."""
|
| 56 |
+
logging.info(f"Downloading model '{model_name}' from Hugging Face Hub...")
|
| 57 |
+
try:
|
| 58 |
+
hf_hub_download(repo_id=model_name, filename="config.json", local_dir=local_dir)
|
| 59 |
+
hf_hub_download(repo_id=model_name, filename="pytorch_model.bin", local_dir=local_dir)
|
| 60 |
+
logging.info("Model downloaded successfully.")
|
| 61 |
+
return True
|
| 62 |
+
except Exception as e:
|
| 63 |
+
logging.error(f"Failed to download model: {e}")
|
| 64 |
+
return False
|
| 65 |
+
|
| 66 |
+
# --- API Authentication ---
|
| 67 |
+
|
| 68 |
+
def require_api_key(f):
|
| 69 |
+
"""Decorator to protect routes with an API key."""
|
| 70 |
+
@wraps(f)
|
| 71 |
+
def decorated_function(*args, **kwargs):
|
| 72 |
+
# If KRONOS_API_KEY is not set on the server, skip authentication (for local/dev)
|
| 73 |
+
if not API_KEY:
|
| 74 |
+
logging.warning("API key not set. Skipping authentication.")
|
| 75 |
+
return f(*args, **kwargs)
|
| 76 |
+
|
| 77 |
+
auth_header = request.headers.get('Authorization')
|
| 78 |
+
if not auth_header or not auth_header.startswith('Bearer '):
|
| 79 |
+
return jsonify({'error': 'Authorization header is missing or invalid. Use Bearer token.'}), 401
|
| 80 |
+
|
| 81 |
+
token = auth_header.split(' ')[1]
|
| 82 |
+
if token != API_KEY:
|
| 83 |
+
return jsonify({'error': 'Invalid API Key.'}), 401
|
| 84 |
+
|
| 85 |
+
return f(*args, **kwargs)
|
| 86 |
+
return decorated_function
|
| 87 |
+
|
| 88 |
+
# --- API Endpoints ---
|
| 89 |
+
|
| 90 |
+
@app.route('/api/load-model', methods=['POST'])
|
| 91 |
+
@require_api_key
|
| 92 |
+
def load_model_endpoint():
|
| 93 |
+
"""Loads the prediction model into memory."""
|
| 94 |
+
global predictor, model_name_global
|
| 95 |
+
|
| 96 |
+
json_data = request.get_json()
|
| 97 |
+
model_key = json_data.get('model_key', model_name_global) # Changed to model_key
|
| 98 |
+
force_reload = json_data.get('force_reload', False)
|
| 99 |
+
|
| 100 |
+
# Validate if the requested model is in the allowed list
|
| 101 |
+
if model_key not in AVAILABLE_MODELS:
|
| 102 |
+
return jsonify({
|
| 103 |
+
'error': f"Invalid model_key. Please choose from the allowed models.",
|
| 104 |
+
'allowed_models': list(AVAILABLE_MODELS.keys())
|
| 105 |
+
}), 400
|
| 106 |
+
|
| 107 |
+
if predictor and not force_reload and model_name_global == model_key:
|
| 108 |
+
return jsonify({'status': 'Model already loaded.'})
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
model_config = AVAILABLE_MODELS[model_key]
|
| 112 |
+
model_id = model_config['model_id']
|
| 113 |
+
tokenizer_id = model_config['tokenizer_id']
|
| 114 |
+
|
| 115 |
+
logging.info(f"Attempting to load model: {model_id}")
|
| 116 |
+
logging.info(f"Attempting to load tokenizer: {tokenizer_id}")
|
| 117 |
+
|
| 118 |
+
# Determine device
|
| 119 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 120 |
+
logging.info(f"Using device: {device}")
|
| 121 |
+
|
| 122 |
+
# --- Proxy Setup ---
|
| 123 |
+
# Check for proxy settings in environment variables, similar to the webui fix
|
| 124 |
+
proxies = {
|
| 125 |
+
"http": os.environ.get("HTTP_PROXY"),
|
| 126 |
+
"https": os.environ.get("HTTPS_PROXY"),
|
| 127 |
+
}
|
| 128 |
+
# Filter out None values
|
| 129 |
+
proxies = {k: v for k, v in proxies.items() if v}
|
| 130 |
+
if proxies:
|
| 131 |
+
logging.info(f"Using proxies: {proxies}")
|
| 132 |
+
|
| 133 |
+
# Load model and tokenizer with proxy support
|
| 134 |
+
model = Kronos.from_pretrained(model_id, proxies=proxies if proxies else None)
|
| 135 |
+
tokenizer = KronosTokenizer.from_pretrained(tokenizer_id, proxies=proxies if proxies else None)
|
| 136 |
+
|
| 137 |
+
# Create the predictor wrapper
|
| 138 |
+
predictor = KronosPredictor(model, tokenizer, device=device)
|
| 139 |
+
model_name_global = model_key
|
| 140 |
+
|
| 141 |
+
logging.info(f"Model '{model_config['name']}' loaded successfully.")
|
| 142 |
+
return jsonify({
|
| 143 |
+
'status': f"Model '{model_config['name']}' loaded successfully.",
|
| 144 |
+
'model_info': model_config
|
| 145 |
+
})
|
| 146 |
+
except Exception as e:
|
| 147 |
+
logging.error(f"Error loading model: {e}")
|
| 148 |
+
return jsonify({'error': str(e)}), 500
|
| 149 |
+
|
| 150 |
+
@app.route('/api/model-status', methods=['GET'])
|
| 151 |
+
def model_status():
|
| 152 |
+
"""Checks if the model is loaded."""
|
| 153 |
+
if predictor:
|
| 154 |
+
return jsonify({
|
| 155 |
+
'status': 'loaded',
|
| 156 |
+
'model_key': model_name_global,
|
| 157 |
+
'model_info': AVAILABLE_MODELS.get(model_name_global)
|
| 158 |
+
})
|
| 159 |
+
else:
|
| 160 |
+
return jsonify({'status': 'not_loaded'})
|
| 161 |
+
|
| 162 |
+
@app.route('/api/available-models', methods=['GET'])
|
| 163 |
+
def get_available_models():
|
| 164 |
+
"""Returns the list of available models and their details."""
|
| 165 |
+
return jsonify(AVAILABLE_MODELS)
|
| 166 |
+
|
| 167 |
+
@app.route('/api/predict_from_data', methods=['POST'])
|
| 168 |
+
@require_api_key
|
| 169 |
+
def predict_from_data():
|
| 170 |
+
"""
|
| 171 |
+
Receives raw K-line data in the request body, makes a prediction,
|
| 172 |
+
and returns the results.
|
| 173 |
+
"""
|
| 174 |
+
if not predictor:
|
| 175 |
+
return jsonify({'error': 'Model not loaded. Please call /api/load-model first.'}), 400
|
| 176 |
+
|
| 177 |
+
data = request.get_json()
|
| 178 |
+
if not data or 'k_lines' not in data:
|
| 179 |
+
return jsonify({'error': 'Missing "k_lines" in request body.'}), 400
|
| 180 |
+
|
| 181 |
+
k_lines = data['k_lines']
|
| 182 |
+
params = data.get('prediction_params', {})
|
| 183 |
+
pred_len = params.get('pred_len', 120)
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
# Define column names based on standard Binance API format
|
| 187 |
+
# We only need the first 6 columns for the model
|
| 188 |
+
columns = [
|
| 189 |
+
'timestamp', 'open', 'high', 'low', 'close', 'volume',
|
| 190 |
+
'close_time', 'quote_asset_volume', 'number_of_trades',
|
| 191 |
+
'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
# Ensure we only use the first 12 columns if more are provided
|
| 195 |
+
k_lines_standardized = [line[:12] for line in k_lines]
|
| 196 |
+
|
| 197 |
+
df = pd.DataFrame(k_lines_standardized, columns=columns)
|
| 198 |
+
|
| 199 |
+
# --- Data Type Conversion ---
|
| 200 |
+
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
|
| 201 |
+
numeric_cols = ['open', 'high', 'low', 'close', 'volume']
|
| 202 |
+
for col in numeric_cols:
|
| 203 |
+
df[col] = pd.to_numeric(df[col])
|
| 204 |
+
|
| 205 |
+
# Keep only the necessary columns for the model
|
| 206 |
+
df_model_input = df[['timestamp', 'open', 'high', 'low', 'close', 'volume']]
|
| 207 |
+
|
| 208 |
+
logging.info(f"Making prediction with pred_len={pred_len} on data with shape {df_model_input.shape}")
|
| 209 |
+
|
| 210 |
+
# Make prediction
|
| 211 |
+
# --- Timestamp Generation for Predictor ---
|
| 212 |
+
# The predictor requires historical and future timestamps
|
| 213 |
+
x_timestamp = df_model_input['timestamp']
|
| 214 |
+
|
| 215 |
+
# Assuming the K-line interval is consistent, calculate the interval
|
| 216 |
+
# from the last two points to generate future timestamps.
|
| 217 |
+
if len(x_timestamp) > 1:
|
| 218 |
+
interval = x_timestamp.iloc[-1] - x_timestamp.iloc[-2]
|
| 219 |
+
else:
|
| 220 |
+
# If only one data point, assume a 1-minute interval as a fallback
|
| 221 |
+
interval = pd.Timedelta(minutes=1)
|
| 222 |
+
|
| 223 |
+
y_timestamp = pd.date_range(
|
| 224 |
+
start=x_timestamp.iloc[-1] + interval,
|
| 225 |
+
periods=pred_len,
|
| 226 |
+
freq=interval
|
| 227 |
+
)
|
| 228 |
+
# Convert DatetimeIndex to Series to prevent '.dt' accessor error inside the model
|
| 229 |
+
y_timestamp = pd.Series(y_timestamp, name='timestamp')
|
| 230 |
+
|
| 231 |
+
# Make prediction using the predictor wrapper
|
| 232 |
+
pred_df = predictor.predict(
|
| 233 |
+
df=df_model_input,
|
| 234 |
+
x_timestamp=x_timestamp,
|
| 235 |
+
y_timestamp=y_timestamp,
|
| 236 |
+
pred_len=pred_len,
|
| 237 |
+
verbose=False # Keep logs clean
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
# Format results for JSON response
|
| 241 |
+
prediction_results = pred_df.to_dict(orient='records')
|
| 242 |
+
|
| 243 |
+
return jsonify({
|
| 244 |
+
'success': True,
|
| 245 |
+
'prediction_params': {'pred_len': pred_len},
|
| 246 |
+
'prediction_results': prediction_results
|
| 247 |
+
})
|
| 248 |
+
|
| 249 |
+
except Exception as e:
|
| 250 |
+
logging.error(f"Prediction failed: {e}")
|
| 251 |
+
return jsonify({'error': f'An error occurred during prediction: {str(e)}'}), 500
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: '3.8'
|
| 2 |
+
|
| 3 |
+
services:
|
| 4 |
+
kronos-api:
|
| 5 |
+
build:
|
| 6 |
+
context: ..
|
| 7 |
+
dockerfile: ./kronos-api-service/Dockerfile
|
| 8 |
+
ports:
|
| 9 |
+
- "7860:7860"
|
| 10 |
+
environment:
|
| 11 |
+
# For local testing, you can set a fixed API key.
|
| 12 |
+
# For production (like Hugging Face Spaces), this should be set via secrets.
|
| 13 |
+
- KRONOS_API_KEY=my-secret-local-key
|
| 14 |
+
volumes:
|
| 15 |
+
# Mount the service code for live-reloading during development
|
| 16 |
+
- .:/app
|
| 17 |
+
# Mount a local directory to the container's huggingface cache directory.
|
| 18 |
+
# This will persist downloaded models on your host machine.
|
| 19 |
+
- ../.hf_cache:/root/.cache/huggingface
|
| 20 |
+
restart: unless-stopped
|
model/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .kronos import KronosTokenizer, Kronos, KronosPredictor
|
| 2 |
+
|
| 3 |
+
model_dict = {
|
| 4 |
+
'kronos_tokenizer': KronosTokenizer,
|
| 5 |
+
'kronos': Kronos,
|
| 6 |
+
'kronos_predictor': KronosPredictor
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def get_model_class(model_name):
|
| 11 |
+
if model_name in model_dict:
|
| 12 |
+
return model_dict[model_name]
|
| 13 |
+
else:
|
| 14 |
+
print(f"Model {model_name} not found in model_dict")
|
| 15 |
+
raise NotImplementedError
|
| 16 |
+
|
model/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (651 Bytes). View file
|
|
|
model/__pycache__/kronos.cpython-312.pyc
ADDED
|
Binary file (37.6 kB). View file
|
|
|
model/__pycache__/module.cpython-312.pyc
ADDED
|
Binary file (37.4 kB). View file
|
|
|
model/kronos.py
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import torch
|
| 4 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 5 |
+
from tqdm import trange
|
| 6 |
+
|
| 7 |
+
from .module import *
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class KronosTokenizer(nn.Module, PyTorchModelHubMixin):
|
| 11 |
+
"""
|
| 12 |
+
KronosTokenizer module for tokenizing input data using a hybrid quantization approach.
|
| 13 |
+
|
| 14 |
+
This tokenizer utilizes a combination of encoder and decoder Transformer blocks
|
| 15 |
+
along with the Binary Spherical Quantization (BSQuantizer) to compress and decompress input data.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
d_in (int): Input dimension.
|
| 19 |
+
d_model (int): Model dimension.
|
| 20 |
+
n_heads (int): Number of attention heads.
|
| 21 |
+
ff_dim (int): Feed-forward dimension.
|
| 22 |
+
n_enc_layers (int): Number of encoder layers.
|
| 23 |
+
n_dec_layers (int): Number of decoder layers.
|
| 24 |
+
ffn_dropout_p (float): Dropout probability for feed-forward networks.
|
| 25 |
+
attn_dropout_p (float): Dropout probability for attention mechanisms.
|
| 26 |
+
resid_dropout_p (float): Dropout probability for residual connections.
|
| 27 |
+
s1_bits (int): Number of bits for the pre token in BSQuantizer.
|
| 28 |
+
s2_bits (int): Number of bits for the post token in BSQuantizer.
|
| 29 |
+
beta (float): Beta parameter for BSQuantizer.
|
| 30 |
+
gamma0 (float): Gamma0 parameter for BSQuantizer.
|
| 31 |
+
gamma (float): Gamma parameter for BSQuantizer.
|
| 32 |
+
zeta (float): Zeta parameter for BSQuantizer.
|
| 33 |
+
group_size (int): Group size parameter for BSQuantizer.
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
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):
|
| 38 |
+
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.d_in = d_in
|
| 41 |
+
self.d_model = d_model
|
| 42 |
+
self.n_heads = n_heads
|
| 43 |
+
self.ff_dim = ff_dim
|
| 44 |
+
self.enc_layers = n_enc_layers
|
| 45 |
+
self.dec_layers = n_dec_layers
|
| 46 |
+
self.ffn_dropout_p = ffn_dropout_p
|
| 47 |
+
self.attn_dropout_p = attn_dropout_p
|
| 48 |
+
self.resid_dropout_p = resid_dropout_p
|
| 49 |
+
|
| 50 |
+
self.s1_bits = s1_bits
|
| 51 |
+
self.s2_bits = s2_bits
|
| 52 |
+
self.codebook_dim = s1_bits + s2_bits # Total dimension of the codebook after quantization
|
| 53 |
+
self.embed = nn.Linear(self.d_in, self.d_model)
|
| 54 |
+
self.head = nn.Linear(self.d_model, self.d_in)
|
| 55 |
+
|
| 56 |
+
# Encoder Transformer Blocks
|
| 57 |
+
self.encoder = nn.ModuleList([
|
| 58 |
+
TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
|
| 59 |
+
for _ in range(self.enc_layers - 1)
|
| 60 |
+
])
|
| 61 |
+
# Decoder Transformer Blocks
|
| 62 |
+
self.decoder = nn.ModuleList([
|
| 63 |
+
TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
|
| 64 |
+
for _ in range(self.dec_layers - 1)
|
| 65 |
+
])
|
| 66 |
+
self.quant_embed = nn.Linear(in_features=self.d_model, out_features=self.codebook_dim) # Linear layer before quantization
|
| 67 |
+
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)
|
| 68 |
+
self.post_quant_embed = nn.Linear(in_features=self.codebook_dim, out_features=self.d_model) # Linear layer after quantization (full codebook)
|
| 69 |
+
self.tokenizer = BSQuantizer(self.s1_bits, self.s2_bits, beta, gamma0, gamma, zeta, group_size) # BSQuantizer module
|
| 70 |
+
|
| 71 |
+
def forward(self, x):
|
| 72 |
+
"""
|
| 73 |
+
Forward pass of the KronosTokenizer.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
x (torch.Tensor): Input tensor of shape (batch_size, seq_len, d_in).
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
tuple: A tuple containing:
|
| 80 |
+
- tuple: (z_pre, z) - Reconstructed outputs from decoder with s1_bits and full codebook respectively,
|
| 81 |
+
both of shape (batch_size, seq_len, d_in).
|
| 82 |
+
- torch.Tensor: bsq_loss - Loss from the BSQuantizer.
|
| 83 |
+
- torch.Tensor: quantized - Quantized representation from BSQuantizer.
|
| 84 |
+
- torch.Tensor: z_indices - Indices from the BSQuantizer.
|
| 85 |
+
"""
|
| 86 |
+
z = self.embed(x)
|
| 87 |
+
|
| 88 |
+
for layer in self.encoder:
|
| 89 |
+
z = layer(z)
|
| 90 |
+
|
| 91 |
+
z = self.quant_embed(z) # (B, T, codebook)
|
| 92 |
+
|
| 93 |
+
bsq_loss, quantized, z_indices = self.tokenizer(z)
|
| 94 |
+
|
| 95 |
+
quantized_pre = quantized[:, :, :self.s1_bits] # Extract the first part of quantized representation (s1_bits)
|
| 96 |
+
z_pre = self.post_quant_embed_pre(quantized_pre)
|
| 97 |
+
|
| 98 |
+
z = self.post_quant_embed(quantized)
|
| 99 |
+
|
| 100 |
+
# Decoder layers (for pre part - s1 bits)
|
| 101 |
+
for layer in self.decoder:
|
| 102 |
+
z_pre = layer(z_pre)
|
| 103 |
+
z_pre = self.head(z_pre)
|
| 104 |
+
|
| 105 |
+
# Decoder layers (for full codebook)
|
| 106 |
+
for layer in self.decoder:
|
| 107 |
+
z = layer(z)
|
| 108 |
+
z = self.head(z)
|
| 109 |
+
|
| 110 |
+
return (z_pre, z), bsq_loss, quantized, z_indices
|
| 111 |
+
|
| 112 |
+
def indices_to_bits(self, x, half=False):
|
| 113 |
+
"""
|
| 114 |
+
Converts indices to bit representations and scales them.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
x (torch.Tensor): Indices tensor.
|
| 118 |
+
half (bool, optional): Whether to process only half of the codebook dimension. Defaults to False.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
torch.Tensor: Bit representation tensor.
|
| 122 |
+
"""
|
| 123 |
+
if half:
|
| 124 |
+
x1 = x[0] # Assuming x is a tuple of indices if half is True
|
| 125 |
+
x2 = x[1]
|
| 126 |
+
mask = 2 ** torch.arange(self.codebook_dim//2, device=x1.device, dtype=torch.long) # Create a mask for bit extraction
|
| 127 |
+
x1 = (x1.unsqueeze(-1) & mask) != 0 # Extract bits for the first half
|
| 128 |
+
x2 = (x2.unsqueeze(-1) & mask) != 0 # Extract bits for the second half
|
| 129 |
+
x = torch.cat([x1, x2], dim=-1) # Concatenate the bit representations
|
| 130 |
+
else:
|
| 131 |
+
mask = 2 ** torch.arange(self.codebook_dim, device=x.device, dtype=torch.long) # Create a mask for bit extraction
|
| 132 |
+
x = (x.unsqueeze(-1) & mask) != 0 # Extract bits
|
| 133 |
+
|
| 134 |
+
x = x.float() * 2 - 1 # Convert boolean to bipolar (-1, 1)
|
| 135 |
+
q_scale = 1. / (self.codebook_dim ** 0.5) # Scaling factor
|
| 136 |
+
x = x * q_scale
|
| 137 |
+
return x
|
| 138 |
+
|
| 139 |
+
def encode(self, x, half=False):
|
| 140 |
+
"""
|
| 141 |
+
Encodes the input data into quantized indices.
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
x (torch.Tensor): Input tensor of shape (batch_size, seq_len, d_in).
|
| 145 |
+
half (bool, optional): Whether to use half quantization in BSQuantizer. Defaults to False.
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
torch.Tensor: Quantized indices from BSQuantizer.
|
| 149 |
+
"""
|
| 150 |
+
z = self.embed(x)
|
| 151 |
+
for layer in self.encoder:
|
| 152 |
+
z = layer(z)
|
| 153 |
+
z = self.quant_embed(z)
|
| 154 |
+
|
| 155 |
+
bsq_loss, quantized, z_indices = self.tokenizer(z, half)
|
| 156 |
+
return z_indices
|
| 157 |
+
|
| 158 |
+
def decode(self, x, half=False):
|
| 159 |
+
"""
|
| 160 |
+
Decodes quantized indices back to the input data space.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
x (torch.Tensor): Quantized indices tensor.
|
| 164 |
+
half (bool, optional): Whether the indices were generated with half quantization. Defaults to False.
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
torch.Tensor: Reconstructed output tensor of shape (batch_size, seq_len, d_in).
|
| 168 |
+
"""
|
| 169 |
+
quantized = self.indices_to_bits(x, half)
|
| 170 |
+
z = self.post_quant_embed(quantized)
|
| 171 |
+
for layer in self.decoder:
|
| 172 |
+
z = layer(z)
|
| 173 |
+
z = self.head(z)
|
| 174 |
+
return z
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class Kronos(nn.Module, PyTorchModelHubMixin):
|
| 178 |
+
"""
|
| 179 |
+
Kronos Model.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
s1_bits (int): Number of bits for pre tokens.
|
| 183 |
+
s2_bits (int): Number of bits for post tokens.
|
| 184 |
+
n_layers (int): Number of Transformer blocks.
|
| 185 |
+
d_model (int): Dimension of the model's embeddings and hidden states.
|
| 186 |
+
n_heads (int): Number of attention heads in the MultiheadAttention layers.
|
| 187 |
+
ff_dim (int): Dimension of the feedforward network in the Transformer blocks.
|
| 188 |
+
ffn_dropout_p (float): Dropout probability for the feedforward network.
|
| 189 |
+
attn_dropout_p (float): Dropout probability for the attention layers.
|
| 190 |
+
resid_dropout_p (float): Dropout probability for residual connections.
|
| 191 |
+
token_dropout_p (float): Dropout probability for token embeddings.
|
| 192 |
+
learn_te (bool): Whether to use learnable temporal embeddings.
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
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):
|
| 196 |
+
super().__init__()
|
| 197 |
+
self.s1_bits = s1_bits
|
| 198 |
+
self.s2_bits = s2_bits
|
| 199 |
+
self.n_layers = n_layers
|
| 200 |
+
self.d_model = d_model
|
| 201 |
+
self.n_heads = n_heads
|
| 202 |
+
self.learn_te = learn_te
|
| 203 |
+
self.ff_dim = ff_dim
|
| 204 |
+
self.ffn_dropout_p = ffn_dropout_p
|
| 205 |
+
self.attn_dropout_p = attn_dropout_p
|
| 206 |
+
self.resid_dropout_p = resid_dropout_p
|
| 207 |
+
self.token_dropout_p = token_dropout_p
|
| 208 |
+
|
| 209 |
+
self.s1_vocab_size = 2 ** self.s1_bits
|
| 210 |
+
self.token_drop = nn.Dropout(self.token_dropout_p)
|
| 211 |
+
self.embedding = HierarchicalEmbedding(self.s1_bits, self.s2_bits, self.d_model)
|
| 212 |
+
self.time_emb = TemporalEmbedding(self.d_model, self.learn_te)
|
| 213 |
+
self.transformer = nn.ModuleList([
|
| 214 |
+
TransformerBlock(self.d_model, self.n_heads, self.ff_dim, self.ffn_dropout_p, self.attn_dropout_p, self.resid_dropout_p)
|
| 215 |
+
for _ in range(self.n_layers)
|
| 216 |
+
])
|
| 217 |
+
self.norm = RMSNorm(self.d_model)
|
| 218 |
+
self.dep_layer = DependencyAwareLayer(self.d_model)
|
| 219 |
+
self.head = DualHead(self.s1_bits, self.s2_bits, self.d_model)
|
| 220 |
+
self.apply(self._init_weights)
|
| 221 |
+
|
| 222 |
+
def _init_weights(self, module):
|
| 223 |
+
|
| 224 |
+
if isinstance(module, nn.Linear):
|
| 225 |
+
nn.init.xavier_normal_(module.weight)
|
| 226 |
+
if module.bias is not None:
|
| 227 |
+
nn.init.zeros_(module.bias)
|
| 228 |
+
elif isinstance(module, nn.Embedding):
|
| 229 |
+
nn.init.normal_(module.weight, mean=0, std=self.embedding.d_model ** -0.5)
|
| 230 |
+
elif isinstance(module, nn.LayerNorm):
|
| 231 |
+
nn.init.ones_(module.weight)
|
| 232 |
+
nn.init.zeros_(module.bias)
|
| 233 |
+
elif isinstance(module, RMSNorm):
|
| 234 |
+
nn.init.ones_(module.weight)
|
| 235 |
+
|
| 236 |
+
def forward(self, s1_ids, s2_ids, stamp=None, padding_mask=None, use_teacher_forcing=False, s1_targets=None):
|
| 237 |
+
"""
|
| 238 |
+
Args:
|
| 239 |
+
s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
|
| 240 |
+
s2_ids (torch.Tensor): Input tensor of s2 token IDs. Shape: [batch_size, seq_len]
|
| 241 |
+
stamp (torch.Tensor, optional): Temporal stamp tensor. Shape: [batch_size, seq_len]. Defaults to None.
|
| 242 |
+
padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
|
| 243 |
+
use_teacher_forcing (bool, optional): Whether to use teacher forcing for s1 decoding. Defaults to False.
|
| 244 |
+
s1_targets (torch.Tensor, optional): Target s1 token IDs for teacher forcing. Shape: [batch_size, seq_len]. Defaults to None.
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
Tuple[torch.Tensor, torch.Tensor]:
|
| 248 |
+
- s1 logits: Logits for s1 token predictions. Shape: [batch_size, seq_len, s1_vocab_size]
|
| 249 |
+
- s2_logits: Logits for s2 token predictions, conditioned on s1. Shape: [batch_size, seq_len, s2_vocab_size]
|
| 250 |
+
"""
|
| 251 |
+
x = self.embedding([s1_ids, s2_ids])
|
| 252 |
+
if stamp is not None:
|
| 253 |
+
time_embedding = self.time_emb(stamp)
|
| 254 |
+
x = x + time_embedding
|
| 255 |
+
x = self.token_drop(x)
|
| 256 |
+
|
| 257 |
+
for layer in self.transformer:
|
| 258 |
+
x = layer(x, key_padding_mask=padding_mask)
|
| 259 |
+
|
| 260 |
+
x = self.norm(x)
|
| 261 |
+
|
| 262 |
+
s1_logits = self.head(x)
|
| 263 |
+
|
| 264 |
+
if use_teacher_forcing:
|
| 265 |
+
sibling_embed = self.embedding.emb_s1(s1_targets)
|
| 266 |
+
else:
|
| 267 |
+
s1_probs = F.softmax(s1_logits.detach(), dim=-1)
|
| 268 |
+
sample_s1_ids = torch.multinomial(s1_probs.view(-1, self.s1_vocab_size), 1).view(s1_ids.shape)
|
| 269 |
+
sibling_embed = self.embedding.emb_s1(sample_s1_ids)
|
| 270 |
+
|
| 271 |
+
x2 = self.dep_layer(x, sibling_embed, key_padding_mask=padding_mask) # Dependency Aware Layer: Condition on s1 embeddings
|
| 272 |
+
s2_logits = self.head.cond_forward(x2)
|
| 273 |
+
return s1_logits, s2_logits
|
| 274 |
+
|
| 275 |
+
def decode_s1(self, s1_ids, s2_ids, stamp=None, padding_mask=None):
|
| 276 |
+
"""
|
| 277 |
+
Decodes only the s1 tokens.
|
| 278 |
+
|
| 279 |
+
This method performs a forward pass to predict only s1 tokens. It returns the s1 logits
|
| 280 |
+
and the context representation from the Transformer, which can be used for subsequent s2 decoding.
|
| 281 |
+
|
| 282 |
+
Args:
|
| 283 |
+
s1_ids (torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
|
| 284 |
+
s2_ids (torch.Tensor): Input tensor of s2 token IDs. Shape: [batch_size, seq_len]
|
| 285 |
+
stamp (torch.Tensor, optional): Temporal stamp tensor. Shape: [batch_size, seq_len]. Defaults to None.
|
| 286 |
+
padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
|
| 287 |
+
|
| 288 |
+
Returns:
|
| 289 |
+
Tuple[torch.Tensor, torch.Tensor]:
|
| 290 |
+
- s1 logits: Logits for s1 token predictions. Shape: [batch_size, seq_len, s1_vocab_size]
|
| 291 |
+
- context: Context representation from the Transformer. Shape: [batch_size, seq_len, d_model]
|
| 292 |
+
"""
|
| 293 |
+
x = self.embedding([s1_ids, s2_ids])
|
| 294 |
+
if stamp is not None:
|
| 295 |
+
time_embedding = self.time_emb(stamp)
|
| 296 |
+
x = x + time_embedding
|
| 297 |
+
x = self.token_drop(x)
|
| 298 |
+
|
| 299 |
+
for layer in self.transformer:
|
| 300 |
+
x = layer(x, key_padding_mask=padding_mask)
|
| 301 |
+
|
| 302 |
+
x = self.norm(x)
|
| 303 |
+
|
| 304 |
+
s1_logits = self.head(x)
|
| 305 |
+
return s1_logits, x
|
| 306 |
+
|
| 307 |
+
def decode_s2(self, context, s1_ids, padding_mask=None):
|
| 308 |
+
"""
|
| 309 |
+
Decodes the s2 tokens, conditioned on the context and s1 tokens.
|
| 310 |
+
|
| 311 |
+
This method decodes s2 tokens based on a pre-computed context representation (typically from `decode_s1`)
|
| 312 |
+
and the s1 token IDs. It uses the dependency-aware layer and the conditional s2 head to predict s2 tokens.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
context (torch.Tensor): Context representation from the transformer (output of decode_s1).
|
| 316 |
+
Shape: [batch_size, seq_len, d_model]
|
| 317 |
+
s1_ids (torch.torch.Tensor): Input tensor of s1 token IDs. Shape: [batch_size, seq_len]
|
| 318 |
+
padding_mask (torch.Tensor, optional): Mask for padding tokens. Shape: [batch_size, seq_len]. Defaults to None.
|
| 319 |
+
|
| 320 |
+
Returns:
|
| 321 |
+
torch.Tensor: s2 logits. Shape: [batch_size, seq_len, s2_vocab_size]
|
| 322 |
+
"""
|
| 323 |
+
sibling_embed = self.embedding.emb_s1(s1_ids)
|
| 324 |
+
x2 = self.dep_layer(context, sibling_embed, key_padding_mask=padding_mask)
|
| 325 |
+
return self.head.cond_forward(x2)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def top_k_top_p_filtering(
|
| 329 |
+
logits,
|
| 330 |
+
top_k: int = 0,
|
| 331 |
+
top_p: float = 1.0,
|
| 332 |
+
filter_value: float = -float("Inf"),
|
| 333 |
+
min_tokens_to_keep: int = 1,
|
| 334 |
+
):
|
| 335 |
+
"""Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
|
| 336 |
+
Args:
|
| 337 |
+
logits: logits distribution shape (batch size, vocabulary size)
|
| 338 |
+
if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
|
| 339 |
+
if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
|
| 340 |
+
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
|
| 341 |
+
Make sure we keep at least min_tokens_to_keep per batch example in the output
|
| 342 |
+
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
|
| 343 |
+
"""
|
| 344 |
+
if top_k > 0:
|
| 345 |
+
top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check
|
| 346 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
| 347 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 348 |
+
logits[indices_to_remove] = filter_value
|
| 349 |
+
return logits
|
| 350 |
+
|
| 351 |
+
if top_p < 1.0:
|
| 352 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 353 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 354 |
+
|
| 355 |
+
# Remove tokens with cumulative probability above the threshold (token with 0 are kept)
|
| 356 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 357 |
+
if min_tokens_to_keep > 1:
|
| 358 |
+
# Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
|
| 359 |
+
sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
|
| 360 |
+
# Shift the indices to the right to keep also the first token above the threshold
|
| 361 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 362 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 363 |
+
|
| 364 |
+
# scatter sorted tensors to original indexing
|
| 365 |
+
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
| 366 |
+
logits[indices_to_remove] = filter_value
|
| 367 |
+
return logits
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def sample_from_logits(logits, temperature=1.0, top_k=None, top_p=None, sample_logits=True):
|
| 371 |
+
logits = logits / temperature
|
| 372 |
+
if top_k is not None or top_p is not None:
|
| 373 |
+
if top_k > 0 or top_p < 1.0:
|
| 374 |
+
logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
|
| 375 |
+
|
| 376 |
+
probs = F.softmax(logits, dim=-1)
|
| 377 |
+
|
| 378 |
+
if not sample_logits:
|
| 379 |
+
_, x = top_k(probs, k=1, dim=-1)
|
| 380 |
+
else:
|
| 381 |
+
x = torch.multinomial(probs, num_samples=1)
|
| 382 |
+
|
| 383 |
+
return x
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
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):
|
| 387 |
+
with torch.no_grad():
|
| 388 |
+
batch_size = x.size(0)
|
| 389 |
+
initial_seq_len = x.size(1)
|
| 390 |
+
x = torch.clip(x, -clip, clip)
|
| 391 |
+
|
| 392 |
+
device = x.device
|
| 393 |
+
x = x.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, x.size(1), x.size(2)).to(device)
|
| 394 |
+
x_stamp = x_stamp.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, x_stamp.size(1), x_stamp.size(2)).to(device)
|
| 395 |
+
y_stamp = y_stamp.unsqueeze(1).repeat(1, sample_count, 1, 1).reshape(-1, y_stamp.size(1), y_stamp.size(2)).to(device)
|
| 396 |
+
|
| 397 |
+
x_token = tokenizer.encode(x, half=True)
|
| 398 |
+
|
| 399 |
+
def get_dynamic_stamp(x_stamp, y_stamp, current_seq_len, pred_step):
|
| 400 |
+
|
| 401 |
+
if current_seq_len <= max_context - pred_step:
|
| 402 |
+
return torch.cat([x_stamp, y_stamp[:, :pred_step, :]], dim=1)
|
| 403 |
+
else:
|
| 404 |
+
start_idx = max_context - pred_step
|
| 405 |
+
return torch.cat([x_stamp[:, -start_idx:, :], y_stamp[:, :pred_step, :]], dim=1)
|
| 406 |
+
|
| 407 |
+
if verbose:
|
| 408 |
+
ran = trange
|
| 409 |
+
else:
|
| 410 |
+
ran = range
|
| 411 |
+
for i in ran(pred_len):
|
| 412 |
+
current_seq_len = initial_seq_len + i
|
| 413 |
+
|
| 414 |
+
if current_seq_len <= max_context:
|
| 415 |
+
input_tokens = x_token
|
| 416 |
+
else:
|
| 417 |
+
input_tokens = [t[:, -max_context:].contiguous() for t in x_token]
|
| 418 |
+
|
| 419 |
+
current_stamp = get_dynamic_stamp(x_stamp, y_stamp, current_seq_len, i)
|
| 420 |
+
|
| 421 |
+
s1_logits, context = model.decode_s1(input_tokens[0], input_tokens[1], current_stamp)
|
| 422 |
+
s1_logits = s1_logits[:, -1, :]
|
| 423 |
+
sample_pre = sample_from_logits(s1_logits, temperature=T, top_k=top_k, top_p=top_p, sample_logits=True)
|
| 424 |
+
|
| 425 |
+
s2_logits = model.decode_s2(context, sample_pre)
|
| 426 |
+
s2_logits = s2_logits[:, -1, :]
|
| 427 |
+
sample_post = sample_from_logits(s2_logits, temperature=T, top_k=top_k, top_p=top_p, sample_logits=True)
|
| 428 |
+
|
| 429 |
+
x_token[0] = torch.cat([x_token[0], sample_pre], dim=1)
|
| 430 |
+
x_token[1] = torch.cat([x_token[1], sample_post], dim=1)
|
| 431 |
+
|
| 432 |
+
torch.cuda.empty_cache()
|
| 433 |
+
|
| 434 |
+
input_tokens = [t[:, -max_context:].contiguous() for t in x_token]
|
| 435 |
+
z = tokenizer.decode(input_tokens, half=True)
|
| 436 |
+
z = z.reshape(batch_size, sample_count, z.size(1), z.size(2))
|
| 437 |
+
preds = z.cpu().numpy()
|
| 438 |
+
preds = np.mean(preds, axis=1)
|
| 439 |
+
|
| 440 |
+
return preds
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def calc_time_stamps(x_timestamp):
|
| 444 |
+
time_df = pd.DataFrame()
|
| 445 |
+
time_df['minute'] = x_timestamp.dt.minute
|
| 446 |
+
time_df['hour'] = x_timestamp.dt.hour
|
| 447 |
+
time_df['weekday'] = x_timestamp.dt.weekday
|
| 448 |
+
time_df['day'] = x_timestamp.dt.day
|
| 449 |
+
time_df['month'] = x_timestamp.dt.month
|
| 450 |
+
return time_df
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
class KronosPredictor:
|
| 454 |
+
|
| 455 |
+
def __init__(self, model, tokenizer, device="cuda:0", max_context=512, clip=5):
|
| 456 |
+
self.tokenizer = tokenizer
|
| 457 |
+
self.model = model
|
| 458 |
+
self.max_context = max_context
|
| 459 |
+
self.clip = clip
|
| 460 |
+
self.price_cols = ['open', 'high', 'low', 'close']
|
| 461 |
+
self.vol_col = 'volume'
|
| 462 |
+
self.amt_vol = 'amount'
|
| 463 |
+
self.time_cols = ['minute', 'hour', 'weekday', 'day', 'month']
|
| 464 |
+
self.device = device
|
| 465 |
+
|
| 466 |
+
self.tokenizer = self.tokenizer.to(self.device)
|
| 467 |
+
self.model = self.model.to(self.device)
|
| 468 |
+
|
| 469 |
+
def generate(self, x, x_stamp, y_stamp, pred_len, T, top_k, top_p, sample_count, verbose):
|
| 470 |
+
|
| 471 |
+
x_tensor = torch.from_numpy(np.array(x).astype(np.float32)).to(self.device)
|
| 472 |
+
x_stamp_tensor = torch.from_numpy(np.array(x_stamp).astype(np.float32)).to(self.device)
|
| 473 |
+
y_stamp_tensor = torch.from_numpy(np.array(y_stamp).astype(np.float32)).to(self.device)
|
| 474 |
+
|
| 475 |
+
preds = auto_regressive_inference(self.tokenizer, self.model, x_tensor, x_stamp_tensor, y_stamp_tensor, self.max_context, pred_len,
|
| 476 |
+
self.clip, T, top_k, top_p, sample_count, verbose)
|
| 477 |
+
preds = preds[:, -pred_len:, :]
|
| 478 |
+
return preds
|
| 479 |
+
|
| 480 |
+
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):
|
| 481 |
+
|
| 482 |
+
if not isinstance(df, pd.DataFrame):
|
| 483 |
+
raise ValueError("Input must be a pandas DataFrame.")
|
| 484 |
+
|
| 485 |
+
if not all(col in df.columns for col in self.price_cols):
|
| 486 |
+
raise ValueError(f"Price columns {self.price_cols} not found in DataFrame.")
|
| 487 |
+
|
| 488 |
+
df = df.copy()
|
| 489 |
+
if self.vol_col not in df.columns:
|
| 490 |
+
df[self.vol_col] = 0.0 # Fill missing volume with zeros
|
| 491 |
+
df[self.amt_vol] = 0.0 # Fill missing amount with zeros
|
| 492 |
+
if self.amt_vol not in df.columns and self.vol_col in df.columns:
|
| 493 |
+
df[self.amt_vol] = df[self.vol_col] * df[self.price_cols].mean(axis=1)
|
| 494 |
+
|
| 495 |
+
if df[self.price_cols + [self.vol_col, self.amt_vol]].isnull().values.any():
|
| 496 |
+
raise ValueError("Input DataFrame contains NaN values in price or volume columns.")
|
| 497 |
+
|
| 498 |
+
x_time_df = calc_time_stamps(x_timestamp)
|
| 499 |
+
y_time_df = calc_time_stamps(y_timestamp)
|
| 500 |
+
|
| 501 |
+
x = df[self.price_cols + [self.vol_col, self.amt_vol]].values.astype(np.float32)
|
| 502 |
+
x_stamp = x_time_df.values.astype(np.float32)
|
| 503 |
+
y_stamp = y_time_df.values.astype(np.float32)
|
| 504 |
+
|
| 505 |
+
x_mean, x_std = np.mean(x, axis=0), np.std(x, axis=0)
|
| 506 |
+
|
| 507 |
+
x = (x - x_mean) / (x_std + 1e-5)
|
| 508 |
+
x = np.clip(x, -self.clip, self.clip)
|
| 509 |
+
|
| 510 |
+
x = x[np.newaxis, :]
|
| 511 |
+
x_stamp = x_stamp[np.newaxis, :]
|
| 512 |
+
y_stamp = y_stamp[np.newaxis, :]
|
| 513 |
+
|
| 514 |
+
preds = self.generate(x, x_stamp, y_stamp, pred_len, T, top_k, top_p, sample_count, verbose)
|
| 515 |
+
|
| 516 |
+
preds = preds.squeeze(0)
|
| 517 |
+
preds = preds * (x_std + 1e-5) + x_mean
|
| 518 |
+
|
| 519 |
+
pred_df = pd.DataFrame(preds, columns=self.price_cols + [self.vol_col, self.amt_vol], index=y_timestamp)
|
| 520 |
+
return pred_df
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
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):
|
| 524 |
+
"""
|
| 525 |
+
Perform parallel (batch) prediction on multiple time series. All series must have the same historical length and prediction length (pred_len).
|
| 526 |
+
|
| 527 |
+
Args:
|
| 528 |
+
df_list (List[pd.DataFrame]): List of input DataFrames, each containing price columns and optional volume/amount columns.
|
| 529 |
+
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.
|
| 530 |
+
y_timestamp_list (List[pd.DatetimeIndex or Series]): List of future prediction timestamps, length should equal pred_len.
|
| 531 |
+
pred_len (int): Number of prediction steps.
|
| 532 |
+
T (float): Sampling temperature.
|
| 533 |
+
top_k (int): Top-k filtering threshold.
|
| 534 |
+
top_p (float): Top-p (nucleus sampling) threshold.
|
| 535 |
+
sample_count (int): Number of parallel samples per series, automatically averaged internally.
|
| 536 |
+
verbose (bool): Whether to display autoregressive progress.
|
| 537 |
+
|
| 538 |
+
Returns:
|
| 539 |
+
List[pd.DataFrame]: List of prediction results in the same order as input, each DataFrame contains
|
| 540 |
+
`open, high, low, close, volume, amount` columns, indexed by corresponding `y_timestamp`.
|
| 541 |
+
"""
|
| 542 |
+
# Basic validation
|
| 543 |
+
if not isinstance(df_list, (list, tuple)) or not isinstance(x_timestamp_list, (list, tuple)) or not isinstance(y_timestamp_list, (list, tuple)):
|
| 544 |
+
raise ValueError("df_list, x_timestamp_list, y_timestamp_list must be list or tuple types.")
|
| 545 |
+
if not (len(df_list) == len(x_timestamp_list) == len(y_timestamp_list)):
|
| 546 |
+
raise ValueError("df_list, x_timestamp_list, y_timestamp_list must have consistent lengths.")
|
| 547 |
+
|
| 548 |
+
num_series = len(df_list)
|
| 549 |
+
|
| 550 |
+
x_list = []
|
| 551 |
+
x_stamp_list = []
|
| 552 |
+
y_stamp_list = []
|
| 553 |
+
means = []
|
| 554 |
+
stds = []
|
| 555 |
+
seq_lens = []
|
| 556 |
+
y_lens = []
|
| 557 |
+
|
| 558 |
+
for i in range(num_series):
|
| 559 |
+
df = df_list[i]
|
| 560 |
+
if not isinstance(df, pd.DataFrame):
|
| 561 |
+
raise ValueError(f"Input at index {i} is not a pandas DataFrame.")
|
| 562 |
+
if not all(col in df.columns for col in self.price_cols):
|
| 563 |
+
raise ValueError(f"DataFrame at index {i} is missing price columns {self.price_cols}.")
|
| 564 |
+
|
| 565 |
+
df = df.copy()
|
| 566 |
+
if self.vol_col not in df.columns:
|
| 567 |
+
df[self.vol_col] = 0.0
|
| 568 |
+
df[self.amt_vol] = 0.0
|
| 569 |
+
if self.amt_vol not in df.columns and self.vol_col in df.columns:
|
| 570 |
+
df[self.amt_vol] = df[self.vol_col] * df[self.price_cols].mean(axis=1)
|
| 571 |
+
|
| 572 |
+
if df[self.price_cols + [self.vol_col, self.amt_vol]].isnull().values.any():
|
| 573 |
+
raise ValueError(f"DataFrame at index {i} contains NaN values in price or volume columns.")
|
| 574 |
+
|
| 575 |
+
x_timestamp = x_timestamp_list[i]
|
| 576 |
+
y_timestamp = y_timestamp_list[i]
|
| 577 |
+
|
| 578 |
+
x_time_df = calc_time_stamps(x_timestamp)
|
| 579 |
+
y_time_df = calc_time_stamps(y_timestamp)
|
| 580 |
+
|
| 581 |
+
x = df[self.price_cols + [self.vol_col, self.amt_vol]].values.astype(np.float32)
|
| 582 |
+
x_stamp = x_time_df.values.astype(np.float32)
|
| 583 |
+
y_stamp = y_time_df.values.astype(np.float32)
|
| 584 |
+
|
| 585 |
+
if x.shape[0] != x_stamp.shape[0]:
|
| 586 |
+
raise ValueError(f"Inconsistent lengths at index {i}: x has {x.shape[0]} vs x_stamp has {x_stamp.shape[0]}.")
|
| 587 |
+
if y_stamp.shape[0] != pred_len:
|
| 588 |
+
raise ValueError(f"y_timestamp length at index {i} should equal pred_len={pred_len}, got {y_stamp.shape[0]}.")
|
| 589 |
+
|
| 590 |
+
x_mean, x_std = np.mean(x, axis=0), np.std(x, axis=0)
|
| 591 |
+
x_norm = (x - x_mean) / (x_std + 1e-5)
|
| 592 |
+
x_norm = np.clip(x_norm, -self.clip, self.clip)
|
| 593 |
+
|
| 594 |
+
x_list.append(x_norm)
|
| 595 |
+
x_stamp_list.append(x_stamp)
|
| 596 |
+
y_stamp_list.append(y_stamp)
|
| 597 |
+
means.append(x_mean)
|
| 598 |
+
stds.append(x_std)
|
| 599 |
+
|
| 600 |
+
seq_lens.append(x_norm.shape[0])
|
| 601 |
+
y_lens.append(y_stamp.shape[0])
|
| 602 |
+
|
| 603 |
+
# Require all series to have consistent historical and prediction lengths for batch processing
|
| 604 |
+
if len(set(seq_lens)) != 1:
|
| 605 |
+
raise ValueError(f"Parallel prediction requires all series to have consistent historical lengths, got: {seq_lens}")
|
| 606 |
+
if len(set(y_lens)) != 1:
|
| 607 |
+
raise ValueError(f"Parallel prediction requires all series to have consistent prediction lengths, got: {y_lens}")
|
| 608 |
+
|
| 609 |
+
x_batch = np.stack(x_list, axis=0).astype(np.float32) # (B, seq_len, feat)
|
| 610 |
+
x_stamp_batch = np.stack(x_stamp_list, axis=0).astype(np.float32) # (B, seq_len, time_feat)
|
| 611 |
+
y_stamp_batch = np.stack(y_stamp_list, axis=0).astype(np.float32) # (B, pred_len, time_feat)
|
| 612 |
+
|
| 613 |
+
preds = self.generate(x_batch, x_stamp_batch, y_stamp_batch, pred_len, T, top_k, top_p, sample_count, verbose)
|
| 614 |
+
# preds: (B, pred_len, feat)
|
| 615 |
+
|
| 616 |
+
pred_dfs = []
|
| 617 |
+
for i in range(num_series):
|
| 618 |
+
preds_i = preds[i] * (stds[i] + 1e-5) + means[i]
|
| 619 |
+
pred_df = pd.DataFrame(preds_i, columns=self.price_cols + [self.vol_col, self.amt_vol], index=y_timestamp_list[i])
|
| 620 |
+
pred_dfs.append(pred_df)
|
| 621 |
+
|
| 622 |
+
return pred_dfs
|
model/module.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.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):
|
| 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 |
+
indices = self.codes_to_indexes(zq.detach())
|
| 96 |
+
group_indices = self.codes_to_group_indexes(zq.detach())
|
| 97 |
+
if not self.training:
|
| 98 |
+
used_codes = torch.unique(indices, return_counts=False)
|
| 99 |
+
else:
|
| 100 |
+
used_codes = None
|
| 101 |
+
|
| 102 |
+
q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
|
| 103 |
+
|
| 104 |
+
if self.soft_entropy:
|
| 105 |
+
persample_entropy, cb_entropy, avg_prob = self.soft_entropy_loss(z)
|
| 106 |
+
entropy_penalty = self.gamma0 * persample_entropy - self.gamma * cb_entropy
|
| 107 |
+
else:
|
| 108 |
+
zb_by_sample = ((zq + 1) / 2).reshape(z.shape[0], -1, z.shape[-1]).to(torch.float32)
|
| 109 |
+
persample_entropy = self.get_hard_per_sample_entropy(zb_by_sample)
|
| 110 |
+
cb_entropy = codebook_entropy(zq, self.basis, self.embed_dim)
|
| 111 |
+
entropy_penalty = self.gamma0 * persample_entropy - self.gamma * cb_entropy
|
| 112 |
+
|
| 113 |
+
zq = zq * q_scale
|
| 114 |
+
|
| 115 |
+
# commit loss
|
| 116 |
+
commit_loss = self.beta * torch.mean(((zq.detach() - z) ** 2).sum(dim=-1))
|
| 117 |
+
|
| 118 |
+
# if self.input_format == 'bchw':
|
| 119 |
+
# zq = rearrange(zq, 'b h w c -> b c h w')
|
| 120 |
+
|
| 121 |
+
return (
|
| 122 |
+
zq,
|
| 123 |
+
commit_loss + self.zeta * entropy_penalty / self.inv_temperature,
|
| 124 |
+
{"H": cb_entropy, "used_codes": used_codes, "indices": indices, "group_indices": group_indices,
|
| 125 |
+
"avg_prob": avg_prob}
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def soft_entropy_loss(self, z):
|
| 129 |
+
# if we divide the code in subgroups of size group_size, the codebook will be of size 2 ** group_size
|
| 130 |
+
# the sub-code is the last group_size bits of the full code
|
| 131 |
+
group_code_book = self.group_codebook / (self.embed_dim ** 0.5 if self.l2_norm else 1)
|
| 132 |
+
divided_z = rearrange(z, '... (g c) -> ... g c', c=self.group_size)
|
| 133 |
+
|
| 134 |
+
# we calculate the distance between the divided_z and the codebook for each subgroup
|
| 135 |
+
distance = - 2 * torch.einsum('... g c, d c ->... g d', divided_z, group_code_book)
|
| 136 |
+
prob = (-distance * self.inv_temperature).softmax(dim=-1)
|
| 137 |
+
if self.persample_entropy_compute == 'analytical':
|
| 138 |
+
if self.l2_norm:
|
| 139 |
+
p = torch.sigmoid(-4 * z / (self.embed_dim ** 0.5) * self.inv_temperature)
|
| 140 |
+
else:
|
| 141 |
+
p = torch.sigmoid(-4 * z * self.inv_temperature)
|
| 142 |
+
prob = torch.stack([p, 1 - p], dim=-1)
|
| 143 |
+
per_sample_entropy = self.get_entropy(prob, dim=-1, normalize=False).sum(dim=-1).mean()
|
| 144 |
+
else:
|
| 145 |
+
per_sample_entropy = self.get_entropy(prob, dim=-1, normalize=False).sum(dim=-1).mean()
|
| 146 |
+
|
| 147 |
+
# macro average of the probability of each subgroup
|
| 148 |
+
avg_prob = reduce(prob, '... g d ->g d', 'mean')
|
| 149 |
+
codebook_entropy = self.get_entropy(avg_prob, dim=-1, normalize=False)
|
| 150 |
+
|
| 151 |
+
# the approximation of the entropy is the sum of the entropy of each subgroup
|
| 152 |
+
return per_sample_entropy, codebook_entropy.sum(), avg_prob
|
| 153 |
+
|
| 154 |
+
def get_hard_per_sample_entropy(self, zb_by_sample):
|
| 155 |
+
probs_per_dim = zb_by_sample.sum(1) / zb_by_sample.shape[1]
|
| 156 |
+
persample_entropy = - probs_per_dim * torch.log(probs_per_dim + 1e-8) - (1 - probs_per_dim) * torch.log(1 - probs_per_dim + 1e-8)
|
| 157 |
+
persample_entropy = persample_entropy.sum(-1)
|
| 158 |
+
return persample_entropy.mean()
|
| 159 |
+
|
| 160 |
+
def codes_to_indexes(self, zhat):
|
| 161 |
+
"""Converts a `code` to an index in the codebook.
|
| 162 |
+
Args:
|
| 163 |
+
zhat: A tensor of shape (B, ..., C) containing the codes. must be in {-1, 1}
|
| 164 |
+
"""
|
| 165 |
+
assert zhat.shape[-1] == self.embed_dim, f"Expected {self.embed_dim} dimensions, got {zhat.shape[-1]}"
|
| 166 |
+
return ((zhat + 1) / 2 * self.basis).sum(axis=-1).to(torch.int64)
|
| 167 |
+
|
| 168 |
+
def codes_to_group_indexes(self, zhat):
|
| 169 |
+
"""Converts a `code` to a list of indexes (in groups) in the codebook.
|
| 170 |
+
Args:
|
| 171 |
+
zhat: A tensor of shape (B, ..., C) containing the codes. must be in {-1, 1}
|
| 172 |
+
"""
|
| 173 |
+
zhat_in_group = rearrange(zhat, 'b ... (g c) -> b ... g c', c=self.group_size)
|
| 174 |
+
return ((zhat_in_group + 1) / 2 * self.group_basis).sum(axis=-1).to(torch.int64)
|
| 175 |
+
|
| 176 |
+
def indexes_to_codes(self, indices):
|
| 177 |
+
"""Inverse of `indexes_to_codes`."""
|
| 178 |
+
indices = indices.unsqueeze(-1)
|
| 179 |
+
codes_non_centered = torch.remainder(
|
| 180 |
+
torch.floor_divide(indices, self.basis), 2
|
| 181 |
+
)
|
| 182 |
+
return codes_non_centered * 2 - 1
|
| 183 |
+
|
| 184 |
+
def group_indexes_to_codes(self, group_indices):
|
| 185 |
+
"""Inverse of `group_indexes_to_codes`."""
|
| 186 |
+
group_indices = group_indices.unsqueeze(-1)
|
| 187 |
+
codes_non_centered = torch.remainder(
|
| 188 |
+
torch.floor_divide(group_indices, self.group_basis), 2
|
| 189 |
+
)
|
| 190 |
+
codes_non_centered = rearrange(codes_non_centered, 'b ... g c -> b ... (g c)')
|
| 191 |
+
return codes_non_centered * 2 - 1
|
| 192 |
+
|
| 193 |
+
def get_entropy(self, count, dim=-1, eps=1e-4, normalize=True):
|
| 194 |
+
if normalize:
|
| 195 |
+
probs = (count + eps) / (count + eps).sum(dim=dim, keepdim=True)
|
| 196 |
+
else:
|
| 197 |
+
probs = count
|
| 198 |
+
H = -(probs * torch.log(probs + 1e-8)).sum(dim=dim)
|
| 199 |
+
return H
|
| 200 |
+
|
| 201 |
+
def get_group_codebook_entry(self, group_indices):
|
| 202 |
+
z_q = self.group_indexes_to_codes(group_indices)
|
| 203 |
+
q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
|
| 204 |
+
z_q = z_q * q_scale
|
| 205 |
+
if self.input_format == 'bchw':
|
| 206 |
+
h, w = int(z_q.shape[1] ** 0.5)
|
| 207 |
+
assert h * w == z_q.shape[1], 'Invalid sequence length'
|
| 208 |
+
z_q = rearrange(z_q, 'b (h w) c -> b c h w', h=h)
|
| 209 |
+
return z_q
|
| 210 |
+
|
| 211 |
+
def get_codebook_entry(self, indices):
|
| 212 |
+
z_q = self.indexes_to_codes(indices)
|
| 213 |
+
q_scale = 1. / (self.embed_dim ** 0.5) if self.l2_norm else 1.
|
| 214 |
+
z_q = z_q * q_scale
|
| 215 |
+
if self.input_format == 'bchw':
|
| 216 |
+
h, w = int(z_q.shape[1] ** 0.5)
|
| 217 |
+
assert h * w == z_q.shape[1], 'Invalid sequence length'
|
| 218 |
+
z_q = rearrange(z_q, 'b (h w) c -> b c h w', h=h)
|
| 219 |
+
return z_q
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class BSQuantizer(nn.Module):
|
| 223 |
+
|
| 224 |
+
def __init__(self, s1_bits, s2_bits, beta, gamma0, gamma, zeta, group_size):
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.codebook_dim = s1_bits + s2_bits
|
| 227 |
+
self.s1_bits = s1_bits
|
| 228 |
+
self.s2_bits = s2_bits
|
| 229 |
+
self.bsq = BinarySphericalQuantizer(self.codebook_dim, beta, gamma0, gamma, zeta, group_size=group_size)
|
| 230 |
+
|
| 231 |
+
def bits_to_indices(self, bits):
|
| 232 |
+
bits = (bits >= 0).to(torch.long)
|
| 233 |
+
indices = 2 ** torch.arange(
|
| 234 |
+
0,
|
| 235 |
+
bits.shape[-1],
|
| 236 |
+
1,
|
| 237 |
+
dtype=torch.long,
|
| 238 |
+
device=bits.device,
|
| 239 |
+
)
|
| 240 |
+
return (bits * indices).sum(-1)
|
| 241 |
+
|
| 242 |
+
def forward(self, z, half=False):
|
| 243 |
+
z = F.normalize(z, dim=-1)
|
| 244 |
+
quantized, bsq_loss, metrics = self.bsq(z)
|
| 245 |
+
if half:
|
| 246 |
+
q_pre = quantized[:, :, :self.s1_bits]
|
| 247 |
+
q_post = quantized[:, :, self.s1_bits:]
|
| 248 |
+
z_indices = [self.bits_to_indices(q_pre), self.bits_to_indices(q_post)]
|
| 249 |
+
else:
|
| 250 |
+
z_indices = self.bits_to_indices(quantized)
|
| 251 |
+
return bsq_loss, quantized, z_indices
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class RMSNorm(torch.nn.Module):
|
| 255 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 256 |
+
super().__init__()
|
| 257 |
+
self.eps = eps
|
| 258 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 259 |
+
|
| 260 |
+
def _norm(self, x):
|
| 261 |
+
return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
|
| 262 |
+
|
| 263 |
+
def forward(self, x):
|
| 264 |
+
output = self._norm(x.float()).type_as(x)
|
| 265 |
+
return output * self.weight
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class FeedForward(nn.Module):
|
| 269 |
+
def __init__(self, d_model, ff_dim, ffn_dropout_p=0.0):
|
| 270 |
+
super().__init__()
|
| 271 |
+
|
| 272 |
+
self.w1 = nn.Linear(d_model, ff_dim, bias=False)
|
| 273 |
+
self.w3 = nn.Linear(d_model, ff_dim, bias=False)
|
| 274 |
+
self.w2 = nn.Linear(ff_dim, d_model, bias=False)
|
| 275 |
+
self.ffn_dropout = nn.Dropout(ffn_dropout_p)
|
| 276 |
+
|
| 277 |
+
def forward(self, x):
|
| 278 |
+
return self.ffn_dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class RotaryPositionalEmbedding(nn.Module):
|
| 282 |
+
def __init__(self, dim):
|
| 283 |
+
super().__init__()
|
| 284 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
| 285 |
+
self.register_buffer("inv_freq", inv_freq)
|
| 286 |
+
self.seq_len_cached = None
|
| 287 |
+
self.cos_cached = None
|
| 288 |
+
self.sin_cached = None
|
| 289 |
+
|
| 290 |
+
def _update_cos_sin_cache(self, x, seq_len):
|
| 291 |
+
if seq_len != self.seq_len_cached:
|
| 292 |
+
self.seq_len_cached = seq_len
|
| 293 |
+
t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
|
| 294 |
+
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
|
| 295 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
| 296 |
+
self.cos_cached = emb.cos()[None, None, :, :]
|
| 297 |
+
self.sin_cached = emb.sin()[None, None, :, :]
|
| 298 |
+
return self.cos_cached, self.sin_cached
|
| 299 |
+
|
| 300 |
+
def forward(self, q, k):
|
| 301 |
+
cos, sin = self._update_cos_sin_cache(q, q.shape[-2])
|
| 302 |
+
return (
|
| 303 |
+
(q * cos) + (self._rotate_half(q) * sin),
|
| 304 |
+
(k * cos) + (self._rotate_half(k) * sin),
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
def _rotate_half(self, x):
|
| 308 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 309 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None) -> torch.Tensor:
|
| 313 |
+
L, S = query.size(-2), key.size(-2)
|
| 314 |
+
scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale
|
| 315 |
+
attn_bias = torch.zeros(L, S, dtype=query.dtype).to(query.device)
|
| 316 |
+
|
| 317 |
+
if is_causal:
|
| 318 |
+
assert attn_mask is None
|
| 319 |
+
temp_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0).to(query.device)
|
| 320 |
+
attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
|
| 321 |
+
attn_bias.to(query.dtype)
|
| 322 |
+
|
| 323 |
+
attn_weight = query @ key.transpose(-2, -1) * scale_factor
|
| 324 |
+
attn_weight += attn_bias
|
| 325 |
+
|
| 326 |
+
if attn_mask is not None:
|
| 327 |
+
attn_mask_bias = torch.zeros_like(attn_weight)
|
| 328 |
+
if attn_mask.dtype == torch.bool:
|
| 329 |
+
attn_mask_bias.masked_fill_(attn_mask, float("-inf"))
|
| 330 |
+
else:
|
| 331 |
+
attn_mask_bias += attn_mask
|
| 332 |
+
attn_weight += attn_mask_bias
|
| 333 |
+
|
| 334 |
+
attn_weight = torch.softmax(attn_weight, dim=-1)
|
| 335 |
+
attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
|
| 336 |
+
return attn_weight @ value
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class MultiHeadAttentionWithRoPE(nn.Module):
|
| 340 |
+
def __init__(self, d_model, n_heads, attn_dropout_p=0.0, resid_dropout_p=0.0):
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.d_model = d_model
|
| 343 |
+
self.n_heads = n_heads
|
| 344 |
+
self.head_dim = d_model // n_heads
|
| 345 |
+
|
| 346 |
+
self.q_proj = nn.Linear(d_model, d_model)
|
| 347 |
+
self.k_proj = nn.Linear(d_model, d_model)
|
| 348 |
+
self.v_proj = nn.Linear(d_model, d_model)
|
| 349 |
+
self.out_proj = nn.Linear(d_model, d_model)
|
| 350 |
+
self.rotary = RotaryPositionalEmbedding(self.head_dim)
|
| 351 |
+
self.attn_dropout_p = attn_dropout_p
|
| 352 |
+
self.resid_dropout = nn.Dropout(resid_dropout_p)
|
| 353 |
+
|
| 354 |
+
def forward(self, x, key_padding_mask=None):
|
| 355 |
+
batch_size, seq_len, _ = x.shape
|
| 356 |
+
|
| 357 |
+
q = self.q_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 358 |
+
k = self.k_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 359 |
+
v = self.v_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 360 |
+
|
| 361 |
+
q, k = self.rotary(q, k)
|
| 362 |
+
|
| 363 |
+
if key_padding_mask is not None:
|
| 364 |
+
attn_mask = key_padding_mask.unsqueeze(1).unsqueeze(2) # [batch, 1, 1, seq_len]
|
| 365 |
+
attn_mask = attn_mask.expand(-1, self.n_heads, seq_len, -1) # [batch, n_heads, q_len, k_len]
|
| 366 |
+
else:
|
| 367 |
+
attn_mask = None
|
| 368 |
+
|
| 369 |
+
attn_output = scaled_dot_product_attention(
|
| 370 |
+
q, k, v,
|
| 371 |
+
attn_mask=attn_mask,
|
| 372 |
+
dropout_p=self.attn_dropout_p,
|
| 373 |
+
is_causal=True
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
|
| 377 |
+
return self.resid_dropout(self.out_proj(attn_output))
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class MultiHeadCrossAttentionWithRoPE(nn.Module):
|
| 381 |
+
def __init__(self, d_model, n_heads, attn_dropout_p=0.0, resid_dropout=0.0):
|
| 382 |
+
super().__init__()
|
| 383 |
+
self.d_model = d_model
|
| 384 |
+
self.n_heads = n_heads
|
| 385 |
+
self.head_dim = d_model // n_heads
|
| 386 |
+
|
| 387 |
+
self.q_proj = nn.Linear(d_model, d_model)
|
| 388 |
+
self.k_proj = nn.Linear(d_model, d_model)
|
| 389 |
+
self.v_proj = nn.Linear(d_model, d_model)
|
| 390 |
+
self.out_proj = nn.Linear(d_model, d_model)
|
| 391 |
+
self.rotary = RotaryPositionalEmbedding(self.head_dim)
|
| 392 |
+
self.attn_dropout_p = attn_dropout_p
|
| 393 |
+
self.resid_dropout = nn.Dropout(resid_dropout)
|
| 394 |
+
|
| 395 |
+
def forward(self, query, key, value, key_padding_mask=None):
|
| 396 |
+
batch_size, q_len, _ = query.shape
|
| 397 |
+
_, seq_len, _ = key.shape
|
| 398 |
+
|
| 399 |
+
q = self.q_proj(query).view(batch_size, q_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 400 |
+
k = self.k_proj(key).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 401 |
+
v = self.v_proj(value).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
|
| 402 |
+
|
| 403 |
+
q, k = self.rotary(q, k)
|
| 404 |
+
|
| 405 |
+
if key_padding_mask is not None:
|
| 406 |
+
attn_mask = key_padding_mask.unsqueeze(1).unsqueeze(2)
|
| 407 |
+
attn_mask = attn_mask.expand(-1, self.n_heads, q_len, -1)
|
| 408 |
+
else:
|
| 409 |
+
attn_mask = None
|
| 410 |
+
|
| 411 |
+
is_causal_flag = self.training
|
| 412 |
+
|
| 413 |
+
attn_output = scaled_dot_product_attention(
|
| 414 |
+
q, k, v,
|
| 415 |
+
attn_mask=attn_mask,
|
| 416 |
+
dropout_p=self.attn_dropout_p,
|
| 417 |
+
is_causal=is_causal_flag
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, q_len, self.d_model)
|
| 421 |
+
return self.resid_dropout(self.out_proj(attn_output))
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class HierarchicalEmbedding(nn.Module):
|
| 425 |
+
def __init__(self, s1_bits, s2_bits, d_model=256):
|
| 426 |
+
super().__init__()
|
| 427 |
+
self.s1_bits = s1_bits
|
| 428 |
+
self.s2_bits = s2_bits
|
| 429 |
+
|
| 430 |
+
vocab_s1 = 2 ** s1_bits
|
| 431 |
+
vocab_s2 = 2 ** s2_bits
|
| 432 |
+
|
| 433 |
+
self.emb_s1 = nn.Embedding(vocab_s1, d_model)
|
| 434 |
+
self.emb_s2 = nn.Embedding(vocab_s2, d_model)
|
| 435 |
+
self.d_model = d_model
|
| 436 |
+
self.fusion_proj = nn.Linear(d_model * 2, d_model)
|
| 437 |
+
|
| 438 |
+
nn.init.normal_(self.emb_s1.weight, mean=0, std=d_model ** -0.5)
|
| 439 |
+
nn.init.normal_(self.emb_s2.weight, mean=0, std=d_model ** -0.5)
|
| 440 |
+
|
| 441 |
+
def forward(self, token_ids):
|
| 442 |
+
"""Inputs:
|
| 443 |
+
token_ids: [batch_size, seq_len] token ID
|
| 444 |
+
Output: [batch_size, seq_len, d_model]
|
| 445 |
+
"""
|
| 446 |
+
if isinstance(token_ids, tuple) or isinstance(token_ids, list):
|
| 447 |
+
s1_ids, s2_ids = token_ids
|
| 448 |
+
else:
|
| 449 |
+
s1_ids, s2_ids = self.split_token(token_ids, self.s2_bits)
|
| 450 |
+
s1_emb = self.emb_s1(s1_ids) * math.sqrt(self.d_model)
|
| 451 |
+
s2_emb = self.emb_s2(s2_ids) * math.sqrt(self.d_model)
|
| 452 |
+
return self.fusion_proj(torch.cat([s1_emb, s2_emb], dim=-1))
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class DependencyAwareLayer(nn.Module):
|
| 456 |
+
def __init__(self, d_model, n_heads=4, attn_dropout_p=0.0, resid_dropout=0.0):
|
| 457 |
+
super().__init__()
|
| 458 |
+
self.cross_attn = MultiHeadCrossAttentionWithRoPE(d_model, n_heads, attn_dropout_p, resid_dropout)
|
| 459 |
+
self.norm = RMSNorm(d_model)
|
| 460 |
+
|
| 461 |
+
def forward(self, hidden_states, sibling_embed, key_padding_mask=None):
|
| 462 |
+
"""hidden_states: [batch, seq_len, d_model]
|
| 463 |
+
sibling_embed: Embedding from another subtoken
|
| 464 |
+
"""
|
| 465 |
+
attn_out = self.cross_attn(
|
| 466 |
+
query=sibling_embed,
|
| 467 |
+
key=hidden_states,
|
| 468 |
+
value=hidden_states,
|
| 469 |
+
key_padding_mask=key_padding_mask
|
| 470 |
+
)
|
| 471 |
+
return self.norm(hidden_states + attn_out)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
class TransformerBlock(nn.Module):
|
| 475 |
+
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):
|
| 476 |
+
super().__init__()
|
| 477 |
+
self.norm1 = RMSNorm(d_model)
|
| 478 |
+
self.self_attn = MultiHeadAttentionWithRoPE(d_model, n_heads, attn_dropout_p, resid_dropout_p)
|
| 479 |
+
self.norm2 = RMSNorm(d_model)
|
| 480 |
+
self.ffn = FeedForward(d_model, ff_dim, ffn_dropout_p)
|
| 481 |
+
|
| 482 |
+
def forward(self, x, key_padding_mask=None):
|
| 483 |
+
residual = x
|
| 484 |
+
x = self.norm1(x)
|
| 485 |
+
attn_out = self.self_attn(x, key_padding_mask=key_padding_mask)
|
| 486 |
+
x = residual + attn_out
|
| 487 |
+
|
| 488 |
+
residual = x
|
| 489 |
+
x = self.norm2(x)
|
| 490 |
+
ffn_out = self.ffn(x)
|
| 491 |
+
x = residual + ffn_out
|
| 492 |
+
return x
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class DualHead(nn.Module):
|
| 496 |
+
def __init__(self, s1_bits, s2_bits, d_model):
|
| 497 |
+
super().__init__()
|
| 498 |
+
self.vocab_s1 = 2 ** s1_bits
|
| 499 |
+
self.vocab_s2 = 2 ** s2_bits
|
| 500 |
+
self.proj_s1 = nn.Linear(d_model, self.vocab_s1)
|
| 501 |
+
self.proj_s2 = nn.Linear(d_model, self.vocab_s2)
|
| 502 |
+
|
| 503 |
+
def compute_loss(self, s1_logits, s2_logits, s1_targets, s2_targets, padding_mask=None):
|
| 504 |
+
if padding_mask is not None:
|
| 505 |
+
valid_mask = (padding_mask == 0)
|
| 506 |
+
s1_logits = s1_logits[valid_mask]
|
| 507 |
+
s2_logits = s2_logits[valid_mask]
|
| 508 |
+
s1_targets = s1_targets[valid_mask]
|
| 509 |
+
s2_targets = s2_targets[valid_mask]
|
| 510 |
+
ce_s1 = F.cross_entropy(s1_logits, s1_targets)
|
| 511 |
+
ce_s2 = F.cross_entropy(s2_logits, s2_targets)
|
| 512 |
+
else:
|
| 513 |
+
ce_s1 = F.cross_entropy(s1_logits.reshape(-1, self.vocab_s1), s1_targets.reshape(-1))
|
| 514 |
+
ce_s2 = F.cross_entropy(s2_logits.reshape(-1, self.vocab_s2), s2_targets.reshape(-1))
|
| 515 |
+
ce_loss = (ce_s1 + ce_s2) / 2
|
| 516 |
+
return ce_loss, ce_s1, ce_s2
|
| 517 |
+
|
| 518 |
+
def forward(self, x):
|
| 519 |
+
return self.proj_s1(x)
|
| 520 |
+
|
| 521 |
+
def cond_forward(self, x2):
|
| 522 |
+
return self.proj_s2(x2)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
class FixedEmbedding(nn.Module):
|
| 526 |
+
def __init__(self, c_in, d_model):
|
| 527 |
+
super(FixedEmbedding, self).__init__()
|
| 528 |
+
|
| 529 |
+
w = torch.zeros(c_in, d_model).float()
|
| 530 |
+
w.require_grad = False
|
| 531 |
+
|
| 532 |
+
position = torch.arange(0, c_in).float().unsqueeze(1)
|
| 533 |
+
div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()
|
| 534 |
+
|
| 535 |
+
w[:, 0::2] = torch.sin(position * div_term)
|
| 536 |
+
w[:, 1::2] = torch.cos(position * div_term)
|
| 537 |
+
|
| 538 |
+
self.emb = nn.Embedding(c_in, d_model)
|
| 539 |
+
self.emb.weight = nn.Parameter(w, requires_grad=False)
|
| 540 |
+
|
| 541 |
+
def forward(self, x):
|
| 542 |
+
return self.emb(x).detach()
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
class TemporalEmbedding(nn.Module):
|
| 546 |
+
def __init__(self, d_model, learn_pe):
|
| 547 |
+
super(TemporalEmbedding, self).__init__()
|
| 548 |
+
|
| 549 |
+
minute_size = 60
|
| 550 |
+
hour_size = 24
|
| 551 |
+
weekday_size = 7
|
| 552 |
+
day_size = 32
|
| 553 |
+
month_size = 13
|
| 554 |
+
|
| 555 |
+
Embed = FixedEmbedding if not learn_pe else nn.Embedding
|
| 556 |
+
self.minute_embed = Embed(minute_size, d_model)
|
| 557 |
+
self.hour_embed = Embed(hour_size, d_model)
|
| 558 |
+
self.weekday_embed = Embed(weekday_size, d_model)
|
| 559 |
+
self.day_embed = Embed(day_size, d_model)
|
| 560 |
+
self.month_embed = Embed(month_size, d_model)
|
| 561 |
+
|
| 562 |
+
def forward(self, x):
|
| 563 |
+
x = x.long()
|
| 564 |
+
|
| 565 |
+
minute_x = self.minute_embed(x[:, :, 0])
|
| 566 |
+
hour_x = self.hour_embed(x[:, :, 1])
|
| 567 |
+
weekday_x = self.weekday_embed(x[:, :, 2])
|
| 568 |
+
day_x = self.day_embed(x[:, :, 3])
|
| 569 |
+
month_x = self.month_embed(x[:, :, 4])
|
| 570 |
+
|
| 571 |
+
return hour_x + weekday_x + day_x + month_x + minute_x
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
|
payload.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"model_key": "kronos-mini"}
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
pandas
|
| 3 |
+
huggingface_hub
|
| 4 |
+
transformers
|
| 5 |
+
torch
|
| 6 |
+
gunicorn
|
test_data.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"k_lines": [
|
| 3 |
+
[1711324800000, "18.545", "19.514", "18.385", "19.395", "2080487", 1711411199999, "1092736.30112304", 59329, "1007730", "529389.05883658", "0"],
|
| 4 |
+
[1711411200000, "19.397", "20.759", "19.356", "20.032", "3020519", 1711497599999, "1502245.89655719", 77276, "1422706", "707574.10254861", "0"],
|
| 5 |
+
[1711497600000, "20.030", "20.211", "19.011", "19.303", "2351359", 1711583999999, "1205611.99079432", 70060, "1150003", "589583.26387940", "0"],
|
| 6 |
+
[1711584000000, "19.310", "19.842", "19.061", "19.174", "1498684", 1711670399999, "772148.06325709", 42672, "730820", "376522.82105490", "0"],
|
| 7 |
+
[1711670400000, "19.176", "19.317", "18.731", "18.997", "1276366", 1711756799999, "672331.34540941", 39575, "576711", "303861.73102728", "0"],
|
| 8 |
+
[1711756800000, "18.997", "19.322", "18.818", "18.962", "1277625", 1711843199999, "669849.29994672", 37466, "570865", "299380.69307957", "0"],
|
| 9 |
+
[1711843200000, "18.961", "19.387", "18.900", "19.197", "673959", 1711929599999, "352343.27851097", 22935, "345672", "180770.39994390", "0"],
|
| 10 |
+
[1711929600000, "19.198", "19.310", "17.865", "18.382", "2094936", 1712015999999, "1136096.28613666", 65345, "935722", "507815.72222223", "0"],
|
| 11 |
+
[1712016000000, "18.383", "18.508", "17.400", "17.976", "2847065", 1712102399999, "1588776.10375730", 92088, "1298542", "724052.81684420", "0"],
|
| 12 |
+
[1712102400000, "17.977", "18.359", "17.405", "17.712", "1464834", 1712188799999, "818927.47579969", 53296, "678165", "378712.54514030", "0"]
|
| 13 |
+
],
|
| 14 |
+
"prediction_params": {
|
| 15 |
+
"pred_len": 12
|
| 16 |
+
}
|
| 17 |
+
}
|