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 _load_local_dataset(self, path: str) -> pd.DataFrame:
"""Loads the dataset from the specified local source.
Returns:
dict: The loaded dataset.
"""
dataset_path = Path(path)
if not dataset_path.exists():
raise FileNotFoundError(f"File not found: {data... | Loads the dataset from the specified local source.
Returns:
dict: The loaded dataset.
| _load_local_dataset | python | oumi-ai/oumi | src/oumi/core/datasets/base_map_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_map_dataset.py | Apache-2.0 |
def _load_hf_hub_dataset(self) -> pd.DataFrame:
"""Loads the dataset from the specified Hugging Face Hub source.
Returns:
dict: The loaded dataset.
"""
splits_or_dataset = datasets.load_dataset(
path=self.dataset_name,
name=self.dataset_subset,
... | Loads the dataset from the specified Hugging Face Hub source.
Returns:
dict: The loaded dataset.
| _load_hf_hub_dataset | python | oumi-ai/oumi | src/oumi/core/datasets/base_map_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_map_dataset.py | Apache-2.0 |
def __init__(
self,
*,
tokenizer: BaseTokenizer,
seq_length: int,
dataset_text_field: str = "text",
append_concat_token: bool = True,
add_special_tokens: bool = True,
skip_last: bool = True,
**kwargs,
):
"""Initializes a new instance of... | Initializes a new instance of the BasePretrainingDataset class. | __init__ | python | oumi-ai/oumi | src/oumi/core/datasets/base_pretraining_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_pretraining_dataset.py | Apache-2.0 |
def __iter__(self):
"""Iterates over the dataset and yields samples of a specified sequence length.
The underlying dataset is a stream of documents. Each document is expected to
contain a text field `self._dataset_text_field` that will be tokenized.
Training samples are then yielded in ... | Iterates over the dataset and yields samples of a specified sequence length.
The underlying dataset is a stream of documents. Each document is expected to
contain a text field `self._dataset_text_field` that will be tokenized.
Training samples are then yielded in sequences of length `self.seq_l... | __iter__ | python | oumi-ai/oumi | src/oumi/core/datasets/base_pretraining_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_pretraining_dataset.py | Apache-2.0 |
def tokenize(self, text: str) -> list[int]:
"""Tokenizes the given text.
Should not apply any padding/truncation to allow for packing.
"""
return self.tokenizer.encode(
text=text,
return_tensors=None,
max_length=None,
padding=False,
... | Tokenizes the given text.
Should not apply any padding/truncation to allow for packing.
| tokenize | python | oumi-ai/oumi | src/oumi/core/datasets/base_pretraining_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_pretraining_dataset.py | Apache-2.0 |
def _create_training_sample(self, tokens: list) -> dict[str, torch.Tensor]:
"""Creates a training sample from the given tokens."""
input_ids = torch.tensor(tokens)
attention_mask = torch.ones_like(input_ids)
return {
"input_ids": input_ids,
"attention_mask": atten... | Creates a training sample from the given tokens. | _create_training_sample | python | oumi-ai/oumi | src/oumi/core/datasets/base_pretraining_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_pretraining_dataset.py | Apache-2.0 |
def __init__(
self,
*,
dataset_name: Optional[str] = None,
dataset_path: Optional[str] = None,
split: Optional[str] = None,
tokenizer: Optional[BaseTokenizer] = None,
task: Literal["sft", "generation", "auto"] = "auto",
return_tensors: bool = False,
... | Initializes a new instance of the BaseSftDataset class. | __init__ | python | oumi-ai/oumi | src/oumi/core/datasets/base_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_sft_dataset.py | Apache-2.0 |
def transform(self, sample: pd.Series) -> dict:
"""Preprocesses the inputs in the given sample."""
conversation = self.transform_conversation(sample)
if self._return_conversations:
# This may require `use_torchdata=True` for TRL_SFT trainer,
# but compatible with TRL_GRPO... | Preprocesses the inputs in the given sample. | transform | python | oumi-ai/oumi | src/oumi/core/datasets/base_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_sft_dataset.py | Apache-2.0 |
def tokenize(
self,
sample: Union[dict, pd.Series, Conversation],
tokenize: bool = True,
) -> dict:
"""Applies the chat template carried by the tokenizer to the input example.
Args:
sample (Dict): Mapping `messages` to a List containing the (ordered)
... | Applies the chat template carried by the tokenizer to the input example.
Args:
sample (Dict): Mapping `messages` to a List containing the (ordered)
messages exchanged within a single chat dialogue.
Each item of example["messages"] is a dict mapping the `content` of t... | tokenize | python | oumi-ai/oumi | src/oumi/core/datasets/base_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_sft_dataset.py | Apache-2.0 |
def __init__(
self,
base_dataset: BaseSftDataset,
max_seq_len: int,
show_progress: bool = True,
split_samples: bool = False,
concat_token_id: Optional[int] = None,
pad_token_id: Optional[int] = None,
enable_padding: bool = True,
**kwargs,
):
... | Initialize the PackedSftDataset.
Args:
base_dataset: The base SFT dataset to pack samples from.
max_seq_len: Maximum sequence length for packed samples.
show_progress: Whether to show progress bar during packing.
Defaults to True.
split_samples: W... | __init__ | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def _load_data(self) -> None:
"""Pack the base dataset into constant-length samples."""
buffer = self._get_empty_buffer()
iterator = range(len(self.base_dataset))
for idx in tqdm(
iterator,
desc="Packing dataset",
dynamic_ncols=True,
disa... | Pack the base dataset into constant-length samples. | _load_data | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
"""Get a pack from the dataset by index."""
if idx >= len(self):
raise IndexError(f"Index {idx} is out of bounds for PackedSftDataset")
return self._data[idx] | Get a pack from the dataset by index. | __getitem__ | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def _append_packed_sample_to_dataset(self, buffer: dict[str, list]) -> None:
"""Creates a fixed length training sample from the buffer and add to dataset."""
buffer_len = self._get_sample_len(buffer)
if buffer_len > self._max_seq_len:
raise ValueError(
"Buffer is too... | Creates a fixed length training sample from the buffer and add to dataset. | _append_packed_sample_to_dataset | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def _append_sample_to_buffer(
self, sample: dict[str, list], buffer: dict[str, list]
) -> None:
"""Append a single training sample to the buffer.
If concat token is enabled, and if and only if we actually concatenate
two samples, we add the concat token in between the two samples
... | Append a single training sample to the buffer.
If concat token is enabled, and if and only if we actually concatenate
two samples, we add the concat token in between the two samples
| _append_sample_to_buffer | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def _split_sample(
self, sample: dict[str, list], cutoff: int
) -> tuple[dict[str, list], dict[str, list]]:
"""Split a sample into two parts at the cutoff point.
Args:
sample: Dictionary containing lists to split
cutoff: Index at which to split the lists
Ret... | Split a sample into two parts at the cutoff point.
Args:
sample: Dictionary containing lists to split
cutoff: Index at which to split the lists
Returns:
Tuple of two dictionaries containing the split lists
| _split_sample | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def _get_empty_buffer(self) -> dict[str, list]:
"""Get an empty buffer with all required fields."""
return {
"input_ids": [],
"labels": [],
} | Get an empty buffer with all required fields. | _get_empty_buffer | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def _get_potential_sample_len(
self, sample: dict[str, list], buffer: dict[str, list]
) -> int:
"""Get the length of the samples in the buffer."""
buffer_len = self._get_sample_len(buffer)
sample_len = self._get_sample_len(sample)
# In case we don't need to add a concat toke... | Get the length of the samples in the buffer. | _get_potential_sample_len | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def _check_dataset_compatibility(self) -> None:
"""Check the base dataset for errors."""
if len(self.base_dataset) == 0:
raise ValueError("Base dataset is empty. Cannot pack empty dataset.")
keys = set(self.base_dataset[0].keys())
if "input_ids" not in keys:
rai... | Check the base dataset for errors. | _check_dataset_compatibility | python | oumi-ai/oumi | src/oumi/core/datasets/packed_sft_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/packed_sft_dataset.py | Apache-2.0 |
def __init__(
self,
tokenizer: Optional[BaseTokenizer],
dataset: datasets.Dataset,
dataset_text_field: Optional[str] = None,
formatting_func: Optional[Callable] = None,
infinite: bool = False,
seq_length: int = 1024,
sequence_buffer_size: int = 1024,
... | Iterable dataset that returns constant length chunks of tokens.
Args:
tokenizer (`BaseTokenizer`):
The tokenizer used for converting strings to tokens.
dataset (`dataset.Dataset`):
Dataset of text samples.
dataset_text_field (`str`, **optional... | __init__ | python | oumi-ai/oumi | src/oumi/core/datasets/pretraining_async_text_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/pretraining_async_text_dataset.py | Apache-2.0 |
def _add_example_to_queue(self, example):
"""Adds a single example to the queue."""
# Shuffle by using a priority queue with random priority values
# Note that the tensors themselves are identical,
# Only the order they are returned is shuffled.
priority = _SMALLEST_PRIORITY_VALU... | Adds a single example to the queue. | _add_example_to_queue | python | oumi-ai/oumi | src/oumi/core/datasets/pretraining_async_text_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/pretraining_async_text_dataset.py | Apache-2.0 |
def __iter__(self):
"""Iterates through the dataset with most work on a separate thread."""
# Set worker thread to daemon so it dies when the program finishes.
worker_thread = threading.Thread(
target=self._dataset_iterator_worker, args=(), daemon=True
)
worker_thread... | Iterates through the dataset with most work on a separate thread. | __iter__ | python | oumi-ai/oumi | src/oumi/core/datasets/pretraining_async_text_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/pretraining_async_text_dataset.py | Apache-2.0 |
def transform(self, sample: dict) -> dict:
"""Transforms an Oumi conversation into a dictionary of inputs for a model.
Args:
sample (dict): A dictionary representing a single conversation example.
Returns:
dict: A dictionary of inputs for a model.
"""
co... | Transforms an Oumi conversation into a dictionary of inputs for a model.
Args:
sample (dict): A dictionary representing a single conversation example.
Returns:
dict: A dictionary of inputs for a model.
| transform | python | oumi-ai/oumi | src/oumi/core/datasets/vision_language_dataset.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/vision_language_dataset.py | Apache-2.0 |
def evaluate(self, config: EvaluationConfig, **kwargs) -> list[EvaluationResult]:
"""Evaluates a model using the provided evaluation configuration.
Args:
config: The desired configuration for evaluation.
kwargs: Additional keyword arguments required by evaluator backends.
... | Evaluates a model using the provided evaluation configuration.
Args:
config: The desired configuration for evaluation.
kwargs: Additional keyword arguments required by evaluator backends.
Returns:
List of evaluation results (one per task, in the same order with `tas... | evaluate | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def evaluate_task(
self,
task_params: EvaluationTaskParams,
config: EvaluationConfig,
**kwargs,
) -> EvaluationResult:
"""Evaluates a model using the provided configuration on a specific task.
Args:
task_params: The task parameters for evaluation.
... | Evaluates a model using the provided configuration on a specific task.
Args:
task_params: The task parameters for evaluation.
config: The desired evaluation configuration for evaluation.
kwargs: Additional keyword arguments required by evaluator backends.
Returns:
... | evaluate_task | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def save_output(
self,
task_params: EvaluationTaskParams,
evaluation_result: EvaluationResult,
base_output_dir: str,
config: Optional[EvaluationConfig],
) -> None:
"""Saves the evaluation's output to the specified output directory.
Args:
task_para... | Saves the evaluation's output to the specified output directory.
Args:
task_params: The task parameters used for this evaluation.
evaluation_result: The evaluation result.
base_output_dir: The directory where the evaluation results will be saved.
config: The eval... | save_output | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def _get_custom_evaluation_fn(task_name: Optional[str]) -> Callable:
"""Retrieve the evaluation function of the custom task."""
if not task_name:
raise ValueError(
"Missing `task_name` for custom Oumi evaluation. Please specify the "
"task name, which should b... | Retrieve the evaluation function of the custom task. | _get_custom_evaluation_fn | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def _get_backend_task_params(
task_params: EvaluationTaskParams,
) -> Union[LMHarnessTaskParams, AlpacaEvalTaskParams]:
"""Returns the evaluation backend-specific task parameters."""
if task_params.get_evaluation_backend() == EvaluationBackend.LM_HARNESS:
target_class = LMHarness... | Returns the evaluation backend-specific task parameters. | _get_backend_task_params | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def _get_init_kwargs_for_task_params_class(
task_params: EvaluationTaskParams,
target_class: type[EvaluationTaskParams],
) -> dict[str, Any]:
"""Returns the init keyword arguments for a `target_class` of name *TaskParams.
Given a target class of name <evaluation backend>TaskParams, ... | Returns the init keyword arguments for a `target_class` of name *TaskParams.
Given a target class of name <evaluation backend>TaskParams, which subclasses
`EvaluationTaskParams`, this method returns a 'flattened' dict with all
arguments needed to instantiate it. The dict includes all the parame... | _get_init_kwargs_for_task_params_class | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def _validate_custom_kwargs(
custom_kwargs: dict[str, Any],
evaluation_fn: Callable,
evaluation_fn_name: str,
) -> None:
"""Validates the keyword arguments of the custom evaluation function."""
# Ensure that user-provided keyword arguments, which are passed into method
... | Validates the keyword arguments of the custom evaluation function. | _validate_custom_kwargs | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def _add_reserved_keys_into_custom_kwargs(
self,
custom_kwargs: dict[str, Any],
evaluation_fn: Callable,
task_params: EvaluationTaskParams,
config: EvaluationConfig,
) -> None:
"""Adds reserved keys into the keyword arguments, if needed.
Reserved keys are key... | Adds reserved keys into the keyword arguments, if needed.
Reserved keys are keys that, if defined in the custom evaluation function
(`evaluation_fn`), are automatically populated by the Evaluator. This function
is responsible to add them into the keyword arguments.
| _add_reserved_keys_into_custom_kwargs | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def _add_inference_engine_if_needed(
self,
evaluation_function: Callable,
kwargs: dict[str, Any],
config: EvaluationConfig,
) -> None:
"""Adds an inference engine to the keyword arguments (`kwargs`), if needed."""
# Check if the evaluation function requires an inferen... | Adds an inference engine to the keyword arguments (`kwargs`), if needed. | _add_inference_engine_if_needed | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def _get_inference_engine(self, config: EvaluationConfig) -> BaseInferenceEngine:
"""Returns the inference engine based on the evaluation configuration."""
if not self._inference_engine:
self._inference_engine = build_inference_engine(
engine_type=config.inference_engine,
... | Returns the inference engine based on the evaluation configuration. | _get_inference_engine | python | oumi-ai/oumi | src/oumi/core/evaluation/evaluator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/evaluator.py | Apache-2.0 |
def bootstrap(
y_true: list[int],
y_pred: list[int],
metric_fn: Callable[..., float],
alpha: float = 0.95,
n_iter: int = 1000,
sample_prop=1.0,
) -> tuple[float, float]:
"""Perform bootstrap resampling to calculate confidence intervals for a metric.
Args:
y_true (list): True lab... | Perform bootstrap resampling to calculate confidence intervals for a metric.
Args:
y_true (list): True labels.
y_pred (list): Predicted labels.
metric_fn (callable): A function that computes a performance metric. The
required signature for this function is:
`metric_f... | bootstrap | python | oumi-ai/oumi | src/oumi/core/evaluation/metrics.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/metrics.py | Apache-2.0 |
def f1_score(
y_true: list[int],
y_pred: list[int],
average: str = "binary",
pos_label: int = 1,
populate_ci: bool = True,
alpha: float = 0.95,
n_iter: int = 1000,
sample_prop=1.0,
) -> Metric:
"""Calculate the F1 score and its confidence interval."""
# Ensure that our inputs are... | Calculate the F1 score and its confidence interval. | f1_score | python | oumi-ai/oumi | src/oumi/core/evaluation/metrics.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/metrics.py | Apache-2.0 |
def evaluate(
task_params: AlpacaEvalTaskParams,
config: EvaluationConfig,
inference_engine: BaseInferenceEngine,
) -> EvaluationResult:
"""Evaluates a model using the Alpaca Eval framework.
For detailed documentation on the AlpacaEval framework, we refer you to the
following readme: https://gi... | Evaluates a model using the Alpaca Eval framework.
For detailed documentation on the AlpacaEval framework, we refer you to the
following readme: https://github.com/tatsu-lab/alpaca_eval.
Args:
task_params: The AlpacaEval parameters to use for evaluation.
config: The desired configuration f... | evaluate | python | oumi-ai/oumi | src/oumi/core/evaluation/backends/alpaca_eval.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/backends/alpaca_eval.py | Apache-2.0 |
def _generate_lm_harness_model_args(
lm_harness_model: str,
is_multimodal: bool,
device: str,
model_params: ModelParams,
generation_params: GenerationParams,
inference_engine_type: InferenceEngineType,
inference_remote_params: Optional[RemoteParams],
) -> dict[str, Any]:
"""Converts Oumi... | Converts Oumi's ModelParams to LM Harness model arguments. | _generate_lm_harness_model_args | python | oumi-ai/oumi | src/oumi/core/evaluation/backends/lm_harness.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/backends/lm_harness.py | Apache-2.0 |
def _apply_to_all_tasks(
task_dict: dict[Union[str, ConfigurableGroup], Union[Task, dict]],
fn: Callable,
fn_kwargs: Optional[dict[str, Any]] = None,
) -> None:
"""Apply the provided function `fn` to all tasks in the `task_dict`."""
fn_kwargs = fn_kwargs or {}
for task_obj in task_dict.values():... | Apply the provided function `fn` to all tasks in the `task_dict`. | _apply_to_all_tasks | python | oumi-ai/oumi | src/oumi/core/evaluation/backends/lm_harness.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/backends/lm_harness.py | Apache-2.0 |
def _get_task_dict(
task_params: LMHarnessTaskParams,
) -> dict[Union[str, ConfigurableGroup], Union[Task, dict]]:
"""Get a dictionary of LM Harness tasks, given Oumi's `task_params`."""
if not task_params.task_name:
raise ValueError("The `task_name` must be specified for LM Harness evaluation.")
... | Get a dictionary of LM Harness tasks, given Oumi's `task_params`. | _get_task_dict | python | oumi-ai/oumi | src/oumi/core/evaluation/backends/lm_harness.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/backends/lm_harness.py | Apache-2.0 |
def _set_random_seeds(random_seed, numpy_random_seed, torch_random_seed) -> None:
"""Setting random seeds for reproducibility and consistency with LM Harness."""
if random_seed is not None:
random.seed(random_seed)
if numpy_random_seed is not None:
np.random.seed(numpy_random_seed)
if ... | Setting random seeds for reproducibility and consistency with LM Harness. | _set_random_seeds | python | oumi-ai/oumi | src/oumi/core/evaluation/backends/lm_harness.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/backends/lm_harness.py | Apache-2.0 |
def evaluate(
task_params: LMHarnessTaskParams,
config: EvaluationConfig,
random_seed: Optional[int] = 0,
numpy_random_seed: Optional[int] = 1234,
torch_random_seed: Optional[int] = 1234,
) -> EvaluationResult:
"""Evaluates a model using the LM Evaluation Harness framework (EleutherAI).
For... | Evaluates a model using the LM Evaluation Harness framework (EleutherAI).
For detailed documentation, we refer you to the following readme:
https://github.com/EleutherAI/lm-evaluation-harness
Args:
task_params: The LM Harness parameters to use for evaluation.
config: The evaluation configu... | evaluate | python | oumi-ai/oumi | src/oumi/core/evaluation/backends/lm_harness.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/backends/lm_harness.py | Apache-2.0 |
def check_prerequisites(
evaluation_backend: EvaluationBackend,
task_name: Optional[str] = None,
) -> None:
"""Check whether the evaluation backend prerequisites are satisfied.
Args:
evaluation_backend: The evaluation backend that the task will run.
task_name (for LM Harness backend onl... | Check whether the evaluation backend prerequisites are satisfied.
Args:
evaluation_backend: The evaluation backend that the task will run.
task_name (for LM Harness backend only): The name of the task to run.
Raises:
RuntimeError: If the evaluation backend prerequisites are not satisfi... | check_prerequisites | python | oumi-ai/oumi | src/oumi/core/evaluation/utils/platform_prerequisites.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/utils/platform_prerequisites.py | Apache-2.0 |
def _find_non_existing_output_dir_from_base_dir(base_dir: Path) -> Path:
"""Finds a new output directory, if the provided `base_dir` already exists.
Why is this function useful?
Users may repeatedly run the same evaluation script, which will overwrite the
results of the existing output director... | Finds a new output directory, if the provided `base_dir` already exists.
Why is this function useful?
Users may repeatedly run the same evaluation script, which will overwrite the
results of the existing output directory. When this happens, we could fail, to
avoid corrupting previous evalua... | _find_non_existing_output_dir_from_base_dir | python | oumi-ai/oumi | src/oumi/core/evaluation/utils/save_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/utils/save_utils.py | Apache-2.0 |
def save_evaluation_output(
backend_name: str,
task_params: EvaluationTaskParams,
evaluation_result: EvaluationResult,
base_output_dir: Optional[str],
config: Optional[EvaluationConfig],
) -> None:
"""Writes configuration settings and evaluation outputs to files.
Args:
backend_name:... | Writes configuration settings and evaluation outputs to files.
Args:
backend_name: The name of the evaluation backend used (e.g., "lm_harness").
task_params: Oumi task parameters used for this evaluation.
evaluation_result: The evaluation results to save.
base_output_dir: The direct... | save_evaluation_output | python | oumi-ai/oumi | src/oumi/core/evaluation/utils/save_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/evaluation/utils/save_utils.py | Apache-2.0 |
def transform_conversation(
self, conversation: Conversation, options: Optional[FeatureGeneratorOptions]
) -> dict:
"""Transforms a single Oumi conversation into a dictionary of model inputs.
Args:
conversation: An input conversation.
options: Options for the feature... | Transforms a single Oumi conversation into a dictionary of model inputs.
Args:
conversation: An input conversation.
options: Options for the feature generator.
Returns:
dict: A dictionary of inputs for a model.
| transform_conversation | python | oumi-ai/oumi | src/oumi/core/feature_generators/base_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/base_feature_generator.py | Apache-2.0 |
def transform_conversations(
self,
conversations: list[Conversation],
options: Optional[FeatureGeneratorOptions],
) -> dict:
"""Transforms a list of Oumi conversations into a dictionary of model inputs.
Args:
conversations: A list of input conversations.
... | Transforms a list of Oumi conversations into a dictionary of model inputs.
Args:
conversations: A list of input conversations.
options: Options for the feature generator.
Returns:
dict: A dictionary of inputs for a model.
| transform_conversations | python | oumi-ai/oumi | src/oumi/core/feature_generators/base_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/base_feature_generator.py | Apache-2.0 |
def _prepare_simple_model(
self, conversation: Conversation
) -> tuple[Image.Image, str]:
"""Prepares the images and prompt for a simple model.
Simple models only use the last image and text turn in the conversation. They
don't use the chat template, so the prompt is just the last t... | Prepares the images and prompt for a simple model.
Simple models only use the last image and text turn in the conversation. They
don't use the chat template, so the prompt is just the last text turn.
| _prepare_simple_model | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def _prepare_instruct_model(
self, conversation: Conversation
) -> tuple[list[Image.Image], str]:
"""Prepares the images and prompt for an instruct model.
Instruct models use the chat template to generate the prompt, and can include
multiple images and text turns.
"""
... | Prepares the images and prompt for an instruct model.
Instruct models use the chat template to generate the prompt, and can include
multiple images and text turns.
| _prepare_instruct_model | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def _load_image(self, image_item: ContentItem) -> Image.Image:
"""Loads an image from a message.
Args:
image_item (`ContentItem`): A content item representing an image.
Returns:
Image.Image: A PIL image.
"""
if self._image_processor is None:
... | Loads an image from a message.
Args:
image_item (`ContentItem`): A content item representing an image.
Returns:
Image.Image: A PIL image.
| _load_image | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def transform_conversation(
self, conversation: Conversation, options: Optional[FeatureGeneratorOptions]
) -> dict:
"""Transforms a single Oumi conversation into a dictionary of model inputs.
Args:
conversation: An input conversation.
options: Options for the feature... | Transforms a single Oumi conversation into a dictionary of model inputs.
Args:
conversation: An input conversation.
options: Options for the feature generator.
Returns:
dict: A dictionary of inputs for a model.
| transform_conversation | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def transform_conversations(
self,
conversations: list[Conversation],
options: Optional[FeatureGeneratorOptions],
) -> dict:
"""Transforms a list of Oumi conversations into a dictionary of model inputs.
Args:
conversations: An input conversation.
opti... | Transforms a list of Oumi conversations into a dictionary of model inputs.
Args:
conversations: An input conversation.
options: Options for the feature generator.
Returns:
dict: A dictionary of inputs for a model.
| transform_conversations | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def _truncate_text_in_content_items(self, messages: list[Message]) -> list[Message]:
"""Truncates text contents in Messages to `max_length` total tokens.
Note that we have to truncate plain texts *before* we apply chat template
as the final processed prompt is generally unsafe to truncate at ar... | Truncates text contents in Messages to `max_length` total tokens.
Note that we have to truncate plain texts *before* we apply chat template
as the final processed prompt is generally unsafe to truncate at arbitrary
offset: it may break invariants (e.g., prompt contains `N` images tokens)
... | _truncate_text_in_content_items | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def _truncate_text_pieces(self, text_pieces: list[str]) -> list[str]:
"""Truncates text pieces to total length not exceeding `max_length`."""
if not (
self._truncation and self._max_length is not None and self._max_length > 0
):
return copy.deepcopy(text_pieces)
... | Truncates text pieces to total length not exceeding `max_length`. | _truncate_text_pieces | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def _apply_completion_only_masking(self, inputs: Any) -> None:
"""Apply masking to keep only assistant responses for loss computation."""
labels = inputs.get("labels")
input_ids = inputs.get("input_ids")
if labels is None or input_ids is None:
raise ValueError(
... | Apply masking to keep only assistant responses for loss computation. | _apply_completion_only_masking | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def _mask_single_conversation(
self, labels: np.ndarray, input_ids: np.ndarray
) -> None:
"""Mask a single conversation to keep only assistant responses."""
ignore_index = int(self._special_tokens.label_ignore_index or -100)
# Choose masking strategy based on whether instruction tok... | Mask a single conversation to keep only assistant responses. | _mask_single_conversation | python | oumi-ai/oumi | src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/feature_generators/vision_language_conversation_feature_generator.py | Apache-2.0 |
def __init__(
self,
model_params: ModelParams,
*,
generation_params: Optional[GenerationParams] = None,
):
"""Initializes the inference engine.
Args:
model_params: The model parameters.
generation_params: The generation parameters.
"""... | Initializes the inference engine.
Args:
model_params: The model parameters.
generation_params: The generation parameters.
| __init__ | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def infer(
self,
input: Optional[list[Conversation]] = None,
inference_config: Optional[InferenceConfig] = None,
) -> list[Conversation]:
"""Runs model inference.
Args:
input: A list of conversations to run inference on. Optional.
inference_config: Pa... | Runs model inference.
Args:
input: A list of conversations to run inference on. Optional.
inference_config: Parameters for inference.
If not specified, a default config is inferred.
Returns:
List[Conversation]: Inference output.
| infer | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def _maybe_log_latency_histogram(self, histogram: Optional[HdrHistogram]) -> None:
"""Logs the histogram if it is not None.
Args:
histogram: The histogram to log.
"""
if histogram is None:
return
total_count = histogram.get_total_count()
# TODO: D... | Logs the histogram if it is not None.
Args:
histogram: The histogram to log.
| _maybe_log_latency_histogram | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def _read_conversations(self, input_filepath: str) -> list[Conversation]:
"""Reads conversations from a file in Oumi chat format.
Args:
input_filepath: The path to the file containing the conversations.
Returns:
List[Conversation]: A list of conversations read from the ... | Reads conversations from a file in Oumi chat format.
Args:
input_filepath: The path to the file containing the conversations.
Returns:
List[Conversation]: A list of conversations read from the file.
| _read_conversations | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def _get_scratch_filepath(self, output_filepath: Optional[str]) -> str:
"""Returns a scratch filepath for the given output filepath.
For example, if the output filepath is "/foo/bar/output.json", the scratch
filepath will be "/foo/bar/scratch/output.json"
If no output filepath is provi... | Returns a scratch filepath for the given output filepath.
For example, if the output filepath is "/foo/bar/output.json", the scratch
filepath will be "/foo/bar/scratch/output.json"
If no output filepath is provided, a temporary file is used and placed in the
current working directory u... | _get_scratch_filepath | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def _save_conversation_to_scratch(
self, conversation: Conversation, output_filepath: Optional[str]
) -> None:
"""Appends a conversation to a file in Oumi chat format.
Args:
conversation: The conversation to save.
output_filepath: The path to the file where the conve... | Appends a conversation to a file in Oumi chat format.
Args:
conversation: The conversation to save.
output_filepath: The path to the file where the conversation should be
saved.
| _save_conversation_to_scratch | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def _cleanup_scratch_file(self, output_filepath: Optional[str]) -> None:
"""Delete the scratch file from the file system if it exists.
Args:
output_filepath: The path to the output file. This is used to determine the
location of the scratch file.
"""
scratch_... | Delete the scratch file from the file system if it exists.
Args:
output_filepath: The path to the output file. This is used to determine the
location of the scratch file.
| _cleanup_scratch_file | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def _save_conversations(
self, conversations: list[Conversation], output_filepath: str
) -> None:
"""Saves conversations to a file in Oumi chat format.
Args:
conversations: A list of conversations to save.
output_filepath: The path to the file where the conversations... | Saves conversations to a file in Oumi chat format.
Args:
conversations: A list of conversations to save.
output_filepath: The path to the file where the conversations should be
saved.
| _save_conversations | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def _check_unsupported_params(self, generation_params: GenerationParams):
"""Checks for unsupported parameters and logs warnings.
If a parameter is not supported, and a non-default value is provided,
a warning is logged.
"""
supported_params = self.get_supported_params()
... | Checks for unsupported parameters and logs warnings.
If a parameter is not supported, and a non-default value is provided,
a warning is logged.
| _check_unsupported_params | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def infer_online(
self,
input: list[Conversation],
inference_config: Optional[InferenceConfig] = None,
) -> list[Conversation]:
"""Runs model inference online.
Args:
input: A list of conversations to run inference on.
inference_config: Parameters for ... | Runs model inference online.
Args:
input: A list of conversations to run inference on.
inference_config: Parameters for inference.
Returns:
List[Conversation]: Inference output.
| infer_online | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def infer_from_file(
self,
input_filepath: str,
inference_config: Optional[InferenceConfig] = None,
) -> list[Conversation]:
"""Runs model inference on inputs in the provided file.
This is a convenience method to prevent boilerplate from asserting the existence
of in... | Runs model inference on inputs in the provided file.
This is a convenience method to prevent boilerplate from asserting the existence
of input_filepath in the generation_params.
Args:
input_filepath: Path to the input file containing prompts for generation.
inference_co... | infer_from_file | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def apply_chat_template(
self, conversation: Conversation, **tokenizer_kwargs
) -> str:
"""Applies the chat template to the conversation.
Args:
conversation: The conversation to apply the chat template to.
tokenizer_kwargs: Additional keyword arguments to pass to the... | Applies the chat template to the conversation.
Args:
conversation: The conversation to apply the chat template to.
tokenizer_kwargs: Additional keyword arguments to pass to the tokenizer.
Returns:
str: The conversation with the chat template applied.
| apply_chat_template | python | oumi-ai/oumi | src/oumi/core/inference/base_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/inference/base_inference_engine.py | Apache-2.0 |
def __call__(
self,
images: list[PIL.Image.Image],
*,
return_tensors: Optional[str] = "pt",
) -> transformers.BatchFeature:
"""Extracts image features.
Args:
images: A list of input images.
return_tensors: The format of returned tensors.
... | Extracts image features.
Args:
images: A list of input images.
return_tensors: The format of returned tensors.
Returns:
transformers.BatchFeature: The model-specific input features.
| __call__ | python | oumi-ai/oumi | src/oumi/core/processors/base_image_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/base_image_processor.py | Apache-2.0 |
def __call__(
self,
*,
text: list[str],
padding: bool,
images: Optional[list[PIL.Image.Image]] = None,
return_tensors: Optional[str] = "pt",
) -> transformers.BatchEncoding:
"""Invokes the processor to extract features.
Args:
text: A list ... | Invokes the processor to extract features.
Args:
text: A list of text prompts.
padding: Whether to pad sequences to common length.
images: A list of input images.
return_tensors: The format of returned tensors.
Returns:
transformers.BatchEnco... | __call__ | python | oumi-ai/oumi | src/oumi/core/processors/base_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/base_processor.py | Apache-2.0 |
def apply_chat_template(
self, conversation: list[Message], add_generation_prompt: bool = False
) -> str:
"""Applies a chat template.
Args:
conversation: A list of messages (conversation "turns").
add_generation_prompt: Whether to append generation prompt to the outp... | Applies a chat template.
Args:
conversation: A list of messages (conversation "turns").
add_generation_prompt: Whether to append generation prompt to the output.
Returns:
A text prompt, which includes all input messages formatted into a string.
| apply_chat_template | python | oumi-ai/oumi | src/oumi/core/processors/base_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/base_processor.py | Apache-2.0 |
def truncate_text(
self,
text: str,
*,
max_tokens: int,
truncation_side: str = "right",
) -> tuple[str, int]:
"""Truncates text to `max_length` in tokens.
Args:
text: A text prompt.
max_tokens: Maximum number of tokens to keep.
... | Truncates text to `max_length` in tokens.
Args:
text: A text prompt.
max_tokens: Maximum number of tokens to keep.
truncation_side: The side to truncate the tokens ("right" or "left").
Returns:
A tuple containing truncated text prompt and the number of t... | truncate_text | python | oumi-ai/oumi | src/oumi/core/processors/base_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/base_processor.py | Apache-2.0 |
def __call__(
self,
images: list[PIL.Image.Image],
*,
return_tensors: Optional[str] = "pt",
) -> transformers.BatchFeature:
"""Extracts image features.
Args:
images: A list of input images.
return_tensors: The format of returned tensors.
... | Extracts image features.
Args:
images: A list of input images.
return_tensors: The format of returned tensors.
Returns:
transformers.BatchFeature: The model-specific input features.
| __call__ | python | oumi-ai/oumi | src/oumi/core/processors/default_image_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/default_image_processor.py | Apache-2.0 |
def tokenizer(self, new_tokenizer: BaseTokenizer) -> None:
"""Sets a tokenizer associated with this processor."""
self._worker_processor.tokenizer = new_tokenizer
self._tokenizer = new_tokenizer | Sets a tokenizer associated with this processor. | tokenizer | python | oumi-ai/oumi | src/oumi/core/processors/default_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/default_processor.py | Apache-2.0 |
def __call__(
self,
*,
text: list[str],
padding: bool,
images: Optional[list[PIL.Image.Image]] = None,
return_tensors: Optional[str] = "pt",
) -> transformers.BatchEncoding:
"""Invokes the processor to extract features.
Args:
text: A list ... | Invokes the processor to extract features.
Args:
text: A list of text prompts.
padding: Whether to pad sequences to common length.
images: A list of input images.
return_tensors: The format of returned tensors.
Returns:
transformers.BatchEnco... | __call__ | python | oumi-ai/oumi | src/oumi/core/processors/default_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/default_processor.py | Apache-2.0 |
def apply_chat_template(
self, conversation: list[Message], add_generation_prompt: bool = False
) -> str:
"""Applies a chat template.
Args:
conversation: A list of messages (conversation "turns").
add_generation_prompt: Whether to append generation prompt to the outp... | Applies a chat template.
Args:
conversation: A list of messages (conversation "turns").
add_generation_prompt: Whether to append generation prompt to the output.
Returns:
A text prompt, which includes all input messages formatted into a string.
| apply_chat_template | python | oumi-ai/oumi | src/oumi/core/processors/default_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/default_processor.py | Apache-2.0 |
def save_config(self, output_dir: Union[Path, str]) -> None:
"""Saves processor config to the directory."""
if not (
hasattr(self._worker_processor, "save_pretrained")
and self._worker_processor.save_pretrained is not None
and callable(self._worker_processor.save_pret... | Saves processor config to the directory. | save_config | python | oumi-ai/oumi | src/oumi/core/processors/default_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/default_processor.py | Apache-2.0 |
def truncate_text(
self,
text: str,
*,
max_tokens: int,
truncation_side: str = "right",
) -> tuple[str, int]:
"""Truncates text to `max_length` in tokens.
Args:
text: A text prompt.
max_tokens: Maximum number of tokens to keep.
... | Truncates text to `max_length` in tokens.
Args:
text: A text prompt.
max_tokens: Maximum number of tokens to keep.
truncation_side: The side to truncate the tokens ("right" or "left").
Returns:
A tuple containing truncated text prompt and the number of t... | truncate_text | python | oumi-ai/oumi | src/oumi/core/processors/default_processor.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/processors/default_processor.py | Apache-2.0 |
def _load_user_requirements(requirements_file: str):
"""Loads user-defined requirements from a file."""
logger.info(f"Loading user-defined registry from: {requirements_file}")
logger.info(
"This value can be set using the OUMI_EXTRA_DEPS_FILE environment variable."
)
requirements_path = Path... | Loads user-defined requirements from a file. | _load_user_requirements | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def _register_dependencies(cls_function):
"""Decorator to ensure core dependencies are added to the Registry."""
@functools.wraps(cls_function)
def wrapper(self, *args, **kwargs):
if not self._initialized:
# Immediately set the initialized flag to avoid infinite recursion.
s... | Decorator to ensure core dependencies are added to the Registry. | _register_dependencies | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def get(
self,
name: str,
type: RegistryType,
) -> Optional[Callable]:
"""Gets a record by name and type."""
registry_key = RegistryKey(name, type)
return self._registry.get(registry_key) | Gets a record by name and type. | get | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def get_all(self, type: RegistryType) -> dict:
"""Gets all records of a specific type."""
return {
key.name: value
for key, value in self._registry.items()
if key.registry_type == type
} | Gets all records of a specific type. | get_all | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def get_dataset(
self, name: str, subset: Optional[str] = None
) -> Optional[Callable]:
"""Gets a record that corresponds to a registered dataset."""
if subset:
# If a subset is provided, first check for subset-specific dataset.
# If not found, try to get the dataset ... | Gets a record that corresponds to a registered dataset. | get_dataset | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def __getitem__(self, args: tuple[str, RegistryType]) -> Callable:
"""Gets a record by name and type."""
if not isinstance(args, tuple) or len(args) != 2:
raise ValueError(
"Expected a tuple of length 2 with the first element being the name "
"and the second e... | Gets a record by name and type. | __getitem__ | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def register(registry_name: str, registry_type: RegistryType) -> Callable:
"""Returns function to register decorated `obj` in the Oumi global registry.
Args:
registry_name: The name that the object should be registered with.
registry_type: The type of object we are registering.
Returns:
... | Returns function to register decorated `obj` in the Oumi global registry.
Args:
registry_name: The name that the object should be registered with.
registry_type: The type of object we are registering.
Returns:
Decorator function to register the target object.
| register | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def register_dataset(registry_name: str, subset: Optional[str] = None) -> Callable:
"""Returns function to register decorated `obj` in the Oumi global registry.
Args:
registry_name: The name that the object should be registered with.
subset: The type of object we are registering.
Returns:
... | Returns function to register decorated `obj` in the Oumi global registry.
Args:
registry_name: The name that the object should be registered with.
subset: The type of object we are registering.
Returns:
Decorator function to register the target object.
| register_dataset | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def decorator_register(obj):
"""Decorator to register its target `obj`."""
full_name = f"{registry_name}/{subset}" if subset else registry_name
REGISTRY.register(name=full_name, type=RegistryType.DATASET, value=obj)
return obj | Decorator to register its target `obj`. | decorator_register | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def register_cloud_builder(registry_name: str) -> Callable:
"""Returns a function to register decorated builder in the Oumi global registry.
Use this decorator to register cloud builder functions in the global registry.
A cloud builder function is a function that accepts no arguments and returns an
ins... | Returns a function to register decorated builder in the Oumi global registry.
Use this decorator to register cloud builder functions in the global registry.
A cloud builder function is a function that accepts no arguments and returns an
instance of a class that implements the `BaseCloud` interface.
Ar... | register_cloud_builder | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def register_judge(registry_name: str) -> Callable:
"""Returns a function to register a judge configuration in the Oumi global registry.
This decorator is used to register judge configuration in the global registry.
A judge configuration function typically returns a JudgeConfig object that defines
the ... | Returns a function to register a judge configuration in the Oumi global registry.
This decorator is used to register judge configuration in the global registry.
A judge configuration function typically returns a JudgeConfig object that defines
the parameters and attributes for a specific judge.
Args:
... | register_judge | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def register_evaluation_function(registry_name: str) -> Callable:
"""Returns function to register an evaluation function in the Oumi global registry.
Args:
registry_name: The name that the evaluation function should be registered with.
Returns:
Decorator function to register the target eva... | Returns function to register an evaluation function in the Oumi global registry.
Args:
registry_name: The name that the evaluation function should be registered with.
Returns:
Decorator function to register the target evaluation function.
| register_evaluation_function | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def decorator_register(obj):
"""Decorator to register its target `obj`."""
check_evaluation_function_signature(obj)
REGISTRY.register(
name=registry_name, type=RegistryType.EVALUATION_FUNCTION, value=obj
)
return obj | Decorator to register its target `obj`. | decorator_register | python | oumi-ai/oumi | src/oumi/core/registry/registry.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/registry/registry.py | Apache-2.0 |
def get_default_special_tokens(
tokenizer: Optional[BaseTokenizer],
) -> SpecialTokensMixin:
"""Returns the default special tokens for the tokenizer that was provided.
Args:
tokenizer: The tokenizer to get special tokens for.
Returns:
The special tokens mixin for the tokenizer.
De... | Returns the default special tokens for the tokenizer that was provided.
Args:
tokenizer: The tokenizer to get special tokens for.
Returns:
The special tokens mixin for the tokenizer.
Description:
This function looks up the special tokens for the provided tokenizer, for a list
... | get_default_special_tokens | python | oumi-ai/oumi | src/oumi/core/tokenizers/special_tokens.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/tokenizers/special_tokens.py | Apache-2.0 |
def tokenize_for_completions_only_training_with_template(
tokenizer: BaseTokenizer, conversation: Conversation
) -> dict:
"""Tokenize a conversation for completions-only training with a template."""
batch: transformers.BatchEncoding = tokenizer.apply_chat_template(
conversation=conversation, # type... | Tokenize a conversation for completions-only training with a template. | tokenize_for_completions_only_training_with_template | python | oumi-ai/oumi | src/oumi/core/tokenizers/utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/tokenizers/utils.py | Apache-2.0 |
def tokenize_for_completions_only_training_with_prefix(
tokenizer: BaseTokenizer,
conversation: Conversation,
response_template: str,
instruction_template: str,
response_token_ids: list[int],
instruction_token_ids: list[int],
) -> dict:
"""Tokenize a conversation for completions-only trainin... | Tokenize a conversation for completions-only training with a prefix. | tokenize_for_completions_only_training_with_prefix | python | oumi-ai/oumi | src/oumi/core/tokenizers/utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/tokenizers/utils.py | Apache-2.0 |
def mask_labels_without_user_template(
labels: np.ndarray,
response_token_ids: list[int],
ignore_index: int = LABEL_IGNORE_INDEX,
) -> None:
"""Apply completion-only masking when no user template is provided.
This strategy masks everything except the last assistant response, allowing
the model ... | Apply completion-only masking when no user template is provided.
This strategy masks everything except the last assistant response, allowing
the model to learn only from the final assistant turn in the conversation.
Args:
labels: Label array to mask
response_token_ids: Token IDs of the res... | mask_labels_without_user_template | python | oumi-ai/oumi | src/oumi/core/tokenizers/utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/tokenizers/utils.py | Apache-2.0 |
def mask_labels_for_completions_only(
labels: np.ndarray,
response_token_ids: list[int],
instruction_token_ids: list[int],
ignore_index: int = LABEL_IGNORE_INDEX,
) -> None:
"""Apply completion-only masking to labels with user and assistant templates.
This strategy masks everything except assis... | Apply completion-only masking to labels with user and assistant templates.
This strategy masks everything except assistant response content, using user
templates to determine the boundaries of each assistant response.
Args:
labels: Label array to mask
response_token_ids: Token IDs of the r... | mask_labels_for_completions_only | python | oumi-ai/oumi | src/oumi/core/tokenizers/utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/tokenizers/utils.py | Apache-2.0 |
def find_all_sequences(arr: np.ndarray, target: list[int]) -> list[int]:
"""Find all occurrences of target sequence in array.
Returns the positions of the target sequence AFTER the found sequence.
"""
arr_list = arr.tolist()
positions = []
for i in range(len(arr_list) - len(target) + 1):
... | Find all occurrences of target sequence in array.
Returns the positions of the target sequence AFTER the found sequence.
| find_all_sequences | python | oumi-ai/oumi | src/oumi/core/tokenizers/utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/tokenizers/utils.py | Apache-2.0 |
def save_state(self) -> None:
"""Saves the Trainer state.
Under distributed environment this is done only for a process with rank 0.
"""
# TODO: Define semantics of this method more clearly.
# Can it be merged with save_model()? | Saves the Trainer state.
Under distributed environment this is done only for a process with rank 0.
| save_state | python | oumi-ai/oumi | src/oumi/core/trainers/base_trainer.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/base_trainer.py | Apache-2.0 |
def save_model(self, config: TrainingConfig, final: bool = True) -> None:
"""Saves the model's weights to the specified output directory.
Args:
config: The Oumi training config.
final: Whether this is the final model being saved during training.
- Applies optimiz... | Saves the model's weights to the specified output directory.
Args:
config: The Oumi training config.
final: Whether this is the final model being saved during training.
- Applies optimizations for the final model checkpoint.
- In the case of FSDP, this wi... | save_model | python | oumi-ai/oumi | src/oumi/core/trainers/hf_trainer.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/hf_trainer.py | Apache-2.0 |
def _save_model(self, config: TrainingConfig, final: bool = True) -> None:
"""Saves the model's weights to the specified output directory."""
if not is_world_process_zero():
return
output_dir = config.training.output_dir
if not config.training.use_peft:
self._hf_... | Saves the model's weights to the specified output directory. | _save_model | python | oumi-ai/oumi | src/oumi/core/trainers/hf_trainer.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/hf_trainer.py | Apache-2.0 |
def _save_fsdp_model(self, config: TrainingConfig, final: bool = True) -> None:
"""Saves the model's weights to the specified output directory.
For FSDP, all ranks should call into this function
"""
if final:
# For the final checkpoint, we need to save the FULL_STATE_DICT in... | Saves the model's weights to the specified output directory.
For FSDP, all ranks should call into this function
| _save_fsdp_model | python | oumi-ai/oumi | src/oumi/core/trainers/hf_trainer.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/hf_trainer.py | Apache-2.0 |
def _train_epoch(self, progress_bar: tqdm) -> None:
"""Trains the model for one epoch."""
epoch_start_time = time.perf_counter()
self.model.train()
self._cuda_sync_and_empty_cache()
self.optimizer.zero_grad(set_to_none=True)
micro_step = 0
data_iter = iter(self.... | Trains the model for one epoch. | _train_epoch | python | oumi-ai/oumi | src/oumi/core/trainers/oumi_trainer.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/oumi_trainer.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.