GoldenGrapeGentleman1 commited on
Commit
e1715de
·
verified ·
1 Parent(s): a5c429a

Upload fin-mm before machine wipe

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +21 -0
  2. fin-mm/code/Dockerfile.finpy +9 -0
  3. fin-mm/code/Dockerfile.llava +41 -0
  4. fin-mm/code/Dockerfile.llava-rocm +59 -0
  5. fin-mm/code/FinMME/README.md +123 -0
  6. fin-mm/code/FinMME/eval.py +246 -0
  7. fin-mm/code/FinMME/eval_hf_llava_plus_fin_kline_v1_3_7b.csv +3 -0
  8. fin-mm/code/FinMME/eval_hf_llava_plus_fin_kline_v1_5_7b_full.csv +3 -0
  9. fin-mm/code/FinMME/eval_llava.py +415 -0
  10. fin-mm/code/FinMME/inference_log.txt +3 -0
  11. fin-mm/code/FinMME/plot/example.png +3 -0
  12. fin-mm/code/FinMME/plot/taxo.png +3 -0
  13. fin-mm/code/FinMME/requirements.txt +9 -0
  14. fin-mm/code/FinMultiTime_download.py +207 -0
  15. fin-mm/code/FinMultiTime_index.py +72 -0
  16. fin-mm/code/FinMultiTime_kline_news.py +780 -0
  17. fin-mm/code/FinMultiTime_to_llava.py +221 -0
  18. fin-mm/code/FinMultiTime_to_llava_multimodel.py +779 -0
  19. fin-mm/code/LLaVA-Plus/.devcontainer/Dockerfile +53 -0
  20. fin-mm/code/LLaVA-Plus/.devcontainer/devcontainer.env +2 -0
  21. fin-mm/code/LLaVA-Plus/.devcontainer/devcontainer.json +71 -0
  22. fin-mm/code/LLaVA-Plus/.devcontainer/postCreateCommand.sh +45 -0
  23. fin-mm/code/LLaVA-Plus/.dockerignore +21 -0
  24. fin-mm/code/LLaVA-Plus/.editorconfig +18 -0
  25. fin-mm/code/LLaVA-Plus/.gitattributes +29 -0
  26. fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/1-usage.yaml +31 -0
  27. fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/2-feature-request.yaml +13 -0
  28. fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/3-question.yaml +13 -0
  29. fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/4-discussion.yaml +13 -0
  30. fin-mm/code/LLaVA-Plus/.gitignore +35 -0
  31. fin-mm/code/LLaVA-Plus/LICENSE +201 -0
  32. fin-mm/code/LLaVA-Plus/README.md +236 -0
  33. fin-mm/code/LLaVA-Plus/cog.yaml +37 -0
  34. fin-mm/code/LLaVA-Plus/docs/llava-plus/dataset.md +12 -0
  35. fin-mm/code/LLaVA-Plus/docs/llava-plus/modelzoo.md +8 -0
  36. fin-mm/code/LLaVA-Plus/docs/llava-plus/tools.md +45 -0
  37. fin-mm/code/LLaVA-Plus/docs/llava/Customize_Component.md +20 -0
  38. fin-mm/code/LLaVA-Plus/docs/llava/Data.md +29 -0
  39. fin-mm/code/LLaVA-Plus/docs/llava/Evaluation.md +167 -0
  40. fin-mm/code/LLaVA-Plus/docs/llava/Finetune_Custom_Data.md +37 -0
  41. fin-mm/code/LLaVA-Plus/docs/llava/Intel.md +7 -0
  42. fin-mm/code/LLaVA-Plus/docs/llava/LLaVA_Bench.md +31 -0
  43. fin-mm/code/LLaVA-Plus/docs/llava/LLaVA_from_LLaMA2.md +29 -0
  44. fin-mm/code/LLaVA-Plus/docs/llava/LoRA.md +46 -0
  45. fin-mm/code/LLaVA-Plus/docs/llava/MODEL_ZOO.md +138 -0
  46. fin-mm/code/LLaVA-Plus/docs/llava/ScienceQA.md +53 -0
  47. fin-mm/code/LLaVA-Plus/docs/llava/Windows.md +27 -0
  48. fin-mm/code/LLaVA-Plus/docs/llava/macOS.md +29 -0
  49. fin-mm/code/LLaVA-Plus/images/demo_cli.gif +3 -0
  50. fin-mm/code/LLaVA-Plus/images/llava-plus-arch.png +3 -0
.gitattributes CHANGED
@@ -33,3 +33,24 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ fin-mm/code/FinMME/eval_hf_llava_plus_fin_kline_v1_3_7b.csv filter=lfs diff=lfs merge=lfs -text
37
+ fin-mm/code/FinMME/eval_hf_llava_plus_fin_kline_v1_5_7b_full.csv filter=lfs diff=lfs merge=lfs -text
38
+ fin-mm/code/FinMME/inference_log.txt filter=lfs diff=lfs merge=lfs -text
39
+ fin-mm/code/FinMME/plot/example.png filter=lfs diff=lfs merge=lfs -text
40
+ fin-mm/code/FinMME/plot/taxo.png filter=lfs diff=lfs merge=lfs -text
41
+ fin-mm/code/LLaVA-Plus/images/demo_cli.gif filter=lfs diff=lfs merge=lfs -text
42
+ fin-mm/code/LLaVA-Plus/images/llava-plus-arch.png filter=lfs diff=lfs merge=lfs -text
43
+ fin-mm/code/LLaVA-Plus/images/llava_example_cmp.png filter=lfs diff=lfs merge=lfs -text
44
+ fin-mm/code/LLaVA-Plus/images/llava_logo.png filter=lfs diff=lfs merge=lfs -text
45
+ fin-mm/code/LLaVA-Plus/images/llava_v1_5_radar.jpg filter=lfs diff=lfs merge=lfs -text
46
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/Judas.png filter=lfs diff=lfs merge=lfs -text
47
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/calendar.png filter=lfs diff=lfs merge=lfs -text
48
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/cat_comp.jpeg filter=lfs diff=lfs merge=lfs -text
49
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/frisbee.jpg filter=lfs diff=lfs merge=lfs -text
50
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/mask_twitter.png filter=lfs diff=lfs merge=lfs -text
51
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/mooncake.png filter=lfs diff=lfs merge=lfs -text
52
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/paris.png filter=lfs diff=lfs merge=lfs -text
53
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/road.png filter=lfs diff=lfs merge=lfs -text
54
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/road_ref2.webp filter=lfs diff=lfs merge=lfs -text
55
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/tower.png filter=lfs diff=lfs merge=lfs -text
56
+ fin-mm/code/LLaVA-Plus/llava/serve/examples/wranch_box.png filter=lfs diff=lfs merge=lfs -text
fin-mm/code/Dockerfile.finpy ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+ RUN apt-get update && apt-get install -y \
3
+ build-essential \
4
+ git \
5
+ && rm -rf /var/lib/apt/lists/*
6
+ WORKDIR /workspace
7
+ RUN pip install --no-cache-dir \
8
+ yfinance pandas numpy matplotlib seaborn tqdm datasets
9
+ CMD ["/bin/bash"]
fin-mm/code/Dockerfile.llava ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:11.8.0-cudnn8-devel-ubuntu22.04
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+
5
+ RUN apt-get update && apt-get install -y \
6
+ git wget curl vim ca-certificates \
7
+ build-essential python3 python3-pip python3-dev \
8
+ && rm -rf /var/lib/apt/lists/* \
9
+ && ln -s /usr/bin/python3 /usr/bin/python \
10
+ && pip install --upgrade pip
11
+
12
+ RUN pip install --index-url https://download.pytorch.org/whl/cu117 \
13
+ torch==2.0.1 torchvision==0.15.2
14
+
15
+ RUN pip install \
16
+ transformers==4.31.0 tokenizers==0.13.3 sentencepiece==0.1.99 \
17
+ accelerate==0.21.0 peft==0.4.0 bitsandbytes==0.41.0 \
18
+ einops==0.6.1 einops-exts==0.0.4 timm==0.6.13 \
19
+ gradio==3.35.2 gradio_client==0.2.9 httpx==0.24.0 \
20
+ scikit-learn==1.2.2 supervision==0.10.0 pydantic==1.10.12 \
21
+ shortuuid==1.0.11 markdown2==2.4.10 requests==2.31.0 \
22
+ uvicorn==0.23.2 fastapi==0.100.1 pillow==10.0.0 tqdm==4.66.1 \
23
+ datasets==2.14.4 deepspeed==0.9.5 wandb==0.15.8
24
+
25
+ RUN pip install numpy==1.24.4 pyarrow==12.0.1 packaging==23.1 wheel==0.41.2 setuptools==68.0.0 ninja==1.11.1 psutil==5.9.5 \
26
+ && pip install "flash-attn==2.3.6" --no-build-isolation
27
+
28
+ WORKDIR /workspace
29
+
30
+ # Install additional dependencies for Project_FinMM
31
+ RUN pip install \
32
+ mplfinance>=0.12.0 \
33
+ yfinance>=0.2.0 \
34
+ scienceplots>=2.1.0 \
35
+ jsonlines>=3.1.0
36
+
37
+ CMD ["/bin/bash"]
38
+
39
+ # Build: docker build -t llava -f Dockerfile.llava .
40
+ # Run: docker run --shm-size=16g --gpus all -it --rm -v /path/to/Finance:/workspace/Finance --name llava llava:latest
41
+ # Setup: cd /workspace/Finance/fin-mm/code/LLaVA-Plus && pip install --no-deps -e . && pip install --no-deps -e ".[train]"
fin-mm/code/Dockerfile.llava-rocm ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM rocm/pytorch-training:v25.2
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+ # Required environment variables for ROCm
5
+ ENV HSA_NO_SCRATCH_RECLAIM=1
6
+ ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942"
7
+
8
+ # Install system dependencies
9
+ RUN apt-get update && apt-get install -y \
10
+ git wget curl vim ca-certificates \
11
+ build-essential python3-dev \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Downgrade transformers and install other dependencies
15
+ # Note: Do NOT reinstall PyTorch, base image already contains ROCm version
16
+ RUN pip install --upgrade pip && \
17
+ pip install \
18
+ transformers==4.31.0 \
19
+ tokenizers==0.13.3 \
20
+ sentencepiece==0.1.99 \
21
+ accelerate==0.21.0 \
22
+ peft==0.4.0 \
23
+ einops==0.6.1 \
24
+ einops-exts==0.0.4 \
25
+ timm==0.6.13 \
26
+ gradio==3.35.2 \
27
+ gradio_client==0.2.9 \
28
+ httpx==0.24.0 \
29
+ scikit-learn==1.2.2 \
30
+ supervision==0.10.0 \
31
+ "pydantic>=1.10,<2.0" \
32
+ shortuuid==1.0.11 \
33
+ markdown2==2.4.10 \
34
+ requests==2.31.0 \
35
+ uvicorn==0.23.2 \
36
+ fastapi==0.100.1 \
37
+ pillow==10.0.0 \
38
+ tqdm==4.66.1 \
39
+ datasets==2.14.4 \
40
+ deepspeed==0.9.5 \
41
+ wandb==0.15.8
42
+
43
+ # Install additional utility packages
44
+ RUN pip install \
45
+ numpy==1.24.4 \
46
+ pyarrow==12.0.1 \
47
+ packaging==23.1 \
48
+ wheel==0.41.2 \
49
+ setuptools==68.0.0 \
50
+ ninja==1.11.1 \
51
+ psutil==5.9.5
52
+
53
+
54
+ WORKDIR /workspace
55
+ CMD ["/bin/bash"]
56
+
57
+ # Build: docker build -t llava-rocm -f Dockerfile.llava-rocm .
58
+ # Run: docker run --shm-size=64g --device=/dev/kfd --device=/dev/dri --group-add video -it -v /home/amd/yueyuan:/workspace --name llava llava-rocm:latest
59
+ # Inside container: cd /workspace/Finance/fin-mm/code/LLaVA-Plus && pip install --no-deps -e . && pip install --no-deps -e ".[train]"
fin-mm/code/FinMME/README.md ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FinMME: Benchmark Dataset for Financial Multi-Modal Reasoning Evaluation
2
+
3
+ [![Dataset](https://img.shields.io/badge/🤗%20Dataset-FinMME-blue)](https://huggingface.co/datasets/luojunyu/FinMME)
4
+ [![Paper](https://img.shields.io/badge/📄%20Paper-ACL%202025-red)](https://github.com/luo-junyu/FinMME)
5
+ [![License](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ ## 🔥 Overview
8
+
9
+ Paper Link: [Arxiv](https://arxiv.org/abs/2505.24714).
10
+
11
+ **FinMME** is a comprehensive benchmark dataset designed to evaluate Multimodal Large Language Models (MLLMs) in the financial domain. With around **11,000 high-quality financial samples** spanning **18 financial domains** and **6 asset classes**, FinMME provides a rigorous evaluation framework for financial multimodal reasoning capabilities.
12
+
13
+ ![Taxonomy](plot/taxo.png)
14
+
15
+
16
+ ## 🚀 Quick Start
17
+
18
+ ### Installation
19
+
20
+ ```bash
21
+ git clone https://github.com/luo-junyu/FinMME.git
22
+ cd FinMME
23
+ pip install -r requirements.txt
24
+ ```
25
+
26
+ ### Dataset Loading
27
+
28
+ ```python
29
+ from datasets import load_dataset
30
+
31
+ # Load the dataset
32
+ dataset = load_dataset("luojunyu/FinMME", split="train")
33
+
34
+ # Access a sample
35
+ sample = dataset[0]
36
+ print(f"Question: {sample['question_text']}")
37
+ print(f"Answer: {sample['answer']}")
38
+ print(f"Question Type: {sample['question_type']}")
39
+ ```
40
+
41
+ ### Running Evaluation
42
+
43
+ ```bash
44
+ # Basic test
45
+ python eval.py --sample_size 50 --num_processes 32
46
+
47
+ # Full evaluation
48
+ python eval.py
49
+
50
+ # Custom evaluation
51
+ python eval.py --sample_size 100 --num_processes 16
52
+ ```
53
+
54
+ #### Evaluation Parameters
55
+
56
+ - `--dataset`: Dataset name (default: `luojunyu/FinMME`)
57
+ - `--split`: Dataset split (default: `train`)
58
+ - `--sample_size`: Number of samples to evaluate (default: all)
59
+ - `--num_processes`: Number of parallel processes (default: 4)
60
+
61
+ ### Configuration
62
+
63
+ Before running evaluation, configure your API settings in `eval.py`:
64
+
65
+ ```python
66
+ model = "gpt-4o" # Your model choice
67
+ api_key = 'YOUR_API_KEY' # Your OpenAI API key
68
+ base_url = 'https://api.openai.com/v1' # API endpoint
69
+ ```
70
+
71
+ ## 🏗️ Dataset Structure
72
+
73
+ ### Question Types
74
+ - **Single Choice**: Multiple choice questions with one correct answer
75
+ - **Multiple Choice**: Questions with multiple correct answers
76
+ - **Numerical**: Calculation-based questions requiring numerical answers
77
+
78
+ ### Financial Domains
79
+ - TMT (Technology, Media & Telecom)
80
+ - Consumer Goods
81
+ - Pharmaceuticals & Biotechnology
82
+ - Financial Services
83
+ - Real Estate & Construction
84
+ - Energy & Utilities
85
+ - And 12+ more specialized domains
86
+
87
+ ### Asset Classes
88
+ - Equity
89
+ - Foreign Exchange
90
+ - Rates
91
+ - Commodity
92
+ - Credits
93
+ - Cross-Asset
94
+
95
+ ## 🎯 Evaluation Methodology
96
+
97
+ ### FinScore Calculation
98
+
99
+ FinScore combines domain-normalized performance with hallucination penalties:
100
+
101
+ ```
102
+ FinScore = Domain_Normalized_Score × (1 - Hallucination_Penalty)
103
+ ```
104
+
105
+ ### Multi-dimensional Assessment
106
+
107
+ 1. **Comprehensive Perception**: Temporal sequence recognition, multi-chart analysis
108
+ 2. **Fine-grained Perception**: Numerical extraction, local variation analysis
109
+ 3. **Cognition & Reasoning**: Data inference, trend prediction, causal analysis
110
+
111
+
112
+ ## 📚 Citation
113
+
114
+ If you find FinMME useful, please consider citing:
115
+
116
+ ```bibtex
117
+ @article{luo2025finmme,
118
+ title={FinMME: Benchmark Dataset for Financial Multi-Modal Reasoning Evaluation},
119
+ author={Luo, Junyu and Kou, Zhizhuo and Yang, Liming and Luo, Xiao and Huang, Jinsheng and Xiao, Zhiping and Peng, Jingshu and Liu, Chengzhong and Ji, Jiaming and Liu, Xuanzhe and others},
120
+ journal={arXiv preprint arXiv:2505.24714},
121
+ year={2025}
122
+ }
123
+ ```
fin-mm/code/FinMME/eval.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import base64
3
+ from openai import OpenAI
4
+ import os
5
+ from typing import Dict, List, Iterator
6
+ from multiprocessing import Pool
7
+ from tqdm import tqdm
8
+ import re
9
+ from datasets import load_dataset
10
+ from PIL import Image
11
+ import io
12
+ import gc
13
+
14
+
15
+ api_key = "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" # 替换成你自己的 key
16
+ base_url = "https://integrate.api.nvidia.com/v1/chat/completions"
17
+ model = "meta/llama-3.2-90b-vision-instruct"
18
+
19
+
20
+ INSTRUCTIONS = {
21
+ 'single_choice': "Please answer this single choice question about the image. The caption of the image is {verified_caption}. The related sentences are {related_sentences}.\n Please answer the question directly. The answer MUST be of the following format: 'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem (the single letter of the correct answer, A, B, C, D, etc.).",
22
+ 'multiple_choice': "Please answer this multiple choice question about the image. The caption of the image is {verified_caption}. The related sentences are {related_sentences}.\n Please answer the question directly. The answer MUST be of the following format: 'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem (the letter(s) of the correct answer(s), split by ',').",
23
+ 'numerical': "Please answer this numerical question about the image. The unit of the answer is {unit}. The caption of the image is {verified_caption}. The related sentences are {related_sentences}.\n Please answer the question directly. The answer MUST be of the following format: 'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem (digit number only, without unit or any other text)."
24
+ }
25
+
26
+ def encode_image_from_pil(image: Image.Image) -> str:
27
+ if image.mode in ('RGBA', 'LA', 'P'):
28
+ background = Image.new('RGB', image.size, (255, 255, 255))
29
+ if image.mode == 'P':
30
+ image = image.convert('RGBA')
31
+ background.paste(image, mask=image.split()[-1] if image.mode == 'RGBA' else None)
32
+ image = background
33
+
34
+ max_size = (1024, 1024)
35
+ if image.size[0] > max_size[0] or image.size[1] > max_size[1]:
36
+ image = image.copy()
37
+ image.thumbnail(max_size, Image.Resampling.LANCZOS)
38
+
39
+ buffered = io.BytesIO()
40
+ image.save(buffered, format="JPEG", quality=80, optimize=True)
41
+ encoded = base64.b64encode(buffered.getvalue()).decode('utf-8')
42
+ buffered.close()
43
+ return encoded
44
+
45
+ def extract_result(res):
46
+ if not res:
47
+ return ''
48
+ match = re.search(r"(?i)Answer\s*:\s*([^\s\n]+)", res)
49
+ return match.group(1) if match else ''
50
+
51
+ def normalize_response(response):
52
+ return response.replace("**", "").replace(":", "").replace("$\\boxed{", "").replace("}$", "").replace("\\$", "").replace("$", "").replace("{", "").replace("\\boxed", "")
53
+
54
+ def check_answer(item: Dict, model_answer: str):
55
+ question_type = item['question_type']
56
+ correct_answer = str(item['answer']) if item['answer'] is not None else ""
57
+ pred_answer = normalize_response(extract_result(model_answer))
58
+
59
+ if question_type == 'numerical':
60
+ try:
61
+ model_value = float(''.join(c for c in pred_answer if c.isdigit() or c in '.-'))
62
+ correct_value = float(''.join(c for c in correct_answer if c.isdigit() or c in '.-'))
63
+ tolerance = float(item.get('tolerance', 0.0))
64
+ return abs(model_value - correct_value) <= tolerance, pred_answer
65
+ except (ValueError, TypeError):
66
+ return False, pred_answer
67
+ else:
68
+ model_answers = {c for c in pred_answer.upper() if c in 'ABCDEFGHIJKLMN'}
69
+ correct_answers = {c for c in correct_answer.upper() if c in 'ABCDEFGHIJKLMN'}
70
+ return model_answers == correct_answers, pred_answer
71
+
72
+ def get_model_response(client: OpenAI, image: Image.Image, question: str, question_type: str,
73
+ options: str = "", unit: str = "", verified_caption: str = "", related_sentences: str = "") -> str:
74
+ try:
75
+ base64_image = encode_image_from_pil(image)
76
+
77
+ if question_type == 'numerical':
78
+ prompt = INSTRUCTIONS[question_type].format(unit=unit, verified_caption=verified_caption, related_sentences=related_sentences)
79
+ prompt += f'\nQuestion: {question}'
80
+ else:
81
+ prompt = INSTRUCTIONS[question_type].format(verified_caption=verified_caption, related_sentences=related_sentences)
82
+ prompt += f'\nQuestion: {question}'
83
+ if options:
84
+ prompt += f'\nOptions: {options}'
85
+
86
+ response = client.chat.completions.create(
87
+ model=model,
88
+ messages=[{
89
+ "role": "user",
90
+ "content": [
91
+ {"type": "text", "text": prompt},
92
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
93
+ ]
94
+ }],
95
+ max_tokens=1280,
96
+ temperature=0.0,
97
+ timeout=600
98
+ )
99
+ del base64_image
100
+ return response.choices[0].message.content.strip()
101
+ except Exception as e:
102
+ print(f"Error: {e}")
103
+ return ""
104
+ finally:
105
+ gc.collect()
106
+
107
+ def process_single_item(args):
108
+ item, api_key, base_url = args
109
+ client = OpenAI(api_key=api_key, base_url=base_url)
110
+
111
+ try:
112
+ image = item['image']
113
+ model_answer = get_model_response(
114
+ client=client,
115
+ image=image,
116
+ question=item['question_text'],
117
+ question_type=item['question_type'],
118
+ options=str(item.get('options', '')),
119
+ unit=str(item.get('unit', '')),
120
+ verified_caption=str(item.get('verified_caption', '')),
121
+ related_sentences=str(item.get('related_sentences', ''))
122
+ )
123
+ is_correct, pred_answer = check_answer(item, model_answer)
124
+ del image
125
+ return {
126
+ 'idx': item['idx'],
127
+ 'question_text': item['question_text'],
128
+ 'question_type': item['question_type'],
129
+ 'answer': item['answer'],
130
+ 'options': item.get('options', ''),
131
+ 'unit': item.get('unit', ''),
132
+ 'verified_caption': item.get('verified_caption', ''),
133
+ 'related_sentences': item.get('related_sentences', ''),
134
+ 'tolerance': item.get('tolerance', 0.0),
135
+ 'knowledge_domain': item.get('knowledge_domain', ''),
136
+ 'model_answer': model_answer,
137
+ 'pred_answer': pred_answer,
138
+ 'correct_or_not': is_correct
139
+ }
140
+ except Exception as e:
141
+ print(f"Error processing item {item['idx']}: {e}")
142
+ return None
143
+ finally:
144
+ gc.collect()
145
+
146
+ def load_dataset_streaming(dataset_name: str, split: str = "train") -> Iterator[Dict]:
147
+ dataset = load_dataset(dataset_name, split=split, streaming=True)
148
+ for idx, item in enumerate(dataset):
149
+ new_item = item.copy()
150
+ new_item['idx'] = idx
151
+ yield new_item
152
+
153
+ def get_existing_results(output_file: str) -> set:
154
+ if os.path.exists(output_file):
155
+ try:
156
+ return set(pd.read_excel(output_file)['idx'].tolist())
157
+ except Exception as e:
158
+ print(f"Could not read existing results from {output_file}: {e}")
159
+ return set()
160
+ return set()
161
+
162
+ def calculate_finscore(df: pd.DataFrame):
163
+ """Calculates and prints the FinScore, Hallucination Rate, and Final Score."""
164
+ if 'knowledge_domain' not in df.columns or df['knowledge_domain'].isnull().all():
165
+ print("Warning: 'knowledge_domain' column not found or is empty. Cannot calculate FinScore.")
166
+ return
167
+
168
+ domain_scores = df.groupby('knowledge_domain')['correct_or_not'].mean()
169
+ domain_normed_scores = domain_scores.mean()
170
+ multi_answer_df = df[(df['question_type'] == 'multiple_choice') & (df['answer'].astype(str).str.len() > 1)]
171
+ hallucination_rate = 0.0
172
+ if not multi_answer_df.empty:
173
+ hallucination_rate = (~multi_answer_df['correct_or_not']).mean()
174
+
175
+ finscore = domain_normed_scores * (1 - hallucination_rate)
176
+
177
+ print("-" * 20)
178
+ print("FinMME Benchmark Scores:")
179
+ print(f"FinScore: {finscore:.2f}")
180
+ print("-" * 20)
181
+
182
+ def main(dataset_name: str = "luojunyu/FinMME", split: str = "train",
183
+ sample_size: int = None, num_processes: int = 8):
184
+
185
+ output_file = f'eval_hf_{model.replace("/", "_").replace("-", "_")}.xlsx'
186
+
187
+ # 1. Load existing results
188
+ try:
189
+ existing_df = pd.read_excel(output_file)
190
+ processed_indices = set(existing_df['idx'].tolist())
191
+ except FileNotFoundError:
192
+ existing_df = pd.DataFrame()
193
+ processed_indices = set()
194
+
195
+ # 2. Create a generator for items to process
196
+ items_stream = (item for item in load_dataset_streaming(dataset_name, split) if item['idx'] not in processed_indices)
197
+ if sample_size:
198
+ from itertools import islice
199
+ items_stream = islice(items_stream, sample_size)
200
+
201
+ process_args_stream = ((item, api_key, base_url) for item in items_stream)
202
+
203
+ # 3. Process items in parallel
204
+ new_results = []
205
+ with Pool(processes=num_processes) as pool:
206
+ # Estimate total for tqdm progress bar
207
+ FINMME_TOTAL_COUNT = 11099
208
+ total = sample_size if sample_size else FINMME_TOTAL_COUNT - len(processed_indices)
209
+
210
+ desc = f"Processing with {num_processes} processes"
211
+ results_iterator = pool.imap_unordered(process_single_item, process_args_stream)
212
+
213
+ for result in tqdm(results_iterator, total=total, desc=desc):
214
+ if result:
215
+ new_results.append(result)
216
+
217
+ # 4. Combine, save, and report results
218
+ if not new_results:
219
+ print("\nNo new items were processed.")
220
+ if existing_df.empty:
221
+ return
222
+ combined_df = existing_df
223
+ else:
224
+ new_df = pd.DataFrame(new_results)
225
+ combined_df = pd.concat([existing_df, new_df], ignore_index=True).sort_values(by='idx').reset_index(drop=True)
226
+
227
+ if not combined_df.empty:
228
+ combined_df.to_excel(output_file, index=False)
229
+ print(f"\nResults saved to {output_file}")
230
+ accuracy = combined_df['correct_or_not'].mean()
231
+ print(f"Overall accuracy: {accuracy:.2%}")
232
+ calculate_finscore(combined_df)
233
+ else:
234
+ print("No results to process or save.")
235
+
236
+
237
+ if __name__ == "__main__":
238
+ import argparse
239
+ parser = argparse.ArgumentParser()
240
+ parser.add_argument('--dataset', default='luojunyu/FinMME')
241
+ parser.add_argument('--split', default='train')
242
+ parser.add_argument('--sample_size', type=int, default=None)
243
+ parser.add_argument('--num_processes', type=int, default=16)
244
+ args = parser.parse_args()
245
+
246
+ main(args.dataset, args.split, args.sample_size, args.num_processes)
fin-mm/code/FinMME/eval_hf_llava_plus_fin_kline_v1_3_7b.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae021c1912c567ce37bf86a09805f540db365fd8f822ffbd5bc6d5ecf791fecb
3
+ size 13144733
fin-mm/code/FinMME/eval_hf_llava_plus_fin_kline_v1_5_7b_full.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd161e73ff09d3692e757fbe60e9be0a093d734edbc440adce77909cb4fa80ed
3
+ size 13124260
fin-mm/code/FinMME/eval_llava.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import re
3
+ import os
4
+ import json
5
+ from typing import Dict, Iterator
6
+
7
+ import torch
8
+ import pandas as pd
9
+ from datasets import load_dataset
10
+ from multiprocessing import Pool
11
+ from tqdm import tqdm
12
+ from PIL import Image
13
+
14
+ from transformers import AutoTokenizer
15
+ from llava.mm_utils import process_images, tokenizer_image_token
16
+ from llava.model.builder import load_pretrained_model # 新增:使用 builder 加载模型
17
+
18
+ # ============ 本地 LLaVA 模型路径与标识 ============
19
+ MODEL_PATH = "/workspace/models/llava-plus-fin-kline-v1.5-7b-full"
20
+ MODEL_TAG = "llava_plus_fin_kline_v1_5_7b_full" # 只用于输出文件名
21
+
22
+ # ============ FinMME 提示模版(保持与官方一致) ============
23
+ INSTRUCTIONS = {
24
+ 'single_choice': (
25
+ "Please answer this single choice question about the image. "
26
+ "The caption of the image is {verified_caption}. "
27
+ "The related sentences are {related_sentences}.\n"
28
+ "Please answer the question directly. The answer MUST be of the following format: "
29
+ "'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem "
30
+ "(the single letter of the correct answer, A, B, C, D, etc.)."
31
+ ),
32
+ 'multiple_choice': (
33
+ "Please answer this multiple choice question about the image. "
34
+ "The caption of the image is {verified_caption}. "
35
+ "The related sentences are {related_sentences}.\n"
36
+ "Please answer the question directly. The answer MUST be of the following format: "
37
+ "'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem "
38
+ "(the letter(s) of the correct answer(s), split by ',')."
39
+ ),
40
+ 'numerical': (
41
+ "Please answer this numerical question about the image. "
42
+ "The unit of the answer is {unit}. "
43
+ "The caption of the image is {verified_caption}. "
44
+ "The related sentences are {related_sentences}.\n"
45
+ "Please answer the question directly. The answer MUST be of the following format: "
46
+ "'Answer: $ANSWER' (without quotes) where $ANSWER is the answer to the problem "
47
+ "(digit number only, without unit or any other text)."
48
+ ),
49
+ }
50
+
51
+ # ============ 本地 LLaVA 封装(单进程内全局加载一次) ============
52
+ print(f"[LLaVA] loading model from {MODEL_PATH} ...")
53
+
54
+ # 使用官方 builder 一次性加载 tokenizer, model, image_processor
55
+ _llava_tokenizer, _llava_model, _image_processor, _ = load_pretrained_model(
56
+ model_path=MODEL_PATH,
57
+ model_base=None, # fin-kline 为全参数权重
58
+ model_name="llava", # LLaVA / LLaVA-Plus 系列用这个
59
+ )
60
+
61
+ _llava_model = _llava_model.cuda().eval()
62
+
63
+ print("[LLaVA] model loaded.")
64
+
65
+ # ============ 推理日志记录 ============
66
+ INFERENCE_LOG_FILE = "/workspace/code/FinMME/inference_log.txt"
67
+ LOG_INFERENCE = True # 设为 False 关闭日志
68
+
69
+ def log_inference(message: str):
70
+ """记录推理过程到文件"""
71
+ if LOG_INFERENCE:
72
+ with open(INFERENCE_LOG_FILE, "a", encoding="utf-8") as f:
73
+ f.write(message + "\n")
74
+
75
+ def llava_answer(prompt: str, image: Image.Image | None, max_new_tokens: int = 256, idx: int = -1) -> str:
76
+ """
77
+ 使用本地 LLaVA 模型回答一个问题(0/1 张图)。
78
+ """
79
+ log_inference(f"\n{'='*60}")
80
+ log_inference(f"[INFERENCE] Sample idx={idx}")
81
+ log_inference(f"{'='*60}")
82
+
83
+ # ===== 图像处理 =====
84
+ log_inference(f"\n[IMAGE PROCESSING]")
85
+ if image is not None:
86
+ log_inference(f" - Image provided: YES")
87
+ log_inference(f" - Original size: {image.size} (W x H)")
88
+ log_inference(f" - Mode: {image.mode}")
89
+
90
+ img_tensor = process_images([image], _image_processor, _llava_model.config)
91
+ img_tensor = img_tensor.to(_llava_model.device, dtype=torch.float16)
92
+
93
+ log_inference(f" - Tensor shape: {img_tensor.shape}")
94
+ log_inference(f" - Tensor dtype: {img_tensor.dtype}")
95
+ log_inference(f" - Tensor device: {img_tensor.device}")
96
+ log_inference(f" - Tensor min/max: {img_tensor.min().item():.4f} / {img_tensor.max().item():.4f}")
97
+
98
+ conv = "<image>\n" + prompt
99
+ else:
100
+ log_inference(f" - Image provided: NO")
101
+ img_tensor = None
102
+ conv = prompt
103
+
104
+ # ===== 文字处理 =====
105
+ log_inference(f"\n[TEXT PROCESSING]")
106
+ log_inference(f" - Prompt length: {len(prompt)} chars")
107
+ log_inference(f" - Prompt preview: {prompt[:200]}...")
108
+ log_inference(f" - Has <image> token: {'<image>' in conv}")
109
+
110
+ input_ids = tokenizer_image_token(
111
+ conv, _llava_tokenizer, return_tensors="pt"
112
+ ).unsqueeze(0).to(_llava_model.device)
113
+
114
+ log_inference(f" - Input IDs shape: {input_ids.shape}")
115
+ log_inference(f" - Input IDs device: {input_ids.device}")
116
+
117
+ # ===== 模型推理 =====
118
+ log_inference(f"\n[MODEL INFERENCE]")
119
+ log_inference(f" - max_new_tokens: {max_new_tokens}")
120
+ log_inference(f" - images tensor: {'YES' if img_tensor is not None else 'NO'}")
121
+
122
+ out_ids = _llava_model.generate(
123
+ input_ids,
124
+ images=img_tensor,
125
+ max_new_tokens=max_new_tokens,
126
+ do_sample=False,
127
+ temperature=0.0,
128
+ )
129
+
130
+ vocab_size = _llava_tokenizer.vocab_size
131
+ out_ids = out_ids.clamp_(0, vocab_size - 1)
132
+
133
+ text = _llava_tokenizer.decode(out_ids[0], skip_special_tokens=True).strip()
134
+
135
+ # ===== 输出记录 =====
136
+ log_inference(f"\n[MODEL OUTPUT]")
137
+ log_inference(f" - Output IDs shape: {out_ids.shape}")
138
+ log_inference(f" - Output length: {len(text)} chars")
139
+ log_inference(f" - Output text:\n{text}")
140
+ log_inference(f"\n{'='*60}\n")
141
+
142
+ return text
143
+
144
+ # ============ 工具函数:解析答案 & 计算正确性 ============
145
+ import re
146
+
147
+ def extract_result(res):
148
+ """从末尾开始匹配,优先取最后一个 Answer: X"""
149
+ if not res:
150
+ return ''
151
+ # 找所有匹配,取最后一个(模型真正的答案在末尾)
152
+ matches = re.findall(r"(?i)Answer\s*:\s*([^\s\n'\"]+)", res)
153
+ if matches:
154
+ result = matches[-1]
155
+ # 过滤掉模板占位符 $ANSWER
156
+ if result.upper().replace('$', '') == 'ANSWER':
157
+ # 如果最后一个是占位符,尝试倒数第二个
158
+ if len(matches) > 1:
159
+ result = matches[-2]
160
+ else:
161
+ result = ''
162
+ return result.rstrip('.,')
163
+ return ''
164
+
165
+
166
+ def normalize_response(resp: str) -> str:
167
+ return (
168
+ resp.replace("**", "")
169
+ .replace(":", "")
170
+ .replace("$\\boxed{", "")
171
+ .replace("}$", "")
172
+ .replace("\\$", "")
173
+ .replace("$", "")
174
+ .replace("{", "")
175
+ .replace("\\boxed", "")
176
+ )
177
+
178
+ def check_answer(item: Dict, model_answer: str):
179
+ question_type = item["question_type"]
180
+ correct_answer = str(item["answer"]) if item["answer"] is not None else ""
181
+ pred_answer = normalize_response(extract_result(model_answer))
182
+
183
+ if question_type == "numerical":
184
+ try:
185
+ model_value = float("".join(c for c in pred_answer if c.isdigit() or c in ".-"))
186
+ correct_value = float("".join(c for c in correct_answer if c.isdigit() or c in ".-"))
187
+ tolerance = float(item.get("tolerance", 0.0))
188
+ return abs(model_value - correct_value) <= tolerance, pred_answer
189
+ except (ValueError, TypeError):
190
+ return False, pred_answer
191
+ else:
192
+ model_answers = {c for c in pred_answer.upper() if c in "ABCDEFGHIJKLMN"}
193
+ correct_answers = {c for c in correct_answer.upper() if c in "ABCDEFGHIJKLMN"}
194
+ return model_answers == correct_answers, pred_answer
195
+
196
+ # ============ 单题推理 ============
197
+ def call_model_with_llava(
198
+ image: Image.Image | None,
199
+ question: str,
200
+ question_type: str,
201
+ options: str = "",
202
+ unit: str = "",
203
+ verified_caption: str = "",
204
+ related_sentences: str = "",
205
+ idx: int = -1,
206
+ ) -> str:
207
+ # 用 caption / description 填充
208
+ if not verified_caption:
209
+ verified_caption = ""
210
+ if not related_sentences:
211
+ related_sentences = ""
212
+
213
+ if question_type == "numerical":
214
+ prompt = INSTRUCTIONS[question_type].format(
215
+ unit=unit, verified_caption=verified_caption, related_sentences=related_sentences
216
+ )
217
+ prompt += f"\nQuestion: {question}"
218
+ else:
219
+ prompt = INSTRUCTIONS[question_type].format(
220
+ verified_caption=verified_caption, related_sentences=related_sentences
221
+ )
222
+ prompt += f"\nQuestion: {question}"
223
+ if options:
224
+ prompt += f"\nOptions: {options}"
225
+
226
+ return llava_answer(prompt, image, idx=idx).strip()
227
+
228
+ # ============ 多进程处理单个样本 ============
229
+ def process_single_item(item: Dict):
230
+ try:
231
+ # 从 image_path 打开图片(因为 PIL Image 无法跨进程传递)
232
+ image = item.get("image", None)
233
+ img_path = item.get("image_path")
234
+
235
+ # 记录图像加载过程
236
+ log_inference(f"\n[IMAGE LOADING] idx={item.get('idx')}")
237
+ log_inference(f" - image_path field: {img_path}")
238
+
239
+ if image is None:
240
+ if img_path and os.path.exists(img_path):
241
+ image = Image.open(img_path).convert("RGB")
242
+ log_inference(f" - Status: LOADED from path")
243
+ else:
244
+ log_inference(f" - Status: NOT FOUND or path is None")
245
+
246
+ question = item.get("question", "")
247
+ q_type_raw = item.get("question_type", "single_choice")
248
+ # 映射问题类型到支持的格式
249
+ q_type_map = {
250
+ "single_choice": "single_choice",
251
+ "multiple_choice": "multiple_choice",
252
+ "multi_choice": "multiple_choice", # 兼容
253
+ "numerical": "numerical",
254
+ "other": "single_choice", # 默认当作单选
255
+ }
256
+ q_type = q_type_map.get(q_type_raw, "single_choice")
257
+ # options 是 list,需要拼成字符串
258
+ opts = item.get("options", [])
259
+ if isinstance(opts, list):
260
+ options_str = " ".join(opts)
261
+ else:
262
+ options_str = str(opts)
263
+
264
+ unit = str(item.get("unit") or "")
265
+ verified_caption = str(item.get("caption") or "")
266
+ related_sentences = str(item.get("description") or "")
267
+ sample_idx = int(item.get("id", item.get("idx", -1)))
268
+
269
+ model_answer = call_model_with_llava(
270
+ image=image,
271
+ question=question,
272
+ question_type=q_type,
273
+ options=options_str,
274
+ unit=unit,
275
+ verified_caption=verified_caption,
276
+ related_sentences=related_sentences,
277
+ idx=sample_idx,
278
+ )
279
+
280
+ is_correct, pred_answer = check_answer(item, model_answer)
281
+
282
+ del image
283
+ return {
284
+ "idx": int(item.get("id", item["idx"])),
285
+ "question_text": question,
286
+ "question_type": q_type,
287
+ "answer": item.get("answer"),
288
+ "options": options_str,
289
+ "unit": unit,
290
+ "verified_caption": verified_caption,
291
+ "related_sentences": related_sentences,
292
+ "tolerance": item.get("tolerance", 0.0) or 0.0,
293
+ "knowledge_domain": item.get("knowledge_domain", ""),
294
+ "model_answer": model_answer,
295
+ "pred_answer": pred_answer,
296
+ "correct_or_not": is_correct,
297
+ }
298
+ except Exception as e:
299
+ print(f"Error processing item {item.get('id', item.get('idx'))}: {e}")
300
+ return None
301
+ finally:
302
+ gc.collect()
303
+
304
+ # ============ 数据加载 & 增量评估 ============
305
+ import json
306
+
307
+ def load_dataset_streaming(dataset_name: str = None, split: str = "train") -> Iterator[Dict]:
308
+ """
309
+ 直接从本地 finmme_raw.jsonl + image_path 读取数据,不再访问 Hugging Face。
310
+ 注意:只传递路径,不在这里打开图片(PIL Image 无法跨进程传递)
311
+ """
312
+ jsonl_path = "/workspace/data/finmme_raw.jsonl" # 按你的真实路径修改
313
+
314
+ with open(jsonl_path, "r", encoding="utf-8") as f:
315
+ for idx, line in enumerate(f):
316
+ item = json.loads(line)
317
+ item["idx"] = idx
318
+ # 只保留路径,不打开图片
319
+ item["image"] = None # 稍后在推理时根据 image_path 打开
320
+ yield item
321
+
322
+ def calculate_finscore(df: pd.DataFrame):
323
+ if "knowledge_domain" not in df.columns or df["knowledge_domain"].isnull().all():
324
+ print("Warning: 'knowledge_domain' column not found or empty. Cannot calculate FinScore.")
325
+ return
326
+
327
+ domain_scores = df.groupby("knowledge_domain")["correct_or_not"].mean()
328
+ domain_normed_scores = domain_scores.mean()
329
+
330
+ multi_answer_df = df[
331
+ (df["question_type"] == "multiple_choice") & (df["answer"].astype(str).str.len() > 1)
332
+ ]
333
+ hallucination_rate = 0.0
334
+ if not multi_answer_df.empty:
335
+ hallucination_rate = (~multi_answer_df["correct_or_not"]).mean()
336
+
337
+ finscore = domain_normed_scores * (1 - hallucination_rate)
338
+
339
+ print("-" * 20)
340
+ print("FinMME Benchmark Scores (LLaVA local):")
341
+ print(f"FinScore: {finscore:.4f}")
342
+ print(f"Domain-Normalized Score: {domain_normed_scores:.4f}")
343
+ print(f"Hallucination Rate (multi-answer subset): {hallucination_rate:.4f}")
344
+ print("-" * 20)
345
+
346
+ def main(
347
+ dataset_name: str = "luojunyu/FinMME",
348
+ split: str = "train",
349
+ sample_size: int | None = None,
350
+ num_processes: int = 4,
351
+ ):
352
+ output_file = f"eval_hf_{MODEL_TAG}.csv" # 改用 CSV,不需要 openpyxl
353
+
354
+ # 1. 读取已有结果,实现断点续跑
355
+ try:
356
+ existing_df = pd.read_csv(output_file)
357
+ processed_indices = set(existing_df["idx"].tolist())
358
+ print(f"Loaded {len(existing_df)} existing results from {output_file}")
359
+ except FileNotFoundError:
360
+ existing_df = pd.DataFrame()
361
+ processed_indices = set()
362
+
363
+ # 2. 构造样本流
364
+ items_stream = (
365
+ item for item in load_dataset_streaming(dataset_name, split) if item["idx"] not in processed_indices
366
+ )
367
+ if sample_size:
368
+ from itertools import islice
369
+ items_stream = islice(items_stream, sample_size)
370
+
371
+ # 3. 推理(单进程直接迭代,因为 CUDA 模型无法跨进程共享)
372
+ new_results = []
373
+ FINMME_TOTAL_COUNT = 11099
374
+ total = sample_size if sample_size else FINMME_TOTAL_COUNT - len(processed_indices)
375
+
376
+ # 注意:LLaVA 模型在 GPU 上,不能用 multiprocessing.Pool
377
+ # 直接在主进程迭代
378
+ desc = "Processing (LLaVA local, single process)"
379
+ for item in tqdm(items_stream, total=total, desc=desc):
380
+ result = process_single_item(item)
381
+ if result:
382
+ new_results.append(result)
383
+
384
+ # 4. 合并 & 保存 & 统计
385
+ if not new_results and existing_df.empty:
386
+ print("No items processed; nothing to save.")
387
+ return
388
+
389
+ if new_results:
390
+ new_df = pd.DataFrame(new_results)
391
+ combined_df = (
392
+ pd.concat([existing_df, new_df], ignore_index=True)
393
+ .sort_values(by="idx")
394
+ .reset_index(drop=True)
395
+ )
396
+ else:
397
+ combined_df = existing_df
398
+
399
+ combined_df.to_csv(output_file, index=False)
400
+ print(f"\nResults saved to {output_file}")
401
+ accuracy = combined_df["correct_or_not"].mean()
402
+ print(f"Overall accuracy: {accuracy:.4%}")
403
+ calculate_finscore(combined_df)
404
+
405
+ if __name__ == "__main__":
406
+ import argparse
407
+
408
+ parser = argparse.ArgumentParser()
409
+ parser.add_argument("--dataset", default="luojunyu/FinMME")
410
+ parser.add_argument("--split", default="train")
411
+ parser.add_argument("--sample_size", type=int, default=None)
412
+ parser.add_argument("--num_processes", type=int, default=4)
413
+ args = parser.parse_args()
414
+
415
+ main(args.dataset, args.split, args.sample_size, args.num_processes)
fin-mm/code/FinMME/inference_log.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21c06f26eddc25d4a1e45556fce13cd9d8927f23a96827176069446b5540a1e1
3
+ size 41630149
fin-mm/code/FinMME/plot/example.png ADDED

Git LFS Details

  • SHA256: c2601a1b0c48a0258157b5a92d45914989cf5fe3fbb49e65d718cd89c37d8e68
  • Pointer size: 131 Bytes
  • Size of remote file: 559 kB
fin-mm/code/FinMME/plot/taxo.png ADDED

Git LFS Details

  • SHA256: 5c99a4bf5ed6a9ef762441cfd3b2bb782f47a47ba364edb140c63c779ef9fcc3
  • Pointer size: 131 Bytes
  • Size of remote file: 753 kB
fin-mm/code/FinMME/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pandas>=1.5.0
2
+ openai>=1.0.0
3
+ datasets>=2.14.0
4
+ tqdm>=4.64.0
5
+ numpy>=1.24.0
6
+ Pillow>=9.0.0
7
+ openpyxl>=3.0.0
8
+ requests>=2.28.0
9
+ huggingface_hub>=0.16.0
fin-mm/code/FinMultiTime_download.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Dict, Any
3
+ from pathlib import Path
4
+ import csv
5
+ import json
6
+ from tqdm import tqdm
7
+ from huggingface_hub import snapshot_download
8
+
9
+ # ========= 全局路径配置 =========
10
+ DATA_ROOT = Path("/workspace/data/finmultitime_hf") # HuggingFace 仓库本地目录
11
+ OUT_STOCK_MODAL_INDEX = Path("/workspace/data/finmultitime_stock_modal_index.jsonl")
12
+ OUT_FOUR_MODAL_INDEX = Path("/workspace/data/finmultitime_four_modal_files.jsonl")
13
+
14
+
15
+ # ========= 第一步:下载完整 FinMultiTime 仓库(只在本地不完整时下载) =========
16
+
17
+ def repo_already_downloaded() -> bool:
18
+ """
19
+ 只有当四个模态目录和两份 *_stock_data_description.csv 都存在时,
20
+ 才认为仓库已完整下载。
21
+ """
22
+ if not DATA_ROOT.exists():
23
+ return False
24
+
25
+ # 四个模态目录都要有
26
+ need_dirs = ["image", "table", "text", "time_series"]
27
+ for d in need_dirs:
28
+ if not (DATA_ROOT / d).is_dir():
29
+ return False
30
+
31
+ # 两个描述 CSV 也要有
32
+ if not (DATA_ROOT / "sp500stock_data_description.csv").is_file():
33
+ return False
34
+ if not (DATA_ROOT / "hs300stock_data_description.csv").is_file():
35
+ return False
36
+
37
+ return True
38
+
39
+
40
+ def download_repo_if_needed():
41
+ DATA_ROOT.mkdir(parents=True, exist_ok=True)
42
+ if repo_already_downloaded():
43
+ print(f"[FinMultiTime] Repo already complete at {DATA_ROOT}, skip download.")
44
+ return
45
+
46
+ print("[FinMultiTime] Repo not complete locally, start downloading from HF Hub...")
47
+ snapshot_download(
48
+ repo_id="Wenyan0110/Multimodal-Dataset-Image_Text_Table_TimeSeries-for-Financial-Time-Series-Forecasting",
49
+ repo_type="dataset",
50
+ local_dir=str(DATA_ROOT),
51
+ local_dir_use_symlinks=False,
52
+ )
53
+ print(f"[FinMultiTime] Repo downloaded to: {DATA_ROOT}")
54
+
55
+
56
+ # ========= 第二步:解析 *_data_description.csv (股票层面模态标记) =========
57
+
58
+ def load_desc(csv_path: Path, market: str) -> Dict[str, Dict[str, Any]]:
59
+ """
60
+ 读取 *_stock_data_description.csv,返回:
61
+ { stock_id: {market, has_image, has_time_series, has_table, has_text, extra } }
62
+ """
63
+
64
+ def read_csv_with_encoding(path: Path):
65
+ # 先尝试 utf-8,不行再退到 gbk / latin1,解决编码问题
66
+ for enc in ("utf-8", "gbk", "gb2312", "latin1"):
67
+ try:
68
+ with path.open("r", encoding=enc) as f:
69
+ content = f.read()
70
+ return content, enc
71
+ except UnicodeDecodeError:
72
+ continue
73
+ raise UnicodeDecodeError(f"Cannot decode {path} with any encoding")
74
+
75
+ meta: Dict[str, Dict[str, Any]] = {}
76
+ content, enc = read_csv_with_encoding(csv_path)
77
+ reader = csv.DictReader(content.splitlines())
78
+ for row in reader:
79
+ # —— 这里根据实际表头修改 —— #
80
+ stock_id = row.get("stock_id") or row.get("ticker") or row.get("symbol")
81
+ if not stock_id:
82
+ continue
83
+
84
+ rec: Dict[str, Any] = {
85
+ "stock_id": stock_id,
86
+ "market": market,
87
+ }
88
+
89
+ # 假设 CSV 里用 0/1 或 True/False 标记四模态,可按真实字段名调整
90
+ def flag(name: str) -> bool:
91
+ v = (row.get(name) or "").strip()
92
+ return v in ("1", "True", "true", "TRUE", "Y", "y", "Yes", "yes")
93
+
94
+ # —— 这些字段名要按照 CSV 表头修改 —— #
95
+ rec["has_image"] = flag("has_image")
96
+ rec["has_time_series"] = flag("has_time_series")
97
+ rec["has_table"] = flag("has_table")
98
+ rec["has_text"] = flag("has_text")
99
+
100
+ rec["extra"] = row
101
+ meta[stock_id] = rec
102
+ return meta
103
+
104
+
105
+ def build_stock_modal_index():
106
+ sp500_desc = DATA_ROOT / "sp500stock_data_description.csv"
107
+ hs300_desc = DATA_ROOT / "hs300stock_data_description.csv"
108
+
109
+ sp500_meta = load_desc(sp500_desc, market="SP500")
110
+ hs300_meta = load_desc(hs300_desc, market="HS300")
111
+
112
+ OUT_STOCK_MODAL_INDEX.parent.mkdir(parents=True, exist_ok=True)
113
+ with OUT_STOCK_MODAL_INDEX.open("w", encoding="utf-8") as f:
114
+ for d in sp500_meta.values():
115
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
116
+ for d in hs300_meta.values():
117
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
118
+
119
+ print(f"[FinMultiTime] Stock-level modal index saved to: {OUT_STOCK_MODAL_INDEX}")
120
+
121
+
122
+ # ========= 第三步:遍历四个模态目录,按股票 ID 归并文件路径 =========
123
+
124
+ def load_stock_modal_index(path: Path) -> Dict[str, Dict[str, Any]]:
125
+ meta: Dict[str, Dict[str, Any]] = {}
126
+ with path.open("r", encoding="utf-8") as f:
127
+ for line in f:
128
+ line = line.strip()
129
+ if not line:
130
+ continue
131
+ obj = json.loads(line)
132
+ meta[obj["stock_id"]] = obj
133
+ return meta
134
+
135
+
136
+ def add_files_by_stock(
137
+ base_dir: Path,
138
+ pattern: str,
139
+ key: str,
140
+ mapping: Dict[str, Dict[str, Any]],
141
+ ):
142
+ """
143
+ 遍历 base_dir 下所有匹配 pattern 的文件,
144
+ 根据文件名里的股票代码归类到 mapping[stock_id][key] 列表。
145
+ 假设文件名类似 AAPL_XXXX.* 或 600000_XXXX.*,stock_id 是前缀。
146
+ 根据真实命名规则修改解析方式即可。
147
+ """
148
+ if not base_dir.is_dir():
149
+ return
150
+ files = list(base_dir.rglob(pattern))
151
+ for path in tqdm(files, desc=f"Indexing {key} files"):
152
+ stem = path.stem
153
+ stock_id = stem.split("_")[0] # 按实际文件名规则调整
154
+ if stock_id not in mapping:
155
+ continue
156
+ mapping.setdefault(stock_id, {}).setdefault(key, []).append(str(path))
157
+
158
+
159
+ def build_four_modal_index():
160
+ stock_meta = load_stock_modal_index(OUT_STOCK_MODAL_INDEX)
161
+
162
+ # 初始化四模态文件列表
163
+ for rec in stock_meta.values():
164
+ rec.setdefault("image_files", [])
165
+ rec.setdefault("time_series_files", [])
166
+ rec.setdefault("table_files", [])
167
+ rec.setdefault("text_files", [])
168
+
169
+ # 1) 图像
170
+ image_root = DATA_ROOT / "image"
171
+ add_files_by_stock(image_root, "*.png", "image_files", stock_meta)
172
+
173
+ # 2) 时间序列
174
+ ts_root = DATA_ROOT / "time_series"
175
+ add_files_by_stock(ts_root, "*.csv", "time_series_files", stock_meta)
176
+ add_files_by_stock(ts_root, "*.zip", "time_series_files", stock_meta)
177
+
178
+ # 3) 表格
179
+ table_root = DATA_ROOT / "table"
180
+ add_files_by_stock(table_root, "*.json", "table_files", stock_meta)
181
+ add_files_by_stock(table_root, "*.jsonl", "table_files", stock_meta)
182
+ add_files_by_stock(table_root, "*.zip", "table_files", stock_meta)
183
+
184
+ # 4) 文本
185
+ text_root = DATA_ROOT / "text"
186
+ add_files_by_stock(text_root, "*.jsonl", "text_files", stock_meta)
187
+ add_files_by_stock(text_root, "*.zip", "text_files", stock_meta)
188
+
189
+ OUT_FOUR_MODAL_INDEX.parent.mkdir(parents=True, exist_ok=True)
190
+ with OUT_FOUR_MODAL_INDEX.open("w", encoding="utf-8") as f:
191
+ for stock_id, rec in stock_meta.items():
192
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
193
+
194
+ print(f"[FinMultiTime] Four-modal file index saved to: {OUT_FOUR_MODAL_INDEX}")
195
+
196
+
197
+ # ========= 主入口 =========
198
+
199
+ if __name__ == "__main__":
200
+ # 1) 如果本地没有完整仓库就下载;已经完整就直接跳过
201
+ download_repo_if_needed()
202
+
203
+ # 2) 构建股票层面的模态存在标记
204
+ build_stock_modal_index()
205
+
206
+ # 3) 构建四模态文件路径索引
207
+ build_four_modal_index()
fin-mm/code/FinMultiTime_index.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # build_kline_index.py
2
+ import json
3
+ from pathlib import Path
4
+
5
+ ROOT = Path("/workspace/data/finmultitime_hf")
6
+
7
+ # HS300
8
+ HS300_IMG_ROOT = ROOT / "image" / "HS300_image" / "HS300_image"
9
+ HS300_TS_ROOT = ROOT / "time_series" / "HS300_time_series" / "HS300_time_series"
10
+
11
+ # S&P500 图片:image/S&P500_image_a .../b.../c...
12
+ SP500_IMG_ROOT = ROOT / "image" / "image"
13
+ SP500_TS_ROOT = ROOT / "time_series" / "S&P500_time_series" / "S&P500_time_series"
14
+
15
+ OUT_PATH = ROOT / "finmultitime_kline_index.jsonl"
16
+
17
+
18
+ def collect_hs300():
19
+ for code_dir in sorted(HS300_IMG_ROOT.glob("*")):
20
+ if not code_dir.is_dir():
21
+ continue
22
+ stock_id = code_dir.name # 例如 000001.SZ
23
+ image_files = sorted(str(p) for p in code_dir.glob("*.png"))
24
+ if not image_files:
25
+ continue
26
+ ts_file = HS300_TS_ROOT / f"{stock_id}.csv"
27
+ rec = {
28
+ "market": "HS300",
29
+ "stock_id": stock_id,
30
+ "image_files": image_files,
31
+ "time_series_files": [str(ts_file)] if ts_file.is_file() else [],
32
+ }
33
+ yield rec
34
+
35
+
36
+ def collect_sp500():
37
+ # 遍历 S&P500_image_a ~ S&P500_image_h 等大目录
38
+ for big_dir in sorted(SP500_IMG_ROOT.glob("S&P500_image_*")):
39
+ if not big_dir.is_dir():
40
+ continue
41
+ # big_dir 下是按首字母分的子目录:aa, aapl, ...
42
+ for code_dir in sorted(big_dir.glob("*")):
43
+ if not code_dir.is_dir():
44
+ continue
45
+ stock_id = code_dir.name # 例如 aa, aapl
46
+ image_files = sorted(str(p) for p in code_dir.glob("*.png"))
47
+ if not image_files:
48
+ continue
49
+ ts_file = SP500_TS_ROOT / f"{stock_id}.csv"
50
+ rec = {
51
+ "market": "SP500",
52
+ "stock_id": stock_id,
53
+ "image_files": image_files,
54
+ "time_series_files": [str(ts_file)] if ts_file.is_file() else [],
55
+ }
56
+ yield rec
57
+
58
+
59
+ def main():
60
+ count = 0
61
+ with OUT_PATH.open("w", encoding="utf-8") as f:
62
+ for rec in collect_hs300():
63
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
64
+ count += 1
65
+ for rec in collect_sp500():
66
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
67
+ count += 1
68
+ print(f"[OK] wrote {count} records -> {OUT_PATH}")
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
fin-mm/code/FinMultiTime_kline_news.py ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ K线图 + 新闻 指令微调数据生成脚本
4
+ 生成 LLaVA 格式的训练数据,结合 K 线图和新闻摘要进行情感分析和趋势判断
5
+
6
+ 输出两个版本:
7
+ - 原版 (finmultitime_kline_news_llavaplus.json): 完整新闻,用于大模型训练
8
+ - 短版 (finmultitime_kline_news_llavaplus_short.json): 限制长度,用于 7B 模型训练
9
+ """
10
+
11
+ from __future__ import annotations
12
+ import json
13
+ import random
14
+ import os
15
+ from pathlib import Path
16
+ from typing import Dict, Any, List, Optional, Tuple
17
+ from datetime import datetime
18
+ from tqdm import tqdm
19
+ import re
20
+ import requests
21
+ import sys
22
+
23
+ # ========= NIM API 配置 =========
24
+ NIM_API_KEY = "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"
25
+ NIM_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions"
26
+ MODEL_NAME = "meta/llama-3.2-90b-vision-instruct"
27
+
28
+ # ========= 配置 =========
29
+ random.seed(42)
30
+
31
+ # 数据根目录
32
+ DATA_ROOT = Path("/workspace/data/finmultitime_hf")
33
+
34
+ # 输出文件
35
+ OUT_PATH_FULL = Path("/workspace/data/finmultitime_hf/finmultitime_kline_news_llavaplus.json")
36
+ OUT_PATH_SHORT = Path("/workspace/data/finmultitime_hf/finmultitime_kline_news_llavaplus_short.json")
37
+
38
+ # ========= 新闻采样配置 =========
39
+ # 原版配置 (完整新闻)
40
+ MAX_NEWS_PER_SAMPLE_FULL = 5 # 每个样本最多使用的新闻条数
41
+ MAX_NEWS_CHARS_FULL = None # 每条新闻最大字符数(None 表示不截断)
42
+ MAX_PROMPT_CHARS_FULL = None # prompt 最大字符数(None 表示不限制)
43
+
44
+ # 短版配置 (用于 7B 模型训练)
45
+ MAX_NEWS_PER_SAMPLE_SHORT = 3 # 每个样本最多使用的新闻条数
46
+ MAX_NEWS_CHARS_SHORT = 1500 # 每条新闻最大字符数
47
+ MAX_PROMPT_CHARS_SHORT = 8000 # prompt 最大字符数 (约 2600 tokens,留余量给回答)
48
+
49
+
50
+ def log(msg: str):
51
+ print(msg, flush=True)
52
+
53
+
54
+ # ========= 文本清理 =========
55
+
56
+ def clean_mojibake(text: str) -> str:
57
+ """清理编码乱码(Windows-1252 误读为 UTF-8 产生的乱码)
58
+
59
+ 常见乱码映射:
60
+ - 禄 → » (right double angle quote)
61
+ - 鈥? → — (em dash) 或 ' (smart quote)
62
+ - 鈥淭 → "T (left double quote)
63
+ - 鈥渕 → "m (left double quote)
64
+ - 鈥檚 → 's (right single quote)
65
+
66
+ 注意:替换顺序很重要!长的模式必须在短的之前,否则短的会先匹配。
67
+ """
68
+ # 使用列表保证顺序:长的在前,短的在后
69
+ replacements = [
70
+ # 先处理长的组合模式
71
+ ("鈥檚", "'s"),
72
+ ("鈥檛", "'t"),
73
+ ("鈥檝", "'v"),
74
+ ("鈥檒", "'l"),
75
+ ("鈥檙", "'r"),
76
+ ("鈥榮", "'s"),
77
+ ("鈥淭", '"T'),
78
+ ("鈥渕", '"m'),
79
+ ("鈥漑", '"['),
80
+ ("鈥?", "—"), # em dash with ?
81
+ # 再处理短的单字符模式
82
+ ("鈥", '"'), # 单独的鈥
83
+ ("禄", "»"),
84
+ ("芦", "«"),
85
+ # 其他常见乱码
86
+ ("脙聝", "Ã"),
87
+ ("脗", ""),
88
+ ("锟斤拷", ""),
89
+ ]
90
+
91
+ for bad, good in replacements:
92
+ text = text.replace(bad, good)
93
+
94
+ return text
95
+
96
+
97
+ # ========= NIM API 调用 =========
98
+
99
+ def call_nim(prompt: str, lang: str = "zh") -> str:
100
+ """调用 NIM API 生成回答
101
+
102
+ Args:
103
+ prompt: 用户提示词
104
+ lang: 语言,"zh" 中文 或 "en" 英文
105
+ """
106
+ headers = {
107
+ "Authorization": f"Bearer {NIM_API_KEY}",
108
+ "Content-Type": "application/json",
109
+ }
110
+
111
+ if lang == "zh":
112
+ system_content = (
113
+ "你是一名专业金融分析师,已经看到了题目中提到的 K 线图和相关新闻。"
114
+ "请用简洁、客观的中文回答用户问题,回答控制在 3–6 句,"
115
+ "严格按照指定的小标题结构输出,不要编造具体数值或未提及的事件。"
116
+ )
117
+ else:
118
+ system_content = (
119
+ "You are a professional financial analyst who has seen the K-line chart and related news mentioned in the question. "
120
+ "Please answer the user's question concisely and objectively in English. Keep the answer to 3-6 sentences, "
121
+ "strictly follow the specified subheading structure, and do not fabricate specific numbers or unmentioned events."
122
+ )
123
+
124
+ payload = {
125
+ "model": MODEL_NAME,
126
+ "messages": [
127
+ {"role": "system", "content": system_content},
128
+ {"role": "user", "content": prompt},
129
+ ],
130
+ "temperature": 0.4,
131
+ "max_tokens": 1024,
132
+ }
133
+
134
+ try:
135
+ resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=120)
136
+ resp.raise_for_status()
137
+ data = resp.json()
138
+ content = data["choices"][0]["message"]["content"].strip()
139
+ return content
140
+ except Exception as e:
141
+ log(f"[NIM ERROR] {e}")
142
+ # 返回默认回答
143
+ if lang == "zh":
144
+ return (
145
+ "【新闻情感】综合新闻摘要,整体情感偏向中性。\n\n"
146
+ "【走势关联】K线走势与新闻情感基本吻合。\n\n"
147
+ "【综合判断】短期内可能维持震荡走势。"
148
+ )
149
+ else:
150
+ return (
151
+ "【News Sentiment】The overall sentiment appears neutral.\n\n"
152
+ "【Price Correlation】The price movement aligns with the news sentiment.\n\n"
153
+ "【Overall Judgment】The stock may continue range-bound trading in the short term."
154
+ )
155
+
156
+
157
+ # ========= 路径查找函数 =========
158
+
159
+ def get_hs300_image_dir(stock_id: str) -> Optional[Path]:
160
+ """获取 HS300 股票的图像目录"""
161
+ img_dir = DATA_ROOT / "image" / "HS300_image" / "HS300_image" / stock_id
162
+ return img_dir if img_dir.exists() else None
163
+
164
+
165
+ def get_sp500_image_dir(ticker: str) -> Optional[Path]:
166
+ """获取 SP500 股票的图像目录(按首字母分目录)"""
167
+ first_letter = ticker[0].lower()
168
+ img_dir = DATA_ROOT / "image" / "image" / f"S&P500_image_{first_letter}" / ticker.lower()
169
+ return img_dir if img_dir.exists() else None
170
+
171
+
172
+ def get_hs300_news_file(stock_id: str) -> Optional[Path]:
173
+ """获取 HS300 股票的新闻文件(文件名包含公司名)"""
174
+ news_dir = DATA_ROOT / "text" / "hs300news_summary" / "hs300news_summary"
175
+ if not news_dir.exists():
176
+ return None
177
+ # 文件名格式: {股票代码}_{公司名}.jsonl
178
+ for f in news_dir.iterdir():
179
+ if f.name.startswith(stock_id + "_") and f.suffix == ".jsonl":
180
+ return f
181
+ return None
182
+
183
+
184
+ def get_sp500_news_file(ticker: str) -> Optional[Path]:
185
+ """获取 SP500 股票的新闻文件(新闻文件名是大写)"""
186
+ # 新闻文件名是大写
187
+ news_file = DATA_ROOT / "text" / "sp500_news" / "sp500_news" / f"{ticker.upper()}.jsonl"
188
+ return news_file if news_file.exists() else None
189
+
190
+
191
+ # ========= 新闻处理函数 =========
192
+
193
+ def load_news(
194
+ news_file: Path,
195
+ max_count: int = MAX_NEWS_PER_SAMPLE_SHORT,
196
+ lang: str = "zh",
197
+ time_range: Optional[Tuple[str, str]] = None,
198
+ ticker: Optional[str] = None,
199
+ ) -> List[Dict[str, Any]]:
200
+ """加载并采样新闻
201
+
202
+ Args:
203
+ news_file: 新闻文件路径
204
+ max_count: 最多返回的新闻条数
205
+ lang: "zh" 使用 summary 字段 (HS300), "en" 使用 Article 字段 (SP500)
206
+ time_range: 时间范围 (start_date, end_date),格式为 'YYYY-MM-DD',用于过滤新闻
207
+ ticker: 股票代码(SP500),用于验证新闻是否与该股票相关
208
+
209
+ Returns:
210
+ 过滤和采样后的新闻列表(按时间排序)
211
+ """
212
+ news_list = []
213
+ # 根据语言选择内容字段
214
+ content_field = "summary" if lang == "zh" else "Article"
215
+ # 日期字段:HS300 用 datetime, SP500 用 Date
216
+ date_field = "datetime" if lang == "zh" else "Date"
217
+
218
+ try:
219
+ with open(news_file, "r", encoding="utf-8") as f:
220
+ for line in f:
221
+ if not line.strip():
222
+ continue
223
+ try:
224
+ item = json.loads(line)
225
+ # 只保留有内容的新闻
226
+ content = item.get(content_field, "")
227
+ if not content or str(content).lower() == "nan" or len(str(content)) < 10:
228
+ continue
229
+
230
+ # 时间范围过滤
231
+ if time_range:
232
+ news_date = item.get(date_field, "")
233
+ if news_date:
234
+ # 提取日期部分 (YYYY-MM-DD)
235
+ news_date_str = str(news_date)[:10]
236
+ start_date, end_date = time_range
237
+ # 只保留在时间范围内的新闻
238
+ if not (start_date <= news_date_str <= end_date):
239
+ continue
240
+
241
+ # SP500: 验证新闻是否与该股票相关
242
+ if ticker and lang == "en":
243
+ # 检查新闻内容或标题是否提及该股票
244
+ title = item.get("Article_title", "") or ""
245
+ # 如果新闻中完全没有提到该股票代码,跳过
246
+ ticker_upper = ticker.upper()
247
+ if ticker_upper not in str(content).upper() and ticker_upper not in str(title).upper():
248
+ continue
249
+
250
+ # 统一使用 summary 字段存储内容
251
+ item["summary"] = str(content)
252
+ news_list.append(item)
253
+ except json.JSONDecodeError:
254
+ continue
255
+ except Exception as e:
256
+ log(f"[WARN] Failed to load news from {news_file}: {e}")
257
+ return []
258
+
259
+ # 按日期排序(最新的在前)
260
+ news_list.sort(key=lambda x: str(x.get(date_field, ""))[:10], reverse=True)
261
+
262
+ # 随机采样(如果数量超过限制)
263
+ if len(news_list) > max_count:
264
+ # 优先保留最新的一半,随机采样另一半
265
+ recent_count = max_count // 2
266
+ recent_news = news_list[:recent_count]
267
+ older_news = news_list[recent_count:]
268
+ sampled_older = random.sample(older_news, min(len(older_news), max_count - recent_count))
269
+ news_list = recent_news + sampled_older
270
+ # 重新按时间排序
271
+ news_list.sort(key=lambda x: str(x.get(date_field, ""))[:10], reverse=True)
272
+
273
+ return news_list
274
+
275
+
276
+ def format_news_text(
277
+ news_list: List[Dict[str, Any]],
278
+ lang: str = "zh",
279
+ max_chars_per_news: Optional[int] = None,
280
+ ) -> str:
281
+ """将新闻列表格式化为文本
282
+
283
+ Args:
284
+ news_list: 新闻列表
285
+ lang: 语言
286
+ max_chars_per_news: 每条新闻最大字符数(None 表示不截断)
287
+ """
288
+ formatted = []
289
+ for i, item in enumerate(news_list, 1):
290
+ summary = str(item.get("summary", "")).strip()
291
+ # 清理乱码
292
+ summary = clean_mojibake(summary)
293
+
294
+ # 截断过长新闻
295
+ if max_chars_per_news and len(summary) > max_chars_per_news:
296
+ summary = summary[:max_chars_per_news] + "..."
297
+
298
+ # HS300 用 datetime, SP500 用 Date
299
+ dt = item.get("datetime", "") or item.get("Date", "")
300
+ # HS300 用 title, SP500 用 Article_title
301
+ title = item.get("title", "") or item.get("Article_title", "")
302
+ # 清理标题乱码
303
+ if title:
304
+ title = clean_mojibake(str(title))
305
+
306
+ if title and str(title).lower() != "nan" and title.strip():
307
+ formatted.append(f"[{i}] ({dt}) {title}: {summary}")
308
+ else:
309
+ formatted.append(f"[{i}] ({dt}) {summary}")
310
+
311
+ return "\n".join(formatted)
312
+
313
+
314
+ def parse_image_period(image_name: str, lang: str = "zh") -> Optional[str]:
315
+ """从图像文件名解析时间段
316
+
317
+ Args:
318
+ image_name: 图像文件名,如 '000001.SZ_2020_H1_candlestick.png'
319
+ lang: 语言,"zh" 返回中文格式,"en" 返回英文格式
320
+
321
+ Returns:
322
+ 中文: '2020年上半年'
323
+ 英文: '2020 H1'
324
+ """
325
+ match = re.search(r"(\d{4})_H([12])", image_name)
326
+ if match:
327
+ year, half = match.groups()
328
+ if lang == "zh":
329
+ half_text = "上半年" if half == "1" else "下半年"
330
+ return f"{year}年{half_text}"
331
+ else:
332
+ return f"{year} H{half}"
333
+ return None
334
+
335
+
336
+ def parse_image_time_range(image_name: str) -> Optional[Tuple[str, str]]:
337
+ """从图像文件名解析时间范围
338
+
339
+ Args:
340
+ image_name: 图像文件名,如 '000001.SZ_2020_H1_candlestick.png'
341
+
342
+ Returns:
343
+ (start_date, end_date) 格式为 'YYYY-MM-DD'
344
+ 例如 2020_H1 -> ('2020-01-01', '2020-06-30')
345
+ """
346
+ match = re.search(r"(\d{4})_H([12])", image_name)
347
+ if match:
348
+ year, half = match.groups()
349
+ if half == "1":
350
+ return (f"{year}-01-01", f"{year}-06-30")
351
+ else:
352
+ return (f"{year}-07-01", f"{year}-12-31")
353
+ return None
354
+
355
+
356
+ # ========= 指令模板 =========
357
+
358
+ def build_kline_news_sample_zh(
359
+ stock_id: str,
360
+ image_path: str,
361
+ news_text: str,
362
+ period: str,
363
+ difficulty: str = "medium",
364
+ max_prompt_chars: Optional[int] = None,
365
+ ) -> Optional[Dict[str, Any]]:
366
+ """构建中文 K线+新闻 样本
367
+
368
+ Args:
369
+ max_prompt_chars: prompt 最大字符数,超过则返回 None
370
+
371
+ Returns:
372
+ 样本字典,如果 prompt 太长则返回 None
373
+ """
374
+
375
+ user_text = (
376
+ "<image>\n"
377
+ f"你已经获得股票 {stock_id} 在{period}的日 K 线图。"
378
+ f"同时,以下是该时间段内与该股票相关的新闻摘要:\n\n"
379
+ f"{news_text}\n\n"
380
+ "请严格按照下面三段结构,用简洁的中文做出分析:\n"
381
+ "【新闻情感】判断这些新闻整体偏利好、利空还是中性,并说明主要依据(如业绩增长、政策利好、负面事件等)。\n"
382
+ "【走势关联】结合 K 线图的走势特征,分析新闻情感与股价走势是否一致(如利好新闻是否伴随上涨),并指出可能的原因。\n"
383
+ "【综合判断】综合新闻面和技术面,判断该股票短期内更可能延续当前趋势、出现反转还是震荡,并给出 1 句话理由。\n"
384
+ "注意:不要预测具体价格,不要编造新闻中未提及的事件,只基于提供的信息做定性分析。"
385
+ )
386
+
387
+ # 检查 prompt 长度
388
+ if max_prompt_chars and len(user_text) > max_prompt_chars:
389
+ return None
390
+
391
+ # 使用 NIM API 生成回答
392
+ nim_prompt = (
393
+ f"你已经看到了股票 {stock_id} 在{period}的日 K 线图,以及以下新闻摘要:\n\n"
394
+ f"{news_text[:2000]}...\n\n" # 截断过长的新闻给 API
395
+ "请用中文严格按照下面三段输出,每段 1-2 句,总字数控制在 3-6 句:\n"
396
+ "【新闻情感】判断新闻整体偏利好、利空还是中性,并说明依据。\n"
397
+ "【走势关联】分析新闻情感与K线走势是否一致,指出可能原因。\n"
398
+ "【综合判断】判断短期走势方向(延续、反转或震荡),并给出理由。\n"
399
+ "不要预测具体价格,不要编造未提及的事件。"
400
+ )
401
+ assistant = call_nim(nim_prompt, lang="zh")
402
+
403
+ return {
404
+ "id": None,
405
+ "image": Path(image_path).name,
406
+ "conversations": [
407
+ {"from": "human", "value": user_text},
408
+ {"from": "gpt", "value": assistant},
409
+ ],
410
+ "task_type": "kline_news_sentiment",
411
+ "difficulty": difficulty,
412
+ "images": [image_path],
413
+ "news_count": len(news_text.split("\n")),
414
+ "prompt_chars": len(user_text),
415
+ }
416
+
417
+
418
+ def build_kline_news_sample_en(
419
+ ticker: str,
420
+ image_path: str,
421
+ news_text: str,
422
+ period: str,
423
+ difficulty: str = "medium",
424
+ max_prompt_chars: Optional[int] = None,
425
+ ) -> Optional[Dict[str, Any]]:
426
+ """构建英文 K线+新闻 样本
427
+
428
+ Args:
429
+ max_prompt_chars: prompt 最大字符数,超过则返回 None
430
+
431
+ Returns:
432
+ 样本字典,如果 prompt 太长则返回 None
433
+ """
434
+
435
+ user_text = (
436
+ "<image>\n"
437
+ f"You have been given the daily K-line chart of stock {ticker} for {period}. "
438
+ f"Below are news summaries related to this stock during the same period:\n\n"
439
+ f"{news_text}\n\n"
440
+ "Please analyze according to the following three-part structure:\n"
441
+ "【News Sentiment】Determine whether the overall sentiment of these news is bullish, bearish, or neutral, "
442
+ "and explain the main basis (e.g., earnings growth, policy support, negative events).\n"
443
+ "【Price Correlation】Based on the K-line chart pattern, analyze whether the news sentiment aligns with "
444
+ "the stock price movement, and explain possible reasons.\n"
445
+ "【Overall Judgment】Combining fundamental news and technical analysis, determine whether the stock is "
446
+ "more likely to continue its current trend, reverse, or consolidate in the short term, with a brief explanation.\n"
447
+ "Note: Do not predict specific prices or fabricate events not mentioned in the news."
448
+ )
449
+
450
+ # 检查 prompt 长度
451
+ if max_prompt_chars and len(user_text) > max_prompt_chars:
452
+ return None
453
+
454
+ # 使用 NIM API 生成回答
455
+ nim_prompt = (
456
+ f"You have seen the daily K-line chart of stock {ticker} for {period}, along with these news summaries:\n\n"
457
+ f"{news_text[:2000]}...\n\n" # 截断过长的新闻给 API
458
+ "Please output in English strictly following the three sections below, 1-2 sentences each, total 3-6 sentences:\n"
459
+ "【News Sentiment】Determine if the news is bullish, bearish, or neutral, with reasoning.\n"
460
+ "【Price Correlation】Analyze if news sentiment aligns with K-line movement, explain why.\n"
461
+ "【Overall Judgment】Predict short-term direction (continue, reverse, or consolidate) with reason.\n"
462
+ "Do not predict specific prices or fabricate unmentioned events."
463
+ )
464
+ assistant = call_nim(nim_prompt, lang="en")
465
+
466
+ return {
467
+ "id": None,
468
+ "image": Path(image_path).name,
469
+ "conversations": [
470
+ {"from": "human", "value": user_text},
471
+ {"from": "gpt", "value": assistant},
472
+ ],
473
+ "task_type": "kline_news_sentiment",
474
+ "difficulty": difficulty,
475
+ "images": [image_path],
476
+ "news_count": len(news_text.split("\n")),
477
+ "prompt_chars": len(user_text),
478
+ }
479
+
480
+
481
+ # ========= 主流程 =========
482
+
483
+ def process_hs300(
484
+ max_samples: Optional[int] = None,
485
+ max_news: int = MAX_NEWS_PER_SAMPLE_SHORT,
486
+ max_news_chars: Optional[int] = None,
487
+ max_prompt_chars: Optional[int] = None,
488
+ ) -> List[Dict[str, Any]]:
489
+ """处理 HS300 数据
490
+
491
+ Args:
492
+ max_samples: 最大样本数,None 表示不限制
493
+ max_news: 每个样本最多新闻条数
494
+ max_news_chars: 每条新闻最大字符数
495
+ max_prompt_chars: prompt 最大字符数
496
+ """
497
+ samples = []
498
+ skipped_long = 0
499
+
500
+ # 遍历所有 HS300 股票
501
+ hs300_img_root = DATA_ROOT / "image" / "HS300_image" / "HS300_image"
502
+ if not hs300_img_root.exists():
503
+ log(f"[WARN] HS300 image dir not found: {hs300_img_root}")
504
+ return samples
505
+
506
+ stock_dirs = [d for d in hs300_img_root.iterdir() if d.is_dir()]
507
+ log(f"[HS300] Found {len(stock_dirs)} stock directories")
508
+
509
+ for stock_dir in tqdm(stock_dirs, desc="Processing HS300"):
510
+ # 检查是否达到限制
511
+ if max_samples and len(samples) >= max_samples:
512
+ break
513
+
514
+ stock_id = stock_dir.name
515
+
516
+ # 获取新闻文件
517
+ news_file = get_hs300_news_file(stock_id)
518
+ if not news_file:
519
+ continue
520
+
521
+ # 获取所有图像
522
+ images = list(stock_dir.glob("*.png"))
523
+ if not images:
524
+ continue
525
+
526
+ # 随机选一张图像生成样本(限制时)
527
+ selected_images = [random.choice(images)] if max_samples else images
528
+
529
+ for img_path in selected_images:
530
+ if max_samples and len(samples) >= max_samples:
531
+ break
532
+
533
+ # 解析图片的时间范围
534
+ time_range = parse_image_time_range(img_path.name)
535
+ period = parse_image_period(img_path.name, lang="zh")
536
+ if not period:
537
+ period = "某一时间段"
538
+
539
+ # 加载该时间段内的新闻
540
+ news_list = load_news(news_file, max_count=max_news, lang="zh", time_range=time_range)
541
+ if not news_list:
542
+ # 如果该时间段没有新闻,跳过这张图片
543
+ continue
544
+
545
+ news_text = format_news_text(news_list, lang="zh", max_chars_per_news=max_news_chars)
546
+
547
+ try:
548
+ sample = build_kline_news_sample_zh(
549
+ stock_id=stock_id,
550
+ image_path=str(img_path),
551
+ news_text=news_text,
552
+ period=period,
553
+ difficulty="medium",
554
+ max_prompt_chars=max_prompt_chars,
555
+ )
556
+ if sample is None:
557
+ skipped_long += 1
558
+ continue
559
+ sample["id"] = f"HS300_{stock_id}_kline_news_{len(samples)}"
560
+ samples.append(sample)
561
+ log(f"[HS300] {len(samples)}/{max_samples or '∞'} - {stock_id} ({period})")
562
+ except Exception as e:
563
+ log(f"[WARN] Failed on {stock_id}: {e}")
564
+ continue
565
+
566
+ if skipped_long > 0:
567
+ log(f"[HS300] Skipped {skipped_long} samples due to prompt length")
568
+
569
+ return samples
570
+
571
+
572
+ def process_sp500(
573
+ max_samples: Optional[int] = None,
574
+ max_news: int = MAX_NEWS_PER_SAMPLE_SHORT,
575
+ max_news_chars: Optional[int] = None,
576
+ max_prompt_chars: Optional[int] = None,
577
+ ) -> List[Dict[str, Any]]:
578
+ """处理 SP500 数据
579
+
580
+ Args:
581
+ max_samples: 最大样本数,None 表示不限制
582
+ max_news: 每个样本最多新闻条数
583
+ max_news_chars: 每条新闻最大字符数
584
+ max_prompt_chars: prompt 最大字符数
585
+ """
586
+ samples = []
587
+ skipped_long = 0
588
+
589
+ # 遍历所有 SP500 图像目录 (a-z)
590
+ sp500_img_root = DATA_ROOT / "image" / "image"
591
+ if not sp500_img_root.exists():
592
+ log(f"[WARN] SP500 image dir not found: {sp500_img_root}")
593
+ return samples
594
+
595
+ # 收集所有股票目录
596
+ stock_dirs = []
597
+ for letter_dir in sp500_img_root.iterdir():
598
+ if letter_dir.is_dir() and letter_dir.name.startswith("S&P500_image_"):
599
+ for stock_dir in letter_dir.iterdir():
600
+ if stock_dir.is_dir():
601
+ stock_dirs.append(stock_dir)
602
+
603
+ log(f"[SP500] Found {len(stock_dirs)} stock directories")
604
+
605
+ for stock_dir in tqdm(stock_dirs, desc="Processing SP500"):
606
+ # 检查是否达到限制
607
+ if max_samples and len(samples) >= max_samples:
608
+ break
609
+
610
+ ticker = stock_dir.name.upper()
611
+
612
+ # 获取新闻文件
613
+ news_file = get_sp500_news_file(ticker)
614
+ if not news_file:
615
+ continue
616
+
617
+ # 获取所有图像
618
+ images = list(stock_dir.glob("*.png"))
619
+ if not images:
620
+ continue
621
+
622
+ # 随机选图像生成样本
623
+ if max_samples:
624
+ selected_images = [random.choice(images)]
625
+ else:
626
+ selected_images = random.sample(images, min(len(images), 3))
627
+
628
+ for img_path in selected_images:
629
+ if max_samples and len(samples) >= max_samples:
630
+ break
631
+
632
+ # 解析图片的时间范围
633
+ time_range = parse_image_time_range(img_path.name)
634
+ period = parse_image_period(img_path.name, lang="en")
635
+ if not period:
636
+ period = "a certain period"
637
+
638
+ # 加载该时间段内且与该股票相关的新闻
639
+ news_list = load_news(news_file, max_count=max_news, lang="en", time_range=time_range, ticker=ticker)
640
+ if not news_list:
641
+ # 如果该时间段没有相关新闻,跳过这张图片
642
+ continue
643
+
644
+ news_text = format_news_text(news_list, lang="en", max_chars_per_news=max_news_chars)
645
+
646
+ try:
647
+ sample = build_kline_news_sample_en(
648
+ ticker=ticker,
649
+ image_path=str(img_path),
650
+ news_text=news_text,
651
+ period=period,
652
+ difficulty="medium",
653
+ max_prompt_chars=max_prompt_chars,
654
+ )
655
+ if sample is None:
656
+ skipped_long += 1
657
+ continue
658
+ sample["id"] = f"SP500_{ticker}_kline_news_{len(samples)}"
659
+ samples.append(sample)
660
+ log(f"[SP500] {len(samples)}/{max_samples or '∞'} - {ticker} ({period})")
661
+ except Exception as e:
662
+ log(f"[WARN] Failed on {ticker}: {e}")
663
+ continue
664
+
665
+ if skipped_long > 0:
666
+ log(f"[SP500] Skipped {skipped_long} samples due to prompt length")
667
+
668
+ return samples
669
+
670
+
671
+ def save_samples(samples: List[Dict[str, Any]], out_path: Path, version_name: str):
672
+ """保存样本并打印统计"""
673
+ with out_path.open("w", encoding="utf-8") as f:
674
+ json.dump(samples, f, ensure_ascii=False, indent=2)
675
+
676
+ # 统计
677
+ hs300_count = sum(1 for s in samples if s["id"].startswith("HS300"))
678
+ sp500_count = sum(1 for s in samples if s["id"].startswith("SP500"))
679
+ prompt_lengths = [s.get("prompt_chars", 0) for s in samples]
680
+
681
+ log(f"\n[{version_name}] Statistics:")
682
+ log(f" - Total: {len(samples)}")
683
+ log(f" - HS300: {hs300_count}")
684
+ log(f" - SP500: {sp500_count}")
685
+ if prompt_lengths:
686
+ log(f" - Prompt chars: min={min(prompt_lengths)}, max={max(prompt_lengths)}, avg={sum(prompt_lengths)//len(prompt_lengths)}")
687
+ log(f" - Output: {out_path}")
688
+
689
+
690
+ def main(max_samples: Optional[int] = None, generate_full: bool = False, generate_short: bool = True):
691
+ """
692
+ Args:
693
+ max_samples: 最大样本数(每个市场各生成 max_samples/2 个),None 表示不限制
694
+ generate_full: 是否生成完整版(用于大模型训练)
695
+ generate_short: 是否生成短版本(用于 7B 模型训练)
696
+ """
697
+ log("=" * 60)
698
+ log("K线图 + 新闻 指令微调数据生成 (NIM API)")
699
+ log("=" * 60)
700
+ if max_samples:
701
+ log(f"[CONFIG] max_samples = {max_samples} (HS300: {max_samples//2}, SP500: {max_samples//2})")
702
+ log(f"[CONFIG] generate_full = {generate_full}")
703
+ log(f"[CONFIG] generate_short = {generate_short}")
704
+
705
+ OUT_PATH_FULL.parent.mkdir(parents=True, exist_ok=True)
706
+
707
+ hs300_limit = max_samples // 2 if max_samples else None
708
+ sp500_limit = max_samples // 2 if max_samples else None
709
+
710
+ # ========== 生成完整版 ==========
711
+ if generate_full:
712
+ log("\n" + "=" * 60)
713
+ log("[FULL VERSION] Generating full-length samples...")
714
+ log("=" * 60)
715
+
716
+ all_samples_full = []
717
+
718
+ log("\n[1/2] Processing HS300 (FULL)...")
719
+ hs300_full = process_hs300(
720
+ max_samples=hs300_limit,
721
+ max_news=MAX_NEWS_PER_SAMPLE_FULL,
722
+ max_news_chars=MAX_NEWS_CHARS_FULL,
723
+ max_prompt_chars=MAX_PROMPT_CHARS_FULL,
724
+ )
725
+ all_samples_full.extend(hs300_full)
726
+
727
+ log("\n[2/2] Processing SP500 (FULL)...")
728
+ sp500_full = process_sp500(
729
+ max_samples=sp500_limit,
730
+ max_news=MAX_NEWS_PER_SAMPLE_FULL,
731
+ max_news_chars=MAX_NEWS_CHARS_FULL,
732
+ max_prompt_chars=MAX_PROMPT_CHARS_FULL,
733
+ )
734
+ all_samples_full.extend(sp500_full)
735
+
736
+ random.shuffle(all_samples_full)
737
+ save_samples(all_samples_full, OUT_PATH_FULL, "FULL")
738
+
739
+ # ========== 生成短版 ==========
740
+ if generate_short:
741
+ log("\n" + "=" * 60)
742
+ log("[SHORT VERSION] Generating short samples for 7B model...")
743
+ log("=" * 60)
744
+
745
+ # 重置随机种子确保一致性
746
+ random.seed(42)
747
+
748
+ all_samples_short = []
749
+
750
+ log("\n[1/2] Processing HS300 (SHORT)...")
751
+ hs300_short = process_hs300(
752
+ max_samples=hs300_limit,
753
+ max_news=MAX_NEWS_PER_SAMPLE_SHORT,
754
+ max_news_chars=MAX_NEWS_CHARS_SHORT,
755
+ max_prompt_chars=MAX_PROMPT_CHARS_SHORT,
756
+ )
757
+ all_samples_short.extend(hs300_short)
758
+
759
+ log("\n[2/2] Processing SP500 (SHORT)...")
760
+ sp500_short = process_sp500(
761
+ max_samples=sp500_limit,
762
+ max_news=MAX_NEWS_PER_SAMPLE_SHORT,
763
+ max_news_chars=MAX_NEWS_CHARS_SHORT,
764
+ max_prompt_chars=MAX_PROMPT_CHARS_SHORT,
765
+ )
766
+ all_samples_short.extend(sp500_short)
767
+
768
+ random.shuffle(all_samples_short)
769
+ save_samples(all_samples_short, OUT_PATH_SHORT, "SHORT")
770
+
771
+ log("\n" + "=" * 60)
772
+ log("[DONE] All data generation complete!")
773
+ log("=" * 60)
774
+
775
+
776
+ if __name__ == "__main__":
777
+ # ============ 测试时设置 max_samples,正式运行设为 None ============
778
+ # main(max_samples=10) # 测试:每个市场各 5 条
779
+ # main(max_samples=None, generate_full=True, generate_short=True) # 生成两个版本
780
+ main(max_samples=None, generate_full=False, generate_short=True) # 只生成 SHORT 版本
fin-mm/code/FinMultiTime_to_llava.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import random
4
+ from pathlib import Path
5
+ from typing import Dict, Any, List, Optional
6
+ import requests
7
+ import sys
8
+ from tqdm import tqdm
9
+
10
+ # ========= 配置 =========
11
+ NIM_API_KEY = "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" # 换成你的
12
+ NIM_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions"
13
+ MODEL_NAME = "meta/llama-3.2-90b-vision-instruct"
14
+
15
+ # 上一步生成的 k 线索引
16
+ INPUT_INDEX = Path("/workspace/data/finmultitime_hf/finmultitime_kline_index.jsonl")
17
+ # 输出:直接供 LLaVA-Plus --data_path 使用
18
+ OUT_PATH = Path("/workspace/data/finmultitime_hf/finmultitime_kline_llavaplus.json")
19
+
20
+ random.seed(42)
21
+
22
+
23
+ def log(msg: str):
24
+ print(msg)
25
+ sys.stdout.flush()
26
+
27
+
28
+ def call_nim(prompt: str) -> str:
29
+ headers = {
30
+ "Authorization": f"Bearer {NIM_API_KEY}",
31
+ "Content-Type": "application/json",
32
+ }
33
+ payload = {
34
+ "model": MODEL_NAME,
35
+ "messages": [
36
+ {
37
+ "role": "system",
38
+ "content": (
39
+ "你是一名专业量化分析师,已经看到了题目中提到的 K 线图或价格序列。"
40
+ "请用简洁、客观的中文回答用户问题,回答控制在 2–5 句,"
41
+ "严格按照指定的小标题结构输出,不要编造具体数值或未提及的事件。"
42
+ ),
43
+ },
44
+ {"role": "user", "content": prompt},
45
+ ],
46
+ "temperature": 0.4,
47
+ "max_tokens": 512,
48
+ }
49
+ log("[NIM] sending request...")
50
+ resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=60)
51
+ log(f"[NIM] status: {resp.status_code}")
52
+ resp.raise_for_status()
53
+ data = resp.json()
54
+ content = data["choices"][0]["message"]["content"].strip()
55
+ log(f"[NIM] got {len(content)} chars")
56
+ return content
57
+
58
+
59
+ def file_exists_any(paths: List[str]) -> List[str]:
60
+ return [p for p in paths if Path(p).is_file()]
61
+
62
+
63
+ # ==== 模板 1:单图 K 线阅读 ====
64
+
65
+ def build_kline_only_sample(
66
+ base_rec: Dict[str, Any],
67
+ image_path: str,
68
+ difficulty: str = "easy",
69
+ ) -> Dict[str, Any]:
70
+ stock_id = base_rec["stock_id"]
71
+ user_text = (
72
+ "<image>\n"
73
+ f"你已经看到了股票 {stock_id} 在一个固定时间窗口内的日 K 线图(包含价格和成交量)。"
74
+ "请严格按照下面的三段结构,用简洁的中文回答问题:\n"
75
+ "【总体趋势】判断该时间段内股价整体是上涨、下跌还是震荡,并用 1 句话概括上涨或下跌的大致节奏,例如“先跌后涨”“缓慢震荡上行”等。\n"
76
+ "【关键波动】指出这段时间内最明显的 1–3 次急涨或急跌,大致说明发生在前段、中段还是末段,以及这些波动是顺势放大还是趋势中的回调。\n"
77
+ "【交易含义】站在短线交易者角度,总结这段走势更偏向于高位追涨风险大、逢低布局机会多,还是应以观望为主,并给出 1 句简要理由(例如“频繁剧烈波动,追涨容易被套”)。\n"
78
+ "注意:不要给出具体价格或收益百分比,不要编造任何图上看不到的消息或事件,只基于 K 线本身做定性判断。"
79
+ )
80
+
81
+ assistant = call_nim(
82
+ "你已经仔细观察了一张股票日 K 线图(包含价格和成交量)。"
83
+ "请用中文严格按照下面三段输出,每段 1 句左右,总字数控制在 3–5 句:\n"
84
+ "【总体趋势】...\n"
85
+ "【关键波动】...\n"
86
+ "【交易含义】...\n"
87
+ "不要写出具体价格数值或收益百分比,不要提及任何图上看不到的新闻或事件,只描述从 K 线本身能看到的走势特征和含义。"
88
+ )
89
+
90
+ sample = {
91
+ "id": None,
92
+ "image": Path(image_path).name, # LLaVA-Plus 用相对文件名
93
+ "conversations": [
94
+ {"from": "human", "value": user_text},
95
+ {"from": "gpt", "value": assistant},
96
+ ],
97
+ "task_type": "kline_reading",
98
+ "difficulty": difficulty,
99
+ "images": [image_path],
100
+ "timeseries_files": [],
101
+ "table_files": [],
102
+ "text_files": [],
103
+ }
104
+ return sample
105
+
106
+
107
+ # ==== 模板 2:图 + 时间序列趋势 ====
108
+
109
+ def build_kline_trend_sample(
110
+ base_rec: Dict[str, Any],
111
+ image_path: str,
112
+ ts_path: str,
113
+ difficulty: str = "easy",
114
+ future_label: Optional[Dict[str, Any]] = None,
115
+ ) -> Dict[str, Any]:
116
+ stock_id = base_rec["stock_id"]
117
+ user_text = (
118
+ "<image>\n"
119
+ f"你已经获得股票 {stock_id} 在一个固定时间窗口内的日 K 线图,以及同一时间段的收盘价时间序列。"
120
+ "请严格按照下面三段结构,用简洁的中文做出分析:\n"
121
+ "【历史趋势】综合 K 线和价格序列,判断该时间段内股价是缓慢上涨、震荡上行、区间震荡、震荡下跌还是快速下跌,并用 1 句话概括整体节奏(例如“前期横盘、后期快速拉升”)。\n"
122
+ "【风险与机会】指出这段走势中最大的 1–2 个风险点(如高位放量长上影、大幅跳空下跌等)和 1–2 个潜在机会(如低位放量企稳、缩量回调等),并说明它们大致出现在前段、中段还是末段。\n"
123
+ "【未来偏向】在不考虑估值和基本面信息的前提下,仅基于当前这段走势形态,判断接下来短期更可能是延续当前方向、出现方向性反转,还是维持区间震荡,并用 1 句话给出理由(如“放量突破箱体后回踩不深,更可能延续上涨”)。\n"
124
+ "注意:不要预测具体价格或收益百分比,不要编造任何新闻或基本面事件,只基于走势形态和价格变化做方向性判断。"
125
+ )
126
+
127
+ assistant = call_nim(
128
+ "你已经看到了某只股票一段时间内的日 K 线图和对应收盘价时间序列。"
129
+ "请用中文严格按照下面三段输出,总 3–5 句:\n"
130
+ "【历史趋势】...\n"
131
+ "【风险与机会】...\n"
132
+ "【未来偏向】...\n"
133
+ "每段 1–2 句,不要写具体价格或收益数值,不要提及任何图上看不到的新闻或政策,只描述走势形态、风险和方向性判断。"
134
+ )
135
+
136
+ sample = {
137
+ "id": None,
138
+ "image": Path(image_path).name,
139
+ "conversations": [
140
+ {"from": "human", "value": user_text},
141
+ {"from": "gpt", "value": assistant},
142
+ ],
143
+ "task_type": "kline_trend",
144
+ "difficulty": difficulty,
145
+ "images": [image_path],
146
+ "timeseries_files": [ts_path],
147
+ "table_files": [],
148
+ "text_files": [],
149
+ }
150
+ if future_label is not None:
151
+ # 预留给你后续从 ts 里计算真实 10 日收益/方向
152
+ sample["label"] = future_label
153
+ return sample
154
+
155
+
156
+ def main(max_samples: Optional[int] = None):
157
+ OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
158
+
159
+ records: List[Dict[str, Any]] = []
160
+ with INPUT_INDEX.open("r", encoding="utf-8") as fin:
161
+ for line in fin:
162
+ if not line.strip():
163
+ continue
164
+ records.append(json.loads(line))
165
+
166
+ log(f"[MAIN] kline records: {len(records)}")
167
+ all_samples: List[Dict[str, Any]] = []
168
+ count = 0
169
+
170
+ for rec in tqdm(records, desc="Generating kline samples"):
171
+ images = file_exists_any(rec.get("image_files", []))
172
+ ts_files = file_exists_any(rec.get("time_series_files", []))
173
+ if not images:
174
+ continue
175
+
176
+ templates: List[str] = []
177
+ if images and ts_files:
178
+ templates.extend(["kline_trend"] * 3) # 让 trend 占比高一点
179
+ templates.append("kline_reading")
180
+
181
+ tpl = random.choice(templates)
182
+ log(f"[MAIN] {rec['market']} {rec['stock_id']} tpl={tpl}")
183
+
184
+ try:
185
+ if tpl == "kline_trend" and ts_files:
186
+ future_label = {
187
+ "future_return_10d": None,
188
+ "future_direction_10d": None,
189
+ }
190
+ sample = build_kline_trend_sample(
191
+ rec,
192
+ random.choice(images),
193
+ random.choice(ts_files),
194
+ difficulty="easy",
195
+ future_label=future_label,
196
+ )
197
+ else:
198
+ sample = build_kline_only_sample(
199
+ rec,
200
+ random.choice(images),
201
+ difficulty="easy",
202
+ )
203
+ except Exception as e:
204
+ log(f"[WARN] fail on {rec['stock_id']} ({tpl}): {e}")
205
+ continue
206
+
207
+ sample["id"] = f"{rec['market']}_{rec['stock_id']}_{tpl}_{count}"
208
+ all_samples.append(sample)
209
+ count += 1
210
+ if max_samples is not None and count >= max_samples:
211
+ break
212
+
213
+ with OUT_PATH.open("w", encoding="utf-8") as f:
214
+ json.dump(all_samples, f, ensure_ascii=False, indent=2)
215
+
216
+ log(f"[OK] generated {count} samples -> {OUT_PATH}")
217
+
218
+
219
+ if __name__ == "__main__":
220
+ # 先用小一点的 max_samples 验证一下,再放开
221
+ main(max_samples=None)
fin-mm/code/FinMultiTime_to_llava_multimodel.py ADDED
@@ -0,0 +1,779 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ NIM 多模型 K线图指令微调数据生成脚本
4
+ 支持 NVIDIA NIM 平台上最强的商用模型
5
+
6
+ 功能:
7
+ 1. 多模型对比测试
8
+ 2. 优化提示词设计(便于评估)
9
+ 3. 自动评分对比
10
+ """
11
+
12
+ from __future__ import annotations
13
+ import json
14
+ import random
15
+ from pathlib import Path
16
+ from typing import Dict, Any, List, Optional, Tuple
17
+ import requests
18
+ import sys
19
+ from tqdm import tqdm
20
+ from datetime import datetime
21
+
22
+ # ========= NIM API 配置 =========
23
+ NIM_API_KEY = "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"
24
+ NIM_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions"
25
+
26
+ # ========= NIM 可用最强模型 (按类别分组) =========
27
+ NIM_MODELS = {
28
+ # === 超大模型 (最强综合能力) ===
29
+ "mistral-large-3-675b": "mistralai/mistral-large-3-675b-instruct-2512",
30
+ "deepseek-v3.2": "deepseek-ai/deepseek-v3.2",
31
+ "llama-3.1-405b": "meta/llama-3.1-405b-instruct",
32
+ "nemotron-ultra-253b": "nvidia/llama-3.1-nemotron-ultra-253b-v1",
33
+
34
+ # === 推理模型 (思维链) ===
35
+ "deepseek-r1": "deepseek-ai/deepseek-r1",
36
+ "kimi-k2-thinking": "moonshotai/kimi-k2-thinking",
37
+
38
+ # === 最新一代 (Llama 4 / Qwen 3) ===
39
+ "llama-4-maverick": "meta/llama-4-maverick-17b-128e-instruct",
40
+ "llama-4-scout": "meta/llama-4-scout-17b-16e-instruct",
41
+ "qwen3-coder-480b": "qwen/qwen3-coder-480b-a35b-instruct",
42
+ "qwen3-next-80b": "qwen/qwen3-next-80b-a3b-instruct",
43
+
44
+ # === 高性价比 (70B 级别) ===
45
+ "llama-3.3-70b": "meta/llama-3.3-70b-instruct",
46
+ "mistral-large-2": "mistralai/mistral-large-2-instruct",
47
+ "kimi-k2": "moonshotai/kimi-k2-instruct-0905",
48
+
49
+ # === Google 开源 ===
50
+ "gemma-3-27b": "google/gemma-3-27b-it",
51
+
52
+ # === OpenAI 开源复刻 ===
53
+ "gpt-oss-120b": "openai/gpt-oss-120b",
54
+
55
+ # === 中文特化 ===
56
+ "chatglm3-6b": "thudm/chatglm3-6b",
57
+ "baichuan2-13b": "baichuan-inc/baichuan2-13b-chat",
58
+
59
+ # === 多模态视觉 ===
60
+ "llama-3.2-90b-vision": "meta/llama-3.2-90b-vision-instruct",
61
+ "phi-4-multimodal": "microsoft/phi-4-multimodal-instruct",
62
+ }
63
+
64
+ # 模型分类
65
+ MODEL_CATEGORIES = {
66
+ "超大模型": ["mistral-large-3-675b", "deepseek-v3.2", "llama-3.1-405b", "nemotron-ultra-253b"],
67
+ "推理模型": ["deepseek-r1", "kimi-k2-thinking"],
68
+ "最新一代": ["llama-4-maverick", "llama-4-scout", "qwen3-coder-480b", "qwen3-next-80b"],
69
+ "高性价比": ["llama-3.3-70b", "mistral-large-2", "kimi-k2"],
70
+ "Google开源": ["gemma-3-27b"],
71
+ "GPT开源": ["gpt-oss-120b"],
72
+ "中文特化": ["chatglm3-6b", "baichuan2-13b"],
73
+ "多模态": ["llama-3.2-90b-vision", "phi-4-multimodal"],
74
+ }
75
+
76
+ # ========= 数据路径 =========
77
+ INPUT_INDEX = Path("/workspace/data/finmultitime_hf/finmultitime_kline_index.jsonl")
78
+ OUTPUT_DIR = Path("/workspace/data/finmultitime_hf")
79
+
80
+ random.seed(42)
81
+
82
+
83
+ def log(msg: str):
84
+ print(msg)
85
+ sys.stdout.flush()
86
+
87
+
88
+ # ========= 优化后的提示词设计 =========
89
+ # 设计原则:
90
+ # 1. 要求具体、可量化的分析
91
+ # 2. 结构化输出便于评估
92
+ # 3. 包含评分维度
93
+
94
+ SYSTEM_PROMPT_ZH = """你是一名资深金融量化分析师,擅长解读 K 线图和技术分析。
95
+
96
+ 分析要求:
97
+ 1. 基于 K 线形态、量价关系进行客观分析
98
+ 2. 使用专业但易懂的金融术语
99
+ 3. 结论需有明确依据,不可凭空臆测
100
+ 4. 严格按照指定格式输出
101
+
102
+ 评分标准(供参考):
103
+ - 趋势判断准确性:是否正确识别主趋势
104
+ - 形态识别能力:是否识别出关键 K 线形态
105
+ - 风险提示合理性:风险点是否切合实际
106
+ - 逻辑连贯性:分析是否前后一致
107
+ - 专业术语使用:是否正确使用金融术语"""
108
+
109
+ SYSTEM_PROMPT_EN = """You are a senior financial quantitative analyst specializing in K-line chart interpretation and technical analysis.
110
+
111
+ Analysis Requirements:
112
+ 1. Provide objective analysis based on candlestick patterns and volume-price relationships
113
+ 2. Use professional but understandable financial terminology
114
+ 3. Conclusions must be evidence-based, no speculation
115
+ 4. Strictly follow the specified output format
116
+
117
+ Evaluation Criteria (for reference):
118
+ - Trend Judgment Accuracy: Correctly identify the main trend
119
+ - Pattern Recognition: Identify key candlestick patterns
120
+ - Risk Assessment: Reasonable risk identification
121
+ - Logical Coherence: Consistent analysis throughout
122
+ - Professional Terminology: Correct use of financial terms"""
123
+
124
+
125
+ # ========= 优化后的任务模板 =========
126
+
127
+ def get_kline_reading_prompt_zh(stock_id: str, period: str) -> Tuple[str, str]:
128
+ """K 线阅读任务 - 中文版 (优化后)"""
129
+
130
+ user_text = f"""<image>
131
+ 这是股票 {stock_id} 在 {period} 期间的日 K 线图(包含价格和成交量)。
132
+
133
+ 请从以下 5 个维度进行专业分析:
134
+
135
+ 【1. 主趋势判断】
136
+ - 判断这段时间股价是:上涨趋势 / 下跌趋势 / 横盘震荡
137
+ - 给出判断依据(如:高点抬高、低点抬高 → 上涨趋势��
138
+
139
+ 【2. 关键形态识别】
140
+ - 识别 1-2 个最明显的 K 线形态(如:锤子线、十字星、吞没形态、三只乌鸦等)
141
+ - 说明该形态出现的位置(前段/中段/末段)和技术含义
142
+
143
+ 【3. 量价关系分析】
144
+ - 描述成交量变化趋势(放量/缩量/量价背离)
145
+ - 分析量价配合情况对趋势的支撑或警示作用
146
+
147
+ 【4. 关键价位识别】
148
+ - 指出图中最重要的 1-2 个支撑位或阻力位区域
149
+ - 说明该价位的形成原因(如:多次回踩、密集成交区)
150
+
151
+ 【5. 交易策略建议】
152
+ - 基于以上分析,给出交易偏向:
153
+ A) 逢低布局(看多)
154
+ B) 逢高减仓(看空)
155
+ C) 观望等待(中性)
156
+ - 给出 1 句话理由
157
+
158
+ 注意:不要编造具体价格数值,只做定性分析。"""
159
+
160
+ nim_prompt = f"""请分析一张股票 {stock_id} 在 {period} 的日 K 线图。
161
+
162
+ 要求严格按以下格式输出(每点 1-2 句话,总计 8-12 句):
163
+
164
+ 【1. 主趋势判断】
165
+ 趋势方向 + 判断依据
166
+
167
+ 【2. 关键形态识别】
168
+ 形态名称 + 出现位置 + 技术含义
169
+
170
+ 【3. 量价关系分析】
171
+ 量能变化 + 量价配合评价
172
+
173
+ 【4. 关键价位识别】
174
+ 支撑/阻力位 + 形成原因
175
+
176
+ 【5. 交易策略建议】
177
+ 交易偏向(A/B/C) + 理由
178
+
179
+ 注意:基于典型走势特征进行分析,不编造具体数值。"""
180
+
181
+ return user_text, nim_prompt
182
+
183
+
184
+ def get_kline_reading_prompt_en(stock_id: str, period: str) -> Tuple[str, str]:
185
+ """K 线阅读任务 - 英文版 (优化后)"""
186
+
187
+ user_text = f"""<image>
188
+ This is the daily K-line chart (with price and volume) for stock {stock_id} during {period}.
189
+
190
+ Please provide professional analysis from these 5 dimensions:
191
+
192
+ 【1. Main Trend Judgment】
193
+ - Determine if the price is in: Uptrend / Downtrend / Sideways
194
+ - Provide evidence (e.g., higher highs and higher lows → uptrend)
195
+
196
+ 【2. Key Pattern Recognition】
197
+ - Identify 1-2 most prominent candlestick patterns (e.g., hammer, doji, engulfing, three black crows)
198
+ - State the pattern's location (early/mid/late period) and technical significance
199
+
200
+ 【3. Volume-Price Analysis】
201
+ - Describe volume trend (increasing/decreasing/divergence)
202
+ - Analyze how volume confirms or warns against the price trend
203
+
204
+ 【4. Key Price Levels】
205
+ - Identify 1-2 most important support or resistance zones
206
+ - Explain how these levels were formed (e.g., multiple bounces, high-volume area)
207
+
208
+ 【5. Trading Strategy Suggestion】
209
+ - Based on the above analysis, suggest trading bias:
210
+ A) Buy on dips (Bullish)
211
+ B) Sell on rallies (Bearish)
212
+ C) Wait and observe (Neutral)
213
+ - Give one sentence of reasoning
214
+
215
+ Note: Do not fabricate specific price values, only qualitative analysis."""
216
+
217
+ nim_prompt = f"""Analyze a daily K-line chart for stock {stock_id} during {period}.
218
+
219
+ Output strictly in this format (1-2 sentences per point, 8-12 sentences total):
220
+
221
+ 【1. Main Trend Judgment】
222
+ Trend direction + evidence
223
+
224
+ 【2. Key Pattern Recognition】
225
+ Pattern name + location + significance
226
+
227
+ 【3. Volume-Price Analysis】
228
+ Volume trend + volume-price assessment
229
+
230
+ 【4. Key Price Levels】
231
+ Support/resistance + formation reason
232
+
233
+ 【5. Trading Strategy Suggestion】
234
+ Trading bias (A/B/C) + reasoning
235
+
236
+ Note: Analyze based on typical chart characteristics, don't fabricate specific values."""
237
+
238
+ return user_text, nim_prompt
239
+
240
+
241
+ def get_kline_trend_prompt_zh(stock_id: str, period: str) -> Tuple[str, str]:
242
+ """K 线趋势分析任务 - 中文版 (优化后)"""
243
+
244
+ user_text = f"""<image>
245
+ 这是股票 {stock_id} 在 {period} 期间的日 K 线图和收盘价时间序列。
246
+
247
+ 请进行综合技术分析,从以下 5 个维度输出:
248
+
249
+ 【1. 趋势阶段划分】
250
+ - 将该时段划分为 2-3 个明显阶段(如:初期上涨 → 中期震荡 → 末期回落)
251
+ - 每个阶段用一句话描述特征
252
+
253
+ 【2. 波动特征分析】
254
+ - 描述价格波动的幅度和频率(剧烈波动/温和波动/窄幅整理)
255
+ - 识别最大的单日涨跌发生在哪个阶段
256
+
257
+ 【3. 趋势强度评估】
258
+ - 使用 1-5 分评估趋势强度(1=极弱,5=极强)
259
+ - 说明评分依据(如:坡度、回调深度、持续时间)
260
+
261
+ 【4. 转折点识别】
262
+ - 指出 1-2 个最重要的趋势转折点
263
+ - 分析转折的技术信号(如:放量长上影、跌破均线)
264
+
265
+ 【5. 未来走势预判】
266
+ - 基于当前形态,判断短期(5-10 个交易日)可能走势:
267
+ A) 延续当前方向
268
+ B) 出现反转
269
+ C) 进入盘整
270
+ - 给出概率评估(高/中/低)和核心理由
271
+
272
+ 注意:只基于走势形态分析,不考虑基本面。"""
273
+
274
+ nim_prompt = f"""请综合分析股票 {stock_id} 在 {period} 的 K 线走势。
275
+
276
+ 严格按以下格式输出(每点 1-2 句话,总计 10-15 句):
277
+
278
+ 【1. 趋势阶段划分】
279
+ 2-3 个阶段划分 + 各阶段特征
280
+
281
+ 【2. 波动特征分析】
282
+ 波动描述 + 最大涨跌出现位置
283
+
284
+ 【3. 趋势强度评估】
285
+ 评分(1-5) + 评分依据
286
+
287
+ 【4. 转折点识别】
288
+ 转折点位置 + 技术信号
289
+
290
+ 【5. ���来走势预判】
291
+ 预判方向(A/B/C) + 概率(高/中/低) + 核心理由
292
+
293
+ 注意:基于典型走势规律分析,不编造数值。"""
294
+
295
+ return user_text, nim_prompt
296
+
297
+
298
+ def get_kline_trend_prompt_en(stock_id: str, period: str) -> Tuple[str, str]:
299
+ """K 线趋势分析任务 - 英文版 (优化后)"""
300
+
301
+ user_text = f"""<image>
302
+ This is the daily K-line chart and closing price time series for stock {stock_id} during {period}.
303
+
304
+ Please provide comprehensive technical analysis from these 5 dimensions:
305
+
306
+ 【1. Trend Phase Division】
307
+ - Divide the period into 2-3 distinct phases (e.g., initial rise → mid consolidation → late decline)
308
+ - Describe each phase in one sentence
309
+
310
+ 【2. Volatility Analysis】
311
+ - Describe price volatility magnitude and frequency (high/moderate/narrow range)
312
+ - Identify which phase had the largest single-day move
313
+
314
+ 【3. Trend Strength Assessment】
315
+ - Rate trend strength from 1-5 (1=very weak, 5=very strong)
316
+ - Explain the rating basis (e.g., slope, pullback depth, duration)
317
+
318
+ 【4. Turning Point Identification】
319
+ - Identify 1-2 most important trend reversal points
320
+ - Analyze the technical signals at these points (e.g., volume spike with long upper shadow)
321
+
322
+ 【5. Future Outlook】
323
+ - Based on current pattern, predict short-term (5-10 trading days) direction:
324
+ A) Continue current trend
325
+ B) Reversal expected
326
+ C) Enter consolidation
327
+ - Provide probability assessment (High/Medium/Low) and key reasoning
328
+
329
+ Note: Analysis based on chart patterns only, no fundamentals."""
330
+
331
+ nim_prompt = f"""Provide comprehensive analysis for stock {stock_id} during {period}.
332
+
333
+ Output strictly in this format (1-2 sentences per point, 10-15 sentences total):
334
+
335
+ 【1. Trend Phase Division】
336
+ 2-3 phases + characteristics of each
337
+
338
+ 【2. Volatility Analysis】
339
+ Volatility description + location of largest move
340
+
341
+ 【3. Trend Strength Assessment】
342
+ Score (1-5) + basis for rating
343
+
344
+ 【4. Turning Point Identification】
345
+ Turning points + technical signals
346
+
347
+ 【5. Future Outlook】
348
+ Direction (A/B/C) + Probability (High/Medium/Low) + key reasoning
349
+
350
+ Note: Analyze based on typical pattern rules, don't fabricate values."""
351
+
352
+ return user_text, nim_prompt
353
+
354
+
355
+ # ========= NIM API 调用 =========
356
+ def call_nim(prompt: str, system_prompt: str, model_key: str) -> str:
357
+ """调用 NIM API"""
358
+ model_name = NIM_MODELS.get(model_key, model_key)
359
+
360
+ headers = {
361
+ "Authorization": f"Bearer {NIM_API_KEY}",
362
+ "Content-Type": "application/json",
363
+ }
364
+ payload = {
365
+ "model": model_name,
366
+ "messages": [
367
+ {"role": "system", "content": system_prompt},
368
+ {"role": "user", "content": prompt},
369
+ ],
370
+ "temperature": 0.3, # 降低温度提高一致性
371
+ "max_tokens": 1500, # 增加 token 以支持更长回答
372
+ }
373
+
374
+ try:
375
+ resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=180)
376
+ resp.raise_for_status()
377
+ data = resp.json()
378
+ content = data["choices"][0]["message"]["content"]
379
+ if content:
380
+ return content.strip()
381
+ return ""
382
+ except Exception as e:
383
+ log(f"[NIM:{model_key}] Error: {e}")
384
+ raise
385
+
386
+
387
+ def file_exists_any(paths: List[str]) -> List[str]:
388
+ return [p for p in paths if Path(p).is_file()]
389
+
390
+
391
+ def parse_period(image_name: str, market: str) -> str:
392
+ """从图片名解析时间段"""
393
+ # 000001.SZ_2020_H1_candlestick.png
394
+ parts = image_name.replace("_candlestick.png", "").split("_")
395
+ if len(parts) >= 3:
396
+ year = parts[-2]
397
+ half = parts[-1]
398
+ if market == "HS300":
399
+ return f"{year}年{'上半年' if half == 'H1' else '下半年'}"
400
+ else:
401
+ return f"{year} {'H1' if half == 'H1' else 'H2'}"
402
+ return "某时间段"
403
+
404
+
405
+ # ========= 样本构建函数 =========
406
+ def build_kline_reading_sample(
407
+ model_key: str,
408
+ base_rec: Dict[str, Any],
409
+ image_path: str,
410
+ ) -> Dict[str, Any]:
411
+ """K 线阅读样本"""
412
+ stock_id = base_rec["stock_id"]
413
+ market = base_rec["market"]
414
+ period = parse_period(Path(image_path).name, market)
415
+
416
+ if market == "HS300":
417
+ user_text, nim_prompt = get_kline_reading_prompt_zh(stock_id, period)
418
+ system_prompt = SYSTEM_PROMPT_ZH
419
+ else:
420
+ user_text, nim_prompt = get_kline_reading_prompt_en(stock_id, period)
421
+ system_prompt = SYSTEM_PROMPT_EN
422
+
423
+ assistant = call_nim(nim_prompt, system_prompt, model_key)
424
+
425
+ return {
426
+ "id": None,
427
+ "image": Path(image_path).name,
428
+ "conversations": [
429
+ {"from": "human", "value": user_text},
430
+ {"from": "gpt", "value": assistant},
431
+ ],
432
+ "task_type": "kline_reading",
433
+ "difficulty": "medium",
434
+ "images": [image_path],
435
+ "model": model_key,
436
+ "market": market,
437
+ "stock_id": stock_id,
438
+ "period": period,
439
+ }
440
+
441
+
442
+ def build_kline_trend_sample(
443
+ model_key: str,
444
+ base_rec: Dict[str, Any],
445
+ image_path: str,
446
+ ts_path: str,
447
+ ) -> Dict[str, Any]:
448
+ """K 线趋势分析样本"""
449
+ stock_id = base_rec["stock_id"]
450
+ market = base_rec["market"]
451
+ period = parse_period(Path(image_path).name, market)
452
+
453
+ if market == "HS300":
454
+ user_text, nim_prompt = get_kline_trend_prompt_zh(stock_id, period)
455
+ system_prompt = SYSTEM_PROMPT_ZH
456
+ else:
457
+ user_text, nim_prompt = get_kline_trend_prompt_en(stock_id, period)
458
+ system_prompt = SYSTEM_PROMPT_EN
459
+
460
+ assistant = call_nim(nim_prompt, system_prompt, model_key)
461
+
462
+ return {
463
+ "id": None,
464
+ "image": Path(image_path).name,
465
+ "conversations": [
466
+ {"from": "human", "value": user_text},
467
+ {"from": "gpt", "value": assistant},
468
+ ],
469
+ "task_type": "kline_trend",
470
+ "difficulty": "hard",
471
+ "images": [image_path],
472
+ "timeseries_files": [ts_path],
473
+ "model": model_key,
474
+ "market": market,
475
+ "stock_id": stock_id,
476
+ "period": period,
477
+ }
478
+
479
+
480
+ # ========= 数据集生成 =========
481
+ def generate_dataset(
482
+ model_key: str,
483
+ max_samples: Optional[int] = None,
484
+ output_suffix: str = "",
485
+ ) -> Tuple[str, List[Dict]]:
486
+ """使用指定模型生成数据集"""
487
+
488
+ model_name_safe = model_key.replace("/", "_").replace(".", "_").replace("-", "_")
489
+ suffix = f"_{output_suffix}" if output_suffix else ""
490
+ output_path = OUTPUT_DIR / f"finmultitime_kline_llavaplus_{model_name_safe}{suffix}.json"
491
+ output_path.parent.mkdir(parents=True, exist_ok=True)
492
+
493
+ records: List[Dict[str, Any]] = []
494
+ with INPUT_INDEX.open("r", encoding="utf-8") as fin:
495
+ for line in fin:
496
+ if not line.strip():
497
+ continue
498
+ records.append(json.loads(line))
499
+
500
+ log(f"\n{'='*60}")
501
+ log(f"[MAIN] Total records: {len(records)}")
502
+ log(f"[MAIN] Model: {model_key} -> {NIM_MODELS.get(model_key, model_key)}")
503
+ log(f"[MAIN] Max samples: {max_samples or 'ALL'}")
504
+ log(f"[MAIN] Output: {output_path}")
505
+ log(f"{'='*60}\n")
506
+
507
+ all_samples: List[Dict[str, Any]] = []
508
+ count = 0
509
+ errors = 0
510
+
511
+ for rec in tqdm(records, desc=f"{model_key}"):
512
+ images = file_exists_any(rec.get("image_files", []))
513
+ ts_files = file_exists_any(rec.get("time_series_files", []))
514
+ if not images:
515
+ continue
516
+
517
+ # 交替任务类型
518
+ if count % 2 == 0 and ts_files:
519
+ tpl = "kline_trend"
520
+ else:
521
+ tpl = "kline_reading"
522
+
523
+ try:
524
+ if tpl == "kline_trend":
525
+ sample = build_kline_trend_sample(
526
+ model_key, rec, random.choice(images), random.choice(ts_files)
527
+ )
528
+ else:
529
+ sample = build_kline_reading_sample(
530
+ model_key, rec, random.choice(images)
531
+ )
532
+ except Exception as e:
533
+ log(f"[WARN] {rec['stock_id']}: {e}")
534
+ errors += 1
535
+ if errors > 20:
536
+ log(f"[ERROR] Too many errors ({errors}), stopping...")
537
+ break
538
+ continue
539
+
540
+ sample["id"] = f"{rec['market']}_{rec['stock_id']}_{tpl}_{count}"
541
+ all_samples.append(sample)
542
+ count += 1
543
+
544
+ if max_samples and count >= max_samples:
545
+ break
546
+
547
+ with output_path.open("w", encoding="utf-8") as f:
548
+ json.dump(all_samples, f, ensure_ascii=False, indent=2)
549
+
550
+ log(f"\n[OK] Generated {count} samples -> {output_path}")
551
+ return str(output_path), all_samples
552
+
553
+
554
+ def compare_models(sample_count: int = 100) -> Dict[str, Any]:
555
+ """对比所有模型,生成各 100 个样本"""
556
+
557
+ results = {}
558
+
559
+ # 测试每个类别的所有模型
560
+ all_models = []
561
+ for category, models in MODEL_CATEGORIES.items():
562
+ for model in models:
563
+ all_models.append((category, model))
564
+
565
+ log(f"\n{'='*70}")
566
+ log(f"开始多模型对比测试")
567
+ log(f"每个模型生成 {sample_count} 个样本")
568
+ log(f"共测试 {len(all_models)} 个模型")
569
+ log(f"{'='*70}\n")
570
+
571
+ for category, model_key in all_models:
572
+ log(f"\n[{category}] {model_key}")
573
+ try:
574
+ output_path, samples = generate_dataset(
575
+ model_key,
576
+ max_samples=sample_count,
577
+ output_suffix="compare"
578
+ )
579
+
580
+ # 统计
581
+ total_chars = sum(len(s["conversations"][1]["value"]) for s in samples)
582
+ avg_chars = total_chars / len(samples) if samples else 0
583
+
584
+ results[model_key] = {
585
+ "category": category,
586
+ "sample_count": len(samples),
587
+ "avg_response_chars": avg_chars,
588
+ "output_path": output_path,
589
+ "status": "success",
590
+ }
591
+ except Exception as e:
592
+ log(f"[ERROR] {model_key}: {e}")
593
+ results[model_key] = {
594
+ "category": category,
595
+ "status": "failed",
596
+ "error": str(e),
597
+ }
598
+
599
+ # 保存对比结果
600
+ compare_result_path = OUTPUT_DIR / "model_comparison_results.json"
601
+ with compare_result_path.open("w", encoding="utf-8") as f:
602
+ json.dump(results, f, ensure_ascii=False, indent=2)
603
+
604
+ log(f"\n[OK] Comparison results saved to {compare_result_path}")
605
+ return results
606
+
607
+
608
+ def print_comparison_report(results: Dict[str, Any]):
609
+ """打印对比报告"""
610
+ print("\n" + "=" * 70)
611
+ print("模型对比报告")
612
+ print("=" * 70)
613
+
614
+ # 按类别分组
615
+ by_category = {}
616
+ for model, data in results.items():
617
+ cat = data.get("category", "未知")
618
+ if cat not in by_category:
619
+ by_category[cat] = []
620
+ by_category[cat].append((model, data))
621
+
622
+ for category, models in by_category.items():
623
+ print(f"\n[{category}]")
624
+ print("-" * 50)
625
+ for model, data in models:
626
+ if data.get("status") == "success":
627
+ avg_chars = data.get("avg_response_chars", 0)
628
+ count = data.get("sample_count", 0)
629
+ print(f" ✅ {model:30s} | 样本:{count:3d} | 平均长度:{avg_chars:.0f}字")
630
+ else:
631
+ print(f" ❌ {model:30s} | 失败: {data.get('error', '未知错误')[:30]}")
632
+
633
+ print("\n" + "=" * 70)
634
+
635
+
636
+ def list_models():
637
+ """列出所有可用模型"""
638
+ print("\n" + "=" * 70)
639
+ print("NIM 可用模型列表")
640
+ print("=" * 70)
641
+
642
+ for category, models in MODEL_CATEGORIES.items():
643
+ print(f"\n[{category}]")
644
+ for key in models:
645
+ full_name = NIM_MODELS.get(key, key)
646
+ print(f" {key:30s} -> {full_name}")
647
+
648
+ print("\n" + "=" * 70)
649
+
650
+
651
+ def select_top_models(results: Dict[str, Any], top_n: int = 4) -> List[str]:
652
+ """从对比结果中选出每个类别最强的模型,总共 top_n 个"""
653
+ # 按类别分组
654
+ by_category = {}
655
+ for model, data in results.items():
656
+ if data.get("status") != "success":
657
+ continue
658
+ cat = data.get("category", "未知")
659
+ if cat not in by_category:
660
+ by_category[cat] = []
661
+ by_category[cat].append((model, data))
662
+
663
+ # 每个类别选最强的
664
+ top_models = []
665
+ for category, models in by_category.items():
666
+ if not models:
667
+ continue
668
+ # 按回答长度排序(越长通常质量越好)
669
+ models.sort(key=lambda x: x[1].get("avg_response_chars", 0), reverse=True)
670
+ best_model, best_data = models[0]
671
+ top_models.append({
672
+ "model": best_model,
673
+ "category": category,
674
+ "avg_chars": best_data.get("avg_response_chars", 0),
675
+ "sample_count": best_data.get("sample_count", 0),
676
+ })
677
+ log(f" [{category}] 最强: {best_model} (平均 {best_data.get('avg_response_chars', 0):.0f} 字)")
678
+
679
+ # 按平均字数排序,取 TOP N
680
+ top_models.sort(key=lambda x: x["avg_chars"], reverse=True)
681
+ return [m["model"] for m in top_models[:top_n]]
682
+
683
+
684
+ def auto_full_pipeline(compare_samples: int = 100, top_n: int = 4):
685
+ """自动完成全流程:对比 -> 选模型 -> 全量生成"""
686
+
687
+ log("\n" + "=" * 70)
688
+ log("🚀 自动全流程启动")
689
+ log(f" 阶段1: 每个模型生成 {compare_samples} 样本进行对比")
690
+ log(f" 阶段2: 选出 TOP {top_n} 模型")
691
+ log(f" 阶段3: 用 TOP 模型生成全量数据")
692
+ log("=" * 70)
693
+
694
+ # 阶段 1: 对比测试
695
+ log("\n" + "=" * 70)
696
+ log("[阶段 1/3] 多模型对比测试")
697
+ log("=" * 70)
698
+ results = compare_models(compare_samples)
699
+ print_comparison_report(results)
700
+
701
+ # 阶段 2: 选出最强模型
702
+ log("\n" + "=" * 70)
703
+ log("[阶段 2/3] 选出每类最强模型")
704
+ log("=" * 70)
705
+ top_models = select_top_models(results, top_n)
706
+
707
+ if not top_models:
708
+ log("[ERROR] 没有成功的模型,无法继续")
709
+ return
710
+
711
+ log(f"\n最终选出 {len(top_models)} 个模型:")
712
+ for i, model in enumerate(top_models, 1):
713
+ log(f" {i}. {model}")
714
+
715
+ # 阶段 3: 全量生成
716
+ log("\n" + "=" * 70)
717
+ log("[阶段 3/3] 使用 TOP 模型生成全量数据")
718
+ log("=" * 70)
719
+
720
+ for i, model in enumerate(top_models, 1):
721
+ log(f"\n[{i}/{len(top_models)}] 生成全量: {model}")
722
+ try:
723
+ output_path, samples = generate_dataset(model, max_samples=None)
724
+ log(f" ✅ 完成! {len(samples)} 样本 -> {output_path}")
725
+ except Exception as e:
726
+ log(f" ❌ 失败: {e}")
727
+
728
+ # 完成
729
+ log("\n" + "=" * 70)
730
+ log("🎉 全部任务完成!")
731
+ log("=" * 70)
732
+ log(f"对比结果: {OUTPUT_DIR / 'model_comparison_results.json'}")
733
+ log(f"数据目录: {OUTPUT_DIR}")
734
+
735
+
736
+ def main():
737
+ """主函数"""
738
+ import argparse
739
+
740
+ parser = argparse.ArgumentParser(description="NIM 多模型 K 线图数据生成 (LLaVA 格式)")
741
+ parser.add_argument("--model", "-m", type=str, default=None,
742
+ help="指定单个模型生成")
743
+ parser.add_argument("--max-samples", "-n", type=int, default=None,
744
+ help="最大样本数")
745
+ parser.add_argument("--list", "-l", action="store_true",
746
+ help="列出所有模型")
747
+ parser.add_argument("--compare", "-c", type=int, default=None,
748
+ metavar="N", help="对比所有模型,每个生成 N 个样本")
749
+ parser.add_argument("--auto", action="store_true",
750
+ help="自动全流程:对比(100样本) -> 选TOP4 -> 全量生成")
751
+ parser.add_argument("--top-n", type=int, default=4,
752
+ help="选出多少个最强模型 (默认: 4)")
753
+
754
+ args = parser.parse_args()
755
+
756
+ if args.list:
757
+ list_models()
758
+ return
759
+
760
+ if args.auto:
761
+ compare_n = args.compare if args.compare else 100
762
+ auto_full_pipeline(compare_samples=compare_n, top_n=args.top_n)
763
+ return
764
+
765
+ if args.compare:
766
+ results = compare_models(args.compare)
767
+ print_comparison_report(results)
768
+ return
769
+
770
+ if args.model:
771
+ generate_dataset(args.model, args.max_samples)
772
+ return
773
+
774
+ # 默认:显示帮助
775
+ parser.print_help()
776
+
777
+
778
+ if __name__ == "__main__":
779
+ main()
fin-mm/code/LLaVA-Plus/.devcontainer/Dockerfile ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM mcr.microsoft.com/devcontainers/base:ubuntu-20.04
2
+
3
+ SHELL [ "bash", "-c" ]
4
+
5
+ # update apt and install packages
6
+ RUN apt update && \
7
+ apt install -yq \
8
+ ffmpeg \
9
+ dkms \
10
+ build-essential
11
+
12
+ # add user tools
13
+ RUN sudo apt install -yq \
14
+ jq \
15
+ jp \
16
+ tree \
17
+ tldr
18
+
19
+ # add git-lfs and install
20
+ RUN curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash && \
21
+ sudo apt-get install -yq git-lfs && \
22
+ git lfs install
23
+
24
+ ############################################
25
+ # Setup user
26
+ ############################################
27
+
28
+ USER vscode
29
+
30
+ # install azcopy, a tool to copy to/from blob storage
31
+ # for more info: https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-blobs-upload#upload-a-file
32
+ RUN cd /tmp && \
33
+ wget https://azcopyvnext.azureedge.net/release20230123/azcopy_linux_amd64_10.17.0.tar.gz && \
34
+ tar xvf azcopy_linux_amd64_10.17.0.tar.gz && \
35
+ mkdir -p ~/.local/bin && \
36
+ mv azcopy_linux_amd64_10.17.0/azcopy ~/.local/bin && \
37
+ chmod +x ~/.local/bin/azcopy && \
38
+ rm -rf azcopy_linux_amd64*
39
+
40
+ # Setup conda
41
+ RUN cd /tmp && \
42
+ wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && \
43
+ bash ./Miniconda3-latest-Linux-x86_64.sh -b && \
44
+ rm ./Miniconda3-latest-Linux-x86_64.sh
45
+
46
+ # Install dotnet
47
+ RUN cd /tmp && \
48
+ wget https://dot.net/v1/dotnet-install.sh && \
49
+ chmod +x dotnet-install.sh && \
50
+ ./dotnet-install.sh --channel 7.0 && \
51
+ ./dotnet-install.sh --channel 3.1 && \
52
+ rm ./dotnet-install.sh
53
+
fin-mm/code/LLaVA-Plus/.devcontainer/devcontainer.env ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ SAMPLE_ENV_VAR1="Sample Value"
2
+ SAMPLE_ENV_VAR2=332431bf-68bf
fin-mm/code/LLaVA-Plus/.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "LLaVA",
3
+ "build": {
4
+ "dockerfile": "Dockerfile",
5
+ "context": "..",
6
+ "args": {}
7
+ },
8
+ "features": {
9
+ "ghcr.io/devcontainers/features/docker-in-docker:2": {},
10
+ "ghcr.io/devcontainers/features/azure-cli:1": {},
11
+ "ghcr.io/azure/azure-dev/azd:0": {},
12
+ "ghcr.io/devcontainers/features/powershell:1": {},
13
+ "ghcr.io/devcontainers/features/common-utils:2": {},
14
+ "ghcr.io/devcontainers-contrib/features/zsh-plugins:0": {},
15
+ },
16
+ // "forwardPorts": [],
17
+ "postCreateCommand": "bash ./.devcontainer/postCreateCommand.sh",
18
+ "customizations": {
19
+ "vscode": {
20
+ "settings": {
21
+ "python.analysis.autoImportCompletions": true,
22
+ "python.analysis.autoImportUserSymbols": true,
23
+ "python.defaultInterpreterPath": "~/miniconda3/envs/llava/bin/python",
24
+ "python.formatting.provider": "yapf",
25
+ "python.linting.enabled": true,
26
+ "python.linting.flake8Enabled": true,
27
+ "isort.check": true,
28
+ "dev.containers.copyGitConfig": true,
29
+ "terminal.integrated.defaultProfile.linux": "zsh",
30
+ "terminal.integrated.profiles.linux": {
31
+ "zsh": {
32
+ "path": "/usr/bin/zsh"
33
+ },
34
+ }
35
+ },
36
+ "extensions": [
37
+ "aaron-bond.better-comments",
38
+ "eamodio.gitlens",
39
+ "EditorConfig.EditorConfig",
40
+ "foxundermoon.shell-format",
41
+ "GitHub.copilot-chat",
42
+ "GitHub.copilot-labs",
43
+ "GitHub.copilot",
44
+ "lehoanganh298.json-lines-viewer",
45
+ "mhutchie.git-graph",
46
+ "ms-azuretools.vscode-docker",
47
+ "ms-dotnettools.dotnet-interactive-vscode",
48
+ "ms-python.flake8",
49
+ "ms-python.isort",
50
+ "ms-python.python",
51
+ "ms-python.vscode-pylance",
52
+ "njpwerner.autodocstring",
53
+ "redhat.vscode-yaml",
54
+ "stkb.rewrap",
55
+ "yzhang.markdown-all-in-one",
56
+ ]
57
+ }
58
+ },
59
+ "mounts": [],
60
+ "runArgs": [
61
+ "--gpus",
62
+ "all",
63
+ // "--ipc",
64
+ // "host",
65
+ "--ulimit",
66
+ "memlock=-1",
67
+ "--env-file",
68
+ ".devcontainer/devcontainer.env"
69
+ ],
70
+ // "remoteUser": "root"
71
+ }
fin-mm/code/LLaVA-Plus/.devcontainer/postCreateCommand.sh ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ git config --global safe.directory '*'
2
+ git config --global core.editor "code --wait"
3
+ git config --global pager.branch false
4
+
5
+ # Set AZCOPY concurrency to auto
6
+ echo "export AZCOPY_CONCURRENCY_VALUE=AUTO" >> ~/.zshrc
7
+ echo "export AZCOPY_CONCURRENCY_VALUE=AUTO" >> ~/.bashrc
8
+
9
+ # Activate conda by default
10
+ echo ". /home/vscode/miniconda3/bin/activate" >> ~/.zshrc
11
+ echo ". /home/vscode/miniconda3/bin/activate" >> ~/.bashrc
12
+
13
+ # Use llava environment by default
14
+ echo "conda activate llava" >> ~/.zshrc
15
+ echo "conda activate llava" >> ~/.bashrc
16
+
17
+ # Add dotnet to PATH
18
+ echo 'export PATH="$PATH:$HOME/.dotnet"' >> ~/.bashrc
19
+ echo 'export PATH="$PATH:$HOME/.dotnet"' >> ~/.zshrc
20
+
21
+ # Create and activate llava environment
22
+ source /home/vscode/miniconda3/bin/activate
23
+ conda create -y -q -n llava python=3.10
24
+ conda activate llava
25
+
26
+ # Install Nvidia Cuda Compiler
27
+ conda install -y -c nvidia cuda-compiler
28
+
29
+ pip install pre-commit==3.0.2
30
+
31
+ # Install package locally
32
+ pip install --upgrade pip # enable PEP 660 support
33
+ pip install -e .
34
+
35
+ # Install additional packages for training
36
+ pip install -e ".[train]"
37
+ pip install flash-attn --no-build-isolation
38
+
39
+ # Download checkpoints to location outside of the repo
40
+ git clone https://huggingface.co/liuhaotian/llava-v1.5-7b ~/llava-v1.5-7b
41
+
42
+ # Commented because it is unlikely for users to have enough local GPU memory to load the model
43
+ # git clone https://huggingface.co/liuhaotian/llava-v1.5-13b ~/llava-v1.5-13b
44
+
45
+ echo "postCreateCommand.sh COMPLETE!"
fin-mm/code/LLaVA-Plus/.dockerignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The .dockerignore file excludes files from the container build process.
2
+ #
3
+ # https://docs.docker.com/engine/reference/builder/#dockerignore-file
4
+
5
+ # Exclude Git files
6
+ .git
7
+ .github
8
+ .gitignore
9
+
10
+ # Exclude Python cache files
11
+ __pycache__
12
+ .mypy_cache
13
+ .pytest_cache
14
+ .ruff_cache
15
+
16
+ # Exclude Python virtual environment
17
+ /venv
18
+
19
+ # Exclude some weights
20
+ /openai
21
+ /liuhaotian
fin-mm/code/LLaVA-Plus/.editorconfig ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ # Unix-style newlines with a newline ending every file
4
+ [*]
5
+ end_of_line = lf
6
+ insert_final_newline = true
7
+ trim_trailing_whitespace = true
8
+ charset = utf-8
9
+
10
+ # 4 space indentation
11
+ [*.{py,json}]
12
+ indent_style = space
13
+ indent_size = 4
14
+
15
+ # 2 space indentation
16
+ [*.{md,sh,yaml,yml}]
17
+ indent_style = space
18
+ indent_size = 2
fin-mm/code/LLaVA-Plus/.gitattributes ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://git-scm.com/docs/gitattributes
2
+
3
+ # Set the default behavior, in case people don't have core.autocrlf set.
4
+ # https://git-scm.com/docs/gitattributes#_end_of_line_conversion
5
+ * text=auto
6
+
7
+ # common python attributes, taken from https://github.com/alexkaratarakis/gitattributes/blob/710900479a2bedeec7003d381719521ffbb18bf8/Python.gitattributes
8
+ # Source files
9
+ # ============
10
+ *.pxd text diff=python
11
+ *.py text diff=python
12
+ *.py3 text diff=python
13
+ *.pyw text diff=python
14
+ *.pyx text diff=python
15
+ *.pyz text diff=python
16
+ *.pyi text diff=python
17
+
18
+ # Binary files
19
+ # ============
20
+ *.db binary
21
+ *.p binary
22
+ *.pkl binary
23
+ *.pickle binary
24
+ *.pyc binary export-ignore
25
+ *.pyo binary export-ignore
26
+ *.pyd binary
27
+
28
+ # Jupyter notebook
29
+ *.ipynb text eol=lf
fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/1-usage.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Usage issues
2
+ description: Report issues in usage.
3
+ title: "[Usage] "
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ Thanks for taking the time to fill out this form. Please give as detailed description as possible for us to better assist with the issue :)
9
+ - type: textarea
10
+ id: what-happened
11
+ attributes:
12
+ label: Describe the issue
13
+ description: Please give as detailed description as possible for us to better assist with the issue. Please paste the **FULL** error log here, so that we can better understand the issue. Wrap the log with ``` for better readability in GitHub.
14
+ placeholder: Issue
15
+ value: |
16
+ Issue:
17
+
18
+ Command:
19
+ ```
20
+ PASTE THE COMMANDS HERE.
21
+ ```
22
+
23
+ Log:
24
+ ```
25
+ PASTE THE LOGS HERE.
26
+ ```
27
+
28
+ Screenshots:
29
+ You may attach screenshots if it better explains the issue.
30
+ validations:
31
+ required: true
fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/2-feature-request.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Feature Request
2
+ description: Request for a new feature
3
+ title: "[Feature request] "
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ Thanks for your interest in our work. Please share your thoughts of the new features below.
9
+ - type: textarea
10
+ id: feature
11
+ attributes:
12
+ label: feature
13
+ placeholder: Start your thoughts here...
fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/3-question.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Questions
2
+ description: General questions about the work
3
+ title: "[Question] "
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ Thanks for your interest in our work. For this type of question, it may be more suitable to go to [discussion](https://github.com/haotian-liu/LLaVA/discussions) sections. If you believe an issue would be better for your request, please continue your post below :)
9
+ - type: textarea
10
+ id: question
11
+ attributes:
12
+ label: Question
13
+ placeholder: Start question here...
fin-mm/code/LLaVA-Plus/.github/ISSUE_TEMPLATE/4-discussion.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Discussions
2
+ description: General discussions about the work
3
+ title: "[Discussion] "
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ Thanks for your interest in our work. For this type of question, it may be more suitable to go to [discussion](https://github.com/haotian-liu/LLaVA/discussions) sections. If you believe an issue would be better for your request, please continue your post below :)
9
+ - type: textarea
10
+ id: discussion
11
+ attributes:
12
+ label: Discussion
13
+ placeholder: Start discussion here...
fin-mm/code/LLaVA-Plus/.gitignore ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__
3
+ *.pyc
4
+ *.egg-info
5
+ dist
6
+
7
+ # Log
8
+ *.log
9
+ *.log.*
10
+ *.json
11
+ *.jsonl
12
+
13
+ # Data
14
+ !**/alpaca-data-conversation.json
15
+
16
+ # Editor
17
+ .idea
18
+ *.swp
19
+
20
+ # Other
21
+ .DS_Store
22
+ wandb
23
+ output
24
+
25
+ checkpoints
26
+ ckpts*
27
+
28
+ .ipynb_checkpoints
29
+ *.ipynb
30
+
31
+ # DevContainer
32
+ !.devcontainer/*
33
+
34
+ # Demo
35
+ serve_images/
fin-mm/code/LLaVA-Plus/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
fin-mm/code/LLaVA-Plus/README.md ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🌋 LLaVA-Plus: Large Language and Vision Assistants that Plug and Learn to Use Skills
2
+
3
+
4
+ **Learning to Use Tools For Creating Multimodal Agents.**
5
+
6
+ [[Project Page](https://llava-vl.github.io/llava-plus)] [[Arxiv](https://arxiv.org/abs/2311.05437)] [[Demo](https://llavaplus.ngrok.io/)] [[Data](https://huggingface.co/datasets/LLaVA-VL/llava-plus-data)] [[Model Zoo](https://github.com/LLaVA-VL/LLaVA-Plus-Codebase/blob/main/docs/llava-plus/modelzoo.md)]
7
+
8
+ **Note: Some sections of the code are currently being prepared and updated. Please stay tuned.**
9
+
10
+
11
+ ## Release
12
+ - [11/11] 🔥 We released **LLaVA-Plus: Large Language and Vision Assistants that Plug and Learn to Use Skills**. Enable LMM to use tools for general vision tasks! Checkout the [paper]() and [demo](https://llavaplus.ngrok.io/).
13
+
14
+
15
+ [![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](https://github.com/tatsu-lab/stanford_alpaca/blob/main/LICENSE)
16
+ [![Data License](https://img.shields.io/badge/Data%20License-CC%20By%20NC%204.0-red.svg)](https://github.com/tatsu-lab/stanford_alpaca/blob/main/DATA_LICENSE)
17
+ **Usage and License Notices**: The data and checkpoint are intended and licensed for research use only. They are also restricted to uses that follow the license agreement of LLaVA, LLaMA, Vicuna, and GPT-4. The dataset is CC BY NC 4.0 (allowing only non-commercial use) and models trained using the dataset should not be used outside of research purposes.
18
+
19
+
20
+ ## Contents
21
+ - [Install](#install)
22
+ - [LLaVA-Plus Weights](#llava-plus-weights)
23
+ - [Demo](#demo)
24
+ - [Model Zoo](docs/llava-plus/modelzoo.md)
25
+ - [Dataset](docs/llava-plus/dataset.md)
26
+ - [Train](#train)
27
+ - [Evaluation](#evaluation)
28
+
29
+ ## Install
30
+
31
+ If you are not using Linux, do *NOT* proceed, see instructions for [macOS](https://github.com/haotian-liu/LLaVA/blob/main/docs/macOS.md) and [Windows](https://github.com/haotian-liu/LLaVA/blob/main/docs/Windows.md) from LLaVA.
32
+
33
+ 1. Clone this repository and navigate to the LLaVA-Plus folder
34
+ ```bash
35
+ git clone https://github.com/LLaVA-VL/LLaVA-Plus-Codebase LLaVA-Plus
36
+ cd LLaVA-Plus
37
+ ```
38
+
39
+ 2. Install Package
40
+ ```Shell
41
+ conda create -n llava python=3.10 -y
42
+ conda activate llava
43
+ pip install --upgrade pip # enable PEP 660 support
44
+ pip install -e .
45
+ ```
46
+
47
+ 3. Install additional packages for training cases
48
+ ```
49
+ pip install -e ".[train]"
50
+ pip install flash-attn --no-build-isolation
51
+ ```
52
+
53
+ ## LLaVA-Plus Weights
54
+
55
+ **We are still preparing the part. Stay tuned!**
56
+
57
+ Please check out our [Model Zoo](https://github.com/LLaVA-VL/LLaVA-Plus-Codebase/blob/main/docs/llava-plus/modelzoo.md) for all public LLaVA-Plus checkpoints, and the instructions on how to use the weights.
58
+
59
+ ## Demo
60
+
61
+ - [Demo: https://llavaplus.ngrok.io/](https://llavaplus.ngrok.io/)
62
+
63
+ ### Demo Architecture
64
+
65
+ ![llava-plus-arch](images/llava-plus-arch.png)
66
+
67
+
68
+ To run our demo, you have four steps.
69
+
70
+ 1. [Launch a controller](#1-Launch-a-controller): enable to control different works.
71
+ 2. [Launch a model worker](#2-Launch-a-model-worker): core llava-plus model.
72
+ 3. [Launch tool workers](#3-Launch-tool-workers): the tools you want to call.
73
+ 4. [Launch a gradio web server](#4-Launch-a-gradio-web-server): a front end page for users.
74
+
75
+ #### 1. Launch a controller
76
+ ```Shell
77
+ python -m llava.serve.controller --host 0.0.0.0 --port 20001
78
+ ```
79
+
80
+ #### 2. Launch a model worker
81
+
82
+ This is the actual *worker* that performs the inference on the GPU. Each worker is responsible for a single model specified in `--model-path`.
83
+
84
+ ```Shell
85
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:20001 --port 40000 --worker http://localhost:40000 --model-path <huggingface or local path>
86
+ ```
87
+
88
+ Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list.
89
+
90
+ If you are using an Apple device with an M1 or M2 chip, you can specify the mps device by using the `--device` flag: `--device mps`.
91
+
92
+ <details>
93
+ <summary>Multiple works</summary>
94
+ You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker.
95
+ ```Shell
96
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:20001 --port <different from 40000, say 40001> --worker http://localhost:<change accordingly, i.e. 40001> --model-path <ckpt2>
97
+ ```
98
+ </details>
99
+
100
+
101
+ <details>
102
+ <summary>Launch a model worker (Multiple GPUs, when GPU VRAM <= 24GB)</summary>
103
+
104
+ If the VRAM of your GPU is less than 24GB (e.g., RTX 3090, RTX 4090, etc.), you may try running it with multiple GPUs. Our latest code base will automatically try to use multiple GPUs if you have more than one GPU. You can specify which GPUs to use with `CUDA_VISIBLE_DEVICES`. Below is an example of running with the first two GPUs.
105
+
106
+ ```Shell
107
+ CUDA_VISIBLE_DEVICES=0,1 python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:20001 --port 40000 --worker http://localhost:40000 --model-path <huggingface or local path>
108
+ ```
109
+ </details>
110
+
111
+ #### 3. Launch tool workers
112
+ You need to open different tool works, as shown in the figure above, which means you need to prepare codes from other projects.
113
+
114
+ We provide a detailed [guideline](docs/llava-plus/tools.md) for different projects.
115
+
116
+
117
+ #### 4. Launch a gradio web server.
118
+ ```Shell
119
+ python -m llava.serve.gradio_web_server_llava_plus --controller http://localhost:20001 --model-list-mode reload
120
+ ```
121
+ You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen.
122
+
123
+
124
+
125
+ ## Train
126
+
127
+
128
+
129
+ LLaVA training consists of two stages: (1) feature alignment stage, and (2) visual instruction tuning stage.
130
+
131
+ Our llava-plus is trained from the llava-stage-1-pre-trained projectors.
132
+
133
+ <details>
134
+ <summary>Training cost</summary>
135
+ LLaVA-Plus is trained on 4/8 A100 GPUs with 80GB memory. To train on fewer GPUs, you can reduce the `per_device_train_batch_size` and increase the `gradient_accumulation_steps` accordingly. Always keep the global batch size the same: `per_device_train_batch_size` x `gradient_accumulation_steps` x `num_gpus`.
136
+ </details>
137
+
138
+
139
+ <details>
140
+ <summary>Download Vicuna checkpoints (automatically)</summary>
141
+
142
+ Our base model Vicuna v1.5, which is an instruction-tuned chatbot, will be downloaded automatically when you run our provided training scripts. No action is needed.
143
+ </details>
144
+
145
+ ### Stage 1: Pretrain (feature alignment)
146
+
147
+ Download [pre-trained projector](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md#projector-weights) directly as we did.
148
+
149
+ Or you may train the projector following the [guideline in LLaVA](https://github.com/haotian-liu/LLaVA/tree/main#pretrain-feature-alignment).
150
+
151
+
152
+
153
+ ### Stage 2: Tool Augmented Visual Instruction Tuning
154
+
155
+ 1. Prepare data
156
+
157
+ Please download [the training data](https://huggingface.co/datasets/LLaVA-VL/llava-plus-data), and download the images from constituting datasets:
158
+
159
+ - COCO: [train2017](http://images.cocodataset.org/zips/train2017.zip)
160
+ - VisualGenome: [part1](https://cs.stanford.edu/people/rak248/VG_100K_2/images.zip), [part2](https://cs.stanford.edu/people/rak248/VG_100K_2/images2.zip)
161
+ - [infoseek](https://open-vision-language.github.io/infoseek/)
162
+ - [hiertext](https://github.com/google-research-datasets/hiertext)
163
+
164
+ 2. Start training!
165
+
166
+ Training script with DeepSpeed ZeRO-2: [`training_llava_plus_v0_7b.sh`](scripts/llava_plus/training_llava_plus_v0_7b.sh) or [`training_llava_plus_v1.3_7b.sh`](scripts/llava_plus/training_llava_plus_v1.3_7b.sh)
167
+
168
+
169
+
170
+ <details>
171
+ <summary>If you do not have enough GPU memory:</summary>
172
+ - Use LoRA. See LLaVA repo for more details.
173
+ - Replace `zero2.json` with `zero3.json` or `zero3_offload.json`.
174
+ </details>
175
+
176
+ <details>
177
+ <summary>If you are interested in finetuning LLaVA(LLaVA-Plus) model to your own task/data:</summary>
178
+ please check out [`Finetune_Custom_Data.md`](https://github.com/haotian-liu/LLaVA/blob/main/docs/Finetune_Custom_Data.md)。
179
+ </details>
180
+ <details>
181
+ <summary>Some explainations of options:</summary>
182
+
183
+ - `--data_path path/to/llava-150k-tool-aug.json,path/to/llava-plus-v1-117k-tool-merge.json`: You may pass multiple data files with `,` separated.
184
+ - `--image_folder /path/to/coco/train2017/,/path/to/hiertext/train,/path/to/infoseek/infoseek_images,/path/to/instruct-pix2pix/clip-filtered-dataset,/path/to/goldg/vg_mdetr/images`: You may pass multiple image folders with `,` separated. Note that it may cause problems if multiple folders have images with the same name.
185
+ - `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
186
+ - `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
187
+ - `--image_aspect_ratio pad`: this pads the non-square images to square, instead of cropping them; it slightly reduces hallucination.
188
+ - `--group_by_modality_length True`: this should only be used when your instruction tuning dataset contains both language (e.g. ShareGPT) and multimodal (e.g. LLaVA-Instruct). It makes the training sampler only sample a single modality (either image or language) during training, which we observe to speed up training by ~25%, and does not affect the final outcome.
189
+ </details>
190
+
191
+ ## Evaluation
192
+
193
+ See [LLaVA's Instruction](https://github.com/haotian-liu/LLaVA/tree/main#evaluation) on model evaluations.
194
+
195
+ ## Citation
196
+
197
+ If you find LLaVA useful for your research and applications, please cite using this BibTeX:
198
+ ```bibtex
199
+
200
+ @article{liu2023llavaplus,
201
+ title={LLaVA-Plus: Learning to Use Tools for Creating Multimodal Agents},
202
+ author={Liu, Shilong and Cheng, Hao and Liu, Haotian and Zhang, Hao and Li, Feng and Ren, Tianhe and Zou, Xueyan and Yang, Jianwei and Su, Hang and Zhu, Jun and Zhang, Lei and Gao, Jianfeng and Li, Chunyuan},
203
+ journal={arXiv:2311.05437},
204
+ year={2023}
205
+ }
206
+
207
+ @misc{liu2023llava,
208
+ title={Visual Instruction Tuning},
209
+ author={Liu, Haotian and Li, Chunyuan and Wu, Qingyang and Lee, Yong Jae},
210
+ publisher={arXiv:2304.08485},
211
+ year={2023}
212
+ }
213
+ ```
214
+
215
+ ## Acknowledgement
216
+
217
+ - [LLaVA](https://github.com/haotian-liu/LLaVA), [Vicuna](https://github.com/lm-sys/FastChat): Thanks to their amazing codebase.
218
+
219
+
220
+ ## Related Projects
221
+ - [LLaVA](https://llava-vl.github.io/)
222
+
223
+ Included Tools
224
+ - [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO)
225
+ - [Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything)
226
+ - [Recognize Anythging](https://github.com/xinyu1205/recognize-anything)
227
+ - [Segment-Anything](https://github.com/facebookresearch/segment-anything).
228
+ - [SEEM: Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once)
229
+ - [Semantic-SAM](https://github.com/UX-Decoder/Semantic-SAM)
230
+ - [Segment-Anything](https://github.com/facebookresearch/segment-anything)
231
+
232
+
233
+ For future project ideas, please check out:
234
+ - [Instruction Tuning with GPT-4](https://github.com/Instruction-Tuning-with-GPT-4/GPT-4-LLM)
235
+ - [LLaVA-Med: Training a Large Language-and-Vision Assistant for Biomedicine in One Day](https://github.com/microsoft/LLaVA-Med)
236
+ - [Otter: In-Context Multi-Modal Instruction Tuning](https://github.com/Luodian/Otter)
fin-mm/code/LLaVA-Plus/cog.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for Cog ⚙️
2
+ # Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md
3
+
4
+ build:
5
+ gpu: true
6
+
7
+ python_version: "3.11"
8
+
9
+ python_packages:
10
+ - "torch==2.0.1"
11
+ - "accelerate==0.21.0"
12
+ - "bitsandbytes==0.41.0"
13
+ - "deepspeed==0.9.5"
14
+ - "einops-exts==0.0.4"
15
+ - "einops==0.6.1"
16
+ - "gradio==3.35.2"
17
+ - "gradio_client==0.2.9"
18
+ - "httpx==0.24.0"
19
+ - "markdown2==2.4.10"
20
+ - "numpy==1.26.0"
21
+ - "peft==0.4.0"
22
+ - "scikit-learn==1.2.2"
23
+ - "sentencepiece==0.1.99"
24
+ - "shortuuid==1.0.11"
25
+ - "timm==0.6.13"
26
+ - "tokenizers==0.13.3"
27
+ - "torch==2.0.1"
28
+ - "torchvision==0.15.2"
29
+ - "transformers==4.31.0"
30
+ - "wandb==0.15.12"
31
+ - "wavedrom==2.0.3.post3"
32
+ - "Pygments==2.16.1"
33
+ run:
34
+ - curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.0.3/pget" && chmod +x /usr/local/bin/pget
35
+
36
+ # predict.py defines how predictions are run on your model
37
+ predict: "predict.py:Predictor"
fin-mm/code/LLaVA-Plus/docs/llava-plus/dataset.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA-Plus Data
2
+
3
+ ## Released Data
4
+
5
+ [huggingface](https://huggingface.co/datasets/LLaVA-VL/llava-plus-data)
6
+
7
+ - [llava-150k-tool-aug.json](https://huggingface.co/datasets/LLaVA-VL/llava-plus-data/blob/main/llava-150k-tool-aug.json) augment the llava-insttrution-150 with extrac `"thoughts"` and `"actions"` to ensure the data format as llava-plus required.
8
+ - [llava-plus-v1-117k-tool-merge.json](https://huggingface.co/datasets/LLaVA-VL/llava-plus-data/blob/main/llava-plus-v1-117k-tool-merge.json) is tool learning visual instruction data by prompting ChatGPT/GPT-4.
9
+
10
+
11
+ ## How to build the Instruction Data
12
+ We provide an example to constuct grounding data [here](playground/llava-plus-data/grounding/run.sh).
fin-mm/code/LLaVA-Plus/docs/llava-plus/modelzoo.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # LLaVA-Plus Checkpoints
2
+
3
+ We will continuously update the model zoo.
4
+
5
+ | Model Name | Training Data | LLM version | projector |
6
+ |------------|---------------|-------------|-----------|
7
+ | [llava_plus_v0_7b](https://huggingface.co/LLaVA-VL/llava_plus_v0_7b) | [url](https://huggingface.co/datasets/LLaVA-VL/llava-plus-data) | vicuna-v0-7b | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v0-CC3M-595K-original_caption.bin) |
8
+
fin-mm/code/LLaVA-Plus/docs/llava-plus/tools.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA-Plus Server
2
+
3
+ ![llava-plus-arch](../../images/llava-plus-arch.png)
4
+
5
+ As shown in the figure above, we need to build an API cloud to main all tools.
6
+
7
+ ## Launch a controller
8
+ Build a controller like the guides in [readme](README.md#1-Launch-a-controller).
9
+
10
+ Our tool workers and llm-model workers share the same controller.
11
+
12
+ ## Launch tool workers: An Example
13
+ We provide all model workers in the `serve/` folder. The tool worker is named as `{tool_name}_worker.py`. To run a worker, make sure you have installed the required tool(or copy the worker file to different tool folders).
14
+
15
+ An example for the Grounded-SAM, whch includes Grounding-DINO, SAM, and Grounded-SAM.
16
+
17
+ ```sh
18
+ git clone https://github.com/IDEA-Research/Grounded-Segment-Anything
19
+ python -m pip install -e GroundingDINO
20
+ python -m pip install -e segment_anything
21
+ python serve/grounding_dino_worker.py
22
+ ```
23
+
24
+ Wait until the process finishes loading the model and you see "Uvicorn running on ...". You need to open another terminal process for other operations.
25
+
26
+ Test the worker:
27
+ ```sh
28
+ python serve/grounding_dino_test_message.py
29
+ ```
30
+
31
+ ## All Tools
32
+
33
+ | Tool Name | Install Source |
34
+ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
35
+ | Grounding DINO | [https://github.com/IDEA-Research/Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything) |
36
+ | SAM | [https://github.com/IDEA-Research/Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything) |
37
+ | Grounded-SAM | [https://github.com/IDEA-Research/Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything) |
38
+ | CLIP-Retrieval | [https://github.com/rom1504/clip-retrieval](https://github.com/rom1504/clip-retrieval) |
39
+ | InstructPix2Pix | [https://github.com/huggingface/diffusers](https://github.com/huggingface/diffusers) |
40
+ | StableDiffusion | [https://github.com/huggingface/diffusers](https://github.com/huggingface/diffusers) |
41
+ | BLIP2 | [https://github.com/huggingface/transformers](https://github.com/huggingface/transformers) |
42
+ | RAM | [https://github.com/IDEA-Research/Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything) |
43
+ | Semantic-SAM | [https://github.com/UX-Decoder/Semantic-SAM](https://github.com/UX-Decoder/Semantic-SAM) |
44
+ | SEEM | [https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once) |
45
+ | OCR(easyocr) | [https://github.com/JaidedAI/EasyOCR](https://github.com/JaidedAI/EasyOCR) |
fin-mm/code/LLaVA-Plus/docs/llava/Customize_Component.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Customize Components in LLaVA
2
+
3
+ This is an initial guide on how to replace the LLMs, visual encoders, etc. with your choice of components.
4
+
5
+ ## LLM
6
+
7
+ It is quite simple to swap out LLaMA to any other LLMs. You can refer to our implementation of [`llava_llama.py`](https://raw.githubusercontent.com/haotian-liu/LLaVA/main/llava/model/language_model/llava_llama.py) for an example of how to replace the LLM.
8
+
9
+ Although it may seem that it still needs ~100 lines of code, most of them are copied from the original `llama.py` from HF. The only part that is different is to insert some lines for processing the multimodal inputs.
10
+
11
+ In `forward` function, you can see that we call `self.prepare_inputs_labels_for_multimodal` to process the multimodal inputs. This function is defined in `LlavaMetaForCausalLM` and you just need to insert it into the `forward` function of your LLM.
12
+
13
+ In `prepare_inputs_for_generation` function, you can see that we add `images` to the `model_inputs`. This is because we need to pass the images to the LLM during generation.
14
+
15
+ These are basically all the changes you need to make to replace the LLM.
16
+
17
+ ## Visual Encoder
18
+
19
+ You can check out [`clip_encoder.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/multimodal_encoder/clip_encoder.py) on how we implement the CLIP visual encoder.
20
+
fin-mm/code/LLaVA-Plus/docs/llava/Data.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Data
2
+
3
+ | Data file name | Size |
4
+ | --- | ---: |
5
+ | [llava_instruct_150k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json) | 229 MB |
6
+ | [llava_instruct_80k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_80k.json) | 229 MB |
7
+ | [conversation_58k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/conversation_58k.json) | 126 MB |
8
+ | [detail_23k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/detail_23k.json) | 20.5 MB |
9
+ | [complex_reasoning_77k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/complex_reasoning_77k.json) | 79.6 MB |
10
+
11
+ ### Pretraining Dataset
12
+ The pretraining dataset used in this release is a subset of CC-3M dataset, filtered with a more balanced concept coverage distribution. Please see [here](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K) for a detailed description of the dataset structure and how to download the images.
13
+
14
+ If you already have CC-3M dataset on your disk, the image names follow this format: `GCC_train_000000000.jpg`. You may edit the `image` field correspondingly if necessary.
15
+
16
+ | Data | Chat File | Meta Data | Size |
17
+ | --- | --- | --- | ---: |
18
+ | CC-3M Concept-balanced 595K | [chat.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/chat.json) | [metadata.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/metadata.json) | 211 MB
19
+ | LAION/CC/SBU BLIP-Caption Concept-balanced 558K | [blip_laion_cc_sbu_558k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json) | [metadata.json](#) | 181 MB
20
+
21
+ **Important notice**: Upon the request from the community, as ~15% images of the original CC-3M dataset are no longer accessible, we upload [`images.zip`](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/images.zip) for better reproducing our work in research community. It must not be used for any other purposes. The use of these images must comply with the CC-3M license. This may be taken down at any time when requested by the original CC-3M dataset owner or owners of the referenced images.
22
+
23
+ ### GPT-4 Prompts
24
+
25
+ We provide our prompts and few-shot samples for GPT-4 queries, to better facilitate research in this domain. Please check out the [`prompts`](https://github.com/haotian-liu/LLaVA/tree/main/playground/data/prompts) folder for three kinds of questions: conversation, detail description, and complex reasoning.
26
+
27
+ They are organized in a format of `system_message.txt` for system message, pairs of `abc_caps.txt` for few-shot sample user input, and `abc_conv.txt` for few-shot sample reference output.
28
+
29
+ Note that you may find them in different format. For example, `conversation` is in `jsonl`, and detail description is answer-only. The selected format in our preliminary experiments works slightly better than a limited set of alternatives that we tried: `jsonl`, more natural format, answer-only. If interested, you may try other variants or conduct more careful study in this. Contributions are welcomed!
fin-mm/code/LLaVA-Plus/docs/llava/Evaluation.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation
2
+
3
+ In LLaVA-1.5, we evaluate models on a diverse set of 12 benchmarks. To ensure the reproducibility, we evaluate the models with greedy decoding. We do not evaluate using beam search to make the inference process consistent with the chat demo of real-time outputs.
4
+
5
+ Currently, we mostly utilize the official toolkit or server for the evaluation.
6
+
7
+ ## Evaluate on Custom Datasets
8
+
9
+ You can evaluate LLaVA on your custom datasets by converting your dataset to LLaVA's jsonl format, and evaluate using [`model_vqa.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/model_vqa.py).
10
+
11
+ Below we provide a general guideline for evaluating datasets with some common formats.
12
+
13
+ 1. Short-answer (e.g. VQAv2, MME).
14
+
15
+ ```
16
+ <question>
17
+ Answer the question using a single word or phrase.
18
+ ```
19
+
20
+ 2. Option-only for multiple-choice (e.g. MMBench, SEED-Bench).
21
+
22
+ ```
23
+ <question>
24
+ A. <option_1>
25
+ B. <option_2>
26
+ C. <option_3>
27
+ D. <option_4>
28
+ Answer with the option's letter from the given choices directly.
29
+ ```
30
+
31
+ 3. Natural QA (e.g. LLaVA-Bench, MM-Vet).
32
+
33
+ No postprocessing is needed.
34
+
35
+ ## Scripts
36
+
37
+ Before preparing task-specific data, **you MUST first download [eval.zip](https://drive.google.com/file/d/1atZSBBrAX54yYpxtVVW33zFvcnaHeFPy/view?usp=sharing)**. It contains custom annotations, scripts, and the prediction files with LLaVA v1.5. Extract to `./playground/data/eval`. This also provides a general structure for all datasets.
38
+
39
+ ### VQAv2
40
+
41
+ 1. Download [`test2015`](http://images.cocodataset.org/zips/test2015.zip) and put it under `./playground/data/eval/vqav2`.
42
+ 2. Multi-GPU inference.
43
+ ```Shell
44
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/vqav2.sh
45
+ ```
46
+ 3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/830/my-submission): `./playground/data/eval/vqav2/answers_upload`.
47
+
48
+ ### GQA
49
+
50
+ 1. Download the [data](https://cs.stanford.edu/people/dorarad/gqa/download.html) and [evaluation scripts](https://cs.stanford.edu/people/dorarad/gqa/evaluate.html) following the official instructions and put under `./playground/data/eval/gqa/data`. You may need to modify `eval.py` as [this](https://gist.github.com/haotian-liu/db6eddc2a984b4cbcc8a7f26fd523187) due to the missing assets in the GQA v1.2 release.
51
+ 2. Multi-GPU inference.
52
+ ```Shell
53
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/gqa.sh
54
+ ```
55
+
56
+ ### VisWiz
57
+
58
+ 1. Download [`test.json`](https://vizwiz.cs.colorado.edu/VizWiz_final/vqa_data/Annotations.zip) and extract [`test.zip`](https://vizwiz.cs.colorado.edu/VizWiz_final/images/test.zip) to `test`. Put them under `./playground/data/eval/vizwiz`.
59
+ 2. Single-GPU inference.
60
+ ```Shell
61
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/vizwiz.sh
62
+ ```
63
+ 3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/1911/my-submission): `./playground/data/eval/vizwiz/answers_upload`.
64
+
65
+ ### ScienceQA
66
+
67
+ 1. Under `./playground/data/eval/scienceqa`, download `images`, `pid_splits.json`, `problems.json` from the `data/scienceqa` folder of the ScienceQA [repo](https://github.com/lupantech/ScienceQA).
68
+ 2. Single-GPU inference and evaluate.
69
+ ```Shell
70
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/sqa.sh
71
+ ```
72
+
73
+ ### TextVQA
74
+
75
+ 1. Download [`TextVQA_0.5.1_val.json`](https://dl.fbaipublicfiles.com/textvqa/data/TextVQA_0.5.1_val.json) and [images](https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip) and extract to `./playground/data/eval/textvqa`.
76
+ 2. Single-GPU inference and evaluate.
77
+ ```Shell
78
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/textvqa.sh
79
+ ```
80
+
81
+ ### POPE
82
+
83
+ 1. Download `coco` from [POPE](https://github.com/AoiDragon/POPE/tree/e3e39262c85a6a83f26cf5094022a782cb0df58d/output/coco) and put under `./playground/data/eval/pope`.
84
+ 2. Single-GPU inference and evaluate.
85
+ ```Shell
86
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/pope.sh
87
+ ```
88
+
89
+ ### MME
90
+
91
+ 1. Download the data following the official instructions [here](https://github.com/BradyFU/Awesome-Multimodal-Large-Language-Models/tree/Evaluation).
92
+ 2. Downloaded images to `MME_Benchmark_release_version`.
93
+ 3. put the official `eval_tool` and `MME_Benchmark_release_version` under `./playground/data/eval/MME`.
94
+ 4. Single-GPU inference and evaluate.
95
+ ```Shell
96
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mme.sh
97
+ ```
98
+
99
+ ### MMBench
100
+
101
+ 1. Download [`mmbench_dev_20230712.tsv`](https://download.openmmlab.com/mmclassification/datasets/mmbench/mmbench_dev_20230712.tsv) and put under `./playground/data/eval/mmbench`.
102
+ 2. Single-GPU inference.
103
+ ```Shell
104
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench.sh
105
+ ```
106
+ 3. Submit the results to the [evaluation server](https://opencompass.org.cn/leaderboard-multimodal): `./playground/data/eval/mmbench/answers_upload/mmbench_dev_20230712`.
107
+
108
+ ### MMBench-CN
109
+
110
+ 1. Download [`mmbench_dev_cn_20231003.tsv`](https://download.openmmlab.com/mmclassification/datasets/mmbench/mmbench_dev_cn_20231003.tsv) and put under `./playground/data/eval/mmbench`.
111
+ 2. Single-GPU inference.
112
+ ```Shell
113
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench_cn.sh
114
+ ```
115
+ 3. Submit the results to the evaluation server: `./playground/data/eval/mmbench/answers_upload/mmbench_dev_cn_20231003`.
116
+
117
+
118
+ ### SEED-Bench
119
+
120
+ 1. Following the official [instructions](https://github.com/AILab-CVC/SEED-Bench/blob/main/DATASET.md) to download the images and the videos. Put images under `./playground/data/eval/seed_bench/SEED-Bench-image`.
121
+ 2. Extract the video frame in the middle from the downloaded videos, and put them under `./playground/data/eval/seed_bench/SEED-Bench-video-image`. We provide our script `extract_video_frames.py` modified from the official one.
122
+ 3. Multiple-GPU inference and evaluate.
123
+ ```Shell
124
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/seed.sh
125
+ ```
126
+ 4. Optionally, submit the results to the leaderboard: `./playground/data/eval/seed_bench/answers_upload` using the official jupyter notebook.
127
+
128
+ ### LLaVA-Bench-in-the-Wild
129
+
130
+ 1. Extract contents of [`llava-bench-in-the-wild`](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to `./playground/data/eval/llava-bench-in-the-wild`.
131
+ 2. Single-GPU inference and evaluate.
132
+ ```Shell
133
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/llavabench.sh
134
+ ```
135
+
136
+ ### MM-Vet
137
+
138
+ 1. Extract [`mm-vet.zip`](https://github.com/yuweihao/MM-Vet/releases/download/v1/mm-vet.zip) to `./playground/data/eval/mmvet`.
139
+ 2. Single-GPU inference.
140
+ ```Shell
141
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmvet.sh
142
+ ```
143
+ 3. Evaluate the predictions in `./playground/data/eval/mmvet/results` using the official jupyter notebook.
144
+
145
+ ## More Benchmarks
146
+
147
+ Below are awesome benchmarks for multimodal understanding from the research community, that are not initially included in the LLaVA-1.5 release.
148
+
149
+ ### Q-Bench
150
+
151
+ 1. Download [`llvisionqa_dev.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/llvisionqa_dev.json) (for `dev`-subset) and [`llvisionqa_test.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/llvisionqa_test.json) (for `test`-subset). Put them under `./playground/data/eval/qbench`.
152
+ 2. Download and extract [images](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/images_llvisionqa.tar) and put all the images directly under `./playground/data/eval/qbench/images_llviqionqa`.
153
+ 3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
154
+ ```Shell
155
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench.sh dev
156
+ ```
157
+ 4. Submit the results by instruction [here](https://github.com/VQAssessment/Q-Bench#option-1-submit-results): `./playground/data/eval/qbench/llvisionqa_dev_answers.jsonl`.
158
+
159
+ ### Chinese-Q-Bench
160
+
161
+ 1. Download [`质衡-问答-验证集.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/%E8%B4%A8%E8%A1%A1-%E9%97%AE%E7%AD%94-%E9%AA%8C%E8%AF%81%E9%9B%86.json) (for `dev`-subset) and [`质衡-问答-测试集.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/%E8%B4%A8%E8%A1%A1-%E9%97%AE%E7%AD%94-%E6%B5%8B%E8%AF%95%E9%9B%86.json) (for `test`-subset). Put them under `./playground/data/eval/qbench`.
162
+ 2. Download and extract [images](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/images_llvisionqa.tar) and put all the images directly under `./playground/data/eval/qbench/images_llviqionqa`.
163
+ 3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
164
+ ```Shell
165
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench_zh.sh dev
166
+ ```
167
+ 4. Submit the results by instruction [here](https://github.com/VQAssessment/Q-Bench#option-1-submit-results): `./playground/data/eval/qbench/llvisionqa_zh_dev_answers.jsonl`.
fin-mm/code/LLaVA-Plus/docs/llava/Finetune_Custom_Data.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Finetune LLaVA on Custom Datasets
2
+
3
+ ## Dataset Format
4
+
5
+ Convert your data to a JSON file of a List of all samples. Sample metadata should contain `id` (a unique identifier), `image` (the path to the image), and `conversations` (the conversation data between human and AI).
6
+
7
+ A sample JSON for finetuning LLaVA for generating tag-style captions for Stable Diffusion:
8
+
9
+ ```json
10
+ [
11
+ {
12
+ "id": "997bb945-628d-4724-b370-b84de974a19f",
13
+ "image": "part-000001/997bb945-628d-4724-b370-b84de974a19f.jpg",
14
+ "conversations": [
15
+ {
16
+ "from": "human",
17
+ "value": "<image>\nWrite a prompt for Stable Diffusion to generate this image."
18
+ },
19
+ {
20
+ "from": "gpt",
21
+ "value": "a beautiful painting of chernobyl by nekro, pascal blanche, john harris, greg rutkowski, sin jong hun, moebius, simon stalenhag. in style of cg art. ray tracing. cel shading. hyper detailed. realistic. ue 5. maya. octane render. "
22
+ },
23
+ ]
24
+ },
25
+ ...
26
+ ]
27
+ ```
28
+
29
+ ## Command
30
+
31
+ If you have a limited task-specific data, we recommend finetuning from LLaVA checkpoints with LoRA following this [script](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_task_lora.sh).
32
+
33
+ If the amount of the task-specific data is sufficient, you can also finetune from LLaVA checkpoints with full-model finetuning following this [script](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_task.sh).
34
+
35
+ You may need to adjust the hyperparameters to fit each specific dataset and your hardware constraint.
36
+
37
+
fin-mm/code/LLaVA-Plus/docs/llava/Intel.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Intel Platforms
2
+
3
+ * Support [Intel GPU Max Series](https://www.intel.com/content/www/us/en/products/details/discrete-gpus/data-center-gpu/max-series.html)
4
+ * Support [Intel CPU Sapphire Rapides](https://ark.intel.com/content/www/us/en/ark/products/codename/126212/products-formerly-sapphire-rapids.html)
5
+ * Based on [Intel Extention for Pytorch](https://intel.github.io/intel-extension-for-pytorch)
6
+
7
+ More details in [**intel branch**](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
fin-mm/code/LLaVA-Plus/docs/llava/LLaVA_Bench.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA-Bench [[Download](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild)]
2
+
3
+ **-Introduction-** Large commercial multimodal chatbots have been released in this week, including
4
+ - [Multimodal Bing-Chat by Microsoft](https://blogs.bing.com/search/july-2023/Bing-Chat-Enterprise-announced,-multimodal-Visual-Search-rolling-out-to-Bing-Chat) (July 18, 2023)
5
+ - [Multimodal Bard by Google](https://bard.google.com/).
6
+
7
+ These chatbots are presumably supported by proprietary large multimodal models (LMM). Compared with the open-source LMM such as LLaVA, proprietary LMM represent the scaling success upperbound of the current SoTA techniques. They share the goal of developing multimodal chatbots that follow human intents to complete various daily-life visual tasks in the wild. While it remains less explored how to evaluate multimodal chat ability, it provides useful feedback to study open-source LMMs against the commercial multimodal chatbots. In addition to the *LLaVA-Bench (COCO)* dataset we used to develop the early versions of LLaVA, we are releasing [*LLaVA-Bench (In-the-Wild)*](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to the community for the public use.
8
+
9
+ ## LLaVA-Bench (In-the-Wild *[Ongoing work]*)
10
+
11
+ To evaluate the model's capability in more challenging tasks and generalizability to novel domains, we collect a diverse set of 24 images with 60 questions in total, including indoor and outdoor scenes, memes, paintings, sketches, etc, and associate each image with a highly-detailed and manually-curated description and a proper selection of questions. Such design also assesses the model's robustness to different prompts. In this release, we also categorize questions into three categories: conversation (simple QA), detailed description, and complex reasoning. We continue to expand and improve the diversity of the LLaVA-Bench (In-the-Wild). We manually query Bing-Chat and Bard to get the responses.
12
+
13
+ ### Results
14
+
15
+ The score is measured by comparing against a reference answer generated by text-only GPT-4. It is generated by feeding the question, along with the ground truth image annotations as the context. A text-only GPT-4 evaluator rates both answers. We query GPT-4 by putting the reference answer first, and then the answer generated by the candidate model. We upload images at their original resolution to Bard and Bing-Chat to obtain the results.
16
+
17
+ | Approach | Conversation | Detail | Reasoning | Overall |
18
+ |----------------|--------------|--------|-----------|---------|
19
+ | Bard-0718 | 83.7 | 69.7 | 78.7 | 77.8 |
20
+ | Bing-Chat-0629 | 59.6 | 52.2 | 90.1 | 71.5 |
21
+ | LLaVA-13B-v1-336px-0719 (beam=1) | 64.3 | 55.9 | 81.7 | 70.1 |
22
+ | LLaVA-13B-v1-336px-0719 (beam=5) | 68.4 | 59.9 | 84.3 | 73.5 |
23
+
24
+ Note that Bard sometimes refuses to answer questions about images containing humans, and Bing-Chat blurs the human faces in the images. We also provide the benchmark score for the subset without humans.
25
+
26
+ | Approach | Conversation | Detail | Reasoning | Overall |
27
+ |----------------|--------------|--------|-----------|---------|
28
+ | Bard-0718 | 94.9 | 74.3 | 84.3 | 84.6 |
29
+ | Bing-Chat-0629 | 55.8 | 53.6 | 93.5 | 72.6 |
30
+ | LLaVA-13B-v1-336px-0719 (beam=1) | 62.2 | 56.4 | 82.2 | 70.0 |
31
+ | LLaVA-13B-v1-336px-0719 (beam=5) | 65.6 | 61.7 | 85.0 | 73.6 |
fin-mm/code/LLaVA-Plus/docs/llava/LLaVA_from_LLaMA2.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA (based on Llama 2 LLM, Preview)
2
+
3
+ *NOTE: This is a technical preview. We are still running hyperparameter search, and will release the final model soon. If you'd like to contribute to this, please contact us.*
4
+
5
+ :llama: **-Introduction-** [Llama 2 is an open-source LLM released by Meta AI](https://about.fb.com/news/2023/07/llama-2/) today (July 18, 2023). Compared with its early version [Llama 1](https://ai.meta.com/blog/large-language-model-llama-meta-ai/), Llama 2 is more favored in ***stronger language performance***, ***longer context window***, and importantly ***commercially usable***! While Llama 2 is changing the LLM market landscape in the language space, its multimodal ability remains unknown. We quickly develop the LLaVA variant based on the latest Llama 2 checkpoints, and release it to the community for the public use.
6
+
7
+ You need to apply for and download the latest Llama 2 checkpoints to start your own training (apply [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/))
8
+
9
+
10
+ ## Training
11
+
12
+ Please checkout [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh), [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune.sh), [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh).
13
+
14
+ ## LLaVA (based on Llama 2), What is different?
15
+
16
+ :volcano: How is the new LLaVA based on Llama 2 different from Llama 1? The comparisons of the training process are described:
17
+ - **Pre-training**. The pre-trained base LLM is changed from Llama 1 to Llama 2
18
+ - **Language instruction-tuning**. The previous LLaVA model starts with Vicuna, which is instruct tuned on ShareGPT data from Llama 1; The new LLaVA model starts with Llama 2 Chat, which is an instruct tuned checkpoint on dialogue data from Llama 2.
19
+ - **Multimodal instruction-tuning**. The same LLaVA-Lighting process is applied.
20
+
21
+
22
+ ### Results
23
+
24
+ - Llama 2 is better at following the instructions of role playing; Llama 2 fails in following the instructions of translation
25
+ - The quantitative evaluation on [LLaVA-Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) demonstrates on-par performance between Llama 2 and Llama 1 in LLaVA's multimodal chat ability.
26
+
27
+
28
+ <img src="../images/llava_example_cmp.png" width="100%">
29
+
fin-mm/code/LLaVA-Plus/docs/llava/LoRA.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA (LoRA, Preview)
2
+
3
+ NOTE: This is a technical preview, and is not yet ready for production use. We are still running hyperparameter search for the LoRA model, and will release the final model soon. If you'd like to contribute to this, please contact us.
4
+
5
+ You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base))
6
+
7
+ ## Demo (Web UI)
8
+
9
+ Please execute each of the commands below one by one (after the previous one has finished). The commands are the same as launching other demos except for an additional `--model-base` flag to specify the base model to use. Please make sure the base model corresponds to the LoRA checkpoint that you are using. For this technical preview, you need Vicuna v1.1 (7B) checkpoint (if you do not have that already, follow the instructions [here](https://github.com/lm-sys/FastChat#vicuna-weights)).
10
+
11
+ #### Launch a controller
12
+ ```Shell
13
+ python -m llava.serve.controller --host 0.0.0.0 --port 10000
14
+ ```
15
+
16
+ #### Launch a gradio web server.
17
+ ```Shell
18
+ python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
19
+ ```
20
+ You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker.
21
+
22
+ #### Launch a model worker
23
+ ```Shell
24
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-vicuna-7b-v1.1-lcs_558k-instruct_80k_3e-lora-preview-alpha --model-base /path/to/vicuna-v1.1
25
+ ```
26
+ Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list.
27
+
28
+ You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker.
29
+
30
+
31
+ ## Training
32
+
33
+ Please see sample training scripts for [LoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh) and [QLoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_qlora.sh).
34
+
35
+ We provide sample DeepSpeed configs, [`zero3.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3.json) is more like PyTorch FSDP, and [`zero3_offload.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3_offload.json) can further save memory consumption by offloading parameters to CPU. `zero3.json` is usually faster than `zero3_offload.json` but requires more GPU memory, therefore, we recommend trying `zero3.json` first, and if you run out of GPU memory, try `zero3_offload.json`. You can also tweak the `per_device_train_batch_size` and `gradient_accumulation_steps` in the config to save memory, and just to make sure that `per_device_train_batch_size` and `gradient_accumulation_steps` remains the same.
36
+
37
+ If you are having issues with ZeRO-3 configs, and there are enough VRAM, you may try [`zero2.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero2.json). This consumes slightly more memory than ZeRO-3, and behaves more similar to PyTorch FSDP, while still supporting parameter-efficient tuning.
38
+
39
+ ## Create Merged Checkpoints
40
+
41
+ ```Shell
42
+ python scripts/merge_lora_weights.py \
43
+ --model-path /path/to/lora_model \
44
+ --model-base /path/to/base_model \
45
+ --save-model-path /path/to/merge_model
46
+ ```
fin-mm/code/LLaVA-Plus/docs/llava/MODEL_ZOO.md ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Zoo
2
+
3
+ **To Use LLaVA-1.5 checkpoints, your llava package version must be newer than 1.1.0. [Instructions](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base) on how to upgrade.**
4
+
5
+ If you are interested in including any other details in Model Zoo, please open an issue :)
6
+
7
+ The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license: [Llama 2](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md).
8
+
9
+ ## LLaVA-v1.5
10
+
11
+ | Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | T-VQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet |
12
+ |----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|
13
+ | LLaVA-1.5 | 7B | full_ft-1e | [liuhaotian/llava-v1.5-7b](https://huggingface.co/liuhaotian/llava-v1.5-7b) | 78.5 | 62.0 | 50.0 | 66.8 | 58.2 | 85.9 | 1510.7 | 64.3 | 58.3 | 58.6 | 65.4 | 31.1 |
14
+ | LLaVA-1.5 | 13B | full_ft-1e | [liuhaotian/llava-v1.5-13b](https://huggingface.co/liuhaotian/llava-v1.5-13b) | 80.0 | 63.3 | 53.6 | 71.6 | 61.3 | 85.9 | 1531.3 | 67.7 | 63.6 | 61.6 | 72.5 | 36.1 |
15
+ | LLaVA-1.5 | 7B | lora-1e | [liuhaotian/llava-v1.5-7b-lora](https://huggingface.co/liuhaotian/llava-v1.5-7b-lora) | 79.1 | 63.0 | 47.8 | 68.4 | 58.2 | 86.4 | 1476.9 | 66.1 | 58.9 | 60.1 | 67.9 | 30.2 |
16
+ | LLaVA-1.5 | 13B | lora-1e | [liuhaotian/llava-v1.5-13b-lora](https://huggingface.co/liuhaotian/llava-v1.5-13b-lora) | 80.0 | 63.3 | 58.9 | 71.2 | 60.2 | 86.7 | 1541.7 | 68.5 | 61.5 | 61.3 | 69.5 | 38.3 |
17
+
18
+ Base model: Vicuna v1.5. Training logs: [wandb](https://api.wandb.ai/links/lht/6orh56wc).
19
+
20
+ <p align="center">
21
+ <img src="../images/llava_v1_5_radar.jpg" width="500px"> <br>
22
+ LLaVA-1.5 achieves SoTA performance across 11 benchmarks.
23
+ </p>
24
+
25
+
26
+ ## LLaVA-v1
27
+
28
+ *Note: We recommend using the most capable LLaVA-v1.5 series above for the best performance.*
29
+
30
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | LLaVA-Bench-Conv | LLaVA-Bench-Detail | LLaVA-Bench-Complex | LLaVA-Bench-Overall | Download |
31
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|--------------------|---------------------|---------------------|---------------------|
32
+ | Vicuna-13B-v1.3 | CLIP-L-336px | LCS-558K | 1e | LLaVA-Instruct-80K | proj-1e, lora-1e | 64.3 | 55.9 | 81.7 | 70.1 | [LoRA](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-vicuna-13b-v1.3) [LoRA-Merged](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-merge-vicuna-13b-v1.3) |
33
+ | LLaMA-2-13B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | 56.7 | 58.6 | 80.0 | 67.9 | [ckpt](https://huggingface.co/liuhaotian/llava-llama-2-13b-chat-lightning-preview) |
34
+ | LLaMA-2-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | lora-1e | 51.2 | 58.9 | 71.6 | 62.8 | [LoRA](https://huggingface.co/liuhaotian/llava-llama-2-7b-chat-lightning-lora-preview) |
35
+
36
+
37
+ ## Projector weights
38
+
39
+ These are projector weights we have pretrained. You can use these projector weights for visual instruction tuning. They are just pretrained on image-text pairs and are NOT instruction-tuned, which means they do NOT follow instructions as well as our official models and can output repetitive, lengthy, and garbled outputs. If you want to have nice conversations with LLaVA, use the checkpoints above (LLaVA v1.5).
40
+
41
+ NOTE: These projector weights are only compatible with `llava>=1.0.0`. Please check out the latest codebase if your local code version is below v1.0.0.
42
+
43
+ NOTE: When you use our pretrained projector for visual instruction tuning, it is very important to use the same base LLM and vision encoder as the one we used for pretraining the projector. Otherwise, the performance will be very poor.
44
+
45
+ When using these projector weights to instruction-tune your LMM, please make sure that these options are correctly set as follows,
46
+
47
+ ```Shell
48
+ --mm_use_im_start_end False
49
+ --mm_use_im_patch_token False
50
+ ```
51
+
52
+ | Base LLM | Vision Encoder | Projection | Pretrain Data | Pretraining schedule | Download |
53
+ |----------|----------------|---------------|----------------------|----------|----------|
54
+ | Vicuna-13B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-13b-v1.5) |
55
+ | Vicuna-7B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-7b-v1.5) |
56
+ | LLaMA-2-13B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-13b-chat) |
57
+ | LLaMA-2-7B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-7b-chat) |
58
+ | LLaMA-2-13B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-13b-chat) |
59
+ | LLaMA-2-7B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-7b-chat) |
60
+ | Vicuna-13B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-13b-v1.3) |
61
+ | Vicuna-7B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-7b-v1.3) |
62
+ | Vicuna-13B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-13b-v1.3) |
63
+ | Vicuna-7B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-7b-v1.3) |
64
+
65
+
66
+ ## Science QA Checkpoints
67
+
68
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
69
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|---------------------|
70
+ | Vicuna-13B-v1.3 | CLIP-L | LCS-558K | 1e | ScienceQA | full_ft-12e | [ckpt](https://huggingface.co/liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3) |
71
+
72
+
73
+ ## Legacy Models (merged weights)
74
+
75
+ The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license.
76
+
77
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
78
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
79
+ | MPT-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview) |
80
+
81
+
82
+ ## Legacy Models (delta weights)
83
+
84
+ The model weights below are *delta* weights. The usage of LLaVA checkpoints should comply with the base LLM's model license: [LLaMA](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md).
85
+
86
+ You can add our delta to the original LLaMA weights to obtain the LLaVA weights.
87
+
88
+ Instructions:
89
+
90
+ 1. Get the original LLaMA weights in the huggingface format by following the instructions [here](https://huggingface.co/docs/transformers/main/model_doc/llama).
91
+ 2. Use the following scripts to get LLaVA weights by applying our delta. It will automatically download delta weights from our Hugging Face account. In the script below, we use the delta weights of [`liuhaotian/LLaVA-7b-delta-v0`](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) as an example. It can be adapted for other delta weights by changing the `--delta` argument (and base/target accordingly).
92
+
93
+ ```bash
94
+ python3 -m llava.model.apply_delta \
95
+ --base /path/to/llama-7b \
96
+ --target /output/path/to/LLaVA-7B-v0 \
97
+ --delta liuhaotian/LLaVA-7b-delta-v0
98
+ ```
99
+
100
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
101
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
102
+ | Vicuna-13B-v1.1 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v1-1) |
103
+ | Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-Lightning-7B-delta-v1-1) |
104
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0) |
105
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | ScienceQA | full_ft-12e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0-science_qa) |
106
+ | Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) |
107
+
108
+
109
+
110
+ ## Legacy Projector weights
111
+
112
+ The following projector weights are deprecated, and the support for them may be removed in the future. They do not support zero-shot inference. Please use the projector weights in the [table above](#projector-weights) if possible.
113
+
114
+ **NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad.
115
+
116
+ When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
117
+
118
+ ```Shell
119
+ --mm_use_im_start_end True
120
+ --mm_use_im_patch_token False
121
+ ```
122
+
123
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
124
+ |----------|----------------|---------------|----------------------|----------|
125
+ | Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v1-1-LCS-558K-blip_caption.bin) |
126
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption.bin) |
127
+ | Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v0-CC3M-595K-original_caption.bin) |
128
+
129
+ When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
130
+
131
+ ```Shell
132
+ --mm_use_im_start_end False
133
+ --mm_use_im_patch_token False
134
+ ```
135
+
136
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
137
+ |----------|----------------|---------------|----------------------|----------|
138
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption-no_im_token.bin) |
fin-mm/code/LLaVA-Plus/docs/llava/ScienceQA.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### ScienceQA
2
+
3
+ #### Prepare Data
4
+ 1. Please see ScienceQA [repo](https://github.com/lupantech/ScienceQA) for setting up the dataset.
5
+ 2. Generate ScienceQA dataset for LLaVA conversation-style format.
6
+
7
+ ```Shell
8
+ python scripts/convert_sqa_to_llava.py \
9
+ convert_to_llava \
10
+ --base-dir /path/to/ScienceQA/data/scienceqa \
11
+ --prompt-format "QCM-LEA" \
12
+ --split {train,val,minival,test,minitest}
13
+ ```
14
+
15
+ #### Training
16
+
17
+ 1. Pretraining
18
+
19
+ You can download our pretrained projector weights from our [Model Zoo](), or train your own projector weights using [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh).
20
+
21
+ 2. Finetuning
22
+
23
+ See [`finetune_sqa.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_sqa.sh).
24
+
25
+ #### Evaluation
26
+
27
+ 1. Multiple-GPU inference
28
+ You may evaluate this with multiple GPUs, and concatenate the generated jsonl files. Please refer to our script for [batch evaluation](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_batch.sh) and [results gathering](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_gather.sh).
29
+
30
+ 2. Single-GPU inference
31
+
32
+ (a) Generate LLaVA responses on ScienceQA dataset
33
+
34
+ ```Shell
35
+ python -m llava.eval.model_vqa_science \
36
+ --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \
37
+ --question-file /path/to/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \
38
+ --image-folder /path/to/ScienceQA/data/scienceqa/images/test \
39
+ --answers-file vqa/results/ScienceQA/test_llava-13b.jsonl \
40
+ --conv-mode llava_v1
41
+ ```
42
+
43
+ (b) Evaluate the generated responses
44
+
45
+ ```Shell
46
+ python eval_science_qa.py \
47
+ --base-dir /path/to/ScienceQA/data/scienceqa \
48
+ --result-file vqa/results/ScienceQA/test_llava-13b.jsonl \
49
+ --output-file vqa/results/ScienceQA/test_llava-13b_output.json \
50
+ --output-result vqa/results/ScienceQA/test_llava-13b_result.json \
51
+ ```
52
+
53
+ For reference, we attach our prediction file [`test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json) and [`test_sqa_llava_13b_v0.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_13b_v0.json) for comparison when reproducing our results, as well as for further analysis in detail.
fin-mm/code/LLaVA-Plus/docs/llava/Windows.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run LLaVA on Windows
2
+
3
+ *NOTE: LLaVA on Windows is not fully supported. Currently we only support 16-bit inference. For a more complete support, please use [WSL2](https://learn.microsoft.com/en-us/windows/wsl/install) for now. More functionalities on Windows is to be added soon, stay tuned.*
4
+
5
+ ## Installation
6
+
7
+ 1. Clone this repository and navigate to LLaVA folder
8
+ ```bash
9
+ git clone https://github.com/haotian-liu/LLaVA.git
10
+ cd LLaVA
11
+ ```
12
+
13
+ 2. Install Package
14
+ ```Shell
15
+ conda create -n llava python=3.10 -y
16
+ conda activate llava
17
+ python -mpip install --upgrade pip # enable PEP 660 support
18
+ pip install torch==2.0.1+cu117 torchvision==0.15.2+cu117 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu117
19
+ pip install -e .
20
+ pip uninstall bitsandbytes
21
+ ```
22
+
23
+ ## Run demo
24
+
25
+ See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
26
+
27
+ Note that quantization (4-bit, 8-bit) is *NOT* supported on Windows. Stay tuned for the 4-bit support on Windows!
fin-mm/code/LLaVA-Plus/docs/llava/macOS.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run LLaVA on macOS
2
+
3
+ *NOTE: LLaVA on macOS is not fully supported. Currently we only support 16-bit inference. More functionalities on macOS is to be added soon, stay tuned.*
4
+
5
+ ## Installation
6
+
7
+ 1. Clone this repository and navigate to LLaVA folder
8
+ ```bash
9
+ git clone https://github.com/haotian-liu/LLaVA.git
10
+ cd LLaVA
11
+ ```
12
+
13
+ 2. Install Package
14
+ ```Shell
15
+ conda create -n llava python=3.10 -y
16
+ conda activate llava
17
+ python -mpip install --upgrade pip # enable PEP 660 support
18
+ pip install -e .
19
+ pip install torch==2.1.0 torchvision==0.16.0
20
+ pip uninstall bitsandbytes
21
+ ```
22
+
23
+ ## Run demo
24
+
25
+ Specify `--device mps` when launching model worker or CLI.
26
+
27
+ See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
28
+
29
+ Note that quantization (4-bit, 8-bit) is *NOT* supported on macOS. Stay tuned for the 4-bit support on macOS!
fin-mm/code/LLaVA-Plus/images/demo_cli.gif ADDED

Git LFS Details

  • SHA256: 09227563f4fe04f077587eeb7b7c33ace2fbb8830e6cc9cfce03a25a57c43bfe
  • Pointer size: 133 Bytes
  • Size of remote file: 10 MB
fin-mm/code/LLaVA-Plus/images/llava-plus-arch.png ADDED

Git LFS Details

  • SHA256: 0f19f01effa1f731142d9efa81799f5d79b081c05c1f92021b317d77e1c1f83d
  • Pointer size: 131 Bytes
  • Size of remote file: 226 kB