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.
Files changed (52) hide show
  1. dataflex/__init__.py +4 -0
  2. dataflex/cli.py +202 -0
  3. dataflex/configs/components.yaml +151 -0
  4. dataflex/core/__init__.py +0 -0
  5. dataflex/core/registry.py +32 -0
  6. dataflex/launcher.py +147 -0
  7. dataflex/offline_selector/offline_near_selector.py +195 -0
  8. dataflex/offline_selector/offline_tsds_selector.py +251 -0
  9. dataflex/train/__init__.py +0 -0
  10. dataflex/train/data/__init__.py +0 -0
  11. dataflex/train/data/loader.py +164 -0
  12. dataflex/train/dataset/__init__.py +3 -0
  13. dataflex/train/dataset/mixed_proportion_manager.py +167 -0
  14. dataflex/train/hparams/__init__.py +0 -0
  15. dataflex/train/hparams/dynamic_data_params.py +200 -0
  16. dataflex/train/hparams/dynamic_params.py +649 -0
  17. dataflex/train/mixer/__init__.py +5 -0
  18. dataflex/train/mixer/base_mixer.py +21 -0
  19. dataflex/train/mixer/doremi_mixer.py +312 -0
  20. dataflex/train/mixer/dynamic_moe_mixer.py +381 -0
  21. dataflex/train/mixer/odm_mixer.py +278 -0
  22. dataflex/train/mixer/random_mixer.py +27 -0
  23. dataflex/train/mixer/static_mixer.py +47 -0
  24. dataflex/train/selector/__init__.py +8 -0
  25. dataflex/train/selector/base_selector.py +56 -0
  26. dataflex/train/selector/custom_selector.py +38 -0
  27. dataflex/train/selector/delta_loss_selector.py +271 -0
  28. dataflex/train/selector/less_selector.py +389 -0
  29. dataflex/train/selector/loss_selector.py +197 -0
  30. dataflex/train/selector/near_selector.py +83 -0
  31. dataflex/train/selector/nice_selector.py +658 -0
  32. dataflex/train/selector/random_selector.py +59 -0
  33. dataflex/train/selector/tsds_selector.py +45 -0
  34. dataflex/train/trainer/__init__.py +0 -0
  35. dataflex/train/trainer/mix_trainer.py +1102 -0
  36. dataflex/train/trainer/select_trainer.py +887 -0
  37. dataflex/train/trainer/weight_trainer.py +773 -0
  38. dataflex/train/weighter/__init__.py +3 -0
  39. dataflex/train/weighter/base_weighter.py +147 -0
  40. dataflex/train/weighter/custom_weighter.py +52 -0
  41. dataflex/train/weighter/loss_weighter.py +133 -0
  42. dataflex/utils/__init__.py +0 -0
  43. dataflex/utils/load_component.py +24 -0
  44. dataflex/utils/logging.py +6 -0
  45. dataflex/utils/selector_io.py +43 -0
  46. dataflex/version.py +21 -0
  47. dataflex-1.0.0.dist-info/METADATA +385 -0
  48. dataflex-1.0.0.dist-info/RECORD +52 -0
  49. dataflex-1.0.0.dist-info/WHEEL +5 -0
  50. dataflex-1.0.0.dist-info/entry_points.txt +2 -0
  51. dataflex-1.0.0.dist-info/licenses/LICENSE +200 -0
  52. dataflex-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,278 @@
1
+ from dataflex.core.registry import register_mixer
2
+ from dataflex.utils.logging import logger
3
+ from .base_mixer import Mixer
4
+
5
+ import numpy as np
6
+ import torch
7
+ import os
8
+
9
+ @register_mixer("odm")
10
+ class ODMMixer(Mixer):
11
+ def __init__(self, mixture_manager, alpha=0.90, warmup_steps=2000, output_dir=None,
12
+ accelerator=None, initial_proportions=None, **kwargs):
13
+ """
14
+ Initialize Online Data Mixing (ODM) Mixer based on Multi-Armed Bandits (Exp3).
15
+
16
+ ODM uses Exp3 with Moving Average to dynamically adjust domain weights during training.
17
+ Key formula: R_hat_t = alpha * R_hat_{t-1} + (1-alpha) * (reward_t / pi_{t-1})
18
+
19
+ Args:
20
+ mixture_manager: The mixture manager object
21
+ alpha: Smoothing factor for moving average
22
+ warmup_steps: Number of warmup steps with initial proportions
23
+ output_dir: Output directory for saving weight logs
24
+ accelerator: Accelerator object for distributed training
25
+ initial_proportions: Initial domain proportions. If None, uses uniform distribution.
26
+ reward_scale: Scale factor for loss values to amplify signal
27
+ min_exploration_rate: Minimum exploration rate to maintain algorithm sensitivity
28
+ """
29
+ super().__init__(mixture_manager)
30
+ self.alpha = float(alpha)
31
+ self.warmup_steps = int(warmup_steps)
32
+ self.output_dir = output_dir
33
+ self.accelerator = accelerator
34
+
35
+ # Reward scaling to amplify loss signal for better differentiation
36
+ self.reward_scale = float(kwargs.get('reward_scale', 15.0))
37
+
38
+ # Minimum exploration rate to prevent algorithm from "freezing" in late stages
39
+ self.min_exploration_rate = float(kwargs.get('min_exploration_rate', 0.03))
40
+
41
+ # Number of domains
42
+ self.k = len(self.mixture_manager.names)
43
+
44
+ # Initialize proportions
45
+ if initial_proportions is not None:
46
+ initial_proportions = np.array(initial_proportions, dtype=float)
47
+ if len(initial_proportions) == self.k:
48
+ self.initial_proportions = initial_proportions / np.sum(initial_proportions)
49
+ logger.info(f"[ODMMixer] Using provided initial proportions: {self.initial_proportions}")
50
+ else:
51
+ logger.warning(f"[ODMMixer] Initial proportions mismatch. Using uniform distribution.")
52
+ self.initial_proportions = np.ones(self.k) / self.k
53
+ elif hasattr(self.mixture_manager, 'initial_proportions') and self.mixture_manager.initial_proportions is not None:
54
+ init_props = np.array(self.mixture_manager.initial_proportions, dtype=float)
55
+ if len(init_props) == self.k:
56
+ self.initial_proportions = init_props / np.sum(init_props)
57
+ logger.info(f"[ODMMixer] Using initial proportions from mixture_manager: {self.initial_proportions}")
58
+ else:
59
+ self.initial_proportions = np.ones(self.k) / self.k
60
+ else:
61
+ self.initial_proportions = np.ones(self.k) / self.k
62
+ logger.info(f"[ODMMixer] Using uniform initial distribution")
63
+
64
+ # Current domain sampling policy π_t
65
+ self.domain_weights = self.initial_proportions.copy()
66
+
67
+ # Estimated rewards (moving average, NOT cumulative sum)
68
+ self.estimated_rewards = np.zeros(self.k)
69
+
70
+ # Exploration rate ε_t
71
+ self.exploration_rate = 1.0 / self.k
72
+
73
+ # Track previous batch info for reward computation
74
+ self.prev_batch_info = None
75
+
76
+ logger.info(f"[ODMMixer] Initialized: K={self.k}, alpha={self.alpha}, warmup={self.warmup_steps}")
77
+ logger.info(f"[ODMMixer] Scaling: reward_scale={self.reward_scale}, min_eps={self.min_exploration_rate}")
78
+ logger.info(f"[ODMMixer] Domain names: {self.mixture_manager.names}")
79
+
80
+ def _compute_exploration_rate(self, t):
81
+ """
82
+ Compute exploration rate: ε_t = max{min_eps, min{1/K, sqrt(ln(K) / (K * t))}}
83
+ The min_eps floor ensures algorithm maintains sensitivity in late stages.
84
+ """
85
+ if t <= 0:
86
+ return 1.0 / self.k
87
+ decay_term = np.sqrt(np.log(self.k) / (self.k * t))
88
+ calculated_rate = min(1.0 / self.k, decay_term)
89
+ # Apply floor to maintain minimum exploration (annealing with lower bound)
90
+ return max(self.min_exploration_rate, calculated_rate)
91
+
92
+ def _update_policy(self, step_t):
93
+ """
94
+ Update sampling policy using Exp3 algorithm.
95
+ π_t(D_i) ∝ exp(ε_{t-1} * R̂_i) * (1 - K*ε_t) + ε_t
96
+ """
97
+ # Validate estimated_rewards
98
+ if not np.all(np.isfinite(self.estimated_rewards)):
99
+ logger.warning(f"[ODMMixer] Invalid estimated_rewards, resetting to 0")
100
+ self.estimated_rewards[:] = 0.0
101
+
102
+ # Store previous exploration rate
103
+ prev_eps = self.exploration_rate
104
+
105
+ # Compute new exploration rate
106
+ self.exploration_rate = self._compute_exploration_rate(step_t)
107
+
108
+ # Compute exp(prev_eps * R̂_i) for each domain
109
+ x = prev_eps * self.estimated_rewards
110
+ x = x - np.max(x)
111
+ x = np.clip(x, -5.0, 0.0) # Prevent overflow
112
+ exp_scaled_rewards = np.exp(x)
113
+ total_exp = np.sum(exp_scaled_rewards)
114
+
115
+ # Safety check
116
+ if not np.isfinite(total_exp) or total_exp <= 0:
117
+ logger.warning(f"[ODMMixer] Invalid exp sum, resetting to initial proportions")
118
+ self.domain_weights = self.initial_proportions.copy()
119
+ self.estimated_rewards[:] = 0.0
120
+ return
121
+
122
+ # scaling_factor = (1 - K*ε_t) / Σ exp(...)
123
+ numerator = max(0.0, 1.0 - self.k * self.exploration_rate)
124
+ scaling_factor = numerator / total_exp
125
+
126
+ # w_i = exp(...) * scaling_factor + ε_t
127
+ self.domain_weights = exp_scaled_rewards * scaling_factor + self.exploration_rate
128
+
129
+ # Normalize
130
+ if np.all(np.isfinite(self.domain_weights)) and np.sum(self.domain_weights) > 0:
131
+ self.domain_weights = self.domain_weights / np.sum(self.domain_weights)
132
+ self.domain_weights = np.maximum(self.domain_weights, 1e-8)
133
+ self.domain_weights = self.domain_weights / np.sum(self.domain_weights)
134
+ else:
135
+ logger.warning(f"[ODMMixer] Invalid weights after update, resetting")
136
+ self.domain_weights = self.initial_proportions.copy()
137
+ self.estimated_rewards[:] = 0.0
138
+
139
+ def _update_reward_from_batch(self, batch_loss, domain_id):
140
+ """
141
+ Update estimated reward using moving average (ODM core formula).
142
+ R̂_t = alpha * R̂_{t-1} + (1-alpha) * (reward / π_{t-1})
143
+
144
+ This is the KEY difference from standard Exp3: using moving average instead of cumulative sum.
145
+ """
146
+ if not np.isfinite(batch_loss):
147
+ logger.warning(f"[ODMMixer] Invalid batch_loss: {batch_loss}, skipping update")
148
+ return
149
+
150
+ # Scale loss to amplify signal for Exp3 algorithm
151
+ # Current loss range: ~3-12, scaled to ~150-600 for better differentiation
152
+ reward = batch_loss * self.reward_scale
153
+
154
+ # Get previous policy probability for importance weighting
155
+ prob = max(self.domain_weights[domain_id], 1e-8)
156
+
157
+ # Importance-weighted reward
158
+ importance_weighted_reward = reward / prob
159
+
160
+ if not np.isfinite(importance_weighted_reward):
161
+ logger.warning(f"[ODMMixer] Invalid importance_weighted_reward, skipping")
162
+ return
163
+
164
+ # CRITICAL: Moving average update (not cumulative sum!)
165
+ # This is the core innovation of ODM over standard Exp3
166
+ old_estimate = self.estimated_rewards[domain_id]
167
+ new_estimate = self.alpha * old_estimate + (1.0 - self.alpha) * importance_weighted_reward
168
+
169
+ # Validate and clip for numerical stability
170
+ if np.isfinite(new_estimate):
171
+ self.estimated_rewards[domain_id] = np.clip(new_estimate, -10000.0, 10000.0)
172
+ else:
173
+ logger.warning(f"[ODMMixer] Invalid new_estimate for domain {domain_id}, keeping old value")
174
+
175
+ def mix(self, model, step_id: int, **kwargs) -> np.ndarray:
176
+ """
177
+ Compute new domain weights using ODM algorithm.
178
+
179
+ Args:
180
+ model: Current model being trained
181
+ step_id: Current training step
182
+ **kwargs: Must contain training batch info for reward update
183
+
184
+ Returns:
185
+ np.ndarray: Updated domain proportions
186
+ """
187
+ output_dir = kwargs.get('output_dir', self.output_dir)
188
+
189
+ # Warmup phase: use initial proportions
190
+ if step_id <= self.warmup_steps:
191
+ logger.info(f"[ODMMixer] Step {step_id} (warmup): Using initial proportions")
192
+ return self.initial_proportions.copy()
193
+
194
+ logger.info(f"[ODMMixer] Step {step_id}: Updating domain weights with ODM")
195
+
196
+ # Update reward from previous training batch
197
+ if self.prev_batch_info is not None:
198
+ prev_loss = self.prev_batch_info.get('loss')
199
+ prev_domain_id = self.prev_batch_info.get('domain_id')
200
+
201
+ if prev_loss is not None and prev_domain_id is not None:
202
+ # Update reward using moving average (ODM's key innovation)
203
+ self._update_reward_from_batch(prev_loss, prev_domain_id)
204
+ domain_name = self.mixture_manager.names[prev_domain_id]
205
+ logger.info(f"[ODMMixer] Updated reward for '{domain_name}': "
206
+ f"loss={prev_loss:.4f}, R̂={self.estimated_rewards[prev_domain_id]:.4f}")
207
+
208
+ # Update policy using Exp3
209
+ self._update_policy(step_id - self.warmup_steps)
210
+
211
+ # Validate and normalize
212
+ if np.any(~np.isfinite(self.domain_weights)):
213
+ logger.error(f"[ODMMixer] Invalid domain weights, falling back to initial proportions")
214
+ return self.initial_proportions.copy()
215
+
216
+ self.domain_weights = np.maximum(self.domain_weights, 0)
217
+ self.domain_weights = self.domain_weights / np.sum(self.domain_weights)
218
+
219
+ # Log results
220
+ logger.info(f"[ODMMixer] ε_t={self.exploration_rate:.6f}")
221
+ logger.info(f"[ODMMixer] Updated domain weights:")
222
+ for i, name in enumerate(self.mixture_manager.names):
223
+ logger.info(f" {name}: {self.domain_weights[i]:.4f} (R̂={self.estimated_rewards[i]:.4f})")
224
+
225
+ # Save weights
226
+ if output_dir is not None:
227
+ self.save_weights_to_jsonl(output_dir, step_id)
228
+
229
+ return self.domain_weights.copy()
230
+
231
+ def update_batch_info(self, batch_loss, domain_id):
232
+ """
233
+ Store batch information for next reward update.
234
+ Should be called from trainer after each training step.
235
+
236
+ Args:
237
+ batch_loss: Training loss from the batch
238
+ domain_id: Domain ID of the sampled batch
239
+ """
240
+ self.prev_batch_info = {
241
+ 'loss': batch_loss,
242
+ 'domain_id': domain_id
243
+ }
244
+
245
+ def save_weights_to_jsonl(self, output_dir, step_id):
246
+ """Save domain weights to JSONL file (append mode, one line per update)."""
247
+ if self.accelerator is not None and not self.accelerator.is_main_process:
248
+ return
249
+
250
+ try:
251
+ import json
252
+ import time
253
+
254
+ if output_dir is None:
255
+ return
256
+
257
+ os.makedirs(output_dir, exist_ok=True)
258
+ weights_file = os.path.join(output_dir, "odm_weights.jsonl")
259
+
260
+ log_entry = {
261
+ "step": step_id,
262
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
263
+ "domain_names": self.mixture_manager.names,
264
+ "domain_weights": self.domain_weights.tolist(),
265
+ "estimated_rewards": self.estimated_rewards.tolist(),
266
+ "exploration_rate": float(self.exploration_rate),
267
+ "alpha": self.alpha,
268
+ }
269
+
270
+ with open(weights_file, 'a') as f:
271
+ f.write(json.dumps(log_entry) + '\n')
272
+
273
+ except Exception as e:
274
+ logger.warning(f"[ODMMixer] Failed to log weights: {e}")
275
+
276
+ def get_current_weights(self):
277
+ """Get current domain weights."""
278
+ return self.domain_weights.copy()
@@ -0,0 +1,27 @@
1
+ from dataflex.core.registry import register_mixer
2
+ from dataflex.utils.logging import logger
3
+ from .base_mixer import Mixer
4
+
5
+ import numpy as np
6
+
7
+ @register_mixer("random")
8
+ class RandomMixer(Mixer):
9
+ def __init__(self, mixture_manager, seed):
10
+ super().__init__(mixture_manager)
11
+ self.seed = seed
12
+
13
+ def mix(self, model, step_id: int, **kwargs) -> np.ndarray:
14
+ """
15
+ 随机生成一组比例向量。
16
+
17
+ Returns:
18
+ np.ndarray: 长度为源数量的归一化比例数组。
19
+ """
20
+ k = len(self.mixture_manager.names)
21
+ np.random.seed(self.seed)
22
+ raw = np.random.random(k)
23
+ probs = raw / raw.sum() # 归一化
24
+ logger.info(f"[RandomMixer] Step {step_id} Generated proportions: {probs}")
25
+
26
+ return probs
27
+
@@ -0,0 +1,47 @@
1
+ from dataflex.core.registry import register_mixer
2
+ from dataflex.utils.logging import logger
3
+ from .base_mixer import Mixer
4
+
5
+ import numpy as np
6
+
7
+ @register_mixer("static")
8
+ class StaticMixer(Mixer):
9
+ def __init__(self, mixture_manager, proportions=None, **kwargs):
10
+
11
+ super().__init__(mixture_manager)
12
+
13
+ k = len(self.mixture_manager.names)
14
+
15
+ if proportions is None:
16
+ # Use uniform distribution if no proportions specified
17
+ self.proportions = np.ones(k) / k
18
+ logger.info(f"[StaticMixer] No proportions specified, using uniform distribution: {self.proportions}")
19
+ else:
20
+ # Validate and normalize proportions
21
+ proportions = np.array(proportions, dtype=float)
22
+
23
+ if len(proportions) != k:
24
+ raise ValueError(f"[StaticMixer] Number of proportions ({len(proportions)}) "
25
+ f"must match number of domains ({k})")
26
+
27
+ if np.any(proportions < 0):
28
+ raise ValueError("[StaticMixer] All proportions must be non-negative")
29
+
30
+ if np.sum(proportions) == 0:
31
+ raise ValueError("[StaticMixer] Sum of proportions cannot be zero")
32
+
33
+ # Normalize to ensure they sum to 1
34
+ self.proportions = proportions / np.sum(proportions)
35
+
36
+ logger.info(f"[StaticMixer] Using fixed proportions: {self.proportions}")
37
+ logger.info(f"[StaticMixer] Domain names: {self.mixture_manager.names}")
38
+
39
+ def mix(self, model, step_id: int, **kwargs) -> np.ndarray:
40
+
41
+ logger.info(f"[StaticMixer] Step {step_id} Using fixed proportions: {self.proportions}")
42
+
43
+ # Log domain-wise proportions for clarity
44
+ for i, name in enumerate(self.mixture_manager.names):
45
+ logger.info(f" {name}: {self.proportions[i]:.4f}")
46
+
47
+ return self.proportions.copy()
@@ -0,0 +1,8 @@
1
+ from .loss_selector import *
2
+ from .less_selector import *
3
+ from .delta_loss_selector import *
4
+ from .custom_selector import *
5
+ from .tsds_selector import *
6
+ from .nice_selector import *
7
+ from .random_selector import *
8
+ from .near_selector import *
@@ -0,0 +1,56 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import List
3
+ import torch
4
+ from torch import distributed as dist
5
+
6
+ class Selector(ABC):
7
+ def __init__(self, dataset, accelerator, data_collator, cache_dir):
8
+ self.dataset = dataset
9
+ self.accelerator = accelerator
10
+ self.data_collator = data_collator
11
+ self.cache_dir = cache_dir
12
+ self.seed = 42
13
+
14
+ def warmup(self, num_samples: int, replacement: bool) -> List[List[int]]:
15
+ if self.accelerator.is_main_process:
16
+ dataset_size = len(self.dataset)
17
+ gen = torch.Generator()
18
+ gen.manual_seed(self.seed)
19
+
20
+ if replacement:
21
+ full_indices = torch.randint(
22
+ low=0, high=dataset_size, size=(num_samples,), generator=gen
23
+ ).tolist()
24
+ else:
25
+ if num_samples > dataset_size:
26
+ raise ValueError(
27
+ f"Cannot sample {num_samples} without replacement from {dataset_size} samples"
28
+ )
29
+ full_indices = torch.randperm(dataset_size, generator=gen)[:num_samples].tolist()
30
+ else:
31
+ full_indices = None
32
+
33
+ obj = [full_indices]
34
+ if dist.is_available() and dist.is_initialized():
35
+ dist.broadcast_object_list(obj, src=0)
36
+ full_indices = obj[0]
37
+ else:
38
+ full_indices = full_indices or []
39
+
40
+ return full_indices
41
+
42
+ @abstractmethod
43
+ def select(self, model, step_id: int, num_samples: int, **kwargs):
44
+ """
45
+ Select samples from the dataset for the model in 'step_id'.
46
+
47
+ Args:
48
+ model: The model object used in the selection process.
49
+ step_id (int): The ID of the current training step or stage.
50
+ num_samples (int): The number of samples to select.
51
+ **kwargs: Additional keyword arguments, allowing for flexible expansion by subclasses.
52
+
53
+ Returns:
54
+ List[int]: A list of the selected sample indices.
55
+ """
56
+ pass
@@ -0,0 +1,38 @@
1
+ from dataflex.core.registry import register_selector
2
+ from dataflex.utils.logging import logger
3
+ from .base_selector import Selector
4
+
5
+ @register_selector('custom')
6
+ class CustomSelector(Selector):
7
+ """
8
+ 一个自定义数据选择器的示例实现。
9
+ """
10
+ def __init__(
11
+ self,
12
+ dataset,
13
+ accelerator,
14
+ data_collator,
15
+ cache_dir,
16
+ ):
17
+ """
18
+ 构造函数,用于初始化选择器。
19
+ """
20
+ super().__init__(dataset, accelerator, data_collator, cache_dir)
21
+ logger.info(f"CustomSelector initialized.")
22
+
23
+ def select(self, model, step_id: int, num_samples: int, **kwargs):
24
+ """
25
+ 核心选择逻辑。
26
+ 此方法定义了如何从数据集中选择样本。
27
+
28
+ Args:
29
+ model: 当前的模型。
30
+ step_id (int): 当前的训练步数。
31
+ num_samples (int): 需要选择的样本数量。
32
+
33
+ Returns:
34
+ list: 包含被选中样本索引的列表。
35
+ """
36
+ # 示例逻辑:简单返回从 0 到 num_samples-1 的索引列表。
37
+ # 您可以在此实现更复杂的选择算法。
38
+ return list(range(num_samples))