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 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 transform_conversation(self, sample: pd.Series) -> Conversation: """Validate and transform the sample into Python `dict`.""" sample_dict = self.transform(sample) prompt_message = sample_dict["prompt"][0] del sample_dict["prompt"] conversation_dict = {"messages": [prompt_messa...
Validate and transform the sample into Python `dict`.
transform_conversation
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 transform(self, sample: pd.Series) -> dict: """Validate and 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 { ...
Validate and transform the sample into Python `dict`.
transform
python
oumi-ai/oumi
src/oumi/datasets/grpo/letter_count.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/letter_count.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/letter_count.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/letter_count.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
def _extract_prediction(response: str) -> Optional[int]: r"""Returns the numeric answer extracted from `\boxed{...}`, or None otherwise.""" regex_result = re.findall(r"\\boxed\{([-+]?\d+)\}", response) if not regex_result or len(regex_result) != 1: return None number_str = regex_result[0] # ...
Returns the numeric answer extracted from `\boxed{...}`, or None otherwise.
_extract_prediction
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/count_letters_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/count_letters_rewards.py
Apache-2.0
def compute_letter_count_reward(completion: str, target_count: int) -> float: """Computes the rewards for counting the letters in a string. Args: completion: The completion string from the LLM. target_count: The target count of letters. Returns: The reward value. """ count ...
Computes the rewards for counting the letters in a string. Args: completion: The completion string from the LLM. target_count: The target count of letters. Returns: The reward value.
compute_letter_count_reward
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/count_letters_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/count_letters_rewards.py
Apache-2.0
def _count_letters( completions: list[list[dict[str, Any]]], letter_count: list[int], **kwargs: dict[str, Any], ) -> list[float]: """Custom reward function for counting letters in a string. For more details on custom reward functions used in trl's GRPOTrainer, see: https://huggingface.co/docs/t...
Custom reward function for counting letters in a string. For more details on custom reward functions used in trl's GRPOTrainer, see: https://huggingface.co/docs/trl/main/en/grpo_trainer#using-a-custom-reward-function. Args: completions: The list of completions from the LLM. letter_count: T...
_count_letters
python
oumi-ai/oumi
src/oumi/datasets/grpo/rewards/count_letters_rewards.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/grpo/rewards/count_letters_rewards.py
Apache-2.0
def __init__( self, *, include_system_prompt: bool = True, **kwargs, ) -> None: """Initializes a new instance of the AlpacaDataset class.""" self.include_system_prompt = include_system_prompt super().__init__(**kwargs)
Initializes a new instance of the AlpacaDataset class.
__init__
python
oumi-ai/oumi
src/oumi/datasets/sft/alpaca.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/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`, and `output` entries. ...
Preprocesses the inputs of the example and returns a dictionary. Args: example (dict or Pandas Series): An example containing `input` (optional), `instruction`, and `output` entries. Returns: dict: The input example converted to Alpaca dictionary format. ...
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/alpaca.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/alpaca.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transform a dataset example into a Conversation object.""" question: str = example.get("inputs", None) or "" answer: str = example.get("targets", None) or "" messages = [ Message(role=Role....
Transform a dataset example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/aya.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/aya.py
Apache-2.0
def transform_conversation( self, raw_conversation: Union[dict, pd.Series] ) -> Conversation: """Preprocesses the inputs of the example and returns a dictionary. ChatQA is a conversational question answering dataset. It contains 10 subsets. Some subsets contain grounding documents. ...
Preprocesses the inputs of the example and returns a dictionary. ChatQA is a conversational question answering dataset. It contains 10 subsets. Some subsets contain grounding documents. See the dataset page for more information: https://huggingface.co/datasets/nvidia/ChatQA-Training-Da...
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/chatqa.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/chatqa.py
Apache-2.0
def __init__( self, *, split: str = "test", task: str = "generation", subset: Optional[str] = None, num_context_docs: int = 5, **kwargs, ) -> None: """Initialize the ChatRag dataset. Args: split: The split of the dataset to use. De...
Initialize the ChatRag dataset. Args: split: The split of the dataset to use. Defaults to "test". num_context_docs: The number of context documents to include in each example. subset: The subset of the dataset to use. Defaults to None. task: The task ...
__init__
python
oumi-ai/oumi
src/oumi/datasets/sft/chatrag_bench.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/chatrag_bench.py
Apache-2.0
def _get_instruction(self) -> Optional[str]: """Get an appropriate instruction for each dataset subset.""" subset_instructions = { "doc2dial": "Please give a full and complete answer for the question.", "quac": "Please give a full and complete answer for the question.", ...
Get an appropriate instruction for each dataset subset.
_get_instruction
python
oumi-ai/oumi
src/oumi/datasets/sft/chatrag_bench.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/chatrag_bench.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transforms a given example into a Conversation object. Args: example (Union[dict, pd.Series]): The example to transform. Returns: Conversation: The transformed Conversation object. ...
Transforms a given example into a Conversation object. Args: example (Union[dict, pd.Series]): The example to transform. Returns: Conversation: The transformed Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/chatrag_bench.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/chatrag_bench.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transform a dataset example into a Conversation object. Args: example: A single example from the dataset. Returns: Conversation: A Conversation object containing the transformed messag...
Transform a dataset example into a Conversation object. Args: example: A single example from the dataset. Returns: Conversation: A Conversation object containing the transformed messages.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/dolly.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/dolly.py
Apache-2.0
def _get_field_value(example: Union[dict, pd.Series], field: str) -> str: """Helper method to get the value from a field. Args: example (Union[Dict, pd.Series]): A single example from the dataset. field (str): The field name to retrieve. Returns: str: The va...
Helper method to get the value from a field. Args: example (Union[Dict, pd.Series]): A single example from the dataset. field (str): The field name to retrieve. Returns: str: The value of the field.
_get_field_value
python
oumi-ai/oumi
src/oumi/datasets/sft/dolly.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/dolly.py
Apache-2.0
def __init__( self, *, hf_dataset_path: str = "", messages_column: str = "messages", exclude_final_assistant_message: bool = False, **kwargs, ) -> None: """Initializes a new instance of the OumiDataset class.""" if not hf_dataset_path: rais...
Initializes a new instance of the OumiDataset class.
__init__
python
oumi-ai/oumi
src/oumi/datasets/sft/huggingface.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/huggingface.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: An example containing `messages` entries. Returns: Conversation: A Conversation object containing the me...
Preprocesses the inputs of the example and returns a dictionary. Args: example: An example containing `messages` entries. Returns: Conversation: A Conversation object containing the messages.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/huggingface.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/huggingface.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transform a dataset example into a Conversation object.""" instruction: str = example.get("instruction", None) or "" response: str = example.get("response", None) or "" messages = [ Message...
Transform a dataset example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/magpie.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/magpie.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transform a dataset example into a Conversation object.""" conversation = example.get("conversations") if conversation is None: raise ValueError("Conversation is None") messages = [] ...
Transform a dataset example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/magpie.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/magpie.py
Apache-2.0
def __init__( self, *, hf_dataset_path: str = "O1-OPEN/OpenO1-SFT", prompt_column: str = "instruction", response_column: str = "output", **kwargs, ) -> None: """Initializes a new instance of the PromptResponseDataset class.""" self.prompt_column = prom...
Initializes a new instance of the PromptResponseDataset class.
__init__
python
oumi-ai/oumi
src/oumi/datasets/sft/prompt_response.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/prompt_response.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`, and `output` entries. ...
Preprocesses the inputs of the example and returns a dictionary. Args: example (dict or Pandas Series): An example containing `input` (optional), `instruction`, and `output` entries. Returns: dict: The input example converted to messages dictionary format. ...
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/prompt_response.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/prompt_response.py
Apache-2.0
def __init__( self, dataset_path: Optional[Union[str, Path]] = None, data: Optional[list[dict[str, Any]]] = None, format: Optional[str] = None, **kwargs, ): """Initializes a new instance of the TextSftJsonLinesDataset class. Args: dataset_path (Op...
Initializes a new instance of the TextSftJsonLinesDataset class. Args: dataset_path (Optional): Path to the JSON lines dataset file. data (Optional): List of conversation dicts if not loading from a file. format (Optional): The format of the data. Either "conversations", ...
__init__
python
oumi-ai/oumi
src/oumi/datasets/sft/sft_jsonlines.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/sft_jsonlines.py
Apache-2.0
def _detect_format(self, data_frame: pd.DataFrame) -> str: """Detect the format of the data based on the first item. Args: data_frame: The DataFrame containing the data. Returns: str: The detected format ("oumi", or "alpaca"). Raises: ValueError: If...
Detect the format of the data based on the first item. Args: data_frame: The DataFrame containing the data. Returns: str: The detected format ("oumi", or "alpaca"). Raises: ValueError: If the format cannot be detected.
_detect_format
python
oumi-ai/oumi
src/oumi/datasets/sft/sft_jsonlines.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/sft_jsonlines.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform a single conversation example into a Conversation object. Args: example: The input example containing the messages or Alpaca-style turn. Returns: Conversation: A Conversation object containing...
Transform a single conversation example into a Conversation object. Args: example: The input example containing the messages or Alpaca-style turn. Returns: Conversation: A Conversation object containing the messages.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/sft_jsonlines.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/sft_jsonlines.py
Apache-2.0
def _alpaca_to_conversation(self, turn: dict) -> Conversation: """Convert an Alpaca-style turn to a Conversation object. Args: turn: A dictionary containing 'instruction', 'input', and 'output' keys. Returns: Conversation: A Conversation object representing the Alpaca-s...
Convert an Alpaca-style turn to a Conversation object. Args: turn: A dictionary containing 'instruction', 'input', and 'output' keys. Returns: Conversation: A Conversation object representing the Alpaca-style turn. Raises: ValueError: If the turn doesn't co...
_alpaca_to_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/sft_jsonlines.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/sft_jsonlines.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transform a dataset example into a Conversation object.""" raw_messages = example.get("messages") if raw_messages is None: raise ValueError("Invalid messages") messages = [Message.model_val...
Transform a dataset example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/ultrachat.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/ultrachat.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Transform a dataset example into a Conversation object.""" raw_messages = example.get("conversation") if raw_messages is None: raise ValueError("Invalid field, expected 'conversation'") mes...
Transform a dataset example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/sft/wildchat.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/sft/wildchat.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform a single conversation example into a Conversation object.""" input_text = self.default_prompt for required_key in (_COCO_COLUMN_SENTENCES, _COCO_COLUMN_IMAGE): if required_key not in example: ...
Transform a single conversation example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/coco_captions.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/coco_captions.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform a single conversation example into a Conversation object.""" input_text = "Describe this image:" output_text = example["caption"][0] return Conversation( messages=[ Message( ...
Transform a single conversation example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/flickr30k.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/flickr30k.py
Apache-2.0
def __init__( self, *, add_system_instruction: bool = False, **kwargs, ) -> None: """Initializes a new instance of the Geometry3kDataset class.""" self._add_system_instruction = add_system_instruction super().__init__(**kwargs)
Initializes a new instance of the Geometry3kDataset class.
__init__
python
oumi-ai/oumi
src/oumi/datasets/vision_language/geometry3k.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/geometry3k.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform a single conversation example into a Conversation object.""" input_text = self._process_text_value(example["problem"]) input_text = input_text.removeprefix("<image>") if not self._add_system_instruction: ...
Transform a single conversation example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/geometry3k.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/geometry3k.py
Apache-2.0
def __init__( self, *, hf_dataset_path: str, image_column: str, question_column: str, answer_column: Optional[str] = None, system_prompt_column: Optional[str] = None, system_prompt: Optional[str] = None, **kwargs, ) -> None: """Initiali...
Initializes a new instance of the HuggingFaceVisionDataset class. Args: hf_dataset_path: Path to the HuggingFace dataset. image_column: Name of the column containing image data. question_column: Name of the column containing the question/prompt text. answer_colum...
__init__
python
oumi-ai/oumi
src/oumi/datasets/vision_language/huggingface.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/huggingface.py
Apache-2.0
def _get_image_content_item(self, image_data) -> ContentItem: """Create a ContentItem for the image data. Args: image_data: Image data from the dataset (could be bytes, PIL Image, etc.). Returns: ContentItem containing the image data. """ if isinstance(i...
Create a ContentItem for the image data. Args: image_data: Image data from the dataset (could be bytes, PIL Image, etc.). Returns: ContentItem containing the image data.
_get_image_content_item
python
oumi-ai/oumi
src/oumi/datasets/vision_language/huggingface.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/huggingface.py
Apache-2.0
def transform_conversation(self, example: Union[dict, pd.Series]) -> Conversation: """Preprocesses the inputs of the example and returns a Conversation. Args: example: An example containing image, question, and optionally answer data. Returns: Conversation: A Conversati...
Preprocesses the inputs of the example and returns a Conversation. Args: example: An example containing image, question, and optionally answer data. Returns: Conversation: A Conversation object containing the messages.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/huggingface.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/huggingface.py
Apache-2.0
def _process_text_value(self, s: Any) -> str: """Process a text value. Args: s: The text value to process. Returns: The processed text value. """ if s is None: return "" if isinstance(s, str): # The data contains occasiona...
Process a text value. Args: s: The text value to process. Returns: The processed text value.
_process_text_value
python
oumi-ai/oumi
src/oumi/datasets/vision_language/huggingface.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/huggingface.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform a dataset example into a Conversation object.""" example_messages = example.get("messages") if example_messages is None or len(example_messages) == 0: raise ValueError("No messages in input example.") ...
Transform a dataset example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/llava_instruct_mix_vsft.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/llava_instruct_mix_vsft.py
Apache-2.0
def __init__(self, **kwargs) -> None: """Initializes the LMMS Lab Multimodal Open R1 dataset. Args: **kwargs: Additional arguments passed to the parent class such as: - split: Dataset split to use ("train", "test", etc.) - system_prompt: Optional system promp...
Initializes the LMMS Lab Multimodal Open R1 dataset. Args: **kwargs: Additional arguments passed to the parent class such as: - split: Dataset split to use ("train", "test", etc.) - system_prompt: Optional system prompt to add to conversations - max_l...
__init__
python
oumi-ai/oumi
src/oumi/datasets/vision_language/lmms_lab_multimodal_open_r1.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/lmms_lab_multimodal_open_r1.py
Apache-2.0
def __init__( self, *, dataset_name: Optional[str] = None, **kwargs, ) -> None: """Initializes a new instance of the MnistSftDataset class.""" super().__init__( dataset_name="ylecun/mnist", **kwargs, )
Initializes a new instance of the MnistSftDataset class.
__init__
python
oumi-ai/oumi
src/oumi/datasets/vision_language/mnist_sft.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/mnist_sft.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform a single MNIST example into a Conversation object.""" input_text = "What digit is in this picture?" output_digit = self._to_digit(example["label"]) return Conversation( messages=[ M...
Transform a single MNIST example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/mnist_sft.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/mnist_sft.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform the example into a Conversation object.""" conversation = Conversation( messages=[ Message( role=Role.USER, content=[ ContentItem(type...
Transform the example into a Conversation object.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/pixmo_ask_model_anything.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/pixmo_ask_model_anything.py
Apache-2.0
def transform_conversation(self, example: dict) -> Conversation: """Transform the example into a Conversation object. A "transcripts" column is also available but not used yet. """ input_text = "Describe this image:" messages: list[Message] = [] messages.append( ...
Transform the example into a Conversation object. A "transcripts" column is also available but not used yet.
transform_conversation
python
oumi-ai/oumi
src/oumi/datasets/vision_language/pixmo_cap.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/datasets/vision_language/pixmo_cap.py
Apache-2.0