MRiabov commited on
Commit
8943a48
·
1 Parent(s): 32c94fb

Add benchmark to infer.py

Browse files
Files changed (1) hide show
  1. infer.py +202 -4
infer.py CHANGED
@@ -1,7 +1,8 @@
1
  import argparse
2
  import os
3
  import pprint
4
- from typing import List, Tuple, Optional
 
5
  import yaml
6
 
7
  import numpy as np
@@ -257,6 +258,42 @@ def main():
257
  parser.add_argument(
258
  "--save_prob", action="store_true", help="Also save probability .npy"
259
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
 
261
  args = parser.parse_args()
262
 
@@ -270,9 +307,11 @@ def main():
270
  print("[WireSegHR][infer] Loaded config from:", cfg_path)
271
  pprint.pprint(cfg)
272
 
273
- assert (args.image is not None) ^ (args.images_dir is not None), (
274
- "Provide exactly one of --image or --images_dir"
275
- )
 
 
276
 
277
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
278
  precision = str(cfg["optim"].get("precision", "fp32")).lower()
@@ -294,6 +333,165 @@ def main():
294
  model.load_state_dict(state["model"])
295
  model.eval()
296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  if args.image is not None:
298
  infer_image(
299
  model,
 
1
  import argparse
2
  import os
3
  import pprint
4
+ import time
5
+ from typing import List, Tuple, Optional, Dict, Any
6
  import yaml
7
 
8
  import numpy as np
 
258
  parser.add_argument(
259
  "--save_prob", action="store_true", help="Also save probability .npy"
260
  )
261
+ # Benchmarking options
262
+ parser.add_argument(
263
+ "--benchmark",
264
+ action="store_true",
265
+ help="Run benchmarking on a directory (defaults to cfg.data.test_images)",
266
+ )
267
+ parser.add_argument(
268
+ "--bench_images_dir",
269
+ type=str,
270
+ default="",
271
+ help="Images dir for benchmark (overrides cfg.data.test_images if set)",
272
+ )
273
+ parser.add_argument(
274
+ "--bench_limit",
275
+ type=int,
276
+ default=0,
277
+ help="Limit number of images for benchmark (0 means all)",
278
+ )
279
+ parser.add_argument(
280
+ "--bench_warmup",
281
+ type=int,
282
+ default=2,
283
+ help="Number of warmup images (excluded from stats)",
284
+ )
285
+ parser.add_argument(
286
+ "--bench_size_filter",
287
+ type=str,
288
+ default="",
289
+ help="Only benchmark images matching HxW, e.g. 3000x4000",
290
+ )
291
+ parser.add_argument(
292
+ "--bench_report_json",
293
+ type=str,
294
+ default="",
295
+ help="Optional path to save JSON report of timings",
296
+ )
297
 
298
  args = parser.parse_args()
299
 
 
307
  print("[WireSegHR][infer] Loaded config from:", cfg_path)
308
  pprint.pprint(cfg)
309
 
310
+ # If benchmarking, do not require --image/--images_dir
311
+ if not args.benchmark:
312
+ assert (args.image is not None) ^ (args.images_dir is not None), (
313
+ "Provide exactly one of --image or --images_dir"
314
+ )
315
 
316
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
317
  precision = str(cfg["optim"].get("precision", "fp32")).lower()
 
333
  model.load_state_dict(state["model"])
334
  model.eval()
335
 
336
+ # Benchmark mode
337
+ if args.benchmark:
338
+ if args.bench_images_dir:
339
+ bench_dir = args.bench_images_dir
340
+ else:
341
+ bench_dir = cfg["data"]["test_images"]
342
+ assert os.path.isdir(bench_dir), f"Not a directory: {bench_dir}"
343
+
344
+ size_filter: Optional[Tuple[int, int]] = None
345
+ if args.bench_size_filter:
346
+ try:
347
+ h_str, w_str = args.bench_size_filter.lower().split("x")
348
+ size_filter = (int(h_str), int(w_str))
349
+ except Exception:
350
+ raise AssertionError(
351
+ f"Invalid --bench_size_filter format: {args.bench_size_filter} (use HxW)"
352
+ )
353
+
354
+ img_files = sorted(
355
+ [
356
+ os.path.join(bench_dir, p)
357
+ for p in os.listdir(bench_dir)
358
+ if p.lower().endswith((".jpg", ".jpeg"))
359
+ ]
360
+ )
361
+ assert len(img_files) > 0, f"No .jpg/.jpeg in {bench_dir}"
362
+
363
+ # Filter by size if requested
364
+ if size_filter is not None:
365
+ filt_files: List[str] = []
366
+ for p in img_files:
367
+ bgr = cv2.imread(p, cv2.IMREAD_COLOR)
368
+ assert bgr is not None, f"Failed to read {p}"
369
+ if bgr.shape[0] == size_filter[0] and bgr.shape[1] == size_filter[1]:
370
+ filt_files.append(p)
371
+ img_files = filt_files
372
+ assert len(img_files) > 0, (
373
+ f"No images matching {size_filter[0]}x{size_filter[1]} in {bench_dir}"
374
+ )
375
+
376
+ if args.bench_limit > 0:
377
+ img_files = img_files[: args.bench_limit]
378
+
379
+ print(f"[WireSegHR][bench] Images: {len(img_files)} from {bench_dir}")
380
+ print(f"[WireSegHR][bench] Warmup: {args.bench_warmup}")
381
+
382
+ def _sync():
383
+ if device.type == "cuda":
384
+ torch.cuda.synchronize()
385
+
386
+ timings: List[Dict[str, Any]] = []
387
+
388
+ # Warmup
389
+ for i in range(min(args.bench_warmup, len(img_files))):
390
+ _ = infer_image(
391
+ model,
392
+ img_files[i],
393
+ cfg,
394
+ device,
395
+ amp_enabled,
396
+ amp_dtype,
397
+ out_dir=None,
398
+ save_prob=False,
399
+ )
400
+
401
+ # Timed runs
402
+ for p in img_files[args.bench_warmup :]:
403
+ # Replicate internals to time coarse vs fine separately
404
+ bgr = cv2.imread(p, cv2.IMREAD_COLOR)
405
+ assert bgr is not None, f"Failed to read {p}"
406
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
407
+
408
+ coarse_size = int(cfg["coarse"]["test_size"])
409
+ minmax_enable = bool(cfg["minmax"]["enable"])
410
+ minmax_kernel = int(cfg["minmax"]["kernel"])
411
+
412
+ _sync(); t0 = time.perf_counter()
413
+ prob_c, cond_map, t_img, y_min_full, y_max_full = _coarse_forward(
414
+ model,
415
+ rgb,
416
+ coarse_size,
417
+ minmax_enable,
418
+ minmax_kernel,
419
+ device,
420
+ amp_enabled,
421
+ amp_dtype,
422
+ )
423
+ _sync(); t1 = time.perf_counter()
424
+
425
+ patch_size = int(cfg["inference"]["fine_patch_size"]) # 1024
426
+ overlap = int(cfg["fine"]["overlap"])
427
+
428
+ prob_f = _tiled_fine_forward(
429
+ model,
430
+ t_img,
431
+ cond_map,
432
+ y_min_full,
433
+ y_max_full,
434
+ patch_size,
435
+ overlap,
436
+ int(cfg.get("eval", {}).get("fine_batch", 16)),
437
+ device,
438
+ amp_enabled,
439
+ amp_dtype,
440
+ )
441
+ _sync(); t2 = time.perf_counter()
442
+
443
+ timings.append(
444
+ {
445
+ "path": p,
446
+ "H": int(t_img.shape[2]),
447
+ "W": int(t_img.shape[3]),
448
+ "t_coarse_ms": (t1 - t0) * 1000.0,
449
+ "t_fine_ms": (t2 - t1) * 1000.0,
450
+ "t_total_ms": (t2 - t0) * 1000.0,
451
+ }
452
+ )
453
+
454
+ if len(timings) == 0:
455
+ print("[WireSegHR][bench] Nothing to benchmark after warmup.")
456
+ return
457
+
458
+ def _agg(key: str) -> Tuple[float, float, float]:
459
+ vals = sorted([t[key] for t in timings])
460
+ n = len(vals)
461
+ p50 = vals[n // 2]
462
+ p95 = vals[min(n - 1, int(0.95 * (n - 1)))]
463
+ avg = sum(vals) / n
464
+ return avg, p50, p95
465
+
466
+ avg_c, p50_c, p95_c = _agg("t_coarse_ms")
467
+ avg_f, p50_f, p95_f = _agg("t_fine_ms")
468
+ avg_t, p50_t, p95_t = _agg("t_total_ms")
469
+
470
+ print("[WireSegHR][bench] Results (ms):")
471
+ print(f" Coarse avg={avg_c:.2f} p50={p50_c:.2f} p95={p95_c:.2f}")
472
+ print(f" Fine avg={avg_f:.2f} p50={p50_f:.2f} p95={p95_f:.2f}")
473
+ print(f" Total avg={avg_t:.2f} p50={p50_t:.2f} p95={p95_t:.2f}")
474
+ print(f" Target < 1000 ms per 3000x4000 image: {'YES' if p50_t < 1000.0 else 'NO'}")
475
+
476
+ if args.bench_report_json:
477
+ import json
478
+
479
+ report = {
480
+ "summary": {
481
+ "avg_ms": avg_t,
482
+ "p50_ms": p50_t,
483
+ "p95_ms": p95_t,
484
+ "avg_coarse_ms": avg_c,
485
+ "avg_fine_ms": avg_f,
486
+ "images": len(timings),
487
+ },
488
+ "per_image": timings,
489
+ }
490
+ with open(args.bench_report_json, "w") as f:
491
+ json.dump(report, f, indent=2)
492
+
493
+ return
494
+
495
  if args.image is not None:
496
  infer_image(
497
  model,