id
int64
1
6.07M
name
stringlengths
1
295
code
stringlengths
12
426k
language
stringclasses
1 value
source_file
stringlengths
5
202
start_line
int64
1
158k
end_line
int64
1
158k
repo
dict
4,001
__init__
def __init__(self, api: Api, config: Dict[str, Any]): """Initialize a launch agent. Arguments: api: Api object to use for making requests to the backend. config: Config dictionary for the agent. """ self._entity = config["entity"] self._project = config["project"] self._api = api self._base_url = self._api.settings().get("base_url") self._ticks = 0 self._jobs: Dict[int, JobAndRunStatus] = {} self._jobs_lock = threading.Lock() self._jobs_event = Event() self._jobs_event.set() self._cwd = os.getcwd() self._namespace = runid.generate_id() self._access = _convert_access("project") self._max_jobs = _max_from_config(config, "max_jobs") self._max_schedulers = _max_from_config(config, "max_schedulers") self._pool = ThreadPool( processes=int(min(MAX_THREADS, self._max_jobs + self._max_schedulers)), initargs=(self._jobs, self._jobs_lock), ) self.default_config: Dict[str, Any] = config # serverside creation self.gorilla_supports_agents = ( self._api.launch_agent_introspection() is not None ) self._gorilla_supports_fail_run_queue_items = ( self._api.fail_run_queue_item_introspection() ) self._queues = config.get("queues", ["default"]) create_response = self._api.create_launch_agent( self._entity, self._project, self._queues, self.gorilla_supports_agents, ) self._id = create_response["launchAgentId"] self._name = "" # hacky: want to display this to the user but we don't get it back from gql until polling starts. fix later if self._api.entity_is_team(self._entity): wandb.termwarn( f"{LOG_PREFIX}Agent is running on team entity ({self._entity}). Members of this team will be able to run code on this device." )
python
wandb/sdk/launch/agent/agent.py
127
174
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,002
fail_run_queue_item
def fail_run_queue_item(self, run_queue_item_id: str) -> None: if self._gorilla_supports_fail_run_queue_items: self._api.fail_run_queue_item(run_queue_item_id)
python
wandb/sdk/launch/agent/agent.py
176
178
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,003
thread_ids
def thread_ids(self) -> List[int]: """Returns a list of keys running thread ids for the agent.""" with self._jobs_lock: return list(self._jobs.keys())
python
wandb/sdk/launch/agent/agent.py
181
184
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,004
num_running_schedulers
def num_running_schedulers(self) -> int: """Return just the number of schedulers.""" with self._jobs_lock: return len([x for x in self._jobs if self._jobs[x].is_scheduler])
python
wandb/sdk/launch/agent/agent.py
187
190
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,005
num_running_jobs
def num_running_jobs(self) -> int: """Return the number of jobs not including schedulers.""" with self._jobs_lock: return len([x for x in self._jobs if not self._jobs[x].is_scheduler])
python
wandb/sdk/launch/agent/agent.py
193
196
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,006
pop_from_queue
def pop_from_queue(self, queue: str) -> Any: """Pops an item off the runqueue to run as a job. Arguments: queue: Queue to pop from. Returns: Item popped off the queue. Raises: Exception: if there is an error popping from the queue. """ try: ups = self._api.pop_from_run_queue( queue, entity=self._entity, project=self._project, agent_id=self._id, ) except Exception as e: print("Exception:", e) return None return ups
python
wandb/sdk/launch/agent/agent.py
198
220
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,007
print_status
def print_status(self) -> None: """Prints the current status of the agent.""" output_str = "agent " if self._name: output_str += f"{self._name} " if self.num_running_jobs < self._max_jobs: output_str += "polling on " if self._project != LAUNCH_DEFAULT_PROJECT: output_str += f"project {self._project}, " output_str += f"queues {','.join(self._queues)}, " output_str += ( f"running {self.num_running_jobs} out of a maximum of {self._max_jobs} jobs" ) wandb.termlog(f"{LOG_PREFIX}{output_str}") if self.num_running_jobs > 0: output_str += f": {','.join(str(job_id) for job_id in self.thread_ids)}" _logger.info(output_str)
python
wandb/sdk/launch/agent/agent.py
222
240
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,008
update_status
def update_status(self, status: str) -> None: """Update the status of the agent. Arguments: status: Status to update the agent to. """ update_ret = self._api.update_launch_agent_status( self._id, status, self.gorilla_supports_agents ) if not update_ret["success"]: wandb.termerror(f"{LOG_PREFIX}Failed to update agent status to {status}")
python
wandb/sdk/launch/agent/agent.py
242
252
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,009
finish_thread_id
def finish_thread_id(self, thread_id: int) -> None: """Removes the job from our list for now.""" job_and_run_status = self._jobs[thread_id] if not job_and_run_status.run_id or not job_and_run_status.project: self.fail_run_queue_item(job_and_run_status.run_queue_item_id) else: run_info = None # sweep runs exist but have no info before they are started # so run_info returned will be None # normal runs just throw a comm error try: run_info = self._api.get_run_info( self._entity, job_and_run_status.project, job_and_run_status.run_id ) except CommError: pass if run_info is None: self.fail_run_queue_item(job_and_run_status.run_queue_item_id) # TODO: keep logs or something for the finished jobs with self._jobs_lock: del self._jobs[thread_id] # update status back to polling if no jobs are running if len(self.thread_ids) == 0: self.update_status(AGENT_POLLING)
python
wandb/sdk/launch/agent/agent.py
254
280
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,010
_update_finished
def _update_finished(self, thread_id: int) -> None: """Check our status enum.""" with self._jobs_lock: job = self._jobs[thread_id] if job.job_completed: self.finish_thread_id(thread_id)
python
wandb/sdk/launch/agent/agent.py
282
287
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,011
run_job
def run_job(self, job: Dict[str, Any]) -> None: """Set up project and run the job. Arguments: job: Job to run. """ _msg = f"{LOG_PREFIX}Launch agent received job:\n{pprint.pformat(job)}\n" wandb.termlog(_msg) _logger.info(_msg) # update agent status self.update_status(AGENT_RUNNING) # parse job _logger.info("Parsing launch spec") launch_spec = job["runSpec"] if launch_spec.get("overrides") and isinstance( launch_spec["overrides"].get("args"), list ): launch_spec["overrides"]["args"] = util._user_args_to_dict( launch_spec["overrides"].get("args", []) ) self._pool.apply_async( self.thread_run_job, ( launch_spec, job, self.default_config, self._api, ), )
python
wandb/sdk/launch/agent/agent.py
289
319
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,012
loop
def loop(self) -> None: """Loop infinitely to poll for jobs and run them. Raises: KeyboardInterrupt: if the agent is requested to stop. """ self.print_status() try: while True: self._ticks += 1 agent_response = self._api.get_launch_agent( self._id, self.gorilla_supports_agents ) self._name = agent_response["name"] # hack: first time we get name if agent_response["stopPolling"]: # shutdown process and all jobs if requested from ui raise KeyboardInterrupt if self.num_running_jobs < self._max_jobs: # only check for new jobs if we're not at max for queue in self._queues: job = self.pop_from_queue(queue) if job: if _job_is_scheduler(job.get("runSpec")): # If job is a scheduler, and we are already at the cap, ignore, # don't ack, and it will be pushed back onto the queue in 1 min if self.num_running_schedulers >= self._max_schedulers: wandb.termwarn( f"{LOG_PREFIX}Agent already running the maximum number " f"of sweep schedulers: {self._max_schedulers}. To set " "this value use `max_schedulers` key in the agent config" ) continue try: self.run_job(job) except Exception as e: wandb.termerror( f"{LOG_PREFIX}Error running job: {traceback.format_exc()}" ) wandb._sentry.exception(e) self.fail_run_queue_item(job["runQueueItemId"]) for thread_id in self.thread_ids: self._update_finished(thread_id) if self._ticks % 2 == 0: if len(self.thread_ids) == 0: self.update_status(AGENT_POLLING) else: self.update_status(AGENT_RUNNING) self.print_status() if ( self.num_running_jobs == self._max_jobs or self.num_running_schedulers == 0 ): # all threads busy or no schedulers running time.sleep(AGENT_POLLING_INTERVAL) else: time.sleep(ACTIVE_SWEEP_POLLING_INTERVAL) except KeyboardInterrupt: self._jobs_event.clear() self.update_status(AGENT_KILLED) wandb.termlog(f"{LOG_PREFIX}Shutting down, active jobs:") self.print_status() self._pool.close() self._pool.join()
python
wandb/sdk/launch/agent/agent.py
321
387
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,013
thread_run_job
def thread_run_job( self, launch_spec: Dict[str, Any], job: Dict[str, Any], default_config: Dict[str, Any], api: Api, ) -> None: thread_id = threading.current_thread().ident assert thread_id is not None try: self._thread_run_job(launch_spec, job, default_config, api, thread_id) except LaunchDockerError as e: wandb.termerror( f"{LOG_PREFIX}agent {self._name} encountered an issue while starting Docker, see above output for details." ) self.finish_thread_id(thread_id) wandb._sentry.exception(e) except Exception as e: wandb.termerror(f"{LOG_PREFIX}Error running job: {traceback.format_exc()}") self.finish_thread_id(thread_id) wandb._sentry.exception(e)
python
wandb/sdk/launch/agent/agent.py
390
410
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,014
_thread_run_job
def _thread_run_job( self, launch_spec: Dict[str, Any], job: Dict[str, Any], default_config: Dict[str, Any], api: Api, thread_id: int, ) -> None: job_tracker = JobAndRunStatus(job["runQueueItemId"]) with self._jobs_lock: self._jobs[thread_id] = job_tracker project = create_project_from_spec(launch_spec, api) job_tracker.update_run_info(project) _logger.info("Fetching and validating project...") project = fetch_and_validate_project(project, api) _logger.info("Fetching resource...") resource = launch_spec.get("resource") or "local-container" backend_config: Dict[str, Any] = { PROJECT_SYNCHRONOUS: False, # agent always runs async } _logger.info("Loading backend") override_build_config = launch_spec.get("builder") build_config, registry_config = construct_builder_args( default_config, override_build_config ) environment = loader.environment_from_config( default_config.get("environment", {}) ) registry = loader.registry_from_config(registry_config, environment) builder = loader.builder_from_config(build_config, environment, registry) backend = loader.runner_from_config(resource, api, backend_config, environment) _logger.info("Backend loaded...") api.ack_run_queue_item(job["runQueueItemId"], project.run_id) run = backend.run(project, builder) if _job_is_scheduler(launch_spec): with self._jobs_lock: self._jobs[thread_id].is_scheduler = True wandb.termlog( f"{LOG_PREFIX}Preparing to run sweep scheduler " f"({self.num_running_schedulers}/{self._max_schedulers})" ) if not run: with self._jobs_lock: job_tracker.failed_to_start = True return with self._jobs_lock: job_tracker.run = run while self._jobs_event.is_set(): if self._check_run_finished(job_tracker): return time.sleep(AGENT_POLLING_INTERVAL) # temp: for local, kill all jobs. we don't yet have good handling for different # types of runners in general if isinstance(run, LocalSubmittedRun): run.command_proc.kill()
python
wandb/sdk/launch/agent/agent.py
412
470
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,015
_check_run_finished
def _check_run_finished(self, job_tracker: JobAndRunStatus) -> bool: if job_tracker.completed: return True # the run can be done before the run has started # but can also be none if the run failed to start # so if there is no run, either the run hasn't started yet # or it has failed if job_tracker.run is None: if job_tracker.failed_to_start: return True return False known_error = False try: run = job_tracker.run status = run.get_status().state if status in ["stopped", "failed", "finished"]: if job_tracker.is_scheduler: wandb.termlog(f"{LOG_PREFIX}Scheduler finished with ID: {run.id}") else: wandb.termlog(f"{LOG_PREFIX}Job finished with ID: {run.id}") with self._jobs_lock: job_tracker.completed = True return True return False except LaunchError as e: wandb.termerror( f"{LOG_PREFIX}Terminating job {run.id} because it failed to start: {str(e)}" ) known_error = True with self._jobs_lock: job_tracker.failed_to_start = True # TODO: make get_status robust to errors for each runner, and handle them except Exception as e: wandb.termerror(f"{LOG_PREFIX}Error getting status for job {run.id}") wandb.termerror(traceback.format_exc()) _logger.info("---") _logger.info("Caught exception while getting status.") _logger.info(f"Job ID: {run.id}") _logger.info(traceback.format_exc()) _logger.info("---") wandb._sentry.exception(e) return known_error
python
wandb/sdk/launch/agent/agent.py
472
515
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,016
__init__
def __init__( self, *args: Any, num_workers: int = 8, heartbeat_queue_timeout: float = 1.0, heartbeat_queue_sleep: float = 1.0, **kwargs: Any, ): super().__init__(*args, **kwargs) self._num_workers: int = num_workers # Thread will pop items off the Sweeps RunQueue using AgentHeartbeat # and put them in this internal queue, which will be used to populate # the Launch RunQueue self._heartbeat_queue: "queue.Queue[SweepRun]" = queue.Queue() self._heartbeat_queue_timeout: float = heartbeat_queue_timeout self._heartbeat_queue_sleep: float = heartbeat_queue_sleep
python
wandb/sdk/launch/sweeps/scheduler_sweep.py
27
42
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,017
_start
def _start(self) -> None: for worker_id in range(self._num_workers): _logger.debug(f"{LOG_PREFIX}Starting AgentHeartbeat worker {worker_id}\n") agent_config = self._api.register_agent( f"{socket.gethostname()}-{worker_id}", # host sweep_id=self._sweep_id, project_name=self._project, entity=self._entity, ) self._workers[worker_id] = _Worker( agent_config=agent_config, agent_id=agent_config["id"], )
python
wandb/sdk/launch/sweeps/scheduler_sweep.py
44
56
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,018
_get_sweep_commands
def _get_sweep_commands(self, worker_id: int) -> List[Dict[str, Any]]: # AgentHeartbeat wants a Dict of runs which are running or queued _run_states: Dict[str, bool] = {} for run_id, run in self._yield_runs(): # Filter out runs that are from a different worker thread if run.worker_id == worker_id and run.state == RunState.ALIVE: _run_states[run_id] = True _logger.debug(f"{LOG_PREFIX}Sending states: \n{pf(_run_states)}\n") commands: List[Dict[str, Any]] = self._api.agent_heartbeat( self._workers[worker_id].agent_id, # agent_id: str {}, # metrics: dict _run_states, # run_states: dict ) _logger.debug(f"{LOG_PREFIX}AgentHeartbeat commands: \n{pf(commands)}\n") return commands
python
wandb/sdk/launch/sweeps/scheduler_sweep.py
58
74
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,019
_heartbeat
def _heartbeat(self, worker_id: int) -> bool: # Make sure Scheduler is alive if not self.is_alive(): return False elif self.state == SchedulerState.FLUSH_RUNS: # already hit run_cap, just noop return False commands: List[Dict[str, Any]] = self._get_sweep_commands(worker_id) for command in commands: # The command "type" can be one of "run", "resume", "stop", "exit" _type = command.get("type") if _type in ["exit", "stop"]: run_cap = command.get("run_cap") if run_cap is not None: # If Sweep hit run_cap, go into flushing state wandb.termlog(f"{LOG_PREFIX}Sweep hit run_cap: {run_cap}") self.state = SchedulerState.FLUSH_RUNS else: # Tell (virtual) agent to stop running self.state = SchedulerState.STOPPED return False if _type in ["run", "resume"]: _run_id = command.get("run_id") if not _run_id: self.state = SchedulerState.FAILED raise SchedulerError(f"No runId in agent heartbeat: {command}") if _run_id in self._runs: wandb.termlog(f"{LOG_PREFIX}Skipping duplicate run: {_run_id}") continue run = SweepRun( id=_run_id, args=command.get("args", {}), logs=command.get("logs", []), worker_id=worker_id, ) self._runs[run.id] = run self._heartbeat_queue.put(run) else: self.state = SchedulerState.FAILED raise SchedulerError(f"AgentHeartbeat unknown command: {_type}") return True
python
wandb/sdk/launch/sweeps/scheduler_sweep.py
76
119
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,020
_run
def _run(self) -> None: # Go through all workers and heartbeat for worker_id in self._workers: self._heartbeat(worker_id) for _worker_id in self._workers: try: run: SweepRun = self._heartbeat_queue.get( timeout=self._heartbeat_queue_timeout ) # If run is already stopped just ignore the request if run.state in [RunState.DEAD, RunState.UNKNOWN]: wandb.termwarn(f"{LOG_PREFIX}Ignoring dead run {run.id}") _logger.debug(f"dead run {run.id} state: {run.state}") continue sweep_args = _create_sweep_command_args({"args": run.args})["args_dict"] launch_config = {"overrides": {"run_config": sweep_args}} self._add_to_launch_queue(run_id=run.id, config=launch_config) except queue.Empty: if self.state == SchedulerState.FLUSH_RUNS: wandb.termlog(f"{LOG_PREFIX}Sweep stopped, waiting on runs...") else: wandb.termlog(f"{LOG_PREFIX}No new runs to launch, waiting...") time.sleep(self._heartbeat_queue_sleep) return
python
wandb/sdk/launch/sweeps/scheduler_sweep.py
121
147
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,021
_exit
def _exit(self) -> None: pass
python
wandb/sdk/launch/sweeps/scheduler_sweep.py
149
150
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,022
_import_sweep_scheduler
def _import_sweep_scheduler() -> Any: from .scheduler_sweep import SweepScheduler return SweepScheduler
python
wandb/sdk/launch/sweeps/__init__.py
15
18
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,023
load_scheduler
def load_scheduler(scheduler_name: str) -> Any: scheduler_name = scheduler_name.lower() if scheduler_name not in _WANDB_SCHEDULERS: raise SchedulerError( f"The `scheduler_name` argument must be one of " f"{list(_WANDB_SCHEDULERS.keys())}, got: {scheduler_name}" ) log.warn(f"Loading dependencies for Scheduler of type: {scheduler_name}") import_func = _WANDB_SCHEDULERS[scheduler_name] return import_func()
python
wandb/sdk/launch/sweeps/__init__.py
26
36
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,024
__init__
def __init__( self, api: Api, *args: Optional[Any], sweep_id: Optional[str] = None, entity: Optional[str] = None, project: Optional[str] = None, project_queue: Optional[str] = None, **kwargs: Optional[Any], ): self._api = api self._entity = ( entity or os.environ.get("WANDB_ENTITY") or api.settings("entity") or api.default_entity ) self._project = ( project or os.environ.get("WANDB_PROJECT") or api.settings("project") ) self._sweep_id: str = sweep_id or "empty-sweep-id" self._state: SchedulerState = SchedulerState.PENDING # Make sure the provided sweep_id corresponds to a valid sweep try: resp = self._api.sweep( sweep_id, "{}", entity=self._entity, project=self._project ) if resp.get("state") == SchedulerState.CANCELLED.name: self._state = SchedulerState.CANCELLED self._sweep_config = yaml.safe_load(resp["config"]) except Exception as e: raise SchedulerError(f"{LOG_PREFIX}Exception when finding sweep: {e}") # Dictionary of the runs being managed by the scheduler self._runs: Dict[str, SweepRun] = {} # Threading lock to ensure thread-safe access to the runs dictionary self._threading_lock: threading.Lock = threading.Lock() self._project_queue = project_queue # Optionally run multiple workers in (pseudo-)parallel. Workers do not # actually run training workloads, they simply send heartbeat messages # (emulating a real agent) and add new runs to the launch queue. The # launch agent is the one that actually runs the training workloads. self._workers: Dict[int, _Worker] = {} # Scheduler may receive additional kwargs which will be piped into the launch command self._kwargs: Dict[str, Any] = kwargs
python
wandb/sdk/launch/sweeps/scheduler.py
64
110
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,025
_start
def _start(self) -> None: pass
python
wandb/sdk/launch/sweeps/scheduler.py
113
114
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,026
_run
def _run(self) -> None: pass
python
wandb/sdk/launch/sweeps/scheduler.py
117
118
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,027
_exit
def _exit(self) -> None: pass
python
wandb/sdk/launch/sweeps/scheduler.py
121
122
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,028
state
def state(self) -> SchedulerState: _logger.debug(f"{LOG_PREFIX}Scheduler state is {self._state.name}") return self._state
python
wandb/sdk/launch/sweeps/scheduler.py
125
127
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,029
state
def state(self, value: SchedulerState) -> None: _logger.debug(f"{LOG_PREFIX}Scheduler was {self.state.name} is {value.name}") self._state = value
python
wandb/sdk/launch/sweeps/scheduler.py
130
132
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,030
is_alive
def is_alive(self) -> bool: if self.state in [ SchedulerState.COMPLETED, SchedulerState.FAILED, SchedulerState.STOPPED, SchedulerState.CANCELLED, ]: return False return True
python
wandb/sdk/launch/sweeps/scheduler.py
134
142
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,031
start
def start(self) -> None: """Start a scheduler, confirms prerequisites, begins execution loop.""" wandb.termlog(f"{LOG_PREFIX}Scheduler starting.") if not self.is_alive(): wandb.termerror( f"{LOG_PREFIX}Sweep already {self.state.name.lower()}! Exiting..." ) self.exit() return self._state = SchedulerState.STARTING if not self._try_load_executable(): wandb.termerror( f"{LOG_PREFIX}No 'job' or 'image_uri' loaded from sweep config." ) self.exit() return self._start() self.run()
python
wandb/sdk/launch/sweeps/scheduler.py
144
162
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,032
run
def run(self) -> None: """Main run function for all external schedulers.""" wandb.termlog(f"{LOG_PREFIX}Scheduler Running.") self.state = SchedulerState.RUNNING try: while True: if not self.is_alive(): break self._update_run_states() self._run() # if we hit the run_cap, now set to stopped after launching runs if self.state == SchedulerState.FLUSH_RUNS: if len(self._runs.keys()) == 0: wandb.termlog(f"{LOG_PREFIX}Done polling on runs, exiting.") self.state = SchedulerState.STOPPED except KeyboardInterrupt: wandb.termlog(f"{LOG_PREFIX}Scheduler received KeyboardInterrupt. Exiting.") self.state = SchedulerState.STOPPED self.exit() return except Exception as e: wandb.termlog(f"{LOG_PREFIX}Scheduler failed with exception {e}") self.state = SchedulerState.FAILED self.exit() raise e else: wandb.termlog(f"{LOG_PREFIX}Scheduler completed.") self.exit()
python
wandb/sdk/launch/sweeps/scheduler.py
164
191
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,033
exit
def exit(self) -> None: self._exit() if self.state not in [ SchedulerState.COMPLETED, SchedulerState.STOPPED, ]: self.state = SchedulerState.FAILED self._stop_runs()
python
wandb/sdk/launch/sweeps/scheduler.py
193
200
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,034
_try_load_executable
def _try_load_executable(self) -> bool: """Check existance of valid executable for a run. logs and returns False when job is unreachable """ if self._kwargs.get("job"): _public_api = public.Api() try: _job_artifact = _public_api.artifact(self._kwargs["job"], type="job") wandb.termlog( f"{LOG_PREFIX}Successfully loaded job: {_job_artifact.name} in scheduler" ) except Exception: wandb.termerror(f"{LOG_PREFIX}{traceback.format_exc()}") return False return True elif self._kwargs.get("image_uri"): # TODO(gst): check docker existance? Use registry in launch config? return True else: return False
python
wandb/sdk/launch/sweeps/scheduler.py
202
222
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,035
_yield_runs
def _yield_runs(self) -> Iterator[Tuple[str, SweepRun]]: """Thread-safe way to iterate over the runs.""" with self._threading_lock: yield from self._runs.items()
python
wandb/sdk/launch/sweeps/scheduler.py
224
227
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,036
_stop_runs
def _stop_runs(self) -> None: for run_id, _ in self._yield_runs(): wandb.termlog(f"{LOG_PREFIX}Stopping run {run_id}.") self._stop_run(run_id)
python
wandb/sdk/launch/sweeps/scheduler.py
229
232
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,037
_stop_run
def _stop_run(self, run_id: str) -> None: """Stop a run and removes it from the scheduler.""" if run_id in self._runs: run: SweepRun = self._runs[run_id] run.state = RunState.DEAD # TODO(hupo): Send command to backend to stop run wandb.termlog(f"{LOG_PREFIX} Stopped run {run_id}.")
python
wandb/sdk/launch/sweeps/scheduler.py
234
240
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,038
_update_run_states
def _update_run_states(self) -> None: """Iterate through runs. Get state from backend and deletes runs if not in running state. Threadsafe. """ _runs_to_remove: List[str] = [] for run_id, run in self._yield_runs(): try: _state = self._api.get_run_state(self._entity, self._project, run_id) _rqi_state = run.queued_run.state if run.queued_run else None if ( not _state or _state in [ "crashed", "failed", "killed", "finished", ] or _rqi_state == "failed" ): _logger.debug( f"({run_id}) run-state:{_state}, rqi-state:{_rqi_state}" ) run.state = RunState.DEAD _runs_to_remove.append(run_id) elif _state in [ "running", "pending", "preempted", "preempting", ]: run.state = RunState.ALIVE except CommError as e: wandb.termlog( f"{LOG_PREFIX}Issue when getting RunState for Run {run_id}: {e}" ) run.state = RunState.UNKNOWN continue # Remove any runs that are dead with self._threading_lock: for run_id in _runs_to_remove: wandb.termlog(f"{LOG_PREFIX}Cleaning up dead run {run_id}.") del self._runs[run_id]
python
wandb/sdk/launch/sweeps/scheduler.py
242
285
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,039
_add_to_launch_queue
def _add_to_launch_queue( self, run_id: Optional[str] = None, entry_point: Optional[List[str]] = None, config: Optional[Dict[str, Any]] = None, ) -> "public.QueuedRun": """Add a launch job to the Launch RunQueue. run_id: supplied by gorilla from agentHeartbeat entry_point: sweep entrypoint overrides image_uri/job entrypoint config: launch config """ # job and image first from CLI args, then from sweep config _job = self._kwargs.get("job") or self._sweep_config.get("job") _sweep_config_uri = self._sweep_config.get("image_uri") _image_uri = self._kwargs.get("image_uri") or _sweep_config_uri if _job is None and _image_uri is None: raise SchedulerError( f"{LOG_PREFIX}No 'job' nor 'image_uri' (run: {run_id})" ) elif _job is not None and _image_uri is not None: raise SchedulerError(f"{LOG_PREFIX}Sweep has both 'job' and 'image_uri'") if self._sweep_config.get("command"): entry_point = Agent._create_sweep_command(self._sweep_config["command"]) wandb.termwarn( f"{LOG_PREFIX}Sweep command {entry_point} will override" f' {"job" if _job else "image_uri"} entrypoint' ) run_id = run_id or generate_id() queued_run = launch_add( run_id=run_id, entry_point=entry_point, config=config, docker_image=_image_uri, # TODO(gst): make agnostic (github? run uri?) job=_job, project=self._project, entity=self._entity, queue_name=self._kwargs.get("queue"), project_queue=self._project_queue, resource=self._kwargs.get("resource", None), resource_args=self._kwargs.get("resource_args", None), ) self._runs[run_id].queued_run = queued_run wandb.termlog( f"{LOG_PREFIX}Added run to Launch queue: {self._kwargs.get('queue')} RunID:{run_id}." ) return queued_run
python
wandb/sdk/launch/sweeps/scheduler.py
287
336
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,040
verify
def verify(self) -> None: """Verify that the registry is configured correctly.""" raise NotImplementedError
python
wandb/sdk/launch/registry/abstract.py
14
16
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,041
get_username_password
def get_username_password(self) -> Tuple[str, str]: """Get the username and password for the registry. Returns: (str, str): The username and password. """ raise NotImplementedError
python
wandb/sdk/launch/registry/abstract.py
19
25
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,042
get_repo_uri
def get_repo_uri(self) -> str: """Get the URI for a repository. Returns: str: The URI. """ raise NotImplementedError
python
wandb/sdk/launch/registry/abstract.py
28
34
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,043
check_image_exists
def check_image_exists(self, image_uri: str) -> bool: """Check if an image exists in the registry. Arguments: image_uri (str): The URI of the image. Returns: bool: True if the image exists. """ raise NotImplementedError
python
wandb/sdk/launch/registry/abstract.py
37
46
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,044
from_config
def from_config( cls, config: dict, environment: "AbstractEnvironment", verify: bool = True ) -> "AbstractRegistry": """Create a registry from a config.""" raise NotImplementedError
python
wandb/sdk/launch/registry/abstract.py
50
54
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,045
__init__
def __init__(self, repo_name: str, environment: AwsEnvironment) -> None: """Initialize the Elastic Container Registry. Arguments: repo_name (str): The name of the repository. environment (AwsEnvironment): The AWS environment. Raises: LaunchError: If there is an error verifying the registry. """ super().__init__() _logger.info( f"Initializing Elastic Container Registry with repotisory {repo_name}." ) self.repo_name = repo_name self.environment = environment self.verify()
python
wandb/sdk/launch/registry/elastic_container_registry.py
34
50
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,046
from_config
def from_config( # type: ignore[override] cls, config: Dict, environment: AwsEnvironment, verify: bool = True, ) -> "ElasticContainerRegistry": """Create an Elastic Container Registry from a config. Arguments: config (dict): The config. environment (AwsEnvironment): The AWS environment. Returns: ElasticContainerRegistry: The Elastic Container Registry. """ if config.get("type") != "ecr": raise LaunchError( f"Could not create ElasticContainerRegistry from config. Expected type 'ecr' " f"but got '{config.get('type')}'." ) repository = config.get("repository") if not repository: raise LaunchError( "Could not create ElasticContainerRegistry from config. 'repository' is required." ) return cls(repository, environment)
python
wandb/sdk/launch/registry/elastic_container_registry.py
53
78
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,047
verify
def verify(self) -> None: """Verify that the registry is accessible and the configured repo exists. Raises: RegistryError: If there is an error verifying the registry. """ _logger.debug("Verifying Elastic Container Registry.") try: session = self.environment.get_session() client = session.client("ecr") response = client.describe_repositories(repositoryNames=[self.repo_name]) self.uri = response["repositories"][0]["repositoryUri"].split("/")[0] except botocore.exceptions.ClientError as e: code = e.response["Error"]["Code"] msg = e.response["Error"]["Message"] # TODO: Log the code and the message here? raise LaunchError( f"Error verifying Elastic Container Registry: {code} {msg}" )
python
wandb/sdk/launch/registry/elastic_container_registry.py
80
99
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,048
get_username_password
def get_username_password(self) -> Tuple[str, str]: """Get the username and password for the registry. Returns: (str, str): The username and password. Raises: RegistryError: If there is an error getting the username and password. """ _logger.debug("Getting username and password for Elastic Container Registry.") try: session = self.environment.get_session() client = session.client("ecr") response = client.get_authorization_token() username, password = base64.standard_b64decode( response["authorizationData"][0]["authorizationToken"] ).split(b":") return username.decode("utf-8"), password.decode("utf-8") except botocore.exceptions.ClientError as e: code = e.response["Error"]["Code"] msg = e.response["Error"]["Message"] # TODO: Log the code and the message here? raise LaunchError(f"Error getting username and password: {code} {msg}")
python
wandb/sdk/launch/registry/elastic_container_registry.py
101
124
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,049
get_repo_uri
def get_repo_uri(self) -> str: """Get the uri of the repository. Returns: str: The uri of the repository. """ return self.uri + "/" + self.repo_name
python
wandb/sdk/launch/registry/elastic_container_registry.py
126
132
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,050
check_image_exists
def check_image_exists(self, image_uri: str) -> bool: """Check if the image tag exists. Arguments: image_uri (str): The full image_uri. Returns: bool: True if the image tag exists. """ uri, tag = image_uri.split(":") if uri != self.get_repo_uri(): raise LaunchError( f"Image uri {image_uri} does not match Elastic Container Registry uri {self.get_repo_uri()}." ) _logger.debug("Checking if image tag exists.") try: session = self.environment.get_session() client = session.client("ecr") response = client.describe_images( repositoryName=self.repo_name, imageIds=[{"imageTag": tag}] ) return len(response["imageDetails"]) > 0 except botocore.exceptions.ClientError as e: code = e.response["Error"]["Code"] msg = e.response["Error"]["Message"] raise LaunchError(f"Error checking if image tag exists: {code} {msg}")
python
wandb/sdk/launch/registry/elastic_container_registry.py
134
161
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,051
__init__
def __init__(self) -> None: """Initialize a local registry.""" pass
python
wandb/sdk/launch/registry/local_registry.py
19
21
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,052
from_config
def from_config( cls, config: dict, environment: "AbstractEnvironment", verify: bool = True ) -> "LocalRegistry": """Create a local registry from a config. Arguments: config (dict): The config. This is ignored. environment (AbstractEnvironment): The environment. This is ignored. Returns: LocalRegistry: The local registry. """ return cls()
python
wandb/sdk/launch/registry/local_registry.py
24
36
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,053
verify
def verify(self) -> None: """Verify the local registry by doing nothing.""" pass
python
wandb/sdk/launch/registry/local_registry.py
38
40
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,054
get_username_password
def get_username_password(self) -> Tuple[str, str]: """Get the username and password of the local registry.""" raise LaunchError("Attempted to get username and password for LocalRegistry.")
python
wandb/sdk/launch/registry/local_registry.py
42
44
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,055
get_repo_uri
def get_repo_uri(self) -> str: """Get the uri of the local registry. Returns: An empty string. """ return ""
python
wandb/sdk/launch/registry/local_registry.py
46
51
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,056
check_image_exists
def check_image_exists(self, image_uri: str) -> bool: """Check if an image exists in the local registry. Arguments: image_uri (str): The uri of the image. Returns: bool: True. """ return docker_image_exists(image_uri)
python
wandb/sdk/launch/registry/local_registry.py
53
62
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,057
__init__
def __init__( self, repository: str, image_name: str, environment: GcpEnvironment, verify: bool = True, ) -> None: """Initialize the Google Artifact Registry. Arguments: repository: The repository name. image_name: The image name. environment: A GcpEnvironment configured for access to this registry. verify: Whether to verify the credentials, region, and project. Raises: LaunchError: If verify is True and the container registry or its environment have not been properly configured. Or if the environment is not an instance of GcpEnvironment. """ _logger.info( f"Initializing Google Artifact Registry with repository {repository} " f"and image name {image_name}" ) self.repository = repository self.image_name = image_name if not re.match(r"^\w[\w.-]+$", image_name): raise LaunchError( f"The image name {image_name} is invalid. The image name must " "consist of alphanumeric characters and underscores." ) self.environment = environment if verify: self.verify()
python
wandb/sdk/launch/registry/google_artifact_registry.py
45
78
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,058
uri
def uri(self) -> str: """The uri of the registry.""" return f"{self.environment.region}-docker.pkg.dev/{self.environment.project}/{self.repository}/{self.image_name}"
python
wandb/sdk/launch/registry/google_artifact_registry.py
81
83
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,059
uri
def uri(self, uri: str) -> None: """Set the uri of the registry.""" raise LaunchError("The uri of the Google Artifact Registry cannot be set.")
python
wandb/sdk/launch/registry/google_artifact_registry.py
86
88
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,060
from_config
def from_config( # type: ignore[override] cls, config: dict, environment: GcpEnvironment, verify: bool = True, ) -> "GoogleArtifactRegistry": """Create a Google Artifact Registry from a config. Arguments: config: A dictionary containing the following keys: repository: The repository name. image_name: The image name. environment: A GcpEnvironment configured for access to this registry. Returns: A GoogleArtifactRegistry. """ repository = config.get("repository") if not repository: raise LaunchError( "The Google Artifact Registry repository must be specified." ) image_name = config.get("image_name") if not image_name: raise LaunchError("The image name must be specified.") return cls(repository, image_name, environment, verify=verify)
python
wandb/sdk/launch/registry/google_artifact_registry.py
91
116
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,061
verify
def verify(self) -> None: """Verify the registry is properly configured. Raises: LaunchError: If the registry is not properly configured. """ credentials = self.environment.get_credentials() parent = ( f"projects/{self.environment.project}/locations/{self.environment.region}" ) # We need to list the repositories to verify that the repository exists. request = google.cloud.artifactregistry.ListRepositoriesRequest(parent=parent) client = google.cloud.artifactregistry.ArtifactRegistryClient( credentials=credentials ) try: response = client.list_repositories(request=request) except google.api_core.exceptions.PermissionDenied: raise LaunchError( "The provided credentials do not have permission to access the " f"Google Artifact Registry repository {self.repository}." ) # Look for self.repository in the list of responses. for repo in response: if repo.name.endswith(self.repository): break # If we didn't find the repository, raise an error. else: raise LaunchError( f"The Google Artifact Registry repository {self.repository} does not exist." )
python
wandb/sdk/launch/registry/google_artifact_registry.py
118
148
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,062
get_username_password
def get_username_password(self) -> Tuple[str, str]: """Get the username and password for the registry. Returns: A tuple of the username and password. """ credentials = self.environment.get_credentials() return "oauth2accesstoken", credentials.token
python
wandb/sdk/launch/registry/google_artifact_registry.py
150
157
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,063
get_repo_uri
def get_repo_uri(self) -> str: """Get the URI for the given repository. Arguments: repo_name: The repository name. Returns: The repository URI. """ return ( f"{self.environment.region}-docker.pkg.dev/" f"{self.environment.project}/{self.repository}/{self.image_name}" )
python
wandb/sdk/launch/registry/google_artifact_registry.py
159
171
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,064
check_image_exists
def check_image_exists(self, image_uri: str) -> bool: """Check if the image exists. Arguments: image_uri: The image URI. Returns: True if the image exists, False otherwise. """ _logger.info( f"Checking if image {image_uri} exists. In Google Artifact Registry {self.uri}." ) return False # TODO: Test GCP Artifact Registry image exists to get working # repo_uri, _ = image_uri.split(":") # if repo_uri != self.get_repo_uri(): # raise LaunchError( # f"The image {image_uri} does not belong to the Google Artifact " # f"Repository {self.get_repo_uri()}." # ) # credentials = self.environment.get_credentials() # request = google.cloud.artifactregistry.GetTagRequest(parent=image_uri) # client = google.cloud.artifactregistry.ArtifactRegistryClient( # credentials=credentials # ) # try: # client.get_tag(request=request) # return True # except google.api_core.exceptions.NotFound: # return False
python
wandb/sdk/launch/registry/google_artifact_registry.py
173
203
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,065
verify
def verify(self) -> None: """Verify that the environment is configured correctly.""" raise NotImplementedError
python
wandb/sdk/launch/environment/abstract.py
11
13
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,066
upload_file
def upload_file(self, source: str, destination: str) -> None: """Upload a file from the local filesystem to storage in the environment.""" raise NotImplementedError
python
wandb/sdk/launch/environment/abstract.py
16
18
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,067
upload_dir
def upload_dir(self, source: str, destination: str) -> None: """Upload the contents of a directory from the local filesystem to the environment.""" raise NotImplementedError
python
wandb/sdk/launch/environment/abstract.py
21
23
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,068
verify_storage_uri
def verify_storage_uri(self, uri: str) -> None: """Verify that the storage URI is configured correctly.""" raise NotImplementedError
python
wandb/sdk/launch/environment/abstract.py
26
28
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,069
__init__
def __init__( self, region: str, access_key: str, secret_key: str, session_token: str, verify: bool = True, ) -> None: """Initialize the AWS environment. Arguments: region (str): The AWS region. Raises: LaunchError: If the AWS environment is not configured correctly. """ super().__init__() _logger.info(f"Initializing AWS environment in region {region}.") self._region = region self._access_key = access_key self._secret_key = secret_key self._session_token = session_token if verify: self.verify()
python
wandb/sdk/launch/environment/aws_environment.py
32
55
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,070
from_default
def from_default(cls, region: str, verify: bool = True) -> "AwsEnvironment": """Create an AWS environment from the default AWS environment. Arguments: region (str): The AWS region. verify (bool, optional): Whether to verify the AWS environment. Defaults to True. Returns: AwsEnvironment: The AWS environment. """ _logger.info("Creating AWS environment from default credentials.") try: session = boto3.Session() region = region or session.region_name credentials = session.get_credentials() if not credentials: raise LaunchError( "Could not create AWS environment from default environment. Please verify that your AWS credentials are configured correctly." ) access_key = credentials.access_key secret_key = credentials.secret_key session_token = credentials.token except botocore.client.ClientError as e: raise LaunchError( f"Could not create AWS environment from default environment. Please verify that your AWS credentials are configured correctly. {e}" ) return cls( region=region, access_key=access_key, secret_key=secret_key, session_token=session_token, verify=verify, )
python
wandb/sdk/launch/environment/aws_environment.py
58
90
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,071
from_config
def from_config( cls, config: Dict[str, str], verify: bool = True ) -> "AwsEnvironment": """Create an AWS environment from the default AWS environment. Arguments: config (dict): Configuration dictionary. verify (bool, optional): Whether to verify the AWS environment. Defaults to True. Returns: AwsEnvironment: The AWS environment. """ region = str(config.get("region", "")) if not region: raise LaunchError( "Could not create AWS environment from config. Region not specified." ) return cls.from_default( region=region, verify=verify, )
python
wandb/sdk/launch/environment/aws_environment.py
93
113
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,072
region
def region(self) -> str: """The AWS region.""" return self._region
python
wandb/sdk/launch/environment/aws_environment.py
116
118
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,073
region
def region(self, region: str) -> None: self._region = region
python
wandb/sdk/launch/environment/aws_environment.py
121
122
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,074
verify
def verify(self) -> None: """Verify that the AWS environment is configured correctly. Raises: LaunchError: If the AWS environment is not configured correctly. """ _logger.debug("Verifying AWS environment.") try: session = self.get_session() client = session.client("sts") client.get_caller_identity() # TODO: log identity details from the response except botocore.exceptions.ClientError as e: raise LaunchError( f"Could not verify AWS environment. Please verify that your AWS credentials are configured correctly. {e}" ) from e
python
wandb/sdk/launch/environment/aws_environment.py
124
139
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,075
get_session
def get_session(self) -> "boto3.Session": # type: ignore """Get an AWS session. Returns: boto3.Session: The AWS session. Raises: LaunchError: If the AWS session could not be created. """ _logger.debug(f"Creating AWS session in region {self._region}") try: return boto3.Session( aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, aws_session_token=self._session_token, region_name=self._region, ) except botocore.exceptions.ClientError as e: raise LaunchError(f"Could not create AWS session. {e}")
python
wandb/sdk/launch/environment/aws_environment.py
141
159
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,076
upload_file
def upload_file(self, source: str, destination: str) -> None: """Upload a file to s3 from local storage. The destination is a valid s3 URI, e.g. s3://bucket/key and will be used as a prefix for the uploaded file. Only the filename of the source is kept in the upload key. So if the source is "foo/bar" and the destination is "s3://bucket/key", the file "foo/bar" will be uploaded to "s3://bucket/key/bar". Arguments: source (str): The path to the file or directory. destination (str): The uri of the storage destination. This should be a valid s3 URI, e.g. s3://bucket/key. Raises: LaunchError: If the copy fails, the source path does not exist, or the destination is not a valid s3 URI, or the upload fails. """ _logger.debug(f"Uploading {source} to {destination}") if not os.path.isfile(source): raise LaunchError(f"Source {source} does not exist.") match = S3_URI_RE.match(destination) if not match: raise LaunchError(f"Destination {destination} is not a valid s3 URI.") bucket = match.group(1) key = match.group(2).lstrip("/") if not key: key = "" session = self.get_session() try: client = session.client("s3") client.upload_file(source, bucket, key) except botocore.exceptions.ClientError as e: raise LaunchError( f"botocore error attempting to copy {source} to {destination}. {e}" ) from e
python
wandb/sdk/launch/environment/aws_environment.py
161
196
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,077
upload_dir
def upload_dir(self, source: str, destination: str) -> None: """Upload a directory to s3 from local storage. The upload will place the contents of the source directory in the destination with the same directory structure. So if the source is "foo/bar" and the destination is "s3://bucket/key", the contents of "foo/bar" will be uploaded to "s3://bucket/key/bar". Arguments: source (str): The path to the file or directory. destination (str): The URI of the storage. recursive (bool, optional): If True, copy the directory recursively. Defaults to False. Raises: LaunchError: If the copy fails, the source path does not exist, or the destination is not a valid s3 URI. """ _logger.debug(f"Uploading {source} to {destination}") if not os.path.isdir(source): raise LaunchError(f"Source {source} does not exist.") match = S3_URI_RE.match(destination) if not match: raise LaunchError(f"Destination {destination} is not a valid s3 URI.") bucket = match.group(1) key = match.group(2).lstrip("/") if not key: key = "" session = self.get_session() try: client = session.client("s3") for path, _, files in os.walk(source): for file in files: abs_path = os.path.join(path, file) key_path = ( abs_path.replace(source, "").replace("\\", "/").lstrip("/") ) client.upload_file( abs_path, bucket, key_path, ) except botocore.exceptions.ClientError as e: raise LaunchError( f"botocore error attempting to copy {source} to {destination}. {e}" ) from e except Exception as e: raise LaunchError( f"Unexpected error attempting to copy {source} to {destination}. {e}" ) from e
python
wandb/sdk/launch/environment/aws_environment.py
198
246
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,078
verify_storage_uri
def verify_storage_uri(self, uri: str) -> None: """Verify that s3 storage is configured correctly. This will check that the bucket exists and that the credentials are configured correctly. Arguments: uri (str): The URI of the storage. Raises: LaunchError: If the storage is not configured correctly or the URI is not a valid s3 URI. Returns: None """ _logger.debug(f"Verifying storage {uri}") match = S3_URI_RE.match(uri) if not match: raise LaunchError(f"Destination {uri} is not a valid s3 URI.") bucket = match.group(1) try: session = self.get_session() client = session.client("s3") client.head_bucket(Bucket=bucket) except botocore.exceptions.ClientError as e: raise LaunchError( f"Could not verify AWS storage. Please verify that your AWS credentials are configured correctly. {e}" ) from e
python
wandb/sdk/launch/environment/aws_environment.py
248
276
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,079
__init__
def __init__(self, region: str, verify: bool = True) -> None: """Initialize the GCP environment. Arguments: region: The GCP region. verify: Whether to verify the credentials, region, and project. Raises: LaunchError: If verify is True and the environment is not properly configured. """ super().__init__() _logger.info(f"Initializing GcpEnvironment in region {region}") self.region: str = region self._project = "" if verify: self.verify()
python
wandb/sdk/launch/environment/gcp_environment.py
57
73
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,080
from_config
def from_config(cls, config: dict) -> "GcpEnvironment": """Create a GcpEnvironment from a config dictionary. Arguments: config: The config dictionary. Returns: GcpEnvironment: The GcpEnvironment. """ if config.get("type") != "gcp": raise LaunchError( f"Could not create GcpEnvironment from config. Expected type 'gcp' " f"but got '{config.get('type')}'." ) region = config.get("region", None) if not region: raise LaunchError( "Could not create GcpEnvironment from config. Missing 'region' " "field." ) return cls(region=region)
python
wandb/sdk/launch/environment/gcp_environment.py
76
96
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,081
project
def project(self) -> str: """Get the name of the gcp project. The project name is determined by the credentials, so this method verifies the credentials if they have not already been verified. Returns: str: The name of the gcp project. Raises: LaunchError: If the launch environment cannot be verified. """ if not self._project: raise LaunchError( "This GcpEnvironment has not been verified. Please call verify() " "before accessing the project." ) return self._project
python
wandb/sdk/launch/environment/gcp_environment.py
99
116
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,082
get_credentials
def get_credentials(self) -> google.auth.credentials.Credentials: # type: ignore """Get the GCP credentials. Uses google.auth.default() to get the credentials. If the credentials are invalid, this method will refresh them. If the credentials are still invalid after refreshing, this method will raise an error. Returns: google.auth.credentials.Credentials: The GCP credentials. Raises: LaunchError: If the GCP credentials are invalid. """ _logger.debug("Getting GCP credentials") # TODO: Figure out a minimal set of scopes. scopes = [ "https://www.googleapis.com/auth/cloud-platform", ] try: creds, project = google.auth.default(scopes=scopes) if not self._project: self._project = project _logger.debug("Refreshing GCP credentials") creds.refresh(google.auth.transport.requests.Request()) except google.auth.exceptions.DefaultCredentialsError as e: raise LaunchError( "No Google Cloud Platform credentials found. Please run " "`gcloud auth application-default login` or set the environment " "variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid " "service account key file." ) from e except google.auth.exceptions.RefreshError as e: raise LaunchError( "Could not refresh Google Cloud Platform credentials. Please run " "`gcloud auth application-default login` or set the environment " "variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid " "service account key file." ) from e if not creds.valid: raise LaunchError( "Invalid Google Cloud Platform credentials. Please run " "`gcloud auth application-default login` or set the environment " "variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid " "service account key file." ) return creds
python
wandb/sdk/launch/environment/gcp_environment.py
118
163
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,083
verify
def verify(self) -> None: """Verify the credentials, region, and project. Credentials and region are verified by calling get_credentials(). The region and is verified by calling the compute API. Raises: LaunchError: If the credentials, region, or project are invalid. Returns: None """ _logger.debug("Verifying GCP environment") creds = self.get_credentials() try: # Check if the region is available using the compute API. compute_client = google.cloud.compute_v1.RegionsClient(credentials=creds) compute_client.get(project=self.project, region=self.region) except google.api_core.exceptions.NotFound as e: raise LaunchError( f"Region {self.region} is not available in project {self.project}." ) from e
python
wandb/sdk/launch/environment/gcp_environment.py
165
186
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,084
verify_storage_uri
def verify_storage_uri(self, uri: str) -> None: """Verify that a storage URI is valid. Arguments: uri: The storage URI. Raises: LaunchError: If the storage URI is invalid. """ match = GCS_URI_RE.match(uri) if not match: raise LaunchError(f"Invalid GCS URI: {uri}") bucket = match.group(1) try: storage_client = google.cloud.storage.Client( credentials=self.get_credentials() ) bucket = storage_client.post_bucket(bucket) except google.api_core.exceptions.NotFound as e: raise LaunchError(f"Bucket {bucket} does not exist.") from e
python
wandb/sdk/launch/environment/gcp_environment.py
188
207
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,085
upload_file
def upload_file(self, source: str, destination: str) -> None: """Upload a file to GCS. Arguments: source: The path to the local file. destination: The path to the GCS file. Raises: LaunchError: If the file cannot be uploaded. """ _logger.debug(f"Uploading file {source} to {destination}") if not os.path.isfile(source): raise LaunchError(f"File {source} does not exist.") match = GCS_URI_RE.match(destination) if not match: raise LaunchError(f"Invalid GCS URI: {destination}") bucket = match.group(1) key = match.group(2).lstrip("/") try: storage_client = google.cloud.storage.Client( credentials=self.get_credentials() ) bucket = storage_client.bucket(bucket) blob = bucket.blob(key) blob.upload_from_filename(source) except google.api_core.exceptions.GoogleAPICallError as e: raise LaunchError(f"Could not upload file to GCS: {e}") from e
python
wandb/sdk/launch/environment/gcp_environment.py
209
235
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,086
upload_dir
def upload_dir(self, source: str, destination: str) -> None: """Upload a directory to GCS. Arguments: source: The path to the local directory. destination: The path to the GCS directory. Raises: LaunchError: If the directory cannot be uploaded. """ _logger.debug(f"Uploading directory {source} to {destination}") if not os.path.isdir(source): raise LaunchError(f"Directory {source} does not exist.") match = GCS_URI_RE.match(destination) if not match: raise LaunchError(f"Invalid GCS URI: {destination}") bucket = match.group(1) key = match.group(2).lstrip("/") try: storage_client = google.cloud.storage.Client( credentials=self.get_credentials() ) bucket = storage_client.bucket(bucket) for root, _, files in os.walk(source): for file in files: local_path = os.path.join(root, file) gcs_path = os.path.join( key, os.path.relpath(local_path, source) ).replace("\\", "/") blob = bucket.blob(gcs_path) blob.upload_from_filename(local_path) except google.api_core.exceptions.GoogleAPICallError as e: raise LaunchError(f"Could not upload directory to GCS: {e}") from e raise LaunchError(f"Could not upload directory to GCS: {e}") from e raise LaunchError(f"Could not upload directory to GCS: {e}") from e
python
wandb/sdk/launch/environment/gcp_environment.py
237
271
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,087
__init__
def __init__(self) -> None: """Initialize a local environment by doing nothing.""" pass
python
wandb/sdk/launch/environment/local_environment.py
12
14
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,088
from_config
def from_config( cls, config: Dict[str, Union[Dict[str, Any], str]] ) -> "LocalEnvironment": """Create a local environment from a config. Arguments: config (dict): The config. This is ignored. Returns: LocalEnvironment: The local environment. """ return cls()
python
wandb/sdk/launch/environment/local_environment.py
17
28
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,089
verify
def verify(self) -> None: """Verify that the local environment is configured correctly.""" raise LaunchError("Attempted to verify LocalEnvironment.")
python
wandb/sdk/launch/environment/local_environment.py
30
32
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,090
verify_storage_uri
def verify_storage_uri(self, uri: str) -> None: """Verify that the storage URI is configured correctly. Arguments: uri (str): The storage URI. This is ignored. """ raise LaunchError("Attempted to verify storage uri for LocalEnvironment.")
python
wandb/sdk/launch/environment/local_environment.py
34
40
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,091
upload_file
def upload_file(self, source: str, destination: str) -> None: """Upload a file from the local filesystem to storage in the environment. Arguments: source (str): The source file. This is ignored. destination (str): The destination file. This is ignored. """ raise LaunchError("Attempted to upload file for LocalEnvironment.")
python
wandb/sdk/launch/environment/local_environment.py
42
49
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,092
upload_dir
def upload_dir(self, source: str, destination: str) -> None: """Upload the contents of a directory from the local filesystem to the environment. Arguments: source (str): The source directory. This is ignored. destination (str): The destination directory. This is ignored. """ raise LaunchError("Attempted to upload directory for LocalEnvironment.")
python
wandb/sdk/launch/environment/local_environment.py
51
58
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,093
get_project
def get_project(self) -> str: """Get the project of the local environment. Returns: An empty string. """ raise LaunchError("Attempted to get project for LocalEnvironment.")
python
wandb/sdk/launch/environment/local_environment.py
60
65
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,094
__init__
def __init__( self, environment: AbstractEnvironment, registry: AbstractRegistry, verify: bool = True, ) -> None: """Initialize a builder. Arguments: builder_config: The builder config. registry: The registry to use. verify: Whether to verify the functionality of the builder. Raises: LaunchError: If the builder cannot be intialized or verified. """ raise NotImplementedError
python
wandb/sdk/launch/builder/abstract.py
20
36
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,095
from_config
def from_config( cls, config: dict, environment: AbstractEnvironment, registry: AbstractRegistry, verify: bool = True, ) -> "AbstractBuilder": """Create a builder from a config dictionary. Arguments: config: The config dictionary. environment: The environment to use. registry: The registry to use. verify: Whether to verify the functionality of the builder. login: Whether to login to the registry immediately. Returns: The builder. """ raise NotImplementedError
python
wandb/sdk/launch/builder/abstract.py
40
59
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,096
build_image
def build_image( self, launch_project: LaunchProject, entrypoint: EntryPoint, ) -> str: """Build the image for the given project. Arguments: launch_project: The project to build. build_ctx_path: The path to the build context. Returns: The image name. """ raise NotImplementedError
python
wandb/sdk/launch/builder/abstract.py
62
76
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,097
verify
def verify(self) -> None: """Verify that the builder can be used to build images. Raises: LaunchError: If the builder cannot be used to build images. """ raise NotImplementedError
python
wandb/sdk/launch/builder/abstract.py
79
85
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,098
validate_docker_installation
def validate_docker_installation() -> None: """Verify if Docker is installed on host machine.""" if not find_executable("docker"): raise ExecutionError( "Could not find Docker executable. " "Ensure Docker is installed as per the instructions " "at https://docs.docker.com/install/overview/." )
python
wandb/sdk/launch/builder/build.py
50
57
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,099
get_docker_user
def get_docker_user(launch_project: LaunchProject, runner_type: str) -> Tuple[str, int]: import getpass username = getpass.getuser() if runner_type == "sagemaker" and not launch_project.docker_image: # unless user has provided their own image, sagemaker must run as root but keep the name for workdir etc return username, 0 userid = launch_project.docker_user_id or os.geteuid() return username, userid
python
wandb/sdk/launch/builder/build.py
60
70
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,100
get_current_python_version
def get_current_python_version() -> Tuple[str, str]: full_version = sys.version.split()[0].split(".") major = full_version[0] version = ".".join(full_version[:2]) if len(full_version) >= 2 else major + ".0" return version, major
python
wandb/sdk/launch/builder/build.py
181
185
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }