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,312 @@
1
+ from dataflex.core.registry import register_mixer
2
+ from dataflex.utils.logging import logger
3
+ from .base_mixer import Mixer
4
+ import numpy as np
5
+ import torch
6
+ import os
7
+ from contextlib import nullcontext
8
+
9
+ @register_mixer("doremi")
10
+ class DoremiMixer(Mixer):
11
+ def __init__(self, mixture_manager, reference_model_path=None, reweight_eta=1.0, reweight_eps=1e-3,
12
+ accelerator=None, output_dir=None, dataset=None, data_collator=None, **kwargs):
13
+ super().__init__(mixture_manager)
14
+ self.reference_model_path = reference_model_path
15
+ self.reweight_eta = float(reweight_eta)
16
+ self.reweight_eps = float(reweight_eps)
17
+ self.accelerator = accelerator
18
+ self.output_dir = output_dir
19
+ self.dataset = dataset
20
+ self.data_collator = data_collator
21
+
22
+ k = len(self.mixture_manager.names)
23
+ self.domain_weights = np.ones(k) / k # Algorithm 1 line 26
24
+ self.perdomain_scores = np.zeros(k)
25
+ self.weight_history = []
26
+ self.step_history = []
27
+
28
+ self.reference_model = None
29
+ self.reference_model_loaded = False
30
+
31
+ # Check for DeepSpeed ZeRO-3 which requires special handling
32
+ self.using_deepspeed_zero3 = False
33
+ if accelerator is not None and hasattr(accelerator, 'state'):
34
+ if hasattr(accelerator.state, 'deepspeed_plugin'):
35
+ ds_plugin = accelerator.state.deepspeed_plugin
36
+ if ds_plugin is not None and hasattr(ds_plugin, 'zero_stage'):
37
+ if ds_plugin.zero_stage == 3:
38
+ self.using_deepspeed_zero3 = True
39
+ logger.warning(
40
+ "[DoremiMixer] DeepSpeed ZeRO-3 detected! "
41
+ "For best results, consider using:\n"
42
+ " 1. ZeRO-2 instead of ZeRO-3 (change deepspeed config)\n"
43
+ " 2. LoRA instead of full finetuning (set finetuning_type: lora)\n"
44
+ "Proceeding with workaround but evaluation may be slow."
45
+ )
46
+
47
+ logger.info(f"[DoremiMixer] Init: k={k}, η={self.reweight_eta}, c={self.reweight_eps}")
48
+
49
+ def _load_reference_model(self, proxy_model):
50
+ if self.reference_model_loaded:
51
+ return
52
+
53
+ if self.reference_model_path is None or not os.path.exists(self.reference_model_path):
54
+ self.reference_model_loaded = True
55
+ return
56
+
57
+ try:
58
+ from transformers import AutoModelForCausalLM
59
+ self.reference_model = AutoModelForCausalLM.from_pretrained(
60
+ self.reference_model_path,
61
+ torch_dtype=proxy_model.dtype if hasattr(proxy_model, 'dtype') else torch.float32,
62
+ trust_remote_code=True
63
+ )
64
+ device = next(proxy_model.parameters()).device
65
+ self.reference_model = self.reference_model.to(device)
66
+ self.reference_model.eval()
67
+ for param in self.reference_model.parameters():
68
+ param.requires_grad = False
69
+
70
+ # Log model info
71
+ num_params = sum(p.numel() for p in self.reference_model.parameters())
72
+ logger.info(f"[DoremiMixer] Reference model loaded successfully with {num_params:,} parameters")
73
+ logger.info(f"[DoremiMixer] Reference model device: {device}, dtype: {self.reference_model.dtype}")
74
+
75
+ self.reference_model_loaded = True
76
+ except Exception as e:
77
+ logger.error(f"[DoremiMixer] Failed to load reference model: {e}")
78
+ self.reference_model = None
79
+ self.reference_model_loaded = True
80
+
81
+ def _prepare_model_for_eval(self, model, log_info=False):
82
+ # For ZeRO-3, we need to gather parameters before evaluation
83
+ if self.using_deepspeed_zero3:
84
+ try:
85
+ import deepspeed
86
+ # Get the unwrapped model
87
+ if hasattr(model, 'module'):
88
+ base_model = model.module
89
+ else:
90
+ base_model = model
91
+
92
+ # Create context manager for gathering all parameters
93
+ # modifier_rank=None means all ranks get full parameters
94
+ params_to_gather = [p for p in base_model.parameters() if hasattr(p, 'ds_id')]
95
+
96
+ if params_to_gather:
97
+ if log_info:
98
+ logger.info(f"[DoremiMixer] Using DeepSpeed parameter gathering for {len(params_to_gather)} parameters")
99
+ context = deepspeed.zero.GatheredParameters(params_to_gather, modifier_rank=None)
100
+ return base_model, context
101
+ else:
102
+ if log_info:
103
+ logger.warning(f"[DoremiMixer] No DeepSpeed parameters found, using model as-is")
104
+ return base_model, nullcontext()
105
+
106
+ except Exception as e:
107
+ logger.error(f"[DoremiMixer] Failed to setup DeepSpeed parameter gathering: {e}")
108
+ # Fallback to using model as-is
109
+ return model, nullcontext()
110
+
111
+ # For non-ZeRO-3, just unwrap the model
112
+ if hasattr(model, 'module'):
113
+ return model.module, nullcontext()
114
+
115
+ return model, nullcontext()
116
+
117
+ def _compute_per_token_loss(self, model, batch):
118
+ # Algorithm 1 line 31: compute ℓ_{θ,j}(x) for each token j
119
+ with torch.no_grad():
120
+ was_training = model.training
121
+ model.eval()
122
+
123
+ input_ids = batch['input_ids']
124
+ labels = batch.get('labels')
125
+ attention_mask = batch.get('attention_mask', torch.ones_like(input_ids))
126
+
127
+ try:
128
+ # Prepare model for evaluation (handles DeepSpeed ZeRO-3)
129
+ eval_model, param_context = self._prepare_model_for_eval(model, log_info=False)
130
+
131
+ # Prepare batch for model
132
+ model_batch = {
133
+ 'input_ids': input_ids,
134
+ 'attention_mask': attention_mask,
135
+ 'labels': labels,
136
+ 'return_dict': True
137
+ }
138
+
139
+ # Forward pass with parameter gathering context
140
+ with param_context:
141
+ outputs = eval_model(**model_batch)
142
+ logits = outputs.logits
143
+
144
+ shift_logits = logits[..., :-1, :].contiguous()
145
+ shift_labels = labels[..., 1:].contiguous()
146
+
147
+ vocab_size = shift_logits.size(-1)
148
+ loss_fct = torch.nn.CrossEntropyLoss(reduction='none', ignore_index=-100)
149
+ per_token_loss = loss_fct(shift_logits.view(-1, vocab_size), shift_labels.view(-1)).view(shift_labels.size())
150
+
151
+ valid_mask = (shift_labels != -100)
152
+
153
+ if was_training:
154
+ model.train()
155
+
156
+ return per_token_loss, valid_mask
157
+ except Exception as e:
158
+ if was_training:
159
+ model.train()
160
+ logger.error(f"[DoremiMixer] Error in _compute_per_token_loss: {e}")
161
+ raise
162
+
163
+ def compute_batch_excess_losses(self, proxy_model, batch, domain_ids):
164
+ # Algorithm 1 line 30-31: λ_t[i] ← (1/Σ|x|) · Σ Σ_j max{ℓ_θ,j - ℓ_ref,j, 0}
165
+ k = len(self.mixture_manager.names)
166
+ perdomain_scores = np.zeros(k)
167
+ domain_has_data = np.zeros(k, dtype=bool)
168
+
169
+ if not self.reference_model_loaded:
170
+ self._load_reference_model(proxy_model)
171
+
172
+ with torch.no_grad():
173
+ device = next(proxy_model.parameters()).device
174
+ batch = {key: val.to(device) if isinstance(val, torch.Tensor) else val for key, val in batch.items()}
175
+ domain_ids = domain_ids.to(device)
176
+
177
+ proxy_token_losses, valid_mask = self._compute_per_token_loss(proxy_model, batch)
178
+
179
+ if self.reference_model is not None:
180
+ ref_token_losses, _ = self._compute_per_token_loss(self.reference_model, batch)
181
+ # CRITICAL: clip at token level THEN average
182
+ excess_token_losses = torch.clamp(proxy_token_losses - ref_token_losses, min=0.0)
183
+ else:
184
+ excess_token_losses = proxy_token_losses
185
+
186
+ for domain_id in range(k):
187
+ domain_mask = (domain_ids == domain_id)
188
+ if domain_mask.sum() > 0:
189
+ domain_mask_expanded = domain_mask.unsqueeze(1).expand_as(excess_token_losses)
190
+ domain_valid_mask = valid_mask & domain_mask_expanded
191
+
192
+ domain_excess_sum = (excess_token_losses * domain_valid_mask.float()).sum().item()
193
+ domain_token_count = domain_valid_mask.sum().item()
194
+
195
+ if domain_token_count > 0:
196
+ domain_has_data[domain_id] = True
197
+ perdomain_scores[domain_id] = domain_excess_sum / domain_token_count
198
+
199
+ return perdomain_scores, domain_has_data
200
+
201
+
202
+ def _update_domain_weights(self, perdomain_scores, domain_has_data):
203
+ # Algorithm 1 lines 32-33
204
+ k = len(self.domain_weights)
205
+ # alpha_prime = self.domain_weights * np.exp(self.reweight_eta * perdomain_scores)
206
+ scores = perdomain_scores.copy()
207
+ valid = domain_has_data
208
+ if valid.any():
209
+ mu = scores[valid].mean()
210
+ scores[valid] = scores[valid] - mu
211
+ scores = np.clip(scores, -5.0, 5.0)
212
+ alpha_prime = self.domain_weights * np.exp(self.reweight_eta * scores)
213
+
214
+ u = 1.0 / k
215
+ new_weights = (1 - self.reweight_eps) * (alpha_prime / alpha_prime.sum()) + self.reweight_eps * u
216
+ return new_weights / new_weights.sum()
217
+
218
+ def mix(self, model, step_id: int, **kwargs) -> np.ndarray:
219
+ # Algorithm 1: Use current training batch to compute λ_t, update α_t, store for averaging
220
+ batch = kwargs.get('batch')
221
+ domain_ids = kwargs.get('domain_ids')
222
+ output_dir = kwargs.get('output_dir', self.output_dir)
223
+
224
+ if batch is None or domain_ids is None:
225
+ raise ValueError(
226
+ "[DoremiMixer] Algorithm 1 requires current training batch. "
227
+ "batch and domain_ids must be provided to mix() method."
228
+ )
229
+
230
+ if not self.reference_model_loaded:
231
+ self._load_reference_model(model)
232
+
233
+ # Algorithm 1 line 30-31: Compute λ_t
234
+ perdomain_scores, domain_has_data = self.compute_batch_excess_losses(model, batch, domain_ids)
235
+ self.perdomain_scores = perdomain_scores
236
+
237
+ # Algorithm 1 lines 32-33: Update α_t
238
+ self.domain_weights = self._update_domain_weights(perdomain_scores, domain_has_data)
239
+
240
+ # Algorithm 1 line 36: Store for averaging
241
+ self.weight_history.append(self.domain_weights.copy())
242
+ self.step_history.append(step_id)
243
+
244
+ logger.info(f"[DoremiMixer] Step {step_id} - α_t: {self.domain_weights}, λ_t: {perdomain_scores}")
245
+
246
+ if output_dir:
247
+ self.save_weights_to_jsonl(output_dir, step_id)
248
+
249
+ # Algorithm 1: Return uniform weights for sampling (u = 1/k)
250
+ # The domain_weights α_t will be used for loss reweighting in training_step
251
+ k = len(self.domain_weights)
252
+ uniform_weights = np.ones(k) / k
253
+ logger.info(f"[DoremiMixer] Returning uniform weights for sampling: {uniform_weights}")
254
+ return uniform_weights
255
+
256
+ def get_current_doremi_weights(self) -> np.ndarray:
257
+ return self.domain_weights.copy()
258
+
259
+ def save_weights_to_jsonl(self, output_dir, step_id):
260
+ if self.accelerator is not None and not self.accelerator.is_main_process:
261
+ return
262
+
263
+ try:
264
+ import json, time
265
+ os.makedirs(output_dir, exist_ok=True)
266
+ weights_file = os.path.join(output_dir, "doremi_weights.jsonl")
267
+
268
+ log_entry = {
269
+ "step": step_id,
270
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
271
+ "domain_names": self.mixture_manager.names,
272
+ "domain_weights": self.domain_weights.tolist(),
273
+ "perdomain_scores": self.perdomain_scores.tolist(),
274
+ }
275
+
276
+ with open(weights_file, 'a') as f:
277
+ f.write(json.dumps(log_entry) + '\n')
278
+ except Exception as e:
279
+ logger.warning(f"[DoremiMixer] Failed to log weights: {e}")
280
+
281
+ def get_average_weights(self):
282
+ # Algorithm 1 line 36: Return ̄α = 1/T·Σα_t
283
+ if len(self.weight_history) == 0:
284
+ return self.domain_weights.copy()
285
+ avg_weights = np.mean(self.weight_history, axis=0)
286
+ return avg_weights / avg_weights.sum()
287
+
288
+ def save_average_weights(self, output_dir):
289
+ try:
290
+ import json
291
+ avg_weights = self.get_average_weights()
292
+ os.makedirs(output_dir, exist_ok=True)
293
+
294
+ weights_data = {
295
+ "description": "DoReMi Step 2: average domain weights for Step 3",
296
+ "update_times": len(self.weight_history),
297
+ "domain_names": self.mixture_manager.names,
298
+ "average_weights": avg_weights.tolist(),
299
+ }
300
+
301
+ with open(os.path.join(output_dir, "doremi_average_weights.json"), 'w') as f:
302
+ json.dump(weights_data, f, indent=2)
303
+
304
+ with open(os.path.join(output_dir, "doremi_step3_proportions.txt"), 'w') as f:
305
+ f.write("# DoReMi Step 3 proportions\n")
306
+ f.write(f"# proportions: {avg_weights.tolist()}\n")
307
+ for name, weight in zip(self.mixture_manager.names, avg_weights):
308
+ f.write(f"{name}: {weight:.6f}\n")
309
+
310
+ logger.info(f"[DoremiMixer] Saved average weights for Step 3")
311
+ except Exception as e:
312
+ logger.error(f"[DoremiMixer] Failed to save average weights: {e}")
@@ -0,0 +1,381 @@
1
+ """
2
+ Optimized Dynamic MoE Mixer — drop-in replacement for DynamicMoEMixer.
3
+
4
+ Key optimizations over the original:
5
+ 1. Pre-built eval batch cache (collate once, reuse every mix())
6
+ 2. Configurable eval_batch_size (default 32, up from hardcoded 4)
7
+ 3. torch.inference_mode() instead of torch.no_grad()
8
+ 4. Reduced CUDA synchronization (empty_cache only at boundaries)
9
+ 5. Algorithm is 100% identical — same math, same results
10
+
11
+ Author: DataFlex Team
12
+ """
13
+
14
+ import json
15
+ import os
16
+ import time
17
+ import torch
18
+ import torch.distributed as dist
19
+ import numpy as np
20
+
21
+ from dataflex.core.registry import register_mixer
22
+ from dataflex.utils.logging import logger
23
+ from .base_mixer import Mixer
24
+
25
+ from transformers.trainer_pt_utils import nested_detach
26
+
27
+
28
+ @register_mixer("dynamic_moe")
29
+ class DynamicMoEMixer(Mixer):
30
+ def __init__(self, mixture_manager, eta: float = 10.0, c: float = 0.05,
31
+ collect_steps: int = 10, eval_samples: int = 1000,
32
+ eval_batch_size: int = 32,
33
+ output_dir: str = None, accelerator=None):
34
+ """
35
+ Optimized Dynamic MoE Mixer implementing Algorithm 1 from the paper.
36
+
37
+ Args:
38
+ mixture_manager: MixedProportionManager instance.
39
+ eta (float): Update step size (learning rate for weights).
40
+ c (float): Smoothing parameter to prevent extreme weights.
41
+ collect_steps (int): Number of batches to sample per domain to estimate gate loads.
42
+ eval_samples (int): Number of samples per domain reserved for gate load evaluation.
43
+ eval_batch_size (int): Batch size for gate load inference (default 32).
44
+ output_dir (str): Directory to save weight logs.
45
+ accelerator: Accelerator for distributed training.
46
+ """
47
+ super().__init__(mixture_manager)
48
+ self.eta = eta
49
+ self.c = c
50
+ self.collect_steps = collect_steps
51
+ self.eval_batch_size = eval_batch_size
52
+ self.output_dir = output_dir
53
+ self.accelerator = accelerator
54
+
55
+ # Initialize weights uniformly (Algorithm 1)
56
+ self.current_weights = np.ones(len(self.mixture_manager.names)) / len(self.mixture_manager.names)
57
+ self._gate_load_seed = 42
58
+
59
+ # Eval batch cache: populated on first mix() call
60
+ # Dict[str, List[Dict[str, Tensor]]] — domain -> list of collated CPU batches
61
+ self._eval_batch_cache = None
62
+
63
+ # ── Use independent eval datasets for gate load evaluation ──────────
64
+ self.eval_datasets = {}
65
+
66
+ pre_loaded = getattr(self.mixture_manager, 'mixer_eval_datasets', None)
67
+ if pre_loaded:
68
+ for name in self.mixture_manager.names:
69
+ if name in pre_loaded:
70
+ self.eval_datasets[name] = pre_loaded[name]
71
+ logger.info(
72
+ f"[DynamicMoEMixer] Domain '{name}': using independent eval dataset "
73
+ f"({len(pre_loaded[name])} samples)"
74
+ )
75
+ else:
76
+ dataset = self.mixture_manager.sources[name]
77
+ n = len(dataset)
78
+ n_eval = min(eval_samples, n // 2)
79
+ if n_eval <= 0:
80
+ logger.warning(f"[DynamicMoEMixer] Domain '{name}' has {n} samples, too few to split eval set.")
81
+ self.eval_datasets[name] = dataset
82
+ continue
83
+ eval_rng = np.random.RandomState(seed=0)
84
+ all_indices = eval_rng.permutation(n)
85
+ eval_indices = sorted(all_indices[:n_eval].tolist())
86
+ train_indices = sorted(all_indices[n_eval:].tolist())
87
+ self.eval_datasets[name] = dataset.select(eval_indices)
88
+ self.mixture_manager.sources[name] = dataset.select(train_indices)
89
+ logger.info(
90
+ f"[DynamicMoEMixer] Domain '{name}': no independent eval, "
91
+ f"split {n_eval} from training (train: {len(train_indices)})"
92
+ )
93
+ logger.info("[DynamicMoEMixer] Using independent eval datasets for gate load evaluation.")
94
+ else:
95
+ eval_rng = np.random.RandomState(seed=0)
96
+ for name in self.mixture_manager.names:
97
+ dataset = self.mixture_manager.sources[name]
98
+ n = len(dataset)
99
+ n_eval = min(eval_samples, n // 2)
100
+
101
+ if n_eval <= 0:
102
+ logger.warning(f"[DynamicMoEMixer] Domain '{name}' has {n} samples, too few to split eval set.")
103
+ self.eval_datasets[name] = dataset
104
+ continue
105
+
106
+ all_indices = eval_rng.permutation(n)
107
+ eval_indices = sorted(all_indices[:n_eval].tolist())
108
+ train_indices = sorted(all_indices[n_eval:].tolist())
109
+
110
+ self.eval_datasets[name] = dataset.select(eval_indices)
111
+ self.mixture_manager.sources[name] = dataset.select(train_indices)
112
+
113
+ logger.info(
114
+ f"[DynamicMoEMixer] Domain '{name}': split {n_eval} eval samples "
115
+ f"(train: {len(train_indices)}, eval: {n_eval})"
116
+ )
117
+ logger.info("[DynamicMoEMixer] No independent eval datasets found, split from training data.")
118
+
119
+ # ── Optimization 1: pre-build & cache eval batches ──────────────────────
120
+
121
+ def _build_eval_batch_cache(self, data_collator):
122
+ """
123
+ Pre-collate all eval batches once and cache as CPU tensors.
124
+
125
+ Uses the same fixed-seed sampling logic as the original so that
126
+ the first mix() produces identical batches. Subsequent mix() calls
127
+ reuse the cache (the paper uses the same eval data every time).
128
+ """
129
+ logger.info("[DynamicMoEMixer] Building eval batch cache (one-time cost) ...")
130
+ cache = {}
131
+ rng = np.random.RandomState(42) # same starting seed as original
132
+
133
+ batch_size = self.eval_batch_size
134
+ domain_names = self.mixture_manager.names
135
+
136
+ for name in domain_names:
137
+ dataset = self.eval_datasets[name]
138
+ if len(dataset) == 0:
139
+ cache[name] = []
140
+ continue
141
+
142
+ num_samples = min(len(dataset), self.collect_steps * batch_size)
143
+ if num_samples == 0:
144
+ cache[name] = []
145
+ continue
146
+
147
+ indices = rng.choice(len(dataset), num_samples, replace=False)
148
+
149
+ batches = []
150
+ for step in range(0, num_samples, batch_size):
151
+ batch_indices = indices[step: step + batch_size]
152
+ samples = [dataset[int(idx)] for idx in batch_indices]
153
+ batch = data_collator(samples)
154
+ # Keep only tensor values, store on CPU
155
+ cpu_batch = {k: v.cpu() for k, v in batch.items() if isinstance(v, torch.Tensor)}
156
+ batches.append(cpu_batch)
157
+
158
+ cache[name] = batches
159
+ logger.info(
160
+ f"[DynamicMoEMixer] Cached {len(batches)} batches "
161
+ f"({num_samples} samples, bs={batch_size}) for domain '{name}'"
162
+ )
163
+
164
+ self._eval_batch_cache = cache
165
+ logger.info("[DynamicMoEMixer] Eval batch cache ready.")
166
+
167
+ # ── Optimization 2-4: efficient gate load collection ────────────────────
168
+
169
+ def _collect_gate_loads(self, model, data_collator):
170
+ """
171
+ Collects aggregated gate loads per domain using cached batches,
172
+ larger batch size, inference_mode, and minimal CUDA sync.
173
+
174
+ Returns:
175
+ np.ndarray: [num_domains, num_experts] normalized gate loads.
176
+ """
177
+ # Build cache on first call (data_collator is now available)
178
+ if self._eval_batch_cache is None:
179
+ self._build_eval_batch_cache(data_collator)
180
+
181
+ # Single cache clear at start (Optimization 4)
182
+ torch.cuda.empty_cache()
183
+
184
+ # Unwrap model for DeepSpeed compatibility
185
+ if hasattr(model, "module"):
186
+ real_model = model.module
187
+ else:
188
+ real_model = model
189
+
190
+ real_model.eval()
191
+ device = next(real_model.parameters()).device
192
+
193
+ domain_names = self.mixture_manager.names
194
+ raw_loads_list = []
195
+ num_experts = getattr(real_model.config, "num_experts", None)
196
+
197
+ # Use no_grad (not inference_mode) to avoid creating inference tensors
198
+ # that corrupt model state under DeepSpeed ZeRO-3
199
+ with torch.no_grad():
200
+ for name in domain_names:
201
+ cached_batches = self._eval_batch_cache[name]
202
+
203
+ if len(cached_batches) == 0:
204
+ if num_experts is None:
205
+ num_experts = 8
206
+ raw_loads_list.append(np.ones(num_experts) / num_experts)
207
+ continue
208
+
209
+ domain_load_sum = None
210
+
211
+ for batch_cpu in cached_batches:
212
+ # Move cached CPU batch to device
213
+ batch = {k: v.to(device, non_blocking=True) for k, v in batch_cpu.items()}
214
+
215
+ outputs = real_model(**batch)
216
+
217
+ # Extract gate_load
218
+ gate_load = None
219
+ if hasattr(outputs, "gate_load") and outputs.gate_load is not None:
220
+ gate_load = outputs.gate_load
221
+ gate_load = gate_load[-1]
222
+ if gate_load is not None:
223
+ gate_load = nested_detach(gate_load)
224
+
225
+ if gate_load.dim() > 1:
226
+ gate_load = gate_load.sum(dim=0)
227
+
228
+ gate_load_cpu = gate_load.float().cpu()
229
+
230
+ if domain_load_sum is None:
231
+ domain_load_sum = torch.zeros_like(gate_load_cpu)
232
+ if num_experts is None:
233
+ num_experts = gate_load_cpu.shape[0]
234
+
235
+ domain_load_sum += gate_load_cpu
236
+ else:
237
+ if domain_load_sum is None:
238
+ logger.warning(f"[DynamicMoEMixer] Model output does not contain 'gate_load'. Using uniform load.")
239
+ if num_experts is None:
240
+ num_experts = 8
241
+ if domain_load_sum is None:
242
+ domain_load_sum = torch.ones(num_experts, dtype=torch.float32)
243
+ else:
244
+ domain_load_sum += torch.ones(num_experts, dtype=torch.float32)
245
+
246
+ # Delete intermediate tensors to free GPU memory
247
+ del outputs
248
+ del batch
249
+ del gate_load
250
+
251
+ # No per-domain empty_cache (Optimization 4)
252
+
253
+ # L1 normalization (identical to original)
254
+ if domain_load_sum is not None and domain_load_sum.sum() > 0:
255
+ load_np = domain_load_sum.numpy()
256
+ l1_sum = load_np.sum()
257
+ if l1_sum > 0:
258
+ normalized_load = load_np / l1_sum
259
+ else:
260
+ normalized_load = load_np
261
+ else:
262
+ if num_experts is None:
263
+ num_experts = 8
264
+ normalized_load = np.ones(num_experts) / num_experts
265
+
266
+ raw_loads_list.append(normalized_load)
267
+
268
+ real_model.train()
269
+
270
+ # Single cache clear at end (Optimization 4)
271
+ torch.cuda.empty_cache()
272
+
273
+ result = np.stack(raw_loads_list)
274
+
275
+ # Broadcast from rank 0 for consistency
276
+ if dist.is_initialized():
277
+ result_tensor = torch.from_numpy(result).float().to(device)
278
+ dist.broadcast(result_tensor, src=0)
279
+ result = result_tensor.cpu().numpy()
280
+
281
+ return result
282
+
283
+ # ── mix(): Algorithm 1 — 100% identical math ───────────────────────────
284
+
285
+ def mix(self, model, step_id: int, **kwargs) -> np.ndarray:
286
+ """
287
+ Implements Algorithm 1: DynamicSampling.
288
+ Math is identical to original; only I/O and inference are optimized.
289
+ """
290
+ data_collator = kwargs.get('data_collator')
291
+ if data_collator is None:
292
+ logger.warning("[DynamicMoEMixer] data_collator not found in kwargs, cannot collect gate loads. Returning current weights.")
293
+ return self.current_weights
294
+
295
+ domain_names = self.mixture_manager.names
296
+
297
+ # 2. Collect Normalized Gate Loads (O_hat)
298
+ O_hat = self._collect_gate_loads(model, data_collator)
299
+
300
+ # ── Detailed diagnostic logging ──────────────────────────────────────
301
+ np.set_printoptions(precision=6, suppress=True)
302
+ logger.info(f"[DynamicMoEMixer] ═══ Step {step_id} Diagnostic ═══")
303
+ logger.info(f"[DynamicMoEMixer] Domain order: {domain_names}")
304
+ for i, name in enumerate(domain_names):
305
+ logger.info(f"[DynamicMoEMixer] O_hat[{name}] (L1-normalized gate load): {O_hat[i]}")
306
+
307
+ # 3. L2 distance across datasets (identical to original)
308
+ l2_dist_matrix = np.linalg.norm(O_hat[:, np.newaxis] - O_hat, axis=2) # [|D|, |D|]
309
+
310
+ logger.info(f"[DynamicMoEMixer] L2 Distance Matrix:")
311
+ for i, name_i in enumerate(domain_names):
312
+ row_str = " ".join(f"{name_j}={l2_dist_matrix[i,j]:.6f}" for j, name_j in enumerate(domain_names))
313
+ logger.info(f"[DynamicMoEMixer] {name_i}: {row_str}")
314
+
315
+ # 4. Delta_i = mean_j(||load_i - load_j||_2) — includes self-distance=0
316
+ Delta = l2_dist_matrix.mean(axis=1) # [|D|]
317
+
318
+ delta_detail = ", ".join(f"{name}={Delta[i]:.6f}" for i, name in enumerate(domain_names))
319
+ logger.info(f"[DynamicMoEMixer] Delta (mean L2 dist): {delta_detail}")
320
+
321
+ # 5. Updated sampling weights (Algorithm 1 lines 6-9)
322
+ log_w_prev = np.log(self.current_weights + 1e-10)
323
+ logits = log_w_prev + self.eta * Delta
324
+
325
+ # Softmax
326
+ exp_logits = np.exp(logits - np.max(logits))
327
+ alpha = exp_logits / exp_logits.sum()
328
+
329
+ # Smoothing: w'_t <- (1 - c) * alpha + c / |D|
330
+ num_datasets = len(self.current_weights)
331
+ w_prime = (1 - self.c) * alpha + self.c / num_datasets
332
+
333
+ # Normalize: w_t <- w'_t / sum(w'_t)
334
+ new_weights = w_prime / w_prime.sum()
335
+
336
+ old_w_str = ", ".join(f"{name}={self.current_weights[i]:.6f}" for i, name in enumerate(domain_names))
337
+ new_w_str = ", ".join(f"{name}={new_weights[i]:.6f}" for i, name in enumerate(domain_names))
338
+ logger.info(f"[DynamicMoEMixer] Old weights: {old_w_str}")
339
+ logger.info(f"[DynamicMoEMixer] New weights: {new_w_str}")
340
+ logger.info(f"[DynamicMoEMixer] ═══ End Step {step_id} ═══")
341
+
342
+ self.current_weights = new_weights
343
+
344
+ self.save_weights_to_jsonl(step_id, O_hat, Delta, alpha, new_weights)
345
+
346
+ return new_weights
347
+
348
+ def save_weights_to_jsonl(self, step_id: int, O_hat: np.ndarray,
349
+ Delta: np.ndarray, alpha: np.ndarray,
350
+ new_weights: np.ndarray):
351
+ """Save weight update logs (only main process)."""
352
+ if self.accelerator is not None and not self.accelerator.is_main_process:
353
+ return
354
+
355
+ if self.output_dir is None:
356
+ return
357
+
358
+ try:
359
+ os.makedirs(self.output_dir, exist_ok=True)
360
+ weights_file = os.path.join(self.output_dir, "dynamic_moe_weights.jsonl")
361
+
362
+ domain_names = self.mixture_manager.names
363
+ log_entry = {
364
+ "step": step_id,
365
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
366
+ "domain_names": domain_names,
367
+ "gate_loads": {name: O_hat[i].tolist() for i, name in enumerate(domain_names)},
368
+ "delta": {name: float(Delta[i]) for i, name in enumerate(domain_names)},
369
+ "alpha": {name: float(alpha[i]) for i, name in enumerate(domain_names)},
370
+ "new_weights": {name: float(new_weights[i]) for i, name in enumerate(domain_names)},
371
+ "eta": self.eta,
372
+ "c": self.c,
373
+ }
374
+
375
+ with open(weights_file, "a") as f:
376
+ f.write(json.dumps(log_entry) + "\n")
377
+
378
+ logger.info(f"[DynamicMoEMixer] Saved weights to {weights_file} at step {step_id}")
379
+
380
+ except Exception as e:
381
+ logger.warning(f"[DynamicMoEMixer] Failed to save weights: {e}")