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,147 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any, Union
|
|
3
|
+
from torch import nn
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Weighter(ABC):
|
|
8
|
+
"""
|
|
9
|
+
数据加权器的抽象基类,定义了加权器的基本接口和公共功能。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, **kwargs):
|
|
13
|
+
"""
|
|
14
|
+
基类构造函数
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
**kwargs: 子类特定的参数
|
|
18
|
+
"""
|
|
19
|
+
# 子类可以在这里定义公共的初始化逻辑
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
def _per_sample_loss_from_logits(self, logits, labels, ignore_index: int = -100):
|
|
23
|
+
"""
|
|
24
|
+
从 logits 和 labels 计算每个样本的损失
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
logits: 模型输出的 logits
|
|
28
|
+
labels: 真实标签
|
|
29
|
+
ignore_index: 忽略的标签索引
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
torch.Tensor: 每个样本的损失 (B,)
|
|
33
|
+
"""
|
|
34
|
+
shift_logits = logits[..., :-1, :].contiguous()
|
|
35
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
36
|
+
num_active = (shift_labels != ignore_index).sum(dim=1) # (B,)
|
|
37
|
+
loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
|
|
38
|
+
tok_loss = loss_fct(
|
|
39
|
+
shift_logits.view(-1, shift_logits.size(-1)),
|
|
40
|
+
shift_labels.view(-1).long()
|
|
41
|
+
)
|
|
42
|
+
return tok_loss.view(shift_logits.size(0), -1).sum(dim=1) / torch.clamp(num_active, min=1)
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
def get_weighted_loss(
|
|
46
|
+
self,
|
|
47
|
+
losses: torch.Tensor,
|
|
48
|
+
*,
|
|
49
|
+
ctx: Any = None,
|
|
50
|
+
model: nn.Module | None = None,
|
|
51
|
+
inputs: dict[str, Union[torch.Tensor, Any]] | None = None,
|
|
52
|
+
) -> torch.Tensor:
|
|
53
|
+
"""
|
|
54
|
+
核心加权方法,子类必须实现此方法
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
losses: 本卡的 per-sample loss (B,)
|
|
58
|
+
ctx: Trainer 上下文,可获取 global_step 等信息
|
|
59
|
+
model: 当前模型
|
|
60
|
+
inputs: 输入数据
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
torch.Tensor: 加权后的总损失(标量)
|
|
64
|
+
"""
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
def training_step(self, ctx, model, inputs, num_items_in_batch=None, use_weighter=False):
|
|
68
|
+
"""
|
|
69
|
+
执行训练步骤,包含前向传播、损失计算、加权和反向传播
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
ctx: Trainer 上下文
|
|
73
|
+
model: 模型
|
|
74
|
+
inputs: 输入数据
|
|
75
|
+
num_items_in_batch: 批次中的样本数量
|
|
76
|
+
use_weighter: 是否使用加权器
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
本步骤的损失值
|
|
80
|
+
"""
|
|
81
|
+
from dataflex.utils.logging import logger
|
|
82
|
+
from transformers.utils import is_apex_available
|
|
83
|
+
from accelerate.utils import DistributedType
|
|
84
|
+
|
|
85
|
+
model.train()
|
|
86
|
+
if hasattr(ctx.optimizer, "train") and callable(ctx.optimizer.train):
|
|
87
|
+
ctx.optimizer.train()
|
|
88
|
+
|
|
89
|
+
inputs = ctx._prepare_inputs(inputs)
|
|
90
|
+
|
|
91
|
+
# 预先保存一份 labels(防止某些实现里被 pop 掉)
|
|
92
|
+
labels_for_weighter = inputs.get("labels", None)
|
|
93
|
+
|
|
94
|
+
with ctx.compute_loss_context_manager():
|
|
95
|
+
# 关键:拿到 outputs
|
|
96
|
+
loss, outputs = ctx.compute_loss(
|
|
97
|
+
model, inputs, num_items_in_batch=num_items_in_batch, return_outputs=True
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
if use_weighter:
|
|
101
|
+
# 1) 如果 compute_loss 已经返回的是 (B,) 向量,直接用
|
|
102
|
+
if torch.is_tensor(loss) and loss.dim() == 1:
|
|
103
|
+
per_sample = loss
|
|
104
|
+
else:
|
|
105
|
+
# 2) 否则用 logits+labels 现场算每样本 loss(不需要二次前向)
|
|
106
|
+
logits = getattr(outputs, "logits", None) if outputs is not None else None
|
|
107
|
+
labels = inputs.get("labels", None)
|
|
108
|
+
if labels is None:
|
|
109
|
+
labels = labels_for_weighter
|
|
110
|
+
per_sample = None
|
|
111
|
+
if logits is not None and labels is not None:
|
|
112
|
+
per_sample = self._per_sample_loss_from_logits(logits, labels)
|
|
113
|
+
|
|
114
|
+
if per_sample is not None:
|
|
115
|
+
# 日志仅主进程打
|
|
116
|
+
if ctx.args.local_rank in [-1, 0]:
|
|
117
|
+
ps = per_sample.detach().float().cpu().view(-1)[0]
|
|
118
|
+
logger.info(f"[Dataflex] Before weighting per-sample (first sample): {ps}")
|
|
119
|
+
# 分布式加权
|
|
120
|
+
loss = self.get_weighted_loss(per_sample, ctx=ctx, model=model, inputs=inputs)
|
|
121
|
+
if ctx.args.local_rank in [-1, 0]:
|
|
122
|
+
logger.info(f"[Dataflex] After weighting (first sample): {float(loss.detach().cpu())}")
|
|
123
|
+
else:
|
|
124
|
+
if ctx.args.local_rank in [-1, 0]:
|
|
125
|
+
logger.info("[Dataflex] Could not form per-sample losses; fallback to scalar loss (no reweight).")
|
|
126
|
+
|
|
127
|
+
del inputs
|
|
128
|
+
|
|
129
|
+
if ctx.args.torch_empty_cache_steps is not None and ctx.state.global_step % ctx.args.torch_empty_cache_steps == 0:
|
|
130
|
+
ctx._empty_cache()
|
|
131
|
+
|
|
132
|
+
kwargs = {}
|
|
133
|
+
if ctx.args.n_gpu > 1:
|
|
134
|
+
loss = loss.mean()
|
|
135
|
+
|
|
136
|
+
if getattr(ctx, "use_apex", False):
|
|
137
|
+
if is_apex_available():
|
|
138
|
+
from apex import amp
|
|
139
|
+
with amp.scale_loss(loss, ctx.optimizer) as scaled_loss:
|
|
140
|
+
scaled_loss.backward()
|
|
141
|
+
else:
|
|
142
|
+
loss = loss / ctx.args.gradient_accumulation_steps
|
|
143
|
+
if ctx.accelerator.distributed_type == DistributedType.DEEPSPEED:
|
|
144
|
+
kwargs["scale_wrt_gas"] = False
|
|
145
|
+
ctx.accelerator.backward(loss, **kwargs)
|
|
146
|
+
|
|
147
|
+
return loss.detach()
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from dataflex.core.registry import register_weighter
|
|
2
|
+
from dataflex.utils.logging import logger
|
|
3
|
+
from typing import Any, Union
|
|
4
|
+
from torch import nn
|
|
5
|
+
import torch
|
|
6
|
+
from .base_weighter import Weighter
|
|
7
|
+
|
|
8
|
+
@register_weighter("custom")
|
|
9
|
+
class CustomWeighter(Weighter):
|
|
10
|
+
def __init__(self, strategy: str = "uniform", **kwargs):
|
|
11
|
+
"""
|
|
12
|
+
自定义加权器的构造函数
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
strategy: 加权策略,如 "uniform"、"loss_based" 等
|
|
16
|
+
**kwargs: 传递给基类的其他参数
|
|
17
|
+
"""
|
|
18
|
+
super().__init__(**kwargs)
|
|
19
|
+
self.strategy = strategy
|
|
20
|
+
logger.info(f"CustomWeighter initialized with strategy: {strategy}")
|
|
21
|
+
|
|
22
|
+
def get_weighted_loss(
|
|
23
|
+
self,
|
|
24
|
+
losses: torch.Tensor,
|
|
25
|
+
*,
|
|
26
|
+
ctx: Any = None,
|
|
27
|
+
model: nn.Module | None = None,
|
|
28
|
+
inputs: dict[str, Union[torch.Tensor, Any]] | None = None,
|
|
29
|
+
) -> torch.Tensor:
|
|
30
|
+
"""
|
|
31
|
+
核心加权逻辑。
|
|
32
|
+
根据样本损失计算加权后的总损失。
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
losses: 本卡的 per-sample loss (B,)
|
|
36
|
+
ctx: Trainer 上下文,可获取 global_step 等信息
|
|
37
|
+
model: 当前模型
|
|
38
|
+
inputs: 输入数据
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
加权后的总损失(标量)
|
|
42
|
+
"""
|
|
43
|
+
# 示例逻辑:简单的均匀加权
|
|
44
|
+
if not torch.is_tensor(losses) or losses.dim() == 0:
|
|
45
|
+
return losses
|
|
46
|
+
|
|
47
|
+
# 这里可以实现您的自定义加权策略
|
|
48
|
+
# 例如:基于损失大小、梯度信息、样本难度等
|
|
49
|
+
weights = torch.ones_like(losses) / losses.numel()
|
|
50
|
+
weighted_loss = torch.sum(weights * losses)
|
|
51
|
+
|
|
52
|
+
return weighted_loss
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
from dataflex.core.registry import register_weighter
|
|
2
|
+
from dataflex.utils.logging import logger
|
|
3
|
+
from typing import Any, Union
|
|
4
|
+
from torch import nn
|
|
5
|
+
from accelerate.utils import DistributedType
|
|
6
|
+
from transformers.training_args import OptimizerNames
|
|
7
|
+
from transformers.utils import is_apex_available
|
|
8
|
+
if is_apex_available():
|
|
9
|
+
from apex import amp
|
|
10
|
+
import torch
|
|
11
|
+
import torch.distributed as dist
|
|
12
|
+
from .base_weighter import Weighter
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@register_weighter('loss')
|
|
16
|
+
class LossWeighter(Weighter):
|
|
17
|
+
"""
|
|
18
|
+
参考论文
|
|
19
|
+
Dynamic Loss-Based Sample Reweighting for Improved Large Language Model Pretraining (ICLR2025)
|
|
20
|
+
"""
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
strategy: str = "linupper",
|
|
24
|
+
delta: float = 1.0,
|
|
25
|
+
**kwargs
|
|
26
|
+
):
|
|
27
|
+
super().__init__(**kwargs)
|
|
28
|
+
self.strategy = strategy
|
|
29
|
+
allowed = {"linupper", "uniform", "quadratic", "extremes"}
|
|
30
|
+
if strategy not in allowed:
|
|
31
|
+
raise ValueError(f"strategy must be one of {allowed}, but got '{strategy}'")
|
|
32
|
+
|
|
33
|
+
self.delta = float(delta)
|
|
34
|
+
self.r = 1
|
|
35
|
+
|
|
36
|
+
# ====== 与参考一致的三个函数 ======
|
|
37
|
+
@staticmethod
|
|
38
|
+
def scale_losses(losses: torch.Tensor, r: float) -> torch.Tensor:
|
|
39
|
+
# Exponential scaling: exp(loss / r)
|
|
40
|
+
return torch.exp(losses / r)
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def normalize_losses(
|
|
44
|
+
losses: torch.Tensor, delta: float = 1.0, l_min: float = 0.0, l_max: float = 1.0
|
|
45
|
+
) -> torch.Tensor:
|
|
46
|
+
denom = max(l_max - l_min, 1e-6)
|
|
47
|
+
return 2.0 * delta * losses / denom - delta * (l_max + l_min) / denom
|
|
48
|
+
|
|
49
|
+
def apply_strategy(self, losses: torch.Tensor, delta: float = 1.0, strategy: str | None = None) -> torch.Tensor:
|
|
50
|
+
s = strategy or self.strategy
|
|
51
|
+
if s == "linupper":
|
|
52
|
+
return torch.minimum(losses + delta, delta * torch.ones_like(losses))
|
|
53
|
+
elif s == "uniform":
|
|
54
|
+
return losses
|
|
55
|
+
elif s == "quadratic":
|
|
56
|
+
return 1 - (losses ** 2) / (delta ** 2)
|
|
57
|
+
elif s == "extremes":
|
|
58
|
+
return torch.abs(losses)
|
|
59
|
+
else:
|
|
60
|
+
raise NotImplementedError(f"Unknown strategy: {s}")
|
|
61
|
+
|
|
62
|
+
def _brief(x):
|
|
63
|
+
if torch.is_tensor(x):
|
|
64
|
+
if x.dim() == 0:
|
|
65
|
+
return float(x.detach().cpu())
|
|
66
|
+
else:
|
|
67
|
+
return x.detach().float().cpu()[:5].tolist()
|
|
68
|
+
return x
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def get_weighted_loss(
|
|
72
|
+
self,
|
|
73
|
+
losses: torch.Tensor,
|
|
74
|
+
*,
|
|
75
|
+
ctx: Any = None, # 可选:Trainer 上下文,便于获取 global_step 等
|
|
76
|
+
model: nn.Module | None = None, # 可选:未来扩展用(梯度/激活/正则等)
|
|
77
|
+
inputs: dict[str, Union[torch.Tensor, Any]] | None = None, # 可选:未来扩展用
|
|
78
|
+
) -> torch.Tensor:
|
|
79
|
+
"""
|
|
80
|
+
参数:
|
|
81
|
+
losses: 本卡的 per-sample loss (B,)。若是标量/非张量,直接原样返回(不加权)。
|
|
82
|
+
ctx: 传入 Trainer(或具备 state/global_step 的对象),用于 r 调度。
|
|
83
|
+
返回:
|
|
84
|
+
标量 loss(已经完成分布式加权,含 ×world_size)。
|
|
85
|
+
"""
|
|
86
|
+
# 兼容:标量或非张量 → 不加权
|
|
87
|
+
if (not torch.is_tensor(losses)) or (losses.dim() == 0):
|
|
88
|
+
return losses
|
|
89
|
+
|
|
90
|
+
# 确保是一维向量
|
|
91
|
+
if losses.dim() > 1:
|
|
92
|
+
losses = losses.view(-1)
|
|
93
|
+
|
|
94
|
+
device_losses = losses # (B,)
|
|
95
|
+
device = device_losses.device
|
|
96
|
+
dtype = device_losses.dtype
|
|
97
|
+
|
|
98
|
+
dist_on = dist.is_available() and dist.is_initialized()
|
|
99
|
+
world_size = dist.get_world_size() if dist_on else 1
|
|
100
|
+
local_rank = dist.get_rank() if dist_on else 0
|
|
101
|
+
|
|
102
|
+
# 1) 收集本批次所有 GPU 的 per-sample loss -> [W, B]
|
|
103
|
+
if dist_on:
|
|
104
|
+
gathered = torch.zeros(world_size, device_losses.numel(), device=device, dtype=dtype)
|
|
105
|
+
if hasattr(dist, "all_gather_into_tensor"):
|
|
106
|
+
dist.all_gather_into_tensor(gathered, device_losses.detach())
|
|
107
|
+
else:
|
|
108
|
+
bufs = [torch.zeros_like(device_losses) for _ in range(world_size)]
|
|
109
|
+
dist.all_gather(bufs, device_losses.detach())
|
|
110
|
+
gathered = torch.stack(bufs, dim=0)
|
|
111
|
+
else:
|
|
112
|
+
gathered = device_losses.detach().unsqueeze(0) # [1, B]
|
|
113
|
+
|
|
114
|
+
r = self.r
|
|
115
|
+
|
|
116
|
+
# 3) 规范化 → 策略加权 → 指数缩放(数值稳定:先减 max)→ 归一化 → 切回本卡
|
|
117
|
+
with torch.no_grad():
|
|
118
|
+
min_loss = gathered.min().item()
|
|
119
|
+
max_loss = gathered.max().item()
|
|
120
|
+
|
|
121
|
+
normalized = self.normalize_losses(
|
|
122
|
+
gathered.view(-1), delta=self.delta, l_min=min_loss, l_max=max_loss
|
|
123
|
+
)
|
|
124
|
+
reweighted = self.apply_strategy(normalized, delta=self.delta, strategy=self.strategy)
|
|
125
|
+
|
|
126
|
+
centered = reweighted - float(reweighted.max().item()) # 数值稳定
|
|
127
|
+
scaled = self.scale_losses(centered, r=r)
|
|
128
|
+
|
|
129
|
+
weights = scaled / torch.clamp(scaled.sum(), min=1e-12)
|
|
130
|
+
device_weights = weights.view(world_size, -1)[local_rank, :] # (B,)
|
|
131
|
+
|
|
132
|
+
# 4) 本卡加权并 × world_size(保持与参考实现一致)
|
|
133
|
+
return torch.sum(device_weights * device_losses) * world_size
|
|
File without changes
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import yaml
|
|
2
|
+
from typing import Dict, Any, Optional
|
|
3
|
+
|
|
4
|
+
def load_component(type: str, cfg_file: str, name: str, runtime_vars: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
|
5
|
+
with open(cfg_file, "r", encoding="utf-8") as f:
|
|
6
|
+
root = yaml.safe_load(f) or {}
|
|
7
|
+
bucket = (root.get(type) or {})
|
|
8
|
+
if name not in bucket:
|
|
9
|
+
available = ", ".join(sorted(bucket.keys()))
|
|
10
|
+
raise ValueError(f"{type} '{name}' not found. Available: {available}")
|
|
11
|
+
params = dict(bucket[name].get("params") or {})
|
|
12
|
+
|
|
13
|
+
# 简单占位替换(如 ${output_dir})
|
|
14
|
+
if runtime_vars:
|
|
15
|
+
def subst(v):
|
|
16
|
+
if isinstance(v, str):
|
|
17
|
+
for k, val in runtime_vars.items(): v = v.replace(k, val)
|
|
18
|
+
return v
|
|
19
|
+
if isinstance(v, dict): return {kk: subst(vv) for kk, vv in v.items()}
|
|
20
|
+
if isinstance(v, list): return [subst(x) for x in v]
|
|
21
|
+
return v
|
|
22
|
+
params = subst(params)
|
|
23
|
+
|
|
24
|
+
return params
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import torch.distributed as dist
|
|
4
|
+
from typing import Dict, List, Optional, Tuple
|
|
5
|
+
from dataflex.utils.logging import logger
|
|
6
|
+
|
|
7
|
+
def _ensure_parent_dir(path: str) -> None:
|
|
8
|
+
parent = os.path.dirname(path)
|
|
9
|
+
if parent:
|
|
10
|
+
os.makedirs(parent, exist_ok=True)
|
|
11
|
+
|
|
12
|
+
def load_cached_selection(
|
|
13
|
+
save_path: str
|
|
14
|
+
) -> Tuple[Optional[List[int]], Optional[Dict[str, List]]]:
|
|
15
|
+
indices = None
|
|
16
|
+
metric = None
|
|
17
|
+
with open(save_path, "r") as f:
|
|
18
|
+
payload = json.load(f)
|
|
19
|
+
indices = payload.get("indices", [])
|
|
20
|
+
metric = payload.get("metric", {})
|
|
21
|
+
|
|
22
|
+
logger.info(f"[Dataflex] Loaded cached selection from {save_path}: {indices is not None}.")
|
|
23
|
+
return indices, metric
|
|
24
|
+
|
|
25
|
+
def save_selection(
|
|
26
|
+
save_path: str,
|
|
27
|
+
indices: List[int],
|
|
28
|
+
metric: Dict[str, List],
|
|
29
|
+
accelerator,
|
|
30
|
+
) -> None:
|
|
31
|
+
"""
|
|
32
|
+
以统一格式保存,并仅由主进程落盘。
|
|
33
|
+
存储为标准的 JSON 格式。
|
|
34
|
+
"""
|
|
35
|
+
if accelerator.is_main_process:
|
|
36
|
+
_ensure_parent_dir(save_path)
|
|
37
|
+
payload = {
|
|
38
|
+
"indices": list(map(int, indices)),
|
|
39
|
+
"metric": metric,
|
|
40
|
+
}
|
|
41
|
+
with open(save_path, "w") as f:
|
|
42
|
+
json.dump(payload, f, indent=4) # 保存为漂亮的JSON格式
|
|
43
|
+
logger.info(f"[Dataflex] Saved selection to {save_path}.")
|
dataflex/version.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
|
2
|
+
short_version = __version__
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def get_version():
|
|
6
|
+
return __version__
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def parse_version_info(version_str):
|
|
10
|
+
version_info = []
|
|
11
|
+
for x in version_str.split("."):
|
|
12
|
+
if x.isdigit():
|
|
13
|
+
version_info.append(int(x))
|
|
14
|
+
elif x.find("rc") != -1:
|
|
15
|
+
patch_version = x.split("rc")
|
|
16
|
+
version_info.append(int(patch_version[0]))
|
|
17
|
+
version_info.append(f"rc{patch_version[1]}")
|
|
18
|
+
return tuple(version_info)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
version_info = parse_version_info(__version__)
|