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 _worker_run_job(self) -> Optional[_LocalJob]:
"""Kicks off and returns a new job. Assumes the mutex is already acquired."""
job = self._get_next_job()
if job is None:
return None
env_copy = os.environ.copy()
env_copy.update(job.config.envs)
# Check if the ... | Kicks off and returns a new job. Assumes the mutex is already acquired. | _worker_run_job | python | oumi-ai/oumi | src/oumi/launcher/clients/local_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/local_client.py | Apache-2.0 |
def _worker_handle_running_job(self, job: _LocalJob) -> None:
"""Polls and handles the specified job. Acquires the mutex."""
# Return immediately if no job is running.
if self._running_process is None:
return
# Wait for the job to finish. No need to grab the mutex here.
... | Polls and handles the specified job. Acquires the mutex. | _worker_handle_running_job | python | oumi-ai/oumi | src/oumi/launcher/clients/local_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/local_client.py | Apache-2.0 |
def _worker_loop(self):
"""The main worker loop that runs jobs."""
while True:
with self._mutex:
# Run the next job if it exists.
job = self._worker_run_job()
# No job to run, sleep for a bit.
if job is None:
time.sleep(... | The main worker loop that runs jobs. | _worker_loop | python | oumi-ai/oumi | src/oumi/launcher/clients/local_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/local_client.py | Apache-2.0 |
def _get_next_job(self) -> Optional[_LocalJob]:
"""Gets the next QUEUED job from the queue."""
queued_jobs = [
job
for job in self._jobs.values()
if job.status.status == _JobState.QUEUED.value
]
if len(queued_jobs) == 0:
return None
... | Gets the next QUEUED job from the queue. | _get_next_job | python | oumi-ai/oumi | src/oumi/launcher/clients/local_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/local_client.py | Apache-2.0 |
def submit_job(self, job: JobConfig) -> JobStatus:
"""Runs the specified job on this cluster."""
with self._mutex:
job_id = self._generate_next_job_id()
name = job.name if job.name else job_id
status = JobStatus(
name=name,
id=job_id,
... | Runs the specified job on this cluster. | submit_job | python | oumi-ai/oumi | src/oumi/launcher/clients/local_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/local_client.py | Apache-2.0 |
def get_job(self, job_id: str) -> Optional[JobStatus]:
"""Gets the specified job's status.
Args:
job_id: The ID of the job to get.
Returns:
The job status if found, None otherwise.
"""
job_list = self.list_jobs()
for job in job_list:
... | Gets the specified job's status.
Args:
job_id: The ID of the job to get.
Returns:
The job status if found, None otherwise.
| get_job | python | oumi-ai/oumi | src/oumi/launcher/clients/local_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/local_client.py | Apache-2.0 |
def cancel(self, job_id) -> Optional[JobStatus]:
"""Cancels the specified job.
Args:
job_id: The ID of the job to cancel.
queue: The name of the queue to search.
Returns:
The job status if found, None otherwise.
"""
with self._mutex:
... | Cancels the specified job.
Args:
job_id: The ID of the job to cancel.
queue: The name of the queue to search.
Returns:
The job status if found, None otherwise.
| cancel | python | oumi-ai/oumi | src/oumi/launcher/clients/local_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/local_client.py | Apache-2.0 |
def _check_connection(user: str):
"""Checks if the connection is still open."""
ssh_cmd = f"ssh {_CTRL_PATH} -O check {user}@polaris.alcf.anl.gov"
try:
child = subprocess.run(
ssh_cmd,
shell=True,
capture_output=True,
timeout=10,
)
except s... | Checks if the connection is still open. | _check_connection | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def retry_auth(user_function):
"""Decorator to ensure auth is fresh before calling a function."""
@functools.wraps(user_function)
def wrapper(self, *args, **kwargs):
self._refresh_creds()
return user_function(self, *args, **kwargs)
return wrapper | Decorator to ensure auth is fresh before calling a function. | retry_auth | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def _split_status_line(self, line: str, metadata: str) -> JobStatus:
"""Splits a status line into a JobStatus object.
The expected order of job fields is:
0. Job ID
1. User
2. Queue
3. Job Name
4. Session ID
5. Node Count
6. Tasks
7. Requi... | Splits a status line into a JobStatus object.
The expected order of job fields is:
0. Job ID
1. User
2. Queue
3. Job Name
4. Session ID
5. Node Count
6. Tasks
7. Required Memory
8. Required Time
9. Status
10. Ellapsed Time
... | _split_status_line | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def _get_short_job_id(self, job_id: str) -> str:
"""Gets the short form of the job ID.
Polaris Job IDs should be of the form:
`2037042.polaris-pbs-01.hsn.cm.polaris.alcf.anl.gov`
where the shortened ID is `2037042`.
Args:
job_id: The job ID to shorten.
Retu... | Gets the short form of the job ID.
Polaris Job IDs should be of the form:
`2037042.polaris-pbs-01.hsn.cm.polaris.alcf.anl.gov`
where the shortened ID is `2037042`.
Args:
job_id: The job ID to shorten.
Returns:
The short form of the job ID.
| _get_short_job_id | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def _refresh_creds(self):
"""Refreshes the credentials for the client."""
try:
_check_connection(self._user)
# We have fresh credentials, so we return early.
return
except _PolarisAuthException:
logger.warning("No connection found. Establishing a n... | Refreshes the credentials for the client. | _refresh_creds | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def get_active_users() -> list[str]:
"""Gets the list of users with an open SSH tunnel to Polaris.
Returns:
A list of users.
"""
# List all active users with an open SSH tunnel to Polaris.
command = "ls ~/.ssh/ | egrep 'control-polaris.alcf.anl.gov-.*-.*'"
re... | Gets the list of users with an open SSH tunnel to Polaris.
Returns:
A list of users.
| get_active_users | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def run_commands(self, commands: list[str]) -> PolarisResponse:
"""Runs the provided commands in a single SSH command.
Args:
commands: The commands to run.
"""
ssh_cmd = f"ssh {_CTRL_PATH} {self._user}@polaris.alcf.anl.gov << 'EOF'"
eof_suffix = "EOF"
new_cm... | Runs the provided commands in a single SSH command.
Args:
commands: The commands to run.
| run_commands | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def list_jobs(self, queue: SupportedQueues) -> list[JobStatus]:
"""Lists a list of job statuses for the given queue.
Returns:
A list of dictionaries, each containing the status of a cluster.
"""
command = f"qstat -s -x -w -u {self._user}"
result = self.run_commands([... | Lists a list of job statuses for the given queue.
Returns:
A list of dictionaries, each containing the status of a cluster.
| list_jobs | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def get_job(self, job_id: str, queue: SupportedQueues) -> Optional[JobStatus]:
"""Gets the specified job's status.
Args:
job_id: The ID of the job to get.
queue: The name of the queue to search.
Returns:
The job status if found, None otherwise.
"""
... | Gets the specified job's status.
Args:
job_id: The ID of the job to get.
queue: The name of the queue to search.
Returns:
The job status if found, None otherwise.
| get_job | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def put_recursive(self, source: str, destination: str) -> None:
"""Puts the specified file/directory to the remote path using rsync.
Args:
source: The local file/directory to write.
destination: The remote path to write the file/directory to.
"""
if Path(source).... | Puts the specified file/directory to the remote path using rsync.
Args:
source: The local file/directory to write.
destination: The remote path to write the file/directory to.
| put_recursive | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def put(self, file_contents: str, destination: str) -> None:
"""Puts the specified file contents to the remote path.
Args:
file_contents: The contents of the file to write.
destination: The remote path to write the file to.
"""
destination_path = Path(destination... | Puts the specified file contents to the remote path.
Args:
file_contents: The contents of the file to write.
destination: The remote path to write the file to.
| put | python | oumi-ai/oumi | src/oumi/launcher/clients/polaris_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/polaris_client.py | Apache-2.0 |
def _get_sky_cloud_from_job(job: JobConfig) -> "sky.clouds.Cloud":
"""Returns the sky.Cloud object from the JobConfig."""
# Delay sky import: https://github.com/oumi-ai/oumi/issues/1605
import sky
if job.resources.cloud == SkyClient.SupportedClouds.GCP.value:
return sky.clouds.GCP()
elif jo... | Returns the sky.Cloud object from the JobConfig. | _get_sky_cloud_from_job | python | oumi-ai/oumi | src/oumi/launcher/clients/sky_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/sky_client.py | Apache-2.0 |
def _get_sky_storage_mounts_from_job(job: JobConfig) -> dict[str, "sky.data.Storage"]:
"""Returns the sky.StorageMount objects from the JobConfig."""
# Delay sky import: https://github.com/oumi-ai/oumi/issues/1605
import sky.data
sky_mounts = {}
for k, v in job.storage_mounts.items():
stora... | Returns the sky.StorageMount objects from the JobConfig. | _get_sky_storage_mounts_from_job | python | oumi-ai/oumi | src/oumi/launcher/clients/sky_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/sky_client.py | Apache-2.0 |
def _get_use_spot_vm_override() -> Optional[bool]:
"""Determines whether to override `use_spot_vm` setting based on OUMI_USE_SPOT_VM.
Fetches the override value from the OUMI_USE_SPOT_VM environment variable
if specified.
Returns:
The override value if specified, or `None`.
"""
_ENV_VA... | Determines whether to override `use_spot_vm` setting based on OUMI_USE_SPOT_VM.
Fetches the override value from the OUMI_USE_SPOT_VM environment variable
if specified.
Returns:
The override value if specified, or `None`.
| _get_use_spot_vm_override | python | oumi-ai/oumi | src/oumi/launcher/clients/sky_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/sky_client.py | Apache-2.0 |
def __init__(self):
"""Initializes a new instance of the SkyClient class."""
# Delay sky import: https://github.com/oumi-ai/oumi/issues/1605
import sky
self._sky_lib = sky | Initializes a new instance of the SkyClient class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clients/sky_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/sky_client.py | Apache-2.0 |
def launch(
self, job: JobConfig, cluster_name: Optional[str] = None, **kwargs
) -> JobStatus:
"""Creates a cluster and starts the provided Job.
Args:
job: The job to execute on the cluster.
cluster_name: The name of the cluster to create.
kwargs: Additio... | Creates a cluster and starts the provided Job.
Args:
job: The job to execute on the cluster.
cluster_name: The name of the cluster to create.
kwargs: Additional arguments to pass to the Sky Pilot client.
Returns:
A JobStatus with only `id` and `cluster` ... | launch | python | oumi-ai/oumi | src/oumi/launcher/clients/sky_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/sky_client.py | Apache-2.0 |
def exec(self, job: JobConfig, cluster_name: str) -> str:
"""Executes the specified job on the target cluster.
Args:
job: The job to execute.
cluster_name: The name of the cluster to execute the job on.
Returns:
The ID of the job that was created.
""... | Executes the specified job on the target cluster.
Args:
job: The job to execute.
cluster_name: The name of the cluster to execute the job on.
Returns:
The ID of the job that was created.
| exec | python | oumi-ai/oumi | src/oumi/launcher/clients/sky_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/sky_client.py | Apache-2.0 |
def _is_job_done(job_state: str) -> bool:
"""Determines if a job is done based on its state.
See https://slurm.schedmd.com/job_state_codes.html for more details.
Args:
job_state: The state of the job.
Returns:
True if the job is done, False otherwise.
"""
terminal_states = {
... | Determines if a job is done based on its state.
See https://slurm.schedmd.com/job_state_codes.html for more details.
Args:
job_state: The state of the job.
Returns:
True if the job is done, False otherwise.
| _is_job_done | python | oumi-ai/oumi | src/oumi/launcher/clients/slurm_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/slurm_client.py | Apache-2.0 |
def _split_status_line(
line: str, column_lengths: list[int], cluster_name: str, metadata: str
) -> JobStatus:
"""Splits a status line into a JobStatus object.
The expected order of job fields is:
0. Job ID
1. Job Name
2. User
3. Job State
4. Job State Reason
Sample status report:
... | Splits a status line into a JobStatus object.
The expected order of job fields is:
0. Job ID
1. Job Name
2. User
3. Job State
4. Job State Reason
Sample status report:
ID NAME USER STATE REASON
----- ------ ------ --------- ------
1 my_job user COMPLETED 0:0... | _split_status_line | python | oumi-ai/oumi | src/oumi/launcher/clients/slurm_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/slurm_client.py | Apache-2.0 |
def __init__(self, user: str, slurm_host: str, cluster_name: str):
"""Initializes a new instance of the SlurmClient class.
Args:
user: The user to act as.
slurm_host: The Slurm Head Node to connect to.
cluster_name: The name of the cluster this client communicates wi... | Initializes a new instance of the SlurmClient class.
Args:
user: The user to act as.
slurm_host: The Slurm Head Node to connect to.
cluster_name: The name of the cluster this client communicates with.
| __init__ | python | oumi-ai/oumi | src/oumi/launcher/clients/slurm_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/slurm_client.py | Apache-2.0 |
def get_active_users(slurm_host: str) -> list[str]:
"""Gets the list of users with an open SSH tunnel to a Slurm cluster.
Returns:
A list of users.
"""
# List all active users with an open SSH tunnel to the Slurm head node.
command = f"ls ~/.ssh/ | egrep 'control-{sl... | Gets the list of users with an open SSH tunnel to a Slurm cluster.
Returns:
A list of users.
| get_active_users | python | oumi-ai/oumi | src/oumi/launcher/clients/slurm_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/slurm_client.py | Apache-2.0 |
def _parse_job_id(self, sbatch_output: str) -> str:
"""Parses the job ID from the result of sbatch.
From the Slurm MAN page:
Outputs only the job id number and the cluster name if present.
The values are separated by a semicolon. Errors will still be displayed.
Args:
... | Parses the job ID from the result of sbatch.
From the Slurm MAN page:
Outputs only the job id number and the cluster name if present.
The values are separated by a semicolon. Errors will still be displayed.
Args:
sbatch_output: The result of sbatch
Returns:
... | _parse_job_id | python | oumi-ai/oumi | src/oumi/launcher/clients/slurm_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/slurm_client.py | Apache-2.0 |
def list_jobs(self) -> list[JobStatus]:
"""Lists all jobs for the current user.
Returns:
A list of JobStatus.
"""
response_format = "JobId%-30,JobName%30,User%30,State%30,Reason%30"
# Forcibly list all jobs since Jan 1, 2025.
# Otherwise completed jobs older ... | Lists all jobs for the current user.
Returns:
A list of JobStatus.
| list_jobs | python | oumi-ai/oumi | src/oumi/launcher/clients/slurm_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/slurm_client.py | Apache-2.0 |
def cancel(self, job_id) -> Optional[JobStatus]:
"""Cancels the specified job.
Args:
job_id: The ID of the job to cancel.
Returns:
The job status if found, None otherwise.
"""
command = f"scancel {job_id}"
result = self.run_commands([command])
... | Cancels the specified job.
Args:
job_id: The ID of the job to cancel.
Returns:
The job status if found, None otherwise.
| cancel | python | oumi-ai/oumi | src/oumi/launcher/clients/slurm_client.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clients/slurm_client.py | Apache-2.0 |
def __init__(self):
"""Initializes a new instance of the LocalCloud class."""
# A mapping from cluster names to Local Cluster instances.
self._clusters = {} | Initializes a new instance of the LocalCloud class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clouds/local_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/local_cloud.py | Apache-2.0 |
def _get_or_create_cluster(self, name: str) -> LocalCluster:
"""Gets the cluster with the specified name, or creates one if it doesn't exist.
Args:
name: The name of the cluster.
Returns:
LocalCluster: The cluster instance.
"""
if name not in self._clust... | Gets the cluster with the specified name, or creates one if it doesn't exist.
Args:
name: The name of the cluster.
Returns:
LocalCluster: The cluster instance.
| _get_or_create_cluster | python | oumi-ai/oumi | src/oumi/launcher/clouds/local_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/local_cloud.py | Apache-2.0 |
def up_cluster(self, job: JobConfig, name: Optional[str], **kwargs) -> JobStatus:
"""Creates a cluster and starts the provided Job."""
# The default cluster.
cluster_name = name or self._DEFAULT_CLUSTER
cluster = self._get_or_create_cluster(cluster_name)
job_status = cluster.run_... | Creates a cluster and starts the provided Job. | up_cluster | python | oumi-ai/oumi | src/oumi/launcher/clouds/local_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/local_cloud.py | Apache-2.0 |
def get_cluster(self, name) -> Optional[BaseCluster]:
"""Gets the cluster with the specified name, or None if not found."""
clusters = self.list_clusters()
for cluster in clusters:
if cluster.name() == name:
return cluster
return None | Gets the cluster with the specified name, or None if not found. | get_cluster | python | oumi-ai/oumi | src/oumi/launcher/clouds/local_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/local_cloud.py | Apache-2.0 |
def __init__(self):
"""Initializes a new instance of the PolarisCloud class."""
# A mapping from user names to Polaris Clients.
self._clients = {}
# A mapping from cluster names to Polaris Cluster instances.
self._clusters = {}
# Check if any users have open SSH tunnels ... | Initializes a new instance of the PolarisCloud class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clouds/polaris_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/polaris_cloud.py | Apache-2.0 |
def _parse_cluster_name(self, name: str) -> _ClusterInfo:
"""Parses the cluster name into queue and user components.
Args:
name: The name of the cluster.
Returns:
_ClusterInfo: The parsed cluster information.
"""
name_splits = name.split(".")
if ... | Parses the cluster name into queue and user components.
Args:
name: The name of the cluster.
Returns:
_ClusterInfo: The parsed cluster information.
| _parse_cluster_name | python | oumi-ai/oumi | src/oumi/launcher/clouds/polaris_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/polaris_cloud.py | Apache-2.0 |
def _get_or_create_client(self, user: str) -> PolarisClient:
"""Gets the client for the specified user, or creates one if it doesn't exist.
Args:
user: The user to get the client for.
Returns:
PolarisClient: The client instance.
"""
if user not in self._... | Gets the client for the specified user, or creates one if it doesn't exist.
Args:
user: The user to get the client for.
Returns:
PolarisClient: The client instance.
| _get_or_create_client | python | oumi-ai/oumi | src/oumi/launcher/clouds/polaris_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/polaris_cloud.py | Apache-2.0 |
def _get_or_create_cluster(self, name: str) -> PolarisCluster:
"""Gets the cluster with the specified name, or creates one if it doesn't exist.
Args:
name: The name of the cluster.
Returns:
PolarisCluster: The cluster instance.
"""
if name not in self._c... | Gets the cluster with the specified name, or creates one if it doesn't exist.
Args:
name: The name of the cluster.
Returns:
PolarisCluster: The cluster instance.
| _get_or_create_cluster | python | oumi-ai/oumi | src/oumi/launcher/clouds/polaris_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/polaris_cloud.py | Apache-2.0 |
def initialize_clusters(self, user) -> list[BaseCluster]:
"""Initializes clusters for the specified user for all Polaris queues.
Args:
user: The user to initialize clusters for.
Returns:
List[PolarisCluster]: The list of initialized clusters.
"""
cluster... | Initializes clusters for the specified user for all Polaris queues.
Args:
user: The user to initialize clusters for.
Returns:
List[PolarisCluster]: The list of initialized clusters.
| initialize_clusters | python | oumi-ai/oumi | src/oumi/launcher/clouds/polaris_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/polaris_cloud.py | Apache-2.0 |
def __init__(self, cloud_name: str):
"""Initializes a new instance of the SkyCloud class."""
self._cloud_name = cloud_name
self._sky_client: Optional[SkyClient] = None | Initializes a new instance of the SkyCloud class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clouds/sky_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/sky_cloud.py | Apache-2.0 |
def _get_clusters_by_class(self, cloud_class: type[T]) -> list[BaseCluster]:
"""Gets the appropriate clusters of type T."""
# Delay sky import: https://github.com/oumi-ai/oumi/issues/1605
import sky
return [
SkyCluster(cluster["name"], self._client)
for cluster i... | Gets the appropriate clusters of type T. | _get_clusters_by_class | python | oumi-ai/oumi | src/oumi/launcher/clouds/sky_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/sky_cloud.py | Apache-2.0 |
def list_clusters(self) -> list[BaseCluster]:
"""Lists the active clusters on this cloud."""
# Delay sky import: https://github.com/oumi-ai/oumi/issues/1605
import sky
if self._cloud_name == SkyClient.SupportedClouds.GCP.value:
return self._get_clusters_by_class(sky.clouds.G... | Lists the active clusters on this cloud. | list_clusters | python | oumi-ai/oumi | src/oumi/launcher/clouds/sky_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/sky_cloud.py | Apache-2.0 |
def __init__(self):
"""Initializes a new instance of the SlurmCloud class."""
# A mapping from cluster names to Slurm Cluster instances.
self._clusters = {}
# Initialize default connections.
self.initialize_clusters() | Initializes a new instance of the SlurmCloud class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clouds/slurm_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/slurm_cloud.py | Apache-2.0 |
def _get_or_create_cluster(self, name: str) -> SlurmCluster:
"""Gets the cluster with the specified name, or creates one if it doesn't exist.
Args:
name: The name of the cluster.
Returns:
SlurmCluster: The cluster instance.
"""
if name not in self._clust... | Gets the cluster with the specified name, or creates one if it doesn't exist.
Args:
name: The name of the cluster.
Returns:
SlurmCluster: The cluster instance.
| _get_or_create_cluster | python | oumi-ai/oumi | src/oumi/launcher/clouds/slurm_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/slurm_cloud.py | Apache-2.0 |
def initialize_clusters(self) -> list[BaseCluster]:
"""Initializes clusters for the specified user for all Slurm queues.
Returns:
List[SlurmCluster]: The list of initialized clusters.
"""
connections = SlurmCluster.get_slurm_connections()
clusters = []
for c ... | Initializes clusters for the specified user for all Slurm queues.
Returns:
List[SlurmCluster]: The list of initialized clusters.
| initialize_clusters | python | oumi-ai/oumi | src/oumi/launcher/clouds/slurm_cloud.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clouds/slurm_cloud.py | Apache-2.0 |
def _validate_job_config(job: JobConfig) -> None:
"""Validates the provided job configuration.
Args:
job: The job to validate.
"""
if not job.working_dir:
raise ValueError("Working directory must be provided for local jobs.")
if not job.run:
raise ValueError("Run script must... | Validates the provided job configuration.
Args:
job: The job to validate.
| _validate_job_config | python | oumi-ai/oumi | src/oumi/launcher/clusters/local_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/local_cluster.py | Apache-2.0 |
def __init__(self, name: str, client: LocalClient) -> None:
"""Initializes a new instance of the LocalCluster class."""
self._name = name
self._client = client | Initializes a new instance of the LocalCluster class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/local_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/local_cluster.py | Apache-2.0 |
def __eq__(self, other: Any) -> bool:
"""Checks if two LocalClusters are equal."""
if not isinstance(other, LocalCluster):
return False
return self.name() == other.name() | Checks if two LocalClusters are equal. | __eq__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/local_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/local_cluster.py | Apache-2.0 |
def get_job(self, job_id: str) -> Optional[JobStatus]:
"""Gets the jobs on this cluster if it exists, else returns None."""
for job in self.get_jobs():
if job.id == job_id:
return job
return None | Gets the jobs on this cluster if it exists, else returns None. | get_job | python | oumi-ai/oumi | src/oumi/launcher/clusters/local_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/local_cluster.py | Apache-2.0 |
def get_jobs(self) -> list[JobStatus]:
"""Lists the jobs on this cluster."""
jobs = self._client.list_jobs()
for job in jobs:
job.cluster = self._name
return jobs | Lists the jobs on this cluster. | get_jobs | python | oumi-ai/oumi | src/oumi/launcher/clusters/local_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/local_cluster.py | Apache-2.0 |
def cancel_job(self, job_id: str) -> JobStatus:
"""Cancels the specified job on this cluster."""
self._client.cancel(job_id)
job = self.get_job(job_id)
if job is None:
raise RuntimeError(f"Job {job_id} not found.")
return job | Cancels the specified job on this cluster. | cancel_job | python | oumi-ai/oumi | src/oumi/launcher/clusters/local_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/local_cluster.py | Apache-2.0 |
def run_job(self, job: JobConfig) -> JobStatus:
"""Runs the specified job on this cluster.
Args:
job: The job to run.
Returns:
The job status.
"""
job_copy = deepcopy(job)
_validate_job_config(job_copy)
if not job_copy.name:
j... | Runs the specified job on this cluster.
Args:
job: The job to run.
Returns:
The job status.
| run_job | python | oumi-ai/oumi | src/oumi/launcher/clusters/local_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/local_cluster.py | Apache-2.0 |
def _last_pbs_line(script: list[str]) -> int:
"""Finds the last PBS instruction line in the script.
Args:
script: The lines of the script.
Returns:
The index of the last PBS instruction line. -1 if not found.
"""
return reduce(
lambda acc, val: val[0] if val[1].startswith("... | Finds the last PBS instruction line in the script.
Args:
script: The lines of the script.
Returns:
The index of the last PBS instruction line. -1 if not found.
| _last_pbs_line | python | oumi-ai/oumi | src/oumi/launcher/clusters/polaris_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/polaris_cluster.py | Apache-2.0 |
def _get_logging_directories(script: str) -> list[str]:
"""Gets the logging directories from the script.
Parses the provided script for commands starting with `#PBS -o`, `#PBS -e`,
`#PBS -oe`, `#PBS -eo`, or `#PBS -doe`.
Args:
script: The script to extract logging directories from.
Return... | Gets the logging directories from the script.
Parses the provided script for commands starting with `#PBS -o`, `#PBS -e`,
`#PBS -oe`, `#PBS -eo`, or `#PBS -doe`.
Args:
script: The script to extract logging directories from.
Returns:
A list of logging directories.
| _get_logging_directories | python | oumi-ai/oumi | src/oumi/launcher/clusters/polaris_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/polaris_cluster.py | Apache-2.0 |
def _create_job_script(job: JobConfig) -> str:
"""Creates a job script for the specified job.
Args:
job: The job to create a script for.
Returns:
The script as a string.
"""
setup_lines = [] if not job.setup else job.setup.strip().split("\n")
run_lines = job.run.strip().split("... | Creates a job script for the specified job.
Args:
job: The job to create a script for.
Returns:
The script as a string.
| _create_job_script | python | oumi-ai/oumi | src/oumi/launcher/clusters/polaris_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/polaris_cluster.py | Apache-2.0 |
def __init__(self, name: str, client: PolarisClient) -> None:
"""Initializes a new instance of the PolarisCluster class."""
self._name = name
self._queue = self._get_queue_from_name()
self._client = client | Initializes a new instance of the PolarisCluster class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/polaris_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/polaris_cluster.py | Apache-2.0 |
def __eq__(self, other: Any) -> bool:
"""Checks if two PolarisClusters are equal."""
if not isinstance(other, PolarisCluster):
return False
return self.name() == other.name() | Checks if two PolarisClusters are equal. | __eq__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/polaris_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/polaris_cluster.py | Apache-2.0 |
def _get_queue_from_name(self) -> PolarisClient.SupportedQueues:
"""Gets the queue from the provided name."""
splits = self._name.split(".")
if len(splits) < 2:
raise ValueError(
f"Invalid queue name: {self._name}. "
"A queue name should be of the form... | Gets the queue from the provided name. | _get_queue_from_name | python | oumi-ai/oumi | src/oumi/launcher/clusters/polaris_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/polaris_cluster.py | Apache-2.0 |
def __init__(self, name: str, client: SkyClient) -> None:
"""Initializes a new instance of the SkyCluster class."""
# Delay sky import: https://github.com/oumi-ai/oumi/issues/1605
import sky.exceptions
self._sky_exceptions = sky.exceptions
self._name = name
self._client ... | Initializes a new instance of the SkyCluster class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/sky_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/sky_cluster.py | Apache-2.0 |
def __eq__(self, other: Any) -> bool:
"""Checks if two SkyClusters are equal."""
if not isinstance(other, SkyCluster):
return False
return self.name() == other.name() | Checks if two SkyClusters are equal. | __eq__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/sky_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/sky_cluster.py | Apache-2.0 |
def _last_sbatch_line(script: list[str]) -> int:
"""Finds the last SBATCH instruction line in the script.
Args:
script: The lines of the script.
Returns:
The index of the last SBATCH instruction line. -1 if not found.
"""
return reduce(
lambda acc, val: val[0] if val[1].sta... | Finds the last SBATCH instruction line in the script.
Args:
script: The lines of the script.
Returns:
The index of the last SBATCH instruction line. -1 if not found.
| _last_sbatch_line | python | oumi-ai/oumi | src/oumi/launcher/clusters/slurm_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/slurm_cluster.py | Apache-2.0 |
def __init__(self, name: str, client: SlurmClient) -> None:
"""Initializes a new instance of the SlurmCluster class."""
self._client = client
self._connection = self.parse_cluster_name(name) | Initializes a new instance of the SlurmCluster class. | __init__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/slurm_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/slurm_cluster.py | Apache-2.0 |
def __eq__(self, other: Any) -> bool:
"""Checks if two SlurmClusters are equal."""
if not isinstance(other, SlurmCluster):
return False
return self.name() == other.name() | Checks if two SlurmClusters are equal. | __eq__ | python | oumi-ai/oumi | src/oumi/launcher/clusters/slurm_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/slurm_cluster.py | Apache-2.0 |
def parse_cluster_name(name: str) -> ConnectionInfo:
"""Parses the cluster name into queue and user components.
Args:
name: The name of the cluster.
Returns:
_ConnectionInfo: The parsed cluster information.
"""
# Expected format: <user>@<hostname>
... | Parses the cluster name into queue and user components.
Args:
name: The name of the cluster.
Returns:
_ConnectionInfo: The parsed cluster information.
| parse_cluster_name | python | oumi-ai/oumi | src/oumi/launcher/clusters/slurm_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/slurm_cluster.py | Apache-2.0 |
def get_slurm_connections() -> list[ConnectionInfo]:
"""Gets Slurm connections from the OUMI_SLURM_CONNECTIONS env variable."""
connections_str = os.getenv(_OUMI_SLURM_CONNECTIONS, "")
if not connections_str:
return []
valid_connections = []
for connection in [h.stri... | Gets Slurm connections from the OUMI_SLURM_CONNECTIONS env variable. | get_slurm_connections | python | oumi-ai/oumi | src/oumi/launcher/clusters/slurm_cluster.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/launcher/clusters/slurm_cluster.py | Apache-2.0 |
def __init__(
self,
image_width: int,
image_height: int,
*,
in_channels: int = 3,
output_dim: int = 10,
kernel_size: int = 5,
):
"""Initialize the ConvNet for image classification.
Args:
image_width: Width of input images in pixels... | Initialize the ConvNet for image classification.
Args:
image_width: Width of input images in pixels.
image_height: Height of input images in pixels.
in_channels: The number of input channels e.g., 3 for RGB, 1 for greyscale.
output_dim: The output dimension i.e.,... | __init__ | python | oumi-ai/oumi | src/oumi/models/cnn_classifier.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/cnn_classifier.py | Apache-2.0 |
def __init__(
self, input_dim: int = 768, hidden_dim: int = 128, output_dim: int = 10
):
"""Initialize the MLPEncoder.
Args:
input_dim (int): The input dimension.
hidden_dim (int): The hidden dimension.
output_dim (int): The output dimension.
"""
... | Initialize the MLPEncoder.
Args:
input_dim (int): The input dimension.
hidden_dim (int): The hidden dimension.
output_dim (int): The output dimension.
| __init__ | python | oumi-ai/oumi | src/oumi/models/mlp.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/mlp.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor,
labels: Optional[torch.LongTensor] = None,
**kwargs,
) -> dict[str, torch.Tensor]:
"""Forward pass of the MLP model.
Args:
input_ids (torch.LongTensor): The input tensor of shape
(batch_size,... | Forward pass of the MLP model.
Args:
input_ids (torch.LongTensor): The input tensor of shape
(batch_size, sequence_length).
labels (torch.LongTensor, optional): The target labels tensor
of shape (batch_size,).
**kwargs: Additional keyword argu... | forward | python | oumi-ai/oumi | src/oumi/models/mlp.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/mlp.py | Apache-2.0 |
def select_best_resolution(original_size, possible_resolutions):
"""Selects the best resolution from a list of possible resolutions based on the original size.
Args:
original_size (tuple): The original size of the image in the format (width, height).
possible_resolutions (list): A list of possi... | Selects the best resolution from a list of possible resolutions based on the original size.
Args:
original_size (tuple): The original size of the image in the format (width, height).
possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...... | select_best_resolution | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/mm_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/mm_utils.py | Apache-2.0 |
def resize_and_pad_image(image, target_resolution):
"""Resize and pad an image to a target resolution while maintaining aspect ratio.
Args:
image (PIL.Image.Image): The input image.
target_resolution (tuple): The target resolution (width, height) of the image.
Returns:
PIL.Image.Im... | Resize and pad an image to a target resolution while maintaining aspect ratio.
Args:
image (PIL.Image.Image): The input image.
target_resolution (tuple): The target resolution (width, height) of the image.
Returns:
PIL.Image.Image: The resized and padded image.
| resize_and_pad_image | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/mm_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/mm_utils.py | Apache-2.0 |
def divide_to_patches(image, patch_size):
"""Divides an image into patches of a specified size.
Args:
image (PIL.Image.Image): The input image.
patch_size (int): The size of each patch.
Returns:
list: A list of PIL.Image.Image objects representing the patches.
"""
patches =... | Divides an image into patches of a specified size.
Args:
image (PIL.Image.Image): The input image.
patch_size (int): The size of each patch.
Returns:
list: A list of PIL.Image.Image objects representing the patches.
| divide_to_patches | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/mm_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/mm_utils.py | Apache-2.0 |
def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
"""Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
Args:
image_size (tuple): The size of the input image in the format (width, height).
grid_pinpoints (str): A string repre... | Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
Args:
image_size (tuple): The size of the input image in the format (width, height).
grid_pinpoints (str): A string representation of a list of possible resolutions.
patch_size (int): The size ... | get_anyres_image_grid_shape | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/mm_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/mm_utils.py | Apache-2.0 |
def process_anyres_image(image, processor, grid_pinpoints):
"""Process an image with variable resolutions.
Args:
image (PIL.Image.Image): The input image to be processed.
processor: The image processor object.
grid_pinpoints (str): A string representation of a list of possible resolutio... | Process an image with variable resolutions.
Args:
image (PIL.Image.Image): The input image to be processed.
processor: The image processor object.
grid_pinpoints (str): A string representation of a list of possible resolutions.
Returns:
torch.Tensor: A tensor containing the pro... | process_anyres_image | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/mm_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/mm_utils.py | Apache-2.0 |
def unpad_image(tensor, original_size):
"""Unpads a PyTorch tensor of a padded and resized image.
Args:
tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
original_size (tuple): The original size of the image (height, width).
Returns:
torch.Tensor: The unpadded image tenso... | Unpads a PyTorch tensor of a padded and resized image.
Args:
tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
original_size (tuple): The original size of the image (height, width).
Returns:
torch.Tensor: The unpadded image tensor.
| unpad_image | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/cambrian_arch.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/cambrian_arch.py | Apache-2.0 |
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
"""grid_size: int of the grid height and width
return:
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
"""
grid_h = np.arange(grid_size, dtype=np.float32)
grid_w = np.arang... | grid_size: int of the grid height and width
return:
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
| get_2d_sincos_pos_embed | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/vision_sampler.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/vision_sampler.py | Apache-2.0 |
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
"""embed_dim: output dimension for each position
pos: a list of positions to be encoded: size (M,)
out: (M, D)
"""
assert embed_dim % 2 == 0
omega = np.arange(embed_dim // 2, dtype=np.float32)
omega /= embed_dim / 2.0
omega = 1.0 / 1... | embed_dim: output dimension for each position
pos: a list of positions to be encoded: size (M,)
out: (M, D)
| get_1d_sincos_pos_embed_from_grid | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/vision_sampler.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/vision_sampler.py | Apache-2.0 |
def __init__(self, vision_tower, args, delay_load=False):
"""Initialize the CLIPConvNextTower.
Args:
vision_tower (str): The name of the vision tower model in the format "clip-convnext-resXXX-interpYYY".
args (argparse.Namespace): The arguments parsed from the command line.
... | Initialize the CLIPConvNextTower.
Args:
vision_tower (str): The name of the vision tower model in the format "clip-convnext-resXXX-interpYYY".
args (argparse.Namespace): The arguments parsed from the command line.
delay_load (bool, optional): Whether to delay loading the mod... | __init__ | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | Apache-2.0 |
def interpolate(self, image_forward_outs):
"""Interpolate the image features to the desired number of patches.
Args:
image_forward_outs (torch.Tensor): The output features from the vision tower.
Returns:
torch.Tensor: The interpolated image features.
"""
... | Interpolate the image features to the desired number of patches.
Args:
image_forward_outs (torch.Tensor): The output features from the vision tower.
Returns:
torch.Tensor: The interpolated image features.
| interpolate | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | Apache-2.0 |
def _forward(self, images):
"""Perform the forward pass of the CLIPConvNextTower.
Args:
images (torch.Tensor): The input images.
Returns:
torch.Tensor: The output features from the vision tower after interpolation.
"""
with torch.set_grad_enabled(self.un... | Perform the forward pass of the CLIPConvNextTower.
Args:
images (torch.Tensor): The input images.
Returns:
torch.Tensor: The output features from the vision tower after interpolation.
| _forward | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | Apache-2.0 |
def num_patches_per_side(self):
"""Get the number of patches per side.
Returns:
int: The number of patches per side.
"""
if self._interp_size is None:
return self._image_size // self._reduction
else:
return int(self._interp_size**0.5) | Get the number of patches per side.
Returns:
int: The number of patches per side.
| num_patches_per_side | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | Apache-2.0 |
def num_patches(self):
"""Get the total number of patches.
Default: 256
Returns:
int: The total number of patches.
"""
if self._interp_size is None:
return (self._image_size // self._reduction) ** 2
else:
return self._interp_size | Get the total number of patches.
Default: 256
Returns:
int: The total number of patches.
| num_patches | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/multimodal_encoder/clip_convnext_encoder.py | Apache-2.0 |
def load_vision_model(vision_tower_name: str, args, **kwargs):
"""Load a vision tower model based on the model name
Args:
vision_tower_name (str): The name of the vision tower model.
args (argparse.Namespace): The arguments parsed from the command line.
kwargs: Additional keyword argume... | Load a vision tower model based on the model name
Args:
vision_tower_name (str): The name of the vision tower model.
args (argparse.Namespace): The arguments parsed from the command line.
kwargs: Additional keyword arguments.
| load_vision_model | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/multimodal_encoder/load.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/multimodal_encoder/load.py | Apache-2.0 |
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Args:
x: (B, L, encoder_hidden_size) tensor from the visual backbone (CLIP visual encoder), including cls token.
"""
if self.pos_emb is not None:
x = x + self.pos_emb
dtype = x.dtype
# x = self._forward(x... | Args:
x: (B, L, encoder_hidden_size) tensor from the visual backbone (CLIP visual encoder), including cls token.
| forward | python | oumi-ai/oumi | src/oumi/models/experimental/cambrian/model/multimodal_projector/projectors.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/experimental/cambrian/model/multimodal_projector/projectors.py | Apache-2.0 |
def extract_local(value, rank, world_size, device, dim=1):
"""Extract the local value from the global value."""
value_chunks = value.chunk(2 * world_size, dim=dim)
local_value = torch.cat(
[value_chunks[rank], value_chunks[2 * world_size - rank - 1]], dim=dim
)
return local_value.to(device) | Extract the local value from the global value. | extract_local | python | oumi-ai/oumi | src/oumi/models/layers/ring_attention.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/ring_attention.py | Apache-2.0 |
def prepare_zigzag_ring_attn_inputs(
input_ids, position_ids, target_ids, rank, world_size, device
):
"""Prepare the inputs for zigzag ring attention."""
local_input_ids = extract_local(
input_ids,
rank,
world_size,
device,
)
local_position_ids = extract_local(
... | Prepare the inputs for zigzag ring attention. | prepare_zigzag_ring_attn_inputs | python | oumi-ai/oumi | src/oumi/models/layers/ring_attention.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/ring_attention.py | Apache-2.0 |
def apply_zigzag_ring_attn_monkey_patch_llama():
"""Apply the zigzag ring attention monkey patch to llama."""
if not is_zigzag_ring_flash_attn_available():
raise RuntimeError(
"Ring attention is not available. "
"Install Flash Attention: `pip install flash-attn --no-build-isolati... | Apply the zigzag ring attention monkey patch to llama. | apply_zigzag_ring_attn_monkey_patch_llama | python | oumi-ai/oumi | src/oumi/models/layers/ring_attention.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/ring_attention.py | Apache-2.0 |
def get_default_args(func) -> dict[str, Any]:
"""Get the default arguments of a function."""
spec = inspect.getfullargspec(func)
defaults = spec.defaults if spec.defaults is not None else ()
padded_defaults = (None,) * (len(spec.args) - len(defaults)) + defaults
args: dict[str, Any] = dict(zip(spec.... | Get the default arguments of a function. | get_default_args | python | oumi-ai/oumi | src/oumi/models/layers/zigzag_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/zigzag_utils.py | Apache-2.0 |
def update_out_and_lse(
out: Optional[torch.Tensor],
lse: Optional[torch.Tensor],
block_out: torch.Tensor,
block_lse: torch.Tensor,
slice_=None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Update the output and log-sum-exp of the attention."""
if out is None:
if slice_ is not None:
... | Update the output and log-sum-exp of the attention. | update_out_and_lse | python | oumi-ai/oumi | src/oumi/models/layers/zigzag_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/zigzag_utils.py | Apache-2.0 |
def flatten_varlen_lse(lse, cu_seqlens):
"""Flatten the log-sum-exp of the attention."""
new_lse = []
for i in range(len(cu_seqlens) - 1):
start, end = cu_seqlens[i], cu_seqlens[i + 1]
new_lse.append(lse[i, :, : end - start])
return torch.cat(new_lse, dim=1) | Flatten the log-sum-exp of the attention. | flatten_varlen_lse | python | oumi-ai/oumi | src/oumi/models/layers/zigzag_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/zigzag_utils.py | Apache-2.0 |
def unflatten_varlen_lse(lse, cu_seqlens, max_seqlen: int):
"""Unflatten the log-sum-exp of the attention."""
num_seq = len(cu_seqlens) - 1
num_head = lse.shape[-2]
new_lse = torch.empty(
(num_seq, max_seqlen, num_head, 1), dtype=torch.float32, device=lse.device
)
for i in range(num_seq)... | Unflatten the log-sum-exp of the attention. | unflatten_varlen_lse | python | oumi-ai/oumi | src/oumi/models/layers/zigzag_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/zigzag_utils.py | Apache-2.0 |
def wait(self):
"""Wait for the operations to complete."""
if self._reqs is None:
raise RuntimeError("wait called before commit")
for req in self._reqs:
req.wait()
self._reqs = None
self._ops = [] | Wait for the operations to complete. | wait | python | oumi-ai/oumi | src/oumi/models/layers/zigzag_utils.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/models/layers/zigzag_utils.py | Apache-2.0 |
def _get_device_flops(device_name: str, dtype: torch.dtype) -> float:
"""Returns peak TFLOPS for the given device name and dtype."""
if device_name not in _DEVICE_SPECS:
raise NotImplementedError(
f"Unknown device name for getting hardware flops: {device_name}"
)
specs = _DEVICE... | Returns peak TFLOPS for the given device name and dtype. | _get_device_flops | python | oumi-ai/oumi | src/oumi/performance/mfu.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/mfu.py | Apache-2.0 |
def _get_model_flops_per_token(
num_params: int,
num_layers: Optional[int] = None,
num_attention_heads: Optional[int] = None,
attention_head_size: Optional[int] = None,
sequence_length: Optional[int] = None,
add_rematerialization: bool = False,
) -> int:
"""Returns the number of FLOPs per to... | Returns the number of FLOPs per token for the given model configuration. | _get_model_flops_per_token | python | oumi-ai/oumi | src/oumi/performance/mfu.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/mfu.py | Apache-2.0 |
def calculate_mfu_from_model_flops_per_second(
device_name: str,
num_devices: int,
dtype: torch.dtype,
model_flops_per_second_on_all_devices: float,
) -> float:
"""Returns the number of MFU for the given model flops per second."""
if num_devices <= 0:
raise ValueError(f"Must have a posit... | Returns the number of MFU for the given model flops per second. | calculate_mfu_from_model_flops_per_second | python | oumi-ai/oumi | src/oumi/performance/mfu.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/mfu.py | Apache-2.0 |
def calculate_mfu(
device_name: str,
num_devices: int,
dtype: torch.dtype,
num_params: int,
num_tokens: int,
delta_time_seconds: float,
num_layers: Optional[int] = None,
num_attention_heads: Optional[int] = None,
attention_head_size: Optional[int] = None,
sequence_length: Optiona... | Returns the number of MFU for the given model configuration. | calculate_mfu | python | oumi-ai/oumi | src/oumi/performance/mfu.py | https://github.com/oumi-ai/oumi/blob/master/src/oumi/performance/mfu.py | Apache-2.0 |
def __init__(self, name: str, measurements: Optional[list[float]] = None):
"""Initializes a TimerContext object.
Args:
name: The name of the timer.
measurements: A list to store the timing measurements.
"""
self.name = name
self.measurements = measurement... | Initializes a TimerContext object.
Args:
name: The name of the timer.
measurements: A list to store the timing measurements.
| __init__ | 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 __exit__(self, *exc) -> bool:
"""Stops the timer and records the elapsed time."""
if self.start_time is not None:
if self.cuda_synchronize:
torch.cuda.synchronize()
elapsed_time = time.perf_counter() - self.start_time
self.measurements.append(elaps... | Stops the timer and records the elapsed time. | __exit__ | 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 __init__(self, name: str, measurements: Optional[list[float]] = None):
"""Initializes a CudaTimerContext object.
Args:
name: The name of the timer.
measurements: A list to store the timing measurements.
"""
self.name = name
self.measurements = measure... | Initializes a CudaTimerContext object.
Args:
name: The name of the timer.
measurements: A list to store the timing measurements.
| __init__ | 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 __exit__(self, *exc) -> bool:
"""Stops the CUDA timer and records the elapsed time."""
if not torch.cuda.is_available():
LOGGER.debug("CUDA is not available. Skipping CUDA benchmark.")
return False
assert self.end_event is not None
self.end_event.record()
... | Stops the CUDA timer and records the elapsed time. | __exit__ | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.