-
Notifications
You must be signed in to change notification settings - Fork 359
Expand file tree
/
Copy pathconfig.py
More file actions
1831 lines (1604 loc) · 68.6 KB
/
config.py
File metadata and controls
1831 lines (1604 loc) · 68.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import copy
import json
import os
import shutil
import sys
import tempfile
import time
import uuid
from argparse import ArgumentError
from contextlib import contextmanager
from datetime import datetime
from typing import Dict, List, Optional, Union
import yaml
from jsonargparse import (
ActionConfigFile,
ArgumentParser,
Namespace,
dict_to_namespace,
namespace_to_dict,
)
from jsonargparse._typehints import ActionTypeHint
from jsonargparse.typing import ClosedUnitInterval, NonNegativeInt, PositiveInt
from loguru import logger
from data_juicer.ops.base_op import OPERATORS
from data_juicer.ops.op_fusion import FUSION_STRATEGIES
from data_juicer.utils.constant import RAY_JOB_ENV_VAR
from data_juicer.utils.logger_utils import setup_logger
from data_juicer.utils.mm_utils import SpecialTokens
from data_juicer.utils.ray_utils import is_ray_mode
global_cfg = None
global_parser = None
@contextmanager
def timing_context(description):
start_time = time.time()
yield
elapsed_time = time.time() - start_time
# Use a consistent format that won't be affected by logger reconfiguration
logger.debug(f"{description} took {elapsed_time:.2f} seconds")
def _generate_module_name(abs_path):
"""Generate a module name based on the absolute path of the file."""
return os.path.splitext(os.path.basename(abs_path))[0]
def load_custom_operators(paths):
"""Dynamically load custom operator modules or packages in the specified path.
This is a re-export from ``data_juicer.utils.custom_op`` kept here for
backward compatibility.
"""
from data_juicer.utils.custom_op import load_custom_operators as _impl
_impl(paths)
def build_base_parser() -> ArgumentParser:
parser = ArgumentParser(default_env=True, default_config_files=None, usage=argparse.SUPPRESS)
# required but mutually exclusive args group
required_group = parser.add_mutually_exclusive_group(required=True)
required_group.add_argument("--config", action=ActionConfigFile, help="Path to a dj basic configuration file.")
required_group.add_argument(
"--auto",
action="store_true",
help="Whether to use an auto analyzing "
"strategy instead of a specific data "
"recipe. If a specific config file is "
"given by --config arg, this arg is "
"disabled. Only available for Analyzer.",
)
parser.add_argument(
"--auto_num",
type=PositiveInt,
default=1000,
help="The number of samples to be analyzed " "automatically. It's 1000 in default.",
)
parser.add_argument(
"--hpo_config", type=str, help="Path to a configuration file when using auto-HPO tool.", required=False
)
parser.add_argument(
"--data_probe_algo",
type=str,
default="uniform",
help='Sampling algorithm to use. Options are "uniform", '
'"frequency_specified_field_selector", or '
'"topk_specified_field_selector". Default is "uniform". Only '
"used for dataset sampling",
required=False,
)
parser.add_argument(
"--data_probe_ratio",
type=ClosedUnitInterval,
default=1.0,
help="The ratio of the sample size to the original dataset size. " # noqa: E251
"Default is 1.0 (no sampling). Only used for dataset sampling",
required=False,
)
# basic global paras with extended type hints
# e.g., files can be mode include flags
# "fr": "path to a file that exists and is readable")
# "fc": "path to a file that can be created if it does not exist")
# "dw": "path to a directory that exists and is writeable")
# "dc": "path to a directory that can be created if it does not exist")
# "drw": "path to a directory that exists and is readable and writeable")
parser.add_argument("--project_name", type=str, default="hello_world", help="Name of your data process project.")
parser.add_argument(
"--executor_type",
type=str,
default="default",
choices=["default", "ray", "ray_partitioned"],
help='Type of executor, support "default", "ray", or "ray_partitioned".',
)
parser.add_argument(
"--dataset_path",
type=str,
default="",
help="Path to datasets with optional weights(0.0-1.0), 1.0 as "
"default. Accepted format:<w1> dataset1-path <w2> dataset2-path "
"<w3> dataset3-path ...",
)
parser.add_argument(
"--dataset",
type=Union[List[Dict], Dict],
default=[],
help="Dataset setting to define local/remote datasets; could be a " # noqa: E251
"dict or a list of dicts; refer to "
"https://datajuicer.github.io/data-juicer/en/main/docs/DatasetCfg.html for more "
"detailed examples",
)
parser.add_argument(
"--generated_dataset_config",
type=Dict,
default=None,
help="Configuration used to create a dataset. " # noqa: E251
"The dataset will be created from this configuration if provided. "
"It must contain the `--type` field to specify the dataset name.",
)
parser.add_argument(
"--validators",
type=List[Dict],
default=[],
help="List of validators to apply to the dataset. Each validator " # noqa: E251
"must have a `type` field specifying the validator type.",
)
parser.add_argument(
"--load_dataset_kwargs",
type=Dict,
default={},
help="Extra keyword arguments passed through to the underlying " # noqa: E251
"datasets.load_dataset() call. Useful for format-specific "
"options such as chunksize (JSON), columns (Parquet), or "
"delimiter (CSV). See the HuggingFace Datasets docs for "
"available options.",
)
parser.add_argument(
"--read_options",
type=Dict,
default={},
help="Read options passed through to PyArrow reading functions "
"(e.g., block_size for JSON reading). This configuration is "
"especially useful when reading large JSON files.",
)
parser.add_argument(
"--work_dir",
type=str,
default=None,
help="Path to a work directory to store outputs during Data-Juicer " # noqa: E251
"running. It's the directory where export_path is at in default.",
)
parser.add_argument(
"--export_path",
type=str,
default="./outputs/hello_world/hello_world.jsonl",
help="Path to export and save the output processed dataset. The " # noqa: E251
"directory to store the processed dataset will be the work "
"directory of this process.",
)
parser.add_argument(
"--export_type",
type=str,
default=None,
help="The export format type. If it's not specified, Data-Juicer will parse from the export_path. The "
"supported types can be found in Exporter._router() for standalone mode and "
"RayExporter._SUPPORTED_FORMATS for ray mode",
)
parser.add_argument(
"--export_shard_size",
type=NonNegativeInt,
default=0,
help="Shard size of exported dataset in Byte. In default, it's 0, " # noqa: E251
"which means export the whole dataset into only one file. If "
"it's set a positive number, the exported dataset will be split "
"into several sub-dataset shards, and the max size of each shard "
"won't larger than the export_shard_size",
)
parser.add_argument(
"--export_in_parallel",
type=bool,
default=False,
help="Whether to export the result dataset in parallel to a single " # noqa: E251
"file, which usually takes less time. It only works when "
"export_shard_size is 0, and its default number of processes is "
"the same as the argument np. **Notice**: If it's True, "
"sometimes exporting in parallel might require much more time "
"due to the IO blocking, especially for very large datasets. "
"When this happens, False is a better choice, although it takes "
"more time.",
)
parser.add_argument(
"--export_extra_args",
type=Dict,
default={},
help="Other optional arguments for exporting in dict. For example, the key mapping info for exporting "
"the WebDataset format.",
)
parser.add_argument(
"--export_aws_credentials",
type=Dict,
default=None,
help="Export-specific AWS credentials for S3 export. If export_path is S3 and this is not provided, "
"an error will be raised. Should contain aws_access_key_id, aws_secret_access_key, aws_region, "
"and optionally aws_session_token and endpoint_url.",
)
parser.add_argument(
"--keep_stats_in_res_ds",
type=bool,
default=False,
help="Whether to keep the computed stats in the result dataset. If " # noqa: E251
"it's False, the intermediate fields to store the stats "
"computed by Filters will be removed. Default: False.",
)
parser.add_argument(
"--keep_hashes_in_res_ds",
type=bool,
default=False,
help="Whether to keep the computed hashes in the result dataset. If " # noqa: E251
"it's False, the intermediate fields to store the hashes "
"computed by Deduplicators will be removed. Default: False.",
)
parser.add_argument("--np", type=PositiveInt, default=4, help="Number of processes to process dataset.")
parser.add_argument(
"--text_keys",
type=Union[str, List[str]],
default="text",
help="Key name of field where the sample texts to be processed, e.g., " # noqa: E251
"`text`, `text.instruction`, `text.output`, ... Note: currently, "
"we support specify only ONE key for each op, for cases "
"requiring multiple keys, users can specify the op multiple "
"times. We will only use the first key of `text_keys` when you "
"set multiple keys.",
)
parser.add_argument(
"--image_key",
type=str,
default="images",
help="Key name of field to store the list of sample image paths.", # noqa: E251
)
parser.add_argument(
"--image_bytes_key",
type=str,
default="image_bytes",
help="Key name of field to store the list of sample image bytes.", # noqa: E251
)
parser.add_argument(
"--image_special_token",
type=str,
default=SpecialTokens.image,
help="The special token that represents an image in the text. In " # noqa: E251
'default, it\'s "<__dj__image>". You can specify your own special'
" token according to your input dataset.",
)
parser.add_argument(
"--audio_key",
type=str,
default="audios",
help="Key name of field to store the list of sample audio paths.", # noqa: E251
)
parser.add_argument(
"--audio_special_token",
type=str,
default=SpecialTokens.audio,
help="The special token that represents an audio in the text. In " # noqa: E251
'default, it\'s "<__dj__audio>". You can specify your own special'
" token according to your input dataset.",
)
parser.add_argument(
"--video_key",
type=str,
default="videos",
help="Key name of field to store the list of sample video paths.", # noqa: E251
)
parser.add_argument(
"--video_special_token",
type=str,
default=SpecialTokens.video,
help="The special token that represents a video in the text. In "
'default, it\'s "<__dj__video>". You can specify your own special'
" token according to your input dataset.",
)
parser.add_argument(
"--eoc_special_token",
type=str,
default=SpecialTokens.eoc,
help="The special token that represents the end of a chunk in the " # noqa: E251
'text. In default, it\'s "<|__dj__eoc|>". You can specify your '
"own special token according to your input dataset.",
)
parser.add_argument(
"--suffixes",
type=Union[str, List[str]],
default=[],
help="Suffixes of files that will be found and loaded. If not set, we " # noqa: E251
"will find all suffix files, and select a suitable formatter "
"with the most files as default.",
)
parser.add_argument(
"--turbo",
type=bool,
default=False,
help="Enable Turbo mode to maximize processing speed when batch size " "is 1.", # noqa: E251
)
parser.add_argument(
"--skip_op_error",
type=bool,
default=True,
help="Skip errors in OPs caused by unexpected invalid samples.", # noqa: E251
)
parser.add_argument(
"--use_cache",
type=bool,
default=True,
help="Whether to use the cache management of huggingface datasets. It " # noqa: E251
"might take up lots of disk space when using cache",
)
parser.add_argument(
"--ds_cache_dir",
type=str,
default=None,
help="Cache dir for HuggingFace datasets. In default it's the same " # noqa: E251
"as the environment variable `HF_DATASETS_CACHE`, whose default "
'value is usually "~/.cache/huggingface/datasets". If this '
"argument is set to a valid path by users, it will override the "
"default cache dir. Modifying this arg might also affect the other two"
" paths to store downloaded and extracted datasets that depend on "
"`HF_DATASETS_CACHE`",
)
parser.add_argument(
"--cache_compress",
type=str,
default=None,
help="The compression method of the cache file, which can be"
'specified in ["gzip", "zstd", "lz4"]. If this parameter is'
"None, the cache file will not be compressed.",
)
parser.add_argument(
"--open_monitor",
type=bool,
default=False,
help="Whether to open the monitor to trace resource utilization for " # noqa: E251
"each OP during data processing. It's False in default.",
)
parser.add_argument(
"--use_checkpoint",
type=bool,
default=False,
help="Whether to use the checkpoint management to save the latest " # noqa: E251
"version of dataset to work dir when processing. Rerun the same "
"config will reload the checkpoint and skip ops before it. Cache "
"will be disabled when it is true . If args of ops before the "
"checkpoint are changed, all ops will be rerun from the "
"beginning.",
)
# Enhanced checkpoint configuration for PartitionedRayExecutor
parser.add_argument(
"--checkpoint.enabled",
type=bool,
default=True,
help="Enable enhanced checkpointing for PartitionedRayExecutor",
)
parser.add_argument(
"--checkpoint.strategy",
type=str,
default="every_n_ops",
choices=["every_op", "every_partition", "every_n_ops", "manual", "disabled"],
help="Checkpoint strategy: every_n_ops (default, balanced), every_op (max protection), "
"manual (after specific ops), disabled (best performance)",
)
parser.add_argument(
"--checkpoint.n_ops",
type=int,
default=5,
help="Number of operations between checkpoints for every_n_ops strategy. "
"Default 5 balances fault tolerance with Ray optimization.",
)
parser.add_argument(
"--checkpoint.op_names",
type=List[str],
default=[],
help="List of operation names to checkpoint for manual strategy",
)
# Event logging configuration
parser.add_argument(
"--event_logging.enabled",
type=bool,
default=True,
help="Enable event logging for job tracking and resumption",
)
# Logging configuration
parser.add_argument(
"--max_log_size_mb",
type=int,
default=100,
help="Maximum log file size in MB before rotation",
)
parser.add_argument(
"--backup_count",
type=int,
default=5,
help="Number of backup log files to keep",
)
# Storage configuration
parser.add_argument(
"--event_log_dir",
type=str,
default=None,
help="Separate directory for event logs (fast storage)",
)
parser.add_argument(
"--checkpoint_dir",
type=str,
default=None,
help="Separate directory for checkpoints (large storage)",
)
# Job management
parser.add_argument(
"--job_id",
type=str,
default=None,
help="Custom job ID for resumption and tracking. If not provided, a unique ID will be auto-generated.",
)
parser.add_argument(
"--temp_dir",
type=str,
default=None,
help="Path to the temp directory to store intermediate caches when " # noqa: E251
"cache is disabled. In default it's None, so the temp dir will "
"be specified by system. NOTICE: you should be caution when "
"setting this argument because it might cause unexpected program "
"behaviors when this path is set to an unsafe directory.",
)
parser.add_argument(
"--open_tracer",
type=bool,
default=False,
help="Whether to open the tracer to trace samples changed during " # noqa: E251
"process. It might take more time when opening tracer.",
)
parser.add_argument(
"--op_list_to_trace",
type=List[str],
default=[],
help="Which ops will be traced by tracer. If it's empty, all ops in " # noqa: E251
"cfg.process will be traced. Only available when open_tracer is "
"true.",
)
parser.add_argument(
"--trace_num",
type=int,
default=10,
help="Number of samples extracted by tracer to show the dataset "
"difference before and after a op. Only available when "
"open_tracer is true.",
)
parser.add_argument(
"--trace_keys",
type=List[str],
default=[],
help="List of field names to include in trace output. If set, the "
"specified fields' values will be included in each trace entry. "
"Only available when open_tracer is true.",
)
parser.add_argument(
"--open_insight_mining",
type=bool,
default=False,
help="Whether to open insight mining to trace the OP-wise stats/tags " # noqa: E251
"changes during process. It might take more time when opening "
"insight mining.",
)
parser.add_argument(
"--op_list_to_mine",
type=List[str],
default=[],
help="Which OPs will be applied on the dataset to mine the insights " # noqa: E251
"in their stats changes. Only those OPs that produce stats or "
"meta are valid. If it's empty, all OPs that produce stats and "
"meta will be involved. Only available when open_insight_mining "
"is true.",
)
parser.add_argument(
"--min_common_dep_num_to_combine",
type=int,
default=-1,
help="The minimum number of common dependencies required to determine whether to merge two operation "
"environment specifications. If set to -1, it means no combination of operation environments, where "
"every OP has its own runtime environment during processing without any merging. If set to >= 0, "
"environments of OPs that share at least min_common_dep_num_to_combine common dependencies will be "
"merged. It will open the operator environment manager to automatically analyze and merge runtime "
"environment for different OPs. It helps different OPs share and reuse the same runtime environment to "
"reduce resource utilization. It's -1 in default. Only available in ray mode. ",
)
parser.add_argument(
"--conflict_resolve_strategy",
type=str,
default="split",
choices=["split", "overwrite", "latest"],
help="Strategy for resolving dependency conflicts, default is 'split' strategy. 'split': Keep the two "
"specs split when there is a conflict. 'overwrite': Overwrite the existing dependency with one "
"from the later OP. 'latest': Use the latest version of all specified dependency versions. "
"Only available when min_common_dep_num_to_combine >= 0.",
)
parser.add_argument(
"--op_fusion",
type=bool,
default=False,
help="Whether to fuse operators that share the same intermediate " # noqa: E251
"variables automatically. Op fusion might reduce the memory "
"requirements slightly but speed up the whole process.",
)
parser.add_argument(
"--fusion_strategy",
type=str,
default="probe",
help='OP fusion strategy. Support ["greedy", "probe"] now. "greedy" ' # noqa: E251
"means keep the basic OP order and put the fused OP to the last "
'of each fused OP group. "probe" means Data-Juicer will probe '
"the running speed for each OP at the beginning and reorder the "
"OPs and fused OPs according to their probed speed (fast to "
'slow). It\'s "probe" in default.',
)
parser.add_argument(
"--adaptive_batch_size",
type=bool,
default=False,
help="Whether to use adaptive batch sizes for each OP according to " # noqa: E251
"the probed results. It's False in default.",
)
parser.add_argument(
"--process",
type=List[Dict],
default=[],
help="List of several operators with their arguments, these ops will " # noqa: E251
"be applied to dataset in order",
)
parser.add_argument(
"--percentiles",
type=List[float],
default=[],
help="Percentiles to analyze the dataset distribution. Only used in " "Analysis.", # noqa: E251
)
parser.add_argument(
"--export_original_dataset",
type=bool,
default=False,
help="whether to export the original dataset with stats. If you only " # noqa: E251
"need the stats of the dataset, setting it to false could speed "
"up the exporting.",
)
parser.add_argument(
"--save_stats_in_one_file",
type=bool,
default=False,
help="Whether to save all stats to only one file. Only used in " "Analysis.",
)
parser.add_argument("--ray_address", type=str, default="auto", help="The address of the Ray cluster.")
# Partitioning configuration for PartitionedRayExecutor
# Support both flat and nested partition configuration
parser.add_argument(
"--partition_size",
type=int,
default=10000,
help="Number of samples per partition for PartitionedRayExecutor (legacy flat config)",
)
parser.add_argument(
"--max_partition_size_mb",
type=int,
default=128,
help="Maximum partition size in MB for PartitionedRayExecutor (legacy flat config)",
)
parser.add_argument(
"--preserve_intermediate_data",
type=bool,
default=False,
help="Preserve intermediate data for debugging (legacy flat config)",
)
# partition configuration
parser.add_argument(
"--partition.mode",
type=str,
default="auto",
choices=["manual", "auto"],
help="Partition mode: manual (specify num_of_partitions) or auto (use partition size optimizer)",
)
parser.add_argument(
"--partition.num_of_partitions",
type=int,
default=4,
help="Number of partitions for manual mode (ignored in auto mode)",
)
parser.add_argument(
"--partition.target_size_mb",
type=int,
default=256,
help="Target partition size in MB for auto mode (128, 256, 512, or 1024). "
"Controls how large each partition should be. Smaller = more checkpoints & better recovery, "
"larger = less overhead. Default 256MB balances memory safety and efficiency.",
)
# Resource optimization configuration
parser.add_argument(
"--resource_optimization.auto_configure",
type=bool,
default=False,
help="Enable automatic optimization of partition size, worker count, and other resource-dependent settings (nested resource_optimization config)",
)
# Intermediate storage configuration
parser.add_argument(
"--intermediate_storage.preserve_intermediate_data",
type=bool,
default=False,
help="Preserve intermediate data for debugging (nested intermediate_storage config)",
)
parser.add_argument(
"--intermediate_storage.cleanup_temp_files",
type=bool,
default=True,
help="Clean up temporary files after processing (nested intermediate_storage config)",
)
parser.add_argument(
"--intermediate_storage.cleanup_on_success",
type=bool,
default=False,
help="Clean up intermediate files even on successful completion (nested intermediate_storage config)",
)
parser.add_argument(
"--intermediate_storage.retention_policy",
type=str,
default="keep_all",
choices=["keep_all", "keep_failed_only", "cleanup_all"],
help="File retention policy (nested intermediate_storage config)",
)
parser.add_argument(
"--intermediate_storage.max_retention_days",
type=int,
default=7,
help="Maximum retention days for files (nested intermediate_storage config)",
)
# Intermediate storage format configuration
parser.add_argument(
"--intermediate_storage.format",
type=str,
default="parquet",
choices=["parquet", "arrow", "jsonl"],
help="Storage format for checkpoints and intermediate data (nested intermediate_storage config)",
)
parser.add_argument(
"--intermediate_storage.compression",
type=str,
default="snappy",
choices=["snappy", "gzip", "none"],
help="Compression format for storage files (nested intermediate_storage config)",
)
parser.add_argument(
"--intermediate_storage.write_partitions",
type=bool,
default=True,
help="Whether to write intermediate partition files to disk (nested intermediate_storage config). Set to false for better performance when intermediate files aren't needed.",
)
parser.add_argument(
"--partition_dir",
type=str,
default=None,
help="Directory to store partition files. Supports {work_dir} placeholder. If not set, defaults to {work_dir}/partitions.",
)
parser.add_argument("--custom-operator-paths", nargs="+", help="Paths to custom operator scripts or directories.")
parser.add_argument("--debug", action="store_true", help="Whether to run in debug mode.")
parser.add_argument(
"--auto_op_parallelism",
type=bool,
default=True,
help="Whether to automatically set operator parallelism.",
)
return parser
def init_configs(args: Optional[List[str]] = None, which_entry: object = None, load_configs_only=False):
"""
initialize the jsonargparse parser and parse configs from one of:
1. POSIX-style commands line args;
2. config files in yaml (json and jsonnet supersets);
3. environment variables
4. hard-coded defaults
:param args: list of params, e.g., ['--config', 'cfg.yaml'], default None.
:param which_entry: which entry to init configs (executor/analyzer)
:param load_configs_only: whether to load the configs only, not including backing up config files, display them, and
setting up logger.
:return: a global cfg object used by the DefaultExecutor or Analyzer
"""
if args is None:
args = sys.argv[1:]
with timing_context("Total config initialization time"):
with timing_context("Initializing parser"):
parser = build_base_parser()
# Filter out non-essential arguments for initial parsing
essential_args = []
if args:
i = 0
while i < len(args):
arg = args[i]
# Handle --help, --config, and --auto in first pass
if arg == "--help":
essential_args.append(arg)
elif arg == "--config":
essential_args.append(arg)
# The next argument must be the config file path
if i + 1 < len(args):
essential_args.append(args[i + 1])
i += 1
elif arg == "--auto":
essential_args.append(arg)
i += 1
# Parse essential arguments first
essential_cfg = parser.parse_args(args=essential_args)
# Now add remaining arguments based on essential config
used_ops = None
if essential_cfg.config:
# Load config file to determine which operators are used
with open(os.path.abspath(essential_cfg.config[0])) as f:
config_data = yaml.safe_load(f)
used_ops = set()
if "process" in config_data:
for op in config_data["process"]:
used_ops.add(list(op.keys())[0])
# Add remaining arguments
ops_sorted_by_types = sort_op_by_types_and_names(OPERATORS.modules.items())
# Only add arguments for used operators
_collect_config_info_from_class_docs(
[(op_name, op_class) for op_name, op_class in ops_sorted_by_types if op_name in used_ops], parser
)
# Parse all arguments
with timing_context("Parsing arguments"):
cfg = parser.parse_args(args=args)
if cfg.executor_type == "ray":
os.environ[RAY_JOB_ENV_VAR] = "1"
if cfg.custom_operator_paths:
load_custom_operators(cfg.custom_operator_paths)
# check the entry
from data_juicer.core.analyzer import Analyzer
if not isinstance(which_entry, Analyzer) and cfg.auto:
err_msg = "--auto argument can only be used for analyzer!"
logger.error(err_msg)
raise NotImplementedError(err_msg)
with timing_context("Initializing setup from config"):
cfg = init_setup_from_cfg(cfg, load_configs_only)
with timing_context("Updating operator process"):
cfg = update_op_process(cfg, parser, used_ops)
# Validate config for resumption if job_id is provided
if not load_configs_only and hasattr(cfg, "job_id") and cfg.job_id:
# Check if this is a resumption attempt by looking for existing job directory
if cfg.work_dir and os.path.exists(cfg.work_dir):
logger.info(f"🔍 Checking for job resumption: {cfg.job_id}")
cfg._same_yaml_config = validate_config_for_resumption(cfg, cfg.work_dir, args)
else:
# New job, set flag to True
cfg._same_yaml_config = True
# copy the config file into the work directory
if not load_configs_only:
config_backup(cfg)
# show the final config tables before the process started
if not load_configs_only:
display_config(cfg)
global global_cfg, global_parser
global_cfg = cfg
global_parser = parser
if cfg.get("debug", False):
logger.debug("In DEBUG mode.")
return cfg
def update_ds_cache_dir_and_related_vars(new_ds_cache_path):
from pathlib import Path
from datasets import config
# update the HF_DATASETS_CACHE
config.HF_DATASETS_CACHE = Path(new_ds_cache_path)
# and two more PATHS that depend on HF_DATASETS_CACHE
# - path to store downloaded datasets (e.g. remote datasets)
config.DEFAULT_DOWNLOADED_DATASETS_PATH = os.path.join(config.HF_DATASETS_CACHE, config.DOWNLOADED_DATASETS_DIR)
config.DOWNLOADED_DATASETS_PATH = Path(config.DEFAULT_DOWNLOADED_DATASETS_PATH)
# - path to store extracted datasets (e.g. xxx.jsonl.zst)
config.DEFAULT_EXTRACTED_DATASETS_PATH = os.path.join(
config.DEFAULT_DOWNLOADED_DATASETS_PATH, config.EXTRACTED_DATASETS_DIR
)
config.EXTRACTED_DATASETS_PATH = Path(config.DEFAULT_EXTRACTED_DATASETS_PATH)
def init_setup_from_cfg(cfg: Namespace, load_configs_only=False):
"""
Do some extra setup tasks after parsing config file or command line.
1. create working directory and logs directory
2. update cache directory
3. update checkpoint and `temp_dir` of tempfile
:param cfg: an original cfg
:param cfg: an updated cfg
"""
# Handle S3 paths differently from local paths
if cfg.export_path.startswith("s3://"):
# For S3 paths, keep as-is (don't use os.path.abspath)
# If work_dir is not provided, use a default local directory for logs/checkpoints
if cfg.work_dir is None:
# Use a default local work directory for S3 exports
# This is where logs, checkpoints, and other local artifacts will be stored
cfg.work_dir = os.path.abspath("./outputs")
logger.info(f"Using default work_dir [{cfg.work_dir}] for S3 export_path [{cfg.export_path}]")
else:
# For local paths, convert to absolute path
cfg.export_path = os.path.abspath(cfg.export_path)
if cfg.work_dir is None:
cfg.work_dir = os.path.dirname(cfg.export_path)
# Call resolve_job_directories to finalize all job-related paths
cfg = resolve_job_id(cfg)
cfg = resolve_job_directories(cfg)
timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
if not load_configs_only:
# For S3 paths, use a simplified export path for log filename
if cfg.export_path.startswith("s3://"):
# Extract bucket and key from S3 path for log filename
s3_path_parts = cfg.export_path.replace("s3://", "").split("/", 1)
export_rel_path = s3_path_parts[1] if len(s3_path_parts) > 1 else s3_path_parts[0]
else:
export_rel_path = os.path.relpath(cfg.export_path, start=cfg.work_dir)
# Ensure event_log_dir (logs/) exists - this is where logs are actually saved
if not os.path.exists(cfg.event_log_dir):
os.makedirs(cfg.event_log_dir, exist_ok=True)
logfile_name = f"export_{export_rel_path}_time_{timestamp}.txt"
setup_logger(
save_dir=cfg.event_log_dir,
filename=logfile_name,
level="DEBUG" if cfg.get("debug", False) else "INFO",
redirect=cfg.get("executor_type", "default") == "default",
)
# check and get dataset dir
if cfg.get("dataset_path", None) and os.path.exists(cfg.dataset_path):
logger.info("dataset_path config is set and a valid local path")
cfg.dataset_path = os.path.abspath(cfg.dataset_path)
elif cfg.get("dataset_path", "") == "" and cfg.get("dataset", None):
logger.info("dataset_path config is empty; dataset is present")
else:
logger.warning(
f"dataset_path [{cfg.get('dataset_path', '')}] is not a valid "
f"local path, AND dataset is not present. "
f"Please check and retry, otherwise we "
f"will treat dataset_path as a remote dataset or a "
f"mixture of several datasets."
)
# check number of processes np
from data_juicer.utils.resource_utils import cpu_count
sys_cpu_count = cpu_count(cfg)
if cfg.get("np", None) and cfg.np > sys_cpu_count:
logger.warning(
f"Number of processes `np` is set as [{cfg.np}], which "
f"is larger than the cpu count [{sys_cpu_count}]. Due "
f"to the data processing of Data-Juicer is a "
f"computation-intensive task, we recommend to set it to"
f" a value <= cpu count. Set it to [{sys_cpu_count}] "
f"here."
)
cfg.np = sys_cpu_count
# whether or not to use cache management
# disabling the cache or using checkpoint explicitly will turn off the
# cache management.
if not cfg.get("use_cache", True) or cfg.get("use_checkpoint", False):
logger.warning("Cache management of datasets is disabled.")
from datasets import disable_caching
disable_caching()
cfg.use_cache = False
# disabled cache compression when cache is disabled
if cfg.cache_compress:
logger.warning("Disable cache compression due to disabled cache.")
cfg.cache_compress = None
# when disabling cache, enable the temp_dir argument
logger.warning(f"Set temp directory to store temp files to " f"[{cfg.temp_dir}].")
import tempfile
if cfg.temp_dir is not None and not os.path.exists(cfg.temp_dir):
os.makedirs(cfg.temp_dir, exist_ok=True)
tempfile.tempdir = cfg.temp_dir
# The checkpoint mode is not compatible with op fusion for now.
if cfg.get("op_fusion", False):
cfg.use_checkpoint = False
cfg.fusion_strategy = cfg.fusion_strategy.lower()
if cfg.fusion_strategy not in FUSION_STRATEGIES:
raise NotImplementedError(
f"Unsupported OP fusion strategy [{cfg.fusion_strategy}]. " f"Should be one of {FUSION_STRATEGIES}."
)
# update huggingface datasets cache directory only when ds_cache_dir is set
from datasets import config
if cfg.get("ds_cache_dir", None) is not None:
logger.warning(
f"Set dataset cache directory to {cfg.ds_cache_dir} "
f"using the ds_cache_dir argument, which is "
f"{config.HF_DATASETS_CACHE} before based on the env "
f"variable HF_DATASETS_CACHE."
)
update_ds_cache_dir_and_related_vars(cfg.ds_cache_dir)
else:
cfg.ds_cache_dir = str(config.HF_DATASETS_CACHE)
# add all filters that produce stats
if cfg.get("auto", False):
cfg.process = load_ops_with_stats_meta()
# Apply text_key modification during initializing configs
# users can freely specify text_key for different ops using `text_key`
# otherwise, set arg text_key of each op to text_keys
cfg.text_keys = cfg.get("text_keys", "text")
if isinstance(cfg.text_keys, list):
text_key = cfg.text_keys[0]
else:
text_key = cfg.text_keys
SpecialTokens.image = cfg.get("image_special_token", SpecialTokens.image)
SpecialTokens.audio = cfg.get("audio_special_token", SpecialTokens.audio)
SpecialTokens.video = cfg.get("video_special_token", SpecialTokens.video)
SpecialTokens.eoc = cfg.get("eoc_special_token", SpecialTokens.eoc)
op_attrs = {
"text_key": text_key,
"image_key": cfg.get("image_key", "images"),
"audio_key": cfg.get("audio_key", "audios"),
"video_key": cfg.get("video_key", "videos"),
"image_bytes_key": cfg.get("image_bytes_key", "image_bytes"),
"turbo": cfg.get("turbo", False),
"skip_op_error": cfg.get("skip_op_error", True),
"auto_op_parallelism": cfg.get("auto_op_parallelism", True),
"work_dir": cfg.work_dir,