cli.py 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947
  1. import asyncio
  2. import datetime
  3. import getpass
  4. import json
  5. import logging
  6. import os
  7. import shlex
  8. import shutil
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import textwrap
  13. import time
  14. import traceback
  15. from functools import wraps
  16. from typing import Any, Dict, Optional, Tuple
  17. import click
  18. import yaml
  19. from click.exceptions import ClickException
  20. import wandb
  21. import wandb.errors
  22. import wandb.sdk.verify.verify as wandb_verify
  23. from wandb import Config, Error, env, util, wandb_agent
  24. from wandb.analytics import get_sentry
  25. from wandb.apis import InternalApi, PublicApi
  26. from wandb.apis.public import RunQueue
  27. from wandb.errors.links import url_registry
  28. from wandb.old import core as old_core
  29. from wandb.sdk import wandb_setup, wandb_sweep
  30. from wandb.sdk.artifacts._validators import is_artifact_registry_project
  31. from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
  32. from wandb.sdk.internal.internal_api import Api as SDKInternalApi
  33. from wandb.sdk.launch import utils as launch_utils
  34. from wandb.sdk.launch._launch_add import _launch_add
  35. from wandb.sdk.launch.errors import ExecutionError, LaunchError
  36. from wandb.sdk.launch.sweeps import utils as sweep_utils
  37. from wandb.sdk.launch.sweeps.scheduler import Scheduler
  38. from wandb.sdk.lib import filesystem, settings_file
  39. from wandb.sync import SyncManager, get_run_from_path, get_runs
  40. from .beta import beta
  41. # Send cli logs to wandb/debug-cli.<username>.log by default and fallback to a temp dir.
  42. _wandb_dir = old_core.wandb_dir(env.get_dir())
  43. if not os.path.exists(_wandb_dir):
  44. _wandb_dir = tempfile.gettempdir()
  45. try:
  46. _username = getpass.getuser()
  47. except KeyError:
  48. # getuser() could raise KeyError in restricted environments like
  49. # chroot jails or docker containers. Return user id in these cases.
  50. _username = str(os.getuid())
  51. _wandb_log_path = os.path.join(_wandb_dir, f"debug-cli.{_username}.log")
  52. logging.basicConfig(
  53. filename=_wandb_log_path,
  54. level=logging.INFO,
  55. format="%(asctime)s %(levelname)s %(message)s",
  56. datefmt="%Y-%m-%d %H:%M:%S",
  57. )
  58. logging.basicConfig(stream=sys.stdout, level=logging.INFO)
  59. logger = logging.getLogger("wandb")
  60. _HAS_DOCKER = bool(shutil.which("docker"))
  61. _HAS_NVIDIA_DOCKER = bool(shutil.which("nvidia-docker"))
  62. # Click Contexts
  63. CONTEXT = {"default_map": {}}
  64. RUN_CONTEXT = {
  65. "default_map": {},
  66. "allow_extra_args": True,
  67. "ignore_unknown_options": True,
  68. }
  69. def cli_unsupported(argument):
  70. wandb.termerror(f"Unsupported argument `{argument}`")
  71. sys.exit(1)
  72. class ClickWandbException(ClickException):
  73. def format_message(self):
  74. orig_type = f"{self.orig_type.__module__}.{self.orig_type.__name__}"
  75. if issubclass(self.orig_type, Error):
  76. return click.style(str(self.message), fg="red")
  77. else:
  78. return (
  79. f"An Exception was raised, see {_wandb_log_path} for full"
  80. " traceback.\n"
  81. f"{orig_type}: {self.message}"
  82. )
  83. def parse_service_config(
  84. ctx: Optional[click.Context],
  85. param: Optional[click.Parameter],
  86. value: Optional[Tuple[str, ...]],
  87. ) -> Dict[str, str]:
  88. """Parse service configurations in format serviceName=policy."""
  89. if not value:
  90. return {}
  91. result = {}
  92. for config in value:
  93. if "=" not in config:
  94. raise click.BadParameter(
  95. f"Service must be in format 'serviceName=policy', got '{config}'"
  96. )
  97. service_name, policy = config.split("=", 1)
  98. service_name = service_name.strip()
  99. policy = policy.strip()
  100. if not service_name:
  101. raise click.BadParameter("Service name cannot be empty")
  102. # Simple validation for two policies
  103. if policy not in ["always", "never"]:
  104. raise click.BadParameter(
  105. f"Policy must be 'always' or 'never', got '{policy}'"
  106. )
  107. result[service_name] = policy
  108. return result
  109. def display_error(func):
  110. """Function decorator for catching common errors and re-raising as wandb.Error."""
  111. @wraps(func)
  112. def wrapper(*args, **kwargs):
  113. try:
  114. return func(*args, **kwargs)
  115. except wandb.Error as e:
  116. exc_type, exc_value, exc_traceback = sys.exc_info()
  117. lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
  118. logger.exception("".join(lines))
  119. wandb.termerror(f"Find detailed error logs at: {_wandb_log_path}")
  120. click_exc = ClickWandbException(e)
  121. click_exc.orig_type = exc_type
  122. raise click_exc.with_traceback(sys.exc_info()[2])
  123. return wrapper
  124. _api = None # caching api instance allows patching from unit tests
  125. def _get_cling_api(reset=None):
  126. """Get a reference to the internal api with cling settings."""
  127. global _api
  128. if reset:
  129. _api = None
  130. wandb.teardown()
  131. if _api is None:
  132. # TODO(jhr): make a settings object that is better for non runs.
  133. # only override the necessary setting
  134. wandb_setup.singleton().settings.x_cli_only_mode = True
  135. _api = InternalApi()
  136. return _api
  137. def prompt_for_project(ctx, entity):
  138. """Ask the user for a project, creating one if necessary."""
  139. result = ctx.invoke(projects, entity=entity, display=False)
  140. api = _get_cling_api()
  141. try:
  142. if len(result) == 0:
  143. project = click.prompt("Enter a name for your first project")
  144. # description = editor()
  145. project = api.upsert_project(project, entity=entity)["name"]
  146. else:
  147. project_names = [project["name"] for project in result] + ["Create New"]
  148. wandb.termlog("Which project should we use?")
  149. result = util.prompt_choices(project_names)
  150. if result:
  151. project = result
  152. else:
  153. project = "Create New"
  154. # TODO: check with the server if the project exists
  155. if project == "Create New":
  156. project = click.prompt(
  157. "Enter a name for your new project", value_proc=api.format_project
  158. )
  159. # description = editor()
  160. project = api.upsert_project(project, entity=entity)["name"]
  161. except wandb.errors.CommError as e:
  162. raise ClickException(str(e))
  163. return project
  164. class RunGroup(click.Group):
  165. @display_error
  166. def get_command(self, ctx, cmd_name):
  167. # TODO: check if cmd_name is a file in the current dir and not require `run`?
  168. rv = click.Group.get_command(self, ctx, cmd_name)
  169. if rv is not None:
  170. return rv
  171. return None
  172. @click.command(cls=RunGroup, invoke_without_command=True)
  173. @click.version_option(version=wandb.__version__)
  174. @click.pass_context
  175. def cli(ctx):
  176. if ctx.invoked_subcommand is None:
  177. click.echo(ctx.get_help())
  178. @cli.command(context_settings=CONTEXT, help="List projects", hidden=True)
  179. @click.option(
  180. "--entity",
  181. "-e",
  182. default=None,
  183. envvar=env.ENTITY,
  184. help="The entity to scope the listing to.",
  185. )
  186. @display_error
  187. def projects(entity, display=True):
  188. api = _get_cling_api()
  189. projects = api.list_projects(entity=entity)
  190. if len(projects) == 0:
  191. message = f"No projects found for {entity}"
  192. else:
  193. message = f'Latest projects for "{entity}"'
  194. if display:
  195. click.echo(click.style(message, bold=True))
  196. for project in projects:
  197. click.echo(
  198. "".join(
  199. (
  200. click.style(project["name"], fg="blue", bold=True),
  201. " - ",
  202. str(project["description"] or "").split("\n")[0],
  203. )
  204. )
  205. )
  206. return projects
  207. @cli.command(context_settings=CONTEXT)
  208. @click.argument("key", nargs=-1)
  209. @click.option("--cloud", is_flag=True, help="Login to the cloud instead of local")
  210. @click.option(
  211. "--host", "--base-url", default=None, help="Login to a specific instance of W&B"
  212. )
  213. @click.option(
  214. "--relogin", default=None, is_flag=True, help="Force relogin if already logged in."
  215. )
  216. @click.option(
  217. "--anonymously",
  218. default=False,
  219. hidden=True,
  220. is_flag=True,
  221. help="Log in anonymously",
  222. )
  223. @click.option(
  224. "--verify/--no-verify",
  225. default=False,
  226. is_flag=True,
  227. help="Verify login credentials",
  228. )
  229. @display_error
  230. def login(key, host, cloud, relogin, anonymously, verify, no_offline=False):
  231. """Verify and store your API key for authentication with W&B services.
  232. By default, only store credentials locally without verifying them with W&B.
  233. To verify credentials, set `--verify=True`.
  234. For server deployments (dedicated cloud or customer-managed instances),
  235. specify the host URL using the `--host` flag. You can also set environment
  236. variables `WANDB_BASE_URL` and `WANDB_API_KEY` instead of running
  237. the `login` command with host parameters.
  238. """
  239. # TODO: handle no_offline
  240. if anonymously:
  241. wandb.termwarn(
  242. "The --anonymously parameter has no effect and will be removed"
  243. + " in a future version.",
  244. repeat=False,
  245. )
  246. if host and cloud:
  247. wandb.termerror("Cannot use --host and --cloud together.")
  248. sys.exit(1)
  249. if cloud:
  250. host = "https://api.wandb.ai"
  251. # A change in click or the test harness means key can be none...
  252. key = key[0] if key is not None and len(key) > 0 else None
  253. relogin = True if key or relogin else False
  254. global_settings = wandb_setup.singleton().settings
  255. global_settings.x_cli_only_mode = True
  256. global_settings.x_disable_viewer = relogin and not verify
  257. wandb.login(
  258. force=True,
  259. host=host,
  260. key=key,
  261. relogin=relogin,
  262. verify=verify,
  263. referrer="models",
  264. )
  265. @cli.command(
  266. context_settings=CONTEXT, help="Configure a directory with Weights & Biases"
  267. )
  268. @click.option("--project", "-p", help="The project to use.")
  269. @click.option("--entity", "-e", help="The entity to scope the project to.")
  270. # TODO(jhr): Enable these with settings rework
  271. # @click.option("--setting", "-s", help="enable an arbitrary setting.", multiple=True)
  272. # @click.option('--show', is_flag=True, help="Show settings")
  273. @click.option("--reset", is_flag=True, help="Reset settings")
  274. @click.option(
  275. "--mode",
  276. "-m",
  277. help=' Can be "online", "offline" or "disabled". Defaults to online.',
  278. )
  279. @click.pass_context
  280. @display_error
  281. def init(ctx, project, entity, reset, mode):
  282. # Load settings from environment variables and other normal sources.
  283. global_settings = wandb_setup.singleton().settings
  284. # non-interactive init
  285. if reset or project or entity or mode:
  286. system_settings = global_settings.read_system_settings()
  287. if reset:
  288. system_settings.clear("entity")
  289. system_settings.clear("project")
  290. system_settings.clear("mode")
  291. if entity:
  292. system_settings.set("entity", entity)
  293. if project:
  294. system_settings.set("project", project)
  295. if mode:
  296. system_settings.set("mode", mode)
  297. system_settings.save()
  298. return
  299. if os.path.exists(global_settings.settings_workspace):
  300. click.confirm(
  301. click.style(
  302. "This directory has been configured previously, should we re-configure it?",
  303. bold=True,
  304. ),
  305. abort=True,
  306. )
  307. else:
  308. click.echo(
  309. click.style("Let's setup this directory for W&B!", fg="green", bold=True)
  310. )
  311. api = _get_cling_api()
  312. if api.api_key is None:
  313. ctx.invoke(login)
  314. api = _get_cling_api(reset=True)
  315. viewer = api.viewer()
  316. # Viewer can be `None` in case your API information became invalid, or
  317. # in testing if you switch hosts.
  318. if not viewer:
  319. click.echo(
  320. click.style(
  321. "Your login information seems to be invalid: can you log in again please?",
  322. fg="red",
  323. bold=True,
  324. )
  325. )
  326. ctx.invoke(login)
  327. api = _get_cling_api(reset=True)
  328. # This shouldn't happen.
  329. viewer = api.viewer()
  330. if not viewer:
  331. click.echo(
  332. click.style(
  333. "We're sorry, there was a problem logging you in. "
  334. "Please send us a note at support@wandb.com and tell us how this happened.",
  335. fg="red",
  336. bold=True,
  337. )
  338. )
  339. sys.exit(1)
  340. # At this point we should be logged in successfully.
  341. if len(viewer["teams"]["edges"]) > 1:
  342. team_names = [e["node"]["name"] for e in viewer["teams"]["edges"]] + [
  343. "Manual entry"
  344. ]
  345. wandb.termlog(
  346. "Which team should we use?",
  347. )
  348. result = util.prompt_choices(team_names)
  349. # result can be empty on click
  350. if result:
  351. entity = result
  352. else:
  353. entity = "Manual Entry"
  354. if entity == "Manual Entry":
  355. entity = click.prompt("Enter the name of the team you want to use")
  356. else:
  357. entity = viewer.get("entity") or click.prompt(
  358. "What username or team should we use?"
  359. )
  360. # TODO: this error handling sucks and the output isn't pretty
  361. try:
  362. project = prompt_for_project(ctx, entity)
  363. except ClickWandbException:
  364. raise ClickException(f"Could not find team: {entity}")
  365. system_settings = global_settings.read_system_settings()
  366. system_settings.set("entity", entity)
  367. system_settings.set("project", project)
  368. system_settings.save()
  369. filesystem.mkdir_exists_ok(global_settings.wandb_dir)
  370. with open(os.path.join(global_settings.wandb_dir, ".gitignore"), "w") as file:
  371. file.write("*\n!settings")
  372. click.echo(
  373. click.style("This directory is configured! Next, track a run:\n", fg="green")
  374. + textwrap.dedent(
  375. """\
  376. * In your training script:
  377. {code1}
  378. {code2}
  379. * then `{run}`.
  380. """
  381. ).format(
  382. code1=click.style("import wandb", bold=True),
  383. code2=click.style(f'wandb.init(project="{project}")', bold=True),
  384. run=click.style("python <train.py>", bold=True),
  385. )
  386. )
  387. @cli.command(context_settings=CONTEXT)
  388. @click.pass_context
  389. @click.argument("path", nargs=-1, type=click.Path(exists=True))
  390. @click.option("--view", is_flag=True, default=False, help="View runs", hidden=True)
  391. @click.option("--verbose", is_flag=True, default=False, help="Verbose", hidden=True)
  392. @click.option("--id", "run_id", help="The run you want to upload to.")
  393. @click.option("--project", "-p", help="The project you want to upload to.")
  394. @click.option("--entity", "-e", help="The entity to scope to.")
  395. @click.option(
  396. "--job_type",
  397. "job_type",
  398. help="Specifies the type of run for grouping related runs together.",
  399. )
  400. @click.option(
  401. "--sync-tensorboard/--no-sync-tensorboard",
  402. is_flag=True,
  403. default=None,
  404. help="Stream tfevent files to wandb.",
  405. )
  406. @click.option("--include-globs", help="Comma separated list of globs to include.")
  407. @click.option("--exclude-globs", help="Comma separated list of globs to exclude.")
  408. @click.option(
  409. "--include-online/--no-include-online",
  410. is_flag=True,
  411. default=None,
  412. help="Include online runs",
  413. )
  414. @click.option(
  415. "--include-offline/--no-include-offline",
  416. is_flag=True,
  417. default=None,
  418. help="Include offline runs",
  419. )
  420. @click.option(
  421. "--include-synced/--no-include-synced",
  422. is_flag=True,
  423. default=None,
  424. help="Include synced runs",
  425. )
  426. @click.option(
  427. "--mark-synced/--no-mark-synced",
  428. is_flag=True,
  429. default=True,
  430. help="Mark runs as synced",
  431. )
  432. @click.option("--sync-all", is_flag=True, default=False, help="Sync all runs")
  433. @click.option("--clean", is_flag=True, default=False, help="Delete synced runs")
  434. @click.option(
  435. "--clean-old-hours",
  436. default=24,
  437. help="Delete runs created before this many hours. To be used alongside --clean flag.",
  438. type=int,
  439. )
  440. @click.option(
  441. "--clean-force",
  442. is_flag=True,
  443. default=False,
  444. help="Clean without confirmation prompt.",
  445. )
  446. @click.option("--ignore", hidden=True)
  447. @click.option("--show", default=5, help="Number of runs to show")
  448. @click.option("--append", is_flag=True, default=False, help="Append run")
  449. @click.option("--skip-console", is_flag=True, default=False, help="Skip console logs")
  450. @click.option(
  451. "--replace-tags",
  452. help="Replace tags in the format 'old_tag1=new_tag1,old_tag2=new_tag2'",
  453. )
  454. @display_error
  455. def sync(
  456. ctx,
  457. path=None,
  458. view=None,
  459. verbose=None,
  460. run_id=None,
  461. project=None,
  462. entity=None,
  463. job_type=None, # trace this back to SyncManager
  464. sync_tensorboard=None,
  465. include_globs=None,
  466. exclude_globs=None,
  467. include_online=None,
  468. include_offline=None,
  469. include_synced=None,
  470. mark_synced=None,
  471. sync_all=None,
  472. ignore=None,
  473. show=None,
  474. clean=None,
  475. clean_old_hours=24,
  476. clean_force=None,
  477. append=None,
  478. skip_console=None,
  479. replace_tags=None,
  480. ):
  481. """Synchronize W&B run data to the cloud.
  482. If PATH is provided, sync runs found at the given path. If a path
  483. is not specified, search for `./wandb` first, then search for a
  484. `wandb/` subdirectory.
  485. To sync a specific run:
  486. wandb sync ./wandb/run-20250813_124246-n67z9ude
  487. Or equivalently:
  488. wandb sync ./wandb/run-20250813_124246-n67z9ude/run-n67z9ude.wandb
  489. """
  490. api = _get_cling_api()
  491. if not api.is_authenticated:
  492. wandb.termlog("Login to W&B to sync runs")
  493. ctx.invoke(login, no_offline=True)
  494. api = _get_cling_api(reset=True)
  495. if ignore:
  496. exclude_globs = ignore
  497. if include_globs:
  498. include_globs = include_globs.split(",")
  499. if exclude_globs:
  500. exclude_globs = exclude_globs.split(",")
  501. replace_tags_dict = _parse_sync_replace_tags(replace_tags)
  502. if replace_tags and replace_tags_dict is None:
  503. return # Error already printed by helper function
  504. def _summary():
  505. all_items = get_runs(
  506. include_online=True,
  507. include_offline=True,
  508. include_synced=True,
  509. include_unsynced=True,
  510. )
  511. sync_items = get_runs(
  512. include_online=include_online if include_online is not None else True,
  513. include_offline=include_offline if include_offline is not None else True,
  514. include_synced=include_synced if include_synced is not None else False,
  515. include_unsynced=True,
  516. exclude_globs=exclude_globs,
  517. include_globs=include_globs,
  518. )
  519. synced = []
  520. unsynced = []
  521. for item in all_items:
  522. (synced if item.synced else unsynced).append(item)
  523. if sync_items:
  524. wandb.termlog(f"Number of runs to be synced: {len(sync_items)}")
  525. if show and show < len(sync_items):
  526. wandb.termlog(f"Showing {show} runs to be synced:")
  527. for item in sync_items[: (show or len(sync_items))]:
  528. wandb.termlog(f" {item}")
  529. else:
  530. wandb.termlog("No runs to be synced.")
  531. if synced:
  532. clean_cmd = click.style("wandb sync --clean", fg="yellow")
  533. wandb.termlog(
  534. f"NOTE: use {clean_cmd} to delete {len(synced)} synced runs from local directory."
  535. )
  536. if unsynced:
  537. sync_cmd = click.style("wandb sync --sync-all", fg="yellow")
  538. wandb.termlog(
  539. f"NOTE: use {sync_cmd} to sync {len(unsynced)} unsynced runs from local directory."
  540. )
  541. def _sync_path(_path, _sync_tensorboard):
  542. if run_id and len(_path) > 1:
  543. wandb.termerror("id can only be set for a single run.")
  544. sys.exit(1)
  545. sm = SyncManager(
  546. project=project,
  547. entity=entity,
  548. run_id=run_id,
  549. job_type=job_type,
  550. mark_synced=mark_synced,
  551. app_url=api.app_url,
  552. view=view,
  553. verbose=verbose,
  554. sync_tensorboard=_sync_tensorboard,
  555. log_path=_wandb_log_path,
  556. append=append,
  557. skip_console=skip_console,
  558. replace_tags=replace_tags_dict,
  559. )
  560. for p in _path:
  561. sm.add(p)
  562. sm.start()
  563. while not sm.is_done():
  564. _ = sm.poll()
  565. def _sync_all():
  566. sync_items = get_runs(
  567. include_online=include_online if include_online is not None else True,
  568. include_offline=include_offline if include_offline is not None else True,
  569. include_synced=include_synced if include_synced is not None else False,
  570. include_unsynced=True,
  571. exclude_globs=exclude_globs,
  572. include_globs=include_globs,
  573. )
  574. if not sync_items:
  575. wandb.termerror("Nothing to sync.")
  576. else:
  577. # When syncing run directories, default to not syncing tensorboard
  578. sync_tb = sync_tensorboard if sync_tensorboard is not None else False
  579. _sync_path(sync_items, sync_tb)
  580. def _clean():
  581. if path:
  582. runs = list(map(get_run_from_path, path))
  583. if not clean_force:
  584. click.confirm(
  585. click.style(
  586. f"Are you sure you want to remove {len(runs)} runs?",
  587. bold=True,
  588. ),
  589. abort=True,
  590. )
  591. for run in runs:
  592. shutil.rmtree(run.path)
  593. click.echo(click.style("Success!", fg="green"))
  594. return
  595. runs = get_runs(
  596. include_online=include_online if include_online is not None else True,
  597. include_offline=include_offline if include_offline is not None else True,
  598. include_synced=include_synced if include_synced is not None else True,
  599. include_unsynced=False,
  600. exclude_globs=exclude_globs,
  601. include_globs=include_globs,
  602. )
  603. since = datetime.datetime.now() - datetime.timedelta(hours=clean_old_hours)
  604. old_runs = [run for run in runs if run.datetime < since]
  605. old_runs.sort(key=lambda _run: _run.datetime)
  606. if old_runs:
  607. click.echo(
  608. f"Found {len(runs)} runs, {len(old_runs)} are older than {clean_old_hours} hours"
  609. )
  610. for run in old_runs:
  611. click.echo(run.path)
  612. if not clean_force:
  613. click.confirm(
  614. click.style(
  615. f"Are you sure you want to remove {len(old_runs)} runs?",
  616. bold=True,
  617. ),
  618. abort=True,
  619. )
  620. for run in old_runs:
  621. shutil.rmtree(run.path)
  622. click.echo(click.style("Success!", fg="green"))
  623. else:
  624. click.echo(
  625. click.style(
  626. f"No runs older than {clean_old_hours} hours found", fg="red"
  627. )
  628. )
  629. if sync_all:
  630. _sync_all()
  631. elif clean:
  632. _clean()
  633. elif path:
  634. # When syncing a specific path, default to syncing tensorboard
  635. sync_tb = sync_tensorboard if sync_tensorboard is not None else True
  636. _sync_path(path, sync_tb)
  637. else:
  638. _summary()
  639. def _parse_sync_replace_tags(replace_tags: str) -> Optional[Dict[str, str]]:
  640. """Parse replace_tags string into a dictionary.
  641. Args:
  642. replace_tags: String in format 'old_tag1=new_tag1,old_tag2=new_tag2'
  643. Returns:
  644. Mapping of old tags to new tags, or None if format is invalid
  645. """
  646. if not replace_tags:
  647. return {}
  648. replace_tags_dict = {}
  649. for pair in replace_tags.split(","):
  650. if "=" not in pair:
  651. wandb.termerror(
  652. f"Invalid replace-tags format: {pair}. Use 'old_tag=new_tag' format."
  653. )
  654. return None
  655. old_tag, new_tag = pair.split("=", 1)
  656. replace_tags_dict[old_tag.strip()] = new_tag.strip()
  657. return replace_tags_dict
  658. @cli.command(
  659. context_settings=CONTEXT,
  660. help="Initialize a hyperparameter sweep. Search for hyperparameters that optimizes a cost function of a machine learning model by testing various combinations.",
  661. )
  662. @click.option(
  663. "--project",
  664. "-p",
  665. default=None,
  666. help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled Uncategorized.""",
  667. )
  668. @click.option(
  669. "--entity",
  670. "-e",
  671. default=None,
  672. help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""",
  673. )
  674. @click.option("--controller", is_flag=True, default=False, help="Run local controller")
  675. @click.option("--verbose", is_flag=True, default=False, help="Display verbose output")
  676. @click.option(
  677. "--name",
  678. default=None,
  679. help="The name of the sweep. The sweep ID is used if no name is specified.",
  680. )
  681. @click.option("--program", default=None, help="Set sweep program")
  682. @click.option("--settings", default=None, help="Set sweep settings", hidden=True)
  683. @click.option("--update", default=None, help="Update pending sweep")
  684. @click.option(
  685. "--stop",
  686. is_flag=True,
  687. default=False,
  688. help="Finish a sweep to stop running new runs and let currently running runs finish.",
  689. )
  690. @click.option(
  691. "--cancel",
  692. is_flag=True,
  693. default=False,
  694. help="Cancel a sweep to kill all running runs and stop running new runs.",
  695. )
  696. @click.option(
  697. "--pause",
  698. is_flag=True,
  699. default=False,
  700. help="Pause a sweep to temporarily stop running new runs.",
  701. )
  702. @click.option(
  703. "--resume",
  704. is_flag=True,
  705. default=False,
  706. help="Resume a sweep to continue running new runs.",
  707. )
  708. @click.option(
  709. "--prior_run",
  710. "-R",
  711. "prior_runs",
  712. multiple=True,
  713. default=None,
  714. help="ID of an existing run to add to this sweep",
  715. )
  716. @click.argument("config_yaml_or_sweep_id")
  717. @click.pass_context
  718. @display_error
  719. def sweep(
  720. ctx,
  721. project,
  722. entity,
  723. controller,
  724. verbose,
  725. name,
  726. program,
  727. settings,
  728. update,
  729. stop,
  730. cancel,
  731. pause,
  732. resume,
  733. prior_runs,
  734. config_yaml_or_sweep_id,
  735. ):
  736. state_args = "stop", "cancel", "pause", "resume"
  737. lcls = locals()
  738. is_state_change_command = sum(lcls[k] for k in state_args)
  739. if is_state_change_command > 1:
  740. raise Exception("Only one state flag (stop/cancel/pause/resume) is allowed.")
  741. elif is_state_change_command == 1:
  742. sweep_id = config_yaml_or_sweep_id
  743. api = _get_cling_api()
  744. if not api.is_authenticated:
  745. wandb.termlog("Login to W&B to use the sweep feature")
  746. ctx.invoke(login, no_offline=True)
  747. api = _get_cling_api(reset=True)
  748. parts = dict(entity=entity, project=project, name=sweep_id)
  749. err = sweep_utils.parse_sweep_id(parts)
  750. if err:
  751. wandb.termerror(err)
  752. return
  753. entity = parts.get("entity") or entity
  754. project = parts.get("project") or project
  755. sweep_id = parts.get("name") or sweep_id
  756. state = [s for s in state_args if lcls[s]][0]
  757. ings = {
  758. "stop": "Stopping",
  759. "cancel": "Cancelling",
  760. "pause": "Pausing",
  761. "resume": "Resuming",
  762. }
  763. wandb.termlog(f"{ings[state]} sweep {entity}/{project}/{sweep_id}")
  764. getattr(api, f"{state}_sweep")(sweep_id, entity=entity, project=project)
  765. wandb.termlog("Done.")
  766. return
  767. else:
  768. config_yaml = config_yaml_or_sweep_id
  769. def _parse_settings(settings):
  770. """Parse settings from json or comma separated assignments."""
  771. ret = {}
  772. # TODO(jhr): merge with magic:_parse_magic
  773. if settings.find("=") > 0:
  774. for item in settings.split(","):
  775. kv = item.split("=")
  776. if len(kv) != 2:
  777. wandb.termwarn(
  778. "Unable to parse sweep settings key value pair", repeat=False
  779. )
  780. ret.update(dict([kv]))
  781. return ret
  782. wandb.termwarn("Unable to parse settings parameter", repeat=False)
  783. return ret
  784. api = _get_cling_api()
  785. if not api.is_authenticated:
  786. wandb.termlog("Login to W&B to use the sweep feature")
  787. ctx.invoke(login, no_offline=True)
  788. api = _get_cling_api(reset=True)
  789. sweep_obj_id = None
  790. if update:
  791. parts = dict(entity=entity, project=project, name=update)
  792. err = sweep_utils.parse_sweep_id(parts)
  793. if err:
  794. wandb.termerror(err)
  795. return
  796. entity = parts.get("entity") or entity
  797. project = parts.get("project") or project
  798. sweep_id = parts.get("name") or update
  799. has_project = (project or api.settings("project")) is not None
  800. has_entity = (entity or api.settings("entity")) is not None
  801. termerror_msg = (
  802. "Sweep lookup requires a valid %s, and none was specified. \n"
  803. "Either set a default %s in wandb/settings, or, if invoking \n`wandb sweep` "
  804. "from the command line, specify the full sweep path via: \n\n"
  805. " wandb sweep {username}/{projectname}/{sweepid}\n\n"
  806. )
  807. if not has_entity:
  808. wandb.termerror(termerror_msg % (("entity",) * 2))
  809. return
  810. if not has_project:
  811. wandb.termerror(termerror_msg % (("project",) * 2))
  812. return
  813. found = api.sweep(sweep_id, "{}", entity=entity, project=project)
  814. if not found:
  815. wandb.termerror(f"Could not find sweep {entity}/{project}/{sweep_id}")
  816. return
  817. sweep_obj_id = found["id"]
  818. action = "Updating" if sweep_obj_id else "Creating"
  819. wandb.termlog(f"{action} sweep from: {config_yaml}")
  820. config = sweep_utils.load_sweep_config(config_yaml)
  821. # Set or override parameters
  822. if name:
  823. config["name"] = name
  824. if program:
  825. config["program"] = program
  826. if settings:
  827. settings = _parse_settings(settings)
  828. if settings:
  829. config.setdefault("settings", {})
  830. config["settings"].update(settings)
  831. if controller:
  832. config.setdefault("controller", {})
  833. config["controller"]["type"] = "local"
  834. is_local = config.get("controller", {}).get("type") == "local"
  835. if is_local:
  836. from wandb import controller as wandb_controller
  837. tuner = wandb_controller()
  838. err = tuner._validate(config)
  839. if err:
  840. wandb.termerror(f"Error in sweep file: {err}")
  841. return
  842. env = os.environ
  843. entity = (
  844. entity
  845. or env.get("WANDB_ENTITY")
  846. or config.get("entity")
  847. or api.settings("entity")
  848. )
  849. project = (
  850. project
  851. or env.get("WANDB_PROJECT")
  852. or config.get("project")
  853. or api.settings("project")
  854. or util.auto_project_name(config.get("program"))
  855. )
  856. sweep_id, warnings = api.upsert_sweep(
  857. config,
  858. project=project,
  859. entity=entity,
  860. obj_id=sweep_obj_id,
  861. prior_runs=prior_runs,
  862. )
  863. sweep_utils.handle_sweep_config_violations(warnings)
  864. # Log nicely formatted sweep information
  865. styled_id = click.style(sweep_id, fg="yellow")
  866. wandb.termlog(f"{action} sweep with ID: {styled_id}")
  867. sweep_url = wandb_sweep._get_sweep_url(api, sweep_id)
  868. if sweep_url:
  869. styled_url = click.style(sweep_url, underline=True, fg="blue")
  870. wandb.termlog(f"View sweep at: {styled_url}")
  871. # re-probe entity and project if it was auto-detected by upsert_sweep
  872. entity = entity or env.get("WANDB_ENTITY")
  873. project = project or env.get("WANDB_PROJECT")
  874. if entity and project:
  875. sweep_path = f"{entity}/{project}/{sweep_id}"
  876. elif project:
  877. sweep_path = f"{project}/{sweep_id}"
  878. else:
  879. sweep_path = sweep_id
  880. if sweep_path.find(" ") >= 0:
  881. sweep_path = f"{sweep_path!r}"
  882. styled_path = click.style(f"wandb agent {sweep_path}", fg="yellow")
  883. wandb.termlog(f"Run sweep agent with: {styled_path}")
  884. if controller:
  885. wandb.termlog("Starting wandb controller...")
  886. from wandb import controller as wandb_controller
  887. tuner = wandb_controller(sweep_id)
  888. tuner.run(verbose=verbose)
  889. @cli.command(
  890. context_settings=CONTEXT,
  891. no_args_is_help=True,
  892. help="Run a W&B launch sweep (Experimental).",
  893. )
  894. @click.option(
  895. "--queue",
  896. "-q",
  897. default=None,
  898. help="The name of a queue to push the sweep to",
  899. )
  900. @click.option(
  901. "--project",
  902. "-p",
  903. default=None,
  904. help="Name of the project which the agent will watch. "
  905. "If passed in, will override the project value passed in using a config file",
  906. )
  907. @click.option(
  908. "--entity",
  909. "-e",
  910. default=None,
  911. help="The entity to use. Defaults to current logged-in user",
  912. )
  913. @click.option(
  914. "--resume_id",
  915. "-r",
  916. default=None,
  917. help="Resume a launch sweep by passing an 8-char sweep id. Queue required",
  918. )
  919. @click.option(
  920. "--prior_run",
  921. "-R",
  922. "prior_runs",
  923. multiple=True,
  924. default=None,
  925. help="ID of an existing run to add to this sweep",
  926. )
  927. @click.argument("config", required=False, type=click.Path(exists=True))
  928. @click.pass_context
  929. @display_error
  930. def launch_sweep(
  931. ctx,
  932. project,
  933. entity,
  934. queue,
  935. config,
  936. resume_id,
  937. prior_runs,
  938. ):
  939. api = _get_cling_api()
  940. env = os.environ
  941. if not api.is_authenticated:
  942. wandb.termlog("Login to W&B to use the sweep feature")
  943. ctx.invoke(login, no_offline=True)
  944. api = _get_cling_api(reset=True)
  945. entity = entity or env.get("WANDB_ENTITY") or api.settings("entity")
  946. if entity is None:
  947. wandb.termerror("Must specify entity when using launch")
  948. return
  949. project = project or env.get("WANDB_PROJECT") or api.settings("project")
  950. if project is None:
  951. wandb.termerror("A project must be configured when using launch")
  952. return
  953. # get personal username, not team name or service account, default to entity
  954. author = api.viewer().get("username") or entity
  955. # if not sweep_config XOR resume_id
  956. if not (config or resume_id):
  957. wandb.termerror("'config' and/or 'resume_id' required")
  958. return
  959. parsed_user_config = sweep_utils.load_launch_sweep_config(config)
  960. # Rip special keys out of config, store in scheduler run_config
  961. launch_args: Dict[str, Any] = parsed_user_config.pop("launch", {})
  962. scheduler_args: Dict[str, Any] = parsed_user_config.pop("scheduler", {})
  963. settings: Dict[str, Any] = scheduler_args.pop("settings", {})
  964. scheduler_job: Optional[str] = scheduler_args.get("job")
  965. if scheduler_job:
  966. wandb.termwarn(
  967. "Using a scheduler job for launch sweeps is *experimental* and may change without warning"
  968. )
  969. queue: Optional[str] = queue or launch_args.get("queue")
  970. sweep_config, sweep_obj_id = None, None
  971. if not resume_id:
  972. sweep_config = parsed_user_config
  973. # check method
  974. method = sweep_config.get("method")
  975. if scheduler_job and not method:
  976. sweep_config["method"] = "custom"
  977. elif scheduler_job and method != "custom":
  978. # TODO(gst): Check if using Anaconda2
  979. wandb.termwarn(
  980. "Use 'method': 'custom' in the sweep config when using scheduler jobs, "
  981. "or omit it entirely. For jobs using the wandb optimization engine (WandbScheduler), "
  982. "set the method in the sweep config under scheduler.settings.method "
  983. )
  984. settings["method"] = method
  985. if settings.get("method"):
  986. # assume WandbScheduler, and user is using this right
  987. sweep_config["method"] = settings["method"]
  988. else: # Resuming an existing sweep
  989. found = api.sweep(resume_id, "{}", entity=entity, project=project)
  990. if not found:
  991. wandb.termerror(f"Could not find sweep {entity}/{project}/{resume_id}")
  992. return
  993. if found.get("state") == "RUNNING":
  994. wandb.termerror(
  995. f"Cannot resume sweep {entity}/{project}/{resume_id}, it is already running"
  996. )
  997. return
  998. sweep_obj_id = found["id"]
  999. sweep_config = yaml.safe_load(found["config"])
  1000. wandb.termlog(f"Resuming from existing sweep {entity}/{project}/{resume_id}")
  1001. if len(parsed_user_config.keys()) > 0:
  1002. wandb.termwarn(
  1003. "Sweep parameters loaded from resumed sweep, ignoring provided config"
  1004. )
  1005. prev_scheduler = json.loads(found.get("scheduler") or "{}")
  1006. run_spec = json.loads(prev_scheduler.get("run_spec", "{}"))
  1007. if (
  1008. scheduler_job
  1009. and run_spec.get("job")
  1010. and run_spec.get("job") != scheduler_job
  1011. ):
  1012. wandb.termerror(
  1013. f"Resuming a launch sweep with a different scheduler job is not supported. Job loaded from sweep: {run_spec.get('job')}, job in config: {scheduler_job}"
  1014. )
  1015. return
  1016. prev_scheduler_args, prev_settings = sweep_utils.get_previous_args(run_spec)
  1017. # Passed in scheduler_args and settings override previous
  1018. scheduler_args.update(prev_scheduler_args)
  1019. settings.update(prev_settings)
  1020. if not queue:
  1021. wandb.termerror(
  1022. "Launch-sweeps require setting a 'queue', use --queue option or a 'queue' key in the 'launch' section in the config"
  1023. )
  1024. return
  1025. entrypoint = Scheduler.ENTRYPOINT if not scheduler_job else None
  1026. args = sweep_utils.construct_scheduler_args(
  1027. return_job=scheduler_job is not None,
  1028. sweep_config=sweep_config,
  1029. queue=queue,
  1030. project=project,
  1031. author=author,
  1032. )
  1033. if not args:
  1034. return
  1035. # validate training job existence
  1036. if not sweep_utils.check_job_exists(PublicApi(), sweep_config.get("job")):
  1037. return False
  1038. # validate scheduler job existence, if present
  1039. if not sweep_utils.check_job_exists(PublicApi(), scheduler_job):
  1040. return False
  1041. # Set run overrides for the Scheduler
  1042. overrides = {"run_config": {}}
  1043. if launch_args:
  1044. overrides["run_config"]["launch"] = launch_args
  1045. if scheduler_args:
  1046. overrides["run_config"]["scheduler"] = scheduler_args
  1047. if settings:
  1048. overrides["run_config"]["settings"] = settings
  1049. if scheduler_job:
  1050. overrides["run_config"]["sweep_args"] = args
  1051. else:
  1052. overrides["args"] = args
  1053. # configure scheduler job resource
  1054. resource = scheduler_args.get("resource")
  1055. if resource:
  1056. if resource == "local-process" and scheduler_job:
  1057. wandb.termerror(
  1058. "Scheduler jobs cannot be run with the 'local-process' resource"
  1059. )
  1060. return
  1061. if resource == "local-process" and scheduler_args.get("docker_image"):
  1062. wandb.termerror(
  1063. "Scheduler jobs cannot be run with the 'local-process' resource and a docker image"
  1064. )
  1065. return
  1066. else: # no resource set, default local-process if not scheduler job, else container
  1067. resource = "local-process" if not scheduler_job else "local-container"
  1068. # Launch job spec for the Scheduler
  1069. launch_scheduler_spec = launch_utils.construct_launch_spec(
  1070. uri=Scheduler.PLACEHOLDER_URI,
  1071. api=api,
  1072. name="Scheduler.WANDB_SWEEP_ID",
  1073. project=project,
  1074. entity=entity,
  1075. docker_image=scheduler_args.get("docker_image"),
  1076. resource=resource,
  1077. entry_point=entrypoint,
  1078. resource_args=scheduler_args.get("resource_args", {}),
  1079. repository=launch_args.get("registry", {}).get("url", None),
  1080. job=scheduler_job,
  1081. version=None,
  1082. launch_config={"overrides": overrides},
  1083. run_id="WANDB_SWEEP_ID", # scheduler inits run with sweep_id=run_id
  1084. author=None, # author gets passed into scheduler override args
  1085. )
  1086. launch_scheduler_with_queue = json.dumps(
  1087. {
  1088. "queue": queue,
  1089. "run_queue_project": launch_utils.LAUNCH_DEFAULT_PROJECT,
  1090. "run_spec": json.dumps(launch_scheduler_spec),
  1091. }
  1092. )
  1093. sweep_id, warnings = api.upsert_sweep(
  1094. sweep_config,
  1095. project=project,
  1096. entity=entity,
  1097. obj_id=sweep_obj_id, # if resuming
  1098. launch_scheduler=launch_scheduler_with_queue,
  1099. state="PENDING",
  1100. prior_runs=prior_runs,
  1101. template_variable_values=scheduler_args.get("template_variables", None),
  1102. )
  1103. sweep_utils.handle_sweep_config_violations(warnings)
  1104. # Log nicely formatted sweep information
  1105. styled_id = click.style(sweep_id, fg="yellow")
  1106. wandb.termlog(f"{'Resumed' if resume_id else 'Created'} sweep with ID: {styled_id}")
  1107. sweep_url = wandb_sweep._get_sweep_url(api, sweep_id)
  1108. if sweep_url:
  1109. styled_url = click.style(sweep_url, underline=True, fg="blue")
  1110. wandb.termlog(f"View sweep at: {styled_url}")
  1111. wandb.termlog(f"Scheduler added to launch queue ({queue})")
  1112. @cli.command(help=f"Launch or queue a W&B Job. See {url_registry.url('wandb-launch')}")
  1113. @click.option(
  1114. "--uri",
  1115. "-u",
  1116. metavar="(str)",
  1117. default=None,
  1118. help="Local path or git repo uri to launch. If provided this command will "
  1119. "create a job from the specified uri.",
  1120. )
  1121. @click.option(
  1122. "--job",
  1123. "-j",
  1124. metavar="(str)",
  1125. default=None,
  1126. help="Name of the job to launch. If passed in, launch does not require a uri.",
  1127. )
  1128. @click.option(
  1129. "--entry-point",
  1130. "-E",
  1131. metavar="NAME",
  1132. default=None,
  1133. help="""Entry point within project. [default: main]. If the entry point is not found,
  1134. attempts to run the project file with the specified name as a script,
  1135. using 'python' to run .py files and the default shell (specified by
  1136. environment variable $SHELL) to run .sh files. If passed in, will override the entrypoint value passed in using a config file.""",
  1137. )
  1138. @click.option(
  1139. "--git-version",
  1140. "-g",
  1141. metavar="GIT-VERSION",
  1142. hidden=True,
  1143. help="Version of the project to run, as a Git commit reference for Git projects.",
  1144. )
  1145. @click.option(
  1146. "--build-context",
  1147. metavar="(str)",
  1148. help="Path to the build context within the source code. Defaults to the "
  1149. "root of the source code. Compatible only with -u.",
  1150. )
  1151. @click.option(
  1152. "--job-name",
  1153. "-J",
  1154. metavar="(str)",
  1155. default=None,
  1156. hidden=True,
  1157. help="Name for the job created if the -u,--uri flag is passed in.",
  1158. )
  1159. @click.option(
  1160. "--name",
  1161. envvar="WANDB_NAME",
  1162. help="""Name of the run under which to launch the run. If not
  1163. specified, a random run name will be used to launch run. If passed in, will override the name passed in using a config file.""",
  1164. )
  1165. @click.option(
  1166. "--entity",
  1167. "-e",
  1168. metavar="(str)",
  1169. default=None,
  1170. help="""Name of the target entity which the new run will be sent to. Defaults to using the entity set by local wandb/settings folder.
  1171. If passed in, will override the entity value passed in using a config file.""",
  1172. )
  1173. @click.option(
  1174. "--project",
  1175. "-p",
  1176. metavar="(str)",
  1177. default=None,
  1178. help="""Name of the target project which the new run will be sent to. Defaults to using the project name given by the source uri
  1179. or for github runs, the git repo name. If passed in, will override the project value passed in using a config file.""",
  1180. )
  1181. @click.option(
  1182. "--resource",
  1183. "-r",
  1184. metavar="BACKEND",
  1185. default=None,
  1186. help="""Execution resource to use for run. Supported values: 'local-process', 'local-container', 'kubernetes', 'sagemaker', 'gcp-vertex'.
  1187. This is now a required parameter if pushing to a queue with no resource configuration.
  1188. If passed in, will override the resource value passed in using a config file.""",
  1189. )
  1190. @click.option(
  1191. "--docker-image",
  1192. "-d",
  1193. default=None,
  1194. metavar="DOCKER IMAGE",
  1195. help="""Specific docker image you'd like to use. In the form name:tag.
  1196. If passed in, will override the docker image value passed in using a config file.""",
  1197. )
  1198. @click.option(
  1199. "--base-image",
  1200. "-B",
  1201. default=None,
  1202. metavar="BASE IMAGE",
  1203. help="""Docker image to run job code in. Incompatible with --docker-image.""",
  1204. )
  1205. @click.option(
  1206. "--config",
  1207. "-c",
  1208. metavar="FILE",
  1209. help="""Path to JSON file (must end in '.json') or JSON string which will be passed
  1210. as a launch config. Dictation how the launched run will be configured.""",
  1211. )
  1212. @click.option(
  1213. "--set-var",
  1214. "-v",
  1215. "cli_template_vars",
  1216. default=None,
  1217. multiple=True,
  1218. help="""Set template variable values for queues with allow listing enabled,
  1219. as key-value pairs e.g. `--set-var key1=value1 --set-var key2=value2`""",
  1220. )
  1221. @click.option(
  1222. "--queue",
  1223. "-q",
  1224. is_flag=False,
  1225. flag_value="default",
  1226. default=None,
  1227. help="""Name of run queue to push to. If none, launches single run directly. If supplied without
  1228. an argument (`--queue`), defaults to queue 'default'. Else, if name supplied, specified run queue must exist under the
  1229. project and entity supplied.""",
  1230. )
  1231. @click.option(
  1232. "--async",
  1233. "run_async",
  1234. is_flag=True,
  1235. help="""Flag to run the job asynchronously. Defaults to false, i.e. unless --async is set, wandb launch will wait for
  1236. the job to finish. This option is incompatible with --queue; asynchronous options when running with an agent should be
  1237. set on wandb launch-agent.""",
  1238. )
  1239. @click.option(
  1240. "--resource-args",
  1241. "-R",
  1242. metavar="FILE",
  1243. help="""Path to JSON file (must end in '.json') or JSON string which will be passed
  1244. as resource args to the compute resource. The exact content which should be
  1245. provided is different for each execution backend. See documentation for layout of this file.""",
  1246. )
  1247. @click.option(
  1248. "--build",
  1249. "-b",
  1250. is_flag=True,
  1251. hidden=True,
  1252. help="Flag to build an associated job and push to queue as an image job.",
  1253. )
  1254. @click.option(
  1255. "--repository",
  1256. "-rg",
  1257. is_flag=False,
  1258. default=None,
  1259. hidden=True,
  1260. help="Name of a remote repository. Will be used to push a built image to.",
  1261. )
  1262. # TODO: this is only included for back compat. But we should remove this in the future
  1263. @click.option(
  1264. "--project-queue",
  1265. "-pq",
  1266. default=None,
  1267. hidden=True,
  1268. help="Name of the project containing the queue to push to. If none, defaults to entity level queues.",
  1269. )
  1270. @click.option(
  1271. "--dockerfile",
  1272. "-D",
  1273. default=None,
  1274. help="Path to the Dockerfile used to build the job, relative to the job's root",
  1275. )
  1276. @click.option(
  1277. "--priority",
  1278. "-P",
  1279. default=None,
  1280. type=click.Choice(["critical", "high", "medium", "low"]),
  1281. help="""When --queue is passed, set the priority of the job. Launch jobs with higher priority
  1282. are served first. The order, from highest to lowest priority, is: critical, high, medium, low""",
  1283. )
  1284. @display_error
  1285. def launch(
  1286. uri,
  1287. job,
  1288. entry_point,
  1289. git_version,
  1290. build_context,
  1291. name,
  1292. resource,
  1293. entity,
  1294. project,
  1295. docker_image,
  1296. base_image,
  1297. config,
  1298. cli_template_vars,
  1299. queue,
  1300. run_async,
  1301. resource_args,
  1302. build,
  1303. repository,
  1304. project_queue,
  1305. dockerfile,
  1306. priority,
  1307. job_name,
  1308. ):
  1309. """Start a W&B run from the given URI.
  1310. The URI can bea wandb URI, a GitHub repo uri, or a local path). In the case of a
  1311. wandb URI the arguments used in the original run will be used by default. These
  1312. arguments can be overridden using the args option, or specifying those arguments in
  1313. the config's 'overrides' key, 'args' field as a list of strings.
  1314. Running `wandb launch [URI]` will launch the run directly. To add the run to a
  1315. queue, run `wandb launch [URI] --queue [optional queuename]`.
  1316. """
  1317. logger.info(
  1318. f"=== Launch called with kwargs {locals()} CLI Version: {wandb.__version__}==="
  1319. )
  1320. from wandb.sdk.launch._launch import _launch
  1321. from wandb.sdk.launch.create_job import _create_job
  1322. from wandb.sdk.launch.utils import _is_git_uri
  1323. api = _get_cling_api()
  1324. get_sentry().configure_scope(process_context="launch_cli")
  1325. if run_async and queue is not None:
  1326. raise LaunchError(
  1327. "Cannot use both --async and --queue with wandb launch, see help for details."
  1328. )
  1329. if queue and docker_image and not project:
  1330. raise LaunchError(
  1331. "Cannot use --queue and --docker together without a project. Please specify a project with --project or -p."
  1332. )
  1333. if priority is not None and queue is None:
  1334. raise LaunchError("--priority flag requires --queue to be set")
  1335. if resource_args is not None:
  1336. resource_args = util.load_json_yaml_dict(resource_args)
  1337. if resource_args is None:
  1338. raise LaunchError("Invalid format for resource-args")
  1339. else:
  1340. resource_args = {}
  1341. if entry_point is not None:
  1342. entry_point = shlex.split(entry_point)
  1343. if config is not None:
  1344. config = util.load_json_yaml_dict(config)
  1345. if config is None:
  1346. raise LaunchError("Invalid format for config")
  1347. else:
  1348. config = {}
  1349. resource = resource or config.get("resource")
  1350. if build and queue is None:
  1351. raise LaunchError("Build flag requires a queue to be set")
  1352. try:
  1353. launch_utils.check_logged_in(api)
  1354. except Exception:
  1355. wandb.termerror(f"Error running job: {traceback.format_exc()}")
  1356. run_id = config.get("run_id")
  1357. # If URI was provided, we need to create a job from it.
  1358. if uri:
  1359. if entry_point is None:
  1360. raise LaunchError(
  1361. "Cannot provide a uri without an entry point. Please provide an "
  1362. "entry point with --entry-point or -E."
  1363. )
  1364. if job is not None:
  1365. raise LaunchError("Cannot provide both a uri and a job name.")
  1366. job_type = (
  1367. "git" if _is_git_uri(uri) else "code"
  1368. ) # TODO: Add support for local URIs with git.
  1369. if entity is None:
  1370. entity = launch_utils.get_default_entity(api, config)
  1371. artifact, _, _ = _create_job(
  1372. api,
  1373. job_type,
  1374. uri,
  1375. entrypoint=" ".join(entry_point),
  1376. git_hash=git_version,
  1377. name=job_name,
  1378. project=project,
  1379. base_image=base_image,
  1380. build_context=build_context,
  1381. dockerfile=dockerfile,
  1382. entity=entity,
  1383. )
  1384. if artifact is None:
  1385. raise LaunchError(f"Failed to create job from uri: {uri}")
  1386. job = f"{entity}/{project}/{artifact.name}"
  1387. if dockerfile:
  1388. if "overrides" in config:
  1389. config["overrides"]["dockerfile"] = dockerfile
  1390. else:
  1391. config["overrides"] = {"dockerfile": dockerfile}
  1392. if priority is not None:
  1393. priority_map = {
  1394. "critical": 0,
  1395. "high": 1,
  1396. "medium": 2,
  1397. "low": 3,
  1398. }
  1399. priority = priority_map[priority.lower()]
  1400. template_variables = None
  1401. if cli_template_vars:
  1402. if queue is None:
  1403. raise LaunchError("'--set-var' flag requires queue to be set")
  1404. if entity is None:
  1405. entity = launch_utils.get_default_entity(api, config)
  1406. public_api = PublicApi()
  1407. runqueue = RunQueue(client=public_api.client, name=queue, entity=entity)
  1408. template_variables = launch_utils.fetch_and_validate_template_variables(
  1409. runqueue, cli_template_vars
  1410. )
  1411. if queue is None:
  1412. # direct launch
  1413. try:
  1414. run = asyncio.run(
  1415. _launch(
  1416. api,
  1417. job,
  1418. project=project,
  1419. entity=entity,
  1420. docker_image=docker_image,
  1421. name=name,
  1422. entry_point=entry_point,
  1423. version=git_version,
  1424. resource=resource,
  1425. resource_args=resource_args,
  1426. launch_config=config,
  1427. synchronous=(not run_async),
  1428. run_id=run_id,
  1429. repository=repository,
  1430. )
  1431. )
  1432. if asyncio.run(run.get_status()).state in [
  1433. "failed",
  1434. "stopped",
  1435. "preempted",
  1436. ]:
  1437. wandb.termerror("Launched run exited with non-zero status")
  1438. sys.exit(1)
  1439. except LaunchError as e:
  1440. logger.exception("An error occurred.")
  1441. get_sentry().exception(e)
  1442. sys.exit(e)
  1443. except ExecutionError as e:
  1444. logger.exception("An error occurred.")
  1445. get_sentry().exception(e)
  1446. sys.exit(e)
  1447. except asyncio.CancelledError:
  1448. sys.exit(0)
  1449. else:
  1450. try:
  1451. _launch_add(
  1452. api,
  1453. job,
  1454. config,
  1455. template_variables,
  1456. project,
  1457. entity,
  1458. queue,
  1459. resource,
  1460. entry_point,
  1461. name,
  1462. git_version,
  1463. docker_image,
  1464. project_queue,
  1465. resource_args,
  1466. build=build,
  1467. run_id=run_id,
  1468. repository=repository,
  1469. priority=priority,
  1470. )
  1471. except Exception as e:
  1472. get_sentry().exception(e)
  1473. raise
  1474. @cli.command(
  1475. context_settings=CONTEXT,
  1476. help="Run a W&B launch agent.",
  1477. )
  1478. @click.pass_context
  1479. @click.option(
  1480. "--queue",
  1481. "-q",
  1482. "queues",
  1483. default=None,
  1484. multiple=True,
  1485. help="The name of a queue for the agent to watch. Multiple -q flags supported.",
  1486. )
  1487. @click.option(
  1488. "--entity",
  1489. "-e",
  1490. default=None,
  1491. help="The entity to use. Defaults to current logged-in user",
  1492. )
  1493. @click.option(
  1494. "--log-file",
  1495. "-l",
  1496. default=None,
  1497. help=(
  1498. "Destination for internal agent logs. Use - for stdout. "
  1499. "By default all agents logs will go to debug.log in your wandb/ "
  1500. "subdirectory or WANDB_DIR if set."
  1501. ),
  1502. )
  1503. @click.option(
  1504. "--max-jobs",
  1505. "-j",
  1506. default=None,
  1507. help="The maximum number of launch jobs this agent can run in parallel. Defaults to 1. Set to -1 for no upper limit",
  1508. )
  1509. @click.option(
  1510. "--config", "-c", default=None, help="path to the agent config yaml to use"
  1511. )
  1512. @click.option(
  1513. "--url",
  1514. "-u",
  1515. default=None,
  1516. hidden=True,
  1517. help="a wandb client registration URL, this is generated in the UI",
  1518. )
  1519. @click.option("--verbose", "-v", count=True, help="Display verbose output")
  1520. @display_error
  1521. def launch_agent(
  1522. ctx,
  1523. entity=None,
  1524. queues=None,
  1525. max_jobs=None,
  1526. config=None,
  1527. url=None,
  1528. log_file=None,
  1529. verbose=0,
  1530. ):
  1531. logger.info(
  1532. f"=== Launch-agent called with kwargs {locals()} CLI Version: {wandb.__version__} ==="
  1533. )
  1534. if url is not None:
  1535. raise LaunchError(
  1536. "--url is not supported in this version, upgrade with: pip install -u wandb"
  1537. )
  1538. import wandb.sdk.launch._launch as _launch
  1539. if log_file is not None:
  1540. _launch.set_launch_logfile(log_file)
  1541. api = _get_cling_api()
  1542. get_sentry().configure_scope(process_context="launch_agent")
  1543. agent_config, api = _launch.resolve_agent_config(
  1544. entity, max_jobs, queues, config, verbose
  1545. )
  1546. if len(agent_config.get("queues")) == 0:
  1547. raise LaunchError(
  1548. "To launch an agent please specify a queue or a list of queues in the configuration file or cli."
  1549. )
  1550. launch_utils.check_logged_in(api)
  1551. wandb.termlog("Starting launch agent ✨")
  1552. try:
  1553. _launch.create_and_run_agent(api, agent_config)
  1554. except Exception as e:
  1555. get_sentry().exception(e)
  1556. raise
  1557. @cli.command(context_settings=CONTEXT, help="Run the W&B agent")
  1558. @click.pass_context
  1559. @click.option(
  1560. "--project",
  1561. "-p",
  1562. default=None,
  1563. help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'.""",
  1564. )
  1565. @click.option(
  1566. "--entity",
  1567. "-e",
  1568. default=None,
  1569. help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""",
  1570. )
  1571. @click.option(
  1572. "--count", default=None, type=int, help="The max number of runs for this agent."
  1573. )
  1574. @click.option(
  1575. "--forward-signals",
  1576. "-f",
  1577. is_flag=True,
  1578. default=False,
  1579. help="""Forward signals delivered to the agent (e.g. SIGINT/SIGTERM) to its child runs so they can shut down cleanly.""",
  1580. )
  1581. @click.argument("sweep_id")
  1582. @display_error
  1583. def agent(ctx, project, entity, count, forward_signals, sweep_id):
  1584. api = _get_cling_api()
  1585. if not api.is_authenticated:
  1586. wandb.termlog("Login to W&B to use the sweep agent feature")
  1587. ctx.invoke(login, no_offline=True)
  1588. api = _get_cling_api(reset=True)
  1589. wandb.termlog("Starting wandb agent 🕵️")
  1590. wandb_agent.agent(
  1591. sweep_id,
  1592. entity=entity,
  1593. project=project,
  1594. count=count,
  1595. forward_signals=forward_signals,
  1596. )
  1597. # you can send local commands like so:
  1598. # agent_api.command({'type': 'run', 'program': 'train.py',
  1599. # 'args': ['--max_epochs=10']})
  1600. @cli.command(
  1601. context_settings=RUN_CONTEXT, help="Run a W&B launch sweep scheduler (Experimental)"
  1602. )
  1603. @click.pass_context
  1604. @click.argument("sweep_id")
  1605. @display_error
  1606. def scheduler(
  1607. ctx,
  1608. sweep_id,
  1609. ):
  1610. api = InternalApi()
  1611. if not api.is_authenticated:
  1612. wandb.termlog("Login to W&B to use the sweep scheduler feature")
  1613. ctx.invoke(login, no_offline=True)
  1614. api = InternalApi(reset=True)
  1615. get_sentry().configure_scope(process_context="sweep_scheduler")
  1616. wandb.termlog("Starting a Launch Scheduler 🚀")
  1617. from wandb.sdk.launch.sweeps import load_scheduler
  1618. # TODO(gst): remove this monstrosity
  1619. # Future-proofing hack to pull any kwargs that get passed in through the CLI
  1620. kwargs = {}
  1621. for i, _arg in enumerate(ctx.args):
  1622. if isinstance(_arg, str) and _arg.startswith("--"):
  1623. # convert input kwargs from hyphens to underscores
  1624. _key = _arg[2:].replace("-", "_")
  1625. _args = ctx.args[i + 1]
  1626. if str.isdigit(_args):
  1627. _args = int(_args)
  1628. kwargs[_key] = _args
  1629. try:
  1630. sweep_type = kwargs.get("sweep_type", "wandb")
  1631. _scheduler = load_scheduler(scheduler_type=sweep_type)(
  1632. api,
  1633. sweep_id=sweep_id,
  1634. **kwargs,
  1635. )
  1636. _scheduler.start()
  1637. except Exception as e:
  1638. get_sentry().exception(e)
  1639. raise
  1640. @cli.group(help="Commands for managing and viewing W&B jobs")
  1641. def job() -> None:
  1642. pass
  1643. @job.command("list", help="List jobs in a project")
  1644. @click.option(
  1645. "--project",
  1646. "-p",
  1647. envvar=env.PROJECT,
  1648. help="The project you want to list jobs from.",
  1649. )
  1650. @click.option(
  1651. "--entity",
  1652. "-e",
  1653. default="models",
  1654. envvar=env.ENTITY,
  1655. help="The entity the jobs belong to",
  1656. )
  1657. def _list(project, entity):
  1658. wandb.termlog(f"Listing jobs in {entity}/{project}")
  1659. public_api = PublicApi()
  1660. try:
  1661. jobs = public_api.list_jobs(entity=entity, project=project)
  1662. except wandb.errors.CommError as e:
  1663. wandb.termerror(f"{e}")
  1664. return
  1665. if len(jobs) == 0:
  1666. wandb.termlog("No jobs found")
  1667. return
  1668. for job in jobs:
  1669. aliases = []
  1670. if len(job["edges"]) == 0:
  1671. # deleted?
  1672. continue
  1673. name = job["edges"][0]["node"]["artifactSequence"]["name"]
  1674. for version in job["edges"]:
  1675. aliases += [x["alias"] for x in version["node"]["aliases"]]
  1676. # only list the most recent 10 job versions
  1677. aliases_str = ",".join(aliases[::-1])
  1678. wandb.termlog(f"{name} -- versions ({len(aliases)}): {aliases_str}")
  1679. @job.command(
  1680. help="Describe a launch job. Provide the launch job in the form of: entity/project/job-name:alias-or-version"
  1681. )
  1682. @click.argument("job")
  1683. def describe(job):
  1684. public_api = PublicApi()
  1685. try:
  1686. job = public_api.job(name=job)
  1687. except wandb.errors.CommError as e:
  1688. wandb.termerror(f"{e}")
  1689. return
  1690. for key in job._job_info:
  1691. if key.startswith("_"):
  1692. continue
  1693. wandb.termlog(f"{key}: {job._job_info[key]}")
  1694. @job.command(
  1695. no_args_is_help=True,
  1696. )
  1697. @click.option(
  1698. "--project",
  1699. "-p",
  1700. envvar=env.PROJECT,
  1701. help="The project you want to list jobs from.",
  1702. )
  1703. @click.option(
  1704. "--entity",
  1705. "-e",
  1706. envvar=env.ENTITY,
  1707. help="The entity the jobs belong to",
  1708. )
  1709. @click.option(
  1710. "--name",
  1711. "-n",
  1712. help="Name for the job",
  1713. )
  1714. @click.option(
  1715. "--description",
  1716. "-d",
  1717. help="Description for the job",
  1718. )
  1719. @click.option(
  1720. "--alias",
  1721. "-a",
  1722. "aliases",
  1723. help="Alias for the job",
  1724. multiple=True,
  1725. default=tuple(),
  1726. )
  1727. @click.option(
  1728. "--entry-point",
  1729. "-E",
  1730. "entrypoint",
  1731. help="Entrypoint to the script, including an executable and an entrypoint "
  1732. "file. Required for code or repo jobs. If --build-context is provided, "
  1733. "paths in the entrypoint command will be relative to the build context.",
  1734. )
  1735. @click.option(
  1736. "--git-hash",
  1737. "-g",
  1738. "git_hash",
  1739. type=str,
  1740. help="Commit reference to use as the source for git jobs",
  1741. )
  1742. @click.option(
  1743. "--runtime",
  1744. "-r",
  1745. type=str,
  1746. help="Python runtime to execute the job",
  1747. )
  1748. @click.option(
  1749. "--build-context",
  1750. "-b",
  1751. type=str,
  1752. help="Path to the build context from the root of the job source code. If "
  1753. "provided, this is used as the base path for the Dockerfile and entrypoint.",
  1754. )
  1755. @click.option(
  1756. "--base-image",
  1757. "-B",
  1758. type=str,
  1759. help="Base image to use for the job. Incompatible with image jobs.",
  1760. )
  1761. @click.option(
  1762. "--dockerfile",
  1763. "-D",
  1764. type=str,
  1765. help="Path to the Dockerfile for the job. If --build-context is provided, "
  1766. "the Dockerfile path will be relative to the build context.",
  1767. )
  1768. @click.argument(
  1769. "job_type",
  1770. type=click.Choice(("git", "code", "image")),
  1771. )
  1772. @click.option(
  1773. "--service",
  1774. "-s",
  1775. "services",
  1776. multiple=True,
  1777. callback=parse_service_config,
  1778. help="Service configurations in format serviceName=policy. Valid policies: always, never",
  1779. hidden=True,
  1780. )
  1781. @click.option(
  1782. "--schema",
  1783. type=str,
  1784. help="Path to the schema file for the job.",
  1785. hidden=True,
  1786. )
  1787. @click.argument("path")
  1788. def create(
  1789. path,
  1790. project,
  1791. entity,
  1792. name,
  1793. job_type,
  1794. description,
  1795. aliases,
  1796. entrypoint,
  1797. git_hash,
  1798. runtime,
  1799. build_context,
  1800. base_image,
  1801. dockerfile,
  1802. services,
  1803. schema,
  1804. ):
  1805. """Create a job from a source, without a wandb run.
  1806. Jobs can be of three types, git, code, or image.
  1807. git: A git source, with an entrypoint either in the path or provided explicitly pointing to the main python executable.
  1808. code: A code path, containing a requirements.txt file.
  1809. image: A docker image.
  1810. """
  1811. from wandb.sdk.launch.create_job import _create_job
  1812. api = _get_cling_api()
  1813. get_sentry().configure_scope(process_context="job_create")
  1814. entity = entity or os.getenv("WANDB_ENTITY") or api.default_entity
  1815. if not entity:
  1816. wandb.termerror("No entity provided, use --entity or set WANDB_ENTITY")
  1817. return
  1818. project = project or os.getenv("WANDB_PROJECT")
  1819. if not project:
  1820. wandb.termerror("No project provided, use --project or set WANDB_PROJECT")
  1821. return
  1822. if entrypoint is None and job_type in ["git", "code"]:
  1823. wandb.termwarn(
  1824. f"No entrypoint provided for {job_type} job, defaulting to main.py"
  1825. )
  1826. entrypoint = "main.py"
  1827. if job_type == "image" and base_image:
  1828. wandb.termerror("Cannot provide --base-image/-B for an `image` job")
  1829. return
  1830. if schema:
  1831. schema_dict = util.load_json_yaml_dict(schema)
  1832. if schema_dict is None:
  1833. wandb.termerror(f"Invalid format for schema file: {schema}")
  1834. return
  1835. artifact, action, aliases = _create_job(
  1836. api=api,
  1837. path=path,
  1838. entity=entity,
  1839. project=project,
  1840. name=name,
  1841. job_type=job_type,
  1842. description=description,
  1843. aliases=list(aliases),
  1844. entrypoint=entrypoint,
  1845. git_hash=git_hash,
  1846. runtime=runtime,
  1847. build_context=build_context,
  1848. base_image=base_image,
  1849. dockerfile=dockerfile,
  1850. services=services,
  1851. schema=schema_dict if schema else None,
  1852. )
  1853. if not artifact:
  1854. wandb.termerror("Job creation failed")
  1855. return
  1856. artifact_path = f"{entity}/{project}/{artifact.name}"
  1857. msg = f"{action} job: {click.style(artifact_path, fg='yellow')}"
  1858. if len(aliases) == 1:
  1859. alias_str = click.style(aliases[0], fg="yellow")
  1860. msg += f", with alias: {alias_str}"
  1861. elif len(aliases) > 1:
  1862. alias_str = click.style(", ".join(aliases), fg="yellow")
  1863. msg += f", with aliases: {alias_str}"
  1864. wandb.termlog(msg)
  1865. web_url = util.app_url(api.settings().get("base_url"))
  1866. url = click.style(f"{web_url}/{entity}/{project}/jobs", underline=True)
  1867. wandb.termlog(f"View all jobs in project '{project}' here: {url}\n")
  1868. @cli.command(context_settings=CONTEXT, help="Run the W&B local sweep controller")
  1869. @click.option("--verbose", is_flag=True, default=False, help="Display verbose output")
  1870. @click.argument("sweep_id")
  1871. @display_error
  1872. def controller(verbose, sweep_id):
  1873. click.echo("Starting wandb controller...")
  1874. from wandb import controller as wandb_controller
  1875. tuner = wandb_controller(sweep_id)
  1876. tuner.run(verbose=verbose)
  1877. @cli.command(context_settings=RUN_CONTEXT, name="docker-run")
  1878. @click.pass_context
  1879. @click.argument("docker_run_args", nargs=-1)
  1880. def docker_run(ctx, docker_run_args):
  1881. """Wrap `docker run` and adds WANDB_API_KEY and WANDB_DOCKER environment variables.
  1882. This will also set the runtime to nvidia if the nvidia-docker executable is present
  1883. on the system and --runtime wasn't set.
  1884. See `docker run --help` for more details.
  1885. """
  1886. import wandb.docker
  1887. api = InternalApi()
  1888. args = list(docker_run_args)
  1889. if len(args) > 0 and args[0] == "run":
  1890. args.pop(0)
  1891. if len([a for a in args if a.startswith("--runtime")]) == 0 and _HAS_NVIDIA_DOCKER:
  1892. args = ["--runtime", "nvidia"] + args
  1893. # TODO: image_from_docker_args uses heuristics to find the docker image arg, there are likely cases
  1894. # where this won't work
  1895. image = util.image_from_docker_args(args)
  1896. resolved_image = None
  1897. if image:
  1898. resolved_image = wandb.docker.image_id(image)
  1899. if resolved_image:
  1900. args = ["-e", f"WANDB_DOCKER={resolved_image}"] + args
  1901. else:
  1902. wandb.termlog(
  1903. "Couldn't detect image argument, running command without the WANDB_DOCKER env variable"
  1904. )
  1905. if api.api_key:
  1906. args = ["-e", f"WANDB_API_KEY={api.api_key}"] + args
  1907. else:
  1908. wandb.termlog(
  1909. "Not logged in, run `wandb login` from the host machine to enable result logging"
  1910. )
  1911. subprocess.call(["docker", "run"] + args)
  1912. @cli.command(context_settings=RUN_CONTEXT)
  1913. @click.pass_context
  1914. @click.argument("docker_run_args", nargs=-1)
  1915. @click.argument("docker_image", required=False)
  1916. @click.option(
  1917. "--nvidia/--no-nvidia",
  1918. default=_HAS_NVIDIA_DOCKER,
  1919. help="Use the nvidia runtime, defaults to nvidia if nvidia-docker is present",
  1920. )
  1921. @click.option(
  1922. "--digest", is_flag=True, default=False, help="Output the image digest and exit"
  1923. )
  1924. @click.option(
  1925. "--jupyter/--no-jupyter", default=False, help="Run jupyter lab in the container"
  1926. )
  1927. @click.option(
  1928. "--dir", default="/app", help="Which directory to mount the code in the container"
  1929. )
  1930. @click.option("--no-dir", is_flag=True, help="Don't mount the current directory")
  1931. @click.option(
  1932. "--shell", default="/bin/bash", help="The shell to start the container with"
  1933. )
  1934. @click.option("--port", default="8888", help="The host port to bind jupyter on")
  1935. @click.option("--cmd", help="The command to run in the container")
  1936. @click.option(
  1937. "--no-tty", is_flag=True, default=False, help="Run the command without a tty"
  1938. )
  1939. @display_error
  1940. def docker(
  1941. ctx,
  1942. docker_run_args,
  1943. docker_image,
  1944. nvidia,
  1945. digest,
  1946. jupyter,
  1947. dir,
  1948. no_dir,
  1949. shell,
  1950. port,
  1951. cmd,
  1952. no_tty,
  1953. ):
  1954. """Run your code in a docker container.
  1955. W&B docker lets you run your code in a docker image ensuring wandb is configured. It
  1956. adds the WANDB_DOCKER and WANDB_API_KEY environment variables to your container and
  1957. mounts the current directory in /app by default. You can pass additional args which
  1958. will be added to `docker run` before the image name is declared, we'll choose a
  1959. default image for you if one isn't passed:
  1960. ```sh
  1961. wandb docker -v /mnt/dataset:/app/data
  1962. wandb docker gcr.io/kubeflow-images-public/tensorflow-1.12.0-notebook-cpu:v0.4.0 --jupyter
  1963. wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py --epochs=5"
  1964. ```
  1965. By default, we override the entrypoint to check for the existence of wandb and
  1966. install it if not present. If you pass the --jupyter flag we will ensure jupyter is
  1967. installed and start jupyter lab on port 8888. If we detect nvidia-docker on your
  1968. system we will use the nvidia runtime. If you just want wandb to set environment
  1969. variable to an existing docker run command, see the wandb docker-run command.
  1970. """
  1971. api = InternalApi()
  1972. if not _HAS_DOCKER:
  1973. raise ClickException("Docker not installed, install it from https://docker.com")
  1974. import wandb.docker
  1975. args = list(docker_run_args)
  1976. image = docker_image or ""
  1977. # remove run for users used to nvidia-docker
  1978. if len(args) > 0 and args[0] == "run":
  1979. args.pop(0)
  1980. if image == "" and len(args) > 0:
  1981. image = args.pop(0)
  1982. # If the user adds docker args without specifying an image (should be rare)
  1983. if not util.docker_image_regex(image.split("@")[0]):
  1984. if image:
  1985. args = args + [image]
  1986. image = wandb.docker.default_image(gpu=nvidia)
  1987. subprocess.call(["docker", "pull", image])
  1988. _, repo_name, tag = wandb.docker.parse(image)
  1989. resolved_image = wandb.docker.image_id(image)
  1990. if resolved_image is None:
  1991. raise ClickException(
  1992. f"Couldn't find image locally or in a registry, try running `docker pull {image}`"
  1993. )
  1994. if digest:
  1995. sys.stdout.write(resolved_image)
  1996. exit(0)
  1997. existing = wandb.docker.shell(["ps", "-f", f"ancestor={resolved_image}", "-q"])
  1998. if existing:
  1999. if click.confirm(
  2000. "Found running container with the same image, do you want to attach?"
  2001. ):
  2002. subprocess.call(["docker", "attach", existing.split("\n")[0]])
  2003. exit(0)
  2004. cwd = os.getcwd()
  2005. command = [
  2006. "docker",
  2007. "run",
  2008. "-e",
  2009. "LANG=C.UTF-8",
  2010. "-e",
  2011. f"WANDB_DOCKER={resolved_image}",
  2012. "--ipc=host",
  2013. "-v",
  2014. wandb.docker.entrypoint + ":/wandb-entrypoint.sh",
  2015. "--entrypoint",
  2016. "/wandb-entrypoint.sh",
  2017. ]
  2018. if nvidia:
  2019. command.extend(["--runtime", "nvidia"])
  2020. if not no_dir:
  2021. # TODO: We should default to the working directory if defined
  2022. command.extend(["-v", cwd + ":" + dir, "-w", dir])
  2023. if api.api_key:
  2024. command.extend(["-e", f"WANDB_API_KEY={api.api_key}"])
  2025. else:
  2026. wandb.termlog(
  2027. "Couldn't find WANDB_API_KEY, run `wandb login` to enable streaming metrics"
  2028. )
  2029. if jupyter:
  2030. command.extend(["-e", "WANDB_ENSURE_JUPYTER=1", "-p", port + ":8888"])
  2031. no_tty = True
  2032. cmd = f"jupyter lab --no-browser --ip=0.0.0.0 --allow-root --NotebookApp.token= --notebook-dir {dir}"
  2033. command.extend(args)
  2034. if no_tty:
  2035. command.extend([image, shell, "-c", cmd])
  2036. else:
  2037. if cmd:
  2038. command.extend(["-e", f"WANDB_COMMAND={cmd}"])
  2039. command.extend(["-it", image, shell])
  2040. wandb.termlog("Launching docker container \U0001f6a2")
  2041. subprocess.call(command)
  2042. @cli.command(
  2043. context_settings=RUN_CONTEXT,
  2044. help="Start a local W&B container (deprecated, see wandb server --help)",
  2045. hidden=True,
  2046. )
  2047. @click.pass_context
  2048. @click.option("--port", "-p", default="8080", help="The host port to bind W&B local on")
  2049. @click.option(
  2050. "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local"
  2051. )
  2052. @click.option(
  2053. "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode"
  2054. )
  2055. @click.option(
  2056. "--upgrade", is_flag=True, default=False, help="Upgrade to the most recent version"
  2057. )
  2058. @click.option(
  2059. "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True
  2060. )
  2061. @display_error
  2062. def local(ctx, *args, **kwargs):
  2063. wandb.termwarn("`wandb local` has been replaced with `wandb server start`.")
  2064. ctx.invoke(start, *args, **kwargs)
  2065. @cli.group(help="Commands for operating a local W&B server")
  2066. def server():
  2067. pass
  2068. @server.command(context_settings=RUN_CONTEXT, help="Start a local W&B server")
  2069. @click.pass_context
  2070. @click.option(
  2071. "--port", "-p", default="8080", help="The host port to bind W&B server on"
  2072. )
  2073. @click.option(
  2074. "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local"
  2075. )
  2076. @click.option(
  2077. "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode"
  2078. )
  2079. @click.option(
  2080. "--upgrade",
  2081. is_flag=True,
  2082. default=False,
  2083. help="Upgrade to the most recent version",
  2084. hidden=True,
  2085. )
  2086. @click.option(
  2087. "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True
  2088. )
  2089. @display_error
  2090. def start(ctx, port, env, daemon, upgrade, edge):
  2091. api = InternalApi()
  2092. if not _HAS_DOCKER:
  2093. raise ClickException("Docker not installed, install it from https://docker.com")
  2094. import wandb.docker
  2095. local_image_sha = wandb.docker.image_id("wandb/local").split("wandb/local")[-1]
  2096. registry_image_sha = wandb.docker.image_id_from_registry("wandb/local").split(
  2097. "wandb/local"
  2098. )[-1]
  2099. if local_image_sha != registry_image_sha:
  2100. if upgrade:
  2101. subprocess.call(["docker", "pull", "wandb/local"])
  2102. else:
  2103. wandb.termlog(
  2104. "A new version of the W&B server is available, upgrade by calling `wandb server start --upgrade`"
  2105. )
  2106. running = subprocess.check_output(
  2107. ["docker", "ps", "--filter", "name=^wandb-local$", "--format", "{{.ID}}"]
  2108. )
  2109. if running != b"":
  2110. if upgrade:
  2111. subprocess.call(["docker", "stop", "wandb-local"])
  2112. else:
  2113. wandb.termerror(
  2114. "A container named wandb-local is already running, run `docker stop wandb-local` if you want to start a new instance"
  2115. )
  2116. exit(1)
  2117. image = "docker.pkg.github.com/wandb/core/local" if edge else "wandb/local"
  2118. username = getpass.getuser()
  2119. env_vars = ["-e", f"LOCAL_USERNAME={username}"]
  2120. for e in env:
  2121. env_vars.append("-e")
  2122. env_vars.append(e)
  2123. command = [
  2124. "docker",
  2125. "run",
  2126. "--rm",
  2127. "-v",
  2128. "wandb:/vol",
  2129. "-p",
  2130. port + ":8080",
  2131. "--name",
  2132. "wandb-local",
  2133. ] + env_vars
  2134. host = f"http://localhost:{port}"
  2135. system_settings = wandb_setup.singleton().settings.read_system_settings()
  2136. system_settings.set("base_url", host, globally=True)
  2137. try:
  2138. system_settings.save()
  2139. except settings_file.SaveSettingsError as e:
  2140. msg = "Failed to update base_url setting"
  2141. logger.exception(msg)
  2142. wandb.termerror(f"{msg}: {e}")
  2143. if daemon:
  2144. command += ["-d"]
  2145. command += [image]
  2146. # DEVNULL is only in py3
  2147. try:
  2148. from subprocess import DEVNULL
  2149. except ImportError:
  2150. DEVNULL = open(os.devnull, "wb") # noqa: N806
  2151. code = subprocess.call(command, stdout=DEVNULL)
  2152. if daemon:
  2153. if code != 0:
  2154. wandb.termerror(
  2155. "Failed to launch the W&B server container, see the above error."
  2156. )
  2157. exit(1)
  2158. else:
  2159. wandb.termlog(f"W&B server started at http://localhost:{port} \U0001f680")
  2160. wandb.termlog("You can stop the server by running `wandb server stop`")
  2161. if not api.api_key:
  2162. # Let the server start before potentially launching a browser
  2163. time.sleep(2)
  2164. ctx.invoke(login, host=host)
  2165. @server.command(context_settings=RUN_CONTEXT, help="Stop a local W&B server")
  2166. def stop():
  2167. if not _HAS_DOCKER:
  2168. raise ClickException("Docker not installed, install it from https://docker.com")
  2169. subprocess.call(["docker", "stop", "wandb-local"])
  2170. @cli.group(help="Commands for interacting with artifacts")
  2171. def artifact():
  2172. pass
  2173. @artifact.command(context_settings=CONTEXT, help="Upload an artifact to wandb")
  2174. @click.argument("path")
  2175. @click.option(
  2176. "--name", "-n", help="The name of the artifact to push: project/artifact_name"
  2177. )
  2178. @click.option("--description", "-d", help="A description of this artifact")
  2179. @click.option("--type", "-t", default="dataset", help="The type of the artifact")
  2180. @click.option(
  2181. "--alias",
  2182. "-a",
  2183. default=["latest"],
  2184. multiple=True,
  2185. help="An alias to apply to this artifact",
  2186. )
  2187. @click.option("--id", "run_id", help="The run you want to upload to.")
  2188. @click.option(
  2189. "--resume",
  2190. is_flag=True,
  2191. default=None,
  2192. help="Resume the last run from your current directory.",
  2193. )
  2194. @click.option(
  2195. "--skip_cache",
  2196. is_flag=True,
  2197. default=False,
  2198. help="Skip caching while uploading artifact files.",
  2199. )
  2200. @click.option(
  2201. "--policy",
  2202. default="mutable",
  2203. type=click.Choice(["mutable", "immutable"]),
  2204. help="Set the storage policy while uploading artifact files.",
  2205. )
  2206. @display_error
  2207. def put(
  2208. path,
  2209. name,
  2210. description,
  2211. type,
  2212. alias,
  2213. run_id,
  2214. resume,
  2215. skip_cache,
  2216. policy,
  2217. ):
  2218. if name is None:
  2219. name = os.path.basename(path)
  2220. public_api = PublicApi()
  2221. entity, project, artifact_name = public_api._parse_artifact_path(name)
  2222. if project is None:
  2223. project = click.prompt("Enter the name of the project you want to use")
  2224. artifact = wandb.Artifact(name=artifact_name, type=type, description=description)
  2225. artifact_path = f"{entity}/{project}/{artifact_name}:{alias[0]}"
  2226. if os.path.isdir(path):
  2227. wandb.termlog(f'Uploading directory {path} to: "{artifact_path}" ({type})')
  2228. artifact.add_dir(path, skip_cache=skip_cache, policy=policy)
  2229. elif os.path.isfile(path):
  2230. wandb.termlog(f'Uploading file {path} to: "{artifact_path}" ({type})')
  2231. artifact.add_file(path, skip_cache=skip_cache, policy=policy)
  2232. elif "://" in path:
  2233. wandb.termlog(
  2234. f'Logging reference artifact from {path} to: "{artifact_path}" ({type})'
  2235. )
  2236. artifact.add_reference(path)
  2237. else:
  2238. raise ClickException("Path argument must be a file or directory")
  2239. with wandb.init(
  2240. entity=entity,
  2241. project=project,
  2242. config={"path": path},
  2243. job_type="cli_put",
  2244. id=run_id,
  2245. resume=resume,
  2246. ) as run:
  2247. run.log_artifact(artifact, aliases=alias)
  2248. artifact.wait()
  2249. wandb.termlog(
  2250. "Artifact uploaded, use this artifact in a run by adding:\n", prefix=False
  2251. )
  2252. wandb.termlog(
  2253. f' artifact = run.use_artifact("{artifact.source_qualified_name}")\n',
  2254. prefix=False,
  2255. )
  2256. @artifact.command(context_settings=CONTEXT, help="Download an artifact from wandb")
  2257. @click.argument("path")
  2258. @click.option("--root", help="The directory you want to download the artifact to")
  2259. @click.option("--type", help="The type of artifact you are downloading")
  2260. @display_error
  2261. def get(path, root, type):
  2262. public_api = PublicApi()
  2263. entity, project, artifact_name = public_api._parse_artifact_path(path)
  2264. if project is None:
  2265. project = click.prompt("Enter the name of the project you want to use")
  2266. try:
  2267. artifact_parts = artifact_name.split(":")
  2268. if len(artifact_parts) > 1:
  2269. version = artifact_parts[1]
  2270. artifact_name = artifact_parts[0]
  2271. else:
  2272. version = "latest"
  2273. if is_artifact_registry_project(project):
  2274. organization = path.split("/")[0] if path.count("/") == 2 else ""
  2275. # set entity to match the settings since in above code it was potentially set to an org
  2276. settings_entity = public_api.settings["entity"] or public_api.default_entity
  2277. # Registry artifacts are under the org entity. Because we offer a shorthand and alias for this path,
  2278. # we need to fetch the org entity to for the user behind the scenes.
  2279. entity = SDKInternalApi()._resolve_org_entity_name(
  2280. entity=settings_entity, organization=organization
  2281. )
  2282. full_path = f"{entity}/{project}/{artifact_name}:{version}"
  2283. wandb.termlog(
  2284. "Downloading {type} artifact {full_path}".format(
  2285. type=type or "dataset", full_path=full_path
  2286. )
  2287. )
  2288. artifact = public_api.artifact(full_path, type=type)
  2289. path = artifact.download(root=root)
  2290. wandb.termlog(f"Artifact downloaded to {path}")
  2291. except ValueError:
  2292. raise ClickException("Unable to download artifact")
  2293. @artifact.command(
  2294. context_settings=CONTEXT, help="List all artifacts in a wandb project"
  2295. )
  2296. @click.argument("path")
  2297. @click.option("--type", "-t", help="The type of artifacts to list")
  2298. @display_error
  2299. def ls(path, type):
  2300. public_api = PublicApi()
  2301. if type is not None:
  2302. types = [public_api.artifact_type(type, path)]
  2303. else:
  2304. types = public_api.artifact_types(path)
  2305. for kind in types:
  2306. for collection in kind.collections():
  2307. versions = public_api.artifact_versions(
  2308. kind.type,
  2309. "/".join([kind.entity, kind.project, collection.name]),
  2310. per_page=1,
  2311. )
  2312. if (latest := next(versions, None)) is not None:
  2313. wandb.termlog(
  2314. f"{kind.type:<15s}{latest.updated_at:<15s}{util.to_human_size(latest.size):>15s} {latest.name:<20s}"
  2315. )
  2316. else:
  2317. # Artifact collection exists but has no versions. This can happen when:
  2318. # 1. A collection was just created but no artifacts have been logged yet.
  2319. # 2. All versions within an artifact collection were deleted.
  2320. wandb.termlog(
  2321. f"{kind.type:<15s}{'N/A':<15s}{'0 B':>15s} {collection.name:<20s} (no versions)"
  2322. )
  2323. @artifact.group(help="Commands for interacting with the artifact cache")
  2324. def cache():
  2325. pass
  2326. @cache.command(
  2327. context_settings=CONTEXT,
  2328. help="Clean up less frequently used files from the artifacts cache",
  2329. )
  2330. @click.argument("target_size")
  2331. @click.option("--remove-temp/--no-remove-temp", default=False, help="Remove temp files")
  2332. @display_error
  2333. def cleanup(target_size, remove_temp):
  2334. target_size = util.from_human_size(target_size)
  2335. cache = get_artifact_file_cache()
  2336. reclaimed_bytes = cache.cleanup(target_size, remove_temp)
  2337. wandb.termlog(f"Reclaimed {util.to_human_size(reclaimed_bytes)} of space")
  2338. @cli.command(context_settings=CONTEXT, help="Pull files from Weights & Biases")
  2339. @click.argument("run", envvar=env.RUN_ID)
  2340. @click.option(
  2341. "--project", "-p", envvar=env.PROJECT, help="The project you want to download."
  2342. )
  2343. @click.option(
  2344. "--entity",
  2345. "-e",
  2346. default="models",
  2347. envvar=env.ENTITY,
  2348. help="The entity to scope the listing to.",
  2349. )
  2350. @display_error
  2351. def pull(run, project, entity):
  2352. api = InternalApi()
  2353. project, run = api.parse_slug(run, project=project)
  2354. urls = api.download_urls(project, run=run, entity=entity)
  2355. if len(urls) == 0:
  2356. raise ClickException("Run has no files")
  2357. click.echo(f"Downloading: {click.style(project, bold=True)}/{run}")
  2358. for name in urls:
  2359. if api.file_current(name, urls[name]["md5"]):
  2360. click.echo(f"File {name} is up to date")
  2361. else:
  2362. length, response = api.download_file(urls[name]["url"])
  2363. # TODO: I had to add this because some versions in CI broke click.progressbar
  2364. sys.stdout.write(f"File {name}\r")
  2365. dirname = os.path.dirname(name)
  2366. if dirname != "":
  2367. filesystem.mkdir_exists_ok(dirname)
  2368. with click.progressbar(
  2369. length=length,
  2370. label=f"File {name}",
  2371. fill_char=click.style("&", fg="green"),
  2372. ) as bar:
  2373. with open(name, "wb") as f:
  2374. for data in response.iter_content(chunk_size=4096):
  2375. f.write(data)
  2376. bar.update(len(data))
  2377. @cli.command(
  2378. context_settings=CONTEXT,
  2379. help="Restore code, config and docker state for a run. Retrieves code from latest commit if code was not saved with `wandb.save()` or `wandb.init(save_code=True)`.",
  2380. )
  2381. @click.pass_context
  2382. @click.argument("run", envvar=env.RUN_ID)
  2383. @click.option("--no-git", is_flag=True, default=False, help="Don't restore git state")
  2384. @click.option(
  2385. "--branch/--no-branch",
  2386. default=True,
  2387. help="Whether to create a branch or checkout detached",
  2388. )
  2389. @click.option(
  2390. "--project", "-p", envvar=env.PROJECT, help="The project you wish to upload to."
  2391. )
  2392. @click.option(
  2393. "--entity", "-e", envvar=env.ENTITY, help="The entity to scope the listing to."
  2394. )
  2395. @display_error
  2396. def restore(ctx, run, no_git, branch, project, entity):
  2397. from wandb.old.core import wandb_dir
  2398. from wandb.sdk.lib.gitlib import GitRepo
  2399. api = _get_cling_api()
  2400. if ":" in run:
  2401. if "/" in run:
  2402. entity, rest = run.split("/", 1)
  2403. else:
  2404. rest = run
  2405. project, run = rest.split(":", 1)
  2406. elif run.count("/") > 1:
  2407. entity, run = run.split("/", 1)
  2408. project, run = api.parse_slug(run, project=project)
  2409. commit, json_config, patch_content, metadata = api.run_config(
  2410. project, run=run, entity=entity
  2411. )
  2412. repo = metadata.get("git", {}).get("repo")
  2413. image = metadata.get("docker")
  2414. restore_message = f"""`wandb restore` needs to be run from the same git repository as the original run.
  2415. Run `git clone {repo}` and restore from there or pass the --no-git flag."""
  2416. git = GitRepo(remote=api.settings("git_remote"))
  2417. if no_git:
  2418. commit = None
  2419. elif not git.enabled:
  2420. if repo:
  2421. raise ClickException(restore_message)
  2422. elif image:
  2423. wandb.termlog(
  2424. "Original run has no git history. Just restoring config and docker"
  2425. )
  2426. if commit and git.enabled:
  2427. wandb.termlog(f"Fetching origin and finding commit: {commit}")
  2428. subprocess.check_call(["git", "fetch", "--all"])
  2429. try:
  2430. git.repo.commit(commit)
  2431. except ValueError:
  2432. wandb.termlog(f"Couldn't find original commit: {commit}")
  2433. commit = None
  2434. files = api.download_urls(project, run=run, entity=entity)
  2435. for filename in files:
  2436. if filename.startswith("upstream_diff_") and filename.endswith(
  2437. ".patch"
  2438. ):
  2439. commit = filename[len("upstream_diff_") : -len(".patch")]
  2440. try:
  2441. git.repo.commit(commit)
  2442. except ValueError:
  2443. commit = None
  2444. else:
  2445. break
  2446. if commit:
  2447. wandb.termlog(f"Falling back to upstream commit: {commit}")
  2448. patch_path, _ = api.download_write_file(files[filename])
  2449. else:
  2450. raise ClickException(restore_message)
  2451. else:
  2452. if patch_content:
  2453. patch_path = os.path.join(wandb_dir(), "diff.patch")
  2454. with open(patch_path, "w") as f:
  2455. f.write(patch_content)
  2456. else:
  2457. patch_path = None
  2458. branch_name = f"wandb/{run}"
  2459. if branch and branch_name not in git.repo.branches:
  2460. git.repo.git.checkout(commit, b=branch_name)
  2461. wandb.termlog(f"Created branch {click.style(branch_name, bold=True)}")
  2462. elif branch:
  2463. wandb.termlog(
  2464. f"Using existing branch, run `git branch -D {branch_name}` from master for a clean checkout"
  2465. )
  2466. git.repo.git.checkout(branch_name)
  2467. else:
  2468. wandb.termlog(f"Checking out {commit} in detached mode")
  2469. git.repo.git.checkout(commit)
  2470. if patch_path:
  2471. # we apply the patch from the repository root so git doesn't exclude
  2472. # things outside the current directory
  2473. root = git.root
  2474. patch_rel_path = os.path.relpath(patch_path, start=root)
  2475. # --reject is necessary or else this fails any time a binary file
  2476. # occurs in the diff
  2477. exit_code = subprocess.call(
  2478. ["git", "apply", "--reject", patch_rel_path], cwd=root
  2479. )
  2480. if exit_code == 0:
  2481. wandb.termlog("Applied patch")
  2482. else:
  2483. wandb.termerror(
  2484. "Failed to apply patch, try un-staging any un-committed changes"
  2485. )
  2486. filesystem.mkdir_exists_ok(wandb_dir())
  2487. config_path = os.path.join(wandb_dir(), "config.yaml")
  2488. config = Config()
  2489. for k, v in json_config.items():
  2490. if k not in ("_wandb", "wandb_version"):
  2491. config[k] = v
  2492. s = b"wandb_version: 1"
  2493. s += b"\n\n" + yaml.dump(
  2494. config._as_dict(),
  2495. Dumper=yaml.SafeDumper,
  2496. default_flow_style=False,
  2497. allow_unicode=True,
  2498. encoding="utf-8",
  2499. )
  2500. s = s.decode("utf-8")
  2501. with open(config_path, "w") as f:
  2502. f.write(s)
  2503. wandb.termlog(f"Restored config variables to {config_path}")
  2504. if image:
  2505. if not metadata["program"].startswith("<") and metadata.get("args") is not None:
  2506. # TODO: we may not want to default to python here.
  2507. runner = util.find_runner(metadata["program"]) or ["python"]
  2508. command = runner + [metadata["program"]] + metadata["args"]
  2509. cmd = " ".join(command)
  2510. else:
  2511. wandb.termlog("Couldn't find original command, just restoring environment")
  2512. cmd = None
  2513. wandb.termlog("Docker image found, attempting to start")
  2514. ctx.invoke(docker, docker_run_args=[image], cmd=cmd)
  2515. return commit, json_config, patch_content, repo, metadata
  2516. @cli.command("online")
  2517. @display_error
  2518. def online():
  2519. """Undo `wandb offline`."""
  2520. system_settings = wandb_setup.singleton().settings.read_system_settings()
  2521. system_settings.clear("mode")
  2522. system_settings.save()
  2523. click.echo(
  2524. "W&B online. Running your script from this directory will now sync to the cloud."
  2525. )
  2526. @cli.command("offline")
  2527. @display_error
  2528. def offline():
  2529. """Save data logged to W&B locally without uploading it to the cloud.
  2530. Use `wandb online` or `wandb sync` to upload offline runs.
  2531. """
  2532. system_settings = wandb_setup.singleton().settings.read_system_settings()
  2533. system_settings.set("mode", "offline")
  2534. system_settings.save()
  2535. click.echo(
  2536. "W&B offline. Running your script from this directory will only write"
  2537. + " metadata locally. Use `wandb disabled` to completely turn off W&B."
  2538. )
  2539. @cli.command("on", hidden=True)
  2540. @click.pass_context
  2541. @display_error
  2542. def on(ctx):
  2543. ctx.invoke(online)
  2544. @cli.command("off", hidden=True)
  2545. @click.pass_context
  2546. @display_error
  2547. def off(ctx):
  2548. ctx.invoke(offline)
  2549. @cli.command("status", help="Show configuration settings")
  2550. @click.option(
  2551. "--settings/--no-settings", help="Show the current settings", default=True
  2552. )
  2553. def status(settings):
  2554. api = _get_cling_api()
  2555. if settings:
  2556. click.echo(click.style("Current Settings", bold=True))
  2557. settings = api.settings()
  2558. click.echo(
  2559. json.dumps(settings, sort_keys=True, indent=2, separators=(",", ": "))
  2560. )
  2561. @cli.command("disabled", help="Disable W&B.")
  2562. @click.option(
  2563. "--service",
  2564. is_flag=True,
  2565. show_default=True,
  2566. default=True,
  2567. help="Disable W&B service",
  2568. )
  2569. def disabled(service):
  2570. system_settings = wandb_setup.singleton().settings.read_system_settings()
  2571. system_settings.set("mode", "disabled")
  2572. system_settings.save()
  2573. click.echo("W&B disabled.")
  2574. @cli.command("enabled", help="Enable W&B.")
  2575. @click.option(
  2576. "--service",
  2577. is_flag=True,
  2578. show_default=True,
  2579. default=True,
  2580. help="Enable W&B service",
  2581. )
  2582. def enabled(service):
  2583. system_settings = wandb_setup.singleton().settings.read_system_settings()
  2584. system_settings.set("mode", "online")
  2585. system_settings.save()
  2586. click.echo("W&B enabled.")
  2587. @cli.command(
  2588. context_settings=CONTEXT,
  2589. help="""Checks and verifies local instance of W&B. W&B checks for:
  2590. Checks that the host is not `api.wandb.ai` (host check).
  2591. Verifies if the user is logged in correctly using the provided API key (login check).
  2592. Checks that requests are made over HTTPS (secure requests).
  2593. Validates the CORS (Cross-Origin Resource Sharing) configuration of the
  2594. object store (CORS configuration).
  2595. Logs metrics, saves, and downloads files to check if runs are correctly
  2596. recorded and accessible (run check).
  2597. Saves and downloads artifacts to verify that the artifact storage and
  2598. retrieval system is working as expected (artifact check).
  2599. Tests the GraphQL endpoint by uploading a file to ensure it can handle
  2600. signed URL uploads (GraphQL PUT check).
  2601. Checks the ability to send large payloads through the proxy (large payload check).
  2602. Verifies that the installed version of the W&B package is up-to-date and
  2603. compatible with the server (W&B version check).
  2604. Creates and executes a sweep to ensure that sweep functionality is
  2605. working correctly (sweeps check).
  2606. """,
  2607. )
  2608. @click.option("--host", default=None, help="Test a specific instance of W&B")
  2609. def verify(host):
  2610. # TODO: (kdg) Build this all into a WandbVerify object, and clean this up.
  2611. os.environ["WANDB_SILENT"] = "true"
  2612. os.environ["WANDB_PROJECT"] = "verify"
  2613. api = _get_cling_api()
  2614. reinit = False
  2615. if host is None:
  2616. host = api.settings("base_url")
  2617. wandb.termlog(f"Default host selected: {host}")
  2618. # if the given host does not match the default host, re-run init
  2619. elif host != api.settings("base_url"):
  2620. reinit = True
  2621. tmp_dir = tempfile.mkdtemp()
  2622. wandb.termlog(
  2623. "Find detailed logs for this test at: {}".format(os.path.join(tmp_dir, "wandb"))
  2624. )
  2625. os.chdir(tmp_dir)
  2626. os.environ["WANDB_BASE_URL"] = host
  2627. wandb.login(host=host)
  2628. if reinit:
  2629. api = _get_cling_api(reset=True)
  2630. if not wandb_verify.check_host(host):
  2631. sys.exit(1)
  2632. if not wandb_verify.check_logged_in(api, host):
  2633. sys.exit(1)
  2634. url_success, url = wandb_verify.check_graphql_put(api, host)
  2635. large_post_success = wandb_verify.check_large_post()
  2636. wandb_verify.check_secure_requests(
  2637. api.settings("base_url"),
  2638. "Checking requests to base url",
  2639. "Connections are not made over https. SSL required for secure communications.",
  2640. )
  2641. if url:
  2642. wandb_verify.check_secure_requests(
  2643. url,
  2644. "Checking requests made over signed URLs",
  2645. "Signed URL requests not made over https. SSL is required for secure communications.",
  2646. )
  2647. wandb_verify.check_cors_configuration(url, host)
  2648. wandb_verify.check_wandb_version(api)
  2649. check_run_success = wandb_verify.check_run(api)
  2650. check_artifacts_success = wandb_verify.check_artifacts()
  2651. check_sweeps_success = wandb_verify.check_sweeps(api)
  2652. if not (
  2653. check_artifacts_success
  2654. and check_run_success
  2655. and large_post_success
  2656. and url_success
  2657. and check_sweeps_success
  2658. ):
  2659. sys.exit(1)
  2660. cli.add_command(beta)