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 _is_mixture_packed(dataset_split_params: DatasetSplitParams) -> bool:
"""Returns whether all datasets in the mixture are packed.
Raises:
ValueError: If a mixture of packed and unpacked datasets is detected.
"""
num_packed = 0
for dataset in dataset_split_params.datasets:
dataset... | Returns whether all datasets in the mixture are packed.
Raises:
ValueError: If a mixture of packed and unpacked datasets is detected.
| _is_mixture_packed | python | oumi-ai/oumi | src/oumi/builders/data.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/data.py | Apache-2.0 |
def build_inference_engine(
engine_type: InferenceEngineType,
model_params: ModelParams,
remote_params: Optional[RemoteParams] = None,
generation_params: Optional[GenerationParams] = None,
) -> BaseInferenceEngine:
"""Returns the inference engine based on the provided config.
Args:
engi... | Returns the inference engine based on the provided config.
Args:
engine_type: Type of inference engine to create
model_params: Model parameters
remote_params: Remote configuration parameters (required for some engines)
generation_params: Generation parameters
Returns:
A... | build_inference_engine | python | oumi-ai/oumi | src/oumi/builders/inference_engines.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/inference_engines.py | Apache-2.0 |
def build_lr_scheduler(
optimizer: torch.optim.Optimizer,
training_params: TrainingParams,
num_training_steps: Optional[int] = None,
current_epoch: int = 0,
) -> torch.optim.lr_scheduler.LRScheduler:
"""Builds a learning rate scheduler based on the provided training parameters.
Args:
op... | Builds a learning rate scheduler based on the provided training parameters.
Args:
optimizer: The optimizer for which to build the learning rate scheduler.
training_params: The training parameters containing the scheduler args.
num_training_steps: The total number of training steps
... | build_lr_scheduler | python | oumi-ai/oumi | src/oumi/builders/lr_schedules.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/lr_schedules.py | Apache-2.0 |
def build_model(
model_params: ModelParams,
peft_params: Optional[PeftParams] = None,
**kwargs,
) -> nn.Module:
"""Builds and returns a model based on the provided Oumi configuration.
Args:
model_params: The model parameters.
peft_params: The PEFT parameters.
kwargs (dict, o... | Builds and returns a model based on the provided Oumi configuration.
Args:
model_params: The model parameters.
peft_params: The PEFT parameters.
kwargs (dict, optional): Additional keyword arguments for model loading.
Returns:
model: The built model.
| build_model | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def _patch_model_for_liger_kernel(model: nn.Module) -> None:
"""Patches the model for Liger Kernel.
The list of support models can be found here:
https://github.com/linkedin/Liger-Kernel/blob/99599091373f178e8ad6a69ecb1b32351d1d5c1f/src/liger_kernel/transformers/monkey_patch.py#L700
If the model is no... | Patches the model for Liger Kernel.
The list of support models can be found here:
https://github.com/linkedin/Liger-Kernel/blob/99599091373f178e8ad6a69ecb1b32351d1d5c1f/src/liger_kernel/transformers/monkey_patch.py#L700
If the model is not supported, liger kernel patching will not be applied,
and a wa... | _patch_model_for_liger_kernel | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def build_oumi_model(
model_params: ModelParams,
peft_params: Optional[PeftParams] = None,
**kwargs,
) -> nn.Module:
"""Builds a custom model from our Oumi registry."""
model_class = REGISTRY[model_params.model_name, RegistryType.MODEL]
model = model_class(**model_params.model_kwargs)
if mo... | Builds a custom model from our Oumi registry. | build_oumi_model | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def build_huggingface_model(
model_params: ModelParams,
peft_params: Optional[PeftParams] = None,
**kwargs,
) -> nn.Module:
"""Builds a HuggingFace model.
If a local directory is specified, the model will be loaded from that checkpoint.
Otherwise, `model_params.model_name` is the name of a Hugg... | Builds a HuggingFace model.
If a local directory is specified, the model will be loaded from that checkpoint.
Otherwise, `model_params.model_name` is the name of a HuggingFaceHub model. The
model will be downloaded from the Hub to a local cache directory if it is not
already present, and will be loaded... | build_huggingface_model | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def is_image_text_llm_using_model_name(
model_name: str, trust_remote_code: bool
) -> bool:
"""Determines whether the model is a basic image+text LLM."""
model_config = find_internal_model_config_using_model_name(
model_name, trust_remote_code=trust_remote_code
)
return model_config is not N... | Determines whether the model is a basic image+text LLM. | is_image_text_llm_using_model_name | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def build_cambrian_model(
model_params: ModelParams,
peft_params: Optional[PeftParams] = None,
**kwargs,
) -> nn.Module:
"""Downloads and builds the model from the HuggingFace Hub."""
from importlib.util import find_spec
for dependency_name in ("diffusers", "einops", "open_clip", "timm"):
... | Downloads and builds the model from the HuggingFace Hub. | build_cambrian_model | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def build_tokenizer(
model_params: ModelParams,
) -> Union[transformers.PreTrainedTokenizer, transformers.PreTrainedTokenizerFast]:
"""Builds and returns a tokenizer based on the provided Oumi configuration.
Args:
model_params (ModelParams): The model parameters.
Returns:
tokenizer: Th... | Builds and returns a tokenizer based on the provided Oumi configuration.
Args:
model_params (ModelParams): The model parameters.
Returns:
tokenizer: The tokenizer object built from the configuration.
| build_tokenizer | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def build_peft_model(
base_model, use_gradient_checkpointing: bool, peft_params: PeftParams
):
"""Builds a PEFT model based on the given base model and params.
Args:
base_model: The base model to build the PEFT model on.
use_gradient_checkpointing: Enable/disable gradient checkpointing.
... | Builds a PEFT model based on the given base model and params.
Args:
base_model: The base model to build the PEFT model on.
use_gradient_checkpointing: Enable/disable gradient checkpointing.
peft_params: The desired params for LORA.
Returns:
The built PEFT model.
| build_peft_model | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def build_chat_template(template_name: str) -> str:
"""Builds a chat template based on code name.
Args:
template_name: the code name describing the chat-template.
Raises:
FileNotFoundError: if the requested template file does not exist.
Returns:
str: a jinja-based chat-templat... | Builds a chat template based on code name.
Args:
template_name: the code name describing the chat-template.
Raises:
FileNotFoundError: if the requested template file does not exist.
Returns:
str: a jinja-based chat-template.
| build_chat_template | python | oumi-ai/oumi | src/oumi/builders/models.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/models.py | Apache-2.0 |
def build_optimizer(
model: torch.nn.Module, config: TrainingParams
) -> torch.optim.Optimizer:
"""Builds and returns a PyTorch optimizer based on the provided configuration.
See pytorch documentation for more information on available optimizers:
https://pytorch.org/docs/stable/optim.html
Args:
... | Builds and returns a PyTorch optimizer based on the provided configuration.
See pytorch documentation for more information on available optimizers:
https://pytorch.org/docs/stable/optim.html
Args:
model: The model whose parameters will be optimized.
config: The configuration object contain... | build_optimizer | python | oumi-ai/oumi | src/oumi/builders/optimizers.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/optimizers.py | Apache-2.0 |
def build_dataset_mixture(
data_params: DataParams,
tokenizer: Optional[BaseTokenizer],
dataset_split: DatasetSplit,
seed: Optional[int] = None,
) -> IterDataPipe:
"""Builds a dataset for the specified split.
Args:
data_params: The data params.
tokenizer: The tokenizer object to... | Builds a dataset for the specified split.
Args:
data_params: The data params.
tokenizer: The tokenizer object to use for preprocessing.
dataset_split: The split of the dataset to load.
seed: If specified, a seed used for random sampling.
Returns:
dataset: The built data... | build_dataset_mixture | python | oumi-ai/oumi | src/oumi/builders/oumi_data.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/oumi_data.py | Apache-2.0 |
def _load_dataset(
dataset_params: DatasetParams,
stream: bool,
tokenizer: Optional[BaseTokenizer] = None,
) -> IterDataPipe:
"""Loads a dataset and wraps it in a DataPipe if necessary."""
# First, try to load a custom dataset from the REGISTRY
dataset_class = REGISTRY.get_dataset(
datas... | Loads a dataset and wraps it in a DataPipe if necessary. | _load_dataset | python | oumi-ai/oumi | src/oumi/builders/oumi_data.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/oumi_data.py | Apache-2.0 |
def build_processor(
processor_name: str,
tokenizer: BaseTokenizer,
*,
processor_kwargs: Optional[dict[str, Any]] = None,
trust_remote_code: bool = False,
) -> BaseProcessor:
"""Builds a processor.
Args:
processor_name: A name of the processor (usually, equals to a model name).
... | Builds a processor.
Args:
processor_name: A name of the processor (usually, equals to a model name).
tokenizer: A tokenizer to use with the processor.
processor_kwargs: A dictionary of processor-specific parameters.
These parameters are passed to the processor constructor.
... | build_processor | python | oumi-ai/oumi | src/oumi/builders/processors.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/processors.py | Apache-2.0 |
def build_trainer(
trainer_type: TrainerType, processor: Optional[BaseProcessor]
) -> Callable[..., BaseTrainer]:
"""Builds a trainer creator functor based on the provided configuration.
Args:
trainer_type (TrainerType): Enum indicating the type of training.
processor: An optional processor... | Builds a trainer creator functor based on the provided configuration.
Args:
trainer_type (TrainerType): Enum indicating the type of training.
processor: An optional processor.
Returns:
A builder function that can create an appropriate trainer based on the trainer
type specified... | build_trainer | python | oumi-ai/oumi | src/oumi/builders/training.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/training.py | Apache-2.0 |
def try_get_config_name_for_alias(
alias: str,
alias_type: AliasType,
) -> str:
"""Gets the config path for a given alias.
This function resolves the config path for a given alias and alias type.
If the alias is not found, the original alias is returned.
Args:
alias (str): The alias to... | Gets the config path for a given alias.
This function resolves the config path for a given alias and alias type.
If the alias is not found, the original alias is returned.
Args:
alias (str): The alias to resolve.
alias_type (AliasType): The type of config to resolve.
Returns:
... | try_get_config_name_for_alias | python | oumi-ai/oumi | src/oumi/cli/alias.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/alias.py | Apache-2.0 |
def parse_extra_cli_args(ctx: typer.Context) -> list[str]:
"""Parses extra CLI arguments into a list of strings.
Args:
ctx: The Typer context object.
Returns:
List[str]: The extra CLI arguments
"""
args = []
# The following formats are supported:
# 1. Space separated: "--f... | Parses extra CLI arguments into a list of strings.
Args:
ctx: The Typer context object.
Returns:
List[str]: The extra CLI arguments
| parse_extra_cli_args | python | oumi-ai/oumi | src/oumi/cli/cli_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/cli_utils.py | Apache-2.0 |
def configure_common_env_vars() -> None:
"""Sets common environment variables if needed."""
if "ACCELERATE_LOG_LEVEL" not in os.environ:
os.environ["ACCELERATE_LOG_LEVEL"] = "info"
if "TOKENIZERS_PARALLELISM" not in os.environ:
os.environ["TOKENIZERS_PARALLELISM"] = "false" | Sets common environment variables if needed. | configure_common_env_vars | python | oumi-ai/oumi | src/oumi/cli/cli_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/cli_utils.py | Apache-2.0 |
def set_log_level(level: Optional[LogLevel]):
"""Sets the logging level for the current command.
Args:
level (Optional[LogLevel]): The log level to use.
"""
if not level:
return
uppercase_level = level.upper()
logger.setLevel(uppercase_level)
CONSOLE.print(f"Set log level to... | Sets the logging level for the current command.
Args:
level (Optional[LogLevel]): The log level to use.
| set_log_level | python | oumi-ai/oumi | src/oumi/cli/cli_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/cli_utils.py | Apache-2.0 |
def _resolve_oumi_prefix(
config_path: str, output_dir: Optional[Path] = None
) -> tuple[str, Path]:
"""Resolves oumi:// prefix and determines output directory.
Args:
config_path: Path that may contain oumi:// prefix
output_dir: Optional output directory override
Returns:
tuple... | Resolves oumi:// prefix and determines output directory.
Args:
config_path: Path that may contain oumi:// prefix
output_dir: Optional output directory override
Returns:
tuple[str, Path]: (cleaned path, output directory)
| _resolve_oumi_prefix | python | oumi-ai/oumi | src/oumi/cli/cli_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/cli_utils.py | Apache-2.0 |
def resolve_and_fetch_config(
config_path: str, output_dir: Optional[Path] = None, force: bool = True
) -> Path:
"""Resolve oumi:// prefix and fetch config if needed.
Args:
config_path: Original config path that may contain oumi:// prefix
output_dir: Optional override for output directory
... | Resolve oumi:// prefix and fetch config if needed.
Args:
config_path: Original config path that may contain oumi:// prefix
output_dir: Optional override for output directory
force: Whether to overwrite an existing config
Returns:
Path: Local path to the config file
| resolve_and_fetch_config | python | oumi-ai/oumi | src/oumi/cli/cli_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/cli_utils.py | Apache-2.0 |
def __init__(
self,
node_rank: int,
world_info: _WorldInfo,
master_address: str,
master_port: int,
node_ips: list[str],
):
"""Initializes run info, and validates arguments."""
if not (world_info.num_nodes > 0 and world_info.gpus_per_node > 0):
... | Initializes run info, and validates arguments. | __init__ | python | oumi-ai/oumi | src/oumi/cli/distributed_run.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/distributed_run.py | Apache-2.0 |
def __repr__(self) -> str:
"""Defines how this class is properly printed."""
fields_dict: dict[str, Any] = {
"node_rank": self.node_rank,
"num_nodes": self.num_nodes,
"gpus_per_node": self.gpus_per_node,
"total_gpus": self.total_gpus,
"master_a... | Defines how this class is properly printed. | __repr__ | python | oumi-ai/oumi | src/oumi/cli/distributed_run.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/distributed_run.py | Apache-2.0 |
def torchrun(
ctx: typer.Context,
level: cli_utils.LOG_LEVEL_TYPE = None,
) -> None:
"""Starts `torchrun` sub-process w/ automatically configured common params.
Args:
ctx: The Typer context object.
level: The logging level for the specified command.
"""
try:
run_info: _P... | Starts `torchrun` sub-process w/ automatically configured common params.
Args:
ctx: The Typer context object.
level: The logging level for the specified command.
| torchrun | python | oumi-ai/oumi | src/oumi/cli/distributed_run.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/distributed_run.py | Apache-2.0 |
def accelerate(
ctx: typer.Context,
level: cli_utils.LOG_LEVEL_TYPE = None,
) -> None:
"""Starts `accelerate` sub-process w/ automatically configured common params.
Args:
ctx: The Typer context object.
level: The logging level for the specified command.
"""
try:
run_info... | Starts `accelerate` sub-process w/ automatically configured common params.
Args:
ctx: The Typer context object.
level: The logging level for the specified command.
| accelerate | python | oumi-ai/oumi | src/oumi/cli/distributed_run.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/distributed_run.py | Apache-2.0 |
def _detect_process_run_info(env: dict[str, str]) -> _ProcessRunInfo:
"""Detects process run info.
Uses known environment variables to detect common runtime parameters.
Args:
env: All environment variables.
Returns:
Process run info.
Raises:
ValueError: If any of the requ... | Detects process run info.
Uses known environment variables to detect common runtime parameters.
Args:
env: All environment variables.
Returns:
Process run info.
Raises:
ValueError: If any of the required environment variables are missing or invalid.
RuntimeError: If t... | _detect_process_run_info | python | oumi-ai/oumi | src/oumi/cli/distributed_run.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/distributed_run.py | Apache-2.0 |
def _get_package_version(package_name: str, version_fallback: str) -> str:
"""Gets the version of the specified package.
Args:
package_name: The name of the package.
version_fallback: The fallback version string.
Returns:
str: The version of the package, or a fallback string if the... | Gets the version of the specified package.
Args:
package_name: The name of the package.
version_fallback: The fallback version string.
Returns:
str: The version of the package, or a fallback string if the package is not
installed.
| _get_package_version | python | oumi-ai/oumi | src/oumi/cli/env.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/env.py | Apache-2.0 |
def env():
"""Prints information about the current environment."""
# Delayed imports
from oumi.utils.torch_utils import format_cudnn_version
# End imports
version_fallback = "<not installed>"
env_var_fallback = "<not set>"
# All relevant environment vars.
env_vars = sorted(
[
... | Prints information about the current environment. | env | python | oumi-ai/oumi | src/oumi/cli/env.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/env.py | Apache-2.0 |
def fetch(
config_path: Annotated[
str,
typer.Argument(
help="Path to config "
"(e.g. oumi://configs/recipes/smollm/inference/135m_infer.yaml)"
),
],
output_dir: Annotated[
Optional[Path],
typer.Option(
"--output-dir",
"... | Fetch configuration files from GitHub repository. | fetch | python | oumi-ai/oumi | src/oumi/cli/fetch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/fetch.py | Apache-2.0 |
def infer(
ctx: typer.Context,
config: Annotated[
str,
typer.Option(
*cli_utils.CONFIG_FLAGS,
help="Path to the configuration file for inference.",
),
],
interactive: Annotated[
bool,
typer.Option("-i", "--interactive", help="Run in an inte... | Run inference on a model.
If `input_filepath` is provided in the configuration file, inference will run on
those input examples. Otherwise, inference will run interactively with user-provided
inputs.
Args:
ctx: The Typer context object.
config: Path to the configuration file for infere... | infer | python | oumi-ai/oumi | src/oumi/cli/infer.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/infer.py | Apache-2.0 |
def model(
ctx: typer.Context,
config: Annotated[
str, typer.Option(*cli_utils.CONFIG_FLAGS, help="Path to the judge config file")
],
inference_config: Annotated[
str,
typer.Option(help="Path to the inference config file"),
],
input_file: Annotated[
Optional[str],... | Judge the outputs of a model on a dataset. | model | python | oumi-ai/oumi | src/oumi/cli/judge.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/judge.py | Apache-2.0 |
def _get_working_dir(current: str) -> str:
"""Prompts the user to select the working directory, if relevant."""
if not is_dev_build():
return current
oumi_root = get_git_root_dir()
if not oumi_root or oumi_root == Path(current).resolve():
return current
use_root = typer.confirm(
... | Prompts the user to select the working directory, if relevant. | _get_working_dir | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def _print_and_wait(
message: str, task: Callable[..., bool], asynchronous=True, **kwargs
) -> None:
"""Prints a message with a loading spinner until the provided task is done."""
with cli_utils.CONSOLE.status(message):
if asynchronous:
with Pool(processes=1) as worker_pool:
... | Prints a message with a loading spinner until the provided task is done. | _print_and_wait | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def _is_job_done(id: str, cloud: str, cluster: str) -> bool:
"""Returns true IFF a job is no longer running."""
from oumi import launcher
running_cloud = launcher.get_cloud(cloud)
running_cluster = running_cloud.get_cluster(cluster)
if not running_cluster:
return True
status = running_c... | Returns true IFF a job is no longer running. | _is_job_done | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def _cancel_worker(id: str, cloud: str, cluster: str) -> bool:
"""Cancels a job.
All workers must return a boolean to indicate whether the task is done.
Cancel has no intermediate states, so it always returns True.
"""
from oumi import launcher
if not cluster:
return True
if not id... | Cancels a job.
All workers must return a boolean to indicate whether the task is done.
Cancel has no intermediate states, so it always returns True.
| _cancel_worker | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def _down_worker(cluster: str, cloud: Optional[str]) -> bool:
"""Turns down a cluster.
All workers must return a boolean to indicate whether the task is done.
Down has no intermediate states, so it always returns True.
"""
from oumi import launcher
if cloud:
target_cloud = launcher.get... | Turns down a cluster.
All workers must return a boolean to indicate whether the task is done.
Down has no intermediate states, so it always returns True.
| _down_worker | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def _stop_worker(cluster: str, cloud: Optional[str]) -> bool:
"""Stops a cluster.
All workers must return a boolean to indicate whether the task is done.
Stop has no intermediate states, so it always returns True.
"""
from oumi import launcher
if cloud:
target_cloud = launcher.get_clou... | Stops a cluster.
All workers must return a boolean to indicate whether the task is done.
Stop has no intermediate states, so it always returns True.
| _stop_worker | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def _poll_job(
job_status: "JobStatus",
detach: bool,
cloud: str,
running_cluster: Optional["BaseCluster"] = None,
) -> None:
"""Polls a job until it is complete.
If the job is running in detached mode and the job is not on the local cloud,
the function returns immediately.
"""
from... | Polls a job until it is complete.
If the job is running in detached mode and the job is not on the local cloud,
the function returns immediately.
| _poll_job | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def cancel(
cloud: Annotated[str, typer.Option(help="Filter results by this cloud.")],
cluster: Annotated[
str,
typer.Option(help="Filter results by clusters matching this name."),
],
id: Annotated[
str, typer.Option(help="Filter results by jobs matching this job ID.")
],
... | Cancels a job.
Args:
cloud: Filter results by this cloud.
cluster: Filter results by clusters matching this name.
id: Filter results by jobs matching this job ID.
level: The logging level for the specified command.
| cancel | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def down(
cluster: Annotated[str, typer.Option(help="The cluster to turn down.")],
cloud: Annotated[
Optional[str],
typer.Option(
help="If specified, only clusters on this cloud will be affected."
),
] = None,
level: cli_utils.LOG_LEVEL_TYPE = None,
) -> None:
"""... | Turns down a cluster.
Args:
cluster: The cluster to turn down.
cloud: If specified, only clusters on this cloud will be affected.
level: The logging level for the specified command.
| down | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def run(
ctx: typer.Context,
config: Annotated[
str,
typer.Option(
*cli_utils.CONFIG_FLAGS, help="Path to the configuration file for the job."
),
],
cluster: Annotated[
Optional[str],
typer.Option(
help=(
"The cluster to use... | Runs a job on the target cluster.
Args:
ctx: The Typer context object.
config: Path to the configuration file for the job.
cluster: The cluster to use for this job. If no such cluster exists, a new
cluster will be created. If unspecified, a new cluster will be created with
... | run | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def status(
cloud: Annotated[
Optional[str], typer.Option(help="Filter results by this cloud.")
] = None,
cluster: Annotated[
Optional[str],
typer.Option(help="Filter results by clusters matching this name."),
] = None,
id: Annotated[
Optional[str], typer.Option(help=... | Prints the status of jobs launched from Oumi.
Optionally, the caller may specify a job id, cluster, or cloud to further filter
results.
Args:
cloud: Filter results by this cloud.
cluster: Filter results by clusters matching this name.
id: Filter results by jobs matching this job ID... | status | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def stop(
cluster: Annotated[str, typer.Option(help="The cluster to stop.")],
cloud: Annotated[
Optional[str],
typer.Option(
help="If specified, only clusters on this cloud will be affected."
),
] = None,
level: cli_utils.LOG_LEVEL_TYPE = None,
) -> None:
"""Stops... | Stops a cluster.
Args:
cluster: The cluster to stop.
cloud: If specified, only clusters on this cloud will be affected.
level: The logging level for the specified command.
| stop | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def up(
ctx: typer.Context,
config: Annotated[
str,
typer.Option(
*cli_utils.CONFIG_FLAGS, help="Path to the configuration file for the job."
),
],
cluster: Annotated[
Optional[str],
typer.Option(
help=(
"The cluster to use ... | Launches a job.
Args:
ctx: The Typer context object.
config: Path to the configuration file for the job.
cluster: The cluster to use for this job. If no such cluster exists, a new
cluster will be created. If unspecified, a new cluster will be created with
a unique na... | up | python | oumi-ai/oumi | src/oumi/cli/launch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/launch.py | Apache-2.0 |
def train(
ctx: typer.Context,
config: Annotated[
str,
typer.Option(
*cli_utils.CONFIG_FLAGS, help="Path to the configuration file for training."
),
],
level: cli_utils.LOG_LEVEL_TYPE = None,
):
"""Train a model.
Args:
ctx: The Typer context object.
... | Train a model.
Args:
ctx: The Typer context object.
config: Path to the configuration file for training.
level: The logging level for the specified command.
| train | python | oumi-ai/oumi | src/oumi/cli/train.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/cli/train.py | Apache-2.0 |
def safe_asyncio_run(main: Coroutine[Any, Any, T]) -> T:
"""Run an Awaitable in a new thread. Blocks until the thread is finished.
This circumvents the issue of running async functions in the main thread when
an event loop is already running (Jupyter notebooks, for example).
Prefer using `safe_asyncio... | Run an Awaitable in a new thread. Blocks until the thread is finished.
This circumvents the issue of running async functions in the main thread when
an event loop is already running (Jupyter notebooks, for example).
Prefer using `safe_asyncio_run` over `asyncio.run` to allow upstream callers to
ignore... | safe_asyncio_run | python | oumi-ai/oumi | src/oumi/core/async_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/async_utils.py | Apache-2.0 |
def _get_use_orig_params(config: TrainingConfig) -> bool:
"""Returns whether to use the PyTorch Module's original parameters for FSDP.
If the user specified a value, return that. Else, infer its value based on other
config values (compilation, FSDP, PEFT).
"""
if config.fsdp.use_orig_params is not ... | Returns whether to use the PyTorch Module's original parameters for FSDP.
If the user specified a value, return that. Else, infer its value based on other
config values (compilation, FSDP, PEFT).
| _get_use_orig_params | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def _parse_rank(rank: Optional[str]) -> int:
"""Parse the rank from the environment variable."""
if not rank:
return 0
# -1 is a special value that means "not set".
# It's used by the Accelerate launcher.
# Defaulting to 0.
if rank.strip() == "-1":
return 0
if not rank.isdi... | Parse the rank from the environment variable. | _parse_rank | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def get_device_rank_info() -> DeviceRankInfo:
"""Returns device rank and world size."""
world_size = int(os.environ.get("WORLD_SIZE", 1))
if world_size <= 0:
raise ValueError(f"WORLD_SIZE must be positive. Actual: {world_size}.")
rank = _parse_rank(os.environ.get("RANK"))
if rank < 0 or rank... | Returns device rank and world size. | get_device_rank_info | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def verify_torch_distributed_initialized_if_needed() -> None:
"""Checks if torch.dist is initialized if WORLD_SIZE> 1."""
device_rank_info: DeviceRankInfo = get_device_rank_info()
world_size = device_rank_info.world_size
if world_size > 1 and not (
torch.distributed.is_available() and torch.dist... | Checks if torch.dist is initialized if WORLD_SIZE> 1. | verify_torch_distributed_initialized_if_needed | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def is_world_process_zero() -> bool:
"""Whether or not this process is the global main process.
When training in a distributed fashion on several machines
this is only going to be `True` for one process.
"""
device_rank_info: DeviceRankInfo = get_device_rank_info()
return device_rank_info.rank ... | Whether or not this process is the global main process.
When training in a distributed fashion on several machines
this is only going to be `True` for one process.
| is_world_process_zero | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def is_local_process_zero() -> bool:
"""Whether or not this process is the local main process.
When training in a distributed fashion on several machines
this is only going to be `True` for one process per node.
"""
device_rank_info: DeviceRankInfo = get_device_rank_info()
return device_rank_in... | Whether or not this process is the local main process.
When training in a distributed fashion on several machines
this is only going to be `True` for one process per node.
| is_local_process_zero | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def is_distributed() -> bool:
"""Whether or not the training is distributed.
Returns:
bool: True if the training is distributed, False otherwise.
"""
device_rank_info: DeviceRankInfo = get_device_rank_info()
return device_rank_info.world_size > 1 | Whether or not the training is distributed.
Returns:
bool: True if the training is distributed, False otherwise.
| is_distributed | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def barrier(
group: Optional[torch.distributed.ProcessGroup] = None, monitored: bool = False
) -> None:
"""Barrier synchronization among all processes in the group."""
if torch.distributed.is_available() and torch.distributed.is_initialized():
if monitored:
torch.distributed.monitored_ba... | Barrier synchronization among all processes in the group. | barrier | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def all_gather_object(
obj: T, group: Optional[torch.distributed.ProcessGroup] = None
) -> list[T]:
"""Gathers picklable objects from the whole group into a list."""
verify_torch_distributed_initialized_if_needed()
if is_distributed():
device_rank_info: DeviceRankInfo = get_device_rank_info()
... | Gathers picklable objects from the whole group into a list. | all_gather_object | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def local_leader_only(*barrier_args, **barrier_kwargs):
"""Decorator for local leaders only operations."""
def decorator(user_function):
@functools.wraps(user_function)
def wrapper(*args, **kwargs):
if is_local_process_zero():
# Execute the user function
... | Decorator for local leaders only operations. | local_leader_only | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def local_leader_first(*args, **kwargs):
"""Context manager for local leader first operations."""
if is_local_process_zero():
yield
barrier(*args, **kwargs)
else:
barrier(*args, **kwargs)
yield | Context manager for local leader first operations. | local_leader_first | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def global_leader_only(*args, **kwargs):
"""Decorator for global leader only operations."""
def decorator(user_function):
@functools.wraps(user_function)
def wrapper(*user_fn_args, **user_fn_kwargs):
if is_world_process_zero():
# Execute the user function
... | Decorator for global leader only operations. | global_leader_only | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def global_leader_first(*args, **kwargs):
"""Context manager for global leader first operations."""
if is_world_process_zero():
yield
barrier(*args, **kwargs)
else:
barrier(*args, **kwargs)
yield | Context manager for global leader first operations. | global_leader_first | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def prepare_model_for_distributed(
model: torch.nn.Module,
config: TrainingConfig,
ddp_find_unused_parameters: Optional[bool] = None,
) -> torch.nn.Module:
"""Wrap the model for distributed training (DDP or FSDP).
Args:
model: The model to be wrapped.
config: The training config.
... | Wrap the model for distributed training (DDP or FSDP).
Args:
model: The model to be wrapped.
config: The training config.
ddp_find_unused_parameters: Whether to traverse the autograd graph from all
tensors contained in the return value of the wrapped module's `forward`
... | prepare_model_for_distributed | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def get_accelerate_env_vars(config: TrainingConfig) -> dict[str, str]:
"""Gets environment vars for FSDP Accelerate corresponding to Oumi training params.
This mimics the environment variables set here:
https://github.com/huggingface/accelerate/blob/bf4572b6ce0a534a9d73537485a0edf1d68144b8/src/accelerate/u... | Gets environment vars for FSDP Accelerate corresponding to Oumi training params.
This mimics the environment variables set here:
https://github.com/huggingface/accelerate/blob/bf4572b6ce0a534a9d73537485a0edf1d68144b8/src/accelerate/utils/launch.py#L260-L285
Note how they lowercase all boolean values, excep... | get_accelerate_env_vars | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def prepare_accelerate_fsdp_run(config: TrainingConfig) -> dict[str, str]:
"""Prepares our FSDP training job to run with the HuggingFace Accelerate library.
This function should be run if we didn't invoke the current training job from the
Accelerate launcher, but still want to use FSDP with Accelerate. The... | Prepares our FSDP training job to run with the HuggingFace Accelerate library.
This function should be run if we didn't invoke the current training job from the
Accelerate launcher, but still want to use FSDP with Accelerate. The motivation for
this is to remove the need for the Accelerate config, centrali... | prepare_accelerate_fsdp_run | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def estimate_dataloader_num_workers(
gpus_per_node: Optional[int] = None, cpu_count: Optional[int] = None
) -> int:
"""Estimates the number of dataloader workers.
Uses a simple heuristic based on the number of GPU-s and CPU-s per node.
Args:
gpus_per_node: The number of GPU-s per node.
... | Estimates the number of dataloader workers.
Uses a simple heuristic based on the number of GPU-s and CPU-s per node.
Args:
gpus_per_node: The number of GPU-s per node.
cpu_count: The number of CPU cores.
Returns:
The estimated number of dataloader workers (a non-zero positive numb... | estimate_dataloader_num_workers | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def set_random_seeds(seed: int = 42, set_deterministic: bool = False) -> None:
"""Set random seeds for reproducibility.
Each worker will have a different seed to ensure that each worker
starts with a different random state.
Args:
seed: The seed value to set for random number generators.
... | Set random seeds for reproducibility.
Each worker will have a different seed to ensure that each worker
starts with a different random state.
Args:
seed: The seed value to set for random number generators.
set_deterministic: Whether to set deterministic mode for CUDA operations.
| set_random_seeds | python | oumi-ai/oumi | src/oumi/core/distributed.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/distributed.py | Apache-2.0 |
def on_save(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Saving callback.
Gets triggered at each saving step to qu... | Saving callback.
Gets triggered at each saving step to quantize trained models
in 1bit precision.
| on_save | python | oumi-ai/oumi | src/oumi/core/callbacks/bitnet_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/bitnet_callback.py | Apache-2.0 |
def __init__(
self,
dtype: torch.dtype,
):
"""Initialize the HfMfuTrainerCallback.
Args:
dtype: The data type of the model.
"""
self._dtype = dtype
self._time_of_second_step: Optional[float] = None
self._flops_at_second_step: Optional[floa... | Initialize the HfMfuTrainerCallback.
Args:
dtype: The data type of the model.
| __init__ | python | oumi-ai/oumi | src/oumi/core/callbacks/hf_mfu_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/hf_mfu_callback.py | Apache-2.0 |
def on_step_begin(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the beginning of each train step."""
... | Event called at the beginning of each train step. | on_step_begin | python | oumi-ai/oumi | src/oumi/core/callbacks/hf_mfu_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/hf_mfu_callback.py | Apache-2.0 |
def on_step_end(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the end of each train step.
Note that... | Event called at the end of each train step.
Note that this will be called after all gradient accumulation substeps.
| on_step_end | python | oumi-ai/oumi | src/oumi/core/callbacks/hf_mfu_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/hf_mfu_callback.py | Apache-2.0 |
def on_log(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called after logging the last logs."""
if self._callb... | Event called after logging the last logs. | on_log | python | oumi-ai/oumi | src/oumi/core/callbacks/hf_mfu_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/hf_mfu_callback.py | Apache-2.0 |
def __init__(
self,
dtype: torch.dtype,
num_params: int,
sequence_length: int,
num_layers: Optional[int] = None,
num_attention_heads: Optional[int] = None,
attention_head_size: Optional[int] = None,
add_rematerialization: bool = False,
):
"""In... | Initialize the MfuTrainerCallback.
Args:
dtype: The data type of the model.
num_params: The number of parameters in the model.
start_time_seconds: The start time of the program.
sequence_length: The sequence length of the model.
num_layers: The number... | __init__ | python | oumi-ai/oumi | src/oumi/core/callbacks/mfu_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/mfu_callback.py | Apache-2.0 |
def __init__(
self,
metrics: list[str],
):
"""Initializes the NanInfDetectionCallback.
Args:
metrics: The list of metrics to monitor.
"""
self._metrics = copy.deepcopy(metrics) | Initializes the NanInfDetectionCallback.
Args:
metrics: The list of metrics to monitor.
| __init__ | python | oumi-ai/oumi | src/oumi/core/callbacks/nan_inf_detection_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/nan_inf_detection_callback.py | Apache-2.0 |
def __init__(self, profiler):
"""Initialize the ProfilerStepCallback.
Args:
profiler: PyTorch profiler object.
"""
self._profiler = profiler
self._microstep_function = None | Initialize the ProfilerStepCallback.
Args:
profiler: PyTorch profiler object.
| __init__ | python | oumi-ai/oumi | src/oumi/core/callbacks/profiler_step_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/profiler_step_callback.py | Apache-2.0 |
def on_step_begin(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the beginning of a training step.
I... | Event called at the beginning of a training step.
If using gradient accumulation, one training step might take several inputs.
| on_step_begin | python | oumi-ai/oumi | src/oumi/core/callbacks/profiler_step_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/profiler_step_callback.py | Apache-2.0 |
def on_substep_end(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the end of an substep during gradient accum... | Event called at the end of an substep during gradient accumulation. | on_substep_end | python | oumi-ai/oumi | src/oumi/core/callbacks/profiler_step_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/profiler_step_callback.py | Apache-2.0 |
def __init__(
self,
skip_first_steps: int = 1,
world_process_zero_only: bool = True,
include_timer_metrics: bool = False,
track_gpu_temperature: bool = False,
output_dir: Optional[pathlib.Path] = None,
):
"""Initializes the TelemetryCallback.
Args:
... | Initializes the TelemetryCallback.
Args:
skip_first_steps: The number of initial steps to exclude from stats.
world_process_zero_only: Whether to collect stats on the main process only.
include_timer_metrics: Whether to add timer stats to reported metrics.
Th... | __init__ | python | oumi-ai/oumi | src/oumi/core/callbacks/telemetry_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/telemetry_callback.py | Apache-2.0 |
def on_substep_end(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the end of a substep during gradient accumu... | Event called at the end of a substep during gradient accumulation. | on_substep_end | python | oumi-ai/oumi | src/oumi/core/callbacks/telemetry_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/telemetry_callback.py | Apache-2.0 |
def on_epoch_begin(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the beginning of an epoch."""
if se... | Event called at the beginning of an epoch. | on_epoch_begin | python | oumi-ai/oumi | src/oumi/core/callbacks/telemetry_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/telemetry_callback.py | Apache-2.0 |
def on_epoch_end(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the end of an epoch."""
if self._perm... | Event called at the end of an epoch. | on_epoch_end | python | oumi-ai/oumi | src/oumi/core/callbacks/telemetry_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/telemetry_callback.py | Apache-2.0 |
def on_train_end(
self,
args: Union[transformers.TrainingArguments, TrainingParams],
state: Optional[transformers.TrainerState] = None,
control: Optional[transformers.TrainerControl] = None,
**kwargs,
):
"""Event called at the end of training."""
if self._call... | Event called at the end of training. | on_train_end | python | oumi-ai/oumi | src/oumi/core/callbacks/telemetry_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/telemetry_callback.py | Apache-2.0 |
def _callback_disabled(self) -> bool:
"""Check if the callback should be disabled."""
if self._permanently_disabled:
return True
if self._skip_first_steps > 0 and self._step <= self._skip_first_steps:
return True
return False | Check if the callback should be disabled. | _callback_disabled | python | oumi-ai/oumi | src/oumi/core/callbacks/telemetry_callback.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/callbacks/telemetry_callback.py | Apache-2.0 |
def __call__(self, batch) -> dict[str, Any]:
"""Pads to the longest length present in the batch.
Args:
batch: List of batch items.
Returns:
Dict[str, torch.Tensor]: Processed batch.
"""
collation_inputs: dict[str, list[Any]] = collections.defaultdict(lis... | Pads to the longest length present in the batch.
Args:
batch: List of batch items.
Returns:
Dict[str, torch.Tensor]: Processed batch.
| __call__ | python | oumi-ai/oumi | src/oumi/core/collators/text_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/text_collator_with_padding.py | Apache-2.0 |
def _log_debug_example(
self,
batch: list[dict[str, Any]],
combined_batch: dict[str, Any],
) -> None:
"""Logs a debug example if debug is enabled.
Args:
batch: The original batch of data.
combined_batch: The collated batch after processing.
""... | Logs a debug example if debug is enabled.
Args:
batch: The original batch of data.
combined_batch: The collated batch after processing.
| _log_debug_example | python | oumi-ai/oumi | src/oumi/core/collators/text_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/text_collator_with_padding.py | Apache-2.0 |
def _update_max_lengths_and_log(self, *, max_input_ids_length: int):
"""Updates max length counters.
Also, logs a truncation warning if increment is large enough.
"""
_LOG_REL_INCREMENT = 0.1 # log if max length is up 10%
log_max_lengths: bool = False
if max_input_ids_... | Updates max length counters.
Also, logs a truncation warning if increment is large enough.
| _update_max_lengths_and_log | python | oumi-ai/oumi | src/oumi/core/collators/text_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/text_collator_with_padding.py | Apache-2.0 |
def __init__(
self,
tokenizer: BaseTokenizer,
instruction_prefix: str,
response_prefix: str,
debug: bool = False,
):
"""Custom collator for text LLM training.
Args:
tokenizer: The tokenizer used for encoding the data.
instruction_prefix: The p... | Custom collator for text LLM training.
Args:
tokenizer: The tokenizer used for encoding the data.
instruction_prefix: The prefix marking the beginning of the user instruction.
response_prefix: The prefix marking the beginning of the assistant response.
debug: If True, enables de... | __init__ | python | oumi-ai/oumi | src/oumi/core/collators/text_completions_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/text_completions_collator_with_padding.py | Apache-2.0 |
def _log_debug_example(
self, batch: list[dict[str, Any]], collated_text_inputs: dict[str, Any]
) -> None:
"""Logs an example of the data in each step for debugging purposes.
Args:
batch: The batch of examples to log.
collated_text_inputs: The collated inputs after p... | Logs an example of the data in each step for debugging purposes.
Args:
batch: The batch of examples to log.
collated_text_inputs: The collated inputs after processing.
| _log_debug_example | python | oumi-ai/oumi | src/oumi/core/collators/text_completions_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/text_completions_collator_with_padding.py | Apache-2.0 |
def _to_py(x):
"""Convert tensor-like objects to Python native types."""
if hasattr(x, "tolist"):
return x.tolist()
elif hasattr(x, "item"):
return x.item()
else:
return x | Convert tensor-like objects to Python native types. | _to_py | python | oumi-ai/oumi | src/oumi/core/collators/text_completions_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/text_completions_collator_with_padding.py | Apache-2.0 |
def __init__(
self,
tokenizer: BaseTokenizer,
*,
max_length: Optional[int],
truncation: bool = False,
label_ignore_index: Optional[int] = None,
allow_multi_image_inputs: bool = True,
main_image_feature: str = "pixel_values",
):
"""Custom collat... | Custom collator for multi-modal vision-language training.
Args:
tokenizer: The tokenizer used for encoding the data.
max_length: Padding length.
truncation: Whether to truncate long inputs to `max_length`.
If False, the long inputs are preserved as is even if they exceed
... | __init__ | python | oumi-ai/oumi | src/oumi/core/collators/vision_language_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/vision_language_collator_with_padding.py | Apache-2.0 |
def __call__(self, batch) -> dict[str, Any]:
"""Custom collator for multi-modal vision-language training.
Args:
batch: List of batch items.
Returns:
Dict[str, torch.Tensor]: Processed batch.
"""
# Collate batch prompts
collated_batch = self._text... | Custom collator for multi-modal vision-language training.
Args:
batch: List of batch items.
Returns:
Dict[str, torch.Tensor]: Processed batch.
| __call__ | python | oumi-ai/oumi | src/oumi/core/collators/vision_language_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/vision_language_collator_with_padding.py | Apache-2.0 |
def collate_images(self, images) -> torch.Tensor:
"""Collate images for multi-modal training.
Args:
images: List of images to collate.
Returns:
torch.Tensor: Batch of processed images.
"""
if len(images) == 0:
raise ValueError("No images foun... | Collate images for multi-modal training.
Args:
images: List of images to collate.
Returns:
torch.Tensor: Batch of processed images.
| collate_images | python | oumi-ai/oumi | src/oumi/core/collators/vision_language_collator_with_padding.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/vision_language_collator_with_padding.py | Apache-2.0 |
def __init__(
self,
tokenizer: BaseTokenizer,
processor_name: str,
*,
processor_kwargs: Optional[dict[str, Any]] = None,
max_length: Optional[int] = None,
truncation: bool = False,
truncation_side: str = "right",
label_ignore_index: Optional[int] =... | Initializes the vision-language SFT collator.
Args:
tokenizer: The tokenizer for encoding text. Should match the model's
tokenizer for proper token alignment.
processor_name: Name or path of the processor to use for feature extraction.
This should typica... | __init__ | python | oumi-ai/oumi | src/oumi/core/collators/vision_language_sft_collator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/vision_language_sft_collator.py | Apache-2.0 |
def __call__(self, batch) -> dict[str, Any]:
"""Process a batch of conversation data into model-ready features.
This method converts serialized conversations into the tensor format expected
by vision-language models. It handles the complete pipeline:
1. Deserializes conversation JSON st... | Process a batch of conversation data into model-ready features.
This method converts serialized conversations into the tensor format expected
by vision-language models. It handles the complete pipeline:
1. Deserializes conversation JSON strings
2. Passes conversations to the feature gen... | __call__ | python | oumi-ai/oumi | src/oumi/core/collators/vision_language_sft_collator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/vision_language_sft_collator.py | Apache-2.0 |
def _collate_individual_results(
self, results: list[dict[str, Any]]
) -> dict[str, Any]:
"""Collate individually processed results by padding to max dimensions.
Args:
results: List of feature dictionaries from individual conversation
processing
Returns:... | Collate individually processed results by padding to max dimensions.
Args:
results: List of feature dictionaries from individual conversation
processing
Returns:
Collated dictionary with padded tensors
Raises:
ValueError: If results have inc... | _collate_individual_results | python | oumi-ai/oumi | src/oumi/core/collators/vision_language_sft_collator.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/collators/vision_language_sft_collator.py | Apache-2.0 |
def _read_config_without_interpolation(config_path: str) -> str:
"""Reads a configuration file without interpolating variables.
Args:
config_path: The path to the configuration file.
Returns:
str: The stringified configuration.
"""
with open(config_path) as f:
stringified_c... | Reads a configuration file without interpolating variables.
Args:
config_path: The path to the configuration file.
Returns:
str: The stringified configuration.
| _read_config_without_interpolation | python | oumi-ai/oumi | src/oumi/core/configs/base_config.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/base_config.py | Apache-2.0 |
def from_yaml(
cls: type[T], config_path: Union[str, Path], ignore_interpolation=True
) -> T:
"""Loads a configuration from a YAML file.
Args:
config_path: The path to the YAML file.
ignore_interpolation: If True, then any interpolation variables in the
... | Loads a configuration from a YAML file.
Args:
config_path: The path to the YAML file.
ignore_interpolation: If True, then any interpolation variables in the
configuration file will be escaped.
Returns:
BaseConfig: The merged configuration object.
... | from_yaml | python | oumi-ai/oumi | src/oumi/core/configs/base_config.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/base_config.py | Apache-2.0 |
def from_str(cls: type[T], config_str: str) -> T:
"""Loads a configuration from a YAML string.
Args:
config_str: The YAML string.
Returns:
BaseConfig: The configuration object.
"""
schema = OmegaConf.structured(cls)
file_config = OmegaConf.create... | Loads a configuration from a YAML string.
Args:
config_str: The YAML string.
Returns:
BaseConfig: The configuration object.
| from_str | python | oumi-ai/oumi | src/oumi/core/configs/base_config.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/base_config.py | Apache-2.0 |
def from_yaml_and_arg_list(
cls: type[T],
config_path: Optional[str],
arg_list: list[str],
logger: Optional[logging.Logger] = None,
ignore_interpolation=True,
) -> T:
"""Loads a configuration from various sources.
If both YAML and arguments list are provided,... | Loads a configuration from various sources.
If both YAML and arguments list are provided, then
parameters specified in `arg_list` have higher precedence.
Args:
config_path: The path to the YAML file.
arg_list: Command line arguments list.
logger: (optional) ... | from_yaml_and_arg_list | python | oumi-ai/oumi | src/oumi/core/configs/base_config.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/base_config.py | Apache-2.0 |
def finalize_and_validate(self) -> None:
"""Finalizes and validates the top level params objects."""
for _, attr_value in self:
if isinstance(attr_value, BaseParams):
attr_value.finalize_and_validate()
self.__finalize_and_validate__() | Finalizes and validates the top level params objects. | finalize_and_validate | python | oumi-ai/oumi | src/oumi/core/configs/base_config.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/base_config.py | Apache-2.0 |
def __finalize_and_validate__(self) -> None:
"""Finalizes and validates the parameters of this object.
This method can be overridden by subclasses to implement custom
validation logic.
In case of validation errors, this method should raise a `ValueError`
or other appropriate ex... | Finalizes and validates the parameters of this object.
This method can be overridden by subclasses to implement custom
validation logic.
In case of validation errors, this method should raise a `ValueError`
or other appropriate exception.
| __finalize_and_validate__ | python | oumi-ai/oumi | src/oumi/core/configs/base_config.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/core/configs/base_config.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.