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 _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 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 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 _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 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 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
def evaluate(self) -> dict[str, float]: """Evaluates the model on the evaluation dataset.""" if self.eval_dataloader is None: raise ValueError("No evaluation dataloader provided.") self.model.eval() eval_losses = [] for batch in tqdm( self.eval_dataloade...
Evaluates the model on the evaluation dataset.
evaluate
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
def _load_from_checkpoint(self, checkpoint_dirname: str): """Loads the training state from a checkpoint.""" checkpoint_dir = Path(checkpoint_dirname) device_rank_info = get_device_rank_info() model_path = checkpoint_dir / "model" optimizer_path = checkpoint_dir / "optimizer" ...
Loads the training state from a checkpoint.
_load_from_checkpoint
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
def log_metrics(self, metrics: dict[str, Any], step: int) -> None: """Logs metrics to wandb and tensorboard.""" # Log to console and log file if not is_world_process_zero(): return self.log(pformat(metrics)) # Log to Weights and Biases if self.params.enable_w...
Logs metrics to wandb and tensorboard.
log_metrics
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
def _set_sampler_epoch(self, epoch: int) -> None: """Sets the current epoch on sampler, if it exists and supports it.""" if self._sampler and hasattr(self._sampler, "set_epoch"): self.log(f"Setting sampler epoch to {epoch}.") self._sampler.set_epoch(epoch)
Sets the current epoch on sampler, if it exists and supports it.
_set_sampler_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
def _process_callbacks( self, event: str, logs: Optional[dict[str, Any]] = None ) -> dict[str, Any]: """Process callbacks. Extremely hacky way to handle HF callbacks. Just here to unblock debugging with our MfuCallback """ logs = logs or {} for callback in s...
Process callbacks. Extremely hacky way to handle HF callbacks. Just here to unblock debugging with our MfuCallback
_process_callbacks
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
def __init__( self, processing_class: Optional[BaseTokenizer], config: TrainingConfig, reward_funcs: list[Callable], train_dataset: Dataset, eval_dataset: Dataset, processor: Optional[BaseProcessor] = None, cache_dir: Optional[Union[str, Path]] = None, ...
Initializes the verl trainer. Args: processing_class: The tokenizer for the model. config: Training config. reward_funcs: List of reward functions to use. train_dataset: Training dataset. eval_dataset: Validation dataset. This is required by verl. ...
__init__
python
oumi-ai/oumi
src/oumi/core/trainers/verl_grpo_trainer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/verl_grpo_trainer.py
Apache-2.0
def _detect_dataset_process_fn( self, ) -> Optional[_DatasetProcessFn]: """Returns a post-processing function to convert data to verl format. Examines dataset samples to determine what post-processing function to use. Returns: A post-processing function to convert data ...
Returns a post-processing function to convert data to verl format. Examines dataset samples to determine what post-processing function to use. Returns: A post-processing function to convert data to verl format. If no post-processing is needed, returns `None`.
_detect_dataset_process_fn
python
oumi-ai/oumi
src/oumi/core/trainers/verl_grpo_trainer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/verl_grpo_trainer.py
Apache-2.0
def _get_data_source_name(params: DatasetSplitParams) -> str: """Returns the verl data source name.""" dataset_names = list({ds.dataset_name for ds in params.datasets}) if len(dataset_names) != 1: if len(dataset_names) > 1: raise ValueError( f"Mult...
Returns the verl data source name.
_get_data_source_name
python
oumi-ai/oumi
src/oumi/core/trainers/verl_grpo_trainer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/verl_grpo_trainer.py
Apache-2.0
def _extract_question_images_answer_from_single_turn_conversation( example: dict, ) -> tuple[str, list, str]: """Finds question, answer, and optional images in a single-turn conversation. Args: example: A dictionary containing the conversation JSON. Returns: ...
Finds question, answer, and optional images in a single-turn conversation. Args: example: A dictionary containing the conversation JSON. Returns: A tuple containing the question, images, and answer. The list of images is empty for text-only conversations.
_extract_question_images_answer_from_single_turn_conversation
python
oumi-ai/oumi
src/oumi/core/trainers/verl_grpo_trainer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/verl_grpo_trainer.py
Apache-2.0
def _create_dataset_files( self, process_fn: Optional[_DatasetProcessFn] = None ) -> None: """Creates dataset files for verl in Parquet format. The Parquet files are saved to the Oumi cache directory. Args: process_fn: Optional function to convert the dataset samples to...
Creates dataset files for verl in Parquet format. The Parquet files are saved to the Oumi cache directory. Args: process_fn: Optional function to convert the dataset samples to verl format.
_create_dataset_files
python
oumi-ai/oumi
src/oumi/core/trainers/verl_grpo_trainer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/verl_grpo_trainer.py
Apache-2.0
def train(self, resume_from_checkpoint: Optional[str] = None) -> None: """Trains the model using verl's RayPPOTrainer. Args: resume_from_checkpoint: Optional path to a checkpoint to resume from. """ if resume_from_checkpoint: raise NotImplementedError("Resuming f...
Trains the model using verl's RayPPOTrainer. Args: resume_from_checkpoint: Optional path to a checkpoint to resume from.
train
python
oumi-ai/oumi
src/oumi/core/trainers/verl_grpo_trainer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/verl_grpo_trainer.py
Apache-2.0
def _export_hf_model(self) -> bool: """Exports the tuned model to HF format. This method is called after training is complete. Returns: True if the model is exported successfully, False otherwise. """ if not (self._final_output_dir and self._temp_output_dir): ...
Exports the tuned model to HF format. This method is called after training is complete. Returns: True if the model is exported successfully, False otherwise.
_export_hf_model
python
oumi-ai/oumi
src/oumi/core/trainers/verl_grpo_trainer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/trainers/verl_grpo_trainer.py
Apache-2.0
def _convert_role_to_proto_role(role: Role) -> pb2.Role: """Converts a Role enum to Protocol Buffer format.""" result: pb2.Role = _ROLE_TO_PROTO_ROLE_MAP.get(role, pb2.Role.ROLE_UNSPECIFIED) if result == pb2.Role.ROLE_UNSPECIFIED: raise ValueError(f"Invalid role: {role}") return result
Converts a Role enum to Protocol Buffer format.
_convert_role_to_proto_role
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def _convert_proto_role_to_role(role: pb2.Role) -> Role: """Converts a Protocol Buffer role format to role.""" result: Optional[Role] = _PROTO_ROLE_TO_ROLE_MAP.get(role, None) if result is None: raise ValueError(f"Invalid role: {role}") return result
Converts a Protocol Buffer role format to role.
_convert_proto_role_to_role
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def _convert_type_to_proto_type(content_type: Type) -> pb2.ContentPart.Type: """Converts a type enum to Protocol Buffer format.""" result: pb2.ContentPart.Type = _CONTENT_ITEM_TYPE_TO_PROTO_TYPE_MAP.get( content_type, pb2.ContentPart.TYPE_UNSPECIFIED ) if result == pb2.ContentPart.TYPE_UNSPECIFI...
Converts a type enum to Protocol Buffer format.
_convert_type_to_proto_type
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def _convert_proto_type_to_type(content_type: pb2.ContentPart.Type) -> Type: """Converts a Protocol Buffer type format to type.""" result: Optional[Type] = _CONTENT_ITEM_PROTO_TYPE_TO_TYPE_MAP.get( content_type, None ) if result is None: raise ValueError(f"Invalid type: {content_type}") ...
Converts a Protocol Buffer type format to type.
_convert_proto_type_to_type
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def _encode_binary(self, value: Optional[bytes]) -> str: """Encode binary value as base64 ASCII string. This is needed for compatibility with JSON. """ if value is None or len(value) == 0: return "" return base64.b64encode(value).decode("ascii")
Encode binary value as base64 ASCII string. This is needed for compatibility with JSON.
_encode_binary
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def model_post_init(self, __context) -> None: """Post-initialization method for the `ContentItem` model. This method is automatically called after the model is initialized. Performs additional validation e.g., to ensure that either content or binary is provided for the message. ...
Post-initialization method for the `ContentItem` model. This method is automatically called after the model is initialized. Performs additional validation e.g., to ensure that either content or binary is provided for the message. Raises: ValueError: If fields are set to inv...
model_post_init
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def from_proto(item_proto: pb2.ContentPart) -> "ContentItem": """Converts a Protocol Buffer to a content item.""" if item_proto.HasField("blob") and item_proto.blob: return ContentItem( type=_convert_proto_type_to_type(item_proto.type), binary=item_proto.blob....
Converts a Protocol Buffer to a content item.
from_proto
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def to_proto(self) -> pb2.ContentPart: """Converts a content item to Protocol Buffer format.""" if self.binary is not None and len(self.binary) > 0: return pb2.ContentPart( type=_convert_type_to_proto_type(self.type), blob=pb2.DataBlob(binary_data=self.binary)...
Converts a content item to Protocol Buffer format.
to_proto
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def model_post_init(self, __context) -> None: """Post-initialization method for the Message model. This method is automatically called after the model is initialized. It performs additional validation to ensure that either content or binary is provided for the message. Raises: ...
Post-initialization method for the Message model. This method is automatically called after the model is initialized. It performs additional validation to ensure that either content or binary is provided for the message. Raises: ValueError: If both content and binary are No...
model_post_init
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def compute_flattened_text_content(self, separator=" ") -> str: """Joins contents of all text items.""" return separator.join( [(item.content or "") for item in self.text_content_items] )
Joins contents of all text items.
compute_flattened_text_content
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def contains_images(self) -> bool: """Checks if the message contains at least one image.""" first_image = next(self._iter_content_items(return_images=True), None) return first_image is not None
Checks if the message contains at least one image.
contains_images
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def contains_text(self) -> bool: """Checks if the message contains at least one text item.""" first_text = next(self._iter_content_items(return_text=True), None) return first_text is not None
Checks if the message contains at least one text item.
contains_text
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def contains_image_content_items_only(self) -> bool: """Checks if the message contains only image items. At least one image item is required. """ counts = self.count_content_items() return counts.image_items > 0 and counts.image_items == counts.total_items
Checks if the message contains only image items. At least one image item is required.
contains_image_content_items_only
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def contains_text_content_items_only(self) -> bool: """Checks if the message contains only text items. At least one text item is required. """ counts = self.count_content_items() return counts.text_items > 0 and counts.text_items == counts.total_items
Checks if the message contains only text items. At least one text item is required.
contains_text_content_items_only
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def contains_single_text_content_item_only(self) -> bool: """Checks if the message contains exactly 1 text item, and nothing else. These are the most common and simple messages, and may need special handling. """ counts = self.count_content_items() return counts.text_items == 1 ...
Checks if the message contains exactly 1 text item, and nothing else. These are the most common and simple messages, and may need special handling.
contains_single_text_content_item_only
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def contains_single_image_content_item_only(self) -> bool: """Checks if the message contains exactly 1 image item, and nothing else.""" counts = self.count_content_items() return counts.image_items == 1 and counts.image_items == counts.total_items
Checks if the message contains exactly 1 image item, and nothing else.
contains_single_image_content_item_only
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def to_proto(self) -> pb2.Message: """Converts a message to Protocol Buffer format.""" return pb2.Message( id=self.id, role=_convert_role_to_proto_role(self.role), parts=[item.to_proto() for item in self.content_items], )
Converts a message to Protocol Buffer format.
to_proto
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def __repr__(self) -> str: """Returns a string representation of the message.""" id_str = "" if self.id: id_str = f"{self.id} - " return f"{id_str}{self.role.upper()}: " + " | ".join( [repr(item) for item in self._iter_all_content_items()] )
Returns a string representation of the message.
__repr__
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def first_message(self, role: Optional[Role] = None) -> Optional[Message]: """Gets the first message in the conversation, optionally filtered by role. Args: role: The role to filter messages by. If None, considers all messages. Returns: Optional[Message]...
Gets the first message in the conversation, optionally filtered by role. Args: role: The role to filter messages by. If None, considers all messages. Returns: Optional[Message]: The first message matching the criteria, or None if no messages are ...
first_message
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def last_message(self, role: Optional[Role] = None) -> Optional[Message]: """Gets the last message in the conversation, optionally filtered by role. Args: role: The role to filter messages by. If None, considers all messages. Returns: Optional[Message]: ...
Gets the last message in the conversation, optionally filtered by role. Args: role: The role to filter messages by. If None, considers all messages. Returns: Optional[Message]: The last message matching the criteria, or None if no messages are fo...
last_message
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def filter_messages( self, *, role: Optional[Role] = None, filter_fn: Optional[Callable[[Message], bool]] = None, ) -> list[Message]: """Gets all messages in the conversation, optionally filtered by role. Args: role (Optional): The role to filter messages...
Gets all messages in the conversation, optionally filtered by role. Args: role (Optional): The role to filter messages by. If None, no filtering by role is applied. filter_fn (Optional): A predicate to filter messages by. If the predicate returns True for...
filter_messages
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def append_id_to_string(self, s: str) -> str: """Appends conversation ID to a string. Can be useful for log or exception errors messages to allow users to identify relevant conversation. """ if not self.conversation_id: return s suffix = f"Conversation id: {s...
Appends conversation ID to a string. Can be useful for log or exception errors messages to allow users to identify relevant conversation.
append_id_to_string
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def to_json(self) -> str: """Converts the conversation to a JSON string.""" return self.model_dump_json( exclude_unset=True, exclude_defaults=False, exclude_none=True )
Converts the conversation to a JSON string.
to_json
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def from_proto(conversation_proto: pb2.Conversation) -> "Conversation": """Converts a conversation from Protocol Buffer format.""" result: Conversation = Conversation( conversation_id=(conversation_proto.conversation_id or None), messages=[Message.from_proto(m) for m in conversat...
Converts a conversation from Protocol Buffer format.
from_proto
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def to_proto(self) -> pb2.Conversation: """Converts a conversation to Protocol Buffer format.""" result = pb2.Conversation( conversation_id=self.conversation_id, messages=[m.to_proto() for m in self.messages], ) if self.metadata is not None: for key, v...
Converts a conversation to Protocol Buffer format.
to_proto
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def content(self) -> str: """Renders the content of the message.""" template = Template(self.template) fields = self.model_dump() fields.pop("template") # remove the template from the fields return template.render(**fields).strip()
Renders the content of the message.
content
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def message(self) -> Message: """Returns the message in oumi format.""" content = str(self.content) return Message(content=content, role=self.role)
Returns the message in oumi format.
message
python
oumi-ai/oumi
src/oumi/core/types/conversation.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/types/conversation.py
Apache-2.0
def __init__( self, dataset_size: int = 1000, feature_dim: int = 128, data_type: str = "float32", num_classes: int = 10, preprocessing_time_ms: float = 0, **kwargs, ): """Initialize a DebugClassificationDataset. This dataset generates random d...
Initialize a DebugClassificationDataset. This dataset generates random data and labels for debugging purposes. Args: dataset_size: The size of the dataset. feature_dim: The dimension of each feature. data_type: The data type of the dataset. Supported...
__init__
python
oumi-ai/oumi
src/oumi/datasets/debug.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/debug.py
Apache-2.0
def __getitem__(self, idx): """Return the data and label at the given index.""" if self.preprocessing_time_ms > 0: time.sleep(self.preprocessing_time_ms * 1000) return {"features": self.data[idx], "labels": self.labels[idx]}
Return the data and label at the given index.
__getitem__
python
oumi-ai/oumi
src/oumi/datasets/debug.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/debug.py
Apache-2.0
def __init__( self, dataset_size: int = 1000, **kwargs, ): """Initializes a DebugPretrainingDataset. Args: dataset_size: The size of the dataset. **kwargs: Additional keyword arguments. """ self.size = dataset_size super().__...
Initializes a DebugPretrainingDataset. Args: dataset_size: The size of the dataset. **kwargs: Additional keyword arguments.
__init__
python
oumi-ai/oumi
src/oumi/datasets/debug.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/debug.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transforms the example into a Conversation object.""" return Conversation( messages=[ Message( role=Role.USER, content=(example.get("user_message", None) or "") ...
Transforms the example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/debug.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/debug.py
Apache-2.0
def transform_preference(self, sample: dict) -> dict: """Transforms the sample into a preference dict.""" return { "prompt": sample["prompt"], "chosen": sample["chosen"], "rejected": sample["rejected"], }
Transforms the sample into a preference dict.
transform_preference
python
oumi-ai/oumi
src/oumi/datasets/debug.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/debug.py
Apache-2.0
def few_shots(cls, dev_data: Dataset, num_shots: int) -> str: """Returns `num_shots` formatted shots from the provided `dev_data`.""" if not num_shots: return "" shots: Dataset = dev_data.select(range(num_shots)) return "".join( cls.format_example(example, include...
Returns `num_shots` formatted shots from the provided `dev_data`.
few_shots
python
oumi-ai/oumi
src/oumi/datasets/mmlu.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/mmlu.py
Apache-2.0
def _prompt_template(self, example: dict[str, Any]) -> str: """Generates the prompt template for evaluations. This template is the "original" MMLU implementation by github.com/ollmer. For details and undertanding the different options to evaluate with MMLU, see: https://huggingface.co/b...
Generates the prompt template for evaluations. This template is the "original" MMLU implementation by github.com/ollmer. For details and undertanding the different options to evaluate with MMLU, see: https://huggingface.co/blog/open-llm-leaderboard-mmlu. After appying the template, the...
_prompt_template
python
oumi-ai/oumi
src/oumi/datasets/mmlu.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/mmlu.py
Apache-2.0
def _update_few_shot_dict(self, subject: str): """Adds few-shot examples for `subject` in the relevant dictionary.""" assert subject in SUBJECTS dataset_dict: DatasetDict = load_dataset("cais/mmlu", subject) # type: ignore dev_dataset: Dataset = dataset_dict["dev"] few_shots = M...
Adds few-shot examples for `subject` in the relevant dictionary.
_update_few_shot_dict
python
oumi-ai/oumi
src/oumi/datasets/mmlu.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/mmlu.py
Apache-2.0
def __init__( self, *, include_system_prompt: bool = False, unused_entries_to_metadata: bool = False, trust_remote_code: bool = True, **kwargs, ) -> None: """Initializes a new instance of the AlpacaEvalDataset class. Args: include_system_p...
Initializes a new instance of the AlpacaEvalDataset class. Args: include_system_prompt: Whether to include a system prompt in the conversation. unused_entries_to_metadata (bool): Whether to save entries that were not used in the conversation (entries othe...
__init__
python
oumi-ai/oumi
src/oumi/datasets/evaluation/alpaca.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/evaluation/alpaca.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Preprocesses the inputs of the example and returns a dictionary. Args: example (dict or Pandas Series): An example containing `input` (optional), `instruction` entries. Returns: ...
Preprocesses the inputs of the example and returns a dictionary. Args: example (dict or Pandas Series): An example containing `input` (optional), `instruction` entries. Returns: dict: The input example converted to Alpaca dictionary format. Note: ...
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/evaluation/alpaca.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/evaluation/alpaca.py
Apache-2.0
def conversation_to_alpaca_format( conversation: Conversation, instruction_field_name: str = _DEFAULT_INSTRUCTION_FIELD_NAME, output_field_name: str = _DEFAULT_OUTPUT_FIELD_NAME, ) -> dict: """Converts an Oumi `Conversation` to Alpaca format. Converts an Oumi single-turn conversation to a dictionar...
Converts an Oumi `Conversation` to Alpaca format. Converts an Oumi single-turn conversation to a dictionary with keys `instruction` and `output`. If the first message is a System Instruction, it is ignored. Any fields in the conversation's metadata are also retained as dict entries. Alpaca format (see...
conversation_to_alpaca_format
python
oumi-ai/oumi
src/oumi/datasets/evaluation/utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/evaluation/utils.py
Apache-2.0
def conversations_to_alpaca_format( conversations: list[Conversation], instruction_field_name: str = _DEFAULT_INSTRUCTION_FIELD_NAME, output_field_name: str = _DEFAULT_OUTPUT_FIELD_NAME, ) -> list[dict]: """Converts a list of conversations to Alpaca format (list of dictionaries).""" return [ ...
Converts a list of conversations to Alpaca format (list of dictionaries).
conversations_to_alpaca_format
python
oumi-ai/oumi
src/oumi/datasets/evaluation/utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/evaluation/utils.py
Apache-2.0
def transform(self, sample: pd.Series) -> dict: """Transform the sample into Python `dict`.""" # Add system prompt before user prompt. system_message = {"content": _SYSTEM_PROMPT, "role": "system"} messages = [system_message, sample["messages"][0]] return { "prompt": ...
Transform the sample into Python `dict`.
transform
python
oumi-ai/oumi
src/oumi/datasets/grpo/berry_bench.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/berry_bench.py
Apache-2.0
def transform_conversation(self, sample: pd.Series) -> Conversation: """Converts the input sample to a Conversation. Args: sample (dict): The input example. Returns: Conversation: The resulting conversation. """ # Example is already in conversation form...
Converts the input sample to a Conversation. Args: sample (dict): The input example. Returns: Conversation: The resulting conversation.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/grpo/berry_bench.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/berry_bench.py
Apache-2.0
def transform(self, sample: pd.Series) -> dict: """Validate and transform the sample into Python `dict`.""" # Convert nums from np array to list target = int(sample["target"]) nums = [int(num) for num in sample["nums"]] prompt = _PROMPT_TEMPLATE.format(nums=nums, target=target) ...
Validate and transform the sample into Python `dict`.
transform
python
oumi-ai/oumi
src/oumi/datasets/grpo/countdown.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/countdown.py
Apache-2.0
def compute_soft_target_token_length_reward(num_tokens: int, *, target_tokens: int): """Returns maximum reward for inputs that are `target_tokens` long. The reward is in the [0,1] range and reduces smoothly from the maximum value of 1.0 if the actual number of tokens deviates from `target_tokens`. The...
Returns maximum reward for inputs that are `target_tokens` long. The reward is in the [0,1] range and reduces smoothly from the maximum value of 1.0 if the actual number of tokens deviates from `target_tokens`. The reward is proportional to: `x*exp(-x)` where `x := num_tokens/target_tokens`.
compute_soft_target_token_length_reward
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/completion_length_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/completion_length_rewards.py
Apache-2.0
def _extract_solution(solution_str: str) -> Optional[str]: """Extracts the equation from the solution string. Args: solution_str: The response from the LLM. Returns: The equation from the solution string, or None if not found. """ solution_str = solution_str.split("\n")[-1] an...
Extracts the equation from the solution string. Args: solution_str: The response from the LLM. Returns: The equation from the solution string, or None if not found.
_extract_solution
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/countdown_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/countdown_rewards.py
Apache-2.0
def _validate_equation(equation_str: str, available_numbers: list[int]) -> bool: """Validates that equation only uses available numbers and each number once. Args: equation_str: The equation to validate. available_numbers: The list of available numbers. Returns: True if the equatio...
Validates that equation only uses available numbers and each number once. Args: equation_str: The equation to validate. available_numbers: The list of available numbers. Returns: True if the equation uses each available number exactly once, else False.
_validate_equation
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/countdown_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/countdown_rewards.py
Apache-2.0
def _evaluate_equation(equation_str: str) -> Optional[float]: """Safely evaluates the arithmetic equation using eval() with precautions.""" try: # Regex that only allows numbers, operators, parentheses and whitespace allowed_pattern = r"^[\d+\-*/().\s]+$" if not re.match(allowed_pattern,...
Safely evaluates the arithmetic equation using eval() with precautions.
_evaluate_equation
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/countdown_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/countdown_rewards.py
Apache-2.0
def countdown_reward( data_source: str, solution_str: str, ground_truth: dict[str, Any], extra_info: dict[str, Any], format_score=0.0, score=1.0, ) -> float: """Custom reward function for the Countdown task. Currently, this function only works with the VERL_GRPO trainer. Args: ...
Custom reward function for the Countdown task. Currently, this function only works with the VERL_GRPO trainer. Args: data_source: The data source. solution_str: The response from the LLM. ground_truth: Dictionary containing target number and available numbers extra_info: Extra ...
countdown_reward
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/countdown_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/countdown_rewards.py
Apache-2.0