Spaces:
Sleeping
Sleeping
File size: 22,365 Bytes
cf2a15a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""The TensorBoard metrics plugin."""
import collections
import imghdr
import json
from werkzeug import wrappers
from tensorboard import errors
from tensorboard import plugin_util
from tensorboard.backend import http_util
from tensorboard.data import provider
from tensorboard.plugins import base_plugin
from tensorboard.plugins.histogram import metadata as histogram_metadata
from tensorboard.plugins.image import metadata as image_metadata
from tensorboard.plugins.metrics import metadata
from tensorboard.plugins.scalar import metadata as scalar_metadata
_IMGHDR_TO_MIMETYPE = {
"bmp": "image/bmp",
"gif": "image/gif",
"jpeg": "image/jpeg",
"png": "image/png",
"svg": "image/svg+xml",
}
_DEFAULT_IMAGE_MIMETYPE = "application/octet-stream"
_SINGLE_RUN_PLUGINS = frozenset(
[histogram_metadata.PLUGIN_NAME, image_metadata.PLUGIN_NAME]
)
_SAMPLED_PLUGINS = frozenset([image_metadata.PLUGIN_NAME])
def _get_tag_description_info(mapping):
"""Gets maps from tags to descriptions, and descriptions to runs.
Args:
mapping: a nested map `d` such that `d[run][tag]` is a time series
produced by DataProvider's `list_*` methods.
Returns:
A tuple containing
tag_to_descriptions: A map from tag strings to a set of description
strings.
description_to_runs: A map from description strings to a set of run
strings.
"""
tag_to_descriptions = collections.defaultdict(set)
description_to_runs = collections.defaultdict(set)
for run, tag_to_content in mapping.items():
for tag, metadatum in tag_to_content.items():
description = metadatum.description
if len(description):
tag_to_descriptions[tag].add(description)
description_to_runs[description].add(run)
return tag_to_descriptions, description_to_runs
def _build_combined_description(descriptions, description_to_runs):
"""Creates a single description from a set of descriptions.
Descriptions may be composites when a single tag has different descriptions
across multiple runs.
Args:
descriptions: A list of description strings.
description_to_runs: A map from description strings to a set of run
strings.
Returns:
The combined description string.
"""
prefixed_descriptions = []
for description in descriptions:
runs = sorted(description_to_runs[description])
run_or_runs = "runs" if len(runs) > 1 else "run"
run_header = "## For " + run_or_runs + ": " + ", ".join(runs)
description_html = run_header + "\n" + description
prefixed_descriptions.append(description_html)
header = "# Multiple descriptions\n"
return header + "\n".join(prefixed_descriptions)
def _get_tag_to_description(mapping):
"""Returns a map of tags to descriptions.
Args:
mapping: a nested map `d` such that `d[run][tag]` is a time series
produced by DataProvider's `list_*` methods.
Returns:
A map from tag strings to description HTML strings. E.g.
{
"loss": "<h1>Multiple descriptions</h1><h2>For runs: test, train
</h2><p>...</p>",
"loss2": "<p>The lossy details</p>",
}
"""
tag_to_descriptions, description_to_runs = _get_tag_description_info(
mapping
)
result = {}
for tag in tag_to_descriptions:
descriptions = sorted(tag_to_descriptions[tag])
if len(descriptions) == 1:
description = descriptions[0]
else:
description = _build_combined_description(
descriptions, description_to_runs
)
result[tag] = plugin_util.markdown_to_safe_html(description)
return result
def _get_run_tag_info(mapping):
"""Returns a map of run names to a list of tag names.
Args:
mapping: a nested map `d` such that `d[run][tag]` is a time series
produced by DataProvider's `list_*` methods.
Returns:
A map from run strings to a list of tag strings. E.g.
{"loss001a": ["actor/loss", "critic/loss"], ...}
"""
return {run: sorted(mapping[run]) for run in mapping}
def _format_basic_mapping(mapping):
"""Prepares a scalar or histogram mapping for client consumption.
Args:
mapping: a nested map `d` such that `d[run][tag]` is a time series
produced by DataProvider's `list_*` methods.
Returns:
A dict with the following fields:
runTagInfo: the return type of `_get_run_tag_info`
tagDescriptions: the return type of `_get_tag_to_description`
"""
return {
"runTagInfo": _get_run_tag_info(mapping),
"tagDescriptions": _get_tag_to_description(mapping),
}
def _format_image_blob_sequence_datum(sorted_datum_list, sample):
"""Formats image metadata from a list of BlobSequenceDatum's for clients.
This expects that frontend clients need to access images based on the
run+tag+sample.
Args:
sorted_datum_list: a list of DataProvider's `BlobSequenceDatum`, sorted by
step. This can be produced via DataProvider's `read_blob_sequences`.
sample: zero-indexed integer for the requested sample.
Returns:
A list of `ImageStepDatum` (see http_api.md).
"""
# For images, ignore the first 2 items of a BlobSequenceDatum's values, which
# correspond to width, height.
index = sample + 2
step_data = []
for datum in sorted_datum_list:
if len(datum.values) <= index:
continue
step_data.append(
{
"step": datum.step,
"wallTime": datum.wall_time,
"imageId": datum.values[index].blob_key,
}
)
return step_data
def _get_tag_run_image_info(mapping):
"""Returns a map of tag names to run information.
Args:
mapping: the result of DataProvider's `list_blob_sequences`.
Returns:
A nested map from run strings to tag string to image info, where image
info is an object of form {"maxSamplesPerStep": num}. For example,
{
"reshaped": {
"test": {"maxSamplesPerStep": 1},
"train": {"maxSamplesPerStep": 1}
},
"convolved": {"test": {"maxSamplesPerStep": 50}},
}
"""
tag_run_image_info = collections.defaultdict(dict)
for run, tag_to_content in mapping.items():
for tag, metadatum in tag_to_content.items():
tag_run_image_info[tag][run] = {
"maxSamplesPerStep": metadatum.max_length - 2 # width, height
}
return dict(tag_run_image_info)
def _format_image_mapping(mapping):
"""Prepares an image mapping for client consumption.
Args:
mapping: the result of DataProvider's `list_blob_sequences`.
Returns:
A dict with the following fields:
tagRunSampledInfo: the return type of `_get_tag_run_image_info`
tagDescriptions: the return type of `_get_tag_description_info`
"""
return {
"tagDescriptions": _get_tag_to_description(mapping),
"tagRunSampledInfo": _get_tag_run_image_info(mapping),
}
class MetricsPlugin(base_plugin.TBPlugin):
"""Metrics Plugin for TensorBoard."""
plugin_name = metadata.PLUGIN_NAME
def __init__(self, context):
"""Instantiates MetricsPlugin.
Args:
context: A base_plugin.TBContext instance. MetricsLoader checks that
it contains a valid `data_provider`.
"""
self._data_provider = context.data_provider
# For histograms, use a round number + 1 since sampling includes both start
# and end steps, so N+1 samples corresponds to dividing the step sequence
# into N intervals.
sampling_hints = context.sampling_hints or {}
self._plugin_downsampling = {
"scalars": sampling_hints.get(scalar_metadata.PLUGIN_NAME, 1000),
"histograms": sampling_hints.get(
histogram_metadata.PLUGIN_NAME, 51
),
"images": sampling_hints.get(image_metadata.PLUGIN_NAME, 10),
}
self._scalar_version_checker = plugin_util._MetadataVersionChecker(
data_kind="scalar time series",
latest_known_version=0,
)
self._histogram_version_checker = plugin_util._MetadataVersionChecker(
data_kind="histogram time series",
latest_known_version=0,
)
self._image_version_checker = plugin_util._MetadataVersionChecker(
data_kind="image time series",
latest_known_version=0,
)
def frontend_metadata(self):
return base_plugin.FrontendMetadata(
is_ng_component=True, tab_name="Time Series"
)
def get_plugin_apps(self):
return {
"/tags": self._serve_tags,
"/timeSeries": self._serve_time_series,
"/imageData": self._serve_image_data,
}
def data_plugin_names(self):
return (
scalar_metadata.PLUGIN_NAME,
histogram_metadata.PLUGIN_NAME,
image_metadata.PLUGIN_NAME,
)
def is_active(self):
return False # 'data_plugin_names' suffices.
@wrappers.Request.application
def _serve_tags(self, request):
ctx = plugin_util.context(request.environ)
experiment = plugin_util.experiment_id(request.environ)
index = self._tags_impl(ctx, experiment=experiment)
return http_util.Respond(request, index, "application/json")
def _tags_impl(self, ctx, experiment=None):
"""Returns tag metadata for a given experiment's logged metrics.
Args:
ctx: A `tensorboard.context.RequestContext` value.
experiment: optional string ID of the request's experiment.
Returns:
A nested dict 'd' with keys in ("scalars", "histograms", "images")
and values being the return type of _format_*mapping.
"""
scalar_mapping = self._data_provider.list_scalars(
ctx,
experiment_id=experiment,
plugin_name=scalar_metadata.PLUGIN_NAME,
)
scalar_mapping = self._filter_by_version(
scalar_mapping,
scalar_metadata.parse_plugin_metadata,
self._scalar_version_checker,
)
histogram_mapping = self._data_provider.list_tensors(
ctx,
experiment_id=experiment,
plugin_name=histogram_metadata.PLUGIN_NAME,
)
if histogram_mapping is None:
histogram_mapping = {}
histogram_mapping = self._filter_by_version(
histogram_mapping,
histogram_metadata.parse_plugin_metadata,
self._histogram_version_checker,
)
image_mapping = self._data_provider.list_blob_sequences(
ctx,
experiment_id=experiment,
plugin_name=image_metadata.PLUGIN_NAME,
)
if image_mapping is None:
image_mapping = {}
image_mapping = self._filter_by_version(
image_mapping,
image_metadata.parse_plugin_metadata,
self._image_version_checker,
)
result = {}
result["scalars"] = _format_basic_mapping(scalar_mapping)
result["histograms"] = _format_basic_mapping(histogram_mapping)
result["images"] = _format_image_mapping(image_mapping)
return result
def _filter_by_version(self, mapping, parse_metadata, version_checker):
"""Filter `DataProvider.list_*` output by summary metadata version."""
result = {run: {} for run in mapping}
for run, tag_to_content in mapping.items():
for tag, metadatum in tag_to_content.items():
md = parse_metadata(metadatum.plugin_content)
if not version_checker.ok(md.version, run, tag):
continue
result[run][tag] = metadatum
return result
@wrappers.Request.application
def _serve_time_series(self, request):
ctx = plugin_util.context(request.environ)
experiment = plugin_util.experiment_id(request.environ)
if request.method == "POST":
series_requests_string = request.form.get("requests")
else:
series_requests_string = request.args.get("requests")
if not series_requests_string:
raise errors.InvalidArgumentError("Missing 'requests' field")
try:
series_requests = json.loads(series_requests_string)
except ValueError:
raise errors.InvalidArgumentError(
"Unable to parse 'requests' as JSON"
)
response = self._time_series_impl(ctx, experiment, series_requests)
return http_util.Respond(request, response, "application/json")
def _time_series_impl(self, ctx, experiment, series_requests):
"""Constructs a list of responses from a list of series requests.
Args:
ctx: A `tensorboard.context.RequestContext` value.
experiment: string ID of the request's experiment.
series_requests: a list of `TimeSeriesRequest` dicts (see http_api.md).
Returns:
A list of `TimeSeriesResponse` dicts (see http_api.md).
"""
responses = [
self._get_time_series(ctx, experiment, request)
for request in series_requests
]
return responses
def _create_base_response(self, series_request):
tag = series_request.get("tag")
run = series_request.get("run")
plugin = series_request.get("plugin")
sample = series_request.get("sample")
response = {"plugin": plugin, "tag": tag}
if isinstance(run, str):
response["run"] = run
if isinstance(sample, int):
response["sample"] = sample
return response
def _get_invalid_request_error(self, series_request):
tag = series_request.get("tag")
plugin = series_request.get("plugin")
run = series_request.get("run")
sample = series_request.get("sample")
if not isinstance(tag, str):
return "Missing tag"
if (
plugin != scalar_metadata.PLUGIN_NAME
and plugin != histogram_metadata.PLUGIN_NAME
and plugin != image_metadata.PLUGIN_NAME
):
return "Invalid plugin"
if plugin in _SINGLE_RUN_PLUGINS and not isinstance(run, str):
return "Missing run"
if plugin in _SAMPLED_PLUGINS and not isinstance(sample, int):
return "Missing sample"
return None
def _get_time_series(self, ctx, experiment, series_request):
"""Returns time series data for a given tag, plugin.
Args:
ctx: A `tensorboard.context.RequestContext` value.
experiment: string ID of the request's experiment.
series_request: a `TimeSeriesRequest` (see http_api.md).
Returns:
A `TimeSeriesResponse` dict (see http_api.md).
"""
tag = series_request.get("tag")
run = series_request.get("run")
plugin = series_request.get("plugin")
sample = series_request.get("sample")
response = self._create_base_response(series_request)
request_error = self._get_invalid_request_error(series_request)
if request_error:
response["error"] = request_error
return response
runs = [run] if run else None
run_to_series = None
if plugin == scalar_metadata.PLUGIN_NAME:
run_to_series = self._get_run_to_scalar_series(
ctx, experiment, tag, runs
)
if plugin == histogram_metadata.PLUGIN_NAME:
run_to_series = self._get_run_to_histogram_series(
ctx, experiment, tag, runs
)
if plugin == image_metadata.PLUGIN_NAME:
run_to_series = self._get_run_to_image_series(
ctx, experiment, tag, sample, runs
)
response["runToSeries"] = run_to_series
return response
def _get_run_to_scalar_series(self, ctx, experiment, tag, runs):
"""Builds a run-to-scalar-series dict for client consumption.
Args:
ctx: A `tensorboard.context.RequestContext` value.
experiment: a string experiment id.
tag: string of the requested tag.
runs: optional list of run names as strings.
Returns:
A map from string run names to `ScalarStepDatum` (see http_api.md).
"""
mapping = self._data_provider.read_scalars(
ctx,
experiment_id=experiment,
plugin_name=scalar_metadata.PLUGIN_NAME,
downsample=self._plugin_downsampling["scalars"],
run_tag_filter=provider.RunTagFilter(runs=runs, tags=[tag]),
)
run_to_series = {}
for result_run, tag_data in mapping.items():
if tag not in tag_data:
continue
values = [
{
"wallTime": datum.wall_time,
"step": datum.step,
"value": datum.value,
}
for datum in tag_data[tag]
]
run_to_series[result_run] = values
return run_to_series
def _format_histogram_datum_bins(self, datum):
"""Formats a histogram datum's bins for client consumption.
Args:
datum: a DataProvider's TensorDatum.
Returns:
A list of `HistogramBin`s (see http_api.md).
"""
numpy_list = datum.numpy.tolist()
bins = [{"min": x[0], "max": x[1], "count": x[2]} for x in numpy_list]
return bins
def _get_run_to_histogram_series(self, ctx, experiment, tag, runs):
"""Builds a run-to-histogram-series dict for client consumption.
Args:
ctx: A `tensorboard.context.RequestContext` value.
experiment: a string experiment id.
tag: string of the requested tag.
runs: optional list of run names as strings.
Returns:
A map from string run names to `HistogramStepDatum` (see http_api.md).
"""
mapping = self._data_provider.read_tensors(
ctx,
experiment_id=experiment,
plugin_name=histogram_metadata.PLUGIN_NAME,
downsample=self._plugin_downsampling["histograms"],
run_tag_filter=provider.RunTagFilter(runs=runs, tags=[tag]),
)
run_to_series = {}
for result_run, tag_data in mapping.items():
if tag not in tag_data:
continue
values = [
{
"wallTime": datum.wall_time,
"step": datum.step,
"bins": self._format_histogram_datum_bins(datum),
}
for datum in tag_data[tag]
]
run_to_series[result_run] = values
return run_to_series
def _get_run_to_image_series(self, ctx, experiment, tag, sample, runs):
"""Builds a run-to-image-series dict for client consumption.
Args:
ctx: A `tensorboard.context.RequestContext` value.
experiment: a string experiment id.
tag: string of the requested tag.
sample: zero-indexed integer for the requested sample.
runs: optional list of run names as strings.
Returns:
A `RunToSeries` dict (see http_api.md).
"""
mapping = self._data_provider.read_blob_sequences(
ctx,
experiment_id=experiment,
plugin_name=image_metadata.PLUGIN_NAME,
downsample=self._plugin_downsampling["images"],
run_tag_filter=provider.RunTagFilter(runs, tags=[tag]),
)
run_to_series = {}
for result_run, tag_data in mapping.items():
if tag not in tag_data:
continue
blob_sequence_datum_list = tag_data[tag]
series = _format_image_blob_sequence_datum(
blob_sequence_datum_list, sample
)
if series:
run_to_series[result_run] = series
return run_to_series
@wrappers.Request.application
def _serve_image_data(self, request):
"""Serves an individual image."""
ctx = plugin_util.context(request.environ)
blob_key = request.args["imageId"]
if not blob_key:
raise errors.InvalidArgumentError("Missing 'imageId' field")
(data, content_type) = self._image_data_impl(ctx, blob_key)
return http_util.Respond(request, data, content_type)
def _image_data_impl(self, ctx, blob_key):
"""Gets the image data for a blob key.
Args:
ctx: A `tensorboard.context.RequestContext` value.
blob_key: a string identifier for a DataProvider blob.
Returns:
A tuple containing:
data: a raw bytestring of the requested image's contents.
content_type: a string HTTP content type.
"""
data = self._data_provider.read_blob(ctx, blob_key=blob_key)
image_type = imghdr.what(None, data)
content_type = _IMGHDR_TO_MIMETYPE.get(
image_type, _DEFAULT_IMAGE_MIMETYPE
)
return (data, content_type)
|