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 gpu_memory_logger(user_function: Callable, synchronize: bool = True) -> Callable: """Decorator function that logs the GPU memory usage of a given function. Args: user_function: The function to be decorated. synchronize: Flag indicating whether to synchronize GPU operations before ...
Decorator function that logs the GPU memory usage of a given function. Args: user_function: The function to be decorated. synchronize: Flag indicating whether to synchronize GPU operations before measuring memory usage. Defaults to True. Returns: The decorated function.
gpu_memory_logger
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def timer(self, name: str) -> TimerContext: """Creates a timer with the given name. Args: name: The name of the timer. Returns: A TimerContext object. """ if name not in self.state.measurements: self.state.measurements[name] = [] retu...
Creates a timer with the given name. Args: name: The name of the timer. Returns: A TimerContext object.
timer
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def cuda_timer(self, name: str) -> CudaTimerContext: """Creates a CUDA benchmark with the given name. Args: name: The name of the benchmark. Returns: A CudaTimerContext object. """ if name not in self.state.cuda_measurements: self.state.cuda_...
Creates a CUDA benchmark with the given name. Args: name: The name of the benchmark. Returns: A CudaTimerContext object.
cuda_timer
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def log_gpu_memory(self, custom_logger: Optional[Callable] = None) -> None: """Logs the GPU memory usage. Args: custom_logger: A custom logging function. If None, store in self.gpu_memory. """ if not torch.cuda.is_available(): LOGGER.debug("CUDA is not available....
Logs the GPU memory usage. Args: custom_logger: A custom logging function. If None, store in self.gpu_memory.
log_gpu_memory
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def record_gpu_temperature(self) -> float: """Records the current GPU temperature. Returns: GPU temperature, in degrees Celsius. """ if not torch.cuda.is_available(): LOGGER.debug("CUDA is not available. GPU temperature cannot be logged.") return 0.0 ...
Records the current GPU temperature. Returns: GPU temperature, in degrees Celsius.
record_gpu_temperature
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def get_summary(self) -> dict[str, Any]: """Returns a summary of the telemetry statistics. Returns: A dictionary containing the summary statistics. """ total_time = time.perf_counter() - self.state.start_time summary = { _SUMMARY_KEY_HOSTNAME: self.state...
Returns a summary of the telemetry statistics. Returns: A dictionary containing the summary statistics.
get_summary
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def print_summary(self) -> None: """Prints a summary of the telemetry statistics.""" summary = self.get_summary() log_lines: list[str] = [ f"Telemetry Summary ({summary[_SUMMARY_KEY_HOSTNAME]}):", f"Total time: {summary['total_time']:.2f} seconds", ] if s...
Prints a summary of the telemetry statistics.
print_summary
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def compute_cross_rank_summaries( self, rank_summaries: list[dict[str, Any]], *, measurement_names: Union[set[str], dict[str, Any]], ) -> dict[str, Any]: """Computes a cross-rank summary from summaries produced by individual ranks. For example, it can be used to comp...
Computes a cross-rank summary from summaries produced by individual ranks. For example, it can be used to compute distribution of `{"gpu_temperature": {"max"}}` over ranks. Args: rank_summaries: An array of summaries indexed by rank e.g., returned by the `get_summar...
compute_cross_rank_summaries
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def _calculate_timer_stats( self, measurements: list[float], total_time: Optional[float] = None ) -> dict[str, float]: """Same as above but also computes `total` and `percentage`.""" stats: dict[str, float] = self._calculate_basic_stats(measurements) count = len(measurements) ...
Same as above but also computes `total` and `percentage`.
_calculate_timer_stats
python
oumi-ai/oumi
src/oumi/performance/telemetry.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/telemetry.py
Apache-2.0
def _configure_torch_profile_save_dir( params: ProfilerParams, training_output_dir: Optional[str] ) -> ProfilerParams: """Auto-generates ProfilerParams.saved_dir if not specified explicitly.""" if not params.save_dir and training_output_dir: params.save_dir = str( pathlib.Path(training_o...
Auto-generates ProfilerParams.saved_dir if not specified explicitly.
_configure_torch_profile_save_dir
python
oumi-ai/oumi
src/oumi/performance/torch_profiler_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/torch_profiler_utils.py
Apache-2.0
def torch_profile( params: ProfilerParams, *, training_output_dir: Optional[str], record_function_name: str = "oumi.train", ): """Creates PyTorch Profiler context manager. Args: params: Profiler config. training_output_dir: If `ProfilerParams.save_dir` is not specified, then ...
Creates PyTorch Profiler context manager. Args: params: Profiler config. training_output_dir: If `ProfilerParams.save_dir` is not specified, then a "profiler" sub-directory will be created under `training_output_dir`, and used to save profiler traces. record_function...
torch_profile
python
oumi-ai/oumi
src/oumi/performance/torch_profiler_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/torch_profiler_utils.py
Apache-2.0
def batch(dataset: list[T], batch_size: int) -> list[list[T]]: """Batches the provided dataset. Args: dataset: The dataset to batch, which is a flat list of items. batch_size: The desired size of each batch. Returns: A list of batches. Each batch is a list of `batch_size` items, as...
Batches the provided dataset. Args: dataset: The dataset to batch, which is a flat list of items. batch_size: The desired size of each batch. Returns: A list of batches. Each batch is a list of `batch_size` items, assuming that the dataset's size is a multiple of `batch_size`. ...
batch
python
oumi-ai/oumi
src/oumi/utils/batching.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/batching.py
Apache-2.0
def load_image_bytes_to_content_item( item: ContentItem, mode: str = DEFAULT_IMAGE_MODE ) -> ContentItem: """Ensures that message content item contains inline image bytes if it's an image. Loads image content if image type is `IMAGE_URL` or `IMAGE_PATH`. Otherwise returns the input content item w/o any...
Ensures that message content item contains inline image bytes if it's an image. Loads image content if image type is `IMAGE_URL` or `IMAGE_PATH`. Otherwise returns the input content item w/o any changes. Args: item: An input message content item. mode: The requested image mode e.g., "RGB",...
load_image_bytes_to_content_item
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def load_pil_image_from_content_item( image_item: ContentItem, mode: str = DEFAULT_IMAGE_MODE ) -> PIL.Image.Image: """Loads a PIL image from a message content item. Args: image_item: A content item representing an image. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", ...
Loads a PIL image from a message content item. Args: image_item: A content item representing an image. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see https://pillow.readthedocs.io/en/stable/handbook/conc...
load_pil_image_from_content_item
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def base64encode_content_item_image_bytes( item: ContentItem, *, add_mime_prefix: bool = True ) -> str: """Creates base-64 encoded image bytes as ASCII string value. Args: item: An input message content item of image type (one of `IMAGE_BINARY`, `IMAGE_PATH, `IMAGE_URL`) wit...
Creates base-64 encoded image bytes as ASCII string value. Args: item: An input message content item of image type (one of `IMAGE_BINARY`, `IMAGE_PATH, `IMAGE_URL`) with the pre-populated `binary` field. add_mime_prefix: Whether to add MIME prefix `data:image/png;base64,` ...
base64encode_content_item_image_bytes
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def convert_message_content_item_to_json_dict( item: ContentItem, ) -> dict[str, Any]: """Returns the content for a message content item. Args: item: The message content item to get the content for. Returns: Dict[str, Any]: The content for the message. """ if item.type == Type....
Returns the content for a message content item. Args: item: The message content item to get the content for. Returns: Dict[str, Any]: The content for the message.
convert_message_content_item_to_json_dict
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def convert_content_items_to_json_list( content_items: list[ContentItem], ) -> list[dict[str, Any]]: """Converts content items to a list of JSON dicts. Args: content_items: A list of content items. Returns: list[Dict[str, Any]]: The list of all content items encoded as JSON dicts. ...
Converts content items to a list of JSON dicts. Args: content_items: A list of content items. Returns: list[Dict[str, Any]]: The list of all content items encoded as JSON dicts.
convert_content_items_to_json_list
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def convert_message_to_json_content_list( message: Message, ) -> list[dict[str, Any]]: """Returns the message content as a list of its content items encoded as JSON dicts. Args: message: The message to get the content for. Returns: list[Dict[str, Any]]: The content for the message for ...
Returns the message content as a list of its content items encoded as JSON dicts. Args: message: The message to get the content for. Returns: list[Dict[str, Any]]: The content for the message for all content items.
convert_message_to_json_content_list
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def convert_message_to_json_content( message: Message, ) -> Union[str, list[dict[str, Any]]]: """Returns the message content. Args: message: The message to get the content for. Returns: The content for the message returned either as a single string, or as a list of content item...
Returns the message content. Args: message: The message to get the content for. Returns: The content for the message returned either as a single string, or as a list of content items.
convert_message_to_json_content
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def create_list_of_message_json_dicts( messages: list[Message], *, group_adjacent_same_role_turns: bool, ) -> list[dict[str, Any]]: """Returns a list of JSON dictionaries representing messages. Loads image bytes and encodes them as base64. Args: messages: The input messages. gr...
Returns a list of JSON dictionaries representing messages. Loads image bytes and encodes them as base64. Args: messages: The input messages. group_adjacent_same_role_turns: Whether to pack adjacent messages from the same role into a single element in output list. Returns: ...
create_list_of_message_json_dicts
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def truncate_text_in_content_items( messages: list[Message], tokenizer: BaseTokenizer, *, max_tokens: int, truncation_side: str = "right", ) -> list[Message]: """Truncates text contents in Messages to `max_length` total tokens. Note that we have to truncate plain texts *before* we apply cha...
Truncates text contents in Messages to `max_length` total tokens. Note that we have to truncate plain texts *before* we apply chat template as the final processed prompt is generally unsafe to truncate at arbitrary offset: it may break invariants (e.g., prompt contains `N` images tokens) leading to run...
truncate_text_in_content_items
python
oumi-ai/oumi
src/oumi/utils/conversation_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/conversation_utils.py
Apache-2.0
def log_example_for_debugging( raw_example: Any, formatted_example: str, tokenized_example: list[tuple[int, str]], model_input: dict[str, Any], ) -> None: """Logs an example of the data in each step for debugging purposes. Args: raw_example: The raw example from the dataset. for...
Logs an example of the data in each step for debugging purposes. Args: raw_example: The raw example from the dataset. formatted_example: The formatted example after processing. tokenized_example: The tokenized example after tokenization. model_input: The final model input after coll...
log_example_for_debugging
python
oumi-ai/oumi
src/oumi/utils/debug_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/debug_utils.py
Apache-2.0
def _initialize_pynvml() -> bool: """Attempts to initialize pynvml library. Returns True on success.""" global pynvml if pynvml is None: return False try: pynvml.nvmlInit() except Exception: logger.error( "Failed to initialize pynvml library. All pynvml calls wil...
Attempts to initialize pynvml library. Returns True on success.
_initialize_pynvml
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def _initialize_pynvml_and_get_pynvml_device_count() -> Optional[int]: """Attempts to initialize pynvml library. Returns device count on success, or None otherwise. """ global pynvml # The call to `pynvml is None` is technically redundant but exists here # to make pyright happy. if pynvml i...
Attempts to initialize pynvml library. Returns device count on success, or None otherwise.
_initialize_pynvml_and_get_pynvml_device_count
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def get_nvidia_gpu_runtime_info( device_index: int = 0, ) -> Optional[NVidiaGpuRuntimeInfo]: """Returns runtime stats for Nvidia GPU.""" return _get_nvidia_gpu_runtime_info_impl( device_index=device_index, memory=True, temperature=True, fan_speed=True, power_usage=Tru...
Returns runtime stats for Nvidia GPU.
get_nvidia_gpu_runtime_info
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def log_nvidia_gpu_runtime_info(device_index: int = 0, log_prefix: str = "") -> None: """Prints the current NVIDIA GPU runtime info.""" info = get_nvidia_gpu_runtime_info(device_index) logger.info(f"{log_prefix.rstrip()} GPU runtime info: {pformat(info)}.")
Prints the current NVIDIA GPU runtime info.
log_nvidia_gpu_runtime_info
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def get_nvidia_gpu_memory_utilization(device_index: int = 0) -> float: """Returns amount of memory being used on an Nvidia GPU in MiB.""" info: Optional[NVidiaGpuRuntimeInfo] = _get_nvidia_gpu_runtime_info_impl( device_index=device_index, memory=True ) return ( info.used_memory_mb ...
Returns amount of memory being used on an Nvidia GPU in MiB.
get_nvidia_gpu_memory_utilization
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def log_nvidia_gpu_memory_utilization( device_index: int = 0, log_prefix: str = "" ) -> None: """Prints amount of memory being used on an Nvidia GPU.""" memory_mib = get_nvidia_gpu_memory_utilization(device_index) logger.info(f"{log_prefix.rstrip()} GPU memory occupied: {memory_mib} MiB.")
Prints amount of memory being used on an Nvidia GPU.
log_nvidia_gpu_memory_utilization
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def get_nvidia_gpu_temperature(device_index: int = 0) -> int: """Returns the current temperature readings for the device, in degrees C.""" info: Optional[NVidiaGpuRuntimeInfo] = _get_nvidia_gpu_runtime_info_impl( device_index=device_index, temperature=True, ) return ( info.temper...
Returns the current temperature readings for the device, in degrees C.
get_nvidia_gpu_temperature
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def log_nvidia_gpu_temperature(device_index: int = 0, log_prefix: str = "") -> None: """Prints the current temperature readings for the device, in degrees C.""" temperature = get_nvidia_gpu_temperature(device_index) logger.info(f"{log_prefix.rstrip()} GPU temperature: {temperature} C.")
Prints the current temperature readings for the device, in degrees C.
log_nvidia_gpu_temperature
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def get_nvidia_gpu_fan_speeds(device_index: int = 0) -> Sequence[int]: """Returns the current fan speeds for NVIDIA GPU device.""" info: Optional[NVidiaGpuRuntimeInfo] = _get_nvidia_gpu_runtime_info_impl( device_index=device_index, fan_speed=True ) return ( info.fan_speeds if (in...
Returns the current fan speeds for NVIDIA GPU device.
get_nvidia_gpu_fan_speeds
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def log_nvidia_gpu_fan_speeds(device_index: int = 0, log_prefix: str = "") -> None: """Prints the current NVIDIA GPU fan speeds.""" fan_speeds = get_nvidia_gpu_fan_speeds(device_index) logger.info(f"{log_prefix.rstrip()} GPU fan speeds: {fan_speeds}.")
Prints the current NVIDIA GPU fan speeds.
log_nvidia_gpu_fan_speeds
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def get_nvidia_gpu_power_usage(device_index: int = 0) -> float: """Returns the current power usage for NVIDIA GPU device.""" info: Optional[NVidiaGpuRuntimeInfo] = _get_nvidia_gpu_runtime_info_impl( device_index=device_index, power_usage=True ) return ( info.power_usage_watts if ...
Returns the current power usage for NVIDIA GPU device.
get_nvidia_gpu_power_usage
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def log_nvidia_gpu_power_usage(device_index: int = 0, log_prefix: str = "") -> None: """Prints the current NVIDIA GPU power usage.""" power_usage = get_nvidia_gpu_power_usage(device_index) logger.info(f"{log_prefix.rstrip()} GPU power usage: {power_usage:.2f}W.")
Prints the current NVIDIA GPU power usage.
log_nvidia_gpu_power_usage
python
oumi-ai/oumi
src/oumi/utils/device_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/device_utils.py
Apache-2.0
def is_using_accelerate() -> bool: """Returns whether the current job was launched with the Accelerate launcher. We do this by checking if the `ACCELERATE_DYNAMO_*` environment variables are set. These variables should always be set by Accelerate. We check for all of them in case Accelerate changes the...
Returns whether the current job was launched with the Accelerate launcher. We do this by checking if the `ACCELERATE_DYNAMO_*` environment variables are set. These variables should always be set by Accelerate. We check for all of them in case Accelerate changes the environment variables in the future.
is_using_accelerate
python
oumi-ai/oumi
src/oumi/utils/distributed_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/distributed_utils.py
Apache-2.0
def get_git_revision_hash() -> Optional[str]: """Get the current git revision hash. Returns: Optional[str]: The current git revision hash, or None if it cannot be retrieved. """ try: return subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=Path(__file__)...
Get the current git revision hash. Returns: Optional[str]: The current git revision hash, or None if it cannot be retrieved.
get_git_revision_hash
python
oumi-ai/oumi
src/oumi/utils/git_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/git_utils.py
Apache-2.0
def get_git_tag() -> Optional[str]: """Get the current git tag. Returns: Optional[str]: The current git tag, or None if it cannot be retrieved. """ try: return subprocess.check_output( ["git", "describe", "--tags", "--abbrev=0", "--exact-match"], cwd=Path(__file_...
Get the current git tag. Returns: Optional[str]: The current git tag, or None if it cannot be retrieved.
get_git_tag
python
oumi-ai/oumi
src/oumi/utils/git_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/git_utils.py
Apache-2.0
def get_git_root_dir() -> Optional[Path]: """Get the root directory of the current git repository. Returns: Optional[str]: The root directory of the current git repository, or None if it cannot be retrieved. """ try: dir_path = Path( subprocess.check_output( ...
Get the root directory of the current git repository. Returns: Optional[str]: The root directory of the current git repository, or None if it cannot be retrieved.
get_git_root_dir
python
oumi-ai/oumi
src/oumi/utils/git_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/git_utils.py
Apache-2.0
def extract_prompt_images_completion_from_single_turn_conversation( example: dict, ) -> tuple[str, list, str]: """Finds prompt, completion, and optional images in a single-turn conversation. Args: example: A dictionary containing the conversation JSON. Returns: A tuple containing the p...
Finds prompt, completion, and optional images in a single-turn conversation. Args: example: A dictionary containing the conversation JSON. Returns: A tuple containing the prompt, images, and completion. The list of images is empty for text-only conversations.
extract_prompt_images_completion_from_single_turn_conversation
python
oumi-ai/oumi
src/oumi/utils/grpo_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/grpo_utils.py
Apache-2.0
def try_prepare_trl_grpo_example( example: dict, ) -> dict: """Prepares an example for GRPO_TRL processing. This function checks if the input example is one of known special cases e.g., SFT example, and transforms it into a GRPO compatible format. Otherwise, it returns the original example. Ar...
Prepares an example for GRPO_TRL processing. This function checks if the input example is one of known special cases e.g., SFT example, and transforms it into a GRPO compatible format. Otherwise, it returns the original example. Args: example (dict): The input example. Returns: GR...
try_prepare_trl_grpo_example
python
oumi-ai/oumi
src/oumi/utils/grpo_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/grpo_utils.py
Apache-2.0
def is_cached_to_disk_hf_dataset(dataset_folder: Union[str, Path]) -> bool: """Detects whether a dataset was saved using `dataset.save_to_disk()`. Such datasets should be loaded using `datasets.Dataset.load_from_disk()` Returns: Whether the dataset was saved using `dataset.save_to_disk()` method. ...
Detects whether a dataset was saved using `dataset.save_to_disk()`. Such datasets should be loaded using `datasets.Dataset.load_from_disk()` Returns: Whether the dataset was saved using `dataset.save_to_disk()` method.
is_cached_to_disk_hf_dataset
python
oumi-ai/oumi
src/oumi/utils/hf_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/hf_utils.py
Apache-2.0
def find_hf_token() -> Optional[str]: """Attempts to find HuggingFace access token. Returns: A valid HF access token, or `None` if not found. """ hf_token = os.environ.get("HF_TOKEN", None) if not hf_token: _DEFAULT_HF_HOME_PATH = "~/.cache/huggingface" file_must_exist = Fa...
Attempts to find HuggingFace access token. Returns: A valid HF access token, or `None` if not found.
find_hf_token
python
oumi-ai/oumi
src/oumi/utils/hf_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/hf_utils.py
Apache-2.0
def get_hf_chat_template( tokenizer_name: str, *, trust_remote_code: bool = False ) -> Optional[str]: """Returns chat template provided by HF for `tokenizer_name`.""" if not tokenizer_name or is_custom_model(tokenizer_name): return None tokenizer = transformers.AutoTokenizer.from_pretrained( ...
Returns chat template provided by HF for `tokenizer_name`.
get_hf_chat_template
python
oumi-ai/oumi
src/oumi/utils/hf_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/hf_utils.py
Apache-2.0
async def get_failure_reason_from_response( response: aiohttp.ClientResponse, ) -> str: """Return a string describing the error from the provided response.""" try: response_json = await response.json() if isinstance(response_json, list): response_json = response_json[0] e...
Return a string describing the error from the provided response.
get_failure_reason_from_response
python
oumi-ai/oumi
src/oumi/utils/http.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/http.py
Apache-2.0
def create_png_bytes_from_image(pil_image: PIL.Image.Image) -> bytes: """Encodes PIL image into PNG format, and returns PNG image bytes. Args: pil_image: An input image. Returns: bytes: PNG bytes representation of the image. """ try: output = io.BytesIO() pil_image....
Encodes PIL image into PNG format, and returns PNG image bytes. Args: pil_image: An input image. Returns: bytes: PNG bytes representation of the image.
create_png_bytes_from_image
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def convert_pil_image_mode( image: PIL.Image.Image, *, mode: Optional[str] ) -> PIL.Image.Image: """Converts a PIL image to the requested mode (if it's not in that mode already) . Args: image: An input image. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit ...
Converts a PIL image to the requested mode (if it's not in that mode already) . Args: image: An input image. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see https://pillow.readthedocs.io/en/stable/handboo...
convert_pil_image_mode
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_pil_image_from_path( input_image_filepath: Union[str, Path], mode: str = DEFAULT_IMAGE_MODE ) -> PIL.Image.Image: """Loads an image from a path. Args: input_image_filepath: A file path of an image. The image can be in any format supported by PIL. mode: The requested ima...
Loads an image from a path. Args: input_image_filepath: A file path of an image. The image can be in any format supported by PIL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see https://pillow...
load_pil_image_from_path
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_pil_image_from_url( input_image_url: str, mode: str = DEFAULT_IMAGE_MODE ) -> PIL.Image.Image: """Loads a PIL image from a URL. Args: input_image_url: An image URL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). ...
Loads a PIL image from a URL. Args: input_image_url: An image URL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes Returns: ...
load_pil_image_from_url
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_pil_image_from_bytes( image_bytes: Optional[bytes], mode: str = DEFAULT_IMAGE_MODE ) -> PIL.Image.Image: """Loads an image from raw image bytes. Args: image_bytes: A input image bytes. Can be in any image format supported by PIL. mode: The requested image mode e.g., "RGB", "HSV", "...
Loads an image from raw image bytes. Args: image_bytes: A input image bytes. Can be in any image format supported by PIL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see https://pillow.readthedocs.io/en/s...
load_pil_image_from_bytes
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_pdf_pages_from_path( input_pdf_filepath: Union[str, Path], *, dpi: int = _DEFAULT_PDF_DPI, mode: str = DEFAULT_IMAGE_MODE, ) -> list[PIL.Image.Image]: """Loads PDF pages as PIL images from a path. Args: input_pdf_filepath: A file path of an PDF document. dpi: Resolution...
Loads PDF pages as PIL images from a path. Args: input_pdf_filepath: A file path of an PDF document. dpi: Resolution to use for PDF page images (dots per inch). mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For ...
load_pdf_pages_from_path
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_pdf_pages_from_bytes( pdf_bytes: Optional[bytes], *, dpi: int = _DEFAULT_PDF_DPI, mode: str = DEFAULT_IMAGE_MODE, ) -> list[PIL.Image.Image]: """Loads PDF pages as PIL images from raw PDF file bytes. Args: pdf_bytes: PDF file content. dpi: Resolution to use for PDF page...
Loads PDF pages as PIL images from raw PDF file bytes. Args: pdf_bytes: PDF file content. dpi: Resolution to use for PDF page images (dots per inch). mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, se...
load_pdf_pages_from_bytes
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_pdf_pages_from_url( pdf_url: str, *, dpi: int = _DEFAULT_PDF_DPI, mode: str = DEFAULT_IMAGE_MODE ) -> list[PIL.Image.Image]: """Loads PDF pages as PIL images from from PDF URL. Args: pdf_url: A PDF URL. dpi: Resolution to use for PDF page images (dots per inch). mode: The r...
Loads PDF pages as PIL images from from PDF URL. Args: pdf_url: A PDF URL. dpi: Resolution to use for PDF page images (dots per inch). mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see https://pillo...
load_pdf_pages_from_url
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def create_png_bytes_from_image_bytes( image_bytes: Optional[bytes], mode: str = DEFAULT_IMAGE_MODE ) -> bytes: """Loads an image from raw image bytes, and converts to PNG image bytes. Args: image_bytes: A input image bytes. Can be in any image format supported by PIL. mode: The requested i...
Loads an image from raw image bytes, and converts to PNG image bytes. Args: image_bytes: A input image bytes. Can be in any image format supported by PIL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see h...
create_png_bytes_from_image_bytes
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_image_png_bytes_from_path( input_image_filepath: Union[str, Path], mode: str = DEFAULT_IMAGE_MODE ) -> bytes: """Loads an image from a path, converts it to PNG, and returns image bytes. Args: input_image_filepath: A file path of an image. The image can be in any format supporte...
Loads an image from a path, converts it to PNG, and returns image bytes. Args: input_image_filepath: A file path of an image. The image can be in any format supported by PIL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette)...
load_image_png_bytes_from_path
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_image_png_bytes_from_url( input_image_url: str, mode: str = DEFAULT_IMAGE_MODE ) -> bytes: """Loads an image from a URL, converts it to PNG, and returns image bytes. Args: input_image_url: An image URL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-b...
Loads an image from a URL, converts it to PNG, and returns image bytes. Args: input_image_url: An image URL. mode: The requested image mode e.g., "RGB", "HSV", "RGBA", "P" (8-bit pixels, using a color palette). For details, see https://pillow.readthedocs.io/en/stable/handboo...
load_image_png_bytes_from_url
python
oumi-ai/oumi
src/oumi/utils/image_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/image_utils.py
Apache-2.0
def load_json(filename: Union[str, Path]) -> Any: """Load JSON data from a file. Args: filename: Path to the JSON file. Returns: dict: Parsed JSON data. Raises: FileNotFoundError: If the file doesn't exist. json.JSONDecodeError: If the file contains invalid JSON. "...
Load JSON data from a file. Args: filename: Path to the JSON file. Returns: dict: Parsed JSON data. Raises: FileNotFoundError: If the file doesn't exist. json.JSONDecodeError: If the file contains invalid JSON.
load_json
python
oumi-ai/oumi
src/oumi/utils/io_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/io_utils.py
Apache-2.0
def save_json( data: dict[str, Any], filename: Union[str, Path], indent: int = 2 ) -> None: """Save data as a formatted JSON file. Args: data: The data to be saved as JSON. filename: Path where the JSON file will be saved. indent: Number of spaces for indentation. Defaults to 2. ...
Save data as a formatted JSON file. Args: data: The data to be saved as JSON. filename: Path where the JSON file will be saved. indent: Number of spaces for indentation. Defaults to 2. Raises: TypeError: If the data is not JSON serializable.
save_json
python
oumi-ai/oumi
src/oumi/utils/io_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/io_utils.py
Apache-2.0
def load_file(filename: Union[str, Path], encoding: str = "utf-8") -> str: """Load a file as a string. Args: filename: Path to the file. encoding: Encoding to use when reading the file. Defaults to "utf-8". Returns: str: The content of the file. Raises: FileNotFoundErr...
Load a file as a string. Args: filename: Path to the file. encoding: Encoding to use when reading the file. Defaults to "utf-8". Returns: str: The content of the file. Raises: FileNotFoundError: If the file doesn't exist.
load_file
python
oumi-ai/oumi
src/oumi/utils/io_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/io_utils.py
Apache-2.0
def load_jsonlines(filename: Union[str, Path]) -> list[dict[str, Any]]: """Load a jsonlines file. Args: filename: Path to the jsonlines file. Returns: List[Dict[str, Any]]: A list of dictionaries, each representing a JSON object from the file. Raises: FileNotFoundE...
Load a jsonlines file. Args: filename: Path to the jsonlines file. Returns: List[Dict[str, Any]]: A list of dictionaries, each representing a JSON object from the file. Raises: FileNotFoundError: If the file doesn't exist. jsonlines.InvalidLineError: If the fil...
load_jsonlines
python
oumi-ai/oumi
src/oumi/utils/io_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/io_utils.py
Apache-2.0
def save_jsonlines(filename: Union[str, Path], data: list[dict[str, Any]]) -> None: """Save a list of dictionaries to a jsonlines file. Args: filename: Path to the jsonlines file to be created or overwritten. data: A list of dictionaries to be saved as JSON objects. Raises: IOError...
Save a list of dictionaries to a jsonlines file. Args: filename: Path to the jsonlines file to be created or overwritten. data: A list of dictionaries to be saved as JSON objects. Raises: IOError: If there's an error writing to the file.
save_jsonlines
python
oumi-ai/oumi
src/oumi/utils/io_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/io_utils.py
Apache-2.0
def get_logger( name: str, level: str = "info", log_dir: Optional[Union[str, Path]] = None, ) -> logging.Logger: """Gets a logger instance with the specified name and log level. Args: name : The name of the logger. level (optional): The log level to set for the logger. Defaults to "...
Gets a logger instance with the specified name and log level. Args: name : The name of the logger. level (optional): The log level to set for the logger. Defaults to "info". log_dir (optional): Directory to store log files. Defaults to None. Returns: logging.Logger: The logger ...
get_logger
python
oumi-ai/oumi
src/oumi/utils/logging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/logging.py
Apache-2.0
def _detect_rank() -> int: """Detects rank. Reading the rank from the environment variables instead of get_device_rank_info to avoid circular imports. """ for var_name in ( "RANK", "SKYPILOT_NODE_RANK", # SkyPilot "PMI_RANK", # HPC ): rank = os.environ.get(var_...
Detects rank. Reading the rank from the environment variables instead of get_device_rank_info to avoid circular imports.
_detect_rank
python
oumi-ai/oumi
src/oumi/utils/logging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/logging.py
Apache-2.0
def configure_logger( name: str, level: str = "info", log_dir: Optional[Union[str, Path]] = None, ) -> None: """Configures a logger with the specified name and log level.""" logger = logging.getLogger(name) # Remove any existing handlers logger.handlers = [] # Configure the logger ...
Configures a logger with the specified name and log level.
configure_logger
python
oumi-ai/oumi
src/oumi/utils/logging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/logging.py
Apache-2.0
def update_logger_level(name: str, level: str = "info") -> None: """Updates the log level of the logger. Args: name (str): The logger instance to update. level (str, optional): The log level to set for the logger. Defaults to "info". """ logger = get_logger(name, level=level) logger...
Updates the log level of the logger. Args: name (str): The logger instance to update. level (str, optional): The log level to set for the logger. Defaults to "info".
update_logger_level
python
oumi-ai/oumi
src/oumi/utils/logging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/logging.py
Apache-2.0
def configure_dependency_warnings(level: Union[str, int] = "info") -> None: """Ignores non-critical warnings from dependencies, unless in debug mode. Args: level (str, optional): The log level to set for the logger. Defaults to "info". """ level_value = logging.DEBUG if isinstance(level, st...
Ignores non-critical warnings from dependencies, unless in debug mode. Args: level (str, optional): The log level to set for the logger. Defaults to "info".
configure_dependency_warnings
python
oumi-ai/oumi
src/oumi/utils/logging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/logging.py
Apache-2.0
def is_power_of_two(n: int) -> bool: """Check if a number is a power of two. Args: n (int): The number to check. Returns: bool: True if n is a power of two, False otherwise. """ n = abs(n) return (n != 0) and (n & (n - 1) == 0)
Check if a number is a power of two. Args: n (int): The number to check. Returns: bool: True if n is a power of two, False otherwise.
is_power_of_two
python
oumi-ai/oumi
src/oumi/utils/math_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/math_utils.py
Apache-2.0
def get_local_filepath_for_gguf( repo_id: str, filename: str, cache_dir=HUGGINGFACE_CACHE ) -> str: """Return a local path for the provided GGUF file, downloading it if necessary. Args: repo_id: HuggingFace Hub repo ID (e.g., `bartowski/Llama-3.2-3B-Instruct-GGUF`) filename: HuggingFace Hub...
Return a local path for the provided GGUF file, downloading it if necessary. Args: repo_id: HuggingFace Hub repo ID (e.g., `bartowski/Llama-3.2-3B-Instruct-GGUF`) filename: HuggingFace Hub filename (e.g., `Llama-3.2-3B-Instruct-Q8_0.gguf`) cache_dir: Local path to cached models. Defaults to...
get_local_filepath_for_gguf
python
oumi-ai/oumi
src/oumi/utils/model_caching.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/model_caching.py
Apache-2.0
def _version_bounds_str(min_package_version, max_package_version): """Returns a string representation of the version bounds.""" if min_package_version is not None and max_package_version is not None: return f"{min_package_version} <= version <= {max_package_version}" elif min_package_version is not ...
Returns a string representation of the version bounds.
_version_bounds_str
python
oumi-ai/oumi
src/oumi/utils/packaging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/packaging.py
Apache-2.0
def _package_error_message( package_name: str, actual_package_version: Union[version.Version, None], min_package_version: Optional[version.Version] = None, max_package_version: Optional[version.Version] = None, ) -> Union[str, None]: """Checks if a package is installed and if its version is compatib...
Checks if a package is installed and if its version is compatible. This function checks if the package with name `package_name` is installed and if the installed version (`actual_package_version`) is compatible with the required version range. The installed version is considered compatible if it is bot...
_package_error_message
python
oumi-ai/oumi
src/oumi/utils/packaging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/packaging.py
Apache-2.0
def _package_prerequisites_error_messages( package_prerequisites: list[PackagePrerequisites], ) -> list[str]: """Checks if a list of package prerequisites are satisfied. This function checks if a list of package prerequisites are satisfied and returns an error message for each package that is not insta...
Checks if a list of package prerequisites are satisfied. This function checks if a list of package prerequisites are satisfied and returns an error message for each package that is not installed or has an incompatible version. If the function returns an empty list, all prerequisites are satisfied.
_package_prerequisites_error_messages
python
oumi-ai/oumi
src/oumi/utils/packaging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/packaging.py
Apache-2.0
def check_package_prerequisites( package_prerequisites: list[PackagePrerequisites], runtime_error_prefix: str = RUNTIME_ERROR_PREFIX, runtime_error_suffix: str = RUNTIME_ERROR_SUFFIX, ) -> None: """Checks if the package prerequisites are satisfied and raises an error if not.""" if error_messages := ...
Checks if the package prerequisites are satisfied and raises an error if not.
check_package_prerequisites
python
oumi-ai/oumi
src/oumi/utils/packaging.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/packaging.py
Apache-2.0
def get_lora_rank(adapter_dir: Union[str, Path]) -> int: """Gets the LoRA rank for a saved adapter model. Example config: https://github.com/huggingface/peft/blob/b5db9c935021a54fb5d1a479457ce63ad94e2fe5/docs/source/developer_guides/checkpoint.md?plain=1#L182 Args: adapter_dir: The directory c...
Gets the LoRA rank for a saved adapter model. Example config: https://github.com/huggingface/peft/blob/b5db9c935021a54fb5d1a479457ce63ad94e2fe5/docs/source/developer_guides/checkpoint.md?plain=1#L182 Args: adapter_dir: The directory containing the adapter model. Returns: int: The LoRA...
get_lora_rank
python
oumi-ai/oumi
src/oumi/utils/peft_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/peft_utils.py
Apache-2.0
def load_infer_prob(input_filepath: str) -> list[list[list[float]]]: """Retrieve batched probabilities from a parquet file.""" probs_count_in_first_batch = None def to_list(probs): """Ensure number of probabilities is the same for all entries.""" probs_list = list(probs) nonlocal pr...
Retrieve batched probabilities from a parquet file.
load_infer_prob
python
oumi-ai/oumi
src/oumi/utils/saver.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/saver.py
Apache-2.0
def to_list(probs): """Ensure number of probabilities is the same for all entries.""" probs_list = list(probs) nonlocal probs_count_in_first_batch probs_count_in_first_batch = probs_count_in_first_batch or len(probs_list) if probs_count_in_first_batch != len(probs_list): ...
Ensure number of probabilities is the same for all entries.
to_list
python
oumi-ai/oumi
src/oumi/utils/saver.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/saver.py
Apache-2.0
def save_infer_prob_csv(output_filepath: str, probabilities: list[list[list[float]]]): """Save batched probabilities into a csv file.""" with open(output_filepath, "w") as write_obj: csv_writer = csv.writer(write_obj) csv_writer.writerows(probabilities)
Save batched probabilities into a csv file.
save_infer_prob_csv
python
oumi-ai/oumi
src/oumi/utils/saver.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/saver.py
Apache-2.0
def load_infer_prob_csv(input_filepath: str) -> list[list[list[float]]]: """Retrieve batched probabilities from a csv file.""" probs_count_in_first_batch = None try: with open(input_filepath) as read_obj: csv_reader = csv.reader(read_obj) probabilities = [] for b...
Retrieve batched probabilities from a csv file.
load_infer_prob_csv
python
oumi-ai/oumi
src/oumi/utils/saver.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/saver.py
Apache-2.0
def str_to_float_list(input: str) -> list[float]: """Convert an `str` representing a list of `floats` to an actual list of `floats`. Example: input: `[1.1, 2.2, 3.3]` => output: [1.1, 2.2, 3.3] """ # 1) Get rid of '[' and ']'. if (input[0] != "[") or (input[-1] != "]"): raise ValueError( ...
Convert an `str` representing a list of `floats` to an actual list of `floats`. Example: input: `[1.1, 2.2, 3.3]` => output: [1.1, 2.2, 3.3]
str_to_float_list
python
oumi-ai/oumi
src/oumi/utils/saver.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/saver.py
Apache-2.0
def default(self, obj): """Extending python's JSON Encoder to serialize torch dtype.""" if obj is None: return "" # JSON does NOT natively support any torch types. elif isinstance(obj, torch.dtype): return str(obj) # JSON does NOT natively support numpy ty...
Extending python's JSON Encoder to serialize torch dtype.
default
python
oumi-ai/oumi
src/oumi/utils/serialization_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/serialization_utils.py
Apache-2.0
def convert_all_keys_to_serializable_types(dictionary: dict) -> None: """Converts all keys in a hierarchical dictionary to serializable types.""" serializable_key_types = {str, int, float, bool, None} non_serializable_keys = [ key for key in dictionary if type(key) not in serializable_key_types ...
Converts all keys in a hierarchical dictionary to serializable types.
convert_all_keys_to_serializable_types
python
oumi-ai/oumi
src/oumi/utils/serialization_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/serialization_utils.py
Apache-2.0
def json_serializer(obj: Any) -> str: """Serializes a Python obj to a JSON formatted string.""" if dataclasses.is_dataclass(obj) and not isinstance(obj, type): dict_to_serialize = dataclasses.asdict(obj) elif isinstance(obj, dict): dict_to_serialize = obj else: raise ValueError(f...
Serializes a Python obj to a JSON formatted string.
json_serializer
python
oumi-ai/oumi
src/oumi/utils/serialization_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/serialization_utils.py
Apache-2.0
def try_str_to_bool(s: str) -> Optional[bool]: """Attempts to convert a string representation to a boolean value. This function interprets various string inputs as boolean values. It is case-insensitive and recognizes common boolean representations. Args: s: The string to convert to a boolean....
Attempts to convert a string representation to a boolean value. This function interprets various string inputs as boolean values. It is case-insensitive and recognizes common boolean representations. Args: s: The string to convert to a boolean. Returns: bool: The boolean interpretatio...
try_str_to_bool
python
oumi-ai/oumi
src/oumi/utils/str_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/str_utils.py
Apache-2.0
def str_to_bool(s: str) -> bool: """Convert a string representation to a boolean value. This function interprets various string inputs as boolean values. It is case-insensitive and recognizes common boolean representations. Args: s: The string to convert to a boolean. Returns: boo...
Convert a string representation to a boolean value. This function interprets various string inputs as boolean values. It is case-insensitive and recognizes common boolean representations. Args: s: The string to convert to a boolean. Returns: bool: The boolean interpretation of the inp...
str_to_bool
python
oumi-ai/oumi
src/oumi/utils/str_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/str_utils.py
Apache-2.0
def compute_utf8_len(s: str) -> int: """Computes string length in UTF-8 bytes.""" # This is inefficient: allocates a temporary copy of string content. # FIXME Can we do better? return len(s.encode("utf-8"))
Computes string length in UTF-8 bytes.
compute_utf8_len
python
oumi-ai/oumi
src/oumi/utils/str_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/str_utils.py
Apache-2.0
def get_editable_install_override_env_var() -> bool: """Returns whether OUMI_FORCE_EDITABLE_INSTALL env var is set to a truthy value.""" s = os.environ.get("OUMI_FORCE_EDITABLE_INSTALL", "") mode = s.lower().strip() bool_result = try_str_to_bool(mode) if bool_result is not None: return bool_...
Returns whether OUMI_FORCE_EDITABLE_INSTALL env var is set to a truthy value.
get_editable_install_override_env_var
python
oumi-ai/oumi
src/oumi/utils/str_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/str_utils.py
Apache-2.0
def set_oumi_install_editable(setup: str) -> str: """Tries to replace oumi PyPi installs with editable installation from source. For example, the following line: `pip install uv && uv pip -q install oumi[gpu,dev] vllm` will be replaced with: `pip install uv && uv pip -q install -e '.[gpu,de...
Tries to replace oumi PyPi installs with editable installation from source. For example, the following line: `pip install uv && uv pip -q install oumi[gpu,dev] vllm` will be replaced with: `pip install uv && uv pip -q install -e '.[gpu,dev]' vllm` Args: setup (str): The bash setup ...
set_oumi_install_editable
python
oumi-ai/oumi
src/oumi/utils/str_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/str_utils.py
Apache-2.0
def truncate_to_max_tokens_limit( text: str, tokenizer: BaseTokenizer, *, max_tokens: int, truncation_side: str = "right", ) -> tuple[str, int]: """Truncates text to `max_length` in tokens. Args: text: A text prompt. tokenizer: The tokenizer used for encoding the data. ...
Truncates text to `max_length` in tokens. Args: text: A text prompt. tokenizer: The tokenizer used for encoding the data. max_tokens: Maximum number of tokens to keep. truncation_side: The side to truncate the tokens ("right" or "left"). Returns: A tuple containing trun...
truncate_to_max_tokens_limit
python
oumi-ai/oumi
src/oumi/utils/str_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/str_utils.py
Apache-2.0
def truncate_text_pieces_to_max_tokens_limit( text_pieces: list[str], tokenizer: BaseTokenizer, *, max_tokens: int, truncation_side: str = "right", ) -> list[str]: """Truncates text pieces to total length not exceeding `max_length`. Args: text_pieces: A list of text prompts. ...
Truncates text pieces to total length not exceeding `max_length`. Args: text_pieces: A list of text prompts. tokenizer: The tokenizer used for encoding the data. max_tokens: Maximum number of tokens to keep in all text pieces combined. truncation_side: The side to truncate the token...
truncate_text_pieces_to_max_tokens_limit
python
oumi-ai/oumi
src/oumi/utils/str_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/str_utils.py
Apache-2.0
def disable_dropout(hf_config: transformers.PretrainedConfig) -> None: """Detects dropout probabilities in config and sets them to 0.0. This essentially removes the dropout layer, which can aid the compiled model's speed. Dropout is normally not used for LLM training, and also hinders the effectiveness...
Detects dropout probabilities in config and sets them to 0.0. This essentially removes the dropout layer, which can aid the compiled model's speed. Dropout is normally not used for LLM training, and also hinders the effectiveness of model compilation. We assume any attribute with "drop" in the name and...
disable_dropout
python
oumi-ai/oumi
src/oumi/utils/torch_naming_heuristics.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_naming_heuristics.py
Apache-2.0
def group_trainable_params( model: torch.nn.Module, weight_decay: float ) -> list[dict[str, Any]]: """Groups trainable params by weight decay for optimization. As a rule of thumb, we generally want to weight decay all 2d matrices, i.e. weight tensors for matmuls/embeddings, and not biases/layernorms. ...
Groups trainable params by weight decay for optimization. As a rule of thumb, we generally want to weight decay all 2d matrices, i.e. weight tensors for matmuls/embeddings, and not biases/layernorms. Args: model: The model whose parameters will be optimized. weight_decay: The weight decay ...
group_trainable_params
python
oumi-ai/oumi
src/oumi/utils/torch_naming_heuristics.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_naming_heuristics.py
Apache-2.0
def guess_transformer_layer_cls(model: nn.Module) -> type[nn.Module]: """Guess the transformer layer class based on the model architecture.""" for module in model.modules(): for layer_pattern in ["layer", "block", "transformerlayer"]: layer_name = str(type(module)).lower() if la...
Guess the transformer layer class based on the model architecture.
guess_transformer_layer_cls
python
oumi-ai/oumi
src/oumi/utils/torch_naming_heuristics.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_naming_heuristics.py
Apache-2.0
def resolve_transformer_layer_cls_string_as_module_set( class_names: str, ) -> set[type[nn.Module]]: """Get a module class from its string name.""" result: set[type[nn.Module]] = set() for class_name in _parse_transformer_layer_cls_string(class_names): parts = class_name.rsplit(".", maxsplit=1) ...
Get a module class from its string name.
resolve_transformer_layer_cls_string_as_module_set
python
oumi-ai/oumi
src/oumi/utils/torch_naming_heuristics.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_naming_heuristics.py
Apache-2.0
def simplify_transformer_layer_cls_string(class_names: str) -> str: """Replaces fully-qualified class names with pure class names. For example, converts 'foo.Block,foo.util.Decoder' to 'Block,Decoder'. The `accelerate` library expects the simplified format, while OUMI trainer requires fully-qualified ...
Replaces fully-qualified class names with pure class names. For example, converts 'foo.Block,foo.util.Decoder' to 'Block,Decoder'. The `accelerate` library expects the simplified format, while OUMI trainer requires fully-qualified class names.
simplify_transformer_layer_cls_string
python
oumi-ai/oumi
src/oumi/utils/torch_naming_heuristics.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_naming_heuristics.py
Apache-2.0
def device_cleanup() -> None: """Empties gpu cache, good to do before and after training for cleanup.""" logger.debug("Running garbage collection.") gc.collect() if torch.cuda.is_available(): logger.debug("Cleaning up GPU memory.") logger.debug( "GPU memory occupied before c...
Empties gpu cache, good to do before and after training for cleanup.
device_cleanup
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0
def format_cudnn_version(v: Optional[int]) -> str: """Formats the cuDNN version number. Args: v: The cuDNN version number. Returns: A formatted string. """ if v is None: return "" return ".".join(map(str, (v // 1000, v // 100 % 10, v % 100)))
Formats the cuDNN version number. Args: v: The cuDNN version number. Returns: A formatted string.
format_cudnn_version
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0
def log_devices_info(filepath: Optional[Path] = None) -> None: """Logs high-level info about all available accelerator devices.""" if not torch.cuda.is_available(): return ncpus = os.cpu_count() num_devices = torch.cuda.device_count() log_lines = [f"CPU cores: {ncpus} CUDA devices: {num_dev...
Logs high-level info about all available accelerator devices.
log_devices_info
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0
def log_peak_gpu_memory(): """Log the peak GPU memory usage.""" if torch.cuda.is_available(): peak_memory = torch.cuda.max_memory_allocated() / 1024**3 # Convert to GB logger.info(f"Peak GPU memory usage: {peak_memory:.2f} GB")
Log the peak GPU memory usage.
log_peak_gpu_memory
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0
def create_model_summary(model: Any) -> str: """Creates a model summary as a free-formed string.""" lines = ["Model summary:", repr(model), ""] module_lines = [f"{name} ({type(layer)})" for name, layer in model.named_modules()] lines.append(f"Modules ({len(module_lines)}):") lines.extend(module_li...
Creates a model summary as a free-formed string.
create_model_summary
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0
def get_device_name() -> str: """Returns the name of the device, assuming all are identical.""" device_name = "CPU" if torch.cuda.is_available(): # Assume all devices are identical device_name = torch.cuda.get_device_name(0) elif torch.backends.mps.is_available(): device_name = "...
Returns the name of the device, assuming all are identical.
get_device_name
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0
def __post_init__(self): """Ensure that the parameters are valid.""" for name, value in [ ("all_params", self.all_params), ("trainable_params", self.trainable_params), ("embedding_params", self.embedding_params), ]: if value < 0: ra...
Ensure that the parameters are valid.
__post_init__
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0
def _get_parameter_names( model: torch.nn.Module, forbidden_layer_types: list[Any] ) -> list[str]: """Returns the names of the model parameters that are not inside a forbidden layer. Borrowed from https://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py. """ result = []...
Returns the names of the model parameters that are not inside a forbidden layer. Borrowed from https://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py.
_get_parameter_names
python
oumi-ai/oumi
src/oumi/utils/torch_utils.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/utils/torch_utils.py
Apache-2.0