code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def analyze_resource_tag(code):
"""
Analyze the resource tag for the given code content string. Should be one
of the "Resource Tags" in `tagging_mappings.json`. It makes the choice
according to their assigning statement to attribute `_accelerator`.
"""
if '_accelerator = \'cuda\'' in code:
... |
Analyze the resource tag for the given code content string. Should be one
of the "Resource Tags" in `tagging_mappings.json`. It makes the choice
according to their assigning statement to attribute `_accelerator`.
| analyze_resource_tag | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def analyze_model_tags(code):
"""
Analyze the model tag for the given code content string. SHOULD be one of
the "Model Tags" in `tagging_mappings.json`. It makes the choice by finding
the `model_type` arg in `prepare_model` method invocation.
"""
pattern = r'model_type=[\'|\"](.*?)[\'|\"]'
g... |
Analyze the model tag for the given code content string. SHOULD be one of
the "Model Tags" in `tagging_mappings.json`. It makes the choice by finding
the `model_type` arg in `prepare_model` method invocation.
| analyze_model_tags | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def analyze_tag_from_code(code_path):
"""
Analyze the tags for the OP from the given code path.
"""
tags = []
op_prefix = code_path.split('/')[-1].split('_')[0]
with open(code_path, 'r', encoding='utf-8') as fin:
content = fin.read()
# analyze modality
tags.extend(analyze... |
Analyze the tags for the OP from the given code path.
| analyze_tag_from_code | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def get_class_and_docstring(code_path):
"""
Get the class name and its doc strings from the given Python code path.
"""
with open(code_path, 'r', encoding='utf-8') as fin:
code = fin.read()
tree = ast.parse(code)
cls_visitor = ClassVisitor()
cls_visitor.visit(tree)
... |
Get the class name and its doc strings from the given Python code path.
| get_class_and_docstring | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def get_op_list_from_code_for_formatter():
"""
Get the OP record list for Formatters specifically.
"""
op_record_list = []
type = 'formatter'
for formatter in os.listdir(FORMATTER_CODE_PREFIX):
if formatter in FORMATTER_EXCLUDE:
continue
if formatter == 'formatter.py'... |
Get the OP record list for Formatters specifically.
| get_op_list_from_code_for_formatter | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def get_op_list_from_code():
"""
Get the OP record list for regular OPs (except Formatters).
"""
# get docs for formatters first
op_record_list = get_op_list_from_code_for_formatter()
# get docs for other ops
for type in os.listdir(OP_CODE_PREFIX):
if type in OP_EXCLUDE:
... |
Get the OP record list for regular OPs (except Formatters).
| get_op_list_from_code | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def generate_new_doc(op_record_list):
"""
Generate new docs for the updated OP records.
"""
op_record_dict = {}
for record in op_record_list:
op_record_dict.setdefault(record.type, []).append(record)
# initialize with abstraction
doc = [DOC_ABSTRACT]
# make overview
doc.appen... |
Generate new docs for the updated OP records.
| generate_new_doc | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def check_and_update_op_record(old_op_record_list, new_op_record_list):
"""
Update states in the new OP records based on the old version.
The update categories cover:
1. usability tags update
1.1 If there is no unittest for this OP, set it to alpha;
otherwise, set it to beta.
... |
Update states in the new OP records based on the old version.
The update categories cover:
1. usability tags update
1.1 If there is no unittest for this OP, set it to alpha;
otherwise, set it to beta.
1.2 Then if it's beta in the new version, but it's *mannally* checked
... | check_and_update_op_record | python | modelscope/data-juicer | .pre-commit-hooks/build_op_doc.py | https://github.com/modelscope/data-juicer/blob/master/.pre-commit-hooks/build_op_doc.py | Apache-2.0 |
def __init__(self, tokenizer):
"""
Initialization method.
:param tokenizer: tokenizer name on huggingface
"""
self.tokenizer = transformers.AutoTokenizer.from_pretrained(
tokenizer, trust_remote_code=True)
self.vocab_size = len(self.tokenizer) |
Initialization method.
:param tokenizer: tokenizer name on huggingface
| __init__ | python | modelscope/data-juicer | data_juicer/analysis/collector.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/collector.py | Apache-2.0 |
def collect(self,
data_path,
text_key,
num_proc=1) -> 'torch.distributions.Categorical':
"""
Tokenize and collect tokens distribution of input dataset
:param data_path: path to input dataset.
:param text_key: field keys that will be conside... |
Tokenize and collect tokens distribution of input dataset
:param data_path: path to input dataset.
:param text_key: field keys that will be considered into token counts.
:param num_proc: number of processes to count tokens.
:return: token distribution.
| collect | python | modelscope/data-juicer | data_juicer/analysis/collector.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/collector.py | Apache-2.0 |
def prepare_tokenizer(
tokenizer,
text_key,
):
"""
Prepare a tokenizer function for dataset.
:param tokenizer: a tokenizer to tokenize sample.
:param text_key: field keys that will be
considered into token counts.
... |
Prepare a tokenizer function for dataset.
:param tokenizer: a tokenizer to tokenize sample.
:param text_key: field keys that will be
considered into token counts.
| prepare_tokenizer | python | modelscope/data-juicer | data_juicer/analysis/collector.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/collector.py | Apache-2.0 |
def get_row_col(total_num, factor=2):
"""
Given the total number of stats figures, get the "best" number of rows and
columns. This function is needed when we need to store all stats figures
into one image.
:param total_num: Total number of stats figures
:param factor: Number of sub-figure types... |
Given the total number of stats figures, get the "best" number of rows and
columns. This function is needed when we need to store all stats figures
into one image.
:param total_num: Total number of stats figures
:param factor: Number of sub-figure types in each figure. In
default, it's 2, ... | get_row_col | python | modelscope/data-juicer | data_juicer/analysis/column_wise_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/column_wise_analysis.py | Apache-2.0 |
def __init__(self,
dataset,
output_path,
overall_result=None,
save_stats_in_one_file=True):
"""
Initialization method
:param dataset: the dataset to be analyzed
:param output_path: path to store the analysis results
... |
Initialization method
:param dataset: the dataset to be analyzed
:param output_path: path to store the analysis results
:param overall_result: optional precomputed overall stats result
:param save_stats_in_one_file: whether save all analysis figures of all
stats int... | __init__ | python | modelscope/data-juicer | data_juicer/analysis/column_wise_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/column_wise_analysis.py | Apache-2.0 |
def analyze(self, show_percentiles=False, show=False, skip_export=False):
"""
Apply analysis and draw the analysis figure for stats.
:param show_percentiles: whether to show the percentile line in
each sub-figure. If it's true, there will be several red
lines to indicate... |
Apply analysis and draw the analysis figure for stats.
:param show_percentiles: whether to show the percentile line in
each sub-figure. If it's true, there will be several red
lines to indicate the quantiles of the stats distributions
:param show: whether to show in a s... | analyze | python | modelscope/data-juicer | data_juicer/analysis/column_wise_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/column_wise_analysis.py | Apache-2.0 |
def draw_hist(self, ax, data, save_path, percentiles=None, show=False):
"""
Draw the histogram for the data.
:param ax: the axes to draw
:param data: data to draw
:param save_path: the path to save the histogram figure
:param percentiles: the overall analysis result of t... |
Draw the histogram for the data.
:param ax: the axes to draw
:param data: data to draw
:param save_path: the path to save the histogram figure
:param percentiles: the overall analysis result of the data
including percentile information
:param show: whether t... | draw_hist | python | modelscope/data-juicer | data_juicer/analysis/column_wise_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/column_wise_analysis.py | Apache-2.0 |
def draw_box(self, ax, data, save_path, percentiles=None, show=False):
"""
Draw the box plot for the data.
:param ax: the axes to draw
:param data: data to draw
:param save_path: the path to save the box figure
:param percentiles: the overall analysis result of the data
... |
Draw the box plot for the data.
:param ax: the axes to draw
:param data: data to draw
:param save_path: the path to save the box figure
:param percentiles: the overall analysis result of the data
including percentile information
:param show: whether to show ... | draw_box | python | modelscope/data-juicer | data_juicer/analysis/column_wise_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/column_wise_analysis.py | Apache-2.0 |
def find_root_verb_and_its_dobj(tree_root):
"""
Find the verb and its object closest to the root.
:param tree_root: the root of lexical tree
:return: valid verb and its object.
"""
# first check if the current node and its children satisfy the condition
if tree_root.pos_ == 'VERB':
... |
Find the verb and its object closest to the root.
:param tree_root: the root of lexical tree
:return: valid verb and its object.
| find_root_verb_and_its_dobj | python | modelscope/data-juicer | data_juicer/analysis/diversity_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/diversity_analysis.py | Apache-2.0 |
def find_root_verb_and_its_dobj_in_string(nlp, s, first_sent=True):
"""
Find the verb and its object closest to the root of lexical tree of input
string.
:param nlp: the diversity model to analyze the diversity strings
:param s: the string to be analyzed
:param first_sent: whether to analyze th... |
Find the verb and its object closest to the root of lexical tree of input
string.
:param nlp: the diversity model to analyze the diversity strings
:param s: the string to be analyzed
:param first_sent: whether to analyze the first sentence in the
input string only. If it's true, return the... | find_root_verb_and_its_dobj_in_string | python | modelscope/data-juicer | data_juicer/analysis/diversity_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/diversity_analysis.py | Apache-2.0 |
def get_diversity(dataset, top_k_verbs=20, top_k_nouns=4, **kwargs):
"""
Given the lexical tree analysis result, return the diversity results.
:param dataset: lexical tree analysis result
:param top_k_verbs: only keep the top_k_verbs largest verb groups
:param top_k_nouns: only keep the top_k_nouns... |
Given the lexical tree analysis result, return the diversity results.
:param dataset: lexical tree analysis result
:param top_k_verbs: only keep the top_k_verbs largest verb groups
:param top_k_nouns: only keep the top_k_nouns largest noun groups
for each verb group
:param kwargs: extra ar... | get_diversity | python | modelscope/data-juicer | data_juicer/analysis/diversity_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/diversity_analysis.py | Apache-2.0 |
def __init__(self, dataset, output_path, lang_or_model='en'):
"""Initialization method :param dataset: the dataset to be analyzed
:param output_path: path to store the analysis results :param
lang_or_model: the diversity model or a specific language used to load
the diversity model."""
... | Initialization method :param dataset: the dataset to be analyzed
:param output_path: path to store the analysis results :param
lang_or_model: the diversity model or a specific language used to load
the diversity model. | __init__ | python | modelscope/data-juicer | data_juicer/analysis/diversity_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/diversity_analysis.py | Apache-2.0 |
def compute(self, lang_or_model=None, column_name='text'):
"""
Apply lexical tree analysis on each sample.
:param lang_or_model: the diversity model or a specific language
used to load the diversity model
:param column_name: the name of column to be analyzed
:return:... |
Apply lexical tree analysis on each sample.
:param lang_or_model: the diversity model or a specific language
used to load the diversity model
:param column_name: the name of column to be analyzed
:return: the analysis result.
| compute | python | modelscope/data-juicer | data_juicer/analysis/diversity_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/diversity_analysis.py | Apache-2.0 |
def analyze(self,
lang_or_model=None,
column_name='text',
postproc_func=get_diversity,
**postproc_kwarg):
"""
Apply diversity analysis on the whole dataset.
:param lang_or_model: the diversity model or a specific language
... |
Apply diversity analysis on the whole dataset.
:param lang_or_model: the diversity model or a specific language
used to load the diversity model
:param column_name: the name of column to be analyzed
:param postproc_func: function to analyze diversity. In default,
... | analyze | python | modelscope/data-juicer | data_juicer/analysis/diversity_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/diversity_analysis.py | Apache-2.0 |
def draw_heatmap(data,
xlabels,
ylabels='auto',
figsize=None,
triangle=False,
show=False):
"""
Draw heatmap of input data with special labels.
:param data: input data, now support
[`list`, `tuple`, `numpy array`, '... |
Draw heatmap of input data with special labels.
:param data: input data, now support
[`list`, `tuple`, `numpy array`, 'torch tensor']
:param xlabels: x axis labels.
:param ylabels: y axis labels, if None, use xlabels.
:param figsize: figure size.
:param triangle: only display triangle.... | draw_heatmap | python | modelscope/data-juicer | data_juicer/analysis/draw.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/draw.py | Apache-2.0 |
def _convert_to_tensor(self, p):
"""
Convert input data to torch tensor.
:param p: input data, now support
[`scalar`,`list`, `tuple`, `torch binary file`, and `Categorical`].
:return: torch tensor
"""
if isinstance(p, torch.Tensor):
return p
... |
Convert input data to torch tensor.
:param p: input data, now support
[`scalar`,`list`, `tuple`, `torch binary file`, and `Categorical`].
:return: torch tensor
| _convert_to_tensor | python | modelscope/data-juicer | data_juicer/analysis/measure.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/measure.py | Apache-2.0 |
def _convert_to_categorical(self, p):
"""
Convert input data to torch Categorical.
:param p: input data, now support
[`scalar`,`list`, `tuple`, `torch binary file`, and `Categorical`].
:return: torch Categorical
"""
if isinstance(p, td.Categorical):
... |
Convert input data to torch Categorical.
:param p: input data, now support
[`scalar`,`list`, `tuple`, `torch binary file`, and `Categorical`].
:return: torch Categorical
| _convert_to_categorical | python | modelscope/data-juicer | data_juicer/analysis/measure.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/measure.py | Apache-2.0 |
def measure(self, p, q):
"""
:param p: the first feature or distribution. (stats/tags/categories)
:param q: the second feature or distribution. (stats/tags/categories)
:return: the T-Test results object -- ([ref](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats._result_cl... |
:param p: the first feature or distribution. (stats/tags/categories)
:param q: the second feature or distribution. (stats/tags/categories)
:return: the T-Test results object -- ([ref](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats._result_classes.TtestResult.html#scipy.stats._... | measure | python | modelscope/data-juicer | data_juicer/analysis/measure.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/measure.py | Apache-2.0 |
def __init__(self, dataset, output_path):
"""
Initialization method.
:param dataset: the dataset to be analyzed
:param output_path: path to store the analysis results.
"""
self.stats = pd.DataFrame(dataset[Fields.stats])
self.meta = pd.DataFrame(dataset[Fields.me... |
Initialization method.
:param dataset: the dataset to be analyzed
:param output_path: path to store the analysis results.
| __init__ | python | modelscope/data-juicer | data_juicer/analysis/overall_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/overall_analysis.py | Apache-2.0 |
def analyze(self, percentiles=[], num_proc=1, skip_export=False):
"""
Apply overall analysis on the whole dataset based on the describe
method of pandas.
:param percentiles: percentiles to analyze
:param num_proc: number of processes to analyze the dataset
:param skip_ex... |
Apply overall analysis on the whole dataset based on the describe
method of pandas.
:param percentiles: percentiles to analyze
:param num_proc: number of processes to analyze the dataset
:param skip_export: whether export the results to disk
:return: the overall analysi... | analyze | python | modelscope/data-juicer | data_juicer/analysis/overall_analysis.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/analysis/overall_analysis.py | Apache-2.0 |
def init_configs(args: Optional[List[str]] = None, which_entry: object = None):
"""
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 de... |
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.
... | init_configs | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def init_setup_from_cfg(cfg: Namespace):
"""
Do some extra setup tasks after parsing config file or command line.
1. create working directory and a log directory
2. update cache directory
3. update checkpoint and `temp_dir` of tempfile
:param cfg: an original cfg
:param cfg: an updated cfg... |
Do some extra setup tasks after parsing config file or command line.
1. create working directory and a log directory
2. update cache directory
3. update checkpoint and `temp_dir` of tempfile
:param cfg: an original cfg
:param cfg: an updated cfg
| init_setup_from_cfg | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def _collect_config_info_from_class_docs(configurable_ops, parser):
"""
Add ops and its params to parser for command line with optimized performance.
"""
with timing_context('Collecting operator configuration info'):
op_params = {}
# Add arguments for all provided operators
for ... |
Add ops and its params to parser for command line with optimized performance.
| _collect_config_info_from_class_docs | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def sort_op_by_types_and_names(op_name_classes):
"""
Split ops items by op type and sort them to sub-ops by name, then concat
together.
:param op_name_classes: a list of op modules
:return: sorted op list , each item is a pair of op_name and
op_class
"""
with timing_context('Sorting... |
Split ops items by op type and sort them to sub-ops by name, then concat
together.
:param op_name_classes: a list of op modules
:return: sorted op list , each item is a pair of op_name and
op_class
| sort_op_by_types_and_names | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def update_op_process(cfg, parser, used_ops=None):
"""
Update operator process configuration with optimized performance.
Args:
cfg: Configuration namespace
parser: Argument parser
used_ops: Set of operator names that are actually used in the config
"""
if used_ops is None:
... |
Update operator process configuration with optimized performance.
Args:
cfg: Configuration namespace
parser: Argument parser
used_ops: Set of operator names that are actually used in the config
| update_op_process | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def export_config(cfg: Namespace,
path: str,
format: str = 'yaml',
skip_none: bool = True,
skip_check: bool = True,
overwrite: bool = False,
multifile: bool = True):
"""
Save the config object, some param... |
Save the config object, some params are from jsonargparse
:param cfg: cfg object to save (Namespace type)
:param path: the save path
:param format: 'yaml', 'json', 'json_indented', 'parser_mode'
:param skip_none: Whether to exclude entries whose value is None.
:param skip_check: Whether to ski... | export_config | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def merge_config(ori_cfg: Namespace, new_cfg: Namespace):
"""
Merge configuration from new_cfg into ori_cfg
:param ori_cfg: the original configuration object, whose type is
expected as namespace from jsonargparse
:param new_cfg: the configuration object to be merged, whose type is
expec... |
Merge configuration from new_cfg into ori_cfg
:param ori_cfg: the original configuration object, whose type is
expected as namespace from jsonargparse
:param new_cfg: the configuration object to be merged, whose type is
expected as dict or namespace from jsonargparse
:return: cfg_afte... | merge_config | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def prepare_side_configs(ori_config: Union[str, Namespace, Dict]):
"""
parse the config if ori_config is a string of a config file path with
yaml, yml or json format
:param ori_config: a config dict or a string of a config file path with
yaml, yml or json format
:return: a config dict
... |
parse the config if ori_config is a string of a config file path with
yaml, yml or json format
:param ori_config: a config dict or a string of a config file path with
yaml, yml or json format
:return: a config dict
| prepare_side_configs | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def get_init_configs(cfg: Union[Namespace, Dict]):
"""
set init configs of data-juicer for cfg
"""
temp_dir = tempfile.gettempdir()
temp_file = os.path.join(temp_dir, 'job_dj_config.json')
if isinstance(cfg, Namespace):
cfg = namespace_to_dict(cfg)
# create an temp config file
wi... |
set init configs of data-juicer for cfg
| get_init_configs | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def get_default_cfg():
"""Get default config values from config_all.yaml"""
cfg = Namespace()
# Get path to config_all.yaml
config_dir = os.path.dirname(os.path.abspath(__file__))
default_config_path = os.path.join(config_dir,
'../../configs/config_min.yaml')
... | Get default config values from config_all.yaml | get_default_cfg | python | modelscope/data-juicer | data_juicer/config/config.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/config/config.py | Apache-2.0 |
def execute_and_probe(dataset, operators, sample_interval=0.5):
"""
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.
"spee... |
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 li... | execute_and_probe | python | modelscope/data-juicer | data_juicer/core/adapter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/adapter.py | Apache-2.0 |
def take_batch(dataset, config):
"""
Split the dataset into batches based on configuration and load factor.
:param dataset: The dataset to be split
:param config: Configuration settings, including batch size
:return: An iterator of batches
"""
# get initial batch... |
Split the dataset into batches based on configuration and load factor.
:param dataset: The dataset to be split
:param config: Configuration settings, including batch size
:return: An iterator of batches
| take_batch | python | modelscope/data-juicer | data_juicer/core/adapter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/adapter.py | Apache-2.0 |
def adapt_workloads(self, dataset, operators):
"""
Manage the scheduling and load balancing for the dataset processing.
:param dataset: The dataset that needs to be processed
:param operators: Operators in the data recipe
"""
# TODO: set batch size to 1 for all OPs for p... |
Manage the scheduling and load balancing for the dataset processing.
:param dataset: The dataset that needs to be processed
:param operators: Operators in the data recipe
| adapt_workloads | python | modelscope/data-juicer | data_juicer/core/adapter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/adapter.py | Apache-2.0 |
def probe_small_batch(self, dataset, operators):
"""
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
... |
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.
:param da... | probe_small_batch | python | modelscope/data-juicer | data_juicer/core/adapter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/adapter.py | Apache-2.0 |
def batch_size_strategy(self, load_analysis_res, base_bs=1, util_th=0.9):
"""
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
... |
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 ... | batch_size_strategy | python | modelscope/data-juicer | data_juicer/core/adapter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/adapter.py | Apache-2.0 |
def analyze_small_batch(self, dataset, current_state):
"""
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 ... |
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.
... | analyze_small_batch | python | modelscope/data-juicer | data_juicer/core/adapter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/adapter.py | Apache-2.0 |
def insight_mining(self, pval_th=0.05):
"""
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 th... |
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
i... | insight_mining | python | modelscope/data-juicer | data_juicer/core/adapter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/adapter.py | Apache-2.0 |
def __init__(self, cfg: Optional[Namespace] = None):
"""
Initialization method.
:param cfg: optional jsonargparse Namespace dict.
"""
self.cfg = init_configs(which_entry=self) if cfg is None else cfg
self.work_dir = self.cfg.work_dir
if self.cfg.use_cache:
... |
Initialization method.
:param cfg: optional jsonargparse Namespace dict.
| __init__ | python | modelscope/data-juicer | data_juicer/core/analyzer.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/analyzer.py | Apache-2.0 |
def run(self,
dataset: Union[Dataset, NestedDataset] = None,
load_data_np: Optional[PositiveInt] = None,
skip_export: bool = False,
skip_return: bool = False):
"""
Running the dataset analysis pipeline.
:param dataset: a Dataset object to be analy... |
Running the dataset analysis pipeline.
:param dataset: a Dataset object to be analyzed.
:param load_data_np: number of workers when loading the dataset.
:param skip_export: whether export the results into disk
:param skip_return: skip return for API called.
:return: ana... | run | python | modelscope/data-juicer | data_juicer/core/analyzer.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/analyzer.py | Apache-2.0 |
def __init__(self,
export_path,
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):
... |
Initialization method.
:param export_path: the path to export datasets.
:param export_shard_size: the size of each shard of exported
dataset. In default, it's 0, which means export the dataset
to a single file.
:param num_proc: number of process to export the da... | __init__ | python | modelscope/data-juicer | data_juicer/core/exporter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/exporter.py | Apache-2.0 |
def _get_suffix(self, export_path):
"""
Get the suffix of export path and check if it's supported.
We only support ["jsonl", "json", "parquet"] for now.
:param export_path: the path to export datasets.
:return: the suffix of export_path.
"""
suffix = export_path... |
Get the suffix of export path and check if it's supported.
We only support ["jsonl", "json", "parquet"] for now.
:param export_path: the path to export datasets.
:return: the suffix of export_path.
| _get_suffix | python | modelscope/data-juicer | data_juicer/core/exporter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/exporter.py | Apache-2.0 |
def _export_impl(self, dataset, export_path, suffix, export_stats=True):
"""
Export a dataset to specific path.
:param dataset: the dataset to export.
:param export_path: the path to export the dataset.
:param suffix: suffix of export path.
:param export_stats: whether t... |
Export a dataset to specific path.
:param dataset: the dataset to export.
:param export_path: the path to export the dataset.
:param suffix: suffix of export path.
:param export_stats: whether to export stats of dataset.
:return:
| _export_impl | python | modelscope/data-juicer | data_juicer/core/exporter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/exporter.py | Apache-2.0 |
def export_compute_stats(self, dataset, export_path):
"""
Export method for saving compute status in filters
"""
keep_stats_in_res_ds = self.keep_stats_in_res_ds
self.keep_stats_in_res_ds = True
self._export_impl(dataset,
export_path,
... |
Export method for saving compute status in filters
| export_compute_stats | python | modelscope/data-juicer | data_juicer/core/exporter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/exporter.py | Apache-2.0 |
def to_json(dataset, export_path, num_proc=1, **kwargs):
"""
Export method for json target files.
:param dataset: the dataset to export.
:param export_path: the path to store the exported dataset.
:param num_proc: the number of processes used to export the dataset.
:para... |
Export method for json target files.
:param dataset: the dataset to export.
:param export_path: the path to store the exported dataset.
:param num_proc: the number of processes used to export the dataset.
:param kwargs: extra arguments.
:return:
| to_json | python | modelscope/data-juicer | data_juicer/core/exporter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/exporter.py | Apache-2.0 |
def _router():
"""
A router from different suffixes to corresponding export methods.
:return: A dict router.
"""
return {
'jsonl': Exporter.to_jsonl,
'json': Exporter.to_json,
'parquet': Exporter.to_parquet,
} |
A router from different suffixes to corresponding export methods.
:return: A dict router.
| _router | python | modelscope/data-juicer | data_juicer/core/exporter.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/exporter.py | Apache-2.0 |
def monitor_current_resources():
"""
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.
"""
resource_dict = dict()
# current time
resource_dict['timesta... |
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.
| monitor_current_resources | python | modelscope/data-juicer | data_juicer/core/monitor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/monitor.py | Apache-2.0 |
def analyze_resource_util_list(resource_util_list):
"""
Analyze the resource utilization for a given resource util list.
Compute {'max', 'min', 'avg'} of resource metrics for each dict item.
"""
res_list = []
for item in resource_util_list:
res_list.append(Mon... |
Analyze the resource utilization for a given resource util list.
Compute {'max', 'min', 'avg'} of resource metrics for each dict item.
| analyze_resource_util_list | python | modelscope/data-juicer | data_juicer/core/monitor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/monitor.py | Apache-2.0 |
def analyze_single_resource_util(resource_util_dict):
"""
Analyze the resource utilization for a single resource util dict.
Compute {'max', 'min', 'avg'} of each resource metrics.
"""
analysis_res = {}
record_list = {}
for record in resource_util_dict['resource']:... |
Analyze the resource utilization for a single resource util dict.
Compute {'max', 'min', 'avg'} of each resource metrics.
| analyze_single_resource_util | python | modelscope/data-juicer | data_juicer/core/monitor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/monitor.py | Apache-2.0 |
def __init__(self, work_dir, show_num=10):
"""
Initialization method.
:param work_dir: the work directory to store the comparison
results
:param show_num: the maximum number of samples to show in the
comparison result files.
"""
self.work_dir = os... |
Initialization method.
:param work_dir: the work directory to store the comparison
results
:param show_num: the maximum number of samples to show in the
comparison result files.
| __init__ | python | modelscope/data-juicer | data_juicer/core/tracer.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/tracer.py | Apache-2.0 |
def trace_mapper(self, op_name: str, previous_ds: Dataset,
processed_ds: Dataset, text_key: str):
"""
Compare datasets before and after a Mapper.
This will mainly show the different sample pairs due to the
modification by the Mapper
:param op_name: the op n... |
Compare datasets before and after a Mapper.
This will mainly show the different sample pairs due to the
modification by the Mapper
:param op_name: the op name of mapper
:param previous_ds: dataset before the mapper process
:param processed_ds: dataset processed by the ... | trace_mapper | python | modelscope/data-juicer | data_juicer/core/tracer.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/tracer.py | Apache-2.0 |
def trace_batch_mapper(self, op_name: str, previous_ds: Dataset,
processed_ds: Dataset, text_key: str):
"""
Compare datasets before and after a BatchMapper.
This will mainly show the new samples augmented by the BatchMapper
:param op_name: the op name of mapp... |
Compare datasets before and after a BatchMapper.
This will mainly show the new samples augmented by the BatchMapper
:param op_name: the op name of mapper
:param previous_ds: dataset before the mapper process
:param processed_ds: dataset processed by the mapper
:param t... | trace_batch_mapper | python | modelscope/data-juicer | data_juicer/core/tracer.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/tracer.py | Apache-2.0 |
def trace_filter(self, op_name: str, previous_ds: Dataset,
processed_ds: Dataset):
"""
Compare datasets before and after a Filter.
This will mainly show the filtered samples by the Filter
:param op_name: the op name of filter
:param previous_ds: dataset bef... |
Compare datasets before and after a Filter.
This will mainly show the filtered samples by the Filter
:param op_name: the op name of filter
:param previous_ds: dataset before the filter process
:param processed_ds: dataset processed by the filter
:return:
| trace_filter | python | modelscope/data-juicer | data_juicer/core/tracer.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/tracer.py | Apache-2.0 |
def trace_deduplicator(self, op_name: str, dup_pairs: list):
"""
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 ... |
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 oth... | trace_deduplicator | python | modelscope/data-juicer | data_juicer/core/tracer.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/tracer.py | Apache-2.0 |
def validate_config(self, ds_config: Dict) -> None:
"""
Validate the configuration dictionary.
Args:
ds_config: Configuration dictionary to validate
Raises:
ValidationError: If validation fails
"""
# Check required fields
missing_fields =... |
Validate the configuration dictionary.
Args:
ds_config: Configuration dictionary to validate
Raises:
ValidationError: If validation fails
| validate_config | python | modelscope/data-juicer | data_juicer/core/data/config_validator.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/config_validator.py | Apache-2.0 |
def rewrite_cli_datapath(dataset_path, max_sample_num=None) -> List:
"""
rewrite the dataset_path from CLI into proper dataset config format
that is compatible with YAML config style; retrofitting CLI input
of local files and huggingface path
:param dataset_path: a dataset file or a dataset dir or ... |
rewrite the dataset_path from CLI into proper dataset config format
that is compatible with YAML config style; retrofitting CLI input
of local files and huggingface path
:param dataset_path: a dataset file or a dataset dir or a list of
them, e.g. `<w1> ds1.jsonl <w2> ds2_dir <w3> ds3_file.json... | rewrite_cli_datapath | python | modelscope/data-juicer | data_juicer/core/data/dataset_builder.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dataset_builder.py | Apache-2.0 |
def parse_cli_datapath(dataset_path) -> Tuple[List[str], List[float]]:
"""
Split every dataset path and its weight.
:param dataset_path: a dataset file or a dataset dir or a list of
them, e.g. `<w1> ds1.jsonl <w2> ds2_dir <w3> ds3_file.json`
:return: list of dataset path and list of weights
... |
Split every dataset path and its weight.
:param dataset_path: a dataset file or a dataset dir or a list of
them, e.g. `<w1> ds1.jsonl <w2> ds2_dir <w3> ds3_file.json`
:return: list of dataset path and list of weights
| parse_cli_datapath | python | modelscope/data-juicer | data_juicer/core/data/dataset_builder.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dataset_builder.py | Apache-2.0 |
def validate(self, dataset: DJDataset) -> None:
"""
Validate dataset content
Args:
dataset: The dataset to validate
Raises:
DataValidationError: If validation fails
"""
if not isinstance(dataset, DJDataset):
raise DataValidationError(... |
Validate dataset content
Args:
dataset: The dataset to validate
Raises:
DataValidationError: If validation fails
| validate | python | modelscope/data-juicer | data_juicer/core/data/data_validator.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/data_validator.py | Apache-2.0 |
def validate(self, dataset: DJDataset) -> None:
"""Base validation for all conversation formats"""
super().validate(dataset)
for item in dataset.get(self.sample_size):
self.validate_conversation(item) | Base validation for all conversation formats | validate | python | modelscope/data-juicer | data_juicer/core/data/data_validator.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/data_validator.py | Apache-2.0 |
def __init__(self, config: Dict):
"""
Initialize validator with config
Args:
config: Dict containing:
- required_fields: List of field names that must exist
- field_types: Optional map of field names to expected types
- allow_missing: ... |
Initialize validator with config
Args:
config: Dict containing:
- required_fields: List of field names that must exist
- field_types: Optional map of field names to expected types
- allow_missing: Optional float for max ratio missing allowed
... | __init__ | python | modelscope/data-juicer | data_juicer/core/data/data_validator.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/data_validator.py | Apache-2.0 |
def validate(self, dataset: DJDataset) -> None:
"""
Validate dataset has required fields with correct types
Args:
dataset: NestedDataset or RayDataset to validate
Raises:
DataValidationError: If validation fails
"""
super().validate(dataset)
... |
Validate dataset has required fields with correct types
Args:
dataset: NestedDataset or RayDataset to validate
Raises:
DataValidationError: If validation fails
| validate | python | modelscope/data-juicer | data_juicer/core/data/data_validator.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/data_validator.py | Apache-2.0 |
def process(
self,
operators, # TODO: add type hint
*,
exporter=None,
checkpointer=None,
tracer=None) -> DJDataset:
"""process a list of operators on the dataset."""
pass | process a list of operators on the dataset. | process | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def wrap_func_with_nested_access(f):
"""
Before conducting actual function `f`, wrap its args and kargs into nested
ones.
:param f: function to be wrapped.
:return: wrapped function
"""
def wrap_nested_structure(*args, **kargs):
wrapped_args = [nested_obj_factory(arg) for arg in ar... |
Before conducting actual function `f`, wrap its args and kargs into nested
ones.
:param f: function to be wrapped.
:return: wrapped function
| wrap_func_with_nested_access | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def nested_obj_factory(obj):
"""
Use nested classes to wrap the input object.
:param obj: object to be nested.
:return: nested object
"""
if isinstance(obj, Dataset):
return NestedDataset(obj)
elif isinstance(obj, DatasetDict):
return NestedDatasetDict(obj)
elif isinstan... |
Use nested classes to wrap the input object.
:param obj: object to be nested.
:return: nested object
| nested_obj_factory | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def map(self, **args):
"""Override the map func, which is called by most common operations,
such that the processed samples can be accessed by nested manner."""
if 'function' not in args or args['function'] is None:
args['function'] = lambda x: nested_obj_factory(x)
else:
... | Override the map func, which is called by most common operations,
such that the processed samples can be accessed by nested manner. | map | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def get_column(self, column: str, k: Optional[int] = None) -> List[Any]:
"""Get column values from HuggingFace dataset.
Args:
column: Name of the column to retrieve
k: Optional number of rows to return. If None, returns all rows
Returns:
List of values from ... | Get column values from HuggingFace dataset.
Args:
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
... | get_column | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def filter(self, *args, **kargs):
"""Override the filter func, which is called by most common operations,
such that the processed samples can be accessed by nested manner."""
args, kargs = self.update_args(args, kargs, is_filter=True)
# For filter, it involves a map and a filter operati... | Override the filter func, which is called by most common operations,
such that the processed samples can be accessed by nested manner. | filter | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def nested_query(root_obj: Union[NestedDatasetDict, NestedDataset,
NestedQueryDict], key):
"""
Find item from a given object, by first checking flatten layer, then
checking nested layers.
:param root_obj: the object
:param key: the stored item to be queried, e.g., "... |
Find item from a given object, by first checking flatten layer, then
checking nested layers.
:param root_obj: the object
:param key: the stored item to be queried, e.g., "meta" or
"meta.date"
:return:
| nested_query | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def add_same_content_to_new_column(sample,
new_column_name,
initial_value=None):
"""
A helper function to speed up add_column function. Apply map on this
function in parallel instead of using add_column.
:param sample: a single sample... |
A helper function to speed up add_column function. Apply map on this
function in parallel instead of using add_column.
:param sample: a single sample to add this new column/field.
:param new_column_name: the name of this new column/field.
:param initial_value: the initial value of this new column/f... | add_same_content_to_new_column | python | modelscope/data-juicer | data_juicer/core/data/dj_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/dj_dataset.py | Apache-2.0 |
def matches(self, other: 'StrategyKey') -> bool:
"""
Check if this key matches another key with wildcard support
Supports Unix-style wildcards:
- '*' matches any string
- '?' matches any single character
- '[seq]' matches any character in seq
- '[!seq]' matches a... |
Check if this key matches another key with wildcard support
Supports Unix-style wildcards:
- '*' matches any string
- '?' matches any single character
- '[seq]' matches any character in seq
- '[!seq]' matches any character not in seq
| matches | python | modelscope/data-juicer | data_juicer/core/data/load_strategy.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/load_strategy.py | Apache-2.0 |
def get_strategy_class(
cls, executor_type: str, data_type: str,
data_source: str) -> Optional[Type[DataLoadStrategy]]:
"""
Retrieve the most specific matching strategy
Matching priority:
1. Exact match
2. Wildcard matches from most specific to most gener... |
Retrieve the most specific matching strategy
Matching priority:
1. Exact match
2. Wildcard matches from most specific to most general
| get_strategy_class | python | modelscope/data-juicer | data_juicer/core/data/load_strategy.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/load_strategy.py | Apache-2.0 |
def specificity_score(key: StrategyKey) -> int:
"""
Calculate specificity score (lower is more specific)
Exact match: 0
One wildcard: 1
Two wildcards: 2
All wildcards: 3
"""
return sum(1 for p... |
Calculate specificity score (lower is more specific)
Exact match: 0
One wildcard: 1
Two wildcards: 2
All wildcards: 3
| specificity_score | python | modelscope/data-juicer | data_juicer/core/data/load_strategy.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/load_strategy.py | Apache-2.0 |
def register(cls, executor_type: str, data_type: str, data_source: str):
"""
Decorator for registering data load strategies with wildcard support
:param executor_type: Type of executor (e.g., 'default', 'ray')
:param data_type: Type of data (e.g., 'local', 'remote')
:param data_... |
Decorator for registering data load strategies with wildcard support
:param executor_type: Type of executor (e.g., 'default', 'ray')
:param data_type: Type of data (e.g., 'local', 'remote')
:param data_source: Specific data source (e.g., 'arxiv', 's3')
:return: Decorator functi... | register | python | modelscope/data-juicer | data_juicer/core/data/load_strategy.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/load_strategy.py | Apache-2.0 |
def decorator(strategy_class: Type[DataLoadStrategy]):
"""
Register the strategy class for the given key
:param strategy_class: Strategy class to register
:return: Original strategy class
"""
key = StrategyKey(executor_type, data_type, data_source... |
Register the strategy class for the given key
:param strategy_class: Strategy class to register
:return: Original strategy class
| decorator | python | modelscope/data-juicer | data_juicer/core/data/load_strategy.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/load_strategy.py | Apache-2.0 |
def set_dataset_to_absolute_path(dataset, dataset_path, cfg):
"""
Set all the path in input data to absolute path.
Checks dataset_dir and project_dir for valid paths.
"""
path_keys = []
columns = dataset.columns()
for key in [cfg.video_key, cfg.image_key, cfg.audio_key]:
if key in co... |
Set all the path in input data to absolute path.
Checks dataset_dir and project_dir for valid paths.
| set_dataset_to_absolute_path | python | modelscope/data-juicer | data_juicer/core/data/ray_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/ray_dataset.py | Apache-2.0 |
def schema(self) -> Schema:
"""Get dataset schema.
Returns:
Schema: Dataset schema containing column names and types
"""
if self.data is None or self.data.columns() is None:
raise ValueError('Dataset is empty or not initialized')
# Get schema from Ray da... | Get dataset schema.
Returns:
Schema: Dataset schema containing column names and types
| schema | python | modelscope/data-juicer | data_juicer/core/data/ray_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/ray_dataset.py | Apache-2.0 |
def get_column(self, column: str, k: Optional[int] = None) -> List[Any]:
"""Get column values from Ray dataset.
Args:
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 spec... | Get column values from Ray dataset.
Args:
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
... | get_column | python | modelscope/data-juicer | data_juicer/core/data/ray_dataset.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/ray_dataset.py | Apache-2.0 |
def map_hf_type_to_python(cls, feature):
"""Map HuggingFace feature type to Python type.
Recursively maps nested types (e.g., List[str], Dict[str, int]).
Examples:
Value('string') -> str
Sequence(Value('int32')) -> List[int]
Dict({'text': Value('string')}) -... | Map HuggingFace feature type to Python type.
Recursively maps nested types (e.g., List[str], Dict[str, int]).
Examples:
Value('string') -> str
Sequence(Value('int32')) -> List[int]
Dict({'text': Value('string')}) -> Dict[str, Any]
Args:
feature:... | map_hf_type_to_python | python | modelscope/data-juicer | data_juicer/core/data/schema.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/schema.py | Apache-2.0 |
def map_ray_type_to_python(cls, ray_type: pa.DataType) -> type:
"""Map Ray/Arrow data type to Python type.
Args:
ray_type: PyArrow DataType
Returns:
Corresponding Python type
"""
# String types
if pa.types.is_string(ray_type):
return... | Map Ray/Arrow data type to Python type.
Args:
ray_type: PyArrow DataType
Returns:
Corresponding Python type
| map_ray_type_to_python | python | modelscope/data-juicer | data_juicer/core/data/schema.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/schema.py | Apache-2.0 |
def __str__(self) -> str:
"""Return formatted string representation of schema"""
lines = ['Dataset Schema:']
lines.append('-' * 40)
for col in self.columns:
lines.append(f'{col}: {self.column_types[col]}')
return '\n'.join(lines) | Return formatted string representation of schema | __str__ | python | modelscope/data-juicer | data_juicer/core/data/schema.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/data/schema.py | Apache-2.0 |
def __init__(self, cfg: Optional[Namespace] = None):
"""
Initialization method.
:param cfg: optional jsonargparse Namespace.
"""
super().__init__(cfg)
self.executor_type = 'default'
self.work_dir = self.cfg.work_dir
self.tracer = None
self.ckpt_m... |
Initialization method.
:param cfg: optional jsonargparse Namespace.
| __init__ | python | modelscope/data-juicer | data_juicer/core/executor/default_executor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/executor/default_executor.py | Apache-2.0 |
def run(self,
dataset: Union[Dataset, NestedDataset] = None,
load_data_np: Optional[PositiveInt] = None,
skip_return=False):
"""
Running the dataset process pipeline.
:param dataset: a Dataset object to be executed.
:param load_data_np: number of work... |
Running the dataset process pipeline.
:param dataset: a Dataset object to be executed.
:param load_data_np: number of workers when loading the dataset.
:param skip_return: skip return for API called.
:return: processed dataset.
| run | python | modelscope/data-juicer | data_juicer/core/executor/default_executor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/executor/default_executor.py | Apache-2.0 |
def sample_data(self,
dataset_to_sample: Dataset = None,
load_data_np=None,
sample_ratio: float = 1.0,
sample_algo: str = 'uniform',
**kwargs):
"""
Sample a subset from the given dataset.
TODO add... |
Sample a subset from the given dataset.
TODO add support other than LocalExecutor
:param dataset_to_sample: Dataset to sample from. If None, will use
the formatter linked by the executor. Default is None.
:param load_data_np: number of workers when loading the dataset.
... | sample_data | python | modelscope/data-juicer | data_juicer/core/executor/default_executor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/executor/default_executor.py | Apache-2.0 |
def __init__(self, cfg: Optional[Namespace] = None):
"""
Initialization method.
:param cfg: optional config dict.
"""
super().__init__(cfg)
self.executor_type = 'ray'
self.work_dir = self.cfg.work_dir
self.adapter = Adapter(self.cfg)
# init ray
... |
Initialization method.
:param cfg: optional config dict.
| __init__ | python | modelscope/data-juicer | data_juicer/core/executor/ray_executor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/executor/ray_executor.py | Apache-2.0 |
def run(self,
load_data_np: Optional[PositiveInt] = None,
skip_return=False):
"""
Running the dataset process pipeline
:param load_data_np: number of workers when loading the dataset.
:param skip_return: skip return for API called.
:return: processed data... |
Running the dataset process pipeline
:param load_data_np: number of workers when loading the dataset.
:param skip_return: skip return for API called.
:return: processed dataset.
| run | python | modelscope/data-juicer | data_juicer/core/executor/ray_executor.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/executor/ray_executor.py | Apache-2.0 |
def __init__(self, job_cfg, watcher, *args, **kwargs):
"""
Initialize the hook for refining the recipe via K Sigma
:param job_cfg: the job configs
:param watcher: for watching the result
"""
super(RefineRecipeViaKSigmaHook,
self).__init__(job_cfg, watcher, ... |
Initialize the hook for refining the recipe via K Sigma
:param job_cfg: the job configs
:param watcher: for watching the result
| __init__ | python | modelscope/data-juicer | data_juicer/core/sandbox/hooks.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/hooks.py | Apache-2.0 |
def __init__(self, job_cfg, watcher, *args, **kwargs):
"""
Initialize the hook for refining the recipe via Model Feedback
:param job_cfg: the job configs
:param watcher: for watching the result
"""
super(RefineRecipeViaModelFeedbackHook,
self).__init__(job_... |
Initialize the hook for refining the recipe via Model Feedback
:param job_cfg: the job configs
:param watcher: for watching the result
| __init__ | python | modelscope/data-juicer | data_juicer/core/sandbox/hooks.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/hooks.py | Apache-2.0 |
async def run(self, run_type, run_obj=None, **kwargs):
"""
conduct some model-related execution tasks
given specified run_type and run_obj
"""
watch_task = asyncio.create_task(
self.watch_run(run_type, run_obj, **kwargs))
if self.watcher is None:
... |
conduct some model-related execution tasks
given specified run_type and run_obj
| run | python | modelscope/data-juicer | data_juicer/core/sandbox/model_executors.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/model_executors.py | Apache-2.0 |
async def watch_run(self, run_type, run_obj=None, **kwargs):
"""
watch the running process in an online manner, and
return the summarized results
"""
met_eof = False
while not met_eof:
if os.path.exists(self.watcher.model_exe_log_file):
asy... |
watch the running process in an online manner, and
return the summarized results
| watch_run | python | modelscope/data-juicer | data_juicer/core/sandbox/model_executors.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/model_executors.py | Apache-2.0 |
def __init__(self, sandbox_cfg):
"""
Initialize the watcher with a reference to an executor instance.
"""
# the web-ui and experiment versioning is based on WandB
project_name = sandbox_cfg.project_name
experiment_name = sandbox_cfg.experiment_name
hpo_config = s... |
Initialize the watcher with a reference to an executor instance.
| __init__ | python | modelscope/data-juicer | data_juicer/core/sandbox/pipelines.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/pipelines.py | Apache-2.0 |
def watch(self, res, meta_name: str = ''):
"""
Flatten the result in dot structure and log it into WandB.
"""
if isinstance(res, dict):
for key, value in res.items():
# getting the left nodes of the given res dictionary.
if isinstance(value, di... |
Flatten the result in dot structure and log it into WandB.
| watch | python | modelscope/data-juicer | data_juicer/core/sandbox/pipelines.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/pipelines.py | Apache-2.0 |
def setup_sweep(self, hpo_config: dict = None, project_name: str = None):
"""
Setup and start a new WandB sweep.
"""
if hpo_config is None:
hpo_config = self.sandbox_cfg.hpo_config
if project_name is None:
project_name = self.sandbox_cfg.project_name
... |
Setup and start a new WandB sweep.
| setup_sweep | python | modelscope/data-juicer | data_juicer/core/sandbox/pipelines.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/pipelines.py | Apache-2.0 |
def watch_cfgs(self, cfgs: List[tuple] = None):
"""
Watch the configuration of the experiment.
"""
merged_cfgs = {}
if cfgs is not None:
for cfg, cfg_prefix in cfgs:
# skip empty configs
if cfg is None:
continue
... |
Watch the configuration of the experiment.
| watch_cfgs | python | modelscope/data-juicer | data_juicer/core/sandbox/pipelines.py | https://github.com/modelscope/data-juicer/blob/master/data_juicer/core/sandbox/pipelines.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.