wandb_run.py 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120
  1. from __future__ import annotations
  2. import contextlib
  3. import functools
  4. import glob
  5. import json
  6. import logging
  7. import numbers
  8. import os
  9. import pathlib
  10. import re
  11. import sys
  12. import threading
  13. import time
  14. import traceback
  15. from collections.abc import Mapping, Sequence
  16. from dataclasses import dataclass, field
  17. from datetime import datetime, timedelta, timezone
  18. from enum import IntEnum
  19. from types import TracebackType
  20. from typing import TYPE_CHECKING, Callable, TextIO, TypeVar
  21. from typing_extensions import Any, Concatenate, Literal, NamedTuple, ParamSpec
  22. import wandb
  23. import wandb.env
  24. import wandb.util
  25. from wandb import trigger
  26. from wandb.analytics import get_sentry
  27. from wandb.errors import CommError, UsageError
  28. from wandb.errors.links import url_registry
  29. from wandb.integration.torch import wandb_torch
  30. from wandb.plot import CustomChart, Visualize
  31. from wandb.proto.wandb_internal_pb2 import (
  32. MetricRecord,
  33. PollExitResponse,
  34. Result,
  35. RunRecord,
  36. )
  37. from wandb.proto.wandb_telemetry_pb2 import Deprecated
  38. from wandb.sdk.lib import wb_logging
  39. from wandb.sdk.lib.filesystem import (
  40. FilesDict,
  41. GlobStr,
  42. LinkStats,
  43. PolicyName,
  44. link_or_copy_with_policy,
  45. unlink_path,
  46. validate_glob_path,
  47. )
  48. from wandb.sdk.lib.import_hooks import (
  49. register_post_import_hook,
  50. unregister_post_import_hook,
  51. )
  52. from wandb.sdk.lib.paths import FilePathStr, StrPath
  53. from wandb.util import (
  54. _is_artifact_object,
  55. _is_artifact_string,
  56. _is_artifact_version_weave_dict,
  57. _is_py_requirements_or_dockerfile,
  58. _resolve_aliases,
  59. add_import_hook,
  60. parse_artifact_string,
  61. )
  62. from . import wandb_config, wandb_metric, wandb_summary
  63. from .data_types._dtypes import TypeRegistry
  64. from .interface.interface import InterfaceBase
  65. from .interface.summary_record import SummaryRecord
  66. from .lib import (
  67. config_util,
  68. deprecation,
  69. filenames,
  70. filesystem,
  71. interrupt,
  72. ipython,
  73. module,
  74. printer,
  75. progress,
  76. proto_util,
  77. redirect,
  78. telemetry,
  79. )
  80. from .lib.exit_hooks import ExitHooks
  81. from .mailbox import (
  82. HandleAbandonedError,
  83. MailboxClosedError,
  84. MailboxHandle,
  85. wait_with_progress,
  86. )
  87. from .wandb_alerts import AlertLevel
  88. from .wandb_setup import _WandbSetup
  89. if TYPE_CHECKING:
  90. from typing import TypedDict
  91. import torch # type: ignore [import-not-found]
  92. from wandb.apis.public import Api as PublicApi
  93. from wandb.proto.wandb_internal_pb2 import (
  94. GetSummaryResponse,
  95. InternalMessagesResponse,
  96. SampledHistoryResponse,
  97. )
  98. from .artifacts.artifact import Artifact
  99. from .backend.backend import Backend
  100. from .interface.interface_queue import InterfaceQueue
  101. from .wandb_settings import Settings
  102. class GitSourceDict(TypedDict):
  103. remote: str
  104. commit: str
  105. entrypoint: list[str]
  106. args: Sequence[str]
  107. class ArtifactSourceDict(TypedDict):
  108. artifact: str
  109. entrypoint: list[str]
  110. args: Sequence[str]
  111. class ImageSourceDict(TypedDict):
  112. image: str
  113. args: Sequence[str]
  114. class JobSourceDict(TypedDict, total=False):
  115. _version: str
  116. source_type: str
  117. source: GitSourceDict | ArtifactSourceDict | ImageSourceDict
  118. input_types: dict[str, Any]
  119. output_types: dict[str, Any]
  120. runtime: str | None
  121. services: dict[str, str]
  122. logger = logging.getLogger("wandb")
  123. EXIT_TIMEOUT = 60
  124. RE_LABEL = re.compile(r"[a-zA-Z0-9_-]+$")
  125. class TeardownStage(IntEnum):
  126. EARLY = 1
  127. LATE = 2
  128. class TeardownHook(NamedTuple):
  129. call: Callable[[], None]
  130. stage: TeardownStage
  131. class RunStatusChecker:
  132. """Periodically polls the background process for relevant updates.
  133. - check if the user has requested a stop.
  134. - check the network status.
  135. - check the run sync status.
  136. """
  137. _stop_status_lock: threading.Lock
  138. _stop_status_handle: MailboxHandle[Result] | None
  139. _network_status_lock: threading.Lock
  140. _network_status_handle: MailboxHandle[Result] | None
  141. _internal_messages_lock: threading.Lock
  142. _internal_messages_handle: MailboxHandle[Result] | None
  143. def __init__(
  144. self,
  145. run_id: str,
  146. interface: InterfaceBase,
  147. settings: Settings,
  148. stop_polling_interval: int = 15,
  149. retry_polling_interval: int = 5,
  150. internal_messages_polling_interval: int = 10,
  151. ) -> None:
  152. self._run_id = run_id
  153. self._interface = interface
  154. self._stop_polling_interval = stop_polling_interval
  155. self._retry_polling_interval = retry_polling_interval
  156. self._internal_messages_polling_interval = internal_messages_polling_interval
  157. self._settings = settings
  158. self._join_event = threading.Event()
  159. self._stop_status_lock = threading.Lock()
  160. self._stop_status_handle = None
  161. self._stop_thread = threading.Thread(
  162. target=self.check_stop_status,
  163. name="ChkStopThr",
  164. daemon=True,
  165. )
  166. self._network_status_lock = threading.Lock()
  167. self._network_status_handle = None
  168. self._network_status_thread = threading.Thread(
  169. target=self.check_network_status,
  170. name="NetStatThr",
  171. daemon=True,
  172. )
  173. self._internal_messages_lock = threading.Lock()
  174. self._internal_messages_handle = None
  175. self._internal_messages_thread = threading.Thread(
  176. target=self.check_internal_messages,
  177. name="IntMsgThr",
  178. daemon=True,
  179. )
  180. def start(self) -> None:
  181. self._stop_thread.start()
  182. self._network_status_thread.start()
  183. self._internal_messages_thread.start()
  184. @staticmethod
  185. def _abandon_status_check(
  186. lock: threading.Lock,
  187. handle: MailboxHandle[Result] | None,
  188. ):
  189. with lock:
  190. if handle:
  191. handle.cancel()
  192. def _loop_check_status(
  193. self,
  194. *,
  195. lock: threading.Lock,
  196. set_handle: Any,
  197. timeout: int,
  198. request: Any,
  199. process: Any,
  200. ) -> None:
  201. local_handle: MailboxHandle[Result] | None = None
  202. join_requested = False
  203. while not join_requested:
  204. time_probe = time.monotonic()
  205. if not local_handle:
  206. try:
  207. local_handle = request()
  208. except MailboxClosedError:
  209. # This can happen if the service process dies.
  210. break
  211. assert local_handle
  212. with lock:
  213. if self._join_event.is_set():
  214. break
  215. set_handle(local_handle)
  216. try:
  217. result = local_handle.wait_or(timeout=timeout)
  218. except HandleAbandonedError:
  219. # This can happen if the service process dies.
  220. break
  221. except TimeoutError:
  222. result = None
  223. with lock:
  224. set_handle(None)
  225. if result:
  226. process(result)
  227. local_handle = None
  228. time_elapsed = time.monotonic() - time_probe
  229. wait_time = max(timeout - time_elapsed, 0)
  230. join_requested = self._join_event.wait(timeout=wait_time)
  231. def check_network_status(self) -> None:
  232. def _process_network_status(result: Result) -> None:
  233. network_status = result.response.network_status_response
  234. for hr in network_status.network_responses:
  235. if (
  236. hr.http_status_code == 200 or hr.http_status_code == 0
  237. ): # we use 0 for non-http errors (eg wandb errors)
  238. wandb.termlog(f"{hr.http_response_text}")
  239. else:
  240. wandb.termlog(
  241. f"{hr.http_status_code} encountered ({hr.http_response_text.rstrip()}), retrying request"
  242. )
  243. with wb_logging.log_to_run(self._run_id):
  244. try:
  245. self._loop_check_status(
  246. lock=self._network_status_lock,
  247. set_handle=lambda x: setattr(self, "_network_status_handle", x),
  248. timeout=self._retry_polling_interval,
  249. request=self._interface.deliver_network_status,
  250. process=_process_network_status,
  251. )
  252. except BrokenPipeError:
  253. self._abandon_status_check(
  254. self._network_status_lock,
  255. self._network_status_handle,
  256. )
  257. def check_stop_status(self) -> None:
  258. def _process_stop_status(result: Result) -> None:
  259. from wandb.agents import pyagent
  260. stop_status = result.response.stop_status_response
  261. if stop_status.run_should_stop and not pyagent.is_running(): # type: ignore
  262. # TODO(frz): This check is required
  263. # until WB-3606 is resolved on server side.
  264. interrupt.interrupt_main()
  265. return
  266. with wb_logging.log_to_run(self._run_id):
  267. try:
  268. self._loop_check_status(
  269. lock=self._stop_status_lock,
  270. set_handle=lambda x: setattr(self, "_stop_status_handle", x),
  271. timeout=self._stop_polling_interval,
  272. request=self._interface.deliver_stop_status,
  273. process=_process_stop_status,
  274. )
  275. except BrokenPipeError:
  276. self._abandon_status_check(
  277. self._stop_status_lock,
  278. self._stop_status_handle,
  279. )
  280. def check_internal_messages(self) -> None:
  281. def _process_internal_messages(result: Result) -> None:
  282. if (
  283. not self._settings.show_warnings
  284. or self._settings.quiet
  285. or self._settings.silent
  286. ):
  287. return
  288. internal_messages = result.response.internal_messages_response
  289. for msg in internal_messages.messages.warning:
  290. wandb.termwarn(msg, repeat=False)
  291. with wb_logging.log_to_run(self._run_id):
  292. try:
  293. self._loop_check_status(
  294. lock=self._internal_messages_lock,
  295. set_handle=lambda x: setattr(self, "_internal_messages_handle", x),
  296. timeout=self._internal_messages_polling_interval,
  297. request=self._interface.deliver_internal_messages,
  298. process=_process_internal_messages,
  299. )
  300. except BrokenPipeError:
  301. self._abandon_status_check(
  302. self._internal_messages_lock,
  303. self._internal_messages_handle,
  304. )
  305. def stop(self) -> None:
  306. self._join_event.set()
  307. self._abandon_status_check(
  308. self._stop_status_lock,
  309. self._stop_status_handle,
  310. )
  311. self._abandon_status_check(
  312. self._network_status_lock,
  313. self._network_status_handle,
  314. )
  315. self._abandon_status_check(
  316. self._internal_messages_lock,
  317. self._internal_messages_handle,
  318. )
  319. def join(self) -> None:
  320. self.stop()
  321. self._stop_thread.join()
  322. self._network_status_thread.join()
  323. self._internal_messages_thread.join()
  324. _P = ParamSpec("_P")
  325. _T = TypeVar("_T")
  326. def _log_to_run(
  327. func: Callable[Concatenate[Run, _P], _T],
  328. ) -> Callable[Concatenate[Run, _P], _T]:
  329. """Decorate a Run method to set the run ID in the logging context.
  330. Any logs during the execution of the method go to the run's log file
  331. and not to other runs' log files.
  332. This is meant for use on all public methods and some callbacks. Private
  333. methods can be assumed to be called from some public method somewhere.
  334. The general rule is to use it on methods that can be called from a
  335. context that isn't specific to this run (such as all user code or
  336. internal methods that aren't run-specific).
  337. """
  338. @functools.wraps(func)
  339. def wrapper(self: Run, *args: _P.args, **kwargs: _P.kwargs) -> _T:
  340. # In "attach" usage, many properties of the Run are not initially
  341. # populated.
  342. if hasattr(self, "_settings"):
  343. run_id = self._settings.run_id
  344. else:
  345. run_id = self._attach_id
  346. with wb_logging.log_to_run(run_id):
  347. return func(self, *args, **kwargs)
  348. return wrapper
  349. _is_attaching: str = ""
  350. def _attach(
  351. func: Callable[Concatenate[Run, _P], _T],
  352. ) -> Callable[Concatenate[Run, _P], _T]:
  353. """Decorate a Run method to auto-attach when in a new process.
  354. When in a forked process or using a pickled Run instance, this automatically
  355. connects to the service process to "attach" to the existing run.
  356. """
  357. @functools.wraps(func)
  358. def wrapper(self: Run, *args: _P.args, **kwargs: _P.kwargs) -> _T:
  359. global _is_attaching
  360. # The _attach_id attribute is only None when running in the "disable
  361. # service" mode.
  362. #
  363. # Since it is set early in `__init__` and included in the run's pickled
  364. # state, the attribute always exists.
  365. is_using_service = self._attach_id is not None
  366. # The _attach_pid attribute is not pickled, so it might not exist.
  367. # It is set when the run is initialized.
  368. attach_pid = getattr(self, "_attach_pid", None)
  369. if is_using_service and attach_pid != os.getpid():
  370. if _is_attaching:
  371. raise RuntimeError(
  372. f"Trying to attach `{func.__name__}`"
  373. + f" while in the middle of attaching `{_is_attaching}`"
  374. )
  375. _is_attaching = func.__name__
  376. try:
  377. wandb._attach(run=self) # type: ignore
  378. finally:
  379. _is_attaching = ""
  380. return func(self, *args, **kwargs)
  381. return wrapper
  382. def _raise_if_finished(
  383. func: Callable[Concatenate[Run, _P], _T],
  384. ) -> Callable[Concatenate[Run, _P], _T]:
  385. """Decorate a Run method to raise an error after the run is finished."""
  386. @functools.wraps(func)
  387. def wrapper_fn(self: Run, *args: _P.args, **kwargs: _P.kwargs) -> _T:
  388. if not getattr(self, "_is_finished", False):
  389. return func(self, *args, **kwargs)
  390. message = (
  391. f"Run ({self.id}) is finished. The call to"
  392. f" `{func.__name__}` will be ignored."
  393. f" Please make sure that you are using an active run."
  394. )
  395. raise UsageError(message)
  396. return wrapper_fn
  397. @dataclass
  398. class RunStatus:
  399. sync_items_total: int = field(default=0)
  400. sync_items_pending: int = field(default=0)
  401. sync_time: datetime | None = field(default=None)
  402. class Run:
  403. """A unit of computation logged by W&B. Typically, this is an ML experiment.
  404. Call [`wandb.init()`](https://docs.wandb.ai/models/ref/python/functions/init) to create a
  405. new run. `wandb.init()` starts a new run and returns a `wandb.Run` object.
  406. Each run is associated with a unique ID (run ID). W&B recommends using
  407. a context (`with` statement) manager to automatically finish the run.
  408. For distributed training experiments, you can either track each process
  409. separately using one run per process or track all processes to a single run.
  410. See [Log distributed training experiments](https://docs.wandb.ai/models/track/log/distributed-training)
  411. for more information.
  412. You can log data to a run with `wandb.Run.log()`. Anything you log using
  413. `wandb.Run.log()` is sent to that run. See
  414. [Create an experiment](https://docs.wandb.ai/models/track/create-an-experiment) or
  415. [`wandb.init`](https://docs.wandb.ai/models/ref/python/functions/init) API reference page
  416. or more information.
  417. There is a another `Run` object in the
  418. [`wandb.apis.public`](https://docs.wandb.ai/models/ref/python/public-api/api)
  419. namespace. Use this object is to interact with runs that have already been
  420. created.
  421. Attributes:
  422. summary: (Summary) A summary of the run, which is a dictionary-like
  423. object. For more information, see
  424. [Log summary metrics](https://docs.wandb.ai/models/track/log/log-summary).
  425. Examples:
  426. Create a run with `wandb.init()`:
  427. ```python
  428. import wandb
  429. # Start a new run and log some data
  430. # Use context manager (`with` statement) to automatically finish the run
  431. with wandb.init(entity="entity", project="project") as run:
  432. run.log({"accuracy": acc, "loss": loss})
  433. ```
  434. <!-- lazydoc-ignore-init: internal -->
  435. """
  436. _telemetry_obj: telemetry.TelemetryRecord
  437. _telemetry_obj_active: bool
  438. _telemetry_obj_dirty: bool
  439. _telemetry_obj_flushed: bytes
  440. _teardown_hooks: list[TeardownHook]
  441. _backend: Backend | None
  442. _internal_run_interface: InterfaceQueue | None
  443. _wl: _WandbSetup | None
  444. _out_redir: redirect.RedirectBase | None
  445. _err_redir: redirect.RedirectBase | None
  446. _redirect_cb: Callable[[str, str], None] | None
  447. _redirect_raw_cb: Callable[[str, str], None] | None
  448. _output_writer: filesystem.CRDedupedFile | None
  449. _atexit_cleanup_called: bool
  450. _hooks: ExitHooks | None
  451. _exit_code: int | None
  452. _run_status_checker: RunStatusChecker | None
  453. _sampled_history: SampledHistoryResponse | None
  454. _final_summary: GetSummaryResponse | None
  455. _poll_exit_handle: MailboxHandle[Result] | None
  456. _poll_exit_response: PollExitResponse | None
  457. _internal_messages_response: InternalMessagesResponse | None
  458. _stdout_slave_fd: int | None
  459. _stderr_slave_fd: int | None
  460. _artifact_slots: list[str]
  461. _init_pid: int
  462. _attach_pid: int
  463. _attach_id: str | None
  464. _is_attached: bool
  465. _is_finished: bool
  466. _settings: Settings
  467. _forked: bool
  468. _launch_artifacts: dict[str, Any] | None
  469. _printer: printer.Printer
  470. summary: wandb_summary.Summary
  471. def __init__(
  472. self,
  473. settings: Settings,
  474. config: dict[str, Any] | None = None,
  475. sweep_config: dict[str, Any] | None = None,
  476. launch_config: dict[str, Any] | None = None,
  477. ) -> None:
  478. # pid is set, so we know if this run object was initialized by this process
  479. self._init_pid = os.getpid()
  480. self._attach_id = None
  481. if settings._noop:
  482. # TODO: properly handle setting for disabled mode
  483. self._settings = settings
  484. return
  485. self._init(
  486. settings=settings,
  487. config=config,
  488. sweep_config=sweep_config,
  489. launch_config=launch_config,
  490. )
  491. def _init(
  492. self,
  493. settings: Settings,
  494. config: dict[str, Any] | None = None,
  495. sweep_config: dict[str, Any] | None = None,
  496. launch_config: dict[str, Any] | None = None,
  497. ) -> None:
  498. self._settings = settings
  499. self._config = wandb_config.Config()
  500. self._config._set_callback(self._config_callback)
  501. self._config._set_artifact_callback(self._config_artifact_callback)
  502. self._config._set_settings(self._settings)
  503. # The _wandb key is always expected on the run config.
  504. wandb_key = "_wandb"
  505. self._config._update({wandb_key: dict()})
  506. # TODO: perhaps this should be a property that is a noop on a finished run
  507. self.summary = wandb_summary.Summary(
  508. self._summary_get_current_summary_callback,
  509. )
  510. self.summary._set_update_callback(self._summary_update_callback)
  511. self._step = 0
  512. self._starting_step = 0
  513. self._start_runtime = 0
  514. # TODO: eventually would be nice to make this configurable using self._settings._start_time
  515. # need to test (jhr): if you set start time to 2 days ago and run a test for 15 minutes,
  516. # does the total time get calculated right (not as 2 days and 15 minutes)?
  517. self._start_time = time.time()
  518. self._printer = printer.new_printer(settings)
  519. self._torch_history: wandb_torch.TorchHistory | None = None # type: ignore
  520. self._backend = None
  521. self._internal_run_interface = None
  522. self._wl = None
  523. # Avoid calling wandb.Api() repeatedly in _public_api()
  524. self._cached_public_api: PublicApi | None = None
  525. self._hooks = None
  526. self._teardown_hooks = []
  527. self._output_writer = None
  528. self._out_redir = None
  529. self._err_redir = None
  530. self._stdout_slave_fd = None
  531. self._stderr_slave_fd = None
  532. self._exit_code = None
  533. self._exit_result = None
  534. self._used_artifact_slots: dict[str, str] = {}
  535. # Created when the run "starts".
  536. self._run_status_checker = None
  537. self._sampled_history = None
  538. self._final_summary = None
  539. self._poll_exit_response = None
  540. self._internal_messages_response = None
  541. self._poll_exit_handle = None
  542. # Initialize telemetry object
  543. self._telemetry_obj = telemetry.TelemetryRecord()
  544. self._telemetry_obj_active = False
  545. self._telemetry_obj_flushed = b""
  546. self._telemetry_obj_dirty = False
  547. self._atexit_cleanup_called = False
  548. # Initial scope setup for sentry.
  549. # This might get updated when the actual run comes back.
  550. get_sentry().configure_scope(
  551. tags=dict(self._settings),
  552. process_context="user",
  553. )
  554. self._launch_artifact_mapping: dict[str, Any] = {}
  555. self._unique_launch_artifact_sequence_names: dict[str, Any] = {}
  556. # Populate config
  557. config = config or dict()
  558. self._config._update(config, allow_val_change=True, ignore_locked=True)
  559. if sweep_config:
  560. self._config.merge_locked(
  561. sweep_config, user="sweep", _allow_val_change=True
  562. )
  563. if launch_config:
  564. self._config.merge_locked(
  565. launch_config, user="launch", _allow_val_change=True
  566. )
  567. # if run is from a launch queue, add queue id to _wandb config
  568. launch_queue_name = wandb.env.get_launch_queue_name()
  569. if launch_queue_name:
  570. self._config[wandb_key]["launch_queue_name"] = launch_queue_name
  571. launch_queue_entity = wandb.env.get_launch_queue_entity()
  572. if launch_queue_entity:
  573. self._config[wandb_key]["launch_queue_entity"] = launch_queue_entity
  574. launch_trace_id = wandb.env.get_launch_trace_id()
  575. if launch_trace_id:
  576. self._config[wandb_key]["launch_trace_id"] = launch_trace_id
  577. self._attach_id = None
  578. self._is_attached = False
  579. self._is_finished = False
  580. self._attach_pid = os.getpid()
  581. self._forked = False
  582. # for now, use runid as attach id, this could/should be versioned in the future
  583. self._attach_id = self._settings.run_id
  584. def _handle_launch_artifact_overrides(self) -> None:
  585. if self._settings.launch and (os.environ.get("WANDB_ARTIFACTS") is not None):
  586. try:
  587. artifacts: dict[str, Any] = json.loads(
  588. os.environ.get("WANDB_ARTIFACTS", "{}")
  589. )
  590. except (ValueError, SyntaxError):
  591. wandb.termwarn("Malformed WANDB_ARTIFACTS, using original artifacts")
  592. else:
  593. self._initialize_launch_artifact_maps(artifacts)
  594. elif (
  595. self._settings.launch
  596. and self._settings.launch_config_path
  597. and os.path.exists(self._settings.launch_config_path)
  598. ):
  599. self.save(self._settings.launch_config_path)
  600. with open(self._settings.launch_config_path) as fp:
  601. launch_config = json.loads(fp.read())
  602. if launch_config.get("overrides", {}).get("artifacts") is not None:
  603. artifacts = launch_config.get("overrides").get("artifacts")
  604. self._initialize_launch_artifact_maps(artifacts)
  605. def _initialize_launch_artifact_maps(self, artifacts: dict[str, Any]) -> None:
  606. for key, item in artifacts.items():
  607. self._launch_artifact_mapping[key] = item
  608. artifact_sequence_tuple_or_slot = key.split(":")
  609. if len(artifact_sequence_tuple_or_slot) == 2:
  610. sequence_name = artifact_sequence_tuple_or_slot[0].split("/")[-1]
  611. if self._unique_launch_artifact_sequence_names.get(sequence_name):
  612. self._unique_launch_artifact_sequence_names.pop(sequence_name)
  613. else:
  614. self._unique_launch_artifact_sequence_names[sequence_name] = item
  615. def _telemetry_callback(self, telem_obj: telemetry.TelemetryRecord) -> None:
  616. if not hasattr(self, "_telemetry_obj") or self._is_finished:
  617. return
  618. self._telemetry_obj.MergeFrom(telem_obj)
  619. self._telemetry_obj_dirty = True
  620. self._telemetry_flush()
  621. def _telemetry_flush(self) -> None:
  622. if not hasattr(self, "_telemetry_obj"):
  623. return
  624. if not self._telemetry_obj_active:
  625. return
  626. if not self._telemetry_obj_dirty:
  627. return
  628. if self._backend and self._backend.interface:
  629. serialized = self._telemetry_obj.SerializeToString()
  630. if serialized == self._telemetry_obj_flushed:
  631. return
  632. self._backend.interface._publish_telemetry(self._telemetry_obj)
  633. self._telemetry_obj_flushed = serialized
  634. self._telemetry_obj_dirty = False
  635. def _freeze(self) -> None:
  636. self._frozen = True
  637. def __setattr__(self, attr: str, value: object) -> None:
  638. if getattr(self, "_frozen", None) and not hasattr(self, attr):
  639. raise Exception(f"Attribute {attr} is not supported on Run object.")
  640. super().__setattr__(attr, value)
  641. def __deepcopy__(self, memo: dict[int, Any]) -> Run:
  642. return self
  643. def __getstate__(self) -> Any:
  644. """Return run state as a custom pickle."""
  645. # We only pickle in service mode
  646. if not self._settings:
  647. return
  648. _attach_id = self._attach_id
  649. if not _attach_id:
  650. return
  651. return dict(
  652. _attach_id=_attach_id,
  653. _init_pid=self._init_pid,
  654. _is_finished=self._is_finished,
  655. )
  656. def __setstate__(self, state: Any) -> None:
  657. """Set run state from a custom pickle."""
  658. if not state:
  659. return
  660. _attach_id = state.get("_attach_id")
  661. if not _attach_id:
  662. return
  663. if state["_init_pid"] == os.getpid():
  664. raise RuntimeError("attach in the same process is not supported currently")
  665. self.__dict__.update(state)
  666. @property
  667. def _torch(self) -> wandb_torch.TorchHistory: # type: ignore
  668. if self._torch_history is None:
  669. self._torch_history = wandb_torch.TorchHistory() # type: ignore
  670. return self._torch_history
  671. @property
  672. @_log_to_run
  673. @_attach
  674. def settings(self) -> Settings:
  675. """A frozen copy of run's Settings object."""
  676. return self._settings.model_copy(deep=True)
  677. @property
  678. @_log_to_run
  679. @_attach
  680. def dir(self) -> str:
  681. """The directory where files associated with the run are saved."""
  682. return self._settings.files_dir
  683. @property
  684. @_log_to_run
  685. @_attach
  686. def config(self) -> wandb_config.Config:
  687. """Config object associated with this run."""
  688. return self._config
  689. @property
  690. @_log_to_run
  691. @_attach
  692. def config_static(self) -> wandb_config.ConfigStatic:
  693. """Static config object associated with this run."""
  694. return wandb_config.ConfigStatic(self._config)
  695. @property
  696. @_log_to_run
  697. @_attach
  698. def name(self) -> str | None:
  699. """Display name of the run.
  700. Display names are not guaranteed to be unique and may be descriptive.
  701. By default, they are randomly generated.
  702. """
  703. return self._settings.run_name
  704. @name.setter
  705. @_log_to_run
  706. @_raise_if_finished
  707. def name(self, name: str) -> None:
  708. with telemetry.context(run=self) as tel:
  709. tel.feature.set_run_name = True
  710. self._settings.run_name = name
  711. if self._backend and self._backend.interface:
  712. self._backend.interface.publish_run(self)
  713. @property
  714. @_log_to_run
  715. @_attach
  716. def notes(self) -> str | None:
  717. """Notes associated with the run, if there are any.
  718. Notes can be a multiline string and can also use markdown and latex
  719. equations inside `$$`, like `$x + 3$`.
  720. """
  721. return self._settings.run_notes
  722. @notes.setter
  723. @_log_to_run
  724. @_raise_if_finished
  725. def notes(self, notes: str) -> None:
  726. self._settings.run_notes = notes
  727. if self._backend and self._backend.interface:
  728. self._backend.interface.publish_run(self)
  729. @property
  730. @_log_to_run
  731. @_attach
  732. def tags(self) -> tuple | None:
  733. """Tags associated with the run, if there are any."""
  734. return self._settings.run_tags or ()
  735. @tags.setter
  736. @_log_to_run
  737. @_raise_if_finished
  738. def tags(self, tags: Sequence) -> None:
  739. with telemetry.context(run=self) as tel:
  740. tel.feature.set_run_tags = True
  741. try:
  742. self._settings.run_tags = tuple(tags)
  743. except ValueError as e:
  744. # For runtime tag setting, warn instead of crash
  745. # Extract the core error message without the pydantic wrapper
  746. error_msg = str(e)
  747. if "Value error," in error_msg:
  748. # Extract the actual error message after "Value error, "
  749. error_msg = error_msg.split("Value error, ")[1].split(" [type=")[0]
  750. wandb.termwarn(f"Invalid tag detected: {error_msg} Tags not updated.")
  751. return
  752. if self._backend and self._backend.interface:
  753. self._backend.interface.publish_run(self)
  754. @property
  755. @_log_to_run
  756. @_attach
  757. def id(self) -> str:
  758. """Identifier for this run."""
  759. assert self._settings.run_id is not None
  760. return self._settings.run_id
  761. @property
  762. @_log_to_run
  763. @_attach
  764. def sweep_id(self) -> str | None:
  765. """Identifier for the sweep associated with the run, if there is one."""
  766. return self._settings.sweep_id
  767. def _get_path(self) -> str:
  768. return "/".join(
  769. e
  770. for e in [
  771. self._settings.entity,
  772. self._settings.project,
  773. self._settings.run_id,
  774. ]
  775. if e is not None
  776. )
  777. @property
  778. @_log_to_run
  779. @_attach
  780. def path(self) -> str:
  781. """Path to the run.
  782. Run paths include entity, project, and run ID, in the format
  783. `entity/project/run_id`.
  784. """
  785. return self._get_path()
  786. @property
  787. @_log_to_run
  788. @_attach
  789. def start_time(self) -> float:
  790. """Unix timestamp (in seconds) of when the run started."""
  791. return self._start_time
  792. @property
  793. @_log_to_run
  794. @_attach
  795. def starting_step(self) -> int:
  796. """The first step of the run.
  797. <!-- lazydoc-ignore: internal -->
  798. """
  799. return self._starting_step
  800. @property
  801. @_log_to_run
  802. @_attach
  803. def resumed(self) -> bool:
  804. """True if the run was resumed, False otherwise."""
  805. return self._settings.resumed
  806. @property
  807. @_log_to_run
  808. @_attach
  809. def step(self) -> int:
  810. """Current value of the step.
  811. This counter is incremented by `wandb.Run.log()`.
  812. <!-- lazydoc-ignore: internal -->
  813. """
  814. return self._step
  815. @property
  816. @_log_to_run
  817. @_attach
  818. def offline(self) -> bool:
  819. """True if the run is offline, False otherwise."""
  820. return self._settings._offline
  821. @property
  822. @_log_to_run
  823. @_attach
  824. def disabled(self) -> bool:
  825. """True if the run is disabled, False otherwise."""
  826. return self._settings._noop
  827. @property
  828. @_log_to_run
  829. @_attach
  830. def group(self) -> str:
  831. """Returns the name of the group associated with this run.
  832. Grouping runs together allows related experiments to be organized and
  833. visualized collectively in the W&B UI. This is especially useful for
  834. scenarios such as distributed training or cross-validation, where
  835. multiple runs should be viewed and managed as a unified experiment.
  836. In shared mode, where all processes share the same run object,
  837. setting a group is usually unnecessary, since there is only one
  838. run and no grouping is required.
  839. """
  840. return self._settings.run_group or ""
  841. @property
  842. @_log_to_run
  843. @_attach
  844. def job_type(self) -> str:
  845. """Name of the job type associated with the run.
  846. View a run's job type in the run's Overview page in the W&B App.
  847. You can use this to categorize runs by their job type, such as
  848. "training", "evaluation", or "inference". This is useful for organizing
  849. and filtering runs in the W&B UI, especially when you have multiple
  850. runs with different job types in the same project. For more
  851. information, see [Organize runs](https://docs.wandb.ai/models/runs#organize-runs).
  852. """
  853. return self._settings.run_job_type or ""
  854. def project_name(self) -> str:
  855. """This method is deprecated and will be removed in a future release. Use `run.project` instead.
  856. Name of the W&B project associated with the run.
  857. <!-- lazydoc-ignore: internal -->
  858. """
  859. deprecation.warn_and_record_deprecation(
  860. feature=Deprecated(run__project_name=True),
  861. message=(
  862. "The project_name method is deprecated and will be removed in a"
  863. " future release. Please use `run.project` instead."
  864. ),
  865. )
  866. return self.project
  867. @property
  868. @_log_to_run
  869. @_attach
  870. def project(self) -> str:
  871. """Name of the W&B project associated with the run."""
  872. assert self._settings.project is not None
  873. return self._settings.project
  874. @_log_to_run
  875. def get_project_url(self) -> str | None:
  876. """This method is deprecated and will be removed in a future release. Use `run.project_url` instead.
  877. URL of the W&B project associated with the run, if there is one.
  878. Offline runs do not have a project URL.
  879. <!-- lazydoc-ignore: internal -->
  880. """
  881. deprecation.warn_and_record_deprecation(
  882. feature=Deprecated(run__get_project_url=True),
  883. message=(
  884. "The get_project_url method is deprecated and will be removed in a"
  885. " future release. Please use `run.project_url` instead."
  886. ),
  887. )
  888. return self.project_url
  889. @property
  890. @_log_to_run
  891. @_attach
  892. def project_url(self) -> str | None:
  893. """URL of the W&B project associated with the run, if there is one.
  894. Offline runs do not have a project URL.
  895. """
  896. if self._settings._offline:
  897. wandb.termwarn("URL not available in offline run")
  898. return None
  899. return self._settings.project_url
  900. @_raise_if_finished
  901. @_log_to_run
  902. @_attach
  903. def log_code(
  904. self,
  905. root: str | None = ".",
  906. name: str | None = None,
  907. include_fn: Callable[[str, str], bool]
  908. | Callable[[str], bool] = _is_py_requirements_or_dockerfile,
  909. exclude_fn: Callable[[str, str], bool]
  910. | Callable[[str], bool] = filenames.exclude_wandb_fn,
  911. ) -> Artifact | None:
  912. """Save the current state of your code to a W&B Artifact.
  913. By default, it walks the current directory and logs all files that end with `.py`.
  914. Args:
  915. root: The relative (to `os.getcwd()`) or absolute path to recursively find code from.
  916. name: (str, optional) The name of our code artifact. By default, we'll name
  917. the artifact `source-$PROJECT_ID-$ENTRYPOINT_RELPATH`. There may be scenarios where you want
  918. many runs to share the same artifact. Specifying name allows you to achieve that.
  919. include_fn: A callable that accepts a file path and (optionally) root path and
  920. returns True when it should be included and False otherwise. This
  921. defaults to `lambda path, root: path.endswith(".py")`.
  922. exclude_fn: A callable that accepts a file path and (optionally) root path and
  923. returns `True` when it should be excluded and `False` otherwise. This
  924. defaults to a function that excludes all files within `<root>/.wandb/`
  925. and `<root>/wandb/` directories.
  926. Examples:
  927. Basic usage
  928. ```python
  929. import wandb
  930. with wandb.init() as run:
  931. run.log_code()
  932. ```
  933. Advanced usage
  934. ```python
  935. import wandb
  936. with wandb.init() as run:
  937. run.log_code(
  938. root="../",
  939. include_fn=lambda path: path.endswith(".py") or path.endswith(".ipynb"),
  940. exclude_fn=lambda path, root: os.path.relpath(path, root).startswith(
  941. "cache/"
  942. ),
  943. )
  944. ```
  945. Returns:
  946. An `Artifact` object if code was logged
  947. """
  948. from wandb.sdk.artifacts._internal_artifact import InternalArtifact
  949. if name is None:
  950. if self.settings._jupyter:
  951. notebook_name = None
  952. if self.settings.notebook_name:
  953. notebook_name = self.settings.notebook_name
  954. elif self.settings.x_jupyter_path:
  955. if self.settings.x_jupyter_path.startswith("fileId="):
  956. notebook_name = self.settings.x_jupyter_name
  957. else:
  958. notebook_name = self.settings.x_jupyter_path
  959. name_string = f"{self._settings.project}-{notebook_name}"
  960. else:
  961. name_string = (
  962. f"{self._settings.project}-{self._settings.program_relpath}"
  963. )
  964. name = wandb.util.make_artifact_name_safe(f"source-{name_string}")
  965. art = InternalArtifact(name, "code")
  966. files_added = False
  967. if root is not None:
  968. root = os.path.abspath(root)
  969. for file_path in filenames.filtered_dir(root, include_fn, exclude_fn):
  970. files_added = True
  971. save_name = os.path.relpath(file_path, root)
  972. art.add_file(file_path, name=save_name)
  973. # Add any manually staged files such as ipynb notebooks
  974. for dirpath, _, files in os.walk(self._settings._tmp_code_dir):
  975. for fname in files:
  976. file_path = os.path.join(dirpath, fname)
  977. save_name = os.path.relpath(file_path, self._settings._tmp_code_dir)
  978. files_added = True
  979. art.add_file(file_path, name=save_name)
  980. if not files_added:
  981. wandb.termwarn(
  982. "No relevant files were detected in the specified directory. No code will be logged to your run."
  983. )
  984. return None
  985. artifact = self._log_artifact(art)
  986. self._config.update(
  987. {"_wandb": {"code_path": artifact.name}},
  988. allow_val_change=True,
  989. )
  990. return artifact
  991. @_log_to_run
  992. def get_sweep_url(self) -> str | None:
  993. """This method is deprecated and will be removed in a future release. Use `run.sweep_url` instead.
  994. The URL of the sweep associated with the run, if there is one.
  995. Offline runs do not have a sweep URL.
  996. <!-- lazydoc-ignore: internal -->
  997. """
  998. deprecation.warn_and_record_deprecation(
  999. feature=Deprecated(run__get_sweep_url=True),
  1000. message=(
  1001. "The get_sweep_url method is deprecated and will be removed in a"
  1002. " future release. Please use `run.sweep_url` instead."
  1003. ),
  1004. )
  1005. return self.sweep_url
  1006. @property
  1007. @_attach
  1008. def sweep_url(self) -> str | None:
  1009. """URL of the sweep associated with the run, if there is one.
  1010. Offline runs do not have a sweep URL.
  1011. """
  1012. if self._settings._offline:
  1013. wandb.termwarn("URL not available in offline run")
  1014. return None
  1015. return self._settings.sweep_url
  1016. @_log_to_run
  1017. def get_url(self) -> str | None:
  1018. """This method is deprecated and will be removed in a future release. Use `run.url` instead.
  1019. URL of the W&B run, if there is one. Offline runs do not have a URL.
  1020. <!-- lazydoc-ignore: internal -->
  1021. """
  1022. deprecation.warn_and_record_deprecation(
  1023. feature=Deprecated(run__get_url=True),
  1024. message=(
  1025. "The get_url method is deprecated and will be removed in a"
  1026. " future release. Please use `run.url` instead."
  1027. ),
  1028. )
  1029. return self.url
  1030. @property
  1031. @_log_to_run
  1032. @_attach
  1033. def url(self) -> str | None:
  1034. """The url for the W&B run, if there is one.
  1035. Offline runs will not have a url.
  1036. """
  1037. if self._settings._offline:
  1038. wandb.termwarn("URL not available in offline run")
  1039. return None
  1040. return self._settings.run_url
  1041. @property
  1042. @_log_to_run
  1043. @_attach
  1044. def entity(self) -> str:
  1045. """The name of the W&B entity associated with the run.
  1046. Entity can be a username or the name of a team or organization.
  1047. """
  1048. return self._settings.entity or ""
  1049. def _label_internal(
  1050. self,
  1051. code: str | None = None,
  1052. repo: str | None = None,
  1053. code_version: str | None = None,
  1054. ) -> None:
  1055. with telemetry.context(run=self) as tel:
  1056. if code and RE_LABEL.match(code):
  1057. tel.label.code_string = code
  1058. if repo and RE_LABEL.match(repo):
  1059. tel.label.repo_string = repo
  1060. if code_version and RE_LABEL.match(code_version):
  1061. tel.label.code_version = code_version
  1062. def _label(
  1063. self,
  1064. code: str | None = None,
  1065. repo: str | None = None,
  1066. code_version: str | None = None,
  1067. **kwargs: str,
  1068. ) -> None:
  1069. if self._settings.label_disable:
  1070. return
  1071. for k, v in (("code", code), ("repo", repo), ("code_version", code_version)):
  1072. if v and not RE_LABEL.match(v):
  1073. wandb.termwarn(
  1074. f"Label added for '{k}' with invalid identifier '{v}' (ignored).",
  1075. repeat=False,
  1076. )
  1077. for v in kwargs:
  1078. wandb.termwarn(
  1079. f"Label added for unsupported key {v!r} (ignored).",
  1080. repeat=False,
  1081. )
  1082. self._label_internal(code=code, repo=repo, code_version=code_version)
  1083. # update telemetry in the backend immediately for _label() callers
  1084. self._telemetry_flush()
  1085. def _label_probe_lines(self, lines: list[str]) -> None:
  1086. if not lines:
  1087. return
  1088. parsed = telemetry._parse_label_lines(lines)
  1089. if not parsed:
  1090. return
  1091. label_dict = {}
  1092. code = parsed.get("code") or parsed.get("c")
  1093. if code:
  1094. label_dict["code"] = code
  1095. repo = parsed.get("repo") or parsed.get("r")
  1096. if repo:
  1097. label_dict["repo"] = repo
  1098. code_ver = parsed.get("version") or parsed.get("v")
  1099. if code_ver:
  1100. label_dict["code_version"] = code_ver
  1101. self._label_internal(**label_dict)
  1102. def _label_probe_main(self) -> None:
  1103. m = sys.modules.get("__main__")
  1104. if not m:
  1105. return
  1106. doc = getattr(m, "__doc__", None)
  1107. if not doc:
  1108. return
  1109. doclines = doc.splitlines()
  1110. self._label_probe_lines(doclines)
  1111. # TODO: annotate jupyter Notebook class
  1112. def _label_probe_notebook(self, notebook: Any) -> None:
  1113. logger.info("probe notebook")
  1114. lines = None
  1115. try:
  1116. data = notebook.probe_ipynb()
  1117. cell0 = data.get("cells", [])[0]
  1118. lines = cell0.get("source")
  1119. # kaggle returns a string instead of a list
  1120. if isinstance(lines, str):
  1121. lines = lines.split()
  1122. except Exception as e:
  1123. logger.info(f"Unable to probe notebook: {e}")
  1124. return
  1125. if lines:
  1126. self._label_probe_lines(lines)
  1127. @_log_to_run
  1128. @_attach
  1129. def display(self, height: int = 420, hidden: bool = False) -> bool:
  1130. """Display this run in Jupyter."""
  1131. if self._settings.silent:
  1132. return False
  1133. if not ipython.in_jupyter() or ipython.in_vscode_notebook():
  1134. return False
  1135. try:
  1136. from IPython import display
  1137. except ImportError:
  1138. wandb.termwarn(".display() only works in jupyter environments")
  1139. return False
  1140. display.display(display.HTML(self.to_html(height, hidden)))
  1141. return True
  1142. @_log_to_run
  1143. @_attach
  1144. def to_html(self, height: int = 420, hidden: bool = False) -> str:
  1145. """Generate HTML containing an iframe displaying the current run.
  1146. If the run is being displayed in a VSCode notebook,
  1147. the string representation of the run is returned instead.
  1148. <!-- lazydoc-ignore: internal -->
  1149. """
  1150. if ipython.in_vscode_notebook():
  1151. import html
  1152. return html.escape(str(self))
  1153. url = self._settings.run_url + "?jupyter=true"
  1154. style = f"border:none;width:100%;height:{height}px;"
  1155. prefix = ""
  1156. if hidden:
  1157. style += "display:none;"
  1158. prefix = ipython.toggle_button()
  1159. return prefix + f"<iframe src={url!r} style={style!r}></iframe>"
  1160. def _repr_mimebundle_(
  1161. self, include: Any | None = None, exclude: Any | None = None
  1162. ) -> dict[str, str]:
  1163. return {"text/html": self.to_html(hidden=True)}
  1164. @_log_to_run
  1165. @_raise_if_finished
  1166. def _config_callback(
  1167. self,
  1168. key: tuple[str, ...] | str | None = None,
  1169. val: Any | None = None,
  1170. data: dict[str, object] | None = None,
  1171. ) -> None:
  1172. logger.info(f"config_cb {key} {val} {data}")
  1173. if self._backend and self._backend.interface:
  1174. self._backend.interface.publish_config(key=key, val=val, data=data)
  1175. @_log_to_run
  1176. def _config_artifact_callback(
  1177. self, key: str, val: str | Artifact | dict
  1178. ) -> Artifact:
  1179. from wandb.apis import public
  1180. from wandb.sdk.artifacts.artifact import Artifact
  1181. # artifacts can look like dicts as they are passed into the run config
  1182. # since the run config stores them on the backend as a dict with fields shown
  1183. # in wandb.util.artifact_to_json
  1184. if _is_artifact_version_weave_dict(val):
  1185. assert isinstance(val, dict)
  1186. public_api = self._public_api()
  1187. artifact = Artifact._from_id(val["id"], public_api.client)
  1188. assert artifact
  1189. return self.use_artifact(artifact)
  1190. elif _is_artifact_string(val):
  1191. # this will never fail, but is required to make mypy happy
  1192. assert isinstance(val, str)
  1193. artifact_string, base_url, is_id = parse_artifact_string(val)
  1194. overrides = {}
  1195. if base_url is not None:
  1196. overrides = {"base_url": base_url}
  1197. public_api = public.Api(overrides)
  1198. else:
  1199. public_api = self._public_api()
  1200. if is_id:
  1201. artifact = Artifact._from_id(artifact_string, public_api._client)
  1202. else:
  1203. artifact = public_api._artifact(name=artifact_string)
  1204. # in the future we'll need to support using artifacts from
  1205. # different instances of wandb.
  1206. assert artifact
  1207. return self.use_artifact(artifact)
  1208. elif _is_artifact_object(val):
  1209. return self.use_artifact(val)
  1210. else:
  1211. raise ValueError(
  1212. f"Cannot call _config_artifact_callback on type {type(val)}"
  1213. )
  1214. def _set_config_wandb(self, key: str, val: Any) -> None:
  1215. self._config_callback(key=("_wandb", key), val=val)
  1216. @_log_to_run
  1217. @_raise_if_finished
  1218. @_attach
  1219. def pin_config_keys(self, keys: Sequence[str] = ()) -> None:
  1220. """Pin config keys to display in the References section on Run Overview.
  1221. Pinned keys appear prominently above Notes on the Run Overview page.
  1222. String values are rendered as markdown; non-strings are rendered as
  1223. plain text. Calling this again replaces the previously pinned list.
  1224. Args:
  1225. keys: Config key names to pin, matching keys set via
  1226. ``run.config``. These are exact key strings (dots and
  1227. slashes are treated literally, not as path separators).
  1228. Order is preserved and determines display order.
  1229. """
  1230. self._set_config_wandb("pinned_keys", list(keys))
  1231. @_log_to_run
  1232. @_raise_if_finished
  1233. def _summary_update_callback(self, summary_record: SummaryRecord) -> None:
  1234. with telemetry.context(run=self) as tel:
  1235. tel.feature.set_summary = True
  1236. if self._backend and self._backend.interface:
  1237. self._backend.interface.publish_summary(self, summary_record)
  1238. @_log_to_run
  1239. def _summary_get_current_summary_callback(self) -> dict[str, Any]:
  1240. if self._is_finished:
  1241. # TODO: WB-18420: fetch summary from backend and stage it before run is finished
  1242. wandb.termwarn("Summary data not available in finished run")
  1243. return {}
  1244. if not self._backend or not self._backend.interface:
  1245. return {}
  1246. handle = self._backend.interface.deliver_get_summary()
  1247. try:
  1248. result = handle.wait_or(timeout=self._settings.summary_timeout)
  1249. except TimeoutError:
  1250. return {}
  1251. get_summary_response = result.response.get_summary_response
  1252. return proto_util.dict_from_proto_list(get_summary_response.item)
  1253. @_log_to_run
  1254. def _metric_callback(self, metric_record: MetricRecord) -> None:
  1255. if self._backend and self._backend.interface:
  1256. self._backend.interface._publish_metric(metric_record)
  1257. @_log_to_run
  1258. def _publish_file(self, fname: str) -> None:
  1259. """Mark a run file to be uploaded with the run.
  1260. This is a W&B-internal function: it can be used by other internal
  1261. wandb code.
  1262. Args:
  1263. fname: The path to the file in the run's files directory, relative
  1264. to the run's files directory.
  1265. """
  1266. if not self._backend or not self._backend.interface:
  1267. return
  1268. files: FilesDict = dict(files=[(GlobStr(fname), "now")])
  1269. self._backend.interface.publish_files(files)
  1270. def _pop_all_charts(
  1271. self,
  1272. data: dict[str, Any],
  1273. key_prefix: str | None = None,
  1274. ) -> dict[str, Any]:
  1275. """Pops all charts from a dictionary including nested charts.
  1276. This function will return a mapping of the charts and a dot-separated
  1277. key for each chart. Indicating the path to the chart in the data dictionary.
  1278. """
  1279. keys_to_remove = set()
  1280. charts: dict[str, Any] = {}
  1281. for k, v in data.items():
  1282. key = f"{key_prefix}.{k}" if key_prefix else k
  1283. if isinstance(v, Visualize):
  1284. keys_to_remove.add(k)
  1285. charts[key] = v
  1286. elif isinstance(v, CustomChart):
  1287. keys_to_remove.add(k)
  1288. charts[key] = v
  1289. elif isinstance(v, dict):
  1290. nested_charts = self._pop_all_charts(v, key)
  1291. charts.update(nested_charts)
  1292. for k in keys_to_remove:
  1293. data.pop(k)
  1294. return charts
  1295. def _serialize_custom_charts(
  1296. self,
  1297. data: dict[str, Any],
  1298. ) -> dict[str, Any]:
  1299. """Process and replace chart objects with their underlying table values.
  1300. This processes the chart objects passed to `wandb.Run.log()`, replacing their entries
  1301. in the given dictionary (which is saved to the run's history) and adding them
  1302. to the run's config.
  1303. Args:
  1304. data: Dictionary containing data that may include plot objects
  1305. Plot objects can be nested in dictionaries, which will be processed recursively.
  1306. Returns:
  1307. The processed dictionary with custom charts transformed into tables.
  1308. """
  1309. if not data:
  1310. return data
  1311. charts = self._pop_all_charts(data)
  1312. for k, v in charts.items():
  1313. v.set_key(k)
  1314. self._config_callback(
  1315. val=v.spec.config_value,
  1316. key=v.spec.config_key,
  1317. )
  1318. if isinstance(v, CustomChart):
  1319. data[v.spec.table_key] = v.table
  1320. elif isinstance(v, Visualize):
  1321. data[k] = v.table
  1322. return data
  1323. @_log_to_run
  1324. def _partial_history_callback(
  1325. self,
  1326. data: dict[str, Any],
  1327. step: int | None = None,
  1328. commit: bool | None = None,
  1329. ) -> None:
  1330. if not (self._backend and self._backend.interface):
  1331. return
  1332. data = data.copy() # avoid modifying the original data
  1333. # Serialize custom charts before publishing
  1334. data = self._serialize_custom_charts(data)
  1335. not_using_tensorboard = len(wandb.patched["tensorboard"]) == 0
  1336. self._backend.interface.publish_partial_history(
  1337. self,
  1338. data,
  1339. user_step=self._step,
  1340. step=step,
  1341. flush=commit,
  1342. publish_step=not_using_tensorboard,
  1343. )
  1344. @_log_to_run
  1345. def _console_callback(self, name: str, data: str) -> None:
  1346. if self._backend and self._backend.interface:
  1347. # nowait=True so that this can be called from an asyncio context.
  1348. self._backend.interface.publish_output(name, data, nowait=True)
  1349. @_log_to_run
  1350. @_raise_if_finished
  1351. def _console_raw_callback(self, name: str, data: str) -> None:
  1352. # NOTE: console output is only allowed on the process which installed the callback
  1353. # this will prevent potential corruption in the socket to the service. Other methods
  1354. # are protected by the _attach run decorator, but this callback was installed on the
  1355. # write function of stdout and stderr streams.
  1356. console_pid = getattr(self, "_attach_pid", 0)
  1357. if console_pid != os.getpid():
  1358. return
  1359. if self._backend and self._backend.interface:
  1360. # nowait=True so that this can be called from an asyncio context.
  1361. self._backend.interface.publish_output_raw(name, data, nowait=True)
  1362. @_log_to_run
  1363. def _tensorboard_callback(
  1364. self, logdir: str, save: bool = True, root_logdir: str = ""
  1365. ) -> None:
  1366. logger.info("tensorboard callback: %s, %s", logdir, save)
  1367. if self._backend and self._backend.interface:
  1368. self._backend.interface.publish_tbdata(logdir, save, root_logdir)
  1369. def _set_library(self, library: _WandbSetup) -> None:
  1370. self._wl = library
  1371. def _set_backend(self, backend: Backend) -> None:
  1372. self._backend = backend
  1373. def _set_internal_run_interface(self, interface: InterfaceQueue) -> None:
  1374. self._internal_run_interface = interface
  1375. def _set_teardown_hooks(self, hooks: list[TeardownHook]) -> None:
  1376. self._teardown_hooks = hooks
  1377. def _set_run_obj(self, run_obj: RunRecord) -> None: # noqa: C901
  1378. if run_obj.starting_step:
  1379. self._starting_step = run_obj.starting_step
  1380. self._step = run_obj.starting_step
  1381. if run_obj.start_time:
  1382. self._start_time = run_obj.start_time.ToMicroseconds() / 1e6
  1383. if run_obj.runtime:
  1384. self._start_runtime = run_obj.runtime
  1385. # Grab the config from resuming
  1386. if run_obj.config:
  1387. c_dict = config_util.dict_no_value_from_proto_list(run_obj.config.update)
  1388. # We update the config object here without triggering the callback
  1389. self._config._update(c_dict, allow_val_change=True, ignore_locked=True)
  1390. # Update the summary, this will trigger an un-needed graphql request :(
  1391. if run_obj.summary:
  1392. summary_dict = {}
  1393. for orig in run_obj.summary.update:
  1394. summary_dict[orig.key] = json.loads(orig.value_json)
  1395. if summary_dict:
  1396. self.summary.update(summary_dict)
  1397. # update settings from run_obj
  1398. if run_obj.run_id:
  1399. self._settings.run_id = run_obj.run_id
  1400. if run_obj.entity:
  1401. self._settings.entity = run_obj.entity
  1402. if run_obj.project:
  1403. self._settings.project = run_obj.project
  1404. if run_obj.run_group:
  1405. self._settings.run_group = run_obj.run_group
  1406. if run_obj.job_type:
  1407. self._settings.run_job_type = run_obj.job_type
  1408. if run_obj.display_name:
  1409. self._settings.run_name = run_obj.display_name
  1410. if run_obj.notes:
  1411. self._settings.run_notes = run_obj.notes
  1412. if run_obj.tags:
  1413. self._settings.run_tags = tuple(run_obj.tags)
  1414. if run_obj.sweep_id:
  1415. self._settings.sweep_id = run_obj.sweep_id
  1416. if run_obj.host:
  1417. self._settings.host = run_obj.host
  1418. if run_obj.resumed:
  1419. self._settings.resumed = run_obj.resumed
  1420. if run_obj.git:
  1421. if run_obj.git.remote_url:
  1422. self._settings.git_remote_url = run_obj.git.remote_url
  1423. if run_obj.git.commit:
  1424. self._settings.git_commit = run_obj.git.commit
  1425. if run_obj.forked:
  1426. self._forked = run_obj.forked
  1427. get_sentry().configure_scope(
  1428. process_context="user",
  1429. tags=dict(self._settings),
  1430. )
  1431. def _populate_git_info(self) -> None:
  1432. from .lib.gitlib import GitRepo
  1433. # Use user-provided git info if available, otherwise resolve it from the environment
  1434. try:
  1435. repo = GitRepo(
  1436. root=self._settings.git_root,
  1437. remote=self._settings.git_remote,
  1438. remote_url=self._settings.git_remote_url,
  1439. commit=self._settings.git_commit,
  1440. lazy=False,
  1441. )
  1442. self._settings.git_remote_url = repo.remote_url
  1443. self._settings.git_commit = repo.last_commit
  1444. except Exception:
  1445. wandb.termwarn("Cannot find valid git repo associated with this directory.")
  1446. def _add_singleton(
  1447. self, data_type: str, key: str, value: dict[int | str, str]
  1448. ) -> None:
  1449. """Store a singleton item to wandb config.
  1450. A singleton in this context is a piece of data that is continually
  1451. logged with the same value in each history step, but represented
  1452. as a single item in the config.
  1453. We do this to avoid filling up history with a lot of repeated unnecessary data
  1454. Add singleton can be called many times in one run, and it will only be
  1455. updated when the value changes. The last value logged will be the one
  1456. persisted to the server.
  1457. """
  1458. value_extra = {"type": data_type, "key": key, "value": value}
  1459. if data_type not in self._config["_wandb"]:
  1460. self._config["_wandb"][data_type] = {}
  1461. if data_type in self._config["_wandb"][data_type]:
  1462. old_value = self._config["_wandb"][data_type][key]
  1463. else:
  1464. old_value = None
  1465. if value_extra != old_value:
  1466. self._config["_wandb"][data_type][key] = value_extra
  1467. self._config.persist()
  1468. def _log(
  1469. self,
  1470. data: dict[str, Any],
  1471. step: int | None = None,
  1472. commit: bool | None = None,
  1473. ) -> None:
  1474. if not isinstance(data, Mapping):
  1475. raise TypeError("wandb.log must be passed a dictionary")
  1476. if any(not isinstance(key, str) for key in data):
  1477. raise TypeError("Key values passed to `wandb.log` must be strings.")
  1478. self._partial_history_callback(data, step, commit)
  1479. if step is not None:
  1480. if os.getpid() != self._init_pid or self._is_attached:
  1481. wandb.termwarn(
  1482. "Note that setting step in multiprocessing can result in data loss. "
  1483. "Please use `run.define_metric(...)` to define a custom metric "
  1484. "to log your step values.",
  1485. repeat=False,
  1486. )
  1487. # if step is passed in when tensorboard_sync is used we honor the step passed
  1488. # to make decisions about how to close out the history record, but will strip
  1489. # this history later on in publish_history()
  1490. if len(wandb.patched["tensorboard"]) > 0:
  1491. wandb.termwarn(
  1492. "Step cannot be set when using tensorboard syncing. "
  1493. "Please use `run.define_metric(...)` to define a custom metric "
  1494. "to log your step values.",
  1495. repeat=False,
  1496. )
  1497. if step > self._step:
  1498. self._step = step
  1499. if (step is None and commit is None) or commit:
  1500. self._step += 1
  1501. @_log_to_run
  1502. @_raise_if_finished
  1503. @_attach
  1504. def log(
  1505. self,
  1506. data: dict[str, Any],
  1507. step: int | None = None,
  1508. commit: bool | None = None,
  1509. ) -> None:
  1510. """Upload run data.
  1511. Use `log` to log data from runs, such as scalars, images, video,
  1512. histograms, plots, and tables. See [Log objects and media](https://docs.wandb.ai/models/track/log) for
  1513. code snippets, best practices, and more.
  1514. Basic usage:
  1515. ```python
  1516. import wandb
  1517. with wandb.init() as run:
  1518. run.log({"train-loss": 0.5, "accuracy": 0.9})
  1519. ```
  1520. The previous code snippet saves the loss and accuracy to the run's
  1521. history and updates the summary values for these metrics.
  1522. Visualize logged data in a workspace at [wandb.ai](https://wandb.ai),
  1523. or locally on a [self-hosted instance](https://docs.wandb.ai/platform/hosting)
  1524. of the W&B app, or export data to visualize and explore locally, such as in a
  1525. Jupyter notebook, with the [Public API](https://docs.wandb.ai/models/track/public-api-guide).
  1526. Logged values don't have to be scalars. You can log any
  1527. [W&B supported Data Type](https://docs.wandb.ai/models/ref/python/data-types)
  1528. such as images, audio, video, and more. For example, you can use
  1529. `wandb.Table` to log structured data. See
  1530. [Log tables, visualize and query data](https://docs.wandb.ai/models/tables/tables-walkthrough)
  1531. tutorial for more details.
  1532. W&B organizes metrics with a forward slash (`/`) in their name
  1533. into sections named using the text before the final slash. For example,
  1534. the following results in two sections named "train" and "validate":
  1535. ```python
  1536. with wandb.init() as run:
  1537. # Log metrics in the "train" section.
  1538. run.log(
  1539. {
  1540. "train/accuracy": 0.9,
  1541. "train/loss": 30,
  1542. "validate/accuracy": 0.8,
  1543. "validate/loss": 20,
  1544. }
  1545. )
  1546. ```
  1547. Only one level of nesting is supported; `run.log({"a/b/c": 1})`
  1548. produces a section named "a".
  1549. `run.log()` is not intended to be called more than a few times per second.
  1550. For optimal performance, limit your logging to once every N iterations,
  1551. or collect data over multiple iterations and log it in a single step.
  1552. By default, each call to `log` creates a new "step".
  1553. The step must always increase, and it is not possible to log
  1554. to a previous step. You can use any metric as the X axis in charts.
  1555. See [Custom log axes](https://docs.wandb.ai/models/track/log/customize-logging-axes)
  1556. for more details.
  1557. In many cases, it is better to treat the W&B step like
  1558. you'd treat a timestamp rather than a training step.
  1559. ```python
  1560. with wandb.init() as run:
  1561. # Example: log an "epoch" metric for use as an X axis.
  1562. run.log({"epoch": 40, "train-loss": 0.5})
  1563. ```
  1564. It is possible to use multiple `wandb.Run.log()` invocations to log to
  1565. the same step with the `step` and `commit` parameters.
  1566. The following are all equivalent:
  1567. ```python
  1568. with wandb.init() as run:
  1569. # Normal usage:
  1570. run.log({"train-loss": 0.5, "accuracy": 0.8})
  1571. run.log({"train-loss": 0.4, "accuracy": 0.9})
  1572. # Implicit step without auto-incrementing:
  1573. run.log({"train-loss": 0.5}, commit=False)
  1574. run.log({"accuracy": 0.8})
  1575. run.log({"train-loss": 0.4}, commit=False)
  1576. run.log({"accuracy": 0.9})
  1577. # Explicit step:
  1578. run.log({"train-loss": 0.5}, step=current_step)
  1579. run.log({"accuracy": 0.8}, step=current_step)
  1580. current_step += 1
  1581. run.log({"train-loss": 0.4}, step=current_step)
  1582. run.log({"accuracy": 0.9}, step=current_step, commit=True)
  1583. ```
  1584. Args:
  1585. data: A `dict` with `str` keys and values that are serializable
  1586. Python objects including: `int`, `float` and `string`;
  1587. any of the `wandb.data_types`; lists, tuples and NumPy arrays
  1588. of serializable Python objects; other `dict`s of this
  1589. structure.
  1590. step: The step number to log. If `None`, then an implicit
  1591. auto-incrementing step is used. See the notes in
  1592. the description.
  1593. commit: If true, finalize and upload the step. If false, then
  1594. accumulate data for the step. See the notes in the description.
  1595. If `step` is `None`, then the default is `commit=True`;
  1596. otherwise, the default is `commit=False`.
  1597. Examples:
  1598. For more and more detailed examples, see
  1599. [our guides to logging](https://docs.wandb.ai/models/track/log).
  1600. Basic usage
  1601. ```python
  1602. import wandb
  1603. with wandb.init() as run:
  1604. run.log({"train-loss": 0.5, "accuracy": 0.9
  1605. ```
  1606. Incremental logging
  1607. ```python
  1608. import wandb
  1609. with wandb.init() as run:
  1610. run.log({"loss": 0.2}, commit=False)
  1611. # Somewhere else when I'm ready to report this step:
  1612. run.log({"accuracy": 0.8})
  1613. ```
  1614. Histogram
  1615. ```python
  1616. import numpy as np
  1617. import wandb
  1618. # sample gradients at random from normal distribution
  1619. gradients = np.random.randn(100, 100)
  1620. with wandb.init() as run:
  1621. run.log({"gradients": wandb.Histogram(gradients)})
  1622. ```
  1623. Image from NumPy
  1624. ```python
  1625. import numpy as np
  1626. import wandb
  1627. with wandb.init() as run:
  1628. examples = []
  1629. for i in range(3):
  1630. pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))
  1631. image = wandb.Image(pixels, caption=f"random field {i}")
  1632. examples.append(image)
  1633. run.log({"examples": examples})
  1634. ```
  1635. Image from PIL
  1636. ```python
  1637. import numpy as np
  1638. from PIL import Image as PILImage
  1639. import wandb
  1640. with wandb.init() as run:
  1641. examples = []
  1642. for i in range(3):
  1643. pixels = np.random.randint(
  1644. low=0,
  1645. high=256,
  1646. size=(100, 100, 3),
  1647. dtype=np.uint8,
  1648. )
  1649. pil_image = PILImage.fromarray(pixels, mode="RGB")
  1650. image = wandb.Image(pil_image, caption=f"random field {i}")
  1651. examples.append(image)
  1652. run.log({"examples": examples})
  1653. ```
  1654. Video from NumPy
  1655. ```python
  1656. import numpy as np
  1657. import wandb
  1658. with wandb.init() as run:
  1659. # axes are (time, channel, height, width)
  1660. frames = np.random.randint(
  1661. low=0,
  1662. high=256,
  1663. size=(10, 3, 100, 100),
  1664. dtype=np.uint8,
  1665. )
  1666. run.log({"video": wandb.Video(frames, fps=4)})
  1667. ```
  1668. Matplotlib plot
  1669. ```python
  1670. from matplotlib import pyplot as plt
  1671. import numpy as np
  1672. import wandb
  1673. with wandb.init() as run:
  1674. fig, ax = plt.subplots()
  1675. x = np.linspace(0, 10)
  1676. y = x * x
  1677. ax.plot(x, y) # plot y = x^2
  1678. run.log({"chart": fig})
  1679. ```
  1680. PR Curve
  1681. ```python
  1682. import wandb
  1683. with wandb.init() as run:
  1684. run.log({"pr": wandb.plot.pr_curve(y_test, y_probas, labels)})
  1685. ```
  1686. 3D Object
  1687. ```python
  1688. import wandb
  1689. with wandb.init() as run:
  1690. run.log(
  1691. {
  1692. "generated_samples": [
  1693. wandb.Object3D(open("sample.obj")),
  1694. wandb.Object3D(open("sample.gltf")),
  1695. wandb.Object3D(open("sample.glb")),
  1696. ]
  1697. }
  1698. )
  1699. ```
  1700. Raises:
  1701. wandb.Error: If called before `wandb.init()`.
  1702. ValueError: If invalid data is passed.
  1703. """
  1704. if step is not None:
  1705. with telemetry.context(run=self) as tel:
  1706. tel.feature.set_step_log = True
  1707. if self._settings._shared and step is not None:
  1708. wandb.termwarn(
  1709. "In shared mode, the use of `wandb.log` with the step argument is not supported "
  1710. f"and will be ignored. Please refer to {url_registry.url('define-metric')} "
  1711. "on how to customize your x-axis.",
  1712. repeat=False,
  1713. )
  1714. self._log(data=data, step=step, commit=commit)
  1715. @_log_to_run
  1716. @_raise_if_finished
  1717. @_attach
  1718. def save(
  1719. self,
  1720. glob_str: str | os.PathLike,
  1721. base_path: str | os.PathLike | None = None,
  1722. policy: PolicyName = "live",
  1723. ) -> bool | list[str]:
  1724. """Sync one or more files to W&B.
  1725. Relative paths are relative to the current working directory.
  1726. A Unix glob, such as "myfiles/*", is expanded at the time `save` is
  1727. called regardless of the `policy`. In particular, new files are not
  1728. picked up automatically.
  1729. A `base_path` may be provided to control the directory structure of
  1730. uploaded files. It should be a prefix of `glob_str`, and the directory
  1731. structure beneath it is preserved.
  1732. When given an absolute path or glob and no `base_path`, one
  1733. directory level is preserved as in the example above.
  1734. Files are automatically deduplicated: calling `save()` multiple times
  1735. on the same file without modifications will not re-upload it.
  1736. Args:
  1737. glob_str: A relative or absolute path or Unix glob.
  1738. base_path: A path to use to infer a directory structure; see examples.
  1739. policy: One of `live`, `now`, or `end`.
  1740. - live: upload the file as it changes, overwriting the previous version
  1741. - now: upload the file once now
  1742. - end: upload file when the run ends
  1743. Returns:
  1744. Paths to the symlinks created for the matched files.
  1745. For historical reasons, this may return a boolean in legacy code.
  1746. ```python
  1747. import wandb
  1748. run = wandb.init()
  1749. run.save("these/are/myfiles/*")
  1750. # => Saves files in a "these/are/myfiles/" folder in the run.
  1751. run.save("these/are/myfiles/*", base_path="these")
  1752. # => Saves files in an "are/myfiles/" folder in the run.
  1753. run.save("/Users/username/Documents/run123/*.txt")
  1754. # => Saves files in a "run123/" folder in the run. See note below.
  1755. run.save("/Users/username/Documents/run123/*.txt", base_path="/Users")
  1756. # => Saves files in a "username/Documents/run123/" folder in the run.
  1757. run.save("files/*/saveme.txt")
  1758. # => Saves each "saveme.txt" file in an appropriate subdirectory
  1759. # of "files/".
  1760. # Explicitly finish the run since a context manager is not used.
  1761. run.finish()
  1762. ```
  1763. """
  1764. if isinstance(glob_str, bytes):
  1765. # Preserved for backward compatibility: allow bytes inputs.
  1766. glob_str = glob_str.decode("utf-8")
  1767. if isinstance(glob_str, str) and (glob_str.startswith(("gs://", "s3://"))):
  1768. # Provide a better error message for a common misuse.
  1769. wandb.termlog(f"{glob_str} is a cloud storage url, can't save file to W&B.")
  1770. return []
  1771. # NOTE: We use PurePath instead of Path because WindowsPath doesn't
  1772. # like asterisks and errors out in resolve(). It also makes logical
  1773. # sense: globs aren't real paths, they're just path-like strings.
  1774. glob_path = pathlib.PurePath(glob_str)
  1775. resolved_glob_path = pathlib.PurePath(os.path.abspath(glob_path))
  1776. if base_path is not None:
  1777. base_path = pathlib.Path(base_path)
  1778. elif not glob_path.is_absolute():
  1779. base_path = pathlib.Path(".")
  1780. else:
  1781. # Absolute glob paths with no base path get special handling.
  1782. wandb.termwarn(
  1783. "Saving files without folders. If you want to preserve "
  1784. "subdirectories pass base_path to wandb.save, i.e. "
  1785. 'wandb.save("/mnt/folder/file.h5", base_path="/mnt")',
  1786. repeat=False,
  1787. )
  1788. base_path = resolved_glob_path.parent.parent
  1789. if policy not in ("live", "end", "now"):
  1790. raise ValueError(
  1791. 'Only "live", "end" and "now" policies are currently supported.'
  1792. )
  1793. resolved_base_path = pathlib.PurePath(os.path.abspath(base_path))
  1794. return self._save(
  1795. resolved_glob_path,
  1796. resolved_base_path,
  1797. policy,
  1798. )
  1799. def _save(
  1800. self,
  1801. glob_path: pathlib.PurePath,
  1802. base_path: pathlib.PurePath,
  1803. policy: PolicyName,
  1804. ) -> list[str]:
  1805. """Materialize matched files into the run's files/ dir for syncing.
  1806. Strategy:
  1807. 1) If settings.symlink is True, try symlink.
  1808. 2) Else (or if symlink fails), try hardlink (same-volume files).
  1809. 3) Else copy and, if requested policy == "live", downgrade those files to "now".
  1810. Args:
  1811. glob_path: Absolute path glob pattern for files to save.
  1812. base_path: Base path to determine relative directory structure.
  1813. policy: Upload policy - "live", "now", or "end".
  1814. Returns:
  1815. List of absolute paths to files in the wandb run directory.
  1816. Raises:
  1817. ValueError: If glob_path is invalid relative to base_path.
  1818. """
  1819. validate_glob_path(glob_path, base_path)
  1820. relative_glob = glob_path.relative_to(base_path)
  1821. relative_glob_str = GlobStr(str(relative_glob))
  1822. with telemetry.context(run=self) as tel:
  1823. tel.feature.save = True
  1824. files_root = pathlib.Path(self._settings.files_dir)
  1825. preexisting = set(files_root.glob(relative_glob_str))
  1826. # Expand sources deterministically.
  1827. src_paths = [
  1828. pathlib.Path(p).absolute()
  1829. for p in sorted(glob.glob(GlobStr(str(base_path / relative_glob_str))))
  1830. ]
  1831. stats = LinkStats()
  1832. publish_entries = []
  1833. created_targets = set()
  1834. for src in src_paths:
  1835. # Preserve directory structure under base_path.
  1836. rel = pathlib.Path(*src.parts[len(base_path.parts) :])
  1837. dst = files_root / rel
  1838. created_targets.add(dst)
  1839. # If already the same file, just publish with requested policy.
  1840. with contextlib.suppress(OSError):
  1841. if dst.exists() and src.samefile(dst):
  1842. publish_entries.append(
  1843. (GlobStr(str(dst.relative_to(files_root))), policy)
  1844. )
  1845. continue
  1846. dst.parent.mkdir(parents=True, exist_ok=True)
  1847. unlink_path(dst)
  1848. effective_policy = link_or_copy_with_policy(
  1849. self._settings, src, dst, policy, stats
  1850. )
  1851. publish_entries.append(
  1852. (GlobStr(str(dst.relative_to(files_root))), effective_policy)
  1853. )
  1854. # Include pre-existing matches we didn't touch.
  1855. for p in sorted(preexisting):
  1856. if p not in created_targets:
  1857. publish_entries.append(
  1858. (GlobStr(str(p.relative_to(files_root))), policy)
  1859. )
  1860. stats.emit_warnings()
  1861. files_dict: FilesDict = {"files": publish_entries}
  1862. if self._backend and self._backend.interface:
  1863. self._backend.interface.publish_files(files_dict)
  1864. abs_targets = {files_root / pathlib.Path(g) for (g, _pol) in publish_entries}
  1865. return [str(p) for p in sorted(abs_targets)]
  1866. @_log_to_run
  1867. @_attach
  1868. def restore(
  1869. self,
  1870. name: str,
  1871. run_path: str | None = None,
  1872. replace: bool = False,
  1873. root: str | None = None,
  1874. ) -> None | TextIO:
  1875. return restore(
  1876. name,
  1877. run_path or self._get_path(),
  1878. replace,
  1879. root or self._settings.files_dir,
  1880. )
  1881. @_log_to_run
  1882. @_attach
  1883. def finish(
  1884. self,
  1885. exit_code: int | None = None,
  1886. quiet: bool | None = None,
  1887. ) -> None:
  1888. """Finish a run and upload any remaining data.
  1889. Marks the completion of a W&B run and ensures all data is synced to the server.
  1890. The run's final state is determined by its exit conditions and sync status.
  1891. Run States:
  1892. - Running: Active run that is logging data and/or sending heartbeats.
  1893. - Crashed: Run that stopped sending heartbeats unexpectedly.
  1894. - Finished: Run completed successfully (`exit_code=0`) with all data synced.
  1895. - Failed: Run completed with errors (`exit_code!=0`).
  1896. - Killed: Run was forcibly stopped before it could finish.
  1897. Args:
  1898. exit_code: Integer indicating the run's exit status. Use 0 for success,
  1899. any other value marks the run as failed.
  1900. quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`.
  1901. """
  1902. if quiet is not None:
  1903. deprecation.warn_and_record_deprecation(
  1904. feature=Deprecated(run__finish_quiet=True),
  1905. message=(
  1906. "The `quiet` argument to `wandb.run.finish()` is deprecated, "
  1907. "use `wandb.Settings(quiet=...)` to set this instead."
  1908. ),
  1909. run=self,
  1910. )
  1911. return self._finish(exit_code)
  1912. @_log_to_run
  1913. def _finish(
  1914. self,
  1915. exit_code: int | None = None,
  1916. ) -> None:
  1917. if self._is_finished:
  1918. return
  1919. assert self._wl
  1920. logger.info(f"finishing run {self._get_path()}")
  1921. with telemetry.context(run=self) as tel:
  1922. tel.feature.finish = True
  1923. # Run hooks that need to happen before the last messages to the
  1924. # internal service, like Jupyter hooks.
  1925. for hook in self._teardown_hooks:
  1926. if hook.stage == TeardownStage.EARLY:
  1927. hook.call()
  1928. # Early-stage hooks may use methods that require _is_finished
  1929. # to be False, so we set this after running those hooks.
  1930. self._is_finished = True
  1931. self._wl.remove_active_run(self)
  1932. try:
  1933. self._atexit_cleanup(exit_code=exit_code)
  1934. # Run hooks that should happen after the last messages to the
  1935. # internal service, like detaching the logger.
  1936. for hook in self._teardown_hooks:
  1937. if hook.stage == TeardownStage.LATE:
  1938. hook.call()
  1939. self._teardown_hooks = []
  1940. # Inform the service that we're done sending messages for this run.
  1941. #
  1942. # TODO: Why not do this in _atexit_cleanup()?
  1943. if self._settings.run_id:
  1944. service = self._wl.assert_service()
  1945. service.inform_finish(run_id=self._settings.run_id)
  1946. finally:
  1947. if wandb.run is self:
  1948. module.unset_globals()
  1949. get_sentry().end_session()
  1950. @_log_to_run
  1951. @_raise_if_finished
  1952. @_attach
  1953. def status(
  1954. self,
  1955. ) -> RunStatus:
  1956. """Get sync info from the internal backend, about the current run's sync status."""
  1957. if not self._backend or not self._backend.interface:
  1958. return RunStatus()
  1959. handle_run_status = self._backend.interface.deliver_request_run_status()
  1960. result = handle_run_status.wait_or(timeout=None)
  1961. sync_data = result.response.run_status_response
  1962. sync_time = None
  1963. if sync_data.sync_time.seconds:
  1964. sync_time = datetime.fromtimestamp(
  1965. sync_data.sync_time.seconds + sync_data.sync_time.nanos / 1e9
  1966. )
  1967. return RunStatus(
  1968. sync_items_total=sync_data.sync_items_total,
  1969. sync_items_pending=sync_data.sync_items_pending,
  1970. sync_time=sync_time,
  1971. )
  1972. def _add_panel(
  1973. self, visualize_key: str, panel_type: str, panel_config: dict
  1974. ) -> None:
  1975. config = {
  1976. "panel_type": panel_type,
  1977. "panel_config": panel_config,
  1978. }
  1979. self._config_callback(val=config, key=("_wandb", "visualize", visualize_key))
  1980. def _redirect(
  1981. self,
  1982. stdout_slave_fd: int | None,
  1983. stderr_slave_fd: int | None,
  1984. console: str | None = None,
  1985. ) -> None:
  1986. if console is None:
  1987. console = self._settings.console
  1988. # only use raw for service to minimize potential changes
  1989. if console == "wrap":
  1990. console = "wrap_raw"
  1991. logger.info("redirect: %s", console)
  1992. out_redir: redirect.RedirectBase
  1993. err_redir: redirect.RedirectBase
  1994. # raw output handles the output_log writing in the internal process
  1995. if console in {"redirect", "wrap_emu"}:
  1996. output_log_path = os.path.join(
  1997. self._settings.files_dir, filenames.OUTPUT_FNAME
  1998. )
  1999. # output writer might have been set up, see wrap_fallback case
  2000. if not self._output_writer:
  2001. self._output_writer = filesystem.CRDedupedFile(
  2002. open(output_log_path, "wb")
  2003. )
  2004. if console == "redirect":
  2005. logger.info("Redirecting console.")
  2006. out_redir = redirect.Redirect(
  2007. src="stdout",
  2008. cbs=[
  2009. lambda data: self._console_callback("stdout", data),
  2010. self._output_writer.write, # type: ignore
  2011. ],
  2012. flush_periodically=(self._settings.mode == "online"),
  2013. )
  2014. err_redir = redirect.Redirect(
  2015. src="stderr",
  2016. cbs=[
  2017. lambda data: self._console_callback("stderr", data),
  2018. self._output_writer.write, # type: ignore
  2019. ],
  2020. flush_periodically=(self._settings.mode == "online"),
  2021. )
  2022. if os.name == "nt":
  2023. def wrap_fallback() -> None:
  2024. if self._out_redir:
  2025. self._out_redir.uninstall()
  2026. if self._err_redir:
  2027. self._err_redir.uninstall()
  2028. msg = (
  2029. "Tensorflow detected. Stream redirection is not supported "
  2030. "on Windows when tensorflow is imported. Falling back to "
  2031. "wrapping stdout/err."
  2032. )
  2033. wandb.termlog(msg)
  2034. self._redirect(None, None, console="wrap")
  2035. add_import_hook("tensorflow", wrap_fallback)
  2036. elif console == "wrap_emu":
  2037. logger.info("Wrapping output streams.")
  2038. out_redir = redirect.StreamWrapper(
  2039. src="stdout",
  2040. cbs=[
  2041. lambda data: self._console_callback("stdout", data),
  2042. self._output_writer.write, # type: ignore
  2043. ],
  2044. flush_periodically=(self._settings.mode == "online"),
  2045. )
  2046. err_redir = redirect.StreamWrapper(
  2047. src="stderr",
  2048. cbs=[
  2049. lambda data: self._console_callback("stderr", data),
  2050. self._output_writer.write, # type: ignore
  2051. ],
  2052. flush_periodically=(self._settings.mode == "online"),
  2053. )
  2054. elif console == "wrap_raw":
  2055. logger.info("Wrapping output streams.")
  2056. out_redir = redirect.StreamRawWrapper(
  2057. src="stdout",
  2058. cbs=[
  2059. lambda data: self._console_raw_callback("stdout", data),
  2060. ],
  2061. )
  2062. err_redir = redirect.StreamRawWrapper(
  2063. src="stderr",
  2064. cbs=[
  2065. lambda data: self._console_raw_callback("stderr", data),
  2066. ],
  2067. )
  2068. elif console == "off":
  2069. return
  2070. else:
  2071. raise ValueError("unhandled console")
  2072. try:
  2073. # save stdout and stderr before installing new write functions
  2074. out_redir.install()
  2075. err_redir.install()
  2076. self._out_redir = out_redir
  2077. self._err_redir = err_redir
  2078. logger.info("Redirects installed.")
  2079. except Exception as e:
  2080. wandb.termwarn(f"Failed to redirect: {e}")
  2081. logger.exception("Failed to redirect.")
  2082. return
  2083. def _restore(self) -> None:
  2084. logger.info("restore")
  2085. # TODO(jhr): drain and shutdown all threads
  2086. if self._out_redir:
  2087. self._out_redir.uninstall()
  2088. if self._err_redir:
  2089. self._err_redir.uninstall()
  2090. logger.info("restore done")
  2091. def _atexit_cleanup(self, exit_code: int | None = None) -> None:
  2092. if self._backend is None:
  2093. logger.warning("process exited without backend configured")
  2094. return
  2095. if self._atexit_cleanup_called:
  2096. return
  2097. self._atexit_cleanup_called = True
  2098. exit_code = exit_code or (self._hooks and self._hooks.exit_code) or 0
  2099. self._exit_code = exit_code
  2100. logger.info(f"got exitcode: {exit_code}")
  2101. # Delete this run's "resume" file if the run finished successfully.
  2102. #
  2103. # This is used by the "auto" resume mode, which resumes from the last
  2104. # failed (or unfinished/crashed) run. If we reach this line, then this
  2105. # run shouldn't be a candidate for "auto" resume.
  2106. if exit_code == 0 and os.path.exists(self._settings.resume_fname):
  2107. os.remove(self._settings.resume_fname)
  2108. try:
  2109. self._on_finish()
  2110. except KeyboardInterrupt:
  2111. if not wandb.wandb_agent._is_running(): # type: ignore
  2112. wandb.termerror("Control-C detected -- Run data was not synced")
  2113. raise
  2114. except Exception:
  2115. self._console_stop()
  2116. logger.exception("Problem finishing run")
  2117. wandb.termerror("Problem finishing run")
  2118. raise
  2119. Run._footer(
  2120. sampled_history=self._sampled_history,
  2121. final_summary=self._final_summary,
  2122. poll_exit_response=self._poll_exit_response,
  2123. internal_messages_response=self._internal_messages_response,
  2124. settings=self._settings,
  2125. printer=self._printer,
  2126. )
  2127. def _console_start(self) -> None:
  2128. logger.info("atexit reg")
  2129. self._hooks = ExitHooks()
  2130. self._redirect(self._stdout_slave_fd, self._stderr_slave_fd)
  2131. def _console_stop(self) -> None:
  2132. self._restore()
  2133. if self._output_writer:
  2134. self._output_writer.close()
  2135. self._output_writer = None
  2136. def _on_start(self) -> None:
  2137. self._header()
  2138. if self._settings.save_code and self._settings.code_dir is not None:
  2139. self.log_code(self._settings.code_dir)
  2140. if (
  2141. self._settings.x_save_requirements
  2142. and self._backend
  2143. and self._backend.interface
  2144. ):
  2145. from wandb.util import working_set
  2146. logger.debug(
  2147. "Saving list of pip packages installed into the current environment"
  2148. )
  2149. self._backend.interface.publish_python_packages(working_set())
  2150. if self._backend and self._backend.interface and not self._settings._offline:
  2151. assert self._settings.run_id
  2152. self._run_status_checker = RunStatusChecker(
  2153. self._settings.run_id,
  2154. interface=self._backend.interface,
  2155. settings=self._settings,
  2156. )
  2157. self._run_status_checker.start()
  2158. self._console_start()
  2159. self._on_ready()
  2160. def _on_attach(self) -> None:
  2161. """Event triggered when run is attached to another run."""
  2162. with telemetry.context(run=self) as tel:
  2163. tel.feature.attach = True
  2164. self._is_attached = True
  2165. self._on_ready()
  2166. def _register_telemetry_import_hooks(
  2167. self,
  2168. ) -> None:
  2169. def _telemetry_import_hook(
  2170. run: Run,
  2171. module: Any,
  2172. ) -> None:
  2173. with telemetry.context(run=run) as tel:
  2174. try:
  2175. name = getattr(module, "__name__", None)
  2176. if name is not None:
  2177. setattr(tel.imports_finish, name, True)
  2178. except AttributeError:
  2179. return
  2180. import_telemetry_set = telemetry.list_telemetry_imports()
  2181. import_hook_fn = functools.partial(_telemetry_import_hook, self)
  2182. if not self._settings.run_id:
  2183. return
  2184. for module_name in import_telemetry_set:
  2185. register_post_import_hook(
  2186. import_hook_fn,
  2187. self._settings.run_id,
  2188. module_name,
  2189. )
  2190. def _on_ready(self) -> None:
  2191. """Event triggered when run is ready for the user."""
  2192. assert self._wl
  2193. self._wl.add_active_run(self)
  2194. self._register_telemetry_import_hooks()
  2195. # start reporting any telemetry changes
  2196. self._telemetry_obj_active = True
  2197. self._telemetry_flush()
  2198. try:
  2199. self._detect_and_apply_job_inputs()
  2200. except Exception:
  2201. logger.exception("Problem applying launch job inputs")
  2202. # object is about to be returned to the user, don't let them modify it
  2203. self._freeze()
  2204. if (not self._settings.resume) and os.path.exists(self._settings.resume_fname):
  2205. os.remove(self._settings.resume_fname)
  2206. def _detect_and_apply_job_inputs(self) -> None:
  2207. """If the user has staged launch inputs, apply them to the run."""
  2208. from wandb.sdk.launch.inputs.internal import StagedLaunchInputs
  2209. StagedLaunchInputs().apply(self)
  2210. def _make_job_source_reqs(self) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
  2211. from wandb.util import working_set
  2212. installed_packages_list = sorted(f"{d.key}=={d.version}" for d in working_set())
  2213. input_types = TypeRegistry.type_of(self.config.as_dict()).to_json()
  2214. output_types = TypeRegistry.type_of(self.summary._as_dict()).to_json()
  2215. return installed_packages_list, input_types, output_types
  2216. def _construct_job_artifact(
  2217. self,
  2218. name: str,
  2219. source_dict: JobSourceDict,
  2220. installed_packages_list: list[str],
  2221. patch_path: os.PathLike | None = None,
  2222. ) -> Artifact:
  2223. from wandb.sdk.artifacts._internal_artifact import InternalArtifact
  2224. from wandb.sdk.internal import job_builder
  2225. job_artifact = InternalArtifact(name, job_builder.JOB_ARTIFACT_TYPE)
  2226. if patch_path and os.path.exists(patch_path):
  2227. job_artifact.add_file(FilePathStr(patch_path), "diff.patch")
  2228. with job_artifact.new_file("requirements.frozen.txt") as f:
  2229. f.write("\n".join(installed_packages_list))
  2230. with job_artifact.new_file("wandb-job.json") as f:
  2231. f.write(json.dumps(source_dict))
  2232. return job_artifact
  2233. def _create_image_job(
  2234. self,
  2235. input_types: dict[str, Any],
  2236. output_types: dict[str, Any],
  2237. installed_packages_list: list[str],
  2238. docker_image_name: str | None = None,
  2239. args: list[str] | None = None,
  2240. ) -> Artifact | None:
  2241. docker_image_name = docker_image_name or os.getenv("WANDB_DOCKER")
  2242. if not docker_image_name:
  2243. return None
  2244. name = wandb.util.make_artifact_name_safe(f"job-{docker_image_name}")
  2245. s_args: Sequence[str] = args if args is not None else self._settings._args
  2246. source_info: JobSourceDict = {
  2247. "_version": "v0",
  2248. "source_type": "image",
  2249. "source": {"image": docker_image_name, "args": s_args},
  2250. "input_types": input_types,
  2251. "output_types": output_types,
  2252. "runtime": self._settings._python,
  2253. }
  2254. job_artifact = self._construct_job_artifact(
  2255. name, source_info, installed_packages_list
  2256. )
  2257. return job_artifact
  2258. def _log_job_artifact_with_image(
  2259. self, docker_image_name: str, args: list[str] | None = None
  2260. ) -> Artifact:
  2261. packages, in_types, out_types = self._make_job_source_reqs()
  2262. job_artifact = self._create_image_job(
  2263. in_types,
  2264. out_types,
  2265. packages,
  2266. args=args,
  2267. docker_image_name=docker_image_name,
  2268. )
  2269. assert job_artifact
  2270. artifact = self.log_artifact(job_artifact)
  2271. if not artifact:
  2272. raise wandb.Error(f"Job Artifact log unsuccessful: {artifact}")
  2273. else:
  2274. return artifact
  2275. def _on_finish(self) -> None:
  2276. trigger.call("on_finished")
  2277. if self._run_status_checker is not None:
  2278. self._run_status_checker.stop()
  2279. self._console_stop() # TODO: there's a race here with jupyter console logging
  2280. assert self._backend and self._backend.interface
  2281. if self._settings.x_update_finish_state:
  2282. exit_handle = self._backend.interface.deliver_exit(self._exit_code)
  2283. else:
  2284. exit_handle = self._backend.interface.deliver_finish_without_exit()
  2285. with progress.progress_printer(
  2286. self._printer,
  2287. default_text="Finishing up...",
  2288. ) as progress_printer:
  2289. # Wait for the run to complete.
  2290. wait_with_progress(
  2291. exit_handle,
  2292. timeout=None,
  2293. display_progress=functools.partial(
  2294. progress.loop_printing_operation_stats,
  2295. progress_printer,
  2296. self._backend.interface,
  2297. ),
  2298. )
  2299. poll_exit_handle = self._backend.interface.deliver_poll_exit()
  2300. result = poll_exit_handle.wait_or(timeout=None)
  2301. self._poll_exit_response = result.response.poll_exit_response
  2302. internal_messages_handle = self._backend.interface.deliver_internal_messages()
  2303. result = internal_messages_handle.wait_or(timeout=None)
  2304. self._internal_messages_response = result.response.internal_messages_response
  2305. # dispatch all our final requests
  2306. final_summary_handle = self._backend.interface.deliver_get_summary()
  2307. sampled_history_handle = (
  2308. self._backend.interface.deliver_request_sampled_history()
  2309. )
  2310. result = sampled_history_handle.wait_or(timeout=None)
  2311. self._sampled_history = result.response.sampled_history_response
  2312. result = final_summary_handle.wait_or(timeout=None)
  2313. self._final_summary = result.response.get_summary_response
  2314. if self._backend:
  2315. self._backend.cleanup()
  2316. if self._run_status_checker:
  2317. self._run_status_checker.join()
  2318. if self._settings.run_id:
  2319. self._unregister_telemetry_import_hooks(self._settings.run_id)
  2320. @staticmethod
  2321. def _unregister_telemetry_import_hooks(run_id: str) -> None:
  2322. import_telemetry_set = telemetry.list_telemetry_imports()
  2323. for module_name in import_telemetry_set:
  2324. unregister_post_import_hook(module_name, run_id)
  2325. @_log_to_run
  2326. @_raise_if_finished
  2327. @_attach
  2328. def define_metric(
  2329. self,
  2330. name: str,
  2331. step_metric: str | wandb_metric.Metric | None = None,
  2332. step_sync: bool | None = None,
  2333. hidden: bool | None = None,
  2334. summary: str | None = None,
  2335. goal: str | None = None,
  2336. overwrite: bool | None = None,
  2337. ) -> wandb_metric.Metric:
  2338. """Customize metrics logged with `wandb.Run.log()`.
  2339. Args:
  2340. name: The name of the metric to customize.
  2341. step_metric: The name of another metric to serve as the X-axis
  2342. for this metric in automatically generated charts.
  2343. step_sync: Automatically insert the last value of step_metric into
  2344. `wandb.Run.log()` if it is not provided explicitly. Defaults to True
  2345. if step_metric is specified.
  2346. hidden: Hide this metric from automatic plots.
  2347. summary: Specify aggregate metrics added to summary.
  2348. Supported aggregations include "min", "max", "mean", "last",
  2349. "first", "best", "copy" and "none". "none" prevents a summary
  2350. from being generated. "best" is used together with the goal
  2351. parameter, "best" is deprecated and should not be used, use
  2352. "min" or "max" instead. "copy" is deprecated and should not be
  2353. used.
  2354. goal: Specify how to interpret the "best" summary type.
  2355. Supported options are "minimize" and "maximize". "goal" is
  2356. deprecated and should not be used, use "min" or "max" instead.
  2357. overwrite: If false, then this call is merged with previous
  2358. `define_metric` calls for the same metric by using their
  2359. values for any unspecified parameters. If true, then
  2360. unspecified parameters overwrite values specified by
  2361. previous calls.
  2362. Returns:
  2363. An object that represents this call but can otherwise be discarded.
  2364. """
  2365. if summary and "copy" in summary:
  2366. deprecation.warn_and_record_deprecation(
  2367. feature=Deprecated(run__define_metric_copy=True),
  2368. message="define_metric(summary='copy') is deprecated and will be removed.",
  2369. run=self,
  2370. )
  2371. if (summary and "best" in summary) or goal is not None:
  2372. deprecation.warn_and_record_deprecation(
  2373. feature=Deprecated(run__define_metric_best_goal=True),
  2374. message="define_metric(summary='best', goal=...) is deprecated and will be removed. "
  2375. "Use define_metric(summary='min') or define_metric(summary='max') instead.",
  2376. run=self,
  2377. )
  2378. return self._define_metric(
  2379. name,
  2380. step_metric,
  2381. step_sync,
  2382. hidden,
  2383. summary,
  2384. goal,
  2385. overwrite,
  2386. )
  2387. def _define_metric(
  2388. self,
  2389. name: str,
  2390. step_metric: str | wandb_metric.Metric | None = None,
  2391. step_sync: bool | None = None,
  2392. hidden: bool | None = None,
  2393. summary: str | None = None,
  2394. goal: str | None = None,
  2395. overwrite: bool | None = None,
  2396. ) -> wandb_metric.Metric:
  2397. if not name:
  2398. raise wandb.Error("define_metric() requires non-empty name argument")
  2399. if isinstance(step_metric, wandb_metric.Metric):
  2400. step_metric = step_metric.name
  2401. for arg_name, arg_val, exp_type in (
  2402. ("name", name, str),
  2403. ("step_metric", step_metric, str),
  2404. ("step_sync", step_sync, bool),
  2405. ("hidden", hidden, bool),
  2406. ("summary", summary, str),
  2407. ("goal", goal, str),
  2408. ("overwrite", overwrite, bool),
  2409. ):
  2410. # NOTE: type checking is broken for isinstance and str
  2411. if arg_val is not None and not isinstance(arg_val, exp_type):
  2412. arg_type = type(arg_val).__name__
  2413. raise wandb.Error(
  2414. f"Unhandled define_metric() arg: {arg_name} type: {arg_type}"
  2415. )
  2416. stripped = name[:-1] if name.endswith("*") else name
  2417. if "*" in stripped:
  2418. raise wandb.Error(
  2419. f"Unhandled define_metric() arg: name (glob suffixes only): {name}"
  2420. )
  2421. summary_ops: Sequence[str] | None = None
  2422. if summary:
  2423. summary_items = [s.lower() for s in summary.split(",")]
  2424. summary_ops = []
  2425. valid = {"min", "max", "mean", "best", "last", "copy", "none", "first"}
  2426. # TODO: deprecate copy and best
  2427. for i in summary_items:
  2428. if i not in valid:
  2429. raise wandb.Error(f"Unhandled define_metric() arg: summary op: {i}")
  2430. summary_ops.append(i)
  2431. with telemetry.context(run=self) as tel:
  2432. tel.feature.metric_summary = True
  2433. # TODO: deprecate goal
  2434. goal_cleaned: str | None = None
  2435. if goal is not None:
  2436. goal_cleaned = goal[:3].lower()
  2437. valid_goal = {"min", "max"}
  2438. if goal_cleaned not in valid_goal:
  2439. raise wandb.Error(f"Unhandled define_metric() arg: goal: {goal}")
  2440. with telemetry.context(run=self) as tel:
  2441. tel.feature.metric_goal = True
  2442. if hidden:
  2443. with telemetry.context(run=self) as tel:
  2444. tel.feature.metric_hidden = True
  2445. if step_sync:
  2446. with telemetry.context(run=self) as tel:
  2447. tel.feature.metric_step_sync = True
  2448. with telemetry.context(run=self) as tel:
  2449. tel.feature.metric = True
  2450. m = wandb_metric.Metric(
  2451. name=name,
  2452. step_metric=step_metric,
  2453. step_sync=step_sync,
  2454. summary=summary_ops,
  2455. hidden=hidden,
  2456. goal=goal_cleaned,
  2457. overwrite=overwrite,
  2458. )
  2459. m._set_callback(self._metric_callback)
  2460. m._commit()
  2461. return m
  2462. @_log_to_run
  2463. @_attach
  2464. def watch(
  2465. self,
  2466. models: torch.nn.Module | Sequence[torch.nn.Module],
  2467. criterion: torch.F | None = None, # type: ignore
  2468. log: Literal["gradients", "parameters", "all"] | None = "gradients",
  2469. log_freq: int = 1000,
  2470. idx: int | None = None,
  2471. log_graph: bool = False,
  2472. ) -> None:
  2473. """Hook into given PyTorch model to monitor gradients and the model's computational graph.
  2474. This function can track parameters, gradients, or both during training.
  2475. Args:
  2476. models: A single model or a sequence of models to be monitored.
  2477. criterion: The loss function being optimized (optional).
  2478. log: Specifies whether to log "gradients", "parameters", or "all".
  2479. Set to None to disable logging. (default="gradients").
  2480. log_freq: Frequency (in batches) to log gradients and parameters. (default=1000)
  2481. idx: Index used when tracking multiple models with `wandb.watch`. (default=None)
  2482. log_graph: Whether to log the model's computational graph. (default=False)
  2483. Raises:
  2484. ValueError:
  2485. If `wandb.init()` has not been called or if any of the models are not instances
  2486. of `torch.nn.Module`.
  2487. """
  2488. wandb.sdk._watch(self, models, criterion, log, log_freq, idx, log_graph)
  2489. @_log_to_run
  2490. @_attach
  2491. def unwatch(
  2492. self, models: torch.nn.Module | Sequence[torch.nn.Module] | None = None
  2493. ) -> None:
  2494. """Remove pytorch model topology, gradient and parameter hooks.
  2495. Args:
  2496. models: Optional list of pytorch models that have had watch called on them.
  2497. """
  2498. wandb.sdk._unwatch(self, models=models)
  2499. @_log_to_run
  2500. @_raise_if_finished
  2501. @_attach
  2502. def link_artifact(
  2503. self,
  2504. artifact: Artifact,
  2505. target_path: str,
  2506. aliases: list[str] | None = None,
  2507. ) -> Artifact:
  2508. """Link the artifact to a collection.
  2509. The term “link” refers to pointers that connect where W&B stores the
  2510. artifact and where the artifact is accessible in the registry. W&B
  2511. does not duplicate artifacts when you link an artifact to a collection.
  2512. View linked artifacts in the Registry UI for the specified collection.
  2513. Args:
  2514. artifact: The artifact object to link to the collection.
  2515. target_path: The path of the collection. Path consists of the prefix
  2516. "wandb-registry-" along with the registry name and the
  2517. collection name `wandb-registry-{REGISTRY_NAME}/{COLLECTION_NAME}`.
  2518. aliases: Add one or more aliases to the linked artifact. The
  2519. "latest" alias is automatically applied to the most recent artifact
  2520. you link.
  2521. Returns:
  2522. The linked artifact.
  2523. """
  2524. from .artifacts._validators import ArtifactPath
  2525. if artifact.is_draft() and not artifact._is_draft_save_started():
  2526. artifact = self._log_artifact(artifact)
  2527. if self._settings._offline:
  2528. # TODO: implement offline mode + sync
  2529. raise NotImplementedError
  2530. # Normalize the target "entity/project/collection" with defaults
  2531. # inferred from this run's entity and project, if needed.
  2532. #
  2533. # HOWEVER, if the target path is a registry collection, avoid setting
  2534. # the target entity to the run's entity. Instead, delegate to
  2535. # Artifact.link() to resolve the required org entity.
  2536. target = ArtifactPath.from_str(target_path)
  2537. if not target.is_registry_path():
  2538. target = target.with_defaults(prefix=self.entity, project=self.project)
  2539. return artifact.link(target.to_str(), aliases)
  2540. @_log_to_run
  2541. @_raise_if_finished
  2542. @_attach
  2543. def use_artifact(
  2544. self,
  2545. artifact_or_name: str | Artifact,
  2546. type: str | None = None,
  2547. aliases: list[str] | None = None,
  2548. use_as: str | None = None,
  2549. ) -> Artifact:
  2550. """Declare an artifact as an input to a run.
  2551. Call `download` or `file` on the returned object to get the contents locally.
  2552. Args:
  2553. artifact_or_name: The name of the artifact to use. May be prefixed
  2554. with the name of the project the artifact was logged to
  2555. ("entity" or "entity/project"). If no
  2556. entity is specified in the name, the Run or API setting's entity is used.
  2557. Valid names can be in the following forms
  2558. - name:version
  2559. - name:alias
  2560. type: The type of artifact to use.
  2561. aliases: Aliases to apply to this artifact
  2562. use_as: This argument is deprecated and does nothing.
  2563. Returns:
  2564. An `Artifact` object.
  2565. Examples:
  2566. ```python
  2567. import wandb
  2568. run = wandb.init(project="<example>")
  2569. # Use an artifact by name and alias
  2570. artifact_a = run.use_artifact(artifact_or_name="<name>:<alias>")
  2571. # Use an artifact by name and version
  2572. artifact_b = run.use_artifact(artifact_or_name="<name>:v<version>")
  2573. # Use an artifact by entity/project/name:alias
  2574. artifact_c = run.use_artifact(
  2575. artifact_or_name="<entity>/<project>/<name>:<alias>"
  2576. )
  2577. # Use an artifact by entity/project/name:version
  2578. artifact_d = run.use_artifact(
  2579. artifact_or_name="<entity>/<project>/<name>:v<version>"
  2580. )
  2581. # Explicitly finish the run since a context manager is not used.
  2582. run.finish()
  2583. ```
  2584. """
  2585. from wandb.apis import internal
  2586. from wandb.sdk.artifacts.artifact import Artifact
  2587. if self._settings._offline:
  2588. raise TypeError("Cannot use artifact when in offline mode.")
  2589. api = internal.Api(
  2590. default_settings={
  2591. "entity": self._settings.entity,
  2592. "project": self._settings.project,
  2593. }
  2594. )
  2595. api.set_current_run_id(self._settings.run_id)
  2596. if use_as is not None:
  2597. deprecation.warn_and_record_deprecation(
  2598. feature=Deprecated(run__use_artifact_use_as=True),
  2599. message=(
  2600. "`use_as` argument is deprecated and does not affect the behaviour of `run.use_artifact`"
  2601. ),
  2602. )
  2603. if isinstance(artifact_or_name, str):
  2604. name = artifact_or_name
  2605. public_api = self._public_api()
  2606. artifact = public_api._artifact(type=type, name=name)
  2607. if type is not None and type != artifact.type:
  2608. raise ValueError(
  2609. f"Supplied type {type} does not match type {artifact.type} of artifact {artifact.name}"
  2610. )
  2611. api.use_artifact(
  2612. artifact.id,
  2613. entity_name=self._settings.entity,
  2614. project_name=self._settings.project,
  2615. artifact_entity_name=artifact.entity,
  2616. artifact_project_name=artifact.project,
  2617. )
  2618. else:
  2619. artifact = artifact_or_name
  2620. if aliases is None:
  2621. aliases = []
  2622. elif isinstance(aliases, str):
  2623. aliases = [aliases]
  2624. if isinstance(artifact_or_name, Artifact) and artifact.is_draft():
  2625. if use_as is not None:
  2626. wandb.termwarn(
  2627. "Indicating use_as is not supported when using a draft artifact"
  2628. )
  2629. self._log_artifact(
  2630. artifact,
  2631. aliases=aliases,
  2632. is_user_created=True,
  2633. use_after_commit=True,
  2634. )
  2635. artifact.wait()
  2636. elif isinstance(artifact, Artifact) and not artifact.is_draft():
  2637. api.use_artifact(
  2638. artifact.id,
  2639. artifact_entity_name=artifact.entity,
  2640. artifact_project_name=artifact.project,
  2641. )
  2642. else:
  2643. raise ValueError(
  2644. 'You must pass an artifact name (e.g. "pedestrian-dataset:v1"), '
  2645. "an instance of `wandb.Artifact`, or `wandb.Api().artifact()` to `use_artifact`"
  2646. )
  2647. if self._backend and self._backend.interface:
  2648. self._backend.interface.publish_use_artifact(artifact)
  2649. return artifact
  2650. @_log_to_run
  2651. @_raise_if_finished
  2652. @_attach
  2653. def log_artifact(
  2654. self,
  2655. artifact_or_path: Artifact | StrPath,
  2656. name: str | None = None,
  2657. type: str | None = None,
  2658. aliases: list[str] | None = None,
  2659. tags: list[str] | None = None,
  2660. ) -> Artifact:
  2661. """Declare an artifact as an output of a run.
  2662. Args:
  2663. artifact_or_path: (str or Artifact) A path to the contents of this artifact,
  2664. can be in the following forms:
  2665. - `/local/directory`
  2666. - `/local/directory/file.txt`
  2667. - `s3://bucket/path`
  2668. You can also pass an Artifact object created by calling
  2669. `wandb.Artifact`.
  2670. name: (str, optional) An artifact name. Valid names can be in the following forms:
  2671. - name:version
  2672. - name:alias
  2673. - digest
  2674. This will default to the basename of the path prepended with the current
  2675. run id if not specified.
  2676. type: (str) The type of artifact to log, examples include `dataset`, `model`
  2677. aliases: (list, optional) Aliases to apply to this artifact,
  2678. defaults to `["latest"]`
  2679. tags: (list, optional) Tags to apply to this artifact, if any.
  2680. Returns:
  2681. An `Artifact` object.
  2682. """
  2683. return self._log_artifact(
  2684. artifact_or_path,
  2685. name=name,
  2686. type=type,
  2687. aliases=aliases,
  2688. tags=tags,
  2689. )
  2690. @_log_to_run
  2691. @_raise_if_finished
  2692. @_attach
  2693. def upsert_artifact(
  2694. self,
  2695. artifact_or_path: Artifact | str,
  2696. name: str | None = None,
  2697. type: str | None = None,
  2698. aliases: list[str] | None = None,
  2699. distributed_id: str | None = None,
  2700. ) -> Artifact:
  2701. """Declare (or append to) a non-finalized artifact as output of a run.
  2702. Note that you must call run.finish_artifact() to finalize the artifact.
  2703. This is useful when distributed jobs need to all contribute to the same artifact.
  2704. Args:
  2705. artifact_or_path: A path to the contents of this artifact,
  2706. can be in the following forms:
  2707. - `/local/directory`
  2708. - `/local/directory/file.txt`
  2709. - `s3://bucket/path`
  2710. name: An artifact name. May be prefixed with "entity/project". Defaults
  2711. to the basename of the path prepended with the current run ID
  2712. if not specified. Valid names can be in the following forms:
  2713. - name:version
  2714. - name:alias
  2715. - digest
  2716. type: The type of artifact to log. Common examples include `dataset`, `model`.
  2717. aliases: Aliases to apply to this artifact, defaults to `["latest"]`.
  2718. distributed_id: Unique string that all distributed jobs share. If None,
  2719. defaults to the run's group name.
  2720. Returns:
  2721. An `Artifact` object.
  2722. """
  2723. if self._settings.run_group is None and distributed_id is None:
  2724. raise TypeError(
  2725. "Cannot upsert artifact unless run is in a group or distributed_id is provided"
  2726. )
  2727. if distributed_id is None:
  2728. distributed_id = self._settings.run_group or ""
  2729. return self._log_artifact(
  2730. artifact_or_path,
  2731. name=name,
  2732. type=type,
  2733. aliases=aliases,
  2734. distributed_id=distributed_id,
  2735. finalize=False,
  2736. )
  2737. @_log_to_run
  2738. @_raise_if_finished
  2739. @_attach
  2740. def finish_artifact(
  2741. self,
  2742. artifact_or_path: Artifact | str,
  2743. name: str | None = None,
  2744. type: str | None = None,
  2745. aliases: list[str] | None = None,
  2746. distributed_id: str | None = None,
  2747. ) -> Artifact:
  2748. """Finishes a non-finalized artifact as output of a run.
  2749. Subsequent "upserts" with the same distributed ID will result in a new version.
  2750. Args:
  2751. artifact_or_path: A path to the contents of this artifact,
  2752. can be in the following forms:
  2753. - `/local/directory`
  2754. - `/local/directory/file.txt`
  2755. - `s3://bucket/path`
  2756. You can also pass an Artifact object created by calling
  2757. `wandb.Artifact`.
  2758. name: An artifact name. May be prefixed with entity/project.
  2759. Valid names can be in the following forms:
  2760. - name:version
  2761. - name:alias
  2762. - digest
  2763. This will default to the basename of the path prepended with the current
  2764. run id if not specified.
  2765. type: The type of artifact to log, examples include `dataset`, `model`
  2766. aliases: Aliases to apply to this artifact,
  2767. defaults to `["latest"]`
  2768. distributed_id: Unique string that all distributed jobs share. If None,
  2769. defaults to the run's group name.
  2770. Returns:
  2771. An `Artifact` object.
  2772. """
  2773. if self._settings.run_group is None and distributed_id is None:
  2774. raise TypeError(
  2775. "Cannot finish artifact unless run is in a group or distributed_id is provided"
  2776. )
  2777. if distributed_id is None:
  2778. distributed_id = self._settings.run_group or ""
  2779. return self._log_artifact(
  2780. artifact_or_path,
  2781. name,
  2782. type,
  2783. aliases,
  2784. distributed_id=distributed_id,
  2785. finalize=True,
  2786. )
  2787. def _log_artifact(
  2788. self,
  2789. artifact_or_path: Artifact | StrPath,
  2790. name: str | None = None,
  2791. type: str | None = None,
  2792. aliases: list[str] | None = None,
  2793. tags: list[str] | None = None,
  2794. distributed_id: str | None = None,
  2795. finalize: bool = True,
  2796. is_user_created: bool = False,
  2797. use_after_commit: bool = False,
  2798. ) -> Artifact:
  2799. from .artifacts._validators import validate_aliases, validate_tags
  2800. if not finalize and distributed_id is None:
  2801. raise TypeError("Must provide distributed_id if artifact is not finalize")
  2802. if aliases is not None:
  2803. aliases = validate_aliases(aliases)
  2804. # Check if artifact tags are supported
  2805. if tags is not None:
  2806. tags = validate_tags(tags)
  2807. artifact, aliases = self._prepare_artifact(
  2808. artifact_or_path, name, type, aliases
  2809. )
  2810. artifact.metadata = {**artifact.metadata} # triggers validation
  2811. artifact.distributed_id = distributed_id
  2812. self._assert_can_log_artifact(artifact)
  2813. if self._backend and self._backend.interface:
  2814. if not self._settings._offline:
  2815. handle = self._backend.interface.deliver_artifact(
  2816. self,
  2817. artifact,
  2818. aliases,
  2819. tags,
  2820. self.step,
  2821. finalize=finalize,
  2822. is_user_created=is_user_created,
  2823. use_after_commit=use_after_commit,
  2824. )
  2825. artifact._set_save_handle(handle, self._public_api().client)
  2826. else:
  2827. self._backend.interface.publish_artifact(
  2828. self,
  2829. artifact,
  2830. aliases,
  2831. tags,
  2832. finalize=finalize,
  2833. is_user_created=is_user_created,
  2834. use_after_commit=use_after_commit,
  2835. )
  2836. elif self._internal_run_interface:
  2837. self._internal_run_interface.publish_artifact(
  2838. self,
  2839. artifact,
  2840. aliases,
  2841. tags,
  2842. finalize=finalize,
  2843. is_user_created=is_user_created,
  2844. use_after_commit=use_after_commit,
  2845. )
  2846. return artifact
  2847. def _public_api(self, overrides: dict[str, str] | None = None) -> PublicApi:
  2848. if self._cached_public_api is not None:
  2849. return self._cached_public_api
  2850. # NOTE: PublicApi is only for type checking, still need to import
  2851. from wandb.apis import public
  2852. overrides = {"run": self._settings.run_id} # type: ignore
  2853. if not self._settings._offline:
  2854. overrides["entity"] = self._settings.entity or ""
  2855. overrides["project"] = self._settings.project or ""
  2856. overrides["base_url"] = self._settings.base_url
  2857. self._cached_public_api = public.Api(overrides, api_key=self._settings.api_key)
  2858. return self._cached_public_api
  2859. # TODO(jhr): annotate this
  2860. def _assert_can_log_artifact(self, artifact) -> None: # type: ignore
  2861. import requests
  2862. from wandb.sdk.artifacts.artifact import Artifact
  2863. if self._settings._offline:
  2864. return
  2865. try:
  2866. public_api = self._public_api()
  2867. entity = public_api.settings["entity"]
  2868. project = public_api.settings["project"]
  2869. expected_type = Artifact._expected_type(
  2870. entity, project, artifact.name, public_api.client
  2871. )
  2872. except requests.exceptions.RequestException:
  2873. # Just return early if there is a network error. This is
  2874. # ok, as this function is intended to help catch an invalid
  2875. # type early, but not a hard requirement for valid operation.
  2876. return
  2877. if expected_type is not None and artifact.type != expected_type:
  2878. raise ValueError(
  2879. f"Artifact {artifact.name} already exists with type '{expected_type}'; "
  2880. f"cannot create another with type '{artifact.type}'"
  2881. )
  2882. if entity and artifact._source_entity and entity != artifact._source_entity:
  2883. raise ValueError(
  2884. f"Artifact {artifact.name} is owned by entity "
  2885. f"'{artifact._source_entity}'; it can't be moved to '{entity}'"
  2886. )
  2887. if project and artifact._source_project and project != artifact._source_project:
  2888. raise ValueError(
  2889. f"Artifact {artifact.name} exists in project "
  2890. f"'{artifact._source_project}'; it can't be moved to '{project}'"
  2891. )
  2892. def _prepare_artifact(
  2893. self,
  2894. artifact_or_path: Artifact | StrPath,
  2895. name: str | None = None,
  2896. type: str | None = None,
  2897. aliases: list[str] | None = None,
  2898. ) -> tuple[Artifact, list[str]]:
  2899. from wandb.sdk.artifacts.artifact import Artifact
  2900. if isinstance(artifact_or_path, (str, os.PathLike)):
  2901. name = (
  2902. name
  2903. or f"run-{self._settings.run_id}-{os.path.basename(artifact_or_path)}"
  2904. )
  2905. artifact = Artifact(name, type or "unspecified")
  2906. if os.path.isfile(artifact_or_path):
  2907. artifact.add_file(str(artifact_or_path))
  2908. elif os.path.isdir(artifact_or_path):
  2909. artifact.add_dir(str(artifact_or_path))
  2910. elif "://" in str(artifact_or_path):
  2911. artifact.add_reference(str(artifact_or_path))
  2912. else:
  2913. raise ValueError(
  2914. "path must be a file, directory or external"
  2915. "reference like s3://bucket/path"
  2916. )
  2917. else:
  2918. artifact = artifact_or_path
  2919. if not isinstance(artifact, Artifact):
  2920. raise TypeError(
  2921. "You must pass an instance of wandb.Artifact or a "
  2922. "valid file path to log_artifact"
  2923. )
  2924. artifact.finalize()
  2925. return artifact, _resolve_aliases(aliases)
  2926. @_log_to_run
  2927. @_raise_if_finished
  2928. @_attach
  2929. def log_model(
  2930. self,
  2931. path: StrPath,
  2932. name: str | None = None,
  2933. aliases: list[str] | None = None,
  2934. ) -> None:
  2935. """Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run.
  2936. The name of model artifact can only contain alphanumeric characters,
  2937. underscores, and hyphens.
  2938. Args:
  2939. path: (str) A path to the contents of this model,
  2940. can be in the following forms:
  2941. - `/local/directory`
  2942. - `/local/directory/file.txt`
  2943. - `s3://bucket/path`
  2944. name: A name to assign to the model artifact that
  2945. the file contents will be added to. This will default to the
  2946. basename of the path prepended with the current run id if
  2947. not specified.
  2948. aliases: Aliases to apply to the created model artifact,
  2949. defaults to `["latest"]`
  2950. Raises:
  2951. ValueError: If name has invalid special characters.
  2952. Returns:
  2953. None
  2954. """
  2955. self._log_artifact(
  2956. artifact_or_path=path, name=name, type="model", aliases=aliases
  2957. )
  2958. @_log_to_run
  2959. @_raise_if_finished
  2960. @_attach
  2961. def use_model(self, name: str) -> FilePathStr:
  2962. """Download the files logged in a model artifact 'name'.
  2963. Args:
  2964. name: A model artifact name. 'name' must match the name of an existing logged
  2965. model artifact. May be prefixed with `entity/project/`. Valid names
  2966. can be in the following forms
  2967. - model_artifact_name:version
  2968. - model_artifact_name:alias
  2969. Returns:
  2970. path (str): Path to downloaded model artifact file(s).
  2971. Raises:
  2972. AssertionError: If model artifact 'name' is of a type that does
  2973. not contain the substring 'model'.
  2974. """
  2975. if self._settings._offline:
  2976. # Downloading artifacts is not supported when offline.
  2977. raise RuntimeError("`use_model` not supported in offline mode.")
  2978. artifact = self.use_artifact(artifact_or_name=name)
  2979. if "model" not in str(artifact.type.lower()):
  2980. raise AssertionError(
  2981. "You can only use this method for 'model' artifacts."
  2982. " For an artifact to be a 'model' artifact, its type property"
  2983. " must contain the substring 'model'."
  2984. )
  2985. path = artifact.download()
  2986. # If returned directory contains only one file, return path to that file
  2987. dir_list = os.listdir(path)
  2988. if len(dir_list) == 1:
  2989. return FilePathStr(os.path.join(path, dir_list[0]))
  2990. return path
  2991. @_log_to_run
  2992. @_raise_if_finished
  2993. @_attach
  2994. def link_model(
  2995. self,
  2996. path: StrPath,
  2997. registered_model_name: str,
  2998. name: str | None = None,
  2999. aliases: list[str] | None = None,
  3000. ) -> Artifact | None:
  3001. """Log a model artifact version and link it to a registered model in the model registry.
  3002. Linked model versions are visible in the UI for the specified registered model.
  3003. This method will:
  3004. - Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files
  3005. located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name'
  3006. of type 'model'.
  3007. - Check if registered model with name 'registered_model_name' exists in the 'model-registry' project.
  3008. If not, create a new registered model with name 'registered_model_name'.
  3009. - Link version of model artifact 'name' to registered model, 'registered_model_name'.
  3010. - Attach aliases from 'aliases' list to the newly linked model artifact version.
  3011. Args:
  3012. path: (str) A path to the contents of this model, can be in the
  3013. following forms:
  3014. - `/local/directory`
  3015. - `/local/directory/file.txt`
  3016. - `s3://bucket/path`
  3017. registered_model_name: The name of the registered model that the
  3018. model is to be linked to. A registered model is a collection of
  3019. model versions linked to the model registry, typically
  3020. representing a team's specific ML Task. The entity that this
  3021. registered model belongs to will be derived from the run.
  3022. name: The name of the model artifact that files in 'path' will be
  3023. logged to. This will default to the basename of the path
  3024. prepended with the current run id if not specified.
  3025. aliases: Aliases that will only be applied on this linked artifact
  3026. inside the registered model. The alias "latest" will always be
  3027. applied to the latest version of an artifact that is linked.
  3028. Raises:
  3029. AssertionError: If registered_model_name is a path or
  3030. if model artifact 'name' is of a type that does not contain
  3031. the substring 'model'.
  3032. ValueError: If name has invalid special characters.
  3033. Returns:
  3034. The linked artifact if linking was successful, otherwise `None`.
  3035. """
  3036. name_parts = registered_model_name.split("/")
  3037. if len(name_parts) != 1:
  3038. raise AssertionError(
  3039. "Please provide only the name of the registered model."
  3040. " Do not append the entity or project name."
  3041. )
  3042. project = "model-registry"
  3043. target_path = self.entity + "/" + project + "/" + registered_model_name
  3044. public_api = self._public_api()
  3045. try:
  3046. artifact = public_api._artifact(name=f"{name}:latest")
  3047. if "model" not in str(artifact.type.lower()):
  3048. raise AssertionError(
  3049. "You can only use this method for 'model' artifacts."
  3050. " For an artifact to be a 'model' artifact, its type"
  3051. " property must contain the substring 'model'."
  3052. )
  3053. artifact = self._log_artifact(
  3054. artifact_or_path=path, name=name, type=artifact.type
  3055. )
  3056. except (ValueError, CommError):
  3057. artifact = self._log_artifact(
  3058. artifact_or_path=path, name=name, type="model"
  3059. )
  3060. return self.link_artifact(
  3061. artifact=artifact, target_path=target_path, aliases=aliases
  3062. )
  3063. @_log_to_run
  3064. @_raise_if_finished
  3065. @_attach
  3066. def alert(
  3067. self,
  3068. title: str,
  3069. text: str,
  3070. level: str | AlertLevel | None = None,
  3071. wait_duration: int | float | timedelta | None = None,
  3072. ) -> None:
  3073. """Create an alert with the given title and text.
  3074. Args:
  3075. title: The title of the alert, must be less than 64 characters long.
  3076. text: The text body of the alert.
  3077. level: The alert level to use, either: `INFO`, `WARN`, or `ERROR`.
  3078. wait_duration: The time to wait (in seconds) before sending another
  3079. alert with this title.
  3080. """
  3081. level = level or AlertLevel.INFO
  3082. level_str: str = level.value if isinstance(level, AlertLevel) else level
  3083. if level_str not in {lev.value for lev in AlertLevel}:
  3084. raise ValueError("level must be one of 'INFO', 'WARN', or 'ERROR'")
  3085. wait_duration = wait_duration or timedelta(minutes=1)
  3086. if isinstance(wait_duration, (int, float)):
  3087. wait_duration = timedelta(seconds=wait_duration)
  3088. elif not callable(getattr(wait_duration, "total_seconds", None)):
  3089. raise TypeError(
  3090. "wait_duration must be an int, float, or datetime.timedelta"
  3091. )
  3092. wait_duration = int(wait_duration.total_seconds() * 1000)
  3093. if self._backend and self._backend.interface:
  3094. self._backend.interface.publish_alert(title, text, level_str, wait_duration)
  3095. def __enter__(self) -> Run:
  3096. return self
  3097. def __exit__(
  3098. self,
  3099. exc_type: type[BaseException] | None,
  3100. exc_val: BaseException | None,
  3101. exc_tb: TracebackType | None,
  3102. ) -> bool:
  3103. exception_raised = exc_type is not None
  3104. if exception_raised:
  3105. traceback.print_exception(exc_type, exc_val, exc_tb)
  3106. exit_code = 1 if exception_raised else 0
  3107. self._finish(exit_code=exit_code)
  3108. return not exception_raised
  3109. @_log_to_run
  3110. @_raise_if_finished
  3111. @_attach
  3112. def mark_preempting(self) -> None:
  3113. """Mark this run as preempting.
  3114. Also tells the internal process to immediately report this to server.
  3115. """
  3116. if self._backend and self._backend.interface:
  3117. self._backend.interface.publish_preempting()
  3118. @property
  3119. @_log_to_run
  3120. @_raise_if_finished
  3121. @_attach
  3122. def _system_metrics(self) -> dict[str, list[tuple[datetime, float]]]:
  3123. """Returns a dictionary of system metrics.
  3124. Returns:
  3125. A dictionary of system metrics.
  3126. """
  3127. from wandb.proto import wandb_internal_pb2
  3128. def pb_to_dict(
  3129. system_metrics_pb: wandb_internal_pb2.GetSystemMetricsResponse,
  3130. ) -> dict[str, list[tuple[datetime, float]]]:
  3131. res = {}
  3132. for metric, records in system_metrics_pb.system_metrics.items():
  3133. measurements = []
  3134. for record in records.record:
  3135. # Convert timestamp to datetime
  3136. dt = datetime.fromtimestamp(
  3137. record.timestamp.seconds, tz=timezone.utc
  3138. )
  3139. dt = dt.replace(microsecond=record.timestamp.nanos // 1000)
  3140. measurements.append((dt, record.value))
  3141. res[metric] = measurements
  3142. return res
  3143. if not self._backend or not self._backend.interface:
  3144. return {}
  3145. handle = self._backend.interface.deliver_get_system_metrics()
  3146. try:
  3147. result = handle.wait_or(timeout=1)
  3148. except TimeoutError:
  3149. return {}
  3150. else:
  3151. try:
  3152. response = result.response.get_system_metrics_response
  3153. return pb_to_dict(response) if response else {}
  3154. except Exception:
  3155. logger.exception("Error getting system metrics.")
  3156. return {}
  3157. # ------------------------------------------------------------------------------
  3158. # HEADER
  3159. # ------------------------------------------------------------------------------
  3160. def _header(self) -> None:
  3161. self._header_wandb_version_info()
  3162. self._header_sync_info()
  3163. self._header_run_info()
  3164. def _header_wandb_version_info(self) -> None:
  3165. if self._settings.quiet or self._settings.silent:
  3166. return
  3167. # TODO: add this to a higher verbosity level
  3168. self._printer.display(f"Tracking run with wandb version {wandb.__version__}")
  3169. def _header_sync_info(self) -> None:
  3170. sync_location_msg = f"Run data is saved locally in {self._printer.files(self._settings.sync_dir)}"
  3171. if self._settings._offline:
  3172. offline_warning = (
  3173. f"W&B syncing is set to {self._printer.code('`offline`')} "
  3174. f"in this directory. Run {self._printer.code('`wandb online`')} "
  3175. f"or set {self._printer.code('WANDB_MODE=online')} "
  3176. "to enable cloud syncing."
  3177. )
  3178. self._printer.display([offline_warning, sync_location_msg])
  3179. else:
  3180. messages = [sync_location_msg]
  3181. if not self._printer.supports_html:
  3182. disable_sync_msg = (
  3183. f"Run {self._printer.code('`wandb offline`')} to turn off syncing."
  3184. )
  3185. messages.append(disable_sync_msg)
  3186. if not self._settings.quiet and not self._settings.silent:
  3187. self._printer.display(messages)
  3188. def _header_run_info(self) -> None:
  3189. settings, printer = self._settings, self._printer
  3190. if settings._offline or settings.silent:
  3191. return
  3192. run_url = settings.run_url
  3193. project_url = settings.project_url
  3194. sweep_url = settings.sweep_url
  3195. run_state_str = (
  3196. "Resuming run"
  3197. if settings.resumed or settings.resume_from
  3198. else "Syncing run"
  3199. )
  3200. run_name = settings.run_name
  3201. if not run_name:
  3202. return
  3203. if printer.supports_html:
  3204. import wandb.jupyter
  3205. if not wandb.jupyter.display_if_magic_is_used(self):
  3206. run_line = f"<strong>{printer.link(run_url, run_name)}</strong>"
  3207. project_line, sweep_line = "", ""
  3208. if not settings.quiet:
  3209. doc_html = printer.link(url_registry.url("developer-guide"), "docs")
  3210. project_html = printer.link(project_url, "Weights & Biases")
  3211. project_line = f"to {project_html} ({doc_html})"
  3212. if sweep_url:
  3213. sweep_line = f"Sweep page: {printer.link(sweep_url, sweep_url)}"
  3214. printer.display(
  3215. [f"{run_state_str} {run_line} {project_line}", sweep_line],
  3216. )
  3217. elif run_name:
  3218. printer.display(f"{run_state_str} {printer.name(run_name)}")
  3219. if not settings.quiet:
  3220. # TODO: add verbosity levels and add this to higher levels
  3221. printer.display(
  3222. f"{printer.emoji('star')} View project at {printer.link(project_url)}"
  3223. )
  3224. if sweep_url:
  3225. printer.display(
  3226. f"{printer.emoji('broom')} View sweep at {printer.link(sweep_url)}"
  3227. )
  3228. printer.display(
  3229. f"{printer.emoji('rocket')} View run at {printer.link(run_url)}",
  3230. )
  3231. # ------------------------------------------------------------------------------
  3232. # FOOTER
  3233. # ------------------------------------------------------------------------------
  3234. # Note: All the footer methods are static methods since we want to share the printing logic
  3235. # with the service execution path that doesn't have access to the run instance
  3236. @staticmethod
  3237. def _footer(
  3238. sampled_history: SampledHistoryResponse | None = None,
  3239. final_summary: GetSummaryResponse | None = None,
  3240. poll_exit_response: PollExitResponse | None = None,
  3241. internal_messages_response: InternalMessagesResponse | None = None,
  3242. *,
  3243. settings: Settings,
  3244. printer: printer.Printer,
  3245. ) -> None:
  3246. Run._footer_history_summary_info(
  3247. history=sampled_history,
  3248. summary=final_summary,
  3249. settings=settings,
  3250. printer=printer,
  3251. )
  3252. Run._footer_sync_info(
  3253. poll_exit_response=poll_exit_response,
  3254. settings=settings,
  3255. printer=printer,
  3256. )
  3257. Run._footer_log_dir_info(settings=settings, printer=printer)
  3258. Run._footer_internal_messages(
  3259. internal_messages_response=internal_messages_response,
  3260. settings=settings,
  3261. printer=printer,
  3262. )
  3263. @staticmethod
  3264. def _footer_sync_info(
  3265. poll_exit_response: PollExitResponse | None = None,
  3266. *,
  3267. settings: Settings,
  3268. printer: printer.Printer,
  3269. ) -> None:
  3270. if settings.silent:
  3271. return
  3272. if settings._offline:
  3273. if not settings.quiet:
  3274. printer.display(
  3275. [
  3276. "You can sync this run to the cloud by running:",
  3277. printer.code(f"wandb sync {settings.sync_dir}"),
  3278. ],
  3279. )
  3280. return
  3281. info = []
  3282. if settings.run_name and settings.run_url:
  3283. info.append(
  3284. f"{printer.emoji('rocket')} View run {printer.name(settings.run_name)} at: {printer.link(settings.run_url)}"
  3285. )
  3286. if settings.project_url:
  3287. info.append(
  3288. f"{printer.emoji('star')} View project at: {printer.link(settings.project_url)}"
  3289. )
  3290. if poll_exit_response and poll_exit_response.file_counts:
  3291. logger.info("logging synced files")
  3292. file_counts = poll_exit_response.file_counts
  3293. info.append(
  3294. f"Synced {file_counts.wandb_count} W&B file(s), {file_counts.media_count} media file(s), "
  3295. f"{file_counts.artifact_count} artifact file(s) and {file_counts.other_count} other file(s)",
  3296. )
  3297. printer.display(info)
  3298. @staticmethod
  3299. def _footer_log_dir_info(
  3300. *,
  3301. settings: Settings,
  3302. printer: printer.Printer,
  3303. ) -> None:
  3304. if settings.quiet or settings.silent:
  3305. return
  3306. log_dir = settings.log_user or settings.log_internal
  3307. if log_dir:
  3308. log_dir = os.path.dirname(log_dir.replace(os.getcwd(), "."))
  3309. printer.display(
  3310. f"Find logs at: {printer.files(log_dir)}",
  3311. )
  3312. @staticmethod
  3313. def _footer_history_summary_info(
  3314. history: SampledHistoryResponse | None = None,
  3315. summary: GetSummaryResponse | None = None,
  3316. *,
  3317. settings: Settings,
  3318. printer: printer.Printer,
  3319. ) -> None:
  3320. if settings.quiet or settings.silent:
  3321. return
  3322. panel: list[str] = []
  3323. if history and (
  3324. history_grid := Run._footer_history(history, printer, settings)
  3325. ):
  3326. panel.append(history_grid)
  3327. if summary and (
  3328. summary_grid := Run._footer_summary(summary, printer, settings)
  3329. ):
  3330. panel.append(summary_grid)
  3331. if panel:
  3332. printer.display(printer.panel(panel))
  3333. @staticmethod
  3334. def _footer_history(
  3335. history: SampledHistoryResponse,
  3336. printer: printer.Printer,
  3337. settings: Settings,
  3338. ) -> str | None:
  3339. """Returns the run history formatted for printing to the console."""
  3340. sorted_history_items = sorted(
  3341. (item for item in history.item if not item.key.startswith("_")),
  3342. key=lambda item: item.key,
  3343. )
  3344. history_rows: list[list[str]] = []
  3345. for item in sorted_history_items:
  3346. if len(history_rows) >= settings.max_end_of_run_history_metrics:
  3347. break
  3348. values = wandb.util.downsample(
  3349. item.values_float or item.values_int,
  3350. 40,
  3351. )
  3352. if sparkline := printer.sparklines(values):
  3353. history_rows.append([item.key, sparkline])
  3354. if not history_rows:
  3355. return None
  3356. if len(history_rows) < len(sorted_history_items):
  3357. remaining = len(sorted_history_items) - len(history_rows)
  3358. history_rows.append([f"+{remaining:,d}", "..."])
  3359. return printer.grid(history_rows, "Run history:")
  3360. @staticmethod
  3361. def _footer_summary(
  3362. summary: GetSummaryResponse,
  3363. printer: printer.Printer,
  3364. settings: Settings,
  3365. ) -> str | None:
  3366. """Returns the run summary formatted for printing to the console."""
  3367. sorted_summary_items = sorted(
  3368. (
  3369. item
  3370. for item in summary.item
  3371. if not item.key.startswith("_") and not item.nested_key
  3372. ),
  3373. key=lambda item: item.key,
  3374. )
  3375. summary_rows: list[list[str]] = []
  3376. skipped = 0
  3377. for item in sorted_summary_items:
  3378. if len(summary_rows) >= settings.max_end_of_run_summary_metrics:
  3379. break
  3380. try:
  3381. value = json.loads(item.value_json)
  3382. except json.JSONDecodeError:
  3383. logger.exception(f"Error decoding summary[{item.key!r}]")
  3384. skipped += 1
  3385. continue
  3386. if isinstance(value, str):
  3387. value = value[:20] + "..." * (len(value) >= 20)
  3388. summary_rows.append([item.key, value])
  3389. elif isinstance(value, numbers.Number):
  3390. value = round(value, 5) if isinstance(value, float) else value
  3391. summary_rows.append([item.key, str(value)])
  3392. else:
  3393. skipped += 1
  3394. if not summary_rows:
  3395. return None
  3396. if len(summary_rows) < len(sorted_summary_items) - skipped:
  3397. remaining = len(sorted_summary_items) - len(summary_rows) - skipped
  3398. summary_rows.append([f"+{remaining:,d}", "..."])
  3399. return printer.grid(summary_rows, "Run summary:")
  3400. @staticmethod
  3401. def _footer_internal_messages(
  3402. internal_messages_response: InternalMessagesResponse | None = None,
  3403. *,
  3404. settings: Settings,
  3405. printer: printer.Printer,
  3406. ) -> None:
  3407. if settings.quiet or settings.silent:
  3408. return
  3409. if not internal_messages_response:
  3410. return
  3411. for message in internal_messages_response.messages.warning:
  3412. printer.display(message, level="warn")
  3413. # We define this outside of the run context to support restoring before init
  3414. def restore(
  3415. name: str,
  3416. run_path: str | None = None,
  3417. replace: bool = False,
  3418. root: str | None = None,
  3419. ) -> None | TextIO:
  3420. """Download the specified file from cloud storage.
  3421. File is placed into the current directory or run directory.
  3422. By default, will only download the file if it doesn't already exist.
  3423. Args:
  3424. name: The name of the file.
  3425. run_path: Optional path to a run to pull files from, i.e. `username/project_name/run_id`
  3426. if wandb.init has not been called, this is required.
  3427. replace: Whether to download the file even if it already exists locally
  3428. root: The directory to download the file to. Defaults to the current
  3429. directory or the run directory if wandb.init was called.
  3430. Returns:
  3431. None if it can't find the file, otherwise a file object open for reading.
  3432. Raises:
  3433. CommError: If W&B can't connect to the W&B backend.
  3434. ValueError: If the file is not found or can't find run_path.
  3435. """
  3436. from wandb.apis import public
  3437. is_disabled = wandb.run is not None and wandb.run.disabled
  3438. run = None if is_disabled else wandb.run
  3439. if run_path is None:
  3440. if run is not None:
  3441. run_path = run.path
  3442. else:
  3443. raise ValueError(
  3444. "run_path required when calling wandb.restore before wandb.init"
  3445. )
  3446. if root is None and run is not None:
  3447. root = run.dir
  3448. api = public.Api()
  3449. api_run = api.run(run_path)
  3450. if root is None:
  3451. root = os.getcwd()
  3452. path = os.path.join(root, name)
  3453. if os.path.exists(path) and replace is False:
  3454. return open(path)
  3455. if is_disabled:
  3456. return None
  3457. files = api_run.files([name])
  3458. if len(files) == 0:
  3459. return None
  3460. # if the file does not exist, the file has an md5 of 0
  3461. if files[0].md5 == "0":
  3462. raise ValueError(f"File {name} not found in {run_path or root}.")
  3463. return files[0].download(root=root, replace=True)
  3464. # propagate our doc string to the runs restore method
  3465. try:
  3466. Run.restore.__doc__ = restore.__doc__
  3467. except AttributeError:
  3468. pass
  3469. def finish(
  3470. exit_code: int | None = None,
  3471. quiet: bool | None = None,
  3472. ) -> None:
  3473. """Finish a run and upload any remaining data.
  3474. Marks the completion of a W&B run and ensures all data is synced to the server.
  3475. The run's final state is determined by its exit conditions and sync status.
  3476. Run States:
  3477. - Running: Active run that is logging data and/or sending heartbeats.
  3478. - Crashed: Run that stopped sending heartbeats unexpectedly.
  3479. - Finished: Run completed successfully (`exit_code=0`) with all data synced.
  3480. - Failed: Run completed with errors (`exit_code!=0`).
  3481. Args:
  3482. exit_code: Integer indicating the run's exit status. Use 0 for success,
  3483. any other value marks the run as failed.
  3484. quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`.
  3485. """
  3486. if wandb.run:
  3487. wandb.run.finish(exit_code=exit_code, quiet=quiet)