Karim Knaebel commited on
Commit
e977198
·
1 Parent(s): cc04c06

app: remove diagnostic timings and stale entry points

Browse files
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import logging
2
  import os
3
  from functools import partial
4
  from pathlib import Path
@@ -17,15 +16,6 @@ from result_processing import export_result, save_reconstruction, update_results
17
  from surge.inference import DEFAULT_CHECKPOINT, infer_image, resize_to_max_size
18
  from surge import SurGe
19
  from surge.utils.background import skyseg_mask
20
- from surge.utils.timing import logger as timing_logger, timed
21
-
22
- timing_handler = logging.StreamHandler()
23
- timing_handler.setFormatter(logging.Formatter(
24
- "%(asctime)s [timing] pid=%(process)d thread=%(thread)d %(message)s"
25
- ))
26
- timing_logger.addHandler(timing_handler)
27
- timing_logger.setLevel(logging.INFO)
28
- timing_logger.propagate = False
29
 
30
  print(
31
  f"PyTorch {torch.__version__}, CUDA build {torch.version.cuda or 'none'}, "
@@ -76,7 +66,6 @@ def _rgb_image(image: np.ndarray) -> np.ndarray:
76
 
77
 
78
  @spaces.GPU(duration=5) # it's really more like <<1s, but just to be safe
79
- @timed("inference.worker_total")
80
  def _inference_result(
81
  image: np.ndarray,
82
  resize_outputs_to_input_size: bool,
@@ -92,19 +81,14 @@ def _inference_result(
92
  )
93
 
94
 
95
- @timed("reconstruction.total")
96
  def run_inference(input_image: np.ndarray, resize_outputs_to_input_size: bool) -> str:
97
  if input_image is None:
98
  raise gr.Error("Upload an image first.")
99
- with timed("reconstruction.input"):
100
- input_image = _resize_for_inference(_rgb_image(input_image))
101
- timing_logger.info("reconstruction.input_shape: %s", input_image.shape)
102
- with timed("inference.call_including_queue_and_transfer"):
103
- result = _inference_result(input_image, resize_outputs_to_input_size)
104
  return save_reconstruction(result, skyseg_mask(result["image"]))
105
 
106
 
107
- @timed("example.generate_total")
108
  def run_example(image: np.ndarray, resize: bool, strength: float, sky: bool, black: bool, white: bool):
109
  path = run_inference(image, resize)
110
  return path, *update_results(path, strength, sky, black, white)
 
 
1
  import os
2
  from functools import partial
3
  from pathlib import Path
 
16
  from surge.inference import DEFAULT_CHECKPOINT, infer_image, resize_to_max_size
17
  from surge import SurGe
18
  from surge.utils.background import skyseg_mask
 
 
 
 
 
 
 
 
 
19
 
20
  print(
21
  f"PyTorch {torch.__version__}, CUDA build {torch.version.cuda or 'none'}, "
 
66
 
67
 
68
  @spaces.GPU(duration=5) # it's really more like <<1s, but just to be safe
 
69
  def _inference_result(
70
  image: np.ndarray,
71
  resize_outputs_to_input_size: bool,
 
81
  )
82
 
83
 
 
84
  def run_inference(input_image: np.ndarray, resize_outputs_to_input_size: bool) -> str:
85
  if input_image is None:
86
  raise gr.Error("Upload an image first.")
87
+ input_image = _resize_for_inference(_rgb_image(input_image))
88
+ result = _inference_result(input_image, resize_outputs_to_input_size)
 
 
 
89
  return save_reconstruction(result, skyseg_mask(result["image"]))
90
 
91
 
 
92
  def run_example(image: np.ndarray, resize: bool, strength: float, sky: bool, black: bool, white: bool):
93
  path = run_inference(image, resize)
94
  return path, *update_results(path, strength, sky, black, white)
pyproject.toml CHANGED
@@ -21,10 +21,6 @@ dependencies = [
21
  ]
22
  requires-python = ">=3.10"
23
 
24
- [project.scripts]
25
- surge-cli = "surge.cli:main"
26
- surge-app = "surge.app:main"
27
-
28
  [project.urls]
29
  Homepage = "https://github.com/karimknaebel/surge"
30
 
 
21
  ]
22
  requires-python = ">=3.10"
23
 
 
 
 
 
24
  [project.urls]
25
  Homepage = "https://github.com/karimknaebel/surge"
26
 
result_processing.py CHANGED
@@ -10,7 +10,6 @@ from PIL import Image
10
  from pointmap_viewer import cleanup_threshold, pointmap_data
11
  from surge.inference import build_mesh, point_cloud_from_result
12
  from surge.utils.io import save_glb, save_ply
13
- from surge.utils.timing import logger as timing_logger, timed
14
  from surge.utils.vis import colorize_depth, colorize_normal
15
 
16
 
@@ -28,26 +27,15 @@ def depth_edge_scores(depth: np.ndarray, mask: np.ndarray) -> np.ndarray:
28
  )
29
 
30
 
31
- @timed("reconstruction.save_total")
32
  def save_reconstruction(result: dict, sky_mask: np.ndarray) -> str:
33
  path = Path(tempfile.mkdtemp(prefix="surge-result-")) / "result.npz"
34
- with timed("reconstruction.prepare_arrays"):
35
- result = {**result, "sky_mask": sky_mask}
36
- with timed("reconstruction.depth_edge_scores"):
37
- result["edge_scores"] = depth_edge_scores(result["depth"], result["mask"])
38
- with timed("reconstruction.black_mask"):
39
- result["black_mask"] = result["image"].sum(axis=-1) < 16
40
- with timed("reconstruction.white_mask"):
41
- result["white_mask"] = np.all(result["image"] > 240, axis=-1)
42
- with timed("reconstruction.colorize_depth"):
43
- result["depth_preview"] = colorize_depth(result["depth"], result["mask"])
44
- with timed("reconstruction.colorize_normals"):
45
- result["normal_preview"] = colorize_normal(result["normal"], result["mask"] & result["normal_mask"])
46
- with timed("reconstruction.write_npz"):
47
- np.savez(path, **result)
48
- timing_logger.info(
49
- "reconstruction.saved: %s (%.1f MB)", path, path.stat().st_size / 1e6,
50
- )
51
  return str(path)
52
 
53
 
@@ -82,16 +70,12 @@ def save_depth_webp(path: Path, depth: np.ndarray, mask: np.ndarray) -> None:
82
 
83
 
84
  @lru_cache(maxsize=4)
85
- @timed("preview.load_cache_miss_total")
86
  def load_reconstruction(path: str) -> tuple[dict, Path]:
87
- timing_logger.info("preview.load_path: %s", path)
88
- with timed("preview.read_npz"), np.load(path) as archive:
89
  result = dict(archive)
90
  assets = Path(tempfile.mkdtemp(prefix="surge-views-"))
91
- with timed("preview.encode_depth_webp"):
92
- save_depth_webp(assets / "depth.webp", result["depth"], result["mask"])
93
- with timed("preview.encode_image_webp"):
94
- Image.fromarray(result["image"]).save(assets / "image.webp", lossless=True, quality=50, method=2, exact=True)
95
  return result, assets
96
 
97
 
@@ -106,25 +90,16 @@ def result_mask(result: dict, strength: float, sky: bool, black: bool, white: bo
106
  return mask
107
 
108
 
109
- @timed("preview.update_total")
110
  def update_results(path: str | None, strength: float, sky: bool, black: bool, white: bool):
111
  if path is None:
112
  return gr.skip(), gr.skip(), gr.skip()
113
- timing_logger.info(
114
- "preview.settings: strength=%s sky=%s black=%s white=%s", strength, sky, black, white,
115
- )
116
- with timed("preview.load_reconstruction"):
117
- result, assets = load_reconstruction(path)
118
- with timed("preview.cleanup_mask"):
119
- mask = result_mask(result, strength, sky, black, white)
120
  output = assets / f"{strength:g}-{int(sky)}{int(black)}{int(white)}"
121
  output.mkdir(exist_ok=True)
122
- with timed("preview.encode_mask_png"):
123
- Image.fromarray(mask).save(output / "mask.png")
124
- with timed("preview.encode_depth_png"):
125
- Image.fromarray(np.where(mask[..., None], result["depth_preview"], 0)).save(output / "depth.png")
126
- with timed("preview.encode_normals_png"):
127
- Image.fromarray(np.where(mask[..., None], result["normal_preview"], 127)).save(output / "normals.png")
128
  return (
129
  pointmap_data(
130
  assets / "depth.webp", assets / "image.webp", result["intrinsics"],
 
10
  from pointmap_viewer import cleanup_threshold, pointmap_data
11
  from surge.inference import build_mesh, point_cloud_from_result
12
  from surge.utils.io import save_glb, save_ply
 
13
  from surge.utils.vis import colorize_depth, colorize_normal
14
 
15
 
 
27
  )
28
 
29
 
 
30
  def save_reconstruction(result: dict, sky_mask: np.ndarray) -> str:
31
  path = Path(tempfile.mkdtemp(prefix="surge-result-")) / "result.npz"
32
+ result = {**result, "sky_mask": sky_mask}
33
+ result["edge_scores"] = depth_edge_scores(result["depth"], result["mask"])
34
+ result["black_mask"] = result["image"].sum(axis=-1) < 16
35
+ result["white_mask"] = np.all(result["image"] > 240, axis=-1)
36
+ result["depth_preview"] = colorize_depth(result["depth"], result["mask"])
37
+ result["normal_preview"] = colorize_normal(result["normal"], result["mask"] & result["normal_mask"])
38
+ np.savez(path, **result)
 
 
 
 
 
 
 
 
 
 
39
  return str(path)
40
 
41
 
 
70
 
71
 
72
  @lru_cache(maxsize=4)
 
73
  def load_reconstruction(path: str) -> tuple[dict, Path]:
74
+ with np.load(path) as archive:
 
75
  result = dict(archive)
76
  assets = Path(tempfile.mkdtemp(prefix="surge-views-"))
77
+ save_depth_webp(assets / "depth.webp", result["depth"], result["mask"])
78
+ Image.fromarray(result["image"]).save(assets / "image.webp", lossless=True, quality=50, method=2, exact=True)
 
 
79
  return result, assets
80
 
81
 
 
90
  return mask
91
 
92
 
 
93
  def update_results(path: str | None, strength: float, sky: bool, black: bool, white: bool):
94
  if path is None:
95
  return gr.skip(), gr.skip(), gr.skip()
96
+ result, assets = load_reconstruction(path)
97
+ mask = result_mask(result, strength, sky, black, white)
 
 
 
 
 
98
  output = assets / f"{strength:g}-{int(sky)}{int(black)}{int(white)}"
99
  output.mkdir(exist_ok=True)
100
+ Image.fromarray(mask).save(output / "mask.png")
101
+ Image.fromarray(np.where(mask[..., None], result["depth_preview"], 0)).save(output / "depth.png")
102
+ Image.fromarray(np.where(mask[..., None], result["normal_preview"], 127)).save(output / "normals.png")
 
 
 
103
  return (
104
  pointmap_data(
105
  assets / "depth.webp", assets / "image.webp", result["intrinsics"],
surge/inference.py CHANGED
@@ -1,4 +1,3 @@
1
- import logging
2
  import os
3
  from typing import Literal
4
 
@@ -11,7 +10,6 @@ import utils3d
11
 
12
  from surge import SurGe
13
  from surge.utils.geometry_numpy import depth_occlusion_edge_numpy
14
- from surge.utils.timing import logger as timing_logger, timed
15
 
16
  DEFAULT_CHECKPOINT = "karimknaebel/surge-large"
17
  DEFAULT_TOKEN_RANGE = (1024, 2802)
@@ -46,15 +44,13 @@ def image_to_tensor(image: np.ndarray, device: torch.device) -> torch.Tensor:
46
  )
47
 
48
 
49
- @timed("inference.postprocess_total")
50
  def postprocess_output(
51
  image: np.ndarray,
52
  output: dict[str, torch.Tensor],
53
  unit_scale: bool = False,
54
  ) -> dict[str, np.ndarray]:
55
- with timed("inference.copy_to_cpu"):
56
- points = output["points"][0].float().cpu().numpy()
57
- depth = output["depth"][0].float().cpu().numpy()
58
 
59
  if image.shape[:2] != points.shape[:2]:
60
  image = cv2.resize(
@@ -70,22 +66,17 @@ def postprocess_output(
70
  depth = depth / scale
71
 
72
  if output["points"].is_cuda:
73
- with timed("inference.gpu_normals"):
74
- gpu_points = output["points"][0].float()
75
- if unit_scale:
76
- gpu_points = gpu_points / float(scale)
77
- normal, normal_mask = utils3d.torch.points_to_normals(
78
- gpu_points, mask=torch.from_numpy(mask).to(gpu_points.device),
79
- )
80
- normal = torch.where(normal_mask[..., None], normal, 0)
81
- if timing_logger.isEnabledFor(logging.INFO):
82
- torch.cuda.synchronize(gpu_points.device)
83
- with timed("inference.copy_normals_to_cpu"):
84
- normal = normal.cpu().numpy()
85
- normal_mask = normal_mask.cpu().numpy()
86
  else:
87
- with timed("inference.cpu_normals"):
88
- normal, normal_mask = utils3d.numpy.points_to_normals(points, mask=mask)
89
  return {
90
  "image": image,
91
  "points": points,
@@ -107,17 +98,13 @@ def infer_image(
107
  fov_x: float | None = None,
108
  unit_scale: bool = False,
109
  ) -> dict[str, np.ndarray]:
110
- with timed("inference.model_and_input_transfer"):
111
- output = model.infer(
112
- image_to_tensor(image, device),
113
- num_tokens=num_tokens,
114
- resize_output=resize_output,
115
- force_projection=force_projection,
116
- fov_x=fov_x,
117
- )
118
- # Attribute asynchronous CUDA work to inference rather than the CPU copy.
119
- if device.type == "cuda" and timing_logger.isEnabledFor(logging.INFO):
120
- torch.cuda.synchronize(device)
121
  return postprocess_output(image, output, unit_scale=unit_scale)
122
 
123
 
 
 
1
  import os
2
  from typing import Literal
3
 
 
10
 
11
  from surge import SurGe
12
  from surge.utils.geometry_numpy import depth_occlusion_edge_numpy
 
13
 
14
  DEFAULT_CHECKPOINT = "karimknaebel/surge-large"
15
  DEFAULT_TOKEN_RANGE = (1024, 2802)
 
44
  )
45
 
46
 
 
47
  def postprocess_output(
48
  image: np.ndarray,
49
  output: dict[str, torch.Tensor],
50
  unit_scale: bool = False,
51
  ) -> dict[str, np.ndarray]:
52
+ points = output["points"][0].float().cpu().numpy()
53
+ depth = output["depth"][0].float().cpu().numpy()
 
54
 
55
  if image.shape[:2] != points.shape[:2]:
56
  image = cv2.resize(
 
66
  depth = depth / scale
67
 
68
  if output["points"].is_cuda:
69
+ gpu_points = output["points"][0].float()
70
+ if unit_scale:
71
+ gpu_points = gpu_points / float(scale)
72
+ normal, normal_mask = utils3d.torch.points_to_normals(
73
+ gpu_points, mask=torch.from_numpy(mask).to(gpu_points.device),
74
+ )
75
+ normal = torch.where(normal_mask[..., None], normal, 0)
76
+ normal = normal.cpu().numpy()
77
+ normal_mask = normal_mask.cpu().numpy()
 
 
 
 
78
  else:
79
+ normal, normal_mask = utils3d.numpy.points_to_normals(points, mask=mask)
 
80
  return {
81
  "image": image,
82
  "points": points,
 
98
  fov_x: float | None = None,
99
  unit_scale: bool = False,
100
  ) -> dict[str, np.ndarray]:
101
+ output = model.infer(
102
+ image_to_tensor(image, device),
103
+ num_tokens=num_tokens,
104
+ resize_output=resize_output,
105
+ force_projection=force_projection,
106
+ fov_x=fov_x,
107
+ )
 
 
 
 
108
  return postprocess_output(image, output, unit_scale=unit_scale)
109
 
110
 
surge/utils/background.py CHANGED
@@ -4,26 +4,20 @@ import cv2
4
  import numpy as np
5
  from huggingface_hub import hf_hub_download
6
 
7
- from surge.utils.timing import timed
8
-
9
  SKYSEG_MODEL = "JianyuanWang/skyseg"
10
  SKYSEG_FILENAME = "skyseg.onnx"
11
 
12
 
13
  @lru_cache(maxsize=1)
14
- @timed("skyseg.initialize")
15
  def skyseg_session():
16
  import onnxruntime
17
 
18
- with timed("skyseg.resolve_model"):
19
- path = hf_hub_download(SKYSEG_MODEL, SKYSEG_FILENAME)
20
- with timed("skyseg.create_session"):
21
- options = onnxruntime.SessionOptions()
22
- options.add_session_config_entry("session.intra_op.allow_spinning", "0")
23
- return onnxruntime.InferenceSession(path, sess_options=options)
24
 
25
 
26
- @timed("skyseg.total")
27
  def skyseg_mask(image: np.ndarray) -> np.ndarray:
28
  resized = cv2.resize(image, (320, 320))
29
  x = resized.astype(np.float32) / 255.0
@@ -34,11 +28,10 @@ def skyseg_mask(image: np.ndarray) -> np.ndarray:
34
  x = x.transpose(2, 0, 1)[None].astype(np.float32)
35
 
36
  session = skyseg_session()
37
- with timed("skyseg.run"):
38
- result = session.run(
39
- [session.get_outputs()[0].name],
40
- {session.get_inputs()[0].name: x},
41
- )[0].squeeze()
42
  result = (result - result.min()) / (result.max() - result.min()) * 255
43
  result = cv2.resize(result.astype(np.uint8), (image.shape[1], image.shape[0]))
44
  return result < 32
 
4
  import numpy as np
5
  from huggingface_hub import hf_hub_download
6
 
 
 
7
  SKYSEG_MODEL = "JianyuanWang/skyseg"
8
  SKYSEG_FILENAME = "skyseg.onnx"
9
 
10
 
11
  @lru_cache(maxsize=1)
 
12
  def skyseg_session():
13
  import onnxruntime
14
 
15
+ path = hf_hub_download(SKYSEG_MODEL, SKYSEG_FILENAME)
16
+ options = onnxruntime.SessionOptions()
17
+ options.add_session_config_entry("session.intra_op.allow_spinning", "0")
18
+ return onnxruntime.InferenceSession(path, sess_options=options)
 
 
19
 
20
 
 
21
  def skyseg_mask(image: np.ndarray) -> np.ndarray:
22
  resized = cv2.resize(image, (320, 320))
23
  x = resized.astype(np.float32) / 255.0
 
28
  x = x.transpose(2, 0, 1)[None].astype(np.float32)
29
 
30
  session = skyseg_session()
31
+ result = session.run(
32
+ [session.get_outputs()[0].name],
33
+ {session.get_inputs()[0].name: x},
34
+ )[0].squeeze()
 
35
  result = (result - result.min()) / (result.max() - result.min()) * 255
36
  result = cv2.resize(result.astype(np.uint8), (image.shape[1], image.shape[0]))
37
  return result < 32
surge/utils/timing.py DELETED
@@ -1,17 +0,0 @@
1
- import logging
2
- from contextlib import contextmanager
3
- from time import perf_counter
4
-
5
- logger = logging.getLogger(__name__)
6
-
7
-
8
- @contextmanager
9
- def timed(stage: str):
10
- if not logger.isEnabledFor(logging.INFO):
11
- yield
12
- return
13
- started = perf_counter()
14
- try:
15
- yield
16
- finally:
17
- logger.info("%s: %.3fs", stage, perf_counter() - started)