data_juicer.core#

class data_juicer.core.Adapter(cfg: Namespace)[source]#

Bases: object

MAX_BATCH_SIZE = 10000#
__init__(cfg: Namespace)[source]#
static execute_and_probe(dataset, operators, sample_interval=0.5)[source]#

Process the input dataset and probe related information for each OP in the specified operator list.

For now, we support the following targets to probe: “resource”: resource utilization for each OP. “speed”: average processing speed for each OP.

The probe result is a list and each item in the list is the probe result for each OP.

static take_batch(dataset, config)[source]#

Split the dataset into batches based on configuration and load factor.

Parameters:
  • dataset – The dataset to be split

  • config – Configuration settings, including batch size

Returns:

An iterator of batches

adapt_workloads(dataset, operators)[source]#

Manage the scheduling and load balancing for the dataset processing.

Parameters:
  • dataset – The dataset that needs to be processed

  • operators – Operators in the data recipe

probe_small_batch(dataset, operators)[source]#

Perform small batch pre-execution to probe available resources, current load and estimated OP speed, returning load factors and speed ranks for each OP.

Notice: the probe should be run with cache enabled to avoid removing the cache files of the input dataset.

Parameters:
  • dataset – The dataset to pre-execute small batch on

  • operators – The OP list to be pre-execution and probe

Returns:

A list of probe results for each OP and the length of data batch to probe.

batch_size_strategy(load_analysis_res, base_bs=1, util_th=0.9)[source]#

Decide the batch size for each op according to their workload analysis result and expected utilization threshold. We need to guarantee that the resource utilization won’t exceed the threshold. Now we only consider the buckets effect, which means the max batch size is decided by the max utilization of all types of resources except GPU util (decided by num_proc).

analyze_small_batch(dataset, current_state)[source]#

Perform small batch analysis to probe the current OP-wise stats/meta distributions. The analyzed results will be stored in the directory {work_dir}/insight_mining.

Notice: the probe should be run with cache enabled to avoid removing the cache files of the input dataset.

Parameters:
  • dataset – The dataset to analyze small batch on

  • current_state – A string to indicate the current state of the input dataset. It usually consists of a number of the index of the OP processed just now and the OP name, e.g. “1_text_length_filter”.

insight_mining(pval_th=0.05)[source]#

Mining the insights from the OP-wise analysis results. For now, we use T-Test to check the significance of stats/meta changes before and after each OP processing. If the p-value is less than a given threshold (usually 0.05), we think the stats/meta changes are significant. The insight mining results will be stored in the file {work_dir}/insight_mining/insight_mining.json.

Parameters:

pval_th – the threshold of p-value.

class data_juicer.core.Analyzer(cfg: Namespace | None = None)[source]#

Bases: object

This Analyzer class is used to analyze a specific dataset.

It will compute stats for all filter ops in the config file, apply multiple analysis (e.g. OverallAnalysis, ColumnWiseAnalysis, etc.) on these stats, and generate the analysis results (stats tables, distribution figures, etc.) to help users understand the input dataset better.

__init__(cfg: Namespace | None = None)[source]#

Initialization method.

Parameters:

cfg – optional jsonargparse Namespace dict.

run(dataset: Dataset | NestedDataset = None, load_data_np: Annotated[int, Gt(gt=0)] | None = None, skip_export: bool = False, skip_return: bool = False)[source]#

Running the dataset analysis pipeline.

Parameters:
  • dataset – a Dataset object to be analyzed.

  • load_data_np – number of workers when loading the dataset.

  • skip_export – whether export the results into disk

  • skip_return – skip return for API called.

Returns:

analyzed dataset.

class data_juicer.core.NestedDataset(*args, **kargs)[source]#

Bases: Dataset, DJDataset

Enhanced HuggingFace-Dataset for better usability and efficiency.

__init__(*args, **kargs)[source]#
schema() Schema[source]#

Get dataset schema.

get(k: int) List[Dict[str, Any]][source]#

Get k rows from the dataset.

get_column(column: str, k: int | None = None) List[Any][source]#

Get column values from HuggingFace dataset.

Parameters:
  • column – Name of the column to retrieve

  • k – Optional number of rows to return. If None, returns all rows

Returns:

List of values from the specified column

Raises:
  • KeyError – If column doesn’t exist

  • ValueError – If k is negative

process(operators, *, work_dir=None, exporter=None, checkpointer=None, tracer=None, adapter=None, open_monitor=True)[source]#

process a list of operators on the dataset.

count() int[source]#

return the count of the dataset

update_args(args, kargs, is_filter=False)[source]#
map(*args, **kargs)[source]#

Override the map func, which is called by most common operations, such that the processed samples can be accessed by nested manner.

filter(*args, **kargs)[source]#

Override the filter func, which is called by most common operations, such that the processed samples can be accessed by nested manner.

select(*args, **kargs)[source]#

Override the select func, such that selected samples can be accessed by nested manner.

to_list() list[source]#

Returns the dataset as a Python list.

Returns:

list

Example:

`py >>> ds.to_list() `

classmethod from_dict(*args, **kargs)[source]#

Override the from_dict func, which is called by most from_xx constructors, such that the constructed dataset object is NestedDataset.

classmethod from_list(*args, **kargs)[source]#

Override the from_dict func, which is called by most from_xx constructors, such that the constructed dataset object is NestedDataset.

add_column(*args, **kargs)[source]#

Override the add column func, such that the processed samples can be accessed by nested manner.

select_columns(*args, **kargs)[source]#

Override the select columns func, such that the processed samples can be accessed by nested manner.

remove_columns(*args, **kargs)[source]#

Override the remove columns func, such that the processed samples can be accessed by nested manner.

cleanup_cache_files()[source]#

Override the cleanup_cache_files func, clear raw and compressed cache files.

static load_from_disk(*args, **kargs)[source]#

Loads a dataset that was previously saved using [save_to_disk] from a dataset directory, or from a filesystem using any implementation of fsspec.spec.AbstractFileSystem.

Parameters:
  • dataset_path (path-like) – Path (e.g. “dataset/train”) or remote URI (e.g. “s3//my-bucket/dataset/train”) of the dataset directory where the dataset will be loaded from.

  • keep_in_memory (bool, defaults to None) – Whether to copy the dataset in-memory. If None, the dataset will not be copied in-memory unless explicitly enabled by setting datasets.config.IN_MEMORY_MAX_SIZE to nonzero. See more details in the [improve performance](../cache#improve-performance) section.

  • storage_options (dict, optional) –

    Key/value pairs to be passed on to the file-system backend, if any.

    <Added version=”2.8.0”/>

Returns:

  • If dataset_path is a path of a dataset directory, the dataset requested.

  • If dataset_path is a path of a dataset dict directory, a datasets.DatasetDict with each split.

Return type:

[Dataset] or [DatasetDict]

Example:

`py >>> ds = load_from_disk("path/to/dataset/directory") `

class data_juicer.core.ExecutorBase(cfg: Namespace | None = None)[source]#

Bases: ABC

abstractmethod __init__(cfg: Namespace | None = None)[source]#
abstractmethod run(load_data_np: Annotated[int, Gt(gt=0)] | None = None, skip_return=False)[source]#

Abstract method for ExecutorBase.run

class data_juicer.core.ExecutorFactory[source]#

Bases: object

static create_executor(executor_type: str) ExecutorBase[source]#
class data_juicer.core.DefaultExecutor(cfg: Namespace | None = None)[source]#

Bases: ExecutorBase, DAGExecutionMixin, EventLoggingMixin

This Executor class is used to process a specific dataset.

It will load the dataset and unify the format, then apply all the ops in the config file in order and generate a processed dataset.

__init__(cfg: Namespace | None = None)[source]#

Initialization method.

Parameters:

cfg – optional jsonargparse Namespace.

run(dataset: Dataset | NestedDataset = None, load_data_np: Annotated[int, Gt(gt=0)] | None = None, skip_export: bool = False, skip_return: bool = False)[source]#

Running the dataset process pipeline.

Parameters:
  • dataset – a Dataset object to be executed.

  • load_data_np – number of workers when loading the dataset.

  • skip_export – whether export the results into disk

  • skip_return – skip return for API called.

Returns:

processed dataset.

sample_data(dataset_to_sample: Dataset = None, load_data_np=None, sample_ratio: float = 1.0, sample_algo: str = 'uniform', **kwargs)[source]#

Sample a subset from the given dataset. TODO add support other than LocalExecutor

Parameters:
  • dataset_to_sample – Dataset to sample from. If None, will use the formatter linked by the executor. Default is None.

  • load_data_np – number of workers when loading the dataset.

  • sample_ratio – The ratio of the sample size to the original dataset size. Default is 1.0 (no sampling).

  • sample_algo – Sampling algorithm to use. Options are “uniform”, “frequency_specified_field_selector”, or “topk_specified_field_selector”. Default is “uniform”.

Returns:

A sampled Dataset.

class data_juicer.core.RayExecutor(cfg: Namespace | None = None)[source]#

Bases: ExecutorBase, DAGExecutionMixin, EventLoggingMixin

Executor based on Ray.

Run Data-Juicer data processing in a distributed cluster.

  1. Support Filter, Mapper and Exact Deduplicator operators for now.

  2. Only support loading .json files.

  3. Advanced functions, such as checkpoint, are not supported.

__init__(cfg: Namespace | None = None)[source]#

Initialization method.

Parameters:

cfg – optional config dict.

run(load_data_np: Annotated[int, Gt(gt=0)] | None = None, skip_export: bool = False, skip_return: bool = False)[source]#

Running the dataset process pipeline

Parameters:
  • load_data_np – number of workers when loading the dataset.

  • skip_export – whether export the results into disk

  • skip_return – skip return for API called.

Returns:

processed dataset.

class data_juicer.core.PartitionedRayExecutor(cfg: Namespace | None = None)[source]#

Bases: ExecutorBase, DAGExecutionMixin, EventLoggingMixin

Simplified Ray executor with dataset partitioning using .split().

Features: - Single DatasetBuilder loads the full dataset - Uses Ray’s .split() method for partitioning - Processes partitions in parallel with Ray tasks - Supports convergence points for global operations - Merges results back into a single dataset

__init__(cfg: Namespace | None = None)[source]#

Initialize the partitioned Ray executor.

run(load_data_np: Annotated[int, Gt(gt=0)] | None = None, skip_return=False)[source]#

Run the simplified partitioned dataset processing pipeline.

Parameters:
  • load_data_np – Number of workers for loading dataset

  • skip_return – Whether to skip returning the dataset

  • job_id – Optional job ID to resume from checkpoints

Returns:

Processed dataset

cleanup_temp_files()[source]#

Manually clean up temporary files from previous runs.

class data_juicer.core.Exporter(export_path, export_type=None, export_shard_size=0, export_in_parallel=True, num_proc=1, export_ds=True, keep_stats_in_res_ds=False, keep_hashes_in_res_ds=False, export_stats=True, **kwargs)[source]#

Bases: object

The Exporter class is used to export a dataset to files of specific format.

__init__(export_path, export_type=None, export_shard_size=0, export_in_parallel=True, num_proc=1, export_ds=True, keep_stats_in_res_ds=False, keep_hashes_in_res_ds=False, export_stats=True, **kwargs)[source]#

Initialization method.

Parameters:
  • export_path – the path to export datasets.

  • export_type – the format type of the exported datasets.

  • export_shard_size – the approximate size of each shard of exported dataset. In default, it’s 0, which means export the dataset to a single file.

  • export_in_parallel – whether to export the datasets in parallel.

  • num_proc – number of process to export the dataset.

  • export_ds – whether to export the dataset contents.

  • keep_stats_in_res_ds – whether to keep stats in the result dataset.

  • keep_hashes_in_res_ds – whether to keep hashes in the result dataset.

  • export_stats – whether to export the stats of dataset.

export(dataset)[source]#

Export method for a dataset.

Parameters:

dataset – the dataset to export.

Returns:

export_compute_stats(dataset, export_path)[source]#

Export method for saving compute status in filters

static to_jsonl(dataset, export_path, num_proc=1, **kwargs)[source]#

Export method for jsonl target files.

Parameters:
  • dataset – the dataset to export.

  • export_path – the path to store the exported dataset.

  • num_proc – the number of processes used to export the dataset.

  • kwargs – extra arguments.

Returns:

static to_json(dataset, export_path, num_proc=1, **kwargs)[source]#

Export method for json target files.

Parameters:
  • dataset – the dataset to export.

  • export_path – the path to store the exported dataset.

  • num_proc – the number of processes used to export the dataset.

  • kwargs – extra arguments.

Returns:

static to_parquet(dataset, export_path, **kwargs)[source]#

Export method for parquet target files.

Parameters:
  • dataset – the dataset to export.

  • export_path – the path to store the exported dataset.

  • kwargs – extra arguments.

Returns:

class data_juicer.core.RayExporter(export_path, export_type=None, export_shard_size=0, keep_stats_in_res_ds=True, keep_hashes_in_res_ds=False, **kwargs)[source]#

Bases: object

The Exporter class is used to export a ray dataset to files of specific format.

__init__(export_path, export_type=None, export_shard_size=0, keep_stats_in_res_ds=True, keep_hashes_in_res_ds=False, **kwargs)[source]#

Initialization method.

Parameters:
  • export_path – the path to export datasets.

  • export_type – the format type of the exported datasets.

  • export_shard_size – the approximate size of each shard of exported dataset. In default, it’s 0, which means export the dataset in the default setting of ray.

  • keep_stats_in_res_ds – whether to keep stats in the result dataset.

  • keep_hashes_in_res_ds – whether to keep hashes in the result dataset.

export(dataset, columns=None)[source]#

Export method for a dataset.

Parameters:
  • dataset – the dataset to export.

  • columns – the columns to export.

Returns:

static write_json(dataset, export_path, **kwargs)[source]#

Export method for json/jsonl target files.

Parameters:
  • dataset – the dataset to export.

  • export_path – the path to store the exported dataset.

  • kwargs – extra arguments.

Returns:

static write_webdataset(dataset, export_path, **kwargs)[source]#

Export method for webdataset target files.

Parameters:
  • dataset – the dataset to export.

  • export_path – the path to store the exported dataset.

  • kwargs – extra arguments.

Returns:

static write_others(dataset, export_path, **kwargs)[source]#

Export method for other target files.

Parameters:
  • dataset – the dataset to export.

  • export_path – the path to store the exported dataset.

  • kwargs – extra arguments.

Returns:

class data_juicer.core.Monitor[source]#

Bases: object

Monitor resource utilization and other information during the data processing.

Resource utilization dict: (for each func) ‘’’python {

‘time’: 10, ‘sampling interval’: 0.5, ‘resource’: [

{

‘timestamp’: xxx, ‘CPU count’: xxx, ‘GPU free mem.’: xxx. …

}, {

‘timestamp’: xxx, ‘CPU count’: xxx, ‘GPU free mem.’: xxx, …

},

]

}#

Based on the structure above, the resource utilization analysis result will add several extra fields on the first level: ‘’’python {

‘time’: 10, ‘sampling interval’: 0.5, ‘resource’: […], ‘resource_analysis’: {

‘GPU free mem.’: {

‘max’: xxx, ‘min’: xxx, ‘avg’: xxx,

}

}#

Only those fields in DYNAMIC_FIELDS will be analyzed.

DYNAMIC_FIELDS = {'Available mem.', 'CPU util.', 'Free mem.', 'GPU free mem.', 'GPU used mem.', 'GPU util.', 'Mem. util.', 'Used mem.'}#
static monitor_current_resources()[source]#

Detect the resource utilization of the current environment/machine. All data of “util.” is ratios in the range of [0.0, 1.0]. All data of “mem.” is in MB.

static draw_resource_util_graph(resource_util_list, store_dir)[source]#
static analyze_resource_util_list(resource_util_list)[source]#

Analyze the resource utilization for a given resource util list. Compute {‘max’, ‘min’, ‘avg’} of resource metrics for each dict item.

static analyze_single_resource_util(resource_util_dict)[source]#

Analyze the resource utilization for a single resource util dict. Compute {‘max’, ‘min’, ‘avg’} of each resource metrics.

static monitor_func(func, args=None, sample_interval=0.5)[source]#

Process the input dataset and probe related information for each OP in the specified operator list.

For now, we support the following targets to probe: “resource”: resource utilization for each OP. “speed”: average processing speed for each OP.

The probe result is a list and each item in the list is the probe result for each OP.

class data_juicer.core.Tracer(work_dir, op_list_to_trace=None, show_num=10, trace_keys=None, lock=None)[source]#

Bases: object

The tracer to trace the sample changes before and after an operator process.

The comparison results will be stored in the work directory. Now supports sample-level tracing for better efficiency and accuracy.

__init__(work_dir, op_list_to_trace=None, show_num=10, trace_keys=None, lock=None)[source]#

Initialization method.

Parameters:
  • work_dir – the work directory to store the comparison results

  • op_list_to_trace – the OP list to be traced.

  • show_num – the maximum number of samples to show in the comparison result files.

  • trace_keys – list of field names to include in trace output. If set, the specified fields’ values will be included in each trace entry.

should_trace_op(op_name: str) bool[source]#

Check if an operator should be traced.

Parameters:

op_name – the operator name

Returns:

True if the operator should be traced

is_collection_complete(op_name: str) bool[source]#

Check if enough samples have been collected for an operator.

Parameters:

op_name – the operator name

Returns:

True if enough samples have been collected

collect_mapper_sample(op_name: str, original_sample: dict, processed_sample: dict, text_key: str)[source]#

Collect a sample-level change for a Mapper operator. This method is thread-safe and will only collect up to show_num samples.

Parameters:
  • op_name – the operator name

  • original_sample – the original sample before processing

  • processed_sample – the processed sample after processing

  • text_key – the key name of the text field to compare

Returns:

True if the sample was collected, False if collection is complete

collect_filter_sample(op_name: str, sample: dict, should_keep: bool)[source]#

Collect a sample-level change for a Filter operator. This method is thread-safe and will only collect up to show_num samples. Only collects samples that are filtered out (should_keep=False).

Parameters:
  • op_name – the operator name

  • sample – the sample being filtered

  • should_keep – True if the sample should be kept, False if filtered

Returns:

True if the sample was collected, False if collection is complete

get_trace_file_path(op_name: str) str[source]#

Get the file path for a trace file.

Parameters:

op_name – the operator name

Returns:

the file path

trace_mapper(op_name: str, previous_ds: Dataset, processed_ds: Dataset, text_key: str)[source]#

Compare datasets before and after a Mapper.

This will mainly show the different sample pairs due to the modification by the Mapper

Parameters:
  • op_name – the op name of mapper

  • previous_ds – dataset before the mapper process

  • processed_ds – dataset processed by the mapper

  • text_key – which text_key to trace

Returns:

trace_batch_mapper(op_name: str, previous_ds: Dataset, processed_ds: Dataset, text_key: str)[source]#

Compare datasets before and after a BatchMapper.

This will mainly show the new samples augmented by the BatchMapper

Parameters:
  • op_name – the op name of mapper

  • previous_ds – dataset before the mapper process

  • processed_ds – dataset processed by the mapper

  • text_key – which text_key to trace

Returns:

trace_filter(op_name: str, previous_ds: Dataset, processed_ds: Dataset)[source]#

Compare datasets before and after a Filter.

This will mainly show the filtered samples by the Filter

Parameters:
  • op_name – the op name of filter

  • previous_ds – dataset before the filter process

  • processed_ds – dataset processed by the filter

Returns:

trace_deduplicator(op_name: str, dup_pairs: dict)[source]#

Compare datasets before and after a Deduplicator.

This will mainly show the near-duplicate sample pairs extracted by the Deduplicator. Different from the other two trace methods, the trace process for deduplicator is embedded into the process method of deduplicator, but the other two trace methods are independent of the process method of mapper and filter operators

Parameters:
  • op_name – the op name of deduplicator

  • dup_pairs – duplicate sample pairs obtained from deduplicator

Returns: