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,773 @@
1
+ # Copyright 2025 HuggingFace Inc. and the LlamaFactory team.
2
+ #
3
+ # This code is inspired by the HuggingFace's transformers library.
4
+ # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/trainer_seq2seq.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import contextlib
19
+ import copy
20
+ import functools
21
+ import glob
22
+ import importlib.metadata
23
+ import os
24
+ import random
25
+ import re
26
+ import shutil
27
+ import numpy as np
28
+ from torch import nn
29
+ import time
30
+ import torch.distributed as dist
31
+ from collections.abc import Mapping
32
+ from pathlib import Path
33
+ from typing import TYPE_CHECKING, Any, Callable, Optional, Union, List
34
+ from torch.utils.data import Subset, DataLoader, IterableDataset
35
+ import os
36
+ from types import MethodType
37
+ from typing import TYPE_CHECKING, Any, Optional, Union
38
+ from packaging import version
39
+ import numpy as np
40
+ import torch
41
+ from typing_extensions import override
42
+ from torch.utils.data import DataLoader, Dataset, IterableDataset, RandomSampler, SequentialSampler
43
+ from llamafactory.extras.constants import IGNORE_INDEX
44
+ from llamafactory.extras.packages import is_transformers_version_greater_than
45
+ from llamafactory.train.callbacks import SaveProcessorCallback
46
+ from llamafactory.train.trainer_utils import create_custom_optimizer, create_custom_scheduler
47
+ from llamafactory.train.sft.trainer import CustomSeq2SeqTrainer
48
+
49
+ from transformers.configuration_utils import PretrainedConfig
50
+ from transformers.data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator
51
+ from transformers.debug_utils import DebugOption, DebugUnderflowOverflow
52
+ from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
53
+ from transformers.feature_extraction_utils import FeatureExtractionMixin
54
+ from transformers.hyperparameter_search import ALL_HYPERPARAMETER_SEARCH_BACKENDS, default_hp_search_backend
55
+ from transformers.image_processing_utils import BaseImageProcessor
56
+ from transformers.integrations.deepspeed import deepspeed_init, deepspeed_load_checkpoint, is_deepspeed_available
57
+ from transformers.integrations.tpu import tpu_spmd_dataloader
58
+ from transformers.modelcard import TrainingSummary
59
+ from transformers.modeling_utils import PreTrainedModel, load_sharded_checkpoint, unwrap_model
60
+ from transformers.models.auto.modeling_auto import (
61
+ MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
62
+ MODEL_MAPPING_NAMES,
63
+ )
64
+ from transformers.optimization import Adafactor, get_scheduler
65
+ from transformers.processing_utils import ProcessorMixin
66
+ from transformers.pytorch_utils import (
67
+ ALL_LAYERNORM_LAYERS,
68
+ is_torch_greater_or_equal_than_2_3,
69
+ )
70
+ from transformers.tokenization_utils_base import PreTrainedTokenizerBase
71
+ from transformers.trainer_callback import (
72
+ CallbackHandler,
73
+ DefaultFlowCallback,
74
+ ExportableState,
75
+ PrinterCallback,
76
+ ProgressCallback,
77
+ TrainerCallback,
78
+ TrainerControl,
79
+ TrainerState,
80
+ )
81
+ from transformers.trainer_pt_utils import (
82
+ DistributedTensorGatherer,
83
+ EvalLoopContainer,
84
+ IterableDatasetShard,
85
+ LabelSmoother,
86
+ LayerWiseDummyOptimizer,
87
+ LengthGroupedSampler,
88
+ SequentialDistributedSampler,
89
+ distributed_broadcast_scalars,
90
+ distributed_concat,
91
+ find_batch_size,
92
+ get_model_param_count,
93
+ get_module_class_from_name,
94
+ get_parameter_names,
95
+ nested_concat,
96
+ nested_detach,
97
+ nested_numpify,
98
+ nested_xla_mesh_reduce,
99
+ reissue_pt_warnings,
100
+ remove_dummy_checkpoint,
101
+ set_rng_state_for_device,
102
+ )
103
+ from transformers.trainer_utils import (
104
+ TrainOutput,
105
+ speed_metrics,
106
+ seed_worker,
107
+ has_length
108
+ )
109
+ from transformers.training_args import OptimizerNames, ParallelMode, TrainingArguments
110
+ from transformers.utils import (
111
+ is_accelerate_available,
112
+ is_apex_available,
113
+ is_apollo_torch_available,
114
+ is_bitsandbytes_available,
115
+ is_datasets_available,
116
+ is_galore_torch_available,
117
+ is_grokadamw_available,
118
+ is_in_notebook,
119
+ is_ipex_available,
120
+ is_liger_kernel_available,
121
+ is_lomo_available,
122
+ is_peft_available,
123
+ is_safetensors_available,
124
+ is_sagemaker_dp_enabled,
125
+ is_sagemaker_mp_enabled,
126
+ is_schedulefree_available,
127
+ is_torch_compile_available,
128
+ is_torch_hpu_available,
129
+ is_torch_mlu_available,
130
+ is_torch_mps_available,
131
+ is_torch_musa_available,
132
+ is_torch_neuroncore_available,
133
+ is_torch_npu_available,
134
+ is_torch_xla_available,
135
+ is_torch_xpu_available,
136
+ is_torchao_available,
137
+ strtobool,
138
+ )
139
+
140
+ from transformers.utils.deprecation import deprecate_kwarg
141
+ from transformers.utils.quantization_config import QuantizationMethod
142
+
143
+ from dataflex.utils.load_component import load_component
144
+ from dataflex.core.registry import REGISTRY
145
+ import dataflex.train.weighter
146
+
147
+ TRAINING_ARGS_NAME = "training_args.bin"
148
+ TRAINER_STATE_NAME = "trainer_state.json"
149
+ OPTIMIZER_NAME = "optimizer.pt"
150
+ SCALER_NAME = "scaler.pt"
151
+ OPTIMIZER_NAME_BIN = "optimizer.bin"
152
+ SCHEDULER_NAME = "scheduler.pt"
153
+ FSDP_MODEL_NAME = "pytorch_model_fsdp"
154
+
155
+
156
+ if TYPE_CHECKING:
157
+ from torch.utils.data import Dataset
158
+ from transformers import PreTrainedTokenizer, ProcessorMixin
159
+ from transformers.trainer import PredictionOutput
160
+
161
+ from llamafactory.hparams import FinetuningArguments
162
+ from dataflex.utils.logging import logger
163
+
164
+ if is_peft_available():
165
+ from peft import PeftModel
166
+
167
+ def _is_peft_model(model):
168
+ if is_peft_available():
169
+ classes_to_check = (PeftModel,) if is_peft_available() else ()
170
+ # Here we also check if the model is an instance of `PeftMixedModel` introduced in peft>=0.7.0: https://github.com/huggingface/transformers/pull/28321
171
+ if version.parse(importlib.metadata.version("peft")) >= version.parse("0.7.0"):
172
+ from peft import PeftMixedModel
173
+
174
+ classes_to_check = (*classes_to_check, PeftMixedModel)
175
+ return isinstance(model, classes_to_check)
176
+ return False
177
+
178
+ if is_sagemaker_mp_enabled():
179
+ # import smdistributed.modelparallel.torch as smp
180
+ # from smdistributed.modelparallel import __version__ as SMP_VERSION
181
+
182
+ # IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10")
183
+
184
+ # from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat
185
+ pass
186
+ else:
187
+ IS_SAGEMAKER_MP_POST_1_10 = False
188
+
189
+ if is_accelerate_available():
190
+ from accelerate import Accelerator, skip_first_batches
191
+ from accelerate import __version__ as accelerate_version
192
+ from accelerate.state import AcceleratorState
193
+ from accelerate.utils import (
194
+ AutocastKwargs,
195
+ DistributedDataParallelKwargs,
196
+ DistributedType,
197
+ load_fsdp_model,
198
+ load_fsdp_optimizer,
199
+ save_fsdp_model,
200
+ save_fsdp_optimizer,
201
+ )
202
+
203
+ DATA_SAMPLERS = [RandomSampler]
204
+ if version.parse(accelerate_version) > version.parse("1.3.0"):
205
+ from accelerate.utils import TorchTensorParallelPlugin
206
+ if version.parse(accelerate_version) > version.parse("0.23.0"):
207
+ from accelerate.data_loader import SeedableRandomSampler
208
+
209
+ DATA_SAMPLERS += [SeedableRandomSampler]
210
+
211
+ if is_deepspeed_available():
212
+ from accelerate.utils import DeepSpeedSchedulerWrapper
213
+
214
+ if is_apex_available():
215
+ from apex import amp
216
+
217
+ if is_datasets_available():
218
+ import datasets
219
+
220
+ if is_torch_xla_available():
221
+ # import torch_xla.core.xla_model as xm
222
+ # import torch_xla.debug.metrics as met
223
+ # from torch_xla import __version__ as XLA_VERSION
224
+
225
+ # IS_XLA_FSDPV2_POST_2_2 = version.parse(XLA_VERSION) >= version.parse(XLA_FSDPV2_MIN_VERSION)
226
+ # if IS_XLA_FSDPV2_POST_2_2:
227
+ # import torch_xla.distributed.spmd as xs
228
+ # import torch_xla.runtime as xr
229
+ pass
230
+ else:
231
+ IS_XLA_FSDPV2_POST_2_2 = False
232
+
233
+
234
+ class WeightTrainer(CustomSeq2SeqTrainer):
235
+ def __init__(self, finetuning_args, processor=None, gen_kwargs=None, **kwargs):
236
+ # 初始化父类
237
+ super().__init__(finetuning_args=finetuning_args, processor=processor, gen_kwargs=gen_kwargs, **kwargs)
238
+ name = finetuning_args.component_name
239
+ # 取该 weighter 的 params(可替换 ${output_dir})
240
+ sel_params = load_component(
241
+ 'weighters',
242
+ finetuning_args.components_cfg_file,
243
+ name,
244
+ runtime_vars={}
245
+ )
246
+
247
+ # 统一提供“动态运行期依赖”,静态类会自动忽略
248
+ runtime = dict(
249
+ dataset=self.train_dataset,
250
+ eval_dataset=self.eval_dataset,
251
+ accelerator=self.accelerator,
252
+ data_collator=self.data_collator,
253
+ )
254
+
255
+ # 实例化(无任何 if/else)
256
+ self.weighter = REGISTRY.build("weighter", name, runtime=runtime, cfg=sel_params)
257
+ logger.info(f"[Dataflex] weighter={name}, params={sel_params}")
258
+ logger.info("[Dataflex] WeightTrainer initialized")
259
+
260
+ # 这个函数也是分别在每个gpu上执行的
261
+ @override
262
+ def _inner_training_loop(
263
+ self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None
264
+ ):
265
+ self.accelerator.free_memory()
266
+ # 这个batchsize就是per_gpu batchsize!
267
+ self._train_batch_size = batch_size
268
+ if self.args.auto_find_batch_size:
269
+ if self.state.train_batch_size != self._train_batch_size:
270
+ from accelerate.utils import release_memory
271
+
272
+ (self.model_wrapped,) = release_memory(self.model_wrapped)
273
+ self.model_wrapped = self.model
274
+
275
+ # Check for DeepSpeed *after* the initial pass and modify the config
276
+ if self.is_deepspeed_enabled:
277
+ # Temporarily unset `self.args.train_batch_size`
278
+ original_bs = self.args.per_device_train_batch_size
279
+ self.args.per_device_train_batch_size = self._train_batch_size // max(1, self.args.n_gpu)
280
+ self.propagate_args_to_deepspeed(True)
281
+ self.args.per_device_train_batch_size = original_bs
282
+ self.state.train_batch_size = self._train_batch_size
283
+ logger.debug(f"Currently training with a batch size of: {self._train_batch_size}")
284
+
285
+ # Setting up training control variables:
286
+ # number of training epochs: num_train_epochs
287
+ # number of training steps per epoch: num_update_steps_per_epoch
288
+ # total number of training steps to execute: max_steps
289
+ # _train_batch_size = micro batch size
290
+ # 这个是global batch size
291
+ total_train_batch_size = self._train_batch_size * args.gradient_accumulation_steps * args.world_size
292
+
293
+ # warmup不换dataloaer,直接通过step去控制
294
+ logger.info(f"[Dataflex] Dynamic training mode")
295
+ logger.info(f"[Dataflex] Warmup step {self.finetuning_args.warmup_step}")
296
+ train_dataloader = self.get_train_dataloader()
297
+
298
+ if self.is_fsdp_xla_v2_enabled:
299
+ train_dataloader = tpu_spmd_dataloader(train_dataloader)
300
+ (
301
+ num_train_epochs,
302
+ num_update_steps_per_epoch, # 等于len_dataloader // acc (或len(dataset)/worldsize/microbatchsize/acc)
303
+ num_examples, # 等于数据集长度
304
+ num_train_samples, # 等于数据集长度 * epoch数
305
+ epoch_based,
306
+ len_dataloader, # 等于数据集长度/worldsize/micro_batchsize
307
+ max_steps,
308
+ ) = self.set_initial_training_values(args, train_dataloader, total_train_batch_size)
309
+ max_steps = self.finetuning_args.train_step
310
+ epoch_based = False
311
+ logger.info(f"[Dataflex]Set max train steps to {max_steps}")
312
+ logger.info(f"[Dataflex]Set epoch_based = False")
313
+ num_train_tokens = None
314
+
315
+ # 这里是每个gpu的tokens
316
+ if self.args.include_tokens_per_second:
317
+ num_train_tokens = self.num_tokens(train_dataloader, None if epoch_based else max_steps)
318
+ # If going by epochs, multiply tokens linearly
319
+ if len_dataloader is not None and epoch_based:
320
+ num_train_tokens *= args.num_train_epochs
321
+ # Otherwise since its steps, we just multiply by grad accum
322
+ else:
323
+ num_train_tokens *= args.gradient_accumulation_steps
324
+
325
+ if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug:
326
+ if self.args.n_gpu > 1:
327
+ # nn.DataParallel(model) replicates the model, creating new variables and module
328
+ # references registered here no longer work on other gpus, breaking the module
329
+ raise ValueError(
330
+ "Currently --debug underflow_overflow is not supported under DP. Please use DDP"
331
+ " (torchrun or torch.distributed.launch (deprecated))."
332
+ )
333
+ else:
334
+ debug_overflow = DebugUnderflowOverflow(self.model) # noqa
335
+
336
+ delay_optimizer_creation = is_sagemaker_mp_enabled() or self.is_fsdp_xla_enabled or self.is_fsdp_enabled
337
+
338
+ # Can't delay optimizer creation when using FSDP2: https://github.com/huggingface/accelerate/blob/3f636d626063ffcf9a337c7d3624d61b7d187d59/src/accelerate/accelerator.py#L1404
339
+ is_fsdp2 = self.is_fsdp_enabled and (getattr(self.accelerator.state.fsdp_plugin, "fsdp_version", 1) == 2)
340
+ if is_fsdp2:
341
+ delay_optimizer_creation = False
342
+
343
+ # We need to reset the scheduler, as its parameters may be different on subsequent calls
344
+ if self._created_lr_scheduler:
345
+ self.lr_scheduler = None
346
+ self._created_lr_scheduler = False
347
+
348
+ if self.is_deepspeed_enabled:
349
+ self.optimizer, self.lr_scheduler = deepspeed_init(self, num_training_steps=max_steps)
350
+
351
+ if not delay_optimizer_creation:
352
+ self.create_optimizer_and_scheduler(num_training_steps=max_steps)
353
+
354
+ self.state = TrainerState(
355
+ stateful_callbacks=[
356
+ cb for cb in self.callback_handler.callbacks + [self.control] if isinstance(cb, ExportableState)
357
+ ]
358
+ )
359
+ self.state.is_hyper_param_search = trial is not None
360
+ self.state.train_batch_size = self._train_batch_size
361
+
362
+ # Compute absolute values for logging, eval, and save if given as ratio
363
+ self.state.compute_steps(args, max_steps)
364
+
365
+ # Activate gradient checkpointing if needed
366
+ if args.gradient_checkpointing:
367
+ self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs=args.gradient_checkpointing_kwargs)
368
+
369
+ model = self._wrap_model(self.model_wrapped)
370
+
371
+ # as the model is wrapped, don't use `accelerator.prepare`
372
+ # this is for unhandled cases such as
373
+ # FSDP-XLA, SageMaker MP/DP, DataParallel, IPEX
374
+ use_accelerator_prepare = True if model is self.model else False
375
+
376
+ if use_accelerator_prepare and self.is_fsdp_enabled:
377
+ # In case of auto_find_batch_size=True
378
+ # Remove FSDP wrapping from sub-models.
379
+ self.model = unwrap_model(self.model, recursive=True)
380
+
381
+ if delay_optimizer_creation:
382
+ if use_accelerator_prepare:
383
+ # configure fsdp plugin for qlora if any
384
+ self._fsdp_qlora_plugin_updates()
385
+ if self.accelerator.mixed_precision != "fp8":
386
+ self.model = self.accelerator.prepare(self.model)
387
+ self.create_optimizer_and_scheduler(num_training_steps=max_steps)
388
+
389
+ # prepare using `accelerator` prepare
390
+ if use_accelerator_prepare:
391
+ self.model.train()
392
+ if hasattr(self.lr_scheduler, "step"):
393
+ if self.use_apex:
394
+ model = self.accelerator.prepare(self.model)
395
+ else:
396
+ model, self.optimizer = self.accelerator.prepare(self.model, self.optimizer)
397
+ else:
398
+ # to handle cases wherein we pass "DummyScheduler" such as when it is specified in DeepSpeed config.
399
+ model, self.optimizer, self.lr_scheduler = self.accelerator.prepare(
400
+ self.model, self.optimizer, self.lr_scheduler
401
+ )
402
+ elif self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
403
+ # In this case we are in DDP + LOMO, which should be supported
404
+ self.optimizer = self.accelerator.prepare(self.optimizer)
405
+
406
+ if self.is_fsdp_enabled:
407
+ self.model = self.model_wrapped = model
408
+
409
+ # for the rest of this function `model` is the outside model, whether it was wrapped or not
410
+ if model is not self.model:
411
+ self.model_wrapped = model
412
+
413
+ # backward compatibility
414
+ if self.is_deepspeed_enabled:
415
+ self.deepspeed = self.model_wrapped
416
+
417
+ # ckpt loading
418
+ if resume_from_checkpoint is not None:
419
+ if self.is_deepspeed_enabled:
420
+ deepspeed_load_checkpoint(
421
+ self.model_wrapped, resume_from_checkpoint, load_module_strict=not _is_peft_model(self.model)
422
+ )
423
+ elif is_sagemaker_mp_enabled() or self.is_fsdp_enabled:
424
+ self._load_from_checkpoint(resume_from_checkpoint, self.model_wrapped)
425
+
426
+ # Check if saved optimizer or scheduler states exist
427
+ self._load_optimizer_and_scheduler(resume_from_checkpoint)
428
+ self._load_scaler(resume_from_checkpoint)
429
+
430
+ # important: at this point:
431
+ # self.model is the Transformers Model
432
+ # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model),
433
+ # FSDP(Transformers Model), Dynamo Optimized Module(Transformers Model) etc.
434
+
435
+ # Train!
436
+ logger.info("***** Dynamic Running training *****")
437
+ logger.info(f" Num examples = {num_examples:,}")
438
+ logger.info(f" Num Epochs = {num_train_epochs:,}")
439
+ logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size:,}")
440
+ if self.args.per_device_train_batch_size != self._train_batch_size:
441
+ logger.info(f" Training with DataParallel so batch size has been adjusted to: {self._train_batch_size:,}")
442
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size:,}")
443
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
444
+ logger.info(f" Total optimization steps = {max_steps:,}")
445
+ logger.info(f" Number of trainable parameters = {get_model_param_count(model, trainable_only=True):,}")
446
+
447
+ self.state.epoch = 0
448
+ start_time = time.time()
449
+ epochs_trained = 0
450
+ steps_trained_in_current_epoch = 0
451
+ steps_trained_progress_bar = None
452
+
453
+ # Check if continuing training from a checkpoint
454
+ if resume_from_checkpoint is not None and os.path.isfile(
455
+ os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)
456
+ ):
457
+ self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME))
458
+ self.compare_trainer_and_checkpoint_args(self.args, self.state)
459
+ self._load_callback_state()
460
+ epochs_trained = int(self.state.global_step // num_update_steps_per_epoch)
461
+ if not args.ignore_data_skip:
462
+ steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)
463
+ steps_trained_in_current_epoch *= args.gradient_accumulation_steps
464
+ else:
465
+ steps_trained_in_current_epoch = 0
466
+
467
+ logger.info(" Continuing training from checkpoint, will skip to saved global_step")
468
+ logger.info(f" Continuing training from epoch {epochs_trained}")
469
+ logger.info(f" Continuing training from global step {self.state.global_step}")
470
+ if not args.ignore_data_skip:
471
+ logger.info(
472
+ f" Will skip the first {epochs_trained} epochs then the first"
473
+ f" {steps_trained_in_current_epoch} batches in the first epoch."
474
+ )
475
+
476
+ # Update the references
477
+ for attr in ("model", "optimizer", "lr_scheduler"):
478
+ setattr(self.callback_handler, attr, getattr(self, attr))
479
+ self.callback_handler.train_dataloader = train_dataloader
480
+
481
+ self.state.init_training_references(self, max_steps, num_train_epochs, trial)
482
+
483
+ # tr_loss is a tensor to avoid synchronization of TPUs through .item()
484
+ tr_loss = torch.tensor(0.0, device=args.device)
485
+ # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
486
+ self._total_loss_scalar = 0.0
487
+ self._globalstep_last_logged = self.state.global_step
488
+ model.zero_grad()
489
+ grad_norm: Optional[float] = None
490
+ learning_rate = None
491
+ self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
492
+
493
+ if args.eval_on_start:
494
+ self._evaluate(trial, ignore_keys_for_eval, skip_scheduler=True)
495
+
496
+ # 放弃epoch逻辑,相当于只训练一个epoch,通过step来训练
497
+ epoch = 0
498
+ if self.state.global_step < self.finetuning_args.warmup_step:
499
+ logger.info("[Dataflex] Model warmup in progress...")
500
+
501
+
502
+ # Reset the past mems state at the beginning of each epoch if necessary.
503
+ if args.past_index >= 0:
504
+ self._past = None
505
+
506
+ steps_in_epoch = max_steps * args.gradient_accumulation_steps
507
+ self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control)
508
+
509
+ if resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0:
510
+ self._load_rng_state(resume_from_checkpoint)
511
+
512
+ rng_to_sync = False
513
+ steps_skipped = 0
514
+ if steps_trained_in_current_epoch > 0:
515
+ train_dataloader = skip_first_batches(train_dataloader, steps_trained_in_current_epoch)
516
+ steps_skipped = steps_trained_in_current_epoch
517
+ steps_trained_in_current_epoch = 0
518
+ rng_to_sync = True
519
+
520
+ step = -1
521
+ current_iterator = iter(train_dataloader)
522
+ # We chunkify the epoch iterator into gradient accumulation steps `n` batches
523
+ remainder = num_examples % args.gradient_accumulation_steps
524
+ if remainder == 0:
525
+ remainder = args.gradient_accumulation_steps
526
+ update_step = -1
527
+ # 一个epoch中的模型总更新次数
528
+ total_updates = steps_in_epoch // args.gradient_accumulation_steps + 1
529
+ if args.gradient_accumulation_steps == 1:
530
+ total_updates -= 1
531
+ for _ in range(total_updates):
532
+ update_step += 1
533
+ # 当前应该拿到的batch数,一般情况是gradient_accumulation_steps,每这么多个batch反向传播一次梯度,每个batch有batch_size个样本
534
+ num_batches = args.gradient_accumulation_steps if update_step != (total_updates - 1) else remainder
535
+
536
+ batch_samples, num_items_in_batch = self.get_batch_samples(current_iterator, num_batches, args.device)
537
+ # 遍历当前批次的样本
538
+ for i, inputs in enumerate(batch_samples):
539
+ step += 1 # 每次迭代时增加全局步数
540
+
541
+ # 判断是否达到同步步数,或者是当前epoch的最后一个步数
542
+ do_sync_step = (step + 1) % args.gradient_accumulation_steps == 0 or (step + 1) == steps_in_epoch
543
+
544
+ # 由于我们使用了预取(prefetching),我们需要手动设置同步梯度
545
+ self.accelerator.gradient_state._set_sync_gradients(do_sync_step)
546
+
547
+ # 如果需要记录输入的token数量
548
+ if self.args.include_num_input_tokens_seen:
549
+ main_input_name = getattr(self.model, "main_input_name", "input_ids") # 获取模型的主输入名称(默认为input_ids)
550
+
551
+ # 检查模型的输入是否包含主输入名称
552
+ if main_input_name not in inputs:
553
+ logger.warning(
554
+ "Tried to track the number of tokens seen, however the current model is "
555
+ "not configured properly to know what item is the input. To fix this, add "
556
+ "a `main_input_name` attribute to the model class you are using."
557
+ )
558
+ else:
559
+ # 计算当前输入的tokens数量,并将其加入到已看到的总token数中
560
+ input_tokens = inputs[main_input_name].numel() # 计算当前输入的tokens数量
561
+ input_tokens = torch.tensor(input_tokens, device=self.args.device, dtype=torch.int64) # 转换为张量
562
+ self.state.num_input_tokens_seen += self.accelerator.gather(input_tokens).sum().item() # 累加已看到的token数量
563
+
564
+ # 如果需要同步随机数生成器(用于恢复训练)
565
+ if rng_to_sync:
566
+ self._load_rng_state(resume_from_checkpoint) # 从检查点加载随机数生成器的状态
567
+ rng_to_sync = False # 重置同步标志
568
+
569
+ # 如果恢复训练且当前epoch还有未训练的步数,跳过已训练的步骤
570
+ if steps_trained_in_current_epoch > 0:
571
+ steps_trained_in_current_epoch -= 1 # 减少剩余的训练步数
572
+ if steps_trained_progress_bar is not None:
573
+ steps_trained_progress_bar.update(1) # 更新已训练步数的进度条
574
+ if steps_trained_in_current_epoch == 0:
575
+ self._load_rng_state(resume_from_checkpoint) # 恢复检查点的随机数生成器状态
576
+ continue # 跳过这次迭代,进入下一次迭代
577
+ elif steps_trained_progress_bar is not None:
578
+ steps_trained_progress_bar.close() # 关闭已训练步数的进度条
579
+ steps_trained_progress_bar = None # 重置进度条
580
+
581
+ # 每当步数达到梯度累积步骤数时,执行一次同步操作
582
+ if step % args.gradient_accumulation_steps == 0:
583
+ self.control = self.callback_handler.on_step_begin(args, self.state, self.control) # 执行步骤开始的回调
584
+
585
+ # 在生成训练时避免依赖`accelerator.accumulate`,显式设置是否同步
586
+ context = (
587
+ functools.partial(self.accelerator.no_sync, model=model) # 如果不是最后一个批次,则不进行同步
588
+ if i != len(batch_samples) - 1
589
+ and self.accelerator.distributed_type != DistributedType.DEEPSPEED
590
+ else contextlib.nullcontext # 否则不使用同步
591
+ )
592
+ use_weighter = (self.state.global_step >= self.finetuning_args.warmup_step) # 是否使用weighter进行加权训练
593
+ with context(): # 在非同步上下文中进行训练
594
+ tr_loss_step = self.weighter.training_step(self, model, inputs, num_items_in_batch, use_weighter) # 执行一次训练步骤,返回该步的损失值
595
+
596
+ # 检查损失是否为NaN或Infinity,如果是,使用之前的损失值替代
597
+ if (
598
+ args.logging_nan_inf_filter
599
+ and not is_torch_xla_available()
600
+ and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step))
601
+ ):
602
+ tr_loss = tr_loss + tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) # 如果损失为NaN或Inf,则使用平均损失
603
+ else:
604
+ if tr_loss.device != tr_loss_step.device:
605
+ raise ValueError(
606
+ f"Calculated loss must be on the original device: {tr_loss.device} but device in use is {tr_loss_step.device}"
607
+ ) # 检查计算的损失是否在原始设备上
608
+ tr_loss = tr_loss + tr_loss_step # 将当前步的损失加入总损失
609
+
610
+ # 累加浮点数操作的数量
611
+ self.current_flos += float(self.floating_point_ops(inputs))
612
+
613
+ # step达到acc,同步梯度
614
+ if do_sync_step:
615
+ # Since we perform prefetching, we need to manually set sync_gradients to True
616
+ self.accelerator.gradient_state._set_sync_gradients(True)
617
+
618
+ # Gradient clipping
619
+ if args.max_grad_norm is not None and args.max_grad_norm > 0:
620
+ if is_sagemaker_mp_enabled() and args.fp16:
621
+ _grad_norm = self.optimizer.clip_master_grads(args.max_grad_norm)
622
+ elif self.use_apex:
623
+ # Revert to normal clipping otherwise, handling Apex or full precision
624
+ _grad_norm = nn.utils.clip_grad_norm_(
625
+ amp.master_params(self.optimizer),
626
+ args.max_grad_norm,
627
+ )
628
+ else:
629
+ _grad_norm = self.accelerator.clip_grad_norm_(
630
+ model.parameters(),
631
+ args.max_grad_norm,
632
+ )
633
+
634
+ if (
635
+ is_accelerate_available()
636
+ and self.accelerator.distributed_type == DistributedType.DEEPSPEED
637
+ ):
638
+ grad_norm = model.get_global_grad_norm()
639
+ # In some cases the grad norm may not return a float
640
+ if hasattr(grad_norm, "item"):
641
+ grad_norm = grad_norm.item()
642
+ else:
643
+ grad_norm = _grad_norm
644
+
645
+ self.control = self.callback_handler.on_pre_optimizer_step(args, self.state, self.control)
646
+
647
+ self.optimizer.step()
648
+
649
+ self.control = self.callback_handler.on_optimizer_step(args, self.state, self.control)
650
+
651
+ # get leaning rate before update
652
+ learning_rate = self._get_learning_rate()
653
+
654
+ if not self.accelerator.optimizer_step_was_skipped:
655
+ # Delay optimizer scheduling until metrics are generated
656
+ if not isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):
657
+ self.lr_scheduler.step()
658
+
659
+ model.zero_grad()
660
+ # 同步精度然后反向传播,此时每个gpu上处理了per_gpu_batch_size * acc个数据,global_step+1
661
+ self.state.global_step += 1
662
+ self.state.epoch = (step + 1 + steps_skipped) / steps_in_epoch
663
+ self.control = self.callback_handler.on_step_end(args, self.state, self.control)
664
+ self._maybe_log_save_evaluate(
665
+ tr_loss,
666
+ grad_norm,
667
+ model,
668
+ trial,
669
+ epoch,
670
+ ignore_keys_for_eval,
671
+ start_time,
672
+ # learning_rate=learning_rate,
673
+ )
674
+
675
+ else:
676
+ self.control = self.callback_handler.on_substep_end(args, self.state, self.control)
677
+
678
+ # PyTorch/XLA relies on the data loader to insert the mark_step for
679
+ # each step. Since we are breaking the loop early, we need to manually
680
+ # insert the mark_step here.
681
+ if self.control.should_epoch_stop or self.control.should_training_stop:
682
+ if is_torch_xla_available():
683
+ xm.mark_step()
684
+ break
685
+ # We also need to break out of the nested loop
686
+ if self.control.should_epoch_stop or self.control.should_training_stop:
687
+ if is_torch_xla_available():
688
+ xm.mark_step()
689
+ break
690
+ if step < 0:
691
+ logger.warning(
692
+ "There seems not to be a single sample in your epoch_iterator, stopping training at step"
693
+ f" {self.state.global_step}! This is expected if you're using an IterableDataset and set"
694
+ f" num_steps ({max_steps}) higher than the number of available samples."
695
+ )
696
+ self.control.should_training_stop = True
697
+
698
+ self.control = self.callback_handler.on_epoch_end(args, self.state, self.control)
699
+ self._maybe_log_save_evaluate(
700
+ tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time
701
+ )
702
+
703
+ if DebugOption.TPU_METRICS_DEBUG in self.args.debug:
704
+ if is_torch_xla_available():
705
+ # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
706
+ xm.master_print(met.metrics_report())
707
+ else:
708
+ logger.warning(
709
+ "You enabled PyTorch/XLA debug metrics but you don't have a TPU "
710
+ "configured. Check your training configuration if this is unexpected."
711
+ )
712
+ # if self.control.should_training_stop:
713
+ # break
714
+ # 结束主训练循环
715
+ if args.past_index and hasattr(self, "_past"):
716
+ # Clean the state at the end of training
717
+ delattr(self, "_past")
718
+
719
+ logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
720
+ if args.load_best_model_at_end and self.state.best_model_checkpoint is not None:
721
+ # Wait for everyone to get here so we are sure the model has been saved by process 0.
722
+ if is_torch_xla_available():
723
+ xm.rendezvous("load_best_model_at_end")
724
+ elif args.parallel_mode == ParallelMode.DISTRIBUTED:
725
+ dist.barrier()
726
+ elif is_sagemaker_mp_enabled():
727
+ smp.barrier()
728
+
729
+ self._load_best_model()
730
+
731
+ # add remaining tr_loss
732
+ self._total_loss_scalar += tr_loss.item()
733
+ effective_global_step = max(self.state.global_step, 0.001) # Avoid ZeroDivisionError
734
+ train_loss = self._total_loss_scalar / effective_global_step
735
+
736
+ metrics = speed_metrics(
737
+ "train",
738
+ start_time,
739
+ num_samples=num_train_samples,
740
+ num_steps=self.state.max_steps,
741
+ num_tokens=num_train_tokens,
742
+ )
743
+ self.store_flos()
744
+ metrics["total_flos"] = self.state.total_flos
745
+ metrics["train_loss"] = train_loss
746
+
747
+ self.is_in_train = False
748
+
749
+ self._memory_tracker.stop_and_update_metrics(metrics)
750
+
751
+ self.log(metrics)
752
+
753
+ run_dir = self._get_output_dir(trial)
754
+ checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir)
755
+
756
+ # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint and process allowed to save.
757
+ if self.args.should_save and self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1:
758
+ for checkpoint in checkpoints_sorted:
759
+ if not os.path.samefile(checkpoint, self.state.best_model_checkpoint):
760
+ logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit")
761
+ shutil.rmtree(checkpoint, ignore_errors=True)
762
+
763
+ self.control = self.callback_handler.on_train_end(args, self.state, self.control)
764
+
765
+ # Wait for the checkpoint to be uploaded.
766
+ self._finish_current_push()
767
+
768
+ # After training we make sure to retrieve back the original forward pass method
769
+ # for the embedding layer by removing the forward post hook.
770
+ if self.neftune_noise_alpha is not None:
771
+ self._deactivate_neftune(self.model)
772
+
773
+ return TrainOutput(self.state.global_step, train_loss, metrics)