Skip to content

Commit ff933ab

Browse files
bottlerfacebook-github-bot
authored andcommitted
make visdom optional
Summary: Make Implicitron run without visdom installed. Reviewed By: shapovalov Differential Revision: D40587974 fbshipit-source-id: dc319596c7a4d10a4c54c556dabc89ad9d25c2fb
1 parent 46cb5aa commit ff933ab

File tree

6 files changed

+44
-22
lines changed

6 files changed

+44
-22
lines changed

projects/implicitron_trainer/experiment.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
Stats are logged and plotted to the file "train_stats.pdf" in the
4242
same directory. The stats are also saved as part of the checkpoint file.
4343
- Visualizations
44-
Prredictions are plotted to a visdom server running at the
44+
Predictions are plotted to a visdom server running at the
4545
port specified by the `visdom_server` and `visdom_port` keys in the
4646
config file.
4747

pytorch3d/implicitron/evaluation/evaluate_new_view_synthesis.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import warnings
1010
from collections import OrderedDict
1111
from dataclasses import dataclass, field
12-
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
12+
from typing import Any, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
1313

1414
import numpy as np
1515
import torch
@@ -27,7 +27,9 @@
2727
from pytorch3d.renderer.cameras import CamerasBase, PerspectiveCameras
2828
from pytorch3d.vis.plotly_vis import plot_scene
2929
from tabulate import tabulate
30-
from visdom import Visdom
30+
31+
if TYPE_CHECKING:
32+
from visdom import Visdom
3133

3234

3335
EVAL_N_SRC_VIEWS = [1, 3, 5, 7, 9]
@@ -43,14 +45,16 @@ class _Visualizer:
4345

4446
visdom_env: str = "eval_debug"
4547

46-
_viz: Visdom = field(init=False)
48+
_viz: Optional["Visdom"] = field(init=False)
4749

4850
def __post_init__(self):
4951
self._viz = vis_utils.get_visdom_connection()
5052

5153
def show_rgb(
5254
self, loss_value: float, metric_name: str, loss_mask_now: torch.Tensor
5355
):
56+
if self._viz is None:
57+
return
5458
self._viz.images(
5559
torch.cat(
5660
(
@@ -68,7 +72,10 @@ def show_rgb(
6872
def show_depth(
6973
self, depth_loss: float, name_postfix: str, loss_mask_now: torch.Tensor
7074
):
71-
self._viz.images(
75+
if self._viz is None:
76+
return
77+
viz = self._viz
78+
viz.images(
7279
torch.cat(
7380
(
7481
make_depth_image(self.depth_render, loss_mask_now),
@@ -80,13 +87,13 @@ def show_depth(
8087
win="depth_abs" + name_postfix,
8188
opts={"title": f"depth_abs_{name_postfix}_{depth_loss:1.2f}"},
8289
)
83-
self._viz.images(
90+
viz.images(
8491
loss_mask_now,
8592
env=self.visdom_env,
8693
win="depth_abs" + name_postfix + "_mask",
8794
opts={"title": f"depth_abs_{name_postfix}_{depth_loss:1.2f}_mask"},
8895
)
89-
self._viz.images(
96+
viz.images(
9097
self.depth_mask,
9198
env=self.visdom_env,
9299
win="depth_abs" + name_postfix + "_maskd",
@@ -126,7 +133,7 @@ def show_depth(
126133
pointcloud_max_points=10000,
127134
pointcloud_marker_size=1,
128135
)
129-
self._viz.plotlyplot(
136+
viz.plotlyplot(
130137
plotlyplot,
131138
env=self.visdom_env,
132139
win=f"pcl{name_postfix}",

pytorch3d/implicitron/models/generic_model.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import math
1313
import warnings
1414
from dataclasses import field
15-
from typing import Any, Dict, List, Optional, Tuple, Union
15+
from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING, Union
1616

1717
import torch
1818
import tqdm
@@ -34,7 +34,9 @@
3434
from pytorch3d.renderer import utils as rend_utils
3535

3636
from pytorch3d.renderer.cameras import CamerasBase
37-
from visdom import Visdom
37+
38+
if TYPE_CHECKING:
39+
from visdom import Visdom
3840

3941
from .base_model import ImplicitronModelBase, ImplicitronRender
4042
from .feature_extractor import FeatureExtractorBase
@@ -544,7 +546,7 @@ def _get_objective(self, preds) -> Optional[torch.Tensor]:
544546

545547
def visualize(
546548
self,
547-
viz: Visdom,
549+
viz: Optional["Visdom"],
548550
visdom_env_imgs: str,
549551
preds: Dict[str, Any],
550552
prefix: str,
@@ -559,7 +561,7 @@ def visualize(
559561
preds: predictions dict like returned by forward()
560562
prefix: prepended to the names of images
561563
"""
562-
if not viz.check_connection():
564+
if viz is None or not viz.check_connection():
563565
logger.info("no visdom server! -> skipping batch vis")
564566
return
565567

pytorch3d/implicitron/models/visualization/render_flyaround.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import math
1111
import os
1212
import random
13-
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
13+
from typing import Any, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
1414

1515
import numpy as np
1616
import torch
@@ -27,7 +27,9 @@
2727
make_depth_image,
2828
)
2929
from tqdm import tqdm
30-
from visdom import Visdom
30+
31+
if TYPE_CHECKING:
32+
from visdom import Visdom
3133

3234
logger = logging.getLogger(__name__)
3335

@@ -272,7 +274,7 @@ def _stack_images(ims: torch.Tensor, size: Optional[Tuple[int, int]]) -> torch.T
272274
def _show_predictions(
273275
preds: List[Dict[str, Any]],
274276
sequence_name: str,
275-
viz: Visdom,
277+
viz: "Visdom",
276278
viz_env: str = "visualizer",
277279
predicted_keys: Sequence[str] = (
278280
"images_render",
@@ -318,7 +320,7 @@ def _show_predictions(
318320
def _generate_prediction_videos(
319321
preds: List[Dict[str, Any]],
320322
sequence_name: str,
321-
viz: Optional[Visdom] = None,
323+
viz: Optional["Visdom"] = None,
322324
viz_env: str = "visualizer",
323325
predicted_keys: Sequence[str] = (
324326
"images_render",

pytorch3d/implicitron/tools/stats.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ def plot_stats(
337337
novisdom = False
338338

339339
viz = get_visdom_connection(server=visdom_server, port=visdom_port)
340-
if not viz.check_connection():
340+
if viz is None or not viz.check_connection():
341341
print("no visdom server! -> skipping visdom plots")
342342
novisdom = True
343343

pytorch3d/implicitron/tools/vis_utils.py

+16-5
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
# LICENSE file in the root directory of this source tree.
66

77
import logging
8-
from typing import Any, Dict, Tuple
8+
from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING
99

1010
import torch
11-
from visdom import Visdom
11+
12+
if TYPE_CHECKING:
13+
from visdom import Visdom
1214

1315

1416
logger = logging.getLogger(__name__)
@@ -40,9 +42,9 @@ def get_visdom_env(visdom_env: str, exp_dir: str) -> str:
4042
def get_visdom_connection(
4143
server: str = "http://localhost",
4244
port: int = 8097,
43-
) -> Visdom:
45+
) -> Optional["Visdom"]:
4446
"""
45-
Obtain a connection to a visdom server.
47+
Obtain a connection to a visdom server if visdom is installed.
4648
4749
Args:
4850
server: Server address.
@@ -51,14 +53,23 @@ def get_visdom_connection(
5153
Returns:
5254
connection: The connection object.
5355
"""
56+
try:
57+
from visdom import Visdom
58+
except ImportError:
59+
logger.debug("Cannot load visdom")
60+
return None
61+
62+
if server == "None":
63+
return None
64+
5465
global _viz_singleton
5566
if _viz_singleton is None:
5667
_viz_singleton = Visdom(server=server, port=port)
5768
return _viz_singleton
5869

5970

6071
def visualize_basics(
61-
viz: Visdom,
72+
viz: "Visdom",
6273
preds: Dict[str, Any],
6374
visdom_env_imgs: str,
6475
title: str = "",

0 commit comments

Comments
 (0)