dataflex 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dataflex/__init__.py +4 -0
- dataflex/cli.py +202 -0
- dataflex/configs/components.yaml +151 -0
- dataflex/core/__init__.py +0 -0
- dataflex/core/registry.py +32 -0
- dataflex/launcher.py +147 -0
- dataflex/offline_selector/offline_near_selector.py +195 -0
- dataflex/offline_selector/offline_tsds_selector.py +251 -0
- dataflex/train/__init__.py +0 -0
- dataflex/train/data/__init__.py +0 -0
- dataflex/train/data/loader.py +164 -0
- dataflex/train/dataset/__init__.py +3 -0
- dataflex/train/dataset/mixed_proportion_manager.py +167 -0
- dataflex/train/hparams/__init__.py +0 -0
- dataflex/train/hparams/dynamic_data_params.py +200 -0
- dataflex/train/hparams/dynamic_params.py +649 -0
- dataflex/train/mixer/__init__.py +5 -0
- dataflex/train/mixer/base_mixer.py +21 -0
- dataflex/train/mixer/doremi_mixer.py +312 -0
- dataflex/train/mixer/dynamic_moe_mixer.py +381 -0
- dataflex/train/mixer/odm_mixer.py +278 -0
- dataflex/train/mixer/random_mixer.py +27 -0
- dataflex/train/mixer/static_mixer.py +47 -0
- dataflex/train/selector/__init__.py +8 -0
- dataflex/train/selector/base_selector.py +56 -0
- dataflex/train/selector/custom_selector.py +38 -0
- dataflex/train/selector/delta_loss_selector.py +271 -0
- dataflex/train/selector/less_selector.py +389 -0
- dataflex/train/selector/loss_selector.py +197 -0
- dataflex/train/selector/near_selector.py +83 -0
- dataflex/train/selector/nice_selector.py +658 -0
- dataflex/train/selector/random_selector.py +59 -0
- dataflex/train/selector/tsds_selector.py +45 -0
- dataflex/train/trainer/__init__.py +0 -0
- dataflex/train/trainer/mix_trainer.py +1102 -0
- dataflex/train/trainer/select_trainer.py +887 -0
- dataflex/train/trainer/weight_trainer.py +773 -0
- dataflex/train/weighter/__init__.py +3 -0
- dataflex/train/weighter/base_weighter.py +147 -0
- dataflex/train/weighter/custom_weighter.py +52 -0
- dataflex/train/weighter/loss_weighter.py +133 -0
- dataflex/utils/__init__.py +0 -0
- dataflex/utils/load_component.py +24 -0
- dataflex/utils/logging.py +6 -0
- dataflex/utils/selector_io.py +43 -0
- dataflex/version.py +21 -0
- dataflex-1.0.0.dist-info/METADATA +385 -0
- dataflex-1.0.0.dist-info/RECORD +52 -0
- dataflex-1.0.0.dist-info/WHEEL +5 -0
- dataflex-1.0.0.dist-info/entry_points.txt +2 -0
- dataflex-1.0.0.dist-info/licenses/LICENSE +200 -0
- dataflex-1.0.0.dist-info/top_level.txt +1 -0
dataflex/__init__.py
ADDED
dataflex/cli.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import random
|
|
4
|
+
import importlib
|
|
5
|
+
import subprocess
|
|
6
|
+
from omegaconf import OmegaConf
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
def uncache(exclude):
|
|
10
|
+
"""Remove package modules from cache except excluded ones.
|
|
11
|
+
On next import they will be reloaded.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
exclude (iter<str>): Sequence of module paths.
|
|
15
|
+
"""
|
|
16
|
+
pkgs = []
|
|
17
|
+
for mod in exclude:
|
|
18
|
+
pkg = mod.split('.', 1)[0]
|
|
19
|
+
pkgs.append(pkg)
|
|
20
|
+
|
|
21
|
+
print(f'{pkgs=}')
|
|
22
|
+
to_uncache = []
|
|
23
|
+
for mod in sys.modules:
|
|
24
|
+
if mod in exclude:
|
|
25
|
+
continue
|
|
26
|
+
|
|
27
|
+
if mod in pkgs:
|
|
28
|
+
to_uncache.append(mod)
|
|
29
|
+
continue
|
|
30
|
+
|
|
31
|
+
for pkg in pkgs:
|
|
32
|
+
if mod.startswith(pkg + '.'):
|
|
33
|
+
to_uncache.append(mod)
|
|
34
|
+
break
|
|
35
|
+
|
|
36
|
+
print(f'{to_uncache=}')
|
|
37
|
+
for mod in to_uncache:
|
|
38
|
+
del sys.modules[mod]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def patch_finetune_params():
|
|
42
|
+
from dataflex.train.hparams.dynamic_params import DynamicFinetuningArguments
|
|
43
|
+
from dataflex.train.hparams.dynamic_data_params import DataArguments
|
|
44
|
+
import llamafactory.hparams
|
|
45
|
+
llamafactory.hparams.finetuning_args.FinetuningArguments = DynamicFinetuningArguments
|
|
46
|
+
llamafactory.hparams.data_args.DataArguments = DataArguments
|
|
47
|
+
|
|
48
|
+
uncache(["llamafactory.hparams.finetuning_args", "llamafactory.hparams.data_args"])
|
|
49
|
+
|
|
50
|
+
def patch_trainer(train_type: str):
|
|
51
|
+
"""
|
|
52
|
+
Monkey-patch LlamaFactory's CustomSeq2SeqTrainer based on train_type.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
train_type (str): Must be one of ["static", "dynamic_select", "dynamic_mix", "dynamic_weight"].
|
|
56
|
+
Determines which trainer class to inject.
|
|
57
|
+
"""
|
|
58
|
+
valid_types = ["static", "dynamic_select", "dynamic_mix", "dynamic_weight"]
|
|
59
|
+
if train_type not in valid_types:
|
|
60
|
+
raise ValueError(f"Invalid train_type '{train_type}'. Must be one of {valid_types}.")
|
|
61
|
+
|
|
62
|
+
if train_type == "dynamic_select":
|
|
63
|
+
from dataflex.train.trainer.select_trainer import SelectTrainer
|
|
64
|
+
TrainerCls = SelectTrainer
|
|
65
|
+
elif train_type == "dynamic_mix":
|
|
66
|
+
from dataflex.train.trainer.mix_trainer import MixTrainer
|
|
67
|
+
TrainerCls = MixTrainer
|
|
68
|
+
elif train_type == "dynamic_weight":
|
|
69
|
+
from dataflex.train.trainer.weight_trainer import WeightTrainer
|
|
70
|
+
TrainerCls = WeightTrainer
|
|
71
|
+
else: # static
|
|
72
|
+
TrainerCls = None
|
|
73
|
+
|
|
74
|
+
if TrainerCls is not None:
|
|
75
|
+
# 1) 替换源头模块
|
|
76
|
+
tmod = importlib.import_module("llamafactory.train.sft.trainer")
|
|
77
|
+
tmod.CustomSeq2SeqTrainer = TrainerCls
|
|
78
|
+
|
|
79
|
+
# 2) 替换包层 re-export
|
|
80
|
+
sft_pkg = importlib.import_module("llamafactory.train.sft")
|
|
81
|
+
setattr(sft_pkg, "CustomSeq2SeqTrainer", TrainerCls)
|
|
82
|
+
|
|
83
|
+
# 3) 替换 workflow 内部引用
|
|
84
|
+
wflow = importlib.import_module("llamafactory.train.sft.workflow")
|
|
85
|
+
setattr(wflow, "CustomSeq2SeqTrainer", TrainerCls)
|
|
86
|
+
|
|
87
|
+
# 4) 替换 PT 训练器
|
|
88
|
+
pt_tmod = importlib.import_module("llamafactory.train.pt.trainer")
|
|
89
|
+
pt_tmod.CustomTrainer = TrainerCls
|
|
90
|
+
|
|
91
|
+
# 5) 替换 PT workflow 内部引用
|
|
92
|
+
pt_wflow = importlib.import_module("llamafactory.train.pt.workflow")
|
|
93
|
+
setattr(pt_wflow, "CustomTrainer", TrainerCls)
|
|
94
|
+
|
|
95
|
+
print(f"[PatchTrainer] Using trainer type: '{train_type}'")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def patch_get_dataset(do_uncache_reload: bool = False):
|
|
99
|
+
"""
|
|
100
|
+
将 LlamaFactory 的 get_dataset 替换为 dataflex 版本。
|
|
101
|
+
- 源头: llamafactory.data.loader.get_dataset -> dataflex.train.data.loader.get_dataset
|
|
102
|
+
- 包层 re-export: 覆盖 llamafactory.data.get_dataset(如有)
|
|
103
|
+
- 就地覆盖: 对已 from-import 的使用方(包含 workflow)直接改其全局符号
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
do_uncache_reload: 为 True 时,会清理下游依赖缓存并预热导入,以确保后续 import 也拿到新函数。
|
|
107
|
+
默认为 False(与“就地打补丁”策略一致)。
|
|
108
|
+
"""
|
|
109
|
+
# 1) 引入新实现
|
|
110
|
+
from dataflex.train.data.loader import get_dataset as _new_get_dataset
|
|
111
|
+
# 2) 覆盖源头模块
|
|
112
|
+
data_loader_mod = importlib.import_module("llamafactory.data.loader")
|
|
113
|
+
setattr(data_loader_mod, "get_dataset", _new_get_dataset)
|
|
114
|
+
# 3) 覆盖包层 re-export(若其它代码从包层 import)
|
|
115
|
+
data_pkg = importlib.import_module("llamafactory.data")
|
|
116
|
+
setattr(data_pkg, "get_dataset", _new_get_dataset)
|
|
117
|
+
# 4) 就地覆盖已 from-import 的使用方(包含 workflow)
|
|
118
|
+
wflow = importlib.import_module("llamafactory.train.sft.workflow")
|
|
119
|
+
setattr(wflow, "get_dataset", _new_get_dataset)
|
|
120
|
+
|
|
121
|
+
# 5) 也要patch PT workflow
|
|
122
|
+
pt_wflow = importlib.import_module("llamafactory.train.pt.workflow")
|
|
123
|
+
setattr(pt_wflow, "get_dataset", _new_get_dataset)
|
|
124
|
+
|
|
125
|
+
def read_args():
|
|
126
|
+
file_path = sys.argv[1]
|
|
127
|
+
override_config = OmegaConf.from_cli(sys.argv[2:])
|
|
128
|
+
|
|
129
|
+
if file_path.endswith((".yaml", ".yml", ".json")):
|
|
130
|
+
dict_config = OmegaConf.load(Path(file_path).absolute())
|
|
131
|
+
cfg = OmegaConf.merge(dict_config, override_config)
|
|
132
|
+
else:
|
|
133
|
+
cfg = OmegaConf.create({}) # CLI 直接传参时
|
|
134
|
+
|
|
135
|
+
return OmegaConf.to_container(cfg)
|
|
136
|
+
|
|
137
|
+
def print_welcome():
|
|
138
|
+
try:
|
|
139
|
+
import importlib.metadata as importlib_metadata # py3.8+
|
|
140
|
+
except ImportError:
|
|
141
|
+
import importlib_metadata
|
|
142
|
+
|
|
143
|
+
try:
|
|
144
|
+
version = importlib_metadata.version("dataflex")
|
|
145
|
+
except importlib_metadata.PackageNotFoundError:
|
|
146
|
+
version = "unknown"
|
|
147
|
+
|
|
148
|
+
print("=" * 60)
|
|
149
|
+
try:
|
|
150
|
+
print(" 🎉 Welcome to DataFlex, a data-centric training system.")
|
|
151
|
+
print(f" 🚀 Installed version: {version}")
|
|
152
|
+
except UnicodeEncodeError:
|
|
153
|
+
print(" Welcome to DataFlex, a data-centric training system.")
|
|
154
|
+
print(f" Installed version: {version}")
|
|
155
|
+
print("=" * 60)
|
|
156
|
+
|
|
157
|
+
def main():
|
|
158
|
+
command = sys.argv.pop(1)
|
|
159
|
+
if command == "version":
|
|
160
|
+
# 只打印版本和欢迎
|
|
161
|
+
print_welcome()
|
|
162
|
+
return
|
|
163
|
+
elif command != 'train':
|
|
164
|
+
raise ValueError(f'Unknown command: {command}')
|
|
165
|
+
cfg = read_args()
|
|
166
|
+
patch_finetune_params()
|
|
167
|
+
patch_trainer(cfg['train_type'] if 'train_type' in cfg else 'static')
|
|
168
|
+
if cfg['train_type'] == 'dynamic_mix':
|
|
169
|
+
patch_get_dataset()
|
|
170
|
+
|
|
171
|
+
from llamafactory.train.tuner import run_exp
|
|
172
|
+
from llamafactory.extras.misc import is_env_enabled, get_device_count, use_ray
|
|
173
|
+
from llamafactory.extras import logging
|
|
174
|
+
from dataflex import launcher
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
logger = logging.get_logger(__name__)
|
|
178
|
+
|
|
179
|
+
force_torchrun = is_env_enabled("FORCE_TORCHRUN")
|
|
180
|
+
if force_torchrun or (get_device_count() > 1 and not use_ray()):
|
|
181
|
+
master_addr = os.getenv("MASTER_ADDR", "127.0.0.1")
|
|
182
|
+
master_port = os.getenv("MASTER_PORT", str(random.randint(20001, 29999)))
|
|
183
|
+
logger.info_rank0(f"Initializing distributed tasks at: {master_addr}:{master_port}")
|
|
184
|
+
process = subprocess.run(
|
|
185
|
+
(
|
|
186
|
+
"torchrun --nnodes {nnodes} --node_rank {node_rank} --nproc_per_node {nproc_per_node} "
|
|
187
|
+
"--master_addr {master_addr} --master_port {master_port} {file_name} {args}"
|
|
188
|
+
)
|
|
189
|
+
.format(
|
|
190
|
+
nnodes=os.getenv("NNODES", "1"),
|
|
191
|
+
node_rank=os.getenv("NODE_RANK", "0"),
|
|
192
|
+
nproc_per_node=os.getenv("NPROC_PER_NODE", str(get_device_count())),
|
|
193
|
+
master_addr=master_addr,
|
|
194
|
+
master_port=master_port,
|
|
195
|
+
file_name=launcher.__file__,
|
|
196
|
+
args=" ".join(sys.argv[1:]),
|
|
197
|
+
)
|
|
198
|
+
.split()
|
|
199
|
+
)
|
|
200
|
+
sys.exit(process.returncode)
|
|
201
|
+
else:
|
|
202
|
+
run_exp()
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# configs/components.yaml
|
|
2
|
+
selectors:
|
|
3
|
+
# Dynamic selectors
|
|
4
|
+
nice:
|
|
5
|
+
name: nice
|
|
6
|
+
params:
|
|
7
|
+
cache_dir: ../dataflex_saves/nice_output
|
|
8
|
+
gradient_type: adam
|
|
9
|
+
proj_dim: 4096
|
|
10
|
+
seed: 123
|
|
11
|
+
save_interval: 16
|
|
12
|
+
reward_model_backend: local_vllm # choices: [local_vllm, api]
|
|
13
|
+
reward_backend_params:
|
|
14
|
+
local_vllm:
|
|
15
|
+
hf_model_name_or_path: meta-llama/Llama-3.1-8B
|
|
16
|
+
vllm_tensor_parallel_size: 1
|
|
17
|
+
vllm_temperature: 0.0
|
|
18
|
+
vllm_top_p: 0.9
|
|
19
|
+
vllm_max_tokens: 512
|
|
20
|
+
vllm_top_k: 40
|
|
21
|
+
vllm_seed: 42
|
|
22
|
+
vllm_max_model_len: null
|
|
23
|
+
vllm_gpu_memory_utilization: 0.9
|
|
24
|
+
api:
|
|
25
|
+
api_url: https://api.openai.com/v1/chat/completions
|
|
26
|
+
api_key: DF_API_KEY
|
|
27
|
+
model_name: gpt-4o
|
|
28
|
+
temperature: 0.0
|
|
29
|
+
mc_samples: 4
|
|
30
|
+
max_new_tokens: 512
|
|
31
|
+
generation_temperature: 0.7
|
|
32
|
+
max_prompt_length: 4096
|
|
33
|
+
|
|
34
|
+
less:
|
|
35
|
+
name: less
|
|
36
|
+
params:
|
|
37
|
+
cache_dir: ../dataflex_saves/less_output
|
|
38
|
+
gradient_type: adam
|
|
39
|
+
proj_dim: 4096
|
|
40
|
+
seed: 123
|
|
41
|
+
save_interval: 16
|
|
42
|
+
|
|
43
|
+
loss:
|
|
44
|
+
name: loss
|
|
45
|
+
params:
|
|
46
|
+
cache_dir: ../dataflex_saves/loss_output
|
|
47
|
+
focus: "medium"
|
|
48
|
+
|
|
49
|
+
delta_loss:
|
|
50
|
+
name: delta_loss
|
|
51
|
+
params:
|
|
52
|
+
cache_dir: ../dataflex_saves/delta_loss_output
|
|
53
|
+
window_size: 0.2
|
|
54
|
+
|
|
55
|
+
tsds:
|
|
56
|
+
name: tsds
|
|
57
|
+
params:
|
|
58
|
+
probs_path: ./src/dataflex/offline_selector/tsds_probs.npy
|
|
59
|
+
cache_dir: ../dataflex_saves/tsds_output
|
|
60
|
+
near:
|
|
61
|
+
name: near
|
|
62
|
+
params:
|
|
63
|
+
indices_path: ./src/dataflex/offline_selector/top_indices.npy
|
|
64
|
+
cache_dir: ../dataflex_saves/near_output
|
|
65
|
+
|
|
66
|
+
random:
|
|
67
|
+
name: random
|
|
68
|
+
params:
|
|
69
|
+
cache_dir: ../dataflex_saves/random_output
|
|
70
|
+
seed: 42
|
|
71
|
+
replacement: false
|
|
72
|
+
|
|
73
|
+
custom:
|
|
74
|
+
name: custom
|
|
75
|
+
params:
|
|
76
|
+
cache_dir: ../dataflex_saves/custom_output
|
|
77
|
+
|
|
78
|
+
mixers:
|
|
79
|
+
# Dynamic mixers
|
|
80
|
+
random:
|
|
81
|
+
name: random
|
|
82
|
+
params:
|
|
83
|
+
seed: 42
|
|
84
|
+
|
|
85
|
+
doremi:
|
|
86
|
+
name: doremi
|
|
87
|
+
params:
|
|
88
|
+
# Path to the reference model checkpoint (Step 1 of DoReMi)
|
|
89
|
+
# reference_model_path: /path/to/ckpt/Qwen2.5-0.5B
|
|
90
|
+
reference_model_path: /path/to/dataflex_saves/Qwen2.5-0.5B/doremi_step1_static_qwen_pt_full_result/checkpoint-xxx
|
|
91
|
+
# # Set to null if no reference model available
|
|
92
|
+
# reference_model_path: null
|
|
93
|
+
# Learning rate for domain weight updates (eta in the paper)
|
|
94
|
+
reweight_eta: 0.1
|
|
95
|
+
reweight_eps: 0.01 # Smoothing parameter for domain weights (epsilon in the paper)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# Static mixer - for DoReMi's Step 1 and Step 3
|
|
99
|
+
static:
|
|
100
|
+
name: static
|
|
101
|
+
params:
|
|
102
|
+
# fixed proportions
|
|
103
|
+
proportions: [0.5, 0.5] # corresponding proportions for each domain
|
|
104
|
+
# proportions: null # use uniform distribution
|
|
105
|
+
# proportions: [0.541, 0.287, 0.042, 0.037, 0.034, 0.031, 0.028] # For SlimePajama-6B dataset
|
|
106
|
+
odm:
|
|
107
|
+
name: odm
|
|
108
|
+
params:
|
|
109
|
+
# Online Data Mixing (ODM) uses Multi-Armed Bandits (Exp3) for dynamic mixing
|
|
110
|
+
|
|
111
|
+
# Alpha (smoothing_factor): smoothing parameter for exponential moving average (0 to 1)
|
|
112
|
+
# Higher alpha = more weight on historical rewards, more stable but slower to adapt
|
|
113
|
+
# Lower alpha = more responsive to recent rewards, faster adaptation but more volatile
|
|
114
|
+
alpha: 0.9
|
|
115
|
+
|
|
116
|
+
# Warmup steps: number of steps to use initial proportions before starting ODM
|
|
117
|
+
# Typically 1% of total training steps
|
|
118
|
+
warmup_steps: 2000
|
|
119
|
+
# warmup_steps: 10 # debug
|
|
120
|
+
# reward_scale: Amplify loss signal for better domain differentiation
|
|
121
|
+
reward_scale: 15.0
|
|
122
|
+
|
|
123
|
+
# min_exploration_rate: Minimum exploration rate (annealing floor)
|
|
124
|
+
min_exploration_rate: 0.03
|
|
125
|
+
# Initial proportions for warmup period and ODM initialization
|
|
126
|
+
# If not specified, uses uniform distribution
|
|
127
|
+
initial_proportions: [0.5, 0.5] # debug
|
|
128
|
+
# initial_proportions: null # Use uniform distribution if null
|
|
129
|
+
# initial_proportions: [0.541, 0.287, 0.042, 0.037, 0.034, 0.031, 0.028] # for odm on SlimePajam-6B dataset
|
|
130
|
+
|
|
131
|
+
dynamic_moe:
|
|
132
|
+
name: dynamic_moe
|
|
133
|
+
params:
|
|
134
|
+
eta: 10.0 # Update step size
|
|
135
|
+
c: 0.05 # Smoothing parameter
|
|
136
|
+
collect_steps: 5 # Number of batches to sample per domain to estimate gate loads
|
|
137
|
+
eval_samples: 1000
|
|
138
|
+
eval_batch_size: 32
|
|
139
|
+
|
|
140
|
+
weighters:
|
|
141
|
+
# Dynamic data weights
|
|
142
|
+
loss:
|
|
143
|
+
name: loss
|
|
144
|
+
params:
|
|
145
|
+
strategy: linupper # choices: [linupper, uniform, quadratic, extremes]
|
|
146
|
+
delta: 1.0
|
|
147
|
+
|
|
148
|
+
custom:
|
|
149
|
+
name: custom
|
|
150
|
+
params:
|
|
151
|
+
strategy: uniform
|
|
File without changes
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from typing import Dict, Type, Any, Optional
|
|
3
|
+
|
|
4
|
+
class Registry:
|
|
5
|
+
def __init__(self):
|
|
6
|
+
self._store: Dict[str, Dict[str, Type]] = {}
|
|
7
|
+
|
|
8
|
+
def register(self, kind: str, name: str):
|
|
9
|
+
def deco(cls: Type):
|
|
10
|
+
self._store.setdefault(kind, {})
|
|
11
|
+
if name in self._store[kind]:
|
|
12
|
+
raise ValueError(f"{kind}.{name} already registered")
|
|
13
|
+
self._store[kind][name] = cls
|
|
14
|
+
return cls
|
|
15
|
+
return deco
|
|
16
|
+
|
|
17
|
+
def get(self, kind: str, name: str) -> Type:
|
|
18
|
+
return self._store[kind][name]
|
|
19
|
+
|
|
20
|
+
def build(self, kind: str, name: str, *, runtime: Dict[str, Any], cfg: Optional[Dict[str, Any]] = None):
|
|
21
|
+
cls = self.get(kind, name)
|
|
22
|
+
cfg = cfg or {}
|
|
23
|
+
merged = {**cfg, **runtime} # 运行期依赖优先
|
|
24
|
+
sig = inspect.signature(cls.__init__)
|
|
25
|
+
accepted = {p.name for p in list(sig.parameters.values())[1:]} # 跳过 self
|
|
26
|
+
filtered = {k: v for k, v in merged.items() if k in accepted} # 只喂需要的
|
|
27
|
+
return cls(**filtered)
|
|
28
|
+
|
|
29
|
+
REGISTRY = Registry()
|
|
30
|
+
def register_selector(name: str): return REGISTRY.register("selector", name)
|
|
31
|
+
def register_mixer(name: str): return REGISTRY.register("mixer", name)
|
|
32
|
+
def register_weighter(name: str): return REGISTRY.register("weighter", name)
|
dataflex/launcher.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import importlib
|
|
3
|
+
from omegaconf import OmegaConf
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from llamafactory.train.tuner import run_exp # use absolute import
|
|
6
|
+
|
|
7
|
+
def uncache(exclude):
|
|
8
|
+
"""Remove package modules from cache except excluded ones.
|
|
9
|
+
On next import they will be reloaded.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
exclude (iter<str>): Sequence of module paths.
|
|
13
|
+
"""
|
|
14
|
+
pkgs = []
|
|
15
|
+
for mod in exclude:
|
|
16
|
+
pkg = mod.split('.', 1)[0]
|
|
17
|
+
pkgs.append(pkg)
|
|
18
|
+
|
|
19
|
+
print(f'{pkgs=}')
|
|
20
|
+
to_uncache = []
|
|
21
|
+
for mod in sys.modules:
|
|
22
|
+
if mod in exclude:
|
|
23
|
+
continue
|
|
24
|
+
|
|
25
|
+
if mod in pkgs:
|
|
26
|
+
to_uncache.append(mod)
|
|
27
|
+
continue
|
|
28
|
+
|
|
29
|
+
for pkg in pkgs:
|
|
30
|
+
if mod.startswith(pkg + '.'):
|
|
31
|
+
to_uncache.append(mod)
|
|
32
|
+
break
|
|
33
|
+
|
|
34
|
+
print(f'{to_uncache=}')
|
|
35
|
+
for mod in to_uncache:
|
|
36
|
+
del sys.modules[mod]
|
|
37
|
+
|
|
38
|
+
def patch_finetune_params():
|
|
39
|
+
from dataflex.train.hparams.dynamic_params import DynamicFinetuningArguments
|
|
40
|
+
from dataflex.train.hparams.dynamic_data_params import DataArguments
|
|
41
|
+
import llamafactory.hparams
|
|
42
|
+
llamafactory.hparams.finetuning_args.FinetuningArguments = DynamicFinetuningArguments
|
|
43
|
+
llamafactory.hparams.data_args.DataArguments = DataArguments
|
|
44
|
+
|
|
45
|
+
uncache(["llamafactory.hparams.finetuning_args", "llamafactory.hparams.data_args"])
|
|
46
|
+
|
|
47
|
+
def patch_trainer(train_type: str):
|
|
48
|
+
"""
|
|
49
|
+
Monkey-patch LlamaFactory's CustomSeq2SeqTrainer based on train_type.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
train_type (str): Must be one of ["static", "dynamic_select", "dynamic_mix", "dynamic_weight"].
|
|
53
|
+
Determines which trainer class to inject.
|
|
54
|
+
"""
|
|
55
|
+
valid_types = ["static", "dynamic_select", "dynamic_mix", "dynamic_weight"]
|
|
56
|
+
if train_type not in valid_types:
|
|
57
|
+
raise ValueError(f"Invalid train_type '{train_type}'. Must be one of {valid_types}.")
|
|
58
|
+
|
|
59
|
+
if train_type == "dynamic_select":
|
|
60
|
+
from dataflex.train.trainer.select_trainer import SelectTrainer
|
|
61
|
+
TrainerCls = SelectTrainer
|
|
62
|
+
elif train_type == "dynamic_mix":
|
|
63
|
+
from dataflex.train.trainer.mix_trainer import MixTrainer
|
|
64
|
+
TrainerCls = MixTrainer
|
|
65
|
+
elif train_type == "dynamic_weight":
|
|
66
|
+
from dataflex.train.trainer.weight_trainer import WeightTrainer
|
|
67
|
+
TrainerCls = WeightTrainer
|
|
68
|
+
else: # static
|
|
69
|
+
TrainerCls = None
|
|
70
|
+
|
|
71
|
+
if TrainerCls is not None:
|
|
72
|
+
# 1) 替换源头模块
|
|
73
|
+
tmod = importlib.import_module("llamafactory.train.sft.trainer")
|
|
74
|
+
tmod.CustomSeq2SeqTrainer = TrainerCls
|
|
75
|
+
|
|
76
|
+
# 2) 替换包层 re-export
|
|
77
|
+
sft_pkg = importlib.import_module("llamafactory.train.sft")
|
|
78
|
+
setattr(sft_pkg, "CustomSeq2SeqTrainer", TrainerCls)
|
|
79
|
+
|
|
80
|
+
# 3) 替换 workflow 内部引用
|
|
81
|
+
wflow = importlib.import_module("llamafactory.train.sft.workflow")
|
|
82
|
+
setattr(wflow, "CustomSeq2SeqTrainer", TrainerCls)
|
|
83
|
+
|
|
84
|
+
# 4) 替换 PT 训练器
|
|
85
|
+
pt_tmod = importlib.import_module("llamafactory.train.pt.trainer")
|
|
86
|
+
pt_tmod.CustomTrainer = TrainerCls
|
|
87
|
+
|
|
88
|
+
# 5) 替换 PT workflow 内部引用
|
|
89
|
+
pt_wflow = importlib.import_module("llamafactory.train.pt.workflow")
|
|
90
|
+
setattr(pt_wflow, "CustomTrainer", TrainerCls)
|
|
91
|
+
|
|
92
|
+
print(f"[PatchTrainer] Using trainer type: '{train_type}'")
|
|
93
|
+
|
|
94
|
+
def patch_get_dataset(do_uncache_reload: bool = False):
|
|
95
|
+
"""
|
|
96
|
+
将 LlamaFactory 的 get_dataset 替换为 dataflex 版本。
|
|
97
|
+
- 源头: llamafactory.data.loader.get_dataset -> dataflex.train.data.loader.get_dataset
|
|
98
|
+
- 包层 re-export: 覆盖 llamafactory.data.get_dataset(如有)
|
|
99
|
+
- 就地覆盖: 对已 from-import 的使用方(包含 workflow)直接改其全局符号
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
do_uncache_reload: 为 True 时,会清理下游依赖缓存并预热导入,以确保后续 import 也拿到新函数。
|
|
103
|
+
默认为 False(与“就地打补丁”策略一致)。
|
|
104
|
+
"""
|
|
105
|
+
# 1) 引入新实现
|
|
106
|
+
from dataflex.train.data.loader import get_dataset as _new_get_dataset
|
|
107
|
+
# 2) 覆盖源头模块
|
|
108
|
+
data_loader_mod = importlib.import_module("llamafactory.data.loader")
|
|
109
|
+
setattr(data_loader_mod, "get_dataset", _new_get_dataset)
|
|
110
|
+
# 3) 覆盖包层 re-export(若其它代码从包层 import)
|
|
111
|
+
data_pkg = importlib.import_module("llamafactory.data")
|
|
112
|
+
setattr(data_pkg, "get_dataset", _new_get_dataset)
|
|
113
|
+
# 4) 就地覆盖已 from-import 的使用方(包含 workflow)
|
|
114
|
+
wflow = importlib.import_module("llamafactory.train.sft.workflow")
|
|
115
|
+
setattr(wflow, "get_dataset", _new_get_dataset)
|
|
116
|
+
|
|
117
|
+
# 5) 也要patch PT workflow
|
|
118
|
+
pt_wflow = importlib.import_module("llamafactory.train.pt.workflow")
|
|
119
|
+
setattr(pt_wflow, "get_dataset", _new_get_dataset)
|
|
120
|
+
|
|
121
|
+
def read_args():
|
|
122
|
+
file_path = sys.argv[1]
|
|
123
|
+
override_config = OmegaConf.from_cli(sys.argv[2:])
|
|
124
|
+
|
|
125
|
+
if file_path.endswith((".yaml", ".yml", ".json")):
|
|
126
|
+
dict_config = OmegaConf.load(Path(file_path).absolute())
|
|
127
|
+
cfg = OmegaConf.merge(dict_config, override_config)
|
|
128
|
+
else:
|
|
129
|
+
cfg = OmegaConf.create({}) # CLI 直接传参时
|
|
130
|
+
|
|
131
|
+
return OmegaConf.to_container(cfg)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def launch():
|
|
135
|
+
print("Launching DataFlex")
|
|
136
|
+
cfg = read_args()
|
|
137
|
+
patch_finetune_params()
|
|
138
|
+
patch_trainer(cfg['train_type'] if 'train_type' in cfg else 'static')
|
|
139
|
+
if cfg['train_type'] == 'dynamic_mix':
|
|
140
|
+
patch_get_dataset()
|
|
141
|
+
|
|
142
|
+
from llamafactory.train.tuner import run_exp
|
|
143
|
+
run_exp()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
if __name__ == "__main__":
|
|
147
|
+
launch()
|