-
Notifications
You must be signed in to change notification settings - Fork 38
/
step.py
2485 lines (2256 loc) · 97.5 KB
/
step.py
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 json
import logging
import os
import shutil
import sys
import warnings
from collections import defaultdict
from collections.abc import Iterable
from datetime import datetime
from functools import cached_property, partial
from importlib import metadata
from io import BytesIO
from logging import Logger
from time import time
from typing import Any, Callable, DefaultDict, Sequence, cast
import dill
from datasets import Dataset, DatasetDict
from datasets.fingerprint import Hasher
from filelock import FileLock, Timeout
from pandas import DataFrame
from .. import __version__, logging as datadreamer_logging
from .._cachable import _Cachable
from ..datadreamer import DataDreamer
from ..datasets import (
OutputDataset,
OutputDatasetColumn,
OutputIterableDataset,
OutputIterableDatasetColumn,
)
from ..errors import StepOutputError
from ..logging import DATEFMT, logger
from ..pickling import unpickle as _unpickle
from ..pickling.pickle import _INTERNAL_PICKLE_KEY, _pickle
from ..project.environment import RUNNING_IN_PYTEST
from ..utils.arg_utils import DEFAULT, Default
from ..utils.background_utils import run_in_background_process_no_block
from ..utils.collection_utils import uniq_str
from ..utils.fingerprint_utils import stable_fingerprint
from ..utils.fs_utils import move_dir, safe_fn
from ..utils.hf_hub_utils import get_readme_contents, hf_hub_login, prepare_to_publish
from ..utils.time_utils import progress_eta
from .data_card import DataCardType, sort_data_card
from .step_background import wait
from .step_export import _path_to_split_paths, _unpickle_export
from .step_operations import (
_INTERNAL_STEP_OPERATION_KEY,
_INTERNAL_STEP_OPERATION_NO_SAVE_KEY,
__concatenate,
_create_add_item_step,
_create_copy_step,
_create_filter_step,
_create_map_step,
_create_remove_columns_step,
_create_rename_column_step,
_create_rename_columns_step,
_create_reverse_step,
_create_save_step,
_create_select_columns_step,
_create_select_step,
_create_shard_step,
_create_shuffle_step,
_create_skip_step,
_create_sort_step,
_create_splits_step,
_create_take_step,
_step_to_dataset_dict,
)
from .step_output import (
LazyRowBatches,
LazyRows,
StepOutputType,
_monkey_patch_iterable_dataset_apply_feature_types,
_output_to_dataset,
)
_INTERNAL_HELP_KEY = "__DataDreamer__help__"
_INTERNAL_TEST_KEY = "__DataDreamer__test__"
class StepMeta(type):
has_base = False
def __new__(meta, name, bases, attrs):
if meta.has_base:
for attribute in attrs:
is_data_source = (
name == "DataSource"
and attrs["__module__"].endswith("steps.data_sources.data_source")
) or (
len(bases) > 0
and bases[0].__module__.endswith("steps.data_sources.data_source")
)
if attribute == "__init__" and not is_data_source:
raise AttributeError(
'Overriding of "%s" not allowed, override setup() instead.'
% attribute
)
meta.has_base = True
klass = super().__new__(meta, name, bases, attrs)
return klass
@property
def help(self) -> str:
if self.__name__.endswith("DataSource"): # pragma: no cover
return "No help string available."
if not hasattr(self, ".__help_str__"):
class StepHelp(self): # type:ignore[valid-type,misc]
pass
StepHelp.__name__ = self.__name__
StepHelp.__qualname__ = self.__name__
setattr(StepHelp, _INTERNAL_HELP_KEY, True)
help_step = StepHelp(name="help_step")
self.__help_str__ = help_step.help
return self.__help_str__
class Step(metaclass=StepMeta):
"""Base class for all steps.
Args:
name: The name of the step.
inputs: The inputs to the step.
args: The args to the step.
outputs: The name mapping to rename outputs produced by the step.
progress_interval: How often to log progress in seconds.
force: Whether to force run the step (ignore saved results).
verbose: Whether or not to print verbose logs.
log_level: The logging level to use (:py:data:`~logging.DEBUG`, :py:data:`~logging.INFO`, etc.).
save_num_proc: The number of processes to use if saving to disk.
save_num_shards: The number of shards on disk to save the dataset into.
background: Whether to run the operation in the background.
"""
def __init__( # noqa: C901
self,
name: str,
inputs: None
| dict[str, OutputDatasetColumn | OutputIterableDatasetColumn] = None,
args: None | dict[str, Any] = None,
outputs: None | dict[str, str] = None,
progress_interval: None | int = 60,
force: bool = False,
verbose: None | bool = None,
log_level: None | int = None,
save_num_proc: None | int = None,
save_num_shards: None | int = None,
background: bool = False,
):
# Get the cls_name
cls_name = self.__class__.__name__
# Check pid
if DataDreamer.is_background_process(): # pragma: no cover
raise RuntimeError(
f"Steps must be initialized in the same process"
f" ({os.getpid()}) as the DataDreamer() context manager"
f" ({DataDreamer.ctx.pid}). Use background=True if you want to"
" run this step in a background process."
)
# Check thread
if not DataDreamer.is_registered_thread(): # pragma: no cover
raise RuntimeError(
"Steps cannot be run in arbitrary threads. Use the"
" concurrent() utility function to run concurrently."
)
# Fill in default argument valu]es
if not isinstance(args, dict):
args = {}
if not isinstance(inputs, dict):
inputs = {}
if not isinstance(outputs, dict):
outputs = {}
assert args is not None
assert inputs is not None
assert outputs is not None
# Initialize variables
self._initialized: bool = False
self._resumed: bool = False
self.name: str = DataDreamer._new_step_name(name)
if len(self.name) == 0:
raise ValueError("You must provide a name for the step.")
self.__progress: None | float = None
self.__progress_rows: None | int = None
self.__progress_logging_rows: bool = False
self.__progress_logged: bool = False
self.progress_interval: None | int = progress_interval
self.progress_start = time()
self.progress_last = time()
self.__output: None | OutputDataset | OutputIterableDataset = None
self._pickled: bool = False
self.__registered: dict[str, Any] = {
"args": {},
"required_args": {},
"inputs": {},
"required_inputs": {},
"outputs": [],
"data_card": defaultdict(lambda: defaultdict(list)),
}
self.output_name_mapping = {}
self.__help: dict[str, Any] = {"args": {}, "inputs": {}, "outputs": {}}
self.force: bool
self.force = force or (
DataDreamer.initialized()
and DataDreamer._get_parent_step() is not None
and cast(Step, DataDreamer._get_parent_step()).force
)
self.save_num_proc = save_num_proc
self.save_num_shards = save_num_shards
self._orig_background = background
self.background = background if not isinstance(self, SuperStep) else False
# Initialize the logger
self.verbose = verbose
self.log_level = log_level
self.logger: Logger
if not hasattr(self.__class__, _INTERNAL_HELP_KEY):
stderr_handler = logging.StreamHandler()
stderr_handler.setLevel(logging.NOTSET)
self.logger = logging.getLogger(
f"datadreamer.steps.{safe_fn(self.name, allow_slashes=True, to_lower=True)}"
)
if RUNNING_IN_PYTEST:
self.logger.propagate = True
else:
self.logger.propagate = False # pragma: no cover
log_format: str = (
logger.handlers[0].formatter and logger.handlers[0].formatter._fmt
) or datadreamer_logging.STANDARD_FORMAT
log_format = log_format.replace(
"%(message)s", f"[ ➡️ {self.name}] %(message)s"
)
formatter = logging.Formatter(log_format, datefmt=DATEFMT, validate=False)
stderr_handler.setFormatter(formatter)
self.logger.handlers.clear()
self.logger.addHandler(stderr_handler)
effective_level = logger.level if self.log_level is None else self.log_level
if self.verbose:
self.logger.setLevel((min(logging.DEBUG, effective_level)))
elif self.verbose is False:
self.logger.setLevel(logging.CRITICAL + 1)
else:
self.logger.setLevel(effective_level)
# Run setup
self.setup()
if hasattr(self.__class__, _INTERNAL_HELP_KEY):
return
self._initialized = True
# Validate and setup args
if (
not set(args.keys()).issubset(set(self.__registered["args"].keys()))
and "**kwargs" not in self.__registered["args"]
) or not set(self.__registered["required_args"].keys()).issubset(
set(args.keys())
):
raise ValueError(
f"Expected {uniq_str(self.__registered['args'].keys())} as args,"
f" with {uniq_str(self.__registered['required_args'].keys())} required,"
f" got {uniq_str(args.keys())}. See `{cls_name}.help`:\n{self.help}"
)
else:
self.__registered["args"].update(args)
if "**kwargs" in self.__registered["args"]:
del self.__registered["args"]["**kwargs"]
# Validate and setup inputs
if (
not set(inputs.keys()).issubset(set(self.__registered["inputs"].keys()))
or not set(self.__registered["required_inputs"].keys()).issubset(
set(inputs.keys())
)
) and not hasattr(self.__class__, _INTERNAL_STEP_OPERATION_KEY):
raise ValueError(
f"Expected {uniq_str(self.__registered['inputs'].keys())} as inputs,"
f" with {uniq_str(self.__registered['required_inputs'].keys())} required,"
f" got {uniq_str(inputs.keys())}. See `{cls_name}.help`:\n{self.help}"
)
elif not all(
[
isinstance(
v, (OutputDatasetColumn, OutputIterableDatasetColumn, type(None))
)
for v in inputs.values()
]
):
raise TypeError(
"All inputs must be of type OutputDatasetColumn or"
" OutputIterableDatasetColumn."
)
else:
self.__registered["inputs"] = inputs
# Propagate trace info from previous steps
prev_data_card: DefaultDict[str, DefaultDict[str, list]] = defaultdict(
lambda: defaultdict(list)
)
for v in inputs.values():
if v is not None:
prev_data_card.update(v.step._data_card)
prev_data_card.update(self.__registered["data_card"])
self.__registered["data_card"] = prev_data_card
# Initialize output names mapping
if len(self.__registered["outputs"]) == 0 and not hasattr(
self.__class__, _INTERNAL_STEP_OPERATION_KEY
):
raise ValueError("The step must register at least one output.")
if not set(outputs.keys()).issubset(
set(self.__registered["outputs"])
) and not hasattr(self.__class__, _INTERNAL_STEP_OPERATION_KEY):
raise ValueError(
f"{cls_name} only defines {uniq_str(self.__registered['outputs'])} as"
f" outputs, got {uniq_str(outputs.keys())}."
f" See `{cls_name}.help`:\n{self.help}"
)
output_names = (
(outputs or {}).keys()
if hasattr(self.__class__, _INTERNAL_STEP_OPERATION_KEY)
else self.__registered["outputs"]
)
self.output_name_mapping = {o: outputs.get(o, o) for o in output_names}
self.output_names = tuple([self.output_name_mapping[o] for o in output_names])
# Run (or resume) within the DataDreamer context
self._output_folder_path: None | str = None
if DataDreamer.initialized():
DataDreamer._start_step(self)
try:
self.__setup_folder_and_resume()
finally:
DataDreamer._stop_step()
if hasattr(self, "_lock"):
self._lock.release()
def __setup_folder_and_resume(self):
if DataDreamer.is_running_in_memory():
self.__start()
return
# Create an output folder for the step
self._output_folder_path = os.path.join(
DataDreamer.get_output_folder_path(),
safe_fn(self.name, allow_slashes=True, to_lower=True),
)
os.makedirs(self._output_folder_path, exist_ok=True)
assert self._output_folder_path is not None
# Lock working on the step
step_lock_path = os.path.join(self._output_folder_path, "._dataset.flock")
self._lock = FileLock(step_lock_path)
try:
self._lock.acquire(timeout=60)
self._lock.release()
except Timeout: # pragma: no cover
logger.info(
f"Step '{self.name}' is being run in two different processes or"
" threads concurrently. Waiting for others to finish before"
" continuing here..."
)
finally:
self._lock.acquire()
# Check if we have already run this step previously and saved the results to
# disk
metadata_path = os.path.join(self._output_folder_path, "step.json")
dataset_path = os.path.join(self._output_folder_path, "_dataset")
prev_fingerprint: None | str = None
try:
with open(metadata_path, "r") as f:
metadata = json.load(f)
prev_fingerprint = metadata["fingerprint"]
except FileNotFoundError:
pass
# We have already run this step, skip running it
if prev_fingerprint == self.fingerprint and not self.force:
self.__output = OutputDataset(
self, Dataset.load_from_disk(dataset_path), pickled=metadata["pickled"]
)
self.progress = 1.0
self._pickled = metadata["pickled"]
self.__registered["data_card"].update(metadata["data_card"])
self._resumed = True
logger.info(
f"Step '{self.name}' results loaded from disk. 🙌 It was previously run"
" and saved."
)
# Skip running it
return
# We have already run this step, but it is outdated, back up the results
if prev_fingerprint is not None and (
prev_fingerprint != self.fingerprint or self.force
):
# ...but it was a different version, backup the results and we'll need
# to re-run this step
logger.info(
f"Step '{self.name}' was previously run and saved, but was outdated. 😞"
)
backup_path = os.path.join(
DataDreamer.get_output_folder_path(),
"_backups",
safe_fn(self.name, allow_slashes=True, to_lower=True),
prev_fingerprint,
)
logger.debug(
f"Step '{self.name}' outdated results are being backed up: {backup_path}"
)
move_dir(self._output_folder_path, backup_path)
logger.debug(
f"Step '{self.name}' outdated results are backed up: {backup_path}"
)
# Check if we have old results for this step that can be restored
restore_path = os.path.join(
DataDreamer.get_output_folder_path(),
"_backups",
safe_fn(self.name, allow_slashes=True, to_lower=True),
self.fingerprint,
)
if os.path.isfile(os.path.join(restore_path, "step.json")) and not self.force:
logger.info(
f"Step '{self.name}' was previously run and the results were backed up. 💾"
)
logger.debug(
f"Step '{self.name}' backed up results are being restored: {restore_path}"
)
move_dir(restore_path, self._output_folder_path)
logger.debug(f"Step '{self.name}' backed up results were restored.")
self.__setup_folder_and_resume() # Retry loading
return
# Run the step
self.__start()
def __start(self):
if self.background:
logger.info(f"Step '{self.name}' is running in the background. ⏳")
self._set_output(None, background_run_func=lambda: self.run())
else:
logger.info(f"Step '{self.name}' is running. ⏳")
if not hasattr(self.__class__, _INTERNAL_TEST_KEY):
self._set_output(self.run())
def __finish(self):
if DataDreamer.is_background_process(): # pragma: no cover
return
if isinstance(self.__output, OutputDataset) and hasattr(
self.__class__, _INTERNAL_STEP_OPERATION_NO_SAVE_KEY
):
self.__delete_progress_from_disk()
logger.info(f"Step '{self.name}' finished running lazily. 🎉")
elif isinstance(self.__output, OutputIterableDataset) or hasattr(
self.__class__, _INTERNAL_STEP_OPERATION_NO_SAVE_KEY
):
self.__delete_progress_from_disk()
logger.info(f"Step '{self.name}' will run lazily. 🥱")
elif not self._output_folder_path:
self.progress = 1.0
self.__delete_progress_from_disk()
logger.info(
f"Step '{self.name}' finished with results available in-memory. 🎉"
)
elif isinstance(self.__output, OutputDataset) and not hasattr(
self.__class__, _INTERNAL_STEP_OPERATION_NO_SAVE_KEY
):
if not self.background:
self.__save_output_to_disk(self.__output)
self.progress = 1.0
self.__delete_progress_from_disk()
self.__delete_save_cache_from_disk()
logger.info(f"Step '{self.name}' finished and is saved to disk. 🎉")
# Set output_names and output_name_mapping if step operation
if hasattr(self.__class__, _INTERNAL_STEP_OPERATION_KEY) and self.__output:
self.output_name_mapping = {n: n for n in self.__output.column_names}
self.output_names = tuple([o for o in self.output_name_mapping.values()])
# Propagate trace info to parent steps
if DataDreamer.initialized():
parent_step = DataDreamer._get_parent_step()
if isinstance(parent_step, Step):
parent_step.__registered["data_card"].update(self._data_card)
def __save_output_to_disk(self, output: OutputDataset):
if not self._output_folder_path: # pragma: no cover
return
logger.debug(
f"Step '{self.name}' is being saved to disk: {self._output_folder_path}."
)
metadata_path = os.path.join(self._output_folder_path, "step.json")
dataset_path = os.path.join(self._output_folder_path, "_dataset")
if self.save_num_shards and self.save_num_shards > 1:
DataDreamer._enable_hf_datasets_logging()
output.save_to_disk(
dataset_path, num_proc=self.save_num_proc, num_shards=self.save_num_shards
)
DataDreamer._disable_hf_datasets_logging()
with open(metadata_path, "w+") as f:
json.dump(self._get_metadata(output), f, indent=4)
logger.debug(
f"Step '{self.name}' is now saved to disk: {self._output_folder_path}."
)
def register_input(
self, input_column_name: str, required: bool = True, help: None | str = None
):
"""Register an input for the step. See :doc:`create your own steps
<pages/advanced_usage/creating_a_new_datadreamer_.../step>` for more details.
Args:
input_column_name: The name of the input column.
required: Whether the input is required.
help: The help string for the input.
"""
if self._initialized:
raise RuntimeError(
"The step is already initialized, you can only run"
" .register_xxx() functions in the setup() method."
)
if not isinstance(input_column_name, str):
raise TypeError(f"Expected str, got {type(input_column_name)}.")
if required:
self.__registered["required_inputs"][input_column_name] = None
self.__registered["inputs"][input_column_name] = None
help_optional = "(optional)"
if not required:
self.__help["inputs"][input_column_name] = (
(help or "") + " " + help_optional
).strip()
else:
self.__help["inputs"][input_column_name] = help
def register_arg(
self,
arg_name: str,
required: bool = True,
default: Any = None,
help: None | str = None,
default_help: None | str = None,
):
"""Register an argument for the step. See :doc:`create your own steps
<pages/advanced_usage/creating_a_new_datadreamer_.../step>` for more details.
Args:
arg_name: The name of the argument.
required: Whether the argument is required.
default: The default value of the argument.
help: The help string for the argument.
default_help: The help string for the default value of the argument.
"""
if self._initialized:
raise RuntimeError(
"The step is already initialized, you can only run"
" .register_xxx() functions in the setup() method."
)
if not isinstance(arg_name, str):
raise TypeError(f"Expected str, got {type(arg_name)}.")
assert (
default is None or not required
), f"`default` cannot be set if arg `{arg_name}` is required."
if required and arg_name != "**kwargs":
self.__registered["required_args"][arg_name] = None
self.__registered["args"][arg_name] = self.__registered["args"][arg_name] = (
{} if arg_name == "**kwargs" else default
)
help_optional = ""
if arg_name == "**kwargs" or (default is None and default_help is None):
help_optional = "(optional)"
else:
help_optional = f"(optional, defaults to {repr(default) if default_help is None else default_help})"
if not required:
self.__help["args"][arg_name] = ((help or "") + " " + help_optional).strip()
else:
self.__help["args"][arg_name] = help
def register_output(self, output_column_name: str, help: None | str = None):
"""Register an output for the step. See :doc:`create your own steps
<pages/advanced_usage/creating_a_new_datadreamer_.../step>` for more details.
Args:
output_column_name: The name of the output column.
help: The help string for the output.
"""
if self._initialized:
raise RuntimeError(
"The step is already initialized, you can only run"
" .register_xxx() functions in the setup() method."
)
if not isinstance(output_column_name, str):
raise TypeError(f"Expected str, got {type(output_column_name)}.")
if output_column_name not in self.__registered["outputs"]:
self.__registered["outputs"].append(output_column_name)
self.__help["outputs"][output_column_name] = help
def register_data_card(self, data_card_type: str, data_card: Any):
"""Register a data card for the step. See :doc:`create your own steps
<pages/advanced_usage/creating_a_new_datadreamer_.../step>` for more details.
Args:
data_card_type: The type of the data card.
data_card: The data card.
"""
if not isinstance(data_card_type, str):
raise TypeError(f"Expected str, got {type(data_card_type)}.")
if data_card is not None:
self.__registered["data_card"][self.name][data_card_type].append(data_card)
@property
def args(self) -> dict[str, Any]:
"""The args of the step."""
return self.__registered["args"].copy()
@property
def inputs(self) -> dict[str, OutputDatasetColumn | OutputIterableDatasetColumn]:
"""The inputs of the step."""
return self.__registered["inputs"].copy()
def setup(self):
if "SPHINX_BUILD" not in os.environ:
raise NotImplementedError("You must implement the .setup() method in Step.")
def run(self) -> StepOutputType | LazyRows | LazyRowBatches:
if "SPHINX_BUILD" not in os.environ:
raise NotImplementedError("You must implement the .run() method in Step.")
else: # pragma: no cover
return None
def get_run_output_folder_path(self) -> str:
"""Get the run output folder path that can be used by the step for writing
persistent data."""
if not self._output_folder_path:
if not DataDreamer.initialized(): # pragma: no cover
raise RuntimeError("You must run the Step in a DataDreamer() context.")
else:
raise RuntimeError(
"No run output folder available. DataDreamer is running in-memory."
)
run_output_folder_path = os.path.join(self._output_folder_path, "run_output")
os.makedirs(run_output_folder_path, exist_ok=True)
return run_output_folder_path
def pickle(self, value: Any, *args: Any, **kwargs: Any) -> bytes:
"""Pickle a value so it can be stored in a row produced by this step. See
:doc:`create your own steps
<pages/advanced_usage/creating_a_new_datadreamer_.../step>` for more details.
Args:
value: The value to pickle.
*args: The args to pass to :py:meth:`~dill.dumps`.
**kwargs: The kwargs to pass to :py:meth:`~dill.dumps`.
"""
self._pickled = True
if self.__output:
self.output._pickled = True
kwargs[_INTERNAL_PICKLE_KEY] = True
return _pickle(value, *args, **kwargs)
def unpickle(self, value: bytes) -> Any:
"""Unpickle a value that was stored in a row produced by this step with
:py:meth:`~Step.pickle`. See :doc:`create your own steps
<pages/advanced_usage/creating_a_new_datadreamer_.../step>` for more details.
Args:
value: The value to unpickle.
"""
return _unpickle(value)
def __write_progress_to_disk(self):
# Write the progress to disk in the child process to share with the parent
if (
self.background
and DataDreamer.is_background_process()
and self._output_folder_path
): # pragma: no cover
background_progress_path = os.path.join(
self._output_folder_path, ".background_progress"
)
try:
with open(background_progress_path, "w+") as f:
json.dump(
{
"progress": self.__progress,
"progress_rows": self.__progress_rows,
},
f,
indent=4,
)
except Exception:
pass
def __read_progress_from_disk(self):
# Read the progress from the disk in the parent process
if (
self.__progress != 1.0
and self.background
and not DataDreamer.is_background_process()
and self._output_folder_path
):
background_progress_path = os.path.join(
self._output_folder_path, ".background_progress"
)
try:
with open(background_progress_path, "r") as f:
progress_data = json.load(f)
if progress_data.get("progress", None) is not None:
self.__progress = max(
progress_data["progress"], self.__progress or 0.0
)
if progress_data.get("progress_rows", None) is not None:
self.__progress_rows = max(
progress_data["progress_rows"], self.__progress_rows or 0
)
except Exception:
pass
def __delete_progress_from_disk(self):
# Delete the progress from the disk once done
if (
self._output_folder_path
and self.background
and not DataDreamer.is_background_process()
):
background_progress_path = os.path.join(
self._output_folder_path, ".background_progress"
)
try:
os.remove(background_progress_path)
except Exception:
pass
def __delete_save_cache_from_disk(self):
# Delete the save cache from the disk once done
if self._output_folder_path:
save_cache_path = os.path.join(
self._output_folder_path, ".datadreamer_save_cache"
)
if os.path.isdir(save_cache_path):
shutil.rmtree(save_cache_path, ignore_errors=True)
@property
def progress(self) -> None | float:
"""The progress of the step."""
self.__read_progress_from_disk()
return self.__progress
@progress.setter
def progress(self, value: float):
prev_progress = self.__progress or 0.0
if isinstance(self.__output, OutputDataset):
value = 1.0
value = max(min(value, 1.0), prev_progress)
should_log = False
if (
(self.__progress_logged or value < 1.0)
and self.progress_interval is not None
and (time() - self.progress_last) > self.progress_interval
and value > prev_progress
and (not self.__progress_logging_rows or value < 1.0)
):
should_log = True
self.progress_last = time()
self.__progress_logged = True
self.__progress = value
if should_log:
eta = progress_eta(self.__progress, self.progress_start)
logger.info(
f"Step '{self.name}' progress:"
f" {self.__get_progress_string()} 🔄 {eta}"
)
self.__write_progress_to_disk()
if (
self.__progress == 1.0
and self.__progress > prev_progress
and isinstance(self.__output, OutputIterableDataset)
):
logger.info(f"Step '{self.name}' finished running lazily. 🎉")
def _set_progress_rows(self, value: int):
value = max(value, self.__progress_rows or 0)
should_log = False
if (
not self.progress
and self.progress_interval is not None
and (time() - self.progress_last) > self.progress_interval
and value > 0
and value > (self.__progress_rows or 0)
):
should_log = True
self.__progress_logging_rows = True
self.progress_last = time()
self.__progress_logged = True
self.__progress_rows = value
if should_log:
logger.info(
f"Step '{self.name}' progress:" f" {self.__progress_rows} row(s) 🔄"
)
self.__write_progress_to_disk()
def __get_progress_string(self):
if not self.progress and self.__progress_rows:
return f"{self.__progress_rows} row(s) processed"
elif self.progress is not None:
progress_int = int(self.progress * 100)
return f"{progress_int}%"
else:
return "0%"
@property
def output(self) -> OutputDataset | OutputIterableDataset:
"""The output dataset of the step."""
if self.__output is None:
if self.__progress is None and not self.background:
raise StepOutputError("Step has not been run. Output is not available.")
elif self.background:
raise StepOutputError(
f"Step is still running in the background"
f" ({self.__get_progress_string()})."
" Output is not available yet. To wait for this step to finish, you"
" can use the wait() utility function."
)
else:
raise StepOutputError(
f"Step is still running ({self.__get_progress_string()})."
" Output is not available yet."
)
else:
return self.__output
@property
def dataset_path(self) -> str:
"""The path to the step's output dataset on disk in HuggingFace
:py:class:`~datasets.Dataset` format if the step has been saved to disk.
"""
assert not DataDreamer.is_running_in_memory(), (
"This step's dataset has not been saved to disk. DataDreamer is running"
" in-memory."
)
if isinstance(self.output, OutputIterableDataset):
raise RuntimeError(
"This step's dataset has not been saved to disk yet."
" Use `.save()` on the step to first save it to disk."
)
else:
return os.path.join(cast(str, self._output_folder_path), "_dataset")
def _set_output( # noqa: C901
self,
value: StepOutputType | LazyRows | LazyRowBatches,
background_run_func: None | Callable = None,
):
if self.__output:
raise StepOutputError("Step has already been run.")
logger.debug(f"Step '{self.name}' results are being processed.")
if background_run_func:
_monkey_patch_iterable_dataset_apply_feature_types()
def with_result_process(process):
DataDreamer._add_process(process)
def with_result(self, output):
data_card, self.__output = dill.loads(output)
self.__registered["data_card"].update(data_card)
self.__finish()
run_in_background_process_no_block(
_output_to_dataset,
result_process_func=with_result_process,
result_func=partial(with_result, self),
step=self,
output_names=tuple(self.__registered["outputs"]),
output_name_mapping=self.output_name_mapping,
set_progress=partial(
lambda self, progress: setattr(self, "progress", progress), self
),
set_progress_rows=partial(
lambda self, rows: self._set_progress_rows(rows), self
),
get_pickled=partial(lambda self: self._pickled, self),
value=background_run_func,
save_output_to_disk=partial(
lambda self, output: self.__save_output_to_disk(output), self
),
)
else:
self.__output = _output_to_dataset(
pipe=None,
step=self,
output_names=tuple(self.__registered["outputs"]),
output_name_mapping=self.output_name_mapping,
set_progress=partial(
lambda self, progress: setattr(self, "progress", progress), self
),
set_progress_rows=partial(
lambda self, rows: self._set_progress_rows(rows), self
),
get_pickled=partial(lambda self: self._pickled, self),
value=value,
save_output_to_disk=partial(
lambda self, output: self.__save_output_to_disk(output), self
),
)
self.__finish()
def head(self, n=5, shuffle=False, seed=None, buffer_size=1000) -> DataFrame:
"""Return the first ``n`` rows of the step's output as a pandas
:py:class:`~pandas.DataFrame` for easy viewing.
Args:
n: The number of rows to return.
shuffle: Whether to shuffle the rows before taking the first ``n``.
seed: The seed to use if shuffling.
buffer_size: The buffer size to use if shuffling and the step's output is
an iterable dataset.
"""
return self.output.head(
n=n, shuffle=shuffle, seed=seed, buffer_size=buffer_size
)
@property
def _data_card(self) -> dict:
data_card = self.__registered["data_card"]
if DataCardType.DATETIME not in data_card[self.name]:
data_card[self.name][DataCardType.DATETIME] = datetime.now().isoformat()
data_card = self.__registered["data_card"].copy()
for step_name in data_card:
sort_data_card(data_card[step_name])
return json.loads(json.dumps(data_card))
def data_card(self) -> None:
"""Print the data card for the step."""
print(json.dumps(self._data_card, indent=4))
def select(
self,
indices: Iterable,
name: None | str = None,
lazy: bool = True,
progress_interval: None | int | Default = DEFAULT,
force: bool = False,
writer_batch_size: None | int = 1000,
save_num_proc: None | int | Default = DEFAULT,
save_num_shards: None | int | Default = DEFAULT,
background: bool = False,
) -> "Step":
"""Select rows from the step's output by their indices. See
:py:meth:`~datasets.Dataset.select` for more details.
Args:
indices: The indices of the rows to select.
name: The name of the operation.
lazy: Whether to run the operation lazily.
progress_interval: How often to log progress in seconds.
force: Whether to force run the step (ignore saved results).
writer_batch_size: The batch size to use if saving to disk.
save_num_proc: The number of processes to use if saving to disk.
save_num_shards: The number of shards on disk to save the dataset into.
background: Whether to run the operation in the background.
Returns:
A new step with the operation applied.
"""
kwargs = dict(locals())
kwargs["step"] = self
del kwargs["self"]
return partial(_create_select_step, **kwargs)()
def select_columns(
self,
column_names: str | list[str],
name: None | str = None,
lazy: bool = True,
progress_interval: None | int | Default = DEFAULT,
force: bool = False,
writer_batch_size: None | int = 1000,
save_num_proc: None | int | Default = DEFAULT,
save_num_shards: None | int | Default = DEFAULT,
background: bool = False,
) -> "Step":
"""Select columns from the step's output. See
:py:meth:`~datasets.Dataset.select_columns` for more details.
Args:
column_names: The names of the columns to select.
name: The name of the operation.
lazy: Whether to run the operation lazily.
progress_interval: How often to log progress in seconds.
force: Whether to force run the step (ignore saved results).
writer_batch_size: The batch size to use if saving to disk.
save_num_proc: The number of processes to use if saving to disk.
save_num_shards: The number of shards on disk to save the dataset into.
background: Whether to run the operation in the background.