writer.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. """Provides an API for writing protocol buffers to event files to be
  2. consumed by TensorBoard for visualization."""
  3. import os
  4. import time
  5. import torch
  6. from tensorboard.compat import tf
  7. from tensorboard.compat.proto.event_pb2 import SessionLog
  8. from tensorboard.compat.proto.event_pb2 import Event
  9. from tensorboard.compat.proto import event_pb2
  10. from tensorboard.plugins.projector.projector_config_pb2 import ProjectorConfig
  11. from tensorboard.summary.writer.event_file_writer import EventFileWriter
  12. from ._convert_np import make_np
  13. from ._embedding import (
  14. make_mat,
  15. make_sprite,
  16. make_tsv,
  17. write_pbtxt,
  18. get_embedding_info,
  19. )
  20. from ._onnx_graph import load_onnx_graph
  21. from ._pytorch_graph import graph
  22. from ._utils import figure_to_image
  23. from .summary import (
  24. scalar,
  25. histogram,
  26. histogram_raw,
  27. image,
  28. audio,
  29. text,
  30. pr_curve,
  31. pr_curve_raw,
  32. video,
  33. custom_scalars,
  34. image_boxes,
  35. mesh,
  36. hparams,
  37. )
  38. __all__ = ['FileWriter', 'SummaryWriter']
  39. class FileWriter:
  40. """Writes protocol buffers to event files to be consumed by TensorBoard.
  41. The `FileWriter` class provides a mechanism to create an event file in a
  42. given directory and add summaries and events to it. The class updates the
  43. file contents asynchronously. This allows a training program to call methods
  44. to add data to the file directly from the training loop, without slowing down
  45. training.
  46. """
  47. def __init__(self, log_dir, max_queue=10, flush_secs=120, filename_suffix=""):
  48. """Creates a `FileWriter` and an event file.
  49. On construction the writer creates a new event file in `log_dir`.
  50. The other arguments to the constructor control the asynchronous writes to
  51. the event file.
  52. Args:
  53. log_dir: A string. Directory where event file will be written.
  54. max_queue: Integer. Size of the queue for pending events and
  55. summaries before one of the 'add' calls forces a flush to disk.
  56. Default is ten items.
  57. flush_secs: Number. How often, in seconds, to flush the
  58. pending events and summaries to disk. Default is every two minutes.
  59. filename_suffix: A string. Suffix added to all event filenames
  60. in the log_dir directory. More details on filename construction in
  61. tensorboard.summary.writer.event_file_writer.EventFileWriter.
  62. """
  63. # Sometimes PosixPath is passed in and we need to coerce it to
  64. # a string in all cases
  65. # TODO: See if we can remove this in the future if we are
  66. # actually the ones passing in a PosixPath
  67. log_dir = str(log_dir)
  68. self.event_writer = EventFileWriter(
  69. log_dir, max_queue, flush_secs, filename_suffix
  70. )
  71. def get_logdir(self):
  72. """Returns the directory where event file will be written."""
  73. return self.event_writer.get_logdir()
  74. def add_event(self, event, step=None, walltime=None):
  75. """Adds an event to the event file.
  76. Args:
  77. event: An `Event` protocol buffer.
  78. step: Number. Optional global step value for training process
  79. to record with the event.
  80. walltime: float. Optional walltime to override the default (current)
  81. walltime (from time.time()) seconds after epoch
  82. """
  83. event.wall_time = time.time() if walltime is None else walltime
  84. if step is not None:
  85. # Make sure step is converted from numpy or other formats
  86. # since protobuf might not convert depending on version
  87. event.step = int(step)
  88. self.event_writer.add_event(event)
  89. def add_summary(self, summary, global_step=None, walltime=None):
  90. """Adds a `Summary` protocol buffer to the event file.
  91. This method wraps the provided summary in an `Event` protocol buffer
  92. and adds it to the event file.
  93. Args:
  94. summary: A `Summary` protocol buffer.
  95. global_step: Number. Optional global step value for training process
  96. to record with the summary.
  97. walltime: float. Optional walltime to override the default (current)
  98. walltime (from time.time()) seconds after epoch
  99. """
  100. event = event_pb2.Event(summary=summary)
  101. self.add_event(event, global_step, walltime)
  102. def add_graph(self, graph_profile, walltime=None):
  103. """Adds a `Graph` and step stats protocol buffer to the event file.
  104. Args:
  105. graph_profile: A `Graph` and step stats protocol buffer.
  106. walltime: float. Optional walltime to override the default (current)
  107. walltime (from time.time()) seconds after epoch
  108. """
  109. graph = graph_profile[0]
  110. stepstats = graph_profile[1]
  111. event = event_pb2.Event(graph_def=graph.SerializeToString())
  112. self.add_event(event, None, walltime)
  113. trm = event_pb2.TaggedRunMetadata(
  114. tag="step1", run_metadata=stepstats.SerializeToString()
  115. )
  116. event = event_pb2.Event(tagged_run_metadata=trm)
  117. self.add_event(event, None, walltime)
  118. def add_onnx_graph(self, graph, walltime=None):
  119. """Adds a `Graph` protocol buffer to the event file.
  120. Args:
  121. graph: A `Graph` protocol buffer.
  122. walltime: float. Optional walltime to override the default (current)
  123. _get_file_writerfrom time.time())
  124. """
  125. event = event_pb2.Event(graph_def=graph.SerializeToString())
  126. self.add_event(event, None, walltime)
  127. def flush(self):
  128. """Flushes the event file to disk.
  129. Call this method to make sure that all pending events have been written to
  130. disk.
  131. """
  132. self.event_writer.flush()
  133. def close(self):
  134. """Flushes the event file to disk and close the file.
  135. Call this method when you do not need the summary writer anymore.
  136. """
  137. self.event_writer.close()
  138. def reopen(self):
  139. """Reopens the EventFileWriter.
  140. Can be called after `close()` to add more events in the same directory.
  141. The events will go into a new events file.
  142. Does nothing if the EventFileWriter was not closed.
  143. """
  144. self.event_writer.reopen()
  145. class SummaryWriter:
  146. """Writes entries directly to event files in the log_dir to be
  147. consumed by TensorBoard.
  148. The `SummaryWriter` class provides a high-level API to create an event file
  149. in a given directory and add summaries and events to it. The class updates the
  150. file contents asynchronously. This allows a training program to call methods
  151. to add data to the file directly from the training loop, without slowing down
  152. training.
  153. """
  154. def __init__(
  155. self,
  156. log_dir=None,
  157. comment="",
  158. purge_step=None,
  159. max_queue=10,
  160. flush_secs=120,
  161. filename_suffix="",
  162. ):
  163. """Creates a `SummaryWriter` that will write out events and summaries
  164. to the event file.
  165. Args:
  166. log_dir (str): Save directory location. Default is
  167. runs/**CURRENT_DATETIME_HOSTNAME**, which changes after each run.
  168. Use hierarchical folder structure to compare
  169. between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.
  170. for each new experiment to compare across them.
  171. comment (str): Comment log_dir suffix appended to the default
  172. ``log_dir``. If ``log_dir`` is assigned, this argument has no effect.
  173. purge_step (int):
  174. When logging crashes at step :math:`T+X` and restarts at step :math:`T`,
  175. any events whose global_step larger or equal to :math:`T` will be
  176. purged and hidden from TensorBoard.
  177. Note that crashed and resumed experiments should have the same ``log_dir``.
  178. max_queue (int): Size of the queue for pending events and
  179. summaries before one of the 'add' calls forces a flush to disk.
  180. Default is ten items.
  181. flush_secs (int): How often, in seconds, to flush the
  182. pending events and summaries to disk. Default is every two minutes.
  183. filename_suffix (str): Suffix added to all event filenames in
  184. the log_dir directory. More details on filename construction in
  185. tensorboard.summary.writer.event_file_writer.EventFileWriter.
  186. Examples::
  187. from torch.utils.tensorboard import SummaryWriter
  188. # create a summary writer with automatically generated folder name.
  189. writer = SummaryWriter()
  190. # folder location: runs/May04_22-14-54_s-MacBook-Pro.local/
  191. # create a summary writer using the specified folder name.
  192. writer = SummaryWriter("my_experiment")
  193. # folder location: my_experiment
  194. # create a summary writer with comment appended.
  195. writer = SummaryWriter(comment="LR_0.1_BATCH_16")
  196. # folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/
  197. """
  198. torch._C._log_api_usage_once("tensorboard.create.summarywriter")
  199. if not log_dir:
  200. import socket
  201. from datetime import datetime
  202. current_time = datetime.now().strftime("%b%d_%H-%M-%S")
  203. log_dir = os.path.join(
  204. "runs", current_time + "_" + socket.gethostname() + comment
  205. )
  206. self.log_dir = log_dir
  207. self.purge_step = purge_step
  208. self.max_queue = max_queue
  209. self.flush_secs = flush_secs
  210. self.filename_suffix = filename_suffix
  211. # Initialize the file writers, but they can be cleared out on close
  212. # and recreated later as needed.
  213. self.file_writer = self.all_writers = None
  214. self._get_file_writer()
  215. # Create default bins for histograms, see generate_testdata.py in tensorflow/tensorboard
  216. v = 1e-12
  217. buckets = []
  218. neg_buckets = []
  219. while v < 1e20:
  220. buckets.append(v)
  221. neg_buckets.append(-v)
  222. v *= 1.1
  223. self.default_bins = neg_buckets[::-1] + [0] + buckets
  224. def _check_caffe2_blob(self, item):
  225. """
  226. Caffe2 users have the option of passing a string representing the name of
  227. a blob in the workspace instead of passing the actual Tensor/array containing
  228. the numeric values. Thus, we need to check if we received a string as input
  229. instead of an actual Tensor/array, and if so, we need to fetch the Blob
  230. from the workspace corresponding to that name. Fetching can be done with the
  231. following:
  232. from caffe2.python import workspace (if not already imported)
  233. workspace.FetchBlob(blob_name)
  234. workspace.FetchBlobs([blob_name1, blob_name2, ...])
  235. """
  236. return isinstance(item, str)
  237. def _get_file_writer(self):
  238. """Returns the default FileWriter instance. Recreates it if closed."""
  239. if self.all_writers is None or self.file_writer is None:
  240. self.file_writer = FileWriter(
  241. self.log_dir, self.max_queue, self.flush_secs, self.filename_suffix
  242. )
  243. self.all_writers = {self.file_writer.get_logdir(): self.file_writer}
  244. if self.purge_step is not None:
  245. most_recent_step = self.purge_step
  246. self.file_writer.add_event(
  247. Event(step=most_recent_step, file_version="brain.Event:2")
  248. )
  249. self.file_writer.add_event(
  250. Event(
  251. step=most_recent_step,
  252. session_log=SessionLog(status=SessionLog.START),
  253. )
  254. )
  255. self.purge_step = None
  256. return self.file_writer
  257. def get_logdir(self):
  258. """Returns the directory where event files will be written."""
  259. return self.log_dir
  260. def add_hparams(
  261. self, hparam_dict, metric_dict, hparam_domain_discrete=None, run_name=None
  262. ):
  263. """Add a set of hyperparameters to be compared in TensorBoard.
  264. Args:
  265. hparam_dict (dict): Each key-value pair in the dictionary is the
  266. name of the hyper parameter and it's corresponding value.
  267. The type of the value can be one of `bool`, `string`, `float`,
  268. `int`, or `None`.
  269. metric_dict (dict): Each key-value pair in the dictionary is the
  270. name of the metric and it's corresponding value. Note that the key used
  271. here should be unique in the tensorboard record. Otherwise the value
  272. you added by ``add_scalar`` will be displayed in hparam plugin. In most
  273. cases, this is unwanted.
  274. hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that
  275. contains names of the hyperparameters and all discrete values they can hold
  276. run_name (str): Name of the run, to be included as part of the logdir.
  277. If unspecified, will use current timestamp.
  278. Examples::
  279. from torch.utils.tensorboard import SummaryWriter
  280. with SummaryWriter() as w:
  281. for i in range(5):
  282. w.add_hparams({'lr': 0.1*i, 'bsize': i},
  283. {'hparam/accuracy': 10*i, 'hparam/loss': 10*i})
  284. Expected result:
  285. .. image:: _static/img/tensorboard/add_hparam.png
  286. :scale: 50 %
  287. """
  288. torch._C._log_api_usage_once("tensorboard.logging.add_hparams")
  289. if type(hparam_dict) is not dict or type(metric_dict) is not dict:
  290. raise TypeError("hparam_dict and metric_dict should be dictionary.")
  291. exp, ssi, sei = hparams(hparam_dict, metric_dict, hparam_domain_discrete)
  292. if not run_name:
  293. run_name = str(time.time())
  294. logdir = os.path.join(self._get_file_writer().get_logdir(), run_name)
  295. with SummaryWriter(log_dir=logdir) as w_hp:
  296. w_hp.file_writer.add_summary(exp)
  297. w_hp.file_writer.add_summary(ssi)
  298. w_hp.file_writer.add_summary(sei)
  299. for k, v in metric_dict.items():
  300. w_hp.add_scalar(k, v)
  301. def add_scalar(
  302. self,
  303. tag,
  304. scalar_value,
  305. global_step=None,
  306. walltime=None,
  307. new_style=False,
  308. double_precision=False,
  309. ):
  310. """Add scalar data to summary.
  311. Args:
  312. tag (str): Data identifier
  313. scalar_value (float or string/blobname): Value to save
  314. global_step (int): Global step value to record
  315. walltime (float): Optional override default walltime (time.time())
  316. with seconds after epoch of event
  317. new_style (boolean): Whether to use new style (tensor field) or old
  318. style (simple_value field). New style could lead to faster data loading.
  319. Examples::
  320. from torch.utils.tensorboard import SummaryWriter
  321. writer = SummaryWriter()
  322. x = range(100)
  323. for i in x:
  324. writer.add_scalar('y=2x', i * 2, i)
  325. writer.close()
  326. Expected result:
  327. .. image:: _static/img/tensorboard/add_scalar.png
  328. :scale: 50 %
  329. """
  330. torch._C._log_api_usage_once("tensorboard.logging.add_scalar")
  331. if self._check_caffe2_blob(scalar_value):
  332. from caffe2.python import workspace
  333. scalar_value = workspace.FetchBlob(scalar_value)
  334. summary = scalar(
  335. tag, scalar_value, new_style=new_style, double_precision=double_precision
  336. )
  337. self._get_file_writer().add_summary(summary, global_step, walltime)
  338. def add_scalars(self, main_tag, tag_scalar_dict, global_step=None, walltime=None):
  339. """Adds many scalar data to summary.
  340. Args:
  341. main_tag (str): The parent name for the tags
  342. tag_scalar_dict (dict): Key-value pair storing the tag and corresponding values
  343. global_step (int): Global step value to record
  344. walltime (float): Optional override default walltime (time.time())
  345. seconds after epoch of event
  346. Examples::
  347. from torch.utils.tensorboard import SummaryWriter
  348. writer = SummaryWriter()
  349. r = 5
  350. for i in range(100):
  351. writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r),
  352. 'xcosx':i*np.cos(i/r),
  353. 'tanx': np.tan(i/r)}, i)
  354. writer.close()
  355. # This call adds three values to the same scalar plot with the tag
  356. # 'run_14h' in TensorBoard's scalar section.
  357. Expected result:
  358. .. image:: _static/img/tensorboard/add_scalars.png
  359. :scale: 50 %
  360. """
  361. torch._C._log_api_usage_once("tensorboard.logging.add_scalars")
  362. walltime = time.time() if walltime is None else walltime
  363. fw_logdir = self._get_file_writer().get_logdir()
  364. for tag, scalar_value in tag_scalar_dict.items():
  365. fw_tag = fw_logdir + "/" + main_tag.replace("/", "_") + "_" + tag
  366. assert self.all_writers is not None
  367. if fw_tag in self.all_writers.keys():
  368. fw = self.all_writers[fw_tag]
  369. else:
  370. fw = FileWriter(
  371. fw_tag, self.max_queue, self.flush_secs, self.filename_suffix
  372. )
  373. self.all_writers[fw_tag] = fw
  374. if self._check_caffe2_blob(scalar_value):
  375. from caffe2.python import workspace
  376. scalar_value = workspace.FetchBlob(scalar_value)
  377. fw.add_summary(scalar(main_tag, scalar_value), global_step, walltime)
  378. def add_histogram(
  379. self,
  380. tag,
  381. values,
  382. global_step=None,
  383. bins="tensorflow",
  384. walltime=None,
  385. max_bins=None,
  386. ):
  387. """Add histogram to summary.
  388. Args:
  389. tag (str): Data identifier
  390. values (torch.Tensor, numpy.ndarray, or string/blobname): Values to build histogram
  391. global_step (int): Global step value to record
  392. bins (str): One of {'tensorflow','auto', 'fd', ...}. This determines how the bins are made. You can find
  393. other options in: https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
  394. walltime (float): Optional override default walltime (time.time())
  395. seconds after epoch of event
  396. Examples::
  397. from torch.utils.tensorboard import SummaryWriter
  398. import numpy as np
  399. writer = SummaryWriter()
  400. for i in range(10):
  401. x = np.random.random(1000)
  402. writer.add_histogram('distribution centers', x + i, i)
  403. writer.close()
  404. Expected result:
  405. .. image:: _static/img/tensorboard/add_histogram.png
  406. :scale: 50 %
  407. """
  408. torch._C._log_api_usage_once("tensorboard.logging.add_histogram")
  409. if self._check_caffe2_blob(values):
  410. from caffe2.python import workspace
  411. values = workspace.FetchBlob(values)
  412. if isinstance(bins, str) and bins == "tensorflow":
  413. bins = self.default_bins
  414. self._get_file_writer().add_summary(
  415. histogram(tag, values, bins, max_bins=max_bins), global_step, walltime
  416. )
  417. def add_histogram_raw(
  418. self,
  419. tag,
  420. min,
  421. max,
  422. num,
  423. sum,
  424. sum_squares,
  425. bucket_limits,
  426. bucket_counts,
  427. global_step=None,
  428. walltime=None,
  429. ):
  430. """Adds histogram with raw data.
  431. Args:
  432. tag (str): Data identifier
  433. min (float or int): Min value
  434. max (float or int): Max value
  435. num (int): Number of values
  436. sum (float or int): Sum of all values
  437. sum_squares (float or int): Sum of squares for all values
  438. bucket_limits (torch.Tensor, numpy.ndarray): Upper value per bucket.
  439. The number of elements of it should be the same as `bucket_counts`.
  440. bucket_counts (torch.Tensor, numpy.ndarray): Number of values per bucket
  441. global_step (int): Global step value to record
  442. walltime (float): Optional override default walltime (time.time())
  443. seconds after epoch of event
  444. see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/histogram/README.md
  445. Examples::
  446. from torch.utils.tensorboard import SummaryWriter
  447. import numpy as np
  448. writer = SummaryWriter()
  449. dummy_data = []
  450. for idx, value in enumerate(range(50)):
  451. dummy_data += [idx + 0.001] * value
  452. bins = list(range(50+2))
  453. bins = np.array(bins)
  454. values = np.array(dummy_data).astype(float).reshape(-1)
  455. counts, limits = np.histogram(values, bins=bins)
  456. sum_sq = values.dot(values)
  457. writer.add_histogram_raw(
  458. tag='histogram_with_raw_data',
  459. min=values.min(),
  460. max=values.max(),
  461. num=len(values),
  462. sum=values.sum(),
  463. sum_squares=sum_sq,
  464. bucket_limits=limits[1:].tolist(),
  465. bucket_counts=counts.tolist(),
  466. global_step=0)
  467. writer.close()
  468. Expected result:
  469. .. image:: _static/img/tensorboard/add_histogram_raw.png
  470. :scale: 50 %
  471. """
  472. torch._C._log_api_usage_once("tensorboard.logging.add_histogram_raw")
  473. if len(bucket_limits) != len(bucket_counts):
  474. raise ValueError(
  475. "len(bucket_limits) != len(bucket_counts), see the document."
  476. )
  477. self._get_file_writer().add_summary(
  478. histogram_raw(
  479. tag, min, max, num, sum, sum_squares, bucket_limits, bucket_counts
  480. ),
  481. global_step,
  482. walltime,
  483. )
  484. def add_image(
  485. self, tag, img_tensor, global_step=None, walltime=None, dataformats="CHW"
  486. ):
  487. """Add image data to summary.
  488. Note that this requires the ``pillow`` package.
  489. Args:
  490. tag (str): Data identifier
  491. img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data
  492. global_step (int): Global step value to record
  493. walltime (float): Optional override default walltime (time.time())
  494. seconds after epoch of event
  495. dataformats (str): Image data format specification of the form
  496. CHW, HWC, HW, WH, etc.
  497. Shape:
  498. img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to
  499. convert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job.
  500. Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long as
  501. corresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``.
  502. Examples::
  503. from torch.utils.tensorboard import SummaryWriter
  504. import numpy as np
  505. img = np.zeros((3, 100, 100))
  506. img[0] = np.arange(0, 10000).reshape(100, 100) / 10000
  507. img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000
  508. img_HWC = np.zeros((100, 100, 3))
  509. img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000
  510. img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000
  511. writer = SummaryWriter()
  512. writer.add_image('my_image', img, 0)
  513. # If you have non-default dimension setting, set the dataformats argument.
  514. writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC')
  515. writer.close()
  516. Expected result:
  517. .. image:: _static/img/tensorboard/add_image.png
  518. :scale: 50 %
  519. """
  520. torch._C._log_api_usage_once("tensorboard.logging.add_image")
  521. if self._check_caffe2_blob(img_tensor):
  522. from caffe2.python import workspace
  523. img_tensor = workspace.FetchBlob(img_tensor)
  524. self._get_file_writer().add_summary(
  525. image(tag, img_tensor, dataformats=dataformats), global_step, walltime
  526. )
  527. def add_images(
  528. self, tag, img_tensor, global_step=None, walltime=None, dataformats="NCHW"
  529. ):
  530. """Add batched image data to summary.
  531. Note that this requires the ``pillow`` package.
  532. Args:
  533. tag (str): Data identifier
  534. img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data
  535. global_step (int): Global step value to record
  536. walltime (float): Optional override default walltime (time.time())
  537. seconds after epoch of event
  538. dataformats (str): Image data format specification of the form
  539. NCHW, NHWC, CHW, HWC, HW, WH, etc.
  540. Shape:
  541. img_tensor: Default is :math:`(N, 3, H, W)`. If ``dataformats`` is specified, other shape will be
  542. accepted. e.g. NCHW or NHWC.
  543. Examples::
  544. from torch.utils.tensorboard import SummaryWriter
  545. import numpy as np
  546. img_batch = np.zeros((16, 3, 100, 100))
  547. for i in range(16):
  548. img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i
  549. img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i
  550. writer = SummaryWriter()
  551. writer.add_images('my_image_batch', img_batch, 0)
  552. writer.close()
  553. Expected result:
  554. .. image:: _static/img/tensorboard/add_images.png
  555. :scale: 30 %
  556. """
  557. torch._C._log_api_usage_once("tensorboard.logging.add_images")
  558. if self._check_caffe2_blob(img_tensor):
  559. from caffe2.python import workspace
  560. img_tensor = workspace.FetchBlob(img_tensor)
  561. self._get_file_writer().add_summary(
  562. image(tag, img_tensor, dataformats=dataformats), global_step, walltime
  563. )
  564. def add_image_with_boxes(
  565. self,
  566. tag,
  567. img_tensor,
  568. box_tensor,
  569. global_step=None,
  570. walltime=None,
  571. rescale=1,
  572. dataformats="CHW",
  573. labels=None,
  574. ):
  575. """Add image and draw bounding boxes on the image.
  576. Args:
  577. tag (str): Data identifier
  578. img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data
  579. box_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Box data (for detected objects)
  580. box should be represented as [x1, y1, x2, y2].
  581. global_step (int): Global step value to record
  582. walltime (float): Optional override default walltime (time.time())
  583. seconds after epoch of event
  584. rescale (float): Optional scale override
  585. dataformats (str): Image data format specification of the form
  586. NCHW, NHWC, CHW, HWC, HW, WH, etc.
  587. labels (list of string): The label to be shown for each bounding box.
  588. Shape:
  589. img_tensor: Default is :math:`(3, H, W)`. It can be specified with ``dataformats`` argument.
  590. e.g. CHW or HWC
  591. box_tensor: (torch.Tensor, numpy.ndarray, or string/blobname): NX4, where N is the number of
  592. boxes and each 4 elements in a row represents (xmin, ymin, xmax, ymax).
  593. """
  594. torch._C._log_api_usage_once("tensorboard.logging.add_image_with_boxes")
  595. if self._check_caffe2_blob(img_tensor):
  596. from caffe2.python import workspace
  597. img_tensor = workspace.FetchBlob(img_tensor)
  598. if self._check_caffe2_blob(box_tensor):
  599. from caffe2.python import workspace
  600. box_tensor = workspace.FetchBlob(box_tensor)
  601. if labels is not None:
  602. if isinstance(labels, str):
  603. labels = [labels]
  604. if len(labels) != box_tensor.shape[0]:
  605. labels = None
  606. self._get_file_writer().add_summary(
  607. image_boxes(
  608. tag,
  609. img_tensor,
  610. box_tensor,
  611. rescale=rescale,
  612. dataformats=dataformats,
  613. labels=labels,
  614. ),
  615. global_step,
  616. walltime,
  617. )
  618. def add_figure(self, tag, figure, global_step=None, close=True, walltime=None):
  619. """Render matplotlib figure into an image and add it to summary.
  620. Note that this requires the ``matplotlib`` package.
  621. Args:
  622. tag (str): Data identifier
  623. figure (matplotlib.pyplot.figure) or list of figures: Figure or a list of figures
  624. global_step (int): Global step value to record
  625. close (bool): Flag to automatically close the figure
  626. walltime (float): Optional override default walltime (time.time())
  627. seconds after epoch of event
  628. """
  629. torch._C._log_api_usage_once("tensorboard.logging.add_figure")
  630. if isinstance(figure, list):
  631. self.add_image(
  632. tag,
  633. figure_to_image(figure, close),
  634. global_step,
  635. walltime,
  636. dataformats="NCHW",
  637. )
  638. else:
  639. self.add_image(
  640. tag,
  641. figure_to_image(figure, close),
  642. global_step,
  643. walltime,
  644. dataformats="CHW",
  645. )
  646. def add_video(self, tag, vid_tensor, global_step=None, fps=4, walltime=None):
  647. """Add video data to summary.
  648. Note that this requires the ``moviepy`` package.
  649. Args:
  650. tag (str): Data identifier
  651. vid_tensor (torch.Tensor): Video data
  652. global_step (int): Global step value to record
  653. fps (float or int): Frames per second
  654. walltime (float): Optional override default walltime (time.time())
  655. seconds after epoch of event
  656. Shape:
  657. vid_tensor: :math:`(N, T, C, H, W)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`.
  658. """
  659. torch._C._log_api_usage_once("tensorboard.logging.add_video")
  660. self._get_file_writer().add_summary(
  661. video(tag, vid_tensor, fps), global_step, walltime
  662. )
  663. def add_audio(
  664. self, tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None
  665. ):
  666. """Add audio data to summary.
  667. Args:
  668. tag (str): Data identifier
  669. snd_tensor (torch.Tensor): Sound data
  670. global_step (int): Global step value to record
  671. sample_rate (int): sample rate in Hz
  672. walltime (float): Optional override default walltime (time.time())
  673. seconds after epoch of event
  674. Shape:
  675. snd_tensor: :math:`(1, L)`. The values should lie between [-1, 1].
  676. """
  677. torch._C._log_api_usage_once("tensorboard.logging.add_audio")
  678. if self._check_caffe2_blob(snd_tensor):
  679. from caffe2.python import workspace
  680. snd_tensor = workspace.FetchBlob(snd_tensor)
  681. self._get_file_writer().add_summary(
  682. audio(tag, snd_tensor, sample_rate=sample_rate), global_step, walltime
  683. )
  684. def add_text(self, tag, text_string, global_step=None, walltime=None):
  685. """Add text data to summary.
  686. Args:
  687. tag (str): Data identifier
  688. text_string (str): String to save
  689. global_step (int): Global step value to record
  690. walltime (float): Optional override default walltime (time.time())
  691. seconds after epoch of event
  692. Examples::
  693. writer.add_text('lstm', 'This is an lstm', 0)
  694. writer.add_text('rnn', 'This is an rnn', 10)
  695. """
  696. torch._C._log_api_usage_once("tensorboard.logging.add_text")
  697. self._get_file_writer().add_summary(
  698. text(tag, text_string), global_step, walltime
  699. )
  700. def add_onnx_graph(self, prototxt):
  701. torch._C._log_api_usage_once("tensorboard.logging.add_onnx_graph")
  702. self._get_file_writer().add_onnx_graph(load_onnx_graph(prototxt))
  703. def add_graph(
  704. self, model, input_to_model=None, verbose=False, use_strict_trace=True
  705. ):
  706. """Add graph data to summary.
  707. Args:
  708. model (torch.nn.Module): Model to draw.
  709. input_to_model (torch.Tensor or list of torch.Tensor): A variable or a tuple of
  710. variables to be fed.
  711. verbose (bool): Whether to print graph structure in console.
  712. use_strict_trace (bool): Whether to pass keyword argument `strict` to
  713. `torch.jit.trace`. Pass False when you want the tracer to
  714. record your mutable container types (list, dict)
  715. """
  716. torch._C._log_api_usage_once("tensorboard.logging.add_graph")
  717. if hasattr(model, "forward"):
  718. # A valid PyTorch model should have a 'forward' method
  719. self._get_file_writer().add_graph(
  720. graph(model, input_to_model, verbose, use_strict_trace)
  721. )
  722. else:
  723. # Caffe2 models do not have the 'forward' method
  724. from caffe2.proto import caffe2_pb2
  725. from caffe2.python import core
  726. from ._caffe2_graph import (
  727. model_to_graph_def,
  728. nets_to_graph_def,
  729. protos_to_graph_def,
  730. )
  731. if isinstance(model, list):
  732. if isinstance(model[0], core.Net):
  733. current_graph = nets_to_graph_def(model)
  734. elif isinstance(model[0], caffe2_pb2.NetDef):
  735. current_graph = protos_to_graph_def(model)
  736. else:
  737. # Handles cnn.CNNModelHelper, model_helper.ModelHelper
  738. current_graph = model_to_graph_def(model)
  739. event = event_pb2.Event(graph_def=current_graph.SerializeToString())
  740. self._get_file_writer().add_event(event)
  741. @staticmethod
  742. def _encode(rawstr):
  743. # I'd use urllib but, I'm unsure about the differences from python3 to python2, etc.
  744. retval = rawstr
  745. retval = retval.replace("%", "%%%02x" % (ord("%")))
  746. retval = retval.replace("/", "%%%02x" % (ord("/")))
  747. retval = retval.replace("\\", "%%%02x" % (ord("\\")))
  748. return retval
  749. def add_embedding(
  750. self,
  751. mat,
  752. metadata=None,
  753. label_img=None,
  754. global_step=None,
  755. tag="default",
  756. metadata_header=None,
  757. ):
  758. """Add embedding projector data to summary.
  759. Args:
  760. mat (torch.Tensor or numpy.ndarray): A matrix which each row is the feature vector of the data point
  761. metadata (list): A list of labels, each element will be convert to string
  762. label_img (torch.Tensor): Images correspond to each data point
  763. global_step (int): Global step value to record
  764. tag (str): Name for the embedding
  765. Shape:
  766. mat: :math:`(N, D)`, where N is number of data and D is feature dimension
  767. label_img: :math:`(N, C, H, W)`
  768. Examples::
  769. import keyword
  770. import torch
  771. meta = []
  772. while len(meta)<100:
  773. meta = meta+keyword.kwlist # get some strings
  774. meta = meta[:100]
  775. for i, v in enumerate(meta):
  776. meta[i] = v+str(i)
  777. label_img = torch.rand(100, 3, 10, 32)
  778. for i in range(100):
  779. label_img[i]*=i/100.0
  780. writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img)
  781. writer.add_embedding(torch.randn(100, 5), label_img=label_img)
  782. writer.add_embedding(torch.randn(100, 5), metadata=meta)
  783. """
  784. torch._C._log_api_usage_once("tensorboard.logging.add_embedding")
  785. mat = make_np(mat)
  786. if global_step is None:
  787. global_step = 0
  788. # clear pbtxt?
  789. # Maybe we should encode the tag so slashes don't trip us up?
  790. # I don't think this will mess us up, but better safe than sorry.
  791. subdir = "%s/%s" % (str(global_step).zfill(5), self._encode(tag))
  792. save_path = os.path.join(self._get_file_writer().get_logdir(), subdir)
  793. fs = tf.io.gfile
  794. if fs.exists(save_path):
  795. if fs.isdir(save_path):
  796. print(
  797. "warning: Embedding dir exists, did you set global_step for add_embedding()?"
  798. )
  799. else:
  800. raise Exception(
  801. "Path: `%s` exists, but is a file. Cannot proceed." % save_path
  802. )
  803. else:
  804. fs.makedirs(save_path)
  805. if metadata is not None:
  806. assert mat.shape[0] == len(
  807. metadata
  808. ), "#labels should equal with #data points"
  809. make_tsv(metadata, save_path, metadata_header=metadata_header)
  810. if label_img is not None:
  811. assert (
  812. mat.shape[0] == label_img.shape[0]
  813. ), "#images should equal with #data points"
  814. make_sprite(label_img, save_path)
  815. assert (
  816. mat.ndim == 2
  817. ), "mat should be 2D, where mat.size(0) is the number of data points"
  818. make_mat(mat, save_path)
  819. # Filesystem doesn't necessarily have append semantics, so we store an
  820. # internal buffer to append to and re-write whole file after each
  821. # embedding is added
  822. if not hasattr(self, "_projector_config"):
  823. self._projector_config = ProjectorConfig()
  824. embedding_info = get_embedding_info(
  825. metadata, label_img, subdir, global_step, tag
  826. )
  827. self._projector_config.embeddings.extend([embedding_info])
  828. from google.protobuf import text_format
  829. config_pbtxt = text_format.MessageToString(self._projector_config)
  830. write_pbtxt(self._get_file_writer().get_logdir(), config_pbtxt)
  831. def add_pr_curve(
  832. self,
  833. tag,
  834. labels,
  835. predictions,
  836. global_step=None,
  837. num_thresholds=127,
  838. weights=None,
  839. walltime=None,
  840. ):
  841. """Adds precision recall curve.
  842. Plotting a precision-recall curve lets you understand your model's
  843. performance under different threshold settings. With this function,
  844. you provide the ground truth labeling (T/F) and prediction confidence
  845. (usually the output of your model) for each target. The TensorBoard UI
  846. will let you choose the threshold interactively.
  847. Args:
  848. tag (str): Data identifier
  849. labels (torch.Tensor, numpy.ndarray, or string/blobname):
  850. Ground truth data. Binary label for each element.
  851. predictions (torch.Tensor, numpy.ndarray, or string/blobname):
  852. The probability that an element be classified as true.
  853. Value should be in [0, 1]
  854. global_step (int): Global step value to record
  855. num_thresholds (int): Number of thresholds used to draw the curve.
  856. walltime (float): Optional override default walltime (time.time())
  857. seconds after epoch of event
  858. Examples::
  859. from torch.utils.tensorboard import SummaryWriter
  860. import numpy as np
  861. labels = np.random.randint(2, size=100) # binary label
  862. predictions = np.random.rand(100)
  863. writer = SummaryWriter()
  864. writer.add_pr_curve('pr_curve', labels, predictions, 0)
  865. writer.close()
  866. """
  867. torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve")
  868. labels, predictions = make_np(labels), make_np(predictions)
  869. self._get_file_writer().add_summary(
  870. pr_curve(tag, labels, predictions, num_thresholds, weights),
  871. global_step,
  872. walltime,
  873. )
  874. def add_pr_curve_raw(
  875. self,
  876. tag,
  877. true_positive_counts,
  878. false_positive_counts,
  879. true_negative_counts,
  880. false_negative_counts,
  881. precision,
  882. recall,
  883. global_step=None,
  884. num_thresholds=127,
  885. weights=None,
  886. walltime=None,
  887. ):
  888. """Adds precision recall curve with raw data.
  889. Args:
  890. tag (str): Data identifier
  891. true_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): true positive counts
  892. false_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): false positive counts
  893. true_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): true negative counts
  894. false_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): false negative counts
  895. precision (torch.Tensor, numpy.ndarray, or string/blobname): precision
  896. recall (torch.Tensor, numpy.ndarray, or string/blobname): recall
  897. global_step (int): Global step value to record
  898. num_thresholds (int): Number of thresholds used to draw the curve.
  899. walltime (float): Optional override default walltime (time.time())
  900. seconds after epoch of event
  901. see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/README.md
  902. """
  903. torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve_raw")
  904. self._get_file_writer().add_summary(
  905. pr_curve_raw(
  906. tag,
  907. true_positive_counts,
  908. false_positive_counts,
  909. true_negative_counts,
  910. false_negative_counts,
  911. precision,
  912. recall,
  913. num_thresholds,
  914. weights,
  915. ),
  916. global_step,
  917. walltime,
  918. )
  919. def add_custom_scalars_multilinechart(
  920. self, tags, category="default", title="untitled"
  921. ):
  922. """Shorthand for creating multilinechart. Similar to ``add_custom_scalars()``, but the only necessary argument
  923. is *tags*.
  924. Args:
  925. tags (list): list of tags that have been used in ``add_scalar()``
  926. Examples::
  927. writer.add_custom_scalars_multilinechart(['twse/0050', 'twse/2330'])
  928. """
  929. torch._C._log_api_usage_once(
  930. "tensorboard.logging.add_custom_scalars_multilinechart"
  931. )
  932. layout = {category: {title: ["Multiline", tags]}}
  933. self._get_file_writer().add_summary(custom_scalars(layout))
  934. def add_custom_scalars_marginchart(
  935. self, tags, category="default", title="untitled"
  936. ):
  937. """Shorthand for creating marginchart. Similar to ``add_custom_scalars()``, but the only necessary argument
  938. is *tags*, which should have exactly 3 elements.
  939. Args:
  940. tags (list): list of tags that have been used in ``add_scalar()``
  941. Examples::
  942. writer.add_custom_scalars_marginchart(['twse/0050', 'twse/2330', 'twse/2006'])
  943. """
  944. torch._C._log_api_usage_once(
  945. "tensorboard.logging.add_custom_scalars_marginchart"
  946. )
  947. assert len(tags) == 3
  948. layout = {category: {title: ["Margin", tags]}}
  949. self._get_file_writer().add_summary(custom_scalars(layout))
  950. def add_custom_scalars(self, layout):
  951. """Create special chart by collecting charts tags in 'scalars'. Note that this function can only be called once
  952. for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called
  953. before or after the training loop.
  954. Args:
  955. layout (dict): {categoryName: *charts*}, where *charts* is also a dictionary
  956. {chartName: *ListOfProperties*}. The first element in *ListOfProperties* is the chart's type
  957. (one of **Multiline** or **Margin**) and the second element should be a list containing the tags
  958. you have used in add_scalar function, which will be collected into the new chart.
  959. Examples::
  960. layout = {'Taiwan':{'twse':['Multiline',['twse/0050', 'twse/2330']]},
  961. 'USA':{ 'dow':['Margin', ['dow/aaa', 'dow/bbb', 'dow/ccc']],
  962. 'nasdaq':['Margin', ['nasdaq/aaa', 'nasdaq/bbb', 'nasdaq/ccc']]}}
  963. writer.add_custom_scalars(layout)
  964. """
  965. torch._C._log_api_usage_once("tensorboard.logging.add_custom_scalars")
  966. self._get_file_writer().add_summary(custom_scalars(layout))
  967. def add_mesh(
  968. self,
  969. tag,
  970. vertices,
  971. colors=None,
  972. faces=None,
  973. config_dict=None,
  974. global_step=None,
  975. walltime=None,
  976. ):
  977. """Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js,
  978. so it allows users to interact with the rendered object. Besides the basic definitions
  979. such as vertices, faces, users can further provide camera parameter, lighting condition, etc.
  980. Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for
  981. advanced usage.
  982. Args:
  983. tag (str): Data identifier
  984. vertices (torch.Tensor): List of the 3D coordinates of vertices.
  985. colors (torch.Tensor): Colors for each vertex
  986. faces (torch.Tensor): Indices of vertices within each triangle. (Optional)
  987. config_dict: Dictionary with ThreeJS classes names and configuration.
  988. global_step (int): Global step value to record
  989. walltime (float): Optional override default walltime (time.time())
  990. seconds after epoch of event
  991. Shape:
  992. vertices: :math:`(B, N, 3)`. (batch, number_of_vertices, channels)
  993. colors: :math:`(B, N, 3)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`.
  994. faces: :math:`(B, N, 3)`. The values should lie in [0, number_of_vertices] for type `uint8`.
  995. Examples::
  996. from torch.utils.tensorboard import SummaryWriter
  997. vertices_tensor = torch.as_tensor([
  998. [1, 1, 1],
  999. [-1, -1, 1],
  1000. [1, -1, -1],
  1001. [-1, 1, -1],
  1002. ], dtype=torch.float).unsqueeze(0)
  1003. colors_tensor = torch.as_tensor([
  1004. [255, 0, 0],
  1005. [0, 255, 0],
  1006. [0, 0, 255],
  1007. [255, 0, 255],
  1008. ], dtype=torch.int).unsqueeze(0)
  1009. faces_tensor = torch.as_tensor([
  1010. [0, 2, 3],
  1011. [0, 3, 1],
  1012. [0, 1, 2],
  1013. [1, 3, 2],
  1014. ], dtype=torch.int).unsqueeze(0)
  1015. writer = SummaryWriter()
  1016. writer.add_mesh('my_mesh', vertices=vertices_tensor, colors=colors_tensor, faces=faces_tensor)
  1017. writer.close()
  1018. """
  1019. torch._C._log_api_usage_once("tensorboard.logging.add_mesh")
  1020. self._get_file_writer().add_summary(
  1021. mesh(tag, vertices, colors, faces, config_dict), global_step, walltime
  1022. )
  1023. def flush(self):
  1024. """Flushes the event file to disk.
  1025. Call this method to make sure that all pending events have been written to
  1026. disk.
  1027. """
  1028. if self.all_writers is None:
  1029. return
  1030. for writer in self.all_writers.values():
  1031. writer.flush()
  1032. def close(self):
  1033. if self.all_writers is None:
  1034. return # ignore double close
  1035. for writer in self.all_writers.values():
  1036. writer.flush()
  1037. writer.close()
  1038. self.file_writer = self.all_writers = None
  1039. def __enter__(self):
  1040. return self
  1041. def __exit__(self, exc_type, exc_val, exc_tb):
  1042. self.close()