cli.py 113 KB

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