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
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
from dataflex.core.registry import register_selector
|
|
2
|
+
from dataflex.utils.selector_io import load_cached_selection, save_selection
|
|
3
|
+
from dataflex.utils.logging import logger
|
|
4
|
+
from .base_selector import Selector
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
import torch.distributed as dist
|
|
8
|
+
from tqdm import tqdm
|
|
9
|
+
from torch.utils.data import Dataset, DataLoader
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
|
|
13
|
+
class IndexedDataset(Dataset):
|
|
14
|
+
def __init__(self, original_dataset):
|
|
15
|
+
self.dataset = original_dataset
|
|
16
|
+
|
|
17
|
+
def __len__(self):
|
|
18
|
+
return len(self.dataset)
|
|
19
|
+
|
|
20
|
+
def __getitem__(self, index):
|
|
21
|
+
data = self.dataset[index]
|
|
22
|
+
return {"idx": index, **data}
|
|
23
|
+
|
|
24
|
+
@register_selector('loss')
|
|
25
|
+
class LossSelector(Selector):
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
dataset,
|
|
29
|
+
accelerator,
|
|
30
|
+
data_collator,
|
|
31
|
+
cache_dir,
|
|
32
|
+
focus: str = "high", # "high" | "medium" | "low"
|
|
33
|
+
focus_weight: float = 5.0, # 权重倍数
|
|
34
|
+
quantiles: tuple = (0.33, 0.66), # 低/中/高切分点
|
|
35
|
+
replacement: bool = False, # 是否放回采样
|
|
36
|
+
temperature: float = 1.0, # 温度控制
|
|
37
|
+
):
|
|
38
|
+
super().__init__(dataset, accelerator, data_collator, cache_dir)
|
|
39
|
+
|
|
40
|
+
# 新增的采样控制参数
|
|
41
|
+
self.focus = str(focus).lower()
|
|
42
|
+
if self.focus not in {"low", "medium", "high"}:
|
|
43
|
+
raise ValueError("focus 必须是 'low'、'medium' 或 'high'")
|
|
44
|
+
self.focus_weight = focus_weight
|
|
45
|
+
self.quantiles = quantiles
|
|
46
|
+
self.replacement = replacement
|
|
47
|
+
self.temperature = temperature
|
|
48
|
+
|
|
49
|
+
logger.info(f"LossSelector initialized.")
|
|
50
|
+
|
|
51
|
+
def select(self, model, step_id: int, num_samples: int, **kwargs):
|
|
52
|
+
model.eval()
|
|
53
|
+
os.makedirs(self.cache_dir, exist_ok=True)
|
|
54
|
+
save_path = os.path.join(self.cache_dir, f"step_{step_id}.json")
|
|
55
|
+
n = len(self.dataset)
|
|
56
|
+
if os.path.exists(save_path):
|
|
57
|
+
if self.accelerator.is_main_process:
|
|
58
|
+
cached_indices, _ = load_cached_selection(save_path)
|
|
59
|
+
else:
|
|
60
|
+
cached_indices = None
|
|
61
|
+
cached_indices_list = [cached_indices]
|
|
62
|
+
if dist.is_available() and dist.is_initialized():
|
|
63
|
+
dist.broadcast_object_list(cached_indices_list, src=0)
|
|
64
|
+
cached_indices = cached_indices_list[0]
|
|
65
|
+
else:
|
|
66
|
+
cached_indices = cached_indices or []
|
|
67
|
+
return cached_indices
|
|
68
|
+
|
|
69
|
+
# 1) DataLoader
|
|
70
|
+
dataloader = DataLoader(
|
|
71
|
+
IndexedDataset(self.dataset),
|
|
72
|
+
batch_size=1,
|
|
73
|
+
shuffle=False,
|
|
74
|
+
num_workers=2,
|
|
75
|
+
collate_fn=self.data_collator,
|
|
76
|
+
)
|
|
77
|
+
dataloader = self.accelerator.prepare(dataloader)
|
|
78
|
+
|
|
79
|
+
# 2) 本地收集 loss 与 idx
|
|
80
|
+
logger.info(f"[Dataflex] Calculating loss using {self.accelerator.num_processes} GPUs")
|
|
81
|
+
local_losses, local_indices = [], []
|
|
82
|
+
for batch in tqdm(
|
|
83
|
+
dataloader,
|
|
84
|
+
desc=f"[Selector step {step_id}]",
|
|
85
|
+
disable=not self.accelerator.is_main_process,
|
|
86
|
+
dynamic_ncols=True,
|
|
87
|
+
):
|
|
88
|
+
idx = batch["idx"]
|
|
89
|
+
if not torch.is_tensor(idx):
|
|
90
|
+
idx = torch.tensor(idx, dtype=torch.long, device=self.accelerator.device)
|
|
91
|
+
idx = idx.view(-1).to(dtype=torch.long)
|
|
92
|
+
|
|
93
|
+
with torch.no_grad():
|
|
94
|
+
# 注意从 batch 中移除 'idx' 再喂给模型
|
|
95
|
+
model_inputs = {k: v for k, v in batch.items() if k != "idx"}
|
|
96
|
+
loss = model(**model_inputs).loss.detach().view(-1) # [B]
|
|
97
|
+
|
|
98
|
+
local_losses.append(loss)
|
|
99
|
+
local_indices.append(idx)
|
|
100
|
+
|
|
101
|
+
local_losses = torch.cat(local_losses, dim=0) # [N_local_padded]
|
|
102
|
+
local_indices = torch.cat(local_indices, dim=0) # [N_local_padded]
|
|
103
|
+
|
|
104
|
+
# 3) 各进程 gather(按 rank 串联,可能含补齐/重复)
|
|
105
|
+
all_losses = self.accelerator.gather(local_losses)
|
|
106
|
+
all_indices = self.accelerator.gather(local_indices)
|
|
107
|
+
|
|
108
|
+
# 4) 主进程按 idx 去重并对齐到 len(dataset)
|
|
109
|
+
if self.accelerator.is_main_process:
|
|
110
|
+
aligned = torch.full((n,), float("inf"), dtype=all_losses.dtype, device=all_losses.device)
|
|
111
|
+
seen = set()
|
|
112
|
+
# 采用“首次出现优先”保证确定性
|
|
113
|
+
for l, i in zip(all_losses.tolist(), all_indices.tolist()):
|
|
114
|
+
if 0 <= i < n and i not in seen:
|
|
115
|
+
aligned[i] = l
|
|
116
|
+
seen.add(i)
|
|
117
|
+
# 若极端情况下有没覆盖到的 idx,仍为 +inf;不会进 largest=True 的 topk
|
|
118
|
+
gathered_losses = aligned
|
|
119
|
+
logger.info(f"[Dataflex] Loss calculation finished")
|
|
120
|
+
else:
|
|
121
|
+
gathered_losses = None
|
|
122
|
+
|
|
123
|
+
# ========= 广播 gathered_losses(等长张量) =========
|
|
124
|
+
# gathered_list = [gathered_losses if self.accelerator.is_main_process else None]
|
|
125
|
+
# dist.broadcast_object_list(gathered_list, src=0)
|
|
126
|
+
# gathered_losses = gathered_list[0]
|
|
127
|
+
|
|
128
|
+
# ========= 主进程:基于分布的采样 =========
|
|
129
|
+
if self.accelerator.is_main_process:
|
|
130
|
+
logger.info(f"[Dataflex] focus={self.focus}, focus_weight={self.focus_weight}")
|
|
131
|
+
losses = gathered_losses.clone().detach().float()
|
|
132
|
+
valid_mask = torch.isfinite(losses)
|
|
133
|
+
|
|
134
|
+
if valid_mask.sum().item() == 0:
|
|
135
|
+
probs = torch.full((len(losses),), 1.0 / len(losses))
|
|
136
|
+
else:
|
|
137
|
+
valid_losses = losses[valid_mask]
|
|
138
|
+
q1 = torch.quantile(valid_losses, self.quantiles[0])
|
|
139
|
+
q2 = torch.quantile(valid_losses, self.quantiles[1])
|
|
140
|
+
|
|
141
|
+
low_mask = (losses <= q1) & valid_mask
|
|
142
|
+
medium_mask = (losses > q1) & (losses <= q2) & valid_mask
|
|
143
|
+
high_mask = (losses > q2) & valid_mask
|
|
144
|
+
|
|
145
|
+
weights = torch.zeros_like(losses).float()
|
|
146
|
+
weights[low_mask] = 1.0
|
|
147
|
+
weights[medium_mask] = 1.0
|
|
148
|
+
weights[high_mask] = 1.0
|
|
149
|
+
|
|
150
|
+
if self.focus == "low":
|
|
151
|
+
weights[low_mask] *= self.focus_weight
|
|
152
|
+
elif self.focus == "medium":
|
|
153
|
+
weights[medium_mask] *= self.focus_weight
|
|
154
|
+
else:
|
|
155
|
+
weights[high_mask] *= self.focus_weight
|
|
156
|
+
|
|
157
|
+
weights[~valid_mask] = 0.0
|
|
158
|
+
eps = 1e-12
|
|
159
|
+
probs = (weights + eps) ** (1.0 / self.temperature)
|
|
160
|
+
if probs.sum() == 0.0:
|
|
161
|
+
probs = valid_mask.float()
|
|
162
|
+
probs = probs / probs.sum()
|
|
163
|
+
|
|
164
|
+
available = int((probs > 0).sum().item())
|
|
165
|
+
effective_replacement = self.replacement
|
|
166
|
+
if not effective_replacement and num_samples > available:
|
|
167
|
+
effective_replacement = True
|
|
168
|
+
logger.info(
|
|
169
|
+
f"[Dataflex] 有效样本量 {available} 小于请求数量 {num_samples},"
|
|
170
|
+
f"已自动改为放回采样。"
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
gen = torch.Generator()
|
|
174
|
+
gen.manual_seed(self.seed + int(step_id))
|
|
175
|
+
sel_tensor = torch.multinomial(
|
|
176
|
+
probs.cpu(), num_samples=num_samples,
|
|
177
|
+
replacement=effective_replacement, generator=gen
|
|
178
|
+
)
|
|
179
|
+
sel = sel_tensor.tolist()
|
|
180
|
+
|
|
181
|
+
# ========= 4) 保存(只保存“被选中的 indices + 对应 metric”) =========
|
|
182
|
+
metric_payload = {
|
|
183
|
+
"loss": [float(losses[i].item()) for i in sel]
|
|
184
|
+
}
|
|
185
|
+
save_selection(save_path, sel, metric_payload, self.accelerator)
|
|
186
|
+
else:
|
|
187
|
+
sel = None
|
|
188
|
+
|
|
189
|
+
# 广播 sel
|
|
190
|
+
sel_list = [sel]
|
|
191
|
+
if dist.is_available() and dist.is_initialized():
|
|
192
|
+
dist.broadcast_object_list(sel_list, src=0)
|
|
193
|
+
sel = sel_list[0]
|
|
194
|
+
else:
|
|
195
|
+
sel = sel or []
|
|
196
|
+
|
|
197
|
+
return sel
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import numpy as np
|
|
3
|
+
from dataflex.core.registry import register_selector
|
|
4
|
+
from dataflex.utils.logging import logger
|
|
5
|
+
from .base_selector import Selector
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@register_selector("near")
|
|
9
|
+
class near_Selector(Selector):
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
dataset,
|
|
14
|
+
accelerator,
|
|
15
|
+
data_collator,
|
|
16
|
+
cache_dir,
|
|
17
|
+
indices_path: str = None):
|
|
18
|
+
super().__init__(dataset, accelerator, data_collator, cache_dir)
|
|
19
|
+
|
|
20
|
+
# 基本检查
|
|
21
|
+
if not indices_path or not os.path.exists(indices_path):
|
|
22
|
+
raise FileNotFoundError(f"top_indices 文件 {indices_path} 不存在!")
|
|
23
|
+
self.top_indices = np.load(indices_path)
|
|
24
|
+
logger.info(f"[near_Selector] Loaded top_indices from: {indices_path}")
|
|
25
|
+
logger.info(f"[near_Selector] top_indices shape: {self.top_indices.shape}")
|
|
26
|
+
if self.top_indices.ndim != 2:
|
|
27
|
+
raise ValueError(
|
|
28
|
+
f"top_indices 必须是二维矩阵,当前 ndim = {self.top_indices.ndim}"
|
|
29
|
+
)
|
|
30
|
+
if not np.issubdtype(self.top_indices.dtype, np.integer):
|
|
31
|
+
raise TypeError(
|
|
32
|
+
f"top_indices 必须是整数类型,当前 dtype = {self.top_indices.dtype}"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
max_idx = int(self.top_indices.max())
|
|
36
|
+
min_idx = int(self.top_indices.min())
|
|
37
|
+
if min_idx < 0 or max_idx >= len(self.dataset):
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"top_indices 中存在越界索引:范围 [{min_idx}, {max_idx}],"
|
|
40
|
+
f"但数据集长度为 {len(self.dataset)}"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
logger.info("[near_Selector] Initialization complete.")
|
|
44
|
+
|
|
45
|
+
def select(self, model, step_id: int, num_samples: int, **kwargs):
|
|
46
|
+
"""
|
|
47
|
+
按列优先顺序,从 top_indices 中选出 num_samples 个不重复的索引:
|
|
48
|
+
- 第 0 列: top_indices[0,0], top_indices[1,0], ..., top_indices[M-1,0]
|
|
49
|
+
- 第 1 列: top_indices[0,1], ...
|
|
50
|
+
- ...
|
|
51
|
+
- 遇到已经选过的 index 就跳过
|
|
52
|
+
- 遍历完所有列仍不足 num_samples,则直接报错阻止运行
|
|
53
|
+
"""
|
|
54
|
+
M, K = self.top_indices.shape
|
|
55
|
+
logger.info(
|
|
56
|
+
f"[near_Selector] Selecting {num_samples} samples "
|
|
57
|
+
f"from matrix of shape (M={M}, K={K}) ..."
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
selected_ids = []
|
|
61
|
+
selected_set = set()
|
|
62
|
+
|
|
63
|
+
for k in range(K):
|
|
64
|
+
for j in range(M):
|
|
65
|
+
idx = int(self.top_indices[j, k])
|
|
66
|
+
|
|
67
|
+
if idx in selected_set:
|
|
68
|
+
continue
|
|
69
|
+
|
|
70
|
+
selected_set.add(idx)
|
|
71
|
+
selected_ids.append(idx)
|
|
72
|
+
|
|
73
|
+
if len(selected_ids) >= num_samples:
|
|
74
|
+
logger.info(
|
|
75
|
+
f"[near_Selector] Col-wise selection reached "
|
|
76
|
+
f"num_samples={num_samples}."
|
|
77
|
+
)
|
|
78
|
+
return selected_ids
|
|
79
|
+
|
|
80
|
+
# 扫完所有列还不够,抛异常
|
|
81
|
+
raise ValueError(
|
|
82
|
+
f"{num_samples} 个不重复样本:最多只能得到 {len(selected_ids)} 个。"
|
|
83
|
+
)
|