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,649 @@
1
+ # Copyright 2025 the LlamaFactory team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib
16
+ from dataclasses import asdict, dataclass, field
17
+ from typing import Any, Literal, Optional
18
+
19
+
20
+ @dataclass
21
+ class FreezeArguments:
22
+ r"""Arguments pertaining to the freeze (partial-parameter) training."""
23
+
24
+ freeze_trainable_layers: int = field(
25
+ default=2,
26
+ metadata={
27
+ "help": (
28
+ "The number of trainable layers for freeze (partial-parameter) fine-tuning. "
29
+ "Positive numbers mean the last n layers are set as trainable, "
30
+ "negative numbers mean the first n layers are set as trainable."
31
+ )
32
+ },
33
+ )
34
+ freeze_trainable_modules: str = field(
35
+ default="all",
36
+ metadata={
37
+ "help": (
38
+ "Name(s) of trainable modules for freeze (partial-parameter) fine-tuning. "
39
+ "Use commas to separate multiple modules. "
40
+ "Use `all` to specify all the available modules."
41
+ )
42
+ },
43
+ )
44
+ freeze_extra_modules: Optional[str] = field(
45
+ default=None,
46
+ metadata={
47
+ "help": (
48
+ "Name(s) of modules apart from hidden layers to be set as trainable "
49
+ "for freeze (partial-parameter) fine-tuning. "
50
+ "Use commas to separate multiple modules."
51
+ )
52
+ },
53
+ )
54
+
55
+
56
+ @dataclass
57
+ class LoraArguments:
58
+ r"""Arguments pertaining to the LoRA training."""
59
+
60
+ additional_target: Optional[str] = field(
61
+ default=None,
62
+ metadata={
63
+ "help": (
64
+ "Name(s) of modules apart from LoRA layers to be set as trainable "
65
+ "and saved in the final checkpoint. "
66
+ "Use commas to separate multiple modules."
67
+ )
68
+ },
69
+ )
70
+ lora_alpha: Optional[int] = field(
71
+ default=None,
72
+ metadata={"help": "The scale factor for LoRA fine-tuning (default: lora_rank * 2)."},
73
+ )
74
+ lora_dropout: float = field(
75
+ default=0.0,
76
+ metadata={"help": "Dropout rate for the LoRA fine-tuning."},
77
+ )
78
+ lora_rank: int = field(
79
+ default=8,
80
+ metadata={"help": "The intrinsic dimension for LoRA fine-tuning."},
81
+ )
82
+ lora_target: str = field(
83
+ default="all",
84
+ metadata={
85
+ "help": (
86
+ "Name(s) of target modules to apply LoRA. "
87
+ "Use commas to separate multiple modules. "
88
+ "Use `all` to specify all the linear modules."
89
+ )
90
+ },
91
+ )
92
+ loraplus_lr_ratio: Optional[float] = field(
93
+ default=None,
94
+ metadata={"help": "LoRA plus learning rate ratio (lr_B / lr_A)."},
95
+ )
96
+ loraplus_lr_embedding: float = field(
97
+ default=1e-6,
98
+ metadata={"help": "LoRA plus learning rate for lora embedding layers."},
99
+ )
100
+ use_rslora: bool = field(
101
+ default=False,
102
+ metadata={"help": "Whether or not to use the rank stabilization scaling factor for LoRA layer."},
103
+ )
104
+ use_dora: bool = field(
105
+ default=False,
106
+ metadata={"help": "Whether or not to use the weight-decomposed lora method (DoRA)."},
107
+ )
108
+ pissa_init: bool = field(
109
+ default=False,
110
+ metadata={"help": "Whether or not to initialize a PiSSA adapter."},
111
+ )
112
+ pissa_iter: int = field(
113
+ default=16,
114
+ metadata={"help": "The number of iteration steps performed by FSVD in PiSSA. Use -1 to disable it."},
115
+ )
116
+ pissa_convert: bool = field(
117
+ default=False,
118
+ metadata={"help": "Whether or not to convert the PiSSA adapter to a normal LoRA adapter."},
119
+ )
120
+ create_new_adapter: bool = field(
121
+ default=False,
122
+ metadata={"help": "Whether or not to create a new adapter with randomly initialized weight."},
123
+ )
124
+
125
+
126
+ @dataclass
127
+ class OFTArguments:
128
+ r"""Arguments pertaining to the OFT training."""
129
+
130
+ additional_target: Optional[str] = field(
131
+ default=None,
132
+ metadata={
133
+ "help": (
134
+ "Name(s) of modules apart from LoRA layers to be set as trainable "
135
+ "and saved in the final checkpoint. "
136
+ "Use commas to separate multiple modules."
137
+ )
138
+ },
139
+ )
140
+ module_dropout: float = field(
141
+ default=0.0,
142
+ metadata={"help": "Dropout rate for the OFT fine-tuning."},
143
+ )
144
+ oft_rank: int = field(
145
+ default=0,
146
+ metadata={"help": "The intrinsic dimension for OFT fine-tuning."},
147
+ )
148
+ oft_block_size: int = field(
149
+ default=32,
150
+ metadata={"help": "The intrinsic dimension for OFT fine-tuning."},
151
+ )
152
+ oft_target: str = field(
153
+ default="all",
154
+ metadata={
155
+ "help": (
156
+ "Name(s) of target modules to apply OFT. "
157
+ "Use commas to separate multiple modules. "
158
+ "Use `all` to specify all the linear modules."
159
+ )
160
+ },
161
+ )
162
+ create_new_adapter: bool = field(
163
+ default=False,
164
+ metadata={"help": "Whether or not to create a new adapter with randomly initialized weight."},
165
+ )
166
+
167
+
168
+ @dataclass
169
+ class RLHFArguments:
170
+ r"""Arguments pertaining to the PPO, DPO and KTO training."""
171
+
172
+ pref_beta: float = field(
173
+ default=0.1,
174
+ metadata={"help": "The beta parameter in the preference loss."},
175
+ )
176
+ pref_ftx: float = field(
177
+ default=0.0,
178
+ metadata={"help": "The supervised fine-tuning loss coefficient in DPO training."},
179
+ )
180
+ pref_bco_weight: float = field(
181
+ default=0.0,
182
+ metadata={"help": "The Binary Classifier Optimization coefficient in DPO training."},
183
+ )
184
+ pref_loss: Literal["sigmoid", "hinge", "ipo", "kto_pair", "orpo", "simpo"] = field(
185
+ default="sigmoid",
186
+ metadata={"help": "The type of DPO loss to use."},
187
+ )
188
+ dpo_label_smoothing: float = field(
189
+ default=0.0,
190
+ metadata={"help": "The robust DPO label smoothing parameter in cDPO that should be between 0 and 0.5."},
191
+ )
192
+ kto_chosen_weight: float = field(
193
+ default=1.0,
194
+ metadata={"help": "The weight factor of the desirable losses in KTO training."},
195
+ )
196
+ kto_rejected_weight: float = field(
197
+ default=1.0,
198
+ metadata={"help": "The weight factor of the undesirable losses in KTO training."},
199
+ )
200
+ simpo_gamma: float = field(
201
+ default=0.5,
202
+ metadata={"help": "The target reward margin term in SimPO loss."},
203
+ )
204
+ ppo_buffer_size: int = field(
205
+ default=1,
206
+ metadata={"help": "The number of mini-batches to make experience buffer in a PPO optimization step."},
207
+ )
208
+ ppo_epochs: int = field(
209
+ default=4,
210
+ metadata={"help": "The number of epochs to perform in a PPO optimization step."},
211
+ )
212
+ ppo_score_norm: bool = field(
213
+ default=False,
214
+ metadata={"help": "Use score normalization in PPO training."},
215
+ )
216
+ ppo_target: float = field(
217
+ default=6.0,
218
+ metadata={"help": "Target KL value for adaptive KL control in PPO training."},
219
+ )
220
+ ppo_whiten_rewards: bool = field(
221
+ default=False,
222
+ metadata={"help": "Whiten the rewards before compute advantages in PPO training."},
223
+ )
224
+ ref_model: Optional[str] = field(
225
+ default=None,
226
+ metadata={"help": "Path to the reference model used for the PPO or DPO training."},
227
+ )
228
+ ref_model_adapters: Optional[str] = field(
229
+ default=None,
230
+ metadata={"help": "Path to the adapters of the reference model."},
231
+ )
232
+ ref_model_quantization_bit: Optional[int] = field(
233
+ default=None,
234
+ metadata={"help": "The number of bits to quantize the reference model."},
235
+ )
236
+ reward_model: Optional[str] = field(
237
+ default=None,
238
+ metadata={"help": "Path to the reward model used for the PPO training."},
239
+ )
240
+ reward_model_adapters: Optional[str] = field(
241
+ default=None,
242
+ metadata={"help": "Path to the adapters of the reward model."},
243
+ )
244
+ reward_model_quantization_bit: Optional[int] = field(
245
+ default=None,
246
+ metadata={"help": "The number of bits to quantize the reward model."},
247
+ )
248
+ reward_model_type: Literal["lora", "full", "api"] = field(
249
+ default="lora",
250
+ metadata={"help": "The type of the reward model in PPO training. Lora model only supports lora training."},
251
+ )
252
+ ld_alpha: Optional[float] = field(
253
+ default=None,
254
+ metadata={
255
+ "help": (
256
+ "Alpha parameter from the LD-DPO paper, which controls the weighting of"
257
+ " the verbose token log-probabilities in responses."
258
+ )
259
+ },
260
+ )
261
+
262
+
263
+ @dataclass
264
+ class GaloreArguments:
265
+ r"""Arguments pertaining to the GaLore algorithm."""
266
+
267
+ use_galore: bool = field(
268
+ default=False,
269
+ metadata={"help": "Whether or not to use the gradient low-Rank projection (GaLore)."},
270
+ )
271
+ galore_target: str = field(
272
+ default="all",
273
+ metadata={
274
+ "help": (
275
+ "Name(s) of modules to apply GaLore. Use commas to separate multiple modules. "
276
+ "Use `all` to specify all the linear modules."
277
+ )
278
+ },
279
+ )
280
+ galore_rank: int = field(
281
+ default=16,
282
+ metadata={"help": "The rank of GaLore gradients."},
283
+ )
284
+ galore_update_interval: int = field(
285
+ default=200,
286
+ metadata={"help": "Number of steps to update the GaLore projection."},
287
+ )
288
+ galore_scale: float = field(
289
+ default=2.0,
290
+ metadata={"help": "GaLore scaling coefficient."},
291
+ )
292
+ galore_proj_type: Literal["std", "reverse_std", "right", "left", "full"] = field(
293
+ default="std",
294
+ metadata={"help": "Type of GaLore projection."},
295
+ )
296
+ galore_layerwise: bool = field(
297
+ default=False,
298
+ metadata={"help": "Whether or not to enable layer-wise update to further save memory."},
299
+ )
300
+
301
+
302
+ @dataclass
303
+ class ApolloArguments:
304
+ r"""Arguments pertaining to the APOLLO algorithm."""
305
+
306
+ use_apollo: bool = field(
307
+ default=False,
308
+ metadata={"help": "Whether or not to use the APOLLO optimizer."},
309
+ )
310
+ apollo_target: str = field(
311
+ default="all",
312
+ metadata={
313
+ "help": (
314
+ "Name(s) of modules to apply APOLLO. Use commas to separate multiple modules. "
315
+ "Use `all` to specify all the linear modules."
316
+ )
317
+ },
318
+ )
319
+ apollo_rank: int = field(
320
+ default=16,
321
+ metadata={"help": "The rank of APOLLO gradients."},
322
+ )
323
+ apollo_update_interval: int = field(
324
+ default=200,
325
+ metadata={"help": "Number of steps to update the APOLLO projection."},
326
+ )
327
+ apollo_scale: float = field(
328
+ default=32.0,
329
+ metadata={"help": "APOLLO scaling coefficient."},
330
+ )
331
+ apollo_proj: Literal["svd", "random"] = field(
332
+ default="random",
333
+ metadata={"help": "Type of APOLLO low-rank projection algorithm (svd or random)."},
334
+ )
335
+ apollo_proj_type: Literal["std", "right", "left"] = field(
336
+ default="std",
337
+ metadata={"help": "Type of APOLLO projection."},
338
+ )
339
+ apollo_scale_type: Literal["channel", "tensor"] = field(
340
+ default="channel",
341
+ metadata={"help": "Type of APOLLO scaling (channel or tensor)."},
342
+ )
343
+ apollo_layerwise: bool = field(
344
+ default=False,
345
+ metadata={"help": "Whether or not to enable layer-wise update to further save memory."},
346
+ )
347
+ apollo_scale_front: bool = field(
348
+ default=False,
349
+ metadata={"help": "Whether or not to use the norm-growth limiter in front of gradient scaling."},
350
+ )
351
+
352
+
353
+ @dataclass
354
+ class BAdamArgument:
355
+ r"""Arguments pertaining to the BAdam optimizer."""
356
+
357
+ use_badam: bool = field(
358
+ default=False,
359
+ metadata={"help": "Whether or not to use the BAdam optimizer."},
360
+ )
361
+ badam_mode: Literal["layer", "ratio"] = field(
362
+ default="layer",
363
+ metadata={"help": "Whether to use layer-wise or ratio-wise BAdam optimizer."},
364
+ )
365
+ badam_start_block: Optional[int] = field(
366
+ default=None,
367
+ metadata={"help": "The starting block index for layer-wise BAdam."},
368
+ )
369
+ badam_switch_mode: Optional[Literal["ascending", "descending", "random", "fixed"]] = field(
370
+ default="ascending",
371
+ metadata={"help": "the strategy of picking block to update for layer-wise BAdam."},
372
+ )
373
+ badam_switch_interval: Optional[int] = field(
374
+ default=50,
375
+ metadata={
376
+ "help": "Number of steps to update the block for layer-wise BAdam. Use -1 to disable the block update."
377
+ },
378
+ )
379
+ badam_update_ratio: float = field(
380
+ default=0.05,
381
+ metadata={"help": "The ratio of the update for ratio-wise BAdam."},
382
+ )
383
+ badam_mask_mode: Literal["adjacent", "scatter"] = field(
384
+ default="adjacent",
385
+ metadata={
386
+ "help": (
387
+ "The mode of the mask for BAdam optimizer. "
388
+ "`adjacent` means that the trainable parameters are adjacent to each other, "
389
+ "`scatter` means that trainable parameters are randomly choosed from the weight."
390
+ )
391
+ },
392
+ )
393
+ badam_verbose: int = field(
394
+ default=0,
395
+ metadata={
396
+ "help": (
397
+ "The verbosity level of BAdam optimizer. "
398
+ "0 for no print, 1 for print the block prefix, 2 for print trainable parameters."
399
+ )
400
+ },
401
+ )
402
+
403
+
404
+ @dataclass
405
+ class SwanLabArguments:
406
+ use_swanlab: bool = field(
407
+ default=False,
408
+ metadata={"help": "Whether or not to use the SwanLab (an experiment tracking and visualization tool)."},
409
+ )
410
+ swanlab_project: Optional[str] = field(
411
+ default="llamafactory",
412
+ metadata={"help": "The project name in SwanLab."},
413
+ )
414
+ swanlab_workspace: Optional[str] = field(
415
+ default=None,
416
+ metadata={"help": "The workspace name in SwanLab."},
417
+ )
418
+ swanlab_run_name: Optional[str] = field(
419
+ default=None,
420
+ metadata={"help": "The experiment name in SwanLab."},
421
+ )
422
+ swanlab_mode: Literal["cloud", "local"] = field(
423
+ default="cloud",
424
+ metadata={"help": "The mode of SwanLab."},
425
+ )
426
+ swanlab_api_key: Optional[str] = field(
427
+ default=None,
428
+ metadata={"help": "The API key for SwanLab."},
429
+ )
430
+ swanlab_logdir: Optional[str] = field(
431
+ default=None,
432
+ metadata={"help": "The log directory for SwanLab."},
433
+ )
434
+ swanlab_lark_webhook_url: Optional[str] = field(
435
+ default=None,
436
+ metadata={"help": "The Lark(飞书) webhook URL for SwanLab."},
437
+ )
438
+ swanlab_lark_secret: Optional[str] = field(
439
+ default=None,
440
+ metadata={"help": "The Lark(飞书) secret for SwanLab."},
441
+ )
442
+
443
+
444
+ @dataclass
445
+ class DynamicFinetuningArguments(
446
+ SwanLabArguments,
447
+ BAdamArgument,
448
+ ApolloArguments,
449
+ GaloreArguments,
450
+ RLHFArguments,
451
+ LoraArguments,
452
+ OFTArguments,
453
+ FreezeArguments,
454
+ ):
455
+ r"""Arguments pertaining to which techniques we are going to fine-tuning with."""
456
+
457
+ pure_bf16: bool = field(
458
+ default=False,
459
+ metadata={"help": "Whether or not to train model in purely bf16 precision (without AMP)."},
460
+ )
461
+ stage: Literal["pt", "sft", "rm", "ppo", "dpo", "kto"] = field(
462
+ default="sft",
463
+ metadata={"help": "Which stage will be performed in training."},
464
+ )
465
+ finetuning_type: Literal["lora", "freeze", "full"] = field(
466
+ default="lora",
467
+ metadata={"help": "Which fine-tuning method to use."},
468
+ )
469
+ use_llama_pro: bool = field(
470
+ default=False,
471
+ metadata={"help": "Whether or not to make only the parameters in the expanded blocks trainable."},
472
+ )
473
+ use_adam_mini: bool = field(
474
+ default=False,
475
+ metadata={"help": "Whether or not to use the Adam-mini optimizer."},
476
+ )
477
+ use_muon: bool = field(
478
+ default=False,
479
+ metadata={"help": "Whether or not to use the Muon optimizer."},
480
+ )
481
+ use_dft_loss: bool = field(
482
+ default=False,
483
+ metadata={"help": "Whether to use the DFT loss."},
484
+ )
485
+ freeze_vision_tower: bool = field(
486
+ default=True,
487
+ metadata={"help": "Whether ot not to freeze the vision tower in MLLM training."},
488
+ )
489
+ freeze_multi_modal_projector: bool = field(
490
+ default=True,
491
+ metadata={"help": "Whether or not to freeze the multi modal projector in MLLM training."},
492
+ )
493
+ freeze_language_model: bool = field(
494
+ default=False,
495
+ metadata={"help": "Whether or not to freeze the language model in MLLM training."},
496
+ )
497
+ compute_accuracy: bool = field(
498
+ default=False,
499
+ metadata={"help": "Whether or not to compute the token-level accuracy at evaluation."},
500
+ )
501
+ disable_shuffling: bool = field(
502
+ default=False,
503
+ metadata={"help": "Whether or not to disable the shuffling of the training set."},
504
+ )
505
+ early_stopping_steps: Optional[int] = field(
506
+ default=None,
507
+ metadata={"help": "Number of steps to stop training if the `metric_for_best_model` does not improve."},
508
+ )
509
+ early_stopping_min_delta: float = field(
510
+ default=0.0,
511
+ metadata={"help": "Minimum improvement (abs) on the monitored metric to reset early stopping patience."},
512
+ )
513
+ plot_loss: bool = field(
514
+ default=False,
515
+ metadata={"help": "Whether or not to save the training loss curves."},
516
+ )
517
+ include_effective_tokens_per_second: bool = field(
518
+ default=False,
519
+ metadata={"help": "Whether or not to compute effective tokens per second."},
520
+ )
521
+ # hyperparameter for dynamic training
522
+ train_type: str = field(
523
+ default="static",
524
+ metadata={
525
+ "help": (
526
+ "Specifies the type of training to use when `enable_dynamic_train` is True. "
527
+ "Choices: ['static', 'dynamic_select', 'dynamic_mix', 'dynamic_weighting']. "
528
+ "If static, uses default LlamaFactory trainer."
529
+ )
530
+ }
531
+ )
532
+ components_cfg_file: str = field(
533
+ default="configs/components.yaml",
534
+ metadata={"help": "Path to the components configuration file."},
535
+ )
536
+ component_name: str = field(
537
+ default="Loss",
538
+ metadata={"help": "The component name defined in the components configuration file."},
539
+ )
540
+ warmup_step: int = field(
541
+ default=0,
542
+ metadata={"help": "Warm up steps for dynamic training"},
543
+ )
544
+ update_step: int = field(
545
+ default=0,
546
+ metadata={"help": "Update steps for dynamic select or mix training"},
547
+ )
548
+ update_times: int = field(
549
+ default=1,
550
+ metadata={"help": "Total update times during the whole dynamic training progress for dynamic select or mix training"},
551
+ )
552
+ static_mix: bool = field(
553
+ default=False,
554
+ metadata={"help": "Whether or not to fix the static mix ratio in dynamic mix training."},
555
+ )
556
+ train_step: int = field(
557
+ default=0,
558
+ metadata={"help": "Only used in dynamic weight trainer and mix trainer (static_mix=True). Total training steps (including warmup)."},
559
+ )
560
+ freeze_gate: bool = field(
561
+ default=False,
562
+ metadata={"help": "Whether to freeze gate parameters in MoE models during SFT training."},
563
+ )
564
+
565
+ def __post_init__(self):
566
+ def split_arg(arg):
567
+ if isinstance(arg, str):
568
+ return [item.strip() for item in arg.split(",")]
569
+ return arg
570
+
571
+ self.freeze_trainable_modules: list[str] = split_arg(self.freeze_trainable_modules)
572
+ self.freeze_extra_modules: Optional[list[str]] = split_arg(self.freeze_extra_modules)
573
+ self.lora_alpha: int = self.lora_alpha or self.lora_rank * 2
574
+ self.lora_target: list[str] = split_arg(self.lora_target)
575
+ self.oft_target: list[str] = split_arg(self.oft_target)
576
+ self.additional_target: Optional[list[str]] = split_arg(self.additional_target)
577
+ self.galore_target: list[str] = split_arg(self.galore_target)
578
+ self.apollo_target: list[str] = split_arg(self.apollo_target)
579
+ self.use_ref_model = self.stage == "dpo" and self.pref_loss not in ["orpo", "simpo"]
580
+
581
+ assert self.finetuning_type in ["lora", "oft", "freeze", "full"], "Invalid fine-tuning method."
582
+ assert self.ref_model_quantization_bit in [None, 8, 4], "We only accept 4-bit or 8-bit quantization."
583
+ assert self.reward_model_quantization_bit in [None, 8, 4], "We only accept 4-bit or 8-bit quantization."
584
+
585
+ if self.stage == "ppo" and self.reward_model is None:
586
+ raise ValueError("`reward_model` is necessary for PPO training.")
587
+
588
+ if self.stage == "ppo" and self.reward_model_type == "lora" and self.finetuning_type != "lora":
589
+ raise ValueError("`reward_model_type` cannot be lora for Freeze/Full PPO training.")
590
+
591
+ if self.stage == "ppo" and self.reward_model_type == "oft" and self.finetuning_type != "oft":
592
+ raise ValueError("`reward_model_type` cannot be oft for Freeze/Full PPO training.")
593
+
594
+ if self.stage == "dpo" and self.pref_loss != "sigmoid" and self.dpo_label_smoothing > 1e-6:
595
+ raise ValueError("`dpo_label_smoothing` is only valid for sigmoid loss function.")
596
+
597
+ if self.use_llama_pro and self.finetuning_type == "full":
598
+ raise ValueError("`use_llama_pro` is only valid for Freeze or LoRA training.")
599
+
600
+ if self.finetuning_type == "lora" and (self.use_galore or self.use_apollo or self.use_badam):
601
+ raise ValueError("Cannot use LoRA with GaLore, APOLLO or BAdam together.")
602
+
603
+ if int(self.use_galore) + int(self.use_apollo) + (self.use_badam) > 1:
604
+ raise ValueError("Cannot use GaLore, APOLLO or BAdam together.")
605
+
606
+ if self.pissa_init and (self.stage in ["ppo", "kto"] or self.use_ref_model):
607
+ raise ValueError("Cannot use PiSSA for current training stage.")
608
+
609
+ if self.early_stopping_min_delta < 0:
610
+ raise ValueError("`early_stopping_min_delta` must be non-negative.")
611
+
612
+ if self.finetuning_type != "lora":
613
+ if self.loraplus_lr_ratio is not None:
614
+ raise ValueError("`loraplus_lr_ratio` is only valid for LoRA training.")
615
+
616
+ if self.use_rslora:
617
+ raise ValueError("`use_rslora` is only valid for LoRA training.")
618
+
619
+ if self.use_dora:
620
+ raise ValueError("`use_dora` is only valid for LoRA training.")
621
+
622
+ if self.pissa_init:
623
+ raise ValueError("`pissa_init` is only valid for LoRA training.")
624
+
625
+ if self.early_stopping_steps is not None:
626
+ _patch_early_stopping_callback(self.early_stopping_min_delta)
627
+
628
+ def to_dict(self) -> dict[str, Any]:
629
+ args = asdict(self)
630
+ args = {k: f"<{k.upper()}>" if k.endswith("api_key") else v for k, v in args.items()}
631
+ return args
632
+
633
+
634
+ def _patch_early_stopping_callback(min_delta: float) -> None:
635
+ from transformers import EarlyStoppingCallback as HFEarlyStoppingCallback
636
+
637
+ try:
638
+ tuner = importlib.import_module("llamafactory.train.tuner")
639
+ except ModuleNotFoundError:
640
+ return
641
+
642
+ class DataFlexEarlyStoppingCallback(HFEarlyStoppingCallback):
643
+ def __init__(self, early_stopping_patience: int):
644
+ super().__init__(
645
+ early_stopping_patience=early_stopping_patience,
646
+ early_stopping_threshold=min_delta,
647
+ )
648
+
649
+ tuner.EarlyStoppingCallback = DataFlexEarlyStoppingCallback
@@ -0,0 +1,5 @@
1
+ from .random_mixer import RandomMixer
2
+ from .doremi_mixer import DoremiMixer
3
+ from .static_mixer import StaticMixer
4
+ from .odm_mixer import ODMMixer
5
+ from .dynamic_moe_mixer import DynamicMoEMixer
@@ -0,0 +1,21 @@
1
+ from abc import ABC, abstractmethod
2
+ import numpy as np
3
+
4
+ class Mixer(ABC):
5
+ def __init__(self, mixture_manager):
6
+ self.mixture_manager = mixture_manager
7
+
8
+ @abstractmethod
9
+ def mix(self, model, step_id: int, **kwargs) -> np.ndarray:
10
+ """
11
+ Change the proportions of samples for the model in 'step_id'.
12
+
13
+ Args:
14
+ model: The model object used in the selection process.
15
+ step_id (int): The ID of the current training step or stage.
16
+ **kwargs: Additional keyword arguments, allowing for flexible expansion by subclasses.
17
+
18
+ Returns:
19
+ np.ndarray: The updated proportions of samples for the model in 'step_id'.
20
+ """
21
+ pass