File size: 26,182 Bytes
e1715de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 | #!/usr/bin/env python3
"""
NIM 多模型 K线图指令微调数据生成脚本
支持 NVIDIA NIM 平台上最强的商用模型
功能:
1. 多模型对比测试
2. 优化提示词设计(便于评估)
3. 自动评分对比
"""
from __future__ import annotations
import json
import random
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
import requests
import sys
from tqdm import tqdm
from datetime import datetime
# ========= NIM API 配置 =========
NIM_API_KEY = "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"
NIM_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions"
# ========= NIM 可用最强模型 (按类别分组) =========
NIM_MODELS = {
# === 超大模型 (最强综合能力) ===
"mistral-large-3-675b": "mistralai/mistral-large-3-675b-instruct-2512",
"deepseek-v3.2": "deepseek-ai/deepseek-v3.2",
"llama-3.1-405b": "meta/llama-3.1-405b-instruct",
"nemotron-ultra-253b": "nvidia/llama-3.1-nemotron-ultra-253b-v1",
# === 推理模型 (思维链) ===
"deepseek-r1": "deepseek-ai/deepseek-r1",
"kimi-k2-thinking": "moonshotai/kimi-k2-thinking",
# === 最新一代 (Llama 4 / Qwen 3) ===
"llama-4-maverick": "meta/llama-4-maverick-17b-128e-instruct",
"llama-4-scout": "meta/llama-4-scout-17b-16e-instruct",
"qwen3-coder-480b": "qwen/qwen3-coder-480b-a35b-instruct",
"qwen3-next-80b": "qwen/qwen3-next-80b-a3b-instruct",
# === 高性价比 (70B 级别) ===
"llama-3.3-70b": "meta/llama-3.3-70b-instruct",
"mistral-large-2": "mistralai/mistral-large-2-instruct",
"kimi-k2": "moonshotai/kimi-k2-instruct-0905",
# === Google 开源 ===
"gemma-3-27b": "google/gemma-3-27b-it",
# === OpenAI 开源复刻 ===
"gpt-oss-120b": "openai/gpt-oss-120b",
# === 中文特化 ===
"chatglm3-6b": "thudm/chatglm3-6b",
"baichuan2-13b": "baichuan-inc/baichuan2-13b-chat",
# === 多模态视觉 ===
"llama-3.2-90b-vision": "meta/llama-3.2-90b-vision-instruct",
"phi-4-multimodal": "microsoft/phi-4-multimodal-instruct",
}
# 模型分类
MODEL_CATEGORIES = {
"超大模型": ["mistral-large-3-675b", "deepseek-v3.2", "llama-3.1-405b", "nemotron-ultra-253b"],
"推理模型": ["deepseek-r1", "kimi-k2-thinking"],
"最新一代": ["llama-4-maverick", "llama-4-scout", "qwen3-coder-480b", "qwen3-next-80b"],
"高性价比": ["llama-3.3-70b", "mistral-large-2", "kimi-k2"],
"Google开源": ["gemma-3-27b"],
"GPT开源": ["gpt-oss-120b"],
"中文特化": ["chatglm3-6b", "baichuan2-13b"],
"多模态": ["llama-3.2-90b-vision", "phi-4-multimodal"],
}
# ========= 数据路径 =========
INPUT_INDEX = Path("/workspace/data/finmultitime_hf/finmultitime_kline_index.jsonl")
OUTPUT_DIR = Path("/workspace/data/finmultitime_hf")
random.seed(42)
def log(msg: str):
print(msg)
sys.stdout.flush()
# ========= 优化后的提示词设计 =========
# 设计原则:
# 1. 要求具体、可量化的分析
# 2. 结构化输出便于评估
# 3. 包含评分维度
SYSTEM_PROMPT_ZH = """你是一名资深金融量化分析师,擅长解读 K 线图和技术分析。
分析要求:
1. 基于 K 线形态、量价关系进行客观分析
2. 使用专业但易懂的金融术语
3. 结论需有明确依据,不可凭空臆测
4. 严格按照指定格式输出
评分标准(供参考):
- 趋势判断准确性:是否正确识别主趋势
- 形态识别能力:是否识别出关键 K 线形态
- 风险提示合理性:风险点是否切合实际
- 逻辑连贯性:分析是否前后一致
- 专业术语使用:是否正确使用金融术语"""
SYSTEM_PROMPT_EN = """You are a senior financial quantitative analyst specializing in K-line chart interpretation and technical analysis.
Analysis Requirements:
1. Provide objective analysis based on candlestick patterns and volume-price relationships
2. Use professional but understandable financial terminology
3. Conclusions must be evidence-based, no speculation
4. Strictly follow the specified output format
Evaluation Criteria (for reference):
- Trend Judgment Accuracy: Correctly identify the main trend
- Pattern Recognition: Identify key candlestick patterns
- Risk Assessment: Reasonable risk identification
- Logical Coherence: Consistent analysis throughout
- Professional Terminology: Correct use of financial terms"""
# ========= 优化后的任务模板 =========
def get_kline_reading_prompt_zh(stock_id: str, period: str) -> Tuple[str, str]:
"""K 线阅读任务 - 中文版 (优化后)"""
user_text = f"""<image>
这是股票 {stock_id} 在 {period} 期间的日 K 线图(包含价格和成交量)。
请从以下 5 个维度进行专业分析:
【1. 主趋势判断】
- 判断这段时间股价是:上涨趋势 / 下跌趋势 / 横盘震荡
- 给出判断依据(如:高点抬高、低点抬高 → 上涨趋势)
【2. 关键形态识别】
- 识别 1-2 个最明显的 K 线形态(如:锤子线、十字星、吞没形态、三只乌鸦等)
- 说明该形态出现的位置(前段/中段/末段)和技术含义
【3. 量价关系分析】
- 描述成交量变化趋势(放量/缩量/量价背离)
- 分析量价配合情况对趋势的支撑或警示作用
【4. 关键价位识别】
- 指出图中最重要的 1-2 个支撑位或阻力位区域
- 说明该价位的形成原因(如:多次回踩、密集成交区)
【5. 交易策略建议】
- 基于以上分析,给出交易偏向:
A) 逢低布局(看多)
B) 逢高减仓(看空)
C) 观望等待(中性)
- 给出 1 句话理由
注意:不要编造具体价格数值,只做定性分析。"""
nim_prompt = f"""请分析一张股票 {stock_id} 在 {period} 的日 K 线图。
要求严格按以下格式输出(每点 1-2 句话,总计 8-12 句):
【1. 主趋势判断】
趋势方向 + 判断依据
【2. 关键形态识别】
形态名称 + 出现位置 + 技术含义
【3. 量价关系分析】
量能变化 + 量价配合评价
【4. 关键价位识别】
支撑/阻力位 + 形成原因
【5. 交易策略建议】
交易偏向(A/B/C) + 理由
注意:基于典型走势特征进行分析,不编造具体数值。"""
return user_text, nim_prompt
def get_kline_reading_prompt_en(stock_id: str, period: str) -> Tuple[str, str]:
"""K 线阅读任务 - 英文版 (优化后)"""
user_text = f"""<image>
This is the daily K-line chart (with price and volume) for stock {stock_id} during {period}.
Please provide professional analysis from these 5 dimensions:
【1. Main Trend Judgment】
- Determine if the price is in: Uptrend / Downtrend / Sideways
- Provide evidence (e.g., higher highs and higher lows → uptrend)
【2. Key Pattern Recognition】
- Identify 1-2 most prominent candlestick patterns (e.g., hammer, doji, engulfing, three black crows)
- State the pattern's location (early/mid/late period) and technical significance
【3. Volume-Price Analysis】
- Describe volume trend (increasing/decreasing/divergence)
- Analyze how volume confirms or warns against the price trend
【4. Key Price Levels】
- Identify 1-2 most important support or resistance zones
- Explain how these levels were formed (e.g., multiple bounces, high-volume area)
【5. Trading Strategy Suggestion】
- Based on the above analysis, suggest trading bias:
A) Buy on dips (Bullish)
B) Sell on rallies (Bearish)
C) Wait and observe (Neutral)
- Give one sentence of reasoning
Note: Do not fabricate specific price values, only qualitative analysis."""
nim_prompt = f"""Analyze a daily K-line chart for stock {stock_id} during {period}.
Output strictly in this format (1-2 sentences per point, 8-12 sentences total):
【1. Main Trend Judgment】
Trend direction + evidence
【2. Key Pattern Recognition】
Pattern name + location + significance
【3. Volume-Price Analysis】
Volume trend + volume-price assessment
【4. Key Price Levels】
Support/resistance + formation reason
【5. Trading Strategy Suggestion】
Trading bias (A/B/C) + reasoning
Note: Analyze based on typical chart characteristics, don't fabricate specific values."""
return user_text, nim_prompt
def get_kline_trend_prompt_zh(stock_id: str, period: str) -> Tuple[str, str]:
"""K 线趋势分析任务 - 中文版 (优化后)"""
user_text = f"""<image>
这是股票 {stock_id} 在 {period} 期间的日 K 线图和收盘价时间序列。
请进行综合技术分析,从以下 5 个维度输出:
【1. 趋势阶段划分】
- 将该时段划分为 2-3 个明显阶段(如:初期上涨 → 中期震荡 → 末期回落)
- 每个阶段用一句话描述特征
【2. 波动特征分析】
- 描述价格波动的幅度和频率(剧烈波动/温和波动/窄幅整理)
- 识别最大的单日涨跌发生在哪个阶段
【3. 趋势强度评估】
- 使用 1-5 分评估趋势强度(1=极弱,5=极强)
- 说明评分依据(如:坡度、回调深度、持续时间)
【4. 转折点识别】
- 指出 1-2 个最重要的趋势转折点
- 分析转折的技术信号(如:放量长上影、跌破均线)
【5. 未来走势预判】
- 基于当前形态,判断短期(5-10 个交易日)可能走势:
A) 延续当前方向
B) 出现反转
C) 进入盘整
- 给出概率评估(高/中/低)和核心理由
注意:只基于走势形态分析,不考虑基本面。"""
nim_prompt = f"""请综合分析股票 {stock_id} 在 {period} 的 K 线走势。
严格按以下格式输出(每点 1-2 句话,总计 10-15 句):
【1. 趋势阶段划分】
2-3 个阶段划分 + 各阶段特征
【2. 波动特征分析】
波动描述 + 最大涨跌出现位置
【3. 趋势强度评估】
评分(1-5) + 评分依据
【4. 转折点识别】
转折点位置 + 技术信号
【5. 未来走势预判】
预判方向(A/B/C) + 概率(高/中/低) + 核心理由
注意:基于典型走势规律分析,不编造数值。"""
return user_text, nim_prompt
def get_kline_trend_prompt_en(stock_id: str, period: str) -> Tuple[str, str]:
"""K 线趋势分析任务 - 英文版 (优化后)"""
user_text = f"""<image>
This is the daily K-line chart and closing price time series for stock {stock_id} during {period}.
Please provide comprehensive technical analysis from these 5 dimensions:
【1. Trend Phase Division】
- Divide the period into 2-3 distinct phases (e.g., initial rise → mid consolidation → late decline)
- Describe each phase in one sentence
【2. Volatility Analysis】
- Describe price volatility magnitude and frequency (high/moderate/narrow range)
- Identify which phase had the largest single-day move
【3. Trend Strength Assessment】
- Rate trend strength from 1-5 (1=very weak, 5=very strong)
- Explain the rating basis (e.g., slope, pullback depth, duration)
【4. Turning Point Identification】
- Identify 1-2 most important trend reversal points
- Analyze the technical signals at these points (e.g., volume spike with long upper shadow)
【5. Future Outlook】
- Based on current pattern, predict short-term (5-10 trading days) direction:
A) Continue current trend
B) Reversal expected
C) Enter consolidation
- Provide probability assessment (High/Medium/Low) and key reasoning
Note: Analysis based on chart patterns only, no fundamentals."""
nim_prompt = f"""Provide comprehensive analysis for stock {stock_id} during {period}.
Output strictly in this format (1-2 sentences per point, 10-15 sentences total):
【1. Trend Phase Division】
2-3 phases + characteristics of each
【2. Volatility Analysis】
Volatility description + location of largest move
【3. Trend Strength Assessment】
Score (1-5) + basis for rating
【4. Turning Point Identification】
Turning points + technical signals
【5. Future Outlook】
Direction (A/B/C) + Probability (High/Medium/Low) + key reasoning
Note: Analyze based on typical pattern rules, don't fabricate values."""
return user_text, nim_prompt
# ========= NIM API 调用 =========
def call_nim(prompt: str, system_prompt: str, model_key: str) -> str:
"""调用 NIM API"""
model_name = NIM_MODELS.get(model_key, model_key)
headers = {
"Authorization": f"Bearer {NIM_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": model_name,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt},
],
"temperature": 0.3, # 降低温度提高一致性
"max_tokens": 1500, # 增加 token 以支持更长回答
}
try:
resp = requests.post(NIM_ENDPOINT, headers=headers, json=payload, timeout=180)
resp.raise_for_status()
data = resp.json()
content = data["choices"][0]["message"]["content"]
if content:
return content.strip()
return ""
except Exception as e:
log(f"[NIM:{model_key}] Error: {e}")
raise
def file_exists_any(paths: List[str]) -> List[str]:
return [p for p in paths if Path(p).is_file()]
def parse_period(image_name: str, market: str) -> str:
"""从图片名解析时间段"""
# 000001.SZ_2020_H1_candlestick.png
parts = image_name.replace("_candlestick.png", "").split("_")
if len(parts) >= 3:
year = parts[-2]
half = parts[-1]
if market == "HS300":
return f"{year}年{'上半年' if half == 'H1' else '下半年'}"
else:
return f"{year} {'H1' if half == 'H1' else 'H2'}"
return "某时间段"
# ========= 样本构建函数 =========
def build_kline_reading_sample(
model_key: str,
base_rec: Dict[str, Any],
image_path: str,
) -> Dict[str, Any]:
"""K 线阅读样本"""
stock_id = base_rec["stock_id"]
market = base_rec["market"]
period = parse_period(Path(image_path).name, market)
if market == "HS300":
user_text, nim_prompt = get_kline_reading_prompt_zh(stock_id, period)
system_prompt = SYSTEM_PROMPT_ZH
else:
user_text, nim_prompt = get_kline_reading_prompt_en(stock_id, period)
system_prompt = SYSTEM_PROMPT_EN
assistant = call_nim(nim_prompt, system_prompt, model_key)
return {
"id": None,
"image": Path(image_path).name,
"conversations": [
{"from": "human", "value": user_text},
{"from": "gpt", "value": assistant},
],
"task_type": "kline_reading",
"difficulty": "medium",
"images": [image_path],
"model": model_key,
"market": market,
"stock_id": stock_id,
"period": period,
}
def build_kline_trend_sample(
model_key: str,
base_rec: Dict[str, Any],
image_path: str,
ts_path: str,
) -> Dict[str, Any]:
"""K 线趋势分析样本"""
stock_id = base_rec["stock_id"]
market = base_rec["market"]
period = parse_period(Path(image_path).name, market)
if market == "HS300":
user_text, nim_prompt = get_kline_trend_prompt_zh(stock_id, period)
system_prompt = SYSTEM_PROMPT_ZH
else:
user_text, nim_prompt = get_kline_trend_prompt_en(stock_id, period)
system_prompt = SYSTEM_PROMPT_EN
assistant = call_nim(nim_prompt, system_prompt, model_key)
return {
"id": None,
"image": Path(image_path).name,
"conversations": [
{"from": "human", "value": user_text},
{"from": "gpt", "value": assistant},
],
"task_type": "kline_trend",
"difficulty": "hard",
"images": [image_path],
"timeseries_files": [ts_path],
"model": model_key,
"market": market,
"stock_id": stock_id,
"period": period,
}
# ========= 数据集生成 =========
def generate_dataset(
model_key: str,
max_samples: Optional[int] = None,
output_suffix: str = "",
) -> Tuple[str, List[Dict]]:
"""使用指定模型生成数据集"""
model_name_safe = model_key.replace("/", "_").replace(".", "_").replace("-", "_")
suffix = f"_{output_suffix}" if output_suffix else ""
output_path = OUTPUT_DIR / f"finmultitime_kline_llavaplus_{model_name_safe}{suffix}.json"
output_path.parent.mkdir(parents=True, exist_ok=True)
records: List[Dict[str, Any]] = []
with INPUT_INDEX.open("r", encoding="utf-8") as fin:
for line in fin:
if not line.strip():
continue
records.append(json.loads(line))
log(f"\n{'='*60}")
log(f"[MAIN] Total records: {len(records)}")
log(f"[MAIN] Model: {model_key} -> {NIM_MODELS.get(model_key, model_key)}")
log(f"[MAIN] Max samples: {max_samples or 'ALL'}")
log(f"[MAIN] Output: {output_path}")
log(f"{'='*60}\n")
all_samples: List[Dict[str, Any]] = []
count = 0
errors = 0
for rec in tqdm(records, desc=f"{model_key}"):
images = file_exists_any(rec.get("image_files", []))
ts_files = file_exists_any(rec.get("time_series_files", []))
if not images:
continue
# 交替任务类型
if count % 2 == 0 and ts_files:
tpl = "kline_trend"
else:
tpl = "kline_reading"
try:
if tpl == "kline_trend":
sample = build_kline_trend_sample(
model_key, rec, random.choice(images), random.choice(ts_files)
)
else:
sample = build_kline_reading_sample(
model_key, rec, random.choice(images)
)
except Exception as e:
log(f"[WARN] {rec['stock_id']}: {e}")
errors += 1
if errors > 20:
log(f"[ERROR] Too many errors ({errors}), stopping...")
break
continue
sample["id"] = f"{rec['market']}_{rec['stock_id']}_{tpl}_{count}"
all_samples.append(sample)
count += 1
if max_samples and count >= max_samples:
break
with output_path.open("w", encoding="utf-8") as f:
json.dump(all_samples, f, ensure_ascii=False, indent=2)
log(f"\n[OK] Generated {count} samples -> {output_path}")
return str(output_path), all_samples
def compare_models(sample_count: int = 100) -> Dict[str, Any]:
"""对比所有模型,生成各 100 个样本"""
results = {}
# 测试每个类别的所有模型
all_models = []
for category, models in MODEL_CATEGORIES.items():
for model in models:
all_models.append((category, model))
log(f"\n{'='*70}")
log(f"开始多模型对比测试")
log(f"每个模型生成 {sample_count} 个样本")
log(f"共测试 {len(all_models)} 个模型")
log(f"{'='*70}\n")
for category, model_key in all_models:
log(f"\n[{category}] {model_key}")
try:
output_path, samples = generate_dataset(
model_key,
max_samples=sample_count,
output_suffix="compare"
)
# 统计
total_chars = sum(len(s["conversations"][1]["value"]) for s in samples)
avg_chars = total_chars / len(samples) if samples else 0
results[model_key] = {
"category": category,
"sample_count": len(samples),
"avg_response_chars": avg_chars,
"output_path": output_path,
"status": "success",
}
except Exception as e:
log(f"[ERROR] {model_key}: {e}")
results[model_key] = {
"category": category,
"status": "failed",
"error": str(e),
}
# 保存对比结果
compare_result_path = OUTPUT_DIR / "model_comparison_results.json"
with compare_result_path.open("w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
log(f"\n[OK] Comparison results saved to {compare_result_path}")
return results
def print_comparison_report(results: Dict[str, Any]):
"""打印对比报告"""
print("\n" + "=" * 70)
print("模型对比报告")
print("=" * 70)
# 按类别分组
by_category = {}
for model, data in results.items():
cat = data.get("category", "未知")
if cat not in by_category:
by_category[cat] = []
by_category[cat].append((model, data))
for category, models in by_category.items():
print(f"\n[{category}]")
print("-" * 50)
for model, data in models:
if data.get("status") == "success":
avg_chars = data.get("avg_response_chars", 0)
count = data.get("sample_count", 0)
print(f" ✅ {model:30s} | 样本:{count:3d} | 平均长度:{avg_chars:.0f}字")
else:
print(f" ❌ {model:30s} | 失败: {data.get('error', '未知错误')[:30]}")
print("\n" + "=" * 70)
def list_models():
"""列出所有可用模型"""
print("\n" + "=" * 70)
print("NIM 可用模型列表")
print("=" * 70)
for category, models in MODEL_CATEGORIES.items():
print(f"\n[{category}]")
for key in models:
full_name = NIM_MODELS.get(key, key)
print(f" {key:30s} -> {full_name}")
print("\n" + "=" * 70)
def select_top_models(results: Dict[str, Any], top_n: int = 4) -> List[str]:
"""从对比结果中选出每个类别最强的模型,总共 top_n 个"""
# 按类别分组
by_category = {}
for model, data in results.items():
if data.get("status") != "success":
continue
cat = data.get("category", "未知")
if cat not in by_category:
by_category[cat] = []
by_category[cat].append((model, data))
# 每个类别选最强的
top_models = []
for category, models in by_category.items():
if not models:
continue
# 按回答长度排序(越长通常质量越好)
models.sort(key=lambda x: x[1].get("avg_response_chars", 0), reverse=True)
best_model, best_data = models[0]
top_models.append({
"model": best_model,
"category": category,
"avg_chars": best_data.get("avg_response_chars", 0),
"sample_count": best_data.get("sample_count", 0),
})
log(f" [{category}] 最强: {best_model} (平均 {best_data.get('avg_response_chars', 0):.0f} 字)")
# 按平均字数排序,取 TOP N
top_models.sort(key=lambda x: x["avg_chars"], reverse=True)
return [m["model"] for m in top_models[:top_n]]
def auto_full_pipeline(compare_samples: int = 100, top_n: int = 4):
"""自动完成全流程:对比 -> 选模型 -> 全量生成"""
log("\n" + "=" * 70)
log("🚀 自动全流程启动")
log(f" 阶段1: 每个模型生成 {compare_samples} 样本进行对比")
log(f" 阶段2: 选出 TOP {top_n} 模型")
log(f" 阶段3: 用 TOP 模型生成全量数据")
log("=" * 70)
# 阶段 1: 对比测试
log("\n" + "=" * 70)
log("[阶段 1/3] 多模型对比测试")
log("=" * 70)
results = compare_models(compare_samples)
print_comparison_report(results)
# 阶段 2: 选出最强模型
log("\n" + "=" * 70)
log("[阶段 2/3] 选出每类最强模型")
log("=" * 70)
top_models = select_top_models(results, top_n)
if not top_models:
log("[ERROR] 没有成功的模型,无法继续")
return
log(f"\n最终选出 {len(top_models)} 个模型:")
for i, model in enumerate(top_models, 1):
log(f" {i}. {model}")
# 阶段 3: 全量生成
log("\n" + "=" * 70)
log("[阶段 3/3] 使用 TOP 模型生成全量数据")
log("=" * 70)
for i, model in enumerate(top_models, 1):
log(f"\n[{i}/{len(top_models)}] 生成全量: {model}")
try:
output_path, samples = generate_dataset(model, max_samples=None)
log(f" ✅ 完成! {len(samples)} 样本 -> {output_path}")
except Exception as e:
log(f" ❌ 失败: {e}")
# 完成
log("\n" + "=" * 70)
log("🎉 全部任务完成!")
log("=" * 70)
log(f"对比结果: {OUTPUT_DIR / 'model_comparison_results.json'}")
log(f"数据目录: {OUTPUT_DIR}")
def main():
"""主函数"""
import argparse
parser = argparse.ArgumentParser(description="NIM 多模型 K 线图数据生成 (LLaVA 格式)")
parser.add_argument("--model", "-m", type=str, default=None,
help="指定单个模型生成")
parser.add_argument("--max-samples", "-n", type=int, default=None,
help="最大样本数")
parser.add_argument("--list", "-l", action="store_true",
help="列出所有模型")
parser.add_argument("--compare", "-c", type=int, default=None,
metavar="N", help="对比所有模型,每个生成 N 个样本")
parser.add_argument("--auto", action="store_true",
help="自动全流程:对比(100样本) -> 选TOP4 -> 全量生成")
parser.add_argument("--top-n", type=int, default=4,
help="选出多少个最强模型 (默认: 4)")
args = parser.parse_args()
if args.list:
list_models()
return
if args.auto:
compare_n = args.compare if args.compare else 100
auto_full_pipeline(compare_samples=compare_n, top_n=args.top_n)
return
if args.compare:
results = compare_models(args.compare)
print_comparison_report(results)
return
if args.model:
generate_dataset(args.model, args.max_samples)
return
# 默认:显示帮助
parser.print_help()
if __name__ == "__main__":
main()
|