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 __iter__(self) -> Iterator[tuple[str, Any]]: """Returns an iterator over field names and values. Note: for an attribute to be a field, it must be declared in the dataclass definition and have a type annotation. """ for param in dataclasses.fields(self): yield par...
Returns an iterator over field names and values. Note: for an attribute to be a field, it must be declared in the dataclass definition and have a type annotation.
__iter__
python
oumi-ai/oumi
src/oumi/core/configs/base_config.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/base_config.py
Apache-2.0
def messages(self) -> list[Message]: """Returns the messages in oumi format. This will include the judge system prompt, and any few-shot examples. """ messages = [Message(content=self.system_prompt, role=Role.SYSTEM)] return messages + [e.message for e in self.examples]
Returns the messages in oumi format. This will include the judge system prompt, and any few-shot examples.
messages
python
oumi-ai/oumi
src/oumi/core/configs/judge_config.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/judge_config.py
Apache-2.0
def load(cls: type, filename: str) -> "JudgeAttribute[T]": """Loads the judge attribute config from a file.""" path = Path(filename) if not path.exists(): raise FileNotFoundError(path) return cls.model_validate_json(path.read_text())
Loads the judge attribute config from a file.
load
python
oumi-ai/oumi
src/oumi/core/configs/judge_config.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/judge_config.py
Apache-2.0
def find_model_hf_config( model_name: str, *, trust_remote_code: bool, revision: Optional[str] = None, **kwargs: dict[str, Any], ): """Finds HF model config by model name.""" hf_config, unused_kwargs = transformers.AutoConfig.from_pretrained( model_name, trust_remote_code=tru...
Finds HF model config by model name.
find_model_hf_config
python
oumi-ai/oumi
src/oumi/core/configs/internal/supported_models.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/internal/supported_models.py
Apache-2.0
def _create_default_vlm_config( *, supports_multiple_images: bool = False, pixel_values_variable_shape: bool = False, pixel_values_first_dim_action: InternalFeatureFirstDimAction = ( InternalFeatureFirstDimAction.DROP_IF_DUMMY ), ) -> InternalModelConfig: """Creates a default configurati...
Creates a default configuration for vision-language models. This function provides a base configuration that can be used for most VLMs. It sets up the basic visual features and configurations that VLMs typically need. Args: supports_multiple_images: Whether the model can process multiple images in...
_create_default_vlm_config
python
oumi-ai/oumi
src/oumi/core/configs/internal/supported_models.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/internal/supported_models.py
Apache-2.0
def _create_molmo_vlm_config() -> InternalModelConfig: """Creates a config for Molmo VLM model. Molmo uses a specific set of features including image masks and input indices for handling images in the model. The config is set up to handle these features appropriately. """ config = InternalModel...
Creates a config for Molmo VLM model. Molmo uses a specific set of features including image masks and input indices for handling images in the model. The config is set up to handle these features appropriately.
_create_molmo_vlm_config
python
oumi-ai/oumi
src/oumi/core/configs/internal/supported_models.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/internal/supported_models.py
Apache-2.0
def get_all_models_map() -> Mapping[ str, # model type _ModelTypeInfo, ]: """Creates a map of all supported models with their configurations. This is the central registry of the non-standard models supported by the Oumi framework. Each entry maps a model type (as defined in the HuggingFace model c...
Creates a map of all supported models with their configurations. This is the central registry of the non-standard models supported by the Oumi framework. Each entry maps a model type (as defined in the HuggingFace model config) to its corresponding configuration and metadata. Returns: An immut...
get_all_models_map
python
oumi-ai/oumi
src/oumi/core/configs/internal/supported_models.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/internal/supported_models.py
Apache-2.0
def is_custom_model(model_name: str) -> bool: """Determines whether the model is a custom model defined in oumi registry.""" result: bool = len(model_name) > 0 and REGISTRY.contains( name=model_name, type=RegistryType.MODEL ) return result
Determines whether the model is a custom model defined in oumi registry.
is_custom_model
python
oumi-ai/oumi
src/oumi/core/configs/internal/supported_models.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/internal/supported_models.py
Apache-2.0
def find_internal_model_config_using_model_name( model_name: str, trust_remote_code: bool ) -> Optional[InternalModelConfig]: """Finds an internal model config for supported models using model name. Args: model_name: The model name, either: - A HuggingFace model ID (e.g., "meta-llama/Ll...
Finds an internal model config for supported models using model name. Args: model_name: The model name, either: - A HuggingFace model ID (e.g., "meta-llama/Llama-2-7b-hf") - A local path to a model directory - A custom model name registered in Oumi trust_remote_c...
find_internal_model_config_using_model_name
python
oumi-ai/oumi
src/oumi/core/configs/internal/supported_models.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/internal/supported_models.py
Apache-2.0
def find_internal_model_config( model_params: ModelParams, ) -> Optional[InternalModelConfig]: """Finds an internal model config for supported models using `ModelParams`. Args: model_params: The model parameters. Returns: Model config, or `None` if model is not recognized. """ ...
Finds an internal model config for supported models using `ModelParams`. Args: model_params: The model parameters. Returns: Model config, or `None` if model is not recognized.
find_internal_model_config
python
oumi-ai/oumi
src/oumi/core/configs/internal/supported_models.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/internal/supported_models.py
Apache-2.0
def _finalize_and_validate(self, validated: Optional[set[int]]) -> None: """Recursively finalizes and validates the parameters.""" if validated is None: validated = set() # If this object has already been validated, return immediately if id(self) in validated: re...
Recursively finalizes and validates the parameters.
_finalize_and_validate
python
oumi-ai/oumi
src/oumi/core/configs/params/base_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/base_params.py
Apache-2.0
def get_literal_value(self) -> Literal["first_exhausted", "all_exhausted"]: """Returns a literal value of the enum.""" if self.value == MixtureStrategy.FIRST_EXHAUSTED: return "first_exhausted" elif self.value == MixtureStrategy.ALL_EXHAUSTED: return "all_exhausted" ...
Returns a literal value of the enum.
get_literal_value
python
oumi-ai/oumi
src/oumi/core/configs/params/data_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/data_params.py
Apache-2.0
def get_split(self, split: DatasetSplit) -> DatasetSplitParams: """A public getting for individual dataset splits.""" if split == DatasetSplit.TRAIN: return self.train elif split == DatasetSplit.TEST: return self.test elif split == DatasetSplit.VALIDATION: ...
A public getting for individual dataset splits.
get_split
python
oumi-ai/oumi
src/oumi/core/configs/params/data_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/data_params.py
Apache-2.0
def get_evaluation_backend(self) -> EvaluationBackend: """Returns the evaluation backend as an Enum.""" if not self.evaluation_backend: raise ValueError( "Missing `evaluation_backend`. When running evaluations, it is " "necessary to specify the evaluation back...
Returns the evaluation backend as an Enum.
get_evaluation_backend
python
oumi-ai/oumi
src/oumi/core/configs/params/evaluation_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/evaluation_params.py
Apache-2.0
def to_torch(self) -> torch_fsdp.ShardingStrategy: """Convert the enum to the corresponding torch_fsdp.ShardingStrategy.""" strategy_map = { ShardingStrategy.FULL_SHARD: torch_fsdp.ShardingStrategy.FULL_SHARD, ShardingStrategy.SHARD_GRAD_OP: torch_fsdp.ShardingStrategy.SHARD_GRAD...
Convert the enum to the corresponding torch_fsdp.ShardingStrategy.
to_torch
python
oumi-ai/oumi
src/oumi/core/configs/params/fsdp_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/fsdp_params.py
Apache-2.0
def to_torch(self) -> torch_fsdp.StateDictType: """Converts to the corresponding torch.distributed.fsdp.StateDictType.""" state_dict_map = { StateDictType.FULL_STATE_DICT: torch_fsdp.StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT: ( torch_fsdp.Sta...
Converts to the corresponding torch.distributed.fsdp.StateDictType.
to_torch
python
oumi-ai/oumi
src/oumi/core/configs/params/fsdp_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/fsdp_params.py
Apache-2.0
def to_torch(self) -> Optional[torch_fsdp.BackwardPrefetch]: """Convert the enum to the corresponding torch_fsdp.BackwardPrefetch.""" map = { BackwardPrefetch.BACKWARD_PRE: torch_fsdp.BackwardPrefetch.BACKWARD_PRE, BackwardPrefetch.BACKWARD_POST: torch_fsdp.BackwardPrefetch.BACKW...
Convert the enum to the corresponding torch_fsdp.BackwardPrefetch.
to_torch
python
oumi-ai/oumi
src/oumi/core/configs/params/fsdp_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/fsdp_params.py
Apache-2.0
def to_hf_trainer_kwargs(self) -> dict[str, Any]: """Converts GrpoParams to TRL's GRPOConfig kwargs.""" result = {} if len(self.model_init_kwargs) > 0: result["model_init_kwargs"] = self.model_init_kwargs if self.max_prompt_length is not None: result["max_prompt_l...
Converts GrpoParams to TRL's GRPOConfig kwargs.
to_hf_trainer_kwargs
python
oumi-ai/oumi
src/oumi/core/configs/params/grpo_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/grpo_params.py
Apache-2.0
def __finalize_and_validate__(self): """Finalizes and validates final config params.""" # If the user didn't specify a LoRA adapter, check to see if the dir/repo # specified by `model_name` contains an adapter, and set `adapter_name` if so. if self.adapter_model is None: # Th...
Finalizes and validates final config params.
__finalize_and_validate__
python
oumi-ai/oumi
src/oumi/core/configs/params/model_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/model_params.py
Apache-2.0
def to_bits_and_bytes(self) -> BitsAndBytesConfig: """Creates a configuration for quantized models via BitsAndBytes. The resulting configuration uses the instantiated peft parameters. """ quantization_config = BitsAndBytesConfig( load_in_4bit=self.q_lora_bits == 4, ...
Creates a configuration for quantized models via BitsAndBytes. The resulting configuration uses the instantiated peft parameters.
to_bits_and_bytes
python
oumi-ai/oumi
src/oumi/core/configs/params/peft_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/peft_params.py
Apache-2.0
def _check_attribute_ids(self, attribute_ids: set[str], id: str): """Check if the attribute ID is already in the set.""" if id in attribute_ids: raise ValueError( f"GeneralSynthesisParams contains duplicate attribute IDs: {id}" ) attribute_ids.add(id)
Check if the attribute ID is already in the set.
_check_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_dataset_source_attribute_ids(self, all_attribute_ids: set[str]) -> None: """Check attribute IDs from dataset sources for uniqueness.""" if self.input_data is None: return if len(self.input_data) == 0: raise ValueError("GeneralSynthesisParams.input_data cannot ...
Check attribute IDs from dataset sources for uniqueness.
_check_dataset_source_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_document_source_attribute_ids(self, all_attribute_ids: set[str]) -> None: """Check attribute IDs from document sources for uniqueness.""" if self.input_documents is None: return if len(self.input_documents) == 0: raise ValueError("GeneralSynthesisParams.input_...
Check attribute IDs from document sources for uniqueness.
_check_document_source_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_example_source_attribute_ids(self, all_attribute_ids: set[str]) -> None: """Check attribute IDs from example sources for uniqueness.""" if self.input_examples is None: return if len(self.input_examples) == 0: raise ValueError("GeneralSynthesisParams.input_exam...
Check attribute IDs from example sources for uniqueness.
_check_example_source_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_permutable_attribute_ids(self, all_attribute_ids: set[str]) -> None: """Check attribute IDs from permutable attributes for uniqueness.""" if self.permutable_attributes is None: return if len(self.permutable_attributes) == 0: raise ValueError( "...
Check attribute IDs from permutable attributes for uniqueness.
_check_permutable_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_generated_attribute_ids(self, all_attribute_ids: set[str]) -> None: """Check attribute IDs from generated attributes for uniqueness.""" if self.generated_attributes is None: return if len(self.generated_attributes) == 0: raise ValueError( "Gene...
Check attribute IDs from generated attributes for uniqueness.
_check_generated_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_transformed_attribute_ids(self, all_attribute_ids: set[str]) -> None: """Check attribute IDs from transformed attributes for uniqueness.""" if self.transformed_attributes is None: return if len(self.transformed_attributes) == 0: raise ValueError( ...
Check attribute IDs from transformed attributes for uniqueness.
_check_transformed_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_combination_sampling_sample_rates(self) -> None: """Validate that the combination sample rates are <= 1.0.""" if self.combination_sampling is None: return if len(self.combination_sampling) == 0: raise ValueError( "GeneralSynthesisParams.combina...
Validate that the combination sample rates are <= 1.0.
_check_combination_sampling_sample_rates
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def _check_passthrough_attribute_ids(self) -> None: """Validate that passthrough attributes are non-empty when defined.""" if self.passthrough_attributes is None: return if len(self.passthrough_attributes) == 0: raise ValueError( "GeneralSynthesisParams.p...
Validate that passthrough attributes are non-empty when defined.
_check_passthrough_attribute_ids
python
oumi-ai/oumi
src/oumi/core/configs/params/synthesis_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/synthesis_params.py
Apache-2.0
def to_hf(self): """Converts Oumi config to HuggingFace's TrainingArguments.""" save_strategy: str = "no" if self.save_epoch: save_strategy = "epoch" if self.save_steps > 0: save_strategy = "steps" dataloader_num_workers = 0 if isinstance(self.dat...
Converts Oumi config to HuggingFace's TrainingArguments.
to_hf
python
oumi-ai/oumi
src/oumi/core/configs/params/training_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/training_params.py
Apache-2.0
def _get_hf_report_to(self) -> list[str]: """Gets the list of reporting tools enabled for the current instance. Returns: list: A list of reporting tools enabled. Possible values are "wandb", "tensorboard", or "none". """ report_to = [] if self.enable_...
Gets the list of reporting tools enabled for the current instance. Returns: list: A list of reporting tools enabled. Possible values are "wandb", "tensorboard", or "none".
_get_hf_report_to
python
oumi-ai/oumi
src/oumi/core/configs/params/training_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/training_params.py
Apache-2.0
def telemetry_dir(self) -> Optional[Path]: """Returns the telemetry stats output directory.""" result: Optional[Path] = None if self.telemetry.telemetry_dir: result = Path(self.telemetry.telemetry_dir) if self.output_dir: output_dir = Path(self.output_dir) ...
Returns the telemetry stats output directory.
telemetry_dir
python
oumi-ai/oumi
src/oumi/core/configs/params/training_params.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/params/training_params.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, return_tensors: bool = False, **kwargs, ) -> None: """Initializes a new insta...
Initializes a new instance of the BaseExperimentalDpoDataset class.
__init__
python
oumi-ai/oumi
src/oumi/core/datasets/base_dpo_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_dpo_dataset.py
Apache-2.0
def transform_preference(self, samples: dict) -> dict: """Transform the samples to the Oumi format.""" prompt = samples[_PROMPT_KEY] chosen_chat = samples[_CHOSEN_KEY] rejected_chat = samples[_REJECTED_KEY] chosen_chat_response = self._extract_from_chat_format(chosen_chat) ...
Transform the samples to the Oumi format.
transform_preference
python
oumi-ai/oumi
src/oumi/core/datasets/base_dpo_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_dpo_dataset.py
Apache-2.0
def _extract_from_chat_format(self, sample: dict) -> str: """Extract the last 'assistant' turn in the chat.""" for turn in sample[::-1]: if turn[_ROLE] == _ASSISTANT: return turn[_CONTENT] raise ValueError("No chat turn was found with an 'assistant' role.")
Extract the last 'assistant' turn in the chat.
_extract_from_chat_format
python
oumi-ai/oumi
src/oumi/core/datasets/base_dpo_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_dpo_dataset.py
Apache-2.0
def __init__( self, *, dataset_name: Optional[str] = None, dataset_path: Optional[str] = None, split: Optional[str] = None, **kwargs, ) -> None: """Initializes a new instance of the BaseExperimentalGrpoDataset class.""" super().__init__( da...
Initializes a new instance of the BaseExperimentalGrpoDataset class.
__init__
python
oumi-ai/oumi
src/oumi/core/datasets/base_grpo_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_grpo_dataset.py
Apache-2.0
def _transform_grpo_example(self, example: Union[dict, pd.Series]) -> dict: """Validate and transform the GRPO sample into Python `dict`.""" for required_key in (_PROMPT_KEY, _COMPLETION_KEY): if required_key not in example: raise ValueError( f"Example doe...
Validate and transform the GRPO sample into Python `dict`.
_transform_grpo_example
python
oumi-ai/oumi
src/oumi/core/datasets/base_grpo_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_grpo_dataset.py
Apache-2.0
def transform_conversation(self, sample: Union[dict, pd.Series]) -> Conversation: """Converts the input sample to a Conversation. Args: sample (Union[dict, pd.Series]): The input example. Returns: Conversation: The resulting conversation. """ # Contains...
Converts the input sample to a Conversation. Args: sample (Union[dict, pd.Series]): The input example. Returns: Conversation: The resulting conversation.
transform_conversation
python
oumi-ai/oumi
src/oumi/core/datasets/base_grpo_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_grpo_dataset.py
Apache-2.0
def __init__( self, *, dataset_name: Optional[str] = None, dataset_path: Optional[str] = None, subset: Optional[str] = None, split: Optional[str] = None, trust_remote_code: bool = False, stream: bool = True, **kwargs, ) -> None: """Init...
Initializes a new instance of the BaseIterableDataset class.
__init__
python
oumi-ai/oumi
src/oumi/core/datasets/base_iterable_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_iterable_dataset.py
Apache-2.0
def to_hf(self, return_iterable: bool = True) -> datasets.IterableDataset: """Converts the dataset to a Hugging Face dataset.""" if not return_iterable: raise NotImplementedError("Only returning IterableDataset is supported.") return datasets.IterableDataset.from_generator(self.__ite...
Converts the dataset to a Hugging Face dataset.
to_hf
python
oumi-ai/oumi
src/oumi/core/datasets/base_iterable_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_iterable_dataset.py
Apache-2.0
def _load_data(self) -> Iterable[Any]: """Loads the dataset from the specified source.""" if self.dataset_path: result = self._load_local_dataset(self.dataset_path) else: result = self._load_hf_hub_dataset() return result
Loads the dataset from the specified source.
_load_data
python
oumi-ai/oumi
src/oumi/core/datasets/base_iterable_dataset.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/datasets/base_iterable_dataset.py
Apache-2.0
def __init__( self, *, dataset_name: Optional[str], dataset_path: Optional[str] = None, subset: Optional[str] = None, split: Optional[str] = None, trust_remote_code: bool = False, transform_num_workers: Optional[Union[str, int]] = None, **kwargs, ...
Initializes a new instance of the BaseDataset class.
__init__
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 __getitem__(self, idx: int) -> dict: """Gets the item at the specified index. Args: idx (int): The index of the item to retrieve. Returns: dict: The item at the specified index. """ sample = self.raw(idx) processed = self.transform(sample) ...
Gets the item at the specified index. Args: idx (int): The index of the item to retrieve. Returns: dict: The item at the specified index.
__getitem__
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 _as_generator_over_shards( self, shards: list[_ExamplesIndicesRange] ) -> Generator[dict[str, Any], None, None]: """Returns a sharded generator for the dataset.""" for shard in shards: for idx in range(shard.start_index, shard.end_index): yield self[idx]
Returns a sharded generator for the dataset.
_as_generator_over_shards
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 _detect_features_and_estimate_element_size_bytes( self, samples_iter: Iterable[dict[str, Any]] ) -> _InferredFeatureMap: """Returns an estimate of max element size in bytes.""" samples_list = list(samples_iter) def _dummy_generator(): yield from samples_list ...
Returns an estimate of max element size in bytes.
_detect_features_and_estimate_element_size_bytes
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 _compute_effective_transform_num_workers(self) -> int: """Returns an effective number of dataset transform workers. Guaranteed to be a positive integer (>= 1). 1 if no parallelism is used. """ num_proc = None if self.transform_num_workers is not None: if isinstan...
Returns an effective number of dataset transform workers. Guaranteed to be a positive integer (>= 1). 1 if no parallelism is used.
_compute_effective_transform_num_workers
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 to_hf( self, return_iterable: bool = False ) -> Union[datasets.Dataset, datasets.IterableDataset]: """Converts the dataset to a Hugging Face dataset. Args: return_iterable: Whether to return an iterable dataset. Iterable datasets aren't cached to disk, which ...
Converts the dataset to a Hugging Face dataset. Args: return_iterable: Whether to return an iterable dataset. Iterable datasets aren't cached to disk, which can sometimes be advantageous. For example, if transformed examples are very large (e.g., if `...
to_hf
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_data(self) -> pd.DataFrame: """Loads the dataset from the specified source. Returns: dict: The loaded dataset. """ if self.dataset_path: result = self._load_local_dataset(self.dataset_path) else: result = self._load_hf_hub_dataset() ...
Loads the dataset from the specified source. Returns: dict: The loaded dataset.
_load_data
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_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_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