a12354 commited on
Commit
f48983a
·
verified ·
1 Parent(s): 789a3a2

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .gitignore +199 -0
  2. LICENSE +21 -0
  3. README.md +111 -0
  4. accelerate_config.yaml +17 -0
  5. accelerate_config_2gpu.yaml +17 -0
  6. accelerate_config_fp16.yaml +17 -0
  7. accelerate_config_gpu1.yaml +17 -0
  8. inference.py +344 -0
  9. inference_rats40k.py +345 -0
  10. inference_tsqa.py +259 -0
  11. infra.bash +1 -0
  12. metrics_eval_20260413_162434.txt +1 -0
  13. metrics_eval_20260606_080757.txt +1 -0
  14. metrics_eval_20260606_234456.txt +1 -0
  15. output_result_all.json +0 -0
  16. random_stage_inference_demo.py +215 -0
  17. requirements.txt +20 -0
  18. swanlog/.gitignore +1 -0
  19. swanlog/run-20260413_125210-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json +1 -0
  20. swanlog/run-20260413_131247-d7ug5qigf62md7jitkhbb/files/config.yaml +1 -0
  21. swanlog/run-20260413_131247-d7ug5qigf62md7jitkhbb/files/requirements.txt +98 -0
  22. swanlog/run-20260413_133130-8ganaif5wa9up9bvv8bxq/backup.swanlab +0 -0
  23. swanlog/run-20260413_133130-8ganaif5wa9up9bvv8bxq/files/config.yaml +1 -0
  24. swanlog/run-20260413_133130-8ganaif5wa9up9bvv8bxq/files/requirements.txt +98 -0
  25. swanlog/run-20260413_133536-creh19v03ah9ycywkyfx0/files/config.yaml +1 -0
  26. swanlog/run-20260413_133536-creh19v03ah9ycywkyfx0/files/requirements.txt +98 -0
  27. swanlog/run-20260413_133536-creh19v03ah9ycywkyfx0/files/swanlab-metadata.json +1 -0
  28. swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/backup.swanlab +0 -0
  29. swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/files/config.yaml +1 -0
  30. swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/files/requirements.txt +98 -0
  31. swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json +1 -0
  32. swanlog/run-20260413_135748-d7ug5qigf62md7jitkhbb/files/config.yaml +1 -0
  33. swanlog/run-20260413_135748-d7ug5qigf62md7jitkhbb/files/requirements.txt +386 -0
  34. swanlog/run-20260413_135748-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json +1 -0
  35. swanlog/run-20260413_140242-d7ug5qigf62md7jitkhbb/files/config.yaml +1 -0
  36. swanlog/run-20260413_140242-d7ug5qigf62md7jitkhbb/files/requirements.txt +386 -0
  37. swanlog/run-20260413_140242-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json +1 -0
  38. train_pretrain.py +102 -0
  39. train_pretrain_rats40k.py +108 -0
  40. train_sft.py +173 -0
  41. train_sft_rats40k.py +189 -0
  42. train_sft_tsqa.py +225 -0
  43. utils/__init__.py +0 -0
  44. utils/accelerate_compat.py +30 -0
  45. utils/dist_util.py +45 -0
  46. utils/gradio_vlm.py +77 -0
  47. utils/log_util.py +64 -0
  48. utils/metrics.py +172 -0
  49. utils/position_coding.py +200 -0
  50. yaml/infer.yaml +22 -0
.gitignore ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Abstra
171
+ # Abstra is an AI-powered process automation framework.
172
+ # Ignore directories containing user credentials, local state, and settings.
173
+ # Learn more at https://abstra.io/docs
174
+ .abstra/
175
+
176
+ # Visual Studio Code
177
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
178
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
179
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
180
+ # you could uncomment the following to ignore the enitre vscode folder
181
+ # .vscode/
182
+
183
+ # Ruff stuff:
184
+ .ruff_cache/
185
+
186
+ # PyPI configuration file
187
+ .pypirc
188
+
189
+ # Cursor
190
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
191
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
192
+ # refer to https://docs.cursor.com/context/ignore-files
193
+ .cursorignore
194
+ .cursorindexingignore
195
+
196
+ /LLM/*
197
+
198
+ /save/*
199
+ *.txt
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 王艺霖
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ITFormer
2
+
3
+ This repository provides the official open-source implementation of ITFormer (Instruct Time Transformer), a novel framework for temporal-textual multimodal question answering (QA).
4
+
5
+ ## Overview
6
+
7
+ ITFormer (Instruct Time Transformer) is a state-of-the-art model for temporal-textual multimodal question answering. This repository provides the official open-source implementation with inference and training scripts.
8
+
9
+ Our work introduces a large-scale multitask dataset (EngineMT-QA) and demonstrates ITFormer's superior performance in bridging time series data with natural language understanding. Remarkably, our 0.5B model is lightweight and efficient while achieving strong performance.
10
+
11
+ ## Features
12
+
13
+ - 📊 **Pre-trained Models**: Ready-to-use ITFormer models (0.5B, 3B, 7B) available on Hugging Face.
14
+ - 🚀 **Lightweight & Efficient**: The 0.5B model offers strong temporal QA capabilities and easy deployment.
15
+ - 🎯 **One-Click Scripts**: Automated scripts for pre-training, SFT, and parallel inference.
16
+ - 📈 **High Performance**: State-of-the-art results on temporal-textual QA benchmarks.
17
+ - 🌐 **Distributed Support**: Fully compatible with `accelerate` for multi-GPU training and inference.
18
+
19
+ ## Quick Start
20
+
21
+ ### 1. Organize Directory Structure
22
+
23
+ After downloading models and datasets, organize your files as follows:
24
+
25
+ <pre>
26
+ ITFormer-ICML25/
27
+ ├── dataset/
28
+ │ └── datasets/ # Place EngineMT-QA dataset files here
29
+ │ ├── time_series_data.h5
30
+ │ ├── train_qa.jsonl
31
+ │ └── test_qa.jsonl
32
+ ├── LLM/ # Base Qwen2.5-Instruct models
33
+ ├── checkpoints/
34
+ │ └── ITFormer-0.5B/ # ITFormer model checkpoints
35
+ ├── scripts/ # One-click automation scripts
36
+ │ ├── run_pretrain.sh
37
+ │ ├── run_sft.sh
38
+ │ └── run_inference.sh
39
+ ├── accelerate_config.yaml # Configuration for distributed execution
40
+ └── yaml/
41
+ └── infer.yaml # Inference configuration
42
+ </pre>
43
+
44
+ ### 2. Run Inference
45
+
46
+ We now support **parallel inference** using `accelerate`. This automatically aggregates results from multiple GPUs.
47
+
48
+ ```bash
49
+ # Using the automated script (Recommended)
50
+ bash scripts/run_inference.sh
51
+
52
+ # Or launch manually via accelerate
53
+ accelerate launch --config_file accelerate_config.yaml inference.py --config yaml/infer.yaml
54
+ ```
55
+
56
+ The inference script will:
57
+ - Load ITFormer and the corresponding Qwen2.5-Instruct.
58
+ - Distribute data across all available GPUs.
59
+ - Aggregate and save results to `inference_results/` and `output_result_all.json`.
60
+
61
+ ---
62
+
63
+ ## Training
64
+
65
+ We provide a streamlined training pipeline using `accelerate`. Ensure your `accelerate_config.yaml` is properly configured for your hardware.
66
+
67
+ ### A. Pre-training (Time-Series Encoder)
68
+
69
+ Stage A focuses on pre-training the `TimeSeriesEncoder` using masked modeling.
70
+
71
+ ```bash
72
+ # One-click pre-training
73
+ bash scripts/run_pretrain.sh
74
+ ```
75
+
76
+ ### B. Supervised Fine-Tuning (SFT)
77
+
78
+ Stage B performs end-to-end SFT, bridging the time-series encoder with the LLM via ITFormer.
79
+
80
+ ```bash
81
+ # One-click SFT (Requires pre-trained ts_encoder weights)
82
+ bash scripts/run_sft.sh
83
+ ```
84
+
85
+ **Key Parameters in SFT:**
86
+ - `--it_d_model`, `--it_n_heads`, `--it_layers`: Configuration for the ITFormer module.
87
+ - `--load_ts_encoder`: Path to the weights generated in Stage A.
88
+ - `--llm_model_path`: Path to the base Qwen2.5-Instruct model.
89
+
90
+ ---
91
+
92
+ ## Model Architecture
93
+
94
+ ITFormer leverages an **Instruction-aware Time Series Transformer** to align temporal features with textual queries before feeding them into a Large Language Model. The framework is designed to be parameter-efficient, freezing the LLM and TS Encoder during SFT while training only the ITFormer and projection layers.
95
+
96
+ ## Citation
97
+
98
+ If you use this code in your research, please cite:
99
+
100
+ ```bibtex
101
+ @inproceedings{wang2025itformer,
102
+ title={ITFormer: Bridging Time Series and Natural Language for Multi-Modal QA with Large-Scale Multitask Dataset},
103
+ author={Yilin Wang and Peixuan Lei and Jie Song and Yuzhe Hao and Tao Chen and Yuxuan Zhang and Lei Jia and Yuanxiang Li and Zhongyu Wei},
104
+ booktitle={International Conference on Machine Learning (ICML)},
105
+ year={2025}
106
+ }
107
+ ```
108
+
109
+ ## License
110
+
111
+ MIT License — see the LICENSE file for details.
accelerate_config.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ deepspeed_config: {}
3
+ distributed_type: MULTI_GPU
4
+ fsdp_config: {}
5
+ gpu_ids: all
6
+ machine_rank: 0
7
+ main_process_ip: null
8
+ main_process_port: null
9
+ main_training_function: main
10
+ mixed_precision: bf16
11
+ num_machines: 1
12
+ num_processes: 4
13
+ rdzv_backend: static
14
+ same_network: true
15
+ tpu_name: null
16
+ tpu_zone: null
17
+ use_cpu: false
accelerate_config_2gpu.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ deepspeed_config: {}
3
+ distributed_type: MULTI_GPU
4
+ fsdp_config: {}
5
+ gpu_ids: all
6
+ machine_rank: 0
7
+ main_process_ip: null
8
+ main_process_port: null
9
+ main_training_function: main
10
+ mixed_precision: bf16
11
+ num_machines: 1
12
+ num_processes: 2
13
+ rdzv_backend: static
14
+ same_network: true
15
+ tpu_name: null
16
+ tpu_zone: null
17
+ use_cpu: false
accelerate_config_fp16.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ deepspeed_config: {}
3
+ distributed_type: MULTI_GPU
4
+ fsdp_config: {}
5
+ gpu_ids: all
6
+ machine_rank: 0
7
+ main_process_ip: null
8
+ main_process_port: null
9
+ main_training_function: main
10
+ mixed_precision: fp16
11
+ num_machines: 1
12
+ num_processes: 4
13
+ rdzv_backend: static
14
+ same_network: true
15
+ tpu_name: null
16
+ tpu_zone: null
17
+ use_cpu: false
accelerate_config_gpu1.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: 'NO'
4
+ downcast_bf16: 'no'
5
+ enable_cpu_affinity: false
6
+ gpu_ids: '1'
7
+ machine_rank: 0
8
+ main_training_function: main
9
+ mixed_precision: bf16
10
+ num_machines: 1
11
+ num_processes: 1
12
+ rdzv_backend: static
13
+ same_network: true
14
+ tpu_env: []
15
+ tpu_use_cluster: false
16
+ tpu_use_sudo: false
17
+ use_cpu: false
inference.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Inference script for Time Language Model (TLM).
5
+ Performs inference on the test set and saves results and evaluation metrics.
6
+ """
7
+ import os
8
+ import yaml
9
+ import json
10
+ import warnings
11
+ warnings.filterwarnings("ignore", category=FutureWarning, message=".*TRANSFORMERS_CACHE.*")
12
+ import argparse
13
+ import random
14
+ import logging
15
+ from transformers.utils import logging as transformers_logging
16
+ import numpy as np
17
+ import torch
18
+ from transformers import AutoTokenizer, AutoProcessor
19
+ from dataset.dataset import TsQaDataset, DataCollator
20
+ from models.TimeLanguageModel import TLM
21
+ from datetime import datetime
22
+ from tqdm import tqdm
23
+ from torch.utils.data import DataLoader
24
+ from utils.metrics import open_question_metrics, closed_question_metrics
25
+ from typing import List, Dict, Any
26
+ from accelerate import Accelerator
27
+
28
+ def set_seed(seed=42):
29
+ """Set random seed for reproducibility."""
30
+ random.seed(seed)
31
+ np.random.seed(seed)
32
+ torch.manual_seed(seed)
33
+ torch.cuda.manual_seed(seed)
34
+ torch.cuda.manual_seed_all(seed)
35
+
36
+ def save_results(results, output_dir, config_name):
37
+ """Save inference results to a JSON file."""
38
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
39
+ filename = f"inference_results_{config_name}_{timestamp}.json"
40
+ os.makedirs(output_dir, exist_ok=True)
41
+ filepath = os.path.join(output_dir, filename)
42
+ with open(filepath, 'w', encoding='utf-8') as f:
43
+ json.dump(results, f, indent=4, ensure_ascii=False)
44
+ print(f"\n✅ Inference results saved to: {filepath}")
45
+
46
+ def count_model_parameters(model):
47
+ """Count the number of parameters in each model component (in millions)."""
48
+ def count_params(module):
49
+ if module is None:
50
+ return 0
51
+ return sum(p.numel() for p in module.parameters())
52
+ llm_params = count_params(model.llm_model) / 1e6
53
+ itformer_params = count_params(model.itformer) / 1e6
54
+ ts_encoder_params = count_params(model.ts_encoder) / 1e6
55
+ total_params = count_params(model) / 1e6
56
+ return {
57
+ 'llm': llm_params,
58
+ 'itformer': itformer_params,
59
+ 'ts_encoder': ts_encoder_params,
60
+ 'total': total_params
61
+ }
62
+
63
+ def main_inference(args):
64
+ """Main inference pipeline."""
65
+ # Initialize accelerator
66
+ accelerator = Accelerator()
67
+
68
+ # 设置日志级别,主进程显示进度,从进程静默
69
+ if accelerator.is_local_main_process:
70
+ transformers_logging.set_verbosity_info()
71
+ else:
72
+ transformers_logging.set_verbosity_error()
73
+ logging.disable(logging.CRITICAL)
74
+
75
+ set_seed(args.seed)
76
+ # Print only in the main process
77
+ if accelerator.is_main_process:
78
+ print("🚀 Starting inference process...")
79
+ print(f"🔧 Using config file: {args.config}")
80
+ print(f"💾 Results will be saved to: {args.output_dir}")
81
+ # Load config
82
+ with open(args.config, 'r') as f:
83
+ config = yaml.safe_load(f)
84
+ args.__dict__.update(config)
85
+ if accelerator.is_main_process:
86
+ print("\n⚙️ Loading model from checkpoint...")
87
+ # Import TLMConfig
88
+ from models.TimeLanguageModel import TLMConfig
89
+
90
+ # Determine LLM model path based on ITFormer model size
91
+ if '0.5B' in args.model_checkpoint:
92
+ llm_model_path = 'LLM/Qwen2.5-0.5B-Instruct'
93
+ elif '3B' in args.model_checkpoint:
94
+ llm_model_path = 'LLM/Qwen2.5-3B-Instruct'
95
+ elif '7B' in args.model_checkpoint:
96
+ llm_model_path = 'LLM/Qwen2.5-7B-Instruct'
97
+ else:
98
+ # Default to 7B if size cannot be determined
99
+ llm_model_path = 'LLM/Qwen2.5-7B-Instruct'
100
+
101
+ # 将推断出的 llm_model_path 存入 args,防止后续 compute_metrics_from_results 报错
102
+ args.llm_model_path = llm_model_path
103
+
104
+ if accelerator.is_main_process:
105
+ print(f"🔗 Using LLM model: {llm_model_path}")
106
+
107
+ # Create TLMConfig
108
+ tlm_config = TLMConfig(
109
+ llm_model_path=llm_model_path,
110
+ freeze_ts_model=True,
111
+ ts_pad_num=args.prefix_num,
112
+ # 显式补全 ITFormer 和 TS Encoder 需要的字段名
113
+ prefix_num=args.prefix_num,
114
+ it_d_model=config.get('it_d_model', 896),
115
+ it_n_heads=config.get('it_n_heads', 16),
116
+ it_layers=config.get('it_layers', 2),
117
+ it_dropout=config.get('it_dropout', 0.1),
118
+ adapter_type=config.get('adapter_type', 'itformer'),
119
+ dropout=config.get('dropout', 0.1),
120
+ d_model=config.get('d_model', 512),
121
+ n_heads=config.get('n_heads', 8),
122
+ e_layers=config.get('e_layers', 4),
123
+ patch_len=config.get('patch_len', 60),
124
+ stride=config.get('stride', 60),
125
+ input_len=config.get('input_len', 600),
126
+ )
127
+
128
+ # Load model - let from_pretrained handle configuration loading
129
+ from models.TimeLanguageModel import TLM
130
+ model = TLM.from_pretrained(args.model_checkpoint, config=tlm_config, ts_config=tlm_config)
131
+ # Print model parameter statistics only in the main process
132
+ if accelerator.is_main_process:
133
+ param_counts = count_model_parameters(model)
134
+ print(f"\n🔢 Model parameter counts (in M):")
135
+ print(f" LLM: {param_counts['llm']:.2f}M")
136
+ print(f" ITFormer: {param_counts['itformer']:.2f}M")
137
+ print(f" TS_Encoder: {param_counts['ts_encoder']:.2f}M")
138
+ print(f" Total: {param_counts['total']:.2f}M")
139
+ # Prepare model with accelerator
140
+ model = accelerator.prepare(model)
141
+ model.eval()
142
+ if accelerator.is_main_process:
143
+ print(f"✅ Model loaded successfully!")
144
+ print("\n📊 Preparing test dataset...")
145
+ # Load tokenizer
146
+ if os.path.exists(os.path.join(args.model_checkpoint, "tokenizer.json")):
147
+ if accelerator.is_main_process:
148
+ print("Loading tokenizer from checkpoint")
149
+ tokenizer = AutoTokenizer.from_pretrained(args.model_checkpoint)
150
+ else:
151
+ if accelerator.is_main_process:
152
+ print("Loading tokenizer from original model")
153
+ tokenizer = model.tokenizer
154
+ # Add special token if not present
155
+ if '<|image_pad|>' not in tokenizer.get_vocab():
156
+ if accelerator.is_main_process:
157
+ print("Adding <|image_pad|> token to tokenizer")
158
+ tokenizer.add_tokens(['<|image_pad|>'])
159
+ model.llm_model.resize_token_embeddings(len(tokenizer))
160
+ tokenizer.padding_side = 'left'
161
+ # Simple config for dataset
162
+ class SimpleConfig:
163
+ def __init__(self, **kwargs):
164
+ for key, value in kwargs.items():
165
+ setattr(self, key, value)
166
+ tlmconfig = SimpleConfig(ts_pad_num=args.prefix_num)
167
+ test_dataset = TsQaDataset(
168
+ args.ts_path_test,
169
+ args.qa_path_test,
170
+ tokenizer,
171
+ tokenizer, # Use tokenizer as processor
172
+ tlmconfig
173
+ )
174
+ data_collator = DataCollator(tokenizer=tokenizer)
175
+ test_loader = DataLoader(
176
+ test_dataset,
177
+ batch_size=args.batch_size,
178
+ collate_fn=data_collator,
179
+ num_workers=args.num_workers
180
+ )
181
+ # Prepare dataloader with accelerator
182
+ test_loader = accelerator.prepare(test_loader)
183
+ if accelerator.is_main_process:
184
+ print(f"📁 Test set size: {len(test_dataset)} samples")
185
+ print(f"🔢 Batch size: {args.batch_size}, Total batches: {len(test_loader)}")
186
+ print("\n🔍 Starting test set inference...")
187
+ results = []
188
+ with torch.no_grad():
189
+ # Show progress bar only in the main process
190
+ if accelerator.is_main_process:
191
+ batch_iterator = tqdm(test_loader, desc="Inference progress")
192
+ else:
193
+ batch_iterator = test_loader
194
+ for batch_idx, batch in enumerate(batch_iterator):
195
+ # if batch_idx ==16:
196
+ # break
197
+ # Data is already on the correct device thanks to accelerator
198
+
199
+ # 使用 unwrap_model 来调用原始模型的 generate 方法
200
+ unwrapped_model = accelerator.unwrap_model(model)
201
+ generated_ids = unwrapped_model.generate(
202
+ input_ids=batch['input_ids'],
203
+ query_ids=batch['query_ids'],
204
+ ts_values=batch['ts_values'],
205
+ stage=batch['stage'],
206
+ attention_mask=batch['attention_mask'],
207
+ max_new_tokens=args.max_new_tokens,
208
+ do_sample=False,
209
+ eos_token_id=tokenizer.eos_token_id,
210
+ pad_token_id=tokenizer.pad_token_id,
211
+ use_cache=True,
212
+ # Optimization parameters, consistent with Time-QA
213
+ num_beams=1, # Greedy search, fastest
214
+ temperature=1.0, # Avoid extra computation
215
+ top_p=None, # Disable nucleus sampling
216
+ top_k=None, # Disable top-k sampling
217
+ repetition_penalty=1.0, # Disable repetition penalty
218
+ length_penalty=1.0, # Disable length penalty
219
+ no_repeat_ngram_size=0, # Disable n-gram repetition check
220
+ output_scores=False, # Do not output scores
221
+ output_attentions=False, # Do not output attention
222
+ output_hidden_states=False, # Do not output hidden states
223
+ return_dict_in_generate=False, # Simplify return format
224
+ )
225
+ batch_predictions = tokenizer.batch_decode(
226
+ generated_ids,
227
+ skip_special_tokens=True
228
+ )
229
+ batch_labels = tokenizer.batch_decode(
230
+ batch['labels'],
231
+ skip_special_tokens=True
232
+ )
233
+ for i in range(len(batch_predictions)):
234
+ prediction = batch_predictions[i].split('assistant\n')[-1]
235
+ results.append({
236
+ "index": batch['index'][i].item(),
237
+ "stage": batch['stage'][i].item(),
238
+ "input": tokenizer.decode(batch['input_ids'][i], skip_special_tokens=True),
239
+ "prediction": prediction,
240
+ "label": batch_labels[i],
241
+ "is_correct": prediction.strip() == batch_labels[i].strip()
242
+ })
243
+ if accelerator.is_main_process:
244
+ print("\n📊 Calculating evaluation metrics...")
245
+
246
+ # 汇总所有进程的结果
247
+ all_results = [None] * accelerator.num_processes
248
+ # 使用 gather_object 汇总 list
249
+ import torch.distributed as dist
250
+ if dist.is_initialized():
251
+ dist.all_gather_object(all_results, results)
252
+ # 将嵌套列表打平
253
+ results = [item for sublist in all_results for item in sublist]
254
+
255
+ if accelerator.is_main_process:
256
+ # 去重(防止分布式采样导致的重复数据)
257
+ seen_indices = set()
258
+ unique_results = []
259
+ for r in results:
260
+ if r['index'] not in seen_indices:
261
+ unique_results.append(r)
262
+ seen_indices.add(r['index'])
263
+ results = sorted(unique_results, key=lambda x: x['index'])
264
+
265
+ metrics = compute_metrics_from_results(results, args)
266
+ print_metrics(metrics)
267
+ config_base = os.path.basename(args.config).split('.yaml')[0]
268
+ save_results(results, args.output_dir, config_base)
269
+ save_metrics(metrics, args.output_dir, config_base)
270
+
271
+ def compute_metrics_from_results(results: List[Dict],args) -> Dict[str, Any]:
272
+ """Compute evaluation metrics for each stage from inference results."""
273
+ stage1_data = [r for r in results if r['stage'] == 1]
274
+ stage2_data = [r for r in results if r['stage'] == 2]
275
+ stage3_data = [r for r in results if r['stage'] == 3]
276
+ stage4_data = [r for r in results if r['stage'] == 4]
277
+ # Create special_id, consistent with Time-QA
278
+ from transformers import AutoTokenizer
279
+ # 为了和设置的模型对齐,tokenizer应与主模型保持一致
280
+ tokenizer = AutoTokenizer.from_pretrained(args.llm_model_path)
281
+ special_id = tokenizer.all_special_ids
282
+ common_punctuations = [".", ",", ":", ";", "!", "?", "(", ")", "[", "]", "{", "}", "-", "_", "\"", "'"]
283
+ punctuation_ids = tokenizer.convert_tokens_to_ids(common_punctuations)
284
+ special_id.extend(punctuation_ids)
285
+ metrics = {}
286
+ if stage1_data:
287
+ stage1_metrics = open_question_metrics(
288
+ [r['prediction'] for r in stage1_data],
289
+ [r['label'] for r in stage1_data],
290
+ special_id
291
+ )
292
+ metrics.update({f"stage1_{k}": v for k, v in stage1_metrics.items()})
293
+ if stage2_data:
294
+ stage2_metrics = closed_question_metrics(
295
+ [r['prediction'] for r in stage2_data],
296
+ [r['label'] for r in stage2_data],
297
+ special_id
298
+ )
299
+ metrics.update({f"stage2_{k}": v for k, v in stage2_metrics.items()})
300
+ if stage3_data:
301
+ stage3_metrics = closed_question_metrics(
302
+ [r['prediction'] for r in stage3_data],
303
+ [r['label'] for r in stage3_data],
304
+ special_id
305
+ )
306
+ metrics.update({f"stage3_{k}": v for k, v in stage3_metrics.items()})
307
+ if stage4_data:
308
+ stage4_metrics = open_question_metrics(
309
+ [r['prediction'] for r in stage4_data],
310
+ [r['label'] for r in stage4_data],
311
+ special_id
312
+ )
313
+ metrics.update({f"stage4_{k}": v for k, v in stage4_metrics.items()})
314
+ return metrics
315
+
316
+ def print_metrics(metrics: Dict[str, Any]):
317
+ """Print evaluation metrics for each stage."""
318
+ print("\n📈 Evaluation results:")
319
+ for stage in [1, 2, 3, 4]:
320
+ stage_metrics = {k.replace(f"stage{stage}_", ""): v
321
+ for k, v in metrics.items() if k.startswith(f"stage{stage}_")}
322
+ if stage_metrics:
323
+ print(f"\n🔹 Stage {stage} metrics:")
324
+ for metric, value in stage_metrics.items():
325
+ print(f" {metric}: {value:.4f}")
326
+
327
+ def save_metrics(metrics: Dict[str, Any], output_dir: str, config_base: str):
328
+ """Save evaluation metrics to a JSON file."""
329
+ metrics_file = os.path.join(output_dir, f"{config_base}_metrics.json")
330
+ with open(metrics_file, 'w', encoding='utf-8') as f:
331
+ json.dump(metrics, f, indent=2, ensure_ascii=False)
332
+ print(f"\n💾 Evaluation metrics saved to: {metrics_file}")
333
+
334
+ if __name__ == '__main__':
335
+ parser = argparse.ArgumentParser(description='TLM Inference')
336
+ parser.add_argument('--config', type=str, default='yaml/infer.yaml', help='YAML config file')
337
+ parser.add_argument('--output_dir', type=str, default='inference_results', help='Output directory')
338
+ parser.add_argument('--model_checkpoint', type=str, default='checkpoints/ITFormer-0.5B', help='Model checkpoint path')
339
+ parser.add_argument('--seed', type=int, default=42, help='Random seed')
340
+ parser.add_argument('--batch_size', type=int, default=12, help='Batch size')
341
+ parser.add_argument('--num_workers', type=int, default=4, help='Number of workers')
342
+ parser.add_argument('--max_new_tokens', type=int, default=128, help='Maximum new tokens to generate')
343
+ args = parser.parse_args()
344
+ main_inference(args)
inference_rats40k.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference & evaluation on RATs40K univariate test split.
3
+
4
+ Metrics computed:
5
+ - binary_accuracy / binary_f1_macro (Normal vs. Anomaly)
6
+ - type_accuracy / type_f1_macro (14-class fine-grained)
7
+ - thought_rouge_l / thought_bleu (reasoning quality)
8
+ """
9
+ import os
10
+ import json
11
+ import logging
12
+ import warnings
13
+ import argparse
14
+ import random
15
+ from contextlib import nullcontext
16
+ from datetime import datetime
17
+ from typing import Dict, List, Any, Optional
18
+
19
+ warnings.filterwarnings("ignore", category=FutureWarning)
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch.utils.data import DataLoader
24
+ from tqdm import tqdm
25
+ from transformers import AutoTokenizer
26
+ from transformers.utils import logging as transformers_logging
27
+ from accelerate import Accelerator
28
+ import torch.distributed as dist
29
+
30
+ from models.TimeLanguageModel import TLM, TLMConfig
31
+ from dataset.rats40k_dataset import (
32
+ RATsQADataset,
33
+ RATsDataCollator,
34
+ ACTION_ID_MAP,
35
+ parse_action_from_response,
36
+ parse_thought_from_response,
37
+ )
38
+ from utils.accelerate_compat import patch_accelerate_unwrap_model as patch_accelerate_compat
39
+
40
+ try:
41
+ from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
42
+ _SKL = True
43
+ except ImportError:
44
+ _SKL = False
45
+
46
+ try:
47
+ from rouge_score import rouge_scorer as _rs_mod
48
+ _ROUGE = True
49
+ except ImportError:
50
+ _ROUGE = False
51
+
52
+ try:
53
+ from nltk.translate.bleu_score import SmoothingFunction, corpus_bleu as _cb
54
+ _NLTK = True
55
+ except ImportError:
56
+ _NLTK = False
57
+
58
+
59
+ # ── metric helpers ────────────────────────────────────────────────────────
60
+
61
+ def _rouge_l(preds: List[str], refs: List[str]) -> float:
62
+ if not preds or not _ROUGE:
63
+ return 0.0
64
+ scorer = _rs_mod.RougeScorer(["rougeL"], use_stemmer=False)
65
+ return sum(scorer.score(p, r)["rougeL"].fmeasure for p, r in zip(preds, refs)) / len(preds)
66
+
67
+
68
+ def _bleu(preds: List[str], refs: List[str]) -> float:
69
+ if not preds or not _NLTK:
70
+ return 0.0
71
+ try:
72
+ return float(_cb([[r.split()] for r in refs], [p.split() for p in preds],
73
+ smoothing_function=SmoothingFunction().method1))
74
+ except Exception:
75
+ return 0.0
76
+
77
+
78
+ def compute_rats40k_metrics(results: List[Dict[str, Any]]) -> Dict[str, float]:
79
+ """Compute all evaluation metrics from a list of per-sample result dicts."""
80
+ gt_type, pred_type, gt_thoughts, pred_thoughts = [], [], [], []
81
+ invalid = 0
82
+
83
+ for r in results:
84
+ pred_id = r.get("pred_action_id")
85
+ gt_id = r.get("gt_action_id")
86
+ if gt_id is None:
87
+ invalid += 1
88
+ continue
89
+ gt_id = int(gt_id)
90
+ gt_type.append(gt_id)
91
+ if pred_id is None:
92
+ invalid += 1
93
+ pred_type.append(-1)
94
+ else:
95
+ pred_type.append(int(pred_id))
96
+ gt_thoughts.append(str(r.get("gt_thought", "") or ""))
97
+ pred_thoughts.append(str(r.get("pred_thought", "") or ""))
98
+
99
+ metrics: Dict[str, Any] = {
100
+ "num_samples": len(results),
101
+ "num_valid": len(results) - invalid,
102
+ "num_invalid": invalid,
103
+ "valid_rate": (len(results) - invalid) / len(results) if results else 0.0,
104
+ }
105
+
106
+ if not gt_type:
107
+ for k in ("binary_accuracy", "binary_precision_macro", "binary_recall_macro",
108
+ "binary_f1_macro", "type_accuracy", "type_precision_macro",
109
+ "type_recall_macro", "type_f1_macro", "thought_rouge_l", "thought_bleu"):
110
+ metrics[k] = 0.0
111
+ return metrics
112
+
113
+ gt_bin = [0 if x == 0 else 1 for x in gt_type]
114
+ pred_bin = [0 if x == 0 else (1 if x > 0 else -1) for x in pred_type]
115
+
116
+ if _SKL:
117
+ metrics.update({
118
+ "binary_accuracy": accuracy_score(gt_bin, pred_bin),
119
+ "binary_precision_macro": precision_score(
120
+ gt_bin, pred_bin, labels=[0, 1], average="macro", zero_division=0
121
+ ),
122
+ "binary_recall_macro": recall_score(
123
+ gt_bin, pred_bin, labels=[0, 1], average="macro", zero_division=0
124
+ ),
125
+ "binary_f1_macro": f1_score(
126
+ gt_bin, pred_bin, labels=[0, 1], average="macro", zero_division=0
127
+ ),
128
+ "type_accuracy": accuracy_score(gt_type, pred_type),
129
+ "type_precision_macro": precision_score(
130
+ gt_type, pred_type, labels=list(ACTION_ID_MAP), average="macro", zero_division=0
131
+ ),
132
+ "type_recall_macro": recall_score(
133
+ gt_type, pred_type, labels=list(ACTION_ID_MAP), average="macro", zero_division=0
134
+ ),
135
+ "type_f1_macro": f1_score(
136
+ gt_type, pred_type, labels=list(ACTION_ID_MAP), average="macro", zero_division=0
137
+ ),
138
+ })
139
+ else:
140
+ # Fallback: manual accuracy
141
+ n = len(gt_type)
142
+ metrics["binary_accuracy"] = sum(g == p for g, p in zip(gt_bin, pred_bin)) / n
143
+ metrics["type_accuracy"] = sum(g == p for g, p in zip(gt_type, pred_type)) / n
144
+ for k in ("binary_precision_macro", "binary_recall_macro", "binary_f1_macro",
145
+ "type_precision_macro", "type_recall_macro", "type_f1_macro"):
146
+ metrics[k] = float("nan")
147
+
148
+ metrics["thought_rouge_l"] = _rouge_l(pred_thoughts, gt_thoughts)
149
+ metrics["thought_bleu"] = _bleu(pred_thoughts, gt_thoughts)
150
+ return metrics
151
+
152
+
153
+ def print_metrics(metrics: Dict[str, Any]):
154
+ print("\n" + "=" * 50)
155
+ print("RATs40K Evaluation Results")
156
+ print("=" * 50)
157
+ for k, v in metrics.items():
158
+ if isinstance(v, float):
159
+ print(f" {k:<30} {v:.4f}")
160
+ else:
161
+ print(f" {k:<30} {v}")
162
+
163
+
164
+ # ── main ──────────────────────────────────────────────────────────────────
165
+
166
+ def main():
167
+ patch_accelerate_compat()
168
+ accelerator = Accelerator()
169
+
170
+ if accelerator.is_local_main_process:
171
+ transformers_logging.set_verbosity_info()
172
+ else:
173
+ transformers_logging.set_verbosity_error()
174
+ logging.disable(logging.CRITICAL)
175
+
176
+ parser = argparse.ArgumentParser(description="Inference on RATs40K")
177
+ parser.add_argument("--checkpoint", required=True, help="Path to SFT checkpoint dir")
178
+ parser.add_argument("--data_path", default="/mnt/share01/sqk/datasets/RATs40K/RATs-Uni-TSImage_Reason.json")
179
+ parser.add_argument("--eval_split", default="TSAD_test")
180
+ parser.add_argument("--llm_model_path", default="/mnt/share01/sqk/models/qwen2.5-7b-instruct")
181
+ # TS encoder (must match training): patch_len=16, input_len=128
182
+ parser.add_argument("--patch_len", type=int, default=16)
183
+ parser.add_argument("--stride", type=int, default=16)
184
+ parser.add_argument("--input_len", type=int, default=128)
185
+ parser.add_argument("--d_model", type=int, default=512)
186
+ parser.add_argument("--n_heads", type=int, default=8)
187
+ parser.add_argument("--e_layers", type=int, default=4)
188
+ parser.add_argument("--dropout", type=float, default=0.1)
189
+ # ITFormer adapter (it_d_model must equal LLM hidden_size: 3584 for 7B)
190
+ parser.add_argument("--it_d_model", type=int, default=3584)
191
+ parser.add_argument("--it_n_heads", type=int, default=28)
192
+ parser.add_argument("--it_layers", type=int, default=2)
193
+ parser.add_argument("--it_dropout", type=float, default=0.1)
194
+ parser.add_argument("--prefix_num", type=int, default=8)
195
+ parser.add_argument("--adapter_type", default="itformer")
196
+ parser.add_argument("--llm_attn_implementation", default=None,
197
+ choices=["eager", "sdpa", "flash_attention_2", None])
198
+ # inference
199
+ parser.add_argument("--batch_size", type=int, default=8)
200
+ parser.add_argument("--max_new_tokens", type=int, default=256)
201
+ parser.add_argument("--num_workers", type=int, default=4)
202
+ parser.add_argument("--output_dir", default="inference_results_rats40k")
203
+ parser.add_argument("--seed", type=int, default=42)
204
+ parser.add_argument("--max_eval_samples", type=int, default=None)
205
+ args = parser.parse_args()
206
+
207
+ random.seed(args.seed)
208
+ np.random.seed(args.seed)
209
+ torch.manual_seed(args.seed)
210
+
211
+ # ── load tokenizer ────────────────────────────────────────────────────
212
+ ckpt = args.checkpoint
213
+ tok_path = ckpt if os.path.exists(os.path.join(ckpt, "tokenizer.json")) else args.llm_model_path
214
+ tokenizer = AutoTokenizer.from_pretrained(tok_path)
215
+ tokenizer.padding_side = "left"
216
+ if tokenizer.pad_token is None:
217
+ tokenizer.pad_token = tokenizer.eos_token
218
+ if "<|image_pad|>" not in tokenizer.get_vocab():
219
+ tokenizer.add_tokens(["<|image_pad|>"])
220
+
221
+ # ── load model ────────────────────────────────────────────────────────
222
+ tlm_config = TLMConfig(
223
+ llm_model_path=args.llm_model_path,
224
+ freeze_ts_model=True,
225
+ ts_pad_num=args.prefix_num,
226
+ llm_attn_implementation=args.llm_attn_implementation,
227
+ )
228
+ # Pass TS / ITFormer params via TLMConfig attributes
229
+ for attr in ("patch_len", "stride", "input_len", "d_model", "n_heads", "e_layers",
230
+ "dropout", "it_d_model", "it_n_heads", "it_layers", "it_dropout",
231
+ "prefix_num", "adapter_type"):
232
+ setattr(tlm_config, attr, getattr(args, attr))
233
+
234
+ if accelerator.is_main_process:
235
+ print(f"Loading checkpoint: {ckpt}")
236
+ model = TLM.from_pretrained(ckpt, config=tlm_config, ts_config=tlm_config)
237
+
238
+ if len(tokenizer) != model.llm_model.config.vocab_size:
239
+ model.llm_model.resize_token_embeddings(len(tokenizer))
240
+
241
+ model = accelerator.prepare(model)
242
+ model.eval()
243
+
244
+ # ── dataset ───────────────────────────────────────────────────────────
245
+ eval_dataset = RATsQADataset(
246
+ data_path=args.data_path,
247
+ split=args.eval_split,
248
+ tokenizer=tokenizer,
249
+ ts_pad_num=args.prefix_num,
250
+ input_len=args.input_len,
251
+ shuffle=False,
252
+ include_answer=False,
253
+ )
254
+ if args.max_eval_samples is not None:
255
+ if args.max_eval_samples < 1:
256
+ raise ValueError("--max_eval_samples must be at least 1")
257
+ eval_dataset.records = eval_dataset.records[:args.max_eval_samples]
258
+ collator = RATsDataCollator(tokenizer)
259
+ loader = DataLoader(eval_dataset, batch_size=args.batch_size,
260
+ collate_fn=collator, num_workers=args.num_workers)
261
+ loader = accelerator.prepare(loader)
262
+
263
+ if accelerator.is_main_process:
264
+ print(f"Eval set: {len(eval_dataset)} samples | batch_size: {args.batch_size}")
265
+
266
+ # ── inference loop ────────────────────────────────────────────────────
267
+ # With flash_attention_2 the LLM is bf16 while the adapter/TS-encoder are fp32;
268
+ # wrap generate() in bf16 autocast so mixed-dtype matmuls are cast automatically.
269
+ use_amp = args.llm_attn_implementation in ("flash_attention_2", "sdpa")
270
+ amp_ctx = torch.autocast(device_type="cuda", dtype=torch.bfloat16) if use_amp else nullcontext()
271
+
272
+ results = []
273
+ it = tqdm(loader, desc="Inference") if accelerator.is_main_process else loader
274
+
275
+ with torch.no_grad(), amp_ctx:
276
+ for batch in it:
277
+ unwrapped = accelerator.unwrap_model(model)
278
+ generated_ids = unwrapped.generate(
279
+ input_ids=batch["input_ids"],
280
+ query_ids=batch["query_ids"],
281
+ ts_values=batch["ts_values"],
282
+ stage=batch["stage"],
283
+ attention_mask=batch["attention_mask"],
284
+ max_new_tokens=args.max_new_tokens,
285
+ do_sample=False,
286
+ eos_token_id=tokenizer.eos_token_id,
287
+ pad_token_id=tokenizer.pad_token_id,
288
+ use_cache=True,
289
+ num_beams=1,
290
+ output_scores=False,
291
+ output_attentions=False,
292
+ output_hidden_states=False,
293
+ return_dict_in_generate=False,
294
+ )
295
+ decoded = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
296
+ for i, text in enumerate(decoded):
297
+ response = text.split("assistant\n")[-1]
298
+ pred_id = parse_action_from_response(response)
299
+ pred_thought = parse_thought_from_response(response)
300
+ sample_index = int(batch["index"][i].item())
301
+ results.append({
302
+ "index": sample_index,
303
+ "gt_action_id": int(batch["gt_action_id"][i].item()),
304
+ "pred_action_id": pred_id,
305
+ "gt_thought": batch["gt_thought"][i],
306
+ "pred_thought": pred_thought,
307
+ "response": response,
308
+ })
309
+
310
+ # ── gather across GPUs ────────────────────────────────────────────────
311
+ if dist.is_initialized():
312
+ all_results = [None] * accelerator.num_processes
313
+ dist.all_gather_object(all_results, results)
314
+ results = [item for sub in all_results for item in sub]
315
+
316
+ if accelerator.is_main_process:
317
+ # De-duplicate
318
+ seen = set()
319
+ unique = []
320
+ for r in results:
321
+ if r["index"] not in seen:
322
+ unique.append(r)
323
+ seen.add(r["index"])
324
+ results = sorted(unique, key=lambda x: x["index"])
325
+
326
+ metrics = compute_rats40k_metrics(results)
327
+ print_metrics(metrics)
328
+
329
+ os.makedirs(args.output_dir, exist_ok=True)
330
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
331
+ pred_path = os.path.join(args.output_dir, f"predictions_{ts}.json")
332
+ metrics_path = os.path.join(args.output_dir, f"metrics_{ts}.json")
333
+
334
+ with open(pred_path, "w", encoding="utf-8") as f:
335
+ json.dump({"TSAD_test": {str(r["index"]): r for r in results}}, f,
336
+ indent=2, ensure_ascii=False)
337
+ with open(metrics_path, "w", encoding="utf-8") as f:
338
+ json.dump(metrics, f, indent=2, ensure_ascii=False)
339
+
340
+ print(f"\nPredictions: {pred_path}")
341
+ print(f"Metrics: {metrics_path}")
342
+
343
+
344
+ if __name__ == "__main__":
345
+ main()
inference_tsqa.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Evaluate a native ITFormer checkpoint with the unified Time-MQA evaluator."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import math
9
+ import os
10
+ import random
11
+ import sys
12
+ from contextlib import nullcontext
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import torch
17
+ from accelerate import Accelerator
18
+ from torch.utils.data import DataLoader
19
+ from tqdm.auto import tqdm
20
+ from transformers import AutoTokenizer
21
+
22
+ MQA_DIR = Path(os.environ.get("MQA_DIR", "/mnt/share01/sqk/MQA"))
23
+ sys.path.insert(0, str(MQA_DIR))
24
+
25
+ from data_utils import compute_group_metrics # noqa: E402
26
+ from dataset.tsqa_dataset import ITFormerTSQACollator, ITFormerTSQADataset
27
+ from models.TimeLanguageModel import TLM, TLMConfig
28
+ from utils.accelerate_compat import patch_accelerate_unwrap_model
29
+
30
+
31
+ def parse_args():
32
+ parser = argparse.ArgumentParser(description="Evaluate ITFormer on Time-MQA TSQA.")
33
+ parser.add_argument("--checkpoint", required=True)
34
+ parser.add_argument("--eval_path", required=True)
35
+ parser.add_argument(
36
+ "--llm_model_path",
37
+ default="/mnt/share01/sqk/models/qwen2.5-7b-instruct",
38
+ )
39
+ parser.add_argument("--output_dir", required=True)
40
+ parser.add_argument("--max_eval_samples", type=int, default=0)
41
+ parser.add_argument("--seed", type=int, default=42)
42
+
43
+ parser.add_argument("--d_model", type=int, default=512)
44
+ parser.add_argument("--n_heads", type=int, default=8)
45
+ parser.add_argument("--e_layers", type=int, default=4)
46
+ parser.add_argument("--patch_len", type=int, default=60)
47
+ parser.add_argument("--stride", type=int, default=60)
48
+ parser.add_argument("--input_len", type=int, default=600)
49
+ parser.add_argument("--dropout", type=float, default=0.1)
50
+ parser.add_argument("--it_d_model", type=int, default=896)
51
+ parser.add_argument("--it_n_heads", type=int, default=16)
52
+ parser.add_argument("--it_layers", type=int, default=2)
53
+ parser.add_argument("--it_dropout", type=float, default=0.1)
54
+ parser.add_argument("--itformer_legacy_double_residual", action="store_true")
55
+ parser.add_argument("--prefix_num", type=int, default=25)
56
+ parser.add_argument("--adapter_type", default="itformer", choices=["itformer"])
57
+ parser.add_argument(
58
+ "--llm_attn_implementation",
59
+ default=None,
60
+ choices=["eager", "sdpa", "flash_attention_2"],
61
+ )
62
+ parser.add_argument(
63
+ "--llm_torch_dtype",
64
+ default=None,
65
+ choices=["float16", "bfloat16", "float32"],
66
+ )
67
+ parser.add_argument("--use_lora", action="store_true")
68
+ parser.add_argument("--lora_r", type=int, default=16)
69
+ parser.add_argument("--lora_alpha", type=int, default=32)
70
+ parser.add_argument("--lora_dropout", type=float, default=0.05)
71
+ parser.add_argument(
72
+ "--lora_target_modules",
73
+ nargs="+",
74
+ default=[
75
+ "q_proj",
76
+ "k_proj",
77
+ "v_proj",
78
+ "o_proj",
79
+ "gate_proj",
80
+ "up_proj",
81
+ "down_proj",
82
+ ],
83
+ )
84
+
85
+ parser.add_argument("--batch_size", type=int, default=1)
86
+ parser.add_argument("--num_workers", type=int, default=2)
87
+ parser.add_argument("--max_new_tokens", type=int, default=256)
88
+ parser.add_argument("--bf16", action="store_true")
89
+ return parser.parse_args()
90
+
91
+
92
+ def response_only(text: str) -> str:
93
+ for marker in ("assistant\n", "<|im_start|>assistant\n"):
94
+ if marker in text:
95
+ text = text.rsplit(marker, 1)[-1]
96
+ return text.strip()
97
+
98
+
99
+ def gather_results(local_results, accelerator):
100
+ if accelerator.num_processes == 1:
101
+ return local_results
102
+ from accelerate.utils import gather_object
103
+
104
+ gathered = gather_object(local_results)
105
+ if gathered and isinstance(gathered[0], list):
106
+ return [item for part in gathered for item in part]
107
+ return gathered
108
+
109
+
110
+ def main():
111
+ patch_accelerate_unwrap_model()
112
+ args = parse_args()
113
+ accelerator = Accelerator()
114
+
115
+ random.seed(args.seed)
116
+ np.random.seed(args.seed)
117
+ torch.manual_seed(args.seed)
118
+
119
+ tokenizer_path = (
120
+ args.checkpoint
121
+ if (Path(args.checkpoint) / "tokenizer.json").is_file()
122
+ else args.llm_model_path
123
+ )
124
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
125
+ tokenizer.padding_side = "left"
126
+ if tokenizer.pad_token is None:
127
+ tokenizer.pad_token = tokenizer.eos_token
128
+ if "<|image_pad|>" not in tokenizer.get_vocab():
129
+ tokenizer.add_tokens(["<|image_pad|>"])
130
+
131
+ tlm_config = TLMConfig(
132
+ llm_model_path=args.llm_model_path,
133
+ freeze_ts_model=True,
134
+ ts_pad_num=args.prefix_num,
135
+ llm_attn_implementation=args.llm_attn_implementation,
136
+ llm_torch_dtype=args.llm_torch_dtype,
137
+ use_lora=args.use_lora,
138
+ lora_r=args.lora_r,
139
+ lora_alpha=args.lora_alpha,
140
+ lora_dropout=args.lora_dropout,
141
+ lora_target_modules=args.lora_target_modules,
142
+ gradient_checkpointing=False,
143
+ )
144
+ for name in (
145
+ "d_model",
146
+ "n_heads",
147
+ "e_layers",
148
+ "patch_len",
149
+ "stride",
150
+ "input_len",
151
+ "dropout",
152
+ "it_d_model",
153
+ "it_n_heads",
154
+ "it_layers",
155
+ "it_dropout",
156
+ "itformer_legacy_double_residual",
157
+ "prefix_num",
158
+ "adapter_type",
159
+ ):
160
+ setattr(tlm_config, name, getattr(args, name))
161
+
162
+ model = TLM.from_pretrained(
163
+ args.checkpoint,
164
+ config=tlm_config,
165
+ ts_config=tlm_config,
166
+ )
167
+ if len(tokenizer) != model.llm_model.config.vocab_size:
168
+ model.llm_model.resize_token_embeddings(len(tokenizer))
169
+ model = accelerator.prepare(model)
170
+ model.eval()
171
+
172
+ dataset = ITFormerTSQADataset(
173
+ args.eval_path,
174
+ tokenizer,
175
+ prefix_num=args.prefix_num,
176
+ input_len=args.input_len,
177
+ max_samples=args.max_eval_samples,
178
+ include_answer=False,
179
+ )
180
+ loader = DataLoader(
181
+ dataset,
182
+ batch_size=args.batch_size,
183
+ shuffle=False,
184
+ collate_fn=ITFormerTSQACollator(tokenizer),
185
+ num_workers=args.num_workers,
186
+ )
187
+ loader = accelerator.prepare(loader)
188
+
189
+ progress = tqdm(
190
+ loader,
191
+ total=math.ceil(len(dataset) / (args.batch_size * accelerator.num_processes)),
192
+ desc="ITFormer TSQA eval",
193
+ disable=not accelerator.is_main_process,
194
+ )
195
+ results = []
196
+ for batch in progress:
197
+ amp = (
198
+ torch.autocast(device_type="cuda", dtype=torch.bfloat16)
199
+ if args.bf16 and torch.cuda.is_available()
200
+ else nullcontext()
201
+ )
202
+ with torch.no_grad(), amp:
203
+ generated = accelerator.unwrap_model(model).generate(
204
+ input_ids=batch["input_ids"],
205
+ query_ids=batch["query_ids"],
206
+ ts_values=batch["ts_values"],
207
+ stage=batch["stage"],
208
+ attention_mask=batch["attention_mask"],
209
+ max_new_tokens=args.max_new_tokens,
210
+ do_sample=False,
211
+ eos_token_id=tokenizer.eos_token_id,
212
+ pad_token_id=tokenizer.pad_token_id,
213
+ use_cache=True,
214
+ num_beams=1,
215
+ return_dict_in_generate=False,
216
+ )
217
+ decoded = tokenizer.batch_decode(generated, skip_special_tokens=True)
218
+ for index, text in enumerate(decoded):
219
+ results.append(
220
+ {
221
+ "_index": int(batch["index"][index].item()),
222
+ "id": batch["id"][index],
223
+ "figure_path": batch["figure_path"][index],
224
+ "application_domain": batch["application_domain"][index],
225
+ "task_type": batch["task_type"][index],
226
+ "source_type": batch["source_type"][index],
227
+ "question_format": batch["question_format"][index],
228
+ "question": batch["question"][index],
229
+ "answer": batch["answer"][index],
230
+ "prediction": response_only(text),
231
+ }
232
+ )
233
+
234
+ results = gather_results(results, accelerator)
235
+ if accelerator.is_main_process:
236
+ unique = {}
237
+ for row in results:
238
+ unique[row["_index"]] = row
239
+ results = [unique[index] for index in sorted(unique)]
240
+ for row in results:
241
+ row.pop("_index", None)
242
+
243
+ metrics = {"by_group": compute_group_metrics(results)}
244
+ output_dir = Path(args.output_dir)
245
+ output_dir.mkdir(parents=True, exist_ok=True)
246
+ with (output_dir / "predictions.jsonl").open("w", encoding="utf-8") as handle:
247
+ for row in results:
248
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
249
+ with (output_dir / "metrics.json").open("w", encoding="utf-8") as handle:
250
+ json.dump(metrics, handle, ensure_ascii=False, indent=2)
251
+ print(json.dumps(metrics, ensure_ascii=False, indent=2))
252
+ print(f"Predictions: {output_dir / 'predictions.jsonl'}")
253
+ print(f"Metrics: {output_dir / 'metrics.json'}")
254
+
255
+ accelerator.wait_for_everyone()
256
+
257
+
258
+ if __name__ == "__main__":
259
+ main()
infra.bash ADDED
@@ -0,0 +1 @@
 
 
1
+ accelerate launch --config_file accelerate_config.yaml inference.py
metrics_eval_20260413_162434.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ {'stage1_BLEU': 0.3444986664812145, 'stage1_rouge1': 0.5992373145597989, 'stage1_rouge2': 0.42266572758391807, 'stage1_rougeL': 0.5537182458265498, 'stage2_precision': 0.6539294554455446, 'stage2_recall': 0.45841015074286956, 'stage2_f1': 0.5389862926362767, 'stage2_exact_match_accuracy': 0.5885161119214958, 'stage3_precision': 0.9964518036664696, 'stage3_recall': 0.9964518036664696, 'stage3_f1': 0.9964518036664696, 'stage3_exact_match_accuracy': 0.9964518036664696, 'stage4_BLEU': 0.3536116102555878, 'stage4_rouge1': 0.5957855733664116, 'stage4_rouge2': 0.41279533490351134, 'stage4_rougeL': 0.5522732459725292}
metrics_eval_20260606_080757.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ {'stage1_BLEU': 0.24847462322597452, 'stage1_rouge1': 0.5209698059306073, 'stage1_rouge2': 0.32633388563523696, 'stage1_rougeL': 0.467276872058015, 'stage2_precision': 0.653015873015873, 'stage2_recall': 0.4569080408707241, 'stage2_f1': 0.5376372190277051, 'stage2_exact_match_accuracy': 0.5884931506849315, 'stage3_precision': 0.9386904761904762, 'stage3_recall': 0.9386904761904762, 'stage3_f1': 0.9386904761904762, 'stage3_exact_match_accuracy': 0.9386904761904762, 'stage4_BLEU': 0.12502197126920916, 'stage4_rouge1': 0.41781885458543744, 'stage4_rouge2': 0.18578331787893307, 'stage4_rougeL': 0.34094122701220153}
metrics_eval_20260606_234456.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ {'stage1_BLEU': 0.3016313191233199, 'stage1_rouge1': 0.5634405361456165, 'stage1_rouge2': 0.3738625792233906, 'stage1_rougeL': 0.5119742617276746, 'stage2_precision': 0.652063492063492, 'stage2_recall': 0.45624167036872504, 'stage2_f1': 0.5368531102979612, 'stage2_exact_match_accuracy': 0.5876712328767123, 'stage3_precision': 0.44226190476190474, 'stage3_recall': 0.44226190476190474, 'stage3_f1': 0.4422619047619048, 'stage3_exact_match_accuracy': 0.44226190476190474, 'stage4_BLEU': 0.2040700976737847, 'stage4_rouge1': 0.48735974033981727, 'stage4_rouge2': 0.26269157817775823, 'stage4_rougeL': 0.4192184644734957}
output_result_all.json ADDED
The diff for this file is too large to render. See raw diff
 
random_stage_inference_demo.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Simple inference demo:
5
+ - randomly sample one example from each stage (1/2/3/4)
6
+ - run generation with the current ITFormer checkpoint
7
+ - print question / reference answer / model prediction
8
+ """
9
+
10
+ import argparse
11
+ import os
12
+ import random
13
+ from typing import Dict, List
14
+
15
+ import numpy as np
16
+ import torch
17
+ import yaml
18
+ from transformers import AutoTokenizer
19
+
20
+ from dataset.dataset import TsQaDataset, DataCollator
21
+ from models.TimeLanguageModel import TLM, TLMConfig
22
+
23
+
24
+ STAGE_DESCRIPTIONS = {
25
+ 1: "Signal interpretation (open-ended)",
26
+ 2: "Fault/root-cause identification (closed-ended)",
27
+ 3: "Degradation/health assessment (closed-ended)",
28
+ 4: "Maintenance recommendation (open-ended)",
29
+ }
30
+
31
+
32
+ def set_seed(seed: int = 42) -> None:
33
+ random.seed(seed)
34
+ np.random.seed(seed)
35
+ torch.manual_seed(seed)
36
+ if torch.cuda.is_available():
37
+ torch.cuda.manual_seed(seed)
38
+ torch.cuda.manual_seed_all(seed)
39
+
40
+
41
+ def resolve_llm_model_path(model_checkpoint: str, llm_model_path: str = "") -> str:
42
+ if llm_model_path:
43
+ return llm_model_path
44
+ if "0.5B" in model_checkpoint:
45
+ return "LLM/Qwen2.5-0.5B-Instruct"
46
+ if "3B" in model_checkpoint:
47
+ return "LLM/Qwen2.5-3B-Instruct"
48
+ if "7B" in model_checkpoint:
49
+ return "LLM/Qwen2.5-7B-Instruct"
50
+ return "LLM/Qwen2.5-7B-Instruct"
51
+
52
+
53
+ def build_tlm_config(raw_config: Dict, llm_model_path: str) -> TLMConfig:
54
+ return TLMConfig(
55
+ llm_model_path=llm_model_path,
56
+ freeze_ts_model=True,
57
+ ts_pad_num=raw_config["prefix_num"],
58
+ prefix_num=raw_config["prefix_num"],
59
+ it_d_model=raw_config.get("it_d_model", 896),
60
+ it_n_heads=raw_config.get("it_n_heads", 16),
61
+ it_layers=raw_config.get("it_layers", 2),
62
+ it_dropout=raw_config.get("it_dropout", 0.1),
63
+ dropout=raw_config.get("dropout", 0.1),
64
+ d_model=raw_config.get("d_model", 512),
65
+ n_heads=raw_config.get("n_heads", 8),
66
+ e_layers=raw_config.get("e_layers", 4),
67
+ patch_len=raw_config.get("patch_len", 60),
68
+ stride=raw_config.get("stride", 60),
69
+ input_len=raw_config.get("input_len", 600),
70
+ )
71
+
72
+
73
+ def pick_one_index_per_stage(dataset: TsQaDataset, stages: List[int]) -> Dict[int, int]:
74
+ stage_to_indices: Dict[int, List[int]] = {stage: [] for stage in stages}
75
+ for idx, sample in enumerate(dataset.datas):
76
+ stage = sample["stage"]
77
+ if stage in stage_to_indices:
78
+ stage_to_indices[stage].append(idx)
79
+
80
+ selected = {}
81
+ for stage in stages:
82
+ if not stage_to_indices[stage]:
83
+ raise ValueError(f"No samples found for stage {stage}")
84
+ selected[stage] = random.choice(stage_to_indices[stage])
85
+ return selected
86
+
87
+
88
+ def prepare_batch(dataset: TsQaDataset, tokenizer, sample_idx: int, device: torch.device):
89
+ collator = DataCollator(tokenizer=tokenizer)
90
+ batch = collator([dataset[sample_idx]])
91
+ moved = {}
92
+ for key, value in batch.items():
93
+ if torch.is_tensor(value):
94
+ moved[key] = value.to(device)
95
+ else:
96
+ moved[key] = value
97
+ return moved
98
+
99
+
100
+ def generate_one(model: TLM, tokenizer, batch: Dict, max_new_tokens: int) -> str:
101
+ with torch.no_grad():
102
+ generated_ids = model.generate(
103
+ input_ids=batch["input_ids"],
104
+ query_ids=batch["query_ids"],
105
+ ts_values=batch["ts_values"],
106
+ stage=batch["stage"],
107
+ attention_mask=batch["attention_mask"],
108
+ max_new_tokens=max_new_tokens,
109
+ do_sample=False,
110
+ eos_token_id=tokenizer.eos_token_id,
111
+ pad_token_id=tokenizer.pad_token_id,
112
+ use_cache=True,
113
+ num_beams=1,
114
+ temperature=1.0,
115
+ top_p=None,
116
+ top_k=None,
117
+ repetition_penalty=1.0,
118
+ length_penalty=1.0,
119
+ no_repeat_ngram_size=0,
120
+ output_scores=False,
121
+ output_attentions=False,
122
+ output_hidden_states=False,
123
+ return_dict_in_generate=False,
124
+ )
125
+ decoded = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
126
+ return decoded.split("assistant\n")[-1].strip()
127
+
128
+
129
+ def parse_args():
130
+ parser = argparse.ArgumentParser(description="Random one-sample-per-stage inference demo")
131
+ parser.add_argument("--config", type=str, default="yaml/infer.yaml", help="YAML config file")
132
+ parser.add_argument(
133
+ "--model_checkpoint",
134
+ type=str,
135
+ default="checkpoints/ITFormer-0.5B",
136
+ help="Model checkpoint path",
137
+ )
138
+ parser.add_argument(
139
+ "--llm_model_path",
140
+ type=str,
141
+ default="",
142
+ help="Optional override for base LLM path",
143
+ )
144
+ parser.add_argument("--seed", type=int, default=42, help="Random seed for sampling")
145
+ parser.add_argument("--max_new_tokens", type=int, default=128, help="Maximum new tokens to generate")
146
+ parser.add_argument(
147
+ "--device",
148
+ type=str,
149
+ default="cuda" if torch.cuda.is_available() else "cpu",
150
+ help="Device to run on, e.g. cpu / cuda / cuda:1",
151
+ )
152
+ return parser.parse_args()
153
+
154
+
155
+ def main():
156
+ args = parse_args()
157
+ set_seed(args.seed)
158
+
159
+ with open(args.config, "r", encoding="utf-8") as f:
160
+ raw_config = yaml.safe_load(f)
161
+
162
+ llm_model_path = resolve_llm_model_path(args.model_checkpoint, args.llm_model_path)
163
+ device = torch.device(args.device)
164
+
165
+ print(f"Loading checkpoint: {args.model_checkpoint}")
166
+ print(f"Using base LLM: {llm_model_path}")
167
+ print(f"Running on device: {device}")
168
+
169
+ tlm_config = build_tlm_config(raw_config, llm_model_path)
170
+ model = TLM.from_pretrained(args.model_checkpoint, config=tlm_config, ts_config=tlm_config)
171
+ model.to(device)
172
+ model.eval()
173
+
174
+ if os.path.exists(os.path.join(args.model_checkpoint, "tokenizer.json")):
175
+ tokenizer = AutoTokenizer.from_pretrained(args.model_checkpoint)
176
+ else:
177
+ tokenizer = model.tokenizer
178
+
179
+ if "<|image_pad|>" not in tokenizer.get_vocab():
180
+ tokenizer.add_tokens(["<|image_pad|>"])
181
+ model.llm_model.resize_token_embeddings(len(tokenizer))
182
+ tokenizer.padding_side = "left"
183
+
184
+ class SimpleConfig:
185
+ def __init__(self, **kwargs):
186
+ for key, value in kwargs.items():
187
+ setattr(self, key, value)
188
+
189
+ dataset_config = SimpleConfig(ts_pad_num=raw_config["prefix_num"])
190
+ dataset = TsQaDataset(
191
+ raw_config["ts_path_test"],
192
+ raw_config["qa_path_test"],
193
+ tokenizer,
194
+ tokenizer,
195
+ dataset_config,
196
+ )
197
+
198
+ selected = pick_one_index_per_stage(dataset, [1, 2, 3, 4])
199
+
200
+ for stage in [1, 2, 3, 4]:
201
+ sample_idx = selected[stage]
202
+ raw_sample = dataset.datas[sample_idx]
203
+ batch = prepare_batch(dataset, tokenizer, sample_idx, device)
204
+ prediction = generate_one(model, tokenizer, batch, args.max_new_tokens)
205
+
206
+ print("=" * 100)
207
+ print(f"Stage {stage}: {STAGE_DESCRIPTIONS[stage]}")
208
+ print(f"Sample id: {raw_sample['id']} | line: {raw_sample['line_num']}")
209
+ print(f"Question: {raw_sample['question']}")
210
+ print(f"Reference: {raw_sample['answer']}")
211
+ print(f"Prediction: {prediction}")
212
+
213
+
214
+ if __name__ == "__main__":
215
+ main()
requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.5.1
2
+ transformers==4.47.1
3
+ datasets==2.4.0
4
+ pyarrow<21
5
+ accelerate==1.6.0
6
+ safetensors==0.4.5
7
+ numpy==1.26.4
8
+ scipy==1.15.2
9
+ pandas==2.2.3
10
+ matplotlib==3.10.1
11
+ tqdm==4.67.1
12
+ requests==2.32.3
13
+ huggingface-hub==0.27.0
14
+ nltk==3.9.1
15
+ rouge-score==0.1.2
16
+ scikit-learn==1.5.2
17
+ xformers==0.0.28.post3
18
+ timm==1.0.15
19
+ tokenizers==0.21.0
20
+ tiktoken==0.7.0
swanlog/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *
swanlog/run-20260413_125210-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"memory": "251", "cpu": {"brand": "Intel(R) Xeon(R) w7-3455", "cores": 48}, "gpu": {"nvidia": {"driver": "550.144.03", "cores": 2, "type": ["NVIDIA RTX 6000 Ada Generation", "NVIDIA RTX 6000 Ada Generation"], "memory": ["48", "48"], "cuda": "12.4", "architecture": ["Ada", "Ada"], "cudacores": [18176, 18176]}}, "os": "Linux-6.8.0-101-generic-x86_64-with-glibc2.35", "os_pretty_name": "Ubuntu 22.04.5 LTS", "hostname": "GPUWorkstation", "pid": 1595007, "cwd": "/mnt/share01/sqk/ITFormer-ICML25", "python": "3.10.20", "python_verbose": "3.10.20 (main, Mar 11 2026, 17:46:40) [GCC 14.3.0]", "executable": "/home/suiqk/py310/bin/python", "command": "/mnt/share01/sqk/ITFormer-ICML25/train_sft.py --model TimeSeriesEncoder --d_model 512 --n_heads 8 --e_layers 4 --patch_len 60 --stride 60 --input_len 600 --it_d_model 896 --it_n_heads 16 --it_layers 2 --prefix_num 25 --llm_model_path LLM/Qwen2.5-0.5B-Instruct --load_ts_encoder save/pretrain/model.safetensors --output_dir save/debug_sft_qwen2.5_0.5B --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --learning_rate 3e-5 --num_train_epochs 1 --dataloader_num_workers 0 --logging_steps 1 --save_steps 200 --report_to none", "git_remote": null, "git_info": [null, null], "swanlab": {"version": "0.7.15", "_monitor": 5, "logdir": "/mnt/share01/sqk/ITFormer-ICML25/swanlog/run-20260413_125210-d7ug5qigf62md7jitkhbb"}}
swanlog/run-20260413_131247-d7ug5qigf62md7jitkhbb/files/config.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
swanlog/run-20260413_131247-d7ug5qigf62md7jitkhbb/files/requirements.txt ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.4.0
2
+ accelerate==1.6.0
3
+ aiohappyeyeballs==2.6.1
4
+ aiohttp==3.13.5
5
+ aiosignal==1.4.0
6
+ annotated-types==0.7.0
7
+ async-timeout==5.0.1
8
+ attrs==26.1.0
9
+ certifi==2026.2.25
10
+ charset-normalizer==3.4.7
11
+ click==8.3.2
12
+ contourpy==1.3.2
13
+ cycler==0.12.1
14
+ datasets==2.4.0
15
+ dill==0.3.5.1
16
+ filelock==3.25.2
17
+ fonttools==4.62.1
18
+ frozenlist==1.8.0
19
+ fsspec==2026.3.0
20
+ h5py==3.16.0
21
+ huggingface-hub==0.27.0
22
+ idna==3.11
23
+ Jinja2==3.1.6
24
+ joblib==1.5.3
25
+ kiwisolver==1.5.0
26
+ markdown-it-py==4.0.0
27
+ MarkupSafe==3.0.3
28
+ matplotlib==3.10.1
29
+ mdurl==0.1.2
30
+ mpmath==1.3.0
31
+ multidict==6.7.1
32
+ multiprocess==0.70.13
33
+ networkx==3.4.2
34
+ nltk==3.9.1
35
+ numpy==1.26.4
36
+ nvidia-cublas-cu12==12.4.5.8
37
+ nvidia-cuda-cupti-cu12==12.4.127
38
+ nvidia-cuda-nvrtc-cu12==12.4.127
39
+ nvidia-cuda-runtime-cu12==12.4.127
40
+ nvidia-cudnn-cu12==9.1.0.70
41
+ nvidia-cufft-cu12==11.2.1.3
42
+ nvidia-curand-cu12==10.3.5.147
43
+ nvidia-cusolver-cu12==11.6.1.9
44
+ nvidia-cusparse-cu12==12.3.1.170
45
+ nvidia-ml-py==13.595.45
46
+ nvidia-nccl-cu12==2.21.5
47
+ nvidia-nvjitlink-cu12==12.4.127
48
+ nvidia-nvtx-cu12==12.4.127
49
+ packaging==26.0
50
+ pandas==2.2.3
51
+ pillow==12.2.0
52
+ pip==26.0.1
53
+ platformdirs==4.9.6
54
+ prettytable==3.17.0
55
+ propcache==0.4.1
56
+ protobuf==6.33.6
57
+ psutil==7.2.2
58
+ pyarrow==20.0.0
59
+ pydantic==2.12.5
60
+ pydantic_core==2.41.5
61
+ pyecharts==2.1.0
62
+ Pygments==2.20.0
63
+ pyparsing==3.3.2
64
+ python-dateutil==2.9.0.post0
65
+ pytz==2026.1.post1
66
+ PyYAML==6.0.3
67
+ regex==2026.4.4
68
+ requests==2.32.3
69
+ responses==0.18.0
70
+ rich==13.9.4
71
+ rouge_score==0.1.2
72
+ safetensors==0.4.5
73
+ scikit-learn==1.5.2
74
+ scipy==1.15.2
75
+ setuptools==82.0.1
76
+ simplejson==3.20.2
77
+ six==1.17.0
78
+ swanlab==0.7.15
79
+ sympy==1.13.1
80
+ threadpoolctl==3.6.0
81
+ tiktoken==0.7.0
82
+ timm==1.0.15
83
+ tokenizers==0.21.0
84
+ torch==2.5.1
85
+ torchvision==0.20.1
86
+ tqdm==4.67.1
87
+ transformers==4.47.1
88
+ triton==3.1.0
89
+ typing_extensions==4.15.0
90
+ typing-inspection==0.4.2
91
+ tzdata==2026.1
92
+ urllib3==2.6.3
93
+ wcwidth==0.6.0
94
+ wheel==0.46.3
95
+ wrapt==2.1.2
96
+ xformers==0.0.28.post3
97
+ xxhash==3.6.0
98
+ yarl==1.23.0
swanlog/run-20260413_133130-8ganaif5wa9up9bvv8bxq/backup.swanlab ADDED
Binary file (28.5 kB). View file
 
swanlog/run-20260413_133130-8ganaif5wa9up9bvv8bxq/files/config.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
swanlog/run-20260413_133130-8ganaif5wa9up9bvv8bxq/files/requirements.txt ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.4.0
2
+ accelerate==1.6.0
3
+ aiohappyeyeballs==2.6.1
4
+ aiohttp==3.13.5
5
+ aiosignal==1.4.0
6
+ annotated-types==0.7.0
7
+ async-timeout==5.0.1
8
+ attrs==26.1.0
9
+ certifi==2026.2.25
10
+ charset-normalizer==3.4.7
11
+ click==8.3.2
12
+ contourpy==1.3.2
13
+ cycler==0.12.1
14
+ datasets==2.4.0
15
+ dill==0.3.5.1
16
+ filelock==3.25.2
17
+ fonttools==4.62.1
18
+ frozenlist==1.8.0
19
+ fsspec==2026.3.0
20
+ h5py==3.16.0
21
+ huggingface-hub==0.27.0
22
+ idna==3.11
23
+ Jinja2==3.1.6
24
+ joblib==1.5.3
25
+ kiwisolver==1.5.0
26
+ markdown-it-py==4.0.0
27
+ MarkupSafe==3.0.3
28
+ matplotlib==3.10.1
29
+ mdurl==0.1.2
30
+ mpmath==1.3.0
31
+ multidict==6.7.1
32
+ multiprocess==0.70.13
33
+ networkx==3.4.2
34
+ nltk==3.9.1
35
+ numpy==1.26.4
36
+ nvidia-cublas-cu12==12.4.5.8
37
+ nvidia-cuda-cupti-cu12==12.4.127
38
+ nvidia-cuda-nvrtc-cu12==12.4.127
39
+ nvidia-cuda-runtime-cu12==12.4.127
40
+ nvidia-cudnn-cu12==9.1.0.70
41
+ nvidia-cufft-cu12==11.2.1.3
42
+ nvidia-curand-cu12==10.3.5.147
43
+ nvidia-cusolver-cu12==11.6.1.9
44
+ nvidia-cusparse-cu12==12.3.1.170
45
+ nvidia-ml-py==13.595.45
46
+ nvidia-nccl-cu12==2.21.5
47
+ nvidia-nvjitlink-cu12==12.4.127
48
+ nvidia-nvtx-cu12==12.4.127
49
+ packaging==26.0
50
+ pandas==2.2.3
51
+ pillow==12.2.0
52
+ pip==26.0.1
53
+ platformdirs==4.9.6
54
+ prettytable==3.17.0
55
+ propcache==0.4.1
56
+ protobuf==6.33.6
57
+ psutil==7.2.2
58
+ pyarrow==20.0.0
59
+ pydantic==2.12.5
60
+ pydantic_core==2.41.5
61
+ pyecharts==2.1.0
62
+ Pygments==2.20.0
63
+ pyparsing==3.3.2
64
+ python-dateutil==2.9.0.post0
65
+ pytz==2026.1.post1
66
+ PyYAML==6.0.3
67
+ regex==2026.4.4
68
+ requests==2.32.3
69
+ responses==0.18.0
70
+ rich==13.9.4
71
+ rouge_score==0.1.2
72
+ safetensors==0.4.5
73
+ scikit-learn==1.5.2
74
+ scipy==1.15.2
75
+ setuptools==82.0.1
76
+ simplejson==3.20.2
77
+ six==1.17.0
78
+ swanlab==0.7.15
79
+ sympy==1.13.1
80
+ threadpoolctl==3.6.0
81
+ tiktoken==0.7.0
82
+ timm==1.0.15
83
+ tokenizers==0.21.0
84
+ torch==2.5.1
85
+ torchvision==0.20.1
86
+ tqdm==4.67.1
87
+ transformers==4.47.1
88
+ triton==3.1.0
89
+ typing_extensions==4.15.0
90
+ typing-inspection==0.4.2
91
+ tzdata==2026.1
92
+ urllib3==2.6.3
93
+ wcwidth==0.6.0
94
+ wheel==0.46.3
95
+ wrapt==2.1.2
96
+ xformers==0.0.28.post3
97
+ xxhash==3.6.0
98
+ yarl==1.23.0
swanlog/run-20260413_133536-creh19v03ah9ycywkyfx0/files/config.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
swanlog/run-20260413_133536-creh19v03ah9ycywkyfx0/files/requirements.txt ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.4.0
2
+ accelerate==1.6.0
3
+ aiohappyeyeballs==2.6.1
4
+ aiohttp==3.13.5
5
+ aiosignal==1.4.0
6
+ annotated-types==0.7.0
7
+ async-timeout==5.0.1
8
+ attrs==26.1.0
9
+ certifi==2026.2.25
10
+ charset-normalizer==3.4.7
11
+ click==8.3.2
12
+ contourpy==1.3.2
13
+ cycler==0.12.1
14
+ datasets==2.4.0
15
+ dill==0.3.5.1
16
+ filelock==3.25.2
17
+ fonttools==4.62.1
18
+ frozenlist==1.8.0
19
+ fsspec==2026.3.0
20
+ h5py==3.16.0
21
+ huggingface-hub==0.27.0
22
+ idna==3.11
23
+ Jinja2==3.1.6
24
+ joblib==1.5.3
25
+ kiwisolver==1.5.0
26
+ markdown-it-py==4.0.0
27
+ MarkupSafe==3.0.3
28
+ matplotlib==3.10.1
29
+ mdurl==0.1.2
30
+ mpmath==1.3.0
31
+ multidict==6.7.1
32
+ multiprocess==0.70.13
33
+ networkx==3.4.2
34
+ nltk==3.9.1
35
+ numpy==1.26.4
36
+ nvidia-cublas-cu12==12.4.5.8
37
+ nvidia-cuda-cupti-cu12==12.4.127
38
+ nvidia-cuda-nvrtc-cu12==12.4.127
39
+ nvidia-cuda-runtime-cu12==12.4.127
40
+ nvidia-cudnn-cu12==9.1.0.70
41
+ nvidia-cufft-cu12==11.2.1.3
42
+ nvidia-curand-cu12==10.3.5.147
43
+ nvidia-cusolver-cu12==11.6.1.9
44
+ nvidia-cusparse-cu12==12.3.1.170
45
+ nvidia-ml-py==13.595.45
46
+ nvidia-nccl-cu12==2.21.5
47
+ nvidia-nvjitlink-cu12==12.4.127
48
+ nvidia-nvtx-cu12==12.4.127
49
+ packaging==26.0
50
+ pandas==2.2.3
51
+ pillow==12.2.0
52
+ pip==26.0.1
53
+ platformdirs==4.9.6
54
+ prettytable==3.17.0
55
+ propcache==0.4.1
56
+ protobuf==6.33.6
57
+ psutil==7.2.2
58
+ pyarrow==20.0.0
59
+ pydantic==2.12.5
60
+ pydantic_core==2.41.5
61
+ pyecharts==2.1.0
62
+ Pygments==2.20.0
63
+ pyparsing==3.3.2
64
+ python-dateutil==2.9.0.post0
65
+ pytz==2026.1.post1
66
+ PyYAML==6.0.3
67
+ regex==2026.4.4
68
+ requests==2.32.3
69
+ responses==0.18.0
70
+ rich==13.9.4
71
+ rouge_score==0.1.2
72
+ safetensors==0.4.5
73
+ scikit-learn==1.5.2
74
+ scipy==1.15.2
75
+ setuptools==82.0.1
76
+ simplejson==3.20.2
77
+ six==1.17.0
78
+ swanlab==0.7.15
79
+ sympy==1.13.1
80
+ threadpoolctl==3.6.0
81
+ tiktoken==0.7.0
82
+ timm==1.0.15
83
+ tokenizers==0.21.0
84
+ torch==2.5.1
85
+ torchvision==0.20.1
86
+ tqdm==4.67.1
87
+ transformers==4.47.1
88
+ triton==3.1.0
89
+ typing_extensions==4.15.0
90
+ typing-inspection==0.4.2
91
+ tzdata==2026.1
92
+ urllib3==2.6.3
93
+ wcwidth==0.6.0
94
+ wheel==0.46.3
95
+ wrapt==2.1.2
96
+ xformers==0.0.28.post3
97
+ xxhash==3.6.0
98
+ yarl==1.23.0
swanlog/run-20260413_133536-creh19v03ah9ycywkyfx0/files/swanlab-metadata.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"memory": "251", "cpu": {"brand": "Intel(R) Xeon(R) w7-3455", "cores": 48}, "gpu": {"nvidia": {"driver": "550.144.03", "cores": 2, "type": ["NVIDIA RTX 6000 Ada Generation", "NVIDIA RTX 6000 Ada Generation"], "memory": ["48", "48"], "cuda": "12.4", "architecture": ["Ada", "Ada"], "cudacores": [18176, 18176]}}, "os": "Linux-6.8.0-101-generic-x86_64-with-glibc2.35", "os_pretty_name": "Ubuntu 22.04.5 LTS", "hostname": "GPUWorkstation", "pid": 1600488, "cwd": "/mnt/share01/sqk/ITFormer-ICML25", "python": "3.10.20", "python_verbose": "3.10.20 (main, Mar 11 2026, 17:46:40) [GCC 14.3.0]", "executable": "/home/suiqk/py310/bin/python", "command": "/mnt/share01/sqk/ITFormer-ICML25/train_pretrain.py --model TimeSeriesEncoder --d_model 512 --n_heads 8 --e_layers 4 --patch_len 60 --stride 60 --input_len 600 --output_dir save/pretrain_ts_small --per_device_train_batch_size 1024 --learning_rate 3e-4 --num_train_epochs 10 --dataloader_num_workers 8 --report_to none", "git_remote": null, "git_info": [null, null], "swanlab": {"version": "0.7.15", "_monitor": 5, "logdir": "/mnt/share01/sqk/ITFormer-ICML25/swanlog/run-20260413_133536-creh19v03ah9ycywkyfx0"}}
swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/backup.swanlab ADDED
Binary file (65.7 kB). View file
 
swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/files/config.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/files/requirements.txt ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.4.0
2
+ accelerate==1.6.0
3
+ aiohappyeyeballs==2.6.1
4
+ aiohttp==3.13.5
5
+ aiosignal==1.4.0
6
+ annotated-types==0.7.0
7
+ async-timeout==5.0.1
8
+ attrs==26.1.0
9
+ certifi==2026.2.25
10
+ charset-normalizer==3.4.7
11
+ click==8.3.2
12
+ contourpy==1.3.2
13
+ cycler==0.12.1
14
+ datasets==2.4.0
15
+ dill==0.3.5.1
16
+ filelock==3.25.2
17
+ fonttools==4.62.1
18
+ frozenlist==1.8.0
19
+ fsspec==2026.3.0
20
+ h5py==3.16.0
21
+ huggingface-hub==0.27.0
22
+ idna==3.11
23
+ Jinja2==3.1.6
24
+ joblib==1.5.3
25
+ kiwisolver==1.5.0
26
+ markdown-it-py==4.0.0
27
+ MarkupSafe==3.0.3
28
+ matplotlib==3.10.1
29
+ mdurl==0.1.2
30
+ mpmath==1.3.0
31
+ multidict==6.7.1
32
+ multiprocess==0.70.13
33
+ networkx==3.4.2
34
+ nltk==3.9.1
35
+ numpy==1.26.4
36
+ nvidia-cublas-cu12==12.4.5.8
37
+ nvidia-cuda-cupti-cu12==12.4.127
38
+ nvidia-cuda-nvrtc-cu12==12.4.127
39
+ nvidia-cuda-runtime-cu12==12.4.127
40
+ nvidia-cudnn-cu12==9.1.0.70
41
+ nvidia-cufft-cu12==11.2.1.3
42
+ nvidia-curand-cu12==10.3.5.147
43
+ nvidia-cusolver-cu12==11.6.1.9
44
+ nvidia-cusparse-cu12==12.3.1.170
45
+ nvidia-ml-py==13.595.45
46
+ nvidia-nccl-cu12==2.21.5
47
+ nvidia-nvjitlink-cu12==12.4.127
48
+ nvidia-nvtx-cu12==12.4.127
49
+ packaging==26.0
50
+ pandas==2.2.3
51
+ pillow==12.2.0
52
+ pip==26.0.1
53
+ platformdirs==4.9.6
54
+ prettytable==3.17.0
55
+ propcache==0.4.1
56
+ protobuf==6.33.6
57
+ psutil==7.2.2
58
+ pyarrow==20.0.0
59
+ pydantic==2.12.5
60
+ pydantic_core==2.41.5
61
+ pyecharts==2.1.0
62
+ Pygments==2.20.0
63
+ pyparsing==3.3.2
64
+ python-dateutil==2.9.0.post0
65
+ pytz==2026.1.post1
66
+ PyYAML==6.0.3
67
+ regex==2026.4.4
68
+ requests==2.32.3
69
+ responses==0.18.0
70
+ rich==13.9.4
71
+ rouge_score==0.1.2
72
+ safetensors==0.4.5
73
+ scikit-learn==1.5.2
74
+ scipy==1.15.2
75
+ setuptools==82.0.1
76
+ simplejson==3.20.2
77
+ six==1.17.0
78
+ swanlab==0.7.15
79
+ sympy==1.13.1
80
+ threadpoolctl==3.6.0
81
+ tiktoken==0.7.0
82
+ timm==1.0.15
83
+ tokenizers==0.21.0
84
+ torch==2.5.1
85
+ torchvision==0.20.1
86
+ tqdm==4.67.1
87
+ transformers==4.47.1
88
+ triton==3.1.0
89
+ typing_extensions==4.15.0
90
+ typing-inspection==0.4.2
91
+ tzdata==2026.1
92
+ urllib3==2.6.3
93
+ wcwidth==0.6.0
94
+ wheel==0.46.3
95
+ wrapt==2.1.2
96
+ xformers==0.0.28.post3
97
+ xxhash==3.6.0
98
+ yarl==1.23.0
swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"memory": "251", "cpu": {"brand": "Intel(R) Xeon(R) w7-3455", "cores": 48}, "gpu": {"nvidia": {"driver": "550.144.03", "cores": 2, "type": ["NVIDIA RTX 6000 Ada Generation", "NVIDIA RTX 6000 Ada Generation"], "memory": ["48", "48"], "cuda": "12.4", "architecture": ["Ada", "Ada"], "cudacores": [18176, 18176]}}, "os": "Linux-6.8.0-101-generic-x86_64-with-glibc2.35", "os_pretty_name": "Ubuntu 22.04.5 LTS", "hostname": "GPUWorkstation", "pid": 1606352, "cwd": "/mnt/share01/sqk/ITFormer-ICML25", "python": "3.10.20", "python_verbose": "3.10.20 (main, Mar 11 2026, 17:46:40) [GCC 14.3.0]", "executable": "/home/suiqk/py310/bin/python", "command": "/mnt/share01/sqk/ITFormer-ICML25/train_sft.py --model TimeSeriesEncoder --d_model 512 --n_heads 8 --e_layers 4 --patch_len 60 --stride 60 --input_len 600 --it_d_model 896 --it_n_heads 16 --it_layers 2 --prefix_num 25 --llm_model_path LLM/Qwen2.5-0.5B-Instruct --load_ts_encoder save/pretrain/model.safetensors --output_dir save/debug_sft_qwen2.5_0.5B --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --learning_rate 3e-5 --num_train_epochs 1 --dataloader_num_workers 0 --logging_steps 1 --save_steps 200 --report_to none", "git_remote": null, "git_info": [null, null], "swanlab": {"version": "0.7.15", "_monitor": 5, "logdir": "/mnt/share01/sqk/ITFormer-ICML25/swanlog/run-20260413_135605-d7ug5qigf62md7jitkhbb"}}
swanlog/run-20260413_135748-d7ug5qigf62md7jitkhbb/files/config.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
swanlog/run-20260413_135748-d7ug5qigf62md7jitkhbb/files/requirements.txt ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiobotocore==2.25.0
2
+ aiodns==3.5.0
3
+ aiohappyeyeballs==2.6.1
4
+ aiohttp==3.13.2
5
+ aioitertools==0.12.0
6
+ aiosignal==1.4.0
7
+ alabaster==0.7.16
8
+ altair==5.5.0
9
+ anaconda-anon-usage==0.7.5
10
+ anaconda-auth==0.12.3
11
+ anaconda-catalogs==0.2.0
12
+ anaconda-cli-base==0.7.0
13
+ anaconda-client==1.14.0
14
+ anaconda-navigator==2.7.0
15
+ anaconda-project==0.11.1
16
+ annotated-types==0.6.0
17
+ anyio==4.10.0
18
+ appdirs==1.4.4
19
+ archspec==0.2.5
20
+ argon2-cffi==21.3.0
21
+ argon2-cffi-bindings==25.1.0
22
+ arrow==1.4.0
23
+ astroid==3.3.11
24
+ astropy==7.1.1
25
+ astropy-iers-data==0.2025.11.10.0.38.31
26
+ asttokens==3.0.0
27
+ async-lru==2.0.5
28
+ asyncssh==2.21.1
29
+ atomicwrites==1.4.0
30
+ attrs==25.4.0
31
+ Automat==24.8.1
32
+ autopep8==2.0.4
33
+ babel==2.17.0
34
+ bcrypt==5.0.0
35
+ beautifulsoup4==4.13.5
36
+ binaryornot==0.4.4
37
+ black==25.9.0
38
+ bleach==6.3.0
39
+ blinker==1.9.0
40
+ bokeh==3.8.0
41
+ boltons==25.0.0
42
+ botocore==1.40.46
43
+ Bottleneck==1.4.2
44
+ brotlicffi==1.1.0.0
45
+ cachetools==5.5.1
46
+ cattrs==25.3.0
47
+ certifi==2025.11.12
48
+ cffi==2.0.0
49
+ chardet==5.2.0
50
+ charset-normalizer==3.4.4
51
+ click==8.2.1
52
+ cloudpickle==3.1.1
53
+ colorcet==3.1.0
54
+ comm==0.2.3
55
+ conda==25.11.1
56
+ conda-anaconda-telemetry==0.3.0
57
+ conda-anaconda-tos==0.2.2
58
+ conda-build==25.11.1
59
+ conda-content-trust==0.2.0
60
+ conda_index==0.7.0
61
+ conda-libmamba-solver==25.11.0
62
+ conda-pack==0.8.1
63
+ conda-package-handling==2.4.0
64
+ conda_package_streaming==0.12.0
65
+ conda-repo-cli==1.0.173
66
+ constantly==23.10.4
67
+ contourpy==1.3.3
68
+ cookiecutter==2.6.0
69
+ cryptography==46.0.3
70
+ cssselect==1.2.0
71
+ cycler==0.11.0
72
+ dask==2025.11.0
73
+ datashader==0.18.2
74
+ debugpy==1.8.16
75
+ decorator==5.2.1
76
+ defusedxml==0.7.1
77
+ diff-match-patch==20200713
78
+ dill==0.4.0
79
+ distributed==2025.11.0
80
+ distro==1.9.0
81
+ docstring-to-markdown==0.17
82
+ docutils==0.21.2
83
+ et_xmlfile==2.0.0
84
+ evalidate==2.0.3
85
+ executing==2.2.1
86
+ fastjsonschema==2.21.2
87
+ filelock==3.20.0
88
+ flake8==7.1.1
89
+ Flask==3.1.2
90
+ fonttools==4.60.1
91
+ frozendict==2.4.6
92
+ frozenlist==1.8.0
93
+ fsspec==2025.10.0
94
+ gitdb==4.0.12
95
+ GitPython==3.1.45
96
+ gmpy2==2.2.1
97
+ greenlet==3.2.4
98
+ h11==0.16.0
99
+ h5py==3.15.1
100
+ HeapDict==1.0.1
101
+ holoviews==1.22.0
102
+ html5lib==1.1
103
+ httpcore==1.0.9
104
+ httpx==0.28.1
105
+ hvplot==0.12.1
106
+ hyperlink==21.0.0
107
+ idna==3.11
108
+ ImageIO==2.37.2
109
+ imagesize==1.4.1
110
+ imbalanced-learn==0.14.0
111
+ importlib_metadata==8.7.0
112
+ incremental==24.7.2
113
+ inflection==0.5.1
114
+ iniconfig==2.1.0
115
+ intake==2.0.8
116
+ intervaltree==3.1.0
117
+ ipykernel==6.31.0
118
+ ipympl==0.9.7
119
+ ipython==9.7.0
120
+ ipython_pygments_lexers==1.1.1
121
+ ipywidgets==8.1.7
122
+ isort==6.1.0
123
+ itemadapter==0.12.1
124
+ itemloaders==1.3.2
125
+ itsdangerous==2.2.0
126
+ jaraco.classes==3.4.0
127
+ jaraco.context==0.0.0
128
+ jaraco.functools==4.1.0
129
+ jedi==0.19.2
130
+ jeepney==0.7.1
131
+ jellyfish==1.2.1
132
+ Jinja2==3.1.6
133
+ jmespath==1.0.1
134
+ joblib==1.5.2
135
+ json5==0.12.1
136
+ jsonpatch==1.33
137
+ jsonpointer==3.0.0
138
+ jsonschema==4.25.0
139
+ jsonschema-specifications==2025.9.1
140
+ jupyter==1.1.1
141
+ jupyter_client==8.6.3
142
+ jupyter-console==6.6.3
143
+ jupyter_core==5.8.1
144
+ jupyter-events==0.12.0
145
+ jupyter-lsp==2.2.5
146
+ jupyter_server==2.16.0
147
+ jupyter_server_terminals==0.5.3
148
+ jupyterlab==4.4.7
149
+ jupyterlab_pygments==0.3.0
150
+ jupyterlab_server==2.28.0
151
+ jupyterlab_widgets==3.0.15
152
+ keyring==25.7.0
153
+ kiwisolver==1.4.9
154
+ lazy_loader==0.4
155
+ lckr_jupyterlab_variableinspector==3.2.4
156
+ libarchive-c==5.1
157
+ libmambapy==2.3.2
158
+ lief==0.16.4
159
+ linkify-it-py==2.0.3
160
+ llvmlite==0.45.1
161
+ lmdb==1.7.5
162
+ locket==1.0.0
163
+ lsprotocol==2025.0.0
164
+ lxml==5.3.0
165
+ lz4==4.4.5
166
+ Markdown==3.8
167
+ markdown-it-py==2.2.0
168
+ MarkupSafe==3.0.2
169
+ matplotlib==3.10.6
170
+ matplotlib-inline==0.2.1
171
+ mccabe==0.7.0
172
+ mdit-py-plugins==0.5.0
173
+ mdurl==0.1.2
174
+ menuinst==2.4.2
175
+ mistune==3.1.2
176
+ mkl_fft==2.1.1
177
+ mkl_random==1.3.0
178
+ mkl-service==2.5.2
179
+ more-itertools==10.8.0
180
+ mpi4py==4.0.3
181
+ mpmath==1.3.0
182
+ msgpack==1.1.1
183
+ multidict==6.7.0
184
+ multipledispatch==1.0.0
185
+ mypy==1.17.1
186
+ mypy_extensions==1.0.0
187
+ narwhals==2.7.0
188
+ navigator-updater==0.6.0
189
+ nbclient==0.10.2
190
+ nbconvert==7.16.6
191
+ nbformat==5.10.4
192
+ nest_asyncio==1.6.0
193
+ networkx==3.5
194
+ nltk==3.9.2
195
+ notebook==7.4.5
196
+ notebook_shim==0.2.4
197
+ numba==0.62.1
198
+ numexpr==2.14.1
199
+ numpy==2.3.5
200
+ numpydoc==1.9.0
201
+ openpyxl==3.1.5
202
+ overrides==7.7.0
203
+ packaging==25.0
204
+ pandas==2.3.3
205
+ pandocfilters==1.5.1
206
+ panel==1.8.3
207
+ param==2.3.0
208
+ parsel==1.10.0
209
+ parso==0.8.5
210
+ partd==1.4.2
211
+ pathspec==0.12.1
212
+ patsy==1.0.1
213
+ pexpect==4.9.0
214
+ pickleshare==0.7.5
215
+ pillow==12.0.0
216
+ pip==25.3
217
+ pkce==1.0.3
218
+ pkginfo==1.12.1.2
219
+ platformdirs==4.5.0
220
+ plotly==6.3.0
221
+ pluggy==1.5.0
222
+ prometheus_client==0.21.1
223
+ prompt_toolkit==3.0.52
224
+ propcache==0.3.1
225
+ Protego==0.4.0
226
+ protobuf==5.29.3
227
+ psutil==7.0.0
228
+ ptyprocess==0.7.0
229
+ pure_eval==0.2.3
230
+ py-cpuinfo==9.0.0
231
+ pyarrow==21.0.0
232
+ pyasn1==0.6.1
233
+ pyasn1_modules==0.4.2
234
+ pycares==4.10.0
235
+ pycodestyle==2.12.1
236
+ pycosat==0.6.6
237
+ pycparser==2.23
238
+ pyct==0.6.0
239
+ pycurl==7.45.7
240
+ pydantic==2.12.4
241
+ pydantic_core==2.41.5
242
+ pydantic-settings==2.12.0
243
+ PyDispatcher==2.0.7
244
+ pydocstyle==6.3.0
245
+ pyerfa==2.0.1.5
246
+ pyflakes==3.2.0
247
+ PyGithub==2.8.1
248
+ Pygments==2.19.2
249
+ PyJWT==2.10.1
250
+ pylint==3.3.8
251
+ pylint-venv==3.0.3
252
+ pyls-spyder==0.4.0
253
+ PyNaCl==1.6.0
254
+ pyodbc==5.3.0
255
+ pyOpenSSL==25.3.0
256
+ pyparsing==3.2.5
257
+ PyQt5==5.15.11
258
+ PyQt5_sip==12.17.0
259
+ PyQtWebEngine==5.15.7
260
+ PySide6==6.9.2
261
+ PySocks==1.7.1
262
+ pytest==8.4.2
263
+ python-dateutil==2.9.0.post0
264
+ python-dotenv==1.1.0
265
+ python-json-logger==3.2.1
266
+ python-lsp-black==2.0.0
267
+ python-lsp-jsonrpc==1.1.2
268
+ python-lsp-ruff==2.3.0
269
+ python-lsp-server==1.13.1
270
+ python-slugify==8.0.4
271
+ pytokens==0.3.0
272
+ pytoolconfig==1.2.6
273
+ pytz==2025.2
274
+ pyuca==1.2
275
+ pyviz_comms==3.0.6
276
+ PyWavelets==1.9.0
277
+ pyxdg==0.28
278
+ PyYAML==6.0.3
279
+ pyzmq==27.1.0
280
+ QDarkStyle==3.2.3
281
+ qstylizer==0.2.2
282
+ QtAwesome==1.4.0
283
+ qtconsole==5.7.0
284
+ QtPy==2.4.3
285
+ queuelib==1.8.0
286
+ readchar==4.2.1
287
+ referencing==0.37.0
288
+ regex==2025.9.1
289
+ requests==2.32.5
290
+ requests-file==2.1.0
291
+ requests-toolbelt==1.0.0
292
+ rfc3339_validator==0.1.4
293
+ rfc3986_validator==0.1.1
294
+ rich==14.2.0
295
+ roman-numerals-py==3.1.0
296
+ rope==1.14.0
297
+ rpds-py==0.28.0
298
+ rtree==1.4.1
299
+ ruamel.yaml==0.18.16
300
+ ruamel.yaml.clib==0.2.14
301
+ ruamel_yaml_conda==0.17.21
302
+ ruff==0.12.0
303
+ s3fs==2025.10.0
304
+ scikit-image==0.25.2
305
+ scikit-learn==1.7.2
306
+ scipy==1.16.3
307
+ Scrapy==2.13.3
308
+ seaborn==0.13.2
309
+ SecretStorage==3.4.0
310
+ semver==3.0.4
311
+ Send2Trash==1.8.2
312
+ service-identity==24.2.0
313
+ setuptools==80.9.0
314
+ shellingham==1.5.4
315
+ shiboken6==6.9.2
316
+ sip==6.12.0
317
+ six==1.17.0
318
+ smmap==4.0.0
319
+ sniffio==1.3.0
320
+ snowballstemmer==3.0.1
321
+ sortedcontainers==2.4.0
322
+ soupsieve==2.5
323
+ Sphinx==8.2.3
324
+ sphinxcontrib-applehelp==2.0.0
325
+ sphinxcontrib-devhelp==2.0.0
326
+ sphinxcontrib-htmlhelp==2.1.0
327
+ sphinxcontrib-jsmath==1.0.1
328
+ sphinxcontrib-qthelp==2.0.0
329
+ sphinxcontrib-serializinghtml==2.0.0
330
+ spyder==6.1.0
331
+ spyder-kernels==3.1.1
332
+ SQLAlchemy==2.0.43
333
+ stack_data==0.6.3
334
+ statsmodels==0.14.5
335
+ streamlit==1.51.0
336
+ superqt==0.7.6
337
+ sympy==1.14.0
338
+ tables==3.10.2
339
+ tabulate==0.9.0
340
+ tblib==3.1.0
341
+ tenacity==9.1.2
342
+ terminado==0.18.1
343
+ text-unidecode==1.3
344
+ textdistance==4.6.3
345
+ threadpoolctl==3.5.0
346
+ three-merge==0.1.1
347
+ tifffile==2025.10.4
348
+ tinycss2==1.4.0
349
+ tldextract==5.1.2
350
+ toml==0.10.2
351
+ tomli==2.2.1
352
+ tomlkit==0.13.3
353
+ toolz==1.0.0
354
+ tornado==6.5.1
355
+ tqdm==4.67.1
356
+ traitlets==5.14.3
357
+ truststore==0.10.1
358
+ Twisted==25.5.0
359
+ typer==0.20.0
360
+ typer-slim==0.20.0
361
+ typing_extensions==4.15.0
362
+ typing-inspection==0.4.2
363
+ tzdata==2025.2
364
+ uc-micro-py==1.0.3
365
+ ujson==5.11.0
366
+ urllib3==2.5.0
367
+ uvloop==0.22.1
368
+ w3lib==2.3.1
369
+ watchdog==6.0.0
370
+ wcwidth==0.2.13
371
+ webencodings==0.5.1
372
+ websocket-client==1.8.0
373
+ Werkzeug==3.1.3
374
+ whatthepatch==1.0.7
375
+ wheel==0.45.1
376
+ widgetsnbextension==4.0.14
377
+ wrapt==1.17.0
378
+ wurlitzer==3.1.1
379
+ xarray==2025.10.1
380
+ xyzservices==2025.4.0
381
+ yapf==0.43.0
382
+ yarl==1.22.0
383
+ zict==3.0.0
384
+ zipp==3.23.0
385
+ zope.interface==8.0.1
386
+ zstandard==0.24.0
swanlog/run-20260413_135748-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"memory": "251", "cpu": {"brand": "Intel(R) Xeon(R) w7-3455", "cores": 48}, "gpu": {"nvidia": {"driver": "550.144.03", "cores": 2, "type": ["NVIDIA RTX 6000 Ada Generation", "NVIDIA RTX 6000 Ada Generation"], "memory": ["48", "48"], "cuda": "12.4", "architecture": ["Ada", "Ada"], "cudacores": [18176, 18176]}}, "os": "Linux-6.8.0-101-generic-x86_64-with-glibc2.35", "os_pretty_name": "Ubuntu 22.04.5 LTS", "hostname": "GPUWorkstation", "pid": 1606953, "cwd": "/mnt/share01/sqk/ITFormer-ICML25", "python": "3.10.20", "python_verbose": "3.10.20 (main, Mar 11 2026, 17:46:40) [GCC 14.3.0]", "executable": "/home/suiqk/py310/bin/python", "command": "/mnt/share01/sqk/ITFormer-ICML25/train_sft.py --model TimeSeriesEncoder --d_model 512 --n_heads 8 --e_layers 4 --patch_len 60 --stride 60 --input_len 600 --it_d_model 896 --it_n_heads 16 --it_layers 2 --prefix_num 25 --llm_model_path LLM/Qwen2.5-0.5B-Instruct --load_ts_encoder save/pretrain/model.safetensors --output_dir save/debug_sft_qwen2.5_0.5B --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --learning_rate 3e-5 --num_train_epochs 1 --dataloader_num_workers 0 --logging_steps 1 --save_steps 200 --report_to none", "git_remote": null, "git_info": [null, null], "swanlab": {"version": "0.7.15", "_monitor": 5, "logdir": "/mnt/share01/sqk/ITFormer-ICML25/swanlog/run-20260413_135748-d7ug5qigf62md7jitkhbb"}}
swanlog/run-20260413_140242-d7ug5qigf62md7jitkhbb/files/config.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
swanlog/run-20260413_140242-d7ug5qigf62md7jitkhbb/files/requirements.txt ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiobotocore==2.25.0
2
+ aiodns==3.5.0
3
+ aiohappyeyeballs==2.6.1
4
+ aiohttp==3.13.2
5
+ aioitertools==0.12.0
6
+ aiosignal==1.4.0
7
+ alabaster==0.7.16
8
+ altair==5.5.0
9
+ anaconda-anon-usage==0.7.5
10
+ anaconda-auth==0.12.3
11
+ anaconda-catalogs==0.2.0
12
+ anaconda-cli-base==0.7.0
13
+ anaconda-client==1.14.0
14
+ anaconda-navigator==2.7.0
15
+ anaconda-project==0.11.1
16
+ annotated-types==0.6.0
17
+ anyio==4.10.0
18
+ appdirs==1.4.4
19
+ archspec==0.2.5
20
+ argon2-cffi==21.3.0
21
+ argon2-cffi-bindings==25.1.0
22
+ arrow==1.4.0
23
+ astroid==3.3.11
24
+ astropy==7.1.1
25
+ astropy-iers-data==0.2025.11.10.0.38.31
26
+ asttokens==3.0.0
27
+ async-lru==2.0.5
28
+ asyncssh==2.21.1
29
+ atomicwrites==1.4.0
30
+ attrs==25.4.0
31
+ Automat==24.8.1
32
+ autopep8==2.0.4
33
+ babel==2.17.0
34
+ bcrypt==5.0.0
35
+ beautifulsoup4==4.13.5
36
+ binaryornot==0.4.4
37
+ black==25.9.0
38
+ bleach==6.3.0
39
+ blinker==1.9.0
40
+ bokeh==3.8.0
41
+ boltons==25.0.0
42
+ botocore==1.40.46
43
+ Bottleneck==1.4.2
44
+ brotlicffi==1.1.0.0
45
+ cachetools==5.5.1
46
+ cattrs==25.3.0
47
+ certifi==2025.11.12
48
+ cffi==2.0.0
49
+ chardet==5.2.0
50
+ charset-normalizer==3.4.4
51
+ click==8.2.1
52
+ cloudpickle==3.1.1
53
+ colorcet==3.1.0
54
+ comm==0.2.3
55
+ conda==25.11.1
56
+ conda-anaconda-telemetry==0.3.0
57
+ conda-anaconda-tos==0.2.2
58
+ conda-build==25.11.1
59
+ conda-content-trust==0.2.0
60
+ conda_index==0.7.0
61
+ conda-libmamba-solver==25.11.0
62
+ conda-pack==0.8.1
63
+ conda-package-handling==2.4.0
64
+ conda_package_streaming==0.12.0
65
+ conda-repo-cli==1.0.173
66
+ constantly==23.10.4
67
+ contourpy==1.3.3
68
+ cookiecutter==2.6.0
69
+ cryptography==46.0.3
70
+ cssselect==1.2.0
71
+ cycler==0.11.0
72
+ dask==2025.11.0
73
+ datashader==0.18.2
74
+ debugpy==1.8.16
75
+ decorator==5.2.1
76
+ defusedxml==0.7.1
77
+ diff-match-patch==20200713
78
+ dill==0.4.0
79
+ distributed==2025.11.0
80
+ distro==1.9.0
81
+ docstring-to-markdown==0.17
82
+ docutils==0.21.2
83
+ et_xmlfile==2.0.0
84
+ evalidate==2.0.3
85
+ executing==2.2.1
86
+ fastjsonschema==2.21.2
87
+ filelock==3.20.0
88
+ flake8==7.1.1
89
+ Flask==3.1.2
90
+ fonttools==4.60.1
91
+ frozendict==2.4.6
92
+ frozenlist==1.8.0
93
+ fsspec==2025.10.0
94
+ gitdb==4.0.12
95
+ GitPython==3.1.45
96
+ gmpy2==2.2.1
97
+ greenlet==3.2.4
98
+ h11==0.16.0
99
+ h5py==3.15.1
100
+ HeapDict==1.0.1
101
+ holoviews==1.22.0
102
+ html5lib==1.1
103
+ httpcore==1.0.9
104
+ httpx==0.28.1
105
+ hvplot==0.12.1
106
+ hyperlink==21.0.0
107
+ idna==3.11
108
+ ImageIO==2.37.2
109
+ imagesize==1.4.1
110
+ imbalanced-learn==0.14.0
111
+ importlib_metadata==8.7.0
112
+ incremental==24.7.2
113
+ inflection==0.5.1
114
+ iniconfig==2.1.0
115
+ intake==2.0.8
116
+ intervaltree==3.1.0
117
+ ipykernel==6.31.0
118
+ ipympl==0.9.7
119
+ ipython==9.7.0
120
+ ipython_pygments_lexers==1.1.1
121
+ ipywidgets==8.1.7
122
+ isort==6.1.0
123
+ itemadapter==0.12.1
124
+ itemloaders==1.3.2
125
+ itsdangerous==2.2.0
126
+ jaraco.classes==3.4.0
127
+ jaraco.context==0.0.0
128
+ jaraco.functools==4.1.0
129
+ jedi==0.19.2
130
+ jeepney==0.7.1
131
+ jellyfish==1.2.1
132
+ Jinja2==3.1.6
133
+ jmespath==1.0.1
134
+ joblib==1.5.2
135
+ json5==0.12.1
136
+ jsonpatch==1.33
137
+ jsonpointer==3.0.0
138
+ jsonschema==4.25.0
139
+ jsonschema-specifications==2025.9.1
140
+ jupyter==1.1.1
141
+ jupyter_client==8.6.3
142
+ jupyter-console==6.6.3
143
+ jupyter_core==5.8.1
144
+ jupyter-events==0.12.0
145
+ jupyter-lsp==2.2.5
146
+ jupyter_server==2.16.0
147
+ jupyter_server_terminals==0.5.3
148
+ jupyterlab==4.4.7
149
+ jupyterlab_pygments==0.3.0
150
+ jupyterlab_server==2.28.0
151
+ jupyterlab_widgets==3.0.15
152
+ keyring==25.7.0
153
+ kiwisolver==1.4.9
154
+ lazy_loader==0.4
155
+ lckr_jupyterlab_variableinspector==3.2.4
156
+ libarchive-c==5.1
157
+ libmambapy==2.3.2
158
+ lief==0.16.4
159
+ linkify-it-py==2.0.3
160
+ llvmlite==0.45.1
161
+ lmdb==1.7.5
162
+ locket==1.0.0
163
+ lsprotocol==2025.0.0
164
+ lxml==5.3.0
165
+ lz4==4.4.5
166
+ Markdown==3.8
167
+ markdown-it-py==2.2.0
168
+ MarkupSafe==3.0.2
169
+ matplotlib==3.10.6
170
+ matplotlib-inline==0.2.1
171
+ mccabe==0.7.0
172
+ mdit-py-plugins==0.5.0
173
+ mdurl==0.1.2
174
+ menuinst==2.4.2
175
+ mistune==3.1.2
176
+ mkl_fft==2.1.1
177
+ mkl_random==1.3.0
178
+ mkl-service==2.5.2
179
+ more-itertools==10.8.0
180
+ mpi4py==4.0.3
181
+ mpmath==1.3.0
182
+ msgpack==1.1.1
183
+ multidict==6.7.0
184
+ multipledispatch==1.0.0
185
+ mypy==1.17.1
186
+ mypy_extensions==1.0.0
187
+ narwhals==2.7.0
188
+ navigator-updater==0.6.0
189
+ nbclient==0.10.2
190
+ nbconvert==7.16.6
191
+ nbformat==5.10.4
192
+ nest_asyncio==1.6.0
193
+ networkx==3.5
194
+ nltk==3.9.2
195
+ notebook==7.4.5
196
+ notebook_shim==0.2.4
197
+ numba==0.62.1
198
+ numexpr==2.14.1
199
+ numpy==2.3.5
200
+ numpydoc==1.9.0
201
+ openpyxl==3.1.5
202
+ overrides==7.7.0
203
+ packaging==25.0
204
+ pandas==2.3.3
205
+ pandocfilters==1.5.1
206
+ panel==1.8.3
207
+ param==2.3.0
208
+ parsel==1.10.0
209
+ parso==0.8.5
210
+ partd==1.4.2
211
+ pathspec==0.12.1
212
+ patsy==1.0.1
213
+ pexpect==4.9.0
214
+ pickleshare==0.7.5
215
+ pillow==12.0.0
216
+ pip==25.3
217
+ pkce==1.0.3
218
+ pkginfo==1.12.1.2
219
+ platformdirs==4.5.0
220
+ plotly==6.3.0
221
+ pluggy==1.5.0
222
+ prometheus_client==0.21.1
223
+ prompt_toolkit==3.0.52
224
+ propcache==0.3.1
225
+ Protego==0.4.0
226
+ protobuf==5.29.3
227
+ psutil==7.0.0
228
+ ptyprocess==0.7.0
229
+ pure_eval==0.2.3
230
+ py-cpuinfo==9.0.0
231
+ pyarrow==21.0.0
232
+ pyasn1==0.6.1
233
+ pyasn1_modules==0.4.2
234
+ pycares==4.10.0
235
+ pycodestyle==2.12.1
236
+ pycosat==0.6.6
237
+ pycparser==2.23
238
+ pyct==0.6.0
239
+ pycurl==7.45.7
240
+ pydantic==2.12.4
241
+ pydantic_core==2.41.5
242
+ pydantic-settings==2.12.0
243
+ PyDispatcher==2.0.7
244
+ pydocstyle==6.3.0
245
+ pyerfa==2.0.1.5
246
+ pyflakes==3.2.0
247
+ PyGithub==2.8.1
248
+ Pygments==2.19.2
249
+ PyJWT==2.10.1
250
+ pylint==3.3.8
251
+ pylint-venv==3.0.3
252
+ pyls-spyder==0.4.0
253
+ PyNaCl==1.6.0
254
+ pyodbc==5.3.0
255
+ pyOpenSSL==25.3.0
256
+ pyparsing==3.2.5
257
+ PyQt5==5.15.11
258
+ PyQt5_sip==12.17.0
259
+ PyQtWebEngine==5.15.7
260
+ PySide6==6.9.2
261
+ PySocks==1.7.1
262
+ pytest==8.4.2
263
+ python-dateutil==2.9.0.post0
264
+ python-dotenv==1.1.0
265
+ python-json-logger==3.2.1
266
+ python-lsp-black==2.0.0
267
+ python-lsp-jsonrpc==1.1.2
268
+ python-lsp-ruff==2.3.0
269
+ python-lsp-server==1.13.1
270
+ python-slugify==8.0.4
271
+ pytokens==0.3.0
272
+ pytoolconfig==1.2.6
273
+ pytz==2025.2
274
+ pyuca==1.2
275
+ pyviz_comms==3.0.6
276
+ PyWavelets==1.9.0
277
+ pyxdg==0.28
278
+ PyYAML==6.0.3
279
+ pyzmq==27.1.0
280
+ QDarkStyle==3.2.3
281
+ qstylizer==0.2.2
282
+ QtAwesome==1.4.0
283
+ qtconsole==5.7.0
284
+ QtPy==2.4.3
285
+ queuelib==1.8.0
286
+ readchar==4.2.1
287
+ referencing==0.37.0
288
+ regex==2025.9.1
289
+ requests==2.32.5
290
+ requests-file==2.1.0
291
+ requests-toolbelt==1.0.0
292
+ rfc3339_validator==0.1.4
293
+ rfc3986_validator==0.1.1
294
+ rich==14.2.0
295
+ roman-numerals-py==3.1.0
296
+ rope==1.14.0
297
+ rpds-py==0.28.0
298
+ rtree==1.4.1
299
+ ruamel.yaml==0.18.16
300
+ ruamel.yaml.clib==0.2.14
301
+ ruamel_yaml_conda==0.17.21
302
+ ruff==0.12.0
303
+ s3fs==2025.10.0
304
+ scikit-image==0.25.2
305
+ scikit-learn==1.7.2
306
+ scipy==1.16.3
307
+ Scrapy==2.13.3
308
+ seaborn==0.13.2
309
+ SecretStorage==3.4.0
310
+ semver==3.0.4
311
+ Send2Trash==1.8.2
312
+ service-identity==24.2.0
313
+ setuptools==80.9.0
314
+ shellingham==1.5.4
315
+ shiboken6==6.9.2
316
+ sip==6.12.0
317
+ six==1.17.0
318
+ smmap==4.0.0
319
+ sniffio==1.3.0
320
+ snowballstemmer==3.0.1
321
+ sortedcontainers==2.4.0
322
+ soupsieve==2.5
323
+ Sphinx==8.2.3
324
+ sphinxcontrib-applehelp==2.0.0
325
+ sphinxcontrib-devhelp==2.0.0
326
+ sphinxcontrib-htmlhelp==2.1.0
327
+ sphinxcontrib-jsmath==1.0.1
328
+ sphinxcontrib-qthelp==2.0.0
329
+ sphinxcontrib-serializinghtml==2.0.0
330
+ spyder==6.1.0
331
+ spyder-kernels==3.1.1
332
+ SQLAlchemy==2.0.43
333
+ stack_data==0.6.3
334
+ statsmodels==0.14.5
335
+ streamlit==1.51.0
336
+ superqt==0.7.6
337
+ sympy==1.14.0
338
+ tables==3.10.2
339
+ tabulate==0.9.0
340
+ tblib==3.1.0
341
+ tenacity==9.1.2
342
+ terminado==0.18.1
343
+ text-unidecode==1.3
344
+ textdistance==4.6.3
345
+ threadpoolctl==3.5.0
346
+ three-merge==0.1.1
347
+ tifffile==2025.10.4
348
+ tinycss2==1.4.0
349
+ tldextract==5.1.2
350
+ toml==0.10.2
351
+ tomli==2.2.1
352
+ tomlkit==0.13.3
353
+ toolz==1.0.0
354
+ tornado==6.5.1
355
+ tqdm==4.67.1
356
+ traitlets==5.14.3
357
+ truststore==0.10.1
358
+ Twisted==25.5.0
359
+ typer==0.20.0
360
+ typer-slim==0.20.0
361
+ typing_extensions==4.15.0
362
+ typing-inspection==0.4.2
363
+ tzdata==2025.2
364
+ uc-micro-py==1.0.3
365
+ ujson==5.11.0
366
+ urllib3==2.5.0
367
+ uvloop==0.22.1
368
+ w3lib==2.3.1
369
+ watchdog==6.0.0
370
+ wcwidth==0.2.13
371
+ webencodings==0.5.1
372
+ websocket-client==1.8.0
373
+ Werkzeug==3.1.3
374
+ whatthepatch==1.0.7
375
+ wheel==0.45.1
376
+ widgetsnbextension==4.0.14
377
+ wrapt==1.17.0
378
+ wurlitzer==3.1.1
379
+ xarray==2025.10.1
380
+ xyzservices==2025.4.0
381
+ yapf==0.43.0
382
+ yarl==1.22.0
383
+ zict==3.0.0
384
+ zipp==3.23.0
385
+ zope.interface==8.0.1
386
+ zstandard==0.24.0
swanlog/run-20260413_140242-d7ug5qigf62md7jitkhbb/files/swanlab-metadata.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"memory": "251", "cpu": {"brand": "Intel(R) Xeon(R) w7-3455", "cores": 48}, "gpu": {"nvidia": {"driver": "550.144.03", "cores": 2, "type": ["NVIDIA RTX 6000 Ada Generation", "NVIDIA RTX 6000 Ada Generation"], "memory": ["48", "48"], "cuda": "12.4", "architecture": ["Ada", "Ada"], "cudacores": [18176, 18176]}}, "os": "Linux-6.8.0-101-generic-x86_64-with-glibc2.35", "os_pretty_name": "Ubuntu 22.04.5 LTS", "hostname": "GPUWorkstation", "pid": 1607862, "cwd": "/mnt/share01/sqk/ITFormer-ICML25", "python": "3.10.20", "python_verbose": "3.10.20 (main, Mar 11 2026, 17:46:40) [GCC 14.3.0]", "executable": "/home/suiqk/py310/bin/python", "command": "train_sft.py --model TimeSeriesEncoder --d_model 512 --n_heads 8 --e_layers 4 --patch_len 60 --stride 60 --input_len 600 --it_d_model 896 --it_n_heads 16 --it_layers 2 --prefix_num 25 --llm_model_path LLM/Qwen2.5-0.5B-Instruct --load_ts_encoder save/pretrain/model.safetensors --output_dir save/sft_qwen2.5_0.5B --per_device_train_batch_size 24 --learning_rate 3e-5 --num_train_epochs 2 --dataloader_num_workers 4 --report_to none", "git_remote": null, "git_info": [null, null], "swanlab": {"version": "0.7.15", "_monitor": 5, "logdir": "/mnt/share01/sqk/ITFormer-ICML25/swanlog/run-20260413_140242-d7ug5qigf62md7jitkhbb"}}
train_pretrain.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.simplefilter("ignore", category=UserWarning)
3
+ warnings.filterwarnings("ignore", category=FutureWarning, message=".*TRANSFORMERS_CACHE.*")
4
+ import os
5
+ import logging
6
+ from transformers.utils import logging as transformers_logging
7
+
8
+ # 只在主进程显示进度条和日志
9
+ if os.environ.get("LOCAL_RANK", "0") == "0":
10
+ transformers_logging.set_verbosity_info()
11
+ else:
12
+ transformers_logging.set_verbosity_error()
13
+ logging.disable(logging.CRITICAL)
14
+
15
+ from transformers import AutoTokenizer
16
+ from transformers import AutoProcessor
17
+ import torch.nn as nn
18
+ from dataset.dataset import TsQaDataset,PretrainDataset
19
+ import argparse
20
+ from models.TimeLanguageModel import TLMConfig
21
+ try:
22
+ import swanlab as wandb
23
+ SWANLAB_AVAILABLE = True
24
+ except ModuleNotFoundError:
25
+ SWANLAB_AVAILABLE = False
26
+
27
+ class _NoopWandb:
28
+ @staticmethod
29
+ def init(*args, **kwargs):
30
+ print("swanlab is not installed; training will run without swanlab logging.")
31
+
32
+ wandb = _NoopWandb()
33
+ from EXP.exp_pretraining import Exp_Pretrain
34
+ from accelerate import Accelerator
35
+ from utils.accelerate_compat import patch_accelerate_unwrap_model
36
+
37
+ if __name__ == '__main__':
38
+ patch_accelerate_unwrap_model()
39
+ accelerator = Accelerator()
40
+
41
+ #读取args
42
+ parser = argparse.ArgumentParser(description='TsEncoder Pretrain')
43
+ parser.add_argument('--fix_seed', type=int, default=None, help='seed')
44
+
45
+ #Model settings
46
+ parser.add_argument('--model', type=str, required=False, default='TimeSeriesEncoder',
47
+ help='model name')
48
+ parser.add_argument('--d_model', type=int, default=512,
49
+ help='dimension of model')
50
+ parser.add_argument('--n_heads', type=int, default=8, help='num of heads')
51
+ parser.add_argument('--e_layers', type=int, default=4,
52
+ help='num of encoder layers')
53
+ parser.add_argument("--patch_len", type=int, default=60)
54
+ parser.add_argument("--stride", type=int, default=60)
55
+ parser.add_argument("--input_len", type=int, default=600)
56
+ parser.add_argument('--dropout', type=float, default=0.1, help='dropout')
57
+
58
+ #Pretrain settings
59
+ parser.add_argument('--pretrain', type=bool, default=True, help='pretrain mode')
60
+ parser.add_argument('--min_mask_ratio', type=float, default=0.7, help='minimum mask ratio')
61
+ parser.add_argument('--max_mask_ratio', type=float, default=0.8, help='maximum mask ratio')
62
+
63
+ # Training arguments
64
+ parser.add_argument('--do_train', type=bool, default=True, help='whether to do training')
65
+ parser.add_argument('--per_device_train_batch_size', type=int, default=12, help='batch size per device during training')
66
+ parser.add_argument('--per_device_eval_batch_size', type=int, default=12, help='batch size for evaluation')
67
+ parser.add_argument('--learning_rate', type=float, default=1e-5, help='learning rate')
68
+ parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help='number of updates steps to accumulate before performing a backward/update pass')
69
+ parser.add_argument('--num_train_epochs', type=int, default=10, help='number of training epochs')
70
+ parser.add_argument('--weight_decay', type=float, default=1e-5, help='weight decay')
71
+
72
+ #Efficiency settings
73
+ parser.add_argument('--fp16', type=bool, default=True, help='whether to use 16-bit (mixed) precision')
74
+ parser.add_argument('--dataloader_pin_memory', type=bool, default=True, help='pin memory in data loader')
75
+ parser.add_argument('--dataloader_num_workers', type=int, default=8, help='number of subprocesses to use for data loading')
76
+
77
+ #logging settings
78
+ parser.add_argument('--output_dir', type=str, default='save/pretrain_ts_small', help='output directory')
79
+ parser.add_argument('--save_steps', type=int, default=100, help='save checkpoint every X updates steps')
80
+ parser.add_argument('--save_total_limit', type=int, default=2, help='limit the total amount of checkpoints')
81
+ parser.add_argument('--logging_steps', type=int, default=200, help='log every X updates steps')
82
+ parser.add_argument('--report_to', type=str, default="swanlab", help='report results to')
83
+
84
+ args = parser.parse_args()
85
+ if not SWANLAB_AVAILABLE and args.report_to in {"swanlab", "swandb"}:
86
+ args.report_to = "none"
87
+
88
+ ##data setting
89
+ tlmconfig = TLMConfig(llm_model_path = 'LLM/Qwen2.5-0.5B-Instruct')
90
+ ts_path = 'dataset/datasets/time_series_data.h5'
91
+ tokenizer = AutoTokenizer.from_pretrained(tlmconfig.llm_model_path)
92
+ processor = AutoProcessor.from_pretrained(tlmconfig.llm_model_path)
93
+ dataset = PretrainDataset(ts_path)
94
+
95
+ if accelerator.is_main_process:
96
+ wandb.init(mode="offline",project="TSLLM-TsEncoder", name="XXX")
97
+
98
+ Trainer = Exp_Pretrain(args, dataset)
99
+
100
+ Trainer.train(resume_from_checkpoint=False)
101
+ Trainer.save_model('save/pretrain')
102
+ Trainer.save_state()
train_pretrain_rats40k.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage A: Pre-train TimeSeriesEncoder on RATs40K univariate data
3
+ using masked patch reconstruction (MAE).
4
+
5
+ Key differences from the original train_pretrain.py:
6
+ - input_len=128, patch_len=16, stride=16 (8 patches per sequence)
7
+ - D=1 (univariate), loaded from RATs40K JSON
8
+ - mask_ratio reduced to 0.4-0.6 (short sequences, fewer patches)
9
+ """
10
+ import warnings
11
+ warnings.simplefilter("ignore", category=UserWarning)
12
+ warnings.filterwarnings("ignore", category=FutureWarning, message=".*TRANSFORMERS_CACHE.*")
13
+
14
+ import os
15
+ import logging
16
+ from transformers.utils import logging as transformers_logging
17
+
18
+ if os.environ.get("LOCAL_RANK", "0") == "0":
19
+ transformers_logging.set_verbosity_info()
20
+ else:
21
+ transformers_logging.set_verbosity_error()
22
+ logging.disable(logging.CRITICAL)
23
+
24
+ import argparse
25
+ from accelerate import Accelerator
26
+ from utils.accelerate_compat import patch_accelerate_unwrap_model as patch_accelerate_compat
27
+
28
+ try:
29
+ import swanlab as wandb
30
+ _SWANLAB = True
31
+ except ModuleNotFoundError:
32
+ _SWANLAB = False
33
+
34
+ class _Noop:
35
+ @staticmethod
36
+ def init(*a, **k):
37
+ print("swanlab not installed; running without logging.")
38
+
39
+ wandb = _Noop()
40
+
41
+ from EXP.exp_pretraining import Exp_Pretrain
42
+ from dataset.rats40k_dataset import RATsPretrainDataset
43
+
44
+
45
+ def main():
46
+ patch_accelerate_compat()
47
+ accelerator = Accelerator()
48
+
49
+ parser = argparse.ArgumentParser(description="Pretrain TimeSeriesEncoder on RATs40K")
50
+ # ── data ──────────────────────────────────────────────────────────────
51
+ parser.add_argument("--data_path", default="/mnt/share01/sqk/datasets/RATs40K/RATs-Uni-TSImage_Reason.json")
52
+ parser.add_argument("--train_split", default="TSAD_train")
53
+ # ── TS encoder ────────────────────────────────────────────────────────
54
+ parser.add_argument("--model", default="TimeSeriesEncoder")
55
+ parser.add_argument("--d_model", type=int, default=512)
56
+ parser.add_argument("--n_heads", type=int, default=8)
57
+ parser.add_argument("--e_layers", type=int, default=4)
58
+ # patch_len=16 / input_len=128 -> 8 patches (from-scratch MAE on RATs40K)
59
+ parser.add_argument("--patch_len", type=int, default=16)
60
+ parser.add_argument("--stride", type=int, default=16)
61
+ parser.add_argument("--input_len", type=int, default=128)
62
+ parser.add_argument("--dropout", type=float, default=0.1)
63
+ # ── MAE ───────────────────────────────────────────────────────────────
64
+ parser.add_argument("--pretrain", type=bool, default=True)
65
+ parser.add_argument("--min_mask_ratio", type=float, default=0.4)
66
+ parser.add_argument("--max_mask_ratio", type=float, default=0.6)
67
+ # ── training ──────────────────────────────────────────────────────────
68
+ parser.add_argument("--per_device_train_batch_size", type=int, default=256)
69
+ parser.add_argument("--per_device_eval_batch_size", type=int, default=256)
70
+ parser.add_argument("--learning_rate", type=float, default=1e-4)
71
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
72
+ parser.add_argument("--num_train_epochs", type=int, default=20)
73
+ parser.add_argument("--weight_decay", type=float, default=1e-5)
74
+ parser.add_argument("--fp16", type=bool, default=True)
75
+ parser.add_argument("--dataloader_pin_memory", type=bool, default=True)
76
+ parser.add_argument("--dataloader_num_workers", type=int, default=4)
77
+ # ── logging / saving ──────────────────────────────────────────────────
78
+ parser.add_argument("--output_dir", default="save/pretrain_rats40k")
79
+ parser.add_argument("--save_steps", type=int, default=200)
80
+ parser.add_argument("--save_total_limit", type=int, default=2)
81
+ parser.add_argument("--logging_steps", type=int, default=50)
82
+ parser.add_argument("--report_to", default="none")
83
+
84
+ args = parser.parse_args()
85
+ if not _SWANLAB and args.report_to in {"swanlab", "swandb"}:
86
+ args.report_to = "none"
87
+
88
+ dataset = RATsPretrainDataset(
89
+ data_path=args.data_path,
90
+ split=args.train_split,
91
+ input_len=args.input_len,
92
+ )
93
+ if accelerator.is_main_process:
94
+ print(f"Pretrain dataset size: {len(dataset)}")
95
+ print(f"ts_values shape per sample: {dataset[0]['ts_values'].shape}")
96
+ wandb.init(mode="offline", project="ITFormer-RATs40K-Pretrain", name="pretrain")
97
+
98
+ trainer = Exp_Pretrain(args, dataset)
99
+ trainer.train(resume_from_checkpoint=False)
100
+ trainer.save_model("save/pretrain_rats40k")
101
+ trainer.save_state()
102
+
103
+ if accelerator.is_main_process:
104
+ print(f"Pre-training done. Weights saved to save/pretrain_rats40k/model.safetensors")
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
train_sft.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel, PretrainedConfig, AutoTokenizer, AutoModelForCausalLM
2
+ from transformers import AutoProcessor, AutoModel
3
+ import warnings
4
+ warnings.filterwarnings("ignore", category=FutureWarning, message=".*TRANSFORMERS_CACHE.*")
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from transformers.modeling_outputs import CausalLMOutputWithPast
9
+ from transformers import Trainer, TrainingArguments, DataCollatorWithPadding
10
+ from dataset.dataset import TsQaDataset,DataCollator
11
+ import argparse
12
+ from models.TimeLanguageModel import TLMConfig, TLM
13
+ import os
14
+ try:
15
+ import swanlab as wandb
16
+ SWANLAB_AVAILABLE = True
17
+ except ModuleNotFoundError:
18
+ SWANLAB_AVAILABLE = False
19
+
20
+ class _NoopWandb:
21
+ @staticmethod
22
+ def init(*args, **kwargs):
23
+ print("swanlab is not installed; training will run without swanlab logging.")
24
+
25
+ wandb = _NoopWandb()
26
+ from EXP.exp_instruct import Exp_Instruct
27
+ from accelerate import Accelerator
28
+ from utils.accelerate_compat import patch_accelerate_unwrap_model
29
+
30
+ patch_accelerate_unwrap_model()
31
+ accelerator = Accelerator(device_placement=True)# # 限制只使用 GPU 0,debug模式
32
+ import os
33
+ import random
34
+ import numpy as np
35
+ import sys
36
+ import logging
37
+ from transformers.utils import logging as transformers_logging
38
+
39
+ def str2bool(value):
40
+ if isinstance(value, bool):
41
+ return value
42
+ return str(value).lower() in {"true", "1", "yes", "y"}
43
+
44
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
45
+ os.environ["WANDB_MODE"] = "offline"
46
+
47
+ # 设置日志级别,主进程显示进度,从进程静默
48
+ if os.environ.get("LOCAL_RANK", "0") == "0":
49
+ transformers_logging.set_verbosity_info()
50
+ else:
51
+ transformers_logging.set_verbosity_error()
52
+ logging.disable(logging.CRITICAL)
53
+
54
+ # # 启用异常检测
55
+
56
+ if __name__ == '__main__':
57
+ #读取args
58
+ parser = argparse.ArgumentParser(description='Mutimodal SFT')
59
+ parser.add_argument('--fix_seed', type=int, default=None, help='seed')
60
+
61
+ #TsEncoder settings
62
+ parser.add_argument('--model', type=str, required=False, default='TimeSeriesEncoder',
63
+ help='model name')
64
+ parser.add_argument('--d_model', type=int, default=512,
65
+ help='dimension of model')
66
+ parser.add_argument('--n_heads', type=int, default=8, help='num of heads')
67
+ parser.add_argument('--e_layers', type=int, default=4,
68
+ help='num of encoder layers')
69
+ parser.add_argument("--patch_len", type=int, default=60)
70
+ parser.add_argument("--stride", type=int, default=60)
71
+ parser.add_argument("--input_len", type=int, default=600)
72
+ parser.add_argument('--dropout', type=float, default=0.1, help='dropout')
73
+ parser.add_argument('--load_ts_encoder', type=str, default='save/pretrain/model.safetensors', help='load ts_encoder')
74
+
75
+ #ITFormer setting
76
+ parser.add_argument('--it_d_model', type=int, default=896, help='dimension of IT model')
77
+ parser.add_argument('--it_n_heads', type=int, default=16, help='num of IT heads')
78
+ parser.add_argument('--it_layers', type=int, default=2, help='num of IT layers')
79
+ parser.add_argument('--it_dropout', type=float, default=0.1, help='dropout for IT model')
80
+ parser.add_argument('--prefix_num', type=int, default=25, help='number of prefixes')
81
+ parser.add_argument('--adapter_type', type=str, default='itformer', choices=['itformer', 'qformer'],
82
+ help='adapter type for bridging time-series and LLM embeddings')
83
+
84
+ #LLM setting
85
+ parser.add_argument('--llm_model_path', type=str, default='LLM/Qwen2.5-0.5B-Instruct', help='LLM model path')
86
+ parser.add_argument('--llm_attn_implementation', type=str, default=None,
87
+ choices=['eager', 'sdpa', 'flash_attention_2'],
88
+ help='attention implementation passed to AutoModelForCausalLM.from_pretrained')
89
+
90
+ #Pretrain settings
91
+ parser.add_argument('--pretrain', type=bool, default=False, help='pretrain mode')
92
+ parser.add_argument('--min_mask_ratio', type=float, default=0.7, help='minimum mask ratio')
93
+ parser.add_argument('--max_mask_ratio', type=float, default=0.8, help='maximum mask ratio')
94
+
95
+ # Training arguments
96
+ parser.add_argument('--do_train', type=bool, default=True, help='whether to do training')
97
+ parser.add_argument('--per_device_train_batch_size', type=int, default=12, help='batch size per device during training')
98
+ parser.add_argument('--per_device_eval_batch_size', type=int, default=12, help='batch size for evaluation')
99
+ parser.add_argument('--learning_rate', type=float, default=1e-5, help='learning rate') #7B 1e-5
100
+ parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help='number of updates steps to accumulate before performing a backward/update pass')
101
+ parser.add_argument('--num_train_epochs', type=int, default=2, help='number of training epochs')
102
+ parser.add_argument('--weight_decay', type=float, default=1e-6, help='weight decay')
103
+ parser.add_argument('--freeze_ts_model',type=bool,default=True,help='wheter freeze ts encoder')
104
+ #Efficiency settings
105
+ parser.add_argument('--fp16', type=str2bool, default=True, help='whether to use fp16 mixed precision')
106
+ parser.add_argument('--bf16', action='store_true', help='whether to use bf16 mixed precision')
107
+ parser.add_argument('--dataloader_pin_memory', type=bool, default=True, help='pin memory in data loader')
108
+ parser.add_argument('--dataloader_num_workers', type=int, default=4, help='number of subprocesses to use for data loading')
109
+
110
+ #logging settings
111
+ parser.add_argument('--output_dir', type=str, default='save/sft_qwen2.5_0.5B_infra', help='output directory')
112
+ parser.add_argument('--save_steps', type=int, default=1000, help='save checkpoint every X updates steps')
113
+
114
+ parser.add_argument('--save_total_limit', type=int, default=2, help='limit the total amount of checkpoints')
115
+ parser.add_argument('--logging_steps', type=int, default=50, help='log every X updates steps')
116
+ parser.add_argument('--eval_steps', type=int, default=300000000000000000, help='eval every X updates steps')
117
+
118
+ parser.add_argument('--report_to', type=str, default="swandb", help='report results to')
119
+ parser.add_argument('--mode', type=str, default='train', help='inference or train')
120
+ parser.add_argument('--eval_stragy',type=str,default="no",help='The evaluation strategy to adopt during training')
121
+ parser.add_argument('--shuffle', type=bool, default=True, help='whether to shuffle the dataset')
122
+
123
+
124
+ args = parser.parse_args()
125
+ if not SWANLAB_AVAILABLE and args.report_to in {"swanlab", "swandb"}:
126
+ args.report_to = "none"
127
+
128
+ # 设置固定的随机种子
129
+ seed = 42
130
+
131
+ # Python 随机模块
132
+ random.seed(seed)
133
+
134
+ # NumPy 随机模块
135
+ np.random.seed(seed)
136
+
137
+ # PyTorch 随机模块
138
+ torch.manual_seed(seed)
139
+ torch.cuda.manual_seed(seed) # 对 CUDA 的种子进行控制
140
+ torch.cuda.manual_seed_all(seed) # 对所有 GPU 进行控制
141
+ ##Model setting
142
+ tlmconfig = TLMConfig(llm_model_path=args.llm_model_path,
143
+ freeze_ts_model=args.freeze_ts_model,
144
+ ts_pad_num=args.prefix_num,
145
+ llm_attn_implementation=args.llm_attn_implementation)
146
+
147
+ ts_past_train = 'dataset/datasets/time_series_data.h5'
148
+ qa_past_train = 'dataset/datasets/train_qa.jsonl'
149
+
150
+ ts_path_test = 'dataset/datasets/time_series_data.h5'
151
+ qa_path_test = 'dataset/datasets/test_qa.jsonl'
152
+
153
+ tokenizer = AutoTokenizer.from_pretrained(tlmconfig.llm_model_path)
154
+ tokenizer.padding_side = 'left'
155
+ processor = AutoProcessor.from_pretrained(tlmconfig.llm_model_path)
156
+ train_dataset = TsQaDataset(ts_past_train, qa_past_train,
157
+ tokenizer, processor, tlmconfig,sft=True, shuffle=args.shuffle)
158
+ test_dataset = TsQaDataset(ts_path_test, qa_path_test,
159
+ tokenizer, processor, tlmconfig)
160
+
161
+ if accelerator.is_main_process:
162
+ # wandb.init(project="TSLLM", name="pandalin")
163
+ #设置offline
164
+ wandb.init(mode="offline", project="XXX", name="XXX")
165
+ Trainer = Exp_Instruct(args, train_dataset=train_dataset, eval_dataset=test_dataset,tlm_config=tlmconfig) # Trainer.train(resume_from_checkpoint=False)
166
+ Trainer.train(resume_from_checkpoint=False)
167
+ Trainer.evaluate()
168
+
169
+
170
+
171
+
172
+
173
+
train_sft_rats40k.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage B: SFT – fine-tune the full TLM (TS Encoder + ITFormer + LLM)
3
+ on RATs40K univariate anomaly reasoning data.
4
+
5
+ All samples are assigned stage=1 (single short window).
6
+ """
7
+ import warnings
8
+ warnings.simplefilter("ignore", category=UserWarning)
9
+ warnings.filterwarnings("ignore", category=FutureWarning, message=".*TRANSFORMERS_CACHE.*")
10
+
11
+ import os
12
+ import logging
13
+ import random
14
+ import numpy as np
15
+ import torch
16
+ from transformers.utils import logging as transformers_logging
17
+
18
+ if os.environ.get("LOCAL_RANK", "0") == "0":
19
+ transformers_logging.set_verbosity_info()
20
+ else:
21
+ transformers_logging.set_verbosity_error()
22
+ logging.disable(logging.CRITICAL)
23
+
24
+ import argparse
25
+ from transformers import AutoTokenizer
26
+ from accelerate import Accelerator
27
+ from utils.accelerate_compat import patch_accelerate_unwrap_model as patch_accelerate_compat
28
+ from models.TimeLanguageModel import TLMConfig
29
+ from EXP.exp_instruct import Exp_Instruct
30
+ from dataset.rats40k_dataset import RATsQADataset, RATsDataCollator
31
+
32
+ try:
33
+ import swanlab as wandb
34
+ _SWANLAB = True
35
+ except ModuleNotFoundError:
36
+ _SWANLAB = False
37
+
38
+ class _Noop:
39
+ @staticmethod
40
+ def init(*a, **k):
41
+ print("swanlab not installed; running without logging.")
42
+
43
+ wandb = _Noop()
44
+
45
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
46
+ os.environ["WANDB_MODE"] = "offline"
47
+
48
+
49
+ def str2bool(v):
50
+ return str(v).lower() in {"true", "1", "yes", "y"}
51
+
52
+
53
+ def main():
54
+ patch_accelerate_compat()
55
+ accelerator = Accelerator(device_placement=True)
56
+
57
+ seed = 42
58
+ random.seed(seed)
59
+ np.random.seed(seed)
60
+ torch.manual_seed(seed)
61
+ if torch.cuda.is_available():
62
+ torch.cuda.manual_seed_all(seed)
63
+
64
+ parser = argparse.ArgumentParser(description="SFT TLM on RATs40K")
65
+ # ── data ──────────────────────────────────────────────────────────────
66
+ parser.add_argument("--data_path", default="/mnt/share01/sqk/datasets/RATs40K/RATs-Uni-TSImage_Reason.json")
67
+ parser.add_argument("--train_split", default="TSAD_train")
68
+ parser.add_argument("--eval_split", default="TSAD_test")
69
+ # ── TS encoder ────────────────────────────────────────────────────────
70
+ parser.add_argument("--model", default="TimeSeriesEncoder")
71
+ parser.add_argument("--d_model", type=int, default=512)
72
+ parser.add_argument("--n_heads", type=int, default=8)
73
+ parser.add_argument("--e_layers", type=int, default=4)
74
+ # patch_len=16 / input_len=128 -> 8 patches (RATs40K-pretrained encoder)
75
+ parser.add_argument("--patch_len", type=int, default=16)
76
+ parser.add_argument("--stride", type=int, default=16)
77
+ parser.add_argument("--input_len", type=int, default=128)
78
+ parser.add_argument("--dropout", type=float, default=0.1)
79
+ parser.add_argument("--load_ts_encoder", default="save/pretrain_rats40k/model.safetensors")
80
+ # ── ITFormer adapter ──────────────────────────────────────────────────
81
+ # it_d_model must equal LLM hidden_size: 896 (0.5B) / 2048 (3B) / 3584 (7B)
82
+ parser.add_argument("--it_d_model", type=int, default=3584)
83
+ parser.add_argument("--it_n_heads", type=int, default=28)
84
+ parser.add_argument("--it_layers", type=int, default=2)
85
+ parser.add_argument("--it_dropout", type=float, default=0.1)
86
+ parser.add_argument("--prefix_num", type=int, default=8,
87
+ help="Number of TS summary tokens (= n_patches for RATs40K)")
88
+ parser.add_argument("--adapter_type", default="itformer", choices=["itformer", "qformer"])
89
+ # ── LLM ───────────────────────────────────────────────────────────────
90
+ parser.add_argument("--llm_model_path", default="/mnt/share01/sqk/models/qwen2.5-7b-instruct")
91
+ parser.add_argument("--llm_attn_implementation", default=None,
92
+ choices=["eager", "sdpa", "flash_attention_2", None])
93
+ parser.add_argument("--freeze_ts_model", type=str2bool, default=True)
94
+ # ── training ──────────────────────────────────────────────────────────
95
+ parser.add_argument("--pretrain", type=bool, default=False)
96
+ parser.add_argument("--min_mask_ratio", type=float, default=0.4)
97
+ parser.add_argument("--max_mask_ratio", type=float, default=0.6)
98
+ parser.add_argument("--per_device_train_batch_size", type=int, default=4)
99
+ parser.add_argument("--per_device_eval_batch_size", type=int, default=4)
100
+ parser.add_argument("--learning_rate", type=float, default=2e-5)
101
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=4)
102
+ parser.add_argument("--num_train_epochs", type=int, default=3)
103
+ parser.add_argument("--weight_decay", type=float, default=1e-6)
104
+ parser.add_argument("--fp16", type=str2bool, default=False)
105
+ parser.add_argument("--bf16", action="store_true")
106
+ parser.add_argument("--dataloader_pin_memory", type=bool, default=True)
107
+ parser.add_argument("--dataloader_num_workers", type=int, default=4)
108
+ # ── logging / saving ──────────────────────────────────────────────────
109
+ parser.add_argument("--output_dir", default="save/sft_rats40k")
110
+ parser.add_argument("--save_steps", type=int, default=500)
111
+ parser.add_argument("--save_total_limit", type=int, default=2)
112
+ parser.add_argument("--logging_steps", type=int, default=20)
113
+ parser.add_argument("--eval_steps", type=int, default=999999999)
114
+ parser.add_argument("--eval_stragy", default="no")
115
+ parser.add_argument("--shuffle", type=str2bool, default=True)
116
+ parser.add_argument("--report_to", default="none")
117
+ parser.add_argument("--mode", default="train")
118
+
119
+ args = parser.parse_args()
120
+ if not _SWANLAB and args.report_to in {"swanlab", "swandb"}:
121
+ args.report_to = "none"
122
+
123
+ # ── tokenizer ─────────────────────────────────────────────────────────
124
+ tokenizer = AutoTokenizer.from_pretrained(args.llm_model_path)
125
+ tokenizer.padding_side = "left"
126
+ if tokenizer.pad_token is None:
127
+ tokenizer.pad_token = tokenizer.eos_token
128
+ if "<|image_pad|>" not in tokenizer.get_vocab():
129
+ tokenizer.add_tokens(["<|image_pad|>"])
130
+
131
+ # ── datasets ──────────────────────────────────────────────────────────
132
+ train_dataset = RATsQADataset(
133
+ data_path=args.data_path,
134
+ split=args.train_split,
135
+ tokenizer=tokenizer,
136
+ ts_pad_num=args.prefix_num,
137
+ input_len=args.input_len,
138
+ shuffle=args.shuffle,
139
+ )
140
+ eval_dataset = RATsQADataset(
141
+ data_path=args.data_path,
142
+ split=args.eval_split,
143
+ tokenizer=tokenizer,
144
+ ts_pad_num=args.prefix_num,
145
+ input_len=args.input_len,
146
+ shuffle=False,
147
+ )
148
+ if accelerator.is_main_process:
149
+ print(f"Train: {len(train_dataset)} samples | Eval: {len(eval_dataset)} samples")
150
+
151
+ # ── TLM config ────────────────────────────────────────────────────────
152
+ tlm_config = TLMConfig(
153
+ llm_model_path=args.llm_model_path,
154
+ freeze_ts_model=args.freeze_ts_model,
155
+ ts_pad_num=args.prefix_num,
156
+ llm_attn_implementation=args.llm_attn_implementation,
157
+ )
158
+
159
+ if accelerator.is_main_process:
160
+ wandb.init(mode="offline", project="ITFormer-RATs40K-SFT", name="sft")
161
+
162
+ # ── Exp_Instruct wraps HuggingFace Trainer ─────────────────────────────
163
+ # We monkey-patch the processor attribute that Exp_Instruct expects
164
+ # (it normally comes from TsQaDataset; here we supply the tokenizer directly)
165
+ train_dataset.processor = tokenizer
166
+
167
+ trainer = Exp_Instruct(
168
+ args,
169
+ train_dataset=train_dataset,
170
+ eval_dataset=eval_dataset,
171
+ tlm_config=tlm_config,
172
+ )
173
+ # Replace default DataCollator with RATs-aware one
174
+ trainer.data_collator = RATsDataCollator(tokenizer)
175
+
176
+ # Resize LLM embeddings if new tokens were added
177
+ if len(tokenizer) != trainer.model.llm_model.config.vocab_size:
178
+ trainer.model.llm_model.resize_token_embeddings(len(tokenizer))
179
+ if accelerator.is_main_process:
180
+ print(f"Resized LLM embeddings to {len(tokenizer)}")
181
+
182
+ trainer.train(resume_from_checkpoint=False)
183
+
184
+ if accelerator.is_main_process:
185
+ print(f"\nSFT done. Checkpoint saved to {args.output_dir}")
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
train_sft_tsqa.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Train native ITFormer on the Time-MQA TSQA train split."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import random
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import torch
13
+ from accelerate import Accelerator
14
+ from transformers import AutoTokenizer
15
+
16
+ from dataset.tsqa_dataset import ITFormerTSQACollator, ITFormerTSQADataset
17
+ from EXP.exp_instruct import Exp_Instruct
18
+ from models.TimeLanguageModel import TLMConfig
19
+ from utils.accelerate_compat import patch_accelerate_unwrap_model
20
+
21
+
22
+ def str2bool(value):
23
+ return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}
24
+
25
+
26
+ def parse_args():
27
+ parser = argparse.ArgumentParser(description="Train ITFormer on Time-MQA TSQA.")
28
+ parser.add_argument("--train_path", required=True)
29
+ parser.add_argument("--eval_path", required=True)
30
+ parser.add_argument(
31
+ "--llm_model_path",
32
+ default="/mnt/share01/sqk/models/qwen2.5-7b-instruct",
33
+ )
34
+ parser.add_argument("--load_ts_encoder", required=True)
35
+ parser.add_argument("--output_dir", required=True)
36
+ parser.add_argument("--max_train_samples", type=int, default=0)
37
+ parser.add_argument("--max_eval_samples", type=int, default=0)
38
+ parser.add_argument("--max_seq_length", type=int, default=4096)
39
+ parser.add_argument("--seed", type=int, default=42)
40
+
41
+ parser.add_argument("--model", default="TimeSeriesEncoder")
42
+ parser.add_argument("--d_model", type=int, default=512)
43
+ parser.add_argument("--n_heads", type=int, default=8)
44
+ parser.add_argument("--e_layers", type=int, default=4)
45
+ parser.add_argument("--patch_len", type=int, default=60)
46
+ parser.add_argument("--stride", type=int, default=60)
47
+ parser.add_argument("--input_len", type=int, default=600)
48
+ parser.add_argument("--dropout", type=float, default=0.1)
49
+ parser.add_argument("--freeze_ts_model", type=str2bool, default=True)
50
+ parser.add_argument("--pretrain", type=str2bool, default=False)
51
+ parser.add_argument("--min_mask_ratio", type=float, default=0.7)
52
+ parser.add_argument("--max_mask_ratio", type=float, default=0.8)
53
+
54
+ parser.add_argument("--it_d_model", type=int, default=896)
55
+ parser.add_argument("--it_n_heads", type=int, default=16)
56
+ parser.add_argument("--it_layers", type=int, default=2)
57
+ parser.add_argument("--it_dropout", type=float, default=0.1)
58
+ parser.add_argument("--itformer_legacy_double_residual", action="store_true")
59
+ parser.add_argument("--prefix_num", type=int, default=25)
60
+ parser.add_argument("--adapter_type", default="itformer", choices=["itformer"])
61
+ parser.add_argument(
62
+ "--llm_attn_implementation",
63
+ default=None,
64
+ choices=["eager", "sdpa", "flash_attention_2"],
65
+ )
66
+ parser.add_argument(
67
+ "--llm_torch_dtype",
68
+ default=None,
69
+ choices=["float16", "bfloat16", "float32"],
70
+ )
71
+ parser.add_argument("--use_lora", type=str2bool, default=True)
72
+ parser.add_argument("--lora_r", type=int, default=16)
73
+ parser.add_argument("--lora_alpha", type=int, default=32)
74
+ parser.add_argument("--lora_dropout", type=float, default=0.05)
75
+ parser.add_argument(
76
+ "--lora_target_modules",
77
+ nargs="+",
78
+ default=[
79
+ "q_proj",
80
+ "k_proj",
81
+ "v_proj",
82
+ "o_proj",
83
+ "gate_proj",
84
+ "up_proj",
85
+ "down_proj",
86
+ ],
87
+ )
88
+ parser.add_argument("--gradient_checkpointing", type=str2bool, default=True)
89
+
90
+ parser.add_argument("--do_train", type=str2bool, default=True)
91
+ parser.add_argument("--per_device_train_batch_size", type=int, default=1)
92
+ parser.add_argument("--per_device_eval_batch_size", type=int, default=1)
93
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=2)
94
+ parser.add_argument("--learning_rate", type=float, default=5e-5)
95
+ parser.add_argument("--max_grad_norm", type=float, default=1.0)
96
+ parser.add_argument("--num_train_epochs", type=float, default=2.0)
97
+ parser.add_argument("--weight_decay", type=float, default=1e-6)
98
+ parser.add_argument("--fp16", type=str2bool, default=False)
99
+ parser.add_argument("--bf16", action="store_true")
100
+ parser.add_argument("--dataloader_pin_memory", type=str2bool, default=True)
101
+ parser.add_argument("--dataloader_num_workers", type=int, default=4)
102
+ parser.add_argument("--save_steps", type=int, default=100)
103
+ parser.add_argument("--save_total_limit", type=int, default=2)
104
+ parser.add_argument("--logging_steps", type=int, default=5)
105
+ parser.add_argument("--eval_steps", type=int, default=999999999)
106
+ parser.add_argument("--eval_stragy", default="no")
107
+ parser.add_argument("--shuffle", type=str2bool, default=True)
108
+ parser.add_argument("--report_to", default="none")
109
+ parser.add_argument("--mode", default="train")
110
+ return parser.parse_args()
111
+
112
+
113
+ def main():
114
+ patch_accelerate_unwrap_model()
115
+ args = parse_args()
116
+ accelerator = Accelerator(device_placement=True)
117
+
118
+ random.seed(args.seed)
119
+ np.random.seed(args.seed)
120
+ torch.manual_seed(args.seed)
121
+ if torch.cuda.is_available():
122
+ torch.cuda.manual_seed_all(args.seed)
123
+
124
+ tokenizer = AutoTokenizer.from_pretrained(args.llm_model_path)
125
+ tokenizer.padding_side = "left"
126
+ if tokenizer.pad_token is None:
127
+ tokenizer.pad_token = tokenizer.eos_token
128
+ if "<|image_pad|>" not in tokenizer.get_vocab():
129
+ tokenizer.add_tokens(["<|image_pad|>"])
130
+
131
+ train_dataset = ITFormerTSQADataset(
132
+ args.train_path,
133
+ tokenizer,
134
+ prefix_num=args.prefix_num,
135
+ input_len=args.input_len,
136
+ max_samples=args.max_train_samples,
137
+ include_answer=True,
138
+ max_seq_length=args.max_seq_length,
139
+ )
140
+ eval_dataset = ITFormerTSQADataset(
141
+ args.eval_path,
142
+ tokenizer,
143
+ prefix_num=args.prefix_num,
144
+ input_len=args.input_len,
145
+ max_samples=args.max_eval_samples,
146
+ include_answer=False,
147
+ )
148
+ if accelerator.is_main_process:
149
+ print(f"TSQA train samples: {len(train_dataset)}")
150
+ print(
151
+ "TSQA overlength train samples skipped: "
152
+ f"{len(train_dataset.skipped_overlength)} "
153
+ f"(max_seq_length={args.max_seq_length})"
154
+ )
155
+ print(f"TSQA eval samples reserved for post-training eval: {len(eval_dataset)}")
156
+
157
+ tlm_config = TLMConfig(
158
+ llm_model_path=args.llm_model_path,
159
+ freeze_ts_model=args.freeze_ts_model,
160
+ ts_pad_num=args.prefix_num,
161
+ llm_attn_implementation=args.llm_attn_implementation,
162
+ llm_torch_dtype=args.llm_torch_dtype,
163
+ use_lora=args.use_lora,
164
+ lora_r=args.lora_r,
165
+ lora_alpha=args.lora_alpha,
166
+ lora_dropout=args.lora_dropout,
167
+ lora_target_modules=args.lora_target_modules,
168
+ gradient_checkpointing=args.gradient_checkpointing,
169
+ )
170
+
171
+ trainer = Exp_Instruct(
172
+ args,
173
+ train_dataset=train_dataset,
174
+ eval_dataset=None,
175
+ tlm_config=tlm_config,
176
+ )
177
+ trainer.data_collator = ITFormerTSQACollator(tokenizer)
178
+
179
+ if accelerator.is_main_process:
180
+ output = Path(args.output_dir)
181
+ output.mkdir(parents=True, exist_ok=True)
182
+ skip_path = output / "skipped_overlength_train.jsonl"
183
+ with skip_path.open("w", encoding="utf-8") as handle:
184
+ for row in train_dataset.skipped_overlength:
185
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
186
+ print(f"Overlength skip manifest: {skip_path}")
187
+
188
+ if len(tokenizer) != trainer.model.llm_model.config.vocab_size:
189
+ trainer.model.llm_model.resize_token_embeddings(len(tokenizer))
190
+
191
+ trainable_params = sum(
192
+ parameter.numel()
193
+ for parameter in trainer.model.parameters()
194
+ if parameter.requires_grad
195
+ )
196
+ total_params = sum(parameter.numel() for parameter in trainer.model.parameters())
197
+ if accelerator.is_main_process:
198
+ print(
199
+ f"ITFormer + LoRA trainable parameters: {trainable_params:,} / "
200
+ f"{total_params:,} ({100 * trainable_params / total_params:.4f}%)"
201
+ )
202
+
203
+ trainer.train(resume_from_checkpoint=False)
204
+ trainer.save_model(args.output_dir)
205
+ if trainer.args.should_save:
206
+ tokenizer.save_pretrained(args.output_dir)
207
+ run_config = vars(args).copy()
208
+ run_config.update(
209
+ {
210
+ "actual_train_samples": len(train_dataset),
211
+ "actual_eval_samples": len(eval_dataset),
212
+ "skipped_overlength_train_samples": len(
213
+ train_dataset.skipped_overlength
214
+ ),
215
+ }
216
+ )
217
+ output = Path(args.output_dir)
218
+ output.mkdir(parents=True, exist_ok=True)
219
+ with (output / "tsqa_run_config.json").open("w", encoding="utf-8") as handle:
220
+ json.dump(run_config, handle, ensure_ascii=False, indent=2)
221
+ print(f"Saved final ITFormer checkpoint: {output}")
222
+
223
+
224
+ if __name__ == "__main__":
225
+ main()
utils/__init__.py ADDED
File without changes
utils/accelerate_compat.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+
3
+
4
+ def patch_accelerate_unwrap_model():
5
+ """Allow newer Transformers Trainer to run with older Accelerate.
6
+
7
+ Some Transformers versions call Accelerator.unwrap_model with the
8
+ keep_torch_compile keyword. Older Accelerate releases do not accept that
9
+ keyword, which raises a TypeError before training starts.
10
+ """
11
+ from accelerate import Accelerator
12
+
13
+ signature = inspect.signature(Accelerator.unwrap_model)
14
+ if "keep_torch_compile" in signature.parameters:
15
+ return False
16
+
17
+ original_unwrap_model = Accelerator.unwrap_model
18
+
19
+ def unwrap_model_compat(self, model, keep_fp32_wrapper=True, keep_torch_compile=False):
20
+ try:
21
+ return original_unwrap_model(
22
+ self,
23
+ model,
24
+ keep_fp32_wrapper=keep_fp32_wrapper,
25
+ )
26
+ except TypeError:
27
+ return original_unwrap_model(self, model)
28
+
29
+ Accelerator.unwrap_model = unwrap_model_compat
30
+ return True
utils/dist_util.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding:utf-8 _*-
3
+ import os
4
+ import torch.distributed as dist
5
+
6
+
7
+ def is_master_process():
8
+ rank = os.getenv('RANK')
9
+ if (rank is None or rank == '0') and is_local_rank_0():
10
+ return True
11
+ else:
12
+ return False
13
+
14
+
15
+ def is_local_rank_0():
16
+ local_rank = os.getenv('LOCAL_RANK')
17
+ if local_rank is None or local_rank == '0':
18
+ return True
19
+ else:
20
+ return False
21
+
22
+
23
+ def get_local_world_size():
24
+ import torch
25
+ local_world_size = os.getenv('LOCAL_WORLD_SIZE')
26
+ if local_world_size is None:
27
+ num_gpus = torch.cuda.device_count()
28
+ local_world_size = num_gpus or 1
29
+ else:
30
+ local_world_size = int(local_world_size)
31
+ return local_world_size
32
+
33
+
34
+ def get_world_size():
35
+ try:
36
+ world_size = dist.get_world_size()
37
+ return world_size
38
+ except Exception:
39
+ pass
40
+ world_size = os.getenv('WORLD_SIZE')
41
+ if world_size is None:
42
+ world_size = 1
43
+ else:
44
+ world_size = int(world_size)
45
+ return world_size
utils/gradio_vlm.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoProcessor, AutoConfig
4
+ from PIL import Image
5
+ from train import VLMConfig, VLM
6
+ import torch
7
+ from torch.nn import functional as F
8
+ device = "cuda:1"
9
+ processor = AutoProcessor.from_pretrained("/home/user/wyf/siglip-base-patch16-224")
10
+ tokenizer = AutoTokenizer.from_pretrained('/home/user/Downloads/Qwen2.5-0.5B-Instruct')
11
+ AutoConfig.register("vlm_model", VLMConfig)
12
+ AutoModelForCausalLM.register(VLMConfig, VLM)
13
+
14
+ pretrain_model = AutoModelForCausalLM.from_pretrained('/home/user/wyf/train_multimodal_from_scratch/save/pretrain')
15
+ pretrain_model.to(device)
16
+
17
+ sft_model = AutoModelForCausalLM.from_pretrained('/home/user/wyf/train_multimodal_from_scratch/save/sft')
18
+ sft_model.to(device)
19
+
20
+ pretrain_model.eval()
21
+ sft_model.eval()
22
+ def generate(mode, image_input, text_input, max_new_tokens = 100, temperature = 0.0, top_k = None):
23
+ q_text = tokenizer.apply_chat_template([{"role":"system", "content":'You are a helpful assistant.'}, {"role":"user", "content":f'{text_input}\n<image>'}], \
24
+ tokenize=False, \
25
+ add_generation_prompt=True).replace('<image>', '<|image_pad|>'*49)
26
+ input_ids = tokenizer(q_text, return_tensors='pt')['input_ids']
27
+ input_ids = input_ids.to(device)
28
+ # image = Image.open(image_input).convert("RGB")
29
+ pixel_values = processor(text=None, images=image_input).pixel_values
30
+ pixel_values = pixel_values.to(device)
31
+ eos = tokenizer.eos_token_id
32
+ s = input_ids.shape[1]
33
+ while input_ids.shape[1] < s + max_new_tokens - 1:
34
+ if mode == 'pretrain':
35
+ model = pretrain_model
36
+ else:
37
+ model = sft_model
38
+ inference_res = model(input_ids, None, pixel_values)
39
+ logits = inference_res.logits
40
+ logits = logits[:, -1, :]
41
+
42
+ for token in set(input_ids.tolist()[0]):
43
+ logits[:, token] /= 1.0
44
+
45
+ if temperature == 0.0:
46
+ _, idx_next = torch.topk(logits, k=1, dim=-1)
47
+ else:
48
+ logits = logits / temperature
49
+ if top_k is not None:
50
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
51
+ logits[logits < v[:, [-1]]] = -float('Inf')
52
+
53
+ probs = F.softmax(logits, dim=-1)
54
+ idx_next = torch.multinomial(probs, num_samples=1, generator=None)
55
+
56
+ if idx_next == eos:
57
+ break
58
+
59
+ input_ids = torch.cat((input_ids, idx_next), dim=1)
60
+ return tokenizer.decode(input_ids[:, s:][0])
61
+
62
+ with gr.Blocks() as demo:
63
+ with gr.Row():
64
+ # 上传图片
65
+ with gr.Column(scale=1):
66
+ image_input = gr.Image(type="pil", label="选择图片")
67
+ with gr.Column(scale=1):
68
+ mode = gr.Radio(["pretrain", "sft"], label="选择模型")
69
+ text_input = gr.Textbox(label="输入文本")
70
+ text_output = gr.Textbox(label="输出文本")
71
+ generate_button = gr.Button("生成")
72
+ generate_button.click(generate, inputs=[mode, image_input, text_input], outputs=text_output)
73
+
74
+
75
+ if __name__ == "__main__":
76
+ demo.launch(share=False, server_name="0.0.0.0", server_port=7891)
77
+
utils/log_util.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding:utf-8 _*-
3
+ import os
4
+ import logging
5
+ import sys
6
+ import typing
7
+
8
+ # -------- log setting ---------
9
+ DEFAULT_LOGGER = "time_moe_logger"
10
+
11
+ DEFAULT_FORMATTER = logging.Formatter(
12
+ '%(asctime)s - %(filename)s[pid:%(process)d;line:%(lineno)d:%(funcName)s] - %(levelname)s: %(message)s'
13
+ )
14
+
15
+ _ch = logging.StreamHandler(stream=sys.stdout)
16
+ _ch.setFormatter(DEFAULT_FORMATTER)
17
+
18
+ _DEFAULT_HANDLERS = [_ch]
19
+
20
+ _LOGGER_CACHE = {} # type: typing.Dict[str, logging.Logger]
21
+
22
+
23
+ def is_local_rank_0():
24
+ local_rank = os.getenv('LOCAL_RANK')
25
+ if local_rank is None or local_rank == '0':
26
+ return True
27
+ else:
28
+ return False
29
+
30
+
31
+ def get_logger(name, level="INFO", handlers=None, update=False):
32
+ if name in _LOGGER_CACHE and not update:
33
+ return _LOGGER_CACHE[name]
34
+ logger = logging.getLogger(name)
35
+ logger.setLevel(level)
36
+ logger.handlers = handlers or _DEFAULT_HANDLERS
37
+ logger.propagate = False
38
+ return logger
39
+
40
+
41
+ def log_in_local_rank_0(*msg, type='info', used_logger=None):
42
+ msg = ' '.join([str(s) for s in msg])
43
+ if used_logger is None:
44
+ used_logger = logger
45
+
46
+ if is_local_rank_0():
47
+ if type == 'warn' or type == 'warning':
48
+ used_logger.warning(msg)
49
+ elif type == 'error':
50
+ used_logger.error(msg)
51
+ else:
52
+ used_logger.info(msg)
53
+
54
+
55
+ def adaptive_print(*args, **kwargs):
56
+ """
57
+ 仅在主进程打印的 print 函数。
58
+ """
59
+ if is_local_rank_0():
60
+ print(*args, **kwargs)
61
+
62
+
63
+ # -------------------------- Singleton Object --------------------------
64
+ logger = get_logger(DEFAULT_LOGGER)
utils/metrics.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict
2
+ from difflib import SequenceMatcher
3
+
4
+ def compute_bleu_from_ids(predictions, references):
5
+ """
6
+ Compute BLEU score using str.
7
+ Args:
8
+ predictions (List[str]): Model predicted texts.
9
+ references (List[str]): Reference texts.
10
+
11
+ Returns:
12
+ float: BLEU score.
13
+ """
14
+ try:
15
+ from nltk.translate.bleu_score import corpus_bleu, SmoothingFunction
16
+ except ModuleNotFoundError:
17
+ print("Warning: nltk is not installed; BLEU will be reported as 0.0.")
18
+ return 0.0
19
+
20
+ # Ensure the reference format matches the requirements of corpus_bleu
21
+ predictions = [pred.split() for pred in predictions]
22
+ references = [[ref.split()] for ref in references]
23
+ smooth = SmoothingFunction().method1
24
+ bleu_score = corpus_bleu(references, predictions, smoothing_function=smooth)
25
+ return bleu_score
26
+
27
+
28
+ def compute_rouge_from_ids(predictions, references):
29
+ """
30
+ Compute ROUGE scores using text.
31
+ Args:
32
+ predictions (List[str]): Model predicted texts.
33
+ references (List[str]): Reference texts.
34
+
35
+ Returns:
36
+ Dict[str, float]: Contains ROUGE-1, ROUGE-2, and ROUGE-L scores.
37
+ """
38
+ try:
39
+ from rouge_score import rouge_scorer
40
+ except ModuleNotFoundError:
41
+ print("Warning: rouge_score is not installed; ROUGE will be reported as 0.0.")
42
+ return {"rouge1": 0.0, "rouge2": 0.0, "rougeL": 0.0}
43
+
44
+ scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=False)
45
+ rouge_scores = {"rouge1": 0, "rouge2": 0, "rougeL": 0}
46
+ count = len(predictions)
47
+
48
+ for pred, ref in zip(predictions, references):
49
+ score = scorer.score(pred, ref)
50
+ rouge_scores["rouge1"] += score["rouge1"].fmeasure
51
+ rouge_scores["rouge2"] += score["rouge2"].fmeasure
52
+ rouge_scores["rougeL"] += score["rougeL"].fmeasure
53
+
54
+ # Average scores
55
+ return {k: v / count for k, v in rouge_scores.items()}
56
+
57
+
58
+
59
+
60
+ def open_question_metrics(predictions, references, special_ids=[151643]):
61
+ """
62
+ Compute BLEU and ROUGE scores for open-ended questions.
63
+ Args:
64
+ predictions (List[str]): Model predicted texts.
65
+ references (List[str]): Reference texts.
66
+ special_ids (int): Indices used for padding.
67
+
68
+ Returns:
69
+ Dict[str, float]: Contains BLEU and ROUGE scores.
70
+ """
71
+ # Remove padding
72
+ decoded_predictions = []
73
+ decoded_labels = []
74
+
75
+ for pred, label in zip(predictions, references):
76
+ pred = [token for token in pred if token not in special_ids]
77
+ label = [token for token in label if token not in special_ids]
78
+ decoded_predictions.append(pred)
79
+ decoded_labels.append(label)
80
+
81
+ # Compute BLEU
82
+ bleu_score = compute_bleu_from_ids(predictions, references)
83
+
84
+ # Compute ROUGE
85
+ rouge_scores = compute_rouge_from_ids(predictions, references)
86
+
87
+ return {"BLEU": bleu_score, **rouge_scores}
88
+
89
+ def compute_rul(predictions, references):
90
+ """
91
+ Compute RUL (Remaining Useful Life) scores.
92
+
93
+ Args:
94
+ predictions (List[str]): Model predicted values.
95
+ references (List[str]): Reference values.
96
+
97
+ Returns:
98
+ Dict[str, float]: Contains MAE and RMSE scores.
99
+ """
100
+ # Convert strings to numeric values
101
+ predictions = [float(pred) if pred.replace('.', '', 1).isdigit() else 30 for pred in predictions]
102
+ references = [float(ref) for ref in references]
103
+
104
+ # Compute MAE (Mean Absolute Error)
105
+ mae = sum(abs(p - r) for p, r in zip(predictions, references)) / len(predictions)
106
+
107
+ # Compute RMSE (Root Mean Squared Error)
108
+ mse = sum((p - r) ** 2 for p, r in zip(predictions, references)) / len(predictions)
109
+ rmse = mse ** 0.5
110
+
111
+ return {"MAE": mae, "RMSE": rmse, "MSE": mse}
112
+
113
+
114
+
115
+
116
+ def closed_question_metrics(predictions, references, special_id=[151643]):
117
+ """
118
+ Compute evaluation metrics for multiple-choice questions: precision, recall, F1 score, and exact match accuracy.
119
+
120
+ Args:
121
+ predictions (List[str]): Model predicted answers, single or multiple choices separated by spaces (e.g., 'a b e').
122
+ references (List[str]): Correct answers, single or multiple choices separated by spaces (e.g., 'a b').
123
+
124
+ Returns:
125
+ dict: Contains precision, recall, F1, and exact match accuracy.
126
+ """
127
+ tp, fp, fn = 0, 0, 0
128
+ exact_match_count = 0
129
+
130
+ for pred, ref in zip(predictions, references):
131
+ # Convert strings to sets
132
+ pred_set = set(pred.split())
133
+ ref_set = set(ref.split())
134
+
135
+ # Convert characters in pred_set to lowercase
136
+ pred_set = {token.lower() for token in pred_set}
137
+ # Remove non-option characters from pred_set (only keep a-z)
138
+ pred_set = {token for token in pred_set if token in [
139
+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
140
+ 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
141
+ 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
142
+ ]}
143
+
144
+ # Compute True Positives, False Positives, False Negatives
145
+ tp += len(pred_set & ref_set) # Correctly predicted options
146
+ fp += len(pred_set - ref_set) # Incorrectly predicted options
147
+ fn += len(ref_set - pred_set) # Missed correct options
148
+
149
+ # Exact match check
150
+ if pred_set == ref_set:
151
+ exact_match_count += 1
152
+
153
+ # Compute metrics
154
+ precision = tp / (tp + fp) if tp + fp > 0 else 0.0
155
+ recall = tp / (tp + fn) if tp + fn > 0 else 0.0
156
+ f1 = 2 * precision * recall / (precision + recall) if precision + recall > 0 else 0.0
157
+ exact_match_accuracy = exact_match_count / len(references) if len(references) > 0 else 0.0
158
+
159
+ return {
160
+ "precision": precision,
161
+ "recall": recall,
162
+ "f1": f1,
163
+ "exact_match_accuracy": exact_match_accuracy,
164
+ }
165
+
166
+ # # Example data
167
+ # predictions = ['a', 'a token', 'a', 'a', 'b', 'b', 'a b e', 'b', 'a', 'a', 'a', 'b']
168
+ # references = ['a', 'a', 'a', 'c', 'b', 'b', 'a b', 'b', 'a', 'a', 'a', 'b']
169
+
170
+ # # Call function
171
+ # metrics = closed_question_metrics(predictions, references)
172
+ # print(metrics)
utils/position_coding.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ from torch import nn
4
+ class RotaryPositionalEncoding(nn.Module):
5
+ def __init__(self, d_model, max_len=5000):
6
+ """
7
+ 初始化 RotaryPositionalEncoding。
8
+
9
+ Args:
10
+ d_model (int): 特征维度。
11
+ max_len (int): 支持的最大序列长度。
12
+ """
13
+ super(RotaryPositionalEncoding, self).__init__()
14
+
15
+ # 确保特征维度为偶数
16
+ assert d_model % 2 == 0, "d_model must be even for RotaryPositionalEncoding."
17
+
18
+ # 创建旋转位置编码矩阵
19
+ position = torch.arange(0, max_len).float().unsqueeze(1) # [max_len, 1]
20
+ dim = torch.arange(0, d_model // 2).float() # [d_model // 2]
21
+ div_term = torch.exp(dim * -(math.log(10000.0) / (d_model // 2))) # [d_model // 2]
22
+
23
+ # 计算正弦和余弦部分
24
+ angle = position * div_term # [max_len, d_model // 2]
25
+ sin_part = torch.sin(angle) # 正弦部分
26
+ cos_part = torch.cos(angle) # 余弦部分
27
+
28
+ # 将 sin 和 cos 部分堆叠
29
+ pe = torch.cat([sin_part, cos_part], dim=-1) # [max_len, d_model]
30
+ pe = pe.unsqueeze(0).unsqueeze(0) # [1, 1, max_len, d_model]
31
+ self.register_buffer('pe', pe) # 注册为非参数张量
32
+
33
+ def forward(self, x, offset=0):
34
+ """
35
+ 前向传播。
36
+
37
+ Args:
38
+ x (Tensor): 输入张量,形状为 [batch_size, seq_len, d_model]。
39
+ offset (int): 位置偏移量,默认为 0。
40
+
41
+ Returns:
42
+ Tensor: 应用旋转位置编码的张量。
43
+ """
44
+ # 获取位置编码
45
+ seq_len = x.size(1)
46
+ pe = self.pe[0, :, offset:offset + seq_len, :] # [1, seq_len, d_model]
47
+
48
+ # 将输入张量拆分为两部分:前半部分与后半部分
49
+ x1, x2 = x[..., :x.size(-1)//2], x[..., x.size(-1)//2:] # [batch_size, seq_len, d_model//2]
50
+
51
+ # 应用旋转操作
52
+ x_rotated = torch.cat([
53
+ x1 * pe[..., :x.size(-1)//2] - x2 * pe[..., x.size(-1)//2:],
54
+ x1 * pe[..., x.size(-1)//2:] + x2 * pe[..., :x.size(-1)//2]
55
+ ], dim=-1) # [batch_size, seq_len, d_model]
56
+
57
+ return x_rotated
58
+
59
+ class ReRoPE:
60
+ def __init__(self, dim: int):
61
+ """
62
+ 初始化 ReRoPE 编码器。
63
+
64
+ Args:
65
+ dim (int): 特征向量的维度(必须为偶数)。
66
+ """
67
+ assert dim % 2 == 0, "Dimension must be even for ReRoPE."
68
+ self.dim = dim
69
+ self.theta = self._compute_base_theta(dim)
70
+
71
+ @staticmethod
72
+ def _compute_base_theta(dim: int):
73
+ """
74
+ 计算基本的 θ 值,用于旋转位置编码。
75
+
76
+ Args:
77
+ dim (int): 特征向量的维度。
78
+
79
+ Returns:
80
+ torch.Tensor: θ 值的张量。
81
+ """
82
+ theta = torch.tensor([10000 ** (-2 * (i // 2) / dim) for i in range(dim)])
83
+ return theta
84
+
85
+ def forward(self, pos: torch.Tensor):
86
+ """
87
+ 计算给定位置的 ReRoPE 编码。
88
+
89
+ Args:
90
+ pos (torch.Tensor): 位置索引的张量,形状为 [seq_len] 或 [batch_size, seq_len]。
91
+
92
+ Returns:
93
+ torch.Tensor: ReRoPE 编码,形状为 [seq_len, dim] 或 [batch_size, seq_len, dim]。
94
+ """
95
+ seq_len = pos.size(-1)
96
+ # 获取正弦和余弦部分
97
+ angles = pos.unsqueeze(-1) * self.theta
98
+ sinusoidal_embedding = torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1)
99
+ return sinusoidal_embedding
100
+
101
+ @staticmethod
102
+ def apply_rotary_embedding(query, key, sincos):
103
+ """
104
+ 应用旋转位置编码到查询和键。
105
+
106
+ Args:
107
+ query (torch.Tensor): 查询向量,形状为 [batch_size, seq_len, dim].
108
+ key (torch.Tensor): 键向量,形状为 [batch_size, seq_len, dim].
109
+ sincos (torch.Tensor): ReRoPE 编码,形状为 [seq_len, dim] 或 [batch_size, seq_len, dim].
110
+
111
+ Returns:
112
+ Tuple[torch.Tensor, torch.Tensor]: 编码后的查询和键。
113
+ """
114
+ sin, cos = sincos[..., :query.size(-1)], sincos[..., query.size(-1):]
115
+ query_rotated = query * cos + torch.roll(query, shifts=1, dims=-1) * sin
116
+ key_rotated = key * cos + torch.roll(key, shifts=1, dims=-1) * sin
117
+ return query_rotated, key_rotated
118
+
119
+ class LearnablePositionalEmbedding(nn.Module):
120
+ def __init__(self, d_model, max_len=5000):
121
+ super(LearnablePositionalEmbedding, self).__init__()
122
+ # Compute the positional encodings once in log space.
123
+ self.pe = nn.Parameter(torch.zeros(
124
+ 1, 1, max_len, d_model), requires_grad=True)
125
+
126
+ pe = torch.zeros(max_len, d_model).float()
127
+ position = torch.arange(0, max_len).float().unsqueeze(1)
128
+ div_term = (torch.arange(0, d_model, 2).float()
129
+ * -(math.log(10000.0) / d_model)).exp()
130
+
131
+ pe[:, 0::2] = torch.sin(position * div_term)
132
+ pe[:, 1::2] = torch.cos(position * div_term)
133
+
134
+ pe = pe.unsqueeze(0).unsqueeze(0)
135
+ self.pe.data.copy_(pe.float())
136
+ del pe
137
+
138
+ def forward(self, x, offset=0):
139
+ return self.pe[0, :, offset:offset+x.size(1), :]
140
+
141
+ class SinusoidalPositionalEncoding(nn.Module):
142
+ def __init__(self, d_model, max_len=5000):
143
+ """
144
+ 初始化 SinusoidalPositionalEncoding。
145
+
146
+ Args:
147
+ d_model (int): 特征维度。
148
+ max_len (int): 支持的最大序列长度。
149
+ """
150
+ super(SinusoidalPositionalEncoding, self).__init__()
151
+ self.d_model = d_model
152
+
153
+ # 创建一个固定的位置编码矩阵
154
+ pe = self._build_encoding(0, max_len, device=torch.device("cpu"))
155
+
156
+ # 将矩阵增加批量维度,方便在 forward 中直接使用
157
+ pe = pe.unsqueeze(0).unsqueeze(0) # [1, 1, max_len, d_model]
158
+ self.register_buffer('pe', pe) # 注册为非参数张量
159
+
160
+ def _build_encoding(self, start, end, device):
161
+ position = torch.arange(start, end, device=device, dtype=torch.float32).unsqueeze(1)
162
+ div_term = torch.exp(
163
+ torch.arange(0, self.d_model, 2, device=device, dtype=torch.float32)
164
+ * -(math.log(10000.0) / self.d_model)
165
+ )
166
+ pe = torch.zeros(end - start, self.d_model, device=device, dtype=torch.float32)
167
+ pe[:, 0::2] = torch.sin(position * div_term)
168
+ pe[:, 1::2] = torch.cos(position * div_term)
169
+ return pe
170
+
171
+ def forward(self, x, offset=0):
172
+ """
173
+ 前向传播。
174
+
175
+ Args:
176
+ x (Tensor): 输入张量,形状为 [batch_size, seq_len, d_model]
177
+ offset (int): 位置偏移量,默认为 0。
178
+
179
+ Returns:
180
+ Tensor: 添加了位置编码的张量。
181
+ """
182
+ end = offset + x.size(1)
183
+ if end <= self.pe.size(2):
184
+ encoding = self.pe[0, :, offset:end, :]
185
+ else:
186
+ # Some TSQA questions exceed the original fixed 5,000 positions.
187
+ # Generate the required range on demand without changing the
188
+ # checkpoint buffer shape.
189
+ encoding = self._build_encoding(offset, end, x.device).unsqueeze(0)
190
+ return encoding.to(device=x.device, dtype=x.dtype)
191
+
192
+ if __name__ == "__main__":
193
+ d_model = 64
194
+ seq_len = 128
195
+ batch_size = 32
196
+
197
+ pos_encoder = LearnablePositionalEmbedding(d_model=d_model, max_len=5000)
198
+ x = torch.randn(batch_size, seq_len, d_model) # 随机输入张量
199
+ pos_encoded_x = pos_encoder(x)
200
+ print("Shape of Positional Encoded Output:", pos_encoded_x.shape)
yaml/infer.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model: TimeSeriesEncoder
2
+ d_model: 512
3
+ n_heads: 8
4
+ e_layers: 4
5
+ patch_len: 60
6
+ stride: 60
7
+ input_len: 600
8
+ dropout: 0.1
9
+
10
+ it_d_model: 896
11
+ it_n_heads: 16
12
+ it_layers: 2
13
+ it_dropout: 0.1
14
+ prefix_num: 25
15
+
16
+ ts_path_test: dataset/datasets/time_series_data.h5
17
+ qa_path_test: dataset/datasets/test_qa.jsonl
18
+
19
+ fp16: true
20
+ dataloader_pin_memory: true
21
+ dataloader_num_workers: 4
22
+