Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/cli.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/logger.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/version.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__init__.py +8 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_env.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_eval.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_init.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_pdf.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_text.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_webui.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/copy_funcs.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/paths.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/utils.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_env.py +86 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_eval.py +467 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_init.py +136 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_pdf.py +526 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_text.py +671 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_webui.py +324 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/copy_funcs.py +98 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_api.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_local.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_api.py +243 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_local.py +245 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/paths.py +38 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/path_to_jsonl_script.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/pdf_to_qa_pipeline.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/llama_factory_trainer.py +369 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/path_to_jsonl_script.py +237 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/pdf_to_qa_pipeline.py +132 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/merge_filter_qa_pairs.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/text_to_qa_pipeline.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/llama_factory_trainer.py +369 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/merge_filter_qa_pairs.py +300 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/text_to_qa_pipeline.py +111 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/utils.py +16 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__init__.py +18 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/llm_serving.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/operator.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/prompt.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/wrapper.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/llm_serving.py +35 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/operator.py +28 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/prompt.py +107 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/wrapper.py +14 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (628 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/cli.cpython-311.pyc
ADDED
|
Binary file (24.7 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/logger.cpython-311.pyc
ADDED
|
Binary file (5.88 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/__pycache__/version.cpython-311.pyc
ADDED
|
Binary file (1.39 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .cli_init import cli_init
|
| 2 |
+
from .cli_env import cli_env
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"cli_env",
|
| 7 |
+
"cli_init"
|
| 8 |
+
]
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (337 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_env.cpython-311.pyc
ADDED
|
Binary file (4.73 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_eval.cpython-311.pyc
ADDED
|
Binary file (26.1 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_init.cpython-311.pyc
ADDED
|
Binary file (7.06 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_pdf.cpython-311.pyc
ADDED
|
Binary file (25.3 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_text.cpython-311.pyc
ADDED
|
Binary file (31.8 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/cli_webui.cpython-311.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/copy_funcs.cpython-311.pyc
ADDED
|
Binary file (5.66 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/paths.cpython-311.pyc
ADDED
|
Binary file (2.29 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (1.33 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_env.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import platform
|
| 4 |
+
from colorama import init, Fore, Style
|
| 5 |
+
from dataflow import __version__
|
| 6 |
+
import importlib.metadata
|
| 7 |
+
from .paths import DataFlowPath
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def is_torch_cuda_available():
|
| 11 |
+
"""
|
| 12 |
+
Check if CUDA is available for PyTorch.
|
| 13 |
+
"""
|
| 14 |
+
return torch.cuda.is_available()
|
| 15 |
+
|
| 16 |
+
def get_env_info():
|
| 17 |
+
info = {
|
| 18 |
+
"`Dataflow` version": __version__,
|
| 19 |
+
"`Dataflow` install path": DataFlowPath.get_dataflow_dir(),
|
| 20 |
+
"Platform": platform.platform(),
|
| 21 |
+
"Python version": platform.python_version(),
|
| 22 |
+
"PyTorch version": torch.__version__,
|
| 23 |
+
"Torchvision version": torch.__version__,
|
| 24 |
+
}
|
| 25 |
+
if is_torch_cuda_available():
|
| 26 |
+
info["PyTorch version"] += " (GPU)"
|
| 27 |
+
info["GPU type"] = torch.cuda.get_device_name()
|
| 28 |
+
info["GPU number"] = torch.cuda.device_count()
|
| 29 |
+
info["GPU memory"] = f"{torch.cuda.mem_get_info()[1] / (1024**3):.2f}GB"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import deepspeed # type: ignore
|
| 34 |
+
|
| 35 |
+
info["DeepSpeed version"] = deepspeed.__version__
|
| 36 |
+
except Exception:
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
import bitsandbytes # type: ignore
|
| 41 |
+
|
| 42 |
+
info["Bitsandbytes version"] = bitsandbytes.__version__
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
import vllm
|
| 48 |
+
|
| 49 |
+
info["vLLM version"] = vllm.__version__
|
| 50 |
+
except Exception:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
import sglang
|
| 55 |
+
info["SGLang version"] = sglang.__version__
|
| 56 |
+
except Exception:
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
mineru_version = importlib.metadata.version("mineru")
|
| 61 |
+
info["MinerU version"] = mineru_version
|
| 62 |
+
except Exception:
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
import subprocess
|
| 67 |
+
# get the dir of imdlbenco package
|
| 68 |
+
imdlbenco_dir = os.path.dirname(os.path.abspath(__file__))
|
| 69 |
+
# move to this dir and get the git commit hash in a subprocess
|
| 70 |
+
# but don't change the current working directory
|
| 71 |
+
os.chdir(imdlbenco_dir)
|
| 72 |
+
commit_info = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True)
|
| 73 |
+
commit_hash = commit_info.stdout.strip()
|
| 74 |
+
info["Git commit"] = commit_hash
|
| 75 |
+
except Exception:
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
print(Fore.BLUE + "=" * os.get_terminal_size().columns + Style.RESET_ALL)
|
| 79 |
+
print("\n" + "\n".join([f"- {key}: {value}" for key, value in info.items()]) + "\n")
|
| 80 |
+
print(Fore.BLUE + "=" * os.get_terminal_size().columns + Style.RESET_ALL)
|
| 81 |
+
|
| 82 |
+
def cli_env():
|
| 83 |
+
get_env_info()
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
print(get_env_info())
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_eval.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# dataflow/cli_funcs/cli_eval.py
|
| 2 |
+
"""DataFlow 评估工具"""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import json
|
| 6 |
+
import shutil
|
| 7 |
+
import importlib.util
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import List, Dict, Any
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from dataflow import get_logger
|
| 12 |
+
from dataflow.serving import LocalModelLLMServing_vllm
|
| 13 |
+
from dataflow.operators.reasoning import ReasoningAnswerGenerator
|
| 14 |
+
from dataflow.prompts.reasoning.diy import DiyAnswerGeneratorPrompt
|
| 15 |
+
from dataflow.utils.storage import FileStorage
|
| 16 |
+
import torch
|
| 17 |
+
import gc
|
| 18 |
+
|
| 19 |
+
logger = get_logger()
|
| 20 |
+
|
| 21 |
+
DEFAULT_ANSWER_PROMPT = """Please answer the following question based on the provided academic literature. Your response should:
|
| 22 |
+
1. Provide accurate information from the source material
|
| 23 |
+
2. Include relevant scientific reasoning and methodology
|
| 24 |
+
3. Reference specific findings, data, or conclusions when applicable
|
| 25 |
+
4. Maintain academic rigor and precision in your explanation
|
| 26 |
+
|
| 27 |
+
Question: {question}
|
| 28 |
+
|
| 29 |
+
Answer:"""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class EvaluationPipeline:
|
| 33 |
+
"""评估管道"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, config: Dict[str, Any]):
|
| 36 |
+
self.config = config
|
| 37 |
+
self.prepared_models = []
|
| 38 |
+
self.generated_files = []
|
| 39 |
+
|
| 40 |
+
def run(self) -> bool:
|
| 41 |
+
try:
|
| 42 |
+
# 1. 获取目标模型
|
| 43 |
+
self.target_models = self._get_target_models()
|
| 44 |
+
if not self.target_models:
|
| 45 |
+
logger.error("No TARGET_MODELS found in config")
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
self.prepared_models = self._prepare_models()
|
| 49 |
+
if not self.prepared_models:
|
| 50 |
+
return False
|
| 51 |
+
|
| 52 |
+
# 2. 生成答案
|
| 53 |
+
self.generated_files = self._generate_answers()
|
| 54 |
+
if not self.generated_files:
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
# 3. 执行评估
|
| 58 |
+
results = self._run_evaluation()
|
| 59 |
+
|
| 60 |
+
# 4. 生成报告
|
| 61 |
+
self._generate_report(results)
|
| 62 |
+
|
| 63 |
+
return True
|
| 64 |
+
|
| 65 |
+
except Exception as e:
|
| 66 |
+
logger.error(f"Evaluation failed: {e}")
|
| 67 |
+
import traceback
|
| 68 |
+
traceback.print_exc()
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
def _get_target_models(self) -> List:
|
| 72 |
+
"""获取目标模型列表"""
|
| 73 |
+
target_config = self.config.get("TARGET_MODELS", [])
|
| 74 |
+
|
| 75 |
+
if not isinstance(target_config, list):
|
| 76 |
+
logger.error(f"TARGET_MODELS must be a list, got {type(target_config)}")
|
| 77 |
+
return []
|
| 78 |
+
|
| 79 |
+
if not target_config:
|
| 80 |
+
logger.error("TARGET_MODELS is empty")
|
| 81 |
+
return []
|
| 82 |
+
|
| 83 |
+
return target_config
|
| 84 |
+
|
| 85 |
+
def _prepare_models(self) -> List[Dict]:
|
| 86 |
+
"""准备模型信息"""
|
| 87 |
+
prepared = []
|
| 88 |
+
default_config = self.config.get("DEFAULT_MODEL_CONFIG", {})
|
| 89 |
+
|
| 90 |
+
for idx, item in enumerate(self.target_models, 1):
|
| 91 |
+
if isinstance(item, str):
|
| 92 |
+
model_info = {
|
| 93 |
+
"name": Path(item).name,
|
| 94 |
+
"path": item,
|
| 95 |
+
"type": "local",
|
| 96 |
+
**default_config
|
| 97 |
+
}
|
| 98 |
+
elif isinstance(item, dict):
|
| 99 |
+
if "path" not in item:
|
| 100 |
+
logger.error(f"Model at index {idx} missing 'path'")
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
model_info = {
|
| 104 |
+
**default_config,
|
| 105 |
+
**item,
|
| 106 |
+
"name": item.get("name", Path(item["path"]).name),
|
| 107 |
+
"type": "local"
|
| 108 |
+
}
|
| 109 |
+
else:
|
| 110 |
+
logger.error(f"Invalid model format at index {idx}")
|
| 111 |
+
continue
|
| 112 |
+
|
| 113 |
+
prepared.append(model_info)
|
| 114 |
+
|
| 115 |
+
return prepared
|
| 116 |
+
|
| 117 |
+
def _clear_vllm_cache(self):
|
| 118 |
+
"""清理 vLLM 缓存"""
|
| 119 |
+
cache_paths = [
|
| 120 |
+
Path.home() / ".cache" / "vllm" / "torch_compile_cache",
|
| 121 |
+
Path.home() / ".cache" / "vllm"
|
| 122 |
+
]
|
| 123 |
+
|
| 124 |
+
for cache_path in cache_paths:
|
| 125 |
+
if cache_path.exists():
|
| 126 |
+
try:
|
| 127 |
+
shutil.rmtree(cache_path)
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.warning(f"Failed to clear cache: {e}")
|
| 130 |
+
|
| 131 |
+
def _generate_answers(self) -> List[Dict]:
|
| 132 |
+
"""生成模型答案 - 每个模型只加载一次"""
|
| 133 |
+
generated_files = []
|
| 134 |
+
bench_config_list = self.config.get("BENCH_CONFIG", [])
|
| 135 |
+
|
| 136 |
+
if not bench_config_list:
|
| 137 |
+
logger.error("No BENCH_CONFIG found")
|
| 138 |
+
return []
|
| 139 |
+
|
| 140 |
+
# 外层循环:遍历模型
|
| 141 |
+
for idx, model_info in enumerate(self.prepared_models, 1):
|
| 142 |
+
llm_serving = None
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
logger.info(f"[{idx}/{len(self.prepared_models)}] Loading model: {model_info['name']}")
|
| 146 |
+
|
| 147 |
+
# 清理缓存(每个模型加载前清理一次)
|
| 148 |
+
self._clear_vllm_cache()
|
| 149 |
+
|
| 150 |
+
# 加载模型
|
| 151 |
+
llm_serving = LocalModelLLMServing_vllm(
|
| 152 |
+
hf_model_name_or_path=model_info['path'],
|
| 153 |
+
vllm_tensor_parallel_size=model_info.get('vllm_tensor_parallel_size', 2),
|
| 154 |
+
vllm_temperature=model_info.get('vllm_temperature', 0.7),
|
| 155 |
+
vllm_top_p=model_info.get('vllm_top_p', 0.9),
|
| 156 |
+
vllm_max_tokens=model_info.get('vllm_max_tokens', 1024),
|
| 157 |
+
vllm_repetition_penalty=model_info.get('vllm_repetition_penalty', 1.0),
|
| 158 |
+
vllm_seed=model_info.get('vllm_seed', None),
|
| 159 |
+
vllm_gpu_memory_utilization=model_info.get('vllm_gpu_memory_utilization', 0.8)
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# 内层循环:遍历bench(复用模型)
|
| 163 |
+
for bench_idx, bench_config in enumerate(bench_config_list, 1):
|
| 164 |
+
answer_generator = None
|
| 165 |
+
storage = None
|
| 166 |
+
|
| 167 |
+
try:
|
| 168 |
+
bench_name = bench_config.get("name", "default")
|
| 169 |
+
logger.info(f" [{bench_idx}/{len(bench_config_list)}] Processing bench: {bench_name}")
|
| 170 |
+
|
| 171 |
+
input_file = bench_config["input_file"]
|
| 172 |
+
if not Path(input_file).exists():
|
| 173 |
+
logger.error(f"Input file not found: {input_file}")
|
| 174 |
+
continue
|
| 175 |
+
|
| 176 |
+
question_key = bench_config.get("question_key", "input")
|
| 177 |
+
bench_output_dir = bench_config.get("output_dir", "./eval_results")
|
| 178 |
+
|
| 179 |
+
# 设置缓存和输出目录
|
| 180 |
+
cache_dir = model_info.get('cache_dir', './.cache/eval')
|
| 181 |
+
Path(cache_dir).mkdir(parents=True, exist_ok=True)
|
| 182 |
+
Path(bench_output_dir).mkdir(parents=True, exist_ok=True)
|
| 183 |
+
|
| 184 |
+
output_file = f"{bench_output_dir}/{bench_name}_answers_{model_info['name']}.json"
|
| 185 |
+
|
| 186 |
+
# 答案生成器(复用llm_serving)
|
| 187 |
+
custom_prompt = model_info.get('answer_prompt', DEFAULT_ANSWER_PROMPT)
|
| 188 |
+
answer_generator = ReasoningAnswerGenerator(
|
| 189 |
+
llm_serving=llm_serving,
|
| 190 |
+
prompt_template=DiyAnswerGeneratorPrompt(custom_prompt)
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# 存储
|
| 194 |
+
cache_path = f"{cache_dir}/{bench_name}_{model_info['name']}_generation"
|
| 195 |
+
storage = FileStorage(
|
| 196 |
+
first_entry_file_name=input_file,
|
| 197 |
+
cache_path=cache_path,
|
| 198 |
+
file_name_prefix=model_info.get('file_prefix', 'answer_gen'),
|
| 199 |
+
cache_type=model_info.get('cache_type', 'json')
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# 运行生成
|
| 203 |
+
answer_generator.run(
|
| 204 |
+
storage=storage.step(),
|
| 205 |
+
input_key=question_key,
|
| 206 |
+
output_key=model_info.get('output_key', 'model_generated_answer')
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# 保存结果
|
| 210 |
+
file_prefix = model_info.get('file_prefix', 'answer_gen')
|
| 211 |
+
cache_type = model_info.get('cache_type', 'json')
|
| 212 |
+
pattern = f"{file_prefix}_step*.{cache_type}"
|
| 213 |
+
matching_files = sorted(Path(cache_path).glob(pattern))
|
| 214 |
+
|
| 215 |
+
if matching_files:
|
| 216 |
+
gen_file = matching_files[-1]
|
| 217 |
+
shutil.copy2(gen_file, output_file)
|
| 218 |
+
generated_files.append({
|
| 219 |
+
"model_name": model_info['name'],
|
| 220 |
+
"model_path": model_info['path'],
|
| 221 |
+
"file_path": output_file,
|
| 222 |
+
"bench_name": bench_name
|
| 223 |
+
})
|
| 224 |
+
logger.success(f" ✓ Generated answers for {bench_name}")
|
| 225 |
+
else:
|
| 226 |
+
logger.error(f"No generated file found in {cache_path}")
|
| 227 |
+
continue
|
| 228 |
+
|
| 229 |
+
except Exception as e:
|
| 230 |
+
logger.error(f"Failed to process bench {bench_name}: {e}")
|
| 231 |
+
import traceback
|
| 232 |
+
traceback.print_exc()
|
| 233 |
+
continue
|
| 234 |
+
|
| 235 |
+
finally:
|
| 236 |
+
# 清理bench级别的资源
|
| 237 |
+
if answer_generator is not None:
|
| 238 |
+
del answer_generator
|
| 239 |
+
if storage is not None:
|
| 240 |
+
del storage
|
| 241 |
+
gc.collect()
|
| 242 |
+
|
| 243 |
+
except Exception as e:
|
| 244 |
+
logger.error(f"Failed to load model {model_info['name']}: {e}")
|
| 245 |
+
import traceback
|
| 246 |
+
traceback.print_exc()
|
| 247 |
+
continue
|
| 248 |
+
|
| 249 |
+
finally:
|
| 250 |
+
# 清理模型级别的资源
|
| 251 |
+
if llm_serving is not None:
|
| 252 |
+
logger.info(f"Unloading model: {model_info['name']}")
|
| 253 |
+
del llm_serving
|
| 254 |
+
gc.collect()
|
| 255 |
+
if torch.cuda.is_available():
|
| 256 |
+
torch.cuda.empty_cache()
|
| 257 |
+
torch.cuda.synchronize()
|
| 258 |
+
|
| 259 |
+
return generated_files
|
| 260 |
+
|
| 261 |
+
def _run_evaluation(self) -> List[Dict]:
|
| 262 |
+
"""运行评估"""
|
| 263 |
+
try:
|
| 264 |
+
logger.info("Loading judge model...")
|
| 265 |
+
judge_serving = self.config["create_judge_serving"]()
|
| 266 |
+
logger.info("✓ Judge model loaded")
|
| 267 |
+
except Exception as e:
|
| 268 |
+
logger.error(f"Failed to create judge: {e}")
|
| 269 |
+
return []
|
| 270 |
+
|
| 271 |
+
results = []
|
| 272 |
+
eval_config = self.config.get("EVALUATOR_RUN_CONFIG", {})
|
| 273 |
+
|
| 274 |
+
total_evals = len(self.generated_files)
|
| 275 |
+
|
| 276 |
+
for eval_idx, file_info in enumerate(self.generated_files, 1):
|
| 277 |
+
try:
|
| 278 |
+
bench_name = file_info.get('bench_name', 'unknown')
|
| 279 |
+
model_name = file_info['model_name']
|
| 280 |
+
|
| 281 |
+
logger.info(f"\n[Eval {eval_idx}/{total_evals}] {model_name} × {bench_name}")
|
| 282 |
+
|
| 283 |
+
# 找到对应的bench配置
|
| 284 |
+
bench_config = None
|
| 285 |
+
for bc in self.config.get("BENCH_CONFIG", []):
|
| 286 |
+
if bc.get("name") == bench_name:
|
| 287 |
+
bench_config = bc
|
| 288 |
+
break
|
| 289 |
+
|
| 290 |
+
if not bench_config:
|
| 291 |
+
logger.warning(f" ⚠️ No bench config found")
|
| 292 |
+
continue
|
| 293 |
+
|
| 294 |
+
eval_output_dir = bench_config.get("eval_output_dir", "./eval_results")
|
| 295 |
+
|
| 296 |
+
# 执行评估
|
| 297 |
+
logger.info(f" 📊 Evaluating...")
|
| 298 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 299 |
+
result_file = f"{eval_output_dir}/{timestamp}_{model_name}/result.json"
|
| 300 |
+
Path(result_file).parent.mkdir(parents=True, exist_ok=True)
|
| 301 |
+
|
| 302 |
+
storage = self.config["create_storage"](
|
| 303 |
+
file_info["file_path"],
|
| 304 |
+
f"./.cache/eval/{model_name}",
|
| 305 |
+
bench_name
|
| 306 |
+
)
|
| 307 |
+
evaluator = self.config["create_evaluator"](judge_serving, result_file)
|
| 308 |
+
|
| 309 |
+
evaluator.run(
|
| 310 |
+
storage=storage.step(),
|
| 311 |
+
input_test_answer_key=eval_config.get("input_test_answer_key", "model_generated_answer"),
|
| 312 |
+
input_gt_answer_key=eval_config.get("input_gt_answer_key", "output"),
|
| 313 |
+
input_question_key=eval_config.get("input_question_key", "input")
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
if Path(result_file).exists():
|
| 317 |
+
with open(result_file, 'r') as f:
|
| 318 |
+
data = json.load(f)
|
| 319 |
+
if data:
|
| 320 |
+
result_data = data[0].copy()
|
| 321 |
+
result_data["model_name"] = model_name
|
| 322 |
+
result_data["bench_name"] = bench_name
|
| 323 |
+
results.append(result_data)
|
| 324 |
+
logger.info(f" ✓ Accuracy: {result_data.get('accuracy', 0):.3f}")
|
| 325 |
+
|
| 326 |
+
except Exception as e:
|
| 327 |
+
logger.error(f" ✗ Evaluation failed: {e}")
|
| 328 |
+
import traceback
|
| 329 |
+
traceback.print_exc()
|
| 330 |
+
continue
|
| 331 |
+
|
| 332 |
+
logger.info(f"\n✓ Evaluation complete: {len(results)} results")
|
| 333 |
+
return results
|
| 334 |
+
|
| 335 |
+
def _generate_report(self, results: List[Dict]):
|
| 336 |
+
"""生成报告 - 支持批量bench独立输出"""
|
| 337 |
+
if not results:
|
| 338 |
+
logger.warning("No results")
|
| 339 |
+
return
|
| 340 |
+
|
| 341 |
+
# 打印报告
|
| 342 |
+
print("\n" + "="*80)
|
| 343 |
+
print("EVALUATION RESULTS - ALL BENCHES & MODELS")
|
| 344 |
+
print("="*80)
|
| 345 |
+
|
| 346 |
+
# 按准确率排序
|
| 347 |
+
sorted_results = sorted(results, key=lambda x: x.get("accuracy", 0), reverse=True)
|
| 348 |
+
|
| 349 |
+
for i, r in enumerate(sorted_results, 1):
|
| 350 |
+
print(f"{i}. [{r.get('bench_name', 'unknown')}] {r['model_name']}")
|
| 351 |
+
print(f" Accuracy: {r.get('accuracy', 0):.3f}")
|
| 352 |
+
print(f" Total: {r.get('total_samples', 0)}")
|
| 353 |
+
print(f" Matched: {r.get('matched_samples', 0)}")
|
| 354 |
+
print()
|
| 355 |
+
|
| 356 |
+
# 按bench分组保存结果
|
| 357 |
+
bench_config_list = self.config.get("BENCH_CONFIG", [])
|
| 358 |
+
|
| 359 |
+
# 为每个bench单独保存结果
|
| 360 |
+
bench_groups = {}
|
| 361 |
+
for result in sorted_results:
|
| 362 |
+
bench_name = result.get('bench_name', 'unknown')
|
| 363 |
+
if bench_name not in bench_groups:
|
| 364 |
+
bench_groups[bench_name] = []
|
| 365 |
+
bench_groups[bench_name].append(result)
|
| 366 |
+
|
| 367 |
+
# 保存���个bench的结果到各自的output_dir
|
| 368 |
+
for bench_name, bench_results in bench_groups.items():
|
| 369 |
+
# 找到对应bench的配置
|
| 370 |
+
bench_output_dir = "./eval_results" # 默认值
|
| 371 |
+
for bench_config in bench_config_list:
|
| 372 |
+
if bench_config.get("name") == bench_name:
|
| 373 |
+
bench_output_dir = bench_config.get("output_dir", "./eval_results")
|
| 374 |
+
break
|
| 375 |
+
|
| 376 |
+
# 保存该bench的结果
|
| 377 |
+
report_file = f"{bench_output_dir}/results.json"
|
| 378 |
+
Path(report_file).parent.mkdir(parents=True, exist_ok=True)
|
| 379 |
+
|
| 380 |
+
report_data = {
|
| 381 |
+
"bench_name": bench_name,
|
| 382 |
+
"timestamp": datetime.now().isoformat(),
|
| 383 |
+
"total_evaluations": len(bench_results),
|
| 384 |
+
"results": bench_results
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
with open(report_file, 'w', encoding='utf-8') as f:
|
| 388 |
+
json.dump(report_data, f, ensure_ascii=False, indent=2)
|
| 389 |
+
|
| 390 |
+
print(f"Bench '{bench_name}' results saved to: {report_file}")
|
| 391 |
+
|
| 392 |
+
# 另外保存一个汇总文件(包含所有bench)
|
| 393 |
+
all_results_file = "./eval_results/all_results.json"
|
| 394 |
+
Path(all_results_file).parent.mkdir(parents=True, exist_ok=True)
|
| 395 |
+
|
| 396 |
+
all_report_data = {
|
| 397 |
+
"timestamp": datetime.now().isoformat(),
|
| 398 |
+
"total_evaluations": len(sorted_results),
|
| 399 |
+
"total_benches": len(bench_groups),
|
| 400 |
+
"results": sorted_results
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
with open(all_results_file, 'w', encoding='utf-8') as f:
|
| 404 |
+
json.dump(all_report_data, f, ensure_ascii=False, indent=2)
|
| 405 |
+
|
| 406 |
+
print("="*80)
|
| 407 |
+
print(f"All results summary saved to: {all_results_file}")
|
| 408 |
+
print("="*80)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
class DataFlowEvalCLI:
|
| 412 |
+
"""CLI工具"""
|
| 413 |
+
|
| 414 |
+
def __init__(self):
|
| 415 |
+
self.current_dir = Path.cwd()
|
| 416 |
+
|
| 417 |
+
def _get_template_path(self, eval_type: str) -> Path:
|
| 418 |
+
current_file = Path(__file__)
|
| 419 |
+
dataflow_dir = current_file.parent.parent
|
| 420 |
+
return dataflow_dir / "cli_funcs" / "eval_pipeline" / f"eval_{eval_type}.py"
|
| 421 |
+
|
| 422 |
+
def init_eval_files(self):
|
| 423 |
+
"""初始化配置文件"""
|
| 424 |
+
files = [("eval_api.py", "api"), ("eval_local.py", "local")]
|
| 425 |
+
|
| 426 |
+
existing = [f for f, _ in files if (self.current_dir / f).exists()]
|
| 427 |
+
if existing:
|
| 428 |
+
if input(f"{', '.join(existing)} exists. Overwrite? (y/n): ").lower() != 'y':
|
| 429 |
+
return False
|
| 430 |
+
|
| 431 |
+
for filename, eval_type in files:
|
| 432 |
+
try:
|
| 433 |
+
template = self._get_template_path(eval_type)
|
| 434 |
+
if not template.exists():
|
| 435 |
+
logger.error(f"Template not found: {template}")
|
| 436 |
+
continue
|
| 437 |
+
shutil.copy2(template, self.current_dir / filename)
|
| 438 |
+
logger.info(f"Created: {filename}")
|
| 439 |
+
except Exception as e:
|
| 440 |
+
logger.error(f"Failed: {e}")
|
| 441 |
+
logger.info("You must modified the eval_api.py or eval_local.py before you run dataflow eval api/local")
|
| 442 |
+
return True
|
| 443 |
+
|
| 444 |
+
def run_eval_file(self, eval_file: str):
|
| 445 |
+
"""运行评估"""
|
| 446 |
+
config_path = self.current_dir / eval_file
|
| 447 |
+
|
| 448 |
+
if not config_path.exists():
|
| 449 |
+
logger.error(f"Config not found: {eval_file}")
|
| 450 |
+
return False
|
| 451 |
+
try:
|
| 452 |
+
spec = importlib.util.spec_from_file_location("config", config_path)
|
| 453 |
+
module = importlib.util.module_from_spec(spec)
|
| 454 |
+
spec.loader.exec_module(module)
|
| 455 |
+
|
| 456 |
+
config = module.get_evaluator_config()
|
| 457 |
+
return run_evaluation(config)
|
| 458 |
+
|
| 459 |
+
except Exception as e:
|
| 460 |
+
logger.error(f"Failed: {e}")
|
| 461 |
+
return False
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def run_evaluation(config):
|
| 465 |
+
"""运行评估"""
|
| 466 |
+
pipeline = EvaluationPipeline(config)
|
| 467 |
+
return pipeline.run()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_init.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Optional
|
| 4 |
+
from colorama import init, Fore, Style
|
| 5 |
+
from .paths import DataFlowPath
|
| 6 |
+
from .copy_funcs import copy_files_without_recursion, copy_file, copy_files_recursively
|
| 7 |
+
from .utils import _echo
|
| 8 |
+
|
| 9 |
+
def _copy_scripts():
|
| 10 |
+
target_dir = os.getcwd()
|
| 11 |
+
if not os.path.exists(target_dir):
|
| 12 |
+
os.makedirs(target_dir)
|
| 13 |
+
|
| 14 |
+
# script_path = DataFlowPath.get_dataflow_scripts_dir()
|
| 15 |
+
|
| 16 |
+
copy_files_recursively(DataFlowPath.get_dataflow_scripts_dir(), target_dir)
|
| 17 |
+
|
| 18 |
+
def _copy_pipelines():
|
| 19 |
+
target_dir = os.getcwd()
|
| 20 |
+
if not os.path.exists(target_dir):
|
| 21 |
+
os.makedirs(target_dir)
|
| 22 |
+
copy_files_recursively(DataFlowPath.get_dataflow_pipelines_dir(), target_dir)
|
| 23 |
+
# Copy pipelines
|
| 24 |
+
|
| 25 |
+
def _copy_playground():
|
| 26 |
+
target_dir = os.getcwd()
|
| 27 |
+
if not os.path.exists(target_dir):
|
| 28 |
+
os.makedirs(target_dir)
|
| 29 |
+
copy_files_recursively(DataFlowPath.get_dataflow_playground_dir(), target_dir)
|
| 30 |
+
|
| 31 |
+
def _copy_examples():
|
| 32 |
+
target_dir = os.path.join(os.getcwd(), "example_data")
|
| 33 |
+
if not os.path.exists(target_dir):
|
| 34 |
+
os.makedirs(target_dir)
|
| 35 |
+
copy_files_recursively(DataFlowPath.get_dataflow_example_dir(), target_dir)
|
| 36 |
+
|
| 37 |
+
def cli_init(subcommand):
|
| 38 |
+
print(f'{Fore.GREEN}Initializing in current working directory...{Style.RESET_ALL}')
|
| 39 |
+
|
| 40 |
+
# base initialize that only contain default scripts
|
| 41 |
+
if subcommand == "base":
|
| 42 |
+
_copy_pipelines()
|
| 43 |
+
_copy_examples()
|
| 44 |
+
_copy_playground()
|
| 45 |
+
# if subcommand == "model_zoo":
|
| 46 |
+
# _copy_train_scripts()
|
| 47 |
+
# _copy_demo_runs()
|
| 48 |
+
# _copy_demo_configs()
|
| 49 |
+
# _copy_dataset_json()
|
| 50 |
+
# # base initialize that only contain default scripts
|
| 51 |
+
# if subcommand == "backbone":
|
| 52 |
+
# _copy_train_scripts()
|
| 53 |
+
# _copy_demo_runs()
|
| 54 |
+
# _copy_demo_configs()
|
| 55 |
+
# _copy_dataset_json()
|
| 56 |
+
# print(f'{Fore.GREEN}Successfully initialized IMDLBenCo scripts.{Style.RESET_ALL}')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def init_repo_scaffold(
|
| 60 |
+
no_input: bool = False,
|
| 61 |
+
context: Optional[dict] = None,
|
| 62 |
+
) -> None:
|
| 63 |
+
"""
|
| 64 |
+
Initialize a DataFlow repository using the built-in scaffold template.
|
| 65 |
+
"""
|
| 66 |
+
import os
|
| 67 |
+
from pathlib import Path
|
| 68 |
+
from colorama import Fore, Style
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
from cookiecutter.main import cookiecutter
|
| 72 |
+
except ImportError:
|
| 73 |
+
raise RuntimeError(
|
| 74 |
+
"cookiecutter is not installed. "
|
| 75 |
+
"Please run: pip install cookiecutter"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
from .paths import DataFlowPath
|
| 79 |
+
|
| 80 |
+
template_path = DataFlowPath.get_dataflow_scaffold_dir()
|
| 81 |
+
output_dir = Path.cwd()
|
| 82 |
+
context = context or {}
|
| 83 |
+
|
| 84 |
+
if not template_path.exists():
|
| 85 |
+
raise FileNotFoundError(f"Scaffold template not found: {template_path}")
|
| 86 |
+
|
| 87 |
+
# ---------- pretty header ----------
|
| 88 |
+
width = 80
|
| 89 |
+
try:
|
| 90 |
+
width = os.get_terminal_size().columns
|
| 91 |
+
except OSError:
|
| 92 |
+
pass
|
| 93 |
+
|
| 94 |
+
print(Fore.BLUE + "=" * width + Style.RESET_ALL)
|
| 95 |
+
print(Fore.CYAN + "🚀 DataFlow Repository Scaffold Initialization\n" + Style.RESET_ALL)
|
| 96 |
+
|
| 97 |
+
info = {
|
| 98 |
+
"Template": template_path,
|
| 99 |
+
"Output Dir": output_dir,
|
| 100 |
+
"Interactive": "No" if no_input else "Yes",
|
| 101 |
+
"Extra Context": "Provided" if context else "None",
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
for k, v in info.items():
|
| 105 |
+
print(f"- {k:<13}: {v}")
|
| 106 |
+
|
| 107 |
+
print("\n" + Fore.BLUE + "-" * width + Style.RESET_ALL)
|
| 108 |
+
print("Generating project from scaffold...")
|
| 109 |
+
print(Fore.BLUE + "-" * width + Style.RESET_ALL + "\n")
|
| 110 |
+
|
| 111 |
+
# ---------- cookiecutter ----------
|
| 112 |
+
generated_path = cookiecutter(
|
| 113 |
+
template=str(template_path),
|
| 114 |
+
no_input=no_input,
|
| 115 |
+
extra_context=context,
|
| 116 |
+
output_dir=str(output_dir),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
generated_path = Path(generated_path).resolve()
|
| 120 |
+
# ---------- footer ----------
|
| 121 |
+
print("\n" + Fore.GREEN + "✔ Repository scaffold initialized successfully 🎉" + Style.RESET_ALL)
|
| 122 |
+
print(Fore.GREEN + f"📁 Project path: {generated_path}" + Style.RESET_ALL)
|
| 123 |
+
|
| 124 |
+
# ---------- post-init guidance ----------
|
| 125 |
+
print("\n" + Fore.CYAN + "Next steps:" + Style.RESET_ALL)
|
| 126 |
+
print(f" 1. Enter project directory:")
|
| 127 |
+
print(f" cd {generated_path}")
|
| 128 |
+
print()
|
| 129 |
+
print(f" 2. Install this project in editable mode (for local development):")
|
| 130 |
+
print(f" pip install -e .")
|
| 131 |
+
print()
|
| 132 |
+
print(f" 3. Initialize a git repository (recommended for release & distribution):")
|
| 133 |
+
print(f" git init")
|
| 134 |
+
print(f" git add .")
|
| 135 |
+
print(f" git commit -m \"Initial commit\"")
|
| 136 |
+
print(Fore.BLUE + "=" * width + Style.RESET_ALL)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_pdf.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
DataFlow PDF2Model CLI Module - dataflow/cli_funcs/cli_pdf.py
|
| 4 |
+
PDF to Model training pipeline with init/train/chat commands
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import yaml
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import datetime
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from colorama import Fore, Style
|
| 15 |
+
from dataflow import get_logger
|
| 16 |
+
from .paths import DataFlowPath
|
| 17 |
+
|
| 18 |
+
logger = get_logger()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def run_script_with_args(script_path: Path, description: str, args: list = None, cwd: str = None) -> bool:
|
| 22 |
+
"""Run a Python script with arguments and real-time output"""
|
| 23 |
+
print(f"\n{Fore.BLUE}{description}{Style.RESET_ALL}")
|
| 24 |
+
cmd = [sys.executable, str(script_path)]
|
| 25 |
+
if args:
|
| 26 |
+
cmd.extend(args)
|
| 27 |
+
print(f"Running: {' '.join(cmd)}")
|
| 28 |
+
if cwd:
|
| 29 |
+
print(f"Working directory: {cwd}")
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
result = subprocess.run(cmd, cwd=cwd, check=True,
|
| 33 |
+
stdout=sys.stdout, stderr=sys.stderr, text=True)
|
| 34 |
+
print(f"{Fore.GREEN}✅ {description} completed{Style.RESET_ALL}")
|
| 35 |
+
return True
|
| 36 |
+
except subprocess.CalledProcessError as e:
|
| 37 |
+
print(f"{Fore.RED}❌ {description} failed{Style.RESET_ALL}")
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_dataflow_script_path(script_name: str) -> Path:
|
| 42 |
+
"""Get the path of dataflow built-in scripts"""
|
| 43 |
+
try:
|
| 44 |
+
import dataflow
|
| 45 |
+
dataflow_path = Path(dataflow.__file__).parent
|
| 46 |
+
|
| 47 |
+
# PDF2Model 脚本在 dataflow/cli_funcs/pdf2model_pipeline/ 目录下
|
| 48 |
+
pdf2model_path = dataflow_path / "cli_funcs" / "pdf2model_pipeline" / script_name
|
| 49 |
+
if pdf2model_path.exists():
|
| 50 |
+
return pdf2model_path
|
| 51 |
+
|
| 52 |
+
# 检查其他可能的路径
|
| 53 |
+
possible_dirs = [
|
| 54 |
+
dataflow_path / "templates" / "pdf2model_pipeline",
|
| 55 |
+
dataflow_path / "pipeline_templates"
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
for dir_path in possible_dirs:
|
| 59 |
+
script_path = dir_path / script_name
|
| 60 |
+
if script_path.exists():
|
| 61 |
+
return script_path
|
| 62 |
+
|
| 63 |
+
return None
|
| 64 |
+
except Exception:
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def copy_customizable_scripts():
|
| 69 |
+
"""Only copy scripts that users might want to customize"""
|
| 70 |
+
print("Step 0: Copying customizable pipeline script...")
|
| 71 |
+
|
| 72 |
+
current_dir = Path(os.getcwd())
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
# 只复制用户可能需要自定义的脚本
|
| 76 |
+
scripts_to_copy = [
|
| 77 |
+
"pdf_to_qa_pipeline.py" # 用户可能需要修改 vLLM/sglang 配置
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
import shutil
|
| 81 |
+
copied_files = []
|
| 82 |
+
|
| 83 |
+
for script_name in scripts_to_copy:
|
| 84 |
+
source_path = get_dataflow_script_path(script_name)
|
| 85 |
+
if source_path is None:
|
| 86 |
+
print(f"Warning: Template not found: {script_name}")
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
target_file = current_dir / script_name
|
| 90 |
+
|
| 91 |
+
shutil.copy2(source_path, target_file)
|
| 92 |
+
copied_files.append(script_name)
|
| 93 |
+
print(f"Copied: {script_name}")
|
| 94 |
+
|
| 95 |
+
if copied_files:
|
| 96 |
+
print(f"Successfully copied {len(copied_files)} customizable script(s)")
|
| 97 |
+
print("You can now modify these files (e.g., switch vLLM/sglang in pdf_to_qa_pipeline.py)")
|
| 98 |
+
return True
|
| 99 |
+
else:
|
| 100 |
+
print("No customizable scripts were copied")
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(f"Failed to copy scripts: {e}")
|
| 105 |
+
return False
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def create_train_config_yaml(cache_path="./", model_name_or_path="Qwen/Qwen2.5-7B-Instruct"):
|
| 109 |
+
"""Create train_config.yaml file using built-in LlamaFactory configuration"""
|
| 110 |
+
cache_path_obj = Path(cache_path)
|
| 111 |
+
if not cache_path_obj.is_absolute():
|
| 112 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 113 |
+
cache_path_obj = caller_cwd / cache_path_obj
|
| 114 |
+
|
| 115 |
+
# 生成时间戳
|
| 116 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 117 |
+
model_dir_name = f"pdf2model_cache_{timestamp}" # 改为pdf2model_cache前缀
|
| 118 |
+
|
| 119 |
+
cache_dir = cache_path_obj / ".cache"
|
| 120 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 121 |
+
config_file = cache_dir / "train_config.yaml"
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
# 使用内置的 LlamaFactory.py 获取默认配置
|
| 125 |
+
llamafactory_script_path = get_dataflow_script_path("llama_factory_trainer.py")
|
| 126 |
+
if llamafactory_script_path is None:
|
| 127 |
+
print("Built-in llama_factory_trainer.py not found")
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
import importlib.util
|
| 131 |
+
spec = importlib.util.spec_from_file_location("llamafactory_trainer", llamafactory_script_path)
|
| 132 |
+
llamafactory_module = importlib.util.module_from_spec(spec)
|
| 133 |
+
spec.loader.exec_module(llamafactory_module)
|
| 134 |
+
|
| 135 |
+
# 创建trainer实例并获取默认配置
|
| 136 |
+
trainer = llamafactory_module.LlamaFactoryTrainer(str(config_file), str(cache_path_obj))
|
| 137 |
+
config = trainer.get_default_config()
|
| 138 |
+
|
| 139 |
+
# 只更新必要的动态参数
|
| 140 |
+
config["model_name_or_path"] = model_name_or_path
|
| 141 |
+
config["output_dir"] = str(cache_path_obj / ".cache" / "saves" / model_dir_name)
|
| 142 |
+
config["dataset_dir"] = str(cache_path_obj / ".cache" / "data")
|
| 143 |
+
|
| 144 |
+
# 根据模型类型设置模板
|
| 145 |
+
if "qwen" in model_name_or_path.lower():
|
| 146 |
+
config["template"] = "qwen"
|
| 147 |
+
elif "llama" in model_name_or_path.lower():
|
| 148 |
+
config["template"] = "llama3"
|
| 149 |
+
elif "chatglm" in model_name_or_path.lower():
|
| 150 |
+
config["template"] = "chatglm3"
|
| 151 |
+
elif "baichuan" in model_name_or_path.lower():
|
| 152 |
+
config["template"] = "baichuan2"
|
| 153 |
+
|
| 154 |
+
# 保存配置
|
| 155 |
+
with open(config_file, 'w', encoding='utf-8') as f:
|
| 156 |
+
yaml.dump(config, f,
|
| 157 |
+
default_flow_style=False,
|
| 158 |
+
allow_unicode=True,
|
| 159 |
+
sort_keys=False,
|
| 160 |
+
indent=2)
|
| 161 |
+
|
| 162 |
+
print(f"train_config.yaml created: {config_file}")
|
| 163 |
+
print(f"Model will be saved to: {model_dir_name}")
|
| 164 |
+
return str(config_file)
|
| 165 |
+
|
| 166 |
+
except Exception as e:
|
| 167 |
+
print(f"Failed to create train_config.yaml: {e}")
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def verify_environment():
|
| 172 |
+
"""Verify runtime environment"""
|
| 173 |
+
print("Checking environment...")
|
| 174 |
+
|
| 175 |
+
missing_deps = []
|
| 176 |
+
|
| 177 |
+
try:
|
| 178 |
+
import llamafactory
|
| 179 |
+
print("✅ LlamaFactory installed")
|
| 180 |
+
except ImportError:
|
| 181 |
+
missing_deps.append("llamafactory[torch,metrics]")
|
| 182 |
+
|
| 183 |
+
try:
|
| 184 |
+
import yaml
|
| 185 |
+
print("✅ PyYAML installed")
|
| 186 |
+
except ImportError:
|
| 187 |
+
missing_deps.append("pyyaml")
|
| 188 |
+
|
| 189 |
+
if missing_deps:
|
| 190 |
+
print(f"❌ Missing dependencies: {', '.join(missing_deps)}")
|
| 191 |
+
print(f"Install with: pip install {' '.join(missing_deps)}")
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
return True
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def check_required_files():
|
| 198 |
+
"""Check if required built-in scripts exist"""
|
| 199 |
+
# 检查所有需要的内置脚本
|
| 200 |
+
required_scripts = [
|
| 201 |
+
"path_to_jsonl_script.py",
|
| 202 |
+
"llama_factory_trainer.py"
|
| 203 |
+
]
|
| 204 |
+
|
| 205 |
+
missing_scripts = []
|
| 206 |
+
for script in required_scripts:
|
| 207 |
+
script_path = get_dataflow_script_path(script)
|
| 208 |
+
if script_path is None:
|
| 209 |
+
missing_scripts.append(script)
|
| 210 |
+
else:
|
| 211 |
+
print(f"✅ Found built-in script: {script}")
|
| 212 |
+
|
| 213 |
+
if missing_scripts:
|
| 214 |
+
print(f"❌ Missing built-in scripts: {', '.join(missing_scripts)}")
|
| 215 |
+
print("These should be part of the dataflow installation")
|
| 216 |
+
return False
|
| 217 |
+
|
| 218 |
+
# 检查用户目录下是否有可自定义的脚本
|
| 219 |
+
current_dir = Path(os.getcwd())
|
| 220 |
+
customizable_script = current_dir / "pdf_to_qa_pipeline.py"
|
| 221 |
+
if customizable_script.exists():
|
| 222 |
+
print("✅ Found customizable script: pdf_to_qa_pipeline.py")
|
| 223 |
+
else:
|
| 224 |
+
print("❌ Missing customizable script: pdf_to_qa_pipeline.py")
|
| 225 |
+
print("Run 'dataflow pdf2model init' first")
|
| 226 |
+
return False
|
| 227 |
+
|
| 228 |
+
return True
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def cli_pdf2model_init(cache_path: str = "./", model_name: str = "Qwen/Qwen2.5-7B-Instruct") -> bool:
|
| 232 |
+
"""
|
| 233 |
+
PDF2Model initialization:
|
| 234 |
+
0. Copy only customizable scripts to current directory
|
| 235 |
+
1. Create train_config.yaml in .cache directory
|
| 236 |
+
"""
|
| 237 |
+
print("Starting PDF2Model initialization...")
|
| 238 |
+
print(f"Cache directory: {cache_path}")
|
| 239 |
+
print(f"Model: {model_name}")
|
| 240 |
+
print(f"Output directory: pdf2model_cache_<timestamp>") # 更新输出目录显示
|
| 241 |
+
print("-" * 60)
|
| 242 |
+
|
| 243 |
+
if not verify_environment():
|
| 244 |
+
return False
|
| 245 |
+
|
| 246 |
+
try:
|
| 247 |
+
# Step 0: Copy only customizable scripts
|
| 248 |
+
if not copy_customizable_scripts():
|
| 249 |
+
return False
|
| 250 |
+
|
| 251 |
+
# Step 1: Create training configuration
|
| 252 |
+
print("Step 1: Creating training configuration...")
|
| 253 |
+
config_file = create_train_config_yaml(cache_path, model_name)
|
| 254 |
+
|
| 255 |
+
if config_file:
|
| 256 |
+
print("PDF2Model initialization completed!")
|
| 257 |
+
return True
|
| 258 |
+
else:
|
| 259 |
+
print("Failed to create training configuration")
|
| 260 |
+
return False
|
| 261 |
+
|
| 262 |
+
except Exception as e:
|
| 263 |
+
print(f"Initialization failed: {e}")
|
| 264 |
+
return False
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def get_latest_model_dir(cache_path_obj):
|
| 268 |
+
"""获取最新的模型目录(基于时间戳)"""
|
| 269 |
+
saves_dir = cache_path_obj / ".cache" / "saves"
|
| 270 |
+
if not saves_dir.exists():
|
| 271 |
+
return None
|
| 272 |
+
|
| 273 |
+
# 查找所有 pdf2model_cache_ 开头的目录
|
| 274 |
+
model_dirs = []
|
| 275 |
+
for dir_path in saves_dir.iterdir():
|
| 276 |
+
if dir_path.is_dir() and dir_path.name.startswith('pdf2model_cache_'):
|
| 277 |
+
# 检查是否包含正确的时间戳格式 (YYYYMMDD_HHMMSS)
|
| 278 |
+
timestamp_part = dir_path.name.replace('pdf2model_cache_', '')
|
| 279 |
+
if len(timestamp_part) == 15 and timestamp_part[8] == '_':
|
| 280 |
+
date_part = timestamp_part[:8]
|
| 281 |
+
time_part = timestamp_part[9:]
|
| 282 |
+
if date_part.isdigit() and time_part.isdigit() and len(time_part) == 6:
|
| 283 |
+
model_dirs.append(dir_path)
|
| 284 |
+
|
| 285 |
+
if not model_dirs:
|
| 286 |
+
return None
|
| 287 |
+
|
| 288 |
+
# 按名称排序(时间戳会自然排序)
|
| 289 |
+
model_dirs.sort(key=lambda x: x.name, reverse=True)
|
| 290 |
+
return model_dirs[0]
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def cli_pdf2model_train(lf_yaml: str = ".cache/train_config.yaml", cache_path: str = "./") -> bool:
|
| 294 |
+
"""
|
| 295 |
+
Start PDF2Model training using mix of built-in and user scripts
|
| 296 |
+
"""
|
| 297 |
+
print("Starting PDF2Model training...")
|
| 298 |
+
|
| 299 |
+
current_dir = Path(os.getcwd())
|
| 300 |
+
|
| 301 |
+
cache_path_obj = Path(cache_path)
|
| 302 |
+
if not cache_path_obj.is_absolute():
|
| 303 |
+
cache_path_obj = current_dir / cache_path_obj
|
| 304 |
+
|
| 305 |
+
config_path_obj = Path(lf_yaml)
|
| 306 |
+
if not config_path_obj.is_absolute():
|
| 307 |
+
config_path_obj = current_dir / config_path_obj
|
| 308 |
+
|
| 309 |
+
if not verify_environment():
|
| 310 |
+
return False
|
| 311 |
+
|
| 312 |
+
if not check_required_files():
|
| 313 |
+
return False
|
| 314 |
+
|
| 315 |
+
if not config_path_obj.exists():
|
| 316 |
+
print(f"Training config file not found: {config_path_obj}")
|
| 317 |
+
print(f"{Style.BRIGHT}Run 'dataflow pdf2model init' first")
|
| 318 |
+
return False
|
| 319 |
+
|
| 320 |
+
print("-" * 60)
|
| 321 |
+
|
| 322 |
+
try:
|
| 323 |
+
# Step 1: PDF Detection
|
| 324 |
+
script1_path = get_dataflow_script_path("path_to_jsonl_script.py")
|
| 325 |
+
args1 = ["./", "--output", str(cache_path_obj / ".cache" / "gpu" / "pdf_list.jsonl")]
|
| 326 |
+
if not run_script_with_args(script1_path, "Step 1: PDF Detection", args1, cwd=str(current_dir)):
|
| 327 |
+
return False
|
| 328 |
+
|
| 329 |
+
# Step 2: Data Processing
|
| 330 |
+
script2 = current_dir / "pdf_to_qa_pipeline.py"
|
| 331 |
+
args2 = ["--cache", cache_path]
|
| 332 |
+
if not run_script_with_args(script2, "Step 2: Data Processing", args2, cwd=str(current_dir)):
|
| 333 |
+
return False
|
| 334 |
+
|
| 335 |
+
# Step 2.5: Create dataset_info.json (dynamically)
|
| 336 |
+
print(f"\n{Fore.BLUE}Step 2.5: Creating dataset_info.json{Style.RESET_ALL}")
|
| 337 |
+
|
| 338 |
+
# 读取训练配置,获取数据集名称
|
| 339 |
+
try:
|
| 340 |
+
with open(config_path_obj, 'r', encoding='utf-8') as f:
|
| 341 |
+
train_config = yaml.safe_load(f)
|
| 342 |
+
|
| 343 |
+
# 获取数据集名称
|
| 344 |
+
dataset_name = train_config.get('dataset')
|
| 345 |
+
if isinstance(dataset_name, list):
|
| 346 |
+
dataset_name = dataset_name[0] # 如果是列表,取第一个
|
| 347 |
+
|
| 348 |
+
if not dataset_name:
|
| 349 |
+
print("Warning: No dataset name found in train_config.yaml, using default 'kb_qa'")
|
| 350 |
+
dataset_name = 'kb_qa'
|
| 351 |
+
|
| 352 |
+
print(f"Dataset name from config: {dataset_name}")
|
| 353 |
+
|
| 354 |
+
except Exception as e:
|
| 355 |
+
print(f"Warning: Could not read train_config.yaml: {e}")
|
| 356 |
+
print("Using default dataset name: kb_qa")
|
| 357 |
+
dataset_name = 'kb_qa'
|
| 358 |
+
|
| 359 |
+
# 创建 dataset_info.json
|
| 360 |
+
dataset_info_path = cache_path_obj / ".cache" / "data" / "dataset_info.json"
|
| 361 |
+
dataset_info_path.parent.mkdir(parents=True, exist_ok=True)
|
| 362 |
+
|
| 363 |
+
dataset_info = {
|
| 364 |
+
dataset_name: { # ← 使用从配置读取的名称
|
| 365 |
+
"file_name": "qa.json",
|
| 366 |
+
"formatting": "alpaca",
|
| 367 |
+
"columns": {
|
| 368 |
+
"prompt": "instruction",
|
| 369 |
+
"query": "input",
|
| 370 |
+
"response": "output"
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
with open(dataset_info_path, 'w', encoding='utf-8') as f:
|
| 376 |
+
json.dump(dataset_info, f, indent=2, ensure_ascii=False)
|
| 377 |
+
|
| 378 |
+
print(f"Created: {dataset_info_path}")
|
| 379 |
+
print(f"Dataset registered as: {dataset_name}")
|
| 380 |
+
print(f"{Fore.GREEN}✅ Step 2.5: Creating dataset_info.json completed{Style.RESET_ALL}")
|
| 381 |
+
|
| 382 |
+
# Step 3: Data Conversion - skip
|
| 383 |
+
print(f"\n{Fore.BLUE}Step 3: Data Conversion{Style.RESET_ALL}")
|
| 384 |
+
qa_json_path = cache_path_obj / ".cache" / "data" / "qa.json"
|
| 385 |
+
if qa_json_path.exists():
|
| 386 |
+
print(f"✅ qa.json already in correct format, skipping conversion")
|
| 387 |
+
print(f"{Fore.GREEN}✅ Step 3: Data Conversion completed{Style.RESET_ALL}")
|
| 388 |
+
else:
|
| 389 |
+
print(f"❌ qa.json not found at {qa_json_path}")
|
| 390 |
+
return False
|
| 391 |
+
|
| 392 |
+
# Step 4: Training
|
| 393 |
+
script4_path = get_dataflow_script_path("llama_factory_trainer.py")
|
| 394 |
+
args4 = ["--config", str(config_path_obj), "--cache", cache_path]
|
| 395 |
+
if not run_script_with_args(script4_path, "Step 4: Training", args4, cwd=str(current_dir)):
|
| 396 |
+
return False
|
| 397 |
+
|
| 398 |
+
# Show completion info
|
| 399 |
+
try:
|
| 400 |
+
with open(config_path_obj, 'r', encoding='utf-8') as f:
|
| 401 |
+
config = yaml.safe_load(f)
|
| 402 |
+
actual_output_dir = config.get('output_dir', 'unknown')
|
| 403 |
+
except Exception:
|
| 404 |
+
actual_output_dir = 'unknown'
|
| 405 |
+
|
| 406 |
+
print("Training completed successfully!")
|
| 407 |
+
print(f"Model saved to: {actual_output_dir}")
|
| 408 |
+
print("Next steps:")
|
| 409 |
+
print(f"{Style.BRIGHT}Test the trained model with 'dataflow chat'")
|
| 410 |
+
|
| 411 |
+
return True
|
| 412 |
+
|
| 413 |
+
except Exception as e:
|
| 414 |
+
print(f"Training error: {e}")
|
| 415 |
+
return False
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def cli_pdf2model_chat(model_path=None, cache_path="./", base_model=None):
|
| 419 |
+
"""Start LlamaFactory chat interface"""
|
| 420 |
+
current_dir = Path(os.getcwd())
|
| 421 |
+
|
| 422 |
+
# 处理cache路径
|
| 423 |
+
cache_path_obj = Path(cache_path)
|
| 424 |
+
if not cache_path_obj.is_absolute():
|
| 425 |
+
cache_path_obj = current_dir / cache_path_obj
|
| 426 |
+
|
| 427 |
+
# 确定模型路径
|
| 428 |
+
if model_path is None:
|
| 429 |
+
# 获取最新的模型目录
|
| 430 |
+
latest_model_dir = get_latest_model_dir(cache_path_obj)
|
| 431 |
+
if latest_model_dir:
|
| 432 |
+
model_path = latest_model_dir
|
| 433 |
+
else:
|
| 434 |
+
print("No trained model found")
|
| 435 |
+
print("Run 'dataflow pdf2model train' to train a model first")
|
| 436 |
+
return False
|
| 437 |
+
|
| 438 |
+
model_path = Path(model_path)
|
| 439 |
+
if not model_path.exists():
|
| 440 |
+
print(f"Model not found: {model_path}")
|
| 441 |
+
print("Run 'dataflow pdf2model train' to train a model first")
|
| 442 |
+
return False
|
| 443 |
+
|
| 444 |
+
# 验证是否为有效的adapter目录
|
| 445 |
+
adapter_files = [
|
| 446 |
+
"adapter_config.json",
|
| 447 |
+
"adapter_model.bin",
|
| 448 |
+
"adapter_model.safetensors"
|
| 449 |
+
]
|
| 450 |
+
|
| 451 |
+
has_adapter = any((model_path / f).exists() for f in adapter_files)
|
| 452 |
+
if not has_adapter:
|
| 453 |
+
print(f"No adapter files found in {model_path}")
|
| 454 |
+
print("This doesn't appear to be a trained adapter directory.")
|
| 455 |
+
print("Expected files: adapter_config.json, adapter_model.bin/safetensors")
|
| 456 |
+
return False
|
| 457 |
+
|
| 458 |
+
# 确定基础模型路径 - 安全的读取方式
|
| 459 |
+
if base_model is None:
|
| 460 |
+
base_model = None # 先设为None
|
| 461 |
+
|
| 462 |
+
# 尝试从训练配置中读取基础模型
|
| 463 |
+
config_file = cache_path_obj / ".cache" / "train_config.yaml"
|
| 464 |
+
if config_file.exists():
|
| 465 |
+
try:
|
| 466 |
+
with open(config_file, 'r', encoding='utf-8') as f:
|
| 467 |
+
config = yaml.safe_load(f)
|
| 468 |
+
base_model = config.get('model_name_or_path')
|
| 469 |
+
if base_model:
|
| 470 |
+
print(f"Found base model in config: {base_model}")
|
| 471 |
+
except Exception as e:
|
| 472 |
+
print(f"Warning: Could not read config file: {e}")
|
| 473 |
+
|
| 474 |
+
# 尝试从adapter_config.json读取
|
| 475 |
+
if not base_model:
|
| 476 |
+
adapter_config_path = model_path / "adapter_config.json"
|
| 477 |
+
if adapter_config_path.exists():
|
| 478 |
+
try:
|
| 479 |
+
with open(adapter_config_path, 'r', encoding='utf-8') as f:
|
| 480 |
+
adapter_config = json.load(f)
|
| 481 |
+
base_model = adapter_config.get('base_model_name_or_path')
|
| 482 |
+
if base_model:
|
| 483 |
+
print(f"Found base model in adapter config: {base_model}")
|
| 484 |
+
except Exception as e:
|
| 485 |
+
print(f"Warning: Could not read adapter config: {e}")
|
| 486 |
+
|
| 487 |
+
# 如果仍然没有找到base_model,报错退出而不是使用默认值
|
| 488 |
+
if not base_model:
|
| 489 |
+
print("Cannot determine base model path")
|
| 490 |
+
print("Please ensure your training config contains 'model_name_or_path'")
|
| 491 |
+
print("Or check that adapter_config.json exists and contains 'base_model_name_or_path'")
|
| 492 |
+
return False
|
| 493 |
+
|
| 494 |
+
# 检查LlamaFactory
|
| 495 |
+
try:
|
| 496 |
+
import llamafactory
|
| 497 |
+
print("LlamaFactory available")
|
| 498 |
+
except ImportError:
|
| 499 |
+
print("LlamaFactory not installed")
|
| 500 |
+
print("Install with: pip install llamafactory[torch,metrics]")
|
| 501 |
+
return False
|
| 502 |
+
|
| 503 |
+
# 直接用命令行参数启动聊天
|
| 504 |
+
chat_cmd = [
|
| 505 |
+
"llamafactory-cli", "chat",
|
| 506 |
+
"--model_name_or_path", base_model,
|
| 507 |
+
"--adapter_name_or_path", str(model_path.absolute())
|
| 508 |
+
]
|
| 509 |
+
|
| 510 |
+
print(f"Base model: {base_model}")
|
| 511 |
+
print(f"Adapter path: {model_path}")
|
| 512 |
+
print(f"Command: {' '.join(chat_cmd)}")
|
| 513 |
+
print("-" * 60)
|
| 514 |
+
print("Starting chat session...")
|
| 515 |
+
print("-" * 60)
|
| 516 |
+
|
| 517 |
+
try:
|
| 518 |
+
result = subprocess.run(chat_cmd, check=True)
|
| 519 |
+
print("\nChat session completed")
|
| 520 |
+
return True
|
| 521 |
+
except subprocess.CalledProcessError as e:
|
| 522 |
+
print(f"\nChat failed: {e}")
|
| 523 |
+
return False
|
| 524 |
+
except KeyboardInterrupt:
|
| 525 |
+
print("\n\nChat session ended by user")
|
| 526 |
+
return True
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_text.py
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
DataFlow Text Processing CLI Module - dataflow/cli_funcs/cli_text.py
|
| 4 |
+
Text data processing pipeline with complete workflow including Text2QA
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import datetime
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import List, Union, Any
|
| 14 |
+
from colorama import Fore, Style
|
| 15 |
+
from dataflow import get_logger
|
| 16 |
+
from .paths import DataFlowPath
|
| 17 |
+
|
| 18 |
+
logger = get_logger()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def run_script_with_args(script_path: Path, description: str, args: list = None, cwd: str = None) -> bool:
|
| 22 |
+
"""Run a Python script with arguments and real-time output"""
|
| 23 |
+
print(f"\n{Fore.BLUE}{description}{Style.RESET_ALL}")
|
| 24 |
+
cmd = [sys.executable, str(script_path)]
|
| 25 |
+
if args:
|
| 26 |
+
cmd.extend(args)
|
| 27 |
+
print(f"Running: {' '.join(cmd)}")
|
| 28 |
+
if cwd:
|
| 29 |
+
print(f"Working directory: {cwd}")
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
result = subprocess.run(cmd, cwd=cwd, check=True,
|
| 33 |
+
stdout=sys.stdout, stderr=sys.stderr, text=True)
|
| 34 |
+
print(f"{Fore.GREEN}✅ {description} completed{Style.RESET_ALL}")
|
| 35 |
+
return True
|
| 36 |
+
except subprocess.CalledProcessError as e:
|
| 37 |
+
print(f"{Fore.RED}❌ {description} failed{Style.RESET_ALL}")
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_dataflow_script_path(script_name: str) -> Path:
|
| 42 |
+
"""Get the path of dataflow built-in scripts"""
|
| 43 |
+
try:
|
| 44 |
+
import dataflow
|
| 45 |
+
dataflow_path = Path(dataflow.__file__).parent
|
| 46 |
+
|
| 47 |
+
# Text2Model 脚本在 dataflow/cli_funcs/text2model_pipeline/ 目录下
|
| 48 |
+
text2model_path = dataflow_path / "cli_funcs" / "text2model_pipeline" / script_name
|
| 49 |
+
if text2model_path.exists():
|
| 50 |
+
return text2model_path
|
| 51 |
+
|
| 52 |
+
# 检查其他可能的路径
|
| 53 |
+
possible_dirs = [
|
| 54 |
+
dataflow_path / "templates" / "text2model_pipeline",
|
| 55 |
+
dataflow_path / "pipeline_templates"
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
for dir_path in possible_dirs:
|
| 59 |
+
script_path = dir_path / script_name
|
| 60 |
+
if script_path.exists():
|
| 61 |
+
return script_path
|
| 62 |
+
|
| 63 |
+
return None
|
| 64 |
+
except Exception:
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def copy_customizable_scripts():
|
| 69 |
+
"""Copy scripts that users might want to customize"""
|
| 70 |
+
print("Step 0: Setting up customizable pipeline scripts...")
|
| 71 |
+
|
| 72 |
+
current_dir = Path(os.getcwd())
|
| 73 |
+
|
| 74 |
+
# 检查当前目录下是否已经存在所需的脚本文件
|
| 75 |
+
required_scripts = [
|
| 76 |
+
"text_to_qa_pipeline.py",
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
existing_scripts = []
|
| 80 |
+
missing_scripts = []
|
| 81 |
+
|
| 82 |
+
for script_name in required_scripts:
|
| 83 |
+
script_path = current_dir / script_name
|
| 84 |
+
if script_path.exists():
|
| 85 |
+
existing_scripts.append(script_name)
|
| 86 |
+
print(f"Found existing: {script_name}")
|
| 87 |
+
else:
|
| 88 |
+
missing_scripts.append(script_name)
|
| 89 |
+
|
| 90 |
+
# 尝试从模板复制缺失的脚本
|
| 91 |
+
copied_files = []
|
| 92 |
+
for script_name in missing_scripts:
|
| 93 |
+
source_path = get_dataflow_script_path(script_name)
|
| 94 |
+
if source_path is not None:
|
| 95 |
+
try:
|
| 96 |
+
import shutil
|
| 97 |
+
target_file = current_dir / script_name
|
| 98 |
+
shutil.copy2(source_path, target_file)
|
| 99 |
+
copied_files.append(script_name)
|
| 100 |
+
print(f"Copied from template: {script_name}")
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"Warning: Failed to copy {script_name}: {e}")
|
| 103 |
+
else:
|
| 104 |
+
print(f"Warning: Template not found for {script_name}")
|
| 105 |
+
|
| 106 |
+
total_available = len(existing_scripts) + len(copied_files)
|
| 107 |
+
|
| 108 |
+
if total_available > 0:
|
| 109 |
+
print(f"Setup completed: {total_available} scripts available")
|
| 110 |
+
if existing_scripts:
|
| 111 |
+
print(f" Existing scripts: {', '.join(existing_scripts)}")
|
| 112 |
+
if copied_files:
|
| 113 |
+
print(f" Copied from templates: {', '.join(copied_files)}")
|
| 114 |
+
return True
|
| 115 |
+
else:
|
| 116 |
+
print("Warning: No pipeline scripts available")
|
| 117 |
+
return False
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def create_train_config_yaml(cache_path="./", model_name_or_path="Qwen/Qwen2.5-7B-Instruct"):
|
| 121 |
+
"""Create train_config.yaml file using built-in LlamaFactory configuration"""
|
| 122 |
+
cache_path_obj = Path(cache_path)
|
| 123 |
+
if not cache_path_obj.is_absolute():
|
| 124 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 125 |
+
cache_path_obj = caller_cwd / cache_path_obj
|
| 126 |
+
|
| 127 |
+
# 生成时间戳
|
| 128 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 129 |
+
model_dir_name = f"text2model_cache_{timestamp}"
|
| 130 |
+
|
| 131 |
+
cache_dir = cache_path_obj / ".cache"
|
| 132 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 133 |
+
config_file = cache_dir / "train_config.yaml"
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
# 使用内置的 LlamaFactory.py 获取默认配置
|
| 137 |
+
llamafactory_script_path = get_dataflow_script_path("llama_factory_trainer.py")
|
| 138 |
+
if llamafactory_script_path is None:
|
| 139 |
+
print("Built-in llama_factory_trainer.py not found")
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
import importlib.util
|
| 143 |
+
spec = importlib.util.spec_from_file_location("llamafactory_trainer", llamafactory_script_path)
|
| 144 |
+
llamafactory_module = importlib.util.module_from_spec(spec)
|
| 145 |
+
spec.loader.exec_module(llamafactory_module)
|
| 146 |
+
|
| 147 |
+
# 创建trainer实例并获取默认配置
|
| 148 |
+
trainer = llamafactory_module.LlamaFactoryTrainer(str(config_file), str(cache_path_obj))
|
| 149 |
+
config = trainer.get_default_config()
|
| 150 |
+
|
| 151 |
+
# 只更新必要的动态参数
|
| 152 |
+
config["model_name_or_path"] = model_name_or_path
|
| 153 |
+
config["output_dir"] = str(cache_path_obj / ".cache" / "saves" / model_dir_name)
|
| 154 |
+
config["dataset_dir"] = str(cache_path_obj / ".cache" / "data")
|
| 155 |
+
|
| 156 |
+
# 根据模型类型设置模板
|
| 157 |
+
if "qwen" in model_name_or_path.lower():
|
| 158 |
+
config["template"] = "qwen"
|
| 159 |
+
elif "llama" in model_name_or_path.lower():
|
| 160 |
+
config["template"] = "llama3"
|
| 161 |
+
elif "chatglm" in model_name_or_path.lower():
|
| 162 |
+
config["template"] = "chatglm3"
|
| 163 |
+
elif "baichuan" in model_name_or_path.lower():
|
| 164 |
+
config["template"] = "baichuan2"
|
| 165 |
+
|
| 166 |
+
# 保存配置
|
| 167 |
+
import yaml
|
| 168 |
+
with open(config_file, 'w', encoding='utf-8') as f:
|
| 169 |
+
yaml.dump(config, f,
|
| 170 |
+
default_flow_style=False,
|
| 171 |
+
allow_unicode=True,
|
| 172 |
+
sort_keys=False,
|
| 173 |
+
indent=2)
|
| 174 |
+
|
| 175 |
+
print(f"train_config.yaml created: {config_file}")
|
| 176 |
+
print(f"Model will be saved to: {model_dir_name}")
|
| 177 |
+
return str(config_file)
|
| 178 |
+
|
| 179 |
+
except Exception as e:
|
| 180 |
+
print(f"Failed to create train_config.yaml: {e}")
|
| 181 |
+
return None
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def verify_environment():
|
| 185 |
+
"""Verify runtime environment"""
|
| 186 |
+
print("Checking environment...")
|
| 187 |
+
|
| 188 |
+
missing_deps = []
|
| 189 |
+
|
| 190 |
+
try:
|
| 191 |
+
import llamafactory
|
| 192 |
+
print("✅ LlamaFactory installed")
|
| 193 |
+
except ImportError:
|
| 194 |
+
missing_deps.append("llamafactory[torch,metrics]")
|
| 195 |
+
|
| 196 |
+
try:
|
| 197 |
+
import yaml
|
| 198 |
+
print("✅ PyYAML installed")
|
| 199 |
+
except ImportError:
|
| 200 |
+
missing_deps.append("pyyaml")
|
| 201 |
+
|
| 202 |
+
try:
|
| 203 |
+
from dataflow.utils.storage import FileStorage
|
| 204 |
+
print("✅ DataFlow storage available")
|
| 205 |
+
except ImportError:
|
| 206 |
+
missing_deps.append("dataflow")
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
# 修复: 使用正确的算子导入路径和类名
|
| 210 |
+
from dataflow.operators.knowledge_cleaning import (
|
| 211 |
+
KBCChunkGeneratorBatch as CorpusTextSplitterBatch,
|
| 212 |
+
KBCTextCleanerBatch as KnowledgeCleanerBatch,
|
| 213 |
+
KBCMultiHopQAGeneratorBatch as MultiHopQAGeneratorBatch
|
| 214 |
+
)
|
| 215 |
+
print("✅ DataFlow operators available")
|
| 216 |
+
except ImportError:
|
| 217 |
+
missing_deps.append("dataflow operators")
|
| 218 |
+
|
| 219 |
+
if missing_deps:
|
| 220 |
+
print(f"❌ Missing dependencies: {', '.join(missing_deps)}")
|
| 221 |
+
print(f"Install with: pip install {' '.join(missing_deps)}")
|
| 222 |
+
return False
|
| 223 |
+
|
| 224 |
+
return True
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def check_required_files_for_training():
|
| 228 |
+
"""Check if required built-in scripts exist for training"""
|
| 229 |
+
# 检查所有需要的内置脚本
|
| 230 |
+
required_scripts = [
|
| 231 |
+
"merge_json_jsonl.py",
|
| 232 |
+
"llama_factory_trainer.py"
|
| 233 |
+
]
|
| 234 |
+
|
| 235 |
+
missing_scripts = []
|
| 236 |
+
for script in required_scripts:
|
| 237 |
+
script_path = get_dataflow_script_path(script)
|
| 238 |
+
if script_path is None:
|
| 239 |
+
missing_scripts.append(script)
|
| 240 |
+
else:
|
| 241 |
+
print(f"✅ Found built-in script: {script}")
|
| 242 |
+
|
| 243 |
+
if missing_scripts:
|
| 244 |
+
print(f"❌ Missing built-in scripts: {', '.join(missing_scripts)}")
|
| 245 |
+
print("These should be part of the dataflow installation")
|
| 246 |
+
return False
|
| 247 |
+
|
| 248 |
+
# 检查用户目录下是否有可自定义的脚本
|
| 249 |
+
current_dir = Path(os.getcwd())
|
| 250 |
+
customizable_scripts = [
|
| 251 |
+
"text_to_qa_pipeline.py",
|
| 252 |
+
]
|
| 253 |
+
|
| 254 |
+
missing_customizable = []
|
| 255 |
+
for script_name in customizable_scripts:
|
| 256 |
+
script_path = current_dir / script_name
|
| 257 |
+
if script_path.exists():
|
| 258 |
+
print(f"✅ Found customizable script: {script_name}")
|
| 259 |
+
else:
|
| 260 |
+
missing_customizable.append(script_name)
|
| 261 |
+
|
| 262 |
+
if missing_customizable:
|
| 263 |
+
print(f"❌ Missing customizable scripts: {', '.join(missing_customizable)}")
|
| 264 |
+
print("Run 'dataflow text2model init' first")
|
| 265 |
+
return False
|
| 266 |
+
|
| 267 |
+
return True
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def analyze_input_data(input_file: str) -> dict:
|
| 271 |
+
"""分析输入数据的字段结构"""
|
| 272 |
+
if not input_file or not Path(input_file).exists():
|
| 273 |
+
return {}
|
| 274 |
+
|
| 275 |
+
try:
|
| 276 |
+
with open(input_file, 'r', encoding='utf-8') as f:
|
| 277 |
+
first_line = f.readline().strip()
|
| 278 |
+
if first_line:
|
| 279 |
+
sample_data = json.loads(first_line)
|
| 280 |
+
return {
|
| 281 |
+
'available_keys': list(sample_data.keys()),
|
| 282 |
+
'has_sft_format': all(key in sample_data for key in ['instruction', 'input', 'output']),
|
| 283 |
+
'has_text_field': 'text' in sample_data,
|
| 284 |
+
'has_raw_content': 'raw_content' in sample_data
|
| 285 |
+
}
|
| 286 |
+
except Exception as e:
|
| 287 |
+
print(f"Could not analyze input file: {e}")
|
| 288 |
+
|
| 289 |
+
return {}
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def get_latest_model_dir(cache_path_obj):
|
| 293 |
+
"""获取最新的模型目录(基于时间戳)"""
|
| 294 |
+
saves_dir = cache_path_obj / ".cache" / "saves"
|
| 295 |
+
if not saves_dir.exists():
|
| 296 |
+
return None
|
| 297 |
+
|
| 298 |
+
# 查找所有 text2model_cache_ 开头的目录
|
| 299 |
+
model_dirs = []
|
| 300 |
+
for dir_path in saves_dir.iterdir():
|
| 301 |
+
if dir_path.is_dir() and dir_path.name.startswith('text2model_cache_'):
|
| 302 |
+
# 检查是否包含正确的时间戳格式 (YYYYMMDD_HHMMSS)
|
| 303 |
+
timestamp_part = dir_path.name.replace('text2model_cache_', '')
|
| 304 |
+
if len(timestamp_part) == 15 and timestamp_part[8] == '_':
|
| 305 |
+
date_part = timestamp_part[:8]
|
| 306 |
+
time_part = timestamp_part[9:]
|
| 307 |
+
if date_part.isdigit() and time_part.isdigit() and len(time_part) == 6:
|
| 308 |
+
model_dirs.append(dir_path)
|
| 309 |
+
|
| 310 |
+
if not model_dirs:
|
| 311 |
+
return None
|
| 312 |
+
|
| 313 |
+
# 按名称排序(时间戳会自然排序)
|
| 314 |
+
model_dirs.sort(key=lambda x: x.name, reverse=True)
|
| 315 |
+
return model_dirs[0]
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def cli_text2model_init(cache_path: str = "./") -> bool:
|
| 319 |
+
"""
|
| 320 |
+
Text2Model initialization:
|
| 321 |
+
0. Check for existing scripts and copy any missing templates
|
| 322 |
+
1. Create train_config.yaml in .cache directory
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
if not verify_environment():
|
| 326 |
+
return False
|
| 327 |
+
|
| 328 |
+
try:
|
| 329 |
+
# Step 0: Check for existing scripts and setup missing ones
|
| 330 |
+
if not copy_customizable_scripts():
|
| 331 |
+
print("Warning: Some scripts may be missing, but continuing...")
|
| 332 |
+
|
| 333 |
+
# Step 1: Create training configuration
|
| 334 |
+
print("Step 1: Creating training configuration...")
|
| 335 |
+
config_file = create_train_config_yaml(cache_path, "Qwen/Qwen2.5-7B-Instruct")
|
| 336 |
+
|
| 337 |
+
if config_file:
|
| 338 |
+
print("Text2Model initialization completed!")
|
| 339 |
+
print("\nWorkflow:")
|
| 340 |
+
print("1. Put your JSON/JSONL files with 'text' field in current directory")
|
| 341 |
+
print("2. Run: dataflow text2model train")
|
| 342 |
+
print(" This will automatically run Text2QA generation and training")
|
| 343 |
+
return True
|
| 344 |
+
else:
|
| 345 |
+
print("Failed to create training configuration")
|
| 346 |
+
return False
|
| 347 |
+
|
| 348 |
+
except Exception as e:
|
| 349 |
+
print(f"Initialization failed: {e}")
|
| 350 |
+
return False
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def cli_text2model_train(input_keys: str = None, lf_yaml: str = "./.cache/train_config.yaml") -> bool:
|
| 354 |
+
"""
|
| 355 |
+
Start Text2Model training using complete pipeline
|
| 356 |
+
"""
|
| 357 |
+
print("Starting Text2Model training...")
|
| 358 |
+
if input_keys:
|
| 359 |
+
print(f"Processing fields: {input_keys}")
|
| 360 |
+
|
| 361 |
+
current_dir = Path(os.getcwd())
|
| 362 |
+
config_path_obj = Path(lf_yaml)
|
| 363 |
+
if not config_path_obj.is_absolute():
|
| 364 |
+
config_path_obj = current_dir / config_path_obj
|
| 365 |
+
|
| 366 |
+
if not verify_environment():
|
| 367 |
+
return False
|
| 368 |
+
|
| 369 |
+
if not config_path_obj.exists():
|
| 370 |
+
print(f"Training config file not found: {config_path_obj}")
|
| 371 |
+
print("Run 'dataflow text2model init' first")
|
| 372 |
+
return False
|
| 373 |
+
|
| 374 |
+
input_dir = "./"
|
| 375 |
+
cache_path_obj = current_dir
|
| 376 |
+
input_path = Path(input_dir)
|
| 377 |
+
if not input_path.is_absolute():
|
| 378 |
+
input_path = current_dir / input_path
|
| 379 |
+
|
| 380 |
+
if not input_path.exists():
|
| 381 |
+
print(f"Input directory not found: {input_path}")
|
| 382 |
+
return False
|
| 383 |
+
|
| 384 |
+
print("-" * 60)
|
| 385 |
+
|
| 386 |
+
try:
|
| 387 |
+
# Step 1: Merge JSON/JSONL files to create text_input.jsonl
|
| 388 |
+
print(f"{Fore.CYAN}Step 1: Merging JSON/JSONL files...{Style.RESET_ALL}")
|
| 389 |
+
|
| 390 |
+
# 调用 merge_json_jsonl.py 的逻辑
|
| 391 |
+
script1_path = get_dataflow_script_path("merge_json_jsonl.py")
|
| 392 |
+
args1 = [str(input_path), "--cache", str(cache_path_obj)]
|
| 393 |
+
if not run_script_with_args(script1_path, "JSON/JSONL merging", args1, cwd=str(current_dir)):
|
| 394 |
+
print(f"{Fore.RED}❌ Step 1: JSON/JSONL merging failed{Style.RESET_ALL}")
|
| 395 |
+
return False
|
| 396 |
+
|
| 397 |
+
# 验证 text_input.jsonl 是否创建成功
|
| 398 |
+
text_input_file = cache_path_obj / ".cache" / "gpu" / "text_input.jsonl"
|
| 399 |
+
if not text_input_file.exists():
|
| 400 |
+
print(
|
| 401 |
+
f"{Fore.RED}❌ text_input.jsonl not created. Check if you have JSON/JSONL files in {input_path}{Style.RESET_ALL}")
|
| 402 |
+
return False
|
| 403 |
+
|
| 404 |
+
file_size = text_input_file.stat().st_size
|
| 405 |
+
print(f"{Fore.GREEN}✅ Step 1 completed: {text_input_file} ({file_size} bytes){Style.RESET_ALL}")
|
| 406 |
+
|
| 407 |
+
# Step 2: Text2QA Pipeline
|
| 408 |
+
print(f"{Fore.CYAN}Step 2: Text2QA generation...{Style.RESET_ALL}")
|
| 409 |
+
|
| 410 |
+
script2_path = cache_path_obj / "text_to_qa_pipeline.py"
|
| 411 |
+
args2 = ["--cache", str(cache_path_obj)]
|
| 412 |
+
if not run_script_with_args(script2_path, "Text2QA generation", args2, cwd=str(current_dir)):
|
| 413 |
+
print(f"{Fore.RED}❌ Step 2: Text2QA generation failed{Style.RESET_ALL}")
|
| 414 |
+
return False
|
| 415 |
+
|
| 416 |
+
# 验证 Text2QA 输出
|
| 417 |
+
qa_output_file = cache_path_obj / ".cache" / "gpu" / "text2qa_step_step3.json"
|
| 418 |
+
if not qa_output_file.exists():
|
| 419 |
+
print(f"{Fore.RED}❌ Text2QA output not found{Style.RESET_ALL}")
|
| 420 |
+
return False
|
| 421 |
+
|
| 422 |
+
file_size = qa_output_file.stat().st_size
|
| 423 |
+
print(f"{Fore.GREEN}✅ Step 2 completed: {qa_output_file} ({file_size} bytes){Style.RESET_ALL}")
|
| 424 |
+
|
| 425 |
+
# Step 3: Convert to training format
|
| 426 |
+
print(f"{Fore.CYAN}Step 3: Converting to training format...{Style.RESET_ALL}")
|
| 427 |
+
|
| 428 |
+
script3_path = get_dataflow_script_path("merge_filter_qa_pairs.py")
|
| 429 |
+
args3 = ["--cache", str(cache_path_obj)]
|
| 430 |
+
if not run_script_with_args(script3_path, "QA format conversion", args3, cwd=str(current_dir)):
|
| 431 |
+
print(f"{Fore.RED}❌ Step 3: QA format conversion failed{Style.RESET_ALL}")
|
| 432 |
+
return False
|
| 433 |
+
|
| 434 |
+
# 验证训练数据
|
| 435 |
+
qa_file = cache_path_obj / ".cache" / "data" / "qa.json"
|
| 436 |
+
dataset_info_file = cache_path_obj / ".cache" / "data" / "dataset_info.json"
|
| 437 |
+
|
| 438 |
+
if not qa_file.exists() or not dataset_info_file.exists():
|
| 439 |
+
print(f"{Fore.RED}❌ Training data files not created{Style.RESET_ALL}")
|
| 440 |
+
return False
|
| 441 |
+
|
| 442 |
+
# 统计样本数
|
| 443 |
+
try:
|
| 444 |
+
import json
|
| 445 |
+
with open(qa_file, 'r', encoding='utf-8') as f:
|
| 446 |
+
qa_data = json.load(f)
|
| 447 |
+
sample_count = len(qa_data)
|
| 448 |
+
file_size = qa_file.stat().st_size
|
| 449 |
+
print(
|
| 450 |
+
f"{Fore.GREEN}✅ Step 3 completed: {sample_count} training samples ({file_size} bytes){Style.RESET_ALL}")
|
| 451 |
+
except Exception:
|
| 452 |
+
print(f"{Fore.GREEN}✅ Step 3 completed{Style.RESET_ALL}")
|
| 453 |
+
|
| 454 |
+
# Step 4: Training
|
| 455 |
+
print(f"{Fore.CYAN}Step 4: Starting model training...{Style.RESET_ALL}")
|
| 456 |
+
|
| 457 |
+
script4_path = get_dataflow_script_path("llama_factory_trainer.py")
|
| 458 |
+
args4 = ["--config", str(config_path_obj), "--cache", str(cache_path_obj)]
|
| 459 |
+
if not run_script_with_args(script4_path, "Model training", args4, cwd=str(current_dir)):
|
| 460 |
+
print(f"{Fore.RED}❌ Step 4: Training failed{Style.RESET_ALL}")
|
| 461 |
+
return False
|
| 462 |
+
|
| 463 |
+
print(f"{Fore.GREEN}✅ Text2Model training completed successfully!{Style.RESET_ALL}")
|
| 464 |
+
print(f"Next steps:")
|
| 465 |
+
print(f" Test the model: dataflow chat")
|
| 466 |
+
|
| 467 |
+
return True
|
| 468 |
+
|
| 469 |
+
except Exception as e:
|
| 470 |
+
print(f"Training error: {e}")
|
| 471 |
+
return False
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def _run_text2qa_workflow(current_dir: Path, cache_path_obj: Path, config_path_obj: Path) -> bool:
|
| 475 |
+
"""Run Text2QA workflow"""
|
| 476 |
+
|
| 477 |
+
# Step 1: Check if Text2QA output exists
|
| 478 |
+
text2qa_output = cache_path_obj / ".cache" / "gpu" / "text2qa_step_step3.json"
|
| 479 |
+
|
| 480 |
+
if not text2qa_output.exists():
|
| 481 |
+
print("Text2QA output not found. Please run text_to_qa_pipeline.py first.")
|
| 482 |
+
print("Example:")
|
| 483 |
+
print(" 1. Prepare JSON/JSONL files with 'text' field in current directory")
|
| 484 |
+
print(" 2. Run: python text_to_qa_pipeline.py")
|
| 485 |
+
print(" 3. Then run: dataflow text2model train --text2qa")
|
| 486 |
+
return False
|
| 487 |
+
|
| 488 |
+
print("Found Text2QA output, proceeding with conversion...")
|
| 489 |
+
|
| 490 |
+
# Step 2: Convert QA to Alpaca format
|
| 491 |
+
script2 = current_dir / "merge_filter_qa_pairs.py"
|
| 492 |
+
args2 = ["--cache", str(cache_path_obj)]
|
| 493 |
+
|
| 494 |
+
if not run_script_with_args(script2, "Step 2: Converting QA to Alpaca format", args2, cwd=str(current_dir)):
|
| 495 |
+
return False
|
| 496 |
+
|
| 497 |
+
# Step 3: Training
|
| 498 |
+
script3_path = get_dataflow_script_path("llama_factory_trainer.py")
|
| 499 |
+
args3 = ["--config", str(config_path_obj)]
|
| 500 |
+
if not run_script_with_args(script3_path, "Step 3: Training", args3, cwd=str(current_dir)):
|
| 501 |
+
return False
|
| 502 |
+
|
| 503 |
+
# 显示训练完成信息
|
| 504 |
+
try:
|
| 505 |
+
import yaml
|
| 506 |
+
with open(config_path_obj, 'r', encoding='utf-8') as f:
|
| 507 |
+
config = yaml.safe_load(f)
|
| 508 |
+
actual_output_dir = config.get('output_dir', 'unknown')
|
| 509 |
+
except Exception:
|
| 510 |
+
actual_output_dir = 'unknown'
|
| 511 |
+
|
| 512 |
+
print("Text2QA training completed successfully!")
|
| 513 |
+
print(f"Model saved to: {actual_output_dir}")
|
| 514 |
+
print("Next steps:")
|
| 515 |
+
print("Test the trained model with 'dataflow chat'")
|
| 516 |
+
return True
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
# def _run_normal_text_workflow(input_path: Path, current_dir: Path, cache_path_obj: Path, config_path_obj: Path,
|
| 520 |
+
# input_keys: str) -> bool:
|
| 521 |
+
# """Run Text2QA workflow as the main processing pipeline"""
|
| 522 |
+
|
| 523 |
+
# # Step 1: Merge JSON/JSONL files and create text_input.jsonl - 使用内置脚本
|
| 524 |
+
# script1_path = get_dataflow_script_path("merge_json_jsonl.py")
|
| 525 |
+
# args1 = [str(input_path), "--cache", str(cache_path_obj)]
|
| 526 |
+
# if not run_script_with_args(script1_path, "Step 1: Preparing text input for Text2QA", args1, cwd=str(current_dir)):
|
| 527 |
+
# return False
|
| 528 |
+
|
| 529 |
+
# # Step 2: Run Text2QA Pipeline - 使用用户目录下的脚本
|
| 530 |
+
# script2 = current_dir / "text_to_qa_pipeline.py"
|
| 531 |
+
# args2 = ["--cache", str(cache_path_obj)]
|
| 532 |
+
|
| 533 |
+
# if not run_script_with_args(script2, "Step 2: Text2QA generation", args2, cwd=str(current_dir)):
|
| 534 |
+
# return False
|
| 535 |
+
|
| 536 |
+
# # Step 3: Convert QA to Alpaca format - 使用用户目录下的脚本
|
| 537 |
+
# script3 = current_dir / "merge_filter_qa_pairs.py"
|
| 538 |
+
# args3 = ["--cache", str(cache_path_obj)]
|
| 539 |
+
|
| 540 |
+
# if not run_script_with_args(script3, "Step 3: Converting QA to training format", args3, cwd=str(current_dir)):
|
| 541 |
+
# return False
|
| 542 |
+
|
| 543 |
+
# # Step 4: Training - 使用内置脚本
|
| 544 |
+
# script4_path = get_dataflow_script_path("llama_factory_trainer.py")
|
| 545 |
+
# args4 = ["--config", str(config_path_obj)]
|
| 546 |
+
# if not run_script_with_args(script4_path, "Step 4: Training", args4, cwd=str(current_dir)):
|
| 547 |
+
# return False
|
| 548 |
+
|
| 549 |
+
# # 显示训练完成信息,从配置文件中读取实际的输出目录
|
| 550 |
+
# try:
|
| 551 |
+
# import yaml
|
| 552 |
+
# with open(config_path_obj, 'r', encoding='utf-8') as f:
|
| 553 |
+
# config = yaml.safe_load(f)
|
| 554 |
+
# actual_output_dir = config.get('output_dir', 'unknown')
|
| 555 |
+
# except Exception:
|
| 556 |
+
# actual_output_dir = 'unknown'
|
| 557 |
+
|
| 558 |
+
# print("Text2QA training completed successfully!")
|
| 559 |
+
# print(f"Model saved to: {actual_output_dir}")
|
| 560 |
+
# print("Next steps:")
|
| 561 |
+
# print("Test the trained model with 'dataflow chat'")
|
| 562 |
+
# return True
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def cli_text2model_chat(model_path=None):
|
| 566 |
+
"""Start LlamaFactory chat interface for text2model"""
|
| 567 |
+
|
| 568 |
+
current_dir = Path(os.getcwd())
|
| 569 |
+
|
| 570 |
+
# 使用默认cache路径
|
| 571 |
+
cache_path_obj = current_dir
|
| 572 |
+
|
| 573 |
+
# 确定模型路径
|
| 574 |
+
if model_path is None:
|
| 575 |
+
# 获取最新的模型目录
|
| 576 |
+
latest_model_dir = get_latest_model_dir(cache_path_obj)
|
| 577 |
+
if latest_model_dir:
|
| 578 |
+
model_path = latest_model_dir
|
| 579 |
+
else:
|
| 580 |
+
print("No trained model found")
|
| 581 |
+
print("Run 'dataflow text2model train' to train a model first")
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
model_path = Path(model_path)
|
| 585 |
+
if not model_path.exists():
|
| 586 |
+
print(f"Model not found: {model_path}")
|
| 587 |
+
print("Run 'dataflow text2model train' to train a model first")
|
| 588 |
+
return False
|
| 589 |
+
|
| 590 |
+
# 验证是否为有效的adapter目录
|
| 591 |
+
adapter_files = [
|
| 592 |
+
"adapter_config.json",
|
| 593 |
+
"adapter_model.bin",
|
| 594 |
+
"adapter_model.safetensors"
|
| 595 |
+
]
|
| 596 |
+
|
| 597 |
+
has_adapter = any((model_path / f).exists() for f in adapter_files)
|
| 598 |
+
if not has_adapter:
|
| 599 |
+
print(f"No adapter files found in {model_path}")
|
| 600 |
+
print("This doesn't appear to be a trained adapter directory.")
|
| 601 |
+
print("Expected files: adapter_config.json, adapter_model.bin/safetensors")
|
| 602 |
+
return False
|
| 603 |
+
|
| 604 |
+
# 安全地确定基础模型
|
| 605 |
+
base_model = None
|
| 606 |
+
|
| 607 |
+
# 尝试从训练配置中读取基础模型
|
| 608 |
+
config_file = cache_path_obj / ".cache" / "train_config.yaml"
|
| 609 |
+
if config_file.exists():
|
| 610 |
+
try:
|
| 611 |
+
import yaml
|
| 612 |
+
with open(config_file, 'r', encoding='utf-8') as f:
|
| 613 |
+
config = yaml.safe_load(f)
|
| 614 |
+
base_model = config.get('model_name_or_path')
|
| 615 |
+
if base_model:
|
| 616 |
+
print(f"Found base model in config: {base_model}")
|
| 617 |
+
except Exception as e:
|
| 618 |
+
print(f"Warning: Could not read config file: {e}")
|
| 619 |
+
|
| 620 |
+
# 尝试从adapter_config.json读取
|
| 621 |
+
if not base_model:
|
| 622 |
+
adapter_config_path = model_path / "adapter_config.json"
|
| 623 |
+
if adapter_config_path.exists():
|
| 624 |
+
try:
|
| 625 |
+
with open(adapter_config_path, 'r', encoding='utf-8') as f:
|
| 626 |
+
adapter_config = json.load(f)
|
| 627 |
+
base_model = adapter_config.get('base_model_name_or_path')
|
| 628 |
+
if base_model:
|
| 629 |
+
print(f"Found base model in adapter config: {base_model}")
|
| 630 |
+
except Exception as e:
|
| 631 |
+
print(f"Warning: Could not read adapter config: {e}")
|
| 632 |
+
|
| 633 |
+
# 如果仍然没有找到base_model,报错退出
|
| 634 |
+
if not base_model:
|
| 635 |
+
print("Cannot determine base model path")
|
| 636 |
+
print("Please ensure your training config contains 'model_name_or_path'")
|
| 637 |
+
print("Or check that adapter_config.json exists and contains 'base_model_name_or_path'")
|
| 638 |
+
return False
|
| 639 |
+
|
| 640 |
+
# 检查LlamaFactory
|
| 641 |
+
try:
|
| 642 |
+
import llamafactory
|
| 643 |
+
print("LlamaFactory available")
|
| 644 |
+
except ImportError:
|
| 645 |
+
print("LlamaFactory not installed")
|
| 646 |
+
print("Install with: pip install llamafactory[torch,metrics]")
|
| 647 |
+
return False
|
| 648 |
+
|
| 649 |
+
# 直接用命令行参数启动聊天
|
| 650 |
+
chat_cmd = [
|
| 651 |
+
"llamafactory-cli", "chat",
|
| 652 |
+
"--model_name_or_path", base_model,
|
| 653 |
+
"--adapter_name_or_path", str(model_path.absolute())
|
| 654 |
+
]
|
| 655 |
+
|
| 656 |
+
print(f"Base model: {base_model}")
|
| 657 |
+
print(f"Adapter path: {model_path}")
|
| 658 |
+
print("-" * 60)
|
| 659 |
+
print("Starting chat session...")
|
| 660 |
+
print("-" * 60)
|
| 661 |
+
|
| 662 |
+
try:
|
| 663 |
+
result = subprocess.run(chat_cmd, check=True)
|
| 664 |
+
print("\nChat session completed")
|
| 665 |
+
return True
|
| 666 |
+
except subprocess.CalledProcessError as e:
|
| 667 |
+
print(f"\nChat failed: {e}")
|
| 668 |
+
return False
|
| 669 |
+
except KeyboardInterrupt:
|
| 670 |
+
print("\n\nChat session ended by user")
|
| 671 |
+
return True
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/cli_webui.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import zipfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Optional, Tuple
|
| 8 |
+
import webbrowser
|
| 9 |
+
import requests
|
| 10 |
+
import threading
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
from dataflow.cli_funcs.utils import _echo
|
| 14 |
+
|
| 15 |
+
OWNER = "OpenDCAI"
|
| 16 |
+
REPO = "DataFlow-WebUI"
|
| 17 |
+
LATEST_API = f"https://api.github.com/repos/{OWNER}/{REPO}/releases/latest"
|
| 18 |
+
REPO_URL = f"https://github.com/{OWNER}/{REPO}"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _ask_yes(prompt: str, default_no: bool = True) -> bool:
|
| 22 |
+
suffix = " [y/N]: " if default_no else " [Y/n]: "
|
| 23 |
+
ans = input(prompt + suffix).strip().lower()
|
| 24 |
+
if not ans:
|
| 25 |
+
return not default_no
|
| 26 |
+
return ans in {"y", "yes"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _confirm_yes() -> None:
|
| 30 |
+
_echo(f"This will run DataFlow-WebUI ({REPO_URL}) by using a GitHub Release zip.", "yellow")
|
| 31 |
+
# if input("Type 'yes' to continue: ").strip().lower() != "yes":
|
| 32 |
+
# if not _ask_yes("Do you confirm to continue?", default_no=False):
|
| 33 |
+
# raise SystemExit(0)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _pick_zip(release: dict) -> Tuple[str, str, str]:
|
| 37 |
+
tag = release.get("tag_name") or "latest"
|
| 38 |
+
for a in release.get("assets", []):
|
| 39 |
+
name = a.get("name", "")
|
| 40 |
+
url = a.get("browser_download_url", "")
|
| 41 |
+
if name.startswith("DataFlow-WebUI-") and name.endswith(".zip") and url:
|
| 42 |
+
return tag, name, url
|
| 43 |
+
raise RuntimeError("No DataFlow-WebUI-*.zip found in latest release.")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _ask_base_dir(default: Path) -> Path:
|
| 47 |
+
_echo(f"Default download directory: {default}", "cyan")
|
| 48 |
+
ans = input(f"Download directory [{default}]: ").strip()
|
| 49 |
+
return (Path(ans).expanduser().resolve() if ans else default.resolve())
|
| 50 |
+
|
| 51 |
+
def _open_browser(url: str) -> None:
|
| 52 |
+
try:
|
| 53 |
+
ok = webbrowser.open(url, new=2) # new=2: new tab if possible
|
| 54 |
+
if ok:
|
| 55 |
+
_echo(f"Opened browser: {url}", "green")
|
| 56 |
+
else:
|
| 57 |
+
_echo(f"Please open in browser: {url}", "cyan")
|
| 58 |
+
except Exception:
|
| 59 |
+
_echo(f"Please open in browser: {url}", "cyan")
|
| 60 |
+
|
| 61 |
+
def _wait_open_browser_async(host: str, port: int, path: str = "", timeout_s: int = 60) -> None:
|
| 62 |
+
"""
|
| 63 |
+
Start a daemon thread:
|
| 64 |
+
- poll http://{host}:{port}{path} every 1s
|
| 65 |
+
- within timeout_s, once any HTTP response is received, open browser and report to stdout
|
| 66 |
+
- if timeout, report startup failure (cannot stop uvicorn because we use os.system)
|
| 67 |
+
"""
|
| 68 |
+
# 0.0.0.0 只能 bind,不能用于本机访问;本机访问用 127.0.0.1
|
| 69 |
+
visit_host = "127.0.0.1" if host in {"0.0.0.0", "0.0.0.0/0"} else host
|
| 70 |
+
url = f"http://{visit_host}:{port}"
|
| 71 |
+
ui_url = f"{url}{path}"
|
| 72 |
+
if not url.endswith("/"):
|
| 73 |
+
url += "/"
|
| 74 |
+
|
| 75 |
+
def _worker() -> None:
|
| 76 |
+
_echo(f"[webui] Waiting for server... {url} (timeout={timeout_s}s)", "cyan")
|
| 77 |
+
start = time.time()
|
| 78 |
+
while time.time() - start < timeout_s:
|
| 79 |
+
try:
|
| 80 |
+
# 只要能建立连接并拿到任意 HTTP 响应就算 ready
|
| 81 |
+
r = requests.get(url, timeout=0.8)
|
| 82 |
+
_echo(f"[webui] Server is up ({r.status_code}). Opening browser: {url}", "green")
|
| 83 |
+
try:
|
| 84 |
+
webbrowser.open(ui_url, new=2)
|
| 85 |
+
except Exception as e:
|
| 86 |
+
_echo(f"[webui] Failed to open browser automatically: {e}", "yellow")
|
| 87 |
+
_echo(f"[webui] Please open manually: {url}", "cyan")
|
| 88 |
+
return
|
| 89 |
+
except Exception:
|
| 90 |
+
time.sleep(1)
|
| 91 |
+
|
| 92 |
+
_echo(f"[webui] Timeout after {timeout_s}s — server did not respond at {url}", "red")
|
| 93 |
+
_echo("[webui] Startup may have failed (or is still starting). Check terminal logs above.", "yellow")
|
| 94 |
+
|
| 95 |
+
t = threading.Thread(target=_worker, daemon=True)
|
| 96 |
+
t.start()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _download_with_progress(url: str, dst: Path) -> None:
|
| 100 |
+
try:
|
| 101 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
with requests.get(url, stream=True, timeout=120) as r:
|
| 103 |
+
r.raise_for_status()
|
| 104 |
+
total = int(r.headers.get("Content-Length", 0))
|
| 105 |
+
downloaded = 0
|
| 106 |
+
last_percent = -1
|
| 107 |
+
|
| 108 |
+
with open(dst, "wb") as f:
|
| 109 |
+
for chunk in r.iter_content(chunk_size=100 * 1024):
|
| 110 |
+
if not chunk:
|
| 111 |
+
continue
|
| 112 |
+
f.write(chunk)
|
| 113 |
+
downloaded += len(chunk)
|
| 114 |
+
|
| 115 |
+
if total > 0:
|
| 116 |
+
percent = int(downloaded * 100 / total)
|
| 117 |
+
if percent != last_percent:
|
| 118 |
+
mb_done = downloaded / (1024 * 1024)
|
| 119 |
+
mb_total = total / (1024 * 1024)
|
| 120 |
+
print(
|
| 121 |
+
f"\rDownloading: {percent:3d}% "
|
| 122 |
+
f"({mb_done:.1f}/{mb_total:.1f} MB)",
|
| 123 |
+
end="",
|
| 124 |
+
flush=True,
|
| 125 |
+
)
|
| 126 |
+
last_percent = percent
|
| 127 |
+
|
| 128 |
+
if total > 0:
|
| 129 |
+
print() # 换行
|
| 130 |
+
except Exception as e:
|
| 131 |
+
print(e)
|
| 132 |
+
if dst.exists():
|
| 133 |
+
dst.unlink(missing_ok=True)
|
| 134 |
+
raise RuntimeError(f"Download failed: {e}, please mannually fetch it from {url}") from e
|
| 135 |
+
|
| 136 |
+
def _run_in_dir(workdir: Path, cmd: str) -> int:
|
| 137 |
+
old = Path.cwd()
|
| 138 |
+
try:
|
| 139 |
+
os.chdir(workdir)
|
| 140 |
+
return os.system(cmd)
|
| 141 |
+
finally:
|
| 142 |
+
os.chdir(old)
|
| 143 |
+
def _resolve_backend_dir(webui_path: Path) -> Path:
|
| 144 |
+
"""
|
| 145 |
+
webui_path 可以是:
|
| 146 |
+
- 直接指向 backend/ 目录
|
| 147 |
+
- 指向解压根目录(里面有 backend/)
|
| 148 |
+
"""
|
| 149 |
+
p = Path(webui_path).expanduser().resolve()
|
| 150 |
+
if not p.exists() or not p.is_dir():
|
| 151 |
+
raise RuntimeError(f"webui-path not found or not a directory: {p}")
|
| 152 |
+
|
| 153 |
+
# 如果直接就是 backend
|
| 154 |
+
if (p / "requirements.txt").is_file() and (p / "app").is_dir():
|
| 155 |
+
return p
|
| 156 |
+
|
| 157 |
+
# 如果是上层目录,尝试找 backend/
|
| 158 |
+
backend = p / "backend"
|
| 159 |
+
if (backend / "requirements.txt").is_file() and (backend / "app").is_dir():
|
| 160 |
+
return backend
|
| 161 |
+
|
| 162 |
+
raise RuntimeError(
|
| 163 |
+
f"Cannot locate backend directory from webui-path: {p}\n"
|
| 164 |
+
"Expected either:\n"
|
| 165 |
+
" - <path>/requirements.txt and <path>/app/\n"
|
| 166 |
+
" - <path>/backend/requirements.txt and <path>/backend/app/"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _load_latest_release() -> Tuple[str, str, str]:
|
| 171 |
+
"""
|
| 172 |
+
返回 (tag, name, url)
|
| 173 |
+
"""
|
| 174 |
+
_echo("loading version info from Github Release...", "cyan")
|
| 175 |
+
r = requests.get(
|
| 176 |
+
LATEST_API,
|
| 177 |
+
headers={"Accept": "application/vnd.github+json"},
|
| 178 |
+
timeout=20,
|
| 179 |
+
)
|
| 180 |
+
r.raise_for_status()
|
| 181 |
+
release = r.json()
|
| 182 |
+
|
| 183 |
+
# 打印 Release 页面路径
|
| 184 |
+
html_url = release.get("html_url")
|
| 185 |
+
if html_url:
|
| 186 |
+
_echo(f"Latest release page: {html_url}", "green")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
tag, name, url = _pick_zip(release)
|
| 190 |
+
return tag, name, url
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def cli_webui(
|
| 194 |
+
zip_path: Optional[Path] = None,
|
| 195 |
+
webui_path: Optional[Path] = None,
|
| 196 |
+
host: str = "0.0.0.0",
|
| 197 |
+
port: int = 8000,
|
| 198 |
+
) -> None:
|
| 199 |
+
_confirm_yes()
|
| 200 |
+
|
| 201 |
+
# 优先级:zip_path > webui_path > 云端下载交互
|
| 202 |
+
if zip_path is not None:
|
| 203 |
+
# ---- Case A: 本地 zip(自动解压并运行)----
|
| 204 |
+
zip_path = Path(zip_path).expanduser().resolve()
|
| 205 |
+
if not zip_path.is_file():
|
| 206 |
+
raise RuntimeError(f"zip-path not found: {zip_path}")
|
| 207 |
+
|
| 208 |
+
_echo(f"Using local zip: {zip_path}", "green")
|
| 209 |
+
|
| 210 |
+
# 选择 base dir(用于解压目录)
|
| 211 |
+
base_dir = _ask_base_dir(Path.cwd() / "dataflow_webui")
|
| 212 |
+
downloads = base_dir / "downloads"
|
| 213 |
+
releases = base_dir / "releases"
|
| 214 |
+
downloads.mkdir(parents=True, exist_ok=True)
|
| 215 |
+
releases.mkdir(parents=True, exist_ok=True)
|
| 216 |
+
_echo(f"Base directory: {base_dir}", "green")
|
| 217 |
+
|
| 218 |
+
tag = "local"
|
| 219 |
+
extract_dir = releases / tag
|
| 220 |
+
|
| 221 |
+
# 解压:若已存在则询问是否覆盖提取
|
| 222 |
+
if extract_dir.exists():
|
| 223 |
+
_echo(f"Found existing extracted dir: {extract_dir}", "yellow")
|
| 224 |
+
if _ask_yes("Overwrite and re-extract?", default_no=True):
|
| 225 |
+
shutil.rmtree(extract_dir)
|
| 226 |
+
_echo(f"Extracting → {extract_dir}", "cyan")
|
| 227 |
+
extract_dir.mkdir(parents=True, exist_ok=True)
|
| 228 |
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
| 229 |
+
zf.extractall(extract_dir)
|
| 230 |
+
else:
|
| 231 |
+
_echo("Using existing extracted files (skip extract).", "green")
|
| 232 |
+
else:
|
| 233 |
+
_echo(f"Extracting → {extract_dir}", "cyan")
|
| 234 |
+
extract_dir.mkdir(parents=True, exist_ok=True)
|
| 235 |
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
| 236 |
+
zf.extractall(extract_dir)
|
| 237 |
+
|
| 238 |
+
# 定位 backend
|
| 239 |
+
dirs = [p for p in extract_dir.iterdir() if p.is_dir()]
|
| 240 |
+
root = dirs[0] if len(dirs) == 1 else extract_dir
|
| 241 |
+
backend = root / "backend"
|
| 242 |
+
if not backend.exists():
|
| 243 |
+
raise RuntimeError("backend/ directory not found after extraction.")
|
| 244 |
+
|
| 245 |
+
elif webui_path is not None:
|
| 246 |
+
# ---- Case B: 直接传已解压的后端目录(直接运行)----
|
| 247 |
+
backend = _resolve_backend_dir(Path(webui_path))
|
| 248 |
+
_echo(f"Using existing backend directory: {backend}", "green")
|
| 249 |
+
|
| 250 |
+
else:
|
| 251 |
+
# ---- Case C: 两者都 None:先加载云端版本 -> 询问是否下载最新 -> 确认下载路径 -> 覆盖询问 ----
|
| 252 |
+
tag, name, url = _load_latest_release()
|
| 253 |
+
_echo(f"Latest release: {tag} ({name})", "green")
|
| 254 |
+
|
| 255 |
+
if not _ask_yes(f"Download latest release {tag} now?", default_no=True):
|
| 256 |
+
_echo("Cancelled. No zip-path/webui-path provided and you chose not to download.", "yellow")
|
| 257 |
+
return
|
| 258 |
+
|
| 259 |
+
# 确认下载路径(base dir)
|
| 260 |
+
base_dir = _ask_base_dir(Path.cwd() / "dataflow_webui")
|
| 261 |
+
downloads = base_dir / "downloads"
|
| 262 |
+
releases = base_dir / "releases"
|
| 263 |
+
downloads.mkdir(parents=True, exist_ok=True)
|
| 264 |
+
releases.mkdir(parents=True, exist_ok=True)
|
| 265 |
+
_echo(f"Base directory: {base_dir}", "green")
|
| 266 |
+
|
| 267 |
+
zip_path = downloads / name
|
| 268 |
+
_echo(f"Download to : {zip_path}", "cyan")
|
| 269 |
+
|
| 270 |
+
# 若 zip 已存在:询问 overwrite download
|
| 271 |
+
if zip_path.exists() and zip_path.stat().st_size > 0:
|
| 272 |
+
_echo(f"Found existing zip: {zip_path}", "yellow")
|
| 273 |
+
if _ask_yes("Overwrite and re-download this zip?", default_no=True):
|
| 274 |
+
zip_path.unlink(missing_ok=True)
|
| 275 |
+
_echo(f"Re-downloading → {zip_path}", "cyan")
|
| 276 |
+
_download_with_progress(url, zip_path)
|
| 277 |
+
else:
|
| 278 |
+
_echo("Using existing zip (skip download).", "green")
|
| 279 |
+
else:
|
| 280 |
+
_echo(f"Downloading: {name}", "cyan")
|
| 281 |
+
_download_with_progress(url, zip_path)
|
| 282 |
+
|
| 283 |
+
# 解压目录:releases/tag
|
| 284 |
+
extract_dir = releases / tag
|
| 285 |
+
|
| 286 |
+
# 若解压目录存在:询问是否覆盖提取
|
| 287 |
+
if extract_dir.exists():
|
| 288 |
+
_echo(f"Found existing extracted dir: {extract_dir}", "yellow")
|
| 289 |
+
if _ask_yes("Overwrite and re-extract?", default_no=True):
|
| 290 |
+
shutil.rmtree(extract_dir)
|
| 291 |
+
_echo(f"Extracting → {extract_dir}", "cyan")
|
| 292 |
+
extract_dir.mkdir(parents=True, exist_ok=True)
|
| 293 |
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
| 294 |
+
zf.extractall(extract_dir)
|
| 295 |
+
else:
|
| 296 |
+
_echo("Using existing extracted files (skip extract).", "green")
|
| 297 |
+
else:
|
| 298 |
+
_echo(f"Extracting → {extract_dir}", "cyan")
|
| 299 |
+
extract_dir.mkdir(parents=True, exist_ok=True)
|
| 300 |
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
| 301 |
+
zf.extractall(extract_dir)
|
| 302 |
+
|
| 303 |
+
# 定位 backend
|
| 304 |
+
dirs = [p for p in extract_dir.iterdir() if p.is_dir()]
|
| 305 |
+
root = dirs[0] if len(dirs) == 1 else extract_dir
|
| 306 |
+
backend = root / "backend"
|
| 307 |
+
if not backend.exists():
|
| 308 |
+
raise RuntimeError("backend/ directory not found after extraction.")
|
| 309 |
+
|
| 310 |
+
# 统一:安装依赖 + 运行(保留 host/port)
|
| 311 |
+
_echo(f"Backend directory: {backend}", "green")
|
| 312 |
+
_echo("Installing backend requirements into current Python environment...", "cyan")
|
| 313 |
+
_rc = _run_in_dir(backend, "python -m pip install -r requirements.txt")
|
| 314 |
+
if _rc != 0:
|
| 315 |
+
raise RuntimeError("pip install failed (see logs above).")
|
| 316 |
+
|
| 317 |
+
_echo(f"Starting WebUI at http://{host}:{port}", "green")
|
| 318 |
+
_wait_open_browser_async(host, port, path="", timeout_s=60)
|
| 319 |
+
_rc = _run_in_dir(
|
| 320 |
+
backend,
|
| 321 |
+
f"python -m uvicorn app.main:app --reload --reload-dir app --host {host} --port {port}",
|
| 322 |
+
)
|
| 323 |
+
if _rc != 0:
|
| 324 |
+
raise RuntimeError("uvicorn exited with error (see logs above).")
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/copy_funcs.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import shutil
|
| 2 |
+
from colorama import init, Fore, Style
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
def copy_file(source: Path, destination: Path):
|
| 6 |
+
"""
|
| 7 |
+
Copy a single file with path, with checking and asking about the existence.
|
| 8 |
+
"""
|
| 9 |
+
if not source.is_file():
|
| 10 |
+
print(f"Error: {source} is not a file.")
|
| 11 |
+
return
|
| 12 |
+
|
| 13 |
+
if destination.exists():
|
| 14 |
+
print(f"Warning: {destination.name} already exists in {destination.parent}.")
|
| 15 |
+
user_input = input(f"Do you want to overwrite {destination.name}? (y/n): ").strip().lower()
|
| 16 |
+
if user_input != 'y':
|
| 17 |
+
print(f"Skipping {destination.name}.")
|
| 18 |
+
return
|
| 19 |
+
|
| 20 |
+
shutil.copy(source, destination)
|
| 21 |
+
print(f"Copied {source.name} to {destination}.")
|
| 22 |
+
|
| 23 |
+
def copy_files_without_recursion(source: Path, destination):
|
| 24 |
+
"""
|
| 25 |
+
Copy files under a path without recursion, with checking and asking about the existence.
|
| 26 |
+
"""
|
| 27 |
+
yes_to_all, none_to_all = False, False
|
| 28 |
+
|
| 29 |
+
for template_file in source.iterdir():
|
| 30 |
+
if template_file.is_file():
|
| 31 |
+
if template_file.name == "__init__.py":
|
| 32 |
+
continue # skip __init__.py files
|
| 33 |
+
destination_file = Path(destination) / template_file.name
|
| 34 |
+
if destination_file.exists():
|
| 35 |
+
if none_to_all:
|
| 36 |
+
print(f' Skipping {template_file.name}.\n')
|
| 37 |
+
continue
|
| 38 |
+
if not yes_to_all:
|
| 39 |
+
# Alert , whether overwrite?
|
| 40 |
+
print(f' {Fore.YELLOW}Warning: {template_file.name} already exists in {destination}.{Style.RESET_ALL}')
|
| 41 |
+
user_input = input(f' Do you want to overwrite {template_file.name}? (y/n/all/none): ').strip().lower()
|
| 42 |
+
if user_input == 'all':
|
| 43 |
+
yes_to_all = True
|
| 44 |
+
elif user_input == 'none':
|
| 45 |
+
none_to_all = True
|
| 46 |
+
print(f' Skipping {template_file.name}.\n')
|
| 47 |
+
continue
|
| 48 |
+
elif user_input != 'y':
|
| 49 |
+
print(f' Skipping {template_file.name}.\n')
|
| 50 |
+
continue
|
| 51 |
+
shutil.copy(template_file, destination_file)
|
| 52 |
+
print(f' Copied {template_file.name} to {destination}.\n')
|
| 53 |
+
|
| 54 |
+
def copy_files_recursively(source_path: Path, destination_path: Path):
|
| 55 |
+
"""
|
| 56 |
+
Recursively copy all contents from source_path to destination_path.
|
| 57 |
+
Prompts user if a file already exists in destination.
|
| 58 |
+
"""
|
| 59 |
+
if not source_path.exists():
|
| 60 |
+
print(f"{Fore.RED}Error: Source path does not exist.{Style.RESET_ALL}")
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
if not source_path.is_dir():
|
| 64 |
+
print(f"{Fore.RED}Error: Source path is not a directory.{Style.RESET_ALL}")
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
yes_to_all = False
|
| 68 |
+
none_to_all = False
|
| 69 |
+
|
| 70 |
+
for item in source_path.rglob('*'):
|
| 71 |
+
relative_path = item.relative_to(source_path)
|
| 72 |
+
dest_item = destination_path / relative_path
|
| 73 |
+
|
| 74 |
+
if item.is_dir():
|
| 75 |
+
dest_item.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
else:
|
| 77 |
+
if dest_item.exists():
|
| 78 |
+
if yes_to_all:
|
| 79 |
+
pass # proceed with overwrite
|
| 80 |
+
elif none_to_all:
|
| 81 |
+
print(f' Skipping {dest_item.name}.\n')
|
| 82 |
+
continue
|
| 83 |
+
else:
|
| 84 |
+
print(f' {Fore.YELLOW}Warning: {dest_item.name} already exists in {destination_path}.{Style.RESET_ALL}')
|
| 85 |
+
user_input = input(f' Do you want to overwrite {dest_item.name}? (y/n/all/none): ').strip().lower()
|
| 86 |
+
if user_input == 'all':
|
| 87 |
+
yes_to_all = True
|
| 88 |
+
elif user_input == 'none':
|
| 89 |
+
none_to_all = True
|
| 90 |
+
print(f' Skipping {dest_item.name}.\n')
|
| 91 |
+
continue
|
| 92 |
+
elif user_input != 'y':
|
| 93 |
+
print(f' Skipping {dest_item.name}.\n')
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
shutil.copy2(item, dest_item)
|
| 97 |
+
# give a clear output with multi line
|
| 98 |
+
print(f'{Fore.GREEN}[Copied]\nFrom: {item}\nTo: {dest_item}{Style.RESET_ALL}\n')
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_api.cpython-311.pyc
ADDED
|
Binary file (6.43 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/__pycache__/eval_local.cpython-311.pyc
ADDED
|
Binary file (8.02 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_api.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# eval_api.py - API评估配置文件
|
| 2 |
+
"""DataFlow API Evaluation Configuration - Enhanced Version"""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
from dataflow.operators.core_text import BenchDatasetEvaluatorQuestion
|
| 6 |
+
from dataflow.serving import APILLMServing_request
|
| 7 |
+
from dataflow.utils.storage import FileStorage
|
| 8 |
+
from dataflow.cli_funcs.cli_eval import run_evaluation
|
| 9 |
+
|
| 10 |
+
# =============================================================================
|
| 11 |
+
# Fair Evaluation Prompt Template
|
| 12 |
+
# =============================================================================
|
| 13 |
+
|
| 14 |
+
class FairAnswerJudgePrompt:
|
| 15 |
+
"""Fair answer evaluation prompt template with English prompts"""
|
| 16 |
+
|
| 17 |
+
# 默认评估模型提示词 该prompt为评估模型的提示词,请勿与被评估模型提示词混淆
|
| 18 |
+
def build_prompt(self, question, answer, reference_answer):
|
| 19 |
+
prompt = f"""You are an expert evaluator assessing answer quality for academic questions.
|
| 20 |
+
**Question:**
|
| 21 |
+
{question}
|
| 22 |
+
|
| 23 |
+
**Answer to Evaluate:**
|
| 24 |
+
{answer}
|
| 25 |
+
|
| 26 |
+
**Evaluation Instructions:**
|
| 27 |
+
Judge this answer based on:
|
| 28 |
+
1. **Factual Accuracy**: Is the information correct?
|
| 29 |
+
2. **Completeness**: Does it address the key aspects of the question?
|
| 30 |
+
3. **Relevance**: Is it directly related to what was asked?
|
| 31 |
+
4. **Academic Quality**: Is the reasoning sound and appropriate?
|
| 32 |
+
|
| 33 |
+
**Important Guidelines:**
|
| 34 |
+
- Focus on content correctness, not writing style
|
| 35 |
+
- A good answer may be longer, shorter, or differently structured
|
| 36 |
+
- Accept different valid approaches or explanations
|
| 37 |
+
- Judge based on whether the answer demonstrates correct understanding
|
| 38 |
+
- Consider partial credit for answers that are mostly correct
|
| 39 |
+
|
| 40 |
+
**Reference Answer (for context only):** {reference_answer}
|
| 41 |
+
|
| 42 |
+
**Output Format:**
|
| 43 |
+
Return your judgment in JSON format:
|
| 44 |
+
{{"judgement_result": true}} if the answer is factually correct and adequately addresses the question
|
| 45 |
+
{{"judgement_result": false}} if the answer contains significant errors or fails to address the question
|
| 46 |
+
|
| 47 |
+
**Your Judgment:**"""
|
| 48 |
+
return prompt
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# =============================================================================
|
| 52 |
+
# Configuration Parameters
|
| 53 |
+
# 参数设置
|
| 54 |
+
# =============================================================================
|
| 55 |
+
|
| 56 |
+
# Judge Model Configuration (API model as judge)
|
| 57 |
+
# 评估模型设置
|
| 58 |
+
JUDGE_MODEL_CONFIG = {
|
| 59 |
+
"model_name": "gpt-4o-mini",
|
| 60 |
+
"api_url": "API_URL", # 请求URL 必填 / request (required)
|
| 61 |
+
"api_key_env": "DF_API_KEY", # api_key 必填 / api_key (required)
|
| 62 |
+
"max_workers": 3,
|
| 63 |
+
"max_retries": 5,
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
# Target Models Configuration (List format - required, each element is a dict)
|
| 67 |
+
# 被评估模型设置 (列表格式 - 必需,每个元素是字典)
|
| 68 |
+
TARGET_MODELS = [
|
| 69 |
+
# {
|
| 70 |
+
# "name": "qwen_3b", # 模型名称(可选,默认使用路径最后一部分) / Model name (optional, uses the last part of the path by default)
|
| 71 |
+
# "path": "./Qwen2.5-3B-Instruct", # 模型路径(必需) / Model path (required)
|
| 72 |
+
|
| 73 |
+
# # ===== 答案生成的模型加载参数(可选)=====
|
| 74 |
+
# "tensor_parallel_size": 1, # GPU并行数量 / Number of GPU parallels
|
| 75 |
+
# "max_tokens": 1024, # 最大生成token数 / Maximum number of generated tokens
|
| 76 |
+
# "gpu_memory_utilization": 0.8, # GPU显存利用率 / GPU memory utilization
|
| 77 |
+
# },
|
| 78 |
+
{
|
| 79 |
+
"name": "qwen_7b",
|
| 80 |
+
"path": "./Qwen2.5-7B-Instruct",
|
| 81 |
+
# 大模型可以用不同的参数
|
| 82 |
+
"vllm_tensor_parallel_size": 1,
|
| 83 |
+
"vllm_temperature" : 0.1,
|
| 84 |
+
"vllm_top_p" :0.9,
|
| 85 |
+
"vllm_max_tokens": 2048,
|
| 86 |
+
"vllm_repetition_penalty":1.0,
|
| 87 |
+
"vllm_seed":None,
|
| 88 |
+
"vllm_gpu_memory_utilization": 0.9,
|
| 89 |
+
|
| 90 |
+
# 可以为每个模型自定义提示词 不写就为默认模板 即build_prompt函数中的prompt
|
| 91 |
+
# 默认被评估模型提示词
|
| 92 |
+
# 再次提示:该prompt为被评估模型的提示词,请勿与评估模型提示词混淆!!!
|
| 93 |
+
# You can customize prompts for each model. If not specified, defaults to the template in build_prompt function.
|
| 94 |
+
# Default prompt for evaluated models
|
| 95 |
+
# IMPORTANT: This is the prompt for models being evaluated, NOT for the judge model!!!
|
| 96 |
+
"answer_prompt": """please answer the following question:""" # 这里不要使用{question} / do not code {question} here
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"name": "qwen_3b",
|
| 100 |
+
"path": "./Qwen2.5-3B-Instruct",
|
| 101 |
+
# 大模型可以用不同的参数
|
| 102 |
+
"vllm_tensor_parallel_size": 1,
|
| 103 |
+
"vllm_temperature" : 0.1,
|
| 104 |
+
"vllm_top_p" :0.9,
|
| 105 |
+
"vllm_max_tokens": 2048,
|
| 106 |
+
"vllm_repetition_penalty":1.0,
|
| 107 |
+
"vllm_seed":None,
|
| 108 |
+
"vllm_gpu_memory_utilization": 0.9,
|
| 109 |
+
|
| 110 |
+
# 可以为每个模型自定义提示词 不写就为默认模板 即build_prompt函数中的prompt
|
| 111 |
+
# 默认被评估模型提示词
|
| 112 |
+
# 再次提示:该prompt为被评估模型的提示词,请勿与评估模型提示词混淆!!!
|
| 113 |
+
# You can customize prompts for each model. If not specified, defaults to the template in build_prompt function.
|
| 114 |
+
# Default prompt for evaluated models
|
| 115 |
+
# IMPORTANT: This is the prompt for models being evaluated, NOT for the judge model!!!
|
| 116 |
+
"answer_prompt": """please answer the following question:""" # 这里不要使用{question} / do not code {question} here
|
| 117 |
+
},
|
| 118 |
+
|
| 119 |
+
# 添加更多模型...
|
| 120 |
+
# {
|
| 121 |
+
# "name": "llama_8b",
|
| 122 |
+
# "path": "meta-llama/Llama-3-8B-Instruct",
|
| 123 |
+
# "tensor_parallel_size": 2
|
| 124 |
+
# }
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
# Data Configuration
|
| 128 |
+
BENCH_CONFIG = [
|
| 129 |
+
{
|
| 130 |
+
"name":"bench_name",
|
| 131 |
+
"input_file": "./.cache/data/qa.json", # 输入数据文件
|
| 132 |
+
"output_dir": "./api_eval", # 输出目录
|
| 133 |
+
"question_key": "input", # 原始数据中的问题字段
|
| 134 |
+
"reference_answer_key": "output" # 原始数据中的参考答案字段
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"name":"bench_name_1",
|
| 138 |
+
"input_file": "./.cache/data/data_qa.json", # 输入数据文件
|
| 139 |
+
"output_dir": "./api_eval", # 输出目录
|
| 140 |
+
"question_key": "input", # 原始数据中的问题字段
|
| 141 |
+
"reference_answer_key": "output" # 原始数据中的参考答案字段
|
| 142 |
+
}
|
| 143 |
+
]
|
| 144 |
+
# Evaluator Run Configuration (parameters passed to BenchDatasetEvaluator.run)
|
| 145 |
+
EVALUATOR_RUN_CONFIG = {
|
| 146 |
+
"input_test_answer_key": "model_generated_answer", # 模型生成的答案字段名
|
| 147 |
+
"input_gt_answer_key": "output", # 标准答案字段名(对应原始数据)
|
| 148 |
+
"input_question_key": "input" # 问题字段名(对应原始数据)
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
# Evaluation Configuration
|
| 152 |
+
EVAL_CONFIG = {
|
| 153 |
+
"compare_method": "semantic", # "semantic" 语义匹配 或 "match" 字段完全匹配
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# =============================================================================
|
| 158 |
+
# Component Creation Functions
|
| 159 |
+
# =============================================================================
|
| 160 |
+
|
| 161 |
+
def create_judge_serving():
|
| 162 |
+
"""创建评估器LLM服务(API模式)"""
|
| 163 |
+
api_key_env = JUDGE_MODEL_CONFIG["api_key_env"]
|
| 164 |
+
if api_key_env not in os.environ:
|
| 165 |
+
raise ValueError(f"Environment variable {api_key_env} is not set. "
|
| 166 |
+
f"Please set it with your API key.")
|
| 167 |
+
|
| 168 |
+
api_key = os.environ[api_key_env]
|
| 169 |
+
if not api_key.strip():
|
| 170 |
+
raise ValueError(f"Environment variable {api_key_env} is empty. "
|
| 171 |
+
f"Please provide a valid API key.")
|
| 172 |
+
|
| 173 |
+
return APILLMServing_request(
|
| 174 |
+
api_url=JUDGE_MODEL_CONFIG["api_url"],
|
| 175 |
+
key_name_of_api_key=api_key_env,
|
| 176 |
+
model_name=JUDGE_MODEL_CONFIG["model_name"],
|
| 177 |
+
max_workers=JUDGE_MODEL_CONFIG.get("max_workers", 10),
|
| 178 |
+
max_retries=JUDGE_MODEL_CONFIG.get("max_retries", 5)
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def create_evaluator(judge_serving, eval_result_path):
|
| 183 |
+
"""创建评估算子"""
|
| 184 |
+
return BenchDatasetEvaluatorQuestion(
|
| 185 |
+
compare_method=EVAL_CONFIG["compare_method"],
|
| 186 |
+
llm_serving=judge_serving,
|
| 187 |
+
prompt_template=FairAnswerJudgePrompt(),
|
| 188 |
+
eval_result_path=eval_result_path
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def create_storage(data_file, cache_path,bench_name="eval_result"):
|
| 193 |
+
"""创建存储算子"""
|
| 194 |
+
return FileStorage(
|
| 195 |
+
first_entry_file_name=data_file,
|
| 196 |
+
cache_path=cache_path,
|
| 197 |
+
file_name_prefix=bench_name,
|
| 198 |
+
cache_type="json"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# =============================================================================
|
| 203 |
+
# Main Configuration Function
|
| 204 |
+
# =============================================================================
|
| 205 |
+
|
| 206 |
+
def get_evaluator_config():
|
| 207 |
+
# 返回完整配置
|
| 208 |
+
# Return complete configuration
|
| 209 |
+
return {
|
| 210 |
+
"JUDGE_MODEL_CONFIG": JUDGE_MODEL_CONFIG, # 评估模型设置映射
|
| 211 |
+
"TARGET_MODELS": TARGET_MODELS, # 被评估模型设置映射
|
| 212 |
+
"BENCH_CONFIG": BENCH_CONFIG, # 数据设置映射
|
| 213 |
+
"EVAL_CONFIG": EVAL_CONFIG, # 评估模式设置映射
|
| 214 |
+
"EVALUATOR_RUN_CONFIG": EVALUATOR_RUN_CONFIG, # 评估数据集字段映射
|
| 215 |
+
"create_judge_serving": create_judge_serving,
|
| 216 |
+
"create_evaluator": create_evaluator,
|
| 217 |
+
"create_storage": create_storage
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# =============================================================================
|
| 222 |
+
# Direct Execution Support
|
| 223 |
+
# 直接运行评估
|
| 224 |
+
# =============================================================================
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
# 直接运行时的简单评估
|
| 228 |
+
# Simple evaluation when run directly
|
| 229 |
+
print("Starting API evaluation...")
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
config = get_evaluator_config()
|
| 233 |
+
success = run_evaluation(config)
|
| 234 |
+
|
| 235 |
+
if success:
|
| 236 |
+
print("API evaluation completed successfully")
|
| 237 |
+
else:
|
| 238 |
+
print("API evaluation failed")
|
| 239 |
+
except Exception as e:
|
| 240 |
+
print(f"Evaluation error: {e}")
|
| 241 |
+
import traceback
|
| 242 |
+
|
| 243 |
+
traceback.print_exc()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/eval_pipeline/eval_local.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
# eval_local.py - 本地评估配置文件
|
| 2 |
+
"""DataFlow Local Evaluation Configuration - Enhanced Version"""
|
| 3 |
+
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from dataflow.serving import LocalModelLLMServing_vllm
|
| 6 |
+
from dataflow.utils.storage import FileStorage
|
| 7 |
+
from dataflow.operators.core_text import BenchDatasetEvaluatorQuestion
|
| 8 |
+
from dataflow.cli_funcs.cli_eval import run_evaluation
|
| 9 |
+
|
| 10 |
+
# =============================================================================
|
| 11 |
+
# Fair Evaluation Prompt Template
|
| 12 |
+
# =============================================================================
|
| 13 |
+
|
| 14 |
+
class FairAnswerJudgePrompt:
|
| 15 |
+
"""Fair answer evaluation prompt template with English prompts"""
|
| 16 |
+
|
| 17 |
+
def build_prompt(self, question, answer, reference_answer):
|
| 18 |
+
prompt = f"""You are an expert evaluator assessing answer quality for academic questions.
|
| 19 |
+
**Question:**
|
| 20 |
+
{question}
|
| 21 |
+
|
| 22 |
+
**Answer to Evaluate:**
|
| 23 |
+
{answer}
|
| 24 |
+
|
| 25 |
+
**Evaluation Instructions:**
|
| 26 |
+
Judge this answer based on:
|
| 27 |
+
1. **Factual Accuracy**: Is the information correct?
|
| 28 |
+
2. **Completeness**: Does it address the key aspects of the question?
|
| 29 |
+
3. **Relevance**: Is it directly related to what was asked?
|
| 30 |
+
4. **Academic Quality**: Is the reasoning sound and appropriate?
|
| 31 |
+
|
| 32 |
+
**Important Guidelines:**
|
| 33 |
+
- Focus on content correctness, not writing style
|
| 34 |
+
- A good answer may be longer, shorter, or differently structured
|
| 35 |
+
- Accept different valid approaches or explanations
|
| 36 |
+
- Judge based on whether the answer demonstrates correct understanding
|
| 37 |
+
- Consider partial credit for answers that are mostly correct
|
| 38 |
+
|
| 39 |
+
**Reference Answer (for context only):** {reference_answer}
|
| 40 |
+
|
| 41 |
+
**Output Format:**
|
| 42 |
+
Return your judgment in JSON format:
|
| 43 |
+
{{"judgement_result": true}} if the answer is factually correct and adequately addresses the question
|
| 44 |
+
{{"judgement_result": false}} if the answer contains significant errors or fails to address the question
|
| 45 |
+
|
| 46 |
+
**Your Judgment:**"""
|
| 47 |
+
return prompt
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# =============================================================================
|
| 51 |
+
# Configuration Parameters
|
| 52 |
+
# =============================================================================
|
| 53 |
+
|
| 54 |
+
# Judge Model Configuration (local strong model as judge)
|
| 55 |
+
JUDGE_MODEL_CONFIG = {
|
| 56 |
+
"model_path": "./Qwen2.5-7B-Instruct", # 用更强的模型做裁判
|
| 57 |
+
"hf_cache_dir": "",
|
| 58 |
+
"hf_local_dir": "",
|
| 59 |
+
"vllm_tensor_parallel_size": 1,
|
| 60 |
+
"vllm_temperature": 0.9,
|
| 61 |
+
"vllm_top_p": 0.9,
|
| 62 |
+
"vllm_max_tokens": 512,
|
| 63 |
+
"vllm_repetition_penalty": 0.8,
|
| 64 |
+
"vllm_seed": None,
|
| 65 |
+
"vllm_max_model_len": None,
|
| 66 |
+
"vllm_gpu_memory_utilization": 0.9
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
# Target Models Configuration (字典格式 - 必需)
|
| 70 |
+
TARGET_MODELS = [
|
| 71 |
+
{
|
| 72 |
+
"name": "qwen_3b", # 模型名称(可选,默认使用路径最后一部分)
|
| 73 |
+
"path": "./Qwen2.5-3B-Instruct", # 模型路径(必需)
|
| 74 |
+
|
| 75 |
+
# 大模型可以用不同的参数
|
| 76 |
+
"vllm_tensor_parallel_size": 1,
|
| 77 |
+
"vllm_temperature": 0.1,
|
| 78 |
+
"vllm_top_p": 0.9,
|
| 79 |
+
"vllm_max_tokens": 2048,
|
| 80 |
+
"vllm_repetition_penalty": 1.0,
|
| 81 |
+
"vllm_seed": None,
|
| 82 |
+
"vllm_gpu_memory_utilization": 0.9,
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"name": "qwen_7b",
|
| 86 |
+
"path": "./Qwen2.5-7B-Instruct",
|
| 87 |
+
# 大模型可以用不同的参数
|
| 88 |
+
"vllm_tensor_parallel_size": 1,
|
| 89 |
+
"vllm_temperature": 0.1,
|
| 90 |
+
"vllm_top_p": 0.9,
|
| 91 |
+
"vllm_max_tokens": 2048,
|
| 92 |
+
"vllm_repetition_penalty": 1.0,
|
| 93 |
+
"vllm_seed": None,
|
| 94 |
+
"vllm_gpu_memory_utilization": 0.9,
|
| 95 |
+
|
| 96 |
+
# 可以为每个模型自定义提示词
|
| 97 |
+
"answer_prompt": """Please answer the following question based on the provided information. Put your answer in \\boxed{{}}.
|
| 98 |
+
|
| 99 |
+
For example, if the answer is B, output: \\boxed{{B}}"""
|
| 100 |
+
|
| 101 |
+
},
|
| 102 |
+
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
# Bench Configuration
|
| 106 |
+
BENCH_CONFIG = [
|
| 107 |
+
{
|
| 108 |
+
"name": "bench_name", # bench名称
|
| 109 |
+
"input_file": "./.cache/data/qa.json", # 数据文件
|
| 110 |
+
"question_key": "input", # 问题字段名
|
| 111 |
+
"reference_answer_key": "output", # 答案字段名
|
| 112 |
+
"output_dir": "./eval_results/bench_name", # 输出目录
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"name": "bench_name_1",
|
| 116 |
+
"input_file": "./.cache/data/data_qa.json",
|
| 117 |
+
"question_key": "input",
|
| 118 |
+
"reference_answer_key": "output",
|
| 119 |
+
"output_dir": "./eval_results/bench_name_1",
|
| 120 |
+
},
|
| 121 |
+
# {
|
| 122 |
+
# "name": "code_bench",
|
| 123 |
+
# "input_file": "./.cache/data/code_qa.json",
|
| 124 |
+
# "question_key": "problem",
|
| 125 |
+
# "reference_answer_key": "solution",
|
| 126 |
+
# "output_dir": "./eval_results/code_bench",
|
| 127 |
+
# },
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
# Evaluator Run Configuration (parameters passed to BenchDatasetEvaluator.run)
|
| 131 |
+
EVALUATOR_RUN_CONFIG = {
|
| 132 |
+
"input_test_answer_key": "model_generated_answer", # 模型生成的答案字段名
|
| 133 |
+
"input_gt_answer_key": "output", # 标准答案字段名(对应原始数据)
|
| 134 |
+
"input_question_key": "input" # 问题字段名(对应原始数据)
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
# Evaluation Configuration
|
| 138 |
+
EVAL_CONFIG = {
|
| 139 |
+
"compare_method": "semantic", # "semantic" 语义匹配 或 "match" 字段完全匹配
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# =============================================================================
|
| 144 |
+
# Component Creation Functions - DataFlow Style
|
| 145 |
+
# =============================================================================
|
| 146 |
+
|
| 147 |
+
def create_judge_serving():
|
| 148 |
+
"""创建本地评估器LLM服务"""
|
| 149 |
+
model_path = JUDGE_MODEL_CONFIG["model_path"]
|
| 150 |
+
|
| 151 |
+
# Enhanced model path validation
|
| 152 |
+
if not model_path.startswith(("Qwen", "meta-llama", "microsoft", "google", "huggingface.co")):
|
| 153 |
+
model_path_obj = Path(model_path)
|
| 154 |
+
if not model_path_obj.exists():
|
| 155 |
+
raise FileNotFoundError(f"Local model path does not exist: {model_path}")
|
| 156 |
+
|
| 157 |
+
# Check for required model files
|
| 158 |
+
required_files = ["config.json"]
|
| 159 |
+
missing_files = [f for f in required_files if not (model_path_obj / f).exists()]
|
| 160 |
+
if missing_files:
|
| 161 |
+
raise ValueError(f"Missing required model files in {model_path}: {missing_files}")
|
| 162 |
+
|
| 163 |
+
# Enhanced VLLM configuration
|
| 164 |
+
vllm_config = {
|
| 165 |
+
"hf_model_name_or_path": model_path,
|
| 166 |
+
"hf_cache_dir": JUDGE_MODEL_CONFIG.get("hf_cache_dir"),
|
| 167 |
+
"hf_local_dir": JUDGE_MODEL_CONFIG.get("hf_local_dir"),
|
| 168 |
+
"vllm_tensor_parallel_size": JUDGE_MODEL_CONFIG.get("vllm_tensor_parallel_size", 1),
|
| 169 |
+
"vllm_temperature": JUDGE_MODEL_CONFIG.get("vllm_temperature", 0.9),
|
| 170 |
+
"vllm_top_p": JUDGE_MODEL_CONFIG.get("vllm_top_p", 0.9),
|
| 171 |
+
"vllm_max_tokens": JUDGE_MODEL_CONFIG.get("max_tokens", 512),
|
| 172 |
+
"vllm_repetition_penalty": JUDGE_MODEL_CONFIG.get("vllm_repetition_penalty", 1.0),
|
| 173 |
+
"vllm_seed": JUDGE_MODEL_CONFIG.get("vllm_seed", None),
|
| 174 |
+
"vllm_max_model_len": JUDGE_MODEL_CONFIG.get("vllm_max_model_len", None),
|
| 175 |
+
"vllm_gpu_memory_utilization": JUDGE_MODEL_CONFIG.get("gpu_memory_utilization", 0.9)
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
# Add optional VLLM parameters if they exist
|
| 179 |
+
optional_params = ["dtype", "trust_remote_code", "enforce_eager", "disable_log_stats"]
|
| 180 |
+
for param in optional_params:
|
| 181 |
+
if param in JUDGE_MODEL_CONFIG:
|
| 182 |
+
vllm_config[f"vllm_{param}"] = JUDGE_MODEL_CONFIG[param]
|
| 183 |
+
|
| 184 |
+
return LocalModelLLMServing_vllm(**vllm_config)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def create_evaluator(judge_serving, eval_result_path):
|
| 188 |
+
"""创建评估算子"""
|
| 189 |
+
return BenchDatasetEvaluatorQuestion(
|
| 190 |
+
compare_method=EVAL_CONFIG["compare_method"],
|
| 191 |
+
llm_serving=judge_serving,
|
| 192 |
+
prompt_template=FairAnswerJudgePrompt(),
|
| 193 |
+
eval_result_path=eval_result_path
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def create_storage(data_file, cache_path, bench_name="eval_result"):
|
| 198 |
+
"""创建存储算子"""
|
| 199 |
+
return FileStorage(
|
| 200 |
+
first_entry_file_name=data_file,
|
| 201 |
+
cache_path=cache_path,
|
| 202 |
+
file_name_prefix=bench_name,
|
| 203 |
+
cache_type="json"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# =============================================================================
|
| 208 |
+
# Main Configuration Function
|
| 209 |
+
# =============================================================================
|
| 210 |
+
|
| 211 |
+
def get_evaluator_config():
|
| 212 |
+
"""返回完整配置"""
|
| 213 |
+
return {
|
| 214 |
+
"JUDGE_MODEL_CONFIG": JUDGE_MODEL_CONFIG,
|
| 215 |
+
"TARGET_MODELS": TARGET_MODELS,
|
| 216 |
+
"BENCH_CONFIG": BENCH_CONFIG,
|
| 217 |
+
"EVALUATOR_RUN_CONFIG": EVALUATOR_RUN_CONFIG,
|
| 218 |
+
"EVAL_CONFIG": EVAL_CONFIG,
|
| 219 |
+
"create_judge_serving": create_judge_serving,
|
| 220 |
+
"create_evaluator": create_evaluator,
|
| 221 |
+
"create_storage": create_storage
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# =============================================================================
|
| 226 |
+
# Direct Execution Support
|
| 227 |
+
# =============================================================================
|
| 228 |
+
|
| 229 |
+
if __name__ == "__main__":
|
| 230 |
+
# 直接运行时的简单评估
|
| 231 |
+
print("Starting local evaluation...")
|
| 232 |
+
|
| 233 |
+
try:
|
| 234 |
+
config = get_evaluator_config()
|
| 235 |
+
success = run_evaluation(config)
|
| 236 |
+
|
| 237 |
+
if success:
|
| 238 |
+
print("Local evaluation completed successfully")
|
| 239 |
+
else:
|
| 240 |
+
print("Local evaluation failed")
|
| 241 |
+
except Exception as e:
|
| 242 |
+
print(f"Evaluation error: {e}")
|
| 243 |
+
import traceback
|
| 244 |
+
|
| 245 |
+
traceback.print_exc()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/paths.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import appdirs
|
| 4 |
+
|
| 5 |
+
class DataFlowPath:
|
| 6 |
+
"""
|
| 7 |
+
Class to manage paths for DataFlow.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@staticmethod
|
| 12 |
+
def get_dataflow_dir():
|
| 13 |
+
# return path of /dataflow
|
| 14 |
+
return Path(__file__).parent.parent
|
| 15 |
+
|
| 16 |
+
# @staticmethod
|
| 17 |
+
# def get_dataflow_scripts_dir():
|
| 18 |
+
# return DataFlowPath.get_dataflow_dir() / "scripts"
|
| 19 |
+
|
| 20 |
+
@staticmethod
|
| 21 |
+
def get_dataflow_example_dir():
|
| 22 |
+
return DataFlowPath.get_dataflow_dir() / "example"
|
| 23 |
+
|
| 24 |
+
@staticmethod
|
| 25 |
+
def get_dataflow_statics_dir():
|
| 26 |
+
return DataFlowPath.get_dataflow_dir() / "statics"
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def get_dataflow_pipelines_dir():
|
| 30 |
+
return DataFlowPath.get_dataflow_statics_dir() / "pipelines"
|
| 31 |
+
|
| 32 |
+
@staticmethod
|
| 33 |
+
def get_dataflow_playground_dir():
|
| 34 |
+
return DataFlowPath.get_dataflow_statics_dir() / "playground"
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def get_dataflow_scaffold_dir():
|
| 38 |
+
return DataFlowPath.get_dataflow_statics_dir() / "scaffold"
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc
ADDED
|
Binary file (16.6 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/path_to_jsonl_script.cpython-311.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/__pycache__/pdf_to_qa_pipeline.cpython-311.pyc
ADDED
|
Binary file (6.09 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/llama_factory_trainer.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
LlamaFactory Training Script with YAML Configuration Management
|
| 4 |
+
Complete "check-create-read-train" workflow
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import yaml
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import subprocess
|
| 11 |
+
import argparse
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class LlamaFactoryTrainer:
|
| 16 |
+
def __init__(self, config_path=None, cache_base="./"):
|
| 17 |
+
# 处理cache_base相对路径 - 基于调用者工作目录
|
| 18 |
+
cache_path = Path(cache_base)
|
| 19 |
+
if not cache_path.is_absolute():
|
| 20 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 21 |
+
cache_path = caller_cwd / cache_path
|
| 22 |
+
|
| 23 |
+
self.cache_path = cache_path
|
| 24 |
+
|
| 25 |
+
# 如果没有指定config_path,使用cache目录下的默认路径
|
| 26 |
+
if config_path is None:
|
| 27 |
+
config_path = str(cache_path / ".cache" / "train_config.yaml")
|
| 28 |
+
else:
|
| 29 |
+
# 处理config_path相对路径
|
| 30 |
+
config_path_obj = Path(config_path)
|
| 31 |
+
if not config_path_obj.is_absolute():
|
| 32 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 33 |
+
config_path = str(caller_cwd / config_path_obj)
|
| 34 |
+
|
| 35 |
+
self.config_path = Path(config_path)
|
| 36 |
+
|
| 37 |
+
def get_default_config(self):
|
| 38 |
+
"""Get default configuration - 基于最新LlamaFactory标准"""
|
| 39 |
+
return {
|
| 40 |
+
# === 基础配置 ===
|
| 41 |
+
"stage": "sft",
|
| 42 |
+
"do_train": True,
|
| 43 |
+
|
| 44 |
+
# === 模型配置 ===
|
| 45 |
+
"model_name_or_path": "Qwen/Qwen2.5-7B-Instruct",
|
| 46 |
+
"template": "qwen",
|
| 47 |
+
"trust_remote_code": True,
|
| 48 |
+
|
| 49 |
+
# === 微调方法配置 ===
|
| 50 |
+
"finetuning_type": "lora",
|
| 51 |
+
"lora_target": "all", # 使用 "all" 而不是具体层名
|
| 52 |
+
"lora_rank": 16,
|
| 53 |
+
"lora_alpha": 32,
|
| 54 |
+
"lora_dropout": 0.05,
|
| 55 |
+
|
| 56 |
+
# === 数据集配置 ===
|
| 57 |
+
"dataset": "kb_qa",
|
| 58 |
+
"dataset_dir": str(self.cache_path / ".cache" / "data"),
|
| 59 |
+
"cutoff_len": 1024,
|
| 60 |
+
"max_samples": None,
|
| 61 |
+
"overwrite_cache": True,
|
| 62 |
+
"preprocessing_num_workers": 4,
|
| 63 |
+
|
| 64 |
+
# === 训练配置 ===
|
| 65 |
+
"per_device_train_batch_size": 2,
|
| 66 |
+
"gradient_accumulation_steps": 4,
|
| 67 |
+
"learning_rate": 5e-5,
|
| 68 |
+
"num_train_epochs": 2.0,
|
| 69 |
+
"lr_scheduler_type": "cosine",
|
| 70 |
+
"warmup_ratio": 0.05,
|
| 71 |
+
"weight_decay": 0.01,
|
| 72 |
+
"max_grad_norm": 1.0,
|
| 73 |
+
"optim": "adamw_torch",
|
| 74 |
+
|
| 75 |
+
# === 输出配置 ===
|
| 76 |
+
"output_dir": str(self.cache_path / ".cache" / "saves" / "qwen2.5_7b_sft_model"),
|
| 77 |
+
"overwrite_output_dir": True,
|
| 78 |
+
"save_only_model": True,
|
| 79 |
+
"plot_loss": True,
|
| 80 |
+
|
| 81 |
+
# === 日志和检查点 ===
|
| 82 |
+
"logging_steps": 10,
|
| 83 |
+
"save_steps": 300,
|
| 84 |
+
"save_total_limit": 2,
|
| 85 |
+
|
| 86 |
+
# === 评估配置 ===
|
| 87 |
+
"val_size": 0.1,
|
| 88 |
+
"per_device_eval_batch_size": 2,
|
| 89 |
+
"eval_strategy": "steps",
|
| 90 |
+
"eval_steps": 300,
|
| 91 |
+
|
| 92 |
+
# === 硬件配置 ===
|
| 93 |
+
"fp16": False,
|
| 94 |
+
"bf16": True,
|
| 95 |
+
"tf32": True,
|
| 96 |
+
"dataloader_num_workers": 2,
|
| 97 |
+
|
| 98 |
+
# === 其他配置 ===
|
| 99 |
+
"seed": 42,
|
| 100 |
+
"ddp_timeout": 1800,
|
| 101 |
+
"report_to": "none",
|
| 102 |
+
"run_name": "qwen2.5_7b_sft_training",
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
def check_and_create_config(self):
|
| 106 |
+
"""
|
| 107 |
+
Core logic: check config file, read if exists, create if not
|
| 108 |
+
"""
|
| 109 |
+
# Ensure directory exists
|
| 110 |
+
self.config_path.parent.mkdir(parents=True, exist_ok=True)
|
| 111 |
+
|
| 112 |
+
if self.config_path.exists():
|
| 113 |
+
# Config file exists, read it
|
| 114 |
+
print(f"Found config file: {self.config_path}")
|
| 115 |
+
return self._load_existing_config()
|
| 116 |
+
else:
|
| 117 |
+
# Config file doesn't exist, create default config
|
| 118 |
+
print(f"Creating new config file: {self.config_path}")
|
| 119 |
+
return self._create_new_config()
|
| 120 |
+
|
| 121 |
+
def _load_existing_config(self):
|
| 122 |
+
"""Load existing config file"""
|
| 123 |
+
try:
|
| 124 |
+
with open(self.config_path, 'r', encoding='utf-8') as f:
|
| 125 |
+
config = yaml.safe_load(f)
|
| 126 |
+
print("Config file loaded successfully")
|
| 127 |
+
|
| 128 |
+
# Check if new default parameters need to be added
|
| 129 |
+
default_config = self.get_default_config()
|
| 130 |
+
updated = False
|
| 131 |
+
|
| 132 |
+
for key, value in default_config.items():
|
| 133 |
+
if key not in config:
|
| 134 |
+
config[key] = value
|
| 135 |
+
updated = True
|
| 136 |
+
print(f"Added missing parameter: {key}")
|
| 137 |
+
|
| 138 |
+
# 移除过时的formatting参数
|
| 139 |
+
if "formatting" in config:
|
| 140 |
+
del config["formatting"]
|
| 141 |
+
updated = True
|
| 142 |
+
print("Removed deprecated parameter: formatting")
|
| 143 |
+
|
| 144 |
+
# Save config if updated
|
| 145 |
+
if updated:
|
| 146 |
+
self._save_config(config)
|
| 147 |
+
print("Config file updated")
|
| 148 |
+
|
| 149 |
+
return config
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
print(f"Failed to read config: {e}")
|
| 153 |
+
print("Creating new default config")
|
| 154 |
+
return self._create_new_config()
|
| 155 |
+
|
| 156 |
+
def _create_new_config(self):
|
| 157 |
+
"""Create new default config file"""
|
| 158 |
+
default_config = self.get_default_config()
|
| 159 |
+
|
| 160 |
+
if self._save_config(default_config):
|
| 161 |
+
print("Default config file created successfully")
|
| 162 |
+
return default_config
|
| 163 |
+
else:
|
| 164 |
+
print("Failed to create config file")
|
| 165 |
+
return None
|
| 166 |
+
|
| 167 |
+
def _save_config(self, config):
|
| 168 |
+
"""Save config to file"""
|
| 169 |
+
try:
|
| 170 |
+
with open(self.config_path, 'w', encoding='utf-8') as f:
|
| 171 |
+
yaml.dump(config, f,
|
| 172 |
+
default_flow_style=False,
|
| 173 |
+
allow_unicode=True,
|
| 174 |
+
sort_keys=False,
|
| 175 |
+
indent=2,
|
| 176 |
+
width=80)
|
| 177 |
+
return True
|
| 178 |
+
except Exception as e:
|
| 179 |
+
print(f"Failed to save config: {e}")
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
def update_config(self, updates):
|
| 183 |
+
"""Update config parameters"""
|
| 184 |
+
config = self.check_and_create_config()
|
| 185 |
+
if config is None:
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
config.update(updates)
|
| 189 |
+
if self._save_config(config):
|
| 190 |
+
print(f"Config updated: {list(updates.keys())}")
|
| 191 |
+
return config
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
def print_config_info(self, config):
|
| 195 |
+
"""Print config information"""
|
| 196 |
+
if not config:
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
print("\n" + "=" * 50)
|
| 200 |
+
print("Training Configuration")
|
| 201 |
+
print("=" * 50)
|
| 202 |
+
|
| 203 |
+
key_info = [
|
| 204 |
+
("Model", "model_name_or_path"),
|
| 205 |
+
("Dataset", "dataset"),
|
| 206 |
+
("Template", "template"),
|
| 207 |
+
("LoRA Rank", "lora_rank"),
|
| 208 |
+
("Learning Rate", "learning_rate"),
|
| 209 |
+
("Epochs", "num_train_epochs"),
|
| 210 |
+
("Batch Size", "per_device_train_batch_size"),
|
| 211 |
+
("Output Dir", "output_dir"),
|
| 212 |
+
]
|
| 213 |
+
|
| 214 |
+
for name, key in key_info:
|
| 215 |
+
print(f"{name:<12}: {config.get(key, 'N/A')}")
|
| 216 |
+
|
| 217 |
+
effective_batch = config.get("per_device_train_batch_size", 1) * config.get("gradient_accumulation_steps", 1)
|
| 218 |
+
print(f"Effective Batch: {effective_batch}")
|
| 219 |
+
print("=" * 50)
|
| 220 |
+
|
| 221 |
+
def check_environment(self):
|
| 222 |
+
"""Check training environment"""
|
| 223 |
+
print("Checking training environment...")
|
| 224 |
+
|
| 225 |
+
# 使用绝对路径 - 直接获取调用者工作目录
|
| 226 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 227 |
+
data_dir = caller_cwd / ".cache" / "data"
|
| 228 |
+
|
| 229 |
+
# Check data files with detailed info
|
| 230 |
+
data_files = [
|
| 231 |
+
str(data_dir / "qa.json"),
|
| 232 |
+
str(data_dir / "dataset_info.json")
|
| 233 |
+
]
|
| 234 |
+
|
| 235 |
+
for file_path in data_files:
|
| 236 |
+
if not Path(file_path).exists():
|
| 237 |
+
print(f"❌ Missing data file: {file_path}")
|
| 238 |
+
return False
|
| 239 |
+
else:
|
| 240 |
+
file_size = Path(file_path).stat().st_size
|
| 241 |
+
print(f"✅ Found data file: {file_path} ({file_size} bytes)")
|
| 242 |
+
|
| 243 |
+
# 检查qa.json的内容
|
| 244 |
+
try:
|
| 245 |
+
import json
|
| 246 |
+
qa_file = str(data_dir / "qa.json")
|
| 247 |
+
with open(qa_file, 'r', encoding='utf-8') as f:
|
| 248 |
+
qa_data = json.load(f)
|
| 249 |
+
print(f"✅ QA data loaded: {len(qa_data)} samples")
|
| 250 |
+
|
| 251 |
+
if len(qa_data) == 0:
|
| 252 |
+
print("❌ QA data is empty! Please check data generation pipeline.")
|
| 253 |
+
return False
|
| 254 |
+
|
| 255 |
+
# 检查第一个样本的格式
|
| 256 |
+
if qa_data:
|
| 257 |
+
sample = qa_data[0]
|
| 258 |
+
required_keys = ["instruction", "input", "output"]
|
| 259 |
+
missing_keys = [key for key in required_keys if key not in sample]
|
| 260 |
+
if missing_keys:
|
| 261 |
+
print(f"❌ Missing keys in QA sample: {missing_keys}")
|
| 262 |
+
return False
|
| 263 |
+
else:
|
| 264 |
+
print("✅ QA data format is correct")
|
| 265 |
+
|
| 266 |
+
except Exception as e:
|
| 267 |
+
print(f"❌ Error checking QA data: {e}")
|
| 268 |
+
return False
|
| 269 |
+
|
| 270 |
+
print("✅ Data files check passed")
|
| 271 |
+
|
| 272 |
+
# Check LlamaFactory
|
| 273 |
+
try:
|
| 274 |
+
import llamafactory
|
| 275 |
+
print("✅ LlamaFactory is installed")
|
| 276 |
+
except ImportError:
|
| 277 |
+
print("❌ LlamaFactory not installed")
|
| 278 |
+
print("Please run: pip install llamafactory[torch,metrics]")
|
| 279 |
+
return False
|
| 280 |
+
|
| 281 |
+
return True
|
| 282 |
+
|
| 283 |
+
def start_training(self):
|
| 284 |
+
"""Start training"""
|
| 285 |
+
if not self.check_environment():
|
| 286 |
+
print("Environment check failed")
|
| 287 |
+
return False
|
| 288 |
+
|
| 289 |
+
# Load config
|
| 290 |
+
config = self.check_and_create_config()
|
| 291 |
+
if not config:
|
| 292 |
+
print("Failed to load config")
|
| 293 |
+
return False
|
| 294 |
+
|
| 295 |
+
# Show config info
|
| 296 |
+
self.print_config_info(config)
|
| 297 |
+
|
| 298 |
+
# Build training command
|
| 299 |
+
train_cmd = f"llamafactory-cli train {self.config_path}"
|
| 300 |
+
|
| 301 |
+
# Start training
|
| 302 |
+
print(f"\nStarting training...")
|
| 303 |
+
print(f"Config file: {self.config_path}")
|
| 304 |
+
print(f"Command: {train_cmd}")
|
| 305 |
+
|
| 306 |
+
try:
|
| 307 |
+
result = subprocess.run(train_cmd, shell=True, check=True)
|
| 308 |
+
print("Training completed!")
|
| 309 |
+
return True
|
| 310 |
+
except subprocess.CalledProcessError as e:
|
| 311 |
+
print(f"Training failed: {e}")
|
| 312 |
+
return False
|
| 313 |
+
except KeyboardInterrupt:
|
| 314 |
+
print("\nTraining interrupted by user")
|
| 315 |
+
return False
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def main():
|
| 319 |
+
parser = argparse.ArgumentParser(description="LlamaFactory Training Script")
|
| 320 |
+
parser.add_argument("--config", default=None,
|
| 321 |
+
help="Config file path (default: cache_dir/.cache/train_config.yaml)")
|
| 322 |
+
parser.add_argument("--cache", default="./", help="Cache directory path")
|
| 323 |
+
parser.add_argument("--update-lr", type=float,
|
| 324 |
+
help="Update learning rate")
|
| 325 |
+
parser.add_argument("--update-epochs", type=int,
|
| 326 |
+
help="Update training epochs")
|
| 327 |
+
parser.add_argument("--update-batch-size", type=int,
|
| 328 |
+
help="Update batch size")
|
| 329 |
+
|
| 330 |
+
args = parser.parse_args()
|
| 331 |
+
|
| 332 |
+
# 处理cache_base相对路径
|
| 333 |
+
cache_path = Path(args.cache)
|
| 334 |
+
if not cache_path.is_absolute():
|
| 335 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 336 |
+
cache_path = caller_cwd / cache_path
|
| 337 |
+
|
| 338 |
+
# Create trainer - 如果没有指定config,会自动使用cache目录下的默认路径
|
| 339 |
+
config_path = args.config
|
| 340 |
+
if config_path is None:
|
| 341 |
+
config_path = str(cache_path / ".cache" / "train_config.yaml")
|
| 342 |
+
|
| 343 |
+
trainer = LlamaFactoryTrainer(config_path, cache_base=str(cache_path))
|
| 344 |
+
|
| 345 |
+
# Update parameters if specified
|
| 346 |
+
updates = {}
|
| 347 |
+
if args.update_lr:
|
| 348 |
+
updates["learning_rate"] = args.update_lr
|
| 349 |
+
if args.update_epochs:
|
| 350 |
+
updates["num_train_epochs"] = args.update_epochs
|
| 351 |
+
if args.update_batch_size:
|
| 352 |
+
updates["per_device_train_batch_size"] = args.update_batch_size
|
| 353 |
+
|
| 354 |
+
if updates:
|
| 355 |
+
print("Updating config parameters...")
|
| 356 |
+
trainer.update_config(updates)
|
| 357 |
+
|
| 358 |
+
# Start training
|
| 359 |
+
success = trainer.start_training()
|
| 360 |
+
|
| 361 |
+
if success:
|
| 362 |
+
print(f"\nOperation completed!")
|
| 363 |
+
print(f"Model saved to: {cache_path / '.cache' / 'saves' / 'qwen2.5_7b_sft_model'}")
|
| 364 |
+
else:
|
| 365 |
+
sys.exit(1)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
if __name__ == "__main__":
|
| 369 |
+
main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/path_to_jsonl_script.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import List, Union
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class PDFDetector:
|
| 9 |
+
"""PDF file detector for scanning directories and generating JSONL config files"""
|
| 10 |
+
|
| 11 |
+
def __init__(self, output_file: str = "./.cache/gpu/pdf_list.jsonl"):
|
| 12 |
+
# Handle output path - based on caller's working directory
|
| 13 |
+
output_path = Path(output_file)
|
| 14 |
+
if not output_path.is_absolute():
|
| 15 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 16 |
+
output_file = str(caller_cwd / output_file)
|
| 17 |
+
self.output_file = output_file
|
| 18 |
+
self.pdf_files = []
|
| 19 |
+
|
| 20 |
+
def scan_directory(self, directory: Union[str, Path], recursive: bool = True) -> List[str]:
|
| 21 |
+
"""
|
| 22 |
+
Scan PDF files in directory
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
directory: Directory path to scan
|
| 26 |
+
recursive: Whether to scan subdirectories recursively
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
List of found PDF file paths
|
| 30 |
+
"""
|
| 31 |
+
directory = Path(directory)
|
| 32 |
+
|
| 33 |
+
if not directory.exists():
|
| 34 |
+
print(f"Error: Directory '{directory}' does not exist")
|
| 35 |
+
return []
|
| 36 |
+
|
| 37 |
+
if not directory.is_dir():
|
| 38 |
+
print(f"Error: '{directory}' is not a valid directory")
|
| 39 |
+
return []
|
| 40 |
+
|
| 41 |
+
pdf_files = []
|
| 42 |
+
|
| 43 |
+
# Directories to exclude from scanning
|
| 44 |
+
exclude_dirs = {'.cache', '__pycache__', '.git', 'node_modules', '.venv', 'venv', '.env'}
|
| 45 |
+
|
| 46 |
+
if recursive:
|
| 47 |
+
# Recursively search all subdirectories
|
| 48 |
+
pattern = "**/*.pdf"
|
| 49 |
+
else:
|
| 50 |
+
# Only search current directory
|
| 51 |
+
pattern = "*.pdf"
|
| 52 |
+
|
| 53 |
+
for pdf_path in directory.glob(pattern):
|
| 54 |
+
# Skip if path contains any excluded directory
|
| 55 |
+
if any(exclude_dir in pdf_path.parts for exclude_dir in exclude_dirs):
|
| 56 |
+
continue
|
| 57 |
+
|
| 58 |
+
# Also skip hidden directories (starting with .)
|
| 59 |
+
if any(part.startswith('.') and part != '.' for part in pdf_path.parts):
|
| 60 |
+
continue
|
| 61 |
+
|
| 62 |
+
if pdf_path.is_file():
|
| 63 |
+
# Convert to absolute path
|
| 64 |
+
pdf_files.append(str(pdf_path.resolve()))
|
| 65 |
+
print(f"Found PDF: {pdf_path}")
|
| 66 |
+
|
| 67 |
+
self.pdf_files.extend(pdf_files)
|
| 68 |
+
return pdf_files
|
| 69 |
+
|
| 70 |
+
def scan_multiple_directories(self, directories: List[Union[str, Path]], recursive: bool = True) -> List[str]:
|
| 71 |
+
"""
|
| 72 |
+
Scan multiple directories
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
directories: List of directory paths
|
| 76 |
+
recursive: Whether to scan recursively
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
List of all found PDF file paths
|
| 80 |
+
"""
|
| 81 |
+
all_pdfs = []
|
| 82 |
+
for directory in directories:
|
| 83 |
+
pdfs = self.scan_directory(directory, recursive)
|
| 84 |
+
all_pdfs.extend(pdfs)
|
| 85 |
+
|
| 86 |
+
return all_pdfs
|
| 87 |
+
|
| 88 |
+
def add_pdf_file(self, file_path: Union[str, Path]) -> bool:
|
| 89 |
+
"""
|
| 90 |
+
Manually add a single PDF file
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
file_path: PDF file path
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
Whether successfully added
|
| 97 |
+
"""
|
| 98 |
+
file_path = Path(file_path)
|
| 99 |
+
|
| 100 |
+
if not file_path.exists():
|
| 101 |
+
print(f"Error: File '{file_path}' does not exist")
|
| 102 |
+
return False
|
| 103 |
+
|
| 104 |
+
if not file_path.is_file():
|
| 105 |
+
print(f"Error: '{file_path}' is not a file")
|
| 106 |
+
return False
|
| 107 |
+
|
| 108 |
+
if file_path.suffix.lower() != '.pdf':
|
| 109 |
+
print(f"Error: '{file_path}' is not a PDF file")
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
abs_path = str(file_path.resolve())
|
| 113 |
+
if abs_path not in self.pdf_files:
|
| 114 |
+
self.pdf_files.append(abs_path)
|
| 115 |
+
print(f"Added PDF: {file_path}")
|
| 116 |
+
return True
|
| 117 |
+
else:
|
| 118 |
+
print(f"PDF already exists: {file_path}")
|
| 119 |
+
return False
|
| 120 |
+
|
| 121 |
+
def generate_jsonl(self, output_file: str = None) -> str:
|
| 122 |
+
"""
|
| 123 |
+
Generate JSONL config file
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
output_file: Output file path, if None use the initialized path
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
Generated JSONL file path
|
| 130 |
+
"""
|
| 131 |
+
if output_file is None:
|
| 132 |
+
output_file = self.output_file
|
| 133 |
+
else:
|
| 134 |
+
# Handle output file relative path - based on caller's working directory
|
| 135 |
+
output_path = Path(output_file)
|
| 136 |
+
if not output_path.is_absolute():
|
| 137 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 138 |
+
output_path = caller_cwd / output_path
|
| 139 |
+
output_file = str(output_path)
|
| 140 |
+
|
| 141 |
+
if not self.pdf_files:
|
| 142 |
+
print("Warning: No PDF files found")
|
| 143 |
+
return output_file
|
| 144 |
+
|
| 145 |
+
# Validate and process output file path
|
| 146 |
+
output_path = Path(output_file)
|
| 147 |
+
|
| 148 |
+
# If output path is directory, auto-generate filename
|
| 149 |
+
if output_path.exists() and output_path.is_dir():
|
| 150 |
+
output_path = output_path / "pdf_list.jsonl"
|
| 151 |
+
output_file = str(output_path)
|
| 152 |
+
print(f"Warning: Output path is directory, auto-generating filename: {output_file}")
|
| 153 |
+
elif output_path.suffix == "":
|
| 154 |
+
# If no extension, add .jsonl
|
| 155 |
+
output_path = output_path.with_suffix(".jsonl")
|
| 156 |
+
output_file = str(output_path)
|
| 157 |
+
print(f"Warning: Auto-adding extension: {output_file}")
|
| 158 |
+
|
| 159 |
+
# Ensure output directory exists
|
| 160 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 161 |
+
|
| 162 |
+
with open(output_file, 'w', encoding='utf-8') as f:
|
| 163 |
+
for pdf_path in self.pdf_files:
|
| 164 |
+
# Write in JSONL format
|
| 165 |
+
json_line = {"raw_content": pdf_path}
|
| 166 |
+
f.write(json.dumps(json_line, ensure_ascii=False) + '\n')
|
| 167 |
+
|
| 168 |
+
print(f"Successfully generated JSONL file: {output_file}")
|
| 169 |
+
print(f"Contains {len(self.pdf_files)} PDF files")
|
| 170 |
+
return output_file
|
| 171 |
+
|
| 172 |
+
def preview_results(self, max_items: int = 10):
|
| 173 |
+
"""Preview detection results"""
|
| 174 |
+
if not self.pdf_files:
|
| 175 |
+
print("No PDF files found")
|
| 176 |
+
return
|
| 177 |
+
|
| 178 |
+
print(f"\nDetected {len(self.pdf_files)} PDF files:")
|
| 179 |
+
print("-" * 50)
|
| 180 |
+
|
| 181 |
+
for i, pdf_path in enumerate(self.pdf_files[:max_items]):
|
| 182 |
+
print(f"{i + 1:3d}. {pdf_path}")
|
| 183 |
+
|
| 184 |
+
if len(self.pdf_files) > max_items:
|
| 185 |
+
print(f"... and {len(self.pdf_files) - max_items} more files")
|
| 186 |
+
print("-" * 50)
|
| 187 |
+
|
| 188 |
+
def clear_results(self):
|
| 189 |
+
"""Clear detection results"""
|
| 190 |
+
self.pdf_files.clear()
|
| 191 |
+
print("Detection results cleared")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def main():
|
| 195 |
+
parser = argparse.ArgumentParser(description='Detect PDF files and generate JSONL config file')
|
| 196 |
+
parser.add_argument('input_dir', nargs='?', default='./input',
|
| 197 |
+
help='Input directory path to scan (default: ./input)')
|
| 198 |
+
parser.add_argument('-o', '--output', default='./.cache/gpu/pdf_list.jsonl',
|
| 199 |
+
help='Output JSONL file path (default: ./.cache/gpu/pdf_list.jsonl)')
|
| 200 |
+
parser.add_argument('-r', '--recursive', action='store_true', default=True, help='Scan subdirectories recursively')
|
| 201 |
+
parser.add_argument('--no-recursive', action='store_false', dest='recursive', help='Do not scan subdirectories')
|
| 202 |
+
|
| 203 |
+
args = parser.parse_args()
|
| 204 |
+
|
| 205 |
+
# Validate input directory - handle relative paths
|
| 206 |
+
input_path = Path(args.input_dir)
|
| 207 |
+
if not input_path.is_absolute():
|
| 208 |
+
# If relative path, resolve based on caller's working directory
|
| 209 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 210 |
+
input_path = caller_cwd / input_path
|
| 211 |
+
|
| 212 |
+
if not input_path.exists():
|
| 213 |
+
print(f"Error: Input directory '{input_path}' does not exist")
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
if not input_path.is_dir():
|
| 217 |
+
print(f"Error: '{input_path}' is not a valid directory")
|
| 218 |
+
return
|
| 219 |
+
|
| 220 |
+
# Create detector
|
| 221 |
+
detector = PDFDetector(args.output)
|
| 222 |
+
|
| 223 |
+
# Use resolved input directory
|
| 224 |
+
input_directory = str(input_path)
|
| 225 |
+
|
| 226 |
+
# Scan directory
|
| 227 |
+
print(f"Starting directory scan: {input_directory}")
|
| 228 |
+
print(f"Recursive mode: {'enabled' if args.recursive else 'disabled'}")
|
| 229 |
+
|
| 230 |
+
detector.scan_directory(input_directory, args.recursive)
|
| 231 |
+
|
| 232 |
+
# Generate JSONL file
|
| 233 |
+
detector.generate_jsonl(output_file=args.output)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/pdf2model_pipeline/pdf_to_qa_pipeline.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from dataflow.operators.knowledge_cleaning import (
|
| 7 |
+
KBCChunkGeneratorBatch,
|
| 8 |
+
FileOrURLToMarkdownConverterLocal,
|
| 9 |
+
FileOrURLToMarkdownConverterFlash,
|
| 10 |
+
KBCTextCleanerBatch,
|
| 11 |
+
KBCMultiHopQAGeneratorBatch,
|
| 12 |
+
QAExtractor
|
| 13 |
+
)
|
| 14 |
+
from dataflow.utils.storage import FileStorage
|
| 15 |
+
from dataflow.serving import LocalModelLLMServing_vllm
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class KBCleaning_batchvllm_GPUPipeline():
|
| 19 |
+
def __init__(self, cache_base="./"):
|
| 20 |
+
# 处理cache_base相对路径
|
| 21 |
+
cache_path = Path(cache_base)
|
| 22 |
+
if not cache_path.is_absolute():
|
| 23 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 24 |
+
cache_path = caller_cwd / cache_path
|
| 25 |
+
|
| 26 |
+
self.storage = FileStorage(
|
| 27 |
+
first_entry_file_name=str(cache_path / ".cache" / "gpu" / "pdf_list.jsonl"),
|
| 28 |
+
cache_path=str(cache_path / ".cache" / "gpu"),
|
| 29 |
+
file_name_prefix="batch_cleaning_step",
|
| 30 |
+
cache_type="json",
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterLocal(
|
| 34 |
+
intermediate_dir=str(cache_path / ".cache"),
|
| 35 |
+
mineru_backend="vlm-vllm-engine", # 可选 pipeline, vlm-vllm-engine, vlm-vllm-transformer, vlm-http-client
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Faster backend by Flash-MinerU
|
| 39 |
+
# See de
|
| 40 |
+
|
| 41 |
+
# self.knowledge_cleaning_step1 = FileOrURLToMarkdownConverterFlash(
|
| 42 |
+
# intermediate_dir="../example_data/KBCleaningPipeline/flash/",
|
| 43 |
+
# mineru_model_path="<your Model Path>/MinerU2.5-2509-1.2B", # !!! place your local model path here !!!
|
| 44 |
+
# # https://huggingface.co/opendatalab/MinerU2.5-2509-1.2B.
|
| 45 |
+
# batch_size=4, # batchsize per vllm worker
|
| 46 |
+
# replicas=1, # num of vllm workers
|
| 47 |
+
# num_gpus_per_replica=0.5, # for ray to schedule vllm workers to GPU, can be float, e.g. 0.5 means each worker uses half GPU, 1 means each worker uses whole GPU
|
| 48 |
+
# engine_gpu_util_rate_to_ray_cap=0.9 # actuall GPU utilization for each worker; acturall memory per worker= num_gpus_per_replica * engine_gpu_util_rate_to_ray_cap; this is to avoid OOM, you can set it to 0.9 or 0.8 to leave some buffer for other processes on
|
| 49 |
+
# )
|
| 50 |
+
|
| 51 |
+
self.knowledge_cleaning_step2 = KBCChunkGeneratorBatch(
|
| 52 |
+
split_method="token",
|
| 53 |
+
chunk_size=512,
|
| 54 |
+
tokenizer_name="./Qwen2.5-7B-Instruct",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
self.extract_format_qa = QAExtractor(
|
| 58 |
+
output_json_file="./.cache/data/qa.json",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def forward(self):
|
| 62 |
+
"""执行完整的Pipeline流程"""
|
| 63 |
+
print("🔄 Step 1: File/URL to Markdown conversion...")
|
| 64 |
+
self.knowledge_cleaning_step1.run(
|
| 65 |
+
storage=self.storage.step(),
|
| 66 |
+
input_key="raw_content",
|
| 67 |
+
output_key="text_path"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
print("🔄 Step 2: Text splitting into chunks...")
|
| 71 |
+
self.knowledge_cleaning_step2.run(
|
| 72 |
+
storage=self.storage.step(),
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
print("🔄 Starting LLM serving...")
|
| 76 |
+
self.llm_serving = LocalModelLLMServing_vllm(
|
| 77 |
+
hf_model_name_or_path="./Qwen2.5-7B-Instruct",
|
| 78 |
+
vllm_max_tokens=2048,
|
| 79 |
+
vllm_tensor_parallel_size=1, # 使用的GPU数量
|
| 80 |
+
vllm_gpu_memory_utilization=0.6, # GPU利用率
|
| 81 |
+
vllm_repetition_penalty=1.2
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
self.knowledge_cleaning_step3 = KBCTextCleanerBatch(
|
| 85 |
+
llm_serving=self.llm_serving,
|
| 86 |
+
lang="en"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
self.knowledge_cleaning_step4 = KBCMultiHopQAGeneratorBatch(
|
| 90 |
+
llm_serving=self.llm_serving,
|
| 91 |
+
lang="en",
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
print("🔄 Step 3: Knowledge cleaning...")
|
| 95 |
+
self.knowledge_cleaning_step3.run(
|
| 96 |
+
storage=self.storage.step(),
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
print("🔄 Step 4: Multi-hop QA generation...")
|
| 100 |
+
self.knowledge_cleaning_step4.run(
|
| 101 |
+
storage=self.storage.step(),
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
print("🔄 Step 5: Extract and format QA...")
|
| 105 |
+
self.extract_format_qa.run(
|
| 106 |
+
storage=self.storage.step(),
|
| 107 |
+
input_qa_key="qa_pairs",
|
| 108 |
+
output_instruction_key="instruction",
|
| 109 |
+
output_question_key="input",
|
| 110 |
+
output_answer_key="output"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
print("✅ Pipeline completed! Output saved to: ./.cache/data/qa.json")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def main():
|
| 117 |
+
parser = argparse.ArgumentParser(description="PDF to QA Pipeline")
|
| 118 |
+
parser.add_argument("--cache", default="./", help="Cache directory path")
|
| 119 |
+
args = parser.parse_args()
|
| 120 |
+
|
| 121 |
+
print("🚀 Starting KB Cleaning Pipeline...")
|
| 122 |
+
print(f"📄 Input: {args.cache}.cache/gpu/pdf_list.jsonl")
|
| 123 |
+
print(f"💾 Cache: {args.cache}.cache/gpu/")
|
| 124 |
+
print(f"📤 Output: {args.cache}.cache/data/qa.json")
|
| 125 |
+
print("-" * 60)
|
| 126 |
+
|
| 127 |
+
model = KBCleaning_batchvllm_GPUPipeline(cache_base=args.cache)
|
| 128 |
+
model.forward()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/llama_factory_trainer.cpython-311.pyc
ADDED
|
Binary file (16.6 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/merge_filter_qa_pairs.cpython-311.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/__pycache__/text_to_qa_pipeline.cpython-311.pyc
ADDED
|
Binary file (5.42 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/llama_factory_trainer.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
LlamaFactory Training Script with YAML Configuration Management
|
| 4 |
+
Complete "check-create-read-train" workflow
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import yaml
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import subprocess
|
| 11 |
+
import argparse
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class LlamaFactoryTrainer:
|
| 16 |
+
def __init__(self, config_path=None, cache_base="./"):
|
| 17 |
+
# 处理cache_base相对路径 - 基于调用者工作目录
|
| 18 |
+
cache_path = Path(cache_base)
|
| 19 |
+
if not cache_path.is_absolute():
|
| 20 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 21 |
+
cache_path = caller_cwd / cache_path
|
| 22 |
+
|
| 23 |
+
self.cache_path = cache_path
|
| 24 |
+
|
| 25 |
+
# 如果没有指定config_path,使用cache目录下的默认路径
|
| 26 |
+
if config_path is None:
|
| 27 |
+
config_path = str(cache_path / ".cache" / "train_config.yaml")
|
| 28 |
+
else:
|
| 29 |
+
# 处理config_path相对路径
|
| 30 |
+
config_path_obj = Path(config_path)
|
| 31 |
+
if not config_path_obj.is_absolute():
|
| 32 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 33 |
+
config_path = str(caller_cwd / config_path_obj)
|
| 34 |
+
|
| 35 |
+
self.config_path = Path(config_path)
|
| 36 |
+
|
| 37 |
+
def get_default_config(self):
|
| 38 |
+
"""Get default configuration - 基于最新LlamaFactory标准"""
|
| 39 |
+
return {
|
| 40 |
+
# === 基础配置 ===
|
| 41 |
+
"stage": "sft",
|
| 42 |
+
"do_train": True,
|
| 43 |
+
|
| 44 |
+
# === 模型配置 ===
|
| 45 |
+
"model_name_or_path": "Qwen/Qwen2.5-7B-Instruct",
|
| 46 |
+
"template": "qwen",
|
| 47 |
+
"trust_remote_code": True,
|
| 48 |
+
|
| 49 |
+
# === 微调方法配置 ===
|
| 50 |
+
"finetuning_type": "lora",
|
| 51 |
+
"lora_target": "all", # 使用 "all" 而不是具体层名
|
| 52 |
+
"lora_rank": 16,
|
| 53 |
+
"lora_alpha": 32,
|
| 54 |
+
"lora_dropout": 0.05,
|
| 55 |
+
|
| 56 |
+
# === 数据集配置 ===
|
| 57 |
+
"dataset": "kb_qa",
|
| 58 |
+
"dataset_dir": str(self.cache_path / ".cache" / "data"),
|
| 59 |
+
"cutoff_len": 1024,
|
| 60 |
+
"max_samples": None,
|
| 61 |
+
"overwrite_cache": True,
|
| 62 |
+
"preprocessing_num_workers": 4,
|
| 63 |
+
|
| 64 |
+
# === 训练配置 ===
|
| 65 |
+
"per_device_train_batch_size": 2,
|
| 66 |
+
"gradient_accumulation_steps": 4,
|
| 67 |
+
"learning_rate": 5e-5,
|
| 68 |
+
"num_train_epochs": 2.0,
|
| 69 |
+
"lr_scheduler_type": "cosine",
|
| 70 |
+
"warmup_ratio": 0.05,
|
| 71 |
+
"weight_decay": 0.01,
|
| 72 |
+
"max_grad_norm": 1.0,
|
| 73 |
+
"optim": "adamw_torch",
|
| 74 |
+
|
| 75 |
+
# === 输出配置 ===
|
| 76 |
+
"output_dir": str(self.cache_path / ".cache" / "saves" / "qwen2.5_7b_sft_model"),
|
| 77 |
+
"overwrite_output_dir": True,
|
| 78 |
+
"save_only_model": True,
|
| 79 |
+
"plot_loss": True,
|
| 80 |
+
|
| 81 |
+
# === 日志和检查点 ===
|
| 82 |
+
"logging_steps": 10,
|
| 83 |
+
"save_steps": 300,
|
| 84 |
+
"save_total_limit": 2,
|
| 85 |
+
|
| 86 |
+
# === 评估配置 ===
|
| 87 |
+
"val_size": 0.1,
|
| 88 |
+
"per_device_eval_batch_size": 2,
|
| 89 |
+
"eval_strategy": "steps",
|
| 90 |
+
"eval_steps": 300,
|
| 91 |
+
|
| 92 |
+
# === 硬件配置 ===
|
| 93 |
+
"fp16": False,
|
| 94 |
+
"bf16": True,
|
| 95 |
+
"tf32": True,
|
| 96 |
+
"dataloader_num_workers": 2,
|
| 97 |
+
|
| 98 |
+
# === 其他配置 ===
|
| 99 |
+
"seed": 42,
|
| 100 |
+
"ddp_timeout": 1800,
|
| 101 |
+
"report_to": "none",
|
| 102 |
+
"run_name": "qwen2.5_7b_sft_training",
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
def check_and_create_config(self):
|
| 106 |
+
"""
|
| 107 |
+
Core logic: check config file, read if exists, create if not
|
| 108 |
+
"""
|
| 109 |
+
# Ensure directory exists
|
| 110 |
+
self.config_path.parent.mkdir(parents=True, exist_ok=True)
|
| 111 |
+
|
| 112 |
+
if self.config_path.exists():
|
| 113 |
+
# Config file exists, read it
|
| 114 |
+
print(f"Found config file: {self.config_path}")
|
| 115 |
+
return self._load_existing_config()
|
| 116 |
+
else:
|
| 117 |
+
# Config file doesn't exist, create default config
|
| 118 |
+
print(f"Creating new config file: {self.config_path}")
|
| 119 |
+
return self._create_new_config()
|
| 120 |
+
|
| 121 |
+
def _load_existing_config(self):
|
| 122 |
+
"""Load existing config file"""
|
| 123 |
+
try:
|
| 124 |
+
with open(self.config_path, 'r', encoding='utf-8') as f:
|
| 125 |
+
config = yaml.safe_load(f)
|
| 126 |
+
print("Config file loaded successfully")
|
| 127 |
+
|
| 128 |
+
# Check if new default parameters need to be added
|
| 129 |
+
default_config = self.get_default_config()
|
| 130 |
+
updated = False
|
| 131 |
+
|
| 132 |
+
for key, value in default_config.items():
|
| 133 |
+
if key not in config:
|
| 134 |
+
config[key] = value
|
| 135 |
+
updated = True
|
| 136 |
+
print(f"Added missing parameter: {key}")
|
| 137 |
+
|
| 138 |
+
# 移除过时的formatting参数
|
| 139 |
+
if "formatting" in config:
|
| 140 |
+
del config["formatting"]
|
| 141 |
+
updated = True
|
| 142 |
+
print("Removed deprecated parameter: formatting")
|
| 143 |
+
|
| 144 |
+
# Save config if updated
|
| 145 |
+
if updated:
|
| 146 |
+
self._save_config(config)
|
| 147 |
+
print("Config file updated")
|
| 148 |
+
|
| 149 |
+
return config
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
print(f"Failed to read config: {e}")
|
| 153 |
+
print("Creating new default config")
|
| 154 |
+
return self._create_new_config()
|
| 155 |
+
|
| 156 |
+
def _create_new_config(self):
|
| 157 |
+
"""Create new default config file"""
|
| 158 |
+
default_config = self.get_default_config()
|
| 159 |
+
|
| 160 |
+
if self._save_config(default_config):
|
| 161 |
+
print("Default config file created successfully")
|
| 162 |
+
return default_config
|
| 163 |
+
else:
|
| 164 |
+
print("Failed to create config file")
|
| 165 |
+
return None
|
| 166 |
+
|
| 167 |
+
def _save_config(self, config):
|
| 168 |
+
"""Save config to file"""
|
| 169 |
+
try:
|
| 170 |
+
with open(self.config_path, 'w', encoding='utf-8') as f:
|
| 171 |
+
yaml.dump(config, f,
|
| 172 |
+
default_flow_style=False,
|
| 173 |
+
allow_unicode=True,
|
| 174 |
+
sort_keys=False,
|
| 175 |
+
indent=2,
|
| 176 |
+
width=80)
|
| 177 |
+
return True
|
| 178 |
+
except Exception as e:
|
| 179 |
+
print(f"Failed to save config: {e}")
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
def update_config(self, updates):
|
| 183 |
+
"""Update config parameters"""
|
| 184 |
+
config = self.check_and_create_config()
|
| 185 |
+
if config is None:
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
config.update(updates)
|
| 189 |
+
if self._save_config(config):
|
| 190 |
+
print(f"Config updated: {list(updates.keys())}")
|
| 191 |
+
return config
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
def print_config_info(self, config):
|
| 195 |
+
"""Print config information"""
|
| 196 |
+
if not config:
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
print("\n" + "=" * 50)
|
| 200 |
+
print("Training Configuration")
|
| 201 |
+
print("=" * 50)
|
| 202 |
+
|
| 203 |
+
key_info = [
|
| 204 |
+
("Model", "model_name_or_path"),
|
| 205 |
+
("Dataset", "dataset"),
|
| 206 |
+
("Template", "template"),
|
| 207 |
+
("LoRA Rank", "lora_rank"),
|
| 208 |
+
("Learning Rate", "learning_rate"),
|
| 209 |
+
("Epochs", "num_train_epochs"),
|
| 210 |
+
("Batch Size", "per_device_train_batch_size"),
|
| 211 |
+
("Output Dir", "output_dir"),
|
| 212 |
+
]
|
| 213 |
+
|
| 214 |
+
for name, key in key_info:
|
| 215 |
+
print(f"{name:<12}: {config.get(key, 'N/A')}")
|
| 216 |
+
|
| 217 |
+
effective_batch = config.get("per_device_train_batch_size", 1) * config.get("gradient_accumulation_steps", 1)
|
| 218 |
+
print(f"Effective Batch: {effective_batch}")
|
| 219 |
+
print("=" * 50)
|
| 220 |
+
|
| 221 |
+
def check_environment(self):
|
| 222 |
+
"""Check training environment"""
|
| 223 |
+
print("Checking training environment...")
|
| 224 |
+
|
| 225 |
+
# 使用绝对路径 - 直接获取调用者工作目录
|
| 226 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 227 |
+
data_dir = caller_cwd / ".cache" / "data"
|
| 228 |
+
|
| 229 |
+
# Check data files with detailed info
|
| 230 |
+
data_files = [
|
| 231 |
+
str(data_dir / "qa.json"),
|
| 232 |
+
str(data_dir / "dataset_info.json")
|
| 233 |
+
]
|
| 234 |
+
|
| 235 |
+
for file_path in data_files:
|
| 236 |
+
if not Path(file_path).exists():
|
| 237 |
+
print(f"❌ Missing data file: {file_path}")
|
| 238 |
+
return False
|
| 239 |
+
else:
|
| 240 |
+
file_size = Path(file_path).stat().st_size
|
| 241 |
+
print(f"✅ Found data file: {file_path} ({file_size} bytes)")
|
| 242 |
+
|
| 243 |
+
# 检查qa.json的内容
|
| 244 |
+
try:
|
| 245 |
+
import json
|
| 246 |
+
qa_file = str(data_dir / "qa.json")
|
| 247 |
+
with open(qa_file, 'r', encoding='utf-8') as f:
|
| 248 |
+
qa_data = json.load(f)
|
| 249 |
+
print(f"✅ QA data loaded: {len(qa_data)} samples")
|
| 250 |
+
|
| 251 |
+
if len(qa_data) == 0:
|
| 252 |
+
print("❌ QA data is empty! Please check data generation pipeline.")
|
| 253 |
+
return False
|
| 254 |
+
|
| 255 |
+
# 检查第一个样本的格式
|
| 256 |
+
if qa_data:
|
| 257 |
+
sample = qa_data[0]
|
| 258 |
+
required_keys = ["instruction", "input", "output"]
|
| 259 |
+
missing_keys = [key for key in required_keys if key not in sample]
|
| 260 |
+
if missing_keys:
|
| 261 |
+
print(f"❌ Missing keys in QA sample: {missing_keys}")
|
| 262 |
+
return False
|
| 263 |
+
else:
|
| 264 |
+
print("✅ QA data format is correct")
|
| 265 |
+
|
| 266 |
+
except Exception as e:
|
| 267 |
+
print(f"❌ Error checking QA data: {e}")
|
| 268 |
+
return False
|
| 269 |
+
|
| 270 |
+
print("✅ Data files check passed")
|
| 271 |
+
|
| 272 |
+
# Check LlamaFactory
|
| 273 |
+
try:
|
| 274 |
+
import llamafactory
|
| 275 |
+
print("✅ LlamaFactory is installed")
|
| 276 |
+
except ImportError:
|
| 277 |
+
print("❌ LlamaFactory not installed")
|
| 278 |
+
print("Please run: pip install llamafactory[torch,metrics]")
|
| 279 |
+
return False
|
| 280 |
+
|
| 281 |
+
return True
|
| 282 |
+
|
| 283 |
+
def start_training(self):
|
| 284 |
+
"""Start training"""
|
| 285 |
+
if not self.check_environment():
|
| 286 |
+
print("Environment check failed")
|
| 287 |
+
return False
|
| 288 |
+
|
| 289 |
+
# Load config
|
| 290 |
+
config = self.check_and_create_config()
|
| 291 |
+
if not config:
|
| 292 |
+
print("Failed to load config")
|
| 293 |
+
return False
|
| 294 |
+
|
| 295 |
+
# Show config info
|
| 296 |
+
self.print_config_info(config)
|
| 297 |
+
|
| 298 |
+
# Build training command
|
| 299 |
+
train_cmd = f"llamafactory-cli train {self.config_path}"
|
| 300 |
+
|
| 301 |
+
# Start training
|
| 302 |
+
print(f"\nStarting training...")
|
| 303 |
+
print(f"Config file: {self.config_path}")
|
| 304 |
+
print(f"Command: {train_cmd}")
|
| 305 |
+
|
| 306 |
+
try:
|
| 307 |
+
result = subprocess.run(train_cmd, shell=True, check=True)
|
| 308 |
+
print("Training completed!")
|
| 309 |
+
return True
|
| 310 |
+
except subprocess.CalledProcessError as e:
|
| 311 |
+
print(f"Training failed: {e}")
|
| 312 |
+
return False
|
| 313 |
+
except KeyboardInterrupt:
|
| 314 |
+
print("\nTraining interrupted by user")
|
| 315 |
+
return False
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def main():
|
| 319 |
+
parser = argparse.ArgumentParser(description="LlamaFactory Training Script")
|
| 320 |
+
parser.add_argument("--config", default=None,
|
| 321 |
+
help="Config file path (default: cache_dir/.cache/train_config.yaml)")
|
| 322 |
+
parser.add_argument("--cache", default="./", help="Cache directory path")
|
| 323 |
+
parser.add_argument("--update-lr", type=float,
|
| 324 |
+
help="Update learning rate")
|
| 325 |
+
parser.add_argument("--update-epochs", type=int,
|
| 326 |
+
help="Update training epochs")
|
| 327 |
+
parser.add_argument("--update-batch-size", type=int,
|
| 328 |
+
help="Update batch size")
|
| 329 |
+
|
| 330 |
+
args = parser.parse_args()
|
| 331 |
+
|
| 332 |
+
# 处理cache_base相对路径
|
| 333 |
+
cache_path = Path(args.cache)
|
| 334 |
+
if not cache_path.is_absolute():
|
| 335 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 336 |
+
cache_path = caller_cwd / cache_path
|
| 337 |
+
|
| 338 |
+
# Create trainer - 如果没有指定config,会自动使用cache目录下的默认路径
|
| 339 |
+
config_path = args.config
|
| 340 |
+
if config_path is None:
|
| 341 |
+
config_path = str(cache_path / ".cache" / "train_config.yaml")
|
| 342 |
+
|
| 343 |
+
trainer = LlamaFactoryTrainer(config_path, cache_base=str(cache_path))
|
| 344 |
+
|
| 345 |
+
# Update parameters if specified
|
| 346 |
+
updates = {}
|
| 347 |
+
if args.update_lr:
|
| 348 |
+
updates["learning_rate"] = args.update_lr
|
| 349 |
+
if args.update_epochs:
|
| 350 |
+
updates["num_train_epochs"] = args.update_epochs
|
| 351 |
+
if args.update_batch_size:
|
| 352 |
+
updates["per_device_train_batch_size"] = args.update_batch_size
|
| 353 |
+
|
| 354 |
+
if updates:
|
| 355 |
+
print("Updating config parameters...")
|
| 356 |
+
trainer.update_config(updates)
|
| 357 |
+
|
| 358 |
+
# Start training
|
| 359 |
+
success = trainer.start_training()
|
| 360 |
+
|
| 361 |
+
if success:
|
| 362 |
+
print(f"\nOperation completed!")
|
| 363 |
+
print(f"Model saved to: {cache_path / '.cache' / 'saves' /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os
|
| 4 |
+
import argparse
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def find_input_file(cache_base="./"):
|
| 9 |
+
"""Find input file relative to cache_base"""
|
| 10 |
+
cache_path = Path(cache_base)
|
| 11 |
+
if not cache_path.is_absolute():
|
| 12 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 13 |
+
cache_path = caller_cwd / cache_path
|
| 14 |
+
|
| 15 |
+
print(f"Cache base directory: {cache_path}")
|
| 16 |
+
|
| 17 |
+
# 优先查找 text2qa_step_step3.json
|
| 18 |
+
possible_paths = [
|
| 19 |
+
cache_path / ".cache" / "gpu" / "text2qa_step_step3.json",
|
| 20 |
+
cache_path / ".cache" / "gpu" / "batch_cleaning_step_step4.json",
|
| 21 |
+
cache_path / "cache" / "gpu" / "batch_cleaning_step_step4.json",
|
| 22 |
+
cache_path / "batch_cleaning_step_step4.json",
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
print("Searching for input file...")
|
| 26 |
+
for path in possible_paths:
|
| 27 |
+
abs_path = path.resolve()
|
| 28 |
+
if abs_path.exists():
|
| 29 |
+
size = abs_path.stat().st_size
|
| 30 |
+
print(f"Found input file: {abs_path} ({size} bytes)")
|
| 31 |
+
return abs_path
|
| 32 |
+
else:
|
| 33 |
+
print(f"Not found: {abs_path}")
|
| 34 |
+
|
| 35 |
+
print("Input file not found!")
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_qa_data_from_files(data_items, input_file):
|
| 40 |
+
"""Load QA data from enhanced_chunk_path files"""
|
| 41 |
+
all_qa_pairs = []
|
| 42 |
+
|
| 43 |
+
for i, item in enumerate(data_items):
|
| 44 |
+
print(f"Processing item {i + 1}/{len(data_items)}: ", end="")
|
| 45 |
+
|
| 46 |
+
enhanced_path = item.get('enhanced_chunk_path')
|
| 47 |
+
if not enhanced_path:
|
| 48 |
+
print("Skip (no enhanced_chunk_path)")
|
| 49 |
+
continue
|
| 50 |
+
|
| 51 |
+
# Convert to absolute path
|
| 52 |
+
if not os.path.isabs(enhanced_path):
|
| 53 |
+
input_file_path = Path(input_file)
|
| 54 |
+
cache_gpu_dir = input_file_path.parent
|
| 55 |
+
cache_dir = cache_gpu_dir.parent
|
| 56 |
+
project_root = cache_dir.parent
|
| 57 |
+
clean_path = enhanced_path.lstrip('./')
|
| 58 |
+
enhanced_path = project_root / clean_path
|
| 59 |
+
else:
|
| 60 |
+
enhanced_path = Path(enhanced_path)
|
| 61 |
+
|
| 62 |
+
if not enhanced_path.exists():
|
| 63 |
+
print(f"Skip (file not exists: {enhanced_path})")
|
| 64 |
+
continue
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
with open(enhanced_path, 'r', encoding='utf-8') as f:
|
| 68 |
+
enhanced_data = json.load(f)
|
| 69 |
+
|
| 70 |
+
chunk_qa_pairs = []
|
| 71 |
+
if isinstance(enhanced_data, list):
|
| 72 |
+
# enhanced_data is chunk list
|
| 73 |
+
for chunk in enhanced_data:
|
| 74 |
+
if isinstance(chunk, dict) and 'qa_pairs' in chunk:
|
| 75 |
+
qa_data = chunk['qa_pairs']
|
| 76 |
+
if isinstance(qa_data, dict) and 'qa_pairs' in qa_data:
|
| 77 |
+
# Double nested: chunk['qa_pairs']['qa_pairs']
|
| 78 |
+
chunk_qa_pairs.extend(qa_data['qa_pairs'])
|
| 79 |
+
elif isinstance(qa_data, list):
|
| 80 |
+
# Single nested: chunk['qa_pairs'] is directly a list
|
| 81 |
+
chunk_qa_pairs.extend(qa_data)
|
| 82 |
+
elif isinstance(enhanced_data, dict) and 'qa_pairs' in enhanced_data:
|
| 83 |
+
# enhanced_data is single object
|
| 84 |
+
qa_data = enhanced_data['qa_pairs']
|
| 85 |
+
if isinstance(qa_data, dict) and 'qa_pairs' in qa_data:
|
| 86 |
+
chunk_qa_pairs = qa_data['qa_pairs']
|
| 87 |
+
elif isinstance(qa_data, list):
|
| 88 |
+
chunk_qa_pairs = qa_data
|
| 89 |
+
|
| 90 |
+
if chunk_qa_pairs and isinstance(chunk_qa_pairs, list):
|
| 91 |
+
print(f"Found {len(chunk_qa_pairs)} QA pairs")
|
| 92 |
+
all_qa_pairs.extend(chunk_qa_pairs)
|
| 93 |
+
else:
|
| 94 |
+
print("Skip (no valid QA data)")
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"Skip (read failed: {e})")
|
| 99 |
+
continue
|
| 100 |
+
|
| 101 |
+
return all_qa_pairs
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def convert_to_alpaca(input_file, output_dir):
|
| 105 |
+
"""Convert QA data to Alpaca format for LlamaFactory"""
|
| 106 |
+
print(f"Reading data file: {input_file}")
|
| 107 |
+
print(f"Output directory: {output_dir}")
|
| 108 |
+
|
| 109 |
+
# Read main data file
|
| 110 |
+
try:
|
| 111 |
+
with open(input_file, 'r', encoding='utf-8') as f:
|
| 112 |
+
data = json.load(f)
|
| 113 |
+
print(
|
| 114 |
+
f"Successfully read main data, type: {type(data)}, length: {len(data) if hasattr(data, '__len__') else 'N/A'}")
|
| 115 |
+
except Exception as e:
|
| 116 |
+
print(f"Failed to read file: {e}")
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
if not isinstance(data, list):
|
| 120 |
+
print("Expected data in list format")
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
# Instruction for the training data
|
| 124 |
+
instruction = (
|
| 125 |
+
"Please answer the following question based on the provided text content. "
|
| 126 |
+
"Your response should:\n"
|
| 127 |
+
"1. Provide accurate information from the source material\n"
|
| 128 |
+
"2. Include relevant analysis and reasoning\n"
|
| 129 |
+
"3. Reference specific details or examples when applicable\n"
|
| 130 |
+
"4. Maintain clarity and precision in your explanation\n\n"
|
| 131 |
+
"Focus on delivering factual, well-reasoned answers based on the text content."
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
print("Loading QA pairs from enhanced files...")
|
| 135 |
+
all_qa_pairs = load_qa_data_from_files(data, input_file)
|
| 136 |
+
|
| 137 |
+
if not all_qa_pairs:
|
| 138 |
+
print("No QA pairs found! Please check data structure")
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
print(f"Total found {len(all_qa_pairs)} QA pairs")
|
| 142 |
+
|
| 143 |
+
# Process QA pairs
|
| 144 |
+
results = []
|
| 145 |
+
processed_pairs = 0
|
| 146 |
+
|
| 147 |
+
for qa in all_qa_pairs:
|
| 148 |
+
if not isinstance(qa, dict):
|
| 149 |
+
continue
|
| 150 |
+
|
| 151 |
+
# Extract question and answer
|
| 152 |
+
question = ""
|
| 153 |
+
answer_text = ""
|
| 154 |
+
|
| 155 |
+
# Try different possible field names for question
|
| 156 |
+
for q_field in ['question', 'Question', 'query', 'Query']:
|
| 157 |
+
if q_field in qa and qa[q_field]:
|
| 158 |
+
question = qa[q_field].strip()
|
| 159 |
+
break
|
| 160 |
+
|
| 161 |
+
# Try different possible field names for answer
|
| 162 |
+
for a_field in ['answer', 'Answer', 'response', 'Response']:
|
| 163 |
+
if a_field in qa and qa[a_field]:
|
| 164 |
+
answer_text = qa[a_field].strip()
|
| 165 |
+
break
|
| 166 |
+
|
| 167 |
+
# Skip empty questions or answers
|
| 168 |
+
if not question or not answer_text:
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
# Include reasoning steps if available
|
| 172 |
+
reasoning_steps = qa.get("reasoning_steps", [])
|
| 173 |
+
reasoning_text = ""
|
| 174 |
+
if isinstance(reasoning_steps, list):
|
| 175 |
+
reasoning_text = "\n".join([
|
| 176 |
+
step.get("step", "").strip()
|
| 177 |
+
for step in reasoning_steps
|
| 178 |
+
if isinstance(step, dict) and step.get("step", "").strip()
|
| 179 |
+
])
|
| 180 |
+
|
| 181 |
+
# Build output (reasoning process + answer)
|
| 182 |
+
if reasoning_text:
|
| 183 |
+
output_text = f"{reasoning_text}\n\n{answer_text}"
|
| 184 |
+
else:
|
| 185 |
+
output_text = answer_text
|
| 186 |
+
|
| 187 |
+
results.append({
|
| 188 |
+
"instruction": instruction,
|
| 189 |
+
"input": question,
|
| 190 |
+
"output": output_text
|
| 191 |
+
})
|
| 192 |
+
|
| 193 |
+
processed_pairs += 1
|
| 194 |
+
|
| 195 |
+
print(f"\nProcessing statistics:")
|
| 196 |
+
print(f"Found QA pairs: {len(all_qa_pairs)}")
|
| 197 |
+
print(f"Valid conversions: {processed_pairs}")
|
| 198 |
+
|
| 199 |
+
if not results:
|
| 200 |
+
print("No QA pairs converted!")
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
# Ensure output directory exists
|
| 204 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 205 |
+
|
| 206 |
+
# Save as qa.json (LlamaFactory standard format)
|
| 207 |
+
qa_file = output_dir / "qa.json"
|
| 208 |
+
try:
|
| 209 |
+
with open(qa_file, 'w', encoding='utf-8') as f:
|
| 210 |
+
json.dump(results, f, ensure_ascii=False, indent=2)
|
| 211 |
+
|
| 212 |
+
file_size = qa_file.stat().st_size
|
| 213 |
+
print(f"Conversion complete: {len(results)} QA pairs -> {qa_file} ({file_size} bytes)")
|
| 214 |
+
|
| 215 |
+
return qa_file
|
| 216 |
+
except Exception as e:
|
| 217 |
+
print(f"Failed to save file: {e}")
|
| 218 |
+
return None
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def create_llamafactory_config(output_dir):
|
| 222 |
+
"""Create dataset_info.json for LlamaFactory"""
|
| 223 |
+
print("Creating LlamaFactory configuration...")
|
| 224 |
+
|
| 225 |
+
dataset_info = {
|
| 226 |
+
"kb_qa": {
|
| 227 |
+
"file_name": "qa.json",
|
| 228 |
+
"columns": {
|
| 229 |
+
"prompt": "instruction",
|
| 230 |
+
"query": "input",
|
| 231 |
+
"response": "output"
|
| 232 |
+
}
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
config_file = output_dir / "dataset_info.json"
|
| 237 |
+
try:
|
| 238 |
+
with open(config_file, 'w', encoding='utf-8') as f:
|
| 239 |
+
json.dump(dataset_info, f, ensure_ascii=False, indent=2)
|
| 240 |
+
|
| 241 |
+
print(f"LlamaFactory configuration created: {config_file}")
|
| 242 |
+
return config_file
|
| 243 |
+
except Exception as e:
|
| 244 |
+
print(f"Failed to create configuration: {e}")
|
| 245 |
+
return None
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def main():
|
| 249 |
+
parser = argparse.ArgumentParser(description="Convert Step 3 QA data to LlamaFactory format")
|
| 250 |
+
parser.add_argument("--cache", default="./", help="Cache directory path")
|
| 251 |
+
args = parser.parse_args()
|
| 252 |
+
|
| 253 |
+
# Handle cache_base relative path
|
| 254 |
+
cache_path = Path(args.cache)
|
| 255 |
+
if not cache_path.is_absolute():
|
| 256 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 257 |
+
cache_path = caller_cwd / cache_path
|
| 258 |
+
|
| 259 |
+
print("Step 3 to LlamaFactory Converter")
|
| 260 |
+
print("=" * 50)
|
| 261 |
+
print(f"Cache base directory: {cache_path}")
|
| 262 |
+
|
| 263 |
+
# Find input file
|
| 264 |
+
input_file = find_input_file(str(cache_path))
|
| 265 |
+
if not input_file:
|
| 266 |
+
print("\nTips:")
|
| 267 |
+
print("1. Ensure Step 3 (Text2QA generation) has been completed")
|
| 268 |
+
print("2. Check if .cache/gpu/ directory exists")
|
| 269 |
+
print("3. Look for text2qa_step_step3.json file")
|
| 270 |
+
exit(1)
|
| 271 |
+
|
| 272 |
+
# Output directory
|
| 273 |
+
output_dir = cache_path / ".cache" / "data"
|
| 274 |
+
|
| 275 |
+
print(f"\nStarting conversion...")
|
| 276 |
+
print(f"Input: {input_file}")
|
| 277 |
+
print(f"Output directory: {output_dir}")
|
| 278 |
+
print("-" * 50)
|
| 279 |
+
|
| 280 |
+
# Convert data
|
| 281 |
+
qa_file = convert_to_alpaca(input_file, output_dir)
|
| 282 |
+
|
| 283 |
+
if qa_file:
|
| 284 |
+
# Create config file
|
| 285 |
+
config_file = create_llamafactory_config(output_dir)
|
| 286 |
+
|
| 287 |
+
if config_file:
|
| 288 |
+
print(f"\nConversion completed successfully!")
|
| 289 |
+
print(f"Files created:")
|
| 290 |
+
print(f" - {qa_file}")
|
| 291 |
+
print(f" - {config_file}")
|
| 292 |
+
print("Ready for LlamaFactory training!")
|
| 293 |
+
else:
|
| 294 |
+
print("Configuration file creation failed")
|
| 295 |
+
else:
|
| 296 |
+
print("Data conversion failed")
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
if __name__ == "__main__":
|
| 300 |
+
main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/text2model_pipeline/text_to_qa_pipeline.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from dataflow.operators.knowledge_cleaning import (
|
| 7 |
+
KBCChunkGeneratorBatch,
|
| 8 |
+
KBCTextCleanerBatch,
|
| 9 |
+
KBCMultiHopQAGeneratorBatch,
|
| 10 |
+
QAExtractor
|
| 11 |
+
)
|
| 12 |
+
# from dataflow.operators.knowledge_cleaning import (
|
| 13 |
+
# CorpusTextSplitterBatch,
|
| 14 |
+
# KnowledgeCleanerBatch,
|
| 15 |
+
# MultiHopQAGeneratorBatch,
|
| 16 |
+
# )
|
| 17 |
+
from dataflow.utils.storage import FileStorage
|
| 18 |
+
from dataflow.serving import LocalModelLLMServing_vllm
|
| 19 |
+
os.environ['OMP_NUM_THREADS'] = '1'
|
| 20 |
+
os.environ['ONNXRUNTIME_THREAD_AFFINITY'] = 'false'
|
| 21 |
+
|
| 22 |
+
class Text2QAPipeline:
|
| 23 |
+
def __init__(self, cache_base="./"):
|
| 24 |
+
# 处理cache_base相对路径
|
| 25 |
+
cache_path = Path(cache_base)
|
| 26 |
+
if not cache_path.is_absolute():
|
| 27 |
+
caller_cwd = Path(os.environ.get('PWD', os.getcwd()))
|
| 28 |
+
cache_path = caller_cwd / cache_path
|
| 29 |
+
|
| 30 |
+
self.storage = FileStorage(
|
| 31 |
+
first_entry_file_name=str(cache_path / ".cache" / "gpu" / "text_input.jsonl"),
|
| 32 |
+
cache_path=str(cache_path / ".cache" / "gpu"),
|
| 33 |
+
file_name_prefix="text2qa_step",
|
| 34 |
+
cache_type="json",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
self.text_splitting_step = KBCChunkGeneratorBatch(
|
| 38 |
+
split_method="token",
|
| 39 |
+
chunk_size=512,
|
| 40 |
+
tokenizer_name="Qwen/Qwen2.5-7B-Instruct",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
self.extract_format_qa = QAExtractor(
|
| 44 |
+
output_json_file="./.cache/data/qa.json",
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
def forward(self):
|
| 48 |
+
"""执行完整的Pipeline流程"""
|
| 49 |
+
print("Step 1: Text splitting into chunks...")
|
| 50 |
+
self.text_splitting_step.run(
|
| 51 |
+
storage=self.storage.step(),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
print("Starting LLM serving...")
|
| 55 |
+
self.llm_serving = LocalModelLLMServing_vllm(
|
| 56 |
+
hf_model_name_or_path="Qwen/Qwen2.5-7B-Instruct",
|
| 57 |
+
vllm_max_tokens=2048,
|
| 58 |
+
vllm_tensor_parallel_size=1,
|
| 59 |
+
vllm_gpu_memory_utilization=0.6,
|
| 60 |
+
vllm_repetition_penalty=1.2
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
self.knowledge_cleaning_step = KBCTextCleanerBatch(
|
| 64 |
+
llm_serving=self.llm_serving,
|
| 65 |
+
lang="en"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
self.qa_generation_step = KBCMultiHopQAGeneratorBatch(
|
| 69 |
+
llm_serving=self.llm_serving,
|
| 70 |
+
lang="en"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
print("Step 2: Knowledge cleaning...")
|
| 74 |
+
self.knowledge_cleaning_step.run(
|
| 75 |
+
storage=self.storage.step(),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
print("Step 3: Multi-hop QA generation...")
|
| 79 |
+
self.qa_generation_step.run(
|
| 80 |
+
storage=self.storage.step(),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
print("🔄 Step 4: Extract and format QA...")
|
| 84 |
+
self.extract_format_qa.run(
|
| 85 |
+
storage=self.storage.step(),
|
| 86 |
+
input_qa_key="qa_pairs",
|
| 87 |
+
output_instruction_key="instruction",
|
| 88 |
+
output_question_key="input",
|
| 89 |
+
output_answer_key="output"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
print("Pipeline completed!")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main():
|
| 96 |
+
parser = argparse.ArgumentParser(description="Text to QA Pipeline")
|
| 97 |
+
parser.add_argument("--cache", default="./", help="Cache directory path")
|
| 98 |
+
args = parser.parse_args()
|
| 99 |
+
|
| 100 |
+
print("Starting Text to QA Pipeline...")
|
| 101 |
+
print(f"Input: {args.cache}.cache/gpu/text_input.jsonl")
|
| 102 |
+
print(f"Cache: {args.cache}.cache/gpu/")
|
| 103 |
+
print(f"Output: {args.cache}.cache/gpu/text2qa_step_step3.json")
|
| 104 |
+
print("-" * 60)
|
| 105 |
+
|
| 106 |
+
model = Text2QAPipeline(cache_base=args.cache)
|
| 107 |
+
model.forward()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/cli_funcs/utils.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import typer
|
| 3 |
+
from colorama import init as color_init, Fore, Style
|
| 4 |
+
from typing import Optional, Tuple, List
|
| 5 |
+
# ---------- helpers ----------
|
| 6 |
+
def _echo(msg: str, color: Optional[str] = None) -> None:
|
| 7 |
+
if color == "red":
|
| 8 |
+
print(Fore.RED + msg + Style.RESET_ALL)
|
| 9 |
+
elif color == "yellow":
|
| 10 |
+
print(Fore.YELLOW + msg + Style.RESET_ALL)
|
| 11 |
+
elif color == "green":
|
| 12 |
+
print(Fore.GREEN + msg + Style.RESET_ALL)
|
| 13 |
+
elif color == "cyan":
|
| 14 |
+
print(Fore.CYAN + msg + Style.RESET_ALL)
|
| 15 |
+
else:
|
| 16 |
+
print(msg)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .operator import OperatorABC, get_operator
|
| 2 |
+
from .llm_serving import LLMServingABC
|
| 3 |
+
from .wrapper import WrapperABC
|
| 4 |
+
|
| 5 |
+
from typing import Union, TypeAlias
|
| 6 |
+
|
| 7 |
+
# 定义类型别名
|
| 8 |
+
OPERATOR_CLASSES: TypeAlias = Union[OperatorABC, WrapperABC]
|
| 9 |
+
LLM_SERVING_CLASSES: TypeAlias = LLMServingABC # 单一类型也可以这么写
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
'OPERATOR_CLASSES',
|
| 13 |
+
'LLM_SERVING_CLASSES',
|
| 14 |
+
'OperatorABC',
|
| 15 |
+
'get_operator',
|
| 16 |
+
'LLMServingABC',
|
| 17 |
+
'WrapperABC',
|
| 18 |
+
]
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (719 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/llm_serving.cpython-311.pyc
ADDED
|
Binary file (2.05 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/operator.cpython-311.pyc
ADDED
|
Binary file (2.04 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/prompt.cpython-311.pyc
ADDED
|
Binary file (7.08 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/__pycache__/wrapper.cpython-311.pyc
ADDED
|
Binary file (884 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/llm_serving.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import Any, List
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class LLMServingABC(ABC):
|
| 6 |
+
"""Abstract base class for data generators. Which may be used to generate data from a model or API. Called by operators
|
| 7 |
+
"""
|
| 8 |
+
@abstractmethod
|
| 9 |
+
def generate_from_input(self, user_inputs: List[str], system_prompt: str) -> List[str]:
|
| 10 |
+
"""
|
| 11 |
+
Generate data from input.
|
| 12 |
+
input: List[str], the input of the generator
|
| 13 |
+
"""
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
@abstractmethod
|
| 17 |
+
def start_serving(self):
|
| 18 |
+
"""
|
| 19 |
+
Cleanup the generator and garbage collect all GPU/CPU memory.
|
| 20 |
+
"""
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
@abstractmethod
|
| 24 |
+
def cleanup(self):
|
| 25 |
+
"""
|
| 26 |
+
Cleanup the generator and garbage collect all GPU/CPU memory.
|
| 27 |
+
"""
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
def load_model(self, model_name_or_path: str, **kwargs: Any):
|
| 31 |
+
"""
|
| 32 |
+
Load the model from the given path.
|
| 33 |
+
This method is optional and can be overridden by subclasses if needed.
|
| 34 |
+
"""
|
| 35 |
+
raise NotImplementedError("This method should be implemented by subclasses.")
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/operator.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from dataflow.logger import get_logger
|
| 3 |
+
from .prompt import DIYPromptABC, PromptABC
|
| 4 |
+
|
| 5 |
+
class OperatorABC(ABC):
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.logger = get_logger()
|
| 8 |
+
self.ALLOWED_PROMPTS = tuple([type[DIYPromptABC | PromptABC]])
|
| 9 |
+
|
| 10 |
+
@abstractmethod
|
| 11 |
+
def run(self) -> None:
|
| 12 |
+
"""
|
| 13 |
+
Main function to run the operator.
|
| 14 |
+
"""
|
| 15 |
+
pass
|
| 16 |
+
|
| 17 |
+
def get_operator(operator_name, args) -> OperatorABC:
|
| 18 |
+
from dataflow.utils import OPERATOR_REGISTRY
|
| 19 |
+
print(operator_name, args)
|
| 20 |
+
operator = OPERATOR_REGISTRY.get(operator_name)(args)
|
| 21 |
+
logger = get_logger()
|
| 22 |
+
if operator is not None:
|
| 23 |
+
logger.info(f"Successfully get operator {operator_name}, args {args}")
|
| 24 |
+
else:
|
| 25 |
+
logger.error(f"operator {operator_name} is not found")
|
| 26 |
+
assert operator is not None
|
| 27 |
+
print(operator)
|
| 28 |
+
return operator
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/prompt.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TypeVar, Protocol, Union, get_type_hints,cast
|
| 2 |
+
from functools import wraps
|
| 3 |
+
import inspect
|
| 4 |
+
# from dataflow.core import OperatorABC
|
| 5 |
+
|
| 6 |
+
class PromptABC():
|
| 7 |
+
def __init__(self):
|
| 8 |
+
pass
|
| 9 |
+
def build_prompt(self):
|
| 10 |
+
raise NotImplementedError
|
| 11 |
+
|
| 12 |
+
class DIYPromptABC(PromptABC):
|
| 13 |
+
def __init__(self):
|
| 14 |
+
super().__init__()
|
| 15 |
+
def build_prompt(self):
|
| 16 |
+
raise NotImplementedError
|
| 17 |
+
|
| 18 |
+
# class OperatorWithAllowedPrompts(Protocol):
|
| 19 |
+
# ALLOWED_PROMPTS: list[type[DIYPromptABC | PromptABC]]
|
| 20 |
+
|
| 21 |
+
def _make_diyprompt_union(allowed_prompts: tuple[type[PromptABC], ...]):
|
| 22 |
+
"""构造一个 Union 类型,包含允许的 prompt + DIYPromptABC 子类 + None"""
|
| 23 |
+
return Union[tuple(allowed_prompts) + (DIYPromptABC, type(None))]
|
| 24 |
+
|
| 25 |
+
# 泛型参数,表示任意传入的 class 类型
|
| 26 |
+
T = TypeVar("T")
|
| 27 |
+
|
| 28 |
+
def prompt_restrict(*allowed_prompts: type[DIYPromptABC]):
|
| 29 |
+
"""
|
| 30 |
+
装饰器:限制 prompt_template 只能是指定 Prompt 类 或 DIYPromptABC 子类
|
| 31 |
+
并在运行时检查 & 更新 __annotations__(供 get_type_hints 等工具使用)
|
| 32 |
+
"""
|
| 33 |
+
def decorator(cls:T) -> T:
|
| 34 |
+
setattr(cls, "ALLOWED_PROMPTS", tuple(allowed_prompts))
|
| 35 |
+
# self.ALLOWED_PROMPTS = list(allowed_prompts)
|
| 36 |
+
|
| 37 |
+
orig_init = cls.__init__
|
| 38 |
+
sig = inspect.signature(orig_init) # 在装饰时就解析一次签名,避免每次实例化重复解析
|
| 39 |
+
if "prompt_template" not in sig.parameters:
|
| 40 |
+
# 若类的 __init__ 根本没有该形参,就仅维持注解/属性设置,不做运行时检查
|
| 41 |
+
# (你也可以选择在这里直接 raise 来强制类必须声明该参数)
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
@wraps(orig_init)
|
| 45 |
+
def new_init(self, *args, **kwargs):
|
| 46 |
+
# 用签名绑定实参:自动把位置/关键字/默认值对齐到参数名
|
| 47 |
+
try:
|
| 48 |
+
bound = sig.bind_partial(self, *args, **kwargs)
|
| 49 |
+
bound.apply_defaults()
|
| 50 |
+
except TypeError:
|
| 51 |
+
# 参数不完整或不匹配时,交给原始 __init__ 去报错更合适
|
| 52 |
+
return orig_init(self, *args, **kwargs)
|
| 53 |
+
|
| 54 |
+
pt = bound.arguments.get("prompt_template", None)
|
| 55 |
+
|
| 56 |
+
if pt is not None and not isinstance(pt, cls.ALLOWED_PROMPTS):
|
| 57 |
+
if not isinstance(pt, DIYPromptABC):
|
| 58 |
+
allowed_names = "\n".join(
|
| 59 |
+
f" - {c.__module__}.{c.__qualname__}"
|
| 60 |
+
for c in cls.ALLOWED_PROMPTS
|
| 61 |
+
)
|
| 62 |
+
raise TypeError(
|
| 63 |
+
f"[{cls.__name__}] Invalid prompt_template type: "
|
| 64 |
+
f"{type(pt).__module__}.{type(pt).__qualname__}\n"
|
| 65 |
+
f"Expected one of:\n{allowed_names}\n"
|
| 66 |
+
f"or a custom subclass of `dataflow.core.prompt.DIYPromptABC.`"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
return orig_init(self, *args, **kwargs)
|
| 70 |
+
|
| 71 |
+
cls.__init__ = new_init
|
| 72 |
+
|
| 73 |
+
# 保持你原本的注解暴露逻辑
|
| 74 |
+
cls.__annotations__ = dict(getattr(cls, "__annotations__", {}))
|
| 75 |
+
cls.__annotations__["prompt_template"] = _make_diyprompt_union(allowed_prompts)
|
| 76 |
+
|
| 77 |
+
return cls
|
| 78 |
+
return decorator
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
import pytest
|
| 83 |
+
|
| 84 |
+
class A(PromptABC): pass
|
| 85 |
+
class B(PromptABC): pass
|
| 86 |
+
class MyDIY(DIYPromptABC): pass
|
| 87 |
+
class Other(PromptABC): pass
|
| 88 |
+
|
| 89 |
+
@prompt_restrict(A, B)
|
| 90 |
+
class Op:
|
| 91 |
+
def __init__(self, prompt_template=None):
|
| 92 |
+
self.prompt_template = prompt_template
|
| 93 |
+
|
| 94 |
+
# 关键字参数:允许
|
| 95 |
+
Op(prompt_template=A())
|
| 96 |
+
Op(prompt_template=B())
|
| 97 |
+
Op(prompt_template=MyDIY())
|
| 98 |
+
Op() # None 允许
|
| 99 |
+
|
| 100 |
+
# 位置参数:同样被检测
|
| 101 |
+
Op(A()) # ✅
|
| 102 |
+
Op(MyDIY()) # ✅
|
| 103 |
+
with pytest.raises(TypeError):
|
| 104 |
+
Op(Other()) # ❌ 非白名单且非 DIY
|
| 105 |
+
|
| 106 |
+
with pytest.raises(TypeError):
|
| 107 |
+
Op(object()) # ❌ 完全无关类型
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/dataflow/core/wrapper.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from dataflow.logger import get_logger
|
| 3 |
+
|
| 4 |
+
class WrapperABC(ABC):
|
| 5 |
+
"""
|
| 6 |
+
Abstract base class for wrappers.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
@abstractmethod
|
| 10 |
+
def run(self) -> None:
|
| 11 |
+
"""
|
| 12 |
+
Main function to run the wrapper.
|
| 13 |
+
"""
|
| 14 |
+
pass
|